- 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=33&format=json
244 linesFirst import 95% · review 5%Last change review in version 17, 2 versions changed it
You're reading version 33. The newest is 318, and 11 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.
10import { createHash } from "node:crypto";
11import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12import { homedir, hostname } from "node:os";
13import { dirname, join } from "node:path";
14import { UsageError } from "./args.ts";
15import { homeFile, homeWritePath, OLD_STATE_DIR } from "./state-dir.ts";
17/** What the person who approved the code allowed: each project with the highest role its agents get there, and how many agents. */
18export interface Grant {
19 readonly projects: readonly { readonly project: string; readonly role: string }[];
20 readonly max_agents: number;
21}
23export interface BoxRecord {
24 readonly server: string;
25 readonly id: string;
26 readonly credential: string;
27 readonly grant: Grant;
28 readonly expiresAt: number;
29}
31export function originOf(server: string): string {
32 try {
33 return new URL(server).origin;
34 } catch {
35 return server;
36 }
37}
39function boxFile(server: string): string {
40 return `${createHash("sha256").update(originOf(server)).digest("hex").slice(0, 16)}.json`;
41}
43export function readBox(server: string, home = homedir()): BoxRecord | undefined {
44 try {
45 const raw = JSON.parse(readFileSync(homeFile(home, "boxes", boxFile(server)), "utf8")) as Partial<BoxRecord>;
46 if (
47 typeof raw.server !== "string" ||
48 originOf(raw.server) !== originOf(server) ||
49 typeof raw.credential !== "string" ||
50 typeof raw.id !== "string" ||
51 typeof raw.expiresAt !== "number" ||
52 !isGrant(raw.grant)
53 )
54 return undefined;
55 return raw as BoxRecord;
56 } catch {
57 return undefined;
58 }
59}
61export function writeBox(record: BoxRecord, home = homedir()): void {
62 const path = homeWritePath(home, "boxes", boxFile(record.server));
63 mkdirSync(dirname(path), { recursive: true });
64 writeFileSync(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
65 try {
66 chmodSync(path, 0o600);
67 } catch {
68 // Windows has no owner-only mode; the file is still outside every project folder.
69 }
70}
72/** Logout ends the sign-in everywhere on this machine: the credential under ~/.abso and any older copy under ~/.avcs. */
73export function forgetBox(server: string, home = homedir()): boolean {
74 const paths = [homeWritePath(home, "boxes", boxFile(server)), join(home, OLD_STATE_DIR, "boxes", boxFile(server))];
75 const had = paths.filter((path) => existsSync(path));
76 for (const path of had) rmSync(path, { force: true });
77 return had.length > 0;
78}
80/** Error text with the credential (and anything shaped like a key) taken out. */
81function scrub(text: string, secrets: readonly string[]): string {
82 let out = text.replace(/abso_(sk|bx)_[A-Za-z0-9_-]+/g, "[redacted]");
83 for (const s of secrets) if (s.length > 0) out = out.split(s).join("[redacted]");
84 return out;
85}
87interface Answer {
88 readonly status: number;
89 readonly body: Record<string, unknown>;
90}
92async function call(
93 server: string,
94 path: string,
95 body: unknown,
96 credential: string | undefined,
97 fetcher: typeof fetch,
98): Promise<Answer> {
99 const secrets = credential ? [credential] : [];
100 let response: Response;
101 try {
102 response = await fetcher(`${originOf(server)}${path}`, {
103 method: "POST",
104 headers: {
105 "content-type": "application/json",
106 ...(credential ? { authorization: `Box ${credential}` } : {}),
107 },
108 body: JSON.stringify(body),
109 signal: AbortSignal.timeout(30_000),
110 });
111 } catch (err) {
112 throw new UsageError(
113 `couldn't reach ${originOf(server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
114 );
115 }
116 const text = await response.text();
117 let parsed: Record<string, unknown> = {};
118 try {
119 parsed = JSON.parse(text) as Record<string, unknown>;
120 } catch {
121 if (response.ok) throw new UsageError(`${originOf(server)}${path} didn't answer JSON`);
122 }
123 if (!response.ok && !(response.status === 400 && path === "/login/token")) {
124 const said = typeof parsed.error === "string" ? parsed.error : text.slice(0, 300);
125 throw new UsageError(scrub(`${originOf(server)} refused (${response.status}): ${said}`, secrets));
126 }
127 return { status: response.status, body: parsed };
128}
130/** This machine's name, as the server takes a box's name: 1-64 letters, digits, '.', '_' or '-'. */
131function boxName(): string {
132 const name = hostname()
133 .replace(/[^A-Za-z0-9._-]/g, "-")
134 .replace(/^[^A-Za-z0-9]+/, "")
135 .slice(0, 64);
136 return name || "box";
137}
139function isGrant(g: unknown): g is Grant {
140 const x = g as Partial<Grant> | null;
141 return (
142 typeof x === "object" &&
143 x !== null &&
144 Array.isArray(x.projects) &&
145 x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string") &&
146 typeof x.max_agents === "number"
147 );
148}
150export interface LoginIo {
151 readonly fetch?: typeof fetch;
152 readonly sleep?: (ms: number) => Promise<void>;
153 readonly now?: () => number;
154 /** Where the code and link go while login waits: stderr, so stdout stays quiet. */
155 readonly say: (line: string) => void;
156}
158/**
159 * Asks `server` for a code, shows it with its link, and waits for a person to
160 * approve it. Answers the box's record, already written to the config folder.
161 */
162export async function login(server: string, io: LoginIo, home = homedir()): Promise<BoxRecord> {
163 const fetcher = io.fetch ?? fetch;
164 const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
165 const now = io.now ?? Date.now;
166 const start = await call(server, "/login/device", { name: boxName(), client: "abso" }, undefined, fetcher);
167 const { device_code: device, user_code: code, verification_uri_complete: link } = start.body;
168 let interval = Number(start.body.interval) || 5;
169 const expiresIn = Number(start.body.expires_in) || 900;
170 if (typeof code !== "string" || typeof link !== "string" || typeof device !== "string")
171 throw new UsageError(`${originOf(server)} didn't give a code to approve`);
172 io.say(`To sign this box in, open ${link} and approve the code ${code}.`);
173 const until = now() + expiresIn * 1000;
174 while (now() < until) {
175 await sleep(interval * 1000);
176 const a = await call(server, "/login/token", { device_code: device }, undefined, fetcher);
177 if (a.status === 400) {
178 if (a.body.error === "authorization_pending") continue;
179 if (a.body.error === "slow_down") {
180 interval += 5;
181 continue;
182 }
183 if (a.body.error === "access_denied") throw new UsageError(`the code ${code} was turned down.`);
184 throw new UsageError(`the code ${code} ran out. Run abso login again.`);
185 }
186 const { box_token: credential, box_id: id, grant, expires_at } = a.body;
187 const expiresAt = typeof expires_at === "string" ? Date.parse(expires_at) : Number.NaN;
188 if (typeof credential !== "string" || typeof id !== "string" || !isGrant(grant) || Number.isNaN(expiresAt))
189 throw new UsageError(`${originOf(server)} approved the code but sent no credential`);
190 const record: BoxRecord = { server: originOf(server), id, credential, grant, expiresAt };
191 writeBox(record, home);
192 return record;
193 }
194 throw new UsageError(`nobody approved the code ${code} in time. Run abso login again.`);
195}
197/** An agent's own key, minted from the box's credential: `{key, id}`, as `abso key install` takes it. */
198export async function mintKey(
199 record: BoxRecord,
200 project: string,
201 agent: string,
202 fetcher: typeof fetch = fetch,
203): Promise<{ key: string; id: string }> {
204 const a = await call(record.server, "/box/agent-key", { project, agent }, record.credential, fetcher);
205 const { key, id } = a.body;
206 if (typeof key !== "string" || typeof id !== "string")
207 throw new UsageError(`${record.server} didn't send a key for ${agent}`);
208 return { key, id };
209}
211/** Ends the box on the server, then forgets it here. Forgets it even when the server can't be reached. */
212export async function logout(record: BoxRecord, fetcher: typeof fetch = fetch, home = homedir()): Promise<boolean> {
213 let ended = true;
214 try {
215 await call(record.server, "/box/logout", {}, record.credential, fetcher);
216 } catch {
217 ended = false;
218 }
219 forgetBox(record.server, home);
220 return ended;
221}
223const day = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
225/** What `abso box` prints: the grant, never the credential. */
226export function boxText(record: BoxRecord | undefined, server: string, now = Date.now()): string {
227 if (!record) return `This box isn't signed in to ${originOf(server)}. abso login signs it in.`;
228 const g = record.grant;
229 const expired = record.expiresAt <= now;
230 return [
231 `Signed in to ${record.server} as box ${record.id}${expired ? ", but the sign-in has expired. abso login renews it." : "."}`,
232 `Projects: ${g.projects.map((p) => `${p.project} (${p.role})`).join(", ")}. Up to ${g.max_agents} agents.`,
233 `${expired ? "Expired" : "Expires"} ${day(record.expiresAt)} UTC.`,
234 ].join("\n");
235}
237/** What `abso box --json` answers: the record without its credential. */
238export function boxPublic(
239 record: BoxRecord | undefined,
240): { server: string; id: string; grant: Grant; expiresAt: string } | null {
241 return record
242 ? { server: record.server, id: record.id, grant: record.grant, expiresAt: new Date(record.expiresAt).toISOString() }
243 : null;
244}