@tempoxyz/id 0.0.0-pr-1074.sha-e7b5a6a → 0.0.0-pr-841.sha-a2d20f3

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.
@@ -0,0 +1,16 @@
1
+ import {
2
+ InvalidError,
3
+ create,
4
+ includes,
5
+ verifyRequest
6
+ } from "./chunk-6E4EKDU6.js";
7
+ import "./chunk-DW2VLCLG.js";
8
+ import "./chunk-GSZJQ6GW.js";
9
+ import "./chunk-TEQAH4BN.js";
10
+ import "./chunk-MLKGABMK.js";
11
+ export {
12
+ InvalidError,
13
+ create,
14
+ includes,
15
+ verifyRequest
16
+ };
@@ -0,0 +1,15 @@
1
+ import {
2
+ attach,
3
+ create,
4
+ pending
5
+ } from "./chunk-WUHLRCSO.js";
6
+ import "./chunk-6E4EKDU6.js";
7
+ import "./chunk-DW2VLCLG.js";
8
+ import "./chunk-GSZJQ6GW.js";
9
+ import "./chunk-TEQAH4BN.js";
10
+ import "./chunk-MLKGABMK.js";
11
+ export {
12
+ attach,
13
+ create,
14
+ pending
15
+ };
@@ -1,13 +1,11 @@
1
1
  import {
2
+ decode,
2
3
  env,
3
4
  modules,
4
5
  stringify
5
- } from "./chunk-FHXDPKTL.js";
6
+ } from "./chunk-TEQAH4BN.js";
6
7
  import "./chunk-MLKGABMK.js";
7
8
 
8
- // ../../accounts/src/stores/File.ts
9
- import { Json } from "ox";
10
-
11
9
  // ../../accounts/src/internal/Expiry.ts
