@oxyhq/core 1.11.17 → 1.11.19

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.
@@ -637,16 +637,28 @@ export class KeyManager {
637
637
  /**
638
638
  * Atomically persist a key pair to secure storage with verification + backup.
639
639
  *
640
- * Write order is critical:
641
- * 1. Backup (BACKUP_PRIVATE_KEY + BACKUP_PUBLIC_KEY + BACKUP_TIMESTAMP)
642
- * 2. Primary public key
643
- * 3. Primary private key (last so a partial write leaves us in a known
644
- * "no identity yet" stateeasier to retry than a half-written one)
645
- * 4. Read back + sign/verify to confirm the storage round-trip works
640
+ * INVARIANT (the reason this method exists): at no instant during the write
641
+ * may the device be left holding ZERO recoverable copies of a healthy
642
+ * identity. This matters most on the OVERWRITE / account-switch path: if we
643
+ * are replacing identity A with B and the write fails halfway, we MUST end
644
+ * up back on A never on a half-written B, and never on nothing.
646
645
  *
647
- * If any step throws, the caller sees the error AND any partial state is
648
- * cleaned up so the device is left either fully consistent or fully empty.
649
- * It never leaves an unusable half-identity that would fool `hasIdentity()`.
646
+ * Algorithm (recoverability-preserving):
647
+ * 0. Snapshot the existing primary (privA, pubA) so we can roll back to
648
+ * EXACTLY what was there.
649
+ * 1. Write the new primary: public first, then private.
650
+ * 2. Read back + sign/verify the new primary.
651
+ * 3. ONLY after the new primary is proven durable, refresh the backup to
652
+ * the new key. The backup is NEVER touched before this point, so any
653
+ * prior identity's backup remains intact and `restoreIdentityFromBackup`
654
+ * can always recover it.
655
+ * 4. On ANY failure in steps 1–2, restore the snapshotted primary verbatim
656
+ * (or delete it if there was none), then surface the error.
657
+ *
658
+ * Earlier versions wrote the *incoming* key to the backup FIRST, which
659
+ * destroyed the previous identity's backup, and rolled back by blindly
660
+ * deleting the primary — so a failed overwrite silently switched the user
661
+ * to (or lost them into) the half-written new identity. That is fixed here.
650
662
  *
651
663
  * @internal
652
664
  */
@@ -663,23 +675,64 @@ export class KeyManager {
663
675
  const canonicalPrivate = KeyManager.canonicalPrivateKey(privateKey);
664
676
  const canonicalPublic = publicKey.toLowerCase();
665
677
 
666
- // Step 1: Backup BEFORE touching primary storage so we always have a
667
- // recoverable copy even if the device crashes mid-write. Store the
668
- // backup in canonical form too so a backup-restore cycle preserves
669
- // canonicalization.
678
+ // Step 0: Snapshot the existing primary so a failed write can be rolled
679
+ // back to EXACTLY the prior state. If the read itself fails we treat the
680
+ // prior primary as unknown and refuse to proceed overwriting blind
681
+ // would risk clobbering an identity we just couldn't see (e.g. a
682
+ // transient keychain lock).
683
+ let priorPrivate: string | null;
684
+ let priorPublic: string | null;
670
685
  try {
671
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, canonicalPrivate, {
672
- keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
673
- });
674
- await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, canonicalPublic);
675
- await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
686
+ priorPrivate = await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
687
+ priorPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
676
688
  } catch (error) {
677
- logger.error('Failed to write identity backup before primary', error, { component: 'KeyManager' });
678
- throw new IdentityPersistError('Failed to write identity backup', error);
689
+ logger.error('Failed to read existing primary before persist', error, { component: 'KeyManager' });
690
+ throw new IdentityPersistError(
691
+ 'Could not read existing identity before writing a new one; refusing to overwrite blind.',
692
+ error,
693
+ );
679
694
  }
680
695
 
