Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/client/src/config.ts?version=261&format=json
269 linesFirst import 72% · pinch 19% · review 9%Last change pinch in version 95, 5 versions changed it

You're reading version 261. The newest is 318, and 3 versions since then changed this file. Go to the newestCompare with 318

1// The folder's settings (.avcs/config.json), finding the folder that holds
2// them, and the token.
3//
4// The token is never in the folder: it comes from the ABSO_TOKEN environment
5// variable, or else from ~/.avcs/token, outside every repo. A pipeline run's
6// key comes from the file ABSO_KEY_FILE names, and is only ever held in memory.
7
8import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9import { homedir } from "node:os";
10import { basename, dirname, join, resolve } from "node:path";
11import { UsageError } from "./args.ts";
12import { type MachineServers, machineServers, TOKEN_SERVERS, tokenGoesTo, trustedList } from "./core.ts";
13import { fromEnv } from "./env-names.ts";
14import { homeFile, stateDir } from "./state-dir.ts";
16/** What .avcs/config.json holds. */
17export interface Settings {
18 readonly server: string;
19 readonly project: string;
20 readonly agent: string;
21 /** A label the folder follows (abso follow): every sync moves it to the newest version with that label. */
22 readonly follow?: string;
23 /** A reader folder (abso join --reader, #37): it reads everything and records nothing; the server refuses its records too. */
24 readonly reader?: boolean;
25 /**
26 * A visitor folder (abso join <project> --reader with no sign-in, for a public project): it reads through the
27 * routes anyone can read and sends no credential. It has no agent; its config holds server, project and this.
28 */
29 readonly visitor?: boolean;
32export interface Config extends Settings {
33 readonly token?: string;
36export function configPath(root: string): string {
37 return join(stateDir(root), "config.json");
40/** The nearest folder at or above `start` that has .abso/config.json (or .avcs/config.json, from before the rename), or undefined. */
41export function findRoot(start: string): string | undefined {
42 let dir = resolve(start);
43 for (;;) {
44 if (existsSync(configPath(dir))) return dir;
45 const up = dirname(dir);
46 if (up === dir) return undefined;
47 dir = up;
48 }
51export function readConfig(root: string, env: Readonly<Record<string, string | undefined>> = process.env): Config {
52 const raw = JSON.parse(readFileSync(configPath(root), "utf8")) as Partial<Settings>;
53 if (raw.visitor === true) {
54 for (const key of ["server", "project"] as const) {
55 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`);
56 }
57 // No token and no key, whatever the environment or the folder holds: a visitor sends no credential.
58 return { server: raw.server!, project: raw.project!, agent: "", visitor: true };
59 }
60 for (const key of ["server", "project", "agent"] as const) {
61 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`);
62 }
63 const token = tokenFor(raw.server!, env, root);
64 return {
65 server: raw.server!,
66 project: raw.project!,
67 agent: raw.agent!,
68 ...(typeof raw.follow === "string" && raw.follow !== "" ? { follow: raw.follow } : {}),
69 ...(raw.reader === true ? { reader: true } : {}),
70 ...(token ? { token } : {}),
71 };
74/** Whether the folder is a visitor's: it reads signed out and sends no credential. Read straight from its config. */
75export function isVisitor(root: string): boolean {
76 try {
77 return (JSON.parse(readFileSync(configPath(root), "utf8")) as { visitor?: unknown }).visitor === true;
78 } catch {
79 return false;
80 }
83/** Whether the folder is a reader (#37): records nothing. Read straight from its config, for the paths that only need this. */
84export function isReader(root: string): boolean {
85 try {
86 return (JSON.parse(readFileSync(configPath(root), "utf8")) as { reader?: unknown }).reader === true;
87 } catch {
88 return false;
89 }
92/**
93 * The token for `server`, refusing a server it may not go to (core.ts
94 * tokenGoesTo): a folder's config names its server, and anyone can write one.
95 */
96/** What status may say about the credential. Never the key or the token. */
97export function credentialLabel(
98 root: string,
99 server: string,
100 env: Readonly<Record<string, string | undefined>> = process.env,
101): { kind: "agent key" | "shared token" | "pipeline run key" | "none"; id: string | null } {
102 const key = readKeyFile(root);
103 if (key) {
104 if (originOf(key.server) !== originOf(server)) return { kind: "none", id: null };
105 return { kind: "agent key", id: key.id };
106 }
107 if (fromEnv(env, "TOKEN")) return { kind: "shared token", id: null };
108 if (fromEnv(env, "KEY_FILE")) return { kind: "pipeline run key", id: null };
109 return { kind: readToken(env) ? "shared token" : "none", id: null };
112interface StoredKey {
113 server: string;
114 key: string;
115 id: string;
118function keyPath(root: string): string {
119 return join(stateDir(root), "key");
122function originOf(server: string): string {
123 try {
124 return new URL(server).origin;
125 } catch {
126 return server;
127 }
130function readKeyFile(root: string): StoredKey | undefined {
131 try {
132 const raw = JSON.parse(readFileSync(keyPath(root), "utf8")) as Partial<StoredKey>;
133 if (typeof raw.server !== "string" || typeof raw.key !== "string" || typeof raw.id !== "string") return undefined;
134 if (!raw.key.startsWith("abso_sk_") || !/^k_[0-9a-f]{8}$/.test(raw.id)) return undefined;
135 return { server: raw.server, key: raw.key, id: raw.id };
136 } catch {
137 return undefined;
138 }
141/**
142 * Writes `.avcs/key` from the JSON the staging issue route printed (`{key, id}`),
143 * pinned to this folder's server, or to `serverFlag` in a folder not joined yet.
144 * Reads stdin. Prints nothing that contains the key.
145 */
146export function installKey(root: string, stdin: string, serverFlag?: string): { id: string } {
147 const configured = existsSync(configPath(root))
148 ? (JSON.parse(readFileSync(configPath(root), "utf8")) as { server?: string }).server
149 : undefined;
150 if (configured && serverFlag && originOf(configured) !== originOf(serverFlag))
151 throw new UsageError(`this folder's server is ${configured}, not ${serverFlag}`);
152 const server = configured ?? serverFlag;
153 if (!server) throw new UsageError("this folder has no .abso/config.json yet: give --server <url>");
154 let parsed: { key?: unknown; id?: unknown };
155 try {
156 parsed = JSON.parse(stdin) as { key?: unknown; id?: unknown };
157 } catch {
158 throw new UsageError("abso key install reads {key, id} as JSON from stdin");
159 }
160 if (
161 typeof parsed.key !== "string" ||
162 !parsed.key.startsWith("abso_sk_") ||
163 typeof parsed.id !== "string" ||
164 !/^k_[0-9a-f]{8}$/.test(parsed.id)
165 )
166 throw new UsageError("stdin needs {key, id} from the staging issue route");
167 mkdirSync(stateDir(root), { recursive: true });
168 writeFileSync(keyPath(root), `${JSON.stringify({ server, key: parsed.key, id: parsed.id })}\n`, { mode: 0o600 });
169 try {
170 chmodSync(keyPath(root), 0o600);
171 } catch {
172 // Windows has no owner-only mode. The file is still under .avcs/, which abso never records.
173 }
174 return { id: parsed.id };
177export function tokenFor(
178 server: string,
179 env: Readonly<Record<string, string | undefined>> = process.env,
180 root?: string,
181): string | undefined {
182 if (root) {
183 const key = readKeyFile(root);
184 if (key) {
185 if (originOf(key.server) !== originOf(server))
186 throw new UsageError("this folder's key was issued for a different server, so abso will not send it");
187 return key.key;
188 }
189 }
190 const token = fromEnv(env, "TOKEN")?.trim() || runKey(env) || readToken(env);
191 const trusted = trustedServers(env);
192 if (token === undefined || tokenGoesTo(server, trusted)) return token;
193 throw new UsageError(
194 `this folder's server is ${server}, and abso sends your token only to ${[...TOKEN_SERVERS, "this machine"].join(", ")}, and the servers ~/.abso/servers.json or ABSO_TRUSTED_SERVERS name. ` +
195 `If ${server} is yours, name it in ~/.abso/servers.json or ABSO_TRUSTED_SERVERS (comma-separated); if you didn't set it, someone else wrote .abso/config.json.`,
196 );
199let machine: MachineServers | undefined;
200/** This machine's servers (core.ts machineServers), from ~/.abso/servers.json (or the older ~/.avcs/servers.json), read once. ABSO_SERVERS_FILE names another file (tests). */
201export function readMachineServers(env: Readonly<Record<string, string | undefined>> = process.env): MachineServers {
202 if (fromEnv(env, "SERVERS_FILE") !== undefined) return machineServers(readOr(fromEnv(env, "SERVERS_FILE") as string));
203 machine ??= machineServers(readOr(homeFile(homedir(), "servers.json")));
204 return machine;
206const readOr = (path: string): string | undefined => {
207 try {
208 return readFileSync(path, "utf8");
209 } catch {
210 return undefined;
211 }
212};
214/** The servers the token may go to beyond abso's own: ABSO_TRUSTED_SERVERS, then this machine's servers.json. */
215export function trustedServers(env: Readonly<Record<string, string | undefined>> = process.env): string {
216 return trustedList(fromEnv(env, "TRUSTED_SERVERS"), readMachineServers(env));
219/**
220 * A pipeline run's key, from the file ABSO_KEY_FILE names (the runner writes it, mode 600, holding the bare key).
221 * Read each time and kept in memory only; nothing abso writes or prints holds it, errors included.
222 */
223export function runKey(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined {
224 const path = fromEnv(env, "KEY_FILE");
225 if (!path) return undefined;
226 let text: string;
227 try {
228 text = readFileSync(path, "utf8");
229 } catch {
230 throw new UsageError(`ABSO_KEY_FILE names ${path}, which abso can't read`);
231 }
232 const key = text.trim();
233 if (!/^abso_sk_[A-Za-z0-9_-]+$/.test(key))
234 throw new UsageError(`ABSO_KEY_FILE names ${path}, which doesn't hold an abso key`);
235 return key;
238/** ABSO_TOKEN if set, else ~/.abso/token, else ~/.avcs/token, else none. */
239export function readToken(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined {
240 const fromVar = fromEnv(env, "TOKEN");
241 if (fromVar) return fromVar.trim();
242 try {
243 return readFileSync(homeFile(homedir(), "token"), "utf8").trim() || undefined;
244 } catch {
245 return undefined;
246 }
249export function writeConfig(root: string, settings: Settings): void {
250 mkdirSync(stateDir(root), { recursive: true });
251 const { server, project, agent, follow, reader, visitor } = settings;
252 const written = visitor
253 ? { server, project, visitor: true }
254 : { server, project, agent, ...(follow ? { follow } : {}), ...(reader ? { reader: true } : {}) };
255 writeFileSync(configPath(root), `${JSON.stringify(written, null, 2)}\n`);
256 excludeFromGit(root);
259/** If the folder is a git repo, keep its state folder (.abso/, or .avcs/ in an older folder) out of it (in .git/info/exclude, so .gitignore isn't changed). */
260function excludeFromGit(root: string): void {
261 const git = join(root, ".git");
262 if (!existsSync(join(git, "HEAD"))) return;
263 const exclude = join(git, "info", "exclude");
264 const text = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
265 const name = `${basename(stateDir(root))}/`;
266 if (text.split(/\r?\n/).some((line) => line.trim() === name || line.trim() === `/${name}`)) return;
267 mkdirSync(dirname(exclude), { recursive: true });
268 writeFileSync(exclude, `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}/${name}\n`);