12
10
  function expired(entry) {
13
11
  return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now();
@@ -29,7 +27,7 @@ var NodeRequiredError = class extends Error {
29
27
  name = "Store.NodeRequiredError";
30
28
  constructor() {
31
29
  super(
32
- "Invalid runtime: the runtime has no file system modules. Run the program in Node, or use another store."
30
+ "Invalid runtime: the runtime has no file system that persists. Run the program in Node, or use another store."
33
31
  );
34
32
  }
35
33
  };
@@ -51,7 +49,7 @@ function create(path) {
51
49
  if (text === void 0) return {};
52
50
  const entries = (() => {
53
51
  try {
54
- return Json.parse(text);
52
+ return decode(text);
55
53
  } catch {
56
54
  return void 0;
57
55
  }
@@ -67,7 +65,10 @@ function create(path) {
67
65
  }
68
66
  function update(fn, options = {}) {
69
67
  const next = pending.catch(() => void 0).then(async () => {
70
- if (options.skip?.(await read())) return void 0;
68
+ if (options.skip?.(await read())) {
69
+ await sweep(resolve());
70
+ return void 0;
71
+ }
71
72
  const { Fs, Path: Path2 } = node();
72
73
  const target = resolve();
73
74
  await Fs.mkdir(Path2.dirname(target), { mode: 448, recursive: true });
@@ -131,9 +132,20 @@ function create(path) {
131
132
  private: true,
132
133
  async setItem(key, value, options = {}) {
133
134
  stringify(value);
134
- await update((entries) => {
135
- entries[key] = { expiresAt: options.expiresAt, value };
136
- });
135
+ await update(
136
+ (entries) => {
137
+ entries[key] = { expiresAt: options.expiresAt, value };
138
+ },
139
+ // A write of the value and expiry that a live entry holds changes nothing, such as the
140
+ // signed-out mark and the empty session of a second sign-out. The comparison reads the value
141
+ // when the queued write runs, as the write does, so a change after the call persists.
142
+ {
143
+ skip: (entries) => {
144
+ const entry = entries[key];
145
+ return !!entry && !expired(entry) && entry.expiresAt === options.expiresAt && stringify(entry.value) === stringify(value);
146
+ }
147
+ }
148
+ );
137
149
  },
138
150
  // A write that another process overtakes runs `fn` again on the new entries. A write whose lock
139
151
  // another process took over before the rename returns `undefined`. So at most one process
@@ -1,18 +1,19 @@
1
1
  import {
2
2
  InvalidError
3
- } from "./chunk-2T7V6ASK.js";
4
- import "./chunk-U56XI6XP.js";
3
+ } from "./chunk-QI2MEU2T.js";
4
+ import "./chunk-7Q66IVZV.js";
5
+ import "./chunk-DW2VLCLG.js";
5
6
  import {
6
7
  PendingNotFoundError,
7
8
  RequestError,
8
9
  authPath,
9
10
  basePath,
10
- from2 as from,
11
+ from3 as from,
11
12
  key,
12
13
  permissions,
13
14
  siwe
14
- } from "./chunk-J6YQRUKO.js";
15
- import "./chunk-FHXDPKTL.js";
15
+ } from "./chunk-GSZJQ6GW.js";
16
+ import "./chunk-TEQAH4BN.js";
16
17
  import "./chunk-MLKGABMK.js";
17
18
 
18
19
  // ../../accounts/src/internal/handlers/Backend.ts
@@ -98,6 +99,7 @@ var sessionMaxAge = 400 * 24 * 60 * 60;
98
99
  var pendingLimit = 3;
99
100
  var pendingBytes = 3072;
100
101
  var maxLogoutBodySize = 64 * 1024;
102
+ var maxJsonBodySize = 64 * 1024;
101
103
  var relayScript = `(() => {
102
104
  const url = new URL(location.href)
103
105
  const state = url.searchParams.getAll('state').at(-1)
@@ -221,7 +223,9 @@ function create(options) {
221
223
  async function dialogCallback(request) {
222
224
  const refusal = foreign(request);
223
225
  if (refusal) return refusal;
224
- const body = await request.json().catch(() => void 0);
226
+ const json = await readJson(request);
227
+ if (json === tooLarge) return refuseTooLarge();
228
+ const body = json;
225
229
  const url = typeof body?.url === "string" ? URL.parse(body.url) : null;
226
230
  if (!url)
227
231
  return Response.json(
@@ -306,7 +310,9 @@ function create(options) {
306
310
  async function siweChallenge(request, actions) {
307
311
  const refusal = foreign(request, { origins: pageOrigins });
308
312
  if (refusal) return refusal;
309
- const body = await request.json().catch(() => void 0);
313
+ const json = await readJson(request);
314
+ if (json === tooLarge) return refuseTooLarge();
315
+ const body = json;
310
316
  const address = body?.address;
311
317
  const chainId = body?.chainId;
312
318
  if (address !== void 0 && (typeof address !== "string" || !Address.validate(address, { strict: false })))
@@ -356,7 +362,9 @@ function create(options) {
356
362
  async function siweVerify(request, actions) {
357
363
  const refusal = foreign(request, { origins: pageOrigins });
358
364
  if (refusal) return refusal;
359
- const body = await request.json().catch(() => void 0);
365
+ const json = await readJson(request);
366
+ if (json === tooLarge) return refuseTooLarge();
367
+ const body = json;
360
368
  const { address, keyAuthorization, message, signature } = body ?? {};
361
369
  const proof = (() => {
362
370
  if (typeof signature === "string" && Hex.validate(signature))
@@ -728,7 +736,9 @@ function refused(refusal, options) {
728
736
  error_uri: refusal.uri,
729
737
  field: refusal.field,
730
738
  meta: refusal.meta,
731
- reason: refusal.reason
739
+ reason: refusal.reason,
740
+ // The page's `Accounts.RequestError` keeps `signedIn`, such as for a refused code exchange.
741
+ signed_in: refusal.signedIn || void 0
732
742
  },
733
743
  { headers: options.headers, status: callbackStatus(refusal) }
734
744
  );
@@ -794,6 +804,25 @@ function withError(path, options) {
794
804
  url.searchParams.set("error", options.error);
795
805
  return `${url.pathname}${url.search}${url.hash}`;
796
806
  }
807
+ var tooLarge = /* @__PURE__ */ Symbol("tooLarge");
808
+ async function readJson(request) {
809
+ const text = await read(request, { limit: maxJsonBodySize }).catch(() => "");
810
+ if (text === void 0) return tooLarge;
811
+ try {
812
+ return JSON.parse(text);
813
+ } catch {
814
+ return void 0;
815
+ }
816
+ }
817
+ function refuseTooLarge() {
818
+ return Response.json(
819
+ {
820
+ error: "invalid_request",
821
+ error_description: "Request too large: the body exceeds 64 KiB. Send only the fields that the route reads."
822
+ },
823
+ { status: 413 }
824
+ );
825
+ }
797
826
  async function read(request, options) {
798
827
  const { limit } = options;
799
828
  if (Number(request.headers.get("content-length")) > limit) {
@@ -4,9 +4,9 @@ import {
4
4
  machines,
5
5
  prompt,
6
6
  waiting
7
- } from "./chunk-AOOG6TLA.js";
8
- import "./chunk-J6YQRUKO.js";
9
- import "./chunk-FHXDPKTL.js";
7
+ } from "./chunk-YQLC24LT.js";
8
+ import "./chunk-GSZJQ6GW.js";
9
+ import "./chunk-TEQAH4BN.js";
10
10
  import "./chunk-MLKGABMK.js";
11
11
  export {
12
12
  create,
@@ -0,0 +1,272 @@
1
+ import {
2
+ create
3
+ } from "./chunk-DW2VLCLG.js";
4
+ import {
5
+ RequestError,
6
+ algorithms
7
+ } from "./chunk-GSZJQ6GW.js";
8
+
9
+ // ../../accounts/src/AccessToken.ts
10
+ import {
11
+ calculateJwkThumbprint,
12
+ EmbeddedJWK,
13
+ errors,
14
+ jwtVerify
15
+ } from "jose";
16
+ import { Address, Base64, Bytes, Hash } from "ox";
17
+ var InvalidError = class extends Error {
18
+ name = "AccessToken.InvalidError";
19
+ constructor(options = {}) {
20
+ super(
21
+ "Invalid access token: the token does not verify, has expired, or names an app that the API does not allow. Request a new access token.",
22
+ { cause: options.cause }
23
+ );
24
+ }
25
+ };
26
+ var accessKeyRequestType = "access-key-request+jwt";
27
+ var proofMaxAge = 300;
28
+ var proofSkew = 60;
29
+ var refusals = [
30
+ errors.JOSEAlgNotAllowed,
31
+ errors.JOSENotSupported,
32
+ errors.JWKSMultipleMatchingKeys,
33
+ errors.JWKSNoMatchingKey,
34
+ errors.JWSInvalid,
35
+ errors.JWSSignatureVerificationFailed,
36
+ errors.JWTClaimValidationFailed,
37
+ errors.JWTExpired,
38
+ errors.JWTInvalid
39
+ ];
40
+ var screeningStates = ["blocked", "clear", "exit_only", "pending"];
41
+ function create2(auth, options = {}) {
42
+ const clientIds = options.clientIds ?? (auth.clientId ? [auth.clientId] : void 0);
43
+ if (!clientIds)
44
+ throw new Error(
45
+ "Missing `clientIds`: the configuration names no `clientId`. Name the client IDs, or set `clientId`."
46
+ );
47
+ const issuer = new URL(options.issuer ?? auth.url).origin;
48
+ if (clientIds === "any" && !options.audience)
49
+ throw new Error(
50
+ "Invalid `clientIds`: `'any'` accepts every app's token for the issuer's origin. Set `audience` to the API's registered resource, or name the client IDs."
51
+ );
52
+ const audience = options.audience ?? issuer;
53
+ const own = [audience, `${issuer}/oauth2/userinfo`];
54
+ const keys = create(auth, {
55
+ maxAge: options.maxAge,
56
+ timeout: options.timeout
57
+ });
58
+ async function check(token, options2) {
59
+ const { payload } = await jwtVerify(token, keys, {
60
+ algorithms: ["RS256"],
61
+ audience,
62
+ issuer,
63
+ requiredClaims: [...options2.requiredClaims],
64
+ typ: options2.typ
65
+ }).catch((error) => {
66
+ if (refusals.some((refusal) => error instanceof refusal))
67
+ throw new InvalidError({ cause: error });
68
+ throw unavailable(error);
69
+ });
70
+ return payload;
71
+ }
72
+ return {
73
+ async verify(verifyOptions) {
74
+ const payload = await check(verifyOptions.accessToken, {
75
+ requiredClaims: ["client_id", "exp", "sub"],
76
+ typ: "at+jwt"
77
+ });
78
+ const audiences = typeof payload.aud === "string" ? [payload.aud] : payload.aud ?? [];
79
+ if (audiences.some((entry) => !own.includes(entry)))
80
+ throw new InvalidError();
81
+ if (typeof payload.client_id !== "string" || clientIds !== "any" && !clientIds.includes(payload.client_id))
82
+ throw new InvalidError();
83
+ const boundTo = thumbprint(payload.cnf);
84
+ if (boundTo === void 0 && verifyOptions.dpop?.scheme?.toLowerCase() === "dpop")
85
+ throw new InvalidError({
86
+ cause: new Error(
87
+ "Invalid authorization scheme: no DPoP key binds the token. Send the token with the Bearer scheme."
88
+ )
89
+ });
90
+ const accepted = boundTo === void 0 ? void 0 : await proof({
91
+ accessToken: verifyOptions.accessToken,
92
+ boundTo,
93
+ dpop: verifyOptions.dpop
94
+ });
95
+ return {
96
+ accessKeys: accessKeys(payload.access_keys),
97
+ accounts: accounts(payload),
98
+ apiAccessKeys: accessKeys(payload.api_access_keys),
99
+ boundTo,
100
+ clientId: payload.client_id,
101
+ compliance: compliance(payload.compliance),
102
+ expiresAt: payload.exp * 1e3,
103
+ issuedAt: typeof payload.iat === "number" ? payload.iat * 1e3 : void 0,
104
+ proof: accepted,
105
+ scope: typeof payload.scope === "string" ? payload.scope.split(" ").filter(Boolean) : [],
106
+ userId: payload.sub
107
+ };
108
+ },
109
+ async verifyAccessKeyRequest(verifyOptions) {
110
+ const payload = await check(verifyOptions.token, {
111
+ requiredClaims: ["chain_id", "client_id", "exp", "jti", "nonce"],
112
+ typ: accessKeyRequestType
113
+ });
114
+ const audiences = typeof payload.aud === "string" ? [payload.aud] : payload.aud ?? [];
115
+ if (audiences.length !== 1 || audiences[0] !== audience)
116
+ throw new InvalidError();
117
+ const { chain_id, client_id, jti, nonce } = payload;
118
+ if (typeof chain_id !== "number" || typeof client_id !== "string" || typeof jti !== "string" || typeof nonce !== "string")
119
+ throw new InvalidError();
120
+ return {
121
+ chainId: chain_id,
122
+ clientId: client_id,
123
+ expiresAt: payload.exp * 1e3,
124
+ id: jti,
125
+ nonce
126
+ };
127
+ }
128
+ };
129
+ }
130
+ function includes(token, options) {
131
+ if (!Address.validate(options.address, { strict: false })) return false;
132
+ return token.accounts.some(
133
+ (account) => Address.isEqual(account, options.address)
134
+ );
135
+ }
136
+ async function verifyRequest(verifier, options) {
137
+ const { request } = options;
138
+ const [scheme, accessToken] = (request.headers.get("authorization") ?? "").split(" ");
139
+ if (!scheme || !accessToken) return void 0;
140
+ if (!["bearer", "dpop"].includes(scheme.toLowerCase())) return void 0;
141
+ const url = (() => {
142
+ if (typeof options.url === "function") return options.url(request);
143
+ if (options.url === void 0) return request.url;
144
+ const { pathname, search } = new URL(request.url);
145
+ return `${new URL(options.url).origin}${pathname}${search}`;
146
+ })();
147
+ try {
148
+ return await verifier.verify({
149
+ accessToken,
150
+ dpop: {
151
+ method: request.method,
152
+ proof: request.headers.get("dpop"),
153
+ scheme,
154
+ url
155
+ }
156
+ });
157
+ } catch (error) {
158
+ if (error instanceof InvalidError) return void 0;
159
+ throw error;
160
+ }
161
+ }
162
+ function accessKeys(claim) {
163
+ if (!Array.isArray(claim)) return [];
164
+ return claim.flatMap((value) => {
165
+ if (typeof value !== "object" || value === null) return [];
166
+ const entry = value;
167
+ const { account, address, chain_id } = entry;
168
+ if (typeof account !== "string" || typeof address !== "string" || typeof chain_id !== "number" || !Address.validate(account, { strict: false }) || !Address.validate(address, { strict: false }))
169
+ return [];
170
+ return [
171
+ {
172
+ account: Address.checksum(account),
173
+ address: Address.checksum(address),
174
+ chainId: chain_id
175
+ }
176
+ ];
177
+ });
178
+ }
179
+ function accounts(payload) {
180
+ const { tempo_accounts } = payload;
181
+ if (!Array.isArray(tempo_accounts)) return [];
182
+ return tempo_accounts.filter(
183
+ (value) => typeof value === "string" && Address.validate(value, { strict: false })
184
+ );
185
+ }
186
+ function compliance(claim) {
187
+ if (typeof claim !== "object" || claim === null || Array.isArray(claim))
188
+ return {};
189
+ const entries = Object.entries(claim).flatMap(
190
+ ([address, value]) => {
191
+ const state = screeningStates.find((entry) => entry === value);
192
+ if (!state || !Address.validate(address, { strict: false })) return [];
193
+ return [[Address.checksum(address), state]];
194
+ }
195
+ );
196
+ const counts = /* @__PURE__ */ new Map();
197
+ for (const [address] of entries)
198
+ counts.set(address, (counts.get(address) ?? 0) + 1);
199
+ return Object.fromEntries(
200
+ entries.filter(([address]) => counts.get(address) === 1)
201
+ );
202
+ }
203
+ async function proof(options) {
204
+ const { accessToken, boundTo, dpop } = options;
205
+ if (!dpop?.proof)
206
+ throw new InvalidError({
207
+ cause: new Error(
208
+ "Missing DPoP proof: a DPoP key binds the token. Send the request with the DPoP proof."
209
+ )
210
+ });
211
+ if (dpop.scheme?.toLowerCase() !== "dpop")
212
+ throw new InvalidError({
213
+ cause: new Error(
214
+ "Invalid authorization scheme: a DPoP key binds the token. Send the token with the DPoP scheme."
215
+ )
216
+ });
217
+ const { payload, protectedHeader } = await jwtVerify(
218
+ dpop.proof,
219
+ EmbeddedJWK,
220
+ {
221
+ algorithms: [...algorithms],
222
+ clockTolerance: proofSkew,
223
+ maxTokenAge: proofMaxAge,
224
+ requiredClaims: ["ath", "htm", "htu", "iat", "jti"],
225
+ typ: "dpop+jwt"
226
+ }
227
+ ).catch((error) => {
228
+ throw new InvalidError({ cause: error });
229
+ });
230
+ const url = (() => {
231
+ try {
232
+ return new URL(dpop.url);
233
+ } catch (error) {
234
+ throw new InvalidError({ cause: error });
235
+ }
236
+ })();
237
+ const ath = Base64.fromBytes(Hash.sha256(Bytes.fromString(accessToken)), {
238
+ pad: false,
239
+ url: true
240
+ });
241
+ if (payload.ath !== ath || payload.htm !== dpop.method || payload.htu !== `${url.origin}${url.pathname}` || await calculateJwkThumbprint(protectedHeader.jwk) !== boundTo)
242
+ throw new InvalidError({
243
+ cause: new Error(
244
+ "Invalid DPoP proof: the proof names another request, access token, or key. Send a new proof for the request."
245
+ )
246
+ });
247
+ return {
248
+ // jose accepts the proof until its age, in whole seconds, exceeds the window and the tolerance.
249
+ expiresAt: (payload.iat + proofMaxAge + proofSkew + 1) * 1e3,
250
+ id: String(payload.jti)
251
+ };
252
+ }
253
+ function thumbprint(claim) {
254
+ if (typeof claim !== "object" || claim === null) return void 0;
255
+ const { jkt } = claim;
256
+ return typeof jkt === "string" ? jkt : void 0;
257
+ }
258
+ function unavailable(error) {
259
+ return new RequestError({
260
+ cause: error,
261
+ code: "temporarily_unavailable",
262
+ message: "Key set unavailable: the request for the issuer's signing keys failed. Retry later.",
263
+ status: 0
264
+ });
265
+ }
266
+
267
+ export {
268
+ InvalidError,
269
+ create2 as create,
270
+ includes,
271
+ verifyRequest
272
+ };
@@ -3,6 +3,7 @@ import {
3
3
  RedirectUriRequiredError,
4
4
  RequestError,
5
5
  SignerRequiredError,
6
+ answered,
6
7
  authorization,
7
8
  authorizeUrl,
8
9
  challengeSignature,
@@ -11,7 +12,7 @@ import {
11
12
  error,
12
13
  error2,
13
14
  from,
14
- get,
15
+ get2 as get,
15
16
  json,
16
17
  own,
17
18
  revoke,
@@ -20,7 +21,7 @@ import {
20
21
  tokens,
21
22
  url,
22
23
  user
23
- } from "./chunk-J6YQRUKO.js";
24
+ } from "./chunk-GSZJQ6GW.js";
24
25
  import {
25
26
  __export
26
27
  } from "./chunk-MLKGABMK.js";
@@ -48,6 +49,7 @@ function save(auth, pending) {
48
49
  chainId: pending.chainId,
49
50
  clientId: pending.clientId,
50
51
  configured: configuredOf(auth),
52
+ issuer: pending.issuer,
51
53
  redirectUri: pending.redirectUri,
52
54
  state: pending.state
53
55
  })
@@ -64,7 +66,8 @@ function started(auth, options) {
64
66
  const value = storage.getItem(markKey);
65
67
  if (!value) return void 0;
66
68
  const mark = JSON.parse(value);
67
- const own2 = mark.configured === void 0 ? owns(auth, mark) : owns(auth, { clientId: mark.clientId }) && mark.configured === configuredOf(auth);
69
+ if (mark.issuer === void 0) storage.removeItem(markKey);
70
+ const own2 = mark.configured === void 0 ? owns(auth, mark) : owns(auth, { clientId: mark.clientId, issuer: mark.issuer }) && mark.configured === configuredOf(auth);
68
71
  if (!own2 || mark.state !== options.state) return void 0;
69
72
  storage.removeItem(markKey);
70
73
  return mark;
@@ -79,6 +82,7 @@ function take(auth) {
79
82
  const value = storage.getItem(storageKey);
80
83
  if (!value) return void 0;
81
84
  const ticket2 = JSON.parse(value);
85
+ if (ticket2.issuer === void 0) storage.removeItem(storageKey);
82
86
  if (!owns(auth, ticket2)) return void 0;
83
87
  storage.removeItem(storageKey);
84
88
  return ticket2;
@@ -87,13 +91,17 @@ function take(auth) {
87
91
  }
88
92
  }
89
93
  function owns(auth, pending) {
90
- return (pending.clientId ?? auth.clientId) === auth.clientId && (pending.chainId ?? auth.chainId) === auth.chainId;
94
+ return (pending.clientId ?? auth.clientId) === auth.clientId && (pending.chainId ?? auth.chainId) === auth.chainId && pending.issuer === issuerOf(auth);
95
+ }
96
+ function issuerOf(auth) {
97
+ return new URL(auth.url).origin;
91
98
  }
92
99
  function ticket(pending) {
93
100
  return {
94
101
  accessKey: pending.accessKey !== false,
95
102
  chainId: pending.chainId,
96
103
  clientId: pending.clientId,
104
+ issuer: pending.issuer,
97
105
  redirectUri: pending.redirectUri,
98
106
  state: pending.state,
99
107
  verifier: pending.verifier
@@ -119,7 +127,7 @@ var storageKey = "tempo-id:redirect";
119
127
 
120
128
  // ../../accounts/src/actions/redirect.ts
121
129
  function complete(auth, options = {}) {
122
- const owner = `${auth.clientId}:${auth.chainId}`;
130
+ const owner = `${auth.clientId}:${auth.chainId}:${issuerOf(auth)}`;
123
131
  const store = get(auth.store);
124
132
  let results = completed.get(store);
125
133
  if (!results) completed.set(store, results = /* @__PURE__ */ new Map());
@@ -144,17 +152,25 @@ function complete(auth, options = {}) {
144
152
  const value = await store.getItem(key);
145
153
  if (value != null) return { key, taken: false, value };
146
154
  }
147
- const legacy = await store.getItem(legacyStoreKey);
148
- if (legacy?.state === state)
149
- return { key: legacyStoreKey, taken: false, value: legacy };
155
+ const legacy2 = await store.getItem(legacyStoreKey);
156
+ if (legacy2?.state === state)
157
+ return { key: legacyStoreKey, taken: false, value: legacy2 };
150
158
  return void 0;
151
- })();
152
- const stored = entry?.value;
153
- const redirectUri = stored?.redirectUri ?? ticket2?.redirectUri ?? started2?.redirectUri ?? auth.redirectUri ?? url2.origin;
159
+ })().then(async (found) => {
160
+ if (found === void 0 || !outdated(auth, found.value)) return found;
161
+ if (!found.taken) await store.removeItem(found.key);
162
+ return found;
163
+ }).catch(async (error4) => {
164
+ await discard(auth, early);
165
+ throw error4;
166
+ });
167
+ const legacy = entry !== void 0 && outdated(auth, entry.value);
168
+ const stored = legacy ? void 0 : entry?.value;
169
+ const redirectUri = entry?.value.redirectUri ?? ticket2?.redirectUri ?? started2?.redirectUri ?? auth.redirectUri ?? url2.origin;
154
170
  const registered = new URL(redirectUri).searchParams;
155
171
  if (stored != null && !owns(auth, stored)) return void 0;
156
172
  const ours = stored != null && state === stored.state;
157
- const mine = ours || started2 !== void 0 || ticket2 !== void 0 && ticket2.state === state;
173
+ const mine = ours || legacy || started2 !== void 0 || ticket2 !== void 0 && ticket2.state === state;
158
174
  const removed = ours && entry && !entry.taken ? (async () => store.removeItem(entry.key))() : void 0;
159
175
  removed?.catch(() => void 0);
160
176
  const callback = [
@@ -185,6 +201,15 @@ function complete(auth, options = {}) {
185
201
  }
186
202
  if (!url2.searchParams.has("code") || !stored) {
187
203
  await removed;
204
+ if (legacy && url2.searchParams.has("code")) {
205
+ await discard(auth, early);
206
+ throw new RequestError({
207
+ code: "invalid_request",
208
+ field: "state",
209
+ message: "Expired sign-in: the redirect started with an earlier version of the package, which names no Tempo ID deployment. Start sign-in again.",
210
+ status: 400
211
+ });
212
+ }
188
213
  if (started2 !== void 0 && stored == null && url2.searchParams.has("code"))
189
214
  throw new RequestError({
190
215
  code: "invalid_request",
@@ -206,10 +231,13 @@ function complete(auth, options = {}) {
206
231
  status: 400
207
232
  });
208
233
  }
209
- const [body] = await Promise.all([
210
- ours && early ? early : redeem(auth, { pending: stored, url: url2 }),
211
- removed
212
- ]);
234
+ const exchange = ours && early ? early : redeem(auth, { pending: stored, url: url2 });
235
+ exchange.catch(() => void 0);
236
+ await removed?.catch(async (error4) => {
237
+ await discard(auth, exchange);
238
+ throw error4;
239
+ });
240
+ const body = await exchange;
213
241
  return await finish_revoke(auth, {
214
242
  accessKey: options.accessKey,
215
243
  body,
@@ -258,6 +286,13 @@ function handleResult(options) {
258
286
  pending: options.pending
259
287
  });
260
288
  }
289
+ async function discard(auth, exchange) {
290
+ const body = await exchange?.catch(() => void 0);
291
+ if (body?.refresh_token)
292
+ await revoke(auth, { refreshToken: body.refresh_token }).catch(
293
+ () => void 0
294
+ );
295
+ }
261
296
  async function redeem(auth, options) {
262
297
  const { redirectUri, state, verifier } = options.pending;
263
298
  const { url: url2 } = options;
@@ -272,7 +307,10 @@ async function redeem(auth, options) {
272
307
  message: "Missing `code` in the callback URL. Start sign-in again.",
273
308
  status: 400
274
309
  });
275
- return await token(auth, {
310
+ const config = answered(auth, {
311
+ message: "The code exchange received no response. Check the connection, and sign in again."
312
+ });
313
+ return await token(config, {
276
314
  code,
277
315
  code_verifier: verifier,
278
316
  grant_type: "authorization_code",
@@ -290,7 +328,9 @@ async function redeem(auth, options) {
290
328
  throw new RequestError({
291
329
  cause: error3,
292
330
  code: "server_error",
293
- message: "The code exchange received no response. Check the connection, and sign in again.",
331
+ // The message can reach the browser, as a backend's refusal, so the fault's own text, which can
332
+ // name a signing service or an access key, stays in `cause`.
333
+ message: "The code exchange failed before its request. Check the client assertion and the DPoP key, and sign in again.",
294
334
  signedIn: true,
295
335
  status: 0
296
336
  });
@@ -329,6 +369,7 @@ function finish(options) {
329
369
  chainId: _chainId,
330
370
  challenge: challenged,
331
371
  clientId: _clientId,
372
+ issuer: _issuer,
332
373
  key: earlier,
333
374
  redirectUri: _redirectUri,
334
375
  state: _state,
@@ -455,6 +496,9 @@ var written = /* @__PURE__ */ new WeakMap();
455
496
  var indexKey = "tempo-id:redirects";
456
497
  var pendingLifetime = 60 * 60 * 1e3;
457
498
  var legacyStoreKey = "tempo-id:redirect";
499
+ function outdated(auth, stored) {
500
+ return stored.issuer === void 0 && owns(auth, { ...stored, issuer: issuerOf(auth) });
501
+ }
458
502
  function storeKey(state) {
459
503
  return `tempo-id:redirect:${state}`;
460
504
  }