@finueva/auth 0.32.0 → 0.34.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/server.js CHANGED
@@ -41,26 +41,59 @@ const messages = {
41
41
  organization_closure_confirmation_mismatch: "The confirmation does not match the organization.",
42
42
  organization_closure_cancellation_ended: "The closure cancellation period has ended.",
43
43
  ceremony_return_refused: "The return address is not registered for this application.",
44
- password_sign_in_required: "A password sign-in method is required for this passkey change."
44
+ password_sign_in_required: "A password sign-in method is required for this passkey change.",
45
+ account_deletion_pending: "This account is scheduled for deletion.",
46
+ account_restore_unavailable: "The restore ticket or link is used or expired, or the account is not scheduled for deletion."
45
47
  };
46
48
  var AuthError = class extends Error {
47
49
  code;
48
50
  status;
49
51
  retryAfterSeconds;
50
- constructor(code, status, retryAfterSeconds) {
52
+ accountDeletion;
53
+ constructor(code, status, retryAfterSeconds, details) {
51
54
  super(messages[code]);
52
55
  this.name = "AuthError";
53
56
  this.code = code;
54
57
  this.status = status;
55
58
  this.retryAfterSeconds = retryAfterSeconds;
59
+ if (details?.accountDeletion) this.accountDeletion = details.accountDeletion;
56
60
  }
57
61
  };
58
62
  //#endregion
63
+ //#region src/account-deletion.ts
64
+ function isObject$2(value) {
65
+ return typeof value === "object" && value !== null && !Array.isArray(value);
66
+ }
67
+ function authorityUnavailable$1() {
68
+ return new AuthError("identity_authority_unavailable", 503);
69
+ }
70
+ const tokenPattern = /^[A-Za-z0-9_-]{43}$(?![\s\S])/;
71
+ function isoDate(value) {
72
+ if (typeof value !== "string") throw authorityUnavailable$1();
73
+ const parsed = new Date(value);
74
+ if (!Number.isFinite(parsed.getTime()) || parsed.toISOString() !== value) throw authorityUnavailable$1();
75
+ return parsed;
76
+ }
77
+ function accountDeletionPending(value, status) {
78
+ if (status !== 403 || !isObject$2(value) || value.code !== "ACCOUNT_DELETION_PENDING") return null;
79
+ let deleteAfter;
80
+ try {
81
+ deleteAfter = isoDate(value.deleteAfter);
82
+ } catch {
83
+ return null;
84
+ }
85
+ const restoreTicket = typeof value.restoreTicket === "string" && tokenPattern.test(value.restoreTicket) ? value.restoreTicket : null;
86
+ return {
87
+ deleteAfter,
88
+ restoreTicket
89
+ };
90
+ }
91
+ //#endregion
59
92
  //#region src/shared.ts
60
93
  const DRIVE_CREDENTIAL_LIFETIME_SECONDS = 840;
61
94
  const id$3 = /^[A-Za-z0-9_-]{1,128}$/;
62
95
  const email = /^[^\s@]+@[^\s@]+$/;
63
- const MAX_SOCIAL_ID_TOKEN_BYTES = 16 * 1024;
96
+ const MAX_SOCIAL_ID_TOKEN_BYTES = 16384;
64
97
  function normalizeEmail(value) {
65
98
  if (typeof value !== "string") throw new TypeError("email is invalid");
66
99
  const normalized = value.trim().toLowerCase();
@@ -70,7 +103,9 @@ function normalizeEmail(value) {
70
103
  function normalizeSocialIdTokenInput(value) {
71
104
  if (!isObject$1(value)) throw new TypeError("social ID token input is invalid");
72
105
  const keys = Object.keys(value);
73
- if (keys.length !== 3 && keys.length !== 4 || keys.some((key) => key !== "provider" && key !== "idToken" && key !== "nonce" && key !== "signUp") || value.provider !== "google" && value.provider !== "apple" || typeof value.signUp !== "boolean" || typeof value.idToken !== "string" || value.idToken.length < 1 || new TextEncoder().encode(value.idToken).byteLength > MAX_SOCIAL_ID_TOKEN_BYTES || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value.idToken) || value.nonce !== void 0 && (typeof value.nonce !== "string" || value.nonce.length < 1 || value.nonce.length > 256 || !/^[\x20-\x7e]+$/.test(value.nonce))) throw new TypeError("social ID token input is invalid");
106
+ if (keys.length !== 3 && keys.length !== 4 || keys.some((key) => {
107
+ return key !== "provider" && key !== "idToken" && key !== "nonce" && key !== "signUp";
108
+ }) || value.provider !== "google" && value.provider !== "apple" || typeof value.signUp !== "boolean" || typeof value.idToken !== "string" || value.idToken.length < 1 || new TextEncoder().encode(value.idToken).byteLength > MAX_SOCIAL_ID_TOKEN_BYTES || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value.idToken) || value.nonce !== void 0 && (typeof value.nonce !== "string" || value.nonce.length < 1 || value.nonce.length > 256 || !/^[\x20-\x7e]+$/.test(value.nonce))) throw new TypeError("social ID token input is invalid");
74
109
  return {
75
110
  provider: value.provider,
76
111
  idToken: value.idToken,
@@ -88,7 +123,15 @@ function socialIdTokenRequest(value) {
88
123
  requestSignUp: value.signUp
89
124
  };
90
125
  }
91
- function normalizeOrigin(value, name) {
126
+ function isPrivateIpv4(hostname) {
127
+ const parts = hostname.split(".").map(Number);
128
+ if (parts.length !== 4 || parts.some((part) => {
129
+ return !Number.isInteger(part) || part < 0 || part > 255;
130
+ })) return false;
131
+ const [first, second] = parts;
132
+ return first === 10 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168;
133
+ }
134
+ function normalizeOrigin(value, name, allowPrivateNetwork = false) {
92
135
  if (value.length === 0 || value.length > 2048 || /[^\x20-\x7e]/.test(value)) throw new TypeError(`${name} must be an ASCII HTTP origin`);
93
136
  let url;
94
137
  try {
@@ -97,7 +140,7 @@ function normalizeOrigin(value, name) {
97
140
  throw new TypeError(`${name} must be an ASCII HTTP origin`);
98
141
  }
99
142
  const local = url.hostname === "localhost" || url.hostname.endsWith(".localhost") || url.hostname === "127.0.0.1";
100
- if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.pathname !== "/" || url.search || url.hash || url.origin !== value) throw new TypeError(`${name} must be an ASCII HTTP origin`);
143
+ if (url.protocol !== "https:" && !((local || allowPrivateNetwork && isPrivateIpv4(url.hostname)) && url.protocol === "http:") || url.username || url.password || url.pathname !== "/" || url.search || url.hash || url.origin !== value) throw new TypeError(`${name} must be an ASCII HTTP origin`);
101
144
  return url.origin;
102
145
  }
103
146
  function normalizeTimeout(value) {
@@ -124,7 +167,7 @@ function normalizeSession(value) {
124
167
  };
125
168
  }
126
169
  function normalizeDriveCredential(value, now) {
127
- if (!isObject$1(value) || value.tokenType !== "Bearer" || value.expiresIn !== DRIVE_CREDENTIAL_LIFETIME_SECONDS || typeof value.token !== "string" || value.token.length === 0 || new TextEncoder().encode(`Bearer ${value.token}`).byteLength > 16 * 1024) throw authorityUnavailable();
170
+ if (!isObject$1(value) || value.tokenType !== "Bearer" || value.expiresIn !== DRIVE_CREDENTIAL_LIFETIME_SECONDS || typeof value.token !== "string" || value.token.length === 0 || new TextEncoder().encode(`Bearer ${value.token}`).byteLength > 16384) throw authorityUnavailable();
128
171
  return {
129
172
  tokenType: "Bearer",
130
173
  token: value.token,
@@ -133,7 +176,9 @@ function normalizeDriveCredential(value, now) {
133
176
  }
134
177
  function normalizeOrganizationPageInput(value) {
135
178
  if (value === void 0) return new URLSearchParams();
136
- if (!isObject$1(value) || Object.keys(value).some((key) => key !== "limit" && key !== "cursor")) throw new AuthError("invalid_request", 400);
179
+ if (!isObject$1(value) || Object.keys(value).some((key) => {
180
+ return key !== "limit" && key !== "cursor";
181
+ })) throw new AuthError("invalid_request", 400);
137
182
  const input = value;
138
183
  const query = new URLSearchParams();
139
184
  if (input.limit !== void 0) {
@@ -148,17 +193,23 @@ function normalizeOrganizationPageInput(value) {
148
193
  }
149
194
  function normalizeOrganizationMemberPageInput(value) {
150
195
  if (value === void 0) return new URLSearchParams();
151
- if (!isObject$1(value) || Object.keys(value).some((key) => ![
152
- "limit",
153
- "cursor",
154
- "search"
155
- ].includes(key))) throw new AuthError("invalid_request", 400);
196
+ if (!isObject$1(value) || Object.keys(value).some((key) => {
197
+ return ![
198
+ "limit",
199
+ "cursor",
200
+ "search"
201
+ ].includes(key);
202
+ })) throw new AuthError("invalid_request", 400);
156
203
  const { search, ...page } = value;
157
204
  const query = normalizeOrganizationPageInput(page);
158
205
  if (search !== void 0) {
159
206
  if (typeof search !== "string") throw new AuthError("invalid_request", 400);
160
- const prefix = search.trim().replace(/[A-Z]/g, (character) => character.toLowerCase());
161
- if (!prefix || prefix.length > 128 || Array.from(prefix).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) throw new AuthError("invalid_request", 400);
207
+ const prefix = search.trim().replace(/[A-Z]/g, (character) => {
208
+ return character.toLowerCase();
209
+ });
210
+ if (!prefix || prefix.length > 128 || Array.from(prefix).some((character) => {
211
+ return character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127;
212
+ })) throw new AuthError("invalid_request", 400);
162
213
  query.set("search", prefix);
163
214
  }
164
215
  return query;
@@ -278,7 +329,9 @@ function normalizeOrganizationMemberInvitationCreationInput(value) {
278
329
  throw new AuthError("invalid_request", 400);
279
330
  }
280
331
  if (new TextEncoder().encode(normalizedEmail).byteLength > 320 || !boundedString(value.idempotencyKey, 255) || value.teamIds !== void 0 && (!Array.isArray(value.teamIds) || value.teamIds.length > 100)) throw new AuthError("invalid_request", 400);
281
- const teamIds = value.teamIds?.map((teamId) => normalizeIdInput(teamId));
332
+ const teamIds = value.teamIds?.map((teamId) => {
333
+ return normalizeIdInput(teamId);
334
+ });
282
335
  if (teamIds && new Set(teamIds).size !== teamIds.length) throw new AuthError("invalid_request", 400);
283
336
  return {
284
337
  email: normalizedEmail,
@@ -345,7 +398,9 @@ function normalizeOrganizations(value) {
345
398
  exact$8(value, ["nextCursor", "organizations"]);
346
399
  if (!Array.isArray(value.organizations) || value.organizations.length > 100) throw authorityUnavailable();
347
400
  return {
348
- organizations: unique(value.organizations.map(normalizeOrganization), (item) => item.id),
401
+ organizations: unique(value.organizations.map(normalizeOrganization), (item) => {
402
+ return item.id;
403
+ }),
349
404
  nextCursor: nullableCursor(value.nextCursor)
350
405
  };
351
406
  }
@@ -366,7 +421,11 @@ function normalizeOrganizationMembers(value) {
366
421
  "userId"
367
422
  ]);
368
423
  if (!isId(member.id) || !isId(member.userId) || !boundedString(member.name, 255) || typeof member.email !== "string" || member.email.length > 320 || !email.test(member.email) || !role(member.role) || typeof member.owner !== "boolean" || !Array.isArray(member.teamIds) || member.teamIds.length > 100) throw authorityUnavailable();
369
- const teamIds = unique(member.teamIds.map((teamId) => normalizeResponseId(teamId)), (item) => item);
424
+ const teamIds = unique(member.teamIds.map((teamId) => {
425
+ return normalizeResponseId(teamId);
426
+ }), (item) => {
427
+ return item;
428
+ });
370
429
  return {
371
430
  id: member.id,
372
431
  userId: member.userId,
@@ -378,7 +437,9 @@ function normalizeOrganizationMembers(value) {
378
437
  joinedAt: responseDate(member.joinedAt),
379
438
  teamIds
380
439
  };
381
- }), (item) => item.id),
440
+ }), (item) => {
441
+ return item.id;
442
+ }),
382
443
  nextCursor: nullableCursor(value.nextCursor)
383
444
  };
384
445
  }
@@ -400,7 +461,9 @@ function normalizeOrganizationTeams(value) {
400
461
  category: team.category,
401
462
  createdAt: responseDate(team.createdAt)
402
463
  };
403
- }), (item) => item.id),
464
+ }), (item) => {
465
+ return item.id;
466
+ }),
404
467
  nextCursor: nullableCursor(value.nextCursor)
405
468
  };
406
469
  }
@@ -408,7 +471,11 @@ function normalizeOrganizationTeamMembers(value) {
408
471
  exact$8(value, ["memberIds", "nextCursor"]);
409
472
  if (!Array.isArray(value.memberIds) || value.memberIds.length > 100) throw authorityUnavailable();
410
473
  return {
411
- memberIds: unique(value.memberIds.map((item) => normalizeResponseId(item)), (item) => item),
474
+ memberIds: unique(value.memberIds.map((item) => {
475
+ return normalizeResponseId(item);
476
+ }), (item) => {
477
+ return item;
478
+ }),
412
479
  nextCursor: nullableCursor(value.nextCursor)
413
480
  };
414
481
  }
@@ -430,7 +497,9 @@ function normalizeOrganizationInvitation(value) {
430
497
  id: value.id,
431
498
  email: value.email,
432
499
  role: value.role,
433
- teamIds: unique(value.teamIds.map(normalizeResponseId), (item) => item),
500
+ teamIds: unique(value.teamIds.map(normalizeResponseId), (item) => {
501
+ return item;
502
+ }),
434
503
  inviter: {
435
504
  membershipId: value.inviter.membershipId,
436
505
  name: value.inviter.name
@@ -444,7 +513,9 @@ function normalizeOrganizationInvitations(value) {
444
513
  exact$8(value, ["invitations", "nextCursor"]);
445
514
  if (!Array.isArray(value.invitations) || value.invitations.length > 100) throw authorityUnavailable();
446
515
  return {
447
- invitations: unique(value.invitations.map(normalizeOrganizationInvitation), (item) => item.id),
516
+ invitations: unique(value.invitations.map(normalizeOrganizationInvitation), (item) => {
517
+ return item.id;
518
+ }),
448
519
  nextCursor: nullableCursor(value.nextCursor)
449
520
  };
450
521
  }
@@ -481,7 +552,9 @@ function normalizeReceivedInvitation(value) {
481
552
  id: team.id,
482
553
  name: team.name
483
554
  };
484
- }), (item) => item.id),
555
+ }), (item) => {
556
+ return item.id;
557
+ }),
485
558
  inviterName: value.inviterName,
486
559
  expiresAt: responseDate(value.expiresAt)
487
560
  };
@@ -490,7 +563,9 @@ function normalizeReceivedInvitations(value) {
490
563
  exact$8(value, ["invitations", "nextCursor"]);
491
564
  if (!Array.isArray(value.invitations) || value.invitations.length > 100) throw authorityUnavailable();
492
565
  return {
493
- invitations: unique(value.invitations.map(normalizeReceivedInvitation), (item) => item.id),
566
+ invitations: unique(value.invitations.map(normalizeReceivedInvitation), (item) => {
567
+ return item.id;
568
+ }),
494
569
  nextCursor: nullableCursor(value.nextCursor)
495
570
  };
496
571
  }
@@ -522,6 +597,8 @@ function fromAuthorityError(value, fallbackStatus, retryAfter) {
522
597
  }
523
598
  function fromAccountAuthorityError(value, status, retryAfter) {
524
599
  const code = isObject$1(value) && typeof value.code === "string" ? value.code : void 0;
600
+ const pendingDeletion = accountDeletionPending(value, status);
601
+ if (pendingDeletion) return new AuthError("account_deletion_pending", 403, void 0, { accountDeletion: pendingDeletion });
525
602
  if (status === 403 && (code === "INVALID_ORIGIN" || code === "MISSING_OR_NULL_ORIGIN")) return new AuthError("request_origin_denied", 403);
526
603
  if (code === "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL") return new AuthError("account_conflict", 409);
527
604
  if (code === "INVALID_TOKEN") return new AuthError("password_reset_invalid", 422);
@@ -714,7 +791,7 @@ function mapError$2(code, status) {
714
791
  };
715
792
  }
716
793
  function parseRetryAfter(value) {
717
- if (!value || !/^\d+$/.test(value)) return void 0;
794
+ if (!value || !/^\d+$/.test(value)) return;
718
795
  const seconds = Number(value);
719
796
  return Number.isSafeInteger(seconds) && seconds >= 1 && seconds <= 3600 ? seconds : void 0;
720
797
  }
@@ -774,7 +851,9 @@ function record$1(value) {
774
851
  return value !== null && typeof value === "object" && !Array.isArray(value);
775
852
  }
