@plasgos/auth-verify 0.0.0-stage → 0.1.0-next.3

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +15 -0
  3. package/README.md +122 -2
  4. package/THIRD_PARTY_NOTICES.md +31 -0
  5. package/dist/express.cjs +157 -0
  6. package/dist/express.cjs.map +1 -0
  7. package/dist/express.d.cts +90 -0
  8. package/dist/express.d.ts +90 -0
  9. package/dist/express.js +127 -0
  10. package/dist/express.js.map +1 -0
  11. package/dist/index.cjs +1254 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +67 -0
  14. package/dist/index.d.ts +67 -0
  15. package/dist/index.js +499 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/nestjs.cjs +1395 -0
  18. package/dist/nestjs.cjs.map +1 -0
  19. package/dist/nestjs.d.cts +153 -0
  20. package/dist/nestjs.d.ts +153 -0
  21. package/dist/nestjs.js +637 -0
  22. package/dist/nestjs.js.map +1 -0
  23. package/dist/types-CGtRnj59.d.cts +193 -0
  24. package/dist/types-CGtRnj59.d.ts +193 -0
  25. package/dist/webhook.cjs +296 -0
  26. package/dist/webhook.cjs.map +1 -0
  27. package/dist/webhook.d.cts +196 -0
  28. package/dist/webhook.d.ts +196 -0
  29. package/dist/webhook.js +265 -0
  30. package/dist/webhook.js.map +1 -0
  31. package/docs/bff-express.md +1314 -0
  32. package/docs/consumers.md +98 -0
  33. package/docs/contoh-hitungcuan.md +255 -0
  34. package/docs/contoh-plaslink.md +244 -0
  35. package/docs/error.md +613 -0
  36. package/docs/examples/auth-verify-readme.ts +42 -0
  37. package/docs/examples/bff-express.ts +370 -0
  38. package/docs/examples/bff-proxy.ts +335 -0
  39. package/docs/examples/bff-redis-lock.ts +187 -0
  40. package/docs/examples/bff-revocation.ts +136 -0
  41. package/docs/examples/config-error.ts +24 -0
  42. package/docs/examples/env.ts +150 -0
  43. package/docs/examples/failure-log.ts +18 -0
  44. package/docs/examples/login-client.ts +46 -0
  45. package/docs/examples/login-flow.ts +186 -0
  46. package/docs/examples/plaslink-connect.ts +48 -0
  47. package/docs/examples/readme.ts +60 -0
  48. package/docs/examples/service-client.ts +105 -0
  49. package/docs/examples/session-store.ts +53 -0
  50. package/docs/examples/token-commonjs.cjs +95 -0
  51. package/docs/examples/token-express.ts +56 -0
  52. package/docs/examples/token-fetch.ts +24 -0
  53. package/docs/examples/token-nestjs-jest.ts +77 -0
  54. package/docs/examples/token-nestjs.ts +127 -0
  55. package/docs/examples/token-socket.ts +59 -0
  56. package/docs/examples/token-testing.ts +100 -0
  57. package/docs/examples/token-verifier.ts +132 -0
  58. package/docs/examples/user-events.ts +110 -0
  59. package/docs/examples/webhook-express.ts +46 -0
  60. package/docs/examples/webhook-fetch.ts +60 -0
  61. package/docs/examples/webhook-nestjs.ts +59 -0
  62. package/docs/examples/webhook-testing.ts +60 -0
  63. package/docs/examples/webhook-verifier.ts +197 -0
  64. package/docs/login-web.md +650 -0
  65. package/docs/memulai.md +419 -0
  66. package/docs/server-ke-server.md +287 -0
  67. package/docs/verifikasi-token.md +1219 -0
  68. package/docs/webhook.md +810 -0
  69. package/package.json +101 -3
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/nestjs/index.ts","../src/nestjs/module.ts","../src/config.ts","../src/core/config.ts","../src/core/jwks.ts","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/buffer_utils.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/util/errors.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/util/base64url.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/validate.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/key.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/key_descriptor.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/jws_algorithms.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/jws_verify.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/jwt_claims_set.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/jwt/verify.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/jwks/local.js","../../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/jwks/remote.js","../src/core/verify.ts","../src/core/requirements.ts","../src/core/verifier.ts","../src/nestjs/guard.ts","../src/core/response.ts","../src/nestjs/tokens.ts","../src/nestjs/decorators.ts"],"sourcesContent":["export { PlasgosAuthModule } from \"./module.js\";\nexport type { PlasgosAuthModuleAsyncOptions } from \"./module.js\";\nexport { PlasgosAccessTokenGuard } from \"./guard.js\";\nexport { PlasgosPrincipal, RequireRecentAuth, RequireScopes } from \"./decorators.js\";\nexport { PLASGOS_ACCESS_TOKEN_VERIFIER } from \"./tokens.js\";\nexport type {\n AccessPrincipal,\n AccessTokenVerifier,\n AccessTokenVerifierOptions,\n ServiceAccessPrincipal,\n UserAccessPrincipal,\n VerifiedAccessTokenClaims,\n} from \"../core/types.js\";\n// The classes this entry throws and recognises: the same classes as in @plasgos/auth-shared, so\n// `instanceof` holds across the packages.\nexport { AuthVerifyError, ConfigError } from \"@plasgos/auth-shared\";\nexport type { AuthVerifyReason } from \"@plasgos/auth-shared\";\n","import { Module } from \"@nestjs/common\";\nimport type { DynamicModule, FactoryProvider, ModuleMetadata } from \"@nestjs/common\";\n\nimport type { AccessPrincipal, AccessTokenVerifierOptions, UserAccessPrincipal } from \"../core/types.js\";\nimport { createAccessTokenVerifier } from \"../core/verifier.js\";\nimport { PlasgosAccessTokenGuard } from \"./guard.js\";\nimport { PLASGOS_ACCESS_TOKEN_VERIFIER } from \"./tokens.js\";\n\n/** Options for one API: user tokens only, or both kinds with `allowServiceTokens: true`. */\ntype ModuleOptions = AccessTokenVerifierOptions | AccessTokenVerifierOptions<AccessPrincipal>;\n\n/**\n * The options of `PlasgosAuthModule.forRootAsync`: a factory that returns the verifier options, its\n * injected providers and the modules that export them.\n *\n * @example\n * PlasgosAuthModule.forRootAsync({\n * imports: [ConfigModule],\n * inject: [ConfigService],\n * useFactory: (config: ConfigService) => ({ environment: \"production\", issuer: config.get(\"ISSUER\"), audience: config.get(\"AUDIENCE\") }),\n * });\n */\nexport interface PlasgosAuthModuleAsyncOptions {\n /** Modules that export the providers `inject` names. */\n imports?: ModuleMetadata[\"imports\"] | undefined;\n /** Providers passed to `useFactory`, in order. */\n inject?: FactoryProvider[\"inject\"] | undefined;\n /** Returns the options of `createAccessTokenVerifier`, or a promise of them. */\n useFactory: (...args: never[]) => ModuleOptions | Promise<ModuleOptions>;\n}\n\nfunction module(provider: DynamicModule[\"providers\"], imports?: ModuleMetadata[\"imports\"]): DynamicModule {\n return {\n module: PlasgosAuthModule,\n global: true,\n ...(imports !== undefined ? { imports } : {}),\n providers: [...(provider ?? []), PlasgosAccessTokenGuard],\n exports: [PLASGOS_ACCESS_TOKEN_VERIFIER, PlasgosAccessTokenGuard],\n };\n}\n\n/**\n * A global NestJS module that provides the access-token verifier under `PLASGOS_ACCESS_TOKEN_VERIFIER`\n * and `PlasgosAccessTokenGuard` to the whole app. Import it once, in the root module. The verifier is\n * created with `createAccessTokenVerifier` when Nest builds the module, so a wrong option stops the\n * app at start with one `ConfigError` listing every problem.\n *\n * @example\n * @Module({\n * imports: [\n * PlasgosAuthModule.forRoot({\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * audience: \"https://api.plasgos.co.id/crm\",\n * requireClaims: [\"plasgos_public_id\", \"cv\"],\n * isRevoked: (principal) => revocations.isRevoked(principal),\n * }),\n * ],\n * })\n * export class AppModule {}\n */\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- a NestJS module must be a class\nexport class PlasgosAuthModule {\n /**\n * The module with fixed options (the options of `createAccessTokenVerifier`). By default the options\n * are user-only and `isRevoked` receives a `UserAccessPrincipal`; to accept service tokens too, name\n * the principal type: `forRoot<AccessPrincipal>({ …, allowServiceTokens: true })`.\n *\n * @example\n * PlasgosAuthModule.forRoot({ environment: \"sandbox\", issuer, audience, isRevoked: () => false });\n */\n static forRoot<P extends AccessPrincipal = UserAccessPrincipal>(options: AccessTokenVerifierOptions<P>): DynamicModule {\n return module([\n { provide: PLASGOS_ACCESS_TOKEN_VERIFIER, useFactory: () => createAccessTokenVerifier(options as AccessTokenVerifierOptions<AccessPrincipal>) },\n ]);\n }\n\n /**\n * The module with options from a factory, for example from a config service. A `ConfigError` from\n * the returned options, or an error of the factory, fails the app's start.\n *\n * @example\n * PlasgosAuthModule.forRootAsync({ inject: [ConfigService], useFactory: (config: ConfigService) => config.get(\"plasgos\") });\n */\n static forRootAsync(options: PlasgosAuthModuleAsyncOptions): DynamicModule {\n const { useFactory } = options;\n return module(\n [\n {\n provide: PLASGOS_ACCESS_TOKEN_VERIFIER,\n useFactory: async (...args: never[]) =>\n createAccessTokenVerifier((await useFactory(...args)) as AccessTokenVerifierOptions<AccessPrincipal>),\n inject: options.inject ?? [],\n },\n ],\n options.imports,\n );\n }\n}\n\nModule({})(PlasgosAuthModule);\n","// Option helpers shared by the entries of this package. Stateless functions only: tsup bundles them\n// into every entry that uses them, so the ESM and CommonJS builds hold no state that could split.\n\n/**\n * True for a non-null object that is not an array.\n *\n * @example\n * if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n */\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * True for a string of whitespace only. Apps pass `process.env` values, where unset is often \"\".\n *\n * @example\n * const secrets = raw.filter((value) => value !== undefined && !isBlank(value));\n */\nexport const isBlank = (value: unknown): boolean => typeof value === \"string\" && value.trim() === \"\";\n\n/**\n * Bounds and default of {@link integerInRange}.\n *\n * @example\n * const range: IntegerRange = { min: 1, max: 900, fallback: 300 };\n */\nexport interface IntegerRange {\n readonly min: number;\n readonly max: number;\n /** Returned for `undefined`, and when the value is refused. */\n readonly fallback: number;\n}\n\n/**\n * An integer option: `undefined` gives the fallback; a safe integer from `min` to `max` is returned\n * as is; anything else collects `<field> must be an integer from <min> to <max>` and gives the\n * fallback. The problem names the field and the bounds, never the value.\n *\n * @example\n * const problems: string[] = [];\n * const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, \"toleranceSeconds\", {\n * min: 1,\n * max: 900,\n * fallback: 300,\n * });\n */\nexport function integerInRange(problems: string[], raw: unknown, field: string, range: IntegerRange): number {\n if (raw === undefined) return range.fallback;\n if (typeof raw === \"number\" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;\n problems.push(`${field} must be an integer from ${String(range.min)} to ${String(range.max)}`);\n return range.fallback;\n}\n\n/**\n * An optional function option: `undefined` stays `undefined`; anything that is not a function\n * collects `<field> must be a function` and gives `undefined`.\n *\n * @example\n * const onReject = optionalFunction(problems, raw.onReject, \"onReject\");\n */\nexport function optionalFunction(problems: string[], raw: unknown, field: string): ((...args: never[]) => unknown) | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw === \"function\") return raw as (...args: never[]) => unknown;\n problems.push(`${field} must be a function`);\n return undefined;\n}\n","import { ConfigError, PRODUCTION_ISSUER, environmentProblems, parseAudience, parseIssuer } from \"@plasgos/auth-shared\";\nimport type { Environment } from \"@plasgos/auth-shared\";\n\nimport { integerInRange, isBlank, isObject, optionalFunction } from \"../config.js\";\nimport type { AccessPrincipal, AuthRejectEvent, JsonWebKeySet, JwksFetch } from \"./types.js\";\n\n/** Default leeway for `exp`/`nbf`: a resource server runs on its own clock. */\nconst DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;\nconst MAX_CLOCK_TOLERANCE_SECONDS = 60;\nconst DEFAULT_JWKS_MS = 5_000;\nconst MAX_TIMEOUT_MS = 60_000;\n/** At most this many required claim names, on the verifier and per call. */\nexport const MAX_REQUIRED_CLAIMS = 16;\n/** A claim name the verifier can require: letters, digits and `_`, at most 64 characters. */\nexport const CLAIM_NAME = /^[A-Za-z0-9_]{1,64}$/;\n/** The audience path whose user tokens must carry `cv`: the revocation check compares it. */\nconst CREDENTIAL_VERSION_PATH = \"/crm\";\n\nconst PROBLEM = {\n https: 'backchannelUrl must use https: when environment is \"production\" unless allowInsecureBackchannel is true',\n isRevokedRequired: \"isRevoked is required for a crm audience\",\n requireClaims: `requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`,\n jwks: \"jwks must be a JSON Web Key Set\",\n jwksSandboxOnly: 'jwks is only allowed when environment is \"sandbox\"',\n} as const;\n\n/**\n * The checked options of `createAccessTokenVerifier`, frozen.\n *\n * @example\n * const config = resolveVerifierConfig(options);\n * const jwksUrl = `${config.backchannelUrl ?? config.issuer}/oidc/jwks`;\n */\nexport interface ResolvedVerifierConfig {\n readonly environment: Environment;\n readonly issuer: string;\n readonly audience: string;\n readonly backchannelUrl: string | null;\n readonly allowInsecureBackchannel: boolean;\n readonly allowServiceTokens: boolean;\n /** The `requireClaims` option: distinct names, in the order given. */\n readonly requiredClaims: readonly string[];\n /** True when the audience path, trailing slashes removed, is `/crm`: user tokens must carry `cv`. */\n readonly requireCredentialVersion: boolean;\n readonly clockToleranceSeconds: number;\n readonly timeouts: Readonly<{ jwksMs: number }>;\n /** A frozen copy of the static key set, or null for the JWKS request. */\n readonly jwks: JsonWebKeySet | null;\n readonly fetch: JwksFetch;\n readonly isRevoked: ((principal: AccessPrincipal) => boolean | Promise<boolean>) | undefined;\n readonly onReject: ((event: AuthRejectEvent) => void | Promise<void>) | undefined;\n}\n\nconst RESOURCE_PROBLEM = 'environment is \"production\" but resource is not a production audience';\nconst AUDIENCE_PROBLEM = 'environment is \"production\" but audience is not a production audience';\n\n/** Resolved at call time, so a `globalThis.fetch` replaced later (a test spy, an instrumentation) is used. */\nconst globalFetch: JwksFetch = (input, init) => globalThis.fetch(input, init);\n\n/** True when the audience's path without trailing slashes is exactly `/crm`. */\nfunction needsCredentialVersion(audience: string): boolean {\n return new URL(audience).pathname.replace(/\\/+$/, \"\") === CREDENTIAL_VERSION_PATH;\n}\n\n/** Runs a single-problem parser of auth-shared; its problem is collected, not thrown. */\nfunction parsed(problems: string[], parse: () => string): string | undefined {\n try {\n return parse();\n } catch (error) {\n if (!(error instanceof ConfigError)) throw error;\n problems.push(...error.problems);\n return undefined;\n }\n}\n\n/** The required claim names, distinct and frozen; an empty list after the problem was collected. */\nfunction requiredClaimsOf(problems: string[], raw: unknown): readonly string[] {\n if (raw === undefined) return Object.freeze([]);\n if (\n !Array.isArray(raw) ||\n raw.length > MAX_REQUIRED_CLAIMS ||\n !raw.every((name): name is string => typeof name === \"string\" && CLAIM_NAME.test(name))\n ) {\n problems.push(PROBLEM.requireClaims);\n return Object.freeze([]);\n }\n return Object.freeze([...new Set(raw)]);\n}\n\n/** A frozen copy of a well-formed key set, or null after the problem was collected. */\nfunction jwksOf(problems: string[], raw: unknown): JsonWebKeySet | null {\n const keys: unknown = isObject(raw) ? raw[\"keys\"] : undefined;\n if (!Array.isArray(keys) || keys.length === 0 || !keys.every((key) => isObject(key))) {\n problems.push(PROBLEM.jwks);\n return null;\n }\n return Object.freeze({ keys: Object.freeze(keys.map((key) => Object.freeze({ ...key }))) });\n}\n\n/** The `timeouts` option: an object whose `jwksMs` is an integer from 1 to 60 000 ms. */\nfunction timeoutsOf(problems: string[], raw: unknown): Readonly<{ jwksMs: number }> {\n if (raw === undefined) return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });\n if (!isObject(raw)) {\n problems.push(\"timeouts must be an object\");\n return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });\n }\n const jwksMs = integerInRange(problems, raw[\"jwksMs\"], \"timeouts.jwksMs\", {\n min: 1,\n max: MAX_TIMEOUT_MS,\n fallback: DEFAULT_JWKS_MS,\n });\n return Object.freeze({ jwksMs });\n}\n\n/**\n * Checks the untyped options of `createAccessTokenVerifier`. Returns the frozen config, or throws one\n * `ConfigError` whose problems name fields only, never values: the environment guard first, then the\n * fields in the order of the option table.\n *\n * @example\n * const config = resolveVerifierConfig({\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * audience: \"https://api.plasgos.co.id/crm\",\n * isRevoked: () => false,\n * });\n * config.requireCredentialVersion; // true\n */\nexport function resolveVerifierConfig(raw: unknown): ResolvedVerifierConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n /** The option when it is a string; a present non-string is reported and counts as unusable. */\n const text = (field: string): string | undefined => {\n const value = raw[field];\n if (value === undefined || typeof value === \"string\") return value;\n problems.push(`${field} must be a string`);\n return undefined;\n };\n const given = (field: string): boolean => raw[field] !== undefined;\n /** A boolean option: `undefined` is `false`; anything else but a boolean is reported. */\n const flag = (field: string): boolean => {\n const value = raw[field];\n if (value === undefined || typeof value === \"boolean\") return value === true;\n problems.push(`${field} must be a boolean`);\n return false;\n };\n\n const environment = raw[\"environment\"];\n // For the URL checks a non-boolean counts as false; the environment guard still sees the raw value.\n const allowInsecureHttp = raw[\"allowInsecureHttp\"] === true;\n\n const issuerRaw = text(\"issuer\");\n const issuer =\n given(\"issuer\") && issuerRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(issuerRaw, { field: \"issuer\", allowInsecureHttp }));\n\n const audienceRaw = text(\"audience\");\n const audience =\n given(\"audience\") && audienceRaw === undefined\n ? undefined\n : parsed(problems, () => parseAudience(audienceRaw, { field: \"audience\", allowInsecureHttp }));\n\n // A blank backchannelUrl (an env var set to \"\") counts as not given.\n const backchannelRaw = given(\"backchannelUrl\") && !isBlank(raw[\"backchannelUrl\"]) ? text(\"backchannelUrl\") : undefined;\n const backchannelUrl =\n backchannelRaw === undefined\n ? undefined\n : parsed(problems, () => parseIssuer(backchannelRaw, { field: \"backchannelUrl\", allowInsecureHttp: true }));\n // The JWKS is the trust root: a plain-http back channel in production needs an explicit opt-in.\n const insecureBackchannelRaw = raw[\"allowInsecureBackchannel\"];\n if (\n environment === \"production\" &&\n backchannelUrl !== undefined &&\n new URL(backchannelUrl).protocol === \"http:\" &&\n insecureBackchannelRaw !== true\n ) {\n problems.push(PROBLEM.https);\n }\n const allowInsecureBackchannel = flag(\"allowInsecureBackchannel\");\n\n const allowServiceTokens = flag(\"allowServiceTokens\");\n const requiredClaims = requiredClaimsOf(problems, raw[\"requireClaims\"]);\n const clockToleranceSeconds = integerInRange(problems, raw[\"clockToleranceSeconds\"], \"clockToleranceSeconds\", {\n min: 0,\n max: MAX_CLOCK_TOLERANCE_SECONDS,\n fallback: DEFAULT_CLOCK_TOLERANCE_SECONDS,\n });\n const timeouts = timeoutsOf(problems, raw[\"timeouts\"]);\n\n const jwks = given(\"jwks\") ? jwksOf(problems, raw[\"jwks\"]) : null;\n if (given(\"jwks\") && environment === \"production\") problems.push(PROBLEM.jwksSandboxOnly);\n\n flag(\"allowInsecureHttp\");\n const fetch = optionalFunction(problems, raw[\"fetch\"], \"fetch\") as JwksFetch | undefined;\n\n const requireCredentialVersion = audience !== undefined && needsCredentialVersion(audience);\n const isRevoked = optionalFunction(problems, raw[\"isRevoked\"], \"isRevoked\") as ResolvedVerifierConfig[\"isRevoked\"];\n // A cv that nothing compares is a revocation check that silently does not run.\n if (requireCredentialVersion && !given(\"isRevoked\")) problems.push(PROBLEM.isRevokedRequired);\n const onReject = optionalFunction(problems, raw[\"onReject\"], \"onReject\") as ResolvedVerifierConfig[\"onReject\"];\n\n // The guard compares parsed values. An issuer that did not parse already has its problem, so the\n // guard gets a value it has nothing to say about and still judges the other fields.\n const guard = environmentProblems({\n environment,\n issuer: issuer ?? (environment === \"production\" ? PRODUCTION_ISSUER : \"\"),\n allowInsecureHttp: raw[\"allowInsecureHttp\"],\n ...(audience !== undefined ? { audiences: [audience] } : {}),\n ...(backchannelUrl !== undefined ? { backchannelUrl } : {}),\n });\n\n // The shared guard names the option of @plasgos/oidc-client (\"resource\"); here the option is \"audience\".\n const named = guard.map((problem) => (problem === RESOURCE_PROBLEM ? AUDIENCE_PROBLEM : problem));\n if (named.length > 0 || problems.length > 0) throw new ConfigError([...named, ...problems]);\n return Object.freeze({\n environment: environment as Environment,\n issuer: issuer as string,\n audience: audience as string,\n backchannelUrl: backchannelUrl ?? null,\n allowInsecureBackchannel,\n allowServiceTokens,\n requiredClaims,\n requireCredentialVersion,\n clockToleranceSeconds,\n timeouts,\n jwks,\n fetch: fetch ?? globalFetch,\n isRevoked,\n onReject,\n });\n}\n","import { OIDC_PATHS } from \"@plasgos/auth-shared\";\nimport { createLocalJWKSet, createRemoteJWKSet, customFetch } from \"jose\";\nimport type { JWTVerifyGetKey, JSONWebKeySet as JoseKeySet } from \"jose\";\n\nimport type { JsonWebKeySet, JwksFetch } from \"./types.js\";\n\n/** jose's default refetch pause after a fetch, made explicit. */\nconst COOLDOWN_MS = 30_000;\n/** The JWKS body cap. A Plasgos key set with a few RSA keys is about 1–2 KiB. */\nconst MAX_JWKS_BYTES = 65_536;\n\n/**\n * The `code` of every error by which the key set could not be read (network, timeout, a status other\n * than 200, a body over 64 KiB, invalid JSON or a malformed key set). The verifier answers it with\n * `unavailable` (503), never as a token problem.\n */\nconst KEY_SET_UNAVAILABLE = \"ERR_PLASGOS_JWKS_UNAVAILABLE\";\n/** jose's codes for a key set that timed out or is malformed, should one reach the verifier. */\nconst JOSE_UNAVAILABLE_CODES: ReadonlySet<string> = new Set([KEY_SET_UNAVAILABLE, \"ERR_JWKS_TIMEOUT\", \"ERR_JWKS_INVALID\"]);\n\n/** The fields of the resolved verifier config a remote key set needs. */\nexport interface KeySetSource {\n readonly issuer: string;\n readonly backchannelUrl: string | null;\n readonly timeouts: Readonly<{ jwksMs: number }>;\n readonly fetch: JwksFetch;\n}\n\n/**\n * A plain error with only a fixed message and the code: nothing of the cause (a network error, the\n * body) travels with it. Not a class, so no class is shared between the entries that bundle this file.\n */\nfunction unavailable(): Error {\n return Object.assign(new Error(\"Plasgos key set unavailable\"), { code: KEY_SET_UNAVAILABLE });\n}\n\n/**\n * True when `error` means the key set could not be read (reason `unavailable`). Mapped by\n * the `code` string, never by `instanceof`, so it holds across bundled copies of jose.\n */\nexport function isKeySetUnavailable(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error)) return false;\n const { code } = error;\n return typeof code === \"string\" && JOSE_UNAVAILABLE_CODES.has(code);\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/** Reads the body up to `MAX_JWKS_BYTES`; throws as soon as the count passes the cap. */\nasync function readCapped(response: Response): Promise<Uint8Array> {\n const length = response.headers.get(\"content-length\");\n if (length !== null && Number(length) > MAX_JWKS_BYTES) throw unavailable();\n if (response.body === null) return new Uint8Array(0);\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const result: { done: boolean; value?: unknown } = await reader.read();\n if (result.done) break;\n const chunk = result.value;\n if (!(chunk instanceof Uint8Array)) throw unavailable();\n total += chunk.byteLength;\n if (total > MAX_JWKS_BYTES) {\n void reader.cancel().catch(() => undefined);\n throw unavailable();\n }\n chunks.push(chunk);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/** True when the bytes are UTF-8 JSON of the shape `{ keys: [object, …] }`. */\nfunction isKeySetJson(bytes: Uint8Array): boolean {\n try {\n const json: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n return isObject(json) && Array.isArray(json[\"keys\"]) && json[\"keys\"].every((key) => isObject(key));\n } catch {\n return false;\n }\n}\n\n/**\n * The fetch jose calls for the key set: never follows a redirect, refuses a status other\n * than 200 before reading the body, reads at most 64 KiB, gives up after `jwksMs` (also when the fetch\n * ignores its abort signal), and hands jose a fresh `200` response of the checked bytes. Every failure\n * is the same plain `unavailable` error.\n */\nfunction boundedFetch(fetchImpl: JwksFetch, jwksMs: number) {\n return async (url: string, init: RequestInit): Promise<Response> => {\n const controller = new AbortController();\n const abort = (): void => {\n controller.abort();\n };\n const outer = init.signal;\n if (outer?.aborted === true) abort();\n outer?.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(abort, jwksMs);\n const aborted = new Promise<never>((_, reject) => {\n const fail = (): void => {\n reject(unavailable());\n };\n if (controller.signal.aborted) fail();\n else controller.signal.addEventListener(\"abort\", fail, { once: true });\n });\n aborted.catch(() => undefined);\n try {\n const response = await Promise.race([\n fetchImpl(url, { ...init, redirect: \"manual\", signal: controller.signal }),\n aborted,\n ]);\n // Checked here, before any byte is read: the rebuilt Response below is always a 200, so jose's own\n // status check would never see a 3xx, 204 or 5xx.\n if (response.status !== 200) {\n void response.body?.cancel().catch(() => undefined);\n throw unavailable();\n }\n const bytes = await Promise.race([readCapped(response), aborted]);\n if (!isKeySetJson(bytes)) throw unavailable();\n return new Response(bytes, { status: 200, headers: { \"content-type\": \"application/json\" } });\n } catch {\n throw unavailable();\n } finally {\n clearTimeout(timer);\n outer?.removeEventListener(\"abort\", abort);\n }\n };\n}\n\n/**\n * The key resolver for `jwtVerify` over the Plasgos JWKS at `<backchannelUrl ?? issuer>/oidc/jwks`.\n * jose caches the set for 10 minutes; an unknown `kid` refetches once, then waits out a 30 s cooldown.\n *\n * @example\n * const keySet = remoteKeySet(config);\n * await jwtVerify(token, keySet, { algorithms: [\"RS256\"], issuer: config.issuer, audience: config.audience });\n */\nexport function remoteKeySet(source: KeySetSource): JWTVerifyGetKey {\n const url = new URL(`${source.backchannelUrl ?? source.issuer}${OIDC_PATHS.jwks}`);\n return createRemoteJWKSet(url, {\n timeoutDuration: source.timeouts.jwksMs,\n cooldownDuration: COOLDOWN_MS,\n [customFetch]: boundedFetch(source.fetch, source.timeouts.jwksMs),\n });\n}\n\n/**\n * The key resolver over a fixed key set (the sandbox-only `jwks` option): no request is ever made.\n *\n * @example\n * const keySet = staticKeySet({ keys: [publicJwk] });\n */\nexport function staticKeySet(jwks: JsonWebKeySet): JWTVerifyGetKey {\n return createLocalJWKSet(jwks as unknown as JoseKeySet);\n}\n","const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), UINT32_RANGE = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= UINT32_RANGE)\n throw new RangeError(`value must be >= 0 and <= ${UINT32_RANGE - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / UINT32_RANGE), low = value % UINT32_RANGE, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n","class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n","import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n","import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch (cause) {\n throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });\n }\n}\nfunction encodeAsciiMember(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch (cause) {\n throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });\n }\n}\nfunction parseJoseHeader(encodedProtectedHeader, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));\n } catch (cause) {\n throw new ErrorClass(message, { cause });\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeAsciiMember,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n","import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, requiresPrivateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (requiresPrivateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present' : `JSON Web Key for this operation must be a ${requiresPrivateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : requiresPrivateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n","function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(parameterSet) {\n const subtle = { name: `ML-DSA-${parameterSet}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n","import { jwsAlgorithm } from \"./jws_algorithms.js\";\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from \"../util/errors.js\";\nimport { concat, decoder, encoder, encode } from \"./buffer_utils.js\";\nimport { decodeBase64url, encodeAsciiMember, parseJoseHeader, isDisjoint, isObject, validateB64, validateCrit, validateAlgorithms, JWS_RECOGNIZED } from \"./validate.js\";\nimport { prepareKey, rawKey, checkModulusLength } from \"./key.js\";\nfunction snapshotJws(jws, sharedPayload) {\n const encodedProtectedHeader = jws.protected, inputHeader = jws.header, header = isObject(inputHeader) ? { ...inputHeader } : inputHeader;\n let payload = sharedPayload ? sharedPayload[0] : jws.payload;\n !sharedPayload && payload instanceof Uint8Array && (payload = new Uint8Array(payload));\n const signature = jws.signature, snapshot = { payload, signature };\n if (encodedProtectedHeader !== void 0 && (snapshot.protected = encodedProtectedHeader), inputHeader !== void 0 && (snapshot.header = header), encodedProtectedHeader === void 0 && header === void 0)\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n if (encodedProtectedHeader !== void 0 && typeof encodedProtectedHeader != \"string\")\n throw new JWSInvalid(\"JWS Protected Header incorrect type\");\n if (payload === void 0)\n throw new JWSInvalid(\"JWS Payload missing\");\n if (typeof signature != \"string\")\n throw new JWSInvalid(\"JWS Signature missing or incorrect type\");\n if (header !== void 0 && !isObject(header))\n throw new JWSInvalid(\"JWS Unprotected Header incorrect type\");\n return snapshot;\n}\nfunction prepareVerify(options) {\n return [options && validateAlgorithms(\"algorithms\", options.algorithms), options?.crit];\n}\nfunction parseProtectedHeader(encodedProtectedHeader) {\n return encodedProtectedHeader === void 0 ? {} : parseJoseHeader(encodedProtectedHeader, JWSInvalid, \"JWS Protected Header is invalid\");\n}\nfunction encodeJsonUnencodedPayload(payload) {\n const invalid = /[\\p{Cs}\\p{Cn}]/u.exec(payload)?.[0];\n if (invalid !== void 0)\n throw new JWSInvalid(/\\p{Cs}/u.test(invalid) ? \"JWS Payload must be a well-formed Unicode string\" : \"JWS Payload must not contain unassigned Unicode code points\");\n return encoder.encode(payload);\n}\nfunction encodeCompactUnencodedPayload(payload) {\n try {\n return encode(payload);\n } catch (cause) {\n throw new JWSInvalid(\"JWS Compact Serialization payload must use only ASCII characters\", {\n cause\n });\n }\n}\nasync function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {\n const { protected: encodedProtectedHeader, header, payload: inputPayload } = jws, protectedHeader = parsedProtected ?? parseProtectedHeader(encodedProtectedHeader);\n if (!isDisjoint(protectedHeader, header))\n throw new JWSInvalid(\"JWS Protected and JWS Unprotected Header Parameter names must be disjoint\");\n const joseHeader = { ...protectedHeader, ...header }, b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], protectedHeader, joseHeader)), { alg } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n if (shared[0] && !shared[0].has(alg))\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n if (b64) {\n if (typeof inputPayload != \"string\")\n throw new JWSInvalid(\"JWS Payload must be a string\");\n } else if (typeof inputPayload != \"string\" && !(inputPayload instanceof Uint8Array))\n throw new JWSInvalid(\"JWS Payload must be a string or an Uint8Array instance\");\n const signingPayload = b64 || typeof inputPayload != \"string\" ? inputPayload : encodeUnencodedPayload(inputPayload);\n let resolvedKey = !1;\n typeof key == \"function\" && (key = await key(protectedHeader, jws), resolvedKey = !0);\n const entry = jwsAlgorithm(alg), signingInput = concat(encodedProtectedHeader !== void 0 ? encode(encodedProtectedHeader) : new Uint8Array(), encode(\".\"), typeof signingPayload == \"string\" ? shared[2] ??= encodeAsciiMember(signingPayload, \"payload\", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, \"signature\", JWSInvalid), verificationKey = await prepareKey(entry, key, \"verify\"), cryptoKey = await rawKey(verificationKey, entry.subtle, \"verify\");\n entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);\n let verified = !1;\n try {\n verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, signingInput);\n } catch (cause) {\n throw new JWSSignatureVerificationFailed(void 0, { cause });\n }\n if (!verified)\n throw new JWSSignatureVerificationFailed();\n const result = { payload: typeof signingPayload == \"string\" ? decodeBase64url(signingPayload, \"payload\", JWSInvalid) : signingPayload };\n return encodedProtectedHeader !== void 0 && (result.protectedHeader = protectedHeader), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: verificationKey }, b64] : [result, b64];\n}\nasync function verifyCompact(jws, shared, key) {\n if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != \"string\")\n throw new JWSInvalid(\"Compact JWS must be a string or Uint8Array\");\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(\".\");\n if (length !== 3)\n throw new JWSInvalid(\"Invalid Compact JWS\");\n return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);\n}\nexport {\n encodeJsonUnencodedPayload,\n parseProtectedHeader,\n prepareVerify,\n snapshotJws,\n verifyCompact,\n verifySignature\n};\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from \"../util/errors.js\";\nimport { encoder, strictDecoder } from \"./buffer_utils.js\";\nimport { isObject } from \"./validate.js\";\nconst epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = {\n s: 1,\n m: 60,\n h: 3600,\n d: 86400,\n w: 604800,\n y: 31557600\n}, REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = \"check_failed\";\nfunction invalidDuration() {\n throw new TypeError(\"Invalid time period format\");\n}\nfunction secs(str) {\n typeof str != \"string\" && invalidDuration();\n const matched = REGEX.exec(str);\n (!matched || matched[4] && matched[1]) && invalidDuration();\n const value = parseFloat(matched[2]), durationSeconds = Math.round(value * multipliers[matched[3][0].toLowerCase()]);\n return Number.isFinite(durationSeconds) || invalidDuration(), matched[1] === \"-\" || matched[4] === \"ago\" ? -durationSeconds : durationSeconds;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input))\n throw new TypeError(`Invalid ${label} input`);\n return input;\n}\nfunction validateStringClaim(claim, value) {\n if (typeof value != \"string\")\n throw new TypeError(`\"${claim}\" claim must be a string`);\n}\nfunction validateAudienceClaim(value) {\n if (typeof value != \"string\" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != \"string\")))\n throw new TypeError('\"aud\" claim must be a string or an array of strings');\n}\nfunction numericDate(value, label) {\n return typeof value == \"number\" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);\n}\nconst normalizeTyp = (value) => {\n const normalized = value.toLowerCase();\n return value.includes(\"/\") ? normalized : `application/${normalized}`;\n}, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == \"string\" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;\nfunction validateNumericDate(claimsSet, claim, required = !1) {\n const value = claimsSet[claim];\n if (!(value === void 0 && !required)) {\n if (typeof value != \"number\")\n throw new JWTClaimValidationFailed(`\"${claim}\" claim must be a number`, claimsSet, claim, \"invalid\");\n return value;\n }\n}\nfunction unexpectedClaim(claimsSet, claim) {\n throw new JWTClaimValidationFailed(`unexpected \"${claim}\" claim value`, claimsSet, claim, checkFailed);\n}\nfunction validateClaimsSet(protectedHeader, claimsSetBytes, options = {}) {\n let claimsSet;\n try {\n claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));\n } catch (cause) {\n throw new JWTInvalid(\"JWT Claims Set must be a top-level JSON object\", { cause });\n }\n if (!isObject(claimsSet))\n throw new JWTInvalid(\"JWT Claims Set must be a top-level JSON object\");\n const { typ } = options;\n if (typ !== void 0 && (typeof protectedHeader.typ != \"string\" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', claimsSet, \"typ\", checkFailed);\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];\n maxTokenAge !== void 0 && presenceCheck.push(\"iat\"), audience !== void 0 && presenceCheck.push(\"aud\"), subject !== void 0 && presenceCheck.push(\"sub\"), issuer !== void 0 && presenceCheck.push(\"iss\");\n for (const claim of new Set(presenceCheck.reverse()))\n if (!Object.hasOwn(claimsSet, claim))\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, claimsSet, claim, \"missing\");\n issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(claimsSet.iss) && unexpectedClaim(claimsSet, \"iss\"), subject !== void 0 && claimsSet.sub !== subject && unexpectedClaim(claimsSet, \"sub\"), audience !== void 0 && !checkAudiencePresence(claimsSet.aud, typeof audience == \"string\" ? [audience] : audience) && unexpectedClaim(claimsSet, \"aud\");\n const { clockTolerance } = options;\n let tolerance = 0;\n if (typeof clockTolerance == \"string\")\n tolerance = secs(clockTolerance);\n else if (clockTolerance !== void 0) {\n if (typeof clockTolerance != \"number\")\n throw new TypeError(\"Invalid clockTolerance option type\");\n tolerance = clockTolerance;\n }\n if (validateInput(\"clockTolerance option\", tolerance), tolerance < 0)\n throw new TypeError(\"Invalid clockTolerance option input\");\n const { currentDate } = options, now = validateInput(\"currentDate option\", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(claimsSet, \"iat\", maxTokenAge !== void 0), nbf = validateNumericDate(claimsSet, \"nbf\");\n if (nbf !== void 0 && nbf > now + tolerance)\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', claimsSet, \"nbf\", checkFailed);\n const exp = validateNumericDate(claimsSet, \"exp\");\n if (exp !== void 0 && exp <= now - tolerance)\n throw new JWTExpired('\"exp\" claim timestamp check failed', claimsSet, \"exp\", checkFailed);\n if (maxTokenAge !== void 0) {\n const age = now - iat, max = validateInput(\"maxTokenAge option\", typeof maxTokenAge == \"number\" ? maxTokenAge : secs(maxTokenAge));\n if (age - tolerance > max)\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', claimsSet, \"iat\", checkFailed);\n if (age < -tolerance)\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', claimsSet, \"iat\", checkFailed);\n }\n return claimsSet;\n}\nlet producerClaimsSets;\nfunction producerClaimsSet(producer) {\n return producerClaimsSets.get(producer);\n}\nfunction jwtClaimsSetBytes(producer) {\n const claimsSet = producerClaimsSet(producer);\n for (const claim of [\"iat\", \"nbf\", \"exp\"]) {\n const value = claimsSet[claim];\n if (typeof value == \"number\" && !Number.isFinite(value))\n throw new TypeError(`\"${claim}\" claim must be a finite number`);\n }\n return encoder.encode(JSON.stringify(claimsSet));\n}\nfunction jwtClaim(producer, claim) {\n return producerClaimsSet(producer)[claim];\n}\nclass JWTClaimsBuilder {\n constructor(claimsSet = {}) {\n if (!isObject(claimsSet))\n throw new TypeError(\"JWT Claims Set MUST be an object\");\n (producerClaimsSets ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(claimsSet));\n }\n setIssuer(value) {\n return validateStringClaim(\"iss\", value), producerClaimsSet(this).iss = value, this;\n }\n setSubject(value) {\n return validateStringClaim(\"sub\", value), producerClaimsSet(this).sub = value, this;\n }\n setAudience(value) {\n return validateAudienceClaim(value), producerClaimsSet(this).aud = value, this;\n }\n setJti(value) {\n return validateStringClaim(\"jti\", value), producerClaimsSet(this).jti = value, this;\n }\n setNotBefore(value) {\n return producerClaimsSet(this).nbf = numericDate(value, \"setNotBefore\"), this;\n }\n setExpirationTime(value) {\n return producerClaimsSet(this).exp = numericDate(value, \"setExpirationTime\"), this;\n }\n setIssuedAt(value) {\n const claimsSet = producerClaimsSet(this);\n return value === void 0 ? claimsSet.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == \"string\" ? claimsSet.iat = validateInput(\"setIssuedAt\", epoch(/* @__PURE__ */ new Date()) + secs(value)) : claimsSet.iat = numericDate(value, \"setIssuedAt\"), this;\n }\n}\nexport {\n JWTClaimsBuilder,\n jwtClaim,\n jwtClaimsSetBytes,\n secs,\n validateClaimsSet\n};\n","import { prepareVerify, verifyCompact } from \"../lib/jws_verify.js\";\nimport { validateClaimsSet } from \"../lib/jwt_claims_set.js\";\nimport { JWTInvalid } from \"../util/errors.js\";\nasync function jwtVerify(jwt, key, options) {\n const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);\n if (!b64)\n throw new JWTInvalid(\"JWTs MUST NOT use unencoded payload\");\n const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n return { ...verified, payload };\n}\nexport {\n jwtVerify\n};\n","import { jwkToKey, snapshotJwk } from \"../lib/key.js\";\nimport { JWS } from \"../lib/jws_algorithms.js\";\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys } from \"../util/errors.js\";\nimport { isJwkSet } from \"../lib/validate.js\";\nfunction isUsableJWK(jwk, entry, alg, kid) {\n const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;\n return (ext === void 0 || typeof ext == \"boolean\") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == \"string\" && keyOps.indexOf(operation) === index) && keyOps.includes(\"verify\")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == \"string\" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== \"AKP\" : alg === jwkAlg) && (use === void 0 || use === \"sig\") && (!entry.crv || crv === entry.crv);\n}\nasync function importWithAlgCache(cache, jwk, entry) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk), { alg } = entry;\n if (cached[alg] === void 0) {\n const pending = jwkToKey(entry, jwk, !0).then((key) => {\n if (key.type !== \"public\")\n throw new JWKSInvalid(\"JSON Web Key Set members must be public keys\");\n return cached[alg] = key, key;\n }).catch((error) => {\n throw cached[alg] === pending && delete cached[alg], error;\n });\n cached[alg] = pending;\n }\n return cached[alg];\n}\nfunction createLocalJWKSet(jwks) {\n let snapshot;\n try {\n snapshot = structuredClone(jwks);\n } catch (cause) {\n throw new JWKSInvalid(\"JSON Web Key Set malformed\", { cause });\n }\n if (!isJwkSet(snapshot))\n throw new JWKSInvalid(\"JSON Web Key Set malformed\");\n const metadata = snapshot.keys.map((jwk) => {\n const normalized = snapshotJwk(jwk);\n return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;\n }), cached = /* @__PURE__ */ new WeakMap();\n return Object.defineProperty(async (protectedHeader, token) => {\n const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry || entry.secret)\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;\n if (!length)\n throw new JWKSNoMatchingKey();\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n throw error[Symbol.asyncIterator] = async function* () {\n for (const jwk2 of candidates)\n try {\n yield await importWithAlgCache(cached, jwk2, entry);\n } catch {\n }\n }, error;\n }\n return importWithAlgCache(cached, jwk, entry);\n }, \"jwks\", {\n value: () => structuredClone(snapshot)\n });\n}\nexport {\n createLocalJWKSet\n};\n","import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from \"../util/errors.js\";\nimport { createLocalJWKSet } from \"./local.js\";\nimport { isJwkSet } from \"../lib/validate.js\";\nfunction isCloudflareWorkers() {\n return typeof WebSocketPair < \"u\" || typeof navigator < \"u\" && navigator.userAgent === \"Cloudflare-Workers\" || typeof EdgeRuntime < \"u\" && EdgeRuntime === \"vercel\";\n}\nlet USER_AGENT;\n(typeof navigator > \"u\" || !navigator.userAgent?.startsWith?.(\"Mozilla/5.0 \")) && (USER_AGENT = \"jose/v6.2.15\");\nconst customFetch = /* @__PURE__ */ Symbol();\nasync function fetchJwks(url, headers, signal, fetchImpl = fetch) {\n const response = await fetchImpl(url, {\n method: \"GET\",\n signal,\n redirect: \"manual\",\n headers\n }).catch((err) => {\n throw err.name === \"TimeoutError\" ? new JWKSTimeout(void 0, { cause: err }) : err;\n });\n if (response.status !== 200)\n throw new JOSEError(\"Expected 200 OK from the JSON Web Key Set HTTP response\");\n try {\n return await response.json();\n } catch (cause) {\n throw new JOSEError(\"Failed to parse the JSON Web Key Set HTTP response as JSON\", { cause });\n }\n}\nconst jwksCache = /* @__PURE__ */ Symbol();\nfunction isFreshFor(timestamp, duration) {\n return Number.isFinite(timestamp) && Date.now() < timestamp + duration;\n}\nfunction validateDuration(value, fallback, option) {\n if (Number.isNaN(value))\n throw new TypeError(`\"${option}\" option must not be NaN`);\n if (typeof value == \"number\" && value < 0)\n throw new TypeError(`\"${option}\" option must not be negative`);\n return typeof value == \"number\" ? value : fallback;\n}\nfunction createRemoteJWKSet(url, options) {\n if (!(url instanceof URL))\n throw new TypeError(\"url must be an instance of URL\");\n const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;\n if (typeof timeoutOption == \"number\" && (!Number.isInteger(timeoutOption) || timeoutOption < 0))\n throw new TypeError('\"timeoutDuration\" option must be a non-negative integer');\n const timeoutDuration = typeof timeoutOption == \"number\" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, \"cooldownDuration\"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, \"cacheMaxAge\"), headers = new Headers(opts.headers);\n USER_AGENT && !headers.has(\"User-Agent\") && headers.set(\"User-Agent\", USER_AGENT), headers.has(\"accept\") || headers.set(\"accept\", \"application/json, application/jwk-set+json\");\n const fetchImpl = opts[customFetch], cache = opts[jwksCache];\n let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;\n if (cache && typeof cache == \"object\") {\n const { uat, jwks } = cache;\n isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));\n }\n const reload = async () => {\n if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {\n const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {\n const next = createLocalJWKSet(json);\n if (sequence <= appliedSequence)\n return;\n local = next;\n const updatedAt = Date.now();\n cache && (cache.uat = updatedAt, cache.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;\n }).finally(() => {\n pendingFetch === current && (pendingFetch = void 0);\n });\n }\n await pendingFetch;\n };\n return Object.defineProperties(async (protectedHeader, token) => {\n (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();\n try {\n return await local(protectedHeader, token);\n } catch (err) {\n if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration))\n return await reload(), local(protectedHeader, token);\n throw err;\n }\n }, {\n coolingDown: {\n get: () => isFreshFor(jwksTimestamp, cooldownDuration),\n enumerable: !0\n },\n fresh: {\n get: () => isFreshFor(jwksTimestamp, cacheMaxAge),\n enumerable: !0\n },\n reload: {\n value: reload,\n enumerable: !0\n },\n reloading: {\n get: () => !!pendingFetch,\n enumerable: !0\n },\n jwks: {\n value: () => local?.jwks(),\n enumerable: !0\n }\n });\n}\nexport {\n createRemoteJWKSet,\n customFetch,\n jwksCache\n};\n","import { ACCESS_TOKEN_TYPES, AuthVerifyError, MAX_JWT_LENGTH, SIGNING_ALG } from \"@plasgos/auth-shared\";\nimport type { AuthVerifyReason } from \"@plasgos/auth-shared\";\nimport { jwtVerify } from \"jose\";\nimport type { JWTVerifyGetKey } from \"jose\";\n\nimport { isObject } from \"../config.js\";\nimport type { ResolvedVerifierConfig } from \"./config.js\";\nimport { isKeySetUnavailable } from \"./jwks.js\";\nimport { resolveVerifyOptions } from \"./requirements.js\";\nimport type { ResolvedVerifyOptions } from \"./requirements.js\";\nimport type { AccessPrincipal, AuthRejectEvent, VerifiedAccessTokenClaims } from \"./types.js\";\n\n/** Any `Authorization` value that names the Bearer scheme; anything else carries no credentials. */\nconst BEARER_SCHEME = /^Bearer /i;\n/** `Bearer` and a compact JWS (an empty signature segment still matches, so `alg: none` reaches the alg check). */\nconst BEARER_TOKEN = /^Bearer +([A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*)$/i;\n/** A client id or request id that is safe to put into the `onReject` event. */\nconst PLAIN_ID = /^[\\w.:-]{1,128}$/;\nconst MAX_PUBLIC_ID_LENGTH = 128;\nconst ACCEPTED_TYPES: readonly string[] = ACCESS_TOKEN_TYPES;\n\n/** What a verifier holds: its checked options and its key resolver. */\nexport interface VerifierState {\n readonly config: ResolvedVerifierConfig;\n readonly keySet: JWTVerifyGetKey;\n}\n\n/** A refusal before it becomes an `AuthVerifyError`: the reason, and the client id once the signature passed. */\ninterface Refusal {\n readonly reason: AuthVerifyReason;\n readonly clientId: string | null;\n}\n\ntype Outcome = { readonly principal: AccessPrincipal; readonly refusal?: never } | { readonly refusal: Refusal };\n\nconst refuse = (reason: AuthVerifyReason, clientId: string | null = null): Outcome => ({ refusal: { reason, clientId } });\n\nconst nonEmptyString = (value: unknown): value is string => typeof value === \"string\" && value !== \"\";\nconst plainId = (value: unknown): string | null => (typeof value === \"string\" && PLAIN_ID.test(value) ? value : null);\n\n/** The protected header as a JSON object, or null when the segment is not base64url UTF-8 JSON of an object. */\nfunction decodeHeader(segment: string): Record<string, unknown> | null {\n try {\n const json: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.from(segment, \"base64url\")));\n return isObject(json) ? json : null;\n } catch {\n return null;\n }\n}\n\n/** A string property of an error, read only to choose a reason; nothing of the error is kept. */\nfunction field(error: unknown, name: string): unknown {\n return isObject(error) || error instanceof Error ? (error as unknown as Record<string, unknown>)[name] : undefined;\n}\n\n/**\n * The reason for an error of the key lookup or of `jwtVerify`, by jose's `code` string (never by\n * `instanceof`, so it holds across bundled copies of jose). Anything not named here is `invalid_token`.\n */\nfunction reasonOfVerifyError(error: unknown): AuthVerifyReason {\n if (isKeySetUnavailable(error)) return \"unavailable\";\n switch (field(error, \"code\")) {\n case \"ERR_JWKS_NO_MATCHING_KEY\":\n return \"unknown_key\";\n case \"ERR_JWT_EXPIRED\":\n return \"expired_token\";\n case \"ERR_JWT_INVALID\":\n // The payload is not a JSON object.\n return \"malformed_token\";\n case \"ERR_JWT_CLAIM_VALIDATION_FAILED\": {\n const claim = field(error, \"claim\");\n if (claim === \"nbf\" && field(error, \"reason\") === \"check_failed\") return \"expired_token\";\n // `exp` missing or not a number: the claims are not those of an access token.\n if (claim === \"exp\") return \"invalid_claims\";\n return \"invalid_token\";\n }\n default:\n return \"invalid_token\";\n }\n}\n\n/** True when the claim is present with a value: an own property that is neither `null` nor `\"\"`. */\nconst hasClaim = (payload: Record<string, unknown>, name: string): boolean =>\n Object.hasOwn(payload, name) && payload[name] !== null && payload[name] !== \"\";\n\n/** The principal for verified claims, or the refusal of claims that are not those of an accepted token. */\nfunction principalOf(\n config: ResolvedVerifierConfig,\n payload: Record<string, unknown>,\n options: ResolvedVerifyOptions,\n): Outcome {\n const clientId = plainId(payload[\"client_id\"]);\n const invalid = (): Outcome => refuse(\"invalid_claims\", clientId);\n const { aud, sub, client_id: client, scope, sid, auth_time: authTime, cv } = payload;\n const publicId = payload[\"plasgos_public_id\"];\n // Exactly this audience: a token minted for several resources is refused.\n if (aud !== config.audience || !nonEmptyString(sub) || !nonEmptyString(client)) return invalid();\n if (scope !== undefined && typeof scope !== \"string\") return invalid();\n if (publicId !== undefined && !(nonEmptyString(publicId) && publicId.length <= MAX_PUBLIC_ID_LENGTH)) return invalid();\n\n const isUser = sid !== undefined;\n if (isUser) {\n if (!nonEmptyString(sid)) return invalid();\n if (typeof authTime !== \"number\" || !Number.isSafeInteger(authTime) || authTime < 0) return invalid();\n if (cv !== undefined && !Number.isSafeInteger(cv)) return invalid();\n } else if (!config.allowServiceTokens || sub !== client || typeof scope !== \"string\") {\n // A token without sid is a service token only when sub is the client and it carries scopes; an\n // offline user token (sub is the user) is never accepted.\n return invalid();\n }\n\n const required = [...config.requiredClaims, ...options.requireClaims];\n if (isUser && config.requireCredentialVersion) required.push(\"cv\");\n if (!required.every((name) => hasClaim(payload, name))) return invalid();\n\n const scopes = Object.freeze(typeof scope === \"string\" ? scope.split(\" \").filter((item) => item !== \"\") : []);\n const claims = Object.freeze({ ...payload }) as VerifiedAccessTokenClaims;\n const principal: AccessPrincipal = isUser\n ? {\n kind: \"user\",\n subject: sub,\n clientId: client,\n sessionId: sid,\n authTime: authTime as number,\n credentialVersion: (cv as number | undefined) ?? null,\n scopes,\n claims,\n }\n : { kind: \"service\", subject: sub, clientId: client, scopes, claims };\n return { principal: Object.freeze(principal) };\n}\n\n/** Runs the checks in order and returns the principal or the first refusal. `isRevoked` errors propagate. */\nasync function check(state: VerifierState, header: unknown, options: ResolvedVerifyOptions): Promise<Outcome> {\n const { config } = state;\n // 1–2. Token shape and size.\n if (typeof header !== \"string\" || !BEARER_SCHEME.test(header)) return refuse(\"missing_token\");\n if (header.length > MAX_JWT_LENGTH + \"Bearer \".length) return refuse(\"malformed_token\");\n const token = BEARER_TOKEN.exec(header)?.[1];\n if (token === undefined) return refuse(\"malformed_token\");\n\n // 3. The protected header, before any key lookup: alg none and HS* never reach verification.\n const protectedHeader = decodeHeader(token.slice(0, token.indexOf(\".\")));\n if (protectedHeader === null) return refuse(\"malformed_token\");\n const { alg, kid, typ } = protectedHeader;\n if (alg !== SIGNING_ALG || !nonEmptyString(kid)) return refuse(\"unknown_key\");\n if (typeof typ !== \"string\" || !ACCEPTED_TYPES.includes(typ.toLowerCase())) return refuse(\"invalid_claims\");\n\n // 4–5. Key, signature, iss, aud, exp, nbf.\n const nowMs = options.now ?? Date.now();\n let payload: Record<string, unknown>;\n try {\n ({ payload } = await jwtVerify(token, state.keySet, {\n algorithms: [SIGNING_ALG],\n issuer: config.issuer,\n audience: config.audience,\n clockTolerance: config.clockToleranceSeconds,\n requiredClaims: [\"exp\"],\n currentDate: new Date(nowMs),\n }));\n } catch (error) {\n // The error is dropped here: jose's claim errors hold the payload.\n return refuse(reasonOfVerifyError(error));\n }\n\n // 6. Claims and required claims.\n const outcome = principalOf(config, payload, options);\n if (outcome.refusal !== undefined) return outcome;\n const { principal } = outcome;\n const clientId = plainId(principal.clientId);\n\n // 7. Revocation, before scope: a revoked session is always told to sign in again.\n if (config.isRevoked !== undefined) {\n const revoked: unknown = await config.isRevoked(principal);\n if (typeof revoked !== \"boolean\") throw new TypeError(\"isRevoked must return a boolean\");\n if (revoked) return refuse(\"revoked\", clientId);\n }\n\n // 8. Every required scope.\n if (!options.scopes.every((scope) => principal.scopes.includes(scope))) return refuse(\"insufficient_scope\", clientId);\n\n // 9. Recent login.\n if (options.maxAuthAge !== null) {\n if (principal.kind !== \"user\" || Math.floor(nowMs / 1000) - principal.authTime > options.maxAuthAge) {\n return refuse(\"stale_auth\", clientId);\n }\n }\n return outcome;\n}\n\n/** Calls `onReject` once; a throw or a rejection of the hook is swallowed. */\nfunction report(config: ResolvedVerifierConfig, refusal: Refusal, requestId: string | null): void {\n const { onReject } = config;\n if (onReject === undefined) return;\n const event: AuthRejectEvent = Object.freeze({\n environment: config.environment,\n reason: refusal.reason,\n clientId: refusal.clientId,\n requestId: plainId(requestId),\n });\n try {\n Promise.resolve(onReject(event)).catch(() => undefined);\n } catch {\n // The hook's own failure never changes the answer.\n }\n}\n\n/**\n * Verifies one `Authorization` header value against the verifier's state: the principal, or a rejection\n * with `AuthVerifyError` (after `onReject`), a `TypeError` for invalid `options`, or the app's own\n * `isRevoked` error.\n *\n * @example\n * const principal = await verifyAccessToken(state, request.headers.get(\"authorization\"), { scopes: [\"crm:access\"] });\n */\nexport async function verifyAccessToken(\n state: VerifierState,\n header: unknown,\n rawOptions: unknown,\n headerRequestId: string | null = null,\n): Promise<AccessPrincipal> {\n const options = resolveVerifyOptions(rawOptions);\n const outcome = await check(state, header, options);\n if (outcome.refusal === undefined) return outcome.principal;\n const error = new AuthVerifyError(outcome.refusal.reason, {\n requiredScopes: options.scopes,\n ...(options.maxAuthAge !== null ? { maxAuthAge: options.maxAuthAge } : {}),\n });\n report(state.config, outcome.refusal, options.requestId !== undefined ? options.requestId : headerRequestId);\n throw error;\n}\n","// The checks of a route's requirements (`VerifyOptions`). No jose import: the framework adapters use\n// this file to check their requirements when a middleware or guard is created.\nimport { isObject } from \"../config.js\";\nimport { CLAIM_NAME, MAX_REQUIRED_CLAIMS } from \"./config.js\";\n\n/** An RFC 6749 §3.3 scope token: printable ASCII without space, `\"` and `\\`, so it fits a quoted challenge. */\nconst SCOPE_TOKEN = /^[\\x21\\x23-\\x5B\\x5D-\\x7E]+$/;\n\n/**\n * The checked requirements of one verification.\n *\n * @example\n * const requirements = resolveRequirements(\"verify\", { scopes: [\"crm:access\"] });\n */\nexport interface ResolvedRequirements {\n readonly scopes: readonly string[];\n readonly requireClaims: readonly string[];\n readonly maxAuthAge: number | null;\n}\n\n/** The checked requirements and the per-call fields of `VerifyOptions`. */\nexport interface ResolvedVerifyOptions extends ResolvedRequirements {\n /** `undefined` when the caller gave none. */\n readonly requestId: string | null | undefined;\n /** Epoch milliseconds, or null for `Date.now()`. */\n readonly now: number | null;\n}\n\n/**\n * Checks the route requirements (`scopes`, `requireClaims`, `maxAuthAge`) of plain JavaScript input.\n * Throws `TypeError` (`<label>: <field> must be …`) that names the field, never the value.\n *\n * @example\n * resolveRequirements(\"requirePlasgosToken\", { scopes: [\"crm:access\"], maxAuthAge: 600 });\n */\nexport function resolveRequirements(label: string, raw: unknown): ResolvedRequirements {\n if (raw === undefined) return { scopes: [], requireClaims: [], maxAuthAge: null };\n if (!isObject(raw)) throw new TypeError(`${label}: options must be an object`);\n const { scopes, requireClaims, maxAuthAge } = raw;\n if (\n scopes !== undefined &&\n (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === \"string\" && SCOPE_TOKEN.test(scope)))\n ) {\n throw new TypeError(`${label}: scopes must be a list of scope tokens`);\n }\n if (\n requireClaims !== undefined &&\n (!Array.isArray(requireClaims) ||\n requireClaims.length > MAX_REQUIRED_CLAIMS ||\n !requireClaims.every((name) => typeof name === \"string\" && CLAIM_NAME.test(name)))\n ) {\n throw new TypeError(`${label}: requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`);\n }\n if (maxAuthAge !== undefined && (typeof maxAuthAge !== \"number\" || !Number.isSafeInteger(maxAuthAge) || maxAuthAge <= 0)) {\n throw new TypeError(`${label}: maxAuthAge must be a positive safe integer`);\n }\n return {\n scopes: Object.freeze([...new Set((scopes ?? []) as string[])]),\n requireClaims: Object.freeze([...new Set((requireClaims ?? []) as string[])]),\n maxAuthAge: maxAuthAge ?? null,\n };\n}\n\n/**\n * Checks `VerifyOptions`: the requirements, plus `requestId` (a string, null or absent) and `now`\n * (finite epoch milliseconds). Throws `TypeError` without the value.\n *\n * @example\n * const options = resolveVerifyOptions(raw); // inside verifyAuthorization\n */\nexport function resolveVerifyOptions(raw: unknown): ResolvedVerifyOptions {\n const requirements = resolveRequirements(\"verify\", raw);\n const fields = isObject(raw) ? raw : {};\n const { requestId, now } = fields;\n if (requestId !== undefined && requestId !== null && typeof requestId !== \"string\") {\n throw new TypeError(\"verify: requestId must be a string\");\n }\n if (now !== undefined && (typeof now !== \"number\" || !Number.isFinite(now))) {\n throw new TypeError(\"verify: now must be a finite number\");\n }\n return { ...requirements, requestId, now: now ?? null };\n}\n","import { isObject } from \"../config.js\";\nimport { resolveVerifierConfig } from \"./config.js\";\nimport { remoteKeySet, staticKeySet } from \"./jwks.js\";\nimport type {\n AccessPrincipal,\n AccessTokenVerifier,\n AccessTokenVerifierOptions,\n VerifyOptions,\n} from \"./types.js\";\nimport { verifyAccessToken } from \"./verify.js\";\nimport type { VerifierState } from \"./verify.js\";\n\n/** The request's `Authorization` and `X-Request-Id`, or a TypeError when `request` is not a Web Request. */\nfunction headersOf(request: unknown): { authorization: string | null; requestId: string | null } {\n const headers: unknown = isObject(request) ? request[\"headers\"] : undefined;\n if (!isObject(headers) || typeof headers[\"get\"] !== \"function\") {\n throw new TypeError(\"verifyRequest: request must be a Web Request\");\n }\n const get = (name: string): string | null => {\n const value: unknown = (headers[\"get\"] as (name: string) => unknown).call(headers, name);\n return typeof value === \"string\" ? value : null;\n };\n return { authorization: get(\"authorization\"), requestId: get(\"x-request-id\") };\n}\n\n/**\n * Creates the verifier of Plasgos JWT access tokens (RFC 9068) for one API, identified by its\n * `audience`. The options are checked once, here: a wrong option throws one `ConfigError` (from\n * `@plasgos/auth-shared`, re-exported by this package) that lists every problem, so a misconfigured\n * app stops at start.\n *\n * Required options: `environment`, `issuer`, `audience`, and `isRevoked` for an audience whose path is\n * `/crm`. Keys come from `<backchannelUrl ?? issuer>/oidc/jwks` (cached; or the sandbox-only `jwks`).\n *\n * Each verification checks, in this order: the `Authorization` header (`missing_token`,\n * `malformed_token`), the protected header (`alg` RS256 and a `kid`, else `unknown_key`; `typ` `at+jwt`,\n * else `invalid_claims`), the key (`unknown_key`, or `unavailable` when the key set cannot be read),\n * the signature, `iss` and `aud` (`invalid_token`), `exp`/`nbf` (`expired_token`), the claims and the\n * required claims (`invalid_claims`), `isRevoked` (`revoked`), the route's scopes\n * (`insufficient_scope`) and its `maxAuthAge` (`stale_auth`). A refusal rejects with `AuthVerifyError`,\n * which carries the HTTP answer (see `authErrorResponse`). An error thrown by `isRevoked`, or a\n * non-boolean result (`TypeError`), rejects the verification as is: answer it as a server error, not\n * a 401. Invalid `VerifyOptions` reject with `TypeError`.\n *\n * With `allowServiceTokens: true` the principal is `AccessPrincipal` (user or service); otherwise it\n * is always a `UserAccessPrincipal`.\n *\n * @example\n * import { createAccessTokenVerifier } from \"@plasgos/auth-verify\";\n *\n * const verifier = createAccessTokenVerifier({\n * environment: \"production\",\n * issuer: \"https://accounts.plasgos.co.id\",\n * audience: \"https://api.plasgos.co.id/crm\",\n * requireClaims: [\"plasgos_public_id\", \"cv\"],\n * isRevoked: async (principal) => sessionIsRevoked(principal.sessionId, principal.credentialVersion),\n * });\n * const principal = await verifier.verifyRequest(request, { scopes: [\"crm:access\"] });\n * principal.claims.plasgos_public_id; // the user's public id\n */\n// User-only first: options without `allowServiceTokens: true` stop here. The explicit `false` keeps\n// `AccessTokenVerifierOptions<AccessPrincipal>` (a flag typed `boolean`) out of this overload.\nexport function createAccessTokenVerifier(\n options: AccessTokenVerifierOptions & { allowServiceTokens?: false | undefined },\n): AccessTokenVerifier;\nexport function createAccessTokenVerifier(\n options: AccessTokenVerifierOptions<AccessPrincipal>,\n): AccessTokenVerifier<AccessPrincipal>;\nexport function createAccessTokenVerifier(\n options: AccessTokenVerifierOptions<AccessPrincipal> | AccessTokenVerifierOptions,\n): AccessTokenVerifier<AccessPrincipal> {\n const config = resolveVerifierConfig(options);\n const state: VerifierState = {\n config,\n keySet: config.jwks !== null ? staticKeySet(config.jwks) : remoteKeySet(config),\n };\n return Object.freeze({\n environment: config.environment,\n issuer: config.issuer,\n audience: config.audience,\n verifyAuthorization: (header: string | null | undefined, verifyOptions?: VerifyOptions) =>\n verifyAccessToken(state, header, verifyOptions),\n verifyRequest: async (request: Request, verifyOptions?: VerifyOptions) => {\n const { authorization, requestId } = headersOf(request);\n return verifyAccessToken(state, authorization, verifyOptions, requestId);\n },\n });\n}\n","import { AuthVerifyError } from \"@plasgos/auth-shared\";\nimport { HttpException, Inject, Injectable } from \"@nestjs/common\";\nimport type { CanActivate, ExecutionContext } from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport { authRefusalOf } from \"../core/response.js\";\nimport type { AuthRefusal } from \"../core/response.js\";\nimport type { AccessPrincipal, AccessTokenVerifier, VerifyOptions } from \"../core/types.js\";\nimport { PLASGOS_ACCESS_TOKEN_VERIFIER, RECENT_AUTH_KEY, REQUIRED_SCOPES_KEY } from \"./tokens.js\";\n\ninterface RequestLike {\n headers?: Readonly<Record<string, unknown>>;\n plasgosPrincipal?: AccessPrincipal;\n}\n\n/**\n * The answer of an `AuthVerifyError`, also one loaded through the other module system (same name);\n * null for any other error, including one that only borrows the name but has no known status.\n */\nfunction refusalOf(error: unknown): AuthRefusal | null {\n const named = error instanceof AuthVerifyError || (error instanceof Error && error.name === \"AuthVerifyError\");\n return named ? authRefusalOf(error) : null;\n}\n\n/** Sets a response header on an Express response (`setHeader`) or a Fastify reply (`header`). */\nfunction setHeader(response: unknown, name: string, value: string): void {\n if (typeof response !== \"object\" || response === null) return;\n const target = response as { setHeader?: unknown; header?: unknown };\n if (typeof target.setHeader === \"function\") (target.setHeader as (n: string, v: string) => unknown).call(response, name, value);\n else if (typeof target.header === \"function\") (target.header as (n: string, v: string) => unknown).call(response, name, value);\n}\n\n/**\n * A NestJS guard that lets a request through only with a valid Plasgos access token. It uses the\n * verifier that `PlasgosAuthModule.forRoot` or `forRootAsync` provides, and the route requirements of\n * `@RequireScopes` (class and method scopes add up) and `@RequireRecentAuth` (the method overrides the\n * class). It reads `Authorization` and `X-Request-Id` (for the verifier's `onReject` event).\n *\n * - Token accepted: stores the principal on the request (read it with `@PlasgosPrincipal()`) and lets\n * the request through.\n * - Token refused (`AuthVerifyError`): sets `Cache-Control: no-store`, and `WWW-Authenticate` when the\n * error has a challenge, on the response (Express and Fastify), and throws\n * `HttpException({ error: errorCode }, status)`, so Nest answers 401, 403 or 503 with that JSON body.\n * An app-wide exception filter that rewrites `HttpException` answers also rewrites this body.\n * - Any other error (for example one thrown by your `isRevoked`) propagates unchanged to Nest's\n * exception layer.\n *\n * @example\n * @Controller(\"contacts\")\n * @UseGuards(PlasgosAccessTokenGuard)\n * @RequireScopes(\"crm:access\")\n * export class ContactsController {\n * @Get()\n * list(@PlasgosPrincipal() principal: UserAccessPrincipal) {\n * return this.contacts.list(principal.claims.plasgos_public_id);\n * }\n * }\n */\nexport class PlasgosAccessTokenGuard implements CanActivate {\n constructor(\n private readonly verifier: AccessTokenVerifier<AccessPrincipal>,\n private readonly reflector: Reflector,\n ) {}\n\n /**\n * Verifies the request's token against the route requirements. Resolves `true`, or rejects with an\n * `HttpException` for a refused token, or with the verifier's own non-token error.\n *\n * @example\n * const allowed = await guard.canActivate(context);\n */\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const targets = [context.getHandler(), context.getClass()];\n const scopes = this.reflector.getAllAndMerge<string[]>(REQUIRED_SCOPES_KEY, targets);\n const maxAuthAge = this.reflector.getAllAndOverride<number | undefined>(RECENT_AUTH_KEY, targets);\n const http = context.switchToHttp();\n const request = http.getRequest<RequestLike>();\n const authorization = request.headers?.[\"authorization\"];\n const requestId = request.headers?.[\"x-request-id\"];\n const options: VerifyOptions = {\n ...(scopes.length > 0 ? { scopes: [...new Set(scopes)] } : {}),\n ...(maxAuthAge !== undefined ? { maxAuthAge } : {}),\n ...(typeof requestId === \"string\" ? { requestId } : {}),\n };\n let principal: AccessPrincipal;\n try {\n principal = await this.verifier.verifyAuthorization(typeof authorization === \"string\" ? authorization : undefined, options);\n } catch (error) {\n const refusal = refusalOf(error);\n if (refusal === null) throw error;\n const response = http.getResponse<unknown>();\n setHeader(response, \"Cache-Control\", \"no-store\");\n if (refusal.wwwAuthenticate !== null) setHeader(response, \"WWW-Authenticate\", refusal.wwwAuthenticate);\n throw new HttpException({ error: refusal.errorCode }, refusal.status);\n }\n request.plasgosPrincipal = principal;\n return true;\n }\n}\n\n// Decorators applied by calling them, so the package needs no decorator syntax or emitted metadata;\n// every constructor parameter names its injection token.\nInjectable()(PlasgosAccessTokenGuard);\nInject(PLASGOS_ACCESS_TOKEN_VERIFIER)(PlasgosAccessTokenGuard, undefined, 0);\nInject(Reflector)(PlasgosAccessTokenGuard, undefined, 1);\n","import { AUTH_VERIFY_REASONS } from \"@plasgos/auth-shared\";\nimport type { AuthVerifyError } from \"@plasgos/auth-shared\";\n\nimport { isObject } from \"../config.js\";\n\nconst STATUSES: readonly unknown[] = [401, 403, 503];\nconst ERROR_CODES: readonly unknown[] = [\n \"invalid_token\",\n \"insufficient_scope\",\n \"insufficient_user_authentication\",\n \"temporarily_unavailable\",\n];\nconst REASONS: readonly unknown[] = AUTH_VERIFY_REASONS;\n\n/** The answer to a refused token, read from an `AuthVerifyError`'s fields. */\nexport interface AuthRefusal {\n readonly status: 401 | 403 | 503;\n readonly errorCode: string;\n readonly wwwAuthenticate: string | null;\n}\n\n/**\n * The answer fields of `error` when it has the shape of an `AuthVerifyError` (a known reason, status\n * and error code, and a string or null challenge), else null. It reads fields, not the class, so an\n * error loaded through the other module system works too; the adapters use it so that an error that\n * only borrows the name never reaches `res.status`.\n *\n * @example\n * const refusal = authRefusalOf(error);\n * if (refusal === null) throw error;\n */\nexport function authRefusalOf(error: unknown): AuthRefusal | null {\n const fields = isObject(error) || error instanceof Error ? (error as unknown as Record<string, unknown>) : null;\n if (fields === null) return null;\n const challenge = fields[\"wwwAuthenticate\"];\n if (\n !REASONS.includes(fields[\"reason\"]) ||\n !STATUSES.includes(fields[\"status\"]) ||\n !ERROR_CODES.includes(fields[\"errorCode\"]) ||\n (challenge !== null && typeof challenge !== \"string\")\n ) {\n return null;\n }\n return {\n status: fields[\"status\"] as AuthRefusal[\"status\"],\n errorCode: fields[\"errorCode\"] as string,\n wwwAuthenticate: challenge,\n };\n}\n\n/**\n * The HTTP answer to a refused token, for servers built on Web `Request`/`Response` (fetch handlers,\n * Hono, React Router, Next.js route handlers): the error's `status` (401, 403 or 503), its\n * `WWW-Authenticate` challenge when it has one, `Cache-Control: no-store`, and the JSON body\n * `{\"error\":\"<errorCode>\"}`. It reads the error's fields, so an `AuthVerifyError` loaded through the\n * other module system (ESM and CommonJS in one app) works too. Throws `TypeError` for anything that is\n * not an `AuthVerifyError`: rethrow such errors instead of answering them.\n *\n * @example\n * import { AuthVerifyError, authErrorResponse } from \"@plasgos/auth-verify\";\n *\n * try {\n * const principal = await verifier.verifyRequest(request, { scopes: [\"crm:access\"] });\n * return Response.json({ id: principal.claims.plasgos_public_id });\n * } catch (error) {\n * if (error instanceof AuthVerifyError) return authErrorResponse(error);\n * throw error;\n * }\n */\nexport function authErrorResponse(error: AuthVerifyError): Response {\n const refusal = authRefusalOf(error);\n if (refusal === null) throw new TypeError(\"authErrorResponse: error must be an AuthVerifyError\");\n const headers = new Headers({ \"content-type\": \"application/json\", \"cache-control\": \"no-store\" });\n if (refusal.wwwAuthenticate !== null) headers.set(\"www-authenticate\", refusal.wwwAuthenticate);\n return new Response(JSON.stringify({ error: refusal.errorCode }), { status: refusal.status, headers });\n}\n","// Strings, never Symbol()s: a symbol made in a module would differ between the ESM and CommonJS copies\n// of this entry, and Nest would not find the provider.\n\n/**\n * The injection token of the `AccessTokenVerifier` that `PlasgosAuthModule` provides.\n *\n * @example\n * constructor(@Inject(PLASGOS_ACCESS_TOKEN_VERIFIER) private readonly verifier: AccessTokenVerifier) {}\n */\nexport const PLASGOS_ACCESS_TOKEN_VERIFIER = \"PLASGOS_ACCESS_TOKEN_VERIFIER\";\n\n/** Metadata key of `@RequireScopes`. */\nexport const REQUIRED_SCOPES_KEY = \"plasgos:required-scopes\";\n/** Metadata key of `@RequireRecentAuth`. */\nexport const RECENT_AUTH_KEY = \"plasgos:recent-auth\";\n","import { SetMetadata, createParamDecorator } from \"@nestjs/common\";\nimport type { CustomDecorator, ExecutionContext } from \"@nestjs/common\";\n\nimport { resolveRequirements } from \"../core/requirements.js\";\nimport type { AccessPrincipal } from \"../core/types.js\";\nimport { RECENT_AUTH_KEY, REQUIRED_SCOPES_KEY } from \"./tokens.js\";\n\n/** The default of `@RequireRecentAuth()`: the user signed in within the last 10 minutes. */\nconst DEFAULT_RECENT_AUTH_SECONDS = 600;\n\n/**\n * Requires scopes on a controller or a route; `PlasgosAccessTokenGuard` refuses a token that lacks any\n * of them with 403 `insufficient_scope`. Scopes on the class and on the method add up. Throws\n * `TypeError` at decoration time without a scope, or for a value that is not an OAuth scope token.\n *\n * @example\n * @Controller(\"contacts\")\n * @UseGuards(PlasgosAccessTokenGuard)\n * @RequireScopes(\"crm:access\")\n * export class ContactsController {}\n */\nexport function RequireScopes(...scopes: string[]): CustomDecorator {\n if (scopes.length === 0) throw new TypeError(\"RequireScopes: give at least one scope\");\n const { scopes: checked } = resolveRequirements(\"RequireScopes\", { scopes });\n return SetMetadata(REQUIRED_SCOPES_KEY, checked);\n}\n\n/**\n * Requires a recent login on a controller or a route: `PlasgosAccessTokenGuard` refuses a token whose\n * `auth_time` is older than `maxAgeSeconds` (default 600) with 401 `insufficient_user_authentication`\n * and `max_age=<seconds>` in `WWW-Authenticate`. The value on the method overrides the one on the\n * class. Throws `TypeError` at decoration time when `maxAgeSeconds` is not a positive integer.\n *\n * @example\n * @Post(\"export\")\n * @RequireRecentAuth(300)\n * exportContacts() {}\n */\nexport function RequireRecentAuth(maxAgeSeconds: number = DEFAULT_RECENT_AUTH_SECONDS): CustomDecorator {\n const raw: unknown = maxAgeSeconds;\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw <= 0) {\n throw new TypeError(\"RequireRecentAuth: maxAgeSeconds must be a positive safe integer\");\n }\n return SetMetadata(RECENT_AUTH_KEY, raw);\n}\n\nconst principalParam = createParamDecorator((_data: unknown, context: ExecutionContext): AccessPrincipal => {\n const request = context.switchToHttp().getRequest<{ plasgosPrincipal?: AccessPrincipal | undefined }>();\n const principal = request.plasgosPrincipal;\n if (principal === undefined) {\n throw new Error(\"PlasgosPrincipal: PlasgosAccessTokenGuard did not run for this request\");\n }\n return principal;\n});\n\n/**\n * Injects the principal that `PlasgosAccessTokenGuard` verified into a route parameter. On a route\n * without the guard it throws `Error` (a wiring mistake, answered with 500).\n *\n * @example\n * @Get(\"me\")\n * me(@PlasgosPrincipal() principal: UserAccessPrincipal) {\n * return { publicId: principal.claims.plasgos_public_id };\n * }\n */\nexport const PlasgosPrincipal = (): ParameterDecorator => principalParam();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,iBAAuB;;;ACShB,IAAM,WAAW,CAAC,UACvB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAQ9D,IAAM,UAAU,CAAC,UAA4B,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM;AA4B3F,SAAS,eAAe,UAAoB,KAAcC,QAAe,OAA6B;AAC3G,MAAI,QAAQ,OAAW,QAAO,MAAM;AACpC,MAAI,OAAO,QAAQ,YAAY,OAAO,cAAc,GAAG,KAAK,OAAO,MAAM,OAAO,OAAO,MAAM,IAAK,QAAO;AACzG,WAAS,KAAK,GAAGA,MAAK,4BAA4B,OAAO,MAAM,GAAG,CAAC,OAAO,OAAO,MAAM,GAAG,CAAC,EAAE;AAC7F,SAAO,MAAM;AACf;AASO,SAAS,iBAAiB,UAAoB,KAAcA,QAA4D;AAC7H,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI,OAAO,QAAQ,WAAY,QAAO;AACtC,WAAS,KAAK,GAAGA,MAAK,qBAAqB;AAC3C,SAAO;AACT;;;ACjEA,yBAAgG;AAOhG,IAAM,kCAAkC;AACxC,IAAM,8BAA8B;AACpC,IAAM,kBAAkB;AACxB,IAAM,iBAAiB;AAEhB,IAAM,sBAAsB;AAE5B,IAAM,aAAa;AAE1B,IAAM,0BAA0B;AAEhC,IAAM,UAAU;AAAA,EACd,OAAO;AAAA,EACP,mBAAmB;AAAA,EACnB,eAAe,2CAA2C,OAAO,mBAAmB,CAAC;AAAA,EACrF,MAAM;AAAA,EACN,iBAAiB;AACnB;AA6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AC,sBAA6C;","names":["import_common","field","field","fetch","import_auth_shared","message","message","isObject","message","parsed","isObject","isObject","isObject","cache","cache","isObject","import_auth_shared","invalid","import_auth_shared","import_auth_shared","module","import_common","import_auth_shared"]}
@@ -0,0 +1,153 @@
1
+ import { DynamicModule, ModuleMetadata, FactoryProvider, CanActivate, ExecutionContext, CustomDecorator } from '@nestjs/common';
2
+ import { A as AccessPrincipal, U as UserAccessPrincipal, b as AccessTokenVerifierOptions, a as AccessTokenVerifier } from './types-CGtRnj59.cjs';
3
+ export { S as ServiceAccessPrincipal, V as VerifiedAccessTokenClaims } from './types-CGtRnj59.cjs';
4
+ import { Reflector } from '@nestjs/core';
5
+ export { AuthVerifyError, AuthVerifyReason, ConfigError } from '@plasgos/auth-shared';
6
+
7
+ /** Options for one API: user tokens only, or both kinds with `allowServiceTokens: true`. */
8
+ type ModuleOptions = AccessTokenVerifierOptions | AccessTokenVerifierOptions<AccessPrincipal>;
9
+ /**
10
+ * The options of `PlasgosAuthModule.forRootAsync`: a factory that returns the verifier options, its
11
+ * injected providers and the modules that export them.
12
+ *
13
+ * @example
14
+ * PlasgosAuthModule.forRootAsync({
15
+ * imports: [ConfigModule],
16
+ * inject: [ConfigService],
17
+ * useFactory: (config: ConfigService) => ({ environment: "production", issuer: config.get("ISSUER"), audience: config.get("AUDIENCE") }),
18
+ * });
19
+ */
20
+ interface PlasgosAuthModuleAsyncOptions {
21
+ /** Modules that export the providers `inject` names. */
22
+ imports?: ModuleMetadata["imports"] | undefined;
23
+ /** Providers passed to `useFactory`, in order. */
24
+ inject?: FactoryProvider["inject"] | undefined;
25
+ /** Returns the options of `createAccessTokenVerifier`, or a promise of them. */
26
+ useFactory: (...args: never[]) => ModuleOptions | Promise<ModuleOptions>;
27
+ }
28
+ /**
29
+ * A global NestJS module that provides the access-token verifier under `PLASGOS_ACCESS_TOKEN_VERIFIER`
30
+ * and `PlasgosAccessTokenGuard` to the whole app. Import it once, in the root module. The verifier is
31
+ * created with `createAccessTokenVerifier` when Nest builds the module, so a wrong option stops the
32
+ * app at start with one `ConfigError` listing every problem.
33
+ *
34
+ * @example
35
+ * @Module({
36
+ * imports: [
37
+ * PlasgosAuthModule.forRoot({
38
+ * environment: "production",
39
+ * issuer: "https://accounts.plasgos.co.id",
40
+ * audience: "https://api.plasgos.co.id/crm",
41
+ * requireClaims: ["plasgos_public_id", "cv"],
42
+ * isRevoked: (principal) => revocations.isRevoked(principal),
43
+ * }),
44
+ * ],
45
+ * })
46
+ * export class AppModule {}
47
+ */
48
+ declare class PlasgosAuthModule {
49
+ /**
50
+ * The module with fixed options (the options of `createAccessTokenVerifier`). By default the options
51
+ * are user-only and `isRevoked` receives a `UserAccessPrincipal`; to accept service tokens too, name
52
+ * the principal type: `forRoot<AccessPrincipal>({ …, allowServiceTokens: true })`.
53
+ *
54
+ * @example
55
+ * PlasgosAuthModule.forRoot({ environment: "sandbox", issuer, audience, isRevoked: () => false });
56
+ */
57
+ static forRoot<P extends AccessPrincipal = UserAccessPrincipal>(options: AccessTokenVerifierOptions<P>): DynamicModule;
58
+ /**
59
+ * The module with options from a factory, for example from a config service. A `ConfigError` from
60
+ * the returned options, or an error of the factory, fails the app's start.
61
+ *
62
+ * @example
63
+ * PlasgosAuthModule.forRootAsync({ inject: [ConfigService], useFactory: (config: ConfigService) => config.get("plasgos") });
64
+ */
65
+ static forRootAsync(options: PlasgosAuthModuleAsyncOptions): DynamicModule;
66
+ }
67
+
68
+ /**
69
+ * A NestJS guard that lets a request through only with a valid Plasgos access token. It uses the
70
+ * verifier that `PlasgosAuthModule.forRoot` or `forRootAsync` provides, and the route requirements of
71
+ * `@RequireScopes` (class and method scopes add up) and `@RequireRecentAuth` (the method overrides the
72
+ * class). It reads `Authorization` and `X-Request-Id` (for the verifier's `onReject` event).
73
+ *
74
+ * - Token accepted: stores the principal on the request (read it with `@PlasgosPrincipal()`) and lets
75
+ * the request through.
76
+ * - Token refused (`AuthVerifyError`): sets `Cache-Control: no-store`, and `WWW-Authenticate` when the
77
+ * error has a challenge, on the response (Express and Fastify), and throws
78
+ * `HttpException({ error: errorCode }, status)`, so Nest answers 401, 403 or 503 with that JSON body.
79
+ * An app-wide exception filter that rewrites `HttpException` answers also rewrites this body.
80
+ * - Any other error (for example one thrown by your `isRevoked`) propagates unchanged to Nest's
81
+ * exception layer.
82
+ *
83
+ * @example
84
+ * @Controller("contacts")
85
+ * @UseGuards(PlasgosAccessTokenGuard)
86
+ * @RequireScopes("crm:access")
87
+ * export class ContactsController {
88
+ * @Get()
89
+ * list(@PlasgosPrincipal() principal: UserAccessPrincipal) {
90
+ * return this.contacts.list(principal.claims.plasgos_public_id);
91
+ * }
92
+ * }
93
+ */
94
+ declare class PlasgosAccessTokenGuard implements CanActivate {
95
+ private readonly verifier;
96
+ private readonly reflector;
97
+ constructor(verifier: AccessTokenVerifier<AccessPrincipal>, reflector: Reflector);
98
+ /**
99
+ * Verifies the request's token against the route requirements. Resolves `true`, or rejects with an
100
+ * `HttpException` for a refused token, or with the verifier's own non-token error.
101
+ *
102
+ * @example
103
+ * const allowed = await guard.canActivate(context);
104
+ */
105
+ canActivate(context: ExecutionContext): Promise<boolean>;
106
+ }
107
+
108
+ /**
109
+ * Requires scopes on a controller or a route; `PlasgosAccessTokenGuard` refuses a token that lacks any
110
+ * of them with 403 `insufficient_scope`. Scopes on the class and on the method add up. Throws
111
+ * `TypeError` at decoration time without a scope, or for a value that is not an OAuth scope token.
112
+ *
113
+ * @example
114
+ * @Controller("contacts")
115
+ * @UseGuards(PlasgosAccessTokenGuard)
116
+ * @RequireScopes("crm:access")
117
+ * export class ContactsController {}
118
+ */
119
+ declare function RequireScopes(...scopes: string[]): CustomDecorator;
120
+ /**
121
+ * Requires a recent login on a controller or a route: `PlasgosAccessTokenGuard` refuses a token whose
122
+ * `auth_time` is older than `maxAgeSeconds` (default 600) with 401 `insufficient_user_authentication`
123
+ * and `max_age=<seconds>` in `WWW-Authenticate`. The value on the method overrides the one on the
124
+ * class. Throws `TypeError` at decoration time when `maxAgeSeconds` is not a positive integer.
125
+ *
126
+ * @example
127
+ * @Post("export")
128
+ * @RequireRecentAuth(300)
129
+ * exportContacts() {}
130
+ */
131
+ declare function RequireRecentAuth(maxAgeSeconds?: number): CustomDecorator;
132
+ /**
133
+ * Injects the principal that `PlasgosAccessTokenGuard` verified into a route parameter. On a route
134
+ * without the guard it throws `Error` (a wiring mistake, answered with 500).
135
+ *
136
+ * @example
137
+ * @Get("me")
138
+ * me(@PlasgosPrincipal() principal: UserAccessPrincipal) {
139
+ * return { publicId: principal.claims.plasgos_public_id };
140
+ * }
141
+ */
142
+ declare const PlasgosPrincipal: () => ParameterDecorator;
143
+
144
+ /**
145
+ * The injection token of the `AccessTokenVerifier` that `PlasgosAuthModule` provides.
146
+ *
147
+ * @example
148
+ * constructor(@Inject(PLASGOS_ACCESS_TOKEN_VERIFIER) private readonly verifier: AccessTokenVerifier) {}
149
+ */
150
+ declare const PLASGOS_ACCESS_TOKEN_VERIFIER = "PLASGOS_ACCESS_TOKEN_VERIFIER";
151
+
152
+ export { AccessPrincipal, AccessTokenVerifier, AccessTokenVerifierOptions, PLASGOS_ACCESS_TOKEN_VERIFIER, PlasgosAccessTokenGuard, PlasgosAuthModule, PlasgosPrincipal, RequireRecentAuth, RequireScopes, UserAccessPrincipal };
153
+ export type { PlasgosAuthModuleAsyncOptions };