681
- // Step 2 + 3: Write primary keys. Public first so that if private write
682
- // fails we are still missing the most critical bit.
696
+ // If we are replacing a DIFFERENT, currently-healthy identity, make sure
697
+ // it is recoverable from the backup slot BEFORE we overwrite the primary.
698
+ // We only do this when the existing backup does not already hold that
699
+ // identity — otherwise we would needlessly churn the keychain. This keeps
700
+ // the "always at least one recoverable copy" invariant intact across the
701
+ // window where the primary briefly holds the new key but the new backup
702
+ // has not been written yet.
703
+ const priorIsHealthyDifferent =
704
+ !!priorPrivate &&
705
+ !!priorPublic &&
706
+ priorPublic.toLowerCase() !== canonicalPublic &&
707
+ KeyManager.isValidPrivateKey(priorPrivate) &&
708
+ KeyManager.isValidPublicKey(priorPublic) &&
709
+ KeyManager.derivePublicKey(priorPrivate).toLowerCase() === priorPublic.toLowerCase();
710
+
711
+ if (priorIsHealthyDifferent && priorPrivate && priorPublic) {
712
+ let existingBackupPublic: string | null = null;
713
+ try {
714
+ existingBackupPublic = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
715
+ } catch {
716
+ existingBackupPublic = null;
717
+ }
718
+ if (existingBackupPublic?.toLowerCase() !== priorPublic.toLowerCase()) {
719
+ try {
720
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, KeyManager.canonicalPrivateKey(priorPrivate), {
721
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
722
+ });
723
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, priorPublic.toLowerCase());
724
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
725
+ } catch (error) {
726
+ logger.error('Failed to back up existing identity before overwrite', error, { component: 'KeyManager' });
727
+ throw new IdentityPersistError('Failed to back up existing identity before overwrite', error);
728
+ }
729
+ }
730
+ }
731
+
732
+ // Step 1: Write the new primary. Public first so that if the private write
733
+ // fails we are missing the most critical bit. The backup is intentionally
734
+ // NOT touched here — it still holds the previous good identity until the
735
+ // new primary is proven durable.
683
736
  try {
684
737
  await store.setItemAsync(STORAGE_KEYS.PUBLIC_KEY, canonicalPublic);
685
738
  await store.setItemAsync(STORAGE_KEYS.PRIVATE_KEY, canonicalPrivate, {
@@ -687,13 +740,11 @@ export class KeyManager {
687
740
  });
688
741
  } catch (error) {
689
742
  logger.error('Failed to write primary identity to secure store', error, { component: 'KeyManager' });
690
- // Roll back the public-key half-write so hasIdentity() doesn't lie later.
691
- try { await store.deleteItemAsync(STORAGE_KEYS.PUBLIC_KEY); } catch { /* best effort */ }
692
- try { await store.deleteItemAsync(STORAGE_KEYS.PRIVATE_KEY); } catch { /* best effort */ }
743
+ await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
693
744
  throw new IdentityPersistError('Failed to write identity to secure store', error);
694
745
  }
695
746
 
696
- // Step 4: Verify round-trip. If the store silently drops our writes
747
+ // Step 2: Verify round-trip. If the store silently drops our writes
697
748
  // (e.g., a misconfigured keychain access group), we MUST surface it
698
749
  // before declaring success — otherwise the caller will think the
699
750
  // identity was saved and discard the in-memory copy.
@@ -704,6 +755,7 @@ export class KeyManager {
704
755
  readBackPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
705
756
  } catch (error) {
706
757
  logger.error('Failed to read identity back after write', error, { component: 'KeyManager' });
758
+ await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
707
759
  throw new IdentityPersistError('Failed to verify identity after write', error);
708
760
  }
709
761
 
@@ -715,6 +767,7 @@ export class KeyManager {
715
767
  readBackPublic?.toLowerCase() !== canonicalPublic
716
768
  ) {
717
769
  logger.error('Identity round-trip mismatch after write', undefined, { component: 'KeyManager' });
770
+ await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
718
771
  throw new IdentityPersistError('Identity write was not persisted correctly (round-trip mismatch).');
719
772
  }
720
773
 
@@ -735,16 +788,72 @@ export class KeyManager {
735
788
  throw new IdentityPersistError('Sign/verify roundtrip failed for newly stored identity.');
736
789
  }
737
790
  } catch (error) {
791
+ await KeyManager._rollbackPrimary(store, priorPrivate, priorPublic);
738
792
  if (error instanceof IdentityPersistError) throw error;
739
793
  logger.error('Identity sign/verify probe failed', error, { component: 'KeyManager' });
740
794
  throw new IdentityPersistError('Stored identity failed crypto self-test', error);
741
795
  }
