@indigoai-us/hq-cloud 6.18.65 → 6.18.67

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 (46) hide show
  1. package/dist/bin/sync-runner.d.ts.map +1 -1
  2. package/dist/bin/sync-runner.js +2 -1
  3. package/dist/bin/sync-runner.js.map +1 -1
  4. package/dist/cognito-auth.d.ts +82 -1
  5. package/dist/cognito-auth.d.ts.map +1 -1
  6. package/dist/cognito-auth.js +411 -35
  7. package/dist/cognito-auth.js.map +1 -1
  8. package/dist/context.d.ts.map +1 -1
  9. package/dist/context.js +2 -1
  10. package/dist/context.js.map +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/outposts/cli-billing.d.ts +11 -0
  16. package/dist/outposts/cli-billing.d.ts.map +1 -1
  17. package/dist/outposts/cli-billing.js +18 -1
  18. package/dist/outposts/cli-billing.js.map +1 -1
  19. package/dist/outposts/cli.d.ts +1 -1
  20. package/dist/outposts/cli.d.ts.map +1 -1
  21. package/dist/outposts/cli.js +1 -1
  22. package/dist/outposts/cli.js.map +1 -1
  23. package/dist/outposts/client.d.ts +38 -0
  24. package/dist/outposts/client.d.ts.map +1 -1
  25. package/dist/outposts/client.js +90 -1
  26. package/dist/outposts/client.js.map +1 -1
  27. package/dist/outposts/command.d.ts +9 -6
  28. package/dist/outposts/command.d.ts.map +1 -1
  29. package/dist/outposts/command.js +171 -12
  30. package/dist/outposts/command.js.map +1 -1
  31. package/dist/outposts/company.d.ts +103 -0
  32. package/dist/outposts/company.d.ts.map +1 -0
  33. package/dist/outposts/company.js +266 -0
  34. package/dist/outposts/company.js.map +1 -0
  35. package/dist/outposts/errors.d.ts +7 -1
  36. package/dist/outposts/errors.d.ts.map +1 -1
  37. package/dist/outposts/errors.js +8 -1
  38. package/dist/outposts/errors.js.map +1 -1
  39. package/dist/token-keychain.d.ts +8 -0
  40. package/dist/token-keychain.d.ts.map +1 -0
  41. package/dist/token-keychain.js +7 -0
  42. package/dist/token-keychain.js.map +1 -0
  43. package/dist/vault-client.d.ts.map +1 -1
  44. package/dist/vault-client.js +3 -2
  45. package/dist/vault-client.js.map +1 -1
  46. package/package.json +1 -1
@@ -15,6 +15,7 @@
15
15
  * up a one-shot HTTP server on the chosen port, capture exactly one
16
16
  * callback, then close it.
17
17
  */
18
+ import { spawnSync } from "child_process";
18
19
  import * as crypto from "crypto";
19
20
  import * as fs from "fs";
20
21
  import * as http from "http";
