@mycadet/cli 0.13.0-dev.202610241003.f9cbe80 → 0.13.0-dev.202610251252.f691e47

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 (44) hide show
  1. package/eslint.config.mjs +1 -1
  2. package/node_modules/@mycadet/assistant-api/events/assistant-status.ts +1 -3
  3. package/node_modules/@mycadet/local-mode/src/__tests__/wake.test.ts +12 -6
  4. package/node_modules/@mycadet/local-mode/src/gateway-proxy.ts +1 -1
  5. package/node_modules/@mycadet/local-mode/src/index.ts +1 -6
  6. package/node_modules/@mycadet/local-mode/src/lockfile-contract.test.ts +1 -7
  7. package/node_modules/@mycadet/local-mode/src/lockfile-contract.ts +4 -8
  8. package/node_modules/@mycadet/local-mode/src/lockfile.test.ts +8 -8
  9. package/node_modules/@mycadet/local-mode/src/lockfile.ts +5 -29
  10. package/node_modules/@mycadet/local-mode/src/pair.ts +2 -2
  11. package/node_modules/@mycadet/local-mode/src/wake.ts +36 -14
  12. package/package.json +1 -1
  13. package/src/__tests__/assistant-config.test.ts +1 -1
  14. package/src/__tests__/backup-ops.test.ts +6 -1
  15. package/src/__tests__/host-teleport.test.ts +0 -5
  16. package/src/__tests__/nginx-ingress.test.ts +36 -0
  17. package/src/__tests__/restore.test.ts +13 -95
  18. package/src/__tests__/root-backup.test.ts +7 -42
  19. package/src/__tests__/statefulset.test.ts +0 -1
  20. package/src/__tests__/upgrade-local.test.ts +11 -21
  21. package/src/__tests__/upgrade-replay-env.test.ts +10 -7
  22. package/src/__tests__/wake.test.ts +43 -357
  23. package/src/commands/client.ts +15 -9
  24. package/src/commands/gateway/token.ts +9 -8
  25. package/src/commands/gateway.ts +14 -15
  26. package/src/commands/ps.ts +13 -47
  27. package/src/commands/restore.ts +5 -11
  28. package/src/commands/upgrade.ts +6 -16
  29. package/src/commands/wake.ts +10 -143
  30. package/src/index.ts +1 -8
  31. package/src/lib/__tests__/docker.test.ts +5 -8
  32. package/src/lib/cli-error.ts +0 -5
  33. package/src/lib/docker.ts +0 -8
  34. package/src/lib/hatch-local.ts +18 -20
  35. package/src/lib/host-teleport.ts +4 -3
  36. package/src/lib/local.ts +4 -18
  37. package/src/lib/nginx-ingress.ts +23 -0
  38. package/src/lib/root-backup.ts +5 -56
  39. package/src/lib/root-signing-key.ts +13 -1
  40. package/src/lib/statefulset.ts +4 -4
  41. package/src/lib/upgrade-lifecycle.ts +2 -10
  42. package/node_modules/@mycadet/local-mode/src/local-signing-key.ts +0 -73
  43. package/src/__tests__/signing-key-continuity.test.ts +0 -170
  44. package/src/__tests__/wake-error.test.ts +0 -75
