@atol-sh/js 0.4.2 → 0.5.0

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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { jwtVerify, createRemoteJWKSet, calculateJwkThumbprint, errors } from 'jose';
1
+ import { jwtVerify, importJWK, createRemoteJWKSet, calculateJwkThumbprint, errors } from 'jose';
2
2
  import { InMemoryWebStorage, WebStorageStateStore, UserManager, OidcClient, User } from 'oidc-client-ts';
3
3
 
4
4
  // src/client/browser-auth-diagnostics.ts
@@ -37,138 +37,6 @@ function base64ToBytes(b64) {
37
37
  }
38
38
  return bytes;
39
39
  }
40
- var managerKeys = /* @__PURE__ */ new WeakMap();
41
- var P256_COORDINATE = /^[A-Za-z0-9_-]{43}$/;
42
- function canonicalPublicJWK(exported) {
43
- if (exported.kty !== "EC" || exported.crv !== "P-256" || typeof exported.x !== "string" || !P256_COORDINATE.test(exported.x) || typeof exported.y !== "string" || !P256_COORDINATE.test(exported.y) || typeof exported.d === "string") {
44
- throw new Error("DPoP: exported public key is invalid");
45
- }
46
- return {
47
- crv: "P-256",
48
- kty: "EC",
49
- x: exported.x,
50
- y: exported.y
51
- };
52
- }
53
- function validP256KeyPair(keyPair) {
54
- const privateAlgorithm = keyPair.privateKey.algorithm;
55
- const publicAlgorithm = keyPair.publicKey.algorithm;
56
- return keyPair.privateKey.type === "private" && keyPair.privateKey.extractable === false && keyPair.privateKey.usages.length === 1 && keyPair.privateKey.usages[0] === "sign" && privateAlgorithm.name === "ECDSA" && privateAlgorithm.namedCurve === "P-256" && keyPair.publicKey.type === "public" && publicAlgorithm.name === "ECDSA" && publicAlgorithm.namedCurve === "P-256";
57
- }
58
- function restoreDPoPKeyManager(keyPair) {
59
- if (!validP256KeyPair(keyPair)) {
60
- throw new Error("DPoP: stored authorization key is invalid");
61
- }
62
- let cachedJWK = null;
63
- let cachedThumbprint = null;
64
- async function pubJWK() {
65
- if (!cachedJWK) {
66
- cachedJWK = canonicalPublicJWK(
67
- await crypto.subtle.exportKey(
68
- "jwk",
69
- keyPair.publicKey
70
- )
71
- );
72
- }
73
- return { ...cachedJWK };
74
- }
75
- const manager = {
76
- async publicJWK() {
77
- return pubJWK();
78
- },
79
- async thumbprint() {
80
- if (!cachedThumbprint) {
81
- cachedThumbprint = await calculateJwkThumbprint(
82
- await pubJWK(),
83
- "sha256"
84
- );
85
- }
86
- return cachedThumbprint;
87
- },
88
- async signProof(method, url, options) {
89
- const jwk = await pubJWK();
90
- const header = {
91
- typ: "dpop+jwt",
92
- alg: "ES256",
93
- jwk
94
- };
95
- const payload = {
96
- jti: newJTI(),
97
- htm: method.toUpperCase(),
98
- htu: canonicalizeURL(url),
99
- iat: Math.floor(Date.now() / 1e3)
100
- };
101
- if (options?.accessToken) {
102
- payload.ath = await accessTokenHash(options.accessToken);
103
- }
104
- if (options?.nonce) {
105
- payload.nonce = options.nonce;
106
- }
107
- const headerB64 = stringToBase64Url(JSON.stringify(header));
108
- const payloadB64 = stringToBase64Url(JSON.stringify(payload));
109
- const signingInput = `${headerB64}.${payloadB64}`;
110
- const sigRaw = await crypto.subtle.sign(
111
- { name: "ECDSA", hash: "SHA-256" },
112
- keyPair.privateKey,
113
- new TextEncoder().encode(signingInput)
114
- );
115
- const sigB64 = bytesToBase64Url(new Uint8Array(sigRaw));
116
- return `${signingInput}.${sigB64}`;
117
- }
118
- };
119
- managerKeys.set(manager, keyPair);
120
- return manager;
121
- }
122
- function dpopKeyPair(manager) {
123
- const keyPair = managerKeys.get(manager);
124
- if (!keyPair) {
125
- throw new Error("DPoP: key manager was not created by this SDK");
126
- }
127
- return keyPair;
128
- }
129
- async function createDPoPKeyManager() {
130
- if (typeof crypto === "undefined" || typeof crypto.subtle === "undefined") {
131
- return null;
132
- }
133
- let keyPair;
134
- try {
135
- keyPair = await crypto.subtle.generateKey(
136
- { name: "ECDSA", namedCurve: "P-256" },
137
- false,
138
- // non-exportable
139
- ["sign"]
140
- );
141
- } catch {
142
- return null;
143
- }
144
- return restoreDPoPKeyManager(keyPair);
145
- }
146
- function canonicalizeURL(raw) {
147
- let u;
148
- try {
149
- u = new URL(raw);
150
- } catch {
151
- throw new Error(`DPoP: cannot canonicalize htu, invalid URL: ${raw}`);
152
- }
153
- u.search = "";
154
- u.hash = "";
155
- return u.toString();
156
- }
157
- async function accessTokenHash(accessToken) {
158
- const digest = await crypto.subtle.digest(
159
- "SHA-256",
160
- new TextEncoder().encode(accessToken)
161
- );
162
- return bytesToBase64Url(new Uint8Array(digest));
163
- }
164
- function newJTI() {
165
- if (typeof crypto.randomUUID === "function") {
166
- return crypto.randomUUID();
167
- }
168
- const bytes = new Uint8Array(16);
169
- crypto.getRandomValues(bytes);
170
- return bytesToBase64Url(bytes);
171
- }
172
40
 
173
41
  // src/oidc/credential-generation.ts
174
42
  var STORAGE_VERSION = 1;
@@ -421,8 +289,8 @@ var RESPONSE_VAULT_DEFAULT_EXECUTION_LEASE_MS = 30 * 1e3;
421
289
  var RESPONSE_VAULT_MAX_EXECUTION_LEASE_MS = 5 * 60 * 1e3;
422
290
  var RESPONSE_VAULT_EXECUTION_LOCK_WAIT_MS = 5 * 1e3;
423
291
  var RESPONSE_VAULT_CANONICAL_OPAQUE = /^[A-Za-z0-9_-]{43}$/;
424
- var RESPONSE_VAULT_TERMINAL_PROOF_BYTES = 58;
425
- var RESPONSE_VAULT_TERMINAL_PROOF_LENGTH = 78;
292
+ var RESPONSE_VAULT_TERMINAL_PROOF_BYTES = 74;
293
+ var RESPONSE_VAULT_TERMINAL_PROOF_LENGTH = 99;
426
294
  var RESPONSE_VAULT_REQUEST_URI_PREFIX = "urn:ietf:params:oauth:request_uri:";
427
295
  var RESPONSE_VAULT_TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
428
296
  "invalid_request",
@@ -698,6 +566,181 @@ var ResponseVaultExecutionBusyError = class extends ResponseVaultAuthorizationBu
698
566
  this.name = "ResponseVaultExecutionBusyError";
699
567
  }
700
568
  };
569
+ var ML_DSA_87 = "ML-DSA-87";
570
+ async function assertMLDSA87VerificationSupport() {
571
+ if (typeof globalThis.crypto?.subtle?.verify !== "function") {
572
+ throw new Error("WebCrypto ML-DSA-87 verification is unavailable");
573
+ }
574
+ try {
575
+ await importJWK(
576
+ { kty: "AKP", alg: ML_DSA_87, pub: "A".repeat(3456), key_ops: ["verify"] },
577
+ ML_DSA_87
578
+ );
579
+ } catch {
580
+ throw new Error("WebCrypto ML-DSA-87 verification is unavailable");
581
+ }
582
+ }
583
+ var managerKeys = /* @__PURE__ */ new WeakMap();
584
+ var MAX_DPOP_PROOF_BYTES = 24 << 10;
585
+ var P256_COORDINATE = /^[A-Za-z0-9_-]{43}$/;
586
+ var ML_DSA_87_PUBLIC_KEY = /^[A-Za-z0-9_-]{3456}$/;
587
+ function canonicalPublicJWK(exported, algorithm) {
588
+ if (algorithm === ML_DSA_87) {
589
+ if (exported.kty !== "AKP" || exported.alg !== algorithm || typeof exported.pub !== "string" || exported.pub.length !== 3456 || !ML_DSA_87_PUBLIC_KEY.test(exported.pub) || "priv" in exported) {
590
+ throw new Error("DPoP: exported ML-DSA-87 public key is invalid");
591
+ }
592
+ return { kty: "AKP", alg: algorithm, pub: exported.pub };
593
+ }
594
+ if (exported.kty !== "EC" || exported.crv !== "P-256" || typeof exported.x !== "string" || !P256_COORDINATE.test(exported.x) || typeof exported.y !== "string" || !P256_COORDINATE.test(exported.y) || typeof exported.d === "string") {
595
+ throw new Error("DPoP: exported public key is invalid");
596
+ }
597
+ return {
598
+ crv: "P-256",
599
+ kty: "EC",
600
+ x: exported.x,
601
+ y: exported.y
602
+ };
603
+ }
604
+ function proofAlgorithm(keyPair) {
605
+ const { publicKey, privateKey } = keyPair;
606
+ if (privateKey.type !== "private" || privateKey.extractable !== false || privateKey.usages.length !== 1 || privateKey.usages[0] !== "sign" || publicKey.type !== "public") {
607
+ return null;
608
+ }
609
+ const privateAlgorithm = privateKey.algorithm;
610
+ const publicAlgorithm = publicKey.algorithm;
611
+ if (privateAlgorithm.name === ML_DSA_87 && publicAlgorithm.name === ML_DSA_87) {
612
+ return ML_DSA_87;
613
+ }
614
+ if (privateAlgorithm.name === "ECDSA" && privateAlgorithm.namedCurve === "P-256" && publicAlgorithm.name === "ECDSA" && publicAlgorithm.namedCurve === "P-256") {
615
+ return "ES256";
616
+ }
617
+ return null;
618
+ }
619
+ function restoreDPoPKeyManager(keyPair) {
620
+ const restoredAlgorithm = proofAlgorithm(keyPair);
621
+ if (!restoredAlgorithm) {
622
+ throw new Error("DPoP: stored authorization key is invalid");
623
+ }
624
+ const algorithm = restoredAlgorithm;
625
+ let cachedJWK = null;
626
+ let cachedThumbprint = null;
627
+ async function pubJWK() {
628
+ if (!cachedJWK) {
629
+ cachedJWK = canonicalPublicJWK(
630
+ await crypto.subtle.exportKey("jwk", keyPair.publicKey),
631
+ algorithm
632
+ );
633
+ }
634
+ return { ...cachedJWK };
635
+ }
636
+ const manager = {
637
+ async publicJWK() {
638
+ return pubJWK();
639
+ },
640
+ async thumbprint() {
641
+ if (!cachedThumbprint) {
642
+ cachedThumbprint = await calculateJwkThumbprint(
643
+ await pubJWK(),
644
+ "sha256"
645
+ );
646
+ }
647
+ return cachedThumbprint;
648
+ },
649
+ async signProof(method, url, options) {
650
+ const jwk = await pubJWK();
651
+ const header = {
652
+ typ: "dpop+jwt",
653
+ alg: algorithm,
654
+ jwk
655
+ };
656
+ const payload = {
657
+ jti: newJTI(),
658
+ htm: method.toUpperCase(),
659
+ htu: canonicalizeURL(url),
660
+ iat: Math.floor(Date.now() / 1e3)
661
+ };
662
+ if (options?.accessToken) {
663
+ payload.ath = await accessTokenHash(options.accessToken);
664
+ }
665
+ if (options?.nonce) {
666
+ payload.nonce = options.nonce;
667
+ }
668
+ const headerB64 = stringToBase64Url(JSON.stringify(header));
669
+ const payloadB64 = stringToBase64Url(JSON.stringify(payload));
670
+ const signingInput = `${headerB64}.${payloadB64}`;
671
+ const sigRaw = await crypto.subtle.sign(
672
+ algorithm === "ES256" ? { name: "ECDSA", hash: "SHA-256" } : algorithm,
673
+ keyPair.privateKey,
674
+ new TextEncoder().encode(signingInput)
675
+ );
676
+ const sigB64 = bytesToBase64Url(new Uint8Array(sigRaw));
677
+ const proof = `${signingInput}.${sigB64}`;
678
+ if (proof.length > MAX_DPOP_PROOF_BYTES) {
679
+ throw new Error("DPoP: proof exceeds size limit");
680
+ }
681
+ return proof;
682
+ }
683
+ };
684
+ managerKeys.set(manager, keyPair);
685
+ return manager;
686
+ }
687
+ function dpopKeyPair(manager) {
688
+ const keyPair = managerKeys.get(manager);
689
+ if (!keyPair) {
690
+ throw new Error("DPoP: key manager was not created by this SDK");
691
+ }
692
+ return keyPair;
693
+ }
694
+ function assertMLDSA87DPoPKey(keyPair) {
695
+ if (!keyPair || proofAlgorithm(keyPair) !== ML_DSA_87) {
696
+ throw new Error("DPoP: ML-DSA-87 is required for the authorization key");
697
+ }
698
+ }
699
+ async function createDPoPKeyManager(algorithm = ML_DSA_87) {
700
+ if (typeof crypto === "undefined" || typeof crypto.subtle === "undefined") {
701
+ return null;
702
+ }
703
+ let keyPair;
704
+ try {
705
+ keyPair = algorithm === ML_DSA_87 ? await crypto.subtle.generateKey(algorithm, false, ["sign", "verify"]) : await crypto.subtle.generateKey(
706
+ { name: "ECDSA", namedCurve: "P-256" },
707
+ false,
708
+ ["sign"]
709
+ );
710
+ } catch {
711
+ return null;
712
+ }
713
+ if (!("privateKey" in keyPair) || proofAlgorithm(keyPair) !== algorithm) {
714
+ throw new Error("DPoP: WebCrypto returned an unexpected proof key");
715
+ }
716
+ return restoreDPoPKeyManager(keyPair);
717
+ }
718
+ function canonicalizeURL(raw) {
719
+ let u;
720
+ try {
721
+ u = new URL(raw);
722
+ } catch {
723
+ throw new Error(`DPoP: cannot canonicalize htu, invalid URL: ${raw}`);
724
+ }
725
+ u.search = "";
726
+ u.hash = "";
727
+ return u.toString();
728
+ }
729
+ async function accessTokenHash(accessToken) {
730
+ const digest = await crypto.subtle.digest(
731
+ "SHA-256",
732
+ new TextEncoder().encode(accessToken)
733
+ );
734
+ return bytesToBase64Url(new Uint8Array(digest));
735
+ }
736
+ function newJTI() {
737
+ if (typeof crypto.randomUUID === "function") {
738
+ return crypto.randomUUID();
739
+ }
740
+ const bytes = new Uint8Array(16);
741
+ crypto.getRandomValues(bytes);
742
+ return bytesToBase64Url(bytes);
743
+ }
701
744
 
