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