@finueva/auth 0.16.1 → 0.17.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
@@ -8,16 +8,16 @@ const ENC_CARET_RE = /%5e/gi;
8
8
  const ENC_BACKTICK_RE = /%60/gi;
9
9
  const ENC_PIPE_RE = /%7c/gi;
10
10
  const ENC_SPACE_RE = /%20/gi;
11
- function encode(text) {
11
+ function encode$2(text) {
12
12
  return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
13
13
  }
14
14
  function encodeQueryValue(input) {
15
- return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
15
+ return encode$2(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
16
16
  }
17
17
  function encodeQueryKey(text) {
18
18
  return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
19
19
  }
20
- function decode(text = "") {
20
+ function decode$1(text = "") {
21
21
  try {
22
22
  return decodeURIComponent("" + text);
23
23
  } catch {
@@ -25,10 +25,10 @@ function decode(text = "") {
25
25
  }
26
26
  }
27
27
  function decodeQueryKey(text) {
28
- return decode(text.replace(PLUS_RE, " "));
28
+ return decode$1(text.replace(PLUS_RE, " "));
29
29
  }
30
30
  function decodeQueryValue(text) {
31
- return decode(text.replace(PLUS_RE, " "));
31
+ return decode$1(text.replace(PLUS_RE, " "));
32
32
  }
33
33
  function parseQuery(parametersString = "") {
34
34
  const object = Object.create(null);
@@ -212,1278 +212,2522 @@ var AuthError = class extends Error {
212
212
  }
213
213
  };
214
214
  //#endregion
215
- //#region src/shared.ts
216
- const DRIVE_CREDENTIAL_LIFETIME_SECONDS = 840;
217
- const id = /^[A-Za-z0-9_-]{1,128}$/;
218
- const email = /^[^\s@]+@[^\s@]+$/;
219
- const MAX_SOCIAL_ID_TOKEN_BYTES = 16 * 1024;
220
- function normalizeEmail(value) {
221
- if (typeof value !== "string") throw new TypeError("email is invalid");
222
- const normalized = value.trim().toLowerCase();
223
- if (normalized.length === 0 || normalized.length > 320 || !email.test(normalized)) throw new TypeError("email is invalid");
224
- return normalized;
215
+ //#region src/user-api/credential.ts
216
+ function userApiApplication(input) {
217
+ if (!input || typeof input.applicationId !== "string" || !/^[A-Za-z0-9_-]{1,128}$(?![\s\S])/.test(input.applicationId) || input.forceRefresh !== void 0 && typeof input.forceRefresh !== "boolean") throw new TypeError("User API credential input is invalid");
218
+ return input.applicationId;
225
219
  }
226
- function normalizeSocialIdTokenInput(value) {
227
- if (!isObject(value)) throw new TypeError("social ID token input is invalid");
228
- const keys = Object.keys(value);
229
- 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");
220
+ function normalizeUserApiCredential(value, startedAt) {
221
+ 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);
230
222
  return {
231
- provider: value.provider,
232
- idToken: value.idToken,
233
- ...value.nonce === void 0 ? {} : { nonce: value.nonce },
234
- signUp: value.signUp
223
+ tokenType: "Bearer",
224
+ token: value.token,
225
+ expiresAt: new Date(startedAt + value.expiresIn * 1e3)
235
226
  };
236
227
  }
237
- function socialIdTokenRequest(value) {
238
- return {
239
- provider: value.provider,
240
- idToken: {
241
- token: value.idToken,
242
- ...value.nonce === void 0 ? {} : { nonce: value.nonce }
243
- },
244
- requestSignUp: value.signUp
245
- };
228
+ //#endregion
229
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/buffer_utils.js
230
+ const encoder$1 = new TextEncoder();
231
+ const decoder = new TextDecoder();
232
+ function concat(...buffers) {
233
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
234
+ const buf = new Uint8Array(size);
235
+ let i = 0;
236
+ for (const buffer of buffers) {
237
+ buf.set(buffer, i);
238
+ i += buffer.length;
239
+ }
240
+ return buf;
241
+ }
242
+ function encode$1(string) {
243
+ const bytes = new Uint8Array(string.length);
244
+ for (let i = 0; i < string.length; i++) {
245
+ const code = string.charCodeAt(i);
246
+ if (code > 127) throw new TypeError("non-ASCII string encountered in encode()");
247
+ bytes[i] = code;
248
+ }
249
+ return bytes;
246
250
  }
247
- function normalizeOrigin(value, name) {
248
- if (value.length === 0 || value.length > 2048 || /[^\x20-\x7e]/.test(value)) throw new TypeError(`${name} must be an ASCII HTTP origin`);
249
- let url;
251
+ //#endregion
252
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/base64.js
253
+ function encodeBase64(input) {
254
+ if (Uint8Array.prototype.toBase64) return input.toBase64();
255
+ const CHUNK_SIZE = 32768;
256
+ const arr = [];
257
+ for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
258
+ return btoa(arr.join(""));
259
+ }
260
+ function decodeBase64(encoded) {
261
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
262
+ const binary = atob(encoded);
263
+ const bytes = new Uint8Array(binary.length);
264
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
265
+ return bytes;
266
+ }
267
+ //#endregion
268
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/base64url.js
269
+ function decode(input) {
270
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
271
+ let encoded = input;
272
+ if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
273
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
250
274
  try {
251
- url = new URL(value);
275
+ return decodeBase64(encoded);
252
276
  } catch {
253
- throw new TypeError(`${name} must be an ASCII HTTP origin`);
277
+ throw new TypeError("The input to be decoded is not correctly encoded.");
254
278
  }
255
- const local = url.hostname === "localhost" || url.hostname.endsWith(".localhost") || url.hostname === "127.0.0.1";
256
- 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`);
257
- return url.origin;
258
279
  }
259
- function normalizeTimeout(value) {
260
- const timeout = value ?? 1e4;
261
- if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 6e4) throw new TypeError("timeoutMs must be an integer from 1 to 60000");
262
- return timeout;
280
+ function encode(input) {
281
+ let unencoded = input;
282
+ if (typeof unencoded === "string") unencoded = encoder$1.encode(unencoded);
283
+ if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
284
+ alphabet: "base64url",
285
+ omitPadding: true
286
+ });
287
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
263
288
  }
264
- function normalizeSession(value) {
265
- if (value === null) return null;
266
- if (!isObject(value) || !isObject(value.session) || !isObject(value.user)) throw authorityUnavailable();
267
- const expiresAt = toDate(value.session.expiresAt);
268
- const image = value.user.image;
269
- if (!isId(value.session.id) || !expiresAt || !isId(value.user.id) || typeof value.user.name !== "string" || value.user.name.length > 256 || typeof value.user.email !== "string" || value.user.email.length > 320 || !email.test(value.user.email) || typeof value.user.emailVerified !== "boolean" || image !== null && image !== void 0 && (typeof image !== "string" || image.length > 2048)) throw authorityUnavailable();
270
- return {
271
- id: value.session.id,
272
- expiresAt,
273
- user: {
274
- id: value.user.id,
275
- name: value.user.name,
276
- email: value.user.email,
277
- emailVerified: value.user.emailVerified,
278
- image: image ?? null
289
+ //#endregion
290
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/crypto_key.js
291
+ const unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
292
+ const isAlgorithm = (algorithm, name) => algorithm.name === name;
293
+ function getHashLength(hash) {
294
+ return parseInt(hash.name.slice(4), 10);
295
+ }
296
+ function checkHashLength(algorithm, expected) {
297
+ if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
298
+ }
299
+ function getNamedCurve(alg) {
300
+ switch (alg) {
301
+ case "ES256": return "P-256";
302
+ case "ES384": return "P-384";
303
+ case "ES512": return "P-521";
304
+ default: throw new Error("unreachable");
305
+ }
306
+ }
307
+ function checkUsage(key, usage) {
308
+ if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
309
+ }
310
+ function checkSigCryptoKey(key, alg, usage) {
311
+ switch (alg) {
312
+ case "HS256":
313
+ case "HS384":
314
+ case "HS512":
315
+ if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
316
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
317
+ break;
318
+ case "RS256":
319
+ case "RS384":
320
+ case "RS512":
321
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
322
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
323
+ break;
324
+ case "PS256":
325
+ case "PS384":
326
+ case "PS512":
327
+ if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
328
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
329
+ break;
330
+ case "Ed25519":
331
+ case "EdDSA":
332
+ if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
333
+ break;
334
+ case "ML-DSA-44":
335
+ case "ML-DSA-65":
336
+ case "ML-DSA-87":
337
+ if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
338
+ break;
339
+ case "ES256":
340
+ case "ES384":
341
+ case "ES512": {
342
+ if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
343
+ const expected = getNamedCurve(alg);
344
+ if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
345
+ break;
279
346
  }
280
- };
347
+ default: throw new TypeError("CryptoKey does not support this operation");
348
+ }
349
+ checkUsage(key, usage);
281
350
  }
282
- function normalizeDriveCredential(value, now) {
283
- if (!isObject(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();
284
- return {
285
- tokenType: "Bearer",
286
- token: value.token,
287
- expiresAt: new Date(now + value.expiresIn * 1e3)
288
- };
351
+ //#endregion
352
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/invalid_key_input.js
353
+ function message(msg, actual, ...types) {
354
+ types = types.filter(Boolean);
355
+ if (types.length > 2) {
356
+ const last = types.pop();
357
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
358
+ } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
359
+ else msg += `of type ${types[0]}.`;
360
+ if (actual == null) msg += ` Received ${actual}`;
361
+ else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
362
+ else if (typeof actual === "object" && actual != null) {
363
+ if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
364
+ }
365
+ return msg;
289
366
  }
290
- function normalizeOrganizationPageInput(value) {
291
- if (value === void 0) return new URLSearchParams();
292
- if (!isObject(value) || Object.keys(value).some((key) => key !== "limit" && key !== "cursor")) throw new AuthError("invalid_request", 400);
293
- const input = value;
294
- const query = new URLSearchParams();
295
- if (input.limit !== void 0) {
296
- if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) throw new AuthError("invalid_request", 400);
297
- query.set("limit", String(input.limit));
367
+ const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
368
+ const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
369
+ //#endregion
370
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/errors.js
371
+ var JOSEError = class extends Error {
372
+ static code = "ERR_JOSE_GENERIC";
373
+ code = "ERR_JOSE_GENERIC";
374
+ constructor(message, options) {
375
+ super(message, options);
376
+ this.name = this.constructor.name;
377
+ Error.captureStackTrace?.(this, this.constructor);
298
378
  }
299
- if (input.cursor !== void 0) {
300
- if (typeof input.cursor !== "string" || input.cursor.length < 1 || input.cursor.length > 820 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(input.cursor)) throw new AuthError("invalid_request", 400);
301
- query.set("cursor", input.cursor);
379
+ };
380
+ var JWTClaimValidationFailed = class extends JOSEError {
381
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
382
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
383
+ claim;
384
+ reason;
385
+ payload;
386
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
387
+ super(message, { cause: {
388
+ claim,
389
+ reason,
390
+ payload
391
+ } });
392
+ this.claim = claim;
393
+ this.reason = reason;
394
+ this.payload = payload;
395
+ }
396
+ };
397
+ var JWTExpired = class extends JOSEError {
398
+ static code = "ERR_JWT_EXPIRED";
399
+ code = "ERR_JWT_EXPIRED";
400
+ claim;
401
+ reason;
402
+ payload;
403
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
404
+ super(message, { cause: {
405
+ claim,
406
+ reason,
407
+ payload
408
+ } });
409
+ this.claim = claim;
410
+ this.reason = reason;
411
+ this.payload = payload;
412
+ }
413
+ };
414
+ var JOSEAlgNotAllowed = class extends JOSEError {
415
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
416
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
417
+ };
418
+ var JOSENotSupported = class extends JOSEError {
419
+ static code = "ERR_JOSE_NOT_SUPPORTED";
420
+ code = "ERR_JOSE_NOT_SUPPORTED";
421
+ };
422
+ var JWSInvalid = class extends JOSEError {
423
+ static code = "ERR_JWS_INVALID";
424
+ code = "ERR_JWS_INVALID";
425
+ };
426
+ var JWTInvalid = class extends JOSEError {
427
+ static code = "ERR_JWT_INVALID";
428
+ code = "ERR_JWT_INVALID";
429
+ };
430
+ var JWKInvalid = class extends JOSEError {
431
+ static code = "ERR_JWK_INVALID";
432
+ code = "ERR_JWK_INVALID";
433
+ };
434
+ var JWSSignatureVerificationFailed = class extends JOSEError {
435
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
436
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
437
+ constructor(message = "signature verification failed", options) {
438
+ super(message, options);
439
+ }
440
+ };
441
+ //#endregion
442
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/is_key_like.js
443
+ const isCryptoKey = (key) => {
444
+ if (key?.[Symbol.toStringTag] === "CryptoKey") return true;
445
+ try {
446
+ return key instanceof CryptoKey;
447
+ } catch {
448
+ return false;
449
+ }
450
+ };
451
+ const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
452
+ const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
453
+ //#endregion
454
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/helpers.js
455
+ function decodeBase64url(value, label, ErrorClass) {
456
+ try {
457
+ return decode(value);
458
+ } catch {
459
+ throw new ErrorClass(`Failed to base64url decode the ${label}`);
302
460
  }
303
- return query;
304
461
  }
305
- function normalizeIdInput(value) {
306
- if (!isId(value)) throw new AuthError("invalid_request", 400);
307
- return value;
462
+ async function digest(algorithm, data) {
463
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
464
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
308
465
  }
309
- function normalizeOrganization(value) {
310
- exact$2(value, [
311
- "capabilities",
312
- "id",
313
- "lifecycle",
314
- "logo",
315
- "name",
316
- "role",
317
- "slug"
318
- ]);
319
- if (!isId(value.id) || !boundedString(value.name, 255) || !boundedString(value.slug, 255) || value.lifecycle !== "ordinary" && value.lifecycle !== "managed" || !role(value.role) || !isObject(value.capabilities)) throw authorityUnavailable();
320
- exact$2(value.capabilities, [
321
- "readInvitations",
322
- "readMembers",
323
- "readTeams"
324
- ]);
325
- if (value.capabilities.readMembers !== true || value.capabilities.readTeams !== true || typeof value.capabilities.readInvitations !== "boolean") throw authorityUnavailable();
326
- return {
327
- id: value.id,
328
- name: value.name,
329
- slug: value.slug,
330
- logo: nullableHttpsUrl(value.logo),
331
- lifecycle: value.lifecycle,
332
- role: value.role,
333
- capabilities: {
334
- readMembers: true,
335
- readTeams: true,
336
- readInvitations: value.capabilities.readInvitations
466
+ //#endregion
467
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/type_checks.js
468
+ const isObjectLike = (value) => typeof value === "object" && value !== null;
469
+ function isObject$1(input) {
470
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
471
+ if (Object.getPrototypeOf(input) === null) return true;
472
+ let proto = input;
473
+ while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
474
+ return Object.getPrototypeOf(input) === proto;
475
+ }
476
+ function isDisjoint(...headers) {
477
+ const sources = headers.filter(Boolean);
478
+ if (sources.length === 0 || sources.length === 1) return true;
479
+ let acc;
480
+ for (const header of sources) {
481
+ const parameters = Object.keys(header);
482
+ if (!acc || acc.size === 0) {
483
+ acc = new Set(parameters);
484
+ continue;
337
485
  }
338
- };
486
+ for (const parameter of parameters) {
487
+ if (acc.has(parameter)) return false;
488
+ acc.add(parameter);
489
+ }
490
+ }
491
+ return true;
339
492
  }
340
- function normalizeOrganizationDisplayInput(value) {
341
- if (!isObject(value) || Object.keys(value).sort().join(",") !== "logo,name,slug") throw new AuthError("invalid_request", 400);
342
- if (!boundedString(value.name, 255) || !boundedString(value.slug, 255)) throw new AuthError("invalid_request", 400);
343
- let logo;
344
- try {
345
- logo = nullableHttpsUrl(value.logo);
346
- } catch {
347
- throw new AuthError("invalid_request", 400);
493
+ const isJWK = (key) => isObject$1(key) && typeof key.kty === "string";
494
+ const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
495
+ const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
496
+ const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
497
+ //#endregion
498
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/signing.js
499
+ function checkKeyLength(alg, key) {
500
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
501
+ const { modulusLength } = key.algorithm;
502
+ if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
348
503
  }
349
- return {
350
- name: value.name,
351
- slug: value.slug,
352
- logo
353
- };
354
504
  }
355
- function normalizeOrganizationDisplay(value) {
356
- try {
357
- return normalizeOrganizationDisplayInput(value);
358
- } catch {
359
- throw authorityUnavailable();
505
+ function subtleAlgorithm(alg, algorithm) {
506
+ const hash = `SHA-${alg.slice(-3)}`;
507
+ switch (alg) {
508
+ case "HS256":
509
+ case "HS384":
510
+ case "HS512": return {
511
+ hash,
512
+ name: "HMAC"
513
+ };
514
+ case "PS256":
515
+ case "PS384":
516
+ case "PS512": return {
517
+ hash,
518
+ name: "RSA-PSS",
519
+ saltLength: parseInt(alg.slice(-3), 10) >> 3
520
+ };
521
+ case "RS256":
522
+ case "RS384":
523
+ case "RS512": return {
524
+ hash,
525
+ name: "RSASSA-PKCS1-v1_5"
526
+ };
527
+ case "ES256":
528
+ case "ES384":
529
+ case "ES512": return {
530
+ hash,
531
+ name: "ECDSA",
532
+ namedCurve: algorithm.namedCurve
533
+ };
534
+ case "Ed25519":
535
+ case "EdDSA": return { name: "Ed25519" };
536
+ case "ML-DSA-44":
537
+ case "ML-DSA-65":
538
+ case "ML-DSA-87": return { name: alg };
539
+ default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
360
540
  }
361
541
  }
362
- function normalizeOrganizationTeamDisplayInput(value) {
363
- if (!isObject(value) || Object.keys(value).join(",") !== "name" || !boundedString(value.name, 255)) throw new AuthError("invalid_request", 400);
364
- return { name: value.name };
542
+ async function getSigKey(alg, key, usage) {
543
+ if (key instanceof Uint8Array) {
544
+ if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
545
+ return crypto.subtle.importKey("raw", key, {
546
+ hash: `SHA-${alg.slice(-3)}`,
547
+ name: "HMAC"
548
+ }, false, [usage]);
549
+ }
550
+ checkSigCryptoKey(key, alg, usage);
551
+ return key;
365
552
  }
366
- function normalizeOrganizationTeamDisplay(value) {
553
+ async function verify(alg, key, signature, data) {
554
+ const cryptoKey = await getSigKey(alg, key, "verify");
555
+ checkKeyLength(alg, cryptoKey);
556
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
367
557
  try {
368
- return normalizeOrganizationTeamDisplayInput(value);
558
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
369
559
  } catch {
370
- throw authorityUnavailable();
560
+ return false;
371
561
  }
372
562
  }
373
- function normalizeOrganizationTeamCreationInput(name, idempotencyKey) {
374
- if (!boundedString(name, 255) || !boundedString(idempotencyKey, 255)) throw new AuthError("invalid_request", 400);
563
+ //#endregion
564
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/jwk_to_key.js
565
+ const unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value";
566
+ function subtleMapping(jwk) {
567
+ let algorithm;
568
+ let keyUsages;
569
+ switch (jwk.kty) {
570
+ case "AKP":
571
+ switch (jwk.alg) {
572
+ case "ML-DSA-44":
573
+ case "ML-DSA-65":
574
+ case "ML-DSA-87":
575
+ algorithm = { name: jwk.alg };
576
+ keyUsages = jwk.priv ? ["sign"] : ["verify"];
577
+ break;
578
+ default: throw new JOSENotSupported(unsupportedAlg);
579
+ }
580
+ break;
581
+ case "RSA":
582
+ switch (jwk.alg) {
583
+ case "PS256":
584
+ case "PS384":
585
+ case "PS512":
586
+ algorithm = {
587
+ name: "RSA-PSS",
588
+ hash: `SHA-${jwk.alg.slice(-3)}`
589
+ };
590
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
591
+ break;
592
+ case "RS256":
593
+ case "RS384":
594
+ case "RS512":
595
+ algorithm = {
596
+ name: "RSASSA-PKCS1-v1_5",
597
+ hash: `SHA-${jwk.alg.slice(-3)}`
598
+ };
599
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
600
+ break;
601
+ case "RSA-OAEP":
602
+ case "RSA-OAEP-256":
603
+ case "RSA-OAEP-384":
604
+ case "RSA-OAEP-512":
605
+ algorithm = {
606
+ name: "RSA-OAEP",
607
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
608
+ };
609
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
610
+ break;
611
+ default: throw new JOSENotSupported(unsupportedAlg);
612
+ }
613
+ break;
614
+ case "EC":
615
+ switch (jwk.alg) {
616
+ case "ES256":
617
+ case "ES384":
618
+ case "ES512":
619
+ algorithm = {
620
+ name: "ECDSA",
621
+ namedCurve: {
622
+ ES256: "P-256",
623
+ ES384: "P-384",
624
+ ES512: "P-521"
625
+ }[jwk.alg]
626
+ };
627
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
628
+ break;
629
+ case "ECDH-ES":
630
+ case "ECDH-ES+A128KW":
631
+ case "ECDH-ES+A192KW":
632
+ case "ECDH-ES+A256KW":
633
+ algorithm = {
634
+ name: "ECDH",
635
+ namedCurve: jwk.crv
636
+ };
637
+ keyUsages = jwk.d ? ["deriveBits"] : [];
638
+ break;
639
+ default: throw new JOSENotSupported(unsupportedAlg);
640
+ }
641
+ break;
642
+ case "OKP":
643
+ switch (jwk.alg) {
644
+ case "Ed25519":
645
+ case "EdDSA":
646
+ algorithm = { name: "Ed25519" };
647
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
648
+ break;
649
+ case "ECDH-ES":
650
+ case "ECDH-ES+A128KW":
651
+ case "ECDH-ES+A192KW":
652
+ case "ECDH-ES+A256KW":
653
+ algorithm = { name: jwk.crv };
654
+ keyUsages = jwk.d ? ["deriveBits"] : [];
655
+ break;
656
+ default: throw new JOSENotSupported(unsupportedAlg);
657
+ }
658
+ break;
659
+ default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
660
+ }
375
661
  return {
376
- name,
377
- idempotencyKey
662
+ algorithm,
663
+ keyUsages
378
664
  };
379
665
  }
380
- function normalizeCreatedOrganizationTeam(value) {
381
- exact$2(value, ["id", "name"]);
382
- if (!isId(value.id) || !boundedString(value.name, 255)) throw authorityUnavailable();
383
- return {
384
- id: value.id,
385
- name: value.name
386
- };
666
+ async function jwkToKey(jwk) {
667
+ if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
668
+ const { algorithm, keyUsages } = subtleMapping(jwk);
669
+ const keyData = { ...jwk };
670
+ if (keyData.kty !== "AKP") delete keyData.alg;
671
+ delete keyData.use;
672
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
387
673
  }
388
- function normalizeOrganizationMemberInvitationCreationInput(value) {
389
- if (!isObject(value)) throw new AuthError("invalid_request", 400);
390
- const keys = Object.keys(value).sort().join(",");
391
- if (keys !== "email,idempotencyKey" && keys !== "email,idempotencyKey,teamIds") throw new AuthError("invalid_request", 400);
392
- let normalizedEmail;
393
- try {
394
- normalizedEmail = normalizeEmail(value.email);
395
- } catch {
396
- throw new AuthError("invalid_request", 400);
674
+ //#endregion
675
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/normalize_key.js
676
+ const unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
677
+ let cache;
678
+ const handleJWK = async (key, jwk, alg, freeze = false) => {
679
+ cache ||= new WeakMap();
680
+ let cached = cache.get(key);
681
+ if (cached?.[alg]) return cached[alg];
682
+ const cryptoKey = await jwkToKey({
683
+ ...jwk,
684
+ alg
685
+ });
686
+ if (freeze) Object.freeze(key);
687
+ if (!cached) cache.set(key, { [alg]: cryptoKey });
688
+ else cached[alg] = cryptoKey;
689
+ return cryptoKey;
690
+ };
691
+ const handleKeyObject = (keyObject, alg) => {
692
+ cache ||= new WeakMap();
693
+ let cached = cache.get(keyObject);
694
+ if (cached?.[alg]) return cached[alg];
695
+ const isPublic = keyObject.type === "public";
696
+ const extractable = isPublic ? true : false;
697
+ let cryptoKey;
698
+ if (keyObject.asymmetricKeyType === "x25519") {
699
+ switch (alg) {
700
+ case "ECDH-ES":
701
+ case "ECDH-ES+A128KW":
702
+ case "ECDH-ES+A192KW":
703
+ case "ECDH-ES+A256KW": break;
704
+ default: throw new TypeError(unusableForAlg);
705
+ }
706
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
397
707
  }
398
- 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);
399
- const teamIds = value.teamIds?.map((teamId) => normalizeIdInput(teamId));
400
- if (teamIds && new Set(teamIds).size !== teamIds.length) throw new AuthError("invalid_request", 400);
401
- return {
402
- email: normalizedEmail,
403
- ...teamIds === void 0 ? {} : { teamIds },
404
- idempotencyKey: value.idempotencyKey
405
- };
708
+ if (keyObject.asymmetricKeyType === "ed25519") {
709
+ if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg);
710
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
711
+ }
712
+ switch (keyObject.asymmetricKeyType) {
713
+ case "ml-dsa-44":
714
+ case "ml-dsa-65":
715
+ case "ml-dsa-87":
716
+ if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg);
717
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
718
+ }
719
+ if (keyObject.asymmetricKeyType === "rsa") {
720
+ let hash;
721
+ switch (alg) {
722
+ case "RSA-OAEP":
723
+ hash = "SHA-1";
724
+ break;
725
+ case "RS256":
726
+ case "PS256":
727
+ case "RSA-OAEP-256":
728
+ hash = "SHA-256";
729
+ break;
730
+ case "RS384":
731
+ case "PS384":
732
+ case "RSA-OAEP-384":
733
+ hash = "SHA-384";
734
+ break;
735
+ case "RS512":
736
+ case "PS512":
737
+ case "RSA-OAEP-512":
738
+ hash = "SHA-512";
739
+ break;
740
+ default: throw new TypeError(unusableForAlg);
741
+ }
742
+ if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
743
+ name: "RSA-OAEP",
744
+ hash
745
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
746
+ cryptoKey = keyObject.toCryptoKey({
747
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
748
+ hash
749
+ }, extractable, [isPublic ? "verify" : "sign"]);
750
+ }
751
+ if (keyObject.asymmetricKeyType === "ec") {
752
+ const namedCurve = new Map([
753
+ ["prime256v1", "P-256"],
754
+ ["secp384r1", "P-384"],
755
+ ["secp521r1", "P-521"]
756
+ ]).get(keyObject.asymmetricKeyDetails?.namedCurve);
757
+ if (!namedCurve) throw new TypeError(unusableForAlg);
758
+ const expectedCurve = {
759
+ ES256: "P-256",
760
+ ES384: "P-384",
761
+ ES512: "P-521"
762
+ };
763
+ if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({
764
+ name: "ECDSA",
765
+ namedCurve
766
+ }, extractable, [isPublic ? "verify" : "sign"]);
767
+ if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
768
+ name: "ECDH",
769
+ namedCurve
770
+ }, extractable, isPublic ? [] : ["deriveBits"]);
771
+ }
772
+ if (!cryptoKey) throw new TypeError(unusableForAlg);
773
+ if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
774
+ else cached[alg] = cryptoKey;
775
+ return cryptoKey;
776
+ };
777
+ async function normalizeKey(key, alg) {
778
+ if (key instanceof Uint8Array) return key;
779
+ if (isCryptoKey(key)) return key;
780
+ if (isKeyObject(key)) {
781
+ if (key.type === "secret") return key.export();
782
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
783
+ return handleKeyObject(key, alg);
784
+ } catch (err) {
785
+ if (err instanceof TypeError) throw err;
786
+ }
787
+ let jwk = key.export({ format: "jwk" });
788
+ return handleJWK(key, jwk, alg);
789
+ }
790
+ if (isJWK(key)) {
791
+ if (key.k) return decode(key.k);
792
+ return handleJWK(key, key, alg, true);
793
+ }
794
+ throw new Error("unreachable");
406
795
  }
407
- function normalizeCreatedOrganizationMemberInvitation(value) {
408
- exact$2(value, ["expiresAt", "id"]);
409
- if (!isId(value.id)) throw authorityUnavailable();
410
- return {
411
- id: value.id,
412
- expiresAt: responseDate(value.expiresAt)
796
+ //#endregion
797
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/key/import.js
798
+ async function importJWK(jwk, alg, options) {
799
+ if (!isObject$1(jwk)) throw new TypeError("JWK must be an object");
800
+ let ext;
801
+ alg ??= jwk.alg;
802
+ ext ??= options?.extractable ?? jwk.ext;
803
+ switch (jwk.kty) {
804
+ case "oct":
805
+ if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
806
+ return decode(jwk.k);
807
+ case "RSA":
808
+ if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
809
+ return jwkToKey({
810
+ ...jwk,
811
+ alg,
812
+ ext
813
+ });
814
+ case "AKP":
815
+ if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
816
+ if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
817
+ return jwkToKey({
818
+ ...jwk,
819
+ ext
820
+ });
821
+ case "EC":
822
+ case "OKP": return jwkToKey({
823
+ ...jwk,
824
+ alg,
825
+ ext
826
+ });
827
+ default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
828
+ }
829
+ }
830
+ //#endregion
831
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/key_to_jwk.js
832
+ function omitUndefinedProperties(jwk) {
833
+ return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== void 0));
834
+ }
835
+ async function keyToJWK(key) {
836
+ if (isKeyObject(key)) if (key.type === "secret") key = key.export();
837
+ else return key.export({ format: "jwk" });
838
+ if (key instanceof Uint8Array) return {
839
+ kty: "oct",
840
+ k: encode(key)
413
841
  };
842
+ if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
843
+ if (!key.extractable) throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
844
+ const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
845
+ if (jwk.kty === "AKP") jwk.alg = alg;
846
+ return jwk;
414
847
  }
415
- function normalizeResentOrganizationInvitation(value, invitationId) {
416
- const invitation = normalizeCreatedOrganizationMemberInvitation(value);
417
- if (invitation.id !== invitationId) throw authorityUnavailable();
418
- return invitation;
848
+ //#endregion
849
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/key/export.js
850
+ async function exportJWK(key) {
851
+ return keyToJWK(key);
419
852
  }
420
- function normalizeOrganizationInvitationAdministrationInput(idempotencyKey) {
421
- if (!boundedString(idempotencyKey, 255)) throw new AuthError("invalid_request", 400);
422
- return { idempotencyKey };
853
+ //#endregion
854
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/validate_crit.js
855
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
856
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
857
+ if (!protectedHeader || protectedHeader.crit === void 0) return new Set();
858
+ 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");
859
+ let recognized;
860
+ if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
861
+ else recognized = recognizedDefault;
862
+ for (const parameter of protectedHeader.crit) {
863
+ if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
864
+ if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
865
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
866
+ }
867
+ return new Set(protectedHeader.crit);
423
868
  }
424
- function normalizeCanceledOrganizationInvitation(value) {
425
- exact$2(value, ["status"]);
426
- if (value.status !== "canceled") throw authorityUnavailable();
427
- return { status: "canceled" };
869
+ //#endregion
870
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/validate_algorithms.js
871
+ function validateAlgorithms(option, algorithms) {
872
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
873
+ if (!algorithms) return;
874
+ return new Set(algorithms);
428
875
  }
429
- function normalizeOrganizations(value) {
430
- exact$2(value, ["nextCursor", "organizations"]);
431
- if (!Array.isArray(value.organizations) || value.organizations.length > 100) throw authorityUnavailable();
432
- return {
433
- organizations: unique(value.organizations.map(normalizeOrganization), (item) => item.id),
434
- nextCursor: nullableCursor(value.nextCursor)
435
- };
876
+ //#endregion
877
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/check_key_type.js
878
+ const tag = (key) => key?.[Symbol.toStringTag];
879
+ const jwkMatchesOp = (alg, key, usage) => {
880
+ if (key.use !== void 0) {
881
+ let expected;
882
+ switch (usage) {
883
+ case "sign":
884
+ case "verify":
885
+ expected = "sig";
886
+ break;
887
+ case "encrypt":
888
+ case "decrypt":
889
+ expected = "enc";
890
+ break;
891
+ }
892
+ if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
893
+ }
894
+ if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
895
+ if (Array.isArray(key.key_ops)) {
896
+ let expectedKeyOp;
897
+ switch (true) {
898
+ case usage === "sign" || usage === "verify":
899
+ case alg === "dir":
900
+ case alg.includes("CBC-HS"):
901
+ expectedKeyOp = usage;
902
+ break;
903
+ case alg.startsWith("PBES2"):
904
+ expectedKeyOp = "deriveBits";
905
+ break;
906
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
907
+ if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
908
+ else expectedKeyOp = usage;
909
+ break;
910
+ case usage === "encrypt" && alg.startsWith("RSA"):
911
+ expectedKeyOp = "wrapKey";
912
+ break;
913
+ case usage === "decrypt":
914
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
915
+ break;
916
+ }
917
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
918
+ }
919
+ return true;
920
+ };
921
+ const symmetricTypeCheck = (alg, key, usage) => {
922
+ if (key instanceof Uint8Array) return;
923
+ if (isJWK(key)) {
924
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
925
+ 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`);
926
+ }
927
+ if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
928
+ if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
929
+ };
930
+ const asymmetricTypeCheck = (alg, key, usage) => {
931
+ if (isJWK(key)) switch (usage) {
932
+ case "decrypt":
933
+ case "sign":
934
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
935
+ throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
936
+ case "encrypt":
937
+ case "verify":
938
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
939
+ throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
940
+ }
941
+ if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
942
+ if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
943
+ if (key.type === "public") switch (usage) {
944
+ case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
945
+ case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
946
+ }
947
+ if (key.type === "private") switch (usage) {
948
+ case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
949
+ case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
950
+ }
951
+ };
952
+ function checkKeyType(alg, key, usage) {
953
+ switch (alg.substring(0, 2)) {
954
+ case "A1":
955
+ case "A2":
956
+ case "di":
957
+ case "HS":
958
+ case "PB":
959
+ symmetricTypeCheck(alg, key, usage);
960
+ break;
961
+ default: asymmetricTypeCheck(alg, key, usage);
962
+ }
436
963
  }
437
- function normalizeOrganizationMembers(value) {
438
- exact$2(value, ["members", "nextCursor"]);
439
- if (!Array.isArray(value.members) || value.members.length > 100) throw authorityUnavailable();
440
- return {
441
- members: unique(value.members.map((member) => {
442
- exact$2(member, [
443
- "email",
444
- "id",
445
- "image",
446
- "joinedAt",
447
- "name",
448
- "owner",
449
- "role",
450
- "teamIds",
451
- "userId"
452
- ]);
453
- 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();
454
- const teamIds = unique(member.teamIds.map((teamId) => normalizeResponseId(teamId)), (item) => item);
455
- return {
456
- id: member.id,
457
- userId: member.userId,
458
- name: member.name,
459
- email: member.email,
460
- image: nullableHttpsUrl(member.image),
461
- role: member.role,
462
- owner: member.owner,
463
- joinedAt: responseDate(member.joinedAt),
464
- teamIds
465
- };
466
- }), (item) => item.id),
467
- nextCursor: nullableCursor(value.nextCursor)
964
+ //#endregion
965
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jws/flattened/verify.js
966
+ async function flattenedVerify(jws, key, options) {
967
+ if (!isObject$1(jws)) throw new JWSInvalid("Flattened JWS must be an object");
968
+ if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
969
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
970
+ if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
971
+ if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
972
+ if (jws.header !== void 0 && !isObject$1(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
973
+ let parsedProt = {};
974
+ if (jws.protected) try {
975
+ const protectedHeader = decode(jws.protected);
976
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
977
+ } catch {
978
+ throw new JWSInvalid("JWS Protected Header is invalid");
979
+ }
980
+ if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
981
+ const joseHeader = {
982
+ ...parsedProt,
983
+ ...jws.header
468
984
  };
469
- }
470
- function normalizeOrganizationTeams(value) {
471
- exact$2(value, ["nextCursor", "teams"]);
472
- if (!Array.isArray(value.teams) || value.teams.length > 100) throw authorityUnavailable();
473
- return {
474
- teams: unique(value.teams.map((team) => {
475
- exact$2(team, [
476
- "category",
477
- "createdAt",
478
- "id",
479
- "name"
480
- ]);
481
- if (!isId(team.id) || !boundedString(team.name, 255) || team.category !== "manual" && team.category !== "managed") throw authorityUnavailable();
482
- return {
483
- id: team.id,
484
- name: team.name,
485
- category: team.category,
486
- createdAt: responseDate(team.createdAt)
487
- };
488
- }), (item) => item.id),
489
- nextCursor: nullableCursor(value.nextCursor)
985
+ const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
986
+ let b64 = true;
987
+ if (extensions.has("b64")) {
988
+ b64 = parsedProt.b64;
989
+ if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
990
+ }
991
+ const { alg } = joseHeader;
992
+ if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
993
+ const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
994
+ if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
995
+ if (b64) {
996
+ if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
997
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
998
+ let resolvedKey = false;
999
+ if (typeof key === "function") {
1000
+ key = await key(parsedProt, jws);
1001
+ resolvedKey = true;
1002
+ }
1003
+ checkKeyType(alg, key, "verify");
1004
+ 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);
1005
+ const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
1006
+ const k = await normalizeKey(key, alg);
1007
+ if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
1008
+ let payload;
1009
+ if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
1010
+ else if (typeof jws.payload === "string") payload = encoder$1.encode(jws.payload);
1011
+ else payload = jws.payload;
1012
+ const result = { payload };
1013
+ if (jws.protected !== void 0) result.protectedHeader = parsedProt;
1014
+ if (jws.header !== void 0) result.unprotectedHeader = jws.header;
1015
+ if (resolvedKey) return {
1016
+ ...result,
1017
+ key: k
490
1018
  };
1019
+ return result;
491
1020
  }
492
- function normalizeOrganizationTeamMembers(value) {
493
- exact$2(value, ["memberIds", "nextCursor"]);
494
- if (!Array.isArray(value.memberIds) || value.memberIds.length > 100) throw authorityUnavailable();
495
- return {
496
- memberIds: unique(value.memberIds.map((item) => normalizeResponseId(item)), (item) => item),
497
- nextCursor: nullableCursor(value.nextCursor)
1021
+ //#endregion
1022
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jws/compact/verify.js
1023
+ async function compactVerify(jws, key, options) {
1024
+ if (jws instanceof Uint8Array) jws = decoder.decode(jws);
1025
+ if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
1026
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
1027
+ if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
1028
+ const verified = await flattenedVerify({
1029
+ payload,
1030
+ protected: protectedHeader,
1031
+ signature
1032
+ }, key, options);
1033
+ const result = {
1034
+ payload: verified.payload,
1035
+ protectedHeader: verified.protectedHeader
498
1036
  };
499
- }
500
- function normalizeOrganizationInvitation(value) {
501
- exact$2(value, [
502
- "createdAt",
503
- "email",
504
- "expiresAt",
505
- "id",
506
- "inviter",
507
- "role",
508
- "status",
509
- "teamIds"
510
- ]);
511
- if (!isId(value.id) || typeof value.email !== "string" || value.email.length > 320 || !email.test(value.email) || !role(value.role) || value.status !== "pending" || !Array.isArray(value.teamIds) || value.teamIds.length > 100 || !isObject(value.inviter)) throw authorityUnavailable();
512
- exact$2(value.inviter, ["membershipId", "name"]);
513
- if (!isId(value.inviter.membershipId) || !boundedString(value.inviter.name, 255)) throw authorityUnavailable();
514
- return {
515
- id: value.id,
516
- email: value.email,
517
- role: value.role,
518
- teamIds: unique(value.teamIds.map(normalizeResponseId), (item) => item),
519
- inviter: {
520
- membershipId: value.inviter.membershipId,
521
- name: value.inviter.name
522
- },
523
- createdAt: responseDate(value.createdAt),
524
- expiresAt: responseDate(value.expiresAt),
525
- status: "pending"
1037
+ if (typeof key === "function") return {
1038
+ ...result,
1039
+ key: verified.key
526
1040
  };
1041
+ return result;
527
1042
  }
528
- function normalizeOrganizationInvitations(value) {
529
- exact$2(value, ["invitations", "nextCursor"]);
530
- if (!Array.isArray(value.invitations) || value.invitations.length > 100) throw authorityUnavailable();
531
- return {
532
- invitations: unique(value.invitations.map(normalizeOrganizationInvitation), (item) => item.id),
533
- nextCursor: nullableCursor(value.nextCursor)
534
- };
1043
+ //#endregion
1044
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
1045
+ const epoch = (date) => Math.floor(date.getTime() / 1e3);
1046
+ const minute = 60;
1047
+ const hour = minute * 60;
1048
+ const day = hour * 24;
1049
+ const week = day * 7;
1050
+ const year = day * 365.25;
1051
+ 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;
1052
+ function secs(str) {
1053
+ const matched = REGEX.exec(str);
1054
+ if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
1055
+ const value = parseFloat(matched[2]);
1056
+ const unit = matched[3].toLowerCase();
1057
+ let numericDate;
1058
+ switch (unit) {
1059
+ case "sec":
1060
+ case "secs":
1061
+ case "second":
1062
+ case "seconds":
1063
+ case "s":
1064
+ numericDate = Math.round(value);
1065
+ break;
1066
+ case "minute":
1067
+ case "minutes":
1068
+ case "min":
1069
+ case "mins":
1070
+ case "m":
1071
+ numericDate = Math.round(value * minute);
1072
+ break;
1073
+ case "hour":
1074
+ case "hours":
1075
+ case "hr":
1076
+ case "hrs":
1077
+ case "h":
1078
+ numericDate = Math.round(value * hour);
1079
+ break;
1080
+ case "day":
1081
+ case "days":
1082
+ case "d":
1083
+ numericDate = Math.round(value * day);
1084
+ break;
1085
+ case "week":
1086
+ case "weeks":
1087
+ case "w":
1088
+ numericDate = Math.round(value * week);
1089
+ break;
1090
+ default:
1091
+ numericDate = Math.round(value * year);
1092
+ break;
1093
+ }
1094
+ if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
1095
+ return numericDate;
535
1096
  }
536
- function normalizeReceivedInvitation(value) {
537
- exact$2(value, [
538
- "expiresAt",
539
- "id",
540
- "inviterName",
541
- "organization",
542
- "role",
543
- "teams"
544
- ]);
545
- if (!isId(value.id) || !boundedString(value.inviterName, 255) || !role(value.role) || !Array.isArray(value.teams) || value.teams.length > 100 || !isObject(value.organization)) throw authorityUnavailable();
546
- exact$2(value.organization, [
547
- "id",
548
- "logo",
549
- "name",
550
- "slug"
551
- ]);
552
- if (!isId(value.organization.id) || !boundedString(value.organization.name, 255) || !boundedString(value.organization.slug, 255)) throw authorityUnavailable();
553
- return {
554
- id: value.id,
555
- organization: {
556
- id: value.organization.id,
557
- name: value.organization.name,
558
- slug: value.organization.slug,
559
- logo: nullableHttpsUrl(value.organization.logo)
560
- },
561
- role: value.role,
562
- teams: unique(value.teams.map((team) => {
563
- exact$2(team, ["id", "name"]);
564
- if (!isId(team.id) || !boundedString(team.name, 255)) throw authorityUnavailable();
565
- return {
566
- id: team.id,
567
- name: team.name
568
- };
569
- }), (item) => item.id),
570
- inviterName: value.inviterName,
571
- expiresAt: responseDate(value.expiresAt)
572
- };
1097
+ const normalizeTyp = (value) => {
1098
+ if (value.includes("/")) return value.toLowerCase();
1099
+ return `application/${value.toLowerCase()}`;
1100
+ };
1101
+ const checkAudiencePresence = (audPayload, audOption) => {
1102
+ if (typeof audPayload === "string") return audOption.includes(audPayload);
1103
+ if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1104
+ return false;
1105
+ };
1106
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
1107
+ let payload;
1108
+ try {
1109
+ payload = JSON.parse(decoder.decode(encodedPayload));
1110
+ } catch {}
1111
+ if (!isObject$1(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
1112
+ const { typ } = options;
1113
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
1114
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
1115
+ const presenceCheck = [...requiredClaims];
1116
+ if (maxTokenAge !== void 0) presenceCheck.push("iat");
1117
+ if (audience !== void 0) presenceCheck.push("aud");
1118
+ if (subject !== void 0) presenceCheck.push("sub");
1119
+ if (issuer !== void 0) presenceCheck.push("iss");
1120
+ for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
1121
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
1122
+ if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
1123
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
1124
+ let tolerance;
1125
+ switch (typeof options.clockTolerance) {
1126
+ case "string":
1127
+ tolerance = secs(options.clockTolerance);
1128
+ break;
1129
+ case "number":
1130
+ tolerance = options.clockTolerance;
1131
+ break;
1132
+ case "undefined":
1133
+ tolerance = 0;
1134
+ break;
1135
+ default: throw new TypeError("Invalid clockTolerance option type");
1136
+ }
1137
+ const { currentDate } = options;
1138
+ const now = epoch(currentDate || new Date());
1139
+ if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
1140
+ if (payload.nbf !== void 0) {
1141
+ if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
1142
+ if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
1143
+ }
1144
+ if (payload.exp !== void 0) {
1145
+ if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
1146
+ if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
1147
+ }
1148
+ if (maxTokenAge) {
1149
+ const age = now - payload.iat;
1150
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
1151
+ if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
1152
+ if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
1153
+ }
1154
+ return payload;
573
1155
  }
574
- function normalizeReceivedInvitations(value) {
575
- exact$2(value, ["invitations", "nextCursor"]);
576
- if (!Array.isArray(value.invitations) || value.invitations.length > 100) throw authorityUnavailable();
577
- return {
578
- invitations: unique(value.invitations.map(normalizeReceivedInvitation), (item) => item.id),
579
- nextCursor: nullableCursor(value.nextCursor)
1156
+ //#endregion
1157
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jwt/verify.js
1158
+ async function jwtVerify(jwt, key, options) {
1159
+ const verified = await compactVerify(jwt, key, options);
1160
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1161
+ const result = {
1162
+ payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
1163
+ protectedHeader: verified.protectedHeader
580
1164
  };
581
- }
582
- function normalizeInvitationInput(value) {
583
- if (!isObject(value) || Object.keys(value).length !== 1 || !isId(value.invitationId)) throw new AuthError("invalid_invitation", 422);
584
- return { invitationId: value.invitationId };
585
- }
586
- function normalizeInvitationAcceptance(value, invitationId) {
587
- if (!isObject(value) || !isObject(value.invitation) || !isObject(value.member) || value.invitation.id !== invitationId || value.invitation.status !== "accepted" || !isId(value.invitation.organizationId) || value.member.organizationId !== value.invitation.organizationId) throw authorityUnavailable();
588
- return { organizationId: value.invitation.organizationId };
589
- }
590
- function normalizeWorkspaceSelection(value) {
591
- if (!isObject(value)) throw new AuthError("invalid_workspace_selection", 422);
592
- const keys = Object.keys(value);
593
- if (value.type === "personal" && keys.length === 1 && keys[0] === "type") return { type: "personal" };
594
- if (value.type === "organization" && keys.length === 2 && keys.includes("type") && keys.includes("organizationId") && typeof value.organizationId === "string" && id.test(value.organizationId)) return {
595
- type: "organization",
596
- organizationId: value.organizationId
1165
+ if (typeof key === "function") return {
1166
+ ...result,
1167
+ key: verified.key
597
1168
  };
598
- throw new AuthError("invalid_workspace_selection", 422);
599
- }
600
- function fromAuthorityError(value, fallbackStatus, retryAfter) {
601
- const mapped = mapError(isObject(value) && typeof value.code === "string" ? value.code : void 0, fallbackStatus);
602
- return new AuthError(mapped.code, mapped.status, parseRetryAfter(retryAfter));
1169
+ return result;
603
1170
  }
604
- function fromAccountAuthorityError(value, status, retryAfter) {
605
- const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
606
- if (status === 403 && (code === "INVALID_ORIGIN" || code === "MISSING_OR_NULL_ORIGIN")) return new AuthError("request_origin_denied", 403);
607
- if (code === "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL") return new AuthError("account_conflict", 409);
608
- if (code === "INVALID_TOKEN") return new AuthError("password_reset_invalid", 422);
609
- if (code === "INVALID_PASSWORD" || code === "INVALID_EMAIL_OR_PASSWORD") return new AuthError("invalid_credentials", 401);
610
- if (code === "INVALID_EMAIL" || code === "PASSWORD_TOO_SHORT" || code === "PASSWORD_TOO_LONG" || code === "BODY_MUST_BE_AN_OBJECT" || code === "EMAIL_CAN_NOT_BE_UPDATED") return new AuthError("invalid_auth_input", 422);
611
- if (status === 401) return new AuthError("authentication_required", 401);
612
- if (status === 403) return new AuthError("access_denied", 403);
613
- if (status === 409) return new AuthError("state_conflict", 409);
614
- if (status === 429) return new AuthError("auth_request_rate_limited", 429, parseRetryAfter(retryAfter));
615
- if (status === 400 || status === 422) return new AuthError("invalid_auth_input", 422);
616
- return authorityUnavailable();
1171
+ //#endregion
1172
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/jwk/thumbprint.js
1173
+ const check = (value, description) => {
1174
+ if (typeof value !== "string" || !value) throw new JWKInvalid(`${description} missing or invalid`);
1175
+ };
1176
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
1177
+ let jwk;
1178
+ if (isJWK(key)) jwk = key;
1179
+ else if (isKeyLike(key)) jwk = await exportJWK(key);
1180
+ else throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1181
+ digestAlgorithm ??= "sha256";
1182
+ if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") throw new TypeError("digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"");
1183
+ let components;
1184
+ switch (jwk.kty) {
1185
+ case "AKP":
1186
+ check(jwk.alg, "\"alg\" (Algorithm) Parameter");
1187
+ check(jwk.pub, "\"pub\" (Public key) Parameter");
1188
+ components = {
1189
+ alg: jwk.alg,
1190
+ kty: jwk.kty,
1191
+ pub: jwk.pub
1192
+ };
1193
+ break;
1194
+ case "EC":
1195
+ check(jwk.crv, "\"crv\" (Curve) Parameter");
1196
+ check(jwk.x, "\"x\" (X Coordinate) Parameter");
1197
+ check(jwk.y, "\"y\" (Y Coordinate) Parameter");
1198
+ components = {
1199
+ crv: jwk.crv,
1200
+ kty: jwk.kty,
1201
+ x: jwk.x,
1202
+ y: jwk.y
1203
+ };
1204
+ break;
1205
+ case "OKP":
1206
+ check(jwk.crv, "\"crv\" (Subtype of Key Pair) Parameter");
1207
+ check(jwk.x, "\"x\" (Public Key) Parameter");
1208
+ components = {
1209
+ crv: jwk.crv,
1210
+ kty: jwk.kty,
1211
+ x: jwk.x
1212
+ };
1213
+ break;
1214
+ case "RSA":
1215
+ check(jwk.e, "\"e\" (Exponent) Parameter");
1216
+ check(jwk.n, "\"n\" (Modulus) Parameter");
1217
+ components = {
1218
+ e: jwk.e,
1219
+ kty: jwk.kty,
1220
+ n: jwk.n
1221
+ };
1222
+ break;
1223
+ case "oct":
1224
+ check(jwk.k, "\"k\" (Key Value) Parameter");
1225
+ components = {
1226
+ k: jwk.k,
1227
+ kty: jwk.kty
1228
+ };
1229
+ break;
1230
+ default: throw new JOSENotSupported("\"kty\" (Key Type) Parameter missing or unsupported");
1231
+ }
1232
+ const data = encode$1(JSON.stringify(components));
1233
+ return encode(await digest(digestAlgorithm, data));
617
1234
  }
618
- function fromSocialIdTokenAuthorityError(value, status, retryAfter) {
619
- const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
620
- if (code === "INVALID_TOKEN" || code === "FAILED_TO_GET_USER_INFO" || code === "USER_EMAIL_NOT_FOUND") return new AuthError("invalid_credentials", 401);
621
- if (code === "OAUTH_LINK_ERROR") return new AuthError("account_conflict", 409);
622
- return fromAccountAuthorityError(value, status, retryAfter);
1235
+ //#endregion
1236
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/decode_protected_header.js
1237
+ function decodeProtectedHeader(token) {
1238
+ let protectedB64u;
1239
+ if (typeof token === "string") {
1240
+ const parts = token.split(".");
1241
+ if (parts.length === 3 || parts.length === 5) [protectedB64u] = parts;
1242
+ } else if (typeof token === "object" && token) if ("protected" in token) protectedB64u = token.protected;
1243
+ else throw new TypeError("Token does not contain a Protected Header");
1244
+ try {
1245
+ if (typeof protectedB64u !== "string" || !protectedB64u) throw new Error();
1246
+ const result = JSON.parse(decoder.decode(decode(protectedB64u)));
1247
+ if (!isObject$1(result)) throw new Error();
1248
+ return result;
1249
+ } catch {
1250
+ throw new TypeError("Invalid Token or Protected Header formatting");
1251
+ }
623
1252
  }
624
- function authorityUnavailable() {
625
- return new AuthError("identity_authority_unavailable", 503);
1253
+ //#endregion
1254
+ //#region ../../node_modules/.pnpm/jose@6.2.4/node_modules/jose/dist/webapi/util/decode_jwt.js
1255
+ function decodeJwt(jwt) {
1256
+ if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
1257
+ const { 1: payload, length } = jwt.split(".");
1258
+ if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
1259
+ if (length !== 3) throw new JWTInvalid("Invalid JWT");
1260
+ if (!payload) throw new JWTInvalid("JWTs must contain a payload");
1261
+ let decoded;
1262
+ try {
1263
+ decoded = decode(payload);
1264
+ } catch {
1265
+ throw new JWTInvalid("Failed to base64url decode the payload");
1266
+ }
1267
+ let result;
1268
+ try {
1269
+ result = JSON.parse(decoder.decode(decoded));
1270
+ } catch {
1271
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
1272
+ }
1273
+ if (!isObject$1(result)) throw new JWTInvalid("Invalid JWT Claims Set");
1274
+ return result;
626
1275
  }
627
- function fromOrganizationListError(error) {
628
- if (error instanceof AuthError && error.status === 401) return new AuthError("authentication_required", 401);
629
- if (error instanceof AuthError) return error;
630
- return authorityUnavailable();
1276
+ //#endregion
1277
+ //#region ../../node_modules/.pnpm/destr@2.0.5/node_modules/destr/dist/index.mjs
1278
+ const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
1279
+ const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
1280
+ const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
1281
+ function jsonParseTransform(key, value) {
1282
+ if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
1283
+ warnKeyDropped(key);
1284
+ return;
1285
+ }
1286
+ return value;
631
1287
  }
632
- function fromOrganizationReadAuthorityError(value, status) {
633
- if (status === 400) return new AuthError("invalid_request", 400);
634
- if (status === 401) return new AuthError("authentication_required", 401);
635
- if (status === 403) return new AuthError("access_denied", 403);
636
- return authorityUnavailable();
1288
+ function warnKeyDropped(key) {
1289
+ console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
637
1290
  }
638
- function fromOrganizationMutationAuthorityError(value, status, retryAfter) {
639
- if (status === 400 || status === 413 || status === 415) return new AuthError("invalid_request", 400);
640
- if (status === 409) return new AuthError("state_conflict", 409);
641
- if (status === 429) return new AuthError("auth_request_rate_limited", 429, parseRetryAfter(retryAfter));
642
- const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
643
- if (status === 403 && code === "REQUEST_ORIGIN_DENIED") return new AuthError("request_origin_denied", 403);
644
- return fromOrganizationReadAuthorityError(value, status);
645
- }
646
- function fromOrganizationInvitationAdministrationError(value, status, retryAfter) {
647
- if (status === 422 && isObject(value) && value.code === "RECOVERY_REQUIRED") return new AuthError("invitation_recovery_required", 422);
648
- return fromOrganizationMutationAuthorityError(value, status, retryAfter);
649
- }
650
- function normalizeOrganizationMemberAuthority(value, organizationId, memberId) {
651
- exact$2(value, [
652
- "organizationId",
653
- "actor",
654
- "target"
655
- ]);
656
- if (!isId(value.organizationId) || value.organizationId !== organizationId) throw authorityUnavailable();
657
- const actor = normalizeOrganizationAuthorityMemberOutcome(value.actor);
658
- const target = normalizeOrganizationAuthorityMemberOutcome(value.target);
659
- if (target.memberId !== memberId || actor.manualRole !== "owner" && actor.manualRole !== "admin") throw authorityUnavailable();
660
- for (const member of [actor, target]) if (member.manualRole === "member" ? member.role === "owner" : member.role !== member.manualRole) throw authorityUnavailable();
661
- if (actor.memberId === target.memberId && (actor.manualRole !== target.manualRole || actor.role !== target.role || actor.authorityRevision !== target.authorityRevision)) throw authorityUnavailable();
662
- return {
663
- organizationId: value.organizationId,
664
- actor,
665
- target
666
- };
1291
+ function destr(value, options = {}) {
1292
+ if (typeof value !== "string") return value;
1293
+ if (value[0] === "\"" && value[value.length - 1] === "\"" && value.indexOf("\\") === -1) return value.slice(1, -1);
1294
+ const _value = value.trim();
1295
+ if (_value.length <= 9) switch (_value.toLowerCase()) {
1296
+ case "true": return true;
1297
+ case "false": return false;
1298
+ case "undefined": return;
1299
+ case "null": return null;
1300
+ case "nan": return NaN;
1301
+ case "infinity": return Number.POSITIVE_INFINITY;
1302
+ case "-infinity": return Number.NEGATIVE_INFINITY;
1303
+ }
1304
+ if (!JsonSigRx.test(value)) {
1305
+ if (options.strict) throw new SyntaxError("[destr] Invalid JSON");
1306
+ return value;
1307
+ }
1308
+ try {
1309
+ if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
1310
+ if (options.strict) throw new Error("[destr] Possible prototype pollution");
1311
+ return JSON.parse(value, jsonParseTransform);
1312
+ }
1313
+ return JSON.parse(value);
1314
+ } catch (error) {
1315
+ if (options.strict) throw error;
1316
+ return value;
1317
+ }
667
1318
  }
668
- function normalizeOrganizationAuthorityMemberOutcome(value, includesStatus = false) {
669
- exact$2(value, [
670
- "memberId",
671
- "manualRole",
672
- "role",
673
- "authorityRevision",
674
- ...includesStatus ? ["status"] : []
675
- ]);
676
- if (!isId(value.memberId) || value.manualRole !== "owner" && value.manualRole !== "admin" && value.manualRole !== "member" || value.role !== "owner" && value.role !== "admin" && value.role !== "member") throw authorityUnavailable();
677
- return {
678
- memberId: value.memberId,
679
- manualRole: value.manualRole,
680
- role: value.role,
681
- authorityRevision: normalizeAuthorityResultRevision(value.authorityRevision)
682
- };
1319
+ //#endregion
1320
+ //#region ../../node_modules/.pnpm/ofetch@1.5.1/node_modules/ofetch/dist/shared/ofetch.CWycOUEr.mjs
1321
+ var FetchError = class extends Error {
1322
+ constructor(message, opts) {
1323
+ super(message, opts);
1324
+ this.name = "FetchError";
1325
+ if (opts?.cause && !this.cause) this.cause = opts.cause;
1326
+ }
1327
+ };
1328
+ function createFetchError(ctx) {
1329
+ const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
1330
+ const method = ctx.request?.method || ctx.options?.method || "GET";
1331
+ const url = ctx.request?.url || String(ctx.request) || "/";
1332
+ const fetchError = new FetchError(`${`[${method}] ${JSON.stringify(url)}`}: ${ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : "<no response>"}${errorMessage ? ` ${errorMessage}` : ""}`, ctx.error ? { cause: ctx.error } : void 0);
1333
+ for (const key of [
1334
+ "request",
1335
+ "options",
1336
+ "response"
1337
+ ]) Object.defineProperty(fetchError, key, { get() {
1338
+ return ctx[key];
1339
+ } });
1340
+ for (const [key, refKey] of [
1341
+ ["data", "_data"],
1342
+ ["status", "status"],
1343
+ ["statusCode", "status"],
1344
+ ["statusText", "statusText"],
1345
+ ["statusMessage", "statusText"]
1346
+ ]) Object.defineProperty(fetchError, key, { get() {
1347
+ return ctx.response && ctx.response[refKey];
1348
+ } });
1349
+ return fetchError;
683
1350
  }
684
- function normalizeAuthorityResultRevision(value) {
685
- if (!Number.isSafeInteger(value) || value < 0 || value >= Number.MAX_SAFE_INTEGER) throw authorityUnavailable();
686
- return value;
1351
+ const payloadMethods = new Set(Object.freeze([
1352
+ "PATCH",
1353
+ "POST",
1354
+ "PUT",
1355
+ "DELETE"
1356
+ ]));
1357
+ function isPayloadMethod(method = "GET") {
1358
+ return payloadMethods.has(method.toUpperCase());
687
1359
  }
688
- function fromInvitationAuthorityError(value, status) {
689
- const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
690
- if (status === 401 && code === "UNAUTHORIZED") return new AuthError("authentication_required", 401);
691
- if (status === 403 && (code === "INVALID_ORIGIN" || code === "MISSING_OR_NULL_ORIGIN")) return new AuthError("request_origin_denied", 403);
692
- if (status === 403 && code === "YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION") return new AuthError("invitation_recipient_mismatch", 403);
693
- if (status === 403 && code === "EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION") return new AuthError("email_verification_required", 403);
694
- if (status === 400 && (code === "INVITATION_NOT_FOUND" || code === "ORGANIZATION_NOT_FOUND" || code === "TEAM_NOT_FOUND")) return new AuthError("invitation_unavailable", 409);
695
- return authorityUnavailable();
1360
+ function isJSONSerializable(value) {
1361
+ if (value === void 0) return false;
1362
+ const t = typeof value;
1363
+ if (t === "string" || t === "number" || t === "boolean" || t === null) return true;
1364
+ if (t !== "object") return false;
1365
+ if (Array.isArray(value)) return true;
1366
+ if (value.buffer) return false;
1367
+ if (value instanceof FormData || value instanceof URLSearchParams) return false;
1368
+ return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
696
1369
  }
697
- function fromInvitationError(error) {
698
- return error instanceof AuthError ? error : authorityUnavailable();
1370
+ const textTypes = new Set([
1371
+ "image/svg",
1372
+ "application/xml",
1373
+ "application/xhtml",
1374
+ "application/html"
1375
+ ]);
1376
+ const JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
1377
+ function detectResponseType(_contentType = "") {
1378
+ if (!_contentType) return "json";
1379
+ const contentType = _contentType.split(";").shift() || "";
1380
+ if (JSON_RE.test(contentType)) return "json";
1381
+ if (contentType === "text/event-stream") return "stream";
1382
+ if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
1383
+ return "blob";
699
1384
  }
700
- function mapError(code, status) {
701
- if (code === "authentication_required") return {
702
- code,
703
- status: 401
704
- };
705
- if (code === "request_origin_denied") return {
706
- code,
707
- status: 403
708
- };
709
- if (code === "invalid_workspace_selection") return {
710
- code,
711
- status: 422
712
- };
713
- if (code === "organization_context_too_large") return {
714
- code,
715
- status: 422
716
- };
717
- if (code === "credential_rate_limited") return {
718
- code,
719
- status: 429
720
- };
721
- if (code === "identity_authority_unavailable") return {
722
- code,
723
- status: 503
724
- };
725
- if (status === 401 || status === 400) return {
726
- code: "invalid_credentials",
727
- status: 401
728
- };
729
- if (status === 403) return {
730
- code: "access_denied",
731
- status: 403
732
- };
733
- if (status === 409) return {
734
- code: "state_conflict",
735
- status: 409
736
- };
737
- if (status === 422) return {
738
- code: "invalid_workspace_selection",
739
- status: 422
740
- };
741
- if (status === 429) return {
742
- code: "credential_rate_limited",
743
- status: 429
1385
+ function resolveFetchOptions(request, input, defaults, Headers) {
1386
+ const headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers);
1387
+ let query;
1388
+ if (defaults?.query || defaults?.params || input?.params || input?.query) query = {
1389
+ ...defaults?.params,
1390
+ ...defaults?.query,
1391
+ ...input?.params,
1392
+ ...input?.query
744
1393
  };
745
1394
  return {
746
- code: "identity_authority_unavailable",
747
- status: 503
1395
+ ...defaults,
1396
+ ...input,
1397
+ query,
1398
+ params: query,
1399
+ headers
748
1400
  };
749
1401
  }
750
- function parseRetryAfter(value) {
751
- if (!value || !/^\d+$/.test(value)) return void 0;
752
- const seconds = Number(value);
753
- return Number.isSafeInteger(seconds) && seconds >= 1 && seconds <= 3600 ? seconds : void 0;
754
- }
755
- function toDate(value) {
756
- const result = value instanceof Date ? value : typeof value === "string" ? new Date(value) : void 0;
757
- return result && Number.isFinite(result.getTime()) ? result : void 0;
758
- }
759
- function isId(value) {
760
- return typeof value === "string" && id.test(value);
761
- }
762
- function exact$2(value, keys) {
763
- if (!isObject(value) || Object.keys(value).sort().join(",") !== [...keys].sort().join(",")) throw authorityUnavailable();
764
- }
765
- function boundedString(value, maximum) {
766
- return typeof value === "string" && value.length > 0 && new TextEncoder().encode(value).byteLength <= maximum;
767
- }
768
- function role(value) {
769
- return value === "owner" || value === "admin" || value === "member";
770
- }
771
- function nullableHttpsUrl(value) {
772
- if (value === null) return null;
773
- if (typeof value !== "string" || value.length > 2048) throw authorityUnavailable();
774
- let url;
775
- try {
776
- url = new URL(value);
777
- } catch {
778
- throw authorityUnavailable();
779
- }
780
- if (url.protocol !== "https:" || url.username || url.password || url.toString() !== value) throw authorityUnavailable();
781
- return value;
782
- }
783
- function responseDate(value) {
784
- if (typeof value !== "string") throw authorityUnavailable();
785
- const date = new Date(value);
786
- if (!Number.isFinite(date.getTime()) || date.toISOString() !== value) throw authorityUnavailable();
787
- return date;
1402
+ function mergeHeaders(input, defaults, Headers) {
1403
+ if (!defaults) return new Headers(input);
1404
+ const headers = new Headers(defaults);
1405
+ if (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers(input)) headers.set(key, value);
1406
+ return headers;
788
1407
  }
789
- function nullableCursor(value) {
790
- if (value === null) return null;
791
- if (typeof value !== "string" || value.length < 1 || value.length > 820 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value)) throw authorityUnavailable();
792
- return value;
1408
+ async function callHooks(context, hooks) {
1409
+ if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
1410
+ else await hooks(context);
793
1411
  }
794
- function normalizeResponseId(value) {
795
- if (!isId(value)) throw authorityUnavailable();
796
- return value;
797
- }
798
- function unique(items, key) {
799
- if (new Set(items.map(key)).size !== items.length) throw authorityUnavailable();
800
- return items;
801
- }
802
- function isObject(value) {
803
- return typeof value === "object" && value !== null && !Array.isArray(value);
804
- }
805
- //#endregion
806
- //#region src/identity-resolution.ts
807
- 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])/;
808
- function exact$1(value, keys) {
809
- return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
810
- }
811
- function createIdentityResolverAuth(options) {
812
- const url = joinURL(normalizeOrigin(options.authOrigin, "authOrigin"), "api/v1/auth/identities/resolve");
813
- const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
814
- if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
815
- const timeoutMs = normalizeTimeout(options.timeoutMs);
816
- let inFlight = false;
817
- return { async resolveIdentity(input, clientAssertion) {
818
- if (!exact$1(input, ["identifier"]) || typeof input.identifier !== "string" || input.identifier.length > 324) throw new AuthError("invalid_request", 400);
819
- const identifier = input.identifier.trim().toLowerCase();
820
- if (!(identifier.length <= 320 && emailPattern$1.test(identifier)) && !/^[a-z0-9_.]{3,30}$(?![\s\S])/.test(identifier)) throw new AuthError("invalid_request", 400);
821
- 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);
822
- if (inFlight) throw new AuthError("state_conflict", 409);
823
- inFlight = true;
824
- const controller = new AbortController();
825
- let reader;
826
- let timer;
827
- let mappedError;
828
- try {
829
- const deadline = new Promise((_, reject) => {
830
- timer = setTimeout(() => {
831
- reject(authorityUnavailable());
832
- controller.abort();
833
- reader?.cancel().catch(() => {});
834
- }, timeoutMs);
835
- });
836
- const exchange = async () => {
837
- const response = await fetchImpl(url, {
838
- method: "POST",
839
- headers: {
840
- authorization: `Bearer ${clientAssertion}`,
841
- accept: "application/json",
842
- "content-type": "application/json"
843
- },
844
- body: JSON.stringify({ identifier }),
845
- credentials: "omit",
846
- cache: "no-store",
847
- redirect: "manual",
848
- signal: controller.signal
1412
+ const retryStatusCodes = new Set([
1413
+ 408,
1414
+ 409,
1415
+ 425,
1416
+ 429,
1417
+ 500,
1418
+ 502,
1419
+ 503,
1420
+ 504
1421
+ ]);
1422
+ const nullBodyResponses = new Set([
1423
+ 101,
1424
+ 204,
1425
+ 205,
1426
+ 304
1427
+ ]);
1428
+ function createFetch(globalOptions = {}) {
1429
+ const { fetch = globalThis.fetch, Headers = globalThis.Headers, AbortController = globalThis.AbortController } = globalOptions;
1430
+ async function onError(context) {
1431
+ const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
1432
+ if (context.options.retry !== false && !isAbort) {
1433
+ let retries;
1434
+ if (typeof context.options.retry === "number") retries = context.options.retry;
1435
+ else retries = isPayloadMethod(context.options.method) ? 0 : 1;
1436
+ const responseCode = context.response && context.response.status || 500;
1437
+ if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
1438
+ const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
1439
+ if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));
1440
+ return $fetchRaw(context.request, {
1441
+ ...context.options,
1442
+ retry: retries - 1
849
1443
  });
850
- if (controller.signal.aborted) {
851
- response.body?.cancel().catch(() => {});
852
- throw authorityUnavailable();
853
- }
854
- if (!response.body) throw authorityUnavailable();
855
- reader = response.body.getReader();
856
- const length = response.headers.get("content-length");
857
- if (response.redirected || response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > 1024)) throw authorityUnavailable();
858
- const bytes = new Uint8Array(1024);
859
- let size = 0;
860
- while (true) {
861
- const chunk = await reader.read();
862
- if (controller.signal.aborted) throw authorityUnavailable();
863
- if (chunk.done) break;
864
- if (size + chunk.value.byteLength > bytes.length) throw authorityUnavailable();
865
- bytes.set(chunk.value, size);
866
- size += chunk.value.byteLength;
867
- }
868
- const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size)));
869
- if (response.status !== 200) {
870
- if (!exact$1(value, ["code", "message"])) throw authorityUnavailable();
871
- if (response.status === 401 && value.code === "UNAUTHORIZED" && value.message === "The identity resolution assertion is invalid.") mappedError = new AuthError("authentication_required", 401);
872
- if (response.status === 429 && value.code === "TOO_MANY_REQUESTS" && value.message === "Identity resolution requests are temporarily limited.") {
873
- const retryAfter = response.headers.get("retry-after");
874
- if (retryAfter === null || !/^(?:[1-9]|[1-5][0-9]|60)$/.test(retryAfter)) throw authorityUnavailable();
875
- mappedError = new AuthError("auth_request_rate_limited", 429, Number(retryAfter));
876
- }
877
- throw mappedError ?? authorityUnavailable();
878
- }
879
- if (!exact$1(value, ["identity"])) throw authorityUnavailable();
880
- if (value.identity === null) return null;
881
- if (!exact$1(value.identity, ["userId"]) || typeof value.identity.userId !== "string" || !/^[A-Za-z0-9_-]{1,128}$(?![\s\S])/.test(value.identity.userId)) throw authorityUnavailable();
882
- return { userId: value.identity.userId };
883
- };
884
- return await Promise.race([exchange().finally(() => {
885
- inFlight = false;
886
- }), deadline]);
1444
+ }
1445
+ }
1446
+ const error = createFetchError(context);
1447
+ if (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);
1448
+ throw error;
1449
+ }
1450
+ const $fetchRaw = async function $fetchRaw2(_request, _options = {}) {
1451
+ const context = {
1452
+ request: _request,
1453
+ options: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers),
1454
+ response: void 0,
1455
+ error: void 0
1456
+ };
1457
+ if (context.options.method) context.options.method = context.options.method.toUpperCase();
1458
+ if (context.options.onRequest) {
1459
+ await callHooks(context, context.options.onRequest);
1460
+ if (!(context.options.headers instanceof Headers)) context.options.headers = new Headers(context.options.headers || {});
1461
+ }
1462
+ if (typeof context.request === "string") {
1463
+ if (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);
1464
+ if (context.options.query) {
1465
+ context.request = withQuery(context.request, context.options.query);
1466
+ delete context.options.query;
1467
+ }
1468
+ if ("query" in context.options) delete context.options.query;
1469
+ if ("params" in context.options) delete context.options.params;
1470
+ }
1471
+ if (context.options.body && isPayloadMethod(context.options.method)) {
1472
+ if (isJSONSerializable(context.options.body)) {
1473
+ const contentType = context.options.headers.get("content-type");
1474
+ if (typeof context.options.body !== "string") context.options.body = contentType === "application/x-www-form-urlencoded" ? new URLSearchParams(context.options.body).toString() : JSON.stringify(context.options.body);
1475
+ if (!contentType) context.options.headers.set("content-type", "application/json");
1476
+ if (!context.options.headers.has("accept")) context.options.headers.set("accept", "application/json");
1477
+ } else if ("pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || typeof context.options.body.pipe === "function") {
1478
+ if (!("duplex" in context.options)) context.options.duplex = "half";
1479
+ }
1480
+ }
1481
+ let abortTimeout;
1482
+ if (!context.options.signal && context.options.timeout) {
1483
+ const controller = new AbortController();
1484
+ abortTimeout = setTimeout(() => {
1485
+ const error = new Error("[TimeoutError]: The operation was aborted due to timeout");
1486
+ error.name = "TimeoutError";
1487
+ error.code = 23;
1488
+ controller.abort(error);
1489
+ }, context.options.timeout);
1490
+ context.options.signal = controller.signal;
1491
+ }
1492
+ try {
1493
+ context.response = await fetch(context.request, context.options);
887
1494
  } catch (error) {
888
- if (mappedError && mappedError === error) throw mappedError;
889
- throw authorityUnavailable();
1495
+ context.error = error;
1496
+ if (context.options.onRequestError) await callHooks(context, context.options.onRequestError);
1497
+ return await onError(context);
890
1498
  } finally {
891
- clearTimeout(timer);
892
- controller.abort();
893
- reader?.cancel().catch(() => {});
1499
+ if (abortTimeout) clearTimeout(abortTimeout);
894
1500
  }
895
- } };
1501
+ if ((context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD") {
1502
+ const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
1503
+ switch (responseType) {
1504
+ case "json": {
1505
+ const data = await context.response.text();
1506
+ const parseFunction = context.options.parseResponse || destr;
1507
+ context.response._data = parseFunction(data);
1508
+ break;
1509
+ }
1510
+ case "stream":
1511
+ context.response._data = context.response.body || context.response._bodyInit;
1512
+ break;
1513
+ default: context.response._data = await context.response[responseType]();
1514
+ }
1515
+ }
1516
+ if (context.options.onResponse) await callHooks(context, context.options.onResponse);
1517
+ if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
1518
+ if (context.options.onResponseError) await callHooks(context, context.options.onResponseError);
1519
+ return await onError(context);
1520
+ }
1521
+ return context.response;
1522
+ };
1523
+ const $fetch = async function $fetch2(request, options) {
1524
+ return (await $fetchRaw(request, options))._data;
1525
+ };
1526
+ $fetch.raw = $fetchRaw;
1527
+ $fetch.native = (...args) => fetch(...args);
1528
+ $fetch.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
1529
+ ...globalOptions,
1530
+ ...customGlobalOptions,
1531
+ defaults: {
1532
+ ...globalOptions.defaults,
1533
+ ...customGlobalOptions.defaults,
1534
+ ...defaultOptions
1535
+ }
1536
+ });
1537
+ return $fetch;
896
1538
  }
897
1539
  //#endregion
898
- //#region src/drive-recipients.ts
899
- const encoder = new TextEncoder();
900
- const emailPattern = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/;
901
- function validEmail(value) {
902
- return typeof value === "string" && encoder.encode(value).byteLength <= 320 && emailPattern.test(value);
1540
+ //#region src/shared.ts
1541
+ const DRIVE_CREDENTIAL_LIFETIME_SECONDS = 840;
1542
+ const id = /^[A-Za-z0-9_-]{1,128}$/;
1543
+ const email = /^[^\s@]+@[^\s@]+$/;
1544
+ const MAX_SOCIAL_ID_TOKEN_BYTES = 16 * 1024;
1545
+ function normalizeEmail(value) {
1546
+ if (typeof value !== "string") throw new TypeError("email is invalid");
1547
+ const normalized = value.trim().toLowerCase();
1548
+ if (normalized.length === 0 || normalized.length > 320 || !email.test(normalized)) throw new TypeError("email is invalid");
1549
+ return normalized;
903
1550
  }
904
- function exact(value, keys) {
905
- return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
1551
+ function normalizeSocialIdTokenInput(value) {
1552
+ if (!isObject(value)) throw new TypeError("social ID token input is invalid");
1553
+ const keys = Object.keys(value);
1554
+ 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");
1555
+ return {
1556
+ provider: value.provider,
1557
+ idToken: value.idToken,
1558
+ ...value.nonce === void 0 ? {} : { nonce: value.nonce },
1559
+ signUp: value.signUp
1560
+ };
906
1561
  }
907
- const failures = {
908
- 400: [
909
- "BAD_REQUEST",
910
- "The recipient request is invalid.",
911
- "invalid_request"
912
- ],
913
- 401: [
914
- "UNAUTHORIZED",
915
- "The recipient service assertion is invalid.",
916
- "authentication_required"
917
- ],
918
- 404: [
919
- "NOT_FOUND",
920
- "The recipient is unavailable.",
921
- "recipient_unavailable"
922
- ],
923
- 405: [
924
- "METHOD_NOT_ALLOWED",
925
- "METHOD_NOT_ALLOWED",
926
- "invalid_request"
927
- ],
928
- 413: [
929
- "REQUEST_TOO_LONG",
930
- "The recipient request is too large.",
931
- "invalid_request"
932
- ],
933
- 429: [
934
- "TOO_MANY_REQUESTS",
935
- "Recipient requests are temporarily limited.",
936
- "auth_request_rate_limited"
937
- ],
938
- 503: [
939
- "SERVICE_UNAVAILABLE",
940
- "Recipient resolution is temporarily unavailable.",
941
- "identity_authority_unavailable"
942
- ]
943
- };
944
- function createDriveRecipientAuth(options) {
945
- const url = joinURL(normalizeOrigin(options.authOrigin, "authOrigin"), "api/v1/auth/drive-share-recipients/resolve");
946
- const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
947
- if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
948
- const timeoutMs = normalizeTimeout(options.timeoutMs);
949
- let inFlight = false;
950
- return { async resolveRecipient(input, clientAssertion) {
951
- let body;
952
- let email;
953
- try {
954
- if (!exact(input, ["email"]) || typeof input.email !== "string") throw new Error();
955
- email = input.email.trim().toLowerCase();
956
- if (!validEmail(email)) throw new Error();
957
- body = JSON.stringify({ email });
958
- } catch {
959
- throw new AuthError("invalid_request", 400);
1562
+ function socialIdTokenRequest(value) {
1563
+ return {
1564
+ provider: value.provider,
1565
+ idToken: {
1566
+ token: value.idToken,
1567
+ ...value.nonce === void 0 ? {} : { nonce: value.nonce }
1568
+ },
1569
+ requestSignUp: value.signUp
1570
+ };
1571
+ }
1572
+ function normalizeOrigin(value, name) {
1573
+ if (value.length === 0 || value.length > 2048 || /[^\x20-\x7e]/.test(value)) throw new TypeError(`${name} must be an ASCII HTTP origin`);
1574
+ let url;
1575
+ try {
1576
+ url = new URL(value);
1577
+ } catch {
1578
+ throw new TypeError(`${name} must be an ASCII HTTP origin`);
1579
+ }
1580
+ const local = url.hostname === "localhost" || url.hostname.endsWith(".localhost") || url.hostname === "127.0.0.1";
1581
+ 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`);
1582
+ return url.origin;
1583
+ }
1584
+ function normalizeTimeout(value) {
1585
+ const timeout = value ?? 1e4;
1586
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 6e4) throw new TypeError("timeoutMs must be an integer from 1 to 60000");
1587
+ return timeout;
1588
+ }
1589
+ function normalizeSession(value) {
1590
+ if (value === null) return null;
1591
+ if (!isObject(value) || !isObject(value.session) || !isObject(value.user)) throw authorityUnavailable();
1592
+ const expiresAt = toDate(value.session.expiresAt);
1593
+ const image = value.user.image;
1594
+ if (!isId(value.session.id) || !expiresAt || !isId(value.user.id) || typeof value.user.name !== "string" || value.user.name.length > 256 || typeof value.user.email !== "string" || value.user.email.length > 320 || !email.test(value.user.email) || typeof value.user.emailVerified !== "boolean" || image !== null && image !== void 0 && (typeof image !== "string" || image.length > 2048)) throw authorityUnavailable();
1595
+ return {
1596
+ id: value.session.id,
1597
+ expiresAt,
1598
+ user: {
1599
+ id: value.user.id,
1600
+ name: value.user.name,
1601
+ email: value.user.email,
1602
+ emailVerified: value.user.emailVerified,
1603
+ image: image ?? null
960
1604
  }
961
- if (encoder.encode(body).byteLength > 1024) throw new AuthError("invalid_request", 413);
962
- 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);
963
- if (inFlight) throw new AuthError("state_conflict", 409);
964
- inFlight = true;
965
- const controller = new AbortController();
966
- let reader;
967
- let timer;
968
- let authorityError;
969
- try {
970
- const deadline = new Promise((_, reject) => {
971
- timer = setTimeout(() => {
972
- reject(authorityUnavailable());
973
- controller.abort();
974
- reader?.cancel().catch(() => {});
975
- }, timeoutMs);
976
- });
977
- const exchange = async () => {
978
- const response = await fetchImpl(url, {
979
- method: "POST",
980
- headers: {
981
- authorization: `Bearer ${clientAssertion}`,
982
- accept: "application/json",
983
- "content-type": "application/json"
984
- },
985
- body,
986
- credentials: "omit",
987
- cache: "no-store",
988
- redirect: "manual",
989
- signal: controller.signal
990
- });
991
- if (controller.signal.aborted) {
992
- response.body?.cancel().catch(() => {});
993
- throw authorityUnavailable();
994
- }
995
- if (!response.body) throw authorityUnavailable();
996
- reader = response.body.getReader();
997
- const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
998
- const length = response.headers.get("content-length");
999
- if (response.redirected || contentType !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > 4096)) throw authorityUnavailable();
1000
- const bytes = new Uint8Array(4096);
1001
- let size = 0;
1002
- while (true) {
1003
- const chunk = await reader.read();
1004
- if (controller.signal.aborted) throw authorityUnavailable();
1005
- if (chunk.done) break;
1006
- if (size + chunk.value.byteLength > bytes.byteLength) throw authorityUnavailable();
1007
- bytes.set(chunk.value, size);
1008
- size += chunk.value.byteLength;
1009
- }
1010
- const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size)));
1011
- if (response.status !== 200) {
1012
- const status = response.status;
1013
- const failure = failures[status];
1014
- if (!failure || !exact(value, ["code", "message"]) || value.code !== failure[0] || value.message !== failure[1]) throw authorityUnavailable();
1015
- let retryAfterSeconds;
1016
- if (status === 429) {
1017
- const retryAfter = response.headers.get("retry-after");
1018
- if (retryAfter === null || !/^(?:[1-9]|[1-5][0-9]|60)$/.test(retryAfter)) throw authorityUnavailable();
1019
- retryAfterSeconds = Number(retryAfter);
1020
- }
1021
- authorityError = new AuthError(failure[2], status, retryAfterSeconds);
1022
- throw authorityError;
1023
- }
1024
- if (!exact(value, ["recipient"]) || !exact(value.recipient, [
1025
- "userId",
1026
- "name",
1027
- "email"
1028
- ])) throw authorityUnavailable();
1029
- const recipient = value.recipient;
1030
- if (typeof recipient.userId !== "string" || !/^[A-Za-z0-9_-]{1,128}$(?![\s\S])/.test(recipient.userId) || typeof recipient.name !== "string" || recipient.name.length === 0 || encoder.encode(recipient.name).byteLength > 1024 || !validEmail(recipient.email) || recipient.email !== recipient.email.trim().toLowerCase() || recipient.email !== email) throw authorityUnavailable();
1031
- return {
1032
- userId: recipient.userId,
1033
- name: recipient.name,
1034
- email: recipient.email
1035
- };
1036
- };
1037
- return await Promise.race([exchange().finally(() => {
1038
- inFlight = false;
1039
- }), deadline]);
1040
- } catch (error) {
1041
- if (authorityError && error === authorityError) throw authorityError;
1042
- throw authorityUnavailable();
1043
- } finally {
1044
- clearTimeout(timer);
1045
- controller.abort();
1046
- reader?.cancel().catch(() => {});
1605
+ };
1606
+ }
1607
+ function normalizeDriveCredential(value, now) {
1608
+ if (!isObject(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();
1609
+ return {
1610
+ tokenType: "Bearer",
1611
+ token: value.token,
1612
+ expiresAt: new Date(now + value.expiresIn * 1e3)
1613
+ };
1614
+ }
1615
+ function normalizeOrganizationPageInput(value) {
1616
+ if (value === void 0) return new URLSearchParams();
1617
+ if (!isObject(value) || Object.keys(value).some((key) => key !== "limit" && key !== "cursor")) throw new AuthError("invalid_request", 400);
1618
+ const input = value;
1619
+ const query = new URLSearchParams();
1620
+ if (input.limit !== void 0) {
1621
+ if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) throw new AuthError("invalid_request", 400);
1622
+ query.set("limit", String(input.limit));
1623
+ }
1624
+ if (input.cursor !== void 0) {
1625
+ if (typeof input.cursor !== "string" || input.cursor.length < 1 || input.cursor.length > 820 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(input.cursor)) throw new AuthError("invalid_request", 400);
1626
+ query.set("cursor", input.cursor);
1627
+ }
1628
+ return query;
1629
+ }
1630
+ function normalizeIdInput(value) {
1631
+ if (!isId(value)) throw new AuthError("invalid_request", 400);
1632
+ return value;
1633
+ }
1634
+ function normalizeOrganization(value) {
1635
+ exact$2(value, [
1636
+ "capabilities",
1637
+ "id",
1638
+ "lifecycle",
1639
+ "logo",
1640
+ "name",
1641
+ "role",
1642
+ "slug"
1643
+ ]);
1644
+ if (!isId(value.id) || !boundedString(value.name, 255) || !boundedString(value.slug, 255) || value.lifecycle !== "ordinary" && value.lifecycle !== "managed" || !role(value.role) || !isObject(value.capabilities)) throw authorityUnavailable();
1645
+ exact$2(value.capabilities, [
1646
+ "readInvitations",
1647
+ "readMembers",
1648
+ "readTeams"
1649
+ ]);
1650
+ if (value.capabilities.readMembers !== true || value.capabilities.readTeams !== true || typeof value.capabilities.readInvitations !== "boolean") throw authorityUnavailable();
1651
+ return {
1652
+ id: value.id,
1653
+ name: value.name,
1654
+ slug: value.slug,
1655
+ logo: nullableHttpsUrl(value.logo),
1656
+ lifecycle: value.lifecycle,
1657
+ role: value.role,
1658
+ capabilities: {
1659
+ readMembers: true,
1660
+ readTeams: true,
1661
+ readInvitations: value.capabilities.readInvitations
1047
1662
  }
1048
- } };
1663
+ };
1049
1664
  }
1050
- //#endregion
1051
- //#region src/provisioning.ts
1052
- const MAX_BYTES = 16 * 1024;
1053
- const compactJwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
1054
- function isCompactCredential(value) {
1055
- return typeof value === "string" && value.length + 7 <= MAX_BYTES && compactJwt.test(value);
1665
+ function normalizeOrganizationDisplayInput(value) {
1666
+ if (!isObject(value) || Object.keys(value).sort().join(",") !== "logo,name,slug") throw new AuthError("invalid_request", 400);
1667
+ if (!boundedString(value.name, 255) || !boundedString(value.slug, 255)) throw new AuthError("invalid_request", 400);
1668
+ let logo;
1669
+ try {
1670
+ logo = nullableHttpsUrl(value.logo);
1671
+ } catch {
1672
+ throw new AuthError("invalid_request", 400);
1673
+ }
1674
+ return {
1675
+ name: value.name,
1676
+ slug: value.slug,
1677
+ logo
1678
+ };
1056
1679
  }
1057
- function createDriveProvisioningAuth(options) {
1058
- const url = joinURL(normalizeOrigin(options.authOrigin, "authOrigin"), "api/v1/auth/drive-provisioning-credential");
1059
- const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
1060
- if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
1061
- const timeoutMs = normalizeTimeout(options.timeoutMs);
1062
- const now = options.now ?? Date.now;
1063
- let inFlight = false;
1064
- return { async getDriveProvisioningCredential(clientAssertion) {
1065
- if (!isCompactCredential(clientAssertion)) throw new AuthError("invalid_request", 400);
1066
- if (inFlight) throw new AuthError("state_conflict", 409);
1067
- inFlight = true;
1068
- const controller = new AbortController();
1069
- let reader;
1070
- let timer;
1071
- let exchangeStarted = false;
1072
- let authorityError;
1073
- try {
1074
- const startedAt = now();
1075
- if (!Number.isSafeInteger(startedAt) || startedAt < 0 || startedAt > 86399999997e5) throw authorityUnavailable();
1076
- const deadline = new Promise((_, reject) => {
1077
- timer = setTimeout(() => {
1078
- reject(authorityUnavailable());
1079
- controller.abort();
1080
- reader?.cancel().catch(() => {});
1081
- }, timeoutMs);
1082
- });
1083
- const exchange = async () => {
1084
- const response = await fetchImpl(url, {
1085
- method: "POST",
1086
- headers: {
1087
- authorization: `Bearer ${clientAssertion}`,
1088
- accept: "application/json"
1089
- },
1090
- credentials: "omit",
1091
- cache: "no-store",
1092
- redirect: "manual",
1093
- signal: controller.signal
1094
- });
1095
- if (controller.signal.aborted) {
1096
- response.body?.cancel().catch(() => {});
1097
- throw authorityUnavailable();
1098
- }
1099
- if (!response.body) throw authorityUnavailable();
1100
- reader = response.body.getReader();
1101
- const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
1102
- const length = response.headers.get("content-length");
1103
- if (contentType !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_BYTES)) throw authorityUnavailable();
1104
- const bytes = new Uint8Array(MAX_BYTES);
1105
- let size = 0;
1106
- while (true) {
1107
- const chunk = await reader.read();
1108
- if (chunk.done) break;
1109
- if (controller.signal.aborted || size + chunk.value.byteLength > MAX_BYTES) throw authorityUnavailable();
1110
- bytes.set(chunk.value, size);
1111
- size += chunk.value.byteLength;
1112
- }
1113
- const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size)));
1114
- if (!value || typeof value !== "object" || Array.isArray(value)) throw authorityUnavailable();
1115
- const record = value;
1116
- if (response.status !== 200) {
1117
- if (Object.keys(record).length !== 2 || !("code" in record) || !("message" in record)) throw authorityUnavailable();
1118
- if (response.status === 401 && record.code === "UNAUTHORIZED" && record.message === "The ecosystem client assertion is invalid.") {
1119
- authorityError = new AuthError("authentication_required", 401);
1120
- throw authorityError;
1121
- }
1122
- const retryAfter = response.headers.get("retry-after");
1123
- if (response.status === 429 && record.code === "TOO_MANY_REQUESTS" && record.message === "Ecosystem credential exchanges are temporarily limited." && retryAfter !== null && /^(?:[1-9]|[1-5][0-9]|60)$/.test(retryAfter)) {
1124
- authorityError = new AuthError("auth_request_rate_limited", 429, Number(retryAfter));
1125
- throw authorityError;
1126
- }
1127
- throw authorityUnavailable();
1128
- }
1129
- if (Object.keys(record).length !== 3 || record.tokenType !== "Bearer" || record.expiresIn !== 300 || !isCompactCredential(record.token)) throw authorityUnavailable();
1130
- const expiresAt = new Date(Math.floor(startedAt / 1e3) * 1e3 + 3e5);
1131
- const completedAt = now();
1132
- if (!Number.isSafeInteger(completedAt) || completedAt < 0 || completedAt >= expiresAt.getTime()) throw authorityUnavailable();
1133
- return {
1134
- tokenType: "Bearer",
1135
- token: record.token,
1136
- expiresAt
1137
- };
1680
+ function normalizeOrganizationDisplay(value) {
1681
+ try {
1682
+ return normalizeOrganizationDisplayInput(value);
1683
+ } catch {
1684
+ throw authorityUnavailable();
1685
+ }
1686
+ }
1687
+ function normalizeOrganizationTeamDisplayInput(value) {
1688
+ if (!isObject(value) || Object.keys(value).join(",") !== "name" || !boundedString(value.name, 255)) throw new AuthError("invalid_request", 400);
1689
+ return { name: value.name };
1690
+ }
1691
+ function normalizeOrganizationTeamDisplay(value) {
1692
+ try {
1693
+ return normalizeOrganizationTeamDisplayInput(value);
1694
+ } catch {
1695
+ throw authorityUnavailable();
1696
+ }
1697
+ }
1698
+ function normalizeOrganizationTeamCreationInput(name, idempotencyKey) {
1699
+ if (!boundedString(name, 255) || !boundedString(idempotencyKey, 255)) throw new AuthError("invalid_request", 400);
1700
+ return {
1701
+ name,
1702
+ idempotencyKey
1703
+ };
1704
+ }
1705
+ function normalizeCreatedOrganizationTeam(value) {
1706
+ exact$2(value, ["id", "name"]);
1707
+ if (!isId(value.id) || !boundedString(value.name, 255)) throw authorityUnavailable();
1708
+ return {
1709
+ id: value.id,
1710
+ name: value.name
1711
+ };
1712
+ }
1713
+ function normalizeOrganizationMemberInvitationCreationInput(value) {
1714
+ if (!isObject(value)) throw new AuthError("invalid_request", 400);
1715
+ const keys = Object.keys(value).sort().join(",");
1716
+ if (keys !== "email,idempotencyKey" && keys !== "email,idempotencyKey,teamIds") throw new AuthError("invalid_request", 400);
1717
+ let normalizedEmail;
1718
+ try {
1719
+ normalizedEmail = normalizeEmail(value.email);
1720
+ } catch {
1721
+ throw new AuthError("invalid_request", 400);
1722
+ }
1723
+ 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);
1724
+ const teamIds = value.teamIds?.map((teamId) => normalizeIdInput(teamId));
1725
+ if (teamIds && new Set(teamIds).size !== teamIds.length) throw new AuthError("invalid_request", 400);
1726
+ return {
1727
+ email: normalizedEmail,
1728
+ ...teamIds === void 0 ? {} : { teamIds },
1729
+ idempotencyKey: value.idempotencyKey
1730
+ };
1731
+ }
1732
+ function normalizeCreatedOrganizationMemberInvitation(value) {
1733
+ exact$2(value, ["expiresAt", "id"]);
1734
+ if (!isId(value.id)) throw authorityUnavailable();
1735
+ return {
1736
+ id: value.id,
1737
+ expiresAt: responseDate(value.expiresAt)
1738
+ };
1739
+ }
1740
+ function normalizeResentOrganizationInvitation(value, invitationId) {
1741
+ const invitation = normalizeCreatedOrganizationMemberInvitation(value);
1742
+ if (invitation.id !== invitationId) throw authorityUnavailable();
1743
+ return invitation;
1744
+ }
1745
+ function normalizeOrganizationInvitationAdministrationInput(idempotencyKey) {
1746
+ if (!boundedString(idempotencyKey, 255)) throw new AuthError("invalid_request", 400);
1747
+ return { idempotencyKey };
1748
+ }
1749
+ function normalizeCanceledOrganizationInvitation(value) {
1750
+ exact$2(value, ["status"]);
1751
+ if (value.status !== "canceled") throw authorityUnavailable();
1752
+ return { status: "canceled" };
1753
+ }
1754
+ function normalizeOrganizations(value) {
1755
+ exact$2(value, ["nextCursor", "organizations"]);
1756
+ if (!Array.isArray(value.organizations) || value.organizations.length > 100) throw authorityUnavailable();
1757
+ return {
1758
+ organizations: unique(value.organizations.map(normalizeOrganization), (item) => item.id),
1759
+ nextCursor: nullableCursor(value.nextCursor)
1760
+ };
1761
+ }
1762
+ function normalizeOrganizationMembers(value) {
1763
+ exact$2(value, ["members", "nextCursor"]);
1764
+ if (!Array.isArray(value.members) || value.members.length > 100) throw authorityUnavailable();
1765
+ return {
1766
+ members: unique(value.members.map((member) => {
1767
+ exact$2(member, [
1768
+ "email",
1769
+ "id",
1770
+ "image",
1771
+ "joinedAt",
1772
+ "name",
1773
+ "owner",
1774
+ "role",
1775
+ "teamIds",
1776
+ "userId"
1777
+ ]);
1778
+ 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();
1779
+ const teamIds = unique(member.teamIds.map((teamId) => normalizeResponseId(teamId)), (item) => item);
1780
+ return {
1781
+ id: member.id,
1782
+ userId: member.userId,
1783
+ name: member.name,
1784
+ email: member.email,
1785
+ image: nullableHttpsUrl(member.image),
1786
+ role: member.role,
1787
+ owner: member.owner,
1788
+ joinedAt: responseDate(member.joinedAt),
1789
+ teamIds
1138
1790
  };
1139
- exchangeStarted = true;
1140
- return await Promise.race([exchange().finally(() => {
1141
- inFlight = false;
1142
- }), deadline]);
1143
- } catch (error) {
1144
- if (authorityError && error === authorityError) throw authorityError;
1145
- throw authorityUnavailable();
1146
- } finally {
1147
- clearTimeout(timer);
1148
- controller.abort();
1149
- reader?.cancel().catch(() => {});
1150
- if (!exchangeStarted) inFlight = false;
1151
- }
1152
- } };
1791
+ }), (item) => item.id),
1792
+ nextCursor: nullableCursor(value.nextCursor)
1793
+ };
1153
1794
  }
1154
- //#endregion
1155
- //#region ../../node_modules/.pnpm/destr@2.0.5/node_modules/destr/dist/index.mjs
1156
- const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
1157
- const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
1158
- const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
1159
- function jsonParseTransform(key, value) {
1160
- if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
1161
- warnKeyDropped(key);
1162
- return;
1795
+ function normalizeOrganizationTeams(value) {
1796
+ exact$2(value, ["nextCursor", "teams"]);
1797
+ if (!Array.isArray(value.teams) || value.teams.length > 100) throw authorityUnavailable();
1798
+ return {
1799
+ teams: unique(value.teams.map((team) => {
1800
+ exact$2(team, [
1801
+ "category",
1802
+ "createdAt",
1803
+ "id",
1804
+ "name"
1805
+ ]);
1806
+ if (!isId(team.id) || !boundedString(team.name, 255) || team.category !== "manual" && team.category !== "managed") throw authorityUnavailable();
1807
+ return {
1808
+ id: team.id,
1809
+ name: team.name,
1810
+ category: team.category,
1811
+ createdAt: responseDate(team.createdAt)
1812
+ };
1813
+ }), (item) => item.id),
1814
+ nextCursor: nullableCursor(value.nextCursor)
1815
+ };
1816
+ }
1817
+ function normalizeOrganizationTeamMembers(value) {
1818
+ exact$2(value, ["memberIds", "nextCursor"]);
1819
+ if (!Array.isArray(value.memberIds) || value.memberIds.length > 100) throw authorityUnavailable();
1820
+ return {
1821
+ memberIds: unique(value.memberIds.map((item) => normalizeResponseId(item)), (item) => item),
1822
+ nextCursor: nullableCursor(value.nextCursor)
1823
+ };
1824
+ }
1825
+ function normalizeOrganizationInvitation(value) {
1826
+ exact$2(value, [
1827
+ "createdAt",
1828
+ "email",
1829
+ "expiresAt",
1830
+ "id",
1831
+ "inviter",
1832
+ "role",
1833
+ "status",
1834
+ "teamIds"
1835
+ ]);
1836
+ if (!isId(value.id) || typeof value.email !== "string" || value.email.length > 320 || !email.test(value.email) || !role(value.role) || value.status !== "pending" || !Array.isArray(value.teamIds) || value.teamIds.length > 100 || !isObject(value.inviter)) throw authorityUnavailable();
1837
+ exact$2(value.inviter, ["membershipId", "name"]);
1838
+ if (!isId(value.inviter.membershipId) || !boundedString(value.inviter.name, 255)) throw authorityUnavailable();
1839
+ return {
1840
+ id: value.id,
1841
+ email: value.email,
1842
+ role: value.role,
1843
+ teamIds: unique(value.teamIds.map(normalizeResponseId), (item) => item),
1844
+ inviter: {
1845
+ membershipId: value.inviter.membershipId,
1846
+ name: value.inviter.name
1847
+ },
1848
+ createdAt: responseDate(value.createdAt),
1849
+ expiresAt: responseDate(value.expiresAt),
1850
+ status: "pending"
1851
+ };
1852
+ }
1853
+ function normalizeOrganizationInvitations(value) {
1854
+ exact$2(value, ["invitations", "nextCursor"]);
1855
+ if (!Array.isArray(value.invitations) || value.invitations.length > 100) throw authorityUnavailable();
1856
+ return {
1857
+ invitations: unique(value.invitations.map(normalizeOrganizationInvitation), (item) => item.id),
1858
+ nextCursor: nullableCursor(value.nextCursor)
1859
+ };
1860
+ }
1861
+ function normalizeReceivedInvitation(value) {
1862
+ exact$2(value, [
1863
+ "expiresAt",
1864
+ "id",
1865
+ "inviterName",
1866
+ "organization",
1867
+ "role",
1868
+ "teams"
1869
+ ]);
1870
+ if (!isId(value.id) || !boundedString(value.inviterName, 255) || !role(value.role) || !Array.isArray(value.teams) || value.teams.length > 100 || !isObject(value.organization)) throw authorityUnavailable();
1871
+ exact$2(value.organization, [
1872
+ "id",
1873
+ "logo",
1874
+ "name",
1875
+ "slug"
1876
+ ]);
1877
+ if (!isId(value.organization.id) || !boundedString(value.organization.name, 255) || !boundedString(value.organization.slug, 255)) throw authorityUnavailable();
1878
+ return {
1879
+ id: value.id,
1880
+ organization: {
1881
+ id: value.organization.id,
1882
+ name: value.organization.name,
1883
+ slug: value.organization.slug,
1884
+ logo: nullableHttpsUrl(value.organization.logo)
1885
+ },
1886
+ role: value.role,
1887
+ teams: unique(value.teams.map((team) => {
1888
+ exact$2(team, ["id", "name"]);
1889
+ if (!isId(team.id) || !boundedString(team.name, 255)) throw authorityUnavailable();
1890
+ return {
1891
+ id: team.id,
1892
+ name: team.name
1893
+ };
1894
+ }), (item) => item.id),
1895
+ inviterName: value.inviterName,
1896
+ expiresAt: responseDate(value.expiresAt)
1897
+ };
1898
+ }
1899
+ function normalizeReceivedInvitations(value) {
1900
+ exact$2(value, ["invitations", "nextCursor"]);
1901
+ if (!Array.isArray(value.invitations) || value.invitations.length > 100) throw authorityUnavailable();
1902
+ return {
1903
+ invitations: unique(value.invitations.map(normalizeReceivedInvitation), (item) => item.id),
1904
+ nextCursor: nullableCursor(value.nextCursor)
1905
+ };
1906
+ }
1907
+ function normalizeInvitationInput(value) {
1908
+ if (!isObject(value) || Object.keys(value).length !== 1 || !isId(value.invitationId)) throw new AuthError("invalid_invitation", 422);
1909
+ return { invitationId: value.invitationId };
1910
+ }
1911
+ function normalizeInvitationAcceptance(value, invitationId) {
1912
+ if (!isObject(value) || !isObject(value.invitation) || !isObject(value.member) || value.invitation.id !== invitationId || value.invitation.status !== "accepted" || !isId(value.invitation.organizationId) || value.member.organizationId !== value.invitation.organizationId) throw authorityUnavailable();
1913
+ return { organizationId: value.invitation.organizationId };
1914
+ }
1915
+ function normalizeWorkspaceSelection(value) {
1916
+ if (!isObject(value)) throw new AuthError("invalid_workspace_selection", 422);
1917
+ const keys = Object.keys(value);
1918
+ if (value.type === "personal" && keys.length === 1 && keys[0] === "type") return { type: "personal" };
1919
+ if (value.type === "organization" && keys.length === 2 && keys.includes("type") && keys.includes("organizationId") && typeof value.organizationId === "string" && id.test(value.organizationId)) return {
1920
+ type: "organization",
1921
+ organizationId: value.organizationId
1922
+ };
1923
+ throw new AuthError("invalid_workspace_selection", 422);
1924
+ }
1925
+ function fromAuthorityError(value, fallbackStatus, retryAfter) {
1926
+ const mapped = mapError(isObject(value) && typeof value.code === "string" ? value.code : void 0, fallbackStatus);
1927
+ return new AuthError(mapped.code, mapped.status, parseRetryAfter(retryAfter));
1928
+ }
1929
+ function fromAccountAuthorityError(value, status, retryAfter) {
1930
+ const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
1931
+ if (status === 403 && (code === "INVALID_ORIGIN" || code === "MISSING_OR_NULL_ORIGIN")) return new AuthError("request_origin_denied", 403);
1932
+ if (code === "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL") return new AuthError("account_conflict", 409);
1933
+ if (code === "INVALID_TOKEN") return new AuthError("password_reset_invalid", 422);
1934
+ if (code === "INVALID_PASSWORD" || code === "INVALID_EMAIL_OR_PASSWORD") return new AuthError("invalid_credentials", 401);
1935
+ if (code === "INVALID_EMAIL" || code === "PASSWORD_TOO_SHORT" || code === "PASSWORD_TOO_LONG" || code === "BODY_MUST_BE_AN_OBJECT" || code === "EMAIL_CAN_NOT_BE_UPDATED") return new AuthError("invalid_auth_input", 422);
1936
+ if (status === 401) return new AuthError("authentication_required", 401);
1937
+ if (status === 403) return new AuthError("access_denied", 403);
1938
+ if (status === 409) return new AuthError("state_conflict", 409);
1939
+ if (status === 429) return new AuthError("auth_request_rate_limited", 429, parseRetryAfter(retryAfter));
1940
+ if (status === 400 || status === 422) return new AuthError("invalid_auth_input", 422);
1941
+ return authorityUnavailable();
1942
+ }
1943
+ function fromSocialIdTokenAuthorityError(value, status, retryAfter) {
1944
+ const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
1945
+ if (code === "INVALID_TOKEN" || code === "FAILED_TO_GET_USER_INFO" || code === "USER_EMAIL_NOT_FOUND") return new AuthError("invalid_credentials", 401);
1946
+ if (code === "OAUTH_LINK_ERROR") return new AuthError("account_conflict", 409);
1947
+ return fromAccountAuthorityError(value, status, retryAfter);
1948
+ }
1949
+ function authorityUnavailable() {
1950
+ return new AuthError("identity_authority_unavailable", 503);
1951
+ }
1952
+ function fromOrganizationListError(error) {
1953
+ if (error instanceof AuthError && error.status === 401) return new AuthError("authentication_required", 401);
1954
+ if (error instanceof AuthError) return error;
1955
+ return authorityUnavailable();
1956
+ }
1957
+ function fromOrganizationReadAuthorityError(value, status) {
1958
+ if (status === 400) return new AuthError("invalid_request", 400);
1959
+ if (status === 401) return new AuthError("authentication_required", 401);
1960
+ if (status === 403) return new AuthError("access_denied", 403);
1961
+ return authorityUnavailable();
1962
+ }
1963
+ function fromOrganizationMutationAuthorityError(value, status, retryAfter) {
1964
+ if (status === 400 || status === 413 || status === 415) return new AuthError("invalid_request", 400);
1965
+ if (status === 409) return new AuthError("state_conflict", 409);
1966
+ if (status === 429) return new AuthError("auth_request_rate_limited", 429, parseRetryAfter(retryAfter));
1967
+ const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
1968
+ if (status === 403 && code === "REQUEST_ORIGIN_DENIED") return new AuthError("request_origin_denied", 403);
1969
+ return fromOrganizationReadAuthorityError(value, status);
1970
+ }
1971
+ function fromOrganizationInvitationAdministrationError(value, status, retryAfter) {
1972
+ if (status === 422 && isObject(value) && value.code === "RECOVERY_REQUIRED") return new AuthError("invitation_recovery_required", 422);
1973
+ return fromOrganizationMutationAuthorityError(value, status, retryAfter);
1974
+ }
1975
+ function normalizeOrganizationMemberAuthority(value, organizationId, memberId) {
1976
+ exact$2(value, [
1977
+ "organizationId",
1978
+ "actor",
1979
+ "target"
1980
+ ]);
1981
+ if (!isId(value.organizationId) || value.organizationId !== organizationId) throw authorityUnavailable();
1982
+ const actor = normalizeOrganizationAuthorityMemberOutcome(value.actor);
1983
+ const target = normalizeOrganizationAuthorityMemberOutcome(value.target);
1984
+ if (target.memberId !== memberId || actor.manualRole !== "owner" && actor.manualRole !== "admin") throw authorityUnavailable();
1985
+ for (const member of [actor, target]) if (member.manualRole === "member" ? member.role === "owner" : member.role !== member.manualRole) throw authorityUnavailable();
1986
+ if (actor.memberId === target.memberId && (actor.manualRole !== target.manualRole || actor.role !== target.role || actor.authorityRevision !== target.authorityRevision)) throw authorityUnavailable();
1987
+ return {
1988
+ organizationId: value.organizationId,
1989
+ actor,
1990
+ target
1991
+ };
1992
+ }
1993
+ function normalizeOrganizationAuthorityMemberOutcome(value, includesStatus = false) {
1994
+ exact$2(value, [
1995
+ "memberId",
1996
+ "manualRole",
1997
+ "role",
1998
+ "authorityRevision",
1999
+ ...includesStatus ? ["status"] : []
2000
+ ]);
2001
+ if (!isId(value.memberId) || value.manualRole !== "owner" && value.manualRole !== "admin" && value.manualRole !== "member" || value.role !== "owner" && value.role !== "admin" && value.role !== "member") throw authorityUnavailable();
2002
+ return {
2003
+ memberId: value.memberId,
2004
+ manualRole: value.manualRole,
2005
+ role: value.role,
2006
+ authorityRevision: normalizeAuthorityResultRevision(value.authorityRevision)
2007
+ };
2008
+ }
2009
+ function normalizeAuthorityResultRevision(value) {
2010
+ if (!Number.isSafeInteger(value) || value < 0 || value >= Number.MAX_SAFE_INTEGER) throw authorityUnavailable();
2011
+ return value;
2012
+ }
2013
+ function fromInvitationAuthorityError(value, status) {
2014
+ const code = isObject(value) && typeof value.code === "string" ? value.code : void 0;
2015
+ if (status === 401 && code === "UNAUTHORIZED") return new AuthError("authentication_required", 401);
2016
+ if (status === 403 && (code === "INVALID_ORIGIN" || code === "MISSING_OR_NULL_ORIGIN")) return new AuthError("request_origin_denied", 403);
2017
+ if (status === 403 && code === "YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION") return new AuthError("invitation_recipient_mismatch", 403);
2018
+ if (status === 403 && code === "EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION") return new AuthError("email_verification_required", 403);
2019
+ if (status === 400 && (code === "INVITATION_NOT_FOUND" || code === "ORGANIZATION_NOT_FOUND" || code === "TEAM_NOT_FOUND")) return new AuthError("invitation_unavailable", 409);
2020
+ return authorityUnavailable();
2021
+ }
2022
+ function fromInvitationError(error) {
2023
+ return error instanceof AuthError ? error : authorityUnavailable();
2024
+ }
2025
+ function mapError(code, status) {
2026
+ if (code === "authentication_required") return {
2027
+ code,
2028
+ status: 401
2029
+ };
2030
+ if (code === "request_origin_denied") return {
2031
+ code,
2032
+ status: 403
2033
+ };
2034
+ if (code === "invalid_workspace_selection") return {
2035
+ code,
2036
+ status: 422
2037
+ };
2038
+ if (code === "organization_context_too_large") return {
2039
+ code,
2040
+ status: 422
2041
+ };
2042
+ if (code === "credential_rate_limited") return {
2043
+ code,
2044
+ status: 429
2045
+ };
2046
+ if (code === "identity_authority_unavailable") return {
2047
+ code,
2048
+ status: 503
2049
+ };
2050
+ if (status === 401 || status === 400) return {
2051
+ code: "invalid_credentials",
2052
+ status: 401
2053
+ };
2054
+ if (status === 403) return {
2055
+ code: "access_denied",
2056
+ status: 403
2057
+ };
2058
+ if (status === 409) return {
2059
+ code: "state_conflict",
2060
+ status: 409
2061
+ };
2062
+ if (status === 422) return {
2063
+ code: "invalid_workspace_selection",
2064
+ status: 422
2065
+ };
2066
+ if (status === 429) return {
2067
+ code: "credential_rate_limited",
2068
+ status: 429
2069
+ };
2070
+ return {
2071
+ code: "identity_authority_unavailable",
2072
+ status: 503
2073
+ };
2074
+ }
2075
+ function parseRetryAfter(value) {
2076
+ if (!value || !/^\d+$/.test(value)) return void 0;
2077
+ const seconds = Number(value);
2078
+ return Number.isSafeInteger(seconds) && seconds >= 1 && seconds <= 3600 ? seconds : void 0;
2079
+ }
2080
+ function toDate(value) {
2081
+ const result = value instanceof Date ? value : typeof value === "string" ? new Date(value) : void 0;
2082
+ return result && Number.isFinite(result.getTime()) ? result : void 0;
2083
+ }
2084
+ function isId(value) {
2085
+ return typeof value === "string" && id.test(value);
2086
+ }
2087
+ function exact$2(value, keys) {
2088
+ if (!isObject(value) || Object.keys(value).sort().join(",") !== [...keys].sort().join(",")) throw authorityUnavailable();
2089
+ }
2090
+ function boundedString(value, maximum) {
2091
+ return typeof value === "string" && value.length > 0 && new TextEncoder().encode(value).byteLength <= maximum;
2092
+ }
2093
+ function role(value) {
2094
+ return value === "owner" || value === "admin" || value === "member";
2095
+ }
2096
+ function nullableHttpsUrl(value) {
2097
+ if (value === null) return null;
2098
+ if (typeof value !== "string" || value.length > 2048) throw authorityUnavailable();
2099
+ let url;
2100
+ try {
2101
+ url = new URL(value);
2102
+ } catch {
2103
+ throw authorityUnavailable();
1163
2104
  }
2105
+ if (url.protocol !== "https:" || url.username || url.password || url.toString() !== value) throw authorityUnavailable();
1164
2106
  return value;
1165
2107
  }
1166
- function warnKeyDropped(key) {
1167
- console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
2108
+ function responseDate(value) {
2109
+ if (typeof value !== "string") throw authorityUnavailable();
2110
+ const date = new Date(value);
2111
+ if (!Number.isFinite(date.getTime()) || date.toISOString() !== value) throw authorityUnavailable();
2112
+ return date;
1168
2113
  }
1169
- function destr(value, options = {}) {
1170
- if (typeof value !== "string") return value;
1171
- if (value[0] === "\"" && value[value.length - 1] === "\"" && value.indexOf("\\") === -1) return value.slice(1, -1);
1172
- const _value = value.trim();
1173
- if (_value.length <= 9) switch (_value.toLowerCase()) {
1174
- case "true": return true;
1175
- case "false": return false;
1176
- case "undefined": return;
1177
- case "null": return null;
1178
- case "nan": return NaN;
1179
- case "infinity": return Number.POSITIVE_INFINITY;
1180
- case "-infinity": return Number.NEGATIVE_INFINITY;
1181
- }
1182
- if (!JsonSigRx.test(value)) {
1183
- if (options.strict) throw new SyntaxError("[destr] Invalid JSON");
1184
- return value;
1185
- }
1186
- try {
1187
- if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
1188
- if (options.strict) throw new Error("[destr] Possible prototype pollution");
1189
- return JSON.parse(value, jsonParseTransform);
1190
- }
1191
- return JSON.parse(value);
1192
- } catch (error) {
1193
- if (options.strict) throw error;
1194
- return value;
1195
- }
2114
+ function nullableCursor(value) {
2115
+ if (value === null) return null;
2116
+ if (typeof value !== "string" || value.length < 1 || value.length > 820 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value)) throw authorityUnavailable();
2117
+ return value;
1196
2118
  }
1197
- //#endregion
1198
- //#region ../../node_modules/.pnpm/ofetch@1.5.1/node_modules/ofetch/dist/shared/ofetch.CWycOUEr.mjs
1199
- var FetchError = class extends Error {
1200
- constructor(message, opts) {
1201
- super(message, opts);
1202
- this.name = "FetchError";
1203
- if (opts?.cause && !this.cause) this.cause = opts.cause;
1204
- }
1205
- };
1206
- function createFetchError(ctx) {
1207
- const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
1208
- const method = ctx.request?.method || ctx.options?.method || "GET";
1209
- const url = ctx.request?.url || String(ctx.request) || "/";
1210
- const fetchError = new FetchError(`${`[${method}] ${JSON.stringify(url)}`}: ${ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : "<no response>"}${errorMessage ? ` ${errorMessage}` : ""}`, ctx.error ? { cause: ctx.error } : void 0);
1211
- for (const key of [
1212
- "request",
1213
- "options",
1214
- "response"
1215
- ]) Object.defineProperty(fetchError, key, { get() {
1216
- return ctx[key];
1217
- } });
1218
- for (const [key, refKey] of [
1219
- ["data", "_data"],
1220
- ["status", "status"],
1221
- ["statusCode", "status"],
1222
- ["statusText", "statusText"],
1223
- ["statusMessage", "statusText"]
1224
- ]) Object.defineProperty(fetchError, key, { get() {
1225
- return ctx.response && ctx.response[refKey];
1226
- } });
1227
- return fetchError;
2119
+ function normalizeResponseId(value) {
2120
+ if (!isId(value)) throw authorityUnavailable();
2121
+ return value;
1228
2122
  }
1229
- const payloadMethods = new Set(Object.freeze([
1230
- "PATCH",
1231
- "POST",
1232
- "PUT",
1233
- "DELETE"
1234
- ]));
1235
- function isPayloadMethod(method = "GET") {
1236
- return payloadMethods.has(method.toUpperCase());
2123
+ function unique(items, key) {
2124
+ if (new Set(items.map(key)).size !== items.length) throw authorityUnavailable();
2125
+ return items;
1237
2126
  }
1238
- function isJSONSerializable(value) {
1239
- if (value === void 0) return false;
1240
- const t = typeof value;
1241
- if (t === "string" || t === "number" || t === "boolean" || t === null) return true;
1242
- if (t !== "object") return false;
1243
- if (Array.isArray(value)) return true;
1244
- if (value.buffer) return false;
1245
- if (value instanceof FormData || value instanceof URLSearchParams) return false;
1246
- return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
2127
+ function isObject(value) {
2128
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1247
2129
  }
1248
- const textTypes = new Set([
1249
- "image/svg",
1250
- "application/xml",
1251
- "application/xhtml",
1252
- "application/html"
1253
- ]);
1254
- const JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
1255
- function detectResponseType(_contentType = "") {
1256
- if (!_contentType) return "json";
1257
- const contentType = _contentType.split(";").shift() || "";
1258
- if (JSON_RE.test(contentType)) return "json";
1259
- if (contentType === "text/event-stream") return "stream";
1260
- if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
1261
- return "blob";
2130
+ //#endregion
2131
+ //#region src/http.ts
2132
+ const MAX_RESPONSE_BYTES = 64 * 1024;
2133
+ async function requestJson(url, options) {
2134
+ return (await requestJsonResponse(url, options)).value;
1262
2135
  }
1263
- function resolveFetchOptions(request, input, defaults, Headers) {
1264
- const headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers);
1265
- let query;
1266
- if (defaults?.query || defaults?.params || input?.params || input?.query) query = {
1267
- ...defaults?.params,
1268
- ...defaults?.query,
1269
- ...input?.params,
1270
- ...input?.query
1271
- };
2136
+ async function requestJsonResponse(url, options) {
2137
+ let response;
2138
+ try {
2139
+ response = await createFetch({ fetch: options.fetch }).raw(url, {
2140
+ method: options.method,
2141
+ headers: options.headers,
2142
+ body: options.body,
2143
+ credentials: options.credentials ?? "include",
2144
+ retry: 0,
2145
+ timeout: options.timeoutMs,
2146
+ redirect: "manual",
2147
+ signal: options.signal,
2148
+ responseType: "stream",
2149
+ ignoreResponseError: true
2150
+ });
2151
+ } catch {
2152
+ throw authorityUnavailable();
2153
+ }
2154
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
2155
+ if (response.status >= 300 || response.status < 200 || contentType !== "application/json") {
2156
+ const body = contentType === "application/json" ? await readJson(response, options.maxResponseBytes) : void 0;
2157
+ await response.body?.cancel();
2158
+ throw (options.mapError ?? fromAuthorityError)(body, response.status, response.headers.get("retry-after"));
2159
+ }
1272
2160
  return {
1273
- ...defaults,
1274
- ...input,
1275
- query,
1276
- params: query,
1277
- headers
2161
+ value: await readJson(response, options.maxResponseBytes),
2162
+ headers: response.headers
1278
2163
  };
1279
2164
  }
1280
- function mergeHeaders(input, defaults, Headers) {
1281
- if (!defaults) return new Headers(input);
1282
- const headers = new Headers(defaults);
1283
- if (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers(input)) headers.set(key, value);
1284
- return headers;
1285
- }
1286
- async function callHooks(context, hooks) {
1287
- if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
1288
- else await hooks(context);
2165
+ async function readJson(response, maximum = MAX_RESPONSE_BYTES) {
2166
+ const length = response.headers.get("content-length");
2167
+ if (length && (!/^\d+$/.test(length) || Number(length) > maximum)) {
2168
+ await response.body?.cancel();
2169
+ throw authorityUnavailable();
2170
+ }
2171
+ if (!response.body) throw authorityUnavailable();
2172
+ const reader = response.body.getReader();
2173
+ const chunks = [];
2174
+ let size = 0;
2175
+ try {
2176
+ while (true) {
2177
+ const { done, value } = await reader.read();
2178
+ if (done) break;
2179
+ size += value.byteLength;
2180
+ if (size > maximum) throw authorityUnavailable();
2181
+ chunks.push(value);
2182
+ }
2183
+ } catch (error) {
2184
+ await reader.cancel();
2185
+ throw error;
2186
+ } finally {
2187
+ reader.releaseLock();
2188
+ }
2189
+ const bytes = new Uint8Array(size);
2190
+ let offset = 0;
2191
+ for (const chunk of chunks) {
2192
+ bytes.set(chunk, offset);
2193
+ offset += chunk.byteLength;
2194
+ }
2195
+ try {
2196
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
2197
+ } catch {
2198
+ throw authorityUnavailable();
2199
+ }
1289
2200
  }
1290
- const retryStatusCodes = new Set([
1291
- 408,
1292
- 409,
1293
- 425,
1294
- 429,
1295
- 500,
1296
- 502,
1297
- 503,
1298
- 504
1299
- ]);
1300
- const nullBodyResponses = new Set([
1301
- 101,
1302
- 204,
1303
- 205,
1304
- 304
1305
- ]);
1306
- function createFetch(globalOptions = {}) {
1307
- const { fetch = globalThis.fetch, Headers = globalThis.Headers, AbortController = globalThis.AbortController } = globalOptions;
1308
- async function onError(context) {
1309
- const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
1310
- if (context.options.retry !== false && !isAbort) {
1311
- let retries;
1312
- if (typeof context.options.retry === "number") retries = context.options.retry;
1313
- else retries = isPayloadMethod(context.options.method) ? 0 : 1;
1314
- const responseCode = context.response && context.response.status || 500;
1315
- if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
1316
- const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
1317
- if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));
1318
- return $fetchRaw(context.request, {
1319
- ...context.options,
1320
- retry: retries - 1
1321
- });
2201
+ //#endregion
2202
+ //#region src/user-api/verifier.ts
2203
+ const ID = /^[A-Za-z0-9_-]{1,128}$(?![\s\S])/;
2204
+ const KID = /^[A-Za-z0-9_-]{43}$(?![\s\S])/;
2205
+ const PROFILE = "finueva-user-api+jwt";
2206
+ const CACHE_MS = 3e5;
2207
+ const REFRESH_COOLDOWN_MS = 3e4;
2208
+ const TIMEOUT_MS = 2e3;
2209
+ const invalid = () => new AuthError("authentication_required", 401);
2210
+ const unavailable = () => new AuthError("identity_authority_unavailable", 503);
2211
+ function record(value) {
2212
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2213
+ }
2214
+ function exactKeys(value, keys) {
2215
+ return Object.keys(value).sort().join(",") === keys.sort().join(",");
2216
+ }
2217
+ function createUserApiVerifier(options) {
2218
+ const { issuer, audience, applicationId, environment } = options;
2219
+ if (!issuer || !audience || issuer.length > 2048 || audience.length > 2048 || !ID.test(applicationId) || ![
2220
+ "local",
2221
+ "development",
2222
+ "staging",
2223
+ "production"
2224
+ ].includes(environment)) throw new TypeError("User API verifier configuration is invalid");
2225
+ const url = new URL(options.jwksUrl);
2226
+ const local = url.hostname === "localhost" || url.hostname.endsWith(".localhost");
2227
+ if (url.protocol !== "https:" && !(environment === "local" && local && url.protocol === "http:") || url.username || url.password || url.search || url.hash) throw new TypeError("User API JWKS URL is invalid");
2228
+ const jwksUrl = url.href;
2229
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2230
+ const now = options.now ?? Date.now;
2231
+ let cached;
2232
+ let pending;
2233
+ let nextRefreshAt = -Infinity;
2234
+ async function loadKeys() {
2235
+ const controller = new AbortController();
2236
+ let timer;
2237
+ const deadline = new Promise((_, reject) => {
2238
+ timer = setTimeout(() => {
2239
+ controller.abort();
2240
+ reject(unavailable());
2241
+ }, TIMEOUT_MS);
2242
+ });
2243
+ const started = now();
2244
+ try {
2245
+ const value = await Promise.race([requestJson(jwksUrl, {
2246
+ fetch: fetchImpl,
2247
+ timeoutMs: TIMEOUT_MS,
2248
+ method: "GET",
2249
+ credentials: "omit",
2250
+ signal: controller.signal,
2251
+ maxResponseBytes: 64 * 1024
2252
+ }), deadline]);
2253
+ if (!record(value) || !exactKeys(value, ["keys"]) || !Array.isArray(value.keys) || value.keys.length < 1 || value.keys.length > 20) throw unavailable();
2254
+ const keys = new Map();
2255
+ for (const entry of value.keys) {
2256
+ if (!record(entry) || !exactKeys(entry, [
2257
+ "kty",
2258
+ "crv",
2259
+ "x",
2260
+ "kid",
2261
+ "alg",
2262
+ "use"
2263
+ ]) || entry.kty !== "OKP" || entry.crv !== "Ed25519" || entry.alg !== "EdDSA" || entry.use !== "sig" || typeof entry.x !== "string" || !KID.test(entry.x) || typeof entry.kid !== "string" || !KID.test(entry.kid) || keys.has(entry.kid)) throw unavailable();
2264
+ const jwk = {
2265
+ kty: "OKP",
2266
+ crv: "Ed25519",
2267
+ x: entry.x
2268
+ };
2269
+ if (await calculateJwkThumbprint(jwk) !== entry.kid) throw unavailable();
2270
+ keys.set(entry.kid, await importJWK(jwk, "EdDSA"));
1322
2271
  }
2272
+ if (controller.signal.aborted || now() < started || now() >= started + CACHE_MS) throw unavailable();
2273
+ cached = {
2274
+ keys,
2275
+ loadedAt: started,
2276
+ expiresAt: started + CACHE_MS
2277
+ };
2278
+ } catch {
2279
+ throw unavailable();
2280
+ } finally {
2281
+ clearTimeout(timer);
2282
+ }
2283
+ }
2284
+ async function keyFor(kid) {
2285
+ const time = now();
2286
+ const known = cached && time >= cached.loadedAt && time < cached.expiresAt ? cached?.keys.get(kid) : void 0;
2287
+ if (known) return known;
2288
+ if (pending) await pending;
2289
+ else if (time >= nextRefreshAt) {
2290
+ nextRefreshAt = time + REFRESH_COOLDOWN_MS;
2291
+ const request = loadKeys().finally(() => {
2292
+ if (pending === request) pending = void 0;
2293
+ });
2294
+ pending = request;
2295
+ await request;
1323
2296
  }
1324
- const error = createFetchError(context);
1325
- if (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);
1326
- throw error;
2297
+ const current = now();
2298
+ if (!cached || current < cached.loadedAt || current >= cached.expiresAt) throw unavailable();
2299
+ const key = cached.keys.get(kid);
2300
+ if (!key) throw invalid();
2301
+ return key;
1327
2302
  }
1328
- const $fetchRaw = async function $fetchRaw2(_request, _options = {}) {
1329
- const context = {
1330
- request: _request,
1331
- options: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers),
1332
- response: void 0,
1333
- error: void 0
1334
- };
1335
- if (context.options.method) context.options.method = context.options.method.toUpperCase();
1336
- if (context.options.onRequest) {
1337
- await callHooks(context, context.options.onRequest);
1338
- if (!(context.options.headers instanceof Headers)) context.options.headers = new Headers(context.options.headers || {});
2303
+ return { async verify(token) {
2304
+ 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();
2305
+ let kid;
2306
+ try {
2307
+ const header = decodeProtectedHeader(token);
2308
+ if (!exactKeys(header, [
2309
+ "alg",
2310
+ "typ",
2311
+ "kid"
2312
+ ]) || header.alg !== "EdDSA" || header.typ !== PROFILE || typeof header.kid !== "string" || !KID.test(header.kid)) throw invalid();
2313
+ kid = header.kid;
2314
+ } catch {
2315
+ throw invalid();
1339
2316
  }
1340
- if (typeof context.request === "string") {
1341
- if (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);
1342
- if (context.options.query) {
1343
- context.request = withQuery(context.request, context.options.query);
1344
- delete context.options.query;
1345
- }
1346
- if ("query" in context.options) delete context.options.query;
1347
- if ("params" in context.options) delete context.options.params;
2317
+ let identity;
2318
+ try {
2319
+ const payload = decodeJwt(token);
2320
+ const time = Math.floor(now() / 1e3);
2321
+ if (!exactKeys(payload, [
2322
+ "iss",
2323
+ "aud",
2324
+ "sub",
2325
+ "sid",
2326
+ "iat",
2327
+ "exp",
2328
+ "ver",
2329
+ "principal_type",
2330
+ "scope",
2331
+ "app",
2332
+ "environment",
2333
+ "user"
2334
+ ]) || payload.iss !== issuer || payload.aud !== audience || payload.app !== applicationId || payload.environment !== environment || payload.ver !== 1 || payload.principal_type !== "user" || payload.scope !== "user:api" || typeof payload.sub !== "string" || !ID.test(payload.sub) || typeof payload.sid !== "string" || !ID.test(payload.sid) || !Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.exp) || payload.iat < 0 || payload.iat > time || payload.exp <= time || payload.exp <= payload.iat || payload.exp - payload.iat > 840) throw invalid();
2335
+ const user = payload.user;
2336
+ if (!record(user) || !exactKeys(user, [
2337
+ "name",
2338
+ "email",
2339
+ "emailVerified",
2340
+ "image"
2341
+ ]) || typeof user.name !== "string" || user.name.length > 200 || typeof user.email !== "string" || user.email.length < 1 || user.email.length > 320 || typeof user.emailVerified !== "boolean" || !(user.image === null || typeof user.image === "string" && user.image.length <= 2048)) throw invalid();
2342
+ identity = {
2343
+ userId: payload.sub,
2344
+ sessionId: payload.sid,
2345
+ applicationId,
2346
+ issuedAt: new Date(payload.iat * 1e3),
2347
+ expiresAt: new Date(payload.exp * 1e3),
2348
+ user: {
2349
+ id: payload.sub,
2350
+ name: user.name,
2351
+ email: user.email,
2352
+ emailVerified: user.emailVerified,
2353
+ image: user.image
2354
+ }
2355
+ };
2356
+ } catch {
2357
+ throw invalid();
1348
2358
  }
1349
- if (context.options.body && isPayloadMethod(context.options.method)) {
1350
- if (isJSONSerializable(context.options.body)) {
1351
- const contentType = context.options.headers.get("content-type");
1352
- if (typeof context.options.body !== "string") context.options.body = contentType === "application/x-www-form-urlencoded" ? new URLSearchParams(context.options.body).toString() : JSON.stringify(context.options.body);
1353
- if (!contentType) context.options.headers.set("content-type", "application/json");
1354
- if (!context.options.headers.has("accept")) context.options.headers.set("accept", "application/json");
1355
- } else if ("pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || typeof context.options.body.pipe === "function") {
1356
- if (!("duplex" in context.options)) context.options.duplex = "half";
1357
- }
2359
+ const key = await keyFor(kid);
2360
+ try {
2361
+ await jwtVerify(token, key, {
2362
+ algorithms: ["EdDSA"],
2363
+ issuer,
2364
+ audience,
2365
+ typ: PROFILE,
2366
+ currentDate: new Date(now()),
2367
+ clockTolerance: 0,
2368
+ requiredClaims: [
2369
+ "iss",
2370
+ "aud",
2371
+ "sub",
2372
+ "sid",
2373
+ "iat",
2374
+ "exp"
2375
+ ]
2376
+ });
2377
+ } catch {
2378
+ throw invalid();
1358
2379
  }
1359
- let abortTimeout;
1360
- if (!context.options.signal && context.options.timeout) {
1361
- const controller = new AbortController();
1362
- abortTimeout = setTimeout(() => {
1363
- const error = new Error("[TimeoutError]: The operation was aborted due to timeout");
1364
- error.name = "TimeoutError";
1365
- error.code = 23;
1366
- controller.abort(error);
1367
- }, context.options.timeout);
1368
- context.options.signal = controller.signal;
2380
+ return identity;
2381
+ } };
2382
+ }
2383
+ //#endregion
2384
+ //#region src/identity-resolution.ts
2385
+ 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])/;
2386
+ function exact$1(value, keys) {
2387
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
2388
+ }
2389
+ function createIdentityResolverAuth(options) {
2390
+ const url = joinURL(normalizeOrigin(options.authOrigin, "authOrigin"), "api/v1/auth/identities/resolve");
2391
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
2392
+ if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
2393
+ const timeoutMs = normalizeTimeout(options.timeoutMs);
2394
+ let inFlight = false;
2395
+ return { async resolveIdentity(input, clientAssertion) {
2396
+ if (!exact$1(input, ["identifier"]) || typeof input.identifier !== "string" || input.identifier.length > 324) throw new AuthError("invalid_request", 400);
2397
+ const identifier = input.identifier.trim().toLowerCase();
2398
+ if (!(identifier.length <= 320 && emailPattern$1.test(identifier)) && !/^[a-z0-9_.]{3,30}$(?![\s\S])/.test(identifier)) throw new AuthError("invalid_request", 400);
2399
+ 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);
2400
+ if (inFlight) throw new AuthError("state_conflict", 409);
2401
+ inFlight = true;
2402
+ const controller = new AbortController();
2403
+ let reader;
2404
+ let timer;
2405
+ let mappedError;
2406
+ try {
2407
+ const deadline = new Promise((_, reject) => {
2408
+ timer = setTimeout(() => {
2409
+ reject(authorityUnavailable());
2410
+ controller.abort();
2411
+ reader?.cancel().catch(() => {});
2412
+ }, timeoutMs);
2413
+ });
2414
+ const exchange = async () => {
2415
+ const response = await fetchImpl(url, {
2416
+ method: "POST",
2417
+ headers: {
2418
+ authorization: `Bearer ${clientAssertion}`,
2419
+ accept: "application/json",
2420
+ "content-type": "application/json"
2421
+ },
2422
+ body: JSON.stringify({ identifier }),
2423
+ credentials: "omit",
2424
+ cache: "no-store",
2425
+ redirect: "manual",
2426
+ signal: controller.signal
2427
+ });
2428
+ if (controller.signal.aborted) {
2429
+ response.body?.cancel().catch(() => {});
2430
+ throw authorityUnavailable();
2431
+ }
2432
+ if (!response.body) throw authorityUnavailable();
2433
+ reader = response.body.getReader();
2434
+ const length = response.headers.get("content-length");
2435
+ if (response.redirected || response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > 1024)) throw authorityUnavailable();
2436
+ const bytes = new Uint8Array(1024);
2437
+ let size = 0;
2438
+ while (true) {
2439
+ const chunk = await reader.read();
2440
+ if (controller.signal.aborted) throw authorityUnavailable();
2441
+ if (chunk.done) break;
2442
+ if (size + chunk.value.byteLength > bytes.length) throw authorityUnavailable();
2443
+ bytes.set(chunk.value, size);
2444
+ size += chunk.value.byteLength;
2445
+ }
2446
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size)));
2447
+ if (response.status !== 200) {
2448
+ if (!exact$1(value, ["code", "message"])) throw authorityUnavailable();
2449
+ if (response.status === 401 && value.code === "UNAUTHORIZED" && value.message === "The identity resolution assertion is invalid.") mappedError = new AuthError("authentication_required", 401);
2450
+ if (response.status === 429 && value.code === "TOO_MANY_REQUESTS" && value.message === "Identity resolution requests are temporarily limited.") {
2451
+ const retryAfter = response.headers.get("retry-after");
2452
+ if (retryAfter === null || !/^(?:[1-9]|[1-5][0-9]|60)$/.test(retryAfter)) throw authorityUnavailable();
2453
+ mappedError = new AuthError("auth_request_rate_limited", 429, Number(retryAfter));
2454
+ }
2455
+ throw mappedError ?? authorityUnavailable();
2456
+ }
2457
+ if (!exact$1(value, ["identity"])) throw authorityUnavailable();
2458
+ if (value.identity === null) return null;
2459
+ if (!exact$1(value.identity, ["userId"]) || typeof value.identity.userId !== "string" || !/^[A-Za-z0-9_-]{1,128}$(?![\s\S])/.test(value.identity.userId)) throw authorityUnavailable();
2460
+ return { userId: value.identity.userId };
2461
+ };
2462
+ return await Promise.race([exchange().finally(() => {
2463
+ inFlight = false;
2464
+ }), deadline]);
2465
+ } catch (error) {
2466
+ if (mappedError && mappedError === error) throw mappedError;
2467
+ throw authorityUnavailable();
2468
+ } finally {
2469
+ clearTimeout(timer);
2470
+ controller.abort();
2471
+ reader?.cancel().catch(() => {});
2472
+ }
2473
+ } };
2474
+ }
2475
+ //#endregion
2476
+ //#region src/drive-recipients.ts
2477
+ const encoder = new TextEncoder();
2478
+ const emailPattern = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/;
2479
+ function validEmail(value) {
2480
+ return typeof value === "string" && encoder.encode(value).byteLength <= 320 && emailPattern.test(value);
2481
+ }
2482
+ function exact(value, keys) {
2483
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
2484
+ }
2485
+ const failures = {
2486
+ 400: [
2487
+ "BAD_REQUEST",
2488
+ "The recipient request is invalid.",
2489
+ "invalid_request"
2490
+ ],
2491
+ 401: [
2492
+ "UNAUTHORIZED",
2493
+ "The recipient service assertion is invalid.",
2494
+ "authentication_required"
2495
+ ],
2496
+ 404: [
2497
+ "NOT_FOUND",
2498
+ "The recipient is unavailable.",
2499
+ "recipient_unavailable"
2500
+ ],
2501
+ 405: [
2502
+ "METHOD_NOT_ALLOWED",
2503
+ "METHOD_NOT_ALLOWED",
2504
+ "invalid_request"
2505
+ ],
2506
+ 413: [
2507
+ "REQUEST_TOO_LONG",
2508
+ "The recipient request is too large.",
2509
+ "invalid_request"
2510
+ ],
2511
+ 429: [
2512
+ "TOO_MANY_REQUESTS",
2513
+ "Recipient requests are temporarily limited.",
2514
+ "auth_request_rate_limited"
2515
+ ],
2516
+ 503: [
2517
+ "SERVICE_UNAVAILABLE",
2518
+ "Recipient resolution is temporarily unavailable.",
2519
+ "identity_authority_unavailable"
2520
+ ]
2521
+ };
2522
+ function createDriveRecipientAuth(options) {
2523
+ const url = joinURL(normalizeOrigin(options.authOrigin, "authOrigin"), "api/v1/auth/drive-share-recipients/resolve");
2524
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
2525
+ if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
2526
+ const timeoutMs = normalizeTimeout(options.timeoutMs);
2527
+ let inFlight = false;
2528
+ return { async resolveRecipient(input, clientAssertion) {
2529
+ let body;
2530
+ let email;
2531
+ try {
2532
+ if (!exact(input, ["email"]) || typeof input.email !== "string") throw new Error();
2533
+ email = input.email.trim().toLowerCase();
2534
+ if (!validEmail(email)) throw new Error();
2535
+ body = JSON.stringify({ email });
2536
+ } catch {
2537
+ throw new AuthError("invalid_request", 400);
1369
2538
  }
2539
+ if (encoder.encode(body).byteLength > 1024) throw new AuthError("invalid_request", 413);
2540
+ 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);
2541
+ if (inFlight) throw new AuthError("state_conflict", 409);
2542
+ inFlight = true;
2543
+ const controller = new AbortController();
2544
+ let reader;
2545
+ let timer;
2546
+ let authorityError;
1370
2547
  try {
1371
- context.response = await fetch(context.request, context.options);
2548
+ const deadline = new Promise((_, reject) => {
2549
+ timer = setTimeout(() => {
2550
+ reject(authorityUnavailable());
2551
+ controller.abort();
2552
+ reader?.cancel().catch(() => {});
2553
+ }, timeoutMs);
2554
+ });
2555
+ const exchange = async () => {
2556
+ const response = await fetchImpl(url, {
2557
+ method: "POST",
2558
+ headers: {
2559
+ authorization: `Bearer ${clientAssertion}`,
2560
+ accept: "application/json",
2561
+ "content-type": "application/json"
2562
+ },
2563
+ body,
2564
+ credentials: "omit",
2565
+ cache: "no-store",
2566
+ redirect: "manual",
2567
+ signal: controller.signal
2568
+ });
2569
+ if (controller.signal.aborted) {
2570
+ response.body?.cancel().catch(() => {});
2571
+ throw authorityUnavailable();
2572
+ }
2573
+ if (!response.body) throw authorityUnavailable();
2574
+ reader = response.body.getReader();
2575
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
2576
+ const length = response.headers.get("content-length");
2577
+ if (response.redirected || contentType !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > 4096)) throw authorityUnavailable();
2578
+ const bytes = new Uint8Array(4096);
2579
+ let size = 0;
2580
+ while (true) {
2581
+ const chunk = await reader.read();
2582
+ if (controller.signal.aborted) throw authorityUnavailable();
2583
+ if (chunk.done) break;
2584
+ if (size + chunk.value.byteLength > bytes.byteLength) throw authorityUnavailable();
2585
+ bytes.set(chunk.value, size);
2586
+ size += chunk.value.byteLength;
2587
+ }
2588
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size)));
2589
+ if (response.status !== 200) {
2590
+ const status = response.status;
2591
+ const failure = failures[status];
2592
+ if (!failure || !exact(value, ["code", "message"]) || value.code !== failure[0] || value.message !== failure[1]) throw authorityUnavailable();
2593
+ let retryAfterSeconds;
2594
+ if (status === 429) {
2595
+ const retryAfter = response.headers.get("retry-after");
2596
+ if (retryAfter === null || !/^(?:[1-9]|[1-5][0-9]|60)$/.test(retryAfter)) throw authorityUnavailable();
2597
+ retryAfterSeconds = Number(retryAfter);
2598
+ }
2599
+ authorityError = new AuthError(failure[2], status, retryAfterSeconds);
2600
+ throw authorityError;
2601
+ }
2602
+ if (!exact(value, ["recipient"]) || !exact(value.recipient, [
2603
+ "userId",
2604
+ "name",
2605
+ "email"
2606
+ ])) throw authorityUnavailable();
2607
+ const recipient = value.recipient;
2608
+ if (typeof recipient.userId !== "string" || !/^[A-Za-z0-9_-]{1,128}$(?![\s\S])/.test(recipient.userId) || typeof recipient.name !== "string" || recipient.name.length === 0 || encoder.encode(recipient.name).byteLength > 1024 || !validEmail(recipient.email) || recipient.email !== recipient.email.trim().toLowerCase() || recipient.email !== email) throw authorityUnavailable();
2609
+ return {
2610
+ userId: recipient.userId,
2611
+ name: recipient.name,
2612
+ email: recipient.email
2613
+ };
2614
+ };
2615
+ return await Promise.race([exchange().finally(() => {
2616
+ inFlight = false;
2617
+ }), deadline]);
1372
2618
  } catch (error) {
1373
- context.error = error;
1374
- if (context.options.onRequestError) await callHooks(context, context.options.onRequestError);
1375
- return await onError(context);
2619
+ if (authorityError && error === authorityError) throw authorityError;
2620
+ throw authorityUnavailable();
1376
2621
  } finally {
1377
- if (abortTimeout) clearTimeout(abortTimeout);
1378
- }
1379
- if ((context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD") {
1380
- const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
1381
- switch (responseType) {
1382
- case "json": {
1383
- const data = await context.response.text();
1384
- const parseFunction = context.options.parseResponse || destr;
1385
- context.response._data = parseFunction(data);
1386
- break;
1387
- }
1388
- case "stream":
1389
- context.response._data = context.response.body || context.response._bodyInit;
1390
- break;
1391
- default: context.response._data = await context.response[responseType]();
1392
- }
1393
- }
1394
- if (context.options.onResponse) await callHooks(context, context.options.onResponse);
1395
- if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
1396
- if (context.options.onResponseError) await callHooks(context, context.options.onResponseError);
1397
- return await onError(context);
1398
- }
1399
- return context.response;
1400
- };
1401
- const $fetch = async function $fetch2(request, options) {
1402
- return (await $fetchRaw(request, options))._data;
1403
- };
1404
- $fetch.raw = $fetchRaw;
1405
- $fetch.native = (...args) => fetch(...args);
1406
- $fetch.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
1407
- ...globalOptions,
1408
- ...customGlobalOptions,
1409
- defaults: {
1410
- ...globalOptions.defaults,
1411
- ...customGlobalOptions.defaults,
1412
- ...defaultOptions
2622
+ clearTimeout(timer);
2623
+ controller.abort();
2624
+ reader?.cancel().catch(() => {});
1413
2625
  }
1414
- });
1415
- return $fetch;
2626
+ } };
1416
2627
  }
1417
2628
  //#endregion
1418
- //#region src/http.ts
1419
- const MAX_RESPONSE_BYTES = 64 * 1024;
1420
- async function requestJson(url, options) {
1421
- return (await requestJsonResponse(url, options)).value;
1422
- }
1423
- async function requestJsonResponse(url, options) {
1424
- let response;
1425
- try {
1426
- response = await createFetch({ fetch: options.fetch }).raw(url, {
1427
- method: options.method,
1428
- headers: options.headers,
1429
- body: options.body,
1430
- credentials: options.credentials ?? "include",
1431
- retry: 0,
1432
- timeout: options.timeoutMs,
1433
- redirect: "manual",
1434
- signal: options.signal,
1435
- responseType: "stream",
1436
- ignoreResponseError: true
1437
- });
1438
- } catch {
1439
- throw authorityUnavailable();
1440
- }
1441
- const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
1442
- if (response.status >= 300 || response.status < 200 || contentType !== "application/json") {
1443
- const body = contentType === "application/json" ? await readJson(response, options.maxResponseBytes) : void 0;
1444
- await response.body?.cancel();
1445
- throw (options.mapError ?? fromAuthorityError)(body, response.status, response.headers.get("retry-after"));
1446
- }
1447
- return {
1448
- value: await readJson(response, options.maxResponseBytes),
1449
- headers: response.headers
1450
- };
2629
+ //#region src/provisioning.ts
2630
+ const MAX_BYTES = 16 * 1024;
2631
+ const compactJwt = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
2632
+ function isCompactCredential(value) {
2633
+ return typeof value === "string" && value.length + 7 <= MAX_BYTES && compactJwt.test(value);
1451
2634
  }
1452
- async function readJson(response, maximum = MAX_RESPONSE_BYTES) {
1453
- const length = response.headers.get("content-length");
1454
- if (length && (!/^\d+$/.test(length) || Number(length) > maximum)) {
1455
- await response.body?.cancel();
1456
- throw authorityUnavailable();
1457
- }
1458
- if (!response.body) throw authorityUnavailable();
1459
- const reader = response.body.getReader();
1460
- const chunks = [];
1461
- let size = 0;
1462
- try {
1463
- while (true) {
1464
- const { done, value } = await reader.read();
1465
- if (done) break;
1466
- size += value.byteLength;
1467
- if (size > maximum) throw authorityUnavailable();
1468
- chunks.push(value);
2635
+ function createDriveProvisioningAuth(options) {
2636
+ const url = joinURL(normalizeOrigin(options.authOrigin, "authOrigin"), "api/v1/auth/drive-provisioning-credential");
2637
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
2638
+ if (typeof fetchImpl !== "function") throw new TypeError("fetch is required");
2639
+ const timeoutMs = normalizeTimeout(options.timeoutMs);
2640
+ const now = options.now ?? Date.now;
2641
+ let inFlight = false;
2642
+ return { async getDriveProvisioningCredential(clientAssertion) {
2643
+ if (!isCompactCredential(clientAssertion)) throw new AuthError("invalid_request", 400);
2644
+ if (inFlight) throw new AuthError("state_conflict", 409);
2645
+ inFlight = true;
2646
+ const controller = new AbortController();
2647
+ let reader;
2648
+ let timer;
2649
+ let exchangeStarted = false;
2650
+ let authorityError;
2651
+ try {
2652
+ const startedAt = now();
2653
+ if (!Number.isSafeInteger(startedAt) || startedAt < 0 || startedAt > 86399999997e5) throw authorityUnavailable();
2654
+ const deadline = new Promise((_, reject) => {
2655
+ timer = setTimeout(() => {
2656
+ reject(authorityUnavailable());
2657
+ controller.abort();
2658
+ reader?.cancel().catch(() => {});
2659
+ }, timeoutMs);
2660
+ });
2661
+ const exchange = async () => {
2662
+ const response = await fetchImpl(url, {
2663
+ method: "POST",
2664
+ headers: {
2665
+ authorization: `Bearer ${clientAssertion}`,
2666
+ accept: "application/json"
2667
+ },
2668
+ credentials: "omit",
2669
+ cache: "no-store",
2670
+ redirect: "manual",
2671
+ signal: controller.signal
2672
+ });
2673
+ if (controller.signal.aborted) {
2674
+ response.body?.cancel().catch(() => {});
2675
+ throw authorityUnavailable();
2676
+ }
2677
+ if (!response.body) throw authorityUnavailable();
2678
+ reader = response.body.getReader();
2679
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
2680
+ const length = response.headers.get("content-length");
2681
+ if (contentType !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_BYTES)) throw authorityUnavailable();
2682
+ const bytes = new Uint8Array(MAX_BYTES);
2683
+ let size = 0;
2684
+ while (true) {
2685
+ const chunk = await reader.read();
2686
+ if (chunk.done) break;
2687
+ if (controller.signal.aborted || size + chunk.value.byteLength > MAX_BYTES) throw authorityUnavailable();
2688
+ bytes.set(chunk.value, size);
2689
+ size += chunk.value.byteLength;
2690
+ }
2691
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size)));
2692
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw authorityUnavailable();
2693
+ const record = value;
2694
+ if (response.status !== 200) {
2695
+ if (Object.keys(record).length !== 2 || !("code" in record) || !("message" in record)) throw authorityUnavailable();
2696
+ if (response.status === 401 && record.code === "UNAUTHORIZED" && record.message === "The ecosystem client assertion is invalid.") {
2697
+ authorityError = new AuthError("authentication_required", 401);
2698
+ throw authorityError;
2699
+ }
2700
+ const retryAfter = response.headers.get("retry-after");
2701
+ if (response.status === 429 && record.code === "TOO_MANY_REQUESTS" && record.message === "Ecosystem credential exchanges are temporarily limited." && retryAfter !== null && /^(?:[1-9]|[1-5][0-9]|60)$/.test(retryAfter)) {
2702
+ authorityError = new AuthError("auth_request_rate_limited", 429, Number(retryAfter));
2703
+ throw authorityError;
2704
+ }
2705
+ throw authorityUnavailable();
2706
+ }
2707
+ if (Object.keys(record).length !== 3 || record.tokenType !== "Bearer" || record.expiresIn !== 300 || !isCompactCredential(record.token)) throw authorityUnavailable();
2708
+ const expiresAt = new Date(Math.floor(startedAt / 1e3) * 1e3 + 3e5);
2709
+ const completedAt = now();
2710
+ if (!Number.isSafeInteger(completedAt) || completedAt < 0 || completedAt >= expiresAt.getTime()) throw authorityUnavailable();
2711
+ return {
2712
+ tokenType: "Bearer",
2713
+ token: record.token,
2714
+ expiresAt
2715
+ };
2716
+ };
2717
+ exchangeStarted = true;
2718
+ return await Promise.race([exchange().finally(() => {
2719
+ inFlight = false;
2720
+ }), deadline]);
2721
+ } catch (error) {
2722
+ if (authorityError && error === authorityError) throw authorityError;
2723
+ throw authorityUnavailable();
2724
+ } finally {
2725
+ clearTimeout(timer);
2726
+ controller.abort();
2727
+ reader?.cancel().catch(() => {});
2728
+ if (!exchangeStarted) inFlight = false;
1469
2729
  }
1470
- } catch (error) {
1471
- await reader.cancel();
1472
- throw error;
1473
- } finally {
1474
- reader.releaseLock();
1475
- }
1476
- const bytes = new Uint8Array(size);
1477
- let offset = 0;
1478
- for (const chunk of chunks) {
1479
- bytes.set(chunk, offset);
1480
- offset += chunk.byteLength;
1481
- }
1482
- try {
1483
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1484
- } catch {
1485
- throw authorityUnavailable();
1486
- }
2730
+ } };
1487
2731
  }
1488
2732
  //#endregion
1489
2733
  //#region src/server.ts
@@ -1734,6 +2978,21 @@ function createServerAuth(options) {
1734
2978
  body: { workspace }
1735
2979
  }), now());
1736
2980
  },
2981
+ async getUserApiCredential(input) {
2982
+ const applicationId = userApiApplication(input);
2983
+ const startedAt = now();
2984
+ return normalizeUserApiCredential(await requestJson(joinURL(authOrigin, "api/v1/auth/user-api-credential"), {
2985
+ fetch: fetchImpl,
2986
+ timeoutMs,
2987
+ method: "POST",
2988
+ credentials,
2989
+ headers: {
2990
+ ...authHeaders(),
2991
+ "content-type": "application/json; charset=utf-8"
2992
+ },
2993
+ body: { applicationId }
2994
+ }), startedAt);
2995
+ },
1737
2996
  async signOut() {
1738
2997
  let response;
1739
2998
  try {
@@ -1785,4 +3044,4 @@ function authAuthorizationHeader(value) {
1785
3044
  return value;
1786
3045
  }
1787
3046
  //#endregion
1788
- export { AuthError, createDriveProvisioningAuth, createDriveRecipientAuth, createIdentityResolverAuth, createServerAuth };
3047
+ export { AuthError, createDriveProvisioningAuth, createDriveRecipientAuth, createIdentityResolverAuth, createServerAuth, createUserApiVerifier };