Lines 12–66 at 318 (were 12–26 at 87)
1212import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; 1313import { homedir, hostname } from "node:os"; 1414import { dirname, join } from "node:path"; 15−import { UsageError } from "./args.ts";
15+import { type Parsed, str, UsageError } from "./args.ts"; 1616import { 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. */
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. 1922export interface Grant { 2023 readonly projects: readonly { readonly project: string; readonly role: string }[]; 21− readonly max_agents: number;
24+ /** Version 2 grants (abso 663): member-all is every project of the approver's, now and later, at most this role. */ 25+ readonly scopes?: readonly { readonly kind: string; readonly role: string }[]; 28+/** The role a box has in all its approver's projects, now and later, or null when its grant is a list (abso 663). */ 29+export function allProjectsRole(grant: Grant): string | null { 30+ return grant.scopes?.find((scope) => scope.kind === "member-all")?.role ?? null; 33+/** Requested access is a suggestion for the person approving, never an authorization. */ 34+export interface LoginRequest { 35+ readonly projects?: readonly { readonly project: string; readonly role: "reader" | "writer" | "owner" }[]; 36+ readonly days?: number; 39+export function loginRequest(args: Parsed): LoginRequest | undefined { 40+ const projects = str(args, "projects"); 41+ const role = str(args, "role"); 42+ const days = str(args, "days"); 43+ if (projects === undefined && role === undefined && days === undefined) return undefined; 44+ if (role !== undefined && projects === undefined) throw new UsageError("--role needs --projects"); 45+ const requestedRole = role ?? "writer"; 46+ if (requestedRole !== "reader" && requestedRole !== "writer" && requestedRole !== "owner") 47+ throw new UsageError("--role is reader, writer or owner"); 48+ const names = projects?.split(",").map((name) => name.trim()); 49+ if (names && (names.length > 100 || names.some((name) => !/^[A-Za-z0-9._-]+$/.test(name)))) 50+ throw new UsageError( 51+ "--projects is a comma-separated list of up to 100 project names (letters, digits, dot, dash and underscore)", 53+ const integer = (value: string, name: string, max: number): number => { 54+ if (!/^[0-9]+$/.test(value) || !Number.isInteger(Number(value)) || Number(value) < 1 || Number(value) > max) 55+ throw new UsageError(`--${name} is from 1 to ${max}`); 56+ return Number(value); 59+ ...(names ? { projects: [...new Set(names)].map((project) => ({ project, role: requestedRole })) } : {}), 60+ ...(days === undefined ? {} : { days: integer(days, "days", 90) }), 2464export interface BoxRecord { 2565 readonly server: string; 2666 readonly id: string; Lines 161–167 at 318 (were 121–126 at 87)
122162 credential: string | undefined, 123163 fetcher: typeof fetch, 164+ headers: Readonly<Record<string, string>> = {}, 124165): Promise<Answer> { 125166 const secrets = credential ? [credential] : []; 126167 let response: Response; Lines 170–176 at 318 (were 129–134 at 87)
131172 "content-type": "application/json", 132174 ...(credential ? { authorization: `Box ${credential}` } : {}), 134176 body: JSON.stringify(body), Lines 222–228 at 318 (were 180–186 at 87)
182224/** This machine's name, as the server takes a box's name: 1-64 letters, digits, '.', '_' or '-'. */ 183−function boxName(): string {
225+export function boxName(): string { 184226 const name = hostname() 185227 .replace(/[^A-Za-z0-9._-]/g, "-") 186228 .replace(/^[^A-Za-z0-9]+/, "") Lines 236–242 at 318 (were 194–201 at 87)
194236 typeof x === "object" && 196238 Array.isArray(x.projects) && 197− x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string") &&
198− typeof x.max_agents === "number"
239+ x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string") Lines 246–252 at 318 (were 205–210 at 87)
205246const STILL_WAITING_MS = 60_000; 207248export interface LoginIo { 249+ readonly request?: LoginRequest; 208250 readonly fetch?: typeof fetch; 209251 readonly sleep?: (ms: number) => Promise<void>; 210252 readonly now?: () => number; Lines 254–282 at 318 (were 212–219 at 87)
212254 readonly say: (line: string) => void; 213255 /** Opens the approve page in a browser, answering whether it tried. None where it shouldn't (--no-browser, SSH, CI). */ 214256 readonly open?: (url: string) => boolean; 258+ * abso 684: in a joined folder, asks a person in its project to approve this sign-in, through an abso ask, so nobody 259+ * relays the code. Answers who was asked, or null to fall back to the code alone. 261+ readonly ask?: (codes: { readonly device: string; readonly user: string }) => Promise<LoginAsked | null>; 264+/** A sign-in asked of people (abso 684). */ 265+export interface LoginAsked { 266+ readonly project: string; 267+ /** "the person who approved this agent's box", or "the owners of <project>". */ 268+ readonly who: string; 269+ readonly asks: readonly number[]; 270+ /** Milliseconds: when the asked sign-in runs out. */ 271+ readonly expiresAt: number; 272+ /** The most the box may be granted: the asking agent's own role. */ 273+ readonly role: string; 274+ /** Withdraws the asks once nobody answered in time. */ 275+ readonly withdraw: () => Promise<void>; 278+const CENTRAL = new Intl.DateTimeFormat("en-US", { timeZone: "America/Chicago", hour: "numeric", minute: "2-digit" }); 218281 * Asks `server` for a code, shows it with its link, and waits for a person to 219282 * approve it. Answers the box's record, already written to the config folder. Lines 285–297 at 318 (were 222–228 at 87)
222285 const fetcher = io.fetch ?? fetch; 223286 const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))); 224287 const now = io.now ?? Date.now; 225− const start = await call(server, "/login/device", { name: boxName(), client: "abso" }, undefined, fetcher);
288+ const start = await call( 291+ { name: boxName(), client: "abso", ...(io.request ? { requested_grant: io.request } : {}) }, 226295 const { device_code: device, user_code: code, verification_uri_complete: link } = start.body; 227296 let interval = Number(start.body.interval) || 5; 228297 // The server says when its code runs out; a server that says never still gets an end. Lines 299–335 at 318 (were 230–245 at 87)
230299 if (typeof code !== "string" || typeof link !== "string" || typeof device !== "string") 231300 throw new UsageError(`${originOf(server)} didn't give a code to approve`); 232301 // 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;
302+ // A failed ask falls back to the code, and says why, so a person can still approve it (abso 684). 303+ const asked = io.ask 304+ ? await io.ask({ device, user: code }).catch((e: unknown) => { 306+ `Couldn't ask a person to approve this (${e instanceof Error ? e.message : String(e)}), so here is the code.`, 312+ const askWord = asked.asks.length === 1 ? `ask ${asked.asks[0]}` : `asks ${asked.asks.join(", ")}`; 313+ io.say(`Asked ${asked.who} (${askWord} in ${asked.project}) to sign this box in, as at most ${asked.role}.`); 315+ `Waiting for their answer, until ${CENTRAL.format(new Date(asked.expiresAt))} CT. To approve it yourself instead: ${link}`, 318+ if (io.open?.(link)) io.say("Opening the approve page in your browser."); 319+ io.say(`To sign this box in, open ${link} and approve the code ${code}.`); 320+ io.say("Waiting for approval. Ctrl-C stops waiting, and abso stops by itself when the code runs out."); 322+ const until = asked ? Math.min(asked.expiresAt, now() + MAX_LOGIN_WAIT_S * 1000) : now() + expiresIn * 1000; 237323 let toldAt = now(); 238324 while (now() < until) { 239325 await sleep(interval * 1000); 240326 // A wait with no word looks like a hang, so say it's still waiting now and then. 241327 if (now() - toldAt >= STILL_WAITING_MS) { 242− io.say(`Still waiting for the code ${code} to be approved.`);
330+ ? `Still waiting (${asked.who} hasn't answered yet).` 331+ : `Still waiting for the code ${code} to be approved.`, 245335 const a = await call(server, "/login/token", { device_code: device }, undefined, fetcher); Lines 339–352 at 318 (were 249–256 at 87)
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.`);
342+ if (a.body.error === "access_denied") 343+ throw new UsageError(asked ? `${asked.who} turned this sign-in down.` : `the code ${code} was turned down.`); 344+ if (asked) await asked.withdraw().catch(() => undefined); 345+ throw new UsageError( 347+ ? "nobody answered in time, so nothing was granted. Run abso login again." 348+ : `the code ${code} ran out. Run abso login again.`, 255351 const { box_token: credential, box_id: id, grant, expires_at } = a.body; 256352 const expiresAt = typeof expires_at === "string" ? Date.parse(expires_at) : Number.NaN; Lines 356–365 at 318 (were 260–265 at 87)
260356 writeBox(record, home); 360+ await asked.withdraw().catch(() => undefined); 361+ throw new UsageError("nobody answered in time, so nothing was granted. Run abso login again."); 263363 throw new UsageError(`nobody approved the code ${code} in time. Run abso login again.`); Lines 377–436 at 318 (were 277–282 at 87)
277377 return { key, id }; 380+/** What a new project from this box starts with (abso 663): the website's own create, as the person who approved the box. */ 381+export interface NewProject { 382+ readonly name: string; 383+ readonly owner?: string; 384+ readonly visibility?: "public" | "private"; 385+ readonly files?: readonly ( 386+ | { readonly path: string; readonly text: string } 387+ | { readonly path: string; readonly base64: string } 392+ * Makes a project as the person who approved this box (abso init, abso 663). One key for every try, so a retry after 393+ * a lost answer or a pending one is the same project, never a second. 395+export async function boxCreateProject( 397+ project: NewProject, 399+ fetcher: typeof fetch = fetch, 400+ sleep: (ms: number) => Promise<void> = (ms) => new Promise((done) => setTimeout(done, ms)), 401+): Promise<Record<string, unknown>> { 402+ for (let attempt = 1; ; attempt++) { 403+ const a = await call(record.server, "/box/projects", project, record.credential, fetcher, { 404+ "Idempotency-Key": key, 406+ const pending = (a.body.operation as { state?: unknown } | undefined)?.state === "pending"; 407+ if (!pending) return a.body; 409+ throw new UsageError( 410+ `${originOf(record.server)} is still making ${project.name}. Run the same abso init again in a minute: it picks up where this left off.`, 412+ await sleep(1000 * attempt); 416+/** Makes an organization as the person who approved this box (abso org new, abso 663). */ 417+export async function boxCreateOrg( 420+ displayName: string | undefined, 421+ fetcher: typeof fetch = fetch, 422+): Promise<Record<string, unknown>> { 427+ { name, ...(displayName === undefined ? {} : { displayName }) }, 280434/** The agent name abso join takes when none is given: the box's name, lower-cased. */ 281435export function defaultAgentName(): string { 282436 return boxName().toLowerCase(); Lines 463–468 at 318 (were 309–318 at 87)
309463 return { ...(await mintKey(record, project, agent, fetcher)), agent }; 311465 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− );
Lines 490–501 at 318 (were 340–348 at 87)
340490 if (!record) return `This box isn't signed in to ${originOf(server)}. abso login signs it in.`; 341491 const g = record.grant; 342492 const expired = record.expiresAt <= now; 493+ const all = allProjectsRole(g); 344495 `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.`,
497+ ? `Projects: ${g.projects.map((p) => `${p.project} (${p.role})`).join(", ")}.` 498+ : `Projects: all of yours, now and later (${all} at most). abso init makes a new one; abso org new makes an organization.`, 346499 `${expired ? "Expired" : "Expires"} ${day(record.expiresAt)} UTC.`,