@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.
- package/CHANGELOG.md +27 -0
- package/LICENSE +15 -0
- package/README.md +122 -2
- package/THIRD_PARTY_NOTICES.md +31 -0
- package/dist/express.cjs +157 -0
- package/dist/express.cjs.map +1 -0
- package/dist/express.d.cts +90 -0
- package/dist/express.d.ts +90 -0
- package/dist/express.js +127 -0
- package/dist/express.js.map +1 -0
- package/dist/index.cjs +1254 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +67 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +499 -0
- package/dist/index.js.map +1 -0
- package/dist/nestjs.cjs +1395 -0
- package/dist/nestjs.cjs.map +1 -0
- package/dist/nestjs.d.cts +153 -0
- package/dist/nestjs.d.ts +153 -0
- package/dist/nestjs.js +637 -0
- package/dist/nestjs.js.map +1 -0
- package/dist/types-CGtRnj59.d.cts +193 -0
- package/dist/types-CGtRnj59.d.ts +193 -0
- package/dist/webhook.cjs +296 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +196 -0
- package/dist/webhook.d.ts +196 -0
- package/dist/webhook.js +265 -0
- package/dist/webhook.js.map +1 -0
- package/docs/bff-express.md +1314 -0
- package/docs/consumers.md +98 -0
- package/docs/contoh-hitungcuan.md +255 -0
- package/docs/contoh-plaslink.md +244 -0
- package/docs/error.md +613 -0
- package/docs/examples/auth-verify-readme.ts +42 -0
- package/docs/examples/bff-express.ts +370 -0
- package/docs/examples/bff-proxy.ts +335 -0
- package/docs/examples/bff-redis-lock.ts +187 -0
- package/docs/examples/bff-revocation.ts +136 -0
- package/docs/examples/config-error.ts +24 -0
- package/docs/examples/env.ts +150 -0
- package/docs/examples/failure-log.ts +18 -0
- package/docs/examples/login-client.ts +46 -0
- package/docs/examples/login-flow.ts +186 -0
- package/docs/examples/plaslink-connect.ts +48 -0
- package/docs/examples/readme.ts +60 -0
- package/docs/examples/service-client.ts +105 -0
- package/docs/examples/session-store.ts +53 -0
- package/docs/examples/token-commonjs.cjs +95 -0
- package/docs/examples/token-express.ts +56 -0
- package/docs/examples/token-fetch.ts +24 -0
- package/docs/examples/token-nestjs-jest.ts +77 -0
- package/docs/examples/token-nestjs.ts +127 -0
- package/docs/examples/token-socket.ts +59 -0
- package/docs/examples/token-testing.ts +100 -0
- package/docs/examples/token-verifier.ts +132 -0
- package/docs/examples/user-events.ts +110 -0
- package/docs/examples/webhook-express.ts +46 -0
- package/docs/examples/webhook-fetch.ts +60 -0
- package/docs/examples/webhook-nestjs.ts +59 -0
- package/docs/examples/webhook-testing.ts +60 -0
- package/docs/examples/webhook-verifier.ts +197 -0
- package/docs/login-web.md +650 -0
- package/docs/memulai.md +419 -0
- package/docs/server-ke-server.md +287 -0
- package/docs/verifikasi-token.md +1219 -0
- package/docs/webhook.md +810 -0
- package/package.json +101 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/nestjs/module.ts","../src/config.ts","../src/core/config.ts","../src/core/jwks.ts","../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","../src/nestjs/index.ts"],"sourcesContent":["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","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","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"],"mappings":";AAAA,SAAS,cAAc;;;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,KAAcA,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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VerifyError","AuthVerifyError","AuthVerifyError","ConfigError"]}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { AccessTokenClaims, Environment, AuthVerifyReason } from '@plasgos/auth-shared';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A JSON Web Key Set as JSON (RFC 7517 §5): what the Plasgos JWKS endpoint returns. Structural, so no
|
|
5
|
+
* public declaration of this package depends on a `jose` type.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const jwks: JsonWebKeySet = { keys: [publicJwk] };
|
|
9
|
+
*/
|
|
10
|
+
interface JsonWebKeySet {
|
|
11
|
+
/** The public keys (JWKs), each with its `kid`. */
|
|
12
|
+
readonly keys: readonly Readonly<Record<string, unknown>>[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The verified payload of an access token: a frozen copy, so `claims.plasgos_public_id` is
|
|
16
|
+
* `string | undefined` without a cast and other claims stay readable as `unknown`.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* const publicId: string | undefined = principal.claims.plasgos_public_id;
|
|
20
|
+
*/
|
|
21
|
+
type VerifiedAccessTokenClaims = Readonly<AccessTokenClaims & Record<string, unknown>>;
|
|
22
|
+
/**
|
|
23
|
+
* The caller of a user access token (it carries a provider session, `sid`).
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* const verifier = createAccessTokenVerifier(options); // user tokens only
|
|
27
|
+
* const principal: UserAccessPrincipal = await verifier.verifyRequest(request);
|
|
28
|
+
* principal.sessionId; // a string, no null check
|
|
29
|
+
*/
|
|
30
|
+
interface UserAccessPrincipal {
|
|
31
|
+
/** Always `"user"`: a token with a provider session. */
|
|
32
|
+
readonly kind: "user";
|
|
33
|
+
/** `sub`: the user's pairwise id for the client. Identify a user across apps by `claims.plasgos_public_id`. */
|
|
34
|
+
readonly subject: string;
|
|
35
|
+
/** `client_id`: the app the token was issued to. */
|
|
36
|
+
readonly clientId: string;
|
|
37
|
+
/** `sid`: the provider session. */
|
|
38
|
+
readonly sessionId: string;
|
|
39
|
+
/** `auth_time`: when the user last signed in, epoch seconds. */
|
|
40
|
+
readonly authTime: number;
|
|
41
|
+
/** `cv`: the user's credential version when the token was issued, or null when the token has none. */
|
|
42
|
+
readonly credentialVersion: number | null;
|
|
43
|
+
/** The granted scopes, from the space-separated `scope` claim. */
|
|
44
|
+
readonly scopes: readonly string[];
|
|
45
|
+
/** The verified payload. */
|
|
46
|
+
readonly claims: VerifiedAccessTokenClaims;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The caller of a service token (`client_credentials`: no `sid`, `sub` equals `client_id`). Accepted only
|
|
50
|
+
* with `allowServiceTokens: true`.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* if (principal.kind === "service") return principal.clientId;
|
|
54
|
+
*/
|
|
55
|
+
interface ServiceAccessPrincipal {
|
|
56
|
+
/** Always `"service"`: a `client_credentials` token without a user. */
|
|
57
|
+
readonly kind: "service";
|
|
58
|
+
/** `sub`: equals `clientId`. */
|
|
59
|
+
readonly subject: string;
|
|
60
|
+
/** `client_id`: the app that called. */
|
|
61
|
+
readonly clientId: string;
|
|
62
|
+
/** The granted scopes, from the space-separated `scope` claim. */
|
|
63
|
+
readonly scopes: readonly string[];
|
|
64
|
+
/** The verified payload. */
|
|
65
|
+
readonly claims: VerifiedAccessTokenClaims;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Who called: a user or, with `allowServiceTokens: true`, a service. Narrow on `kind`.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* const id = principal.kind === "user" ? principal.sessionId : principal.clientId;
|
|
72
|
+
*/
|
|
73
|
+
type AccessPrincipal = UserAccessPrincipal | ServiceAccessPrincipal;
|
|
74
|
+
/**
|
|
75
|
+
* The event of the `onReject` hook: one per refused token. Every field is safe to log: never the token,
|
|
76
|
+
* a claim value other than a well-formed client id, or a header value other than a well-formed request id.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* onReject: (event) => logger.warn({ ...event }, "plasgos access token refused"),
|
|
80
|
+
*/
|
|
81
|
+
interface AuthRejectEvent {
|
|
82
|
+
/** The verifier's `environment`. */
|
|
83
|
+
readonly environment: Environment;
|
|
84
|
+
/** Why the token was refused; the same value as the `AuthVerifyError`'s `reason`. */
|
|
85
|
+
readonly reason: AuthVerifyReason;
|
|
86
|
+
/** The token's `client_id`, only once its signature passed and only when it is a plain id; else null. */
|
|
87
|
+
readonly clientId: string | null;
|
|
88
|
+
/** The request id given by the caller (the adapters read `X-Request-Id`) when it is a plain id; else null. */
|
|
89
|
+
readonly requestId: string | null;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The `fetch` the verifier uses for the JWKS request. The global `fetch` fits it; tests inject their own.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* const fetch: JwksFetch = (input, init) => globalThis.fetch(input, init);
|
|
96
|
+
*/
|
|
97
|
+
type JwksFetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
98
|
+
/**
|
|
99
|
+
* Options of `createAccessTokenVerifier`. Every option is checked once, at creation: a wrong one throws
|
|
100
|
+
* one `ConfigError` listing every problem. `P` is the principal `isRevoked` receives: `UserAccessPrincipal`,
|
|
101
|
+
* or `AccessPrincipal` with `allowServiceTokens: true`.
|
|
102
|
+
*
|
|
103
|
+
* @typeParam P - The principal `isRevoked` receives.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* const options: AccessTokenVerifierOptions = {
|
|
107
|
+
* environment: "production",
|
|
108
|
+
* issuer: "https://accounts.plasgos.co.id",
|
|
109
|
+
* audience: "https://api.plasgos.co.id/crm",
|
|
110
|
+
* requireClaims: ["plasgos_public_id", "cv"],
|
|
111
|
+
* isRevoked: async (principal) => isSessionRevoked(principal.sessionId),
|
|
112
|
+
* };
|
|
113
|
+
*/
|
|
114
|
+
interface AccessTokenVerifierOptions<P extends AccessPrincipal = UserAccessPrincipal> {
|
|
115
|
+
/** `"sandbox"` or `"production"`; checked against `issuer`, `audience` and `backchannelUrl`. */
|
|
116
|
+
environment: Environment;
|
|
117
|
+
/** The issuer origin; the token's `iss` must equal it. `https://accounts.plasgos.co.id` in production. */
|
|
118
|
+
issuer: string;
|
|
119
|
+
/** This API's audience; the token's `aud` must equal it exactly. */
|
|
120
|
+
audience: string;
|
|
121
|
+
/** Internal origin of the Plasgos server for the JWKS request. Default: `issuer`. */
|
|
122
|
+
backchannelUrl?: string | undefined;
|
|
123
|
+
/** Production only: accept an `http:` `backchannelUrl` on a private network the app trusts. Default false. */
|
|
124
|
+
allowInsecureBackchannel?: boolean | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* Also accept service tokens (`client_credentials`). Default false. Typed `false` on the default
|
|
127
|
+
* `AccessTokenVerifierOptions` (user principals only); set it to `true` on
|
|
128
|
+
* `AccessTokenVerifierOptions<AccessPrincipal>`, so `isRevoked` and the verifier see both kinds.
|
|
129
|
+
*/
|
|
130
|
+
allowServiceTokens?: ([P] extends [UserAccessPrincipal] ? false : boolean) | undefined;
|
|
131
|
+
/** Claim names every token must carry, for example `["plasgos_public_id", "cv"]`. Default none. */
|
|
132
|
+
requireClaims?: readonly string[] | undefined;
|
|
133
|
+
/** Leeway for `exp` and `nbf`, integer seconds from 0 to 60. Default 30. */
|
|
134
|
+
clockToleranceSeconds?: number | undefined;
|
|
135
|
+
/** `jwksMs`: budget of the JWKS request including its body, integer ms from 1 to 60 000. Default 5 000. */
|
|
136
|
+
timeouts?: {
|
|
137
|
+
jwksMs?: number | undefined;
|
|
138
|
+
} | undefined;
|
|
139
|
+
/** A fixed key set instead of the JWKS request, for tests. Sandbox only. */
|
|
140
|
+
jwks?: JsonWebKeySet | undefined;
|
|
141
|
+
/** Sandbox only: accept an `http:` issuer, for local development. Default false. */
|
|
142
|
+
allowInsecureHttp?: boolean | undefined;
|
|
143
|
+
/** The `fetch` for the JWKS request. Default: the global `fetch`. */
|
|
144
|
+
fetch?: JwksFetch | undefined;
|
|
145
|
+
/**
|
|
146
|
+
* Called for every token that passed the signature and claim checks: `true` refuses it as `revoked`.
|
|
147
|
+
* A throw or rejection fails the verification with that error (not a 401). Required for an audience
|
|
148
|
+
* whose path is `/crm`.
|
|
149
|
+
*/
|
|
150
|
+
isRevoked?: ((principal: P) => boolean | Promise<boolean>) | undefined;
|
|
151
|
+
/** Called once for every refused token. A throw or rejection of the hook is ignored. */
|
|
152
|
+
onReject?: ((event: AuthRejectEvent) => void | Promise<void>) | undefined;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The requirements of one route, on top of the verifier's own.
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* await verifier.verifyRequest(request, { scopes: ["crm:access"], maxAuthAge: 600 });
|
|
159
|
+
*/
|
|
160
|
+
interface VerifyOptions {
|
|
161
|
+
/** Scopes the token must all hold; else `insufficient_scope`. */
|
|
162
|
+
scopes?: readonly string[] | undefined;
|
|
163
|
+
/** Claim names the token must carry, added to the verifier's `requireClaims`; else `invalid_claims`. */
|
|
164
|
+
requireClaims?: readonly string[] | undefined;
|
|
165
|
+
/** Maximum age of the user's login in seconds (`now - auth_time`); else `stale_auth`. */
|
|
166
|
+
maxAuthAge?: number | undefined;
|
|
167
|
+
/** The request id to put into the `onReject` event. */
|
|
168
|
+
requestId?: string | null | undefined;
|
|
169
|
+
/** The current time in epoch milliseconds, for tests. Default `Date.now()`. */
|
|
170
|
+
now?: number | undefined;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Verifies Plasgos access tokens for one API (one audience). Created by `createAccessTokenVerifier`.
|
|
174
|
+
*
|
|
175
|
+
* @typeParam P - The principal a successful verification resolves to.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* const principal = await verifier.verifyAuthorization(req.headers.authorization, { scopes: ["crm:access"] });
|
|
179
|
+
*/
|
|
180
|
+
interface AccessTokenVerifier<P extends AccessPrincipal = UserAccessPrincipal> {
|
|
181
|
+
/** The configured `environment`. */
|
|
182
|
+
readonly environment: Environment;
|
|
183
|
+
/** The configured issuer origin. */
|
|
184
|
+
readonly issuer: string;
|
|
185
|
+
/** The configured audience of this API. */
|
|
186
|
+
readonly audience: string;
|
|
187
|
+
/** Verifies an `Authorization` header value; rejects with `AuthVerifyError` when the token is refused. */
|
|
188
|
+
verifyAuthorization(header: string | null | undefined, options?: VerifyOptions): Promise<P>;
|
|
189
|
+
/** Verifies the `Authorization` header of a Web `Request`; rejects with `AuthVerifyError` when refused. */
|
|
190
|
+
verifyRequest(request: Request, options?: VerifyOptions): Promise<P>;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export type { AccessPrincipal as A, JsonWebKeySet as J, ServiceAccessPrincipal as S, UserAccessPrincipal as U, VerifiedAccessTokenClaims as V, AccessTokenVerifier as a, AccessTokenVerifierOptions as b, AuthRejectEvent as c, JwksFetch as d, VerifyOptions as e };
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { AccessTokenClaims, Environment, AuthVerifyReason } from '@plasgos/auth-shared';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A JSON Web Key Set as JSON (RFC 7517 §5): what the Plasgos JWKS endpoint returns. Structural, so no
|
|
5
|
+
* public declaration of this package depends on a `jose` type.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const jwks: JsonWebKeySet = { keys: [publicJwk] };
|
|
9
|
+
*/
|
|
10
|
+
interface JsonWebKeySet {
|
|
11
|
+
/** The public keys (JWKs), each with its `kid`. */
|
|
12
|
+
readonly keys: readonly Readonly<Record<string, unknown>>[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The verified payload of an access token: a frozen copy, so `claims.plasgos_public_id` is
|
|
16
|
+
* `string | undefined` without a cast and other claims stay readable as `unknown`.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* const publicId: string | undefined = principal.claims.plasgos_public_id;
|
|
20
|
+
*/
|
|
21
|
+
type VerifiedAccessTokenClaims = Readonly<AccessTokenClaims & Record<string, unknown>>;
|
|
22
|
+
/**
|
|
23
|
+
* The caller of a user access token (it carries a provider session, `sid`).
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* const verifier = createAccessTokenVerifier(options); // user tokens only
|
|
27
|
+
* const principal: UserAccessPrincipal = await verifier.verifyRequest(request);
|
|
28
|
+
* principal.sessionId; // a string, no null check
|
|
29
|
+
*/
|
|
30
|
+
interface UserAccessPrincipal {
|
|
31
|
+
/** Always `"user"`: a token with a provider session. */
|
|
32
|
+
readonly kind: "user";
|
|
33
|
+
/** `sub`: the user's pairwise id for the client. Identify a user across apps by `claims.plasgos_public_id`. */
|
|
34
|
+
readonly subject: string;
|
|
35
|
+
/** `client_id`: the app the token was issued to. */
|
|
36
|
+
readonly clientId: string;
|
|
37
|
+
/** `sid`: the provider session. */
|
|
38
|
+
readonly sessionId: string;
|
|
39
|
+
/** `auth_time`: when the user last signed in, epoch seconds. */
|
|
40
|
+
readonly authTime: number;
|
|
41
|
+
/** `cv`: the user's credential version when the token was issued, or null when the token has none. */
|
|
42
|
+
readonly credentialVersion: number | null;
|
|
43
|
+
/** The granted scopes, from the space-separated `scope` claim. */
|
|
44
|
+
readonly scopes: readonly string[];
|
|
45
|
+
/** The verified payload. */
|
|
46
|
+
readonly claims: VerifiedAccessTokenClaims;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The caller of a service token (`client_credentials`: no `sid`, `sub` equals `client_id`). Accepted only
|
|
50
|
+
* with `allowServiceTokens: true`.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* if (principal.kind === "service") return principal.clientId;
|
|
54
|
+
*/
|
|
55
|
+
interface ServiceAccessPrincipal {
|
|
56
|
+
/** Always `"service"`: a `client_credentials` token without a user. */
|
|
57
|
+
readonly kind: "service";
|
|
58
|
+
/** `sub`: equals `clientId`. */
|
|
59
|
+
readonly subject: string;
|
|
60
|
+
/** `client_id`: the app that called. */
|
|
61
|
+
readonly clientId: string;
|
|
62
|
+
/** The granted scopes, from the space-separated `scope` claim. */
|
|
63
|
+
readonly scopes: readonly string[];
|
|
64
|
+
/** The verified payload. */
|
|
65
|
+
readonly claims: VerifiedAccessTokenClaims;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Who called: a user or, with `allowServiceTokens: true`, a service. Narrow on `kind`.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* const id = principal.kind === "user" ? principal.sessionId : principal.clientId;
|
|
72
|
+
*/
|
|
73
|
+
type AccessPrincipal = UserAccessPrincipal | ServiceAccessPrincipal;
|
|
74
|
+
/**
|
|
75
|
+
* The event of the `onReject` hook: one per refused token. Every field is safe to log: never the token,
|
|
76
|
+
* a claim value other than a well-formed client id, or a header value other than a well-formed request id.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* onReject: (event) => logger.warn({ ...event }, "plasgos access token refused"),
|
|
80
|
+
*/
|
|
81
|
+
interface AuthRejectEvent {
|
|
82
|
+
/** The verifier's `environment`. */
|
|
83
|
+
readonly environment: Environment;
|
|
84
|
+
/** Why the token was refused; the same value as the `AuthVerifyError`'s `reason`. */
|
|
85
|
+
readonly reason: AuthVerifyReason;
|
|
86
|
+
/** The token's `client_id`, only once its signature passed and only when it is a plain id; else null. */
|
|
87
|
+
readonly clientId: string | null;
|
|
88
|
+
/** The request id given by the caller (the adapters read `X-Request-Id`) when it is a plain id; else null. */
|
|
89
|
+
readonly requestId: string | null;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The `fetch` the verifier uses for the JWKS request. The global `fetch` fits it; tests inject their own.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* const fetch: JwksFetch = (input, init) => globalThis.fetch(input, init);
|
|
96
|
+
*/
|
|
97
|
+
type JwksFetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
98
|
+
/**
|
|
99
|
+
* Options of `createAccessTokenVerifier`. Every option is checked once, at creation: a wrong one throws
|
|
100
|
+
* one `ConfigError` listing every problem. `P` is the principal `isRevoked` receives: `UserAccessPrincipal`,
|
|
101
|
+
* or `AccessPrincipal` with `allowServiceTokens: true`.
|
|
102
|
+
*
|
|
103
|
+
* @typeParam P - The principal `isRevoked` receives.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* const options: AccessTokenVerifierOptions = {
|
|
107
|
+
* environment: "production",
|
|
108
|
+
* issuer: "https://accounts.plasgos.co.id",
|
|
109
|
+
* audience: "https://api.plasgos.co.id/crm",
|
|
110
|
+
* requireClaims: ["plasgos_public_id", "cv"],
|
|
111
|
+
* isRevoked: async (principal) => isSessionRevoked(principal.sessionId),
|
|
112
|
+
* };
|
|
113
|
+
*/
|
|
114
|
+
interface AccessTokenVerifierOptions<P extends AccessPrincipal = UserAccessPrincipal> {
|
|
115
|
+
/** `"sandbox"` or `"production"`; checked against `issuer`, `audience` and `backchannelUrl`. */
|
|
116
|
+
environment: Environment;
|
|
117
|
+
/** The issuer origin; the token's `iss` must equal it. `https://accounts.plasgos.co.id` in production. */
|
|
118
|
+
issuer: string;
|
|
119
|
+
/** This API's audience; the token's `aud` must equal it exactly. */
|
|
120
|
+
audience: string;
|
|
121
|
+
/** Internal origin of the Plasgos server for the JWKS request. Default: `issuer`. */
|
|
122
|
+
backchannelUrl?: string | undefined;
|
|
123
|
+
/** Production only: accept an `http:` `backchannelUrl` on a private network the app trusts. Default false. */
|
|
124
|
+
allowInsecureBackchannel?: boolean | undefined;
|
|
125
|
+
/**
|
|
126
|
+
* Also accept service tokens (`client_credentials`). Default false. Typed `false` on the default
|
|
127
|
+
* `AccessTokenVerifierOptions` (user principals only); set it to `true` on
|
|
128
|
+
* `AccessTokenVerifierOptions<AccessPrincipal>`, so `isRevoked` and the verifier see both kinds.
|
|
129
|
+
*/
|
|
130
|
+
allowServiceTokens?: ([P] extends [UserAccessPrincipal] ? false : boolean) | undefined;
|
|
131
|
+
/** Claim names every token must carry, for example `["plasgos_public_id", "cv"]`. Default none. */
|
|
132
|
+
requireClaims?: readonly string[] | undefined;
|
|
133
|
+
/** Leeway for `exp` and `nbf`, integer seconds from 0 to 60. Default 30. */
|
|
134
|
+
clockToleranceSeconds?: number | undefined;
|
|
135
|
+
/** `jwksMs`: budget of the JWKS request including its body, integer ms from 1 to 60 000. Default 5 000. */
|
|
136
|
+
timeouts?: {
|
|
137
|
+
jwksMs?: number | undefined;
|
|
138
|
+
} | undefined;
|
|
139
|
+
/** A fixed key set instead of the JWKS request, for tests. Sandbox only. */
|
|
140
|
+
jwks?: JsonWebKeySet | undefined;
|
|
141
|
+
/** Sandbox only: accept an `http:` issuer, for local development. Default false. */
|
|
142
|
+
allowInsecureHttp?: boolean | undefined;
|
|
143
|
+
/** The `fetch` for the JWKS request. Default: the global `fetch`. */
|
|
144
|
+
fetch?: JwksFetch | undefined;
|
|
145
|
+
/**
|
|
146
|
+
* Called for every token that passed the signature and claim checks: `true` refuses it as `revoked`.
|
|
147
|
+
* A throw or rejection fails the verification with that error (not a 401). Required for an audience
|
|
148
|
+
* whose path is `/crm`.
|
|
149
|
+
*/
|
|
150
|
+
isRevoked?: ((principal: P) => boolean | Promise<boolean>) | undefined;
|
|
151
|
+
/** Called once for every refused token. A throw or rejection of the hook is ignored. */
|
|
152
|
+
onReject?: ((event: AuthRejectEvent) => void | Promise<void>) | undefined;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The requirements of one route, on top of the verifier's own.
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* await verifier.verifyRequest(request, { scopes: ["crm:access"], maxAuthAge: 600 });
|
|
159
|
+
*/
|
|
160
|
+
interface VerifyOptions {
|
|
161
|
+
/** Scopes the token must all hold; else `insufficient_scope`. */
|
|
162
|
+
scopes?: readonly string[] | undefined;
|
|
163
|
+
/** Claim names the token must carry, added to the verifier's `requireClaims`; else `invalid_claims`. */
|
|
164
|
+
requireClaims?: readonly string[] | undefined;
|
|
165
|
+
/** Maximum age of the user's login in seconds (`now - auth_time`); else `stale_auth`. */
|
|
166
|
+
maxAuthAge?: number | undefined;
|
|
167
|
+
/** The request id to put into the `onReject` event. */
|
|
168
|
+
requestId?: string | null | undefined;
|
|
169
|
+
/** The current time in epoch milliseconds, for tests. Default `Date.now()`. */
|
|
170
|
+
now?: number | undefined;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Verifies Plasgos access tokens for one API (one audience). Created by `createAccessTokenVerifier`.
|
|
174
|
+
*
|
|
175
|
+
* @typeParam P - The principal a successful verification resolves to.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* const principal = await verifier.verifyAuthorization(req.headers.authorization, { scopes: ["crm:access"] });
|
|
179
|
+
*/
|
|
180
|
+
interface AccessTokenVerifier<P extends AccessPrincipal = UserAccessPrincipal> {
|
|
181
|
+
/** The configured `environment`. */
|
|
182
|
+
readonly environment: Environment;
|
|
183
|
+
/** The configured issuer origin. */
|
|
184
|
+
readonly issuer: string;
|
|
185
|
+
/** The configured audience of this API. */
|
|
186
|
+
readonly audience: string;
|
|
187
|
+
/** Verifies an `Authorization` header value; rejects with `AuthVerifyError` when the token is refused. */
|
|
188
|
+
verifyAuthorization(header: string | null | undefined, options?: VerifyOptions): Promise<P>;
|
|
189
|
+
/** Verifies the `Authorization` header of a Web `Request`; rejects with `AuthVerifyError` when refused. */
|
|
190
|
+
verifyRequest(request: Request, options?: VerifyOptions): Promise<P>;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export type { AccessPrincipal as A, JsonWebKeySet as J, ServiceAccessPrincipal as S, UserAccessPrincipal as U, VerifiedAccessTokenClaims as V, AccessTokenVerifier as a, AccessTokenVerifierOptions as b, AuthRejectEvent as c, JwksFetch as d, VerifyOptions as e };
|