@catamorphic/work-server 0.1.0-alpha.39 → 0.1.0-alpha.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/NOTICE.txt +7 -0
  2. package/README.md +9 -9
  3. package/dist/admission/routes.d.ts +1 -1
  4. package/dist/admission/routes.d.ts.map +1 -1
  5. package/dist/agent-capabilities.d.ts.map +1 -1
  6. package/dist/agents.d.ts +5 -6
  7. package/dist/agents.d.ts.map +1 -1
  8. package/dist/auth/fastify-auth.d.ts.map +1 -1
  9. package/dist/auth/work-auth-types.d.ts +2 -0
  10. package/dist/auth/work-auth-types.d.ts.map +1 -1
  11. package/dist/auth/work-auth.d.ts.map +1 -1
  12. package/dist/chunk-kcck20aw.js +676 -0
  13. package/dist/chunk-kcck20aw.js.map +11 -0
  14. package/dist/cluster.d.ts +8 -7
  15. package/dist/cluster.d.ts.map +1 -1
  16. package/dist/config.d.ts +5 -15
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/execution-config.d.ts +22 -0
  19. package/dist/execution-config.d.ts.map +1 -1
  20. package/dist/fake-agent.d.ts +1 -0
  21. package/dist/fake-agent.d.ts.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2730 -2851
  25. package/dist/index.js.map +28 -28
  26. package/dist/machines/contract-kit.d.ts +91 -0
  27. package/dist/machines/contract-kit.d.ts.map +1 -0
  28. package/dist/machines/contract.d.ts +383 -0
  29. package/dist/machines/contract.d.ts.map +1 -0
  30. package/dist/machines/sequencer.d.ts +267 -0
  31. package/dist/machines/sequencer.d.ts.map +1 -0
  32. package/dist/machines/simulation.d.ts +124 -0
  33. package/dist/machines/simulation.d.ts.map +1 -0
  34. package/dist/machines/work-machines.d.ts +61 -0
  35. package/dist/machines/work-machines.d.ts.map +1 -0
  36. package/dist/server.d.ts +15 -11
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/setup/machines.d.ts +9 -17
  39. package/dist/setup/machines.d.ts.map +1 -1
  40. package/dist/shares/share-routes.d.ts +1 -1
  41. package/dist/shares/share-routes.d.ts.map +1 -1
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -0
  44. package/dist/testing.js +1013 -0
  45. package/dist/testing.js.map +11 -0
  46. package/dist/workers/disk-care.d.ts +41 -0
  47. package/dist/workers/disk-care.d.ts.map +1 -0
  48. package/dist/workers/harness-sign-ins.d.ts +146 -0
  49. package/dist/workers/harness-sign-ins.d.ts.map +1 -0
  50. package/dist/workers/machine-store.d.ts +196 -0
  51. package/dist/workers/machine-store.d.ts.map +1 -0
  52. package/dist/workers/member-machine-routes.d.ts +5 -3
  53. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  54. package/dist/workers/member-machines.d.ts +47 -28
  55. package/dist/workers/member-machines.d.ts.map +1 -1
  56. package/dist/workers/placement.d.ts +23 -40
  57. package/dist/workers/placement.d.ts.map +1 -1
  58. package/dist/workers/sign-ins.d.ts +44 -17
  59. package/dist/workers/sign-ins.d.ts.map +1 -1
  60. package/dist/workers/worker-protocol.d.ts +5 -2
  61. package/dist/workers/worker-protocol.d.ts.map +1 -1
  62. package/dist/workers/worker-registry.d.ts +174 -223
  63. package/dist/workers/worker-registry.d.ts.map +1 -1
  64. package/dist/workers/worker-routes.d.ts.map +1 -1
  65. package/dist/workers/worker-runtime.d.ts.map +1 -1
  66. package/package.json +31 -21
  67. package/src/admission/routes.ts +5 -2
  68. package/src/agent-capabilities.ts +22 -8
  69. package/src/agents.ts +52 -23
  70. package/src/auth/fastify-auth.ts +149 -17
  71. package/src/auth/work-auth-types.ts +2 -0
  72. package/src/auth/work-auth.ts +27 -0
  73. package/src/cluster.ts +115 -42
  74. package/src/config.ts +15 -41
  75. package/src/execution-config.ts +40 -0
  76. package/src/fake-agent.ts +21 -4
  77. package/src/index.ts +26 -12
  78. package/src/machines/contract-kit.ts +648 -0
  79. package/src/machines/contract.ts +522 -0
  80. package/src/machines/sequencer.ts +1010 -0
  81. package/src/machines/simulation.ts +833 -0
  82. package/src/machines/work-machines.ts +231 -0
  83. package/src/server.ts +235 -150
  84. package/src/setup/machines.ts +128 -121
  85. package/src/shares/share-routes.ts +17 -1
  86. package/src/testing.ts +22 -0
  87. package/src/workers/disk-care.ts +121 -0
  88. package/src/workers/fake-claude-cli.ts +95 -0
  89. package/src/workers/fake-codex-cli.ts +11 -4
  90. package/src/workers/harness-sign-ins.ts +580 -0
  91. package/src/workers/machine-store.ts +1065 -0
  92. package/src/workers/member-machine-routes.ts +92 -20
  93. package/src/workers/member-machines.ts +163 -99
  94. package/src/workers/placement.ts +59 -70
  95. package/src/workers/sign-ins.ts +109 -52
  96. package/src/workers/worker-protocol.ts +5 -2
  97. package/src/workers/worker-registry.ts +894 -754
  98. package/src/workers/worker-routes.ts +4 -1
  99. package/src/workers/worker-runtime.ts +55 -23
  100. package/dist/test-support.d.ts +0 -133
  101. package/dist/test-support.d.ts.map +0 -1
  102. package/dist/workers/codex-sign-ins.d.ts +0 -107
  103. package/dist/workers/codex-sign-ins.d.ts.map +0 -1
  104. package/dist/workers/install-script.d.ts +0 -71
  105. package/dist/workers/install-script.d.ts.map +0 -1
  106. package/dist/workers/machine-classes.d.ts +0 -115
  107. package/dist/workers/machine-classes.d.ts.map +0 -1
  108. package/dist/workers/machine-rules.d.ts +0 -402
  109. package/dist/workers/machine-rules.d.ts.map +0 -1
  110. package/src/test-support.ts +0 -404
  111. package/src/workers/codex-sign-ins.ts +0 -360
  112. package/src/workers/install-script.ts +0 -394
  113. package/src/workers/machine-classes.ts +0 -152
  114. package/src/workers/machine-rules.ts +0 -1954