742
796
 
797
+ // Step 3: The new primary is durable and functional. NOW it is safe to
798
+ // refresh the backup to the new key. If this final backup write fails the
799
+ // user still has a fully working primary, and the backup still holds the
800
+ // PREVIOUS good identity — so we log and continue rather than failing the
801
+ // whole operation (failing here would be strictly worse: a working
802
+ // primary would be reported as an error to the caller).
803
+ try {
804
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY, canonicalPrivate, {
805
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
806
+ });
807
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY, canonicalPublic);
808
+ await store.setItemAsync(STORAGE_KEYS.BACKUP_TIMESTAMP, Date.now().toString());
809
+ } catch (error) {
810
+ logger.warn(
811
+ 'Primary identity persisted successfully but refreshing the backup failed; primary is usable, backup may be stale',
812
+ { component: 'KeyManager' },
813
+ error,
814
+ );
815
+ }
816
+
743
817
  // Update cache only after we are certain the identity is durable.
744
818
  KeyManager.cachedPublicKey = canonicalPublic;
745
819
  KeyManager.cachedHasIdentity = true;
746
820
  }
747
821
 
822
+ /**
823
+ * Restore the primary slot to a previously-snapshotted (privA, pubA) pair,
824
+ * or delete it entirely if there was no prior identity. Best-effort: every
825
+ * step is wrapped so a rollback failure never masks the original error the
826
+ * caller is about to throw. Invalidates the in-memory cache so the next read
827
+ * reflects whatever actually landed on disk.
828
+ *
829
+ * @internal
830
+ */
831
+ private static async _rollbackPrimary(
832
+ store: Awaited<ReturnType<typeof initSecureStore>>,
833
+ priorPrivate: string | null,
834
+ priorPublic: string | null,
835
+ ): Promise<void> {
836
+ try {
837
+ if (priorPrivate && priorPublic) {
838
+ // Restore exactly what was there before the failed write.
839
+ await store.setItemAsync(STORAGE_KEYS.PUBLIC_KEY, priorPublic, {});
840
+ await store.setItemAsync(STORAGE_KEYS.PRIVATE_KEY, priorPrivate, {
841
+ keychainAccessible: store.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
842
+ });
843
+ } else {
844
+ // There was no prior identity — leave the device empty rather than
845
+ // half-written so hasIdentity() does not lie.
846
+ try { await store.deleteItemAsync(STORAGE_KEYS.PUBLIC_KEY); } catch { /* best effort */ }
847
+ try { await store.deleteItemAsync(STORAGE_KEYS.PRIVATE_KEY); } catch { /* best effort */ }
848
+ }
849
+ } catch (rollbackError) {
850
+ logger.error('Failed to roll back primary identity after a failed write', rollbackError, { component: 'KeyManager' });
851
+ } finally {
852
+ // Whatever happened, the cached verdict is no longer trustworthy.
853
+ KeyManager.invalidateCache();
854
+ }
855
+ }
856
+
748
857
  /**
749
858
  * Generate and securely store a new key pair on the device.
750
859
  *
@@ -1122,17 +1231,23 @@ export class KeyManager {
1122
1231
  }
1123
1232
 
1124
1233
  /**
1125
- * Restore identity from backup if primary storage is corrupted.
1234
+ * Restore identity from backup if primary storage is genuinely missing or
1235
+ * corrupt.
1126
1236
  *
1127
- * SAFETY: this method will NEVER overwrite a verifying primary identity.
1128
- * If the primary passes a sign/verify probe, the backup is left untouched
1129
- * and `false` is returned this protects against a transient
1130
- * `verifyIdentityIntegrity()` blip clobbering valid keys with stale
1131
- * backup keys (e.g., from a previous account before an import).
1237
+ * SAFETY (three independent guards against silently switching accounts):
1238
+ * 1. If the primary passes a full sign/verify probe, do nothing.
1239
+ * 2. If the primary keys CANNOT BE READ (storage threw — e.g. a transient
1240
+ * keychain lock during a background launch), do nothing. We must NOT
1241
+ * treat "couldn't read" as "corrupted" and restore a possibly-stale
1242
+ * backup over an identity that is actually fine but momentarily
1243
+ * inaccessible.
1244
+ * 3. If a primary private/public key IS present but does not match the
1245
+ * backup, the backup may belong to a different identity — refuse, so we
1246
+ * never silently switch the user to another account.
1132
1247
  *
1133
- * Additionally, if the backup public key does NOT match the (still-
1134
- * present-but-failing) primary public key, we refuse to overwrite the
1135
- * backup may belong to a different identity entirely.
1248
+ * Only when the primary is provably absent (read succeeded, returned
1249
+ * null/empty) or provably corrupt (read succeeded, bytes malformed AND no
1250
+ * conflicting key material is present) do we rebuild it from the backup.
1136
1251
  */
