@indigoai-us/hq-cloud 6.14.12 → 6.14.13

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 (78) hide show
  1. package/.claude/policies/hq-cloud-strip-types-no-parameter-properties.md +22 -0
  2. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  3. package/dist/bin/sync-runner-company.js +6 -0
  4. package/dist/bin/sync-runner-company.js.map +1 -1
  5. package/dist/bin/sync-runner-planning.d.ts.map +1 -1
  6. package/dist/bin/sync-runner-planning.js +3 -1
  7. package/dist/bin/sync-runner-planning.js.map +1 -1
  8. package/dist/bin/sync-runner-watch-loop.d.ts +1 -0
  9. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  10. package/dist/bin/sync-runner-watch-loop.js +7 -1
  11. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  12. package/dist/bin/sync-runner-watch-routes.d.ts +1 -0
  13. package/dist/bin/sync-runner-watch-routes.d.ts.map +1 -1
  14. package/dist/bin/sync-runner-watch-routes.js +3 -0
  15. package/dist/bin/sync-runner-watch-routes.js.map +1 -1
  16. package/dist/bin/sync-runner.d.ts +10 -0
  17. package/dist/bin/sync-runner.d.ts.map +1 -1
  18. package/dist/bin/sync-runner.js +83 -33
  19. package/dist/bin/sync-runner.js.map +1 -1
  20. package/dist/bin/sync-runner.test.js +93 -5
  21. package/dist/bin/sync-runner.test.js.map +1 -1
  22. package/dist/cli/reindex.d.ts.map +1 -1
  23. package/dist/cli/reindex.js +23 -60
  24. package/dist/cli/reindex.js.map +1 -1
  25. package/dist/cli/reindex.test.d.ts +2 -2
  26. package/dist/cli/reindex.test.js +60 -109
  27. package/dist/cli/reindex.test.js.map +1 -1
  28. package/dist/cli/rescue.reindex.test.js +3 -2
  29. package/dist/cli/rescue.reindex.test.js.map +1 -1
  30. package/dist/cli/share.d.ts.map +1 -1
  31. package/dist/cli/share.js +12 -1
  32. package/dist/cli/share.js.map +1 -1
  33. package/dist/cli/share.test.js +14 -0
  34. package/dist/cli/share.test.js.map +1 -1
  35. package/dist/cli/sync.d.ts.map +1 -1
  36. package/dist/cli/sync.js +9 -1
  37. package/dist/cli/sync.js.map +1 -1
  38. package/dist/cli/sync.test.js +8 -0
  39. package/dist/cli/sync.test.js.map +1 -1
  40. package/dist/cognito-auth.d.ts +44 -12
  41. package/dist/cognito-auth.d.ts.map +1 -1
  42. package/dist/cognito-auth.js +440 -76
  43. package/dist/cognito-auth.js.map +1 -1
  44. package/dist/cognito-auth.test.js +174 -0
  45. package/dist/cognito-auth.test.js.map +1 -1
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +3 -2
  49. package/dist/index.js.map +1 -1
  50. package/dist/machine-auth.test.js +683 -5
  51. package/dist/machine-auth.test.js.map +1 -1
  52. package/dist/vault-client.d.ts +2 -1
  53. package/dist/vault-client.d.ts.map +1 -1
  54. package/dist/vault-client.js +45 -9
  55. package/dist/vault-client.js.map +1 -1
  56. package/dist/vault-client.test.js +77 -7
  57. package/dist/vault-client.test.js.map +1 -1
  58. package/package.json +2 -1
  59. package/src/bin/sync-runner-company.ts +5 -0
  60. package/src/bin/sync-runner-planning.ts +2 -1
  61. package/src/bin/sync-runner-watch-loop.ts +7 -1
  62. package/src/bin/sync-runner-watch-routes.ts +2 -0
  63. package/src/bin/sync-runner.test.ts +122 -4
  64. package/src/bin/sync-runner.ts +92 -32
  65. package/src/cli/reindex.test.ts +63 -120
  66. package/src/cli/reindex.ts +23 -62
  67. package/src/cli/rescue.reindex.test.ts +3 -2
  68. package/src/cli/share.test.ts +20 -0
  69. package/src/cli/share.ts +7 -1
  70. package/src/cli/sync.test.ts +14 -0
  71. package/src/cli/sync.ts +5 -1
  72. package/src/cognito-auth.test.ts +227 -0
  73. package/src/cognito-auth.ts +533 -71
  74. package/src/index.ts +5 -1
  75. package/src/machine-auth.test.ts +808 -5
  76. package/src/vault-client.test.ts +100 -11
  77. package/src/vault-client.ts +55 -10
  78. package/test/share-sync.integration.test.ts +12 -9
@@ -13,6 +13,8 @@
13
13
  import * as fs from "fs";
14
14
  import * as os from "os";
15
15
  import * as path from "path";
16
+ import { spawn } from "child_process";
17
+ import { pathToFileURL } from "url";
16
18
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
17
19
  let originalHome;
18
20
  let originalCredsEnv;
@@ -26,6 +28,7 @@ beforeEach(() => {
26
28
  vi.resetModules();
27
29
  });