702
745
  // src/oidc/response-vault-storage-validation.ts
703
746
  function randomOpaque() {
@@ -4421,7 +4464,7 @@ function bootstrapAttemptChallenge(envelope, requestStartedAt) {
4421
4464
  );
4422
4465
  try {
4423
4466
  const raw = base64ToBytes(capability);
4424
- if (bytesToBase64Url(raw) !== capability || raw[0] !== 1 || raw[1] !== 3) {
4467
+ if (bytesToBase64Url(raw) !== capability || raw[0] !== 2 || raw[1] !== 3) {
4425
4468
  throw new Error();
4426
4469
  }
4427
4470
  let proofDeadline = 0n;
@@ -4631,6 +4674,11 @@ var ResponseVaultContext = class {
4631
4674
  throw new Error("response vault: authorization authority was superseded");
4632
4675
  }
4633
4676
  }
4677
+ assertActiveProofKey(authorization) {
4678
+ if (this.config.dpopAlgorithm !== "ES256") {
4679
+ assertMLDSA87DPoPKey(dpopKeyPair(authorization.dpopKey));
4680
+ }
4681
+ }
4634
4682
  activeReference() {
4635
4683
  const value = this.storage().getItem(this.pointerKey);
4636
4684
  if (value === null) return null;
@@ -5654,6 +5702,7 @@ var ResponseVaultCustodyLayer = class extends ResponseVaultRejection {
5654
5702
  if (cancellation.reference.id === activeReferenceId) continue;
5655
5703
  const owned = cancellation.binding.issuer === this.config.issuer && cancellation.binding.clientId === this.config.clientId && cancellation.binding.redirectUri === this.config.redirectUri && cancellation.binding.audience === this.config.audience && cancellation.binding.scope === this.config.scope && cancellation.credentialGeneration.tabOwner === currentGeneration.tabOwner;
5656
5704
  if (!owned) continue;
5705
+ if (cancellation.expiresAt > Date.now()) continue;
5657
5706
  try {
5658
5707
  await this.probePublishedTerminal(cancellation);
5659
5708
  } catch (error) {
@@ -5844,6 +5893,11 @@ var ResponseVaultCustodyLayer = class extends ResponseVaultRejection {
5844
5893
  if (abandonedCleanupError !== void 0) {
5845
5894
  throw new ResponseVaultCleanupPendingError(void 0);
5846
5895
  }
5896
+ try {
5897
+ this.assertActiveProofKey(authorization);
5898
+ } catch (error) {
5899
+ failAfterCleanup(error);
5900
+ }
5847
5901
  this.setActive(authorization.reference);
5848
5902
  return authorization;
5849
5903
  }
@@ -6510,7 +6564,8 @@ function userFromTokenResponse(tokens) {
6510
6564
  var ORDINARY_AUTHORIZATION_DB_NAME = "atol-sdk-browser-auth";
6511
6565
  var ORDINARY_AUTHORIZATION_DB_VERSION = 2;
6512
6566
  var ORDINARY_AUTHORIZATION_STORE = "ordinary-authorizations";
6513
- var ORDINARY_AUTHORIZATION_RECORD_VERSION = 2;
6567
+ var HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION = 2;
6568
+ var ORDINARY_AUTHORIZATION_RECORD_VERSION = 3;
6514
6569
  var ORDINARY_AUTHORIZATION_POINTER_VERSION = 1;
6515
6570
  var ORDINARY_AUTHORIZATION_PROTOCOL_VERSION = 2;
6516
6571
  var AUTHORIZATION_CODE_LIFETIME_SECONDS = 600;
@@ -6521,12 +6576,13 @@ var CALLBACK_CLAIM_LIFETIME_MS = 2 * 6e4;
6521
6576
  var CALLBACK_EXCHANGE_TIMEOUT_MS = 3e4;
6522
6577
  var MAX_PAR_RESPONSE_BYTES = 16 * 1024;
6523
6578
  var MAX_SETTLEMENT_RESPONSE_BYTES = 1024;
6524
- var TERMINAL_PROOF_BYTES = 58;
6525
- var TERMINAL_PROOF_LENGTH = 78;
6579
+ var TERMINAL_PROOF_BYTES = 74;
6580
+ var TERMINAL_PROOF_LENGTH = 99;
6526
6581
  var REQUEST_URI_PREFIX = "urn:ietf:params:oauth:request_uri:";
6527
6582
  var OIDC_CLIENT_STATE = /^[0-9a-f]{32}$/;
6528
6583
  var CANONICAL_NONCE = /^[0-9a-f]{64}$/;
6529
6584
  var CANONICAL_SHA256 = /^[A-Za-z0-9_-]{43}$/;
6585
+ var CANONICAL_SHA384 = /^[A-Za-z0-9_-]{64}$/;
6530
6586
  var CANONICAL_AUTHORIZATION_CODE = /^[A-Za-z0-9._~-]{1,8192}$/;
6531
6587
  function validCanonicalAttemptCapability(value) {
6532
6588
  if (typeof value !== "string" || value.length !== TERMINAL_PROOF_LENGTH) {
@@ -6534,7 +6590,7 @@ function validCanonicalAttemptCapability(value) {
6534
6590
  }
6535
6591
  try {
6536
6592
  const raw = base64ToBytes(value);
6537
- return raw.length === TERMINAL_PROOF_BYTES && bytesToBase64Url(raw) === value && raw[0] === 1 && raw[1] === 2;
6593
+ return raw.length === TERMINAL_PROOF_BYTES && bytesToBase64Url(raw) === value && raw[0] === 2 && raw[1] === 2;
6538
6594
  } catch {
6539
6595
  return false;
6540
6596
  }
@@ -6590,16 +6646,32 @@ function validCanonicalSHA256(value) {
6590
6646
  return false;
6591
6647
  }
6592
6648
  }
6649
+ function validOrdinaryAuthorizationRequestURI(value, historicalTerminalProof = false) {
6650
+ if (typeof value !== "string" || !value.startsWith(REQUEST_URI_PREFIX)) {
6651
+ return false;
6652
+ }
6653
+ const root = value.slice(REQUEST_URI_PREFIX.length);
6654
+ if (root.length === 64) {
6655
+ return !historicalTerminalProof && CANONICAL_SHA384.test(root);
6656
+ }
6657
+ return validCanonicalSHA256(root);
6658
+ }
6593
6659
  function validCanonicalAuthorizationCode(value) {
6594
6660
  return CANONICAL_AUTHORIZATION_CODE.test(value);
6595
6661
  }
6596
- async function authorizationCodeSHA256(value) {
6662
+ function isLegacyAuthorizationCodeCommitment(value) {
6663
+ return value !== null && validCanonicalSHA256(value);
6664
+ }
6665
+ function validAuthorizationCodeCommitment(value) {
6666
+ return typeof value === "string" && CANONICAL_SHA384.test(value);
6667
+ }
6668
+ async function authorizationCodeCommitment(value) {
6597
6669
  if (!validCanonicalAuthorizationCode(value)) {
6598
6670
  throw new Error("ordinary browser authorization: callback code is invalid");
6599
6671
  }
6600
6672
  const digest = await crypto.subtle.digest(
6601
- "SHA-256",
6602
- new TextEncoder().encode(value)
6673
+ "SHA-384",
6674
+ new TextEncoder().encode(`atol.ordinary-authorization.callback-code.v2\0${value}`)
6603
6675
  );
6604
6676
  return bytesToBase64Url(new Uint8Array(digest));
6605
6677
  }
@@ -7290,9 +7362,7 @@ function admittedSilentAuthorizationURL(opts) {
7290
7362
  }
7291
7363
  const names = new Set(entries.map(([name]) => name));
7292
7364
  const requestUri = authorization.searchParams.get("request_uri");
7293
- if (names.size !== 2 || !names.has("client_id") || !names.has("request_uri") || requestUri === null || !requestUri.startsWith(REQUEST_URI_PREFIX) || !validCanonicalSHA256(
7294
- requestUri.slice(REQUEST_URI_PREFIX.length)
7295
- )) {
7365
+ if (names.size !== 2 || !names.has("client_id") || !names.has("request_uri") || !validOrdinaryAuthorizationRequestURI(requestUri)) {
7296
7366
  throw new Error(
7297
7367
  "silent authorization: admitted PAR navigation URL is invalid"
7298
7368
  );
@@ -7537,16 +7607,16 @@ function createBrowserAuthActions(runtime) {
7537
7607
  runtime.redirectUri
7538
7608
  );
7539
7609
  if (precedingLogout) await precedingLogout;
7540
- const authorizationGeneration = credentialGenerationForLogin(
7541
- runtime.credentialGenerationBinding
7542
- );
7543
- onGeneration?.(authorizationGeneration);
7544
7610
  const authorizationEpoch = runtime.credentialEpoch;
7545
7611
  await runtime.credentialMutationTail;
7546
7612
  await runtime.lifecycleOps.ensureRuntimeInitialized();
7547
7613
  if (runtime.destroyed || authorizationEpoch !== runtime.credentialEpoch) {
7548
7614
  throw new StaleCredentialTransactionError();
7549
7615
  }
7616
+ const authorizationGeneration = credentialGenerationForLogin(
7617
+ runtime.credentialGenerationBinding
7618
+ );
7619
+ onGeneration?.(authorizationGeneration);
7550
7620
  runtime.sessionOps.assertCredentialAuthority(
7551
7621
  authorizationGeneration
7552
7622
  );
@@ -7592,7 +7662,8 @@ function createBrowserAuthActions(runtime) {
7592
7662
  returnTo,
7593
7663
  authorizationGeneration
7594
7664
  ),
7595
- createDPoPKey: createDPoPKeyManager
7665
+ createDPoPKey: runtime.createDPoPKey,
7666
+ requireMLDSA87DPoP: runtime.requireMLDSA87 && runtime.useDPoP
7596
7667
  });
7597
7668
  }
7598
7669
  function beginLogin(options) {
@@ -8014,6 +8085,9 @@ function assertOrdinaryAuthorizationDPoPBinding(binding, custody) {
8014
8085
  return dpop;
8015
8086
  }
8016
8087
  async function exchangeOrdinaryAuthorizationCode(binding, callback, dpop) {
8088
+ if (binding.useDPoP && binding.requireMLDSA87) {
8089
+ assertMLDSA87DPoPKey(dpop ? dpopKeyPair(dpop) : null);
8090
+ }
8017
8091
  const controller = new AbortController();
8018
8092
  const timeout = setTimeout(
8019
8093
  () => controller.abort(),
@@ -8123,6 +8197,93 @@ function stripOrdinaryAuthorizationResponseFromHistory(redirectUri) {
8123
8197
  }
8124
8198
  }
8125
8199
 
8200
+ // src/oidc/ordinary-authorization-lock.ts
8201
+ async function acquireOrdinaryAuthorizationCallbackLock(record) {
8202
+ if (typeof navigator === "undefined" || !navigator.locks || typeof navigator.locks.request !== "function") {
8203
+ throw new Error(
8204
+ "ordinary browser authorization: Web Locks is required"
8205
+ );
8206
+ }
8207
+ if (record.version !== HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION && record.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION) {
8208
+ throw new Error("ordinary browser authorization: unsupported lock format");
8209
+ }
8210
+ const historical = record.version === HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION;
8211
+ const digest = await crypto.subtle.digest(
8212
+ historical ? "SHA-256" : "SHA-384",
8213
+ new TextEncoder().encode(record.slotKey)
8214
+ );
8215
+ const namespace = historical ? "atol:ordinary-callback:" : "atol:ordinary-callback:v3:";
8216
+ const name = namespace + bytesToBase64Url(new Uint8Array(digest));
8217
+ let releaseHold;
8218
+ const hold = new Promise((resolve) => {
8219
+ releaseHold = resolve;
8220
+ });
8221
+ let resolveAcquired;
8222
+ let rejectAcquired;
8223
+ const acquired = new Promise((resolve, reject) => {
8224
+ resolveAcquired = resolve;
8225
+ rejectAcquired = reject;
8226
+ });
8227
+ let acquisitionSettled = false;
8228
+ const request = navigator.locks.request(
8229
+ name,
8230
+ { mode: "exclusive", ifAvailable: true },
8231
+ async (lock) => {
8232
+ if (!lock) {
8233
+ acquisitionSettled = true;
8234
+ rejectAcquired(new OrdinaryAuthorizationPendingError());
8235
+ return;
8236
+ }
8237
+ acquisitionSettled = true;
8238
+ resolveAcquired();
8239
+ await hold;
8240
+ }
8241
+ );
8242
+ void request.catch((error) => {
8243
+ if (!acquisitionSettled) rejectAcquired(error);
8244
+ });
8245
+ try {
8246
+ await acquired;
8247
+ } catch (error) {
8248
+ releaseHold();
8249
+ try {
8250
+ await request;
8251
+ } catch (requestError) {
8252
+ throw requestError;
8253
+ }
8254
+ throw error;
8255
+ }
8256
+ let released = false;
8257
+ return {
8258
+ release: async () => {
8259
+ if (released) return;
8260
+ released = true;
8261
+ releaseHold();
8262
+ await request;
8263
+ }
8264
+ };
8265
+ }
8266
+
8267
+ // src/oidc/ordinary-authorization-legacy-proof.ts
8268
+ function legacyOrdinaryAuthorizationProofDeadline(value, kind) {
8269
+ if (typeof value !== "string" || value.length !== 78) return null;
8270
+ try {
8271
+ const raw = base64ToBytes(value);
8272
+ if (raw.length !== 58 || bytesToBase64Url(raw) !== value || raw[0] !== 1 || raw[1] !== kind) return null;
8273
+ let deadline = 0n;
8274
+ for (let index = 18; index < 26; index++) {
8275
+ deadline = deadline << 8n | BigInt(raw[index]);
8276
+ }
8277
+ return deadline > 0n ? deadline : null;
8278
+ } catch {
8279
+ return null;
8280
+ }
8281
+ }
8282
+ function isLegacyOrdinaryAuthorizationRecord(record) {
8283
+ const attempt = new URLSearchParams(record.form).get("atol_attempt_capability");
8284
+ return legacyOrdinaryAuthorizationProofDeadline(attempt, 2) !== null;
8285
+ }
8286
+
8126
8287
  // src/oidc/ordinary-authorization-protocol.ts
8127
8288
  function ordinaryAuthorizationDiscoveryContract(metadata, binding) {
8128
8289
  if (metadata.issuer !== binding.issuer) {
@@ -8188,7 +8349,7 @@ function validOrdinaryAuthorizationTerminalProof(value, rootExpiresAt) {
8188
8349
  }
8189
8350
  try {
8190
8351
  const raw = base64ToBytes(value);
8191
- if (raw.length !== TERMINAL_PROOF_BYTES || bytesToBase64Url(raw) !== value || raw[0] !== 1 || raw[1] !== 1) {
8352
+ if (raw.length !== TERMINAL_PROOF_BYTES || bytesToBase64Url(raw) !== value || raw[0] !== 2 || raw[1] !== 1) {
8192
8353
  return false;
8193
8354
  }
8194
8355
  let deadline = 0n;
@@ -8270,9 +8431,7 @@ function admittedOrdinaryAuthorizationRecord(record, responseText) {
8270
8431
  "atol_browser_authorization_version",
8271
8432
  "atol_browser_authorization_expires_at",
8272
8433
  "terminal_proof"
8273
- ]) || record.parPhase !== "submitted" || typeof response.request_uri !== "string" || !response.request_uri.startsWith(REQUEST_URI_PREFIX) || !validCanonicalSHA256(
8274
- response.request_uri.slice(REQUEST_URI_PREFIX.length)
8275
- ) || !Number.isInteger(response.expires_in) || response.expires_in <= 0 || response.expires_in > record.ceremonyLifetimeSeconds || response.authorization_code_expires_in !== record.authorizationCodeLifetimeSeconds || response.atol_browser_authorization_version !== record.protocolVersion || typeof response.atol_browser_authorization_expires_at !== "string" || record.attemptExpiresAtMs === null || !new URLSearchParams(record.form).has(
8434
+ ]) || record.parPhase !== "submitted" || !validOrdinaryAuthorizationRequestURI(response.request_uri) || !Number.isInteger(response.expires_in) || response.expires_in <= 0 || response.expires_in > record.ceremonyLifetimeSeconds || response.authorization_code_expires_in !== record.authorizationCodeLifetimeSeconds || response.atol_browser_authorization_version !== record.protocolVersion || typeof response.atol_browser_authorization_expires_at !== "string" || record.attemptExpiresAtMs === null || !new URLSearchParams(record.form).has(
8276
8435
  "atol_attempt_capability"
8277
8436
  )) {
8278
8437
  throw new Error(
@@ -8411,7 +8570,7 @@ function readBoundedParResponse(response, signal) {
8411
8570
  );
8412
8571
  }
8413
8572
  function ordinaryAuthorizationNavigationURL(record) {
8414
- if (record.parPhase !== "admitted" || record.requestUri === null || record.terminalProof === null || record.attemptExpiresAtMs === null || Date.now() >= record.attemptExpiresAtMs) {
8573
+ if (record.parPhase !== "admitted" || record.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION || isLegacyOrdinaryAuthorizationRecord(record) || !validOrdinaryAuthorizationRequestURI(record.requestUri) || record.terminalProof === null || record.attemptExpiresAtMs === null || Date.now() >= record.attemptExpiresAtMs) {
8415
8574
  throw new Error(
8416
8575
  "ordinary browser authorization: admitted root is expired"
8417
8576
  );
@@ -8431,13 +8590,10 @@ var OrdinaryAuthorizationSettlementInvalidError = class extends Error {
8431
8590
  this.name = "OrdinaryAuthorizationSettlementInvalidError";
8432
8591
  }
8433
8592
  };
8434
- function assertSettlementAuthority(authority, mode) {
8435
- if (authority.settlementEndpoint !== `${authority.issuer}/auth/par/settlement` || authority.requestUri === null || !authority.requestUri.startsWith(REQUEST_URI_PREFIX) || !validCanonicalSHA256(
8436
- authority.requestUri.slice(REQUEST_URI_PREFIX.length)
8437
- ) || !validCanonicalSHA256(authority.cancellationSecret) || authority.terminalProof !== null && (authority.rootExpiresAt === null || !validOrdinaryAuthorizationTerminalProof(
8438
- authority.terminalProof,
8439
- authority.rootExpiresAt
8440
- )) || mode === "terminal_only" && authority.terminalProof === null) {
8593
+ function assertSettlementAuthority(authority, mode, historicalTerminalProof) {
8594
+ const deadline = historicalTerminalProof ? legacyOrdinaryAuthorizationProofDeadline(authority.terminalProof, 1) : null;
8595
+ const proofValid = authority.terminalProof === null || authority.rootExpiresAt !== null && (historicalTerminalProof ? deadline !== null && deadline === rfc3339NanoNanoseconds(authority.rootExpiresAt) : validOrdinaryAuthorizationTerminalProof(authority.terminalProof, authority.rootExpiresAt));
8596
+ if (authority.settlementEndpoint !== `${authority.issuer}/auth/par/settlement` || !validOrdinaryAuthorizationRequestURI(authority.requestUri, historicalTerminalProof) || !validCanonicalSHA256(authority.cancellationSecret) || !proofValid || mode === "terminal_only" && authority.terminalProof === null) {
8441
8597
  throw new Error(
8442
8598
  "ordinary browser authorization: settlement authority is invalid"
8443
8599
  );
@@ -8479,7 +8635,13 @@ function settlementBody(authority, mode) {
8479
8635
  });
8480
8636
  }
8481
8637
  async function settleOrdinaryAuthorization(authority, mode) {
8482
- assertSettlementAuthority(authority, mode);
8638
+ return settle(authority, mode, false);
8639
+ }
8640
+ function classifyLegacyOrdinaryAuthorization(authority) {
8641
+ return settle(authority, "terminal_only", true);
8642
+ }
8643
+ async function settle(authority, mode, historicalTerminalProof) {
8644
+ assertSettlementAuthority(authority, mode, historicalTerminalProof);
8483
8645
  const controller = new AbortController();
8484
8646
  const timeout = setTimeout(
8485
8647
  () => controller.abort(),
@@ -8660,7 +8822,7 @@ function parseOrdinaryAuthorizationPointer(raw) {
8660
8822
  }
8661
8823
 
8662
8824
  // src/oidc/ordinary-authorization-validation.ts
8663
- function canonicalOrdinaryAuthorizationForm(authorizationURL, binding, created) {
8825
+ function canonicalOrdinaryAuthorizationForm(authorizationURL, binding, created, historicalCustody = false) {
8664
8826
  const parsed = new URL(authorizationURL);
8665
8827
  if (`${parsed.origin}${parsed.pathname}` !== `${binding.issuer}/auth/authorize` || parsed.username !== "" || parsed.password !== "" || parsed.hash !== "") {
8666
8828
  throw new Error(
@@ -8678,9 +8840,7 @@ function canonicalOrdinaryAuthorizationForm(authorizationURL, binding, created)
8678
8840
  seen.add(name);
8679
8841
  values.set(name, value);
8680
8842
  }
8681
- if (values.get("response_type") !== "code" || values.get("client_id") !== binding.clientId || values.get("redirect_uri") !== binding.redirectUri || values.get("scope") !== binding.scope || !binding.scope.split(" ").includes("openid") || values.get("state") !== created.stateId || !OIDC_CLIENT_STATE.test(created.stateId) || values.get("nonce") !== created.nonce || !CANONICAL_NONCE.test(created.nonce) || values.get("code_challenge") !== created.codeChallenge || !validCanonicalSHA256(created.codeChallenge) || values.get("code_challenge_method") !== "S256" || values.has("atol_attempt_capability") && !validCanonicalAttemptCapability(
8682
- values.get("atol_attempt_capability")
8683
- ) || values.has("dpop_jkt") && !validCanonicalSHA256(values.get("dpop_jkt"))) {
8843
+ if (values.get("response_type") !== "code" || values.get("client_id") !== binding.clientId || values.get("redirect_uri") !== binding.redirectUri || values.get("scope") !== binding.scope || !binding.scope.split(" ").includes("openid") || values.get("state") !== created.stateId || !OIDC_CLIENT_STATE.test(created.stateId) || values.get("nonce") !== created.nonce || !CANONICAL_NONCE.test(created.nonce) || values.get("code_challenge") !== created.codeChallenge || !validCanonicalSHA256(created.codeChallenge) || values.get("code_challenge_method") !== "S256" || values.has("atol_attempt_capability") && (historicalCustody ? legacyOrdinaryAuthorizationProofDeadline(values.get("atol_attempt_capability"), 2) === null : !validCanonicalAttemptCapability(values.get("atol_attempt_capability"))) || values.has("dpop_jkt") && !validCanonicalSHA256(values.get("dpop_jkt"))) {
8684
8844
  throw new Error(
8685
8845
  "ordinary browser authorization: generated form binding is invalid"
8686
8846
  );
@@ -8696,19 +8856,21 @@ function assertOrdinaryAuthorizationRecord(record, binding, generation, intent)
8696
8856
  binding,
8697
8857
  generation.tabOwner
8698
8858
  );
8699
- if (record.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION || !Number.isSafeInteger(record.revision) || record.revision <= 0 || record.slotKey !== expectedSlot || !OIDC_CLIENT_STATE.test(record.stateId) || record.issuer !== binding.issuer || record.clientId !== binding.clientId || record.redirectUri !== binding.redirectUri || record.scope !== binding.scope || !sameCredentialGeneration2(record.credentialGeneration, generation) || record.intent !== intent || typeof record.stateStorage !== "string" || record.stateStorage.length === 0 || record.stateStorage.length > 32 * 1024 || !Number.isSafeInteger(record.stateCreatedAt) || record.stateCreatedAt < 0 || typeof record.form !== "string" || record.form.length === 0 || record.form.length > 16 * 1024 || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0 || !Number.isSafeInteger(record.provisionalExpiresAt) || record.provisionalExpiresAt !== record.createdAt + (record.ceremonyLifetimeSeconds + record.authorizationCodeLifetimeSeconds) * 1e3 || record.attemptExpiresAtMs !== null && (!Number.isSafeInteger(record.attemptExpiresAtMs) || record.attemptExpiresAtMs <= record.createdAt || record.attemptExpiresAtMs > record.provisionalExpiresAt) || record.protocolVersion !== ORDINARY_AUTHORIZATION_PROTOCOL_VERSION || !Number.isSafeInteger(record.ceremonyLifetimeSeconds) || record.ceremonyLifetimeSeconds <= 0 || record.ceremonyLifetimeSeconds > MAX_CEREMONY_LIFETIME_SECONDS || record.authorizationCodeLifetimeSeconds !== AUTHORIZATION_CODE_LIFETIME_SECONDS || record.pushedAuthorizationRequestEndpoint !== `${binding.issuer}/auth/par` || record.preNavigationCancellationEndpoint !== `${binding.issuer}/auth/par/pre-navigation-cancellation` || record.settlementEndpoint !== `${binding.issuer}/auth/par/settlement` || record.authorizationEndpoint !== `${binding.issuer}/auth/authorize` || record.dpopJkt === null !== (record.keys === null) || record.dpopJkt !== null && !validCanonicalSHA256(record.dpopJkt) || !validCanonicalSHA256(record.cancellationSecret) || record.parPhase !== "prepared" && record.parPhase !== "submitted" && record.parPhase !== "admitted" || record.parPhase === "prepared" && record.attemptExpiresAtMs !== null || record.parPhase === "admitted" && record.attemptExpiresAtMs === null || record.parPhase === "admitted" !== (record.requestUri !== null) || record.parPhase === "admitted" !== (record.terminalProof !== null) || record.parPhase === "admitted" !== (record.rootExpiresAt !== null) || record.parPhase === "admitted" !== (record.rootExpiresAtMs !== null) || record.parPhase === "admitted" !== (record.custodyExpiresAtMs !== null) || record.callbackClaimId === null !== (record.callbackClaimExpiresAtMs === null) || record.callbackCode === null !== (record.callbackCodeHash === null) || record.callbackCode !== null && !validCanonicalAuthorizationCode(record.callbackCode) || record.callbackCodeHash !== null && !validCanonicalSHA256(record.callbackCodeHash) || typeof record.compensationRequired !== "boolean" || record.compensationRequired && record.callbackCode === null || typeof record.rejectionRequired !== "boolean" || record.rejectionRequired && record.parPhase !== "admitted" || record.rejectionRequired && record.callbackClaimId !== null || typeof record.cleanupStarted !== "boolean" || record.cleanupStarted && record.callbackClaimId !== null || record.callbackClaimId !== null && (!validCanonicalSHA256(record.callbackClaimId) || !Number.isSafeInteger(record.callbackClaimExpiresAtMs) || record.callbackClaimExpiresAtMs <= 0)) {
8859
+ if (record.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION && record.version !== HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION || !Number.isSafeInteger(record.revision) || record.revision <= 0 || record.slotKey !== expectedSlot || !OIDC_CLIENT_STATE.test(record.stateId) || record.issuer !== binding.issuer || record.clientId !== binding.clientId || record.redirectUri !== binding.redirectUri || record.scope !== binding.scope || !sameCredentialGeneration2(record.credentialGeneration, generation) || record.intent !== intent || typeof record.stateStorage !== "string" || record.stateStorage.length === 0 || record.stateStorage.length > 32 * 1024 || !Number.isSafeInteger(record.stateCreatedAt) || record.stateCreatedAt < 0 || typeof record.form !== "string" || record.form.length === 0 || record.form.length > 16 * 1024 || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0 || !Number.isSafeInteger(record.provisionalExpiresAt) || record.provisionalExpiresAt !== record.createdAt + (record.ceremonyLifetimeSeconds + record.authorizationCodeLifetimeSeconds) * 1e3 || record.attemptExpiresAtMs !== null && (!Number.isSafeInteger(record.attemptExpiresAtMs) || record.attemptExpiresAtMs <= record.createdAt || record.attemptExpiresAtMs > record.provisionalExpiresAt) || record.protocolVersion !== ORDINARY_AUTHORIZATION_PROTOCOL_VERSION || !Number.isSafeInteger(record.ceremonyLifetimeSeconds) || record.ceremonyLifetimeSeconds <= 0 || record.ceremonyLifetimeSeconds > MAX_CEREMONY_LIFETIME_SECONDS || record.authorizationCodeLifetimeSeconds !== AUTHORIZATION_CODE_LIFETIME_SECONDS || record.pushedAuthorizationRequestEndpoint !== `${binding.issuer}/auth/par` || record.preNavigationCancellationEndpoint !== `${binding.issuer}/auth/par/pre-navigation-cancellation` || record.settlementEndpoint !== `${binding.issuer}/auth/par/settlement` || record.authorizationEndpoint !== `${binding.issuer}/auth/authorize` || record.dpopJkt === null !== (record.keys === null) || record.dpopJkt !== null && !validCanonicalSHA256(record.dpopJkt) || !validCanonicalSHA256(record.cancellationSecret) || record.parPhase !== "prepared" && record.parPhase !== "submitted" && record.parPhase !== "admitted" || record.parPhase === "prepared" && record.attemptExpiresAtMs !== null || record.parPhase === "admitted" && record.attemptExpiresAtMs === null || record.parPhase === "admitted" !== (record.requestUri !== null) || record.parPhase === "admitted" !== (record.terminalProof !== null) || record.parPhase === "admitted" !== (record.rootExpiresAt !== null) || record.parPhase === "admitted" !== (record.rootExpiresAtMs !== null) || record.parPhase === "admitted" !== (record.custodyExpiresAtMs !== null) || record.callbackClaimId === null !== (record.callbackClaimExpiresAtMs === null) || record.callbackCode === null !== (record.callbackCodeHash === null) || record.callbackCode !== null && !validCanonicalAuthorizationCode(record.callbackCode) || record.callbackCodeHash !== null && !validAuthorizationCodeCommitment(record.callbackCodeHash) && !isLegacyAuthorizationCodeCommitment(record.callbackCodeHash) || typeof record.compensationRequired !== "boolean" || record.compensationRequired && record.callbackCode === null || typeof record.rejectionRequired !== "boolean" || record.rejectionRequired && record.parPhase !== "admitted" || record.rejectionRequired && record.callbackClaimId !== null || typeof record.cleanupStarted !== "boolean" || record.cleanupStarted && record.callbackClaimId !== null || record.callbackClaimId !== null && (!validCanonicalSHA256(record.callbackClaimId) || !Number.isSafeInteger(record.callbackClaimExpiresAtMs) || record.callbackClaimExpiresAtMs <= 0)) {
8700
8860
  throw new Error("ordinary browser authorization: custody binding mismatch");
8701
8861
  }
8702
8862
  const parameters = new URLSearchParams(record.form);
8863
+ const historicalCustody = isLegacyOrdinaryAuthorizationRecord(record);
8703
8864
  const intentRecord = parseOrdinaryAuthorizationIntent(record.intent);
8704
- if (canonicalOrdinaryAuthorizationForm(
8865
+ if (record.version === ORDINARY_AUTHORIZATION_RECORD_VERSION && (historicalCustody || isLegacyAuthorizationCodeCommitment(record.callbackCodeHash)) || historicalCustody && record.callbackCodeHash !== null && !isLegacyAuthorizationCodeCommitment(record.callbackCodeHash) || canonicalOrdinaryAuthorizationForm(
8705
8866
  `${record.authorizationEndpoint}?${record.form}`,
8706
8867
  binding,
8707
8868
  {
8708
8869
  stateId: record.stateId,
8709
8870
  nonce: parameters.get("nonce") ?? "",
8710
8871
  codeChallenge: parameters.get("code_challenge") ?? ""
8711
- }
8872
+ },
8873
+ historicalCustody
8712
8874
  ) !== record.form || parameters.get("dpop_jkt") !== record.dpopJkt || parameters.has("atol_attempt_capability") !== (record.attemptExpiresAtMs !== null) || parameters.get("response_mode") !== intentRecord.responseMode || parameters.get("prompt") !== intentRecord.prompt || parameters.get("max_age") !== (intentRecord.maxAge === null ? null : String(intentRecord.maxAge)) || parameters.get("acr_values") !== intentRecord.acrValues || Object.entries(intentRecord.extraQueryParams).some(
8713
8875
  ([name, value]) => parameters.get(name) !== value
8714
8876
  ) || intentRecord.dpopRequired && record.dpopJkt === null || !intentRecord.dpopEnabled && record.dpopJkt !== null) {
@@ -8718,16 +8880,7 @@ function assertOrdinaryAuthorizationRecord(record, binding, generation, intent)
8718
8880
  const parsedDeadline = rfc3339NanoMilliseconds(
8719
8881
  record.rootExpiresAt
8720
8882
  );
8721
- if (!record.requestUri.startsWith(REQUEST_URI_PREFIX) || !validCanonicalSHA256(
8722
- record.requestUri.slice(REQUEST_URI_PREFIX.length)
8723
- ) || !validOrdinaryAuthorizationTerminalProof(
8724
- record.terminalProof,
8725
- record.rootExpiresAt
8726
- ) || ordinaryAuthorizationAttemptCapabilityDeadline(
8727
- parameters.get("atol_attempt_capability")
8728
- ) !== rfc3339NanoNanoseconds(
8729
- record.rootExpiresAt
8730
- ) || parsedDeadline !== record.rootExpiresAtMs || Math.min(
8883
+ if (!validOrdinaryAuthorizationRequestURI(record.requestUri, historicalCustody) || !storedOrdinaryAuthorizationProofsMatch(record, parameters, historicalCustody) || parsedDeadline !== record.rootExpiresAtMs || Math.min(
8731
8884
  record.attemptExpiresAtMs + record.authorizationCodeLifetimeSeconds * 1e3,
8732
8885
  record.provisionalExpiresAt
8733
8886
  ) !== record.custodyExpiresAtMs) {
@@ -8737,6 +8890,15 @@ function assertOrdinaryAuthorizationRecord(record, binding, generation, intent)
8737
8890
  }
8738
8891
  }
8739
8892
  }
8893
+ function storedOrdinaryAuthorizationProofsMatch(record, parameters, historicalCustody) {
8894
+ const rootExpiresAt = record.rootExpiresAt;
8895
+ const deadline = rfc3339NanoNanoseconds(rootExpiresAt);
8896
+ const attempt = parameters.get("atol_attempt_capability");
8897
+ if (historicalCustody) {
8898
+ return deadline !== null && legacyOrdinaryAuthorizationProofDeadline(attempt, 2) === deadline && legacyOrdinaryAuthorizationProofDeadline(record.terminalProof, 1) === deadline;
8899
+ }
8900
+ return validOrdinaryAuthorizationTerminalProof(record.terminalProof, rootExpiresAt) && ordinaryAuthorizationAttemptCapabilityDeadline(attempt) === deadline;
8901
+ }
8740
8902
  async function assertOrdinaryAuthorizationRecordState(record) {
8741
8903
  const state = parseUniqueJSONObject(record.stateStorage, 32 * 1024);
8742
8904
  if (!hasExactMembers(
@@ -8793,6 +8955,15 @@ async function assertOrdinaryAuthorizationRecordState(record) {
8793
8955
  "ordinary browser authorization: stored application state mismatch"
8794
8956
  );
8795
8957
  }
8958
+ if (record.callbackCode !== null) {
8959
+ const commitment = isLegacyAuthorizationCodeCommitment(record.callbackCodeHash) ? bytesToBase64Url(new Uint8Array(await crypto.subtle.digest(
8960
+ "SHA-256",
8961
+ new TextEncoder().encode(record.callbackCode)
8962
+ ))) : await authorizationCodeCommitment(record.callbackCode);
8963
+ if (commitment !== record.callbackCodeHash) {
8964
+ throw new Error("ordinary browser authorization: stored callback code commitment mismatch");
8965
+ }
8966
+ }
8796
8967
  }
8797
8968
  function assertOrdinaryAuthorizationCallbackMatches(record, callback, generation) {
8798
8969
  const form = new URLSearchParams(record.form);
@@ -8873,11 +9044,6 @@ async function classifyOrdinaryAuthorizationRecordEnvelope(value) {
8873
9044
  });
8874
9045
  assertOrdinaryAuthorizationRecord(record, binding, generation, record.intent);
8875
9046
  await assertOrdinaryAuthorizationRecordState(record);
8876
- if (record.callbackCode !== null && await authorizationCodeSHA256(record.callbackCode) !== record.callbackCodeHash) {
8877
- throw new Error(
8878
- "ordinary browser authorization: unrecognized custody record"
8879
- );
8880
- }
8881
9047
  if (record.keys !== null) {
8882
9048
  if (typeof record.keys !== "object" || !hasExactMembers(record.keys, [
8883
9049
  "privateKey",
@@ -9051,11 +9217,11 @@ async function markOrdinaryAuthorizationPARSubmitted(expected) {
9051
9217
  store.get(expected.slotKey),
9052
9218
  "PAR submission read"
9053
9219
  );
9054
- if (current && (current.parPhase === "submitted" || current.parPhase === "admitted") && current.stateId === expected.stateId && current.form === expected.form && current.cancellationSecret === expected.cancellationSecret && !current.cleanupStarted && !current.rejectionRequired) {
9220
+ if (current && (current.parPhase === "submitted" || current.parPhase === "admitted") && current.version === expected.version && current.stateId === expected.stateId && current.form === expected.form && current.cancellationSecret === expected.cancellationSecret && !current.cleanupStarted && !current.rejectionRequired) {
9055
9221
  await ordinaryAuthorizationTransactionDone(transaction, "stable PAR submission");
9056
9222
  return current;
9057
9223
  }
9058
- if (!current || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.cancellationSecret !== expected.cancellationSecret || current.parPhase !== "prepared" || current.cleanupStarted || current.rejectionRequired) {
9224
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.cancellationSecret !== expected.cancellationSecret || current.parPhase !== "prepared" || current.cleanupStarted || current.rejectionRequired) {
9059
9225
  transaction.abort();
9060
9226
  throw new OrdinaryAuthorizationPendingError();
9061
9227
  }
@@ -9108,11 +9274,11 @@ async function bindOrdinaryAuthorizationAttemptCapability(expected, attemptCapab
9108
9274
  store.get(expected.slotKey),
9109
9275
  "attempt capability read"
9110
9276
  );
9111
- if (current?.form === updatedForm && current.attemptExpiresAtMs === clippedExpiresAt && current.stateId === expected.stateId && current.cancellationSecret === expected.cancellationSecret && current.parPhase === "submitted" && !current.cleanupStarted && !current.rejectionRequired) {
9277
+ if (current?.form === updatedForm && current.attemptExpiresAtMs === clippedExpiresAt && current.version === expected.version && current.stateId === expected.stateId && current.cancellationSecret === expected.cancellationSecret && current.parPhase === "submitted" && !current.cleanupStarted && !current.rejectionRequired) {
9112
9278
  await ordinaryAuthorizationTransactionDone(transaction, "stable attempt capability binding");
9113
9279
  return current;
9114
9280
  }
9115
- if (!current || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.cancellationSecret !== expected.cancellationSecret || current.parPhase !== "submitted" || current.cleanupStarted || current.rejectionRequired) {
9281
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.cancellationSecret !== expected.cancellationSecret || current.parPhase !== "submitted" || current.cleanupStarted || current.rejectionRequired) {
9116
9282
  transaction.abort();
9117
9283
  throw new OrdinaryAuthorizationPendingError();
9118
9284
  }
@@ -9141,16 +9307,17 @@ async function replaceOrdinaryAuthorizationRecord(expected, replacement) {
9141
9307
  store.get(expected.slotKey),
9142
9308
  "record bind read"
9143
9309
  );
9144
- if (current && !current.cleanupStarted && current.stateId === expected.stateId && current.form === expected.form && current.stateStorage === expected.stateStorage && current.parPhase === "admitted" && !current.rejectionRequired && current.requestUri === replacement.requestUri && current.terminalProof === replacement.terminalProof && current.rootExpiresAt === replacement.rootExpiresAt && current.rootExpiresAtMs === replacement.rootExpiresAtMs && current.custodyExpiresAtMs === replacement.custodyExpiresAtMs) {
9310
+ if (current && !current.cleanupStarted && current.version === expected.version && current.stateId === expected.stateId && current.form === expected.form && current.stateStorage === expected.stateStorage && current.parPhase === "admitted" && !current.rejectionRequired && current.requestUri === replacement.requestUri && current.terminalProof === replacement.terminalProof && current.rootExpiresAt === replacement.rootExpiresAt && current.rootExpiresAtMs === replacement.rootExpiresAtMs && current.custodyExpiresAtMs === replacement.custodyExpiresAtMs) {
9145
9311
  await ordinaryAuthorizationTransactionDone(transaction, "stable record bind");
9146
9312
  return current;
9147
9313
  }
9148
- if (!current || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.stateStorage !== expected.stateStorage || current.parPhase !== "submitted" || current.requestUri !== expected.requestUri || current.terminalProof !== expected.terminalProof || current.rootExpiresAt !== expected.rootExpiresAt || current.cleanupStarted || current.rejectionRequired) {
9314
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.stateStorage !== expected.stateStorage || current.parPhase !== "submitted" || current.requestUri !== expected.requestUri || current.terminalProof !== expected.terminalProof || current.rootExpiresAt !== expected.rootExpiresAt || current.cleanupStarted || current.rejectionRequired) {
9149
9315
  transaction.abort();
9150
9316
  throw new Error("ordinary browser authorization: custody was superseded");
9151
9317
  }
9152
9318
  const next = {
9153
9319
  ...replacement,
9320
+ version: current.version,
9154
9321
  revision: current.revision + 1
9155
9322
  };
9156
9323
  store.put(next);
@@ -9172,11 +9339,11 @@ async function requireOrdinaryAuthorizationRejection(expected) {
9172
9339
  store.get(expected.slotKey),
9173
9340
  "rejection transition read"
9174
9341
  );
9175
- if (current?.rejectionRequired && current.parPhase === "admitted" && current.stateId === expected.stateId && current.form === expected.form) {
9342
+ if (current?.rejectionRequired && current.parPhase === "admitted" && current.version === expected.version && current.stateId === expected.stateId && current.form === expected.form) {
9176
9343
  await ordinaryAuthorizationTransactionDone(transaction, "stable rejection transition");
9177
9344
  return current;
9178
9345
  }
9179
- if (!current || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.parPhase !== "admitted" || current.cleanupStarted) {
9346
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.parPhase !== "admitted" || current.cleanupStarted) {
9180
9347
  transaction.abort();
9181
9348
  throw new OrdinaryAuthorizationPendingError();
9182
9349
  }
@@ -9200,7 +9367,7 @@ function newClaimID() {
9200
9367
  return bytesToBase64Url(value);
9201
9368
  }
9202
9369
  async function claimOrdinaryAuthorizationRecord(expected, callbackCode, callbackCodeHash) {
9203
- if (callbackCode === null !== (callbackCodeHash === null) || callbackCode !== null && !validCanonicalAuthorizationCode(callbackCode) || callbackCodeHash !== null && !validCanonicalSHA256(callbackCodeHash)) {
9370
+ if (callbackCode === null !== (callbackCodeHash === null) || callbackCode !== null && !validCanonicalAuthorizationCode(callbackCode) || callbackCodeHash !== null && !validAuthorizationCodeCommitment(callbackCodeHash)) {
9204
9371
  throw new Error("ordinary browser authorization: callback code is invalid");
9205
9372
  }
9206
9373
  const db = await openOrdinaryAuthorizationDB();
@@ -9215,7 +9382,7 @@ async function claimOrdinaryAuthorizationRecord(expected, callbackCode, callback
9215
9382
  "callback claim read"
9216
9383
  );
9217
9384
  const now = Date.now();
9218
- if (!current || current.revision !== expected.revision || current.stateId !== expected.stateId || current.parPhase !== "admitted" || current.rejectionRequired || current.cleanupStarted || current.callbackCode !== null && current.callbackCode !== callbackCode || current.callbackCodeHash !== null && current.callbackCodeHash !== callbackCodeHash || current.callbackCode === null && current.compensationRequired || current.callbackClaimId !== null && current.callbackClaimExpiresAtMs > now) {
9385
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || current.parPhase !== "admitted" || current.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION || isLegacyOrdinaryAuthorizationRecord(current) || current.rejectionRequired || current.cleanupStarted || current.callbackCode !== null && current.callbackCode !== callbackCode || current.callbackCodeHash !== null && current.callbackCodeHash !== callbackCodeHash || current.callbackCode === null && current.compensationRequired || current.callbackClaimId !== null && current.callbackClaimExpiresAtMs > now) {
9219
9386
  transaction.abort();
9220
9387
  throw new OrdinaryAuthorizationPendingError();
9221
9388
  }
@@ -9253,7 +9420,7 @@ async function markOrdinaryAuthorizationCodeIssued(expected) {
9253
9420
  store.get(expected.slotKey),
9254
9421
  "code issuance transition read"
9255
9422
  );
9256
- if (!current || current.revision !== expected.revision || current.stateId !== expected.stateId || current.callbackClaimId !== expected.callbackClaimId || current.callbackClaimId === null || current.callbackCode === null || current.callbackCodeHash === null || current.compensationRequired || current.rejectionRequired || current.cleanupStarted) {
9423
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || current.callbackClaimId !== expected.callbackClaimId || current.callbackClaimId === null || current.callbackCode === null || current.callbackCodeHash === null || current.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION || isLegacyOrdinaryAuthorizationRecord(current) || !validAuthorizationCodeCommitment(current.callbackCodeHash) || current.compensationRequired || current.rejectionRequired || current.cleanupStarted) {
9257
9424
  transaction.abort();
9258
9425
  throw new Error(
9259
9426
  "ordinary browser authorization: code issuance was superseded"
@@ -9283,11 +9450,11 @@ async function startOrdinaryAuthorizationCleanup(expected) {
9283
9450
  store.get(expected.slotKey),
9284
9451
  "cleanup transition read"
9285
9452
  );
9286
- if (current?.cleanupStarted && current.stateId === expected.stateId && current.form === expected.form && current.stateStorage === expected.stateStorage && current.cancellationSecret === expected.cancellationSecret) {
9453
+ if (current?.cleanupStarted && current.version === expected.version && current.stateId === expected.stateId && current.form === expected.form && current.stateStorage === expected.stateStorage && current.cancellationSecret === expected.cancellationSecret) {
9287
9454
  await ordinaryAuthorizationTransactionDone(transaction, "stable cleanup transition");
9288
9455
  return current;
9289
9456
  }
9290
- if (!current || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.stateStorage !== expected.stateStorage || current.cancellationSecret !== expected.cancellationSecret || current.cleanupStarted) {
9457
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || current.form !== expected.form || current.stateStorage !== expected.stateStorage || current.cancellationSecret !== expected.cancellationSecret || current.cleanupStarted) {
9291
9458
  transaction.abort();
9292
9459
  throw new Error("ordinary browser authorization: cleanup was superseded");
9293
9460
  }
@@ -9317,7 +9484,7 @@ async function releaseOrdinaryAuthorizationClaim(expected) {
9317
9484
  store.get(expected.slotKey),
9318
9485
  "callback release read"
9319
9486
  );
9320
- if (!current || current.revision !== expected.revision || current.callbackClaimId !== expected.callbackClaimId || current.callbackClaimId === null || current.cleanupStarted) {
9487
+ if (!current || current.version !== expected.version || current.revision !== expected.revision || current.callbackClaimId !== expected.callbackClaimId || current.callbackClaimId === null || current.cleanupStarted) {
9321
9488
  transaction.abort();
9322
9489
  throw new Error(
9323
9490
  "ordinary browser authorization: callback release was superseded"
@@ -9351,7 +9518,7 @@ async function deleteOrdinaryAuthorizationRecordRevision(expected) {
9351
9518
  await ordinaryAuthorizationTransactionDone(transaction, "idempotent record discard");
9352
9519
  return;
9353
9520
  }
9354
- if (current.revision !== expected.revision || current.stateId !== expected.stateId || !current.cleanupStarted) {
9521
+ if (current.version !== expected.version || current.revision !== expected.revision || current.stateId !== expected.stateId || !current.cleanupStarted) {
9355
9522
  transaction.abort();
9356
9523
  throw new Error("ordinary browser authorization: discard was superseded");
9357
9524
  }
@@ -9367,6 +9534,10 @@ function validOrdinaryPARResponseHeaders(response) {
9367
9534
  return response.headers.get("cache-control") === "no-store" && response.headers.get("content-type") === "application/json" && response.headers.get("atol-browser-authorization") === "v2";
9368
9535
  }
9369
9536
  async function postOrdinaryPAR(record, signal) {
9537
+ const cancellationChallenge = record.version === HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION && record.parPhase === "submitted" && record.attemptExpiresAtMs === null && !new URLSearchParams(record.form).has("atol_attempt_capability");
9538
+ if (isLegacyOrdinaryAuthorizationRecord(record) || record.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION && !cancellationChallenge) {
9539
+ throw new OrdinaryAuthorizationPendingError();
9540
+ }
9370
9541
  const startedAt = Date.now();
9371
9542
  try {
9372
9543
  const response = await fetch(record.pushedAuthorizationRequestEndpoint, {
@@ -9545,6 +9716,34 @@ var OrdinaryAuthorizationCleanupController = class {
9545
9716
  await settleOrdinaryAuthorization(rejecting, "reject");
9546
9717
  await this.startAndFinishCleanup(rejecting);
9547
9718
  }
9719
+ async retireObsoleteCustody(record, checkOwner = true) {
9720
+ if (record.version !== HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION) return false;
9721
+ const lock = await acquireOrdinaryAuthorizationCallbackLock(record);
9722
+ try {
9723
+ if (checkOwner) {
9724
+ assertCredentialGenerationSnapshot(this.binding, record.credentialGeneration);
9725
+ const pointer = parseOrdinaryAuthorizationPointer(
9726
+ ordinaryAuthorizationPointerStorage().getItem(this.storageKey)
9727
+ );
9728
+ if (pointer) this.assertExactPointer(record);
9729
+ }
9730
+ if (record.cleanupStarted) {
9731
+ await this.finishCleanup(record);
9732
+ } else if (record.parPhase === "prepared") {
9733
+ await this.cleanupPreparedRecordWithoutPointer(record);
9734
+ } else if (record.parPhase === "submitted") {
9735
+ await this.rejectSubmittedAndCleanup(record);
9736
+ } else if (isLegacyOrdinaryAuthorizationRecord(record)) {
9737
+ await classifyLegacyOrdinaryAuthorization(record);
9738
+ await this.startAndFinishCleanup(record);
9739
+ } else {
9740
+ await this.rejectAndCleanup(record);
9741
+ }
9742
+ } finally {
9743
+ await lock.release();
9744
+ }
9745
+ return true;
9746
+ }
9548
9747
  async rejectSubmittedAndCleanup(record) {
9549
9748
  const settled = await cancelSubmittedOrdinaryAuthorization(record);
9550
9749
  await this.startAndFinishCleanup(settled);
@@ -9586,6 +9785,7 @@ var OrdinaryAuthorizationCleanupController = class {
9586
9785
  record.intent
9587
9786
  );
9588
9787
  await assertOrdinaryAuthorizationRecordState(record);
9788
+ if (await this.retireObsoleteCustody(record)) return;
9589
9789
  if (record.cleanupStarted) {
9590
9790
  await this.finishCleanup(record);
9591
9791
  } else if (record.parPhase === "admitted") {
@@ -9607,6 +9807,12 @@ var OrdinaryAuthorizationCleanupController = class {
9607
9807
  (record) => record.issuer === this.binding.issuer && record.clientId === this.binding.clientId && new URL(record.redirectUri).origin === new URL(this.binding.redirectUri).origin
9608
9808
  );
9609
9809
  for (const record of matching) {
9810
+ try {
9811
+ if (await this.retireObsoleteCustody(record, false)) continue;
9812
+ } catch (error) {
9813
+ if (error instanceof OrdinaryAuthorizationPendingError && record.version === HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION && record.credentialGeneration.tabOwner !== currentTabOwnerGeneration(this.binding)) continue;
9814
+ throw error;
9815
+ }
9610
9816
  if (record.cleanupStarted) {
9611
9817
  await this.finishCleanup(record);
9612
9818
  } else if (record.parPhase === "admitted") {
@@ -9622,70 +9828,6 @@ var OrdinaryAuthorizationCleanupController = class {
9622
9828
  }
9623
9829
  };
9624
9830
 
9625
- // src/oidc/ordinary-authorization-lock.ts
9626
- async function acquireOrdinaryAuthorizationCallbackLock(slotKey2) {
9627
- if (typeof navigator === "undefined" || !navigator.locks || typeof navigator.locks.request !== "function") {
9628
- throw new Error(
9629
- "ordinary browser authorization: Web Locks is required"
9630
- );
9631
- }
9632
- const digest = await crypto.subtle.digest(
9633
- "SHA-256",
9634
- new TextEncoder().encode(slotKey2)
9635
- );
9636
- const name = `atol:ordinary-callback:${bytesToBase64Url(
9637
- new Uint8Array(digest)
9638
- )}`;
9639
- let releaseHold;
9640
- const hold = new Promise((resolve) => {
9641
- releaseHold = resolve;
9642
- });
9643
- let resolveAcquired;
9644
- let rejectAcquired;
9645
- const acquired = new Promise((resolve, reject) => {
9646
- resolveAcquired = resolve;
9647
- rejectAcquired = reject;
9648
- });
9649
- let acquisitionSettled = false;
9650
- const request = navigator.locks.request(
9651
- name,
9652
- { mode: "exclusive", ifAvailable: true },
9653
- async (lock) => {
9654
- if (!lock) {
9655
- acquisitionSettled = true;
9656
- rejectAcquired(new OrdinaryAuthorizationPendingError());
9657
- return;
9658
- }
9659
- acquisitionSettled = true;
9660
- resolveAcquired();
9661
- await hold;
9662
- }
9663
- );
9664
- void request.catch((error) => {
9665
- if (!acquisitionSettled) rejectAcquired(error);
9666
- });
9667
- try {
9668
- await acquired;
9669
- } catch (error) {
9670
- releaseHold();
9671
- try {
9672
- await request;
9673
- } catch (requestError) {
9674
- throw requestError;
9675
- }
9676
- throw error;
9677
- }
9678
- let released = false;
9679
- return {
9680
- release: async () => {
9681
- if (released) return;
9682
- released = true;
9683
- releaseHold();
9684
- await request;
9685
- }
9686
- };
9687
- }
9688
-
9689
9831
  // src/oidc/ordinary-authorization-callback.ts
9690
9832
  function callbackFromRecord(record) {
9691
9833
  if (record.callbackCode === null) {
@@ -9755,6 +9897,11 @@ var OrdinaryAuthorizationCallbackController = class {
9755
9897
  record.intent
9756
9898
  );
9757
9899
  await assertOrdinaryAuthorizationRecordState(record);
9900
+ if (record.version === HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION) {
9901
+ assertOrdinaryAuthorizationCallbackMatches(record, callback, generation);
9902
+ await this.retireObsoleteCustodyForResponse(record, callback);
9903
+ throw new Error("ordinary browser authorization: obsolete callback was settled");
9904
+ }
9758
9905
  if (record.cleanupStarted) {
9759
9906
  await this.cleanup.finishCleanup(record);
9760
9907
  throw new Error(
@@ -9772,15 +9919,13 @@ var OrdinaryAuthorizationCallbackController = class {
9772
9919
  callback,
9773
9920
  generation
9774
9921
  );
9775
- const processLock = await acquireOrdinaryAuthorizationCallbackLock(
9776
- record.slotKey
9777
- );
9922
+ const processLock = await acquireOrdinaryAuthorizationCallbackLock(record);
9778
9923
  let claimed;
9779
9924
  try {
9780
9925
  claimed = await claimOrdinaryAuthorizationRecord(
9781
9926
  record,
9782
9927
  callback.code ?? null,
9783
- callback.code === void 0 ? null : await authorizationCodeSHA256(callback.code)
9928
+ callback.code === void 0 ? null : await authorizationCodeCommitment(callback.code)
9784
9929
  );
9785
9930
  } catch (error) {
9786
9931
  await processLock.release();
@@ -9808,7 +9953,7 @@ var OrdinaryAuthorizationCallbackController = class {
9808
9953
  }
9809
9954
  let settled = false;
9810
9955
  const compensationRequired = claimed.compensationRequired;
9811
- const settle = async () => {
9956
+ const settle2 = async () => {
9812
9957
  if (settled) {
9813
9958
  throw new Error(
9814
9959
  "ordinary browser authorization: callback custody is already settled"
@@ -9857,7 +10002,7 @@ var OrdinaryAuthorizationCallbackController = class {
9857
10002
  throw error;
9858
10003
  }
9859
10004
  },
9860
- complete: settle,
10005
+ complete: settle2,
9861
10006
  discard: async () => {
9862
10007
  if (settled) {
9863
10008
  throw new Error(
@@ -9897,6 +10042,7 @@ var OrdinaryAuthorizationCallbackController = class {
9897
10042
  record.intent
9898
10043
  );
9899
10044
  await assertOrdinaryAuthorizationRecordState(record);
10045
+ if (await this.retireObsoleteCustody(record)) return null;
9900
10046
  if (record.cleanupStarted) {
9901
10047
  await this.cleanup.finishCleanup(record);
9902
10048
  return null;
@@ -9944,6 +10090,10 @@ var OrdinaryAuthorizationCallbackController = class {
9944
10090
  callback,
9945
10091
  generation
9946
10092
  );
10093
+ if (record.version === HISTORICAL_ORDINARY_AUTHORIZATION_RECORD_VERSION) {
10094
+ await this.retireObsoleteCustodyForResponse(record, callback);
10095
+ return;
10096
+ }
9947
10097
  if (callback.code !== void 0) {
9948
10098
  record = await this.rejectCallbackCode(
9949
10099
  record,
@@ -9975,9 +10125,20 @@ var OrdinaryAuthorizationCallbackController = class {
9975
10125
  record.intent
9976
10126
  );
9977
10127
  await assertOrdinaryAuthorizationRecordState(record);
9978
- await this.cleanup.finishCleanup(record);
10128
+ if (!await this.retireObsoleteCustody(record)) {
10129
+ await this.cleanup.finishCleanup(record);
10130
+ }
9979
10131
  return true;
9980
10132
  }
10133
+ retireObsoleteCustody(record) {
10134
+ return this.cleanup.retireObsoleteCustody(record);
10135
+ }
10136
+ async retireObsoleteCustodyForResponse(record, callback) {
10137
+ if (record.callbackCode !== null && callback.code !== record.callbackCode) {
10138
+ throw new Error("ordinary browser authorization: obsolete callback code mismatch");
10139
+ }
10140
+ await this.retireObsoleteCustody(record);
10141
+ }
9981
10142
  async invalidateCurrent(generation) {
9982
10143
  return this.cleanup.invalidateCurrent(generation);
9983
10144
  }
@@ -9985,15 +10146,13 @@ var OrdinaryAuthorizationCallbackController = class {
9985
10146
  return this.cleanup.invalidateSignedOutLifecycle();
9986
10147
  }
9987
10148
  async rejectCallbackCode(record, code) {
9988
- const processLock = await acquireOrdinaryAuthorizationCallbackLock(
9989
- record.slotKey
9990
- );
10149
+ const processLock = await acquireOrdinaryAuthorizationCallbackLock(record);
9991
10150
  let claimed = null;
9992
10151
  try {
9993
10152
  claimed = await claimOrdinaryAuthorizationRecord(
9994
10153
  record,
9995
10154
  code,
9996
- await authorizationCodeSHA256(code)
10155
+ await authorizationCodeCommitment(code)
9997
10156
  );
9998
10157
  try {
9999
10158
  return await requireOrdinaryAuthorizationRejection(claimed);
@@ -10050,6 +10209,9 @@ async function rejectOrRetainInvalidAdmission(submitted) {
10050
10209
  throw new OrdinaryAuthorizationPendingError();
10051
10210
  }
10052
10211
  async function admitOrdinaryAuthorization(record) {
10212
+ if (record.version !== ORDINARY_AUTHORIZATION_RECORD_VERSION) {
10213
+ throw new OrdinaryAuthorizationPendingError();
10214
+ }
10053
10215
  if (ordinaryAuthorizationRecordExpired(record)) {
10054
10216
  if (record.parPhase === "submitted") {
10055
10217
  return rejectOrRetainInvalidAdmission(record);
@@ -10149,7 +10311,11 @@ var OrdinaryBrowserAuthorization = class {
10149
10311
  const generation = start.credentialGeneration;
10150
10312
  const intent = serializedOrdinaryAuthorizationIntent(start.intent);
10151
10313
  assertCredentialGenerationSnapshot(this.binding, generation);
10152
- const pending = await this.pendingRecord(generation, intent);
10314
+ const pending = await this.pendingRecord(
10315
+ generation,
10316
+ intent,
10317
+ start.requireMLDSA87DPoP
10318
+ );
10153
10319
  if (pending) {
10154
10320
  await ensureAuthorizationRequestState(
10155
10321
  this.manager,
@@ -10171,6 +10337,9 @@ var OrdinaryBrowserAuthorization = class {
10171
10337
  return;
10172
10338
  }
10173
10339
  const dpopKey = start.intent.dpopEnabled ? await start.createDPoPKey() : null;
10340
+ if (start.requireMLDSA87DPoP) {
10341
+ assertMLDSA87DPoPKey(dpopKey ? dpopKeyPair(dpopKey) : null);
10342
+ }
10174
10343
  if (start.intent.dpopRequired && !dpopKey) {
10175
10344
  throw new Error(
10176
10345
  "DPoP is required but WebCrypto could not create an authorization key"
@@ -10283,7 +10452,11 @@ var OrdinaryBrowserAuthorization = class {
10283
10452
  created.stateId,
10284
10453
  created.stateStorage
10285
10454
  );
10286
- const winner = await this.pendingRecord(generation, intent);
10455
+ const winner = await this.pendingRecord(
10456
+ generation,
10457
+ intent,
10458
+ start.requireMLDSA87DPoP
10459
+ );
10287
10460
  if (!winner) throw error;
10288
10461
  await ensureAuthorizationRequestState(
10289
10462
  this.manager,
@@ -10348,7 +10521,7 @@ var OrdinaryBrowserAuthorization = class {
10348
10521
  invalidateSignedOutLifecycle() {
10349
10522
  return this.callbacks.invalidateSignedOutLifecycle();
10350
10523
  }
10351
- async pendingRecord(generation, intent) {
10524
+ async pendingRecord(generation, intent, requireMLDSA87DPoP) {
10352
10525
  const record = await loadOrdinaryAuthorizationRecord(
10353
10526
  ordinaryAuthorizationSlotKey(
10354
10527
  this.binding,
@@ -10374,6 +10547,7 @@ var OrdinaryBrowserAuthorization = class {
10374
10547
  record.intent
10375
10548
  );
10376
10549
  await assertOrdinaryAuthorizationRecordState(record);
10550
+ if (await this.callbacks.retireObsoleteCustody(record)) return null;
10377
10551
  if (record.intent !== intent) {
10378
10552
  const pending = parseOrdinaryAuthorizationIntent(record.intent);
10379
10553
  throw new OrdinaryAuthorizationIntentConflictError(
@@ -10388,6 +10562,7 @@ var OrdinaryBrowserAuthorization = class {
10388
10562
  await this.callbacks.invalidateCurrent(generation);
10389
10563
  return null;
10390
10564
  }
10565
+ if (requireMLDSA87DPoP) assertMLDSA87DPoPKey(record.keys);
10391
10566
  const expected = {
10392
10567
  stateId: record.stateId,
10393
10568
  tabOwnerGeneration: generation.tabOwner
@@ -10656,6 +10831,7 @@ var ResponseVaultRelay = class extends ResponseVaultSettlement {
10656
10831
  throw new Error("response vault: relay binding is incomplete");
10657
10832
  }
10658
10833
  this.assertAuthorizationCurrent(authorization);
10834
+ this.assertActiveProofKey(authorization);
10659
10835
  const endpoints = await this.endpointRegistry();
10660
10836
  this.assertAuthorizationCurrent(authorization);
10661
10837
  const proof = await authorization.dpopKey.signProof(
@@ -11063,21 +11239,17 @@ var ResponseVaultAdmission = class extends ResponseVaultRelay {
11063
11239
  throw new ResponseVaultAuthorizationBusyError();
11064
11240
  }
11065
11241
  } else {
11066
- await this.endpointRegistry();
11067
- this.assertLifecycle(lifecycleEpoch);
11068
- if (expectedGeneration) {
11069
- assertCredentialGenerationSnapshot(this.config, expectedGeneration);
11070
- }
11071
- const dpopKey = await createDPoPKeyManager();
11072
- this.assertLifecycle(lifecycleEpoch);
11073
- if (expectedGeneration) {
11074
- assertCredentialGenerationSnapshot(this.config, expectedGeneration);
11075
- }
11242
+ const dpopKey = await createDPoPKeyManager(this.config.dpopAlgorithm);
11076
11243
  if (!dpopKey) {
11077
11244
  throw new Error(
11078
11245
  "response vault: WebCrypto could not create a DPoP key"
11079
11246
  );
11080
11247
  }
11248
+ await this.endpointRegistry();
11249
+ this.assertLifecycle(lifecycleEpoch);
11250
+ if (expectedGeneration) {
11251
+ assertCredentialGenerationSnapshot(this.config, expectedGeneration);
11252
+ }
11081
11253
  const codeVerifier = randomOpaque2();
11082
11254
  const challenge = await codeChallenge(codeVerifier);
11083
11255
  this.assertLifecycle(lifecycleEpoch);
@@ -11570,13 +11742,16 @@ function createBrowserAuthCallbackOperations(runtime) {
11570
11742
  }
11571
11743
  const completionEpoch = runtime.credentialEpoch;
11572
11744
  const completion = (async () => {
11745
+ const callbackAuthority = persistedCredentialAuthority(
11746
+ runtime.credentialGenerationBinding
11747
+ );
11748
+ if (runtime.requireMLDSA87 && !callbackAuthority?.signedOut) {
11749
+ await runtime.lifecycleOps.ensureRuntimeInitialized();
11750
+ }
11573
11751
  let returnToApplied = false;
11574
11752
  let preserveCallbackForRetry = false;
11575
11753
  try {
11576
- const callbackAuthority = currentCredentialAuthority(
11577
- runtime.credentialGenerationBinding
11578
- );
11579
- if (callbackAuthority.signedOut) {
11754
+ if (callbackAuthority?.signedOut) {
11580
11755
  if (runtime.responseVault) {
11581
11756
  if (await runtime.lifecycleOps.settleSignedOutStartup(
11582
11757
  callbackAuthority.generation
@@ -11584,7 +11759,6 @@ function createBrowserAuthCallbackOperations(runtime) {
11584
11759
  throw new StaleCredentialTransactionError();
11585
11760
  }
11586
11761
  } else {
11587
- await runtime.lifecycleOps.ensureRuntimeInitialized();
11588
11762
  const callback2 = await readAuthorizationCodeResponseState(
11589
11763
  runtime.manager,
11590
11764
  window.location.href
@@ -11801,6 +11975,7 @@ function createBrowserAuthCallbackOperations(runtime) {
11801
11975
  // src/client/browser-auth-context.ts
11802
11976
  var BrowserAuthRuntime = class {
11803
11977
  constructor(config) {
11978
+ this.createDPoPKey = () => createDPoPKeyManager(this.requireMLDSA87 ? ML_DSA_87 : "ES256");
11804
11979
  this.currentUser = null;
11805
11980
  this.fragmentKEK = null;
11806
11981
  this.vault = null;
@@ -11862,12 +12037,14 @@ var BrowserAuthRuntime = class {
11862
12037
  throw new Error("response-vault authorization requires an audience");
11863
12038
  }
11864
12039
  this.useDPoP = this.useResponseVault || dpopEnabled(config.dpop);
11865
- this.requireDPoP = this.useResponseVault || dpopRequired(config.dpop);
12040
+ this.requireMLDSA87 = config.requireMLDSA87 !== false;
12041
+ this.requireDPoP = this.useResponseVault || dpopRequired(config.dpop) || this.useDPoP && this.requireMLDSA87;
11866
12042
  this.ordinaryExchangeBinding = {
11867
12043
  issuer: this.issuer,
11868
12044
  clientId: this.clientId,
11869
12045
  useDPoP: this.useDPoP,
11870
- requireDPoP: this.requireDPoP
12046
+ requireDPoP: this.requireDPoP,
12047
+ requireMLDSA87: this.requireMLDSA87
11871
12048
  };
11872
12049
  this.useRefreshTokens = config.useRefreshTokens ?? false;
11873
12050
  this.useRefreshTokensFallback = config.useRefreshTokensFallback ?? false;
@@ -11877,6 +12054,9 @@ var BrowserAuthRuntime = class {
11877
12054
  "response-vault v1 does not support deriveEncryptionKey"
11878
12055
  );
11879
12056
  }
12057
+ if (this.requireMLDSA87 && config.allowTestSessions) {
12058
+ throw new Error("ML-DSA-87 mode requires verified credentials");
12059
+ }
11880
12060
  this.allowTestSessions = config.allowTestSessions ?? false;
11881
12061
  this.initialTestSession = this.allowTestSessions ? config.initialTestSession : void 0;
11882
12062
  if (this.allowTestSessions && typeof console !== "undefined") {
@@ -11898,7 +12078,8 @@ var BrowserAuthRuntime = class {
11898
12078
  clientId: this.clientId,
11899
12079
  redirectUri: this.redirectUri,
11900
12080
  audience: this.audience,
11901
- scope: this.scope
12081
+ scope: this.scope,
12082
+ dpopAlgorithm: this.requireMLDSA87 ? ML_DSA_87 : "ES256"
11902
12083
  }) : null;
11903
12084
  this.ordinaryAuthorization = this.responseVault ? null : new OrdinaryBrowserAuthorization(this.manager, {
11904
12085
  issuer: this.issuer,
@@ -11951,6 +12132,7 @@ var BrowserAuthRuntime = class {
11951
12132
  return result;
11952
12133
  }
11953
12134
  };
12135
+ var MAX_JWT_BYTES = 24 << 10;
11954
12136
  var discoveryCache = /* @__PURE__ */ new Map();
11955
12137
  function discover(authority) {
11956
12138
  const cached = discoveryCache.get(authority);
@@ -12008,8 +12190,12 @@ function discover(authority) {
12008
12190
  return promise;
12009
12191
  }
12010
12192
  async function verifyIdToken(idToken, opts) {
12193
+ const token = boundedJWT(idToken);
12194
+ const requireMLDSA87 = opts.requireMLDSA87 !== false;
12195
+ if (requireMLDSA87) await assertMLDSA87VerificationSupport();
12011
12196
  const { issuer, jwks } = await discover(opts.authority);
12012
- const { payload } = await jwtVerify(idToken, jwks, {
12197
+ const { payload } = await jwtVerify(token, jwks, {
12198
+ algorithms: requireMLDSA87 ? [ML_DSA_87] : void 0,
12013
12199
  issuer,
12014
12200
  audience: opts.clientId,
12015
12201
  requiredClaims: ["sub", "exp", "iat"]
@@ -12029,8 +12215,12 @@ async function verifyIdToken(idToken, opts) {
12029
12215
  return payload;
12030
12216
  }
12031
12217
  async function verifyAccessToken(accessToken, opts) {
12218
+ const token = boundedJWT(accessToken);
12219
+ const requireMLDSA87 = opts.requireMLDSA87 !== false;
12220
+ if (requireMLDSA87) await assertMLDSA87VerificationSupport();
12032
12221
  const { issuer, jwks } = await discover(opts.authority);
12033
- const { payload, protectedHeader } = await jwtVerify(accessToken, jwks, {
12222
+ const { payload, protectedHeader } = await jwtVerify(token, jwks, {
12223
+ algorithms: requireMLDSA87 ? [ML_DSA_87] : void 0,
12034
12224
  issuer,
12035
12225
  audience: opts.audience,
12036
12226
  requiredClaims: ["sub", "exp", "iat"]
@@ -12043,6 +12233,12 @@ async function verifyAccessToken(accessToken, opts) {
12043
12233
  }
12044
12234
  return payload;
12045
12235
  }
12236
+ function boundedJWT(token) {
12237
+ if (token.length > MAX_JWT_BYTES) {
12238
+ throw new Error("JWT exceeds size limit");
12239
+ }
12240
+ return token;
12241
+ }
12046
12242
  function _resetDiscoveryCache() {
12047
12243
  discoveryCache.clear();
12048
12244
  }
@@ -12082,7 +12278,8 @@ function createBrowserAuthCredentialOperations(runtime) {
12082
12278
  } else {
12083
12279
  accessClaims = await verifyAccessToken(tokens.access_token, {
12084
12280
  authority: runtime.issuer,
12085
- audience: runtime.audience ?? runtime.issuer
12281
+ audience: runtime.audience ?? runtime.issuer,
12282
+ requireMLDSA87: runtime.requireMLDSA87
12086
12283
  });
12087
12284
  }
12088
12285
  if (!options.testSession) {
@@ -12091,6 +12288,9 @@ function createBrowserAuthCredentialOperations(runtime) {
12091
12288
  }
12092
12289
  const tokenType = tokens.token_type.toLowerCase();
12093
12290
  const proofKey = options.dpopKey === void 0 ? runtime.dpop : options.dpopKey;
12291
+ if (runtime.requireMLDSA87 && runtime.useDPoP && (!proofKey || (await proofKey.publicJWK()).alg !== "ML-DSA-87")) {
12292
+ throw new Error("DPoP: credentials require an ML-DSA-87 proof key");
12293
+ }
12094
12294
  if (proofKey) {
12095
12295
  if (tokenType !== "dpop") {
12096
12296
  throw new Error(
@@ -12127,7 +12327,8 @@ function createBrowserAuthCredentialOperations(runtime) {
12127
12327
  idClaims = await verifyIdToken(idToken, {
12128
12328
  authority: runtime.issuer,
12129
12329
  clientId: runtime.clientId,
12130
- nonce: options.expectedNonce
12330
+ nonce: options.expectedNonce,
12331
+ requireMLDSA87: runtime.requireMLDSA87
12131
12332
  });
12132
12333
  }
12133
12334
  const accessSubject = accessClaims.sub;
@@ -12388,27 +12589,37 @@ function kekBase64ToBytes(b64) {
12388
12589
  }
12389
12590
  async function unwrapDEK(kekBase64, wrappedDEKBase64) {
12390
12591
  const kek = kekBase64ToBytes(kekBase64);
12391
- const wrapped = kekBase64ToBytes(wrappedDEKBase64);
12392
- if (kek.length !== 16 && kek.length !== 24 && kek.length !== 32) {
12592
+ try {
12593
+ return await unwrapDEKWithKEK(kek, wrappedDEKBase64);
12594
+ } finally {
12595
+ kek.fill(0);
12596
+ }
12597
+ }
12598
+ async function unwrapDEKWithKEK(kek, formatted) {
12599
+ const isV2 = formatted.startsWith("v2.");
12600
+ const encoded = isV2 ? formatted.slice(3) : formatted;
12601
+ if (isV2) {
12602
+ if (kek.length !== 32 || encoded.length !== 80 || /[^A-Za-z0-9_-]/.test(encoded)) {
12603
+ throw new Error("unwrapDEK: invalid v2 wrapped DEK or KEK length");
12604
+ }
12605
+ } else if (kek.length !== 16 && kek.length !== 24 && kek.length !== 32) {
12393
12606
  throw new Error(`unwrapDEK: KEK must be 16/24/32 bytes, got ${kek.length}`);
12394
12607
  }
12608
+ const wrapped = base64ToBytes(encoded);
12395
12609
  if (wrapped.length < 12 + 16) {
12396
12610
  throw new Error("unwrapDEK: wrapped DEK shorter than nonce+tag");
12397
12611
  }
12398
12612
  const nonce = wrapped.slice(0, 12);
12399
- const ciphertext = wrapped.slice(12);
12400
12613
  const key = await crypto.subtle.importKey(
12401
12614
  "raw",
12402
- kek.buffer,
12615
+ kek,
12403
12616
  { name: "AES-GCM" },
12404
12617
  false,
12405
12618
  ["decrypt"]
12406
12619
  );
12407
- const plaintext = await crypto.subtle.decrypt(
12408
- { name: "AES-GCM", iv: nonce.buffer },
12409
- key,
12410
- ciphertext
12411
- );
12620
+ const params = { name: "AES-GCM", iv: nonce.buffer };
12621
+ if (isV2) params.additionalData = new TextEncoder().encode("atol.dek.wrap.v2");
12622
+ const plaintext = await crypto.subtle.decrypt(params, key, wrapped.slice(12));
12412
12623
  return new Uint8Array(plaintext);
12413
12624
  }
12414
12625
 
@@ -12547,15 +12758,16 @@ function createBrowserAuthLifecycleOperations(runtime) {
12547
12758
  if (runtime.destroyed) {
12548
12759
  throw new Error("auth client has been destroyed");
12549
12760
  }
12761
+ if (runtime.requireMLDSA87) await assertMLDSA87VerificationSupport();
12550
12762
  if (runtime.deriveEncryptionKey) {
12551
12763
  runtime.fragmentKEK = extractKEKFromFragment();
12552
12764
  }
12553
- if (runtime.useDPoP && !runtime.responseVault) {
12554
- const initializedDPoP = await createDPoPKeyManager();
12765
+ if (runtime.useDPoP && (!runtime.responseVault || runtime.requireMLDSA87)) {
12766
+ const initializedDPoP = await runtime.createDPoPKey();
12555
12767
  if (runtime.destroyed) {
12556
12768
  throw new Error("auth client has been destroyed");
12557
12769
  }
12558
- runtime.dpop = initializedDPoP;
12770
+ if (!runtime.responseVault) runtime.dpop = initializedDPoP;
12559
12771
  if (!initializedDPoP && runtime.requireDPoP) {
12560
12772
  throw new Error(
12561
12773
  "DPoP is required but WebCrypto could not create a key"
@@ -12814,7 +13026,8 @@ function createBrowserAuthRenewalOperations(runtime) {
12814
13026
  credentialGeneration: expectedGeneration,
12815
13027
  nonce: generateAuthorizationNonce(),
12816
13028
  state: authorizationState(void 0, expectedGeneration),
12817
- createDPoPKey: createDPoPKeyManager
13029
+ createDPoPKey: runtime.createDPoPKey,
13030
+ requireMLDSA87DPoP: runtime.requireMLDSA87 && runtime.useDPoP
12818
13031
  };
12819
13032
  let lastError;
12820
13033
  let callbackGrant;
@@ -13215,27 +13428,6 @@ function randomIV() {
13215
13428
  function zero(bytes) {
13216
13429
  for (let i = 0; i < bytes.length; i++) bytes[i] = 0;
13217
13430
  }
13218
- async function unwrapDEKWithKEK(kek, wrappedDEKBase64) {
13219
- const wrapped = base64ToBytes(wrappedDEKBase64);
13220
- if (wrapped.length < 12 + 16) {
13221
- throw new Error("KEKVault: wrapped DEK shorter than nonce+tag");
13222
- }
13223
- const nonce = wrapped.slice(0, 12);
13224
- const ciphertext = wrapped.slice(12);
13225
- const key = await crypto.subtle.importKey(
13226
- "raw",
13227
- kek.buffer,
13228
- { name: "AES-GCM" },
13229
- false,
13230
- ["decrypt"]
13231
- );
13232
- const plaintext = await crypto.subtle.decrypt(
13233
- { name: "AES-GCM", iv: nonce.buffer },
13234
- key,
13235
- ciphertext
13236
- );
13237
- return new Uint8Array(plaintext);
13238
- }
13239
13431
  var KEKVault = class {
13240
13432
  /**
13241
13433
  * Stash the KEK under a fresh device key, then unwrap the DEK and
@@ -13255,33 +13447,36 @@ var KEKVault = class {
13255
13447
  if (wrappedDEKBase64 === "") {
13256
13448
  throw new Error("KEKVault.provision: wrappedDEK is empty");
13257
13449
  }
13258
- const deviceKey = await crypto.subtle.generateKey(
13259
- { name: "AES-GCM", length: 256 },
13260
- false,
13261
- ["encrypt", "decrypt"]
13262
- );
13263
- const iv = randomIV();
13264
- const ciphertext = new Uint8Array(
13265
- await crypto.subtle.encrypt(
13266
- { name: "AES-GCM", iv: iv.buffer },
13267
- deviceKey,
13268
- kekBytes.buffer
13269
- )
13270
- );
13271
- const dek = await unwrapDEKWithKEK(kekBytes, wrappedDEKBase64);
13272
- const db = await openDB2();
13273
13450
  try {
13274
- await writeRecord(db, {
13275
- deviceKey,
13276
- encryptedKEK: ciphertext,
13277
- iv,
13278
- version: CURRENT_VERSION
13279
- });
13451
+ const deviceKey = await crypto.subtle.generateKey(
13452
+ { name: "AES-GCM", length: 256 },
13453
+ false,
13454
+ ["encrypt", "decrypt"]
13455
+ );
13456
+ const iv = randomIV();
13457
+ const ciphertext = new Uint8Array(
13458
+ await crypto.subtle.encrypt(
13459
+ { name: "AES-GCM", iv: iv.buffer },
13460
+ deviceKey,
13461
+ kekBytes
13462
+ )
13463
+ );
13464
+ const dek = await unwrapDEKWithKEK(kekBytes, wrappedDEKBase64);
13465
+ const db = await openDB2();
13466
+ try {
13467
+ await writeRecord(db, {
13468
+ deviceKey,
13469
+ encryptedKEK: ciphertext,
13470
+ iv,
13471
+ version: CURRENT_VERSION
13472
+ });
13473
+ } finally {
13474
+ db.close();
13475
+ }
13476
+ return dek;
13280
13477
  } finally {
13281
- db.close();
13478
+ zero(kekBytes);
13282
13479
  }
13283
- zero(kekBytes);
13284
- return dek;
13285
13480
  }
13286
13481
  /**
13287
13482
  * Rehydrate the DEK from the vault on silent-auth or page reload.
@@ -13735,6 +13930,6 @@ function permissionKey(action, resource) {
13735
13930
  return `${action}:${resource}`;
13736
13931
  }
13737
13932
 
13738
- export { AtolBrowserAuthCleanupError, AuthorizationCodeExchangeUncertainError, DEFAULT_AUTHORIZE_TIMEOUT_MS, DEFAULT_SILENT_RENEW_RETRY_COUNT, KEKVault, LoginRequiredError, NetworkError, OAuthProtocolError, OrdinaryAuthorizationIntentConflictError, OrdinaryAuthorizationPendingError, RESPONSE_VAULT_PROTOCOL_VERSION, RecoveryAction, _resetDiscoveryCache, backoffDelay, base64ToBytes, bytesToBase64Url, classifyRenewalError, createAtolBrowserAuth, createDPoPKeyManager, createTokenBroadcast, createUserManager, decodeJWTPayload, exchangeCode, extractKEKFromFragment, getAccessToken, getIdToken, getTokenExpiry, hasBroadcastSupport, hasTabLockSupport, kekBase64ToBytes, loadPermissions, parseAtolUser, permissionKey, readAuthorizationCodeCallback, refreshTokenGrant, revokeToken, stringToBase64Url, unwrapDEK, userFromTokenResponse, verifyAccessToken, verifyIdToken, withTabLock };
13933
+ export { AtolBrowserAuthCleanupError, AuthorizationCodeExchangeUncertainError, DEFAULT_AUTHORIZE_TIMEOUT_MS, DEFAULT_SILENT_RENEW_RETRY_COUNT, KEKVault, LoginRequiredError, ML_DSA_87, NetworkError, OAuthProtocolError, OrdinaryAuthorizationIntentConflictError, OrdinaryAuthorizationPendingError, RESPONSE_VAULT_PROTOCOL_VERSION, RecoveryAction, _resetDiscoveryCache, backoffDelay, base64ToBytes, bytesToBase64Url, classifyRenewalError, createAtolBrowserAuth, createDPoPKeyManager, createTokenBroadcast, createUserManager, decodeJWTPayload, exchangeCode, extractKEKFromFragment, getAccessToken, getIdToken, getTokenExpiry, hasBroadcastSupport, hasTabLockSupport, kekBase64ToBytes, loadPermissions, parseAtolUser, permissionKey, readAuthorizationCodeCallback, refreshTokenGrant, revokeToken, stringToBase64Url, unwrapDEK, userFromTokenResponse, verifyAccessToken, verifyIdToken, withTabLock };
13739
13934
  //# sourceMappingURL=index.js.map
13740
13935
  //# sourceMappingURL=index.js.map