@@ -0,0 +1,580 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import type { Readable } from "node:stream";
5
+ import {
6
+ SIGN_IN_SPECS,
7
+ type SignInHarness,
8
+ type SignInSpec,
9
+ } from "@catamorphic/sandbox";
10
+ import { z } from "zod";
11
+ import {
12
+ assertMachineFree,
13
+ MachineHeldError,
14
+ noSignInLeft,
15
+ placeSignIn,
16
+ signedIn,
17
+ signInCommand,
18
+ signInEnvironment,
19
+ signOutOnMachine,
20
+ stageSignIn,
21
+ } from "./sign-ins.js";
22
+
23
+ /*
24
+ * A member signs in to Claude Code or Codex on one of their machines from
25
+ * the Work app (ADRs 0213, 0342): this machine runs the harness's own
26
+ * unmodified login into a home of its own for them, the app shows the link
27
+ * it printed, and the member finishes in their own browser. Codex prints a
28
+ * one-time code the member enters there (`codex login --device-auth`);
29
+ * Claude Code's page gives the member a code, which they paste into the
30
+ * app and this machine writes to the login as its one line of input
31
+ * (`claude auth login`). The token is issued to the harness on this
32
+ * machine and never leaves it. Attempts are this process's working state:
33
+ * a machine that restarts forgets them, and the member starts again.
34
+ *
35
+ * The pasted code is a secret in transit: it goes to the login's input and
36
+ * nowhere else. No answer, message, log or error here carries it.
37
+ */
38
+
39
+ /** What a member does with a harness's sign-in on a machine. */
40
+ export type HarnessSignInRequest =
41
+ | { action: "begin"; harness: SignInHarness; member: string }
42
+ | {
43
+ action: "status";
44
+ harness: SignInHarness;
45
+ member: string;
46
+ attempt: string;
47
+ }
48
+ | {
49
+ action: "cancel";
50
+ harness: SignInHarness;
51
+ member: string;
52
+ attempt: string;
53
+ }
54
+ | {
55
+ action: "input";
56
+ harness: SignInHarness;
57
+ member: string;
58
+ attempt: string;
59
+ text: string;
60
+ }
61
+ | { action: "signOut"; harness: SignInHarness; member: string };
62
+
63
+ /** The longest line a login is handed. */
64
+ export const SIGN_IN_INPUT_MAX = 4096;
65
+
66
+ export const HarnessSignInStartedSchema = z.strictObject({
67
+ attempt: z.string().uuid(),
68
+ verificationUrl: z.string().url().max(8192),
69
+ /** The one-time code the login printed, when it printed one. */
70
+ userCode: z.string().min(1).max(32).optional(),
71
+ /** What the login waits for after the link: a code the member pastes. */
72
+ expects: z.literal("code").optional(),
73
+ expiresAt: z.string().datetime(),
74
+ });
75
+ export type HarnessSignInStarted = z.infer<typeof HarnessSignInStartedSchema>;
76
+
77
+ export const HarnessSignInStatusSchema = z.strictObject({
78
+ state: z.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
79
+ message: z.string().max(400).optional(),
80
+ });
81
+ export type HarnessSignInStatus = z.infer<typeof HarnessSignInStatusSchema>;
82
+ export type HarnessSignInState = HarnessSignInStatus["state"];
83
+
84
+ export const HarnessSignedOutSchema = z.strictObject({
85
+ signedOut: z.boolean(),
86
+ });
87
+
88
+ /** What a machine would not do, and why, for the member to read. */
89
+ export const HarnessSignInRefusedSchema = z.strictObject({
90
+ refused: z.string().min(1).max(400),
91
+ });
92
+
93
+ /** How long a login takes at most to print its link. */
94
+ const CODE_TIMEOUT_MS = 30_000;
95
+ /** A login lasts 15 minutes unless it says otherwise. */
96
+ const DEFAULT_CODE_MINUTES = 15;
97
+ /** How long an exited login's remaining output is waited for. */
98
+ const EXIT_DRAIN_MS = 500;
99
+ /** Finished attempts are remembered this long for a late status read. */
100
+ const FINISHED_TTL_MS = 60 * 60_000;
101
+
102
+ interface Attempt {
103
+ harness: SignInHarness;
104
+ member: string;
105
+ child: ChildProcess;
106
+ staging: string;
107
+ expiresAt: number;
108
+ state: HarnessSignInState;
109
+ message?: string;
110
+ finishedAt?: number;
111
+ deadline: NodeJS.Timeout;
112
+ /** What the login said since it printed its link. */
113
+ output: string;
114
+ /**
115
+ * The line the member pasted, kept only while the login runs so nothing
116
+ * the login says back about it reaches a message.
117
+ */
118
+ secret?: string;
119
+ }
120
+
121
+ /** A login's output without its colors. */
122
+ export function plainOutput(text: string): string {
123
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escapes
124
+ return text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "");
125
+ }
126
+
127
+ /**
128
+ * The link, one-time code and lifetime `codex login --device-auth` printed,
129
+ * once it printed both.
130
+ */
131
+ export function parseDeviceCode(
132
+ output: string,
133
+ ): { verificationUrl: string; userCode: string; minutes: number } | undefined {
134
+ const text = plainOutput(output);
135
+ const verificationUrl = /https:\/\/\S+/.exec(text)?.[0];
136
+ const userCode = text
137
+ .split("\n")
138
+ .map((line) => line.trim())
139
+ .find((line) => /^[A-Z0-9]{3,8}-[A-Z0-9]{3,8}$/.test(line));
140
+ if (!verificationUrl || !userCode) return undefined;
141
+ const minutes = Number(/expires in (\d+) minutes?/i.exec(text)?.[1]);
142
+ return {
143
+ verificationUrl,
144
+ userCode,
145
+ minutes:
146
+ Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_CODE_MINUTES,
147
+ };
148
+ }
149
+
150
+ /**
151
+ * The link a login that waits for a pasted code printed (`claude auth
152
+ * login`: "If the browser didn't open, visit: <url>"), once the whole link
153
+ * is there: the first https link on one of the harness's own hosts.
154
+ */
155
+ export function parseSignInLink(input: {
156
+ output: string;
157
+ hosts: readonly string[];
158
+ }): string | undefined {
159
+ // Only links followed by whitespace: one still arriving is not whole.
160
+ for (const match of plainOutput(input.output).matchAll(
161
+ /https:\/\/[^\s"'<>]+(?=\s)/g,
162
+ )) {
163
+ let host: string;
164
+ try {
165
+ host = new URL(match[0]).hostname.toLowerCase();
166
+ } catch {
167
+ continue;
168
+ }
169
+ if (
170
+ input.hosts.some(
171
+ (allowed) => host === allowed || host.endsWith(`.${allowed}`),
172
+ )
173
+ )
174
+ return match[0];
175
+ }
176
+ return undefined;
177
+ }
178
+
179
+ /** Resolves once a stream has given everything it had. */
180
+ function drained(stream: Readable | null): Promise<void> {
181
+ return !stream || stream.readableEnded || stream.destroyed
182
+ ? Promise.resolve()
183
+ : new Promise((resolve) => {
184
+ stream.once("end", resolve);
185
+ stream.once("close", resolve);
186
+ });
187
+ }
188
+
189
+ /** What a login printed for the member to act on, once it printed it all. */
190
+ function parsePrompt(input: {
191
+ spec: SignInSpec;
192
+ output: string;
193
+ }):
194
+ | { verificationUrl: string; userCode?: string; minutes: number }
195
+ | undefined {
196
+ if (input.spec.expects !== "code") return parseDeviceCode(input.output);
197
+ const verificationUrl = parseSignInLink({
198
+ output: input.output,
199
+ hosts: input.spec.linkHosts ?? [],
200
+ });
201
+ return verificationUrl
202
+ ? { verificationUrl, minutes: DEFAULT_CODE_MINUTES }
203
+ : undefined;
204
+ }
205
+
206
+ /**
207
+ * The last thing a login said, for a member to read: one short line that
208
+ * is neither a prompt nor a link, with anything the member pasted removed.
209
+ */
210
+ function lastWords(output: string, secret?: string): string | undefined {
211
+ const lines = plainOutput(output)
212
+ .split("\n")
213
+ .map((line) => line.trim())
214
+ .filter(
215
+ (line) => line && !line.endsWith(">") && !line.includes("https://"),
216
+ );
217
+ const last = lines.at(-1);
218
+ if (!last) return undefined;
219
+ return (secret ? last.split(secret).join("the code") : last).slice(0, 300);
220
+ }
221
+
222
+ export class HarnessSignInRefusedError extends Error {
223
+ constructor(message: string) {
224
+ super(message);
225
+ this.name = "HarnessSignInRefusedError";
226
+ }
227
+ }
228
+
229
+ export class HarnessSignIns {
230
+ /**
231
+ * Replica memory (a): the logins this machine's own process runs, each a
232
+ * child process here; a machine that restarts forgets them and the
233
+ * member starts again.
234
+ */
235
+ private readonly attempts = new Map<string, Attempt>();
236
+
237
+ constructor(
238
+ private readonly options: {
239
+ /** The machine's sign-in root (`<data>/sign-ins`). */
240
+ signInRoot: string;
241
+ /** The machine's data directory, for signing out. */
242
+ dataDir: string;
243
+ env?: NodeJS.ProcessEnv;
244
+ now?: () => number;
245
+ /**
246
+ * A member's sign-in was placed or removed: the machine tells
247
+ * placement now rather than at its next scan.
248
+ */
249
+ onChange?: () => void;
250
+ },
251
+ ) {}
252
+
253
+ /** One request from the control plane (or this server's own routes). */
254
+ async handle(
255
+ request: HarnessSignInRequest,
256
+ ): Promise<
257
+ | HarnessSignInStarted
258
+ | { refused: string }
259
+ | HarnessSignInStatus
260
+ | { signedOut: boolean }
261
+ > {
262
+ // A refusal is an answer the member reads, not a machine failure.
263
+ const refusal = (error: unknown) => {
264
+ if (error instanceof HarnessSignInRefusedError)
265
+ return { refused: error.message.slice(0, 400) };
266
+ throw error;
267
+ };
268
+ switch (request.action) {
269
+ case "begin":
270
+ return this.begin(request).catch(refusal);
271
+ case "status":
272
+ return this.status(request);
273
+ case "cancel":
274
+ return this.cancel(request);
275
+ case "input":
276
+ try {
277
+ return this.input(request);
278
+ } catch (error) {
279
+ return refusal(error);
280
+ }
281
+ case "signOut": {
282
+ const signedOut = signOutOnMachine({
283
+ dataDir: this.options.dataDir,
284
+ harness: request.harness,
285
+ member: request.member,
286
+ });
287
+ if (signedOut) this.options.onChange?.();
288
+ return { signedOut };
289
+ }
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Start a harness's own login for a member. Resolves once it printed its
295
+ * link (and, for Codex, its code); one login of a harness runs per
296
+ * member, so a new one replaces theirs.
297
+ */
298
+ async begin(input: {
299
+ harness: SignInHarness;
300
+ member: string;
301
+ }): Promise<HarnessSignInStarted> {
302
+ this.prune();
303
+ const { harness, member } = input;
304
+ const spec = SIGN_IN_SPECS[harness];
305
+ try {
306
+ assertMachineFree({ root: this.options.signInRoot, member });
307
+ } catch (error) {
308
+ if (error instanceof MachineHeldError)
309
+ throw new HarnessSignInRefusedError(error.message);
310
+ throw error;
311
+ }
312
+ for (const [id, attempt] of this.attempts)
313
+ if (
314
+ attempt.member === member &&
315
+ attempt.harness === harness &&
316
+ attempt.state === "waiting"
317
+ )
318
+ this.finish(id, "cancelled", "A newer sign-in replaced this one");
319
+ const staging = stageSignIn({
320
+ root: this.options.signInRoot,
321
+ harness,
322
+ member,
323
+ });
324
+ const login = signInCommand({
325
+ harness,
326
+ home: staging,
327
+ env: this.options.env,
328
+ });
329
+ const child = spawn(login.command, login.args, {
330
+ env: signInEnvironment({
331
+ harness,
332
+ base: this.options.env ?? process.env,
333
+ login: { ...login.env, NO_COLOR: "1" },
334
+ }),
335
+ // A login that waits for a pasted code reads it from a plain pipe.
336
+ stdio: [spec.expects ? "pipe" : "ignore", "pipe", "pipe"],
337
+ });
338
+ // A login that ended takes no more input; writing then is no failure.
339
+ child.stdin?.on("error", () => undefined);
340
+ const id = randomUUID();
341
+ let output = "";
342
+ return new Promise<HarnessSignInStarted>((resolve, reject) => {
343
+ let settled = false;
344
+ const fail = (message: string) => {
345
+ if (settled) return;
346
+ settled = true;
347
+ clearTimeout(timer);
348
+ child.kill("SIGTERM");
349
+ fs.rmSync(staging, { recursive: true, force: true });
350
+ reject(new HarnessSignInRefusedError(message));
351
+ };
352
+ const timer = setTimeout(
353
+ () =>
354
+ fail(
355
+ `${spec.name} did not print a sign-in link within ${CODE_TIMEOUT_MS / 1000} seconds${lastWords(output) ? `: ${lastWords(output)}` : ""}`,
356
+ ),
357
+ CODE_TIMEOUT_MS,
358
+ );
359
+ const read = (chunk: Buffer) => {
360
+ const text = chunk.toString("utf8");
361
+ const attempt = this.attempts.get(id);
362
+ if (attempt) {
363
+ attempt.output = (attempt.output + text).slice(-64_000);
364
+ return;
365
+ }
366
+ output = (output + text).slice(-64_000);
367
+ if (settled) return;
368
+ const prompt = parsePrompt({ spec, output });
369
+ if (!prompt) return;
370
+ settled = true;
371
+ clearTimeout(timer);
372
+ const now = this.now();
373
+ const lifetime = prompt.minutes * 60_000;
374
+ const expiresAt = now + lifetime;
375
+ this.attempts.set(id, {
376
+ harness,
377
+ member,
378
+ child,
379
+ staging,
380
+ expiresAt,
381
+ state: "waiting",
382
+ output: "",
383
+ deadline: setTimeout(
384
+ () =>
385
+ this.finish(
386
+ id,
387
+ "expired",
388
+ spec.expects
389
+ ? "The sign-in was not finished in time"
390
+ : "The code expired",
391
+ ),
392
+ // Codex gives up on its own, so this only makes sure; a login
393
+ // that waits for a pasted code waits until it is ended.
394
+ spec.expects ? lifetime : lifetime + 60_000,
395
+ ),
396
+ });
397
+ resolve({
398
+ attempt: id,
399
+ verificationUrl: prompt.verificationUrl,
400
+ ...(prompt.userCode ? { userCode: prompt.userCode } : {}),
401
+ ...(spec.expects ? { expects: spec.expects } : {}),
402
+ expiresAt: new Date(expiresAt).toISOString(),
403
+ });
404
+ };
405
+ child.stdout?.on("data", read);
406
+ child.stderr?.on("data", read);
407
+ child.once("error", (error) =>
408
+ fail(
409
+ `Could not run ${spec.name} on this machine: ${error.message}. Install it there first`,
410
+ ),
411
+ );
412
+ const ended = (code: number | null) => {
413
+ if (!settled) {
414
+ fail(
415
+ lastWords(output) ??
416
+ `${spec.name} stopped before printing a sign-in link (exit ${code ?? "signal"})`,
417
+ );
418
+ return;
419
+ }
420
+ const attempt = this.attempts.get(id);
421
+ if (attempt?.state !== "waiting") return;
422
+ if (code === 0 && signedIn({ harness, home: staging })) {
423
+ try {
424
+ // Someone else may have signed in here meanwhile.
425
+ assertMachineFree({ root: this.options.signInRoot, member });
426
+ placeSignIn({
427
+ root: this.options.signInRoot,
428
+ harness,
429
+ member,
430
+ staging,
431
+ });
432
+ } catch (error) {
433
+ // Held by someone else, or the machine was reset meanwhile.
434
+ this.finish(
435
+ id,
436
+ "failed",
437
+ error instanceof Error ? error.message : String(error),
438
+ );
439
+ return;
440
+ }
441
+ this.finish(id, "signed-in");
442
+ this.options.onChange?.();
443
+ return;
444
+ }
445
+ this.finish(
446
+ id,
447
+ this.now() >= attempt.expiresAt ? "expired" : "failed",
448
+ code === 0
449
+ ? noSignInLeft(harness)
450
+ : (lastWords(attempt.output, attempt.secret) ??
451
+ `${spec.name} did not complete the sign-in`),
452
+ );
453
+ };
454
+ // A login's last words may still be in its pipes when it exits:
455
+ // they are read first, for a moment at most (something the login
456
+ // started, such as a browser, may hold a pipe open for long).
457
+ child.once("exit", (code) => {
458
+ void Promise.race([
459
+ Promise.all([drained(child.stdout), drained(child.stderr)]),
460
+ new Promise((resolve) => setTimeout(resolve, EXIT_DRAIN_MS)),
461
+ ]).then(() => ended(code));
462
+ });
463
+ });
464
+ }
465
+
466
+ status(input: {
467
+ harness: SignInHarness;
468
+ member: string;
469
+ attempt: string;
470
+ }): HarnessSignInStatus {
471
+ const attempt = this.own(input);
472
+ if (!attempt)
473
+ return {
474
+ state: "failed",
475
+ message:
476
+ "This machine no longer knows this sign-in; it may have restarted. Start again",
477
+ };
478
+ return {
479
+ state: attempt.state,
480
+ ...(attempt.message ? { message: attempt.message } : {}),
481
+ };
482
+ }
483
+
484
+ cancel(input: {
485
+ harness: SignInHarness;
486
+ member: string;
487
+ attempt: string;
488
+ }): HarnessSignInStatus {
489
+ if (this.own(input)?.state === "waiting")
490
+ this.finish(input.attempt, "cancelled");
491
+ return this.status(input);
492
+ }
493
+
494
+ /**
495
+ * Hand a waiting login the one line it waits for: the code the member
496
+ * copied from their browser. The answer says where the sign-in stands
497
+ * and never repeats the line.
498
+ */
499
+ input(input: {
500
+ harness: SignInHarness;
501
+ member: string;
502
+ attempt: string;
503
+ text: string;
504
+ }): HarnessSignInStatus {
505
+ const spec = SIGN_IN_SPECS[input.harness];
506
+ if (!spec.expects)
507
+ throw new HarnessSignInRefusedError(
508
+ `${spec.name} takes no code here: enter the code it showed on its sign-in page`,
509
+ );
510
+ const attempt = this.own(input);
511
+ if (attempt?.state !== "waiting") return this.status(input);
512
+ const line = input.text.trim();
513
+ if (
514
+ !line ||
515
+ line.length > SIGN_IN_INPUT_MAX ||
516
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: one line only
517
+ /[\u0000-\u001f\u007f]/.test(line)
518
+ )
519
+ throw new HarnessSignInRefusedError(
520
+ "That is not a code: paste the one line the sign-in page gave you",
521
+ );
522
+ const stdin = attempt.child.stdin;
523
+ if (attempt.secret !== undefined || !stdin || stdin.destroyed)
524
+ throw new HarnessSignInRefusedError(
525
+ "This sign-in already has its code. Wait for it to finish, or start again",
526
+ );
527
+ attempt.secret = line;
528
+ // One line, then the end of its input: the login reads no more.
529
+ stdin.end(`${line}\n`);
530
+ return this.status(input);
531
+ }
532
+
533
+ /** End every login this machine runs, when it stops. */
534
+ stop(): void {
535
+ for (const [id, attempt] of this.attempts)
536
+ if (attempt.state === "waiting") this.finish(id, "cancelled");
537
+ }
538
+
539
+ /** The attempt of this id when it is this member's, of this harness. */
540
+ private own(input: {
541
+ harness: SignInHarness;
542
+ member: string;
543
+ attempt: string;
544
+ }): Attempt | undefined {
545
+ const attempt = this.attempts.get(input.attempt);
546
+ return attempt?.member === input.member && attempt.harness === input.harness
547
+ ? attempt
548
+ : undefined;
549
+ }
550
+
551
+ private finish(
552
+ id: string,
553
+ state: HarnessSignInState,
554
+ message?: string,
555
+ ): void {
556
+ const attempt = this.attempts.get(id);
557
+ if (attempt?.state !== "waiting") return;
558
+ attempt.state = state;
559
+ if (message) attempt.message = message;
560
+ attempt.finishedAt = this.now();
561
+ // Nothing of what the member pasted or the login said outlives it.
562
+ delete attempt.secret;
563
+ attempt.output = "";
564
+ clearTimeout(attempt.deadline);
565
+ if (attempt.child.exitCode === null) attempt.child.kill("SIGTERM");
566
+ if (state !== "signed-in")
567
+ fs.rmSync(attempt.staging, { recursive: true, force: true });
568
+ }
569
+
570
+ private prune(): void {
571
+ const now = this.now();
572
+ for (const [id, attempt] of this.attempts)
573
+ if (attempt.finishedAt && now - attempt.finishedAt > FINISHED_TTL_MS)
574
+ this.attempts.delete(id);
575
+ }
576
+
577
+ private now(): number {
578
+ return this.options.now?.() ?? Date.now();
579
+ }
580
+ }