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