1137
1252
  static async restoreIdentityFromBackup(): Promise<boolean> {
1138
1253
  if (isWebPlatform()) {
@@ -1141,15 +1256,38 @@ export class KeyManager {
1141
1256
  try {
1142
1257
  const store = await initSecureStore();
1143
1258
 
1144
- // First: if the primary still works, do nothing. Returning true here
1145
- // would be misleading; returning false (no restore needed) is the
1146
- // honest answer.
1147
- const primaryOk = await KeyManager.verifyIdentityIntegrity();
1148
- if (primaryOk) {
1259
+ // Read the primary DIRECTLY (not via the error-swallowing getters) so
1260
+ // we can distinguish a transient read failure from a genuinely absent
1261
+ // key. A thrown read here means the keychain is locked/unavailable —
1262
+ // bail out and let a later call retry rather than risk restoring over a
1263
+ // healthy-but-locked identity.
1264
+ let primaryPrivate: string | null;
1265
+ let primaryPublic: string | null;
1266
+ try {
1267
+ primaryPrivate = await store.getItemAsync(STORAGE_KEYS.PRIVATE_KEY);
1268
+ primaryPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY);
1269
+ } catch (error) {
1270
+ logger.warn(
1271
+ 'restoreIdentityFromBackup: could not read primary (transient?). Refusing to restore.',
1272
+ { component: 'KeyManager' },
1273
+ error,
1274
+ );
1149
1275
  return false;
1150
1276
  }
1151
1277
 
1152
- // Check if backup exists
1278
+ // If the primary reads back as a complete, self-consistent identity, it
1279
+ // is healthy — nothing to restore. (Guard 1.)
1280
+ if (primaryPrivate && primaryPublic) {
1281
+ if (
1282
+ KeyManager.isValidPrivateKey(primaryPrivate) &&
1283
+ KeyManager.isValidPublicKey(primaryPublic) &&
1284
+ KeyManager.derivePublicKey(primaryPrivate).toLowerCase() === primaryPublic.toLowerCase()
1285
+ ) {
1286
+ return false;
1287
+ }
1288
+ }
1289
+
1290
+ // Load + validate the backup.
1153
1291
  const backupPrivateKey = await store.getItemAsync(STORAGE_KEYS.BACKUP_PRIVATE_KEY);
1154
1292
  const backupPublicKey = await store.getItemAsync(STORAGE_KEYS.BACKUP_PUBLIC_KEY);
1155
1293
 
@@ -1157,7 +1295,6 @@ export class KeyManager {
1157
1295
  return false; // No backup available
1158
1296
  }
1159
1297
 
1160
- // Verify backup integrity
1161
1298
  if (!KeyManager.isValidPrivateKey(backupPrivateKey) || !KeyManager.isValidPublicKey(backupPublicKey)) {
1162
1299
  logger.warn('Backup identity is malformed; refusing to restore', { component: 'KeyManager' });
1163
1300
  return false;
@@ -1172,17 +1309,30 @@ export class KeyManager {
1172
1309
  return false;
1173
1310
  }
1174
1311
 
1175
- // CRITICAL: if there is still a (broken) primary public key present
1176
- // that does NOT match the backup, the backup may be from a completely
1177
- // different identity. Better to surface a corrupted state than
1178
- // silently switch the user to a different account.
1179
- const currentPrimaryPublic = await store.getItemAsync(STORAGE_KEYS.PUBLIC_KEY).catch(() => null);
1312
+ // Guard 3: if ANY primary key material is still present and identifies a
1313
+ // DIFFERENT identity than the backup, refuse — the backup may be from a
1314
+ // completely different account and restoring it would silently switch
1315
+ // the user. We check the private key too (not just the public): a
1316
+ // present private key that derives to a non-backup public means a real,
1317
+ // different identity is sitting in the primary slot.
1318
+ if (
1319
+ primaryPublic &&
1320
+ primaryPublic.toLowerCase() !== backupPublicKey.toLowerCase()
1321
+ ) {
1322
+ logger.error(
1323
+ 'Primary public key is present, corrupt-or-mismatched, AND differs from the backup. Refusing to restore to avoid switching accounts.',
1324
+ undefined,
1325
+ { component: 'KeyManager' },
1326
+ );
1327
+ return false;
1328
+ }
1180
1329
  if (
1181
- currentPrimaryPublic &&
1182
- currentPrimaryPublic.toLowerCase() !== backupPublicKey.toLowerCase()
1330
+ primaryPrivate &&
1331
+ KeyManager.isValidPrivateKey(primaryPrivate) &&
1332
+ KeyManager.derivePublicKey(primaryPrivate).toLowerCase() !== backupPublicKey.toLowerCase()
1183
1333
  ) {
1184
1334
  logger.error(
1185
- 'Primary identity is corrupted AND does not match the backup. Refusing to restore to avoid switching accounts.',
1335
+ 'Primary private key identifies a DIFFERENT identity than the backup. Refusing to restore to avoid switching accounts.',
1186
1336
  undefined,
1187
1337
  { component: 'KeyManager' },
1188
1338
  );
@@ -17,6 +17,88 @@ export interface FedCMConfig {
17
17
  clientId?: string;
18
18
  }
19
19
 
20
+ /**
21
+ * FedCM request mode values.
22
+ *
23
+ * The W3C FedCM spec renamed the `IdentityCredentialRequestOptions.mode` enum:
24
+ * `'widget'` → `'passive'` and `'button'` → `'active'`. Modern Chrome only
25
+ * accepts `'active'`/`'passive'` and throws a synchronous `TypeError` for the
26
+ * legacy values, while Chrome 125–131 only understands `'button'`/`'widget'`.
27
+ * Callers should use the modern values; the legacy values are accepted for
28
+ * convenience and normalised internally.
29
+ */
30
+ export type FedCMRequestMode = 'active' | 'passive' | 'button' | 'widget';
31
+
32
+ // Modern (W3C spec) → legacy (Chrome 125–131) mode value mapping. Used to
33
+ // retry a credential request when an older browser rejects the modern enum.
34
+ const MODERN_TO_LEGACY_MODE: Record<'active' | 'passive', 'button' | 'widget'> = {
35
+ active: 'button',
36
+ passive: 'widget',
37
+ };
38
+
39
+ // Legacy → modern mapping so callers may pass either spelling.
40
+ const LEGACY_TO_MODERN_MODE: Record<'button' | 'widget', 'active' | 'passive'> = {
41
+ button: 'active',
42
+ widget: 'passive',
43
+ };
44
+
45
+ /**
46
+ * Normalise any accepted mode value to the modern W3C spelling
47
+ * (`'active'`/`'passive'`), which is what is sent to the browser first.
48
+ */
49
+ function toModernMode(mode: FedCMRequestMode): 'active' | 'passive' {
50
+ return mode === 'button' || mode === 'widget' ? LEGACY_TO_MODERN_MODE[mode] : mode;
51
+ }
52
+
53
+ /**
54
+ * Detect the synchronous `TypeError` a pre-spec browser throws when it does not
55
+ * recognise a modern `mode` enum value (e.g. Chrome 125–131 rejecting
56
+ * `'active'`/`'passive'`). Such a browser only understands the legacy
57
+ * `'button'`/`'widget'` values, so the caller can retry with those.
58
+ */
59
+ function isUnknownModeEnumError(error: unknown): boolean {
60
+ if (!(error instanceof TypeError)) return false;
61
+ const message = error.message.toLowerCase();
62
+ return (
63
+ message.includes('identitycredentialrequestoptionsmode') ||
64
+ ((message.includes('active') || message.includes('passive')) &&
65
+ (message.includes('enum') || message.includes('not a valid')))
66
+ );
67
+ }
68
+
69
+ // Minimal structural types for the FedCM `navigator.credentials.get` surface.
70
+ // The DOM lib does not ship these in every TypeScript version we build against,
71
+ // so we model only the fields this mixin reads/writes. This lets the FedCM code
72
+ // stay free of `any` without depending on lib-dom FedCM typings.
73
+ interface FedCMProviderRequest {
74
+ configURL: string;
75
+ clientId: string;
76
+ nonce: string;
77
+ params?: { nonce: string };
78
+ loginHint?: string;
79
+ }
80
+
81
+ interface FedCMIdentityRequest {
82
+ providers: FedCMProviderRequest[];
83
+ mode?: FedCMRequestMode;
84
+ }
85
+
86
+ interface FedCMCredentialRequest {
87
+ identity: FedCMIdentityRequest;
88
+ mediation: 'silent' | 'optional' | 'required';
89
+ signal: AbortSignal;
90
+ }
91
+
92
+ interface FedCMIdentityCredential {
93
+ type?: string;
94
+ token?: string;
95
+ isAutoSelected?: boolean;
96
+ }
97
+
98
+ interface FedCMCredentialsContainer {
99
+ get(options: FedCMCredentialRequest): Promise<FedCMIdentityCredential | null>;
100
+ }
101
+
20
102
  const FEDCM_LOGIN_HINT_KEY = 'oxy_fedcm_login_hint';
21
103
 
22
104
  // Global lock to prevent concurrent FedCM requests
@@ -109,7 +191,10 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
109
191
  }
110
192
 
111
193
  try {
112
- const nonce = options.nonce || this.generateNonce();
194
+ // Prefer a server-minted, origin-bound nonce so the downstream
195
+ // `/fedcm/exchange` can validate it. A caller-supplied nonce is
196
+ // respected as-is for advanced use cases.
197
+ const nonce = options.nonce || (await this.getFedcmNonce());
113
198
  const clientId = this.getClientId();
114
199
 
115
200
  // Use provided loginHint, or fall back to stored last-used account ID
@@ -117,15 +202,17 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
117
202
 
118
203
  debug.log('Interactive sign-in: Requesting credential for', clientId, loginHint ? `(hint: ${loginHint})` : '');
119
204
 
120
- // Request credential from browser's native identity flow
121
- // mode: 'button' signals this is a user-gesture-initiated flow (Chrome 125+)
205
+ // Request credential from browser's native identity flow.
206
+ // mode: 'active' signals this is a user-gesture-initiated (button) flow.
207
+ // 'active' is the current W3C spec value; requestIdentityCredential
208
+ // transparently retries with the legacy 'button' value for Chrome 125–131.
122
209
  const credential = await this.requestIdentityCredential({
123
210
  configURL: this.resolveFedcmConfigUrl(),
124
211
  clientId,
125
212
  nonce,
126
213
  context: options.context,
127
214
  loginHint,
128
- mode: 'button',
215
+ mode: 'active',
129
216
  });
130
217
 
131
218
  if (!credential || !credential.token) {
@@ -219,7 +306,9 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
219
306
  const loginHint = this.getStoredLoginHint();
220
307
 
221
308
  try {
222
- const nonce = this.generateNonce();
309
+ // Server-minted, origin-bound nonce required for `/fedcm/exchange`
310
+ // to accept the resulting ID token (anti-replay binding).
311
+ const nonce = await this.getFedcmNonce();
223
312
  debug.log('Silent SSO: Attempting silent mediation...', loginHint ? `(hint: ${loginHint})` : '');
224
313
 
225
314
  credential = await this.requestIdentityCredential({
@@ -317,7 +406,14 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
317
406
  context?: string;
318
407
  loginHint?: string;
319
408
  mediation?: 'silent' | 'optional' | 'required';
320
- mode?: 'button' | 'widget';
409
+ /**
410
+ * FedCM request mode. The W3C spec values are `'active'` (user-gesture
411
+ * button flow) and `'passive'` (browser-initiated widget flow). Chrome
412
+ * 125–131 used the legacy names `'button'`/`'widget'`; those are accepted
413
+ * here and mapped to the modern values, with an automatic legacy retry if
414
+ * the running browser only understands the old enum.
415
+ */
416
+ mode?: FedCMRequestMode;
321
417
  }): Promise<{ token: string; isAutoSelected: boolean } | null> {
322
418
  const requestedMediation = options.mediation || 'optional';
323
419
  const isInteractive = requestedMediation !== 'silent';
@@ -362,31 +458,58 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
362
458
  controller.abort();
363
459
  }, timeoutMs);
364
460
 
461
+ // Normalise the caller's mode to the modern W3C value first. A modern
462
+ // browser accepts it; an older one (Chrome 125–131) rejects it with a
463
+ // synchronous TypeError, in which case we retry with the legacy value.
464
+ const modernMode = options.mode ? toModernMode(options.mode) : undefined;
465
+
466
+ // Build the identity request for a specific mode value. The `mode` field
467
+ // lives on the `identity` object (sibling of `providers`), separate from
468
+ // the top-level `mediation` field.
469
+ const buildCredentialOptions = (modeValue: FedCMRequestMode | undefined): FedCMCredentialRequest => ({
470
+ identity: {
471
+ providers: [
472
+ {
473
+ configURL: options.configURL,
474
+ clientId: options.clientId,
475
+ // Older browsers read `nonce` at the top level; Chrome 145+
476
+ // expects it inside `params`. Send both for full coverage.
477
+ nonce: options.nonce,
478
+ params: {
479
+ nonce: options.nonce,
480
+ },
481
+ ...(options.loginHint && { loginHint: options.loginHint }),
482
+ },
483
+ ],
484
+ ...(modeValue && { mode: modeValue }),
485
+ },
486
+ mediation: requestedMediation,
487
+ signal: controller.signal,
488
+ });
489
+
490
+ // The DOM lib's `CredentialsContainer` does not declare the FedCM `identity`
491
+ // request in every TypeScript version we build against. Re-type through the
492
+ // minimal structural interface above (not `any`) to keep this typed.
493
+ const credentials = navigator.credentials as unknown as FedCMCredentialsContainer;
494
+
365
495
  fedCMRequestPromise = (async () => {
366
496
  try {
367
- debug.log('Calling navigator.credentials.get with mediation:', requestedMediation);
368
- // Type assertion needed as FedCM types may not be in all TypeScript versions
369
- const credentialOptions: any = {
370
- identity: {
371
- providers: [
372
- {
373
- configURL: options.configURL,
374
- clientId: options.clientId,
375
- // Older browsers read `nonce` at the top level; Chrome 145+
376
- // expects it inside `params`. Send both for full coverage.
377
- nonce: options.nonce,
378
- params: {
379
- nonce: options.nonce,
380
- },
381
- ...(options.loginHint && { loginHint: options.loginHint }),
382
- },
383
- ],
384
- ...(options.mode && { mode: options.mode }),
385
- },
386
- mediation: requestedMediation,
387
- signal: controller.signal,
388
- };
389
- const credential = (await (navigator.credentials as any).get(credentialOptions)) as any;
497
+ debug.log('Calling navigator.credentials.get with mediation:', requestedMediation, modernMode ? `mode: ${modernMode}` : '');
498
+ let credential: FedCMIdentityCredential | null;
499
+ try {
500
+ credential = await credentials.get(buildCredentialOptions(modernMode));
501
+ } catch (modeError) {
502
+ // Chrome 125–131 only knows the legacy 'button'/'widget' enum and
503
+ // throws a synchronous TypeError for the modern 'active'/'passive'
504
+ // values. Retry once with the legacy value so older browsers work.
505
+ if (modernMode && isUnknownModeEnumError(modeError)) {
506
+ const legacyMode = MODERN_TO_LEGACY_MODE[modernMode];
507
+ debug.log(`Browser rejected modern mode '${modernMode}'; retrying with legacy mode '${legacyMode}'`);
508
+ credential = await credentials.get(buildCredentialOptions(legacyMode));
509
+ } else {
510
+ throw modeError;
511
+ }
512
+ }
390
513
 
391
514
  debug.log('navigator.credentials.get returned:', {
392
515
  hasCredential: !!credential,
@@ -394,7 +517,7 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
394
517
  hasToken: !!credential?.token,
395
518
  });
396
519
 
397
- if (!credential || credential.type !== 'identity') {
520
+ if (!credential || credential.type !== 'identity' || !credential.token) {
398
521
  debug.log('No valid identity credential returned');
399
522
  return null;
400
523
  }
@@ -494,7 +617,14 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
494
617
  }
495
618
 
496
619
  /**
497
- * Generate a cryptographically secure nonce for FedCM
620
+ * Generate a cryptographically secure local nonce for FedCM.
621
+ *
622
+ * NOTE: this is a *local* fallback only. The server-side `/fedcm/exchange`
623
+ * endpoint requires the nonce embedded in the ID token to have been minted
624
+ * by `POST /fedcm/nonce` (see {@link mintServerNonce}) and bound to this
625
+ * origin. A purely local nonce will be rejected with `invalid_nonce`. Use
626
+ * {@link getFedcmNonce}, which prefers a server-minted nonce and only falls
627
+ * back to this generator when the mint endpoint is unreachable.
498
628
  *
499
629
  * @private
500
630
  */
@@ -510,6 +640,58 @@ export function OxyServicesFedCMMixin<T extends typeof OxyServicesBase>(Base: T)
510
640
  throw new Error('No secure random source available for nonce generation');
511
641
  }
512
642
 
643
+ /**
644
+ * Mint a single-use, origin-bound nonce from the Oxy API.
645
+ *
646
+ * The FedCM ID token issued by the IdP embeds this nonce as the `nonce`
647
+ * claim. When the consuming app calls `POST /fedcm/exchange`, the API burns
648
+ * the nonce (atomic `usedAt` transition) and verifies it was minted for the
649
+ * same origin as the token `aud`. This is the anti-replay binding required
650
+ * by the API's H9 hardening — without a server-minted nonce the exchange
651
+ * always fails.
652
+ *
653
+ * The browser attaches the `Origin` header automatically on this
654
+ * cross-origin request, so the API binds the nonce to the calling app's
655
+ * origin (which also becomes the FedCM `clientId`/token `aud`).
656
+ *
657
+ * @private
658
+ */
659
+ public async mintServerNonce(): Promise<string> {
660
+ const result = await this.makeRequest<{ nonce: string; expiresAt: string }>(
661
+ 'POST',
662
+ '/fedcm/nonce',
663
+ {},
664
+ { cache: false }
665
+ );
666
+ if (!result?.nonce) {
667
+ throw new OxyAuthenticationError('FedCM nonce endpoint returned no nonce');
668
+ }
669
+ return result.nonce;
670
+ }
671
+
672
+ /**
673
+ * Resolve the nonce to use for a FedCM credential request.
674
+ *
675
+ * Prefers a server-minted, origin-bound nonce (required for the token
676
+ * exchange to succeed). If the mint endpoint is unreachable we fall back to
677
+ * a locally generated nonce so the browser flow can still proceed; the
678
+ * exchange may then fail server-side, but that is strictly better than
679
+ * throwing before the browser ever shows its UI.
680
+ *
681
+ * @private
682
+ */
683
+ public async getFedcmNonce(): Promise<string> {
684
+ try {
685
+ return await this.mintServerNonce();
686
+ } catch (error) {
687
+ debug.warn(
688
+ 'Could not mint server nonce, falling back to local nonce:',
689
+ error instanceof Error ? error.message : String(error)
690
+ );
691
+ return this.generateNonce();
692
+ }
693
+ }
694
+
513
695
  /**
514
696
  * Get the client ID for this origin
515
697
  *