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