- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/config.ts?format=json
312 linesFirst import 60% · pinch 21% · readspeed 10% · review 8%Last change pinch in version 287, 8 versions changed it
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.
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 { isLocal, storeDir } from "./local-store.ts";
15import { homeFile, stateDir } from "./state-dir.ts";
17/** What .avcs/config.json holds. */
18export interface Settings {
19 readonly server: string;
20 readonly project: string;
21 readonly agent: string;
22 /** A label the folder follows (abso follow): every sync moves it to the newest version with that label. */
23 readonly follow?: string;
24 /** A reader folder (abso join --reader, #37): it reads everything and records nothing; the server refuses its records too. */
25 readonly reader?: boolean;
26 /**
27 * A visitor folder (abso join <project> --reader with no sign-in, for a public project): it reads through the
28 * routes anyone can read and sends no credential. It has no agent; its config holds server, project and this.
29 */
30 readonly visitor?: boolean;
31 /** A local project's store (abso init --local --store), when it isn't the machine's own: ABSO_STORE or the OS data folder. */
32 readonly store?: string;
33}
35export interface Config extends Settings {
36 readonly token?: string;
37 /** For a local project (server "local"): the store folder its history is in, or undefined when there's none to use. */
38 readonly localStore?: string;
39}
41export function configPath(root: string): string {
42 return join(stateDir(root), "config.json");
43}
45/** The nearest folder at or above `start` that has .abso/config.json (or .avcs/config.json, from before the rename), or undefined. */
46export function findRoot(start: string): string | undefined {
47 let dir = resolve(start);
48 for (;;) {
49 if (existsSync(configPath(dir))) return dir;
50 const up = dirname(dir);
51 if (up === dir) return undefined;
52 dir = up;
53 }
54}
56export function readConfig(
57 root: string,
58 env: Readonly<Record<string, string | undefined>> = process.env,
59 tokenFileOk = false,
60): Config {
61 const raw = JSON.parse(readFileSync(configPath(root), "utf8")) as Partial<Settings>;
62 if (raw.visitor === true) {
63 for (const key of ["server", "project"] as const) {
64 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`);
65 }
66 // No token and no key, whatever the environment or the folder holds: a visitor sends no credential.
67 return { server: raw.server!, project: raw.project!, agent: "", visitor: true };
68 }
69 for (const key of ["server", "project", "agent"] as const) {
70 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`);
71 }
72 // A local project's calls never leave this process, so no credential goes with them.
73 const local = isLocal(raw.server);
74 const token = local ? undefined : tokenFor(raw.server!, env, root, tokenFileOk);
75 return {
76 server: raw.server!,
77 project: raw.project!,
78 agent: raw.agent!,
79 ...(typeof raw.store === "string" && raw.store !== "" ? { store: raw.store } : {}),
80 ...(local ? { localStore: storeDir(env, raw.store, root) } : {}),
81 ...(typeof raw.follow === "string" && raw.follow !== "" ? { follow: raw.follow } : {}),
82 ...(raw.reader === true ? { reader: true } : {}),
83 ...(token ? { token } : {}),
84 };
85}
87/** Whether the folder is a visitor's: it reads signed out and sends no credential. Read straight from its config. */
88export function isVisitor(root: string): boolean {
89 try {
90 return (JSON.parse(readFileSync(configPath(root), "utf8")) as { visitor?: unknown }).visitor === true;
91 } catch {
92 return false;
93 }
94}
96/** Whether the folder is a reader (#37): records nothing. Read straight from its config, for the paths that only need this. */
97export function isReader(root: string): boolean {
98 try {
99 return (JSON.parse(readFileSync(configPath(root), "utf8")) as { reader?: unknown }).reader === true;
100 } catch {
101 return false;
102 }
103}
105/**
106 * The token for `server`, refusing a server it may not go to (core.ts
107 * tokenGoesTo): a folder's config names its server, and anyone can write one.
108 */
109/** What status may say about the credential. Never the key or the token. */
110export function credentialLabel(
111 root: string,
112 server: string,
113 env: Readonly<Record<string, string | undefined>> = process.env,
114 tokenFileOk = false,
115): { kind: "agent key" | "shared token" | "pipeline run key" | "none"; id: string | null } {
116 const key = readKeyFile(root);
117 if (key) {
118 if (originOf(key.server) !== originOf(server)) return { kind: "none", id: null };
119 return { kind: "agent key", id: key.id };
120 }
121 if (fromEnv(env, "TOKEN")) return { kind: "shared token", id: null };
122 if (fromEnv(env, "KEY_FILE")) return { kind: "pipeline run key", id: null };
123 return { kind: tokenFileOk && tokenFile() ? "shared token" : "none", id: null };
124}
126interface StoredKey {
127 server: string;
128 key: string;
129 id: string;
130}
132function keyPath(root: string): string {
133 return join(stateDir(root), "key");
134}
136function originOf(server: string): string {
137 try {
138 return new URL(server).origin;
139 } catch {
140 return server;
141 }
142}
144function readKeyFile(root: string): StoredKey | undefined {
145 try {
146 const raw = JSON.parse(readFileSync(keyPath(root), "utf8")) as Partial<StoredKey>;
147 if (typeof raw.server !== "string" || typeof raw.key !== "string" || typeof raw.id !== "string") return undefined;
148 if (!raw.key.startsWith("abso_sk_") || !/^k_[0-9a-f]{8}$/.test(raw.id)) return undefined;
149 return { server: raw.server, key: raw.key, id: raw.id };
150 } catch {
151 return undefined;
152 }
153}
155/**
156 * Writes `.avcs/key` from the JSON the staging issue route printed (`{key, id}`),
157 * pinned to this folder's server, or to `serverFlag` in a folder not joined yet.
158 * Reads stdin. Prints nothing that contains the key.
159 */
160export function installKey(root: string, stdin: string, serverFlag?: string): { id: string } {
161 const configured = existsSync(configPath(root))
162 ? (JSON.parse(readFileSync(configPath(root), "utf8")) as { server?: string }).server
163 : undefined;
164 if (configured && serverFlag && originOf(configured) !== originOf(serverFlag))
165 throw new UsageError(`this folder's server is ${configured}, not ${serverFlag}`);
166 const server = configured ?? serverFlag;
167 if (!server) throw new UsageError("this folder has no .abso/config.json yet: give --server <url>");
168 let parsed: { key?: unknown; id?: unknown };
169 try {
170 parsed = JSON.parse(stdin) as { key?: unknown; id?: unknown };
171 } catch {
172 throw new UsageError("abso key install reads {key, id} as JSON from stdin");
173 }
174 if (
175 typeof parsed.key !== "string" ||
176 !parsed.key.startsWith("abso_sk_") ||
177 typeof parsed.id !== "string" ||
178 !/^k_[0-9a-f]{8}$/.test(parsed.id)
179 )
180 throw new UsageError("stdin needs {key, id} from the staging issue route");
181 mkdirSync(stateDir(root), { recursive: true });
182 writeFileSync(keyPath(root), `${JSON.stringify({ server, key: parsed.key, id: parsed.id })}\n`, { mode: 0o600 });
183 try {
184 chmodSync(keyPath(root), 0o600);
185 } catch {
186 // Windows has no owner-only mode. The file is still under .avcs/, which abso never records.
187 }
188 return { id: parsed.id };
189}
191export function tokenFor(
192 server: string,
193 env: Readonly<Record<string, string | undefined>> = process.env,
194 root?: string,
195 tokenFileOk = false,
196): string | undefined {
197 if (root) {
198 const key = readKeyFile(root);
199 // A folder with a key signs in with that key and nothing else, even when the server refuses it.
200 if (!key && existsSync(keyPath(root)))
201 throw new UsageError(
202 `this folder's key file (${keyPath(root)}) can't be read, so abso sends nothing; abso key install puts a key back`,
203 );
204 if (key) {
205 if (originOf(key.server) !== originOf(server))
206 throw new UsageError("this folder's key was issued for a different server, so abso will not send it");
207 return key.key;
208 }
209 }
210 return trustedToken(
211 server,
212 env,
213 fromEnv(env, "TOKEN")?.trim() || runKey(env) || (tokenFileOk ? readToken(env) : undefined),
214 );
215}
217/** The token as given, if abso may send it to this server; refused, in words, if not. */
218export function trustedToken(
219 server: string,
220 env: Readonly<Record<string, string | undefined>>,
221 token: string | undefined,
222): string | undefined {
223 if (token === undefined || tokenGoesTo(server, trustedServers(env))) return token;
224 throw new UsageError(
225 `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. ` +
226 `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.`,
227 );
228}
230let machine: MachineServers | undefined;
231/** 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). */
232export function readMachineServers(env: Readonly<Record<string, string | undefined>> = process.env): MachineServers {
233 if (fromEnv(env, "SERVERS_FILE") !== undefined) return machineServers(readOr(fromEnv(env, "SERVERS_FILE") as string));
234 machine ??= machineServers(readOr(homeFile(homedir(), "servers.json")));
235 return machine;
236}
237const readOr = (path: string): string | undefined => {
238 try {
239 return readFileSync(path, "utf8");
240 } catch {
241 return undefined;
242 }
243};
245/** The servers the token may go to beyond abso's own: ABSO_TRUSTED_SERVERS, then this machine's servers.json. */
246export function trustedServers(env: Readonly<Record<string, string | undefined>> = process.env): string {
247 return trustedList(fromEnv(env, "TRUSTED_SERVERS"), readMachineServers(env));
248}
250/**
251 * A pipeline run's key, from the file ABSO_KEY_FILE names (the runner writes it, mode 600, holding the bare key).
252 * Read each time and kept in memory only; nothing abso writes or prints holds it, errors included.
253 */
254export function runKey(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined {
255 const path = fromEnv(env, "KEY_FILE");
256 if (!path) return undefined;
257 let text: string;
258 try {
259 text = readFileSync(path, "utf8");
260 } catch {
261 throw new UsageError(`ABSO_KEY_FILE names ${path}, which abso can't read`);
262 }
263 const key = text.trim();
264 if (!/^abso_sk_[A-Za-z0-9_-]+$/.test(key))
265 throw new UsageError(`ABSO_KEY_FILE names ${path}, which doesn't hold an abso key`);
266 return key;
267}
269/** This machine's token file (~/.abso/token, else ~/.avcs/token), or none. Read only for a command given --token-file. */
270export function tokenFile(): string | undefined {
271 return readToken({});
272}
274/** ABSO_TOKEN if set, else ~/.abso/token, else ~/.avcs/token, else none. */
275export function readToken(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined {
276 const fromVar = fromEnv(env, "TOKEN");
277 if (fromVar) return fromVar.trim();
278 try {
279 return readFileSync(homeFile(homedir(), "token"), "utf8").trim() || undefined;
280 } catch {
281 return undefined;
282 }
283}
285export function writeConfig(root: string, settings: Settings): void {
286 mkdirSync(stateDir(root), { recursive: true });
287 const { server, project, agent, follow, reader, visitor, store } = settings;
288 const written = visitor
289 ? { server, project, visitor: true }
290 : {
291 server,
292 project,
293 agent,
294 ...(follow ? { follow } : {}),
295 ...(reader ? { reader: true } : {}),
296 ...(store ? { store } : {}),
297 };
298 writeFileSync(configPath(root), `${JSON.stringify(written, null, 2)}\n`);
299 excludeFromGit(root);
300}
302/** 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). */
303function excludeFromGit(root: string): void {
304 const git = join(root, ".git");
305 if (!existsSync(join(git, "HEAD"))) return;
306 const exclude = join(git, "info", "exclude");
307 const text = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
308 const name = `${basename(stateDir(root))}/`;
309 if (text.split(/\r?\n/).some((line) => line.trim() === name || line.trim() === `/${name}`)) return;
310 mkdirSync(dirname(exclude), { recursive: true });
311 writeFileSync(exclude, `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}/${name}\n`);
312}