- MCP
- blame on this site's /mcp
- CLI
- abso blame client/src/box.ts --draft login-wait --json
- JSON
- /christopher/abso-core/blame/client/src/box.ts?draft=login-wait&format=json
271 linesFirst import 85% · pinch 11% · review 5%Last change pinch in version 34,
271 lines from 4 changes in 3 versions.
init0Start the project1// 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
pinch34Client: abso orgs and abso org <name>, reading as the person who approved this box's sign-in (abso login): your organizations and roles, invitations waiting for you, and an org's projects, people (by name, never id), settings and open invites. Changes (--invite, --role, --remove, --leave, --members, --projects-by), abso org new and abso init --org are made on the website for now; each says where and sends nothing. One change at a time. MCP serves orgs and org. Client tests 283/283, tsc and biome clean.Compare8// 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";
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare12import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare14import { dirname, join } from "node:path";
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare16import { homeFile, homeWritePath, OLD_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;
22}
24export interface BoxRecord {
25 readonly server: string;
26 readonly id: string;
27 readonly credential: string;
28 readonly grant: Grant;
29 readonly expiresAt: number;
30}
32export function originOf(server: string): string {
33 try {
34 return new URL(server).origin;
35 } catch {
36 return server;
37 }
38}
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare40function 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 {
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare46 const raw = JSON.parse(readFileSync(homeFile(home, "boxes", boxFile(server)), "utf8")) as Partial<BoxRecord>;
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 }
60}
62export function writeBox(record: BoxRecord, home = homedir()): void {
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare63 const path = homeWritePath(home, "boxes", boxFile(record.server));
64 mkdirSync(dirname(path), { recursive: true });
66 try {
67 chmodSync(path, 0o600);
68 } catch {
69 // Windows has no owner-only mode; the file is still outside every project folder.
70 }
71}
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare73/** Logout ends the sign-in everywhere on this machine: the credential under ~/.abso and any older copy under ~/.avcs. */
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare75 const paths = [homeWritePath(home, "boxes", boxFile(server)), join(home, OLD_STATE_DIR, "boxes", boxFile(server))];
76 const had = paths.filter((path) => existsSync(path));
77 for (const path of had) rmSync(path, { force: true });
78 return had.length > 0;
81/** Error text with the credential (and anything shaped like a key) taken out. */
82function scrub(text: string, secrets: readonly string[]): string {
83 let out = text.replace(/abso_(sk|bx)_[A-Za-z0-9_-]+/g, "[redacted]");
84 for (const s of secrets) if (s.length > 0) out = out.split(s).join("[redacted]");
85 return out;
86}
pinch34Client: abso orgs and abso org <name>, reading as the person who approved this box's sign-in (abso login): your organizations and roles, invitations waiting for you, and an org's projects, people (by name, never id), settings and open invites. Changes (--invite, --role, --remove, --leave, --members, --projects-by), abso org new and abso init --org are made on the website for now; each says where and sends nothing. One change at a time. MCP serves orgs and org. Client tests 283/283, tsc and biome clean.Compare88export interface Answer {
90 readonly body: Record<string, unknown>;
91}
93async function call(
94 server: string,
95 path: string,
96 body: unknown,
97 credential: string | undefined,
98 fetcher: typeof fetch,
99): Promise<Answer> {
100 const secrets = credential ? [credential] : [];
101 let response: Response;
102 try {
103 response = await fetcher(`${originOf(server)}${path}`, {
104 method: "POST",
105 headers: {
106 "content-type": "application/json",
107 ...(credential ? { authorization: `Box ${credential}` } : {}),
108 },
109 body: JSON.stringify(body),
110 signal: AbortSignal.timeout(30_000),
111 });
112 } catch (err) {
113 throw new UsageError(
114 `couldn't reach ${originOf(server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
115 );
116 }
117 const text = await response.text();
118 let parsed: Record<string, unknown> = {};
119 try {
120 parsed = JSON.parse(text) as Record<string, unknown>;
121 } catch {
122 if (response.ok) throw new UsageError(`${originOf(server)}${path} didn't answer JSON`);
123 }
124 if (!response.ok && !(response.status === 400 && path === "/login/token")) {
125 const said = typeof parsed.error === "string" ? parsed.error : text.slice(0, 300);
126 throw new UsageError(scrub(`${originOf(server)} refused (${response.status}): ${said}`, secrets));
127 }
128 return { status: response.status, body: parsed };
129}
pinch34Client: abso orgs and abso org <name>, reading as the person who approved this box's sign-in (abso login): your organizations and roles, invitations waiting for you, and an org's projects, people (by name, never id), settings and open invites. Changes (--invite, --role, --remove, --leave, --members, --projects-by), abso org new and abso init --org are made on the website for now; each says where and sends nothing. One change at a time. MCP serves orgs and org. Client tests 283/283, tsc and biome clean.Compare131/**
132 * A read that answers as the person who approved this box: the org reads (GET /orgs, /orgs/<name>). Answers the
133 * status and body as they came, refusals included, so the caller can say what each means; never the credential.
134 */
135export async function boxGet(record: BoxRecord, path: string, fetcher: typeof fetch = fetch): Promise<Answer> {
136 const secrets = [record.credential];
137 let response: Response;
138 try {
139 response = await fetcher(`${originOf(record.server)}${path}`, {
140 headers: { authorization: `Box ${record.credential}` },
141 signal: AbortSignal.timeout(30_000),
142 });
143 } catch (err) {
144 throw new UsageError(
145 `couldn't reach ${originOf(record.server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
146 );
147 }
148 const text = await response.text();
149 try {
150 const body = JSON.parse(text) as unknown;
151 if (typeof body === "object" && body !== null && !Array.isArray(body))
152 return { status: response.status, body: body as Record<string, unknown> };
153 } catch {}
154 return { status: response.status, body: { error: scrub(text.slice(0, 300), secrets) } };
155}
init0Start the project157/** This machine's name, as the server takes a box's name: 1-64 letters, digits, '.', '_' or '-'. */
158function boxName(): string {
159 const name = hostname()
160 .replace(/[^A-Za-z0-9._-]/g, "-")
161 .replace(/^[^A-Za-z0-9]+/, "")
162 .slice(0, 64);
163 return name || "box";
164}
166function isGrant(g: unknown): g is Grant {
167 const x = g as Partial<Grant> | null;
168 return (
169 typeof x === "object" &&
170 x !== null &&
171 Array.isArray(x.projects) &&
172 x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string") &&
173 typeof x.max_agents === "number"
174 );
175}
177export interface LoginIo {
178 readonly fetch?: typeof fetch;
179 readonly sleep?: (ms: number) => Promise<void>;
180 readonly now?: () => number;
181 /** Where the code and link go while login waits: stderr, so stdout stays quiet. */
182 readonly say: (line: string) => void;
183}
185/**
186 * Asks `server` for a code, shows it with its link, and waits for a person to
187 * approve it. Answers the box's record, already written to the config folder.
188 */
189export async function login(server: string, io: LoginIo, home = homedir()): Promise<BoxRecord> {
190 const fetcher = io.fetch ?? fetch;
191 const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
192 const now = io.now ?? Date.now;
193 const start = await call(server, "/login/device", { name: boxName(), client: "abso" }, undefined, fetcher);
194 const { device_code: device, user_code: code, verification_uri_complete: link } = start.body;
195 let interval = Number(start.body.interval) || 5;
196 const expiresIn = Number(start.body.expires_in) || 900;
197 if (typeof code !== "string" || typeof link !== "string" || typeof device !== "string")
198 throw new UsageError(`${originOf(server)} didn't give a code to approve`);
199 io.say(`To sign this box in, open ${link} and approve the code ${code}.`);
200 const until = now() + expiresIn * 1000;
201 while (now() < until) {
202 await sleep(interval * 1000);
203 const a = await call(server, "/login/token", { device_code: device }, undefined, fetcher);
204 if (a.status === 400) {
205 if (a.body.error === "authorization_pending") continue;
206 if (a.body.error === "slow_down") {
207 interval += 5;
208 continue;
209 }
210 if (a.body.error === "access_denied") throw new UsageError(`the code ${code} was turned down.`);
211 throw new UsageError(`the code ${code} ran out. Run abso login again.`);
212 }
213 const { box_token: credential, box_id: id, grant, expires_at } = a.body;
214 const expiresAt = typeof expires_at === "string" ? Date.parse(expires_at) : Number.NaN;
215 if (typeof credential !== "string" || typeof id !== "string" || !isGrant(grant) || Number.isNaN(expiresAt))
216 throw new UsageError(`${originOf(server)} approved the code but sent no credential`);
217 const record: BoxRecord = { server: originOf(server), id, credential, grant, expiresAt };
218 writeBox(record, home);
219 return record;
220 }
221 throw new UsageError(`nobody approved the code ${code} in time. Run abso login again.`);
222}
224/** An agent's own key, minted from the box's credential: `{key, id}`, as `abso key install` takes it. */
225export async function mintKey(
226 record: BoxRecord,
227 project: string,
228 agent: string,
229 fetcher: typeof fetch = fetch,
230): Promise<{ key: string; id: string }> {
231 const a = await call(record.server, "/box/agent-key", { project, agent }, record.credential, fetcher);
232 const { key, id } = a.body;
233 if (typeof key !== "string" || typeof id !== "string")
234 throw new UsageError(`${record.server} didn't send a key for ${agent}`);
235 return { key, id };
236}
238/** Ends the box on the server, then forgets it here. Forgets it even when the server can't be reached. */
239export async function logout(record: BoxRecord, fetcher: typeof fetch = fetch, home = homedir()): Promise<boolean> {
240 let ended = true;
241 try {
242 await call(record.server, "/box/logout", {}, record.credential, fetcher);
243 } catch {
244 ended = false;
245 }
246 forgetBox(record.server, home);
247 return ended;
248}
250const day = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
252/** What `abso box` prints: the grant, never the credential. */
253export function boxText(record: BoxRecord | undefined, server: string, now = Date.now()): string {
254 if (!record) return `This box isn't signed in to ${originOf(server)}. abso login signs it in.`;
255 const g = record.grant;
256 const expired = record.expiresAt <= now;
257 return [
258 `Signed in to ${record.server} as box ${record.id}${expired ? ", but the sign-in has expired. abso login renews it." : "."}`,
259 `Projects: ${g.projects.map((p) => `${p.project} (${p.role})`).join(", ")}. Up to ${g.max_agents} agents.`,
260 `${expired ? "Expired" : "Expires"} ${day(record.expiresAt)} UTC.`,
261 ].join("\n");
262}
264/** What `abso box --json` answers: the record without its credential. */
265export function boxPublic(
266 record: BoxRecord | undefined,
267): { server: string; id: string; grant: Grant; expiresAt: string } | null {
268 return record
269 ? { server: record.server, id: record.id, grant: record.grant, expiresAt: new Date(record.expiresAt).toISOString() }
270 : null;
271}