- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/test/box.test.ts?version=147&format=json
439 linesFirst import 43% · codex-mac-1 23% · trials 15% · speed 13% · pinch 5% · review 1%Last change codex-mac-1 in version 102, 8 versions changed it
You're reading version 147. The newest is 318, and 4 versions since then changed this file.
1// Signing in once per box (abso issue 108): login waits for approval and keeps
2// the credential outside every project folder; it never shows up in output and
3// only goes to the server that issued it.
5import assert from "node:assert/strict";
6import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
7import { tmpdir } from "node:os";
8import { join } from "node:path";
9import { test } from "node:test";
10import { parseArgs } from "../src/args.ts";
11import {
12 boxPublic,
13 boxText,
14 forgetBox,
15 login,
16 loginRequest,
17 logout,
18 mintFreeName,
19 mintKey,
20 readBox,
21 signedInServers,
22 writeBox,
23} from "../src/box.ts";
24import { serverFrom } from "../src/join-commands.ts";
25import { main } from "../src/main.ts";
27const SERVER = "https://staging.abso.example";
28const CREDENTIAL = "abso_bx_the-secret-credential";
29const grant = {
30 projects: [
31 { project: "abso", role: "writer" },
32 { project: "game", role: "reader" },
33 ],
34 max_agents: 5,
35};
36const EXPIRES = "2026-10-15T00:00:00.000Z";
37const record = { server: SERVER, id: "b_0123abcd", credential: CREDENTIAL, grant, expiresAt: Date.parse(EXPIRES) };
39const home = () => mkdtempSync(join(tmpdir(), "abso-box-"));
41type Seen = { url: string; auth: string | null; body: unknown }[];
42function server(answers: [number, unknown][], seen: Seen): typeof fetch {
43 return (async (url, init) => {
44 seen.push({
45 url: String(url),
46 auth: new Headers(init?.headers).get("authorization"),
47 body: JSON.parse(String(init?.body ?? "null")),
48 });
49 const [status, body] = answers.shift() ?? [500, { error: "no more answers" }];
50 return new Response(JSON.stringify(body), { status });
51 }) as typeof fetch;
52}
54const started = {
55 device_code: "device-code-long-enough",
56 user_code: "WXYZ-BCDF",
57 verification_uri_complete: "https://abso.dev/login/box?code=WXYZ-BCDF",
58 expires_in: 60,
59 interval: 2,
60};
62function clock() {
63 let t = 0;
64 return {
65 sleep: async (ms: number) => {
66 t += ms;
67 },
68 now: () => t,
69 slept: () => t,
70 };
71}
73test("login grant options validate project lists, roles, limits and duration", () => {
74 const request = (...words: string[]) =>
75 loginRequest(
76 parseArgs("login", words, {
77 projects: "string",
78 role: "string",
79 "max-agents": "string",
80 days: "string",
81 }),
82 );
83 assert.equal(request(), undefined);
84 assert.deepEqual(request("--projects", "alpha, beta,alpha", "--max-agents", "1", "--days", "30"), {
85 projects: [
86 { project: "alpha", role: "writer" },
87 { project: "beta", role: "writer" },
88 ],
89 max_agents: 1,
90 days: 30,
91 });
92 assert.deepEqual(request("--projects", "alpha", "--role", "reader"), {
93 projects: [{ project: "alpha", role: "reader" }],
94 });
95 assert.deepEqual(request("--projects", "alpha", "--role", "owner"), {
96 projects: [{ project: "alpha", role: "owner" }],
97 });
98 assert.deepEqual(request("--max-agents", "50", "--days", "90"), { max_agents: 50, days: 90 });
99 for (const words of [
100 ["--role", "writer"],
101 ["--projects", ""],
102 ["--projects", "alpha,"],
103 ["--projects", "../alpha"],
104 ["--projects", "alpha", "--role", "admin"],
105 ["--projects", Array.from({ length: 101 }, (_, i) => `p${i}`).join(",")],
106 ])
107 assert.throws(() => request(...words));
108 for (const flag of ["--max-agents", "--days"]) {
109 for (const value of ["0", "-1", "1.5", "1e1", "Infinity", "100", "abc", ""])
110 assert.throws(() => request(flag, value));
111 }
112});
114test("login sends requested grants only at device start and retains the user's actual approval", async () => {
115 const h = home();
116 const seen: Seen = [];
117 const c = clock();
118 const requested = { projects: [{ project: "abso", role: "owner" as const }], max_agents: 10, days: 90 };
119 const approved = { projects: [{ project: "abso", role: "reader" }], max_agents: 1 };
120 const got = await login(
121 SERVER,
122 {
123 request: requested,
124 fetch: server(
125 [
126 [200, started],
127 [400, { error: "authorization_pending" }],
128 [200, { box_id: "b_test", box_token: CREDENTIAL, expires_at: EXPIRES, grant: approved }],
129 ],
130 seen,
131 ),
132 sleep: c.sleep,
133 now: c.now,
134 say: () => {},
135 },
136 h,
137 );
138 assert.ok(seen[0]);
139 assert.deepEqual((seen[0].body as Record<string, unknown>).requested_grant, requested);
140 assert.deepEqual(
141 seen.slice(1).map((call) => call.body),
142 [{ device_code: started.device_code }, { device_code: started.device_code }],
143 );
144 assert.deepEqual(got.grant, approved);
145 assert.deepEqual(readBox(SERVER, h)?.grant, approved);
146});
148test("invalid login grant flags fail before a network request through the CLI", async () => {
149 const original = globalThis.fetch;
150 let calls = 0;
151 globalThis.fetch = (async () => {
152 calls++;
153 throw new Error("unexpected request");
154 }) as typeof fetch;
155 try {
156 const result = await main(["login", "--projects", "alpha", "--days", "0", "--no-browser"], {
157 cwd: home(),
158 env: {},
159 write: () => {},
160 });
161 assert.equal(result.exit, 1);
162 assert.match(result.stderr, /--days is from 1 to 90/);
163 assert.equal(calls, 0);
164 } finally {
165 globalThis.fetch = original;
166 }
167});
169test("login shows the code, waits while it's pending, and keeps the credential in the user folder", async () => {
170 const h = home();
171 const seen: Seen = [];
172 const said: string[] = [];
173 const c = clock();
174 const got = await login(
175 `${SERVER}/some/path`,
176 {
177 fetch: server(
178 [
179 [200, started],
180 [400, { error: "authorization_pending" }],
181 [400, { error: "slow_down" }],
182 [200, { box_id: "b_0123abcd", box_token: CREDENTIAL, expires_at: EXPIRES, grant }],
183 ],
184 seen,
185 ),
186 sleep: c.sleep,
187 now: c.now,
188 say: (line) => said.push(line),
189 },
190 h,
191 );
192 assert.equal(got.server, SERVER);
193 assert.deepEqual(
194 seen.map((s) => s.url),
195 [`${SERVER}/login/device`, `${SERVER}/login/token`, `${SERVER}/login/token`, `${SERVER}/login/token`],
196 );
197 assert.deepEqual(seen[1]?.body, { device_code: "device-code-long-enough" });
198 assert.equal(c.slept(), 2000 + 2000 + 7000, "slow_down adds 5 s to the wait");
199 assert.ok(
200 seen.every((s) => s.auth === null),
201 "nothing is sent with login's calls",
202 );
203 assert.deepEqual(said, [
204 "To sign this box in, open https://abso.dev/login/box?code=WXYZ-BCDF and approve the code WXYZ-BCDF.",
205 "Waiting for approval. Ctrl-C stops waiting, and abso stops by itself when the code runs out.",
206 ]);
207 assert.equal(readBox(SERVER, h)?.credential, CREDENTIAL);
208 const files = readdirSync(join(h, ".abso", "boxes"));
209 assert.equal(files.length, 1);
210 assert.ok(readFileSync(join(h, ".abso", "boxes", files[0]!), "utf8").includes(CREDENTIAL));
211 assert.equal(boxText(got, SERVER, 0).includes(CREDENTIAL), false);
212 assert.match(boxText(got, SERVER, 0), /abso \(writer\), game \(reader\)\. Up to 5 agents\./);
213 assert.equal(JSON.stringify(boxPublic(got)).includes(CREDENTIAL), false);
214});
216test("login opens the approve page with the code in it, and prints the link and code all the same", async () => {
217 const said: string[] = [];
218 const opened: string[] = [];
219 const c = clock();
220 await login(
221 SERVER,
222 {
223 fetch: server(
224 [
225 [200, started],
226 [200, { box_id: "b_0123abcd", box_token: CREDENTIAL, expires_at: EXPIRES, grant }],
227 ],
228 [],
229 ),
230 sleep: c.sleep,
231 now: c.now,
232 say: (line) => said.push(line),
233 open: (url) => (opened.push(url), true),
234 },
235 home(),
236 );
237 assert.deepEqual(opened, ["https://abso.dev/login/box?code=WXYZ-BCDF"]);
238 assert.deepEqual(said.slice(0, 2), [
239 "Opening the approve page in your browser.",
240 "To sign this box in, open https://abso.dev/login/box?code=WXYZ-BCDF and approve the code WXYZ-BCDF.",
241 ]);
242});
244test("an open that doesn't start says nothing about a browser, and the printed link stands", async () => {
245 const said: string[] = [];
246 const c = clock();
247 await login(
248 SERVER,
249 {
250 fetch: server(
251 [
252 [200, started],
253 [200, { box_id: "b_0123abcd", box_token: CREDENTIAL, expires_at: EXPIRES, grant }],
254 ],
255 [],
256 ),
257 sleep: c.sleep,
258 now: c.now,
259 say: (line) => said.push(line),
260 open: () => false,
261 },
262 home(),
263 );
264 assert.equal(
265 said[0],
266 "To sign this box in, open https://abso.dev/login/box?code=WXYZ-BCDF and approve the code WXYZ-BCDF.",
267 );
268 assert.equal(
269 said.some((l) => l.includes("browser")),
270 false,
271 );
272});
274test("a code that's turned down or runs out says so and keeps nothing", async () => {
275 const h = home();
276 const c = clock();
277 const io = { sleep: c.sleep, now: c.now, say: () => {} };
278 await assert.rejects(
279 login(
280 SERVER,
281 {
282 ...io,
283 fetch: server(
284 [
285 [200, started],
286 [400, { error: "access_denied" }],
287 ],
288 [],
289 ),
290 },
291 h,
292 ),
293 /was turned down/,
294 );
295 await assert.rejects(
296 login(
297 SERVER,
298 {
299 ...io,
300 fetch: server(
301 [
302 [200, started],
303 [400, { error: "expired_token" }],
304 ],
305 [],
306 ),
307 },
308 h,
309 ),
310 /ran out\. Run abso login again/,
311 );
312 await assert.rejects(
313 login(
314 SERVER,
315 {
316 ...io,
317 fetch: server(
318 [
319 [200, { ...started, expires_in: 3 }],
320 [400, { error: "authorization_pending" }],
321 [400, { error: "authorization_pending" }],
322 ],
323 [],
324 ),
325 },
326 h,
327 ),
328 /in time\. Run abso login again/,
329 );
330 assert.equal(readBox(SERVER, h), undefined);
331});
333test("login says it's still waiting about once a minute, and stops in the end whatever the server says", async () => {
334 const c = clock();
335 const said: string[] = [];
336 const pending = Array.from({ length: 2000 }, (): [number, unknown] => [400, { error: "authorization_pending" }]);
337 await assert.rejects(
338 login(
339 SERVER,
340 {
341 fetch: server([[200, { ...started, expires_in: 10 ** 9, interval: 5 }], ...pending], []),
342 sleep: c.sleep,
343 now: c.now,
344 say: (line) => said.push(line),
345 },
346 home(),
347 ),
348 /nobody approved the code WXYZ-BCDF in time\. Run abso login again\./,
349 );
350 assert.equal(c.slept(), 30 * 60 * 1000, "a server that says never still gets an end");
351 const still = said.filter((line) => line === "Still waiting for the code WXYZ-BCDF to be approved.");
352 assert.equal(still.length, 30);
353 assert.equal(said.length, 2 + 30);
354});
356test("a key is minted with the box credential, sent only to the box's own server", async () => {
357 const seen: Seen = [];
358 const minted = await mintKey(
359 record,
360 "abso",
361 "tester-1",
362 server([[200, { key: "abso_sk_x", id: "k_0123abcd" }]], seen),
363 );
364 assert.deepEqual(minted, { key: "abso_sk_x", id: "k_0123abcd" });
365 assert.equal(seen[0]?.url.startsWith(`${SERVER}/`), true);
366 assert.equal(seen[0]?.auth, `Box ${CREDENTIAL}`);
367 await assert.rejects(
368 mintKey(record, "secret-project", "a", server([[403, { error: `outside the grant ${CREDENTIAL}` }]], [])),
369 (e: Error) => /refused \(403\)/.test(e.message) && !e.message.includes(CREDENTIAL),
370 );
371});
373test("a box's sign-in is kept per server, and logout forgets it even when the server is down", async () => {
374 const h = home();
375 writeBox(record, h);
376 assert.equal(readBox("https://abso.example", h), undefined, "another server's box isn't this one");
377 assert.match(boxText(undefined, SERVER), /isn't signed in/);
378 const down = (async () => {
379 throw new Error("offline");
380 }) as typeof fetch;
381 assert.equal(await logout(readBox(SERVER, h)!, down, h), false);
382 assert.equal(readBox(SERVER, h), undefined);
383 assert.equal(forgetBox(SERVER, h), false);
384});
386test("join and init pick the server: --server, ABSO_SERVER, the box's sign-in, then api.abso.dev", () => {
387 const h = home();
388 const args = (server?: string) => ({ positionals: [], flags: new Map(server ? [["server", server]] : []) });
389 const none = { env: {} };
390 assert.equal(serverFrom(args(), none, h), "https://api.abso.dev", "nothing signed in: the abso API");
391 writeBox({ ...record, expiresAt: Date.now() + 1e6 }, h);
392 assert.deepEqual(signedInServers(h), [SERVER]);
393 assert.equal(serverFrom(args(), none, h), SERVER, "the server abso login signed this box in to");
394 assert.deepEqual(signedInServers(h, Date.now() + 2e6), [], "an expired sign-in doesn't count");
395 assert.equal(serverFrom(args(), { env: { ABSO_SERVER: "https://env.example" } }, h), "https://env.example");
396 assert.equal(
397 serverFrom(args("https://flag.example"), { env: { ABSO_SERVER: "https://env.example" } }, h),
398 "https://flag.example",
399 );
400 writeBox({ ...record, server: "https://other.abso.example", expiresAt: Date.now() + 1e6 }, h);
401 writeBox({ ...record, expiresAt: Date.now() + 1e6 }, h);
402 assert.throws(
403 () => serverFrom(args(), none, h),
404 /signed in to https:\/\/other\.abso\.example and https:\/\/staging\.abso\.example: say which with --server/,
405 );
406 assert.equal(serverFrom(args(SERVER), none, h), SERVER, "--server settles it");
407});
409test("join with no --agent takes the box's name, skips names this box holds, and moves past a taken one", async () => {
410 const seen: Seen = [];
411 const fetcher = server(
412 [
413 [200, { box_id: record.id, agents: [{ project: "abso", agent: "snow", key_id: "k_0" }] }],
414 [409, { error: "that agent name is already in use in this project; pick a new one" }],
415 [200, { key: "abso_sk_new", id: "k_3" }],
416 ],
417 seen,
418 );
419 const got = await mintFreeName(record, "abso", "snow", fetcher);
420 assert.deepEqual(got, { key: "abso_sk_new", id: "k_3", agent: "snow-3" });
421 assert.deepEqual(
422 seen.map((s) => [new URL(s.url).pathname, (s.body as { agent?: string } | null)?.agent ?? null]),
423 [
424 ["/box", null],
425 ["/box/agent-key", "snow-2"],
426 ["/box/agent-key", "snow-3"],
427 ],
428 "snow is this box's already: never minted again, which would replace its key",
429 );
431 const limit = server(
432 [
433 [200, { box_id: record.id, agents: [] }],
434 [409, { error: "this box is at its agent limit" }],
435 ],
436 [],
437 );
438 await assert.rejects(mintFreeName(record, "abso", "snow", limit), /this box is at its agent limit \(5\)/);
439});