@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,127 @@
1
+ // src/express/middleware.ts
2
+ import { AuthVerifyError } from "@plasgos/auth-shared";
3
+
4
+ // src/core/response.ts
5
+ import { AUTH_VERIFY_REASONS } from "@plasgos/auth-shared";
6
+
7
+ // src/config.ts
8
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9
+
10
+ // src/core/response.ts
11
+ var STATUSES = [401, 403, 503];
12
+ var ERROR_CODES = [
13
+ "invalid_token",
14
+ "insufficient_scope",
15
+ "insufficient_user_authentication",
16
+ "temporarily_unavailable"
17
+ ];
18
+ var REASONS = AUTH_VERIFY_REASONS;
19
+ function authRefusalOf(error) {
20
+ const fields = isObject(error) || error instanceof Error ? error : null;
21
+ if (fields === null) return null;
22
+ const challenge = fields["wwwAuthenticate"];
23
+ if (!REASONS.includes(fields["reason"]) || !STATUSES.includes(fields["status"]) || !ERROR_CODES.includes(fields["errorCode"]) || challenge !== null && typeof challenge !== "string") {
24
+ return null;
25
+ }
26
+ return {
27
+ status: fields["status"],
28
+ errorCode: fields["errorCode"],
29
+ wwwAuthenticate: challenge
30
+ };
31
+ }
32
+
33
+ // src/core/config.ts
34
+ import { ConfigError, PRODUCTION_ISSUER, environmentProblems, parseAudience, parseIssuer } from "@plasgos/auth-shared";
35
+ var MAX_REQUIRED_CLAIMS = 16;
36
+ var CLAIM_NAME = /^[A-Za-z0-9_]{1,64}$/;
37
+ var PROBLEM = {
38
+ https: 'backchannelUrl must use https: when environment is "production" unless allowInsecureBackchannel is true',
39
+ isRevokedRequired: "isRevoked is required for a crm audience",
40
+ requireClaims: `requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`,
41
+ jwks: "jwks must be a JSON Web Key Set",
42
+ jwksSandboxOnly: 'jwks is only allowed when environment is "sandbox"'
43
+ };
44
+
45
+ // src/core/requirements.ts
46
+ var SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
47
+ function resolveRequirements(label, raw) {
48
+ if (raw === void 0) return { scopes: [], requireClaims: [], maxAuthAge: null };
49
+ if (!isObject(raw)) throw new TypeError(`${label}: options must be an object`);
50
+ const { scopes, requireClaims, maxAuthAge } = raw;
51
+ if (scopes !== void 0 && (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === "string" && SCOPE_TOKEN.test(scope)))) {
52
+ throw new TypeError(`${label}: scopes must be a list of scope tokens`);
53
+ }
54
+ if (requireClaims !== void 0 && (!Array.isArray(requireClaims) || requireClaims.length > MAX_REQUIRED_CLAIMS || !requireClaims.every((name) => typeof name === "string" && CLAIM_NAME.test(name)))) {
55
+ throw new TypeError(`${label}: requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`);
56
+ }
57
+ if (maxAuthAge !== void 0 && (typeof maxAuthAge !== "number" || !Number.isSafeInteger(maxAuthAge) || maxAuthAge <= 0)) {
58
+ throw new TypeError(`${label}: maxAuthAge must be a positive safe integer`);
59
+ }
60
+ return {
61
+ scopes: Object.freeze([...new Set(scopes ?? [])]),
62
+ requireClaims: Object.freeze([...new Set(requireClaims ?? [])]),
63
+ maxAuthAge: maxAuthAge ?? null
64
+ };
65
+ }
66
+
67
+ // src/express/middleware.ts
68
+ function refusalOf(error) {
69
+ const named = error instanceof AuthVerifyError || error instanceof Error && error.name === "AuthVerifyError";
70
+ return named ? authRefusalOf(error) : null;
71
+ }
72
+ function isVerifier(verifier) {
73
+ return typeof verifier === "object" && verifier !== null && typeof verifier.verifyAuthorization === "function";
74
+ }
75
+ function requirePlasgosToken(verifier, requirements) {
76
+ if (!isVerifier(verifier)) {
77
+ throw new TypeError("requirePlasgosToken: verifier must come from createAccessTokenVerifier");
78
+ }
79
+ const checked = resolveRequirements("requirePlasgosToken", requirements);
80
+ const options = {
81
+ ...requirements?.scopes !== void 0 ? { scopes: checked.scopes } : {},
82
+ ...requirements?.requireClaims !== void 0 ? { requireClaims: checked.requireClaims } : {},
83
+ ...checked.maxAuthAge !== null ? { maxAuthAge: checked.maxAuthAge } : {}
84
+ };
85
+ return (req, res, next) => {
86
+ const { authorization, "x-request-id": requestId } = req.headers;
87
+ void verifier.verifyAuthorization(typeof authorization === "string" ? authorization : void 0, {
88
+ ...options,
89
+ ...typeof requestId === "string" ? { requestId } : {}
90
+ }).then(
91
+ (principal) => {
92
+ req.plasgosPrincipal = principal;
93
+ next();
94
+ },
95
+ (error) => {
96
+ const refusal = refusalOf(error);
97
+ if (refusal === null || res.headersSent === true) {
98
+ next(error);
99
+ return;
100
+ }
101
+ try {
102
+ res.status(refusal.status);
103
+ res.setHeader("Cache-Control", "no-store");
104
+ if (refusal.wwwAuthenticate !== null) res.setHeader("WWW-Authenticate", refusal.wwwAuthenticate);
105
+ res.json({ error: refusal.errorCode });
106
+ } catch (failure) {
107
+ next(failure);
108
+ }
109
+ }
110
+ );
111
+ };
112
+ }
113
+ function principalOf(req) {
114
+ const principal = req.plasgosPrincipal;
115
+ if (principal === void 0) throw new Error("principalOf: requirePlasgosToken did not run for this request");
116
+ return principal;
117
+ }
118
+
119
+ // src/express/index.ts
120
+ import { AuthVerifyError as AuthVerifyError2, ConfigError as ConfigError2 } from "@plasgos/auth-shared";
121
+ export {
122
+ AuthVerifyError2 as AuthVerifyError,
123
+ ConfigError2 as ConfigError,
124
+ principalOf,
125
+ requirePlasgosToken
126
+ };
127
+ //# sourceMappingURL=express.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/express/middleware.ts","../src/core/response.ts","../src/config.ts","../src/core/config.ts","../src/core/requirements.ts","../src/express/index.ts"],"sourcesContent":["import { AuthVerifyError } from \"@plasgos/auth-shared\";\n\nimport { authRefusalOf } from \"../core/response.js\";\nimport type { AuthRefusal } from \"../core/response.js\";\nimport { resolveRequirements } from \"../core/requirements.js\";\nimport type { AccessPrincipal, AccessTokenVerifier, VerifyOptions } from \"../core/types.js\";\n\n/**\n * The requirements of a route, checked on top of the verifier's own options.\n *\n * @example\n * const requirements: PlasgosRequirements = { scopes: [\"crm:access\"], requireClaims: [\"plasgos_public_id\", \"cv\"] };\n */\nexport interface PlasgosRequirements {\n /** Scopes the token must all hold; else 403 `insufficient_scope`. */\n scopes?: readonly string[] | undefined;\n /** Claim names the token must carry, added to the verifier's `requireClaims`; else 401. */\n requireClaims?: readonly string[] | undefined;\n /** Maximum age of the user's login in seconds; else 401 `insufficient_user_authentication`. */\n maxAuthAge?: number | undefined;\n}\n\n/**\n * The request fields the middleware uses. An Express 4 or 5 `Request` fits it; nothing is imported\n * from `express`.\n *\n * @example\n * const principal = principalOf(req); // req: express.Request\n */\nexport interface PlasgosRequestLike {\n /** The request headers with lower-case names, as Node gives them (`authorization`, `x-request-id`). */\n readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n /** Set by `requirePlasgosToken` once the token passed; read it with `principalOf`. */\n plasgosPrincipal?: AccessPrincipal | undefined;\n}\n\n/**\n * The response methods the middleware uses to answer a refused token. An Express 4 or 5 `Response`\n * fits it.\n *\n * @example\n * res.status(401).json({ error: \"invalid_token\" });\n */\nexport interface PlasgosResponseLike {\n /** True once the headers went out; the middleware then hands a refusal to `next(error)`. */\n readonly headersSent?: boolean | undefined;\n /** Sets the status code of the answer. */\n status(code: number): unknown;\n /** Sets one response header (`Cache-Control`, `WWW-Authenticate`). */\n setHeader(name: string, value: string): unknown;\n /** Sends the JSON body `{ \"error\": \"<errorCode>\" }`. */\n json(body: unknown): unknown;\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/** True when `verifier` has the methods of a verifier made by `createAccessTokenVerifier`. */\nfunction isVerifier(verifier: unknown): boolean {\n return (\n typeof verifier === \"object\" &&\n verifier !== null &&\n typeof (verifier as { verifyAuthorization?: unknown }).verifyAuthorization === \"function\"\n );\n}\n\n/**\n * Express middleware (Express 4 and 5) that lets a request through only with a valid Plasgos access\n * token. `verifier` comes from `createAccessTokenVerifier` of `@plasgos/auth-verify`; `requirements`\n * adds the route's scopes, required claims and maximum login age. The requirements are checked here,\n * when the middleware is created: a wrong one throws `TypeError` (naming the field, never the value).\n *\n * Per request, it reads `Authorization` and `X-Request-Id` (for the verifier's `onReject` event) and:\n * - token accepted: sets `req.plasgosPrincipal` and calls `next()`; read it with `principalOf(req)`;\n * - token refused (`AuthVerifyError`): answers itself with the error's status (401, 403 or 503),\n * `Cache-Control: no-store`, its `WWW-Authenticate` header when it has one, and the JSON body\n * `{ \"error\": \"<errorCode>\" }`;\n * - any other error (for example one thrown by your `isRevoked`): calls `next(error)`, so your error\n * handler answers it.\n *\n * The handler never returns a promise and catches every failure of its own: when the refusal cannot\n * be written (the headers were already sent, or a response method throws), it calls `next(error)`\n * instead, so no rejection is left unhandled in Express 4 or 5.\n *\n * @example\n * import { createAccessTokenVerifier } from \"@plasgos/auth-verify\";\n * import { principalOf, requirePlasgosToken } from \"@plasgos/auth-verify/express\";\n *\n * const verifier = createAccessTokenVerifier(options);\n * app.get(\"/contacts\", requirePlasgosToken(verifier, { scopes: [\"crm:access\"] }), (req, res) => {\n * res.json(listContacts(principalOf(req).claims.plasgos_public_id));\n * });\n */\nexport function requirePlasgosToken(\n verifier: AccessTokenVerifier<AccessPrincipal>,\n requirements?: PlasgosRequirements,\n): (req: PlasgosRequestLike, res: PlasgosResponseLike, next: (error?: unknown) => void) => void {\n if (!isVerifier(verifier)) {\n throw new TypeError(\"requirePlasgosToken: verifier must come from createAccessTokenVerifier\");\n }\n const checked = resolveRequirements(\"requirePlasgosToken\", requirements);\n const options: VerifyOptions = {\n ...(requirements?.scopes !== undefined ? { scopes: checked.scopes } : {}),\n ...(requirements?.requireClaims !== undefined ? { requireClaims: checked.requireClaims } : {}),\n ...(checked.maxAuthAge !== null ? { maxAuthAge: checked.maxAuthAge } : {}),\n };\n\n return (req, res, next) => {\n const { authorization, \"x-request-id\": requestId } = req.headers;\n void verifier\n .verifyAuthorization(typeof authorization === \"string\" ? authorization : undefined, {\n ...options,\n ...(typeof requestId === \"string\" ? { requestId } : {}),\n })\n .then(\n (principal) => {\n req.plasgosPrincipal = principal;\n next();\n },\n (error: unknown) => {\n const refusal = refusalOf(error);\n if (refusal === null || res.headersSent === true) {\n next(error);\n return;\n }\n try {\n res.status(refusal.status);\n res.setHeader(\"Cache-Control\", \"no-store\");\n if (refusal.wwwAuthenticate !== null) res.setHeader(\"WWW-Authenticate\", refusal.wwwAuthenticate);\n res.json({ error: refusal.errorCode });\n } catch (failure) {\n next(failure);\n }\n },\n );\n };\n}\n\n/**\n * The principal `requirePlasgosToken` set on this request. Throws `Error` when the middleware did not\n * run for the request: a wiring mistake, which your error handler should answer with 500.\n *\n * @example\n * app.get(\"/me\", requirePlasgosToken(verifier), (req, res) => {\n * const principal = principalOf(req);\n * res.json({ publicId: principal.claims.plasgos_public_id });\n * });\n */\nexport function principalOf(req: PlasgosRequestLike): AccessPrincipal {\n const principal = req.plasgosPrincipal;\n if (principal === undefined) throw new Error(\"principalOf: requirePlasgosToken did not run for this request\");\n return principal;\n}\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","// 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","// 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","export { principalOf, requirePlasgosToken } from \"./middleware.js\";\nexport type { PlasgosRequestLike, PlasgosRequirements, PlasgosResponseLike } from \"./middleware.js\";\nexport type {\n AccessPrincipal,\n AccessTokenVerifier,\n ServiceAccessPrincipal,\n UserAccessPrincipal,\n VerifiedAccessTokenClaims,\n} from \"../core/types.js\";\n// The classes this entry recognises and throws: 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,uBAAuB;;;ACAhC,SAAS,2BAA2B;;;ACS7B,IAAM,WAAW,CAAC,UACvB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;;;ADLrE,IAAM,WAA+B,CAAC,KAAK,KAAK,GAAG;AACnD,IAAM,cAAkC;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,IAAM,UAA8B;AAmB7B,SAAS,cAAc,OAAoC;AAChE,QAAM,SAAS,SAAS,KAAK,KAAK,iBAAiB,QAAS,QAA+C;AAC3G,MAAI,WAAW,KAAM,QAAO;AAC5B,QAAM,YAAY,OAAO,iBAAiB;AAC1C,MACE,CAAC,QAAQ,SAAS,OAAO,QAAQ,CAAC,KAClC,CAAC,SAAS,SAAS,OAAO,QAAQ,CAAC,KACnC,CAAC,YAAY,SAAS,OAAO,WAAW,CAAC,KACxC,cAAc,QAAQ,OAAO,cAAc,UAC5C;AACA,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,QAAQ,OAAO,QAAQ;AAAA,IACvB,WAAW,OAAO,WAAW;AAAA,IAC7B,iBAAiB;AAAA,EACnB;AACF;;;AEhDA,SAAS,aAAa,mBAAmB,qBAAqB,eAAe,mBAAmB;AAYzF,IAAM,sBAAsB;AAE5B,IAAM,aAAa;AAI1B,IAAM,UAAU;AAAA,EACd,OAAO;AAAA,EACP,mBAAmB;AAAA,EACnB,eAAe,2CAA2C,OAAO,mBAAmB,CAAC;AAAA,EACrF,MAAM;AAAA,EACN,iBAAiB;AACnB;;;AClBA,IAAM,cAAc;AA6Bb,SAAS,oBAAoB,OAAe,KAAoC;AACrF,MAAI,QAAQ,OAAW,QAAO,EAAE,QAAQ,CAAC,GAAG,eAAe,CAAC,GAAG,YAAY,KAAK;AAChF,MAAI,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