package/eslint.config.mjs CHANGED
@@ -10,7 +10,7 @@ const eslintConfig = defineConfig([
10
10
  "error",
11
11
  { argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
12
12
  ],
13
- // Ban `as` casts (the platform repo's rule) at warning level: the
13
+ // Ban `as` casts (the cloud repo's rule) at warning level: the
14
14
  // lint script pins --max-warnings to the current count and each PR
15
15
  // chips away at it — prefer zod schemas or `in`-narrowing.
16
16
  "@typescript-eslint/consistent-type-assertions": [
@@ -1,8 +1,7 @@
1
1
  /**
2
2
  * `assistant_status` SSE event.
3
3
  *
4
- * Server → client status announcement carrying the daemon `version`
5
- * and, when present, the assistant's key `keyFingerprint`.
4
+ * Server → client status announcement carrying the daemon `version`.
6
5
  *
7
6
  * Canonical wire-contract source. Daemon code imports the type
8
7
  * directly from this file; external consumers import via
@@ -14,7 +13,6 @@ import { z } from "zod";
14
13
  export const AssistantStatusEventSchema = z.object({
15
14
  type: z.literal("assistant_status"),
16
15
  version: z.string().optional(),
17
- keyFingerprint: z.string().optional(),
18
16
  });
19
17
 
20
18
  export type AssistantStatusEvent = z.infer<typeof AssistantStatusEventSchema>;
@@ -35,18 +35,21 @@ describe("runWake", () => {
35
35
  expect(spawnArgs[0]).toEqual(["bun", ["run", "cli", "wake", "asst-42"]]);
36
36
  });
37
37
 
38
- test("repairGuardian: true appends --repair-guardian to the CLI args", async () => {
38
+ test("repairGuardian: true chains the gateway's own token re-lease after the wake", async () => {
39
39
  const pending = runWake(invocation, "asst-42", { repairGuardian: true });
40
- lastChild.emit("close", 0);
40
+ lastChild.emit("close", 0); // wake completes...
41
+ await Promise.resolve(); // the chain spawns the re-lease
42
+ expect(spawnArgs[0]).toEqual(["bun", ["run", "cli", "wake", "asst-42"]]);
41
43
 
44
+ lastChild.emit("close", 0); // the re-lease completes
42
45
  expect(await pending).toEqual({ ok: true });
43
- expect(spawnArgs[0]).toEqual([
46
+ expect(spawnArgs[1]).toEqual([
44
47
  "bun",
45
- ["run", "cli", "wake", "asst-42", "--repair-guardian"],
48
+ ["run", "cli", "gateway", "token", "refresh", "asst-42"],
46
49
  ]);
47
50
  });
48
51
 
49
- test("repairGuardian: false omits the flag", async () => {
52
+ test("repairGuardian: false ends at the wake", async () => {
50
53
  const pending = runWake(invocation, "asst-42", { repairGuardian: false });
51
54
  lastChild.emit("close", 0);
52
55
 
@@ -56,7 +59,10 @@ describe("runWake", () => {
56
59
 
57
60
  test("a non-zero exit resolves to a failure carrying the CLI's output", async () => {
58
61
  const pending = runWake(invocation, "asst-42");
59
- lastChild.stderr.emit("data", Buffer.from("no sibling environment to seed from"));
62
+ lastChild.stderr.emit(
63
+ "data",
64
+ Buffer.from("no sibling environment to seed from"),
65
+ );
60
66
  lastChild.emit("close", 1);
61
67
 
62
68
  expect(await pending).toEqual({
@@ -193,7 +193,7 @@ const MAX_GATEWAY_PORT = 65535;
193
193
  * loopback — a connect import's remote gateway) resolves to it directly;
194
194
  * otherwise a loopback-gateway cloud (`local`, `docker`) resolves to its
195
195
  * recorded loopback port via {@link getLoopbackGatewayPort}. Everything
196
- * else — the platform cloud — is left out, and an absent id is a proxy
196
+ * else — the cloud — is left out, and an absent id is a proxy
197
197
  * rejection.
198
198
  *
199
199
  * Pure, so a host holding an in-memory lockfile snapshot (e.g. the Electron
@@ -45,7 +45,7 @@ export {
45
45
  getLockfileData,
46
46
  renameLockfileAssistantIfPresent,
47
47
  stampLockfileAssistantOnboardedIfPresent,
48
- upsertLockfileAssistant,
48
+ saveLockfileAssistant,
49
49
  replaceCloudAssistants,
50
50
  isActiveAssistant,
51
51
  isPairedLockfileEntry,
@@ -148,8 +148,3 @@ export type {
148
148
  PairedForwardAuthorizationResult,
149
149
  PairedGuardianTokenProvider,
150
150
  } from "./gateway-proxy";
151
-
152
- export {
153
- resolveExistingLocalSigningKey,
154
- SigningKeyContinuityError,
155
- } from "./local-signing-key";
@@ -230,7 +230,6 @@ describe("parseLockfile", () => {
230
230
  runtimeVersion: "v0.8.13",
231
231
  runtimeInstallDir: "/tmp/cadet/runtime/0.8.13",
232
232
  cesPort: 7780,
233
- signingKey: "hunter2",
234
233
  },
235
234
  },
236
235
  ],
@@ -243,7 +242,6 @@ describe("parseLockfile", () => {
243
242
  runtimeVersion: "v0.8.13",
244
243
  runtimeInstallDir: "/tmp/cadet/runtime/0.8.13",
245
244
  cesPort: 7780,
246
- signingKey: "hunter2",
247
245
  });
248
246
  const stripped = structuredClone(raw);
249
247
  stripSensitiveFields(stripped);
@@ -384,10 +382,6 @@ describe("taxonomy", () => {
384
382
  });
385
383
 
386
384
  test("SENSITIVE_KEYS lists the redacted secrets", () => {
387
- expect(SENSITIVE_KEYS).toEqual([
388
- "signingKey",
389
- "bearerToken",
390
- "guardianBootstrapSecret",
391
- ]);
385
+ expect(SENSITIVE_KEYS).toEqual(["bearerToken", "guardianBootstrapSecret"]);
392
386
  });
393
387
  });
@@ -57,7 +57,6 @@ export type Remote = z.infer<typeof RemoteSchema>;
57
57
  * place they are modeled.
58
58
  */
59
59
  export const SENSITIVE_KEYS = [
60
- "signingKey",
61
60
  "bearerToken",
62
61
  "guardianBootstrapSecret",
63
62
  ] as const;
@@ -190,11 +189,10 @@ export function getLoopbackGatewayPort(entry: {
190
189
 
191
190
  /**
192
191
  * Per-instance resources for a local assistant: the renderer-facing ports,
193
- * the instance directory, and the local runtime install metadata, plus the
194
- * host-only ports and the persisted signing key the CLI read-modify-writes.
195
- * Strict: every field the CLI round-trips is modeled, so nothing is dropped
196
- * by the parse. The secrets are stripped from renderer reads by
197
- * {@link stripSensitiveFields} before the parse ever sees them.
192
+ * the instance directory, the local runtime install metadata, and the
193
+ * host-only ports. Strict: every field the CLI round-trips is modeled, so
194
+ * nothing is dropped by the parse. The secrets are stripped from renderer
195
+ * reads by {@link stripSensitiveFields} before the parse ever sees them.
198
196
  */
199
197
  export const LocalAssistantResourcesSchema = z.object({
200
198
  instanceDir: z.string().optional(),
@@ -204,8 +202,6 @@ export const LocalAssistantResourcesSchema = z.object({
204
202
  cesPort: z.number().optional(),
205
203
  runtimeVersion: z.string().optional(),
206
204
  runtimeInstallDir: z.string().optional(),
207
- /** Persisted HMAC signing key (hex); survives daemon/gateway restarts so client actor tokens remain valid across wake cycles. */
208
- signingKey: z.string().optional(),
209
205
  });
210
206
  export type LocalAssistantResources = z.infer<
211
207
  typeof LocalAssistantResourcesSchema
@@ -9,7 +9,7 @@ import {
9
9
  renameLockfileAssistantIfPresent,
10
10
  stampLockfileAssistantOnboardedIfPresent,
11
11
  replaceCloudAssistants,
12
- upsertLockfileAssistant,
12
+ saveLockfileAssistant,
13
13
  } from "./lockfile";
14
14
 
15
15
  let dir: string;
@@ -126,9 +126,9 @@ describe("isPairedLockfileEntry", () => {
126
126
  });
127
127
  });
128
128
 
129
- describe("upsertLockfileAssistant", () => {
129
+ describe("saveLockfileAssistant", () => {
130
130
  test("rejects an assistant with no id", () => {
131
- const result = upsertLockfileAssistant(
131
+ const result = saveLockfileAssistant(
132
132
  [lockfilePath],
133
133
  { cloud: "local" },
134
134
  undefined,
@@ -156,7 +156,7 @@ describe("upsertLockfileAssistant", () => {
156
156
  ],
157
157
  });
158
158
 
159
- const result = upsertLockfileAssistant(
159
+ const result = saveLockfileAssistant(
160
160
  [lockfilePath],
161
161
  { assistantId: "asst_new", cloud: "local", runtimeUrl: "http://new" },
162
162
  "asst_new",
@@ -194,7 +194,7 @@ describe("upsertLockfileAssistant", () => {
194
194
  ],
195
195
  });
196
196
 
197
- upsertLockfileAssistant(
197
+ saveLockfileAssistant(
198
198
  [lockfilePath],
199
199
  { assistantId: "asst_1", name: "Renamed" },
200
200
  undefined,
@@ -225,7 +225,7 @@ describe("upsertLockfileAssistant", () => {
225
225
  };
226
226
  writeOnDisk({ activeAssistant: "asst_1", assistants: [entry] });
227
227
 
228
- const result = upsertLockfileAssistant(
228
+ const result = saveLockfileAssistant(
229
229
  [lockfilePath],
230
230
  { assistantId: "asst_1", name: "Renamed" },
231
231
  undefined,
@@ -252,7 +252,7 @@ describe("upsertLockfileAssistant", () => {
252
252
  ],
253
253
  });
254
254
 
255
- const result = upsertLockfileAssistant(
255
+ const result = saveLockfileAssistant(
256
256
  [lockfilePath],
257
257
  { assistantId: "asst_1", name: "Renamed" },
258
258
  undefined,
@@ -519,7 +519,7 @@ describe("lockfile writers under lock contention", () => {
519
519
  const before = fs.readFileSync(lockfilePath, "utf-8");
520
520
  holdLock();
521
521
 
522
- const result = upsertLockfileAssistant(
522
+ const result = saveLockfileAssistant(
523
523
  [lockfilePath],
524
524
  { assistantId: "asst_2", cloud: "local" },
525
525
  undefined,
@@ -274,7 +274,7 @@ function patchLockfileAssistantIfPresent(
274
274
  return locked.ok ? locked.value : lockFailure(locked.error);
275
275
  }
276
276
 
277
- export function upsertLockfileAssistant(
277
+ export function saveLockfileAssistant(
278
278
  lockfilePaths: string[],
279
279
  assistant: Record<string, unknown>,
280
280
  activeAssistant: string | undefined,
@@ -292,34 +292,10 @@ export function upsertLockfileAssistant(
292
292
  (a: Record<string, unknown>) => a?.assistantId === assistant.assistantId,
293
293
  );
294
294
  if (existingIdx >= 0) {
295
- const existing = assistants[existingIdx]!;
296
- let incoming: Record<string, unknown> = assistant;
297
- const storedResources = existing.resources;
298
- const incomingResources = incoming.resources;
299
- if (
300
- incomingResources !== undefined &&
301
- typeof storedResources === "object" &&
302
- storedResources !== null &&
303
- "signingKey" in storedResources &&
304
- typeof storedResources.signingKey === "string" &&
305
- !(
306
- typeof incomingResources === "object" &&
307
- incomingResources !== null &&
308
- "signingKey" in incomingResources &&
309
- incomingResources.signingKey !== undefined
310
- )
311
- ) {
312
- // The signing key is host custody: a save whose resources ride
313
- // without one (the renderer's stripped view) never unsets it.
314
- incoming = {
315
- ...incoming,
316
- resources: {
317
- ...incomingResources,
318
- signingKey: storedResources.signingKey,
319
- },
320
- };
321
- }
322
- assistants[existingIdx] = { ...existing, ...incoming };
295
+ assistants[existingIdx] = {
296
+ ...assistants[existingIdx]!,
297
+ ...assistant,
298
+ };
323
299
  } else {
324
300
  assistants.push(assistant);
325
301
  }
@@ -17,7 +17,7 @@ import { nanoid } from "nanoid";
17
17
 
18
18
  import { guardianTokenPath } from "./config";
19
19
  import { isConfidentialRefreshUrl, saveGuardianToken } from "./guardian-token";
20
- import { readRawLockfile, upsertLockfileAssistant } from "./lockfile";
20
+ import { readRawLockfile, saveLockfileAssistant } from "./lockfile";
21
21
 
22
22
  /**
23
23
  * The session credentials a pairing exchange yields, in the shape
@@ -306,7 +306,7 @@ export function pairAssistant(
306
306
  };
307
307
  }
308
308
 
309
- const writeResult = upsertLockfileAssistant(
309
+ const writeResult = saveLockfileAssistant(
310
310
  lockfilePaths,
311
311
  {
312
312
  assistantId: localId,
@@ -10,12 +10,15 @@ import type { CliInvocation } from "./util";
10
10
  // a slow-but-succeeding wake gets killed and misreported as a timeout.
11
11
  const WAKE_TIMEOUT_MS = 180_000;
12
12
 
13
+ /** The re-lease runs after the wake, inside the same safety-net window. */
14
+ const REPAIR_TIMEOUT_MS = 60_000;
15
+
13
16
  export type WakeResult =
14
17
  | { ok: true }
15
18
  | { ok: false; status: number; error: string };
16
19
 
17
20
  export interface WakeOptions {
18
- /** Pass --repair-guardian to re-provision a missing/expired guardian token. Revokes the assistant's other device-bound tokens, so callers must gate this behind explicit user confirmation. */
21
+ /** Re-provision the guardian credential after the wake (the gateway's bootstrap reset + re-lease, the same machinery `cadet gateway token refresh` runs). Revokes the assistant's other device-bound tokens, so callers must gate this behind explicit user confirmation. */
19
22
  repairGuardian?: boolean;
20
23
  }
21
24
 
@@ -33,18 +36,33 @@ export function runWake(
33
36
  invocation: CliInvocation,
34
37
  assistantId: string,
35
38
  options?: WakeOptions,
39
+ ): Promise<WakeResult> {
40
+ return runCli(invocation, ["wake", assistantId], WAKE_TIMEOUT_MS).then(
41
+ (woken) => {
42
+ if (!woken.ok || !options?.repairGuardian) {
43
+ return woken;
44
+ }
45
+ // The credential repair is the gateway's own machinery now: the
46
+ // gateway is up after the wake, so the re-lease runs against it.
47
+ return runCli(
48
+ invocation,
49
+ ["gateway", "token", "refresh", assistantId],
50
+ REPAIR_TIMEOUT_MS,
51
+ );
52
+ },
53
+ );
54
+ }
55
+
56
+ function runCli(
57
+ invocation: CliInvocation,
58
+ args: string[],
59
+ timeoutMs: number,
36
60
  ): Promise<WakeResult> {
37
61
  return new Promise((resolve) => {
38
- const child = spawn(
39
- invocation.command,
40
- [
41
- ...invocation.baseArgs,
42
- "wake",
43
- assistantId,
44
- ...(options?.repairGuardian ? ["--repair-guardian"] : []),
45
- ],
46
- { stdio: ["ignore", "pipe", "pipe"], windowsHide: true },
47
- );
62
+ const child = spawn(invocation.command, [...invocation.baseArgs, ...args], {
63
+ stdio: ["ignore", "pipe", "pipe"],
64
+ windowsHide: true,
65
+ });
48
66
 
49
67
  let stdout = "";
50
68
  let stderr = "";
@@ -62,9 +80,9 @@ export function runWake(
62
80
  finish({
63
81
  ok: false,
64
82
  status: 500,
65
- error: `Wake timed out after ${WAKE_TIMEOUT_MS / 1000} seconds`,
83
+ error: `CLI invocation timed out after ${timeoutMs / 1000} seconds`,
66
84
  });
67
- }, WAKE_TIMEOUT_MS);
85
+ }, timeoutMs);
68
86
 
69
87
  child.stdout.on("data", (data: Buffer) => {
70
88
  stdout += data.toString();
@@ -83,7 +101,11 @@ export function runWake(
83
101
  });
84
102
 
85
103
  child.on("error", (err) => {
86
- finish({ ok: false, status: 500, error: `Failed to spawn CLI: ${err.message}` });
104
+ finish({
105
+ ok: false,
106
+ status: 500,
107
+ error: `Failed to spawn CLI: ${err.message}`,
108
+ });
87
109
  });
88
110
  });
89
111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/cli",
3
- "version": "0.13.0-dev.202610241003.f9cbe80",
3
+ "version": "0.13.0-dev.202610251252.f691e47",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/vargasjr-dev/mycadet-temp.git"
@@ -144,7 +144,7 @@ describe("assistant-config", () => {
144
144
  expect(result!.assistantId).toBe("beta");
145
145
  });
146
146
 
147
- test("getAssistantDisplayName prefers the platform name", () => {
147
+ test("getAssistantDisplayName prefers the entry's name", () => {
148
148
  expect(
149
149
  getAssistantDisplayName(
150
150
  makeEntry("assistant-1", undefined, { name: "Alice" }),
@@ -7,6 +7,7 @@ import {
7
7
  rm,
8
8
  writeFile,
9
9
  } from "node:fs/promises";
10
+ import { mkdirSync, writeFileSync } from "node:fs";
10
11
  import { tmpdir } from "node:os";
11
12
  import { join } from "node:path";
12
13
  import * as config from "../lib/assistant-config.js";
@@ -26,9 +27,13 @@ const entry: config.LockfileAssistant & { runtimeUrl: string } = {
26
27
  daemonPort: 1,
27
28
  gatewayPort: 2,
28
29
  cesPort: 3,
29
- signingKey: "07".repeat(32),
30
30
  },
31
31
  };
32
+ mkdirSync(join(root, "gateway-security"), { recursive: true });
33
+ writeFileSync(
34
+ join(root, "gateway-security", "actor-token-signing-key"),
35
+ Buffer.from("07".repeat(32), "hex"),
36
+ );
32
37
  const lookup = spyOn(config, "findAssistantByName").mockReturnValue(entry);
33
38
  const location = spyOn(backups, "getBackupsDir").mockReturnValue(backupDir);
34
39
  const save = spyOn(config, "saveLockfileAssistant").mockImplementation(
@@ -3,7 +3,6 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import {
6
- findAssistantByName,
7
6
  getLocalInstanceDir,
8
7
  type LockfileAssistant,
9
8
  saveLockfileAssistant,
@@ -62,7 +61,6 @@ async function instance(
62
61
  daemonPort: 1,
63
62
  gatewayPort: 2,
64
63
  cesPort: 3,
65
- signingKey: byte.toString(16).padStart(2, "0").repeat(32),
66
64
  },
67
65
  };
68
66
  }
@@ -178,9 +176,6 @@ test("moves all four roots and encrypted key pairs using the exact stopped-sourc
178
176
  join(getLocalInstanceDir(target.resources), "ces-security", "store.key"),
179
177
  ),
180
178
  ).toEqual(Buffer.alloc(32, 8));
181
- expect(findAssistantByName("target")!.resources!.signingKey).toBe(
182
- "07".repeat(32),
183
- );
184
179
  expect(order).toEqual([
185
180
  "sleep:source",
186
181
  "backup:source",
@@ -261,6 +261,42 @@ describe("buildIngressNginxConfig", () => {
261
261
  }
262
262
  });
263
263
 
264
+ test("allowlists the Capacitor shells' own webview origins", () => {
265
+ // The mobile shells fetch from `capacitor://localhost` (iOS) and
266
+ // `https://localhost` (Android) — origins no web page can forge, so the
267
+ // edge answers them without per-deployment config. nginx omits an
268
+ // add_header whose value is empty, so an unmapped origin would strip
269
+ // Access-Control-Allow-Origin from the assistant-metadata responses and
270
+ // Safari would block the 200 it got.
271
+ for (const origin of [
272
+ "capacitor://localhost",
273
+ "https://localhost",
274
+ "http://localhost",
275
+ ]) {
276
+ expect(remoteConf).toContain(`${origin}" "${origin}";`);
277
+ }
278
+ });
279
+
280
+ test("still validates the configurable app origins", () => {
281
+ // The shells' origins are fixed platform values; everything configured
282
+ // per deployment keeps the HTTPS-or-loopback constraint.
283
+ expect(() =>
284
+ buildIngressNginxConfig({
285
+ gatewayPort: 7830,
286
+ listenPort: 7840,
287
+ remoteWebIngress: {
288
+ webDistDir: "/tmp/cadet web/dist",
289
+ appDistDir: "/tmp/cadet app/dist/standalone",
290
+ config: {
291
+ remote: "docker",
292
+ apiBaseUrl: "/v1",
293
+ appAllowedOrigins: ["javascript://alert(1)"],
294
+ },
295
+ },
296
+ }),
297
+ ).toThrow("App origins must be HTTPS origins or loopback HTTP origins.");
298
+ });
299
+
264
300
  test("blocks local-only bootstrap helpers before the catch-all proxy", () => {
265
301
  const catchAll = conf.indexOf("location / {");
266
302
  expect(catchAll).toBeGreaterThan(-1);
@@ -15,7 +15,6 @@ import {
15
15
  mkdirSync,
16
16
  mkdtempSync,
17
17
  rmSync,
18
- readFileSync,
19
18
  writeFileSync,
20
19
  } from "node:fs";
21
20
  import { homedir, tmpdir } from "node:os";
@@ -23,7 +22,6 @@ import * as osModule from "node:os";
23
22
  import { basename, join } from "node:path";
24
23
 
25
24
  import {
26
- getLocalInstanceDir,
27
25
  type LockfileAssistant,
28
26
  } from "../lib/assistant-config.js";
29
27
  import * as localModule from "../lib/local.js";
@@ -33,7 +31,7 @@ import { makeEntry } from "./helpers/lockfile-entry.js";
33
31
  // Captured real exports — afterAll restores these so module mocks don't
34
32
  // leak into other test files in the same `bun test` run.
35
33
  const realLocal = {
36
- generateLocalSigningKey: localModule.generateLocalSigningKey,
34
+ generateLocalSecret: localModule.generateLocalSecret,
37
35
  startLocalDaemon: localModule.startLocalDaemon,
38
36
  startGateway: localModule.startGateway,
39
37
  startCes: localModule.startCes,
@@ -80,6 +78,7 @@ const retiredDir = join(testDir, "cadet", "retired");
80
78
  function writeArchiveFixtures(
81
79
  name: string,
82
80
  entry: LockfileAssistant,
81
+ key: string | null = "07".repeat(32),
83
82
  ): {
84
83
  archivePath: string;
85
84
  metadataPath: string;
@@ -96,6 +95,15 @@ function writeArchiveFixtures(
96
95
  writeFileSync(metadataPath, JSON.stringify(entry, null, 2) + "\n");
97
96
  // Create the staging dir that tar would have created
98
97
  mkdirSync(extractedPath, { recursive: true });
98
+ // The identity rides the archive's key file; null stages an archive
99
+ // without one.
100
+ if (key) {
101
+ mkdirSync(join(extractedPath, "gateway-security"), { recursive: true });
102
+ writeFileSync(
103
+ join(extractedPath, "gateway-security", "actor-token-signing-key"),
104
+ Buffer.from(key, "hex"),
105
+ );
106
+ }
99
107
 
100
108
  return { archivePath, metadataPath, extractedPath };
101
109
  }
@@ -175,96 +183,6 @@ describe("restore --help", () => {
175
183
  });
176
184
 
177
185
  describe("restore error cases", () => {
178
- for (const failure of ["missing", "conflict"] as const) {
179
- test(`recovery ${failure} leaves destination and registry untouched and permits retry`, async () => {
180
- const name = `retry-${failure}`;
181
- const instanceDir = join(testDir, "cadet", "assistants", name);
182
- const entry = makeEntry({
183
- assistantId: name,
184
- resources: { instanceDir },
185
- });
186
- delete entry.resources!.signingKey;
187
- const { archivePath, metadataPath, extractedPath } = writeArchiveFixtures(
188
- name,
189
- entry,
190
- );
191
- if (failure === "conflict") {
192
- for (const [dir, hex] of [
193
- ["gateway-security", "ab"],
194
- ["workspace/deprecated", "cd"],
195
- ]) {
196
- mkdirSync(join(extractedPath, dir!), { recursive: true });
197
- writeFileSync(
198
- join(extractedPath, dir!, "actor-token-signing-key"),
199
- Buffer.from(hex!.repeat(32), "hex"),
200
- );
201
- }
202
- }
203
- const registry = resolveLockfilePaths(process.env)[0]!;
204
- const before = readFileSync(registry, "utf8");
205
- process.argv = ["bun", "cadet", "restore", name];
206
- await expect(restore()).rejects.toThrow(`signing key ${failure}`);
207
- expect(existsSync(instanceDir)).toBe(false);
208
- expect(readFileSync(registry, "utf8")).toBe(before);
209
- expect(existsSync(archivePath)).toBe(true);
210
- expect(existsSync(metadataPath)).toBe(true);
211
- expect(startLocalDaemonMock).not.toHaveBeenCalled();
212
- expect(startGatewayMock).not.toHaveBeenCalled();
213
- // Restore the authoritative identity in the archive metadata and retry.
214
- entry.resources!.signingKey = "ab".repeat(32);
215
- writeFileSync(metadataPath, JSON.stringify(entry));
216
- await restore();
217
- expect(existsSync(instanceDir)).toBe(true);
218
- expect(existsSync(archivePath)).toBe(false);
219
- expect(startGatewayMock).toHaveBeenCalledTimes(1);
220
- rmSync(instanceDir, { recursive: true, force: true });
221
- });
222
- }
223
-
224
- test("recovers an archived legacy identity from staging", async () => {
225
- const name = "legacy-staged";
226
- const entry = makeEntry({
227
- guardianBootstrapSecret: "existing-bootstrap",
228
- assistantId: name,
229
- resources: { instanceDir: join(testDir, "cadet", "assistants", name) },
230
- });
231
- delete entry.resources!.signingKey;
232
- const { extractedPath } = writeArchiveFixtures(name, entry);
233
- const dir = join(extractedPath, "workspace", "deprecated");
234
- mkdirSync(dir, { recursive: true });
235
- writeFileSync(
236
- join(dir, "actor-token-signing-key"),
237
- Buffer.from("cd".repeat(32), "hex"),
238
- );
239
- process.argv = ["bun", "cadet", "restore", name];
240
- await restore();
241
- expect(startGatewayMock).toHaveBeenCalledWith(
242
- false,
243
- expect.objectContaining({ signingKey: "cd".repeat(32) }),
244
- { signingKey: "cd".repeat(32), bootstrapSecret: "existing-bootstrap" },
245
- );
246
- rmSync(getLocalInstanceDir(entry.resources), {
247
- recursive: true,
248
- force: true,
249
- });
250
- });
251
-
252
- test("missing identity preserves the archive and starts no processes", async () => {
253
- const name = "missing-key";
254
- const entry = makeEntry({
255
- assistantId: name,
256
- resources: { instanceDir: join(testDir, "cadet", "assistants", name) },
257
- });
258
- delete entry.resources!.signingKey;
259
- const { archivePath, metadataPath } = writeArchiveFixtures(name, entry);
260
- process.argv = ["bun", "cadet", "restore", name];
261
- await expect(restore()).rejects.toThrow("signing key missing");
262
- expect(existsSync(archivePath)).toBe(true);
263
- expect(existsSync(metadataPath)).toBe(true);
264
- expect(startLocalDaemonMock).not.toHaveBeenCalled();
265
- expect(startGatewayMock).not.toHaveBeenCalled();
266
- });
267
-
268
186
  test("exits 1 when no name is given", async () => {
269
187
  process.argv = ["bun", "cadet", "restore"];
270
188
  await expect(restore()).rejects.toThrow("process.exit(1)");
@@ -348,8 +266,8 @@ describe("archive-recovery extraction path — named instance (instanceDir !== h
348
266
  expect(startGatewayMock).toHaveBeenCalledTimes(1);
349
267
  expect(startGatewayMock.mock.calls[0]).toEqual([
350
268
  false,
351
- expect.objectContaining({ signingKey: "ab".repeat(32) }),
352
- { signingKey: "ab".repeat(32), bootstrapSecret: "existing-bootstrap" },
269
+ expect.objectContaining({ instanceDir: expect.any(String) }),
270
+ { bootstrapSecret: "existing-bootstrap" },
353
271
  ]);
354
272
  });
355
273