@finueva/auth 0.17.0 → 0.18.1

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