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/box.ts?version=73&format=json
357 linesFirst import 64% · trials 20% · pinch 12% · review 3% · speed 1%Last change trials in version 64, 8 versions changed it

You're reading version 73. The newest is 318, and 5 versions since then changed this file. Go to the newestCompare with 318

1// Signing in once per box (abso issue 108). `abso login` asks the server for a
2// code, a person approves it on the website, and the box gets a credential
3// with a grant: projects, a role cap, an agent limit and an expiry. Agents on
4// the box then mint their own keys from it at `abso join`.
5//
6// The box credential lives in the user's config folder, one file per server,
7// never in a project folder. It is never printed, never an argument, and only
8// ever sent to the server that issued it: on /box/ routes, and on the org reads,
9// which answer as the person who approved the box.
11import { createHash } from "node:crypto";
12import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13import { homedir, hostname } from "node:os";
14import { dirname, join } from "node:path";
15import { UsageError } from "./args.ts";
16import { homeFile, homeWritePath, OLD_STATE_DIR, STATE_DIR } from "./state-dir.ts";
18/** What the person who approved the code allowed: each project with the highest role its agents get there, and how many agents. */
19export interface Grant {
20 readonly projects: readonly { readonly project: string; readonly role: string }[];
21 readonly max_agents: number;
24export interface BoxRecord {
25 readonly server: string;
26 readonly id: string;
27 readonly credential: string;
28 readonly grant: Grant;
29 readonly expiresAt: number;
32export function originOf(server: string): string {
33 try {
34 return new URL(server).origin;
35 } catch {
36 return server;
37 }
40function boxFile(server: string): string {
41 return `${createHash("sha256").update(originOf(server)).digest("hex").slice(0, 16)}.json`;
44export function readBox(server: string, home = homedir()): BoxRecord | undefined {
45 try {
46 const raw = JSON.parse(readFileSync(homeFile(home, "boxes", boxFile(server)), "utf8")) as Partial<BoxRecord>;
47 if (
48 typeof raw.server !== "string" ||
49 originOf(raw.server) !== originOf(server) ||
50 typeof raw.credential !== "string" ||
51 typeof raw.id !== "string" ||
52 typeof raw.expiresAt !== "number" ||
53 !isGrant(raw.grant)
54 )
55 return undefined;
56 return raw as BoxRecord;
57 } catch {
58 return undefined;
59 }
62/** The servers this box is signed in to and whose sign-in hasn't expired, from ~/.abso/boxes (and an older ~/.avcs/boxes). */
63export function signedInServers(home = homedir(), now = Date.now()): string[] {
64 const servers = new Set<string>();
65 for (const dir of [STATE_DIR, OLD_STATE_DIR]) {
66 let names: string[];
67 try {
68 names = readdirSync(join(home, dir, "boxes"));
69 } catch {
70 continue;
71 }
72 for (const name of names) {
73 try {
74 const server = (JSON.parse(readFileSync(join(home, dir, "boxes", name), "utf8")) as { server?: unknown })
75 .server;
76 if (typeof server !== "string") continue;
77 const record = readBox(server, home);
78 if (record && record.expiresAt > now) servers.add(originOf(record.server));
79 } catch {
80 // Not a sign-in this client wrote: left alone.
81 }
82 }
83 }
84 return [...servers].sort();
87export function writeBox(record: BoxRecord, home = homedir()): void {
88 const path = homeWritePath(home, "boxes", boxFile(record.server));
89 mkdirSync(dirname(path), { recursive: true });
90 writeFileSync(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
91 try {
92 chmodSync(path, 0o600);
93 } catch {
94 // Windows has no owner-only mode; the file is still outside every project folder.
95 }
98/** Logout ends the sign-in everywhere on this machine: the credential under ~/.abso and any older copy under ~/.avcs. */
99export function forgetBox(server: string, home = homedir()): boolean {
100 const paths = [homeWritePath(home, "boxes", boxFile(server)), join(home, OLD_STATE_DIR, "boxes", boxFile(server))];
101 const had = paths.filter((path) => existsSync(path));
102 for (const path of had) rmSync(path, { force: true });
103 return had.length > 0;
106/** Error text with the credential (and anything shaped like a key) taken out. */
107function scrub(text: string, secrets: readonly string[]): string {
108 let out = text.replace(/abso_(sk|bx)_[A-Za-z0-9_-]+/g, "[redacted]");
109 for (const s of secrets) if (s.length > 0) out = out.split(s).join("[redacted]");
110 return out;
113export interface Answer {
114 readonly status: number;
115 readonly body: Record<string, unknown>;
118async function call(
119 server: string,
120 path: string,
121 body: unknown,
122 credential: string | undefined,
123 fetcher: typeof fetch,
124): Promise<Answer> {
125 const secrets = credential ? [credential] : [];
126 let response: Response;
127 try {
128 response = await fetcher(`${originOf(server)}${path}`, {
129 method: "POST",
130 headers: {
131 "content-type": "application/json",
132 ...(credential ? { authorization: `Box ${credential}` } : {}),
133 },
134 body: JSON.stringify(body),
135 signal: AbortSignal.timeout(30_000),
136 });
137 } catch (err) {
138 throw new UsageError(
139 `couldn't reach ${originOf(server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
140 );
141 }
142 const text = await response.text();
143 let parsed: Record<string, unknown> = {};
144 try {
145 parsed = JSON.parse(text) as Record<string, unknown>;
146 } catch {
147 if (response.ok) throw new UsageError(`${originOf(server)}${path} didn't answer JSON`);
148 }
149 if (!response.ok && !(response.status === 400 && path === "/login/token")) {
150 const said = typeof parsed.error === "string" ? parsed.error : text.slice(0, 300);
151 throw new UsageError(scrub(`${originOf(server)} refused (${response.status}): ${said}`, secrets));
152 }
153 return { status: response.status, body: parsed };
156/**
157 * A read that answers as the person who approved this box: the org reads (GET /orgs, /orgs/<name>). Answers the
158 * status and body as they came, refusals included, so the caller can say what each means; never the credential.
159 */
160export async function boxGet(record: BoxRecord, path: string, fetcher: typeof fetch = fetch): Promise<Answer> {
161 const secrets = [record.credential];
162 let response: Response;
163 try {
164 response = await fetcher(`${originOf(record.server)}${path}`, {
165 headers: { authorization: `Box ${record.credential}` },
166 signal: AbortSignal.timeout(30_000),
167 });
168 } catch (err) {
169 throw new UsageError(
170 `couldn't reach ${originOf(record.server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
171 );
172 }
173 const text = await response.text();
174 try {
175 const body = JSON.parse(text) as unknown;
176 if (typeof body === "object" && body !== null && !Array.isArray(body))
177 return { status: response.status, body: body as Record<string, unknown> };
178 } catch {}
179 return { status: response.status, body: { error: scrub(text.slice(0, 300), secrets) } };
182/** This machine's name, as the server takes a box's name: 1-64 letters, digits, '.', '_' or '-'. */
183function boxName(): string {
184 const name = hostname()
185 .replace(/[^A-Za-z0-9._-]/g, "-")
186 .replace(/^[^A-Za-z0-9]+/, "")
187 .slice(0, 64);
188 return name || "box";
191function isGrant(g: unknown): g is Grant {
192 const x = g as Partial<Grant> | null;
193 return (
194 typeof x === "object" &&
195 x !== null &&
196 Array.isArray(x.projects) &&
197 x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string") &&
198 typeof x.max_agents === "number"
199 );
202/** The longest login waits for approval, whatever the server says. */
203const MAX_LOGIN_WAIT_S = 30 * 60;
204/** How often login says it's still waiting. */
205const STILL_WAITING_MS = 60_000;
207export interface LoginIo {
208 readonly fetch?: typeof fetch;
209 readonly sleep?: (ms: number) => Promise<void>;
210 readonly now?: () => number;
211 /** Where the code and link go while login waits: stderr, so stdout stays quiet. */
212 readonly say: (line: string) => void;
213 /** Opens the approve page in a browser, answering whether it tried. None where it shouldn't (--no-browser, SSH, CI). */
214 readonly open?: (url: string) => boolean;
217/**
218 * Asks `server` for a code, shows it with its link, and waits for a person to
219 * approve it. Answers the box's record, already written to the config folder.
220 */
221export async function login(server: string, io: LoginIo, home = homedir()): Promise<BoxRecord> {
222 const fetcher = io.fetch ?? fetch;
223 const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
224 const now = io.now ?? Date.now;
225 const start = await call(server, "/login/device", { name: boxName(), client: "abso" }, undefined, fetcher);
226 const { device_code: device, user_code: code, verification_uri_complete: link } = start.body;
227 let interval = Number(start.body.interval) || 5;
228 // The server says when its code runs out; a server that says never still gets an end.
229 const expiresIn = Math.min(Number(start.body.expires_in) || 900, MAX_LOGIN_WAIT_S);
230 if (typeof code !== "string" || typeof link !== "string" || typeof device !== "string")
231 throw new UsageError(`${originOf(server)} didn't give a code to approve`);
232 // The page opens with the code in it, so nobody copies a link by hand. The link and code are printed all the same.
233 if (io.open?.(link)) io.say("Opening the approve page in your browser.");
234 io.say(`To sign this box in, open ${link} and approve the code ${code}.`);
235 io.say("Waiting for approval. Ctrl-C stops waiting, and abso stops by itself when the code runs out.");
236 const until = now() + expiresIn * 1000;
237 let toldAt = now();
238 while (now() < until) {
239 await sleep(interval * 1000);
240 // A wait with no word looks like a hang, so say it's still waiting now and then.
241 if (now() - toldAt >= STILL_WAITING_MS) {
242 io.say(`Still waiting for the code ${code} to be approved.`);
243 toldAt = now();
244 }
245 const a = await call(server, "/login/token", { device_code: device }, undefined, fetcher);
246 if (a.status === 400) {
247 if (a.body.error === "authorization_pending") continue;
248 if (a.body.error === "slow_down") {
249 interval += 5;
250 continue;
251 }
252 if (a.body.error === "access_denied") throw new UsageError(`the code ${code} was turned down.`);
253 throw new UsageError(`the code ${code} ran out. Run abso login again.`);
254 }
255 const { box_token: credential, box_id: id, grant, expires_at } = a.body;
256 const expiresAt = typeof expires_at === "string" ? Date.parse(expires_at) : Number.NaN;
257 if (typeof credential !== "string" || typeof id !== "string" || !isGrant(grant) || Number.isNaN(expiresAt))
258 throw new UsageError(`${originOf(server)} approved the code but sent no credential`);
259 const record: BoxRecord = { server: originOf(server), id, credential, grant, expiresAt };
260 writeBox(record, home);
261 return record;
262 }
263 throw new UsageError(`nobody approved the code ${code} in time. Run abso login again.`);
266/** An agent's own key, minted from the box's credential: `{key, id}`, as `abso key install` takes it. */
267export async function mintKey(
268 record: BoxRecord,
269 project: string,
270 agent: string,
271 fetcher: typeof fetch = fetch,
272): Promise<{ key: string; id: string }> {
273 const a = await call(record.server, "/box/agent-key", { project, agent }, record.credential, fetcher);
274 const { key, id } = a.body;
275 if (typeof key !== "string" || typeof id !== "string")
276 throw new UsageError(`${record.server} didn't send a key for ${agent}`);
277 return { key, id };
280/** The agent name abso join takes when none is given: the box's name, lower-cased. */
281export function defaultAgentName(): string {
282 return boxName().toLowerCase();
285/**
286 * abso join with no --agent: mints a key under `base`, else `base`-2, -3 and so on. Names this
287 * box already holds in the project are skipped without asking, since minting one again would replace that agent's
288 * key and cut off its folder. A name the server says is taken (409) moves on to the next; any other refusal, the
289 * box's agent limit among them, is said as it is.
290 */
291export async function mintFreeName(
292 record: BoxRecord,
293 project: string,
294 base: string,
295 fetcher: typeof fetch = fetch,
296 tries = 20,
297): Promise<{ key: string; id: string; agent: string }> {
298 const box = await boxGet(record, "/box", fetcher);
299 if (box.status !== 200)
300 throw new UsageError(
301 `${originOf(record.server)} refused (${box.status}): ${String(box.body.error ?? "no reason given")}`,
302 );
303 const agents = Array.isArray(box.body.agents) ? (box.body.agents as { project?: unknown; agent?: unknown }[]) : [];
304 const held = new Set(agents.filter((a) => a.project === project).map((a) => String(a.agent)));
305 for (let n = 1; n <= tries; n++) {
306 const agent = n === 1 ? base : `${base}-${n}`;
307 if (held.has(agent)) continue;
308 try {
309 return { ...(await mintKey(record, project, agent, fetcher)), agent };
310 } catch (err) {
311 if (err instanceof UsageError && /refused \(409\): that agent name/.test(err.message)) continue;
312 if (err instanceof UsageError && /refused \(409\): this box is at its agent limit/.test(err.message))
313 throw new UsageError(
314 `this box is at its agent limit (${record.grant.max_agents}): abso box shows its grant, and an agent can be revoked on the website's Boxes page`,
315 );
316 throw err;
317 }
318 }
319 throw new UsageError(
320 `${base} through ${base}-${tries} are all taken in ${project}: give this agent a name with --agent <name>`,
321 );
324/** Ends the box on the server, then forgets it here. Forgets it even when the server can't be reached. */
325export async function logout(record: BoxRecord, fetcher: typeof fetch = fetch, home = homedir()): Promise<boolean> {
326 let ended = true;
327 try {
328 await call(record.server, "/box/logout", {}, record.credential, fetcher);
329 } catch {
330 ended = false;
331 }
332 forgetBox(record.server, home);
333 return ended;
336const day = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
338/** What `abso box` prints: the grant, never the credential. */
339export function boxText(record: BoxRecord | undefined, server: string, now = Date.now()): string {
340 if (!record) return `This box isn't signed in to ${originOf(server)}. abso login signs it in.`;
341 const g = record.grant;
342 const expired = record.expiresAt <= now;
343 return [
344 `Signed in to ${record.server} as box ${record.id}${expired ? ", but the sign-in has expired. abso login renews it." : "."}`,
345 `Projects: ${g.projects.map((p) => `${p.project} (${p.role})`).join(", ")}. Up to ${g.max_agents} agents.`,
346 `${expired ? "Expired" : "Expires"} ${day(record.expiresAt)} UTC.`,
347 ].join("\n");
350/** What `abso box --json` answers: the record without its credential. */
351export function boxPublic(
352 record: BoxRecord | undefined,
353): { server: string; id: string; grant: Grant; expiresAt: string } | null {
354 return record
355 ? { server: record.server, id: record.id, grant: record.grant, expiresAt: new Date(record.expiresAt).toISOString() }
356 : null;