@@ -297,7 +298,7 @@ function isNotWritableError(err) {
297
298
  * failing the call outright. It is deliberately NOT a substitute for the shared
298
299
  * on-disk cache: a fresh subprocess starts empty and re-mints.
299
300
  */
300
- let inMemoryCachedTokens = null;
301
+ const inMemoryCachedTokens = new Map();
301
302
  /**
302
303
  * True when `tokens` were minted for a machine identity (agent or outpost),
303
304
  * judged by the ID token's `custom:entityType` claim. People never carry that
@@ -306,24 +307,66 @@ let inMemoryCachedTokens = null;
306
307
  */
307
308
  export function tokensCarryMachineIdentity(tokens) {
308
309
  const idClaims = decodeJwtClaims(tokens.idToken);
310
+ const accessClaims = decodeJwtClaims(tokens.accessToken);
309
311
  const entityType = idClaims?.["custom:entityType"];
310
- return typeof entityType === "string" && entityType.trim().length > 0;
312
+ return (typeof entityType === "string" && entityType.trim().length > 0) ||
313
+ (idClaims !== null && hasCompanyMarkers(idClaims)) ||
314
+ (accessClaims !== null && hasCompanyMarkers(accessClaims));
315
+ }
316
+ /**
317
+ * The shared macOS Keychain copy of the person session (see
318
+ * ./token-keychain.ts), or null. Invalidated and machine-identity tokens are
319
+ * refused, the same as the file.
320
+ */
321
+ function loadPersonTokensFromKeychain() {
322
+ const raw = readKeychainTokenJson();
323
+ if (!raw)
324
+ return null;
325
+ try {
326
+ const tokens = JSON.parse(raw);
327
+ if (!tokens ||
328
+ typeof tokens.accessToken !== "string" ||
329
+ tokens.accessToken.length === 0 ||
330
+ typeof tokens.idToken !== "string" ||
331
+ tokens.idToken.length === 0 ||
332
+ tokenIsInvalidated(tokens.accessToken, "person") ||
333
+ tokensCarryMachineIdentity(tokens)) {
334
+ return null;
335
+ }
336
+ return tokens;
337
+ }
338
+ catch {
339
+ return null;
340
+ }
311
341
  }
312
342
  function loadCachedTokensFrom(kind) {
313
343
  const file = cacheFileFor(kind);
344
+ const memory = () => {
345
+ const tokens = inMemoryCachedTokens.get(file);
346
+ return tokens && !tokenIsInvalidated(tokens.accessToken, kind) ? tokens : null;
347
+ };
348
+ // No file means signed out; the Keychain is not consulted.
314
349
  if (!fs.existsSync(file))
315
- return inMemoryCachedTokens;
350
+ return memory();
351
+ let fromFile = null;
352
+ let unreadable = false;
316
353
  try {
317
354
  const raw = fs.readFileSync(file, "utf-8");
318
355
  const tokens = JSON.parse(raw);
319
- if (!tokens.accessToken || tokenIsInvalidated(tokens.accessToken, kind)) {
320
- return null;
356
+ if (tokens.accessToken && !tokenIsInvalidated(tokens.accessToken, kind)) {
357
+ fromFile = tokens;
321
358
  }
322
- return tokens;
323
359
  }
324
360
  catch {
325
- return inMemoryCachedTokens;
361
+ unreadable = true;
362
+ }
363
+ // Person session: the Keychain item first, the newer by expiresAt wins.
364
+ const fromKeychain = kind === "person" ? loadPersonTokensFromKeychain() : null;
365
+ if (unreadable) {
366
+ // This process's own last save competes with the Keychain copy.
367
+ return pickNewerSession(fromKeychain, memory());
326
368
  }
369
+ return pickNewerSession(fromKeychain, fromFile);
327
370
  }
328
371
  /**
329
372
  * The PERSON's cached session, or null.
@@ -334,6 +377,8 @@ function loadCachedTokensFrom(kind) {
334
377
  * the human path re-authenticates.
335
378
  */
336
379
  export function loadCachedTokens() {
380
+ if (companyMachineRequired())
381
+ return null;
337
382
  const tokens = loadCachedTokensFrom("person");
338
383
  if (tokens && tokensCarryMachineIdentity(tokens))
339
384
  return null;
@@ -341,7 +386,21 @@ export function loadCachedTokens() {
341
386
  }
342
387
  /** The MACHINE identity's cached session, or null. */
343
388
  export function loadCachedMachineTokens() {
344
- return loadCachedTokensFrom("machine");
389
+ const tokens = loadCachedTokensFrom("machine");
390
+ if (!companyMachineRequired() || !tokens)
391
+ return tokens;
392
+ const creds = loadMachineCreds();
393
+ if (!creds || creds.entityType !== "company-outpost" || !creds.clientId || !creds.region)
394
+ return null;
395
+ // Company credentials carry their own client and region, so no caller config
396
+ // is needed to validate the same generation key used by the mint path.
397
+ const config = {
398
+ clientId: creds.clientId, region: creds.region, userPoolDomain: "",
399
+ };
400
+ if (tokens.machineCredentialKey !== machineIdentityKey(config, creds) ||
401
+ !machineTokenPairMatchesIdentity(tokens, creds, creds.clientId))
402
+ return null;
403
+ return tokens;
345
404
  }
346
405
  /**
347
406
  * Persist a session to the cache that belongs to the principal it names.
@@ -355,12 +414,12 @@ export function loadCachedMachineTokens() {
355
414
  export function saveCachedTokens(tokens) {
356
415
  // Remember in-process FIRST: whatever happens to the disk write below, this
357
416
  // process must not lose a session it already successfully minted.
358
- inMemoryCachedTokens = tokens;
359
417
  const kind = tokensCarryMachineIdentity(tokens)
360
418
  ? "machine"
361
419
  : "person";
362
420
  const stateDir = stateDirFor(kind);
363
421
  const cacheFile = cacheFileFor(kind);
422
+ inMemoryCachedTokens.set(cacheFile, tokens);
364
423
  try {
365
424
  if (!fs.existsSync(stateDir)) {
366
425
  fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
@@ -381,6 +440,9 @@ export function saveCachedTokens(tokens) {
381
440
  }
382
441
  }
383
442
  function clearCachedTokensOf(kind) {
443
+ inMemoryCachedTokens.delete(cacheFileFor(kind));
444
+ if (kind === "machine")
445
+ inProcessMachineTokens = null;
384
446
  const file = cacheFileFor(kind);
385
447
  const dir = stateDirFor(kind);
386
448
  if (fs.existsSync(file))
@@ -449,8 +511,7 @@ function refreshLockWaitLogMs() {
449
511
  const n = Number(raw);
450
512
  return Number.isFinite(n) && n >= 0 ? n : DEFAULT_REFRESH_LOCK_WAIT_LOG_MS;
451
513
  }
452
- function readLockOwner(kind) {
453
- const lockFile = refreshLockFile(kind);
514
+ function readLockOwner(kind, lockFile = refreshLockFile(kind)) {
454
515
  let raw;
455
516
  try {
456
517
  raw = fs.readFileSync(lockFile, "utf-8");
@@ -486,8 +547,8 @@ function readLockOwner(kind) {
486
547
  return { pid, startedAtMs };
487
548
  }
488
549
  /** The pid recorded in the lockfile, or null if absent/empty/malformed. */
489
- function readLockOwnerPid(kind) {
490
- const owner = readLockOwner(kind);
550
+ function readLockOwnerPid(kind, lockFile = refreshLockFile(kind)) {
551
+ const owner = readLockOwner(kind, lockFile);
491
552
  return owner?.pid ?? null;
492
553
  }
493
554
  /**
@@ -638,7 +699,7 @@ async function withRefreshLock(kind, fn) {
638
699
  catch (err) {
639
700
  if (err.code !== "EEXIST")
640
701
  throw err;
641
- const owner = readLockOwner(kind);
702
+ const owner = readLockOwner(kind, lockFile);
642
703
  const age = owner === null ? Infinity : Date.now() - owner.startedAtMs;
643
704
  const deadHolder = owner !== null && owner.pid !== process.pid && !processAlive(owner.pid);
644
705
  const staleByTtl = owner !== null && age > maxHoldMs;
@@ -680,7 +741,7 @@ async function withRefreshLock(kind, fn) {
680
741
  }
681
742
  finally {
682
743
  // Release ONLY our own lock — never clobber a successor's.
683
- if (held && readLockOwnerPid(kind) === process.pid) {
744
+ if (held && readLockOwnerPid(kind, lockFile) === process.pid) {
684
745
  try {
685
746
  fs.unlinkSync(lockFile);
686
747
  }
@@ -754,11 +815,48 @@ function decodeJwtClaims(token) {
754
815
  return null;
755
816
  }
756
817
  }
818
+ const owns = (bag, key) => Object.prototype.hasOwnProperty.call(bag, key);
819
+ function hasCompanyMarkers(claims) {
820
+ return claims["custom:entityType"] === "company-outpost" ||
821
+ owns(claims, "custom:ownerCompanyUid") || owns(claims, "custom:companyOutpostId");
822
+ }
823
+ function validCompanyCredentials(raw) {
824
+ return typeof raw.entityUid === "string" && /^out_[0-9A-HJKMNP-TV-Z]{26}$/.test(raw.entityUid) &&
825
+ typeof raw.username === "string" && raw.username.trim().length > 0 &&
826
+ typeof raw.secret === "string" && raw.secret.trim().length > 0 &&
827
+ typeof raw.clientId === "string" && raw.clientId.trim().length > 0 &&
828
+ typeof raw.region === "string" && /^[a-z]{2}-[a-z]+-[0-9]+$/.test(raw.region) &&
829
+ (raw.runtime === undefined || raw.runtime === "hosted") &&
830
+ !owns(raw, "delegatedSub") && !owns(raw, "delegatedEmail") &&
831
+ !owns(raw, "custom:delegatedSub") && !owns(raw, "custom:delegatedEmail");
832
+ }
833
+ function companyClaimsMatch(claims, creds, clientId) {
834
+ const company = claims["custom:ownerCompanyUid"];
835
+ return claims["custom:entityType"] === "company-outpost" &&
836
+ claims["custom:entityUid"] === creds.entityUid &&
837
+ claims["custom:authClientId"] === clientId &&
838
+ typeof company === "string" && /^cmp_[A-Za-z0-9]+$/.test(company) &&
839
+ claims["custom:companyOutpostId"] === `outpost_${company}` &&
840
+ (!process.env.HQ_COMPANY_UID || company === process.env.HQ_COMPANY_UID) &&
841
+ (!process.env.HQ_COMPANY_OUTPOST_ID || claims["custom:companyOutpostId"] === process.env.HQ_COMPANY_OUTPOST_ID) &&
842
+ !owns(claims, "custom:delegatedSub") && !owns(claims, "custom:delegatedEmail") &&
843
+ typeof claims.sub === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(claims.sub) &&
844
+ typeof claims.exp === "number" && claims.exp * 1000 > Date.now();
845
+ }
757
846
  function machineTokenPairMatchesIdentity(tokens, creds, expectedClientId) {
758
847
  const accessClaims = decodeJwtClaims(tokens.accessToken);
759
848
  const idClaims = decodeJwtClaims(tokens.idToken);
760
849
  if (!accessClaims || !idClaims)
761
850
  return false;
851
+ if (creds.entityType === "company-outpost") {
852
+ if (!creds.entityUid || !/^out_[0-9A-HJKMNP-TV-Z]{26}$/.test(creds.entityUid) ||
853
+ !companyClaimsMatch(idClaims, creds, expectedClientId) ||
854
+ !companyClaimsMatch(accessClaims, creds, expectedClientId) ||
855
+ idClaims["custom:ownerCompanyUid"] !== accessClaims["custom:ownerCompanyUid"])
856
+ return false;
857
+ }
858
+ else if (hasCompanyMarkers(idClaims) || hasCompanyMarkers(accessClaims))
859
+ return false;
762
860
  const stringClaim = (claims, key) => {
763
861
  const value = claims[key];
764
862
  return typeof value === "string" && value.length > 0 ? value : null;
@@ -774,9 +872,10 @@ function machineTokenPairMatchesIdentity(tokens, creds, expectedClientId) {
774
872
  const entityUid = stringClaim(idClaims, "custom:entityUid");
775
873
  const delegatedSub = stringClaim(idClaims, "custom:delegatedSub");
776
874
  const delegatedEmail = stringClaim(idClaims, "custom:delegatedEmail");
777
- const hasValidMachineClaimShape = (entityType === "agent" &&
778
- entityUid !== null &&
779
- entityUid.startsWith("agt_")) ||
875
+ const hasValidMachineClaimShape = entityType === "company-outpost" ||
876
+ (entityType === "agent" &&
877
+ entityUid !== null &&
878
+ entityUid.startsWith("agt_")) ||
780
879
  (entityType === "outpost" &&
781
880
  entityUid !== null &&
782
881
  entityUid.startsWith("out_") &&
@@ -837,6 +936,12 @@ export function loadMachineCreds() {
837
936
  if (!fs.existsSync(file))
838
937
  return null;
839
938
  const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
939
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
940
+ return null;
941
+ if (companyMachineRequired() && raw.entityType !== "company-outpost")
942
+ return null;
943
+ if (raw.entityType === "company-outpost" && !validCompanyCredentials(raw))
944
+ return null;
840
945
  // `runtime` is a closed set: anything else is a malformed file, not a
841
946
  // silent downgrade to hosted (a typo must never bypass host-key signing).
842
947
  if (raw.runtime !== undefined &&
@@ -864,7 +969,7 @@ export function loadMachineCreds() {
864
969
  typeof raw.entityUid === "string" &&
865
970
  raw.entityUid.startsWith("agt_") &&
866
971
  raw.entityUid.length > "agt_".length) ||
867
- (raw.entityType === "outpost" &&
972
+ ((raw.entityType === "outpost" || raw.entityType === "company-outpost") &&
868
973
  typeof raw.entityUid === "string" &&
869
974
  raw.entityUid.startsWith("out_") &&
870
975
  raw.entityUid.length > "out_".length);
@@ -878,7 +983,7 @@ export function loadMachineCreds() {
878
983
  secret: raw.secret,
879
984
  clientId: typeof raw.clientId === "string" ? raw.clientId : undefined,
880
985
  region: typeof raw.region === "string" ? raw.region : undefined,
881
- ...(raw.entityType === "agent" || raw.entityType === "outpost"
986
+ ...(raw.entityType === "agent" || raw.entityType === "outpost" || raw.entityType === "company-outpost"
882
987
  ? { entityType: raw.entityType }
883
988
  : {}),
884
989
  ...(typeof raw.entityUid === "string"
@@ -955,7 +1060,18 @@ export function isMachineIdentity() {
955
1060
  */
956
1061
  export function machineIdentityRequired() {
957
1062
  const raw = process.env.HQ_REQUIRE_MACHINE_IDENTITY?.trim().toLowerCase();
958
- return raw === "1" || raw === "true" || raw === "yes";
1063
+ return raw === "1" || raw === "true" || raw === "yes" ||
1064
+ companyMachineRequired();
1065
+ }
1066
+ /** Company bootstrap contract; the older switch continues to accept agents. */
1067
+ function companyMachineRequired() {
1068
+ const required = process.env.HQ_MACHINE_AUTH_REQUIRED?.trim().toLowerCase();
1069
+ return required === "1" || required === "true" || required === "yes";
1070
+ }
1071
+ function assertHumanAuthenticationAllowed() {
1072
+ if (companyMachineRequired()) {
1073
+ throw new CognitoAuthError("Human authentication is unavailable in required company machine mode");
1074
+ }
959
1075
  }
960
1076
  /**
961
1077
  * Throw a typed, diagnosable error when machine identity is REQUIRED but the
@@ -971,7 +1087,7 @@ export function assertMachineIdentityWhenRequired() {
971
1087
  const source = explicit !== undefined && explicit.length > 0
972
1088
  ? "HQ_MACHINE_CREDS_FILE"
973
1089
  : `os.homedir()=${os.homedir()}`;
974
- throw new CognitoAuthError(`HQ_REQUIRE_MACHINE_IDENTITY is set but no usable machine credentials were ` +
1090
+ throw new CognitoAuthError(`HQ_REQUIRE_MACHINE_IDENTITY or HQ_MACHINE_AUTH_REQUIRED is set but no usable machine credentials were ` +
975
1091
  `found at ${machineCredsFilePath()} (path from ${source}). Refusing to ` +
976
1092
  `fall back to an interactive human session. Set HQ_MACHINE_CREDS_FILE to ` +
977
1093
  `the credentials file, or run with the HOME that owns it.`);
@@ -1012,11 +1128,19 @@ function backoffDelayMs(attempt, opts) {
1012
1128
  * full jitter (transient, per-user rate limit); every other non-OK response
1013
1129
  * (bad creds, disabled flow) is a hard error surfaced immediately.
1014
1130
  */
1015
- async function mintMachineTokensUnlocked(config, creds, retry) {
1131
+ async function mintMachineTokensUnlocked(config, creds, retry, assertCurrent = () => { }) {
1132
+ assertCurrent();
1016
1133
  const machineCreds = creds ?? loadMachineCreds();
1017
1134
  if (!machineCreds) {
1018
1135
  throw new CognitoAuthError(`No machine credentials found at ${machineCredsFilePath()}`);
1019
1136
  }
1137
+ if (companyMachineRequired() && machineCreds.entityType !== "company-outpost") {
1138
+ throw new CognitoAuthError("Company machine authentication requires company-outpost credentials");
1139
+ }
1140
+ if (machineCreds.entityType === "company-outpost" &&
1141
+ !validCompanyCredentials({ ...machineCreds })) {
1142
+ throw new CognitoAuthError("Invalid company machine credentials");
1143
+ }
1020
1144
  // Prefer the creds file's own clientId/region: provisioning pairs the
1021
1145
  // machine user with an app client that has USER_PASSWORD_AUTH enabled,
1022
1146
  // which the CLI's default (browser) client may not.
@@ -1026,7 +1150,11 @@ async function mintMachineTokensUnlocked(config, creds, retry) {
1026
1150
  // External agents never talk to Cognito directly: hq-pro performs the
1027
1151
  // USER_PASSWORD_AUTH on their behalf once they prove the host key.
1028
1152
  if (isExternalMachineCreds(machineCreds)) {
1029
- return mintExternalMachineTokens(machineCreds, clientId, retryOpts);
1153
+ const tokens = await mintExternalMachineTokens(machineCreds, clientId, retryOpts);
1154
+ assertCurrent();
1155
+ tokens.machineCredentialKey = machineIdentityKey(config, machineCreds);
1156
+ saveCachedTokens(tokens);
1157
+ return tokens;
1030
1158
  }
1031
1159
  let lastError = null;
1032
1160
  for (let attempt = 0; attempt <= retryOpts.maxRetries; attempt++) {
@@ -1074,6 +1202,8 @@ async function mintMachineTokensUnlocked(config, creds, retry) {
1074
1202
  if (!machineTokenPairMatchesIdentity(tokens, machineCreds, clientId)) {
1075
1203
  throw new CognitoAuthError("Machine token mint returned tokens that do not match the requested machine identity");
1076
1204
  }
1205
+ assertCurrent();
1206
+ tokens.machineCredentialKey = machineIdentityKey(config, machineCreds);
1077
1207
  saveCachedTokens(tokens);
1078
1208
  return tokens;
1079
1209
  }
@@ -1185,7 +1315,6 @@ async function mintExternalMachineTokens(creds, clientId, retryOpts) {
1185
1315
  if (!machineTokenPairMatchesIdentity(tokens, creds, clientId)) {
1186
1316
  throw new CognitoAuthError("External machine token mint returned tokens that do not match the requested machine identity");
1187
1317
  }
1188
- saveCachedTokens(tokens);
1189
1318
  return tokens;
1190
1319
  }
1191
1320
  throw lastError ?? new CognitoAuthError("External machine token mint failed: throttled");
@@ -1196,7 +1325,21 @@ async function mintExternalMachineTokens(creds, clientId, retryOpts) {
1196
1325
  * race another process's cache write.
1197
1326
  */
1198
1327
  export async function mintMachineTokens(config, creds, retry) {
1199
- return withRefreshLock("machine", () => mintMachineTokensUnlocked(config, creds, retry));
1328
+ const selected = creds ?? loadMachineCreds();
1329
+ if (!selected)
1330
+ throw new CognitoAuthError("No usable machine credentials found");
1331
+ const identityKey = machineIdentityKey(config, selected);
1332
+ const companyContext = companyMachineRequired() || selected.entityType === "company-outpost";
1333
+ const fileBound = !creds || loadMachineCreds() !== null || machineIdentityRequired();
1334
+ const assertCurrent = () => {
1335
+ if (!companyContext && !companyMachineRequired())
1336
+ return;
1337
+ const current = fileBound ? loadMachineCreds() : selected;
1338
+ if (!current || machineIdentityKey(config, current) !== identityKey) {
1339
+ throw new CognitoAuthError("Machine credentials changed during authentication; retry with the current identity");
1340
+ }
1341
+ };
1342
+ return withRefreshLock("machine", () => mintMachineTokensUnlocked(config, selected, retry, assertCurrent));
1200
1343
  }
1201
1344
  let inProcessMachineTokens = null;
1202
1345
  const inFlightMachineMints = new Map();
@@ -1204,12 +1347,17 @@ export const DEFAULT_MACHINE_TOKEN_MIN_VALIDITY_SECONDS = 360;
1204
1347
  // Machine sessions last one hour; a larger requirement would re-mint on every call.
1205
1348
  export const MAX_MACHINE_TOKEN_MIN_VALIDITY_SECONDS = 1800;
1206
1349
  function machineIdentityKey(config, creds) {
1207
- // Include every credential value that can change the effective mint. Hashing
1208
- // keeps the long-lived secret out of diagnostic heap strings while retaining
1209
- // exact-key behavior when a creds file is reprovisioned in place.
1350
+ // Hash only credential fields that change the effective mint, plus the
1351
+ // company-env bindings that scope a company-outpost token. Env-dependent
1352
+ // process state (HQ_REQUIRE_MACHINE_IDENTITY, HQ_MACHINE_AUTH_REQUIRED,
1353
+ // credential/cache paths) is intentionally excluded so sibling processes
1354
+ // sharing the same creds file compute the same key and share the cache.
1210
1355
  return crypto
1211
1356
  .createHash("sha256")
1212
1357
  .update(JSON.stringify({
1358
+ companyUid: process.env.HQ_COMPANY_UID ?? null,
1359
+ outpostId: process.env.HQ_COMPANY_OUTPOST_ID ?? null,
1360
+ attempt: process.env.HQ_COMPANY_OUTPOST_ATTEMPT ?? null,
1213
1361
  username: creds.username,
1214
1362
  secret: creds.secret,
1215
1363
  clientId: creds.clientId ?? config.clientId,
@@ -1241,9 +1389,32 @@ export async function getValidMachineTokens(config, options = {}) {
1241
1389
  }
1242
1390
  const expectedClientId = machineCreds.clientId ?? config.clientId;
1243
1391
  const identityKey = machineIdentityKey(config, machineCreds);
1392
+ const companyContext = companyMachineRequired() || machineCreds.entityType === "company-outpost";
1393
+ const assertCurrent = () => {
1394
+ if (!companyContext && !companyMachineRequired())
1395
+ return;
1396
+ const current = loadMachineCreds();
1397
+ if (!current || machineIdentityKey(config, current) !== identityKey) {
1398
+ throw new CognitoAuthError("Machine credentials changed during authentication; retry with the current identity");
1399
+ }
1400
+ };
1401
+ // Only company-outpost identities (or company-required mode) enforce exact
1402
+ // machineCredentialKey equality. Agent/outpost identities fall back to the
1403
+ // pre-branch behavior: a claims match on the cached token is sufficient,
1404
+ // regardless of which process minted it. This lets agent-box siblings
1405
+ // (mesh daemon, agent-inbox, bot, mcp op) share one cache even when they
1406
+ // disagree on HQ_REQUIRE_MACHINE_IDENTITY or HQ_MACHINE_CREDS_FILE.
1407
+ const requiresKeyEquality = machineCreds.entityType === "company-outpost" || companyMachineRequired();
1408
+ const cacheMatches = (tokens) => {
1409
+ if (requiresKeyEquality && tokens.machineCredentialKey !== identityKey) {
1410
+ return false;
1411
+ }
1412
+ return machineTokenPairMatchesIdentity(tokens, machineCreds, expectedClientId);
1413
+ };
1244
1414
  const resolutionKey = `${identityKey}\0${minValiditySeconds}`;
1245
1415
  // Hot path: a live in-memory token serves every request after the first.
1246
1416
  if (inProcessMachineTokens?.identityKey === identityKey &&
1417
+ !tokenIsInvalidated(inProcessMachineTokens.tokens.accessToken, "machine") &&
1247
1418
  !isExpiring(inProcessMachineTokens.tokens, minValiditySeconds) &&
1248
1419
  machineTokenPairMatchesIdentity(inProcessMachineTokens.tokens, machineCreds, expectedClientId)) {
1249
1420
  return inProcessMachineTokens.tokens;
@@ -1252,10 +1423,14 @@ export async function getValidMachineTokens(config, options = {}) {
1252
1423
  // The assignment below completes before the first `await` yields, so sibling
1253
1424
  // callers in the same tick see the in-flight promise and reuse it.
1254
1425
  const existingResolution = inFlightMachineMints.get(resolutionKey);
1255
- if (existingResolution)
1256
- return existingResolution;
1426
+ if (existingResolution) {
1427
+ const tokens = await existingResolution;
1428
+ assertCurrent();
1429
+ return tokens;
1430
+ }
1257
1431
  const resolution = (async () => {
1258
1432
  const resolveUnderLock = async () => {
1433
+ assertCurrent();
1259
1434
  // Re-read only after acquiring the process-shared lock. A different hq
1260
1435
  // process may have minted and saved this machine's session while this
1261
1436
  // caller was waiting.
@@ -1265,7 +1440,7 @@ export async function getValidMachineTokens(config, options = {}) {
1265
1440
  // clientId wins over config), and require the cached ID token to prove
1266
1441
  // the exact machine identity. Opaque/missing/human-shaped claims are
1267
1442
  // treated as stale.
1268
- if (machineTokenPairMatchesIdentity(cached, machineCreds, expectedClientId)) {
1443
+ if (cacheMatches(cached)) {
1269
1444
  if (cached.refreshToken === "")
1270
1445
  return cached;
1271
1446
  const normalized = { ...cached, refreshToken: "" };
@@ -1275,7 +1450,7 @@ export async function getValidMachineTokens(config, options = {}) {
1275
1450
  }
1276
1451
  // mintMachineTokens persists before returning, so the complete shared
1277
1452
  // cache read -> USER_PASSWORD_AUTH mint -> save sequence is serialized.
1278
- return mintMachineTokensUnlocked(config, machineCreds);
1453
+ return mintMachineTokensUnlocked(config, machineCreds, undefined, assertCurrent);
1279
1454
  };
1280
1455
  try {
1281
1456
  return await withRefreshLock("machine", resolveUnderLock);
@@ -1287,7 +1462,7 @@ export async function getValidMachineTokens(config, options = {}) {
1287
1462
  // session, reuse it; otherwise surface a retryable auth failure.
1288
1463
  const cached = loadCachedMachineTokens();
1289
1464
  if (cached && !isExpiring(cached, minValiditySeconds)) {
1290
- if (machineTokenPairMatchesIdentity(cached, machineCreds, expectedClientId)) {
1465
+ if (cacheMatches(cached)) {
1291
1466
  // The successful path always leaves a machine cache with no refresh
1292
1467
  // token. If this is legacy state, only normalize it while holding the
1293
1468
  // lock; after a timeout we must not race the live holder's write.
@@ -1306,6 +1481,7 @@ export async function getValidMachineTokens(config, options = {}) {
1306
1481
  inFlightMachineMints.set(resolutionKey, resolution);
1307
1482
  try {
1308
1483
  const tokens = await resolution;
1484
+ assertCurrent();
1309
1485
  inProcessMachineTokens = { identityKey, tokens };
1310
1486
  return tokens;
1311
1487
  }
@@ -1351,6 +1527,7 @@ function redirectUri(port) {
1351
1527
  * Times out after 5 minutes if the user doesn't complete the flow.
1352
1528
  */
1353
1529
  export async function browserLogin(config) {
1530
+ assertHumanAuthenticationAllowed();
1354
1531
  const port = config.port ?? 3000;
1355
1532
  const scopes = (config.scopes ?? ["openid", "email", "profile"]).join(" ");
1356
1533
  const { verifier, challenge } = generatePkce();
@@ -1372,7 +1549,9 @@ export async function browserLogin(config) {
1372
1549
  authUrl.searchParams.set("prompt", config.prompt);
1373
1550
  }
1374
1551
  const code = await waitForAuthCode(port, state);
1552
+ assertHumanAuthenticationAllowed();
1375
1553
  const tokens = await exchangeCodeForTokens(config, code, verifier, port);
1554
+ assertHumanAuthenticationAllowed();
1376
1555
  saveCachedTokens(tokens);
1377
1556
  return tokens;
1378
1557
  // -- inner: spin up loopback server and open browser ---------------------
@@ -1428,6 +1607,11 @@ export async function browserLogin(config) {
1428
1607
  reject(err);
1429
1608
  });
1430
1609
  server.listen(port, "127.0.0.1", () => {
1610
+ if (companyMachineRequired()) {
1611
+ cleanup();
1612
+ reject(new CognitoAuthError("Human authentication is unavailable in required company machine mode"));
1613
+ return;
1614
+ }
1431
1615
  console.log(`\n Opening browser for HQ sign-in...`);
1432
1616
  console.log(` If your browser doesn't open, visit:\n ${authUrl.toString()}\n`);
1433
1617
  open(authUrl.toString()).catch(() => {
@@ -1494,7 +1678,9 @@ function cachedIsForClient(cached, config) {
1494
1678
  * session (AWS). Durable never-log-out is per-box machine identity (ADR-0009).
1495
1679
  */
1496
1680
  export async function refreshTokens(config, currentRefreshToken, currentAccessToken) {
1681
+ assertHumanAuthenticationAllowed();
1497
1682
  const doRefresh = async () => {
1683
+ assertHumanAuthenticationAllowed();
1498
1684
  const cached = loadCachedTokens();
1499
1685
  // Reuse a token another refresher just produced — but ONLY when it belongs
1500
1686
  // to THIS app client (a direct caller may target a different pool than the
@@ -1527,6 +1713,7 @@ export async function refreshTokens(config, currentRefreshToken, currentAccessTo
1527
1713
  });
1528
1714
  let lastFailure;
1529
1715
  for (let attempt = 0; attempt < 2; attempt++) {
1716
+ assertHumanAuthenticationAllowed();
1530
1717
  let res;
1531
1718
  try {
1532
1719
  res = await fetch(`${authBaseUrl(config)}/oauth2/token`, {
@@ -1576,6 +1763,7 @@ export async function refreshTokens(config, currentRefreshToken, currentAccessTo
1576
1763
  throw lastFailure;
1577
1764
  }
1578
1765
  const data = (await res.json());
1766
+ assertHumanAuthenticationAllowed();
1579
1767
  const tokens = {
1580
1768
  accessToken: data.access_token,
1581
1769
  idToken: data.id_token,
@@ -1593,7 +1781,9 @@ export async function refreshTokens(config, currentRefreshToken, currentAccessTo
1593
1781
  new CognitoRefreshError("Cognito refresh failed after retry", false));
1594
1782
  };
1595
1783
  try {
1596
- return await withRefreshLock("person", doRefresh);
1784
+ const tokens = await withRefreshLock("person", doRefresh);
1785
+ assertHumanAuthenticationAllowed();
1786
+ return tokens;
1597
1787
  }
1598
1788
  catch (err) {
1599
1789
  if (!(err instanceof RefreshLockTimeoutError))
@@ -1699,4 +1889,190 @@ export const __testing = {
1699
1889
  linkUnsupportedKinds.clear();
1700
1890
  },
1701
1891
  };
1892
+ // ---------------------------------------------------------------------------
1893
+ // Shared macOS Keychain read of the person session.
1894
+ //
1895
+ // Lives in this file, not a sibling module: cognito-auth.ts is imported
1896
+ // directly with --experimental-strip-types by the cross-process lock tests,
1897
+ // and a relative "./x.js" import does not resolve to x.ts there. The public
1898
+ // surface is re-exported from ./token-keychain.ts.
1899
+ // ---------------------------------------------------------------------------
1900
+ /**
1901
+ * macOS Keychain read of the person Cognito session (step 1 of moving the
1902
+ * session off `~/.hq/cognito-tokens.json`).
1903
+ *
1904
+ * Shared item (must match hq-desktop-app `token_keychain.rs`, desktop #1586,
1905
+ * and hq-cli `src/utils/token-keychain.ts`):
1906
+ * - class: generic password, login keychain
1907
+ * - service: `ai.indigo.hq.cognito-tokens`
1908
+ * - account: `person`
1909
+ * - value: the same camelCase JSON as the token file
1910
+ * - signer: Team ID HWFZ2QDTMR (login-keychain partition `teamid:HWFZ2QDTMR`)
1911
+ *
1912
+ * The read goes through `/usr/bin/security` (no native module). macOS asks
1913
+ * the user once whether `security` may read the item; HQ accepts that prompt
1914
+ * (owner decision) and explains it first:
1915
+ * - Before the first read, a one-line note goes to stderr. Until a read has
1916
+ * succeeded, reads (which may prompt) only happen in a terminal, so a
1917
+ * background sync never raises the prompt unexplained.
1918
+ * - A denied prompt, a timeout or any other failure falls back to the file
1919
+ * quietly and is remembered in `~/.hq/keychain-access.json` (shared with
1920
+ * the hq CLI), so HQ does not ask again on every run.
1921
+ * `hq auth keychain --retry` clears it.
1922
+ * - "Item not found" is a plain miss.
1923
+ *
1924
+ * Choosing between the Keychain and the file (writes still go to the file):
1925
+ * - No file means signed out; the Keychain is not read.
1926
+ * - Both valid: the newer session by `expiresAt` wins; a tie keeps the
1927
+ * Keychain value.
1928
+ *
1929
+ * Non-macOS, an `HQ_STATE_DIR` override and `HQ_TOKEN_KEYCHAIN=0` read the
1930
+ * file only. Token values are never printed or logged.
1931
+ */
1932
+ export const KEYCHAIN_SERVICE = "ai.indigo.hq.cognito-tokens";
1933
+ export const KEYCHAIN_ACCOUNT = "person";
1934
+ export const KEYCHAIN_TEAM_ID = "HWFZ2QDTMR";
1935
+ export const KEYCHAIN_READ_TIMEOUT_MS = 3_000;
1936
+ export const KEYCHAIN_FIRST_READ_TIMEOUT_MS = 60_000;
1937
+ const SECURITY_ITEM_NOT_FOUND = 44;
1938
+ const READ_CACHE_MS = 30_000;
1939
+ export const KEYCHAIN_FIRST_READ_NOTE = "macOS will ask once whether HQ can read your sign-in from the Keychain. Choose Always Allow.";
1940
+ const defaultRunner = (args, timeoutMs) => {
1941
+ try {
1942
+ const result = spawnSync("/usr/bin/security", args, {
1943
+ encoding: "utf8",
1944
+ timeout: timeoutMs,
1945
+ stdio: ["ignore", "pipe", "ignore"],
1946
+ });
1947
+ const timedOut = result.error?.code === "ETIMEDOUT";
1948
+ return { status: result.status, stdout: typeof result.stdout === "string" ? result.stdout : "", timedOut };
1949
+ }
1950
+ catch {
1951
+ return { status: null, stdout: "", timedOut: false };
1952
+ }
1953
+ };
1954
+ let testOverrides = null;
1955
+ /** Test seam: defaults merged into every read (runner, platform, interactive...). */
1956
+ export function setKeychainReaderForTests(overrides) {
1957
+ testOverrides = overrides;
1958
+ readCache = null;
1959
+ }
1960
+ function resolve(opts) {
1961
+ return { ...(testOverrides ?? {}), ...opts };
1962
+ }
1963
+ export function keychainTokenReadEnabled(opts = {}) {
1964
+ const o = resolve(opts);
1965
+ const platform = o.platform ?? process.platform;
1966
+ const env = o.env ?? process.env;
1967
+ if (platform !== "darwin")
1968
+ return false;
1969
+ const flag = env.HQ_TOKEN_KEYCHAIN?.trim().toLowerCase();
1970
+ if (flag === "0" || flag === "false" || flag === "off")
1971
+ return false;
1972
+ if (env.HQ_STATE_DIR?.trim())
1973
+ return false;
1974
+ return true;
1975
+ }
1976
+ export function keychainAccessStateFile(home = os.homedir()) {
1977
+ return path.join(home, ".hq", "keychain-access.json");
1978
+ }
1979
+ export function readKeychainAccessState(home = os.homedir()) {
1980
+ try {
1981
+ const parsed = JSON.parse(fs.readFileSync(keychainAccessStateFile(home), "utf8"));
1982
+ return parsed && typeof parsed === "object" ? parsed : {};
1983
+ }
1984
+ catch {
1985
+ return {};
1986
+ }
1987
+ }
1988
+ function writeKeychainAccessState(home, state) {
1989
+ try {
1990
+ const file = keychainAccessStateFile(home);
1991
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
1992
+ const tmp = `${file}.tmp.${process.pid}`;
1993
+ fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
1994
+ fs.renameSync(tmp, file);
1995
+ }
1996
+ catch {
1997
+ // Best effort: without the marker HQ may ask again, which is safe.
1998
+ }
1999
+ }
2000
+ /** `security -w` prints hex when the secret has non-printable bytes (newlines). */
2001
+ function decodeSecurityOutput(stdout) {
2002
+ const trimmed = stdout.replace(/\r?\n$/, "");
2003
+ if (!trimmed.startsWith("{") && /^(?:[0-9a-fA-F]{2})+$/.test(trimmed)) {
2004
+ return Buffer.from(trimmed, "hex").toString("utf8");
2005
+ }
2006
+ return trimmed;
2007
+ }
2008
+ let readCache = null;
2009
+ /**
2010
+ * The raw JSON string of the Keychain copy (callers validate it like the
2011
+ * file), applying the first-read note, the remembered denial and timeouts.
2012
+ * Never throws.
2013
+ */
2014
+ export function readKeychainTokenJsonDetailed(opts = {}) {
2015
+ const o = resolve(opts);
2016
+ if (!keychainTokenReadEnabled(o))
2017
+ return { json: null, outcome: "disabled" };
2018
+ const home = o.home ?? os.homedir();
2019
+ if (!o.retry && readCache && readCache.home === home && Date.now() - readCache.at < READ_CACHE_MS) {
2020
+ return { json: readCache.json, outcome: readCache.outcome };
2021
+ }
2022
+ const remember = (json, outcome) => {
2023
+ readCache = { at: Date.now(), home, json, outcome };
2024
+ return { json, outcome };
2025
+ };
2026
+ let state = readKeychainAccessState(home);
2027
+ if (o.retry && state.deniedAt) {
2028
+ const { deniedAt: _cleared, ...rest } = state;
2029
+ state = rest;
2030
+ writeKeychainAccessState(home, state);
2031
+ }
2032
+ if (state.deniedAt)
2033
+ return remember(null, "skipped-denied");
2034
+ if (!state.allowedAt) {
2035
+ const interactive = o.interactive ?? Boolean(process.stderr.isTTY);
2036
+ if (!interactive)
2037
+ return remember(null, "skipped-not-interactive");
2038
+ if (!state.noteShownAt) {
2039
+ (o.notify ?? ((line) => process.stderr.write(`${line}\n`)))(KEYCHAIN_FIRST_READ_NOTE);
2040
+ state = { ...state, noteShownAt: new Date().toISOString() };
2041
+ writeKeychainAccessState(home, state);
2042
+ }
2043
+ }
2044
+ const run = o.runSecurity ?? defaultRunner;
2045
+ const result = run(["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", KEYCHAIN_ACCOUNT, "-w"], state.allowedAt ? KEYCHAIN_READ_TIMEOUT_MS : KEYCHAIN_FIRST_READ_TIMEOUT_MS);
2046
+ if (result.status === 0 && !result.timedOut) {
2047
+ if (!state.allowedAt)
2048
+ writeKeychainAccessState(home, { ...state, allowedAt: new Date().toISOString() });
2049
+ return remember(decodeSecurityOutput(result.stdout), "hit");
2050
+ }
2051
+ if (result.status === SECURITY_ITEM_NOT_FOUND && !result.timedOut)
2052
+ return remember(null, "miss");
2053
+ writeKeychainAccessState(home, { ...state, deniedAt: new Date().toISOString() });
2054
+ return remember(null, "denied");
2055
+ }
2056
+ export function readKeychainTokenJson(opts = {}) {
2057
+ return readKeychainTokenJsonDetailed(opts).json;
2058
+ }
2059
+ function expiresAtMs(tokens) {
2060
+ const value = tokens.expiresAt;
2061
+ if (typeof value === "number" && Number.isFinite(value))
2062
+ return value;
2063
+ if (typeof value === "string") {
2064
+ const parsed = Date.parse(value);
2065
+ if (Number.isFinite(parsed))
2066
+ return parsed;
2067
+ }
2068
+ return Number.NEGATIVE_INFINITY;
2069
+ }
2070
+ /** Newer session by `expiresAt`; a tie keeps the Keychain value. */
2071
+ export function pickNewerSession(fromKeychain, other) {
2072
+ if (!fromKeychain)
2073
+ return other;
2074
+ if (!other)
2075
+ return fromKeychain;
2076
+ return expiresAtMs(other) > expiresAtMs(fromKeychain) ? other : fromKeychain;
2077
+ }
1702
2078
  //# sourceMappingURL=cognito-auth.js.map