776
853
  function exact$7(value, keys) {
777
- return record$1(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
854
+ return record$1(value) && Object.keys(value).length === keys.length && keys.every((key) => {
855
+ return Object.hasOwn(value, key);
856
+ });
778
857
  }
779
858
  function directoryId(value) {
780
859
  return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$(?![\s\S])/.test(value);
@@ -1145,8 +1224,10 @@ function mergeHeaders(input, defaults, Headers) {
1145
1224
  return headers;
1146
1225
  }
1147
1226
  async function callHooks(context, hooks) {
1148
- if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
1149
- else await hooks(context);
1227
+ if (hooks) {
1228
+ if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
1229
+ else await hooks(context);
1230
+ }
1150
1231
  }
1151
1232
  const retryStatusCodes = new Set([
1152
1233
  408,
@@ -1277,7 +1358,7 @@ function createFetch(globalOptions = {}) {
1277
1358
  }
1278
1359
  //#endregion
1279
1360
  //#region src/http.ts
1280
- const MAX_RESPONSE_BYTES = 64 * 1024;
1361
+ const MAX_RESPONSE_BYTES = 65536;
1281
1362
  async function requestJson(url, options) {
1282
1363
  return (await requestJsonResponse(url, options)).value;
1283
1364
  }
@@ -1303,7 +1384,7 @@ async function requestJsonResponse(url, options) {
1303
1384
  const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
1304
1385
  if (response.status >= 300 || response.status < 200 || contentType !== "application/json") {
1305
1386
  const body = contentType === "application/json" ? await readJson(response, options.maxResponseBytes, options.signal) : void 0;
1306
- response.body?.cancel().catch(() => void 0);
1387
+ response.body?.cancel().catch(() => {});
1307
1388
  throw (options.mapError ?? fromAuthorityError)(body, response.status, response.headers.get("retry-after"));
1308
1389
  }
1309
1390
  return {
@@ -1314,17 +1395,17 @@ async function requestJsonResponse(url, options) {
1314
1395
  async function readJson(response, maximum = MAX_RESPONSE_BYTES, signal) {
1315
1396
  const length = response.headers.get("content-length");
1316
1397
  if (length && (!/^\d+$/.test(length) || Number(length) > maximum)) {
1317
- response.body?.cancel().catch(() => void 0);
1398
+ response.body?.cancel().catch(() => {});
1318
1399
  throw authorityUnavailable();
1319
1400
  }
1320
1401
  if (!response.body) throw authorityUnavailable();
1321
1402
  if (signal?.aborted) {
1322
- response.body.cancel().catch(() => void 0);
1403
+ response.body.cancel().catch(() => {});
1323
1404
  throw authorityUnavailable();
1324
1405
  }
1325
1406
  const reader = response.body.getReader();
1326
1407
  const cancel = () => {
1327
- reader.cancel().catch(() => void 0);
1408
+ reader.cancel().catch(() => {});
1328
1409
  };
1329
1410
  signal?.addEventListener("abort", cancel, { once: true });
1330
1411
  const chunks = [];
@@ -1339,7 +1420,7 @@ async function readJson(response, maximum = MAX_RESPONSE_BYTES, signal) {
1339
1420
  chunks.push(value);
1340
1421
  }
1341
1422
  } catch (error) {
1342
- reader.cancel().catch(() => void 0);
1423
+ reader.cancel().catch(() => {});
1343
1424
  throw error;
1344
1425
  } finally {
1345
1426
  signal?.removeEventListener("abort", cancel);
@@ -1366,7 +1447,7 @@ function createOrganizationDirectoryAuth(options) {
1366
1447
  const timeoutMs = normalizeTimeout(options.timeoutMs);
1367
1448
  let inFlight = 0;
1368
1449
  async function exchange(operation, body, assertion) {
1369
- if (typeof assertion !== "string" || assertion.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
1450
+ if (typeof assertion !== "string" || assertion.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
1370
1451
  if (inFlight >= 4) throw new AuthError("state_conflict", 409);
1371
1452
  inFlight += 1;
1372
1453
  const controller = new AbortController();
@@ -1390,7 +1471,7 @@ function createOrganizationDirectoryAuth(options) {
1390
1471
  accept: "application/json"
1391
1472
  },
1392
1473
  body,
1393
- maxResponseBytes: 256 * 1024,
1474
+ maxResponseBytes: 262144,
1394
1475
  signal: controller.signal
1395
1476
  }).finally(() => {
1396
1477
  inFlight -= 1;
@@ -1415,17 +1496,27 @@ function createOrganizationDirectoryAuth(options) {
1415
1496
  return organization;
1416
1497
  },
1417
1498
  async searchOrganizations(input, assertion) {
1418
- if (!record$1(input) || Object.keys(input).some((key) => ![
1419
- "applicationId",
1420
- "query",
1421
- "limit",
1422
- "cursor"
1423
- ].includes(key)) || !directoryId(input.applicationId) || input.query !== void 0 && (typeof input.query !== "string" || input.query.length < 1 || input.query.length > 128 || Array.from(input.query).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) || input.limit !== void 0 && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 100) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length > 2048)) throw new AuthError("invalid_request", 400);
1499
+ if (!record$1(input) || Object.keys(input).some((key) => {
1500
+ return ![
1501
+ "applicationId",
1502
+ "query",
1503
+ "limit",
1504
+ "cursor"
1505
+ ].includes(key);
1506
+ }) || !directoryId(input.applicationId) || input.query !== void 0 && (typeof input.query !== "string" || input.query.length < 1 || input.query.length > 128 || Array.from(input.query).some((character) => {
1507
+ return character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127;
1508
+ })) || input.limit !== void 0 && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 100) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length > 2048)) throw new AuthError("invalid_request", 400);
1424
1509
  const limit = input.limit ?? 50;
1425
1510
  const value = await exchange("search", input, assertion);
1426
1511
  if (!exact$7(value, ["organizations", "nextCursor"]) || !Array.isArray(value.organizations) || value.organizations.length > limit || value.nextCursor !== null && (typeof value.nextCursor !== "string" || !value.nextCursor.length || value.nextCursor.length > 2048)) throw authorityUnavailable();
1427
- const organizations = value.organizations.map((item) => normalizeDirectoryEntry(item, input.applicationId));
1428
- if (organizations.some((organization) => organization.lifecycle === "deleted") || new Set(organizations.map((organization) => `${organization.organizationId}:${organization.organizationGeneration}`)).size !== organizations.length) throw authorityUnavailable();
1512
+ const organizations = value.organizations.map((item) => {
1513
+ return normalizeDirectoryEntry(item, input.applicationId);
1514
+ });
1515
+ if (organizations.some((organization) => {
1516
+ return organization.lifecycle === "deleted";
1517
+ }) || new Set(organizations.map((organization) => {
1518
+ return `${organization.organizationId}:${organization.organizationGeneration}`;
1519
+ })).size !== organizations.length) throw authorityUnavailable();
1429
1520
  return {
1430
1521
  organizations,
1431
1522
  nextCursor: value.nextCursor
@@ -1435,25 +1526,39 @@ function createOrganizationDirectoryAuth(options) {
1435
1526
  }
1436
1527
  //#endregion
1437
1528
  //#region src/organization-admission/contract.ts
1438
- const invalid$1 = () => new AuthError("invalid_request", 400);
1439
- const positive = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value < Number.MAX_SAFE_INTEGER;
1440
- const timestamp$1 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13;
1441
- const digest$2 = (value) => typeof value === "string" && /^[a-f0-9]{64}$(?![\s\S])/.test(value);
1442
- const text = (value) => typeof value === "string" && value.length > 0 && new TextEncoder().encode(value).byteLength <= 255;
1443
- const slug = (value) => typeof value === "string" && /^[a-z0-9-]{1,128}$(?![\s\S])/.test(value);
1529
+ const invalid$2 = () => {
1530
+ return new AuthError("invalid_request", 400);
1531
+ };
1532
+ const positive = (value) => {
1533
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value < Number.MAX_SAFE_INTEGER;
1534
+ };
1535
+ const timestamp$1 = (value) => {
1536
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 864e13;
1537
+ };
1538
+ const digest$2 = (value) => {
1539
+ return typeof value === "string" && /^[a-f0-9]{64}$(?![\s\S])/.test(value);
1540
+ };
1541
+ const text = (value) => {
1542
+ return typeof value === "string" && value.length > 0 && new TextEncoder().encode(value).byteLength <= 255;
1543
+ };
1544
+ const slug = (value) => {
1545
+ return typeof value === "string" && /^[a-z0-9-]{1,128}$(?![\s\S])/.test(value);
1546
+ };
1444
1547
  function setupInput(input, additional = []) {
1445
1548
  if (!exact$7(input, [
1446
1549
  "applicationId",
1447
1550
  "setupId",
1448
1551
  ...additional
1449
- ]) || !directoryId(input.applicationId) || !directoryGeneration(input.setupId)) throw invalid$1();
1552
+ ]) || !directoryId(input.applicationId) || !directoryGeneration(input.setupId)) throw invalid$2();
1450
1553
  }
1451
1554
  function pageInput$1(input) {
1452
- if (!record$1(input) || Object.keys(input).some((key) => ![
1453
- "applicationId",
1454
- "cursor",
1455
- "limit"
1456
- ].includes(key)) || !directoryId(input.applicationId) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length < 1 || input.cursor.length > 2048) || input.limit !== void 0 && (!positive(input.limit) || input.limit > 50)) throw invalid$1();
1555
+ if (!record$1(input) || Object.keys(input).some((key) => {
1556
+ return ![
1557
+ "applicationId",
1558
+ "cursor",
1559
+ "limit"
1560
+ ].includes(key);
1561
+ }) || !directoryId(input.applicationId) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length < 1 || input.cursor.length > 2048) || input.limit !== void 0 && (!positive(input.limit) || input.limit > 50)) throw invalid$2();
1457
1562
  }
1458
1563
  const setupKeys = [
1459
1564
  "setupId",
@@ -1504,8 +1609,14 @@ function billingSetup(value, applicationId, setupId) {
1504
1609
  }
1505
1610
  function page(value, input, pending = false) {
1506
1611
  if (!exact$7(value, ["setups", "nextCursor"]) || !Array.isArray(value.setups) || value.setups.length > (input.limit ?? 25) || value.nextCursor !== null && (typeof value.nextCursor !== "string" || !value.nextCursor.length || value.nextCursor.length > 2048 || value.nextCursor === input.cursor)) throw authorityUnavailable();
1507
- const setups = value.setups.map((item) => setup(item, input.applicationId));
1508
- if (new Set(setups.map((item) => item.setupId)).size !== setups.length || pending && setups.some((item) => item.status === "activated")) throw authorityUnavailable();
1612
+ const setups = value.setups.map((item) => {
1613
+ return setup(item, input.applicationId);
1614
+ });
1615
+ if (new Set(setups.map((item) => {
1616
+ return item.setupId;
1617
+ })).size !== setups.length || pending && setups.some((item) => {
1618
+ return item.status === "activated";
1619
+ })) throw authorityUnavailable();
1509
1620
  return {
1510
1621
  setups,
1511
1622
  nextCursor: value.nextCursor
@@ -1536,18 +1647,20 @@ function actorHeaders(proof) {
1536
1647
  "serviceAssertion",
1537
1648
  "request",
1538
1649
  "appOrigin"
1539
- ]) || !(proof.request instanceof Request)) throw invalid$1();
1650
+ ]) || !(proof.request instanceof Request)) throw invalid$2();
1540
1651
  const authorization = proof.request.headers.get("authorization");
1541
1652
  if (authorization !== null) {
1542
- if (new TextEncoder().encode(authorization).byteLength > 16 * 1024 || /[^\x20-\x7e]/.test(authorization) || !/^Bearer [^\s,]+$/i.test(authorization) || /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(authorization.slice(7))) throw new AuthError("authentication_required", 401);
1653
+ if (new TextEncoder().encode(authorization).byteLength > 16384 || /[^\x20-\x7e]/.test(authorization) || !/^Bearer [^\s,]+$/i.test(authorization) || /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(authorization.slice(7))) throw new AuthError("authentication_required", 401);
1543
1654
  return { authorization };
1544
1655
  }
1545
- const cookie = (proof.request.headers.get("cookie") ?? "").split(";").map((entry) => entry.trim()).filter((entry) => {
1656
+ const cookie = (proof.request.headers.get("cookie") ?? "").split(";").map((entry) => {
1657
+ return entry.trim();
1658
+ }).filter((entry) => {
1546
1659
  const separator = entry.indexOf("=");
1547
1660
  const name = entry.slice(0, separator);
1548
1661
  return separator > 0 && (name.startsWith("better-auth.") || name.startsWith("__Secure-better-auth."));
1549
1662
  }).join("; ");
1550
- if (!cookie || new TextEncoder().encode(cookie).byteLength > 16 * 1024) throw new AuthError("authentication_required", 401);
1663
+ if (!cookie || new TextEncoder().encode(cookie).byteLength > 16384) throw new AuthError("authentication_required", 401);
1551
1664
  const origin = normalizeOrigin(proof.appOrigin, "appOrigin");
1552
1665
  if (proof.request.headers.get("origin") !== origin) throw new AuthError("request_origin_denied", 403);
1553
1666
  return {
@@ -1562,12 +1675,12 @@ function transport(options, operations) {
1562
1675
  const timeoutMs = normalizeTimeout(options.timeoutMs);
1563
1676
  let inFlight = 0;
1564
1677
  function audience(operation) {
1565
- if (!operations.includes(operation)) throw invalid$1();
1678
+ if (!operations.includes(operation)) throw invalid$2();
1566
1679
  return joinURL(base, operation);
1567
1680
  }
1568
1681
  async function exchange(operation, body, assertion, actor) {
1569
1682
  const url = audience(operation);
1570
- if (typeof assertion !== "string" || assertion.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion) || new TextEncoder().encode(JSON.stringify(body)).byteLength > 8192) throw invalid$1();
1683
+ if (typeof assertion !== "string" || assertion.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion) || new TextEncoder().encode(JSON.stringify(body)).byteLength > 8192) throw invalid$2();
1571
1684
  const headers = actor ? actorHeaders(actor) : {};
1572
1685
  if (inFlight >= 4) throw new AuthError("state_conflict", 409);
1573
1686
  inFlight += 1;
@@ -1587,7 +1700,7 @@ function transport(options, operations) {
1587
1700
  credentials: "omit",
1588
1701
  cache: "no-store",
1589
1702
  signal: controller.signal,
1590
- maxResponseBytes: 64 * 1024,
1703
+ maxResponseBytes: 65536,
1591
1704
  headers: {
1592
1705
  ...headers,
1593
1706
  "x-finueva-service-assertion": assertion,
@@ -1596,7 +1709,7 @@ function transport(options, operations) {
1596
1709
  },
1597
1710
  body,
1598
1711
  mapError: (_value, status, retryAfter) => {
1599
- if (status === 400) return invalid$1();
1712
+ if (status === 400) return invalid$2();
1600
1713
  if (status === 401) return new AuthError("authentication_required", 401);
1601
1714
  if (status === 403) return new AuthError("access_denied", 403);
1602
1715
  if (status === 409) return new AuthError("state_conflict", 409);
@@ -1624,7 +1737,7 @@ function validate(operation, input) {
1624
1737
  "applicationId",
1625
1738
  "idempotencyKey",
1626
1739
  "target"
1627
- ]) || !directoryId(input.applicationId) || typeof input.idempotencyKey !== "string" || !/^[A-Za-z0-9_-]{16,128}$(?![\s\S])/.test(input.idempotencyKey) || !record$1(input.target)) throw invalid$1();
1740
+ ]) || !directoryId(input.applicationId) || typeof input.idempotencyKey !== "string" || !/^[A-Za-z0-9_-]{16,128}$(?![\s\S])/.test(input.idempotencyKey) || !record$1(input.target)) throw invalid$2();
1628
1741
  const target = input.target;
1629
1742
  if (target.kind === "new" ? !exact$7(target, [
1630
1743
  "kind",
@@ -1634,7 +1747,7 @@ function validate(operation, input) {
1634
1747
  "kind",
1635
1748
  "organizationId",
1636
1749
  "organizationGeneration"
1637
- ]) || !directoryId(target.organizationId) || !directoryGeneration(target.organizationGeneration)) throw invalid$1();
1750
+ ]) || !directoryId(target.organizationId) || !directoryGeneration(target.organizationGeneration)) throw invalid$2();
1638
1751
  } else if (operation === "list" || operation === "pending") {
1639
1752
  pageInput$1(input);
1640
1753
  return {
@@ -1642,20 +1755,22 @@ function validate(operation, input) {
1642
1755
  limit: input.limit ?? 25
1643
1756
  };
1644
1757
  } else if (operation === "identity") {
1645
- if (!exact$7(input, ["applicationId", "organizationId"]) || !directoryId(input.applicationId) || !directoryId(input.organizationId)) throw invalid$1();
1758
+ if (!exact$7(input, ["applicationId", "organizationId"]) || !directoryId(input.applicationId) || !directoryId(input.organizationId)) throw invalid$2();
1646
1759
  } else if (operation === "current") {
1647
- if (!record$1(input) || Object.keys(input).some((key) => ![
1648
- "applicationId",
1649
- "organizationId",
1650
- "organizationGeneration"
1651
- ].includes(key)) || !directoryId(input.applicationId) || !directoryId(input.organizationId) || input.organizationGeneration !== void 0 && !directoryGeneration(input.organizationGeneration)) throw invalid$1();
1760
+ if (!record$1(input) || Object.keys(input).some((key) => {
1761
+ return ![
1762
+ "applicationId",
1763
+ "organizationId",
1764
+ "organizationGeneration"
1765
+ ].includes(key);
1766
+ }) || !directoryId(input.applicationId) || !directoryId(input.organizationId) || input.organizationGeneration !== void 0 && !directoryGeneration(input.organizationGeneration)) throw invalid$2();
1652
1767
  } else if (operation === "amend") {
1653
1768
  setupInput(input, [
1654
1769
  "expectedDisplayRevision",
1655
1770
  "name",
1656
1771
  "slug"
1657
1772
  ]);
1658
- if (!positive(input.expectedDisplayRevision) || !text(input.name) || !slug(input.slug)) throw invalid$1();
1773
+ if (!positive(input.expectedDisplayRevision) || !text(input.name) || !slug(input.slug)) throw invalid$2();
1659
1774
  } else if (operation === "read" || operation === "lookup") setupInput(input);
1660
1775
  else if (operation === "finalize" || operation === "withdraw") {
1661
1776
  setupInput(input, [
@@ -1663,7 +1778,7 @@ function validate(operation, input) {
1663
1778
  "receiptRevision",
1664
1779
  ...operation === "withdraw" ? ["selectionDigest"] : []
1665
1780
  ]);
1666
- if (!directoryId(input.receiptId) || !positive(input.receiptRevision) || operation === "withdraw" && !digest$2(input.selectionDigest)) throw invalid$1();
1781
+ if (!directoryId(input.receiptId) || !positive(input.receiptRevision) || operation === "withdraw" && !digest$2(input.selectionDigest)) throw invalid$2();
1667
1782
  } else if (operation === "attest") {
1668
1783
  setupInput(input, [
1669
1784
  "organizationId",
@@ -1690,19 +1805,25 @@ function validate(operation, input) {
1690
1805
  "paid",
1691
1806
  "trial",
1692
1807
  "complimentary"
1693
- ].includes(String(receipt.source)) || !timestamp$1(receipt.observedAt) || !timestamp$1(receipt.validUntil) || receipt.validUntil <= receipt.observedAt || receipt.validUntil - receipt.observedAt > 6e4 || (receipt.source === "complimentary" ? receipt.observedPriceId !== null : receipt.observedPriceId !== selection.priceId)) throw invalid$1();
1694
- } else throw invalid$1();
1808
+ ].includes(String(receipt.source)) || !timestamp$1(receipt.observedAt) || !timestamp$1(receipt.validUntil) || receipt.validUntil <= receipt.observedAt || receipt.validUntil - receipt.observedAt > 6e4 || (receipt.source === "complimentary" ? receipt.observedPriceId !== null : receipt.observedPriceId !== selection.priceId)) throw invalid$2();
1809
+ } else throw invalid$2();
1695
1810
  return input;
1696
1811
  }
