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