- 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=89&format=json
247 linesFirst import 79% · pinch 11% · review 10%Last change pinch in version 86, 4 versions changed it
You're reading version 89. The newest is 318, and 4 versions 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.
7import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8import { homedir } from "node:os";
9import { basename, dirname, join, resolve } from "node:path";
10import { UsageError } from "./args.ts";
11import { type MachineServers, machineServers, TOKEN_SERVERS, tokenGoesTo, trustedList } from "./core.ts";
12import { fromEnv } from "./env-names.ts";
13import { homeFile, stateDir } from "./state-dir.ts";
15/** What .avcs/config.json holds. */
16export interface Settings {
17 readonly server: string;
18 readonly project: string;
19 readonly agent: string;
20 /** A label the folder follows (abso follow): every sync moves it to the newest version with that label. */
21 readonly follow?: string;
22 /** A reader folder (abso join --reader, #37): it reads everything and records nothing; the server refuses its records too. */
23 readonly reader?: boolean;
24 /**
25 * A visitor folder (abso join <project> --reader with no sign-in, for a public project): it reads through the
26 * routes anyone can read and sends no credential. It has no agent; its config holds server, project and this.
27 */
28 readonly visitor?: boolean;
29}
31export interface Config extends Settings {
32 readonly token?: string;
33}
35export function configPath(root: string): string {
36 return join(stateDir(root), "config.json");
37}
39/** The nearest folder at or above `start` that has .abso/config.json (or .avcs/config.json, from before the rename), or undefined. */
40export function findRoot(start: string): string | undefined {
41 let dir = resolve(start);
42 for (;;) {
43 if (existsSync(configPath(dir))) return dir;
44 const up = dirname(dir);
45 if (up === dir) return undefined;
46 dir = up;
47 }
48}
50export function readConfig(root: string, env: Readonly<Record<string, string | undefined>> = process.env): Config {
51 const raw = JSON.parse(readFileSync(configPath(root), "utf8")) as Partial<Settings>;
52 if (raw.visitor === true) {
53 for (const key of ["server", "project"] as const) {
54 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`);
55 }
56 // No token and no key, whatever the environment or the folder holds: a visitor sends no credential.
57 return { server: raw.server!, project: raw.project!, agent: "", visitor: true };
58 }
59 for (const key of ["server", "project", "agent"] as const) {
60 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`);
61 }
62 const token = tokenFor(raw.server!, env, root);
63 return {
64 server: raw.server!,
65 project: raw.project!,
66 agent: raw.agent!,
67 ...(typeof raw.follow === "string" && raw.follow !== "" ? { follow: raw.follow } : {}),
68 ...(raw.reader === true ? { reader: true } : {}),
69 ...(token ? { token } : {}),
70 };
71}
73/** Whether the folder is a visitor's: it reads signed out and sends no credential. Read straight from its config. */
74export function isVisitor(root: string): boolean {
75 try {
76 return (JSON.parse(readFileSync(configPath(root), "utf8")) as { visitor?: unknown }).visitor === true;
77 } catch {
78 return false;
79 }
80}
82/** Whether the folder is a reader (#37): records nothing. Read straight from its config, for the paths that only need this. */
83export function isReader(root: string): boolean {
84 try {
85 return (JSON.parse(readFileSync(configPath(root), "utf8")) as { reader?: unknown }).reader === true;
86 } catch {
87 return false;
88 }
89}
91/**
92 * The token for `server`, refusing a server it may not go to (core.ts
93 * tokenGoesTo): a folder's config names its server, and anyone can write one.
94 */
95/** What status may say about the credential. Never the key or the token. */
96export function credentialLabel(
97 root: string,
98 server: string,
99 env: Readonly<Record<string, string | undefined>> = process.env,
100): { kind: "agent key" | "shared token" | "none"; id: string | null } {
101 const key = readKeyFile(root);
102 if (key) {
103 if (originOf(key.server) !== originOf(server)) return { kind: "none", id: null };
104 return { kind: "agent key", id: key.id };
105 }
106 return { kind: readToken(env) ? "shared token" : "none", id: null };
107}
109interface StoredKey {
110 server: string;
111 key: string;
112 id: string;
113}
115function keyPath(root: string): string {
116 return join(stateDir(root), "key");
117}
119function originOf(server: string): string {
120 try {
121 return new URL(server).origin;
122 } catch {
123 return server;
124 }
125}
127function readKeyFile(root: string): StoredKey | undefined {
128 try {
129 const raw = JSON.parse(readFileSync(keyPath(root), "utf8")) as Partial<StoredKey>;
130 if (typeof raw.server !== "string" || typeof raw.key !== "string" || typeof raw.id !== "string") return undefined;
131 if (!raw.key.startsWith("abso_sk_") || !/^k_[0-9a-f]{8}$/.test(raw.id)) return undefined;
132 return { server: raw.server, key: raw.key, id: raw.id };
133 } catch {
134 return undefined;
135 }
136}
138/**
139 * Writes `.avcs/key` from the JSON the staging issue route printed (`{key, id}`),
140 * pinned to this folder's server, or to `serverFlag` in a folder not joined yet.
141 * Reads stdin. Prints nothing that contains the key.
142 */
143export function installKey(root: string, stdin: string, serverFlag?: string): { id: string } {
144 const configured = existsSync(configPath(root))
145 ? (JSON.parse(readFileSync(configPath(root), "utf8")) as { server?: string }).server
146 : undefined;
147 if (configured && serverFlag && originOf(configured) !== originOf(serverFlag))
148 throw new UsageError(`this folder's server is ${configured}, not ${serverFlag}`);
149 const server = configured ?? serverFlag;
150 if (!server) throw new UsageError("this folder has no .abso/config.json yet: give --server <url>");
151 let parsed: { key?: unknown; id?: unknown };
152 try {
153 parsed = JSON.parse(stdin) as { key?: unknown; id?: unknown };
154 } catch {
155 throw new UsageError("abso key install reads {key, id} as JSON from stdin");
156 }
157 if (
158 typeof parsed.key !== "string" ||
159 !parsed.key.startsWith("abso_sk_") ||
160 typeof parsed.id !== "string" ||
161 !/^k_[0-9a-f]{8}$/.test(parsed.id)
162 )
163 throw new UsageError("stdin needs {key, id} from the staging issue route");
164 mkdirSync(stateDir(root), { recursive: true });
165 writeFileSync(keyPath(root), `${JSON.stringify({ server, key: parsed.key, id: parsed.id })}\n`, { mode: 0o600 });
166 try {
167 chmodSync(keyPath(root), 0o600);
168 } catch {
169 // Windows has no owner-only mode. The file is still under .avcs/, which abso never records.
170 }
171 return { id: parsed.id };
172}
174export function tokenFor(
175 server: string,
176 env: Readonly<Record<string, string | undefined>> = process.env,
177 root?: string,
178): string | undefined {
179 if (root) {
180 const key = readKeyFile(root);
181 if (key) {
182 if (originOf(key.server) !== originOf(server))
183 throw new UsageError("this folder's key was issued for a different server, so abso will not send it");
184 return key.key;
185 }
186 }
187 const token = readToken(env);
188 const trusted = trustedServers(env);
189 if (token === undefined || tokenGoesTo(server, trusted)) return token;
190 throw new UsageError(
191 `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. ` +
192 `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.`,
193 );
194}
196let machine: MachineServers | undefined;
197/** 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). */
198export function readMachineServers(env: Readonly<Record<string, string | undefined>> = process.env): MachineServers {
199 if (fromEnv(env, "SERVERS_FILE") !== undefined) return machineServers(readOr(fromEnv(env, "SERVERS_FILE") as string));
200 machine ??= machineServers(readOr(homeFile(homedir(), "servers.json")));
201 return machine;
202}
203const readOr = (path: string): string | undefined => {
204 try {
205 return readFileSync(path, "utf8");
206 } catch {
207 return undefined;
208 }
209};
211/** The servers the token may go to beyond abso's own: ABSO_TRUSTED_SERVERS, then this machine's servers.json. */
212export function trustedServers(env: Readonly<Record<string, string | undefined>> = process.env): string {
213 return trustedList(fromEnv(env, "TRUSTED_SERVERS"), readMachineServers(env));
214}
216/** ABSO_TOKEN if set, else ~/.abso/token, else ~/.avcs/token, else none. */
217export function readToken(env: Readonly<Record<string, string | undefined>> = process.env): string | undefined {
218 const fromVar = fromEnv(env, "TOKEN");
219 if (fromVar) return fromVar.trim();
220 try {
221 return readFileSync(homeFile(homedir(), "token"), "utf8").trim() || undefined;
222 } catch {
223 return undefined;
224 }
225}
227export function writeConfig(root: string, settings: Settings): void {
228 mkdirSync(stateDir(root), { recursive: true });
229 const { server, project, agent, follow, reader, visitor } = settings;
230 const written = visitor
231 ? { server, project, visitor: true }
232 : { server, project, agent, ...(follow ? { follow } : {}), ...(reader ? { reader: true } : {}) };
233 writeFileSync(configPath(root), `${JSON.stringify(written, null, 2)}\n`);
234 excludeFromGit(root);
235}
237/** 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). */
238function excludeFromGit(root: string): void {
239 const git = join(root, ".git");
240 if (!existsSync(join(git, "HEAD"))) return;
241 const exclude = join(git, "info", "exclude");
242 const text = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
243 const name = `${basename(stateDir(root))}/`;
244 if (text.split(/\r?\n/).some((line) => line.trim() === name || line.trim() === `/${name}`)) return;
245 mkdirSync(dirname(exclude), { recursive: true });
246 writeFileSync(exclude, `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}/${name}\n`);
247}