1697
1812
  function canonical(value) {
1698
1813
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
1699
- if (record$1(value)) return `{${Object.keys(value).filter((key) => value[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
1814
+ if (record$1(value)) return `{${Object.keys(value).filter((key) => {
1815
+ return value[key] !== void 0;
1816
+ }).sort().map((key) => {
1817
+ return `${JSON.stringify(key)}:${canonical(value[key])}`;
1818
+ }).join(",")}}`;
1700
1819
  return JSON.stringify(value);
1701
1820
  }
1702
1821
  async function organizationAdmissionBodyDigest(operation, input) {
1703
1822
  const bytes = new TextEncoder().encode(canonical(validate(operation, input)));
1704
- if (bytes.byteLength > 8192) throw invalid$1();
1705
- return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (byte) => byte.toString(16).padStart(2, "0")).join("");
1823
+ if (bytes.byteLength > 8192) throw invalid$2();
1824
+ return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (byte) => {
1825
+ return byte.toString(16).padStart(2, "0");
1826
+ }).join("");
1706
1827
  }
1707
1828
  function createOrganizationAdmissionAuth(options) {
1708
1829
  const { audience, exchange } = transport(options, [
@@ -1833,7 +1954,9 @@ const id$2 = /^[A-Za-z0-9_-]{1,128}$(?![\s\S])/;
1833
1954
  const digest$1 = /^[a-f0-9]{64}$(?![\s\S])/;
1834
1955
  const credential = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/;
1835
1956
  function exact$6(value, keys) {
1836
- return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
1957
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => {
1958
+ return Object.hasOwn(value, key);
1959
+ });
1837
1960
  }
1838
1961
  function identifier(value) {
1839
1962
  return typeof value === "string" && id$2.test(value);
@@ -1854,7 +1977,9 @@ function operationProof(value) {
1854
1977
  "development",
1855
1978
  "staging",
1856
1979
  "production"
1857
- ].includes(value.environment) || [value.applicationCredential, value.serviceAssertion].some((token) => typeof token !== "string" || token.length > 16 * 1024 || !credential.test(token))) throw new AuthError("invalid_request", 400);
1980
+ ].includes(value.environment) || [value.applicationCredential, value.serviceAssertion].some((token) => {
1981
+ return typeof token !== "string" || token.length > 16384 || !credential.test(token);
1982
+ })) throw new AuthError("invalid_request", 400);
1858
1983
  return {
1859
1984
  applicationCredential: value.applicationCredential,
1860
1985
  serviceAssertion: value.serviceAssertion,
@@ -1865,7 +1990,9 @@ function operationProof(value) {
1865
1990
  };
1866
1991
  }
1867
1992
  function snapshotInput(value) {
1868
- if (!exact$6(value, ["applicationId", "participantUserUids"]) || !identifier(value.applicationId) || !Array.isArray(value.participantUserUids) || value.participantUserUids.length < 1 || value.participantUserUids.length > 100 || !value.participantUserUids.every((uid, index, all) => identifier(uid) && (index === 0 || all[index - 1] < uid))) throw new AuthError("invalid_request", 400);
1993
+ if (!exact$6(value, ["applicationId", "participantUserUids"]) || !identifier(value.applicationId) || !Array.isArray(value.participantUserUids) || value.participantUserUids.length < 1 || value.participantUserUids.length > 100 || !value.participantUserUids.every((uid, index, all) => {
1994
+ return identifier(uid) && (index === 0 || all[index - 1] < uid);
1995
+ })) throw new AuthError("invalid_request", 400);
1869
1996
  return {
1870
1997
  applicationId: value.applicationId,
1871
1998
  participantUserUids: [...value.participantUserUids]
@@ -2022,20 +2149,22 @@ function createAccountProductOperationAuth(options) {
2022
2149
  };
2023
2150
  }
2024
2151
  //#endregion
2025
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/buffer_utils.js
2152
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js
2026
2153
  const encoder$1 = new TextEncoder();
2027
2154
  const decoder = new TextDecoder();
2155
+ const strictDecoder = new TextDecoder("utf-8", { fatal: !0 });
2028
2156
  function concat(...buffers) {
2029
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
2030
- const buf = new Uint8Array(size);
2157
+ const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);
2031
2158
  let i = 0;
2032
- for (const buffer of buffers) {
2033
- buf.set(buffer, i);
2034
- i += buffer.length;
2035
- }
2159
+ for (const buffer of buffers) buf.set(buffer, i), i += buffer.length;
2036
2160
  return buf;
2037
2161
  }
2162
+ const NON_ASCII = /[^\x00-\x7f]/;
2038
2163
  function encode$1(string) {
2164
+ if (typeof string == "string" && string.length >= 128) {
2165
+ if (NON_ASCII.test(string)) throw new TypeError("non-ASCII string encountered in encode()");
2166
+ return encoder$1.encode(string);
2167
+ }
2039
2168
  const bytes = new Uint8Array(string.length);
2040
2169
  for (let i = 0; i < string.length; i++) {
2041
2170
  const code = string.charCodeAt(i);
@@ -2044,133 +2173,37 @@ function encode$1(string) {
2044
2173
  }
2045
2174
  return bytes;
2046
2175
  }
2047
- //#endregion
2048
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/base64.js
2049
- function encodeBase64(input) {
2050
- if (Uint8Array.prototype.toBase64) return input.toBase64();
2051
- const CHUNK_SIZE = 32768;
2052
- const arr = [];
2176
+ function encodeBase64(input, url = !1) {
2177
+ if (Uint8Array.prototype.toBase64) return input.toBase64({
2178
+ alphabet: url ? "base64url" : "base64",
2179
+ omitPadding: url
2180
+ });
2181
+ const CHUNK_SIZE = 32768, arr = [];
2053
2182
  for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
2054
- return btoa(arr.join(""));
2055
- }
2056
- function decodeBase64(encoded) {
2057
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
2058
- const binary = atob(encoded);
2059
- const bytes = new Uint8Array(binary.length);
2183
+ const encoded = btoa(arr.join(""));
2184
+ return url ? encoded.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") : encoded;
2185
+ }
2186
+ function decodeBase64(encoded, url = !1) {
2187
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
2188
+ if (url) {
2189
+ if (encoded.includes("+") || encoded.includes("/")) throw new TypeError("Invalid base64url");
2190
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
2191
+ }
2192
+ const binary = atob(encoded), bytes = new Uint8Array(binary.length);
2060
2193
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2061
2194
  return bytes;
2062
2195
  }
2063
- //#endregion
2064
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/base64url.js
2065
- function decode(input) {
2066
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
2067
- let encoded = input;
2068
- if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
2069
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
2070
- try {
2071
- return decodeBase64(encoded);
2072
- } catch {
2073
- throw new TypeError("The input to be decoded is not correctly encoded.");
2074
- }
2075
- }
2076
- function encode(input) {
2077
- let unencoded = input;
2078
- if (typeof unencoded === "string") unencoded = encoder$1.encode(unencoded);
2079
- if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
2080
- alphabet: "base64url",
2081
- omitPadding: true
2082
- });
2083
- return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
2084
- }
2085
- //#endregion
2086
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/crypto_key.js
2087
- const unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
2088
- const isAlgorithm = (algorithm, name) => algorithm.name === name;
2089
- function getHashLength(hash) {
2090
- return parseInt(hash.name.slice(4), 10);
2091
- }
2092
- function checkHashLength(algorithm, expected) {
2093
- if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
2094
- }
2095
- function getNamedCurve(alg) {
2096
- switch (alg) {
2097
- case "ES256": return "P-256";
2098
- case "ES384": return "P-384";
2099
- case "ES512": return "P-521";
2100
- default: throw new Error("unreachable");
2101
- }
2102
- }
2103
- function checkUsage(key, usage) {
2104
- if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
2105
- }
2106
- function checkSigCryptoKey(key, alg, usage) {
2107
- switch (alg) {
2108
- case "HS256":
2109
- case "HS384":
2110
- case "HS512":
2111
- if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
2112
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
2113
- break;
2114
- case "RS256":
2115
- case "RS384":
2116
- case "RS512":
2117
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
2118
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
2119
- break;
2120
- case "PS256":
2121
- case "PS384":
2122
- case "PS512":
2123
- if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
2124
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
2125
- break;
2126
- case "Ed25519":
2127
- case "EdDSA":
2128
- if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
2129
- break;
2130
- case "ML-DSA-44":
2131
- case "ML-DSA-65":
2132
- case "ML-DSA-87":
2133
- if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
2134
- break;
2135
- case "ES256":
2136
- case "ES384":
2137
- case "ES512": {
2138
- if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
2139
- const expected = getNamedCurve(alg);
2140
- if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
2141
- break;
2142
- }
2143
- default: throw new TypeError("CryptoKey does not support this operation");
2144
- }
2145
- checkUsage(key, usage);
2146
- }
2147
- //#endregion
2148
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/invalid_key_input.js
2149
- function message(msg, actual, ...types) {
2150
- types = types.filter(Boolean);
2151
- if (types.length > 2) {
2152
- const last = types.pop();
2153
- msg += `one of type ${types.join(", ")}, or ${last}.`;
2154
- } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
2155
- else msg += `of type ${types[0]}.`;
2156
- if (actual == null) msg += ` Received ${actual}`;
2157
- else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
2158
- else if (typeof actual === "object" && actual != null) {
2159
- if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
2160
- }
2161
- return msg;
2196
+ async function digest(algorithm, data) {
2197
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
2198
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
2162
2199
  }
2163
- const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
2164
- const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
2165
2200
  //#endregion
2166
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/errors.js
2201
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/errors.js
2167
2202
  var JOSEError = class extends Error {
2168
2203
  static code = "ERR_JOSE_GENERIC";
2169
2204
  code = "ERR_JOSE_GENERIC";
2170
2205
  constructor(message, options) {
2171
- super(message, options);
2172
- this.name = this.constructor.name;
2173
- Error.captureStackTrace?.(this, this.constructor);
2206
+ super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
2174
2207
  }
2175
2208
  };
2176
2209
  var JWTClaimValidationFailed = class extends JOSEError {
@@ -2184,10 +2217,7 @@ var JWTClaimValidationFailed = class extends JOSEError {
2184
2217
  claim,
2185
2218
  reason,
2186
2219
  payload
2187
- } });
2188
- this.claim = claim;
2189
- this.reason = reason;
2190
- this.payload = payload;
2220
+ } }), this.claim = claim, this.reason = reason, this.payload = payload;
2191
2221
  }
2192
2222
  };
2193
2223
  var JWTExpired = class extends JOSEError {
@@ -2201,10 +2231,7 @@ var JWTExpired = class extends JOSEError {
2201
2231
  claim,
2202
2232
  reason,
2203
2233
  payload
2204
- } });
2205
- this.claim = claim;
2206
- this.reason = reason;
2207
- this.payload = payload;
2234
+ } }), this.claim = claim, this.reason = reason, this.payload = payload;
2208
2235
  }
2209
2236
  };
2210
2237
  var JOSEAlgNotAllowed = class extends JOSEError {
@@ -2235,763 +2262,615 @@ var JWSSignatureVerificationFailed = class extends JOSEError {
2235
2262
  }
2236
2263
  };
2237
2264
  //#endregion
2238
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/is_key_like.js
2239
- const isCryptoKey = (key) => {
2240
- if (key?.[Symbol.toStringTag] === "CryptoKey") return true;
2241
- try {
2242
- return key instanceof CryptoKey;
2243
- } catch {
2244
- return false;
2245
- }
2246
- };
2247
- const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
2248
- const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
2249
- //#endregion
2250
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/helpers.js
2251
- function decodeBase64url(value, label, ErrorClass) {
2265
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js
2266
+ const invalid$1 = "The input to be decoded is not correctly encoded.";
2267
+ function decode(input) {
2252
2268
  try {
2253
- return decode(value);
2254
- } catch {
2255
- throw new ErrorClass(`Failed to base64url decode the ${label}`);
2269
+ return decodeBase64(typeof input == "string" ? input : decoder.decode(input), !0);
2270
+ } catch (cause) {
2271
+ throw new TypeError(invalid$1, { cause });
2256
2272
  }
2257
2273
  }
2258
- async function digest(algorithm, data) {
2259
- const subtleDigest = `SHA-${algorithm.slice(-3)}`;
2260
- return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
2274
+ function encode(input) {
2275
+ return encodeBase64(typeof input == "string" ? encoder$1.encode(input) : input, !0);
2261
2276
  }
2262
2277
  //#endregion
2263
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/type_checks.js
2264
- const isObjectLike = (value) => typeof value === "object" && value !== null;
2278
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js
2265
2279
  function isObject(input) {
2266
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
2267
- if (Object.getPrototypeOf(input) === null) return true;
2268
- let proto = input;
2269
- while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
2270
- return Object.getPrototypeOf(input) === proto;
2280
+ if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") return !1;
2281
+ const prototype = Object.getPrototypeOf(input);
2282
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
2271
2283
  }
2272
2284
  function isDisjoint(...headers) {
2273
- const sources = headers.filter(Boolean);
2274
- if (sources.length === 0 || sources.length === 1) return true;
2275
- let acc;
2276
- for (const header of sources) {
2277
- const parameters = Object.keys(header);
2278
- if (!acc || acc.size === 0) {
2279
- acc = new Set(parameters);
2280
- continue;
2281
- }
2282
- for (const parameter of parameters) {
2283
- if (acc.has(parameter)) return false;
2284
- acc.add(parameter);
2285
- }
2285
+ const parameters = new Set();
2286
+ for (const header of headers) if (header) for (const parameter of Object.keys(header)) {
2287
+ if (parameters.has(parameter)) return !1;
2288
+ parameters.add(parameter);
2286
2289
  }
2287
- return true;
2290
+ return !0;
2288
2291
  }
2289
- const isJWK = (key) => isObject(key) && typeof key.kty === "string";
2290
- const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
2291
- const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
2292
- const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
2293
- //#endregion
2294
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/signing.js
2295
- function checkKeyLength(alg, key) {
2296
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
2297
- const { modulusLength } = key.algorithm;
2298
- if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
2299
- }
2300
- }
2301
- function subtleAlgorithm(alg, algorithm) {
2302
- const hash = `SHA-${alg.slice(-3)}`;
2303
- switch (alg) {
2304
- case "HS256":
2305
- case "HS384":
2306
- case "HS512": return {
2307
- hash,
2308
- name: "HMAC"
2309
- };
2310
- case "PS256":
2311
- case "PS384":
2312
- case "PS512": return {
2313
- hash,
2314
- name: "RSA-PSS",
2315
- saltLength: parseInt(alg.slice(-3), 10) >> 3
2316
- };
2317
- case "RS256":
2318
- case "RS384":
2319
- case "RS512": return {
2320
- hash,
2321
- name: "RSASSA-PKCS1-v1_5"
2322
- };
2323
- case "ES256":
2324
- case "ES384":
2325
- case "ES512": return {
2326
- hash,
2327
- name: "ECDSA",
2328
- namedCurve: algorithm.namedCurve
2329
- };
2330
- case "Ed25519":
2331
- case "EdDSA": return { name: "Ed25519" };
2332
- case "ML-DSA-44":
2333
- case "ML-DSA-65":
2334
- case "ML-DSA-87": return { name: alg };
2335
- default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
2292
+ function decodeBase64url(value, label, ErrorClass) {
2293
+ try {
2294
+ return decode(value);
2295
+ } catch {
2296
+ throw new ErrorClass(`Failed to base64url decode the ${label}`);
2336
2297
  }
2337
2298
  }
2338
- async function getSigKey(alg, key, usage) {
2339
- if (key instanceof Uint8Array) {
2340
- if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
2341
- return crypto.subtle.importKey("raw", key, {
2342
- hash: `SHA-${alg.slice(-3)}`,
2343
- name: "HMAC"
2344
- }, false, [usage]);
2299
+ function encodeBase64url(value, label, ErrorClass) {
2300
+ try {
2301
+ return encode$1(value);
2302
+ } catch {
2303
+ throw new ErrorClass(`The ${label} is not a valid base64url string`);
2345
2304
  }
2346
- checkSigCryptoKey(key, alg, usage);
2347
- return key;
2348
2305
  }
2349
- async function verify(alg, key, signature, data) {
2350
- const cryptoKey = await getSigKey(alg, key, "verify");
2351
- checkKeyLength(alg, cryptoKey);
2352
- const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
2306
+ function parseJoseHeader(b64, ErrorClass, message) {
2307
+ let parsed;
2353
2308
  try {
2354
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
2309
+ parsed = JSON.parse(strictDecoder.decode(decode(b64)));
2355
2310
  } catch {
2356
- return false;
2311
+ throw new ErrorClass(message);
2357
2312
  }
2313
+ if (!isObject(parsed)) throw new ErrorClass(message);
2314
+ return parsed;
2358
2315
  }
2359
- //#endregion
2360
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/jwk_to_key.js
2361
- const unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value";
2362
- function subtleMapping(jwk) {
2363
- let algorithm;
2364
- let keyUsages;
2365
- switch (jwk.kty) {
2366
- case "AKP":
2367
- switch (jwk.alg) {
2368
- case "ML-DSA-44":
2369
- case "ML-DSA-65":
2370
- case "ML-DSA-87":
2371
- algorithm = { name: jwk.alg };
2372
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
2373
- break;
2374
- default: throw new JOSENotSupported(unsupportedAlg);
2375
- }
2376
- break;
2377
- case "RSA":
2378
- switch (jwk.alg) {
2379
- case "PS256":
2380
- case "PS384":
2381
- case "PS512":
2382
- algorithm = {
2383
- name: "RSA-PSS",
2384
- hash: `SHA-${jwk.alg.slice(-3)}`
2385
- };
2386
- keyUsages = jwk.d ? ["sign"] : ["verify"];
2387
- break;
2388
- case "RS256":
2389
- case "RS384":
2390
- case "RS512":
2391
- algorithm = {
2392
- name: "RSASSA-PKCS1-v1_5",
2393
- hash: `SHA-${jwk.alg.slice(-3)}`
2394
- };
2395
- keyUsages = jwk.d ? ["sign"] : ["verify"];
2396
- break;
2397
- case "RSA-OAEP":
2398
- case "RSA-OAEP-256":
2399
- case "RSA-OAEP-384":
2400
- case "RSA-OAEP-512":
2401
- algorithm = {
2402
- name: "RSA-OAEP",
2403
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
2404
- };
2405
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
2406
- break;
2407
- default: throw new JOSENotSupported(unsupportedAlg);
2408
- }
2409
- break;
2410
- case "EC":
2411
- switch (jwk.alg) {
2412
- case "ES256":
2413
- case "ES384":
2414
- case "ES512":
2415
- algorithm = {
2416
- name: "ECDSA",
2417
- namedCurve: {
2418
- ES256: "P-256",
2419
- ES384: "P-384",
2420
- ES512: "P-521"
2421
- }[jwk.alg]
2422
- };
2423
- keyUsages = jwk.d ? ["sign"] : ["verify"];
2424
- break;
2425
- case "ECDH-ES":
2426
- case "ECDH-ES+A128KW":
2427
- case "ECDH-ES+A192KW":
2428
- case "ECDH-ES+A256KW":
2429
- algorithm = {
2430
- name: "ECDH",
2431
- namedCurve: jwk.crv
2432
- };
2433
- keyUsages = jwk.d ? ["deriveBits"] : [];
2434
- break;
2435
- default: throw new JOSENotSupported(unsupportedAlg);
2436
- }
2437
- break;
2438
- case "OKP":
2439
- switch (jwk.alg) {
2440
- case "Ed25519":
2441
- case "EdDSA":
2442
- algorithm = { name: "Ed25519" };
2443
- keyUsages = jwk.d ? ["sign"] : ["verify"];
2444
- break;
2445
- case "ECDH-ES":
2446
- case "ECDH-ES+A128KW":
2447
- case "ECDH-ES+A192KW":
2448
- case "ECDH-ES+A256KW":
2449
- algorithm = { name: jwk.crv };
2450
- keyUsages = jwk.d ? ["deriveBits"] : [];
2451
- break;
2452
- default: throw new JOSENotSupported(unsupportedAlg);
2453
- }
2454
- break;
2455
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
2456
- }
2457
- return {
2458
- algorithm,
2459
- keyUsages
2316
+ const JWS_RECOGNIZED = {
2317
+ __proto__: null,
2318
+ b64: !0
2319
+ };
2320
+ function validateAlgorithms(option, algorithms) {
2321
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
2322
+ return algorithms === void 0 ? void 0 : new Set(algorithms);
2323
+ }
2324
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
2325
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
2326
+ if (!protectedHeader || protectedHeader.crit === void 0) return [];
2327
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
2328
+ const recognized = recognizedOption === void 0 ? recognizedDefault : {
2329
+ __proto__: null,
2330
+ ...recognizedOption,
2331
+ ...recognizedDefault
2460
2332
  };
2333
+ for (const parameter of protectedHeader.crit) {
2334
+ if (!(parameter in recognized)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
2335
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
2336
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
2337
+ }
2338
+ return protectedHeader.crit;
2461
2339
  }
2462
- async function jwkToKey(jwk) {
2463
- if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
2464
- const { algorithm, keyUsages } = subtleMapping(jwk);
2465
- const keyData = { ...jwk };
2466
- if (keyData.kty !== "AKP") delete keyData.alg;
2467
- delete keyData.use;
2468
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
2340
+ function validateB64(protectedHeader, extensions) {
2341
+ if (extensions.includes("b64")) {
2342
+ const b64 = protectedHeader.b64;
2343
+ if (typeof b64 != "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
2344
+ return b64;
2345
+ }
2346
+ return !0;
2469
2347
  }
2470
2348
  //#endregion
2471
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/normalize_key.js
2472
- const unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
2473
- let cache;
2474
- const handleJWK = async (key, jwk, alg, freeze = false) => {
2475
- cache ||= new WeakMap();
2476
- let cached = cache.get(key);
2477
- if (cached?.[alg]) return cached[alg];
2478
- const cryptoKey = await jwkToKey({
2479
- ...jwk,
2480
- alg
2481
- });
2482
- if (freeze) Object.freeze(key);
2483
- if (!cached) cache.set(key, { [alg]: cryptoKey });
2484
- else cached[alg] = cryptoKey;
2485
- return cryptoKey;
2486
- };
2487
- const handleKeyObject = (keyObject, alg) => {
2488
- cache ||= new WeakMap();
2489
- let cached = cache.get(keyObject);
2490
- if (cached?.[alg]) return cached[alg];
2491
- const isPublic = keyObject.type === "public";
2492
- const extractable = isPublic ? true : false;
2493
- let cryptoKey;
2494
- if (keyObject.asymmetricKeyType === "x25519") {
2495
- switch (alg) {
2496
- case "ECDH-ES":
2497
- case "ECDH-ES+A128KW":
2498
- case "ECDH-ES+A192KW":
2499
- case "ECDH-ES+A256KW": break;
2500
- default: throw new TypeError(unusableForAlg);
2501
- }
2502
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
2503
- }
2504
- if (keyObject.asymmetricKeyType === "ed25519") {
2505
- if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg);
2506
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
2349
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key.js
2350
+ const tag = (key) => key[Symbol.toStringTag];
2351
+ const jwkMatchesOp = (entry, key, usage) => {
2352
+ const { alg } = entry;
2353
+ if (key.use !== void 0) {
2354
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
2355
+ if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
2507
2356
  }
2508
- switch (keyObject.asymmetricKeyType) {
2509
- case "ml-dsa-44":
2510
- case "ml-dsa-65":
2511
- case "ml-dsa-87":
2512
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg);
2513
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
2357
+ if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
2358
+ if (Array.isArray(key.key_ops)) {
2359
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
2360
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
2514
2361
  }
2515
- if (keyObject.asymmetricKeyType === "rsa") {
2516
- let hash;
2517
- switch (alg) {
2518
- case "RSA-OAEP":
2519
- hash = "SHA-1";
2520
- break;
2521
- case "RS256":
2522
- case "PS256":
2523
- case "RSA-OAEP-256":
2524
- hash = "SHA-256";
2525
- break;
2526
- case "RS384":
2527
- case "PS384":
2528
- case "RSA-OAEP-384":
2529
- hash = "SHA-384";
2530
- break;
2531
- case "RS512":
2532
- case "PS512":
2533
- case "RSA-OAEP-512":
2534
- hash = "SHA-512";
2535
- break;
2536
- default: throw new TypeError(unusableForAlg);
2362
+ };
2363
+ async function prepareKey(entry, key, usage) {
2364
+ const { alg, secret } = entry, privateKey = usage === "decrypt" || usage === "sign";
2365
+ if (secret && key instanceof Uint8Array) return key;
2366
+ let normalized, keyObject;
2367
+ if (isObject(key)) {
2368
+ if (normalized = normalizeJwk(key), typeof normalized.kty != "string") throw invalidKeyType(alg, key, secret);
2369
+ if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (privateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0))) throw new TypeError(secret ? "JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present" : `JSON Web Key for this operation must be a ${privateKey ? "private" : "public"} JWK`);
2370
+ if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct") return decode(normalized.k);
2371
+ if (!Object.isFrozen(key)) {
2372
+ const { key_ops } = key;
2373
+ Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
2537
2374
  }
2538
- if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
2539
- name: "RSA-OAEP",
2540
- hash
2541
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
2542
- cryptoKey = keyObject.toCryptoKey({
2543
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
2544
- hash
2545
- }, extractable, [isPublic ? "verify" : "sign"]);
2375
+ } else {
2376
+ if (!isKeyLike(key)) throw invalidKeyType(alg, key, secret);
2377
+ const expectedType = secret ? "secret" : privateKey ? "private" : "public";
2378
+ if (key.type !== expectedType && (secret || [
2379
+ "secret",
2380
+ "public",
2381
+ "private"
2382
+ ].includes(key.type))) throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
2383
+ if (isCryptoKey(key)) return key;
2384
+ if (keyObject = key, keyObject.type === "secret") return keyObject.export();
2546
2385
  }
2547
- if (keyObject.asymmetricKeyType === "ec") {
2548
- const namedCurve = new Map([
2549
- ["prime256v1", "P-256"],
2550
- ["secp384r1", "P-384"],
2551
- ["secp521r1", "P-521"]
2552
- ]).get(keyObject.asymmetricKeyDetails?.namedCurve);
2553
- if (!namedCurve) throw new TypeError(unusableForAlg);
2554
- const expectedCurve = {
2555
- ES256: "P-256",
2556
- ES384: "P-384",
2557
- ES512: "P-521"
2558
- };
2559
- if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({
2560
- name: "ECDSA",
2561
- namedCurve
2562
- }, extractable, [isPublic ? "verify" : "sign"]);
2563
- if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
2564
- name: "ECDH",
2565
- namedCurve
2566
- }, extractable, isPublic ? [] : ["deriveBits"]);
2386
+ cache ||= new WeakMap();
2387
+ const cacheKey = key;
2388
+ let cached = cache.get(cacheKey);
2389
+ if (cached?.[alg]) return cached[alg];
2390
+ if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
2391
+ const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({
2392
+ crv,
2393
+ asymmetricKeyType: keyObject.asymmetricKeyType
2394
+ }) ?? entry.subtle;
2395
+ return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
2567
2396
  }
2568
- if (!cryptoKey) throw new TypeError(unusableForAlg);
2569
- if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
2570
- else cached[alg] = cryptoKey;
2571
- return cryptoKey;
2397
+ return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
2398
+ }
2399
+ let cache;
2400
+ const nist = {
2401
+ __proto__: null,
2402
+ prime256v1: "P-256",
2403
+ secp384r1: "P-384",
2404
+ secp521r1: "P-521"
2572
2405
  };
2573
- async function normalizeKey(key, alg) {
2574
- if (key instanceof Uint8Array) return key;
2575
- if (isCryptoKey(key)) return key;
2576
- if (isKeyObject(key)) {
2577
- if (key.type === "secret") return key.export();
2578
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
2579
- return handleKeyObject(key, alg);
2580
- } catch (err) {
2581
- if (err instanceof TypeError) throw err;
2582
- }
2583
- let jwk = key.export({ format: "jwk" });
2584
- return handleJWK(key, jwk, alg);
2585
- }
2586
- if (isJWK(key)) {
2587
- if (key.k) return decode(key.k);
2588
- return handleJWK(key, key, alg, true);
2406
+ const isCryptoKey = (key) => {
2407
+ if (key?.[Symbol.toStringTag] === "CryptoKey") return !0;
2408
+ try {
2409
+ return key instanceof CryptoKey;
2410
+ } catch {
2411
+ return !1;
2589
2412
  }
2590
- throw new Error("unreachable");
2413
+ };
2414
+ const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
2415
+ const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
2416
+ function message(msg, actual, ...types) {
2417
+ if (types.length > 2) {
2418
+ const last = types.pop();
2419
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
2420
+ } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
2421
+ return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;
2591
2422
  }
2592
- //#endregion
2593
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/key/import.js
2594
- async function importJWK(jwk, alg, options) {
2595
- if (!isObject(jwk)) throw new TypeError("JWK must be an object");
2596
- let ext;
2597
- alg ??= jwk.alg;
2598
- ext ??= options?.extractable ?? jwk.ext;
2599
- switch (jwk.kty) {
2600
- case "oct":
2601
- if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
2602
- return decode(jwk.k);
2603
- case "RSA":
2604
- if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
2605
- return jwkToKey({
2606
- ...jwk,
2607
- alg,
2608
- ext
2609
- });
2610
- case "AKP":
2611
- if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
2612
- if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
2613
- return jwkToKey({
2614
- ...jwk,
2615
- ext
2616
- });
2617
- case "EC":
2618
- case "OKP": return jwkToKey({
2619
- ...jwk,
2620
- alg,
2621
- ext
2622
- });
2623
- default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
2423
+ const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
2424
+ function invalidKeyType(alg, actual, secret) {
2425
+ const types = [
2426
+ "CryptoKey",
2427
+ "KeyObject",
2428
+ "JSON Web Key"
2429
+ ];
2430
+ return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
2431
+ }
2432
+ const unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
2433
+ function checkUsage(key, usage) {
2434
+ if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
2435
+ }
2436
+ function checkModulusLength(alg, key) {
2437
+ const { modulusLength } = key.algorithm;
2438
+ if (typeof modulusLength != "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
2439
+ }
2440
+ function checkCryptoKey(key, expected, usage) {
2441
+ const algorithm = key.algorithm;
2442
+ if (algorithm.name !== expected.name) throw unusable(expected.name);
2443
+ if (expected.hash && algorithm.hash?.name !== expected.hash) throw unusable(expected.hash, "algorithm.hash");
2444
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) throw unusable(expected.namedCurve, "algorithm.namedCurve");
2445
+ if (expected.length !== void 0 && algorithm.length !== expected.length) throw unusable(expected.length, "algorithm.length");
2446
+ checkUsage(key, usage);
2447
+ }
2448
+ function snapshotJwk(jwk) {
2449
+ return {
2450
+ __proto__: null,
2451
+ ...jwk
2452
+ };
2453
+ }
2454
+ function normalizeJwk(jwk) {
2455
+ const normalized = snapshotJwk(jwk);
2456
+ if (normalized.ext !== void 0 && typeof normalized.ext != "boolean") throw new TypeError("\"ext\" (Extractable) Parameter must be a boolean");
2457
+ if (normalized.key_ops !== void 0) {
2458
+ const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
2459
+ if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length) throw new TypeError("\"key_ops\" (Key Operations) Parameter must be an array of unique strings");
2460
+ normalized.key_ops = keyOps;
2624
2461
  }
2462
+ return normalized;
2625
2463
  }
2626
- //#endregion
2627
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/key_to_jwk.js
2628
- function omitUndefinedProperties(jwk) {
2629
- return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== void 0));
2464
+ function validateExtractableOption(extractable) {
2465
+ if (extractable !== void 0 && typeof extractable != "boolean") throw new TypeError("\"extractable\" option must be a boolean");
2466
+ return extractable;
2630
2467
  }
2631
- async function keyToJWK(key) {
2632
- if (isKeyObject(key)) if (key.type === "secret") key = key.export();
2633
- else return key.export({ format: "jwk" });
2634
- if (key instanceof Uint8Array) return {
2635
- kty: "oct",
2636
- k: encode(key)
2468
+ async function jwkToKey(entry, jwk, extractable) {
2469
+ if (!entry.kty.includes(jwk.kty)) throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
2470
+ const algorithm = entry.resolve?.({
2471
+ kty: jwk.kty,
2472
+ crv: jwk.crv
2473
+ }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = {
2474
+ ...jwk,
2475
+ ext: extractable ?? jwk.ext
2637
2476
  };
2638
- if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
2639
- if (!key.extractable) throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
2640
- const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
2641
- if (jwk.kty === "AKP") jwk.alg = alg;
2642
- return jwk;
2477
+ return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
2643
2478
  }
2644
- //#endregion
2645
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/key/export.js
2646
- async function exportJWK(key) {
2647
- return keyToJWK(key);
2479
+ async function rawKey(key, expected, usage, extractable = !1) {
2480
+ return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
2648
2481
  }
2649
2482
  //#endregion
2650
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/validate_crit.js
2651
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
2652
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
2653
- if (!protectedHeader || protectedHeader.crit === void 0) return new Set();
2654
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
2655
- let recognized;
2656
- if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
2657
- else recognized = recognizedDefault;
2658
- for (const parameter of protectedHeader.crit) {
2659
- if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
2660
- if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
2661
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
2662
- }
2663
- return new Set(protectedHeader.crit);
2483
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_descriptor.js
2484
+ function table(entries) {
2485
+ const out = { __proto__: null };
2486
+ for (const alg in entries) out[alg] = {
2487
+ ...entries[alg],
2488
+ alg
2489
+ };
2490
+ return out;
2664
2491
  }
2665
2492
  //#endregion
2666
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/validate_algorithms.js
2667
- function validateAlgorithms(option, algorithms) {
2668
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
2669
- if (!algorithms) return;
2670
- return new Set(algorithms);
2493
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwe_algorithms.js
2494
+ const wrap = [["encrypt", "wrapKey"], ["decrypt", "unwrapKey"]];
2495
+ const derive = [[], ["deriveBits"]];
2496
+ const none = [[], []];
2497
+ function rsaes(bits) {
2498
+ return {
2499
+ kty: ["RSA"],
2500
+ mode: "key-encryption",
2501
+ subtle: {
2502
+ name: "RSA-OAEP",
2503
+ hash: `SHA-${bits}`
2504
+ },
2505
+ usages: wrap,
2506
+ ops: ["wrapKey", "unwrapKey"]
2507
+ };
2508
+ }
2509
+ function ecdh(mode) {
2510
+ return {
2511
+ kty: ["EC", "OKP"],
2512
+ mode,
2513
+ subtle: { name: "ECDH" },
2514
+ resolve: ({ kty, crv, asymmetricKeyType }) => {
2515
+ if (crv === "X25519" || asymmetricKeyType === "x25519") return { name: "X25519" };
2516
+ if (kty === "OKP") throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
2517
+ return {
2518
+ name: "ECDH",
2519
+ namedCurve: crv
2520
+ };
2521
+ },
2522
+ usages: derive,
2523
+ ops: [void 0, "deriveBits"]
2524
+ };
2671
2525
  }
2526
+ function aeskw(bits, gcm = !1) {
2527
+ return {
2528
+ kty: ["oct"],
2529
+ mode: "key-wrapping",
2530
+ secret: !0,
2531
+ subtle: {
2532
+ name: gcm ? "AES-GCM" : "AES-KW",
2533
+ length: bits
2534
+ },
2535
+ usages: none,
2536
+ ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"]
2537
+ };
2538
+ }
2539
+ function pbes2() {
2540
+ return {
2541
+ kty: ["oct"],
2542
+ mode: "key-wrapping",
2543
+ secret: !0,
2544
+ subtle: { name: "PBKDF2" },
2545
+ usages: none,
2546
+ ops: ["deriveBits", "deriveBits"]
2547
+ };
2548
+ }
2549
+ const JWE = table({
2550
+ dir: {
2551
+ kty: ["oct"],
2552
+ mode: "direct-encryption",
2553
+ secret: !0,
2554
+ subtle: { name: "AES-GCM" },
2555
+ usages: none,
2556
+ ops: ["encrypt", "decrypt"]
2557
+ },
2558
+ "RSA-OAEP": rsaes(1),
2559
+ "RSA-OAEP-256": rsaes(256),
2560
+ "RSA-OAEP-384": rsaes(384),
2561
+ "RSA-OAEP-512": rsaes(512),
2562
+ "ECDH-ES": ecdh("direct-key-agreement"),
2563
+ "ECDH-ES+A128KW": ecdh("key-agreement-with-key-wrapping"),
2564
+ "ECDH-ES+A192KW": ecdh("key-agreement-with-key-wrapping"),
2565
+ "ECDH-ES+A256KW": ecdh("key-agreement-with-key-wrapping"),
2566
+ A128KW: aeskw(128),
2567
+ A192KW: aeskw(192),
2568
+ A256KW: aeskw(256),
2569
+ A128GCMKW: aeskw(128, !0),
2570
+ A192GCMKW: aeskw(192, !0),
2571
+ A256GCMKW: aeskw(256, !0),
2572
+ "PBES2-HS256+A128KW": pbes2(),
2573
+ "PBES2-HS384+A192KW": pbes2(),
2574
+ "PBES2-HS512+A256KW": pbes2()
2575
+ });
2576
+ const contentOps = ["encrypt", "decrypt"];
2577
+ function contentEncryption(bits, cbc = !1) {
2578
+ return {
2579
+ kty: ["oct"],
2580
+ secret: !0,
2581
+ subtle: {
2582
+ name: cbc ? "AES-CBC" : "AES-GCM",
2583
+ length: bits
2584
+ },
2585
+ usages: none,
2586
+ ops: contentOps,
2587
+ cekBits: bits,
2588
+ ivBits: cbc ? 128 : 96,
2589
+ cbc
2590
+ };
2591
+ }
2592
+ table({
2593
+ A128GCM: contentEncryption(128),
2594
+ A192GCM: contentEncryption(192),
2595
+ A256GCM: contentEncryption(256),
2596
+ "A128CBC-HS256": contentEncryption(256, !0),
2597
+ "A192CBC-HS384": contentEncryption(384, !0),
2598
+ "A256CBC-HS512": contentEncryption(512, !0)
2599
+ });
2672
2600
  //#endregion
2673
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/check_key_type.js
2674
- const tag = (key) => key?.[Symbol.toStringTag];
2675
- const jwkMatchesOp = (alg, key, usage) => {
2676
- if (key.use !== void 0) {
2677
- let expected;
2678
- switch (usage) {
2679
- case "sign":
2680
- case "verify":
2681
- expected = "sig";
2682
- break;
2683
- case "encrypt":
2684
- case "decrypt":
2685
- expected = "enc";
2686
- break;
2687
- }
2688
- if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
2689
- }
2690
- if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
2691
- if (Array.isArray(key.key_ops)) {
2692
- let expectedKeyOp;
2693
- switch (true) {
2694
- case usage === "sign" || usage === "verify":
2695
- case alg === "dir":
2696
- case alg.includes("CBC-HS"):
2697
- expectedKeyOp = usage;
2698
- break;
2699
- case alg.startsWith("PBES2"):
2700
- expectedKeyOp = "deriveBits";
2701
- break;
2702
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
2703
- if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
2704
- else expectedKeyOp = usage;
2705
- break;
2706
- case usage === "encrypt" && alg.startsWith("RSA"):
2707
- expectedKeyOp = "wrapKey";
2708
- break;
2709
- case usage === "decrypt":
2710
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
2711
- break;
2712
- }
2713
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
2714
- }
2715
- return true;
2716
- };
2717
- const symmetricTypeCheck = (alg, key, usage) => {
2718
- if (key instanceof Uint8Array) return;
2719
- if (isJWK(key)) {
2720
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
2721
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
2722
- }
2723
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
2724
- if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
2725
- };
2726
- const asymmetricTypeCheck = (alg, key, usage) => {
2727
- if (isJWK(key)) switch (usage) {
2728
- case "decrypt":
2729
- case "sign":
2730
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
2731
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
2732
- case "encrypt":
2733
- case "verify":
2734
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
2735
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
2736
- }
2737
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
2738
- if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
2739
- if (key.type === "public") switch (usage) {
2740
- case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
2741
- case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
2742
- }
2743
- if (key.type === "private") switch (usage) {
2744
- case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
2745
- case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
2746
- }
2747
- };
2748
- function checkKeyType(alg, key, usage) {
2749
- switch (alg.substring(0, 2)) {
2750
- case "A1":
2751
- case "A2":
2752
- case "di":
2753
- case "HS":
2754
- case "PB":
2755
- symmetricTypeCheck(alg, key, usage);
2756
- break;
2757
- default: asymmetricTypeCheck(alg, key, usage);
2758
- }
2601
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_algorithms.js
2602
+ const sig = [["verify"], ["sign"]];
2603
+ function hmac(bits) {
2604
+ const subtle = {
2605
+ name: "HMAC",
2606
+ hash: `SHA-${bits}`
2607
+ };
2608
+ return {
2609
+ kty: ["oct"],
2610
+ secret: !0,
2611
+ subtle,
2612
+ signing: subtle,
2613
+ usages: sig
2614
+ };
2615
+ }
2616
+ function rsa(bits, saltLength) {
2617
+ const subtle = {
2618
+ name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
2619
+ hash: `SHA-${bits}`
2620
+ };
2621
+ return {
2622
+ kty: ["RSA"],
2623
+ subtle,
2624
+ signing: saltLength ? {
2625
+ ...subtle,
2626
+ saltLength
2627
+ } : subtle,
2628
+ usages: sig,
2629
+ minRsaBits: 2048
2630
+ };
2631
+ }
2632
+ function ecdsa(crv, bits) {
2633
+ return {
2634
+ kty: ["EC"],
2635
+ crv,
2636
+ subtle: {
2637
+ name: "ECDSA",
2638
+ namedCurve: crv
2639
+ },
2640
+ signing: {
2641
+ name: "ECDSA",
2642
+ hash: `SHA-${bits}`
2643
+ },
2644
+ usages: sig
2645
+ };
2646
+ }
2647
+ function eddsa() {
2648
+ const subtle = { name: "Ed25519" };
2649
+ return {
2650
+ kty: ["OKP"],
2651
+ crv: "Ed25519",
2652
+ subtle,
2653
+ signing: subtle,
2654
+ usages: sig
2655
+ };
2656
+ }
2657
+ function mldsa(bits) {
2658
+ const subtle = { name: `ML-DSA-${bits}` };
2659
+ return {
2660
+ kty: ["AKP"],
2661
+ subtle,
2662
+ signing: subtle,
2663
+ usages: sig
2664
+ };
2665
+ }
2666
+ const JWS = table({
2667
+ HS256: hmac(256),
2668
+ HS384: hmac(384),
2669
+ HS512: hmac(512),
2670
+ RS256: rsa(256),
2671
+ RS384: rsa(384),
2672
+ RS512: rsa(512),
2673
+ PS256: rsa(256, 32),
2674
+ PS384: rsa(384, 48),
2675
+ PS512: rsa(512, 64),
2676
+ ES256: ecdsa("P-256", 256),
2677
+ ES384: ecdsa("P-384", 384),
2678
+ ES512: ecdsa("P-521", 512),
2679
+ EdDSA: eddsa(),
2680
+ Ed25519: eddsa(),
2681
+ "ML-DSA-44": mldsa(44),
2682
+ "ML-DSA-65": mldsa(65),
2683
+ "ML-DSA-87": mldsa(87)
2684
+ });
2685
+ function jwsAlgorithm(alg) {
2686
+ const entry = typeof alg == "string" ? JWS[alg] : void 0;
2687
+ if (!entry) throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
2688
+ return entry;
2759
2689
  }
2760
2690
  //#endregion
2761
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jws/flattened/verify.js
2762
- async function flattenedVerify(jws, key, options) {
2763
- if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
2764
- if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
2765
- if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
2766
- if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
2767
- if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
2768
- if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
2769
- let parsedProt = {};
2770
- if (jws.protected) try {
2771
- const protectedHeader = decode(jws.protected);
2772
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
2691
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_verify.js
2692
+ function prepareVerify(options) {
2693
+ return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
2694
+ }
2695
+ function parseProtectedHeader(encodedProtected) {
2696
+ return encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid");
2697
+ }
2698
+ function encodeCompactUnencodedPayload(payload) {
2699
+ try {
2700
+ return encode$1(payload);
2773
2701
  } catch {
2774
- throw new JWSInvalid("JWS Protected Header is invalid");
2702
+ throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters");
2775
2703
  }
2776
- if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2704
+ }
2705
+ async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
2706
+ const { protected: encodedProtected, header, payload: inputPayload } = jws, parsedProt = parsedProtected ?? parseProtectedHeader(encodedProtected);
2707
+ if (!isDisjoint(parsedProt, header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2777
2708
  const joseHeader = {
2778
2709
  ...parsedProt,
2779
- ...jws.header
2780
- };
2781
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
2782
- let b64 = true;
2783
- if (extensions.has("b64")) {
2784
- b64 = parsedProt.b64;
2785
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
2786
- }
2787
- const { alg } = joseHeader;
2788
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
2789
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
2790
- if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
2710
+ ...header
2711
+ }, b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader)), { alg } = joseHeader;
2712
+ if (typeof alg != "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
2713
+ if (shared[0] && !shared[0].has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
2791
2714
  if (b64) {
2792
- if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
2793
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
2794
- let resolvedKey = false;
2795
- if (typeof key === "function") {
2796
- key = await key(parsedProt, jws);
2797
- resolvedKey = true;
2798
- }
2799
- checkKeyType(alg, key, "verify");
2800
- const data = concat(jws.protected !== void 0 ? encode$1(jws.protected) : new Uint8Array(), encode$1("."), typeof jws.payload === "string" ? b64 ? encode$1(jws.payload) : encoder$1.encode(jws.payload) : jws.payload);
2801
- const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
2802
- const k = await normalizeKey(key, alg);
2803
- if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
2804
- let payload;
2805
- if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
2806
- else if (typeof jws.payload === "string") payload = encoder$1.encode(jws.payload);
2807
- else payload = jws.payload;
2808
- const result = { payload };
2809
- if (jws.protected !== void 0) result.protectedHeader = parsedProt;
2810
- if (jws.header !== void 0) result.unprotectedHeader = jws.header;
2811
- if (resolvedKey) return {
2715
+ if (typeof inputPayload != "string") throw new JWSInvalid("JWS Payload must be a string");
2716
+ } else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
2717
+ const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
2718
+ let resolvedKey = !1;
2719
+ typeof key == "function" && (key = await key(parsedProt, jws), resolvedKey = !0);
2720
+ const entry = jwsAlgorithm(alg), data = concat(encodedProtected !== void 0 ? encode$1(encodedProtected) : new Uint8Array(), encode$1("."), typeof signingPayload == "string" ? shared[2] ??= encodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), k = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(k, entry.subtle, "verify");
2721
+ entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
2722
+ let verified = !1;
2723
+ try {
2724
+ verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);
2725
+ } catch {}
2726
+ if (!verified) throw new JWSSignatureVerificationFailed();
2727
+ const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
2728
+ return encodedProtected !== void 0 && (result.protectedHeader = parsedProt), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{
2812
2729
  ...result,
2813
2730
  key: k
2814
- };
2815
- return result;
2731
+ }, b64] : [result, b64];
2816
2732
  }
2817
- //#endregion
2818
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jws/compact/verify.js
2819
- async function compactVerify(jws, key, options) {
2820
- if (jws instanceof Uint8Array) jws = decoder.decode(jws);
2821
- if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
2733
+ async function verifyCompact(jws, shared, key) {
2734
+ if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
2822
2735
  const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
2823
2736
  if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
2824
- const verified = await flattenedVerify({
2737
+ return verifySignature({
2825
2738
  payload,
2826
2739
  protected: protectedHeader,
2827
2740
  signature
2828
- }, key, options);
2829
- const result = {
2830
- payload: verified.payload,
2831
- protectedHeader: verified.protectedHeader
2832
- };
2833
- if (typeof key === "function") return {
2834
- ...result,
2835
- key: verified.key
2836
- };
2837
- return result;
2741
+ }, shared, key, encodeCompactUnencodedPayload);
2838
2742
  }
2839
2743
  //#endregion
2840
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
2744
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
2841
2745
  const epoch = (date) => Math.floor(date.getTime() / 1e3);
2842
- const minute = 60;
2843
- const hour = minute * 60;
2844
- const day = hour * 24;
2845
- const week = day * 7;
2846
- const year = day * 365.25;
2746
+ const multipliers = {
2747
+ s: 1,
2748
+ m: 60,
2749
+ h: 3600,
2750
+ d: 86400,
2751
+ w: 604800,
2752
+ y: 31557600
2753
+ };
2847
2754
  const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
2755
+ const checkFailed = "check_failed";
2756
+ function invalidDuration() {
2757
+ throw new TypeError("Invalid time period format");
2758
+ }
2848
2759
  function secs(str) {
2760
+ typeof str != "string" && invalidDuration();
2849
2761
  const matched = REGEX.exec(str);
2850
- if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
2851
- const value = parseFloat(matched[2]);
2852
- const unit = matched[3].toLowerCase();
2853
- let numericDate;
2854
- switch (unit) {
2855
- case "sec":
2856
- case "secs":
2857
- case "second":
2858
- case "seconds":
2859
- case "s":
2860
- numericDate = Math.round(value);
2861
- break;
2862
- case "minute":
2863
- case "minutes":
2864
- case "min":
2865
- case "mins":
2866
- case "m":
2867
- numericDate = Math.round(value * minute);
2868
- break;
2869
- case "hour":
2870
- case "hours":
2871
- case "hr":
2872
- case "hrs":
2873
- case "h":
2874
- numericDate = Math.round(value * hour);
2875
- break;
2876
- case "day":
2877
- case "days":
2878
- case "d":
2879
- numericDate = Math.round(value * day);
2880
- break;
2881
- case "week":
2882
- case "weeks":
2883
- case "w":
2884
- numericDate = Math.round(value * week);
2885
- break;
2886
- default:
2887
- numericDate = Math.round(value * year);
2888
- break;
2889
- }
2890
- if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
2891
- return numericDate;
2762
+ (!matched || matched[4] && matched[1]) && invalidDuration();
2763
+ const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
2764
+ return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2;
2765
+ }
2766
+ function validateInput(label, input) {
2767
+ if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
2768
+ return input;
2892
2769
  }
2893
2770
  const normalizeTyp = (value) => {
2894
- if (value.includes("/")) return value.toLowerCase();
2895
- return `application/${value.toLowerCase()}`;
2896
- };
2897
- const checkAudiencePresence = (audPayload, audOption) => {
2898
- if (typeof audPayload === "string") return audOption.includes(audPayload);
2899
- if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
2900
- return false;
2771
+ const normalized = value.toLowerCase();
2772
+ return value.includes("/") ? normalized : `application/${normalized}`;
2901
2773
  };
2774
+ const checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;
2775
+ function validateNumericDate(payload, claim, required = !1) {
2776
+ const value = payload[claim];
2777
+ if (!(value === void 0 && !required)) {
2778
+ if (typeof value != "number") throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid");
2779
+ return value;
2780
+ }
2781
+ }
2782
+ function unexpectedClaim(payload, claim) {
2783
+ throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed);
2784
+ }
2902
2785
  function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
2903
2786
  let payload;
2904
2787
  try {
2905
- payload = JSON.parse(decoder.decode(encodedPayload));
2788
+ payload = JSON.parse(strictDecoder.decode(encodedPayload));
2906
2789
  } catch {}
2907
2790
  if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
2908
2791
  const { typ } = options;
2909
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
2910
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
2911
- const presenceCheck = [...requiredClaims];
2912
- if (maxTokenAge !== void 0) presenceCheck.push("iat");
2913
- if (audience !== void 0) presenceCheck.push("aud");
2914
- if (subject !== void 0) presenceCheck.push("sub");
2915
- if (issuer !== void 0) presenceCheck.push("iss");
2916
- for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
2917
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
2918
- if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
2919
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
2920
- let tolerance;
2921
- switch (typeof options.clockTolerance) {
2922
- case "string":
2923
- tolerance = secs(options.clockTolerance);
2924
- break;
2925
- case "number":
2926
- tolerance = options.clockTolerance;
2927
- break;
2928
- case "undefined":
2929
- tolerance = 0;
2930
- break;
2931
- default: throw new TypeError("Invalid clockTolerance option type");
2932
- }
2933
- const { currentDate } = options;
2934
- const now = epoch(currentDate || new Date());
2935
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
2936
- if (payload.nbf !== void 0) {
2937
- if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
2938
- if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
2939
- }
2940
- if (payload.exp !== void 0) {
2941
- if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
2942
- if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
2792
+ if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", checkFailed);
2793
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
2794
+ maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
2795
+ for (const claim of new Set(presenceCheck.reverse())) if (!Object.hasOwn(payload, claim)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
2796
+ issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud");
2797
+ const { clockTolerance } = options;
2798
+ let tolerance = 0;
2799
+ if (typeof clockTolerance == "string") tolerance = secs(clockTolerance);
2800
+ else if (clockTolerance !== void 0) {
2801
+ if (typeof clockTolerance != "number") throw new TypeError("Invalid clockTolerance option type");
2802
+ tolerance = clockTolerance;
2943
2803
  }
2944
- if (maxTokenAge) {
2945
- const age = now - payload.iat;
2946
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
2947
- if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
2948
- if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
2804
+ validateInput("clockTolerance option", tolerance);
2805
+ const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? new Date() : currentDate)), iat = validateNumericDate(payload, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(payload, "nbf");
2806
+ if (nbf !== void 0 && nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", checkFailed);
2807
+ const exp = validateNumericDate(payload, "exp");
2808
+ if (exp !== void 0 && exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", checkFailed);
2809
+ if (maxTokenAge !== void 0) {
2810
+ const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
2811
+ if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", checkFailed);
2812
+ if (age < -tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", checkFailed);
2949
2813
  }
2950
2814
  return payload;
2951
2815
  }
2952
2816
  //#endregion
2953
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jwt/verify.js
2817
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/verify.js
2954
2818
  async function jwtVerify(jwt, key, options) {
2955
- const verified = await compactVerify(jwt, key, options);
2956
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
2957
- const result = {
2958
- payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
2959
- protectedHeader: verified.protectedHeader
2819
+ const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
2820
+ if (!b64) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
2821
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
2822
+ return {
2823
+ ...verified,
2824
+ payload
2960
2825
  };
2961
- if (typeof key === "function") return {
2962
- ...result,
2963
- key: verified.key
2826
+ }
2827
+ //#endregion
2828
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_algorithm.js
2829
+ function unsupportedAlg(source = "JWK \"alg\" (Algorithm) Parameter") {
2830
+ throw new JOSENotSupported(`Invalid or unsupported ${source} value`);
2831
+ }
2832
+ function keyAlgorithm(alg, source) {
2833
+ return (typeof alg == "string" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);
2834
+ }
2835
+ //#endregion
2836
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/key/export.js
2837
+ async function exportJWK(key) {
2838
+ if (isKeyObject(key)) if (key.type === "secret") key = key.export();
2839
+ else return key.export({ format: "jwk" });
2840
+ if (key instanceof Uint8Array) return {
2841
+ kty: "oct",
2842
+ k: encode(key)
2964
2843
  };
2965
- return result;
2844
+ if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
2845
+ if (!key.extractable) throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
2846
+ const jwk = await crypto.subtle.exportKey("jwk", key);
2847
+ delete jwk.ext, delete jwk.key_ops, delete jwk.use, jwk.kty !== "AKP" && delete jwk.alg;
2848
+ for (const parameter of Object.keys(jwk)) jwk[parameter] === void 0 && delete jwk[parameter];
2849
+ return jwk;
2966
2850
  }
2967
2851
  //#endregion
2968
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jwk/thumbprint.js
2852
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwk/thumbprint.js
2969
2853
  const check = (value, description) => {
2970
- if (typeof value !== "string" || !value) throw new JWKInvalid(`${description} missing or invalid`);
2854
+ if (typeof value != "string" || !value) throw new JWKInvalid(`${description} missing or invalid`);
2971
2855
  };
2972
2856
  async function calculateJwkThumbprint(key, digestAlgorithm) {
2973
2857
  let jwk;
2974
- if (isJWK(key)) jwk = key;
2975
- else if (isKeyLike(key)) jwk = await exportJWK(key);
2858
+ if (isObject(key)) {
2859
+ if (jwk = snapshotJwk(key), typeof jwk.kty != "string") throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
2860
+ } else if (isKeyLike(key)) jwk = snapshotJwk(await exportJWK(key));
2976
2861
  else throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
2977
- digestAlgorithm ??= "sha256";
2978
- if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") throw new TypeError("digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"");
2862
+ if (digestAlgorithm ??= "sha256", digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") throw new TypeError("digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"");
2979
2863
  let components;
2980
2864
  switch (jwk.kty) {
2981
2865
  case "AKP":
2982
- check(jwk.alg, "\"alg\" (Algorithm) Parameter");
2983
- check(jwk.pub, "\"pub\" (Public key) Parameter");
2984
- components = {
2866
+ check(jwk.alg, "\"alg\" (Algorithm) Parameter"), check(jwk.pub, "\"pub\" (Public key) Parameter"), components = {
2985
2867
  alg: jwk.alg,
2986
2868
  kty: jwk.kty,
2987
2869
  pub: jwk.pub
2988
2870
  };
2989
2871
  break;
2990
2872
  case "EC":
2991
- check(jwk.crv, "\"crv\" (Curve) Parameter");
2992
- check(jwk.x, "\"x\" (X Coordinate) Parameter");
2993
- check(jwk.y, "\"y\" (Y Coordinate) Parameter");
2994
- components = {
2873
+ check(jwk.crv, "\"crv\" (Curve) Parameter"), check(jwk.x, "\"x\" (X Coordinate) Parameter"), check(jwk.y, "\"y\" (Y Coordinate) Parameter"), components = {
2995
2874
  crv: jwk.crv,
2996
2875
  kty: jwk.kty,
2997
2876
  x: jwk.x,
@@ -2999,25 +2878,21 @@ async function calculateJwkThumbprint(key, digestAlgorithm) {
2999
2878
  };
3000
2879
  break;
3001
2880
  case "OKP":
3002
- check(jwk.crv, "\"crv\" (Subtype of Key Pair) Parameter");
3003
- check(jwk.x, "\"x\" (Public Key) Parameter");
3004
- components = {
2881
+ check(jwk.crv, "\"crv\" (Subtype of Key Pair) Parameter"), check(jwk.x, "\"x\" (Public Key) Parameter"), components = {
3005
2882
  crv: jwk.crv,
3006
2883
  kty: jwk.kty,
3007
2884
  x: jwk.x
3008
2885
  };
3009
2886
  break;
3010
2887
  case "RSA":
3011
- check(jwk.e, "\"e\" (Exponent) Parameter");
3012
- check(jwk.n, "\"n\" (Modulus) Parameter");
3013
- components = {
2888
+ check(jwk.e, "\"e\" (Exponent) Parameter"), check(jwk.n, "\"n\" (Modulus) Parameter"), components = {
3014
2889
  e: jwk.e,
3015
2890
  kty: jwk.kty,
3016
2891
  n: jwk.n
3017
2892
  };
3018
2893
  break;
3019
2894
  case "oct":
3020
- check(jwk.k, "\"k\" (Key Value) Parameter");
2895
+ if (typeof jwk.k != "string") throw new JWKInvalid("\"k\" (Key Value) Parameter missing or invalid");
3021
2896
  components = {
3022
2897
  k: jwk.k,
3023
2898
  kty: jwk.kty
@@ -3029,27 +2904,42 @@ async function calculateJwkThumbprint(key, digestAlgorithm) {
3029
2904
  return encode(await digest(digestAlgorithm, data));
3030
2905
  }
3031
2906
  //#endregion
3032
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/decode_protected_header.js
2907
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/key/import.js
2908
+ async function importJWK(jwk, alg, options) {
2909
+ if (!isObject(jwk)) throw new TypeError("JWK must be an object");
2910
+ const normalized = normalizeJwk(jwk), extractable = validateExtractableOption(options?.extractable), { alg: jwkAlg } = normalized;
2911
+ if (alg ??= jwkAlg, normalized.kty !== "oct" && !alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
2912
+ switch (normalized.kty) {
2913
+ case "oct":
2914
+ if (typeof normalized.k != "string") throw new TypeError("missing \"k\" (Key Value) Parameter value");
2915
+ return decode(normalized.k);
2916
+ case "AKP":
2917
+ if (typeof jwkAlg != "string" || !jwkAlg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
2918
+ if (alg !== jwkAlg) throw new TypeError("JWK alg and alg option value mismatch");
2919
+ return jwkToKey(keyAlgorithm(alg), normalized, extractable);
2920
+ case "RSA":
2921
+ case "EC":
2922
+ case "OKP": return jwkToKey(keyAlgorithm(alg), normalized, extractable);
2923
+ default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
2924
+ }
2925
+ }
2926
+ //#endregion
2927
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/decode_protected_header.js
3033
2928
  function decodeProtectedHeader(token) {
3034
2929
  let protectedB64u;
3035
- if (typeof token === "string") {
2930
+ if (typeof token == "string") {
3036
2931
  const parts = token.split(".");
3037
- if (parts.length === 3 || parts.length === 5) [protectedB64u] = parts;
3038
- } else if (typeof token === "object" && token) if ("protected" in token) protectedB64u = token.protected;
2932
+ (parts.length === 3 || parts.length === 5) && ([protectedB64u] = parts);
2933
+ } else if (typeof token == "object" && token) if ("protected" in token) protectedB64u = token.protected;
3039
2934
  else throw new TypeError("Token does not contain a Protected Header");
3040
- try {
3041
- if (typeof protectedB64u !== "string" || !protectedB64u) throw new Error();
3042
- const result = JSON.parse(decoder.decode(decode(protectedB64u)));
3043
- if (!isObject(result)) throw new Error();
3044
- return result;
3045
- } catch {
3046
- throw new TypeError("Invalid Token or Protected Header formatting");
3047
- }
2935
+ const invalid = "Invalid Token or Protected Header formatting";
2936
+ if (typeof protectedB64u != "string" || !protectedB64u) throw new TypeError(invalid);
2937
+ return parseJoseHeader(protectedB64u, TypeError, invalid);
3048
2938
  }
3049
2939
  //#endregion
3050
- //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/decode_jwt.js
2940
+ //#region ../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/decode_jwt.js
3051
2941
  function decodeJwt(jwt) {
3052
- if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
2942
+ if (typeof jwt != "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
3053
2943
  const { 1: payload, length } = jwt.split(".");
3054
2944
  if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
3055
2945
  if (length !== 3) throw new JWTInvalid("Invalid JWT");
@@ -3062,7 +2952,7 @@ function decodeJwt(jwt) {
3062
2952
  }
3063
2953
  let result;
3064
2954
  try {
3065
- result = JSON.parse(decoder.decode(decoded));
2955
+ result = JSON.parse(strictDecoder.decode(decoded));
3066
2956
  } catch {
3067
2957
  throw new JWTInvalid("Failed to parse the decoded payload as JSON");
3068
2958
  }
@@ -3073,7 +2963,9 @@ function decodeJwt(jwt) {
3073
2963
  //#region src/organization-presence.ts
3074
2964
  const id$1 = /^[A-Za-z0-9_-]{1,128}$(?![\s\S])/;
3075
2965
  function presenceInput(input) {
3076
- if (!input || typeof input.applicationId !== "string" || !id$1.test(input.applicationId) || !Array.isArray(input.userIds) || input.userIds.length < 1 || input.userIds.length > 50 || input.userIds.some((value) => typeof value !== "string" || !id$1.test(value)) || new Set(input.userIds).size !== input.userIds.length) throw new TypeError("Organization presence selection is invalid");
2966
+ if (!input || typeof input.applicationId !== "string" || !id$1.test(input.applicationId) || !Array.isArray(input.userIds) || input.userIds.length < 1 || input.userIds.length > 50 || input.userIds.some((value) => {
2967
+ return typeof value !== "string" || !id$1.test(value);
2968
+ }) || new Set(input.userIds).size !== input.userIds.length) throw new TypeError("Organization presence selection is invalid");
3077
2969
  return {
3078
2970
  applicationId: input.applicationId,
3079
2971
  userIds: [...input.userIds]
@@ -3092,7 +2984,9 @@ function presenceProofActor(token, applicationId) {
3092
2984
  }
3093
2985
  }
3094
2986
  function exact$5(value, keys) {
3095
- return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
2987
+ return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => {
2988
+ return Object.hasOwn(value, key);
2989
+ });
3096
2990
  }
3097
2991
  function normalizePresence(value, organizationId, input, actor) {
3098
2992
  if (!exact$5(value, [
@@ -3101,7 +2995,9 @@ function normalizePresence(value, organizationId, input, actor) {
3101
2995
  "actor",
3102
2996
  "userIds",
3103
2997
  "checkedAt"
3104
- ]) || value.organizationId !== organizationId || value.applicationId !== input.applicationId || !exact$5(value.actor, ["userId", "sessionId"]) || value.actor.userId !== actor.userId || value.actor.sessionId !== actor.sessionId || !Array.isArray(value.userIds) || value.userIds.length !== input.userIds.length || value.userIds.some((userId, index) => userId !== input.userIds[index]) || typeof value.checkedAt !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$(?![\s\S])/.test(value.checkedAt) || Number.isNaN(Date.parse(value.checkedAt)) || new Date(value.checkedAt).toISOString() !== value.checkedAt) throw new AuthError("identity_authority_unavailable", 503);
2998
+ ]) || value.organizationId !== organizationId || value.applicationId !== input.applicationId || !exact$5(value.actor, ["userId", "sessionId"]) || value.actor.userId !== actor.userId || value.actor.sessionId !== actor.sessionId || !Array.isArray(value.userIds) || value.userIds.length !== input.userIds.length || value.userIds.some((userId, index) => {
2999
+ return userId !== input.userIds[index];
3000
+ }) || typeof value.checkedAt !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$(?![\s\S])/.test(value.checkedAt) || Number.isNaN(Date.parse(value.checkedAt)) || new Date(value.checkedAt).toISOString() !== value.checkedAt) throw new AuthError("identity_authority_unavailable", 503);
3105
3001
  return {
3106
3002
  organizationId,
3107
3003
  applicationId: input.applicationId,
@@ -3114,7 +3010,9 @@ function normalizePresence(value, organizationId, input, actor) {
3114
3010
  //#region src/enterprise.ts
3115
3011
  const idPattern$1 = /^[A-Za-z0-9_-]{1,128}$(?![\s\S])/;
3116
3012
  function exact$4(value, keys) {
3117
- return isObject$1(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
3013
+ return isObject$1(value) && Object.keys(value).length === keys.length && keys.every((key) => {
3014
+ return Object.hasOwn(value, key);
3015
+ });
3118
3016
  }
3119
3017
  function normalizeOrganizationSignInState(value) {
3120
3018
  if (exact$4(value, ["status", "mode"]) && value.status === "available" && (value.mode === "membership" || value.mode === "provider")) return {
@@ -3142,17 +3040,23 @@ function normalizeOrganizationSignInStates(value, requestedIds) {
3142
3040
  //#region src/application-access.ts
3143
3041
  const id = /^[A-Za-z0-9_-]{1,128}$(?![\s\S])/;
3144
3042
  function applicationAccessInput(input) {
3145
- if (!input || typeof input.applicationId !== "string" || !id.test(input.applicationId) || !Array.isArray(input.userIds) || input.userIds.length < 1 || input.userIds.length > 50 || input.userIds.some((value) => typeof value !== "string" || !id.test(value)) || new Set(input.userIds).size !== input.userIds.length) throw new TypeError("Application access input is invalid");
3043
+ if (!input || typeof input.applicationId !== "string" || !id.test(input.applicationId) || !Array.isArray(input.userIds) || input.userIds.length < 1 || input.userIds.length > 50 || input.userIds.some((value) => {
3044
+ return typeof value !== "string" || !id.test(value);
3045
+ }) || new Set(input.userIds).size !== input.userIds.length) throw new TypeError("Application access input is invalid");
3146
3046
  return {
3147
3047
  applicationId: input.applicationId,
3148
3048
  userIds: [...input.userIds]
3149
3049
  };
3150
3050
  }
3151
3051
  function exact$3(value, keys) {
3152
- return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
3052
+ return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => {
3053
+ return Object.hasOwn(value, key);
3054
+ });
3153
3055
  }
3154
3056
  function normalizeApplicationAccess(value, userIds) {
3155
- const invalid = () => new AuthError("identity_authority_unavailable", 503);
3057
+ const invalid = () => {
3058
+ return new AuthError("identity_authority_unavailable", 503);
3059
+ };
3156
3060
  if (!exact$3(value, ["members"]) || !Array.isArray(value.members) || value.members.length !== userIds.length) throw invalid();
3157
3061
  return { members: value.members.map((member, index) => {
3158
3062
  if (!exact$3(member, [
@@ -3176,7 +3080,9 @@ function validTicket(value) {
3176
3080
  return typeof value === "string" && /^[A-Za-z0-9_-]{43}$/.test(value);
3177
3081
  }
3178
3082
  function googleRecoveryInput(value, complete) {
3179
- if (!object(value) || Object.keys(value).sort().join(",") !== (complete ? "idToken,recoveryToken" : "idToken") || !object(value.idToken) || Object.keys(value.idToken).some((key) => key !== "token" && key !== "nonce") || complete && !validTicket(value.recoveryToken)) throw new AuthError("invalid_request", 400);
3083
+ if (!object(value) || Object.keys(value).sort().join(",") !== (complete ? "idToken,recoveryToken" : "idToken") || !object(value.idToken) || Object.keys(value.idToken).some((key) => {
3084
+ return key !== "token" && key !== "nonce";
3085
+ }) || complete && !validTicket(value.recoveryToken)) throw new AuthError("invalid_request", 400);
3180
3086
  const social = normalizeSocialIdTokenInput({
3181
3087
  provider: "google",
3182
3088
  idToken: value.idToken.token,
@@ -3194,7 +3100,7 @@ function googleRecoveryInput(value, complete) {
3194
3100
  function normalizeGoogleRecovery(value, now) {
3195
3101
  if (!object(value) || Object.keys(value).sort().join(",") !== "expiresAt,recoveryToken" || !validTicket(value.recoveryToken) || typeof value.expiresAt !== "string") throw authorityUnavailable();
3196
3102
  const expiresAt = Date.parse(value.expiresAt);
3197
- if (!Number.isFinite(expiresAt) || expiresAt <= now || expiresAt > now + 10 * 6e4) throw authorityUnavailable();
3103
+ if (!Number.isFinite(expiresAt) || expiresAt <= now || expiresAt > now + 6e5) throw authorityUnavailable();
3198
3104
  return {
3199
3105
  recoveryToken: value.recoveryToken,
3200
3106
  expiresAt: value.expiresAt
@@ -3223,7 +3129,7 @@ function userApiApplication(input) {
3223
3129
  return input.applicationId;
3224
3130
  }
3225
3131
  function normalizeUserApiCredential(value, startedAt) {
3226
- if (!value || typeof value !== "object" || Array.isArray(value) || !("tokenType" in value) || value.tokenType !== "Bearer" || !("token" in value) || typeof value.token !== "string" || value.token.length + 7 > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value.token) || !("expiresIn" in value) || typeof value.expiresIn !== "number" || !Number.isInteger(value.expiresIn) || value.expiresIn < 1 || value.expiresIn > 840 || Object.keys(value).sort().join(",") !== "expiresIn,token,tokenType") throw new AuthError("identity_authority_unavailable", 503);
3132
+ if (!value || typeof value !== "object" || Array.isArray(value) || !("tokenType" in value) || value.tokenType !== "Bearer" || !("token" in value) || typeof value.token !== "string" || value.token.length + 7 > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value.token) || !("expiresIn" in value) || typeof value.expiresIn !== "number" || !Number.isInteger(value.expiresIn) || value.expiresIn < 1 || value.expiresIn > 840 || Object.keys(value).sort().join(",") !== "expiresIn,token,tokenType") throw new AuthError("identity_authority_unavailable", 503);
3227
3133
  return {
3228
3134
  tokenType: "Bearer",
3229
3135
  token: value.token,
@@ -3238,8 +3144,12 @@ const PROFILE = "finueva-user-api+jwt";
3238
3144
  const CACHE_MS = 3e5;
3239
3145
  const REFRESH_COOLDOWN_MS = 3e4;
3240
3146
  const TIMEOUT_MS = 2e3;
3241
- const invalid = () => new AuthError("authentication_required", 401);
3242
- const unavailable = () => new AuthError("identity_authority_unavailable", 503);
3147
+ const invalid = () => {
3148
+ return new AuthError("authentication_required", 401);
3149
+ };
3150
+ const unavailable = () => {
3151
+ return new AuthError("identity_authority_unavailable", 503);
3152
+ };
3243
3153
  function record(value) {
3244
3154
  return value !== null && typeof value === "object" && !Array.isArray(value);
3245
3155
  }
@@ -3280,7 +3190,7 @@ function createUserApiVerifier(options) {
3280
3190
  method: "GET",
3281
3191
  credentials: "omit",
3282
3192
  signal: controller.signal,
3283
- maxResponseBytes: 64 * 1024
3193
+ maxResponseBytes: 65536
3284
3194
  }), deadline]);
3285
3195
  if (!record(value) || !exactKeys(value, ["keys"]) || !Array.isArray(value.keys) || value.keys.length < 1 || value.keys.length > 20) throw unavailable();
3286
3196
  const keys = new Map();
@@ -3333,7 +3243,7 @@ function createUserApiVerifier(options) {
3333
3243
  return key;
3334
3244
  }
3335
3245
  return { async verify(token) {
3336
- if (typeof token !== "string" || token.length + 7 > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) throw invalid();
3246
+ if (typeof token !== "string" || token.length + 7 > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) throw invalid();
3337
3247
  let kid;
3338
3248
  try {
3339
3249
  const header = decodeProtectedHeader(token);
@@ -3416,7 +3326,9 @@ function createUserApiVerifier(options) {
3416
3326
  //#region src/identity-resolution.ts
3417
3327
  const emailPattern$1 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$(?![\s\S])/;
3418
3328
  function exact$2(value, keys) {
3419
- return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
3329
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => {
3330
+ return Object.hasOwn(value, key);
3331
+ });
3420
3332
  }
3421
3333
  function createIdentityResolverAuth(options) {
3422
3334
  const url = joinURL(normalizeOrigin(options.authOrigin, "authOrigin"), "api/v1/auth/identities/resolve");
@@ -3428,7 +3340,7 @@ function createIdentityResolverAuth(options) {
3428
3340
  if (!exact$2(input, ["identifier"]) || typeof input.identifier !== "string" || input.identifier.length > 324) throw new AuthError("invalid_request", 400);
3429
3341
  const identifier = input.identifier.trim().toLowerCase();
3430
3342
  if (!(identifier.length <= 320 && emailPattern$1.test(identifier)) && !/^[a-z0-9_.]{3,30}$(?![\s\S])/.test(identifier)) throw new AuthError("invalid_request", 400);
3431
- if (typeof clientAssertion !== "string" || clientAssertion.length + 7 > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(clientAssertion)) throw new AuthError("invalid_request", 400);
3343
+ if (typeof clientAssertion !== "string" || clientAssertion.length + 7 > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(clientAssertion)) throw new AuthError("invalid_request", 400);
3432
3344
  if (inFlight) throw new AuthError("state_conflict", 409);
3433
3345
  inFlight = true;
3434
3346
  const controller = new AbortController();
@@ -3524,7 +3436,9 @@ const membershipKeys = [
3524
3436
  "userId"
3525
3437
  ];
3526
3438
  function exact$1(value, keys) {
3527
- return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
3439
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => {
3440
+ return Object.hasOwn(value, key);
3441
+ });
3528
3442
  }
3529
3443
  function parseMembership(value, organizationId, userId) {
3530
3444
  if (!exact$1(value, ["membership"])) throw authorityUnavailable();
@@ -3550,8 +3464,8 @@ function createMembershipResolverAuth(options) {
3550
3464
  let inFlight = false;
3551
3465
  async function exchange(body, clientAssertion, batch, parseResult) {
3552
3466
  const url = joinURL(origin, batch ? "api/v1/auth/memberships/resolve-batch" : "api/v1/auth/memberships/resolve");
3553
- const maxBytes = batch ? 512 * 1024 : 1024;
3554
- if (typeof clientAssertion !== "string" || clientAssertion.length + 7 > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(clientAssertion)) throw new AuthError("invalid_request", 400);
3467
+ const maxBytes = batch ? 524288 : 1024;
3468
+ if (typeof clientAssertion !== "string" || clientAssertion.length + 7 > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(clientAssertion)) throw new AuthError("invalid_request", 400);
3555
3469
  if (inFlight) throw new AuthError("state_conflict", 409);
3556
3470
  inFlight = true;
3557
3471
  const controller = new AbortController();
@@ -3630,14 +3544,20 @@ function createMembershipResolverAuth(options) {
3630
3544
  return exchange({
3631
3545
  organizationId,
3632
3546
  userId
3633
- }, assertion, false, (value) => parseMembership(value, organizationId, userId));
3547
+ }, assertion, false, (value) => {
3548
+ return parseMembership(value, organizationId, userId);
3549
+ });
3634
3550
  },
3635
3551
  async resolveMembershipBatch(input, assertion) {
3636
3552
  if (!input || typeof input !== "object" || Array.isArray(input) || !exact$1(input, Object.hasOwn(input, "teamIds") ? [
3637
3553
  "organizationId",
3638
3554
  "userIds",
3639
3555
  "teamIds"
3640
- ] : ["organizationId", "userIds"]) || typeof input.organizationId !== "string" || !idPattern.test(input.organizationId) || !Array.isArray(input.userIds) || input.userIds.length < 1 || input.userIds.length > 100 || input.userIds.some((id) => typeof id !== "string" || !idPattern.test(id)) || new Set(input.userIds).size !== input.userIds.length || input.teamIds !== void 0 && (!Array.isArray(input.teamIds) || input.teamIds.length > 32 || input.teamIds.some((id) => typeof id !== "string" || !idPattern.test(id)) || new Set(input.teamIds).size !== input.teamIds.length)) throw new AuthError("invalid_request", 400);
3556
+ ] : ["organizationId", "userIds"]) || typeof input.organizationId !== "string" || !idPattern.test(input.organizationId) || !Array.isArray(input.userIds) || input.userIds.length < 1 || input.userIds.length > 100 || input.userIds.some((id) => {
3557
+ return typeof id !== "string" || !idPattern.test(id);
3558
+ }) || new Set(input.userIds).size !== input.userIds.length || input.teamIds !== void 0 && (!Array.isArray(input.teamIds) || input.teamIds.length > 32 || input.teamIds.some((id) => {
3559
+ return typeof id !== "string" || !idPattern.test(id);
3560
+ }) || new Set(input.teamIds).size !== input.teamIds.length)) throw new AuthError("invalid_request", 400);
3641
3561
  const organizationId = input.organizationId;
3642
3562
  const userIds = [...input.userIds];
3643
3563
  const teamIds = [...input.teamIds ?? []];
@@ -3653,7 +3573,9 @@ function createMembershipResolverAuth(options) {
3653
3573
  "userId",
3654
3574
  "membership",
3655
3575
  "matchingTeamIds"
3656
- ]) || entry.userId !== userId || !Array.isArray(entry.matchingTeamIds) || entry.matchingTeamIds.length > teamIds.length || entry.matchingTeamIds.some((id) => typeof id !== "string" || !teamIds.includes(id)) || new Set(entry.matchingTeamIds).size !== entry.matchingTeamIds.length) throw authorityUnavailable();
3576
+ ]) || entry.userId !== userId || !Array.isArray(entry.matchingTeamIds) || entry.matchingTeamIds.length > teamIds.length || entry.matchingTeamIds.some((id) => {
3577
+ return typeof id !== "string" || !teamIds.includes(id);
3578
+ }) || new Set(entry.matchingTeamIds).size !== entry.matchingTeamIds.length) throw authorityUnavailable();
3657
3579
  const membership = parseMembership({ membership: entry.membership }, organizationId, userId);
3658
3580
  if (!membership && entry.matchingTeamIds.length) throw authorityUnavailable();
3659
3581
  return {
@@ -3678,7 +3600,9 @@ function validEmail(value) {
3678
3600
  return typeof value === "string" && encoder.encode(value).byteLength <= 320 && emailPattern.test(value);
3679
3601
  }
3680
3602
  function exact(value, keys) {
3681
- return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
3603
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => {
3604
+ return Object.hasOwn(value, key);
3605
+ });
3682
3606
  }
3683
3607
  const failures = {
3684
3608
  400: [
@@ -3741,7 +3665,7 @@ function createDriveRecipientAuth(options) {
3741
3665
  throw new AuthError("invalid_request", 400);
3742
3666
  }
3743
3667
  if (encoder.encode(body).byteLength > 1024) throw new AuthError("invalid_request", 413);
3744
- if (typeof clientAssertion !== "string" || clientAssertion.length + 7 > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(clientAssertion)) throw new AuthError("invalid_request", 400);
3668
+ if (typeof clientAssertion !== "string" || clientAssertion.length + 7 > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(clientAssertion)) throw new AuthError("invalid_request", 400);
3745
3669
  if (inFlight) throw new AuthError("state_conflict", 409);
3746
3670
  inFlight = true;
3747
3671
  const controller = new AbortController();
@@ -3831,7 +3755,7 @@ function createDriveRecipientAuth(options) {
3831
3755
  }
3832
3756
  //#endregion
3833
3757
  //#region src/provisioning.ts
3834
- const MAX_BYTES = 16 * 1024;
3758
+ const MAX_BYTES = 16384;
3835
3759
  const compactJwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
3836
3760
  function isCompactCredential(value) {
3837
3761
  return typeof value === "string" && value.length + 7 <= MAX_BYTES && compactJwt.test(value);
@@ -3854,7 +3778,7 @@ function createDriveProvisioningAuth(options) {
3854
3778
  let authorityError;
3855
3779
  try {
3856
3780
  const startedAt = now();
3857
- if (!Number.isSafeInteger(startedAt) || startedAt < 0 || startedAt > 86399999997e5) throw authorityUnavailable();
3781
+ if (!Number.isSafeInteger(startedAt) || startedAt < 0 || startedAt > 864e13 - 3e5) throw authorityUnavailable();
3858
3782
  const deadline = new Promise((_, reject) => {
3859
3783
  timer = setTimeout(() => {
3860
3784
  reject(authorityUnavailable());
@@ -3961,12 +3885,14 @@ function exactInput(input) {
3961
3885
  ]) || !directoryId(input.applicationId) || !directoryGeneration(input.userId) || !directoryGeneration(input.userGeneration)) throw new AuthError("invalid_request", 400);
3962
3886
  }
3963
3887
  function pageInput(input, members = false) {
3964
- if (!record$1(input) || Object.keys(input).some((key) => ![
3965
- "applicationId",
3966
- "limit",
3967
- "cursor",
3968
- ...members ? ["organizationId", "organizationGeneration"] : []
3969
- ].includes(key)) || !directoryId(input.applicationId) || input.limit !== void 0 && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 100) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length < 1 || input.cursor.length > 2048) || members && (!directoryId(input.organizationId) || !directoryGeneration(input.organizationGeneration))) throw new AuthError("invalid_request", 400);
3888
+ if (!record$1(input) || Object.keys(input).some((key) => {
3889
+ return ![
3890
+ "applicationId",
3891
+ "limit",
3892
+ "cursor",
3893
+ ...members ? ["organizationId", "organizationGeneration"] : []
3894
+ ].includes(key);
3895
+ }) || !directoryId(input.applicationId) || input.limit !== void 0 && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 100) || input.cursor !== void 0 && (typeof input.cursor !== "string" || input.cursor.length < 1 || input.cursor.length > 2048) || members && (!directoryId(input.organizationId) || !directoryGeneration(input.organizationGeneration))) throw new AuthError("invalid_request", 400);
3970
3896
  }
3971
3897
  function nextCursor(value) {
3972
3898
  if (value !== null && (typeof value !== "string" || !value.length || value.length > 2048)) throw authorityUnavailable();
@@ -3984,7 +3910,7 @@ function createUserDirectoryAuth(options) {
3984
3910
  const timeoutMs = normalizeTimeout(options.timeoutMs);
3985
3911
  let inFlight = 0;
3986
3912
  async function exchange(operation, body, assertion) {
3987
- if (typeof assertion !== "string" || assertion.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
3913
+ if (typeof assertion !== "string" || assertion.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
3988
3914
  if (inFlight >= 4) throw new AuthError("state_conflict", 409);
3989
3915
  inFlight += 1;
3990
3916
  const controller = new AbortController();
@@ -4008,7 +3934,7 @@ function createUserDirectoryAuth(options) {
4008
3934
  accept: "application/json"
4009
3935
  },
4010
3936
  body,
4011
- maxResponseBytes: 128 * 1024,
3937
+ maxResponseBytes: 131072,
4012
3938
  signal: controller.signal
4013
3939
  }).finally(() => {
4014
3940
  inFlight -= 1;
@@ -4026,8 +3952,14 @@ function createUserDirectoryAuth(options) {
4026
3952
  pageInput(input);
4027
3953
  const value = await exchange("list", input, assertion);
4028
3954
  if (!exact$7(value, ["users", "nextCursor"]) || !Array.isArray(value.users) || value.users.length > (input.limit ?? 50)) throw authorityUnavailable();
4029
- const users = value.users.map((item) => user$1(item, input.applicationId));
4030
- if (users.some((item) => item.lifecycle === "deleted") || new Set(users.map((item) => item.userId)).size !== users.length) throw authorityUnavailable();
3955
+ const users = value.users.map((item) => {
3956
+ return user$1(item, input.applicationId);
3957
+ });
3958
+ if (users.some((item) => {
3959
+ return item.lifecycle === "deleted";
3960
+ }) || new Set(users.map((item) => {
3961
+ return item.userId;
3962
+ })).size !== users.length) throw authorityUnavailable();
4031
3963
  return {
4032
3964
  users,
4033
3965
  nextCursor: nextCursor(value.nextCursor)
@@ -4063,7 +3995,9 @@ function createUserDirectoryAuth(options) {
4063
3995
  membershipStatus: item.membershipStatus
4064
3996
  };
4065
3997
  });
4066
- if (new Set(members.map((item) => item.user.userId)).size !== members.length) throw authorityUnavailable();
3998
+ if (new Set(members.map((item) => {
3999
+ return item.user.userId;
4000
+ })).size !== members.length) throw authorityUnavailable();
4067
4001
  return {
4068
4002
  applicationId: input.applicationId,
4069
4003
  organizationId: input.organizationId,
@@ -4179,11 +4113,13 @@ function event(value, version) {
4179
4113
  };
4180
4114
  }
4181
4115
  function listInput(input) {
4182
- if (!record$1(input) || Object.keys(input).some((key) => ![
4183
- "applicationId",
4184
- "after",
4185
- "limit"
4186
- ].includes(key)) || !directoryId(input.applicationId) || input.after !== void 0 && !checkpoint(input.after) || input.limit !== void 0 && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 100)) throw new AuthError("invalid_request", 400);
4116
+ if (!record$1(input) || Object.keys(input).some((key) => {
4117
+ return ![
4118
+ "applicationId",
4119
+ "after",
4120
+ "limit"
4121
+ ].includes(key);
4122
+ }) || !directoryId(input.applicationId) || input.after !== void 0 && !checkpoint(input.after) || input.limit !== void 0 && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 100)) throw new AuthError("invalid_request", 400);
4187
4123
  }
4188
4124
  function mapError$1(value, status, retryAfter) {
4189
4125
  if (status === 409 && exact$7(value, [
@@ -4194,10 +4130,14 @@ function mapError$1(value, status, retryAfter) {
4194
4130
  return fromAuthorityError(value, status, retryAfter);
4195
4131
  }
4196
4132
  function createOrganizationRoleEventsAuth(options) {
4197
- return createRoleEventsClient(options, 1, (value) => event(value, 1));
4133
+ return createRoleEventsClient(options, 1, (value) => {
4134
+ return event(value, 1);
4135
+ });
4198
4136
  }
4199
4137
  function createOrganizationRoleEventsV2Auth(options) {
4200
- return createRoleEventsClient(options, 2, (value) => event(value, 2));
4138
+ return createRoleEventsClient(options, 2, (value) => {
4139
+ return event(value, 2);
4140
+ });
4201
4141
  }
4202
4142
  function createRoleEventsClient(options, version, normalizeEvent) {
4203
4143
  const origin = normalizeOrigin(options.authOrigin, "authOrigin");
@@ -4206,7 +4146,7 @@ function createRoleEventsClient(options, version, normalizeEvent) {
4206
4146
  const timeoutMs = normalizeTimeout(options.timeoutMs);
4207
4147
  let inFlight = 0;
4208
4148
  async function exchange(body, assertion) {
4209
- if (typeof assertion !== "string" || assertion.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
4149
+ if (typeof assertion !== "string" || assertion.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
4210
4150
  if (inFlight >= 4) throw new AuthError("state_conflict", 409);
4211
4151
  inFlight += 1;
4212
4152
  const controller = new AbortController();
@@ -4230,7 +4170,7 @@ function createRoleEventsClient(options, version, normalizeEvent) {
4230
4170
  accept: "application/json"
4231
4171
  },
4232
4172
  body,
4233
- maxResponseBytes: 256 * 1024,
4173
+ maxResponseBytes: 262144,
4234
4174
  signal: controller.signal,
4235
4175
  mapError: mapError$1
4236
4176
  }).finally(() => {
@@ -4311,7 +4251,9 @@ function contactsInput(input) {
4311
4251
  }
4312
4252
  async function organizationServiceClosureBodyDigest(input) {
4313
4253
  const bytes = new TextEncoder().encode(canonical(closureInput(input)));
4314
- return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (byte) => byte.toString(16).padStart(2, "0")).join("");
4254
+ return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (byte) => {
4255
+ return byte.toString(16).padStart(2, "0");
4256
+ }).join("");
4315
4257
  }
4316
4258
  var Outcome = class extends Error {
4317
4259
  outcome;
@@ -4337,7 +4279,7 @@ function createOrganizationLifecycleAuth(options) {
4337
4279
  const timeoutMs = normalizeTimeout(options.timeoutMs);
4338
4280
  let inFlight = 0;
4339
4281
  async function exchange(operation, body, assertion) {
4340
- if (typeof assertion !== "string" || assertion.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
4282
+ if (typeof assertion !== "string" || assertion.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(assertion)) throw new AuthError("invalid_request", 400);
4341
4283
  if (inFlight >= 4) throw new AuthError("state_conflict", 409);
4342
4284
  inFlight += 1;
4343
4285
  const controller = new AbortController();
@@ -4361,7 +4303,7 @@ function createOrganizationLifecycleAuth(options) {
4361
4303
  accept: "application/json"
4362
4304
  },
4363
4305
  body,
4364
- maxResponseBytes: 128 * 1024,
4306
+ maxResponseBytes: 131072,
4365
4307
  signal: controller.signal,
4366
4308
  mapError
4367
4309
  }).finally(() => {
@@ -4437,7 +4379,9 @@ function createOrganizationLifecycleAuth(options) {
4437
4379
  name: item.name
4438
4380
  };
4439
4381
  });
4440
- if (new Set(contacts.map((contact) => contact.userId)).size !== contacts.length) throw authorityUnavailable();
4382
+ if (new Set(contacts.map((contact) => {
4383
+ return contact.userId;
4384
+ })).size !== contacts.length) throw authorityUnavailable();
4441
4385
  return {
4442
4386
  ...selected,
4443
4387
  contacts,
@@ -4448,10 +4392,10 @@ function createOrganizationLifecycleAuth(options) {
4448
4392
  }
4449
4393
  //#endregion
4450
4394
  //#region src/server.ts
4451
- const MAX_AUTHORIZATION_BYTES = 16 * 1024;
4395
+ const MAX_AUTHORIZATION_BYTES = 16384;
4452
4396
  function createServerAuth(options) {
4453
4397
  const authOrigin = normalizeOrigin(options.authOrigin, "authOrigin");
4454
- const appOrigin = normalizeOrigin(options.appOrigin, "appOrigin");
4398
+ const appOrigin = normalizeOrigin(options.appOrigin, "appOrigin", options.allowPrivateNetworkAppOrigin === true);
4455
4399
  const fetchImpl = options.fetch ?? globalThis.fetch;
4456
4400
  if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
4457
4401
  const now = options.now ?? Date.now;
@@ -4459,10 +4403,12 @@ function createServerAuth(options) {
4459
4403
  const authorization = authAuthorizationHeader(options.request.headers.get("authorization"));
4460
4404
  const cookie = authCookieHeader(options.request.headers.get("cookie"));
4461
4405
  const credentials = authorization ? "omit" : "include";
4462
- const authHeaders = (includeOrigin = true) => ({
4463
- ...authorization ? { authorization } : { cookie },
4464
- ...includeOrigin ? { origin: appOrigin } : {}
4465
- });
4406
+ const authHeaders = (includeOrigin = true) => {
4407
+ return {
4408
+ ...authorization ? { authorization } : { cookie },
4409
+ ...includeOrigin ? { origin: appOrigin } : {}
4410
+ };
4411
+ };
4466
4412
  async function teamMembershipMutation(ids, idempotencyKey, action) {
4467
4413
  if (authorization) throw new AuthError("authentication_required", 401);
4468
4414
  const [organization, team, member] = ids.map(normalizeIdInput);
@@ -4489,7 +4435,7 @@ function createServerAuth(options) {
4489
4435
  credentials,
4490
4436
  headers: authHeaders(false),
4491
4437
  mapError: fromOrganizationReadAuthorityError,
4492
- maxResponseBytes: 256 * 1024
4438
+ maxResponseBytes: 262144
4493
4439
  }));
4494
4440
  }
4495
4441
  return {
@@ -4564,16 +4510,20 @@ function createServerAuth(options) {
4564
4510
  getOrganizationSignInStates(organizationIds) {
4565
4511
  if (!Array.isArray(organizationIds) || !organizationIds.length || organizationIds.length > 50 || new Set(organizationIds).size !== organizationIds.length) throw new AuthError("invalid_request", 400);
4566
4512
  const ids = organizationIds.map(normalizeIdInput);
4567
- return organizationRead("sign-in-states", void 0, (value) => normalizeOrganizationSignInStates(value, ids), () => new URLSearchParams({ organizationIds: ids.join(",") }));
4513
+ return organizationRead("sign-in-states", void 0, (value) => {
4514
+ return normalizeOrganizationSignInStates(value, ids);
4515
+ }, () => {
4516
+ return new URLSearchParams({ organizationIds: ids.join(",") });
4517
+ });
4568
4518
  },
4569
4519
  async authorizeOrganizationPresence(organizationId, input, serviceAssertion, options) {
4570
- if (typeof serviceAssertion !== "string" || serviceAssertion.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(serviceAssertion)) throw new TypeError("Organization presence service assertion is invalid");
4520
+ if (typeof serviceAssertion !== "string" || serviceAssertion.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(serviceAssertion)) throw new TypeError("Organization presence service assertion is invalid");
4571
4521
  const organization = normalizeIdInput(organizationId);
4572
4522
  const body = presenceInput(input);
4573
4523
  let applicationCredential;
4574
4524
  if (options !== void 0) {
4575
4525
  const supplied = options?.applicationCredential;
4576
- if (typeof supplied !== "string" || supplied.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(supplied)) throw new TypeError("Organization presence credential is invalid");
4526
+ if (typeof supplied !== "string" || supplied.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(supplied)) throw new TypeError("Organization presence credential is invalid");
4577
4527
  applicationCredential = supplied;
4578
4528
  } else {
4579
4529
  const startedAt = now();
@@ -4594,7 +4544,7 @@ function createServerAuth(options) {
4594
4544
  fetch: fetchImpl,
4595
4545
  timeoutMs,
4596
4546
  method: "POST",
4597
- maxResponseBytes: 16 * 1024,
4547
+ maxResponseBytes: 16384,
4598
4548
  credentials,
4599
4549
  headers: {
4600
4550
  ...authHeaders(!authorization),
@@ -4607,13 +4557,13 @@ function createServerAuth(options) {
4607
4557
  }), organization, body, actor);
4608
4558
  },
4609
4559
  async getOrganizationMemberApplicationAccess(organizationId, input, serviceAssertion, options) {
4610
- if (typeof serviceAssertion !== "string" || serviceAssertion.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(serviceAssertion)) throw new TypeError("Application access service assertion is invalid");
4560
+ if (typeof serviceAssertion !== "string" || serviceAssertion.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(serviceAssertion)) throw new TypeError("Application access service assertion is invalid");
4611
4561
  const organization = normalizeIdInput(organizationId);
4612
4562
  const body = applicationAccessInput(input);
4613
4563
  let applicationCredential;
4614
4564
  if (options !== void 0) {
4615
4565
  const supplied = options?.applicationCredential;
4616
- if (typeof supplied !== "string" || supplied.length > 16 * 1024 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(supplied)) throw new TypeError("Application access credential is invalid");
4566
+ if (typeof supplied !== "string" || supplied.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$(?![\s\S])/.test(supplied)) throw new TypeError("Application access credential is invalid");
4617
4567
  applicationCredential = supplied;
4618
4568
  } else {
4619
4569
  const startedAt = now();
@@ -4633,7 +4583,7 @@ function createServerAuth(options) {
4633
4583
  fetch: fetchImpl,
4634
4584
  timeoutMs,
4635
4585
  method: "POST",
4636
- maxResponseBytes: 16 * 1024,
4586
+ maxResponseBytes: 16384,
4637
4587
  credentials,
4638
4588
  headers: {
4639
4589
  ...authHeaders(!authorization),
@@ -4648,12 +4598,18 @@ function createServerAuth(options) {
4648
4598
  async getOrganizationMemberAuthority(organizationId, memberId) {
4649
4599
  const organization = normalizeIdInput(organizationId);
4650
4600
  const member = normalizeIdInput(memberId);
4651
- return organizationRead(`${organization}/members/${member}/authority`, void 0, (value) => normalizeOrganizationMemberAuthority(value, organization, member));
4601
+ return organizationRead(`${organization}/members/${member}/authority`, void 0, (value) => {
4602
+ return normalizeOrganizationMemberAuthority(value, organization, member);
4603
+ });
4652
4604
  },
4653
4605
  async getOrganizationMemberAuthorityV2(organizationId, memberId) {
4654
4606
  const organization = normalizeIdInput(organizationId);
4655
4607
  const member = normalizeIdInput(memberId);
4656
- return organizationRead(`${organization}/members/${member}/authority`, void 0, (value) => normalizeOrganizationMemberAuthorityV2(value, organization, member), () => new URLSearchParams({ version: "2" }));
4608
+ return organizationRead(`${organization}/members/${member}/authority`, void 0, (value) => {
4609
+ return normalizeOrganizationMemberAuthorityV2(value, organization, member);
4610
+ }, () => {
4611
+ return new URLSearchParams({ version: "2" });
4612
+ });
4657
4613
  },
4658
4614
  async getOrganizationApplicationRegistration(organizationId, applicationId) {
4659
4615
  if (authorization) throw new AuthError("state_conflict", 409);
@@ -4923,7 +4879,9 @@ function createServerAuth(options) {
4923
4879
  body,
4924
4880
  mapError: fromSocialIdTokenAuthorityError
4925
4881
  })).headers);
4926
- const cookieHeader = authCookieHeader(cookies.map((value) => value.split(";", 1)[0]).join("; "));
4882
+ const cookieHeader = authCookieHeader(cookies.map((value) => {
4883
+ return value.split(";", 1)[0];
4884
+ }).join("; "));
4927
4885
  if (!cookieHeader) throw authorityUnavailable();
4928
4886
  const session = normalizeSession(await requestJson(joinURL(authOrigin, "api/v1/auth/get-session"), {
4929
4887
  fetch: fetchImpl,
@@ -5000,14 +4958,18 @@ function createServerAuth(options) {
5000
4958
  }
5001
4959
  function responseCookies(headers) {
5002
4960
  const getSetCookie = headers.getSetCookie;
5003
- return getSetCookie ? getSetCookie.call(headers) : [headers.get("set-cookie")].filter((value) => !!value);
4961
+ return getSetCookie ? getSetCookie.call(headers) : [headers.get("set-cookie")].filter((value) => {
4962
+ return !!value;
4963
+ });
5004
4964
  }
5005
4965
  function applyCookies(cookies, headers) {
5006
4966
  for (const value of cookies) headers.append("set-cookie", value);
5007
4967
  }
5008
4968
  function authCookieHeader(value) {
5009
4969
  if (!value) return "";
5010
- return value.split(";").map((cookie) => cookie.trim()).filter((cookie) => {
4970
+ return value.split(";").map((cookie) => {
4971
+ return cookie.trim();
4972
+ }).filter((cookie) => {
5011
4973
  const separator = cookie.indexOf("=");
5012
4974
  if (separator <= 0) return false;
5013
4975
  const name = cookie.slice(0, separator);
@@ -5015,7 +4977,7 @@ function authCookieHeader(value) {
5015
4977
  }).join("; ");
5016
4978
  }
5017
4979
  function authAuthorizationHeader(value) {
5018
- if (value === null) return void 0;
4980
+ if (value === null) return;
5019
4981
  if (new TextEncoder().encode(value).byteLength > MAX_AUTHORIZATION_BYTES || /[^\x20-\x7e]/.test(value) || !/^Bearer [^\s,]+$/i.test(value)) throw new AuthError("authentication_required", 401);
5020
4982
  return value;
5021
4983
  }