28
30
  afterEach(() => {
31
+ vi.useRealTimers();
29
32
  if (originalHome === undefined)
30
33
  delete process.env.HOME;
31
34
  else
@@ -62,11 +65,38 @@ function stubMintFetch(overrides = {}) {
62
65
  const calls = [];
63
66
  const fetchMock = vi.fn(async (url, init) => {
64
67
  calls.push({ url: String(url), init: init ?? {} });
68
+ const body = JSON.parse(String(init?.body));
69
+ const credsFile = process.env.HQ_MACHINE_CREDS_FILE ??
70
+ path.join(tmpHome, ".hq-agent", "machine-creds.json");
71
+ const creds = JSON.parse(fs.readFileSync(credsFile, "utf-8"));
72
+ const username = body.AuthParameters.USERNAME;
73
+ const subject = `sub:${username}`;
74
+ const entityType = creds.entityType ?? "agent";
75
+ const entityUid = creds.entityUid ?? "agt_01TEST";
65
76
  return new Response(JSON.stringify({
66
77
  AuthenticationResult: {
67
78
  AccessToken: overrides.AccessToken ??
68
- fakeJwt({ token_use: "access", client_id: CONFIG.clientId }),
69
- IdToken: overrides.IdToken ?? fakeJwt({ token_use: "id" }),
79
+ fakeJwt({
80
+ token_use: "access",
81
+ client_id: body.ClientId,
82
+ username,
83
+ sub: subject,
84
+ }),
85
+ IdToken: overrides.IdToken ??
86
+ fakeJwt({
87
+ token_use: "id",
88
+ aud: body.ClientId,
89
+ "custom:entityType": entityType,
90
+ "custom:entityUid": entityUid,
91
+ ...(entityType === "outpost"
92
+ ? {
93
+ "custom:delegatedSub": "human-sub",
94
+ "custom:delegatedEmail": "owner@example.com",
95
+ }
96
+ : {}),
97
+ "cognito:username": username,
98
+ sub: subject,
99
+ }),
70
100
  RefreshToken: overrides.RefreshToken,
71
101
  ExpiresIn: overrides.ExpiresIn ?? 3600,
72
102
  },
@@ -112,6 +142,25 @@ describe("machine identity detection", () => {
112
142
  });
113
143
  expect(isMachineIdentity()).toBe(true);
114
144
  });
145
+ it("parses the expected machine entity type and uid from provisioned creds", async () => {
146
+ writeCreds({
147
+ username: "out-01test@outposts.getindigo.ai",
148
+ secret: "s3cret",
149
+ clientId: "outpost-client-1",
150
+ region: "us-east-1",
151
+ entityType: "outpost",
152
+ entityUid: "out_01TEST",
153
+ });
154
+ const { loadMachineCreds } = await importModule();
155
+ expect(loadMachineCreds()).toEqual({
156
+ username: "out-01test@outposts.getindigo.ai",
157
+ secret: "s3cret",
158
+ clientId: "outpost-client-1",
159
+ region: "us-east-1",
160
+ entityType: "outpost",
161
+ entityUid: "out_01TEST",
162
+ });
163
+ });
115
164
  it("honors HQ_MACHINE_CREDS_FILE override", async () => {
116
165
  const custom = path.join(tmpHome, "elsewhere.json");
117
166
  fs.writeFileSync(custom, JSON.stringify({ username: "machine-agt_X", secret: "y" }));
@@ -129,6 +178,31 @@ describe("machine identity detection", () => {
129
178
  fs.writeFileSync(path.join(tmpHome, ".hq-agent", "machine-creds.json"), "{nope");
130
179
  expect(loadMachineCreds()).toBeNull();
131
180
  });
181
+ it.each([
182
+ { entityType: "agent", entityUid: "out_WRONG" },
183
+ { entityType: "outpost", entityUid: "agt_WRONG" },
184
+ { entityType: "agent", entityUid: "garbage" },
185
+ { entityType: "agent" },
186
+ { entityType: "outpost" },
187
+ { entityUid: "out_NO_TYPE" },
188
+ { entityUid: "garbage" },
189
+ { entityType: "agent", entityUid: "agt_" },
190
+ { entityType: "outpost", entityUid: "out_" },
191
+ ])("rejects malformed or cross-prefix entity metadata: %j", async (identity) => {
192
+ writeCreds({ username: "machine", secret: "secret", ...identity });
193
+ const { loadMachineCreds } = await importModule();
194
+ expect(loadMachineCreds()).toBeNull();
195
+ });
196
+ it("accepts an agt_* uid without a type as the legacy agent inference", async () => {
197
+ writeCreds({
198
+ username: "machine-agt_01TEST",
199
+ secret: "secret",
200
+ entityUid: "agt_01TEST",
201
+ });
202
+ const { loadMachineCreds } = await importModule();
203
+ expect(loadMachineCreds()).toMatchObject({ entityUid: "agt_01TEST" });
204
+ expect(loadMachineCreds()?.entityType).toBeUndefined();
205
+ });
132
206
  });
133
207
  // ---------------------------------------------------------------------------
134
208
  // Minting
@@ -167,7 +241,7 @@ describe("mintMachineTokens", () => {
167
241
  const idClaims = JSON.parse(Buffer.from(tokens.idToken.split(".")[1], "base64url").toString());
168
242
  expect(accessClaims.token_use).toBe("access");
169
243
  expect(idClaims.token_use).toBe("id");
170
- expect(tokens.refreshToken).toBe("rt");
244
+ expect(tokens.refreshToken).toBe("");
171
245
  expect(typeof tokens.expiresAt).toBe("number");
172
246
  // Persisted to the shared cache file.
173
247
  expect(loadCachedTokens()).toEqual(tokens);
@@ -177,11 +251,59 @@ describe("mintMachineTokens", () => {
177
251
  vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ __type: "NotAuthorizedException", message: "nope" }), { status: 400 })));
178
252
  const { mintMachineTokens, CognitoAuthError } = await importModule();
179
253
  await expect(mintMachineTokens(CONFIG)).rejects.toBeInstanceOf(CognitoAuthError);
254
+ expect(fs.existsSync(path.join(tmpHome, ".hq", "cognito-tokens.json.lock"))).toBe(false);
255
+ stubMintFetch();
256
+ await expect(mintMachineTokens(CONFIG)).resolves.toBeDefined();
180
257
  });
181
258
  it("throws when no creds are present", async () => {
182
259
  const { mintMachineTokens, CognitoAuthError } = await importModule();
183
260
  await expect(mintMachineTokens(CONFIG)).rejects.toBeInstanceOf(CognitoAuthError);
184
261
  });
262
+ it.each([
263
+ ["wrong entity type", { "custom:entityType": "agent", "custom:entityUid": "agt_OTHER" }],
264
+ ["wrong entity uid", { "custom:entityUid": "out_OTHER" }],
265
+ ["absent delegatedSub", { "custom:delegatedSub": undefined }],
266
+ ["empty delegatedSub", { "custom:delegatedSub": "" }],
267
+ ["non-string delegatedSub", { "custom:delegatedSub": 42 }],
268
+ ["absent delegatedEmail", { "custom:delegatedEmail": undefined }],
269
+ ["empty delegatedEmail", { "custom:delegatedEmail": "" }],
270
+ ["non-string delegatedEmail", { "custom:delegatedEmail": 42 }],
271
+ ])("rejects and does not cache a first mint with %s", async (_label, claimOverride) => {
272
+ const username = "out-01test@outposts.getindigo.ai";
273
+ writeCreds({
274
+ username,
275
+ secret: "outpost-secret",
276
+ entityType: "outpost",
277
+ entityUid: "out_01TEST",
278
+ });
279
+ const claims = {
280
+ token_use: "id",
281
+ aud: CONFIG.clientId,
282
+ "custom:entityType": "outpost",
283
+ "custom:entityUid": "out_01TEST",
284
+ "custom:delegatedSub": "human-sub",
285
+ "custom:delegatedEmail": "owner@example.com",
286
+ "cognito:username": username,
287
+ sub: "machine-sub",
288
+ ...claimOverride,
289
+ };
290
+ for (const [key, value] of Object.entries(claims)) {
291
+ if (value === undefined)
292
+ delete claims[key];
293
+ }
294
+ stubMintFetch({
295
+ AccessToken: fakeJwt({
296
+ token_use: "access",
297
+ client_id: CONFIG.clientId,
298
+ username,
299
+ sub: "machine-sub",
300
+ }),
301
+ IdToken: fakeJwt(claims),
302
+ });
303
+ const { mintMachineTokens, loadCachedTokens, CognitoAuthError } = await importModule();
304
+ await expect(mintMachineTokens(CONFIG)).rejects.toBeInstanceOf(CognitoAuthError);
305
+ expect(loadCachedTokens()).toBeNull();
306
+ });
185
307
  });
186
308
  // ---------------------------------------------------------------------------
187
309
  // getValidMachineTokens — cache vs re-mint
@@ -216,6 +338,34 @@ describe("getValidMachineTokens", () => {
216
338
  expect(tokens).toEqual(cached);
217
339
  expect(fetchMock).not.toHaveBeenCalled();
218
340
  });
341
+ it("strips and persists an empty refresh token when reusing a machine cache", async () => {
342
+ writeCreds();
343
+ const { fetchMock } = stubMintFetch();
344
+ const { saveCachedTokens, loadCachedTokens, getValidMachineTokens } = await importModule();
345
+ saveCachedTokens({
346
+ accessToken: fakeJwt({
347
+ token_use: "access",
348
+ client_id: CONFIG.clientId,
349
+ username: "machine-agt_01TEST",
350
+ sub: "machine-sub",
351
+ }),
352
+ idToken: fakeJwt({
353
+ token_use: "id",
354
+ aud: CONFIG.clientId,
355
+ "custom:entityType": "agent",
356
+ "custom:entityUid": "agt_01TEST",
357
+ "cognito:username": "machine-agt_01TEST",
358
+ sub: "machine-sub",
359
+ }),
360
+ refreshToken: "legacy-machine-refresh-token",
361
+ expiresAt: Date.now() + 30 * 60 * 1000,
362
+ tokenType: "Bearer",
363
+ });
364
+ const tokens = await getValidMachineTokens(CONFIG);
365
+ expect(tokens.refreshToken).toBe("");
366
+ expect(loadCachedTokens()?.refreshToken).toBe("");
367
+ expect(fetchMock).not.toHaveBeenCalled();
368
+ });
219
369
  it("re-mints when the cache is expiring", async () => {
220
370
  writeCreds();
221
371
  const { fetchMock } = stubMintFetch();
@@ -289,6 +439,333 @@ describe("getValidMachineTokens", () => {
289
439
  expect(token).toBe(freshId);
290
440
  expect(loadCachedTokens()?.idToken).toBe(freshId);
291
441
  });
442
+ it("accepts an Outpost machine cache with delegated claims, then re-mints after expiry without OAuth refresh", async () => {
443
+ const username = "out-01test@outposts.getindigo.ai";
444
+ const entityUid = "out_01TEST";
445
+ writeCreds({
446
+ username,
447
+ secret: "outpost-secret",
448
+ clientId: CONFIG.clientId,
449
+ region: CONFIG.region,
450
+ entityType: "outpost",
451
+ entityUid,
452
+ });
453
+ const accessToken = fakeJwt({
454
+ token_use: "access",
455
+ client_id: CONFIG.clientId,
456
+ username,
457
+ sub: "machine-sub",
458
+ });
459
+ const idToken = fakeJwt({
460
+ token_use: "id",
461
+ aud: CONFIG.clientId,
462
+ "custom:entityType": "outpost",
463
+ "custom:entityUid": entityUid,
464
+ "custom:delegatedSub": "human-sub",
465
+ "custom:delegatedEmail": "owner@example.com",
466
+ "cognito:username": username,
467
+ sub: "machine-sub",
468
+ });
469
+ const { fetchMock, calls } = stubMintFetch({
470
+ AccessToken: accessToken,
471
+ IdToken: idToken,
472
+ RefreshToken: "must-not-be-stored",
473
+ });
474
+ const firstModule = await importModule();
475
+ const first = await firstModule.getValidMachineTokens(CONFIG);
476
+ expect(first.idToken).toBe(idToken);
477
+ expect(firstModule.loadCachedTokens()?.refreshToken).toBe("");
478
+ // A new process accepts the shared Outpost cache without another mint.
479
+ vi.resetModules();
480
+ const cacheHitModule = await importModule();
481
+ await expect(cacheHitModule.getValidMachineTokens(CONFIG)).resolves.toEqual(first);
482
+ expect(fetchMock).toHaveBeenCalledTimes(1);
483
+ // Once expired, a new process re-mints with the permanent secret. It never
484
+ // attempts the browser client's /oauth2/token refresh-token flow.
485
+ cacheHitModule.saveCachedTokens({
486
+ ...first,
487
+ expiresAt: Date.now() - 1,
488
+ });
489
+ vi.resetModules();
490
+ const expiredModule = await importModule();
491
+ await expiredModule.getValidMachineTokens(CONFIG);
492
+ expect(fetchMock).toHaveBeenCalledTimes(2);
493
+ expect(calls.every(({ url }) => !url.includes("/oauth2/token"))).toBe(true);
494
+ for (const { init } of calls) {
495
+ const body = JSON.parse(String(init.body));
496
+ expect(body).toMatchObject({
497
+ AuthFlow: "USER_PASSWORD_AUTH",
498
+ ClientId: CONFIG.clientId,
499
+ AuthParameters: { USERNAME: username, PASSWORD: "outpost-secret" },
500
+ });
501
+ }
502
+ expect(expiredModule.loadCachedTokens()?.refreshToken).toBe("");
503
+ });
504
+ it.each([
505
+ [
506
+ "entity type",
507
+ { entityType: "outpost", entityUid: "out_01TEST" },
508
+ "agent",
509
+ "agt_01TEST",
510
+ ],
511
+ [
512
+ "entity uid",
513
+ { entityType: "outpost", entityUid: "out_01TEST" },
514
+ "outpost",
515
+ "out_OTHER",
516
+ ],
517
+ ])("re-mints when the cached machine %s does not match the creds", async (_label, expectedIdentity, cachedEntityType, cachedEntityUid) => {
518
+ const username = "out-01test@outposts.getindigo.ai";
519
+ writeCreds({
520
+ username,
521
+ secret: "outpost-secret",
522
+ ...expectedIdentity,
523
+ });
524
+ const { fetchMock } = stubMintFetch();
525
+ const { saveCachedTokens, getValidMachineTokens } = await importModule();
526
+ saveCachedTokens({
527
+ accessToken: fakeJwt({
528
+ token_use: "access",
529
+ client_id: CONFIG.clientId,
530
+ username,
531
+ sub: "machine-sub",
532
+ }),
533
+ idToken: fakeJwt({
534
+ token_use: "id",
535
+ aud: CONFIG.clientId,
536
+ "custom:entityType": cachedEntityType,
537
+ "custom:entityUid": cachedEntityUid,
538
+ "custom:delegatedSub": "human-sub",
539
+ "custom:delegatedEmail": "owner@example.com",
540
+ "cognito:username": username,
541
+ sub: "machine-sub",
542
+ }),
543
+ refreshToken: "",
544
+ expiresAt: Date.now() + 30 * 60 * 1000,
545
+ tokenType: "Bearer",
546
+ });
547
+ await getValidMachineTokens(CONFIG);
548
+ expect(fetchMock).toHaveBeenCalledTimes(1);
549
+ });
550
+ it.each(["custom:delegatedSub", "custom:delegatedEmail"])("re-mints when an Outpost cache is missing %s", async (missingClaim) => {
551
+ const username = "out-01test@outposts.getindigo.ai";
552
+ const outpostClaims = {
553
+ token_use: "id",
554
+ aud: CONFIG.clientId,
555
+ "custom:entityType": "outpost",
556
+ "custom:entityUid": "out_01TEST",
557
+ "custom:delegatedSub": "human-sub",
558
+ "custom:delegatedEmail": "owner@example.com",
559
+ "cognito:username": username,
560
+ sub: "machine-sub",
561
+ };
562
+ delete outpostClaims[missingClaim];
563
+ writeCreds({
564
+ username,
565
+ secret: "outpost-secret",
566
+ entityType: "outpost",
567
+ entityUid: "out_01TEST",
568
+ });
569
+ const { fetchMock } = stubMintFetch();
570
+ const { saveCachedTokens, getValidMachineTokens } = await importModule();
571
+ saveCachedTokens({
572
+ accessToken: fakeJwt({
573
+ token_use: "access",
574
+ client_id: CONFIG.clientId,
575
+ username,
576
+ sub: "machine-sub",
577
+ }),
578
+ idToken: fakeJwt(outpostClaims),
579
+ refreshToken: "",
580
+ expiresAt: Date.now() + 30 * 60 * 1000,
581
+ tokenType: "Bearer",
582
+ });
583
+ await getValidMachineTokens(CONFIG);
584
+ expect(fetchMock).toHaveBeenCalledTimes(1);
585
+ });
586
+ it("keeps accepting legacy agent creds without entity fields", async () => {
587
+ writeCreds({ username: "machine-agt_01TEST", secret: "s3cret" });
588
+ const { fetchMock } = stubMintFetch();
589
+ const { saveCachedTokens, getValidMachineTokens } = await importModule();
590
+ const cached = {
591
+ accessToken: fakeJwt({
592
+ token_use: "access",
593
+ client_id: CONFIG.clientId,
594
+ username: "machine-agt_01TEST",
595
+ sub: "machine-sub",
596
+ }),
597
+ idToken: fakeJwt({
598
+ token_use: "id",
599
+ aud: CONFIG.clientId,
600
+ "custom:entityType": "agent",
601
+ "custom:entityUid": "agt_01TEST",
602
+ "cognito:username": "machine-agt_01TEST",
603
+ sub: "machine-sub",
604
+ }),
605
+ refreshToken: "",
606
+ expiresAt: Date.now() + 30 * 60 * 1000,
607
+ tokenType: "Bearer",
608
+ };
609
+ saveCachedTokens(cached);
610
+ await expect(getValidMachineTokens(CONFIG)).resolves.toEqual(cached);
611
+ expect(fetchMock).not.toHaveBeenCalled();
612
+ });
613
+ it("invalidates the memo after the creds file is reprovisioned", async () => {
614
+ writeCreds({
615
+ username: "machine-a",
616
+ secret: "secret-a",
617
+ entityType: "agent",
618
+ entityUid: "agt_A",
619
+ });
620
+ const { fetchMock } = stubMintFetch();
621
+ const { getValidMachineTokens } = await importModule();
622
+ const first = await getValidMachineTokens(CONFIG);
623
+ writeCreds({
624
+ username: "machine-b",
625
+ secret: "secret-b",
626
+ entityType: "outpost",
627
+ entityUid: "out_B",
628
+ });
629
+ const second = await getValidMachineTokens(CONFIG);
630
+ expect(fetchMock).toHaveBeenCalledTimes(2);
631
+ expect(first.idToken).not.toBe(second.idToken);
632
+ expect(JSON.parse(Buffer.from(second.idToken.split(".")[1], "base64url").toString())["custom:entityUid"]).toBe("out_B");
633
+ });
634
+ it("invalidates the memo when legacy creds use a different config client", async () => {
635
+ writeCreds();
636
+ const { fetchMock } = stubMintFetch();
637
+ const { getValidMachineTokens } = await importModule();
638
+ const otherConfig = { ...CONFIG, clientId: "other-client-id" };
639
+ const first = await getValidMachineTokens(CONFIG);
640
+ const second = await getValidMachineTokens(otherConfig);
641
+ expect(fetchMock).toHaveBeenCalledTimes(2);
642
+ expect(first.idToken).not.toBe(second.idToken);
643
+ expect(JSON.parse(Buffer.from(second.idToken.split(".")[1], "base64url").toString()).aud).toBe(otherConfig.clientId);
644
+ });
645
+ it("does not attach a reprovisioned identity to the previous identity's in-flight mint", async () => {
646
+ writeCreds({
647
+ username: "machine-a",
648
+ secret: "secret-a",
649
+ entityType: "agent",
650
+ entityUid: "agt_A",
651
+ });
652
+ let releaseFirstMint;
653
+ const firstMintGate = new Promise((resolve) => {
654
+ releaseFirstMint = resolve;
655
+ });
656
+ let signalFirstMint;
657
+ const firstMintStarted = new Promise((resolve) => {
658
+ signalFirstMint = resolve;
659
+ });
660
+ let callCount = 0;
661
+ const fetchMock = vi.fn(async (_url, init) => {
662
+ callCount += 1;
663
+ const body = JSON.parse(String(init?.body));
664
+ if (callCount === 1) {
665
+ signalFirstMint?.();
666
+ await firstMintGate;
667
+ }
668
+ const username = body.AuthParameters.USERNAME;
669
+ const uid = username === "machine-a" ? "agt_A" : "agt_B";
670
+ return new Response(JSON.stringify({
671
+ AuthenticationResult: {
672
+ AccessToken: fakeJwt({
673
+ token_use: "access",
674
+ client_id: body.ClientId,
675
+ username,
676
+ sub: `sub:${username}`,
677
+ }),
678
+ IdToken: fakeJwt({
679
+ token_use: "id",
680
+ aud: body.ClientId,
681
+ "custom:entityType": "agent",
682
+ "custom:entityUid": uid,
683
+ "cognito:username": username,
684
+ sub: `sub:${username}`,
685
+ }),
686
+ ExpiresIn: 3600,
687
+ },
688
+ }), { status: 200 });
689
+ });
690
+ vi.stubGlobal("fetch", fetchMock);
691
+ const { getValidMachineTokens } = await importModule();
692
+ const first = getValidMachineTokens(CONFIG);
693
+ await firstMintStarted;
694
+ writeCreds({
695
+ username: "machine-b",
696
+ secret: "secret-b",
697
+ entityType: "agent",
698
+ entityUid: "agt_B",
699
+ });
700
+ const second = getValidMachineTokens(CONFIG);
701
+ releaseFirstMint?.();
702
+ const [firstTokens, secondTokens] = await Promise.all([first, second]);
703
+ expect(fetchMock).toHaveBeenCalledTimes(2);
704
+ expect(firstTokens.idToken).not.toBe(secondTokens.idToken);
705
+ expect(JSON.parse(Buffer.from(secondTokens.idToken.split(".")[1], "base64url").toString())["custom:entityUid"]).toBe("agt_B");
706
+ });
707
+ it("reuses only an empty-refresh matching cache after a lock timeout", async () => {
708
+ writeCreds();
709
+ const { fetchMock } = stubMintFetch();
710
+ const { saveCachedTokens, getValidMachineTokens } = await importModule();
711
+ const cached = {
712
+ accessToken: fakeJwt({
713
+ token_use: "access",
714
+ client_id: CONFIG.clientId,
715
+ username: "machine-agt_01TEST",
716
+ sub: "machine-sub",
717
+ }),
718
+ idToken: fakeJwt({
719
+ token_use: "id",
720
+ aud: CONFIG.clientId,
721
+ "custom:entityType": "agent",
722
+ "custom:entityUid": "agt_01TEST",
723
+ "cognito:username": "machine-agt_01TEST",
724
+ sub: "machine-sub",
725
+ }),
726
+ refreshToken: "",
727
+ expiresAt: Date.now() + 30 * 60 * 1000,
728
+ tokenType: "Bearer",
729
+ };
730
+ saveCachedTokens(cached);
731
+ fs.writeFileSync(path.join(tmpHome, ".hq", "cognito-tokens.json.lock"), String(process.pid));
732
+ vi.useFakeTimers();
733
+ const resolution = getValidMachineTokens(CONFIG);
734
+ await vi.advanceTimersByTimeAsync(20_050);
735
+ await expect(resolution).resolves.toEqual(cached);
736
+ expect(fetchMock).not.toHaveBeenCalled();
737
+ });
738
+ it("rejects a legacy non-empty-refresh cache after a lock timeout without minting unlocked", async () => {
739
+ writeCreds();
740
+ const { fetchMock } = stubMintFetch();
741
+ const { saveCachedTokens, getValidMachineTokens, CognitoAuthError, } = await importModule();
742
+ saveCachedTokens({
743
+ accessToken: fakeJwt({
744
+ token_use: "access",
745
+ client_id: CONFIG.clientId,
746
+ username: "machine-agt_01TEST",
747
+ sub: "machine-sub",
748
+ }),
749
+ idToken: fakeJwt({
750
+ token_use: "id",
751
+ aud: CONFIG.clientId,
752
+ "custom:entityType": "agent",
753
+ "custom:entityUid": "agt_01TEST",
754
+ "cognito:username": "machine-agt_01TEST",
755
+ sub: "machine-sub",
756
+ }),
757
+ refreshToken: "legacy-refresh",
758
+ expiresAt: Date.now() + 30 * 60 * 1000,
759
+ tokenType: "Bearer",
760
+ });
761
+ fs.writeFileSync(path.join(tmpHome, ".hq", "cognito-tokens.json.lock"), String(process.pid));
762
+ vi.useFakeTimers();
763
+ const resolution = getValidMachineTokens(CONFIG);
764
+ const rejection = expect(resolution).rejects.toBeInstanceOf(CognitoAuthError);
765
+ await vi.advanceTimersByTimeAsync(20_050);
766
+ await rejection;
767
+ expect(fetchMock).not.toHaveBeenCalled();
768
+ });
292
769
  });
293
770
  // ---------------------------------------------------------------------------
294
771
  // Regression: constant token mints over N files (sync-runner mint storm)
@@ -327,6 +804,195 @@ describe("regression: constant mints regardless of file count", () => {
327
804
  await getValidMachineTokens(CONFIG);
328
805
  expect(fetchMock).toHaveBeenCalledTimes(1);
329
806
  });
807
+ it("serializes independent module instances through the shared cache lock", async () => {
808
+ const username = "machine-agt_01TEST";
809
+ writeCreds({
810
+ username,
811
+ secret: "s3cret",
812
+ entityType: "agent",
813
+ entityUid: "agt_01TEST",
814
+ });
815
+ let releaseMint;
816
+ const mintGate = new Promise((resolve) => {
817
+ releaseMint = resolve;
818
+ });
819
+ let signalMintStarted;
820
+ const mintStarted = new Promise((resolve) => {
821
+ signalMintStarted = resolve;
822
+ });
823
+ const accessToken = fakeJwt({
824
+ token_use: "access",
825
+ client_id: CONFIG.clientId,
826
+ username,
827
+ sub: "machine-sub",
828
+ });
829
+ const idToken = fakeJwt({
830
+ token_use: "id",
831
+ aud: CONFIG.clientId,
832
+ "custom:entityType": "agent",
833
+ "custom:entityUid": "agt_01TEST",
834
+ "cognito:username": username,
835
+ sub: "machine-sub",
836
+ });
837
+ const fetchMock = vi.fn(async () => {
838
+ signalMintStarted?.();
839
+ await mintGate;
840
+ return new Response(JSON.stringify({
841
+ AuthenticationResult: {
842
+ AccessToken: accessToken,
843
+ IdToken: idToken,
844
+ RefreshToken: "must-not-be-stored",
845
+ ExpiresIn: 3600,
846
+ },
847
+ }), { status: 200 });
848
+ });
849
+ vi.stubGlobal("fetch", fetchMock);
850
+ const firstProcessModule = await importModule();
851
+ vi.resetModules();
852
+ const secondProcessModule = await importModule();
853
+ const first = firstProcessModule.getValidMachineTokens(CONFIG);
854
+ await mintStarted;
855
+ const second = secondProcessModule.getValidMachineTokens(CONFIG);
856
+ releaseMint?.();
857
+ const [firstTokens, secondTokens] = await Promise.all([first, second]);
858
+ expect(fetchMock).toHaveBeenCalledTimes(1);
859
+ expect(secondTokens).toEqual(firstTokens);
860
+ expect(secondProcessModule.loadCachedTokens()?.refreshToken).toBe("");
861
+ });
862
+ it("serializes the exported direct mint API", async () => {
863
+ writeCreds();
864
+ let releaseFirstMint;
865
+ const firstMintGate = new Promise((resolve) => {
866
+ releaseFirstMint = resolve;
867
+ });
868
+ let signalFirstMint;
869
+ const firstMintStarted = new Promise((resolve) => {
870
+ signalFirstMint = resolve;
871
+ });
872
+ let activeMints = 0;
873
+ let maxActiveMints = 0;
874
+ let callCount = 0;
875
+ const accessToken = fakeJwt({
876
+ token_use: "access",
877
+ client_id: CONFIG.clientId,
878
+ username: "machine-agt_01TEST",
879
+ sub: "machine-sub",
880
+ });
881
+ const idToken = fakeJwt({
882
+ token_use: "id",
883
+ aud: CONFIG.clientId,
884
+ "custom:entityType": "agent",
885
+ "custom:entityUid": "agt_01TEST",
886
+ "cognito:username": "machine-agt_01TEST",
887
+ sub: "machine-sub",
888
+ });
889
+ const fetchMock = vi.fn(async () => {
890
+ callCount += 1;
891
+ activeMints += 1;
892
+ maxActiveMints = Math.max(maxActiveMints, activeMints);
893
+ if (callCount === 1) {
894
+ signalFirstMint?.();
895
+ await firstMintGate;
896
+ }
897
+ activeMints -= 1;
898
+ return new Response(JSON.stringify({
899
+ AuthenticationResult: {
900
+ AccessToken: accessToken,
901
+ IdToken: idToken,
902
+ ExpiresIn: 3600,
903
+ },
904
+ }), { status: 200 });
905
+ });
906
+ vi.stubGlobal("fetch", fetchMock);
907
+ const firstModule = await importModule();
908
+ vi.resetModules();
909
+ const secondModule = await importModule();
910
+ const first = firstModule.mintMachineTokens(CONFIG);
911
+ await firstMintStarted;
912
+ const second = secondModule.mintMachineTokens(CONFIG);
913
+ releaseFirstMint?.();
914
+ await Promise.all([first, second]);
915
+ expect(fetchMock).toHaveBeenCalledTimes(2);
916
+ expect(maxActiveMints).toBe(1);
917
+ });
918
+ it("serializes direct mints in actual separate processes", async () => {
919
+ const moduleUrl = pathToFileURL(path.join(process.cwd(), "src", "cognito-auth.ts")).href;
920
+ const marker = path.join(tmpHome, "mint-active");
921
+ const overlap = path.join(tmpHome, "mint-overlap");
922
+ const start = path.join(tmpHome, "mint-start");
923
+ const childScript = String.raw `
924
+ import fs from "fs";
925
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
926
+ const fakeJwt = (claims) => {
927
+ const enc = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
928
+ return enc({ alg: "none" }) + "." + enc(claims) + ".sig";
929
+ };
930
+ const auth = await import(process.env.HQ_LOCK_TEST_MODULE_URL);
931
+ fs.writeFileSync(process.env.HQ_LOCK_TEST_READY, "ready");
932
+ while (!fs.existsSync(process.env.HQ_LOCK_TEST_START)) await pause(5);
933
+ globalThis.fetch = async () => {
934
+ let ownsMarker = false;
935
+ try {
936
+ const fd = fs.openSync(process.env.HQ_LOCK_TEST_MARKER, "wx");
937
+ fs.closeSync(fd);
938
+ ownsMarker = true;
939
+ } catch (error) {
940
+ if (error.code === "EEXIST") {
941
+ fs.writeFileSync(process.env.HQ_LOCK_TEST_OVERLAP, "overlap");
942
+ } else {
943
+ throw error;
944
+ }
945
+ }
946
+ await pause(125);
947
+ if (ownsMarker) fs.unlinkSync(process.env.HQ_LOCK_TEST_MARKER);
948
+ return new Response(JSON.stringify({ AuthenticationResult: {
949
+ AccessToken: fakeJwt({ token_use: "access", client_id: "test-client-id", username: "machine", sub: "sub" }),
950
+ IdToken: fakeJwt({ token_use: "id", aud: "test-client-id", "custom:entityType": "agent", "custom:entityUid": "agt_TEST", "cognito:username": "machine", sub: "sub" }),
951
+ ExpiresIn: 3600
952
+ }}), { status: 200 });
953
+ };
954
+ await auth.mintMachineTokens(
955
+ { region: "us-east-1", userPoolDomain: "unused", clientId: "test-client-id" },
956
+ { username: "machine", secret: "secret", entityType: "agent", entityUid: "agt_TEST" },
957
+ { baseDelayMs: 0 }
958
+ );
959
+ `;
960
+ const children = ["a", "b"].map((name) => {
961
+ const child = spawn(process.execPath, ["--experimental-strip-types", "--input-type=module", "-e", childScript], {
962
+ cwd: process.cwd(),
963
+ env: {
964
+ ...process.env,
965
+ HOME: tmpHome,
966
+ HQ_LOCK_TEST_MODULE_URL: moduleUrl,
967
+ HQ_LOCK_TEST_READY: path.join(tmpHome, `ready-${name}`),
968
+ HQ_LOCK_TEST_START: start,
969
+ HQ_LOCK_TEST_MARKER: marker,
970
+ HQ_LOCK_TEST_OVERLAP: overlap,
971
+ },
972
+ });
973
+ let stderr = "";
974
+ child.stderr.on("data", (chunk) => {
975
+ stderr += String(chunk);
976
+ });
977
+ return { child, stderr: () => stderr };
978
+ });
979
+ const readyPaths = ["a", "b"].map((name) => path.join(tmpHome, `ready-${name}`));
980
+ const readyDeadline = Date.now() + 5_000;
981
+ while (!readyPaths.every((readyPath) => fs.existsSync(readyPath)) &&
982
+ Date.now() < readyDeadline) {
983
+ await new Promise((resolve) => setTimeout(resolve, 10));
984
+ }
985
+ expect(readyPaths.every((readyPath) => fs.existsSync(readyPath))).toBe(true);
986
+ fs.writeFileSync(start, "start");
987
+ const exits = await Promise.all(children.map(({ child, stderr }) => new Promise((resolve) => {
988
+ child.on("exit", (code) => resolve({ code, stderr: stderr() }));
989
+ })));
990
+ expect(exits).toEqual([
991
+ { code: 0, stderr: "" },
992
+ { code: 0, stderr: "" },
993
+ ]);
994
+ expect(fs.existsSync(overlap)).toBe(false);
995
+ }, 10_000);
330
996
  });
331
997
  // ---------------------------------------------------------------------------
332
998
  // Throttle handling: retry TooManyRequestsException with backoff
@@ -346,8 +1012,20 @@ describe("mintMachineTokens throttle retry", () => {
346
1012
  }
347
1013
  return new Response(JSON.stringify({
348
1014
  AuthenticationResult: {
349
- AccessToken: fakeJwt({ token_use: "access", client_id: CONFIG.clientId }),
350
- IdToken: fakeJwt({ token_use: "id" }),
1015
+ AccessToken: fakeJwt({
1016
+ token_use: "access",
1017
+ client_id: CONFIG.clientId,
1018
+ username: "machine-agt_01TEST",
1019
+ sub: "machine-sub",
1020
+ }),
1021
+ IdToken: fakeJwt({
1022
+ token_use: "id",
1023
+ aud: CONFIG.clientId,
1024
+ "custom:entityType": "agent",
1025
+ "custom:entityUid": "agt_01TEST",
1026
+ "cognito:username": "machine-agt_01TEST",
1027
+ sub: "machine-sub",
1028
+ }),
351
1029
  ExpiresIn: 3600,
352
1030
  },
353
1031
  }), { status: 200 });