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