@finueva/auth 0.18.0 → 0.19.0

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