@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
package/dist/nestjs.js ADDED
@@ -0,0 +1,637 @@
1
+ // src/nestjs/module.ts
2
+ import { Module } from "@nestjs/common";
3
+
4
+ // src/config.ts
5
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
6
+ var isBlank = (value) => typeof value === "string" && value.trim() === "";
7
+ function integerInRange(problems, raw, field2, range) {
8
+ if (raw === void 0) return range.fallback;
9
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;
10
+ problems.push(`${field2} must be an integer from ${String(range.min)} to ${String(range.max)}`);
11
+ return range.fallback;
12
+ }
13
+ function optionalFunction(problems, raw, field2) {
14
+ if (raw === void 0) return void 0;
15
+ if (typeof raw === "function") return raw;
16
+ problems.push(`${field2} must be a function`);
17
+ return void 0;
18
+ }
19
+
20
+ // src/core/config.ts
21
+ import { ConfigError, PRODUCTION_ISSUER, environmentProblems, parseAudience, parseIssuer } from "@plasgos/auth-shared";
22
+ var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
23
+ var MAX_CLOCK_TOLERANCE_SECONDS = 60;
24
+ var DEFAULT_JWKS_MS = 5e3;
25
+ var MAX_TIMEOUT_MS = 6e4;
26
+ var MAX_REQUIRED_CLAIMS = 16;
27
+ var CLAIM_NAME = /^[A-Za-z0-9_]{1,64}$/;
28
+ var CREDENTIAL_VERSION_PATH = "/crm";
29
+ var PROBLEM = {
30
+ https: 'backchannelUrl must use https: when environment is "production" unless allowInsecureBackchannel is true',
31
+ isRevokedRequired: "isRevoked is required for a crm audience",
32
+ requireClaims: `requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`,
33
+ jwks: "jwks must be a JSON Web Key Set",
34
+ jwksSandboxOnly: 'jwks is only allowed when environment is "sandbox"'
35
+ };
36
+ var RESOURCE_PROBLEM = 'environment is "production" but resource is not a production audience';
37
+ var AUDIENCE_PROBLEM = 'environment is "production" but audience is not a production audience';
38
+ var globalFetch = (input, init) => globalThis.fetch(input, init);
39
+ function needsCredentialVersion(audience) {
40
+ return new URL(audience).pathname.replace(/\/+$/, "") === CREDENTIAL_VERSION_PATH;
41
+ }
42
+ function parsed(problems, parse) {
43
+ try {
44
+ return parse();
45
+ } catch (error) {
46
+ if (!(error instanceof ConfigError)) throw error;
47
+ problems.push(...error.problems);
48
+ return void 0;
49
+ }
50
+ }
51
+ function requiredClaimsOf(problems, raw) {
52
+ if (raw === void 0) return Object.freeze([]);
53
+ if (!Array.isArray(raw) || raw.length > MAX_REQUIRED_CLAIMS || !raw.every((name) => typeof name === "string" && CLAIM_NAME.test(name))) {
54
+ problems.push(PROBLEM.requireClaims);
55
+ return Object.freeze([]);
56
+ }
57
+ return Object.freeze([...new Set(raw)]);
58
+ }
59
+ function jwksOf(problems, raw) {
60
+ const keys = isObject(raw) ? raw["keys"] : void 0;
61
+ if (!Array.isArray(keys) || keys.length === 0 || !keys.every((key) => isObject(key))) {
62
+ problems.push(PROBLEM.jwks);
63
+ return null;
64
+ }
65
+ return Object.freeze({ keys: Object.freeze(keys.map((key) => Object.freeze({ ...key }))) });
66
+ }
67
+ function timeoutsOf(problems, raw) {
68
+ if (raw === void 0) return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });
69
+ if (!isObject(raw)) {
70
+ problems.push("timeouts must be an object");
71
+ return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });
72
+ }
73
+ const jwksMs = integerInRange(problems, raw["jwksMs"], "timeouts.jwksMs", {
74
+ min: 1,
75
+ max: MAX_TIMEOUT_MS,
76
+ fallback: DEFAULT_JWKS_MS
77
+ });
78
+ return Object.freeze({ jwksMs });
79
+ }
80
+ function resolveVerifierConfig(raw) {
81
+ if (!isObject(raw)) throw new ConfigError(["options must be an object"]);
82
+ const problems = [];
83
+ const text = (field2) => {
84
+ const value = raw[field2];
85
+ if (value === void 0 || typeof value === "string") return value;
86
+ problems.push(`${field2} must be a string`);
87
+ return void 0;
88
+ };
89
+ const given = (field2) => raw[field2] !== void 0;
90
+ const flag = (field2) => {
91
+ const value = raw[field2];
92
+ if (value === void 0 || typeof value === "boolean") return value === true;
93
+ problems.push(`${field2} must be a boolean`);
94
+ return false;
95
+ };
96
+ const environment = raw["environment"];
97
+ const allowInsecureHttp = raw["allowInsecureHttp"] === true;
98
+ const issuerRaw = text("issuer");
99
+ const issuer = given("issuer") && issuerRaw === void 0 ? void 0 : parsed(problems, () => parseIssuer(issuerRaw, { field: "issuer", allowInsecureHttp }));
100
+ const audienceRaw = text("audience");
101
+ const audience = given("audience") && audienceRaw === void 0 ? void 0 : parsed(problems, () => parseAudience(audienceRaw, { field: "audience", allowInsecureHttp }));
102
+ const backchannelRaw = given("backchannelUrl") && !isBlank(raw["backchannelUrl"]) ? text("backchannelUrl") : void 0;
103
+ const backchannelUrl = backchannelRaw === void 0 ? void 0 : parsed(problems, () => parseIssuer(backchannelRaw, { field: "backchannelUrl", allowInsecureHttp: true }));
104
+ const insecureBackchannelRaw = raw["allowInsecureBackchannel"];
105
+ if (environment === "production" && backchannelUrl !== void 0 && new URL(backchannelUrl).protocol === "http:" && insecureBackchannelRaw !== true) {
106
+ problems.push(PROBLEM.https);
107
+ }
108
+ const allowInsecureBackchannel = flag("allowInsecureBackchannel");
109
+ const allowServiceTokens = flag("allowServiceTokens");
110
+ const requiredClaims = requiredClaimsOf(problems, raw["requireClaims"]);
111
+ const clockToleranceSeconds = integerInRange(problems, raw["clockToleranceSeconds"], "clockToleranceSeconds", {
112
+ min: 0,
113
+ max: MAX_CLOCK_TOLERANCE_SECONDS,
114
+ fallback: DEFAULT_CLOCK_TOLERANCE_SECONDS
115
+ });
116
+ const timeouts = timeoutsOf(problems, raw["timeouts"]);
117
+ const jwks = given("jwks") ? jwksOf(problems, raw["jwks"]) : null;
118
+ if (given("jwks") && environment === "production") problems.push(PROBLEM.jwksSandboxOnly);
119
+ flag("allowInsecureHttp");
120
+ const fetch = optionalFunction(problems, raw["fetch"], "fetch");
121
+ const requireCredentialVersion = audience !== void 0 && needsCredentialVersion(audience);
122
+ const isRevoked = optionalFunction(problems, raw["isRevoked"], "isRevoked");
123
+ if (requireCredentialVersion && !given("isRevoked")) problems.push(PROBLEM.isRevokedRequired);
124
+ const onReject = optionalFunction(problems, raw["onReject"], "onReject");
125
+ const guard = environmentProblems({
126
+ environment,
127
+ issuer: issuer ?? (environment === "production" ? PRODUCTION_ISSUER : ""),
128
+ allowInsecureHttp: raw["allowInsecureHttp"],
129
+ ...audience !== void 0 ? { audiences: [audience] } : {},
130
+ ...backchannelUrl !== void 0 ? { backchannelUrl } : {}
131
+ });
132
+ const named = guard.map((problem) => problem === RESOURCE_PROBLEM ? AUDIENCE_PROBLEM : problem);
133
+ if (named.length > 0 || problems.length > 0) throw new ConfigError([...named, ...problems]);
134
+ return Object.freeze({
135
+ environment,
136
+ issuer,
137
+ audience,
138
+ backchannelUrl: backchannelUrl ?? null,
139
+ allowInsecureBackchannel,
140
+ allowServiceTokens,
141
+ requiredClaims,
142
+ requireCredentialVersion,
143
+ clockToleranceSeconds,
144
+ timeouts,
145
+ jwks,
146
+ fetch: fetch ?? globalFetch,
147
+ isRevoked,
148
+ onReject
149
+ });
150
+ }
151
+
152
+ // src/core/jwks.ts
153
+ import { OIDC_PATHS } from "@plasgos/auth-shared";
154
+ import { createLocalJWKSet, createRemoteJWKSet, customFetch } from "jose";
155
+ var COOLDOWN_MS = 3e4;
156
+ var MAX_JWKS_BYTES = 65536;
157
+ var KEY_SET_UNAVAILABLE = "ERR_PLASGOS_JWKS_UNAVAILABLE";
158
+ var JOSE_UNAVAILABLE_CODES = /* @__PURE__ */ new Set([KEY_SET_UNAVAILABLE, "ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID"]);
159
+ function unavailable() {
160
+ return Object.assign(new Error("Plasgos key set unavailable"), { code: KEY_SET_UNAVAILABLE });
161
+ }
162
+ function isKeySetUnavailable(error) {
163
+ if (typeof error !== "object" || error === null || !("code" in error)) return false;
164
+ const { code } = error;
165
+ return typeof code === "string" && JOSE_UNAVAILABLE_CODES.has(code);
166
+ }
167
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
168
+ async function readCapped(response) {
169
+ const length = response.headers.get("content-length");
170
+ if (length !== null && Number(length) > MAX_JWKS_BYTES) throw unavailable();
171
+ if (response.body === null) return new Uint8Array(0);
172
+ const reader = response.body.getReader();
173
+ const chunks = [];
174
+ let total = 0;
175
+ for (; ; ) {
176
+ const result = await reader.read();
177
+ if (result.done) break;
178
+ const chunk = result.value;
179
+ if (!(chunk instanceof Uint8Array)) throw unavailable();
180
+ total += chunk.byteLength;
181
+ if (total > MAX_JWKS_BYTES) {
182
+ void reader.cancel().catch(() => void 0);
183
+ throw unavailable();
184
+ }
185
+ chunks.push(chunk);
186
+ }
187
+ const bytes = new Uint8Array(total);
188
+ let offset = 0;
189
+ for (const chunk of chunks) {
190
+ bytes.set(chunk, offset);
191
+ offset += chunk.byteLength;
192
+ }
193
+ return bytes;
194
+ }
195
+ function isKeySetJson(bytes) {
196
+ try {
197
+ const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
198
+ return isObject2(json) && Array.isArray(json["keys"]) && json["keys"].every((key) => isObject2(key));
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+ function boundedFetch(fetchImpl, jwksMs) {
204
+ return async (url, init) => {
205
+ const controller = new AbortController();
206
+ const abort = () => {
207
+ controller.abort();
208
+ };
209
+ const outer = init.signal;
210
+ if (outer?.aborted === true) abort();
211
+ outer?.addEventListener("abort", abort, { once: true });
212
+ const timer = setTimeout(abort, jwksMs);
213
+ const aborted = new Promise((_, reject) => {
214
+ const fail = () => {
215
+ reject(unavailable());
216
+ };
217
+ if (controller.signal.aborted) fail();
218
+ else controller.signal.addEventListener("abort", fail, { once: true });
219
+ });
220
+ aborted.catch(() => void 0);
221
+ try {
222
+ const response = await Promise.race([
223
+ fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal }),
224
+ aborted
225
+ ]);
226
+ if (response.status !== 200) {
227
+ void response.body?.cancel().catch(() => void 0);
228
+ throw unavailable();
229
+ }
230
+ const bytes = await Promise.race([readCapped(response), aborted]);
231
+ if (!isKeySetJson(bytes)) throw unavailable();
232
+ return new Response(bytes, { status: 200, headers: { "content-type": "application/json" } });
233
+ } catch {
234
+ throw unavailable();
235
+ } finally {
236
+ clearTimeout(timer);
237
+ outer?.removeEventListener("abort", abort);
238
+ }
239
+ };
240
+ }
241
+ function remoteKeySet(source) {
242
+ const url = new URL(`${source.backchannelUrl ?? source.issuer}${OIDC_PATHS.jwks}`);
243
+ return createRemoteJWKSet(url, {
244
+ timeoutDuration: source.timeouts.jwksMs,
245
+ cooldownDuration: COOLDOWN_MS,
246
+ [customFetch]: boundedFetch(source.fetch, source.timeouts.jwksMs)
247
+ });
248
+ }
249
+ function staticKeySet(jwks) {
250
+ return createLocalJWKSet(jwks);
251
+ }
252
+
253
+ // src/core/verify.ts
254
+ import { ACCESS_TOKEN_TYPES, AuthVerifyError, MAX_JWT_LENGTH, SIGNING_ALG } from "@plasgos/auth-shared";
255
+ import { jwtVerify } from "jose";
256
+
257
+ // src/core/requirements.ts
258
+ var SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
259
+ function resolveRequirements(label, raw) {
260
+ if (raw === void 0) return { scopes: [], requireClaims: [], maxAuthAge: null };
261
+ if (!isObject(raw)) throw new TypeError(`${label}: options must be an object`);
262
+ const { scopes, requireClaims, maxAuthAge } = raw;
263
+ if (scopes !== void 0 && (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === "string" && SCOPE_TOKEN.test(scope)))) {
264
+ throw new TypeError(`${label}: scopes must be a list of scope tokens`);
265
+ }
266
+ if (requireClaims !== void 0 && (!Array.isArray(requireClaims) || requireClaims.length > MAX_REQUIRED_CLAIMS || !requireClaims.every((name) => typeof name === "string" && CLAIM_NAME.test(name)))) {
267
+ throw new TypeError(`${label}: requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`);
268
+ }
269
+ if (maxAuthAge !== void 0 && (typeof maxAuthAge !== "number" || !Number.isSafeInteger(maxAuthAge) || maxAuthAge <= 0)) {
270
+ throw new TypeError(`${label}: maxAuthAge must be a positive safe integer`);
271
+ }
272
+ return {
273
+ scopes: Object.freeze([...new Set(scopes ?? [])]),
274
+ requireClaims: Object.freeze([...new Set(requireClaims ?? [])]),
275
+ maxAuthAge: maxAuthAge ?? null
276
+ };
277
+ }
278
+ function resolveVerifyOptions(raw) {
279
+ const requirements = resolveRequirements("verify", raw);
280
+ const fields = isObject(raw) ? raw : {};
281
+ const { requestId, now } = fields;
282
+ if (requestId !== void 0 && requestId !== null && typeof requestId !== "string") {
283
+ throw new TypeError("verify: requestId must be a string");
284
+ }
285
+ if (now !== void 0 && (typeof now !== "number" || !Number.isFinite(now))) {
286
+ throw new TypeError("verify: now must be a finite number");
287
+ }
288
+ return { ...requirements, requestId, now: now ?? null };
289
+ }
290
+
291
+ // src/core/verify.ts
292
+ var BEARER_SCHEME = /^Bearer /i;
293
+ var BEARER_TOKEN = /^Bearer +([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)$/i;
294
+ var PLAIN_ID = /^[\w.:-]{1,128}$/;
295
+ var MAX_PUBLIC_ID_LENGTH = 128;
296
+ var ACCEPTED_TYPES = ACCESS_TOKEN_TYPES;
297
+ var refuse = (reason, clientId = null) => ({ refusal: { reason, clientId } });
298
+ var nonEmptyString = (value) => typeof value === "string" && value !== "";
299
+ var plainId = (value) => typeof value === "string" && PLAIN_ID.test(value) ? value : null;
300
+ function decodeHeader(segment) {
301
+ try {
302
+ const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(segment, "base64url")));
303
+ return isObject(json) ? json : null;
304
+ } catch {
305
+ return null;
306
+ }
307
+ }
308
+ function field(error, name) {
309
+ return isObject(error) || error instanceof Error ? error[name] : void 0;
310
+ }
311
+ function reasonOfVerifyError(error) {
312
+ if (isKeySetUnavailable(error)) return "unavailable";
313
+ switch (field(error, "code")) {
314
+ case "ERR_JWKS_NO_MATCHING_KEY":
315
+ return "unknown_key";
316
+ case "ERR_JWT_EXPIRED":
317
+ return "expired_token";
318
+ case "ERR_JWT_INVALID":
319
+ return "malformed_token";
320
+ case "ERR_JWT_CLAIM_VALIDATION_FAILED": {
321
+ const claim = field(error, "claim");
322
+ if (claim === "nbf" && field(error, "reason") === "check_failed") return "expired_token";
323
+ if (claim === "exp") return "invalid_claims";
324
+ return "invalid_token";
325
+ }
326
+ default:
327
+ return "invalid_token";
328
+ }
329
+ }
330
+ var hasClaim = (payload, name) => Object.hasOwn(payload, name) && payload[name] !== null && payload[name] !== "";
331
+ function principalOf(config, payload, options) {
332
+ const clientId = plainId(payload["client_id"]);
333
+ const invalid = () => refuse("invalid_claims", clientId);
334
+ const { aud, sub, client_id: client, scope, sid, auth_time: authTime, cv } = payload;
335
+ const publicId = payload["plasgos_public_id"];
336
+ if (aud !== config.audience || !nonEmptyString(sub) || !nonEmptyString(client)) return invalid();
337
+ if (scope !== void 0 && typeof scope !== "string") return invalid();
338
+ if (publicId !== void 0 && !(nonEmptyString(publicId) && publicId.length <= MAX_PUBLIC_ID_LENGTH)) return invalid();
339
+ const isUser = sid !== void 0;
340
+ if (isUser) {
341
+ if (!nonEmptyString(sid)) return invalid();
342
+ if (typeof authTime !== "number" || !Number.isSafeInteger(authTime) || authTime < 0) return invalid();
343
+ if (cv !== void 0 && !Number.isSafeInteger(cv)) return invalid();
344
+ } else if (!config.allowServiceTokens || sub !== client || typeof scope !== "string") {
345
+ return invalid();
346
+ }
347
+ const required = [...config.requiredClaims, ...options.requireClaims];
348
+ if (isUser && config.requireCredentialVersion) required.push("cv");
349
+ if (!required.every((name) => hasClaim(payload, name))) return invalid();
350
+ const scopes = Object.freeze(typeof scope === "string" ? scope.split(" ").filter((item) => item !== "") : []);
351
+ const claims = Object.freeze({ ...payload });
352
+ const principal = isUser ? {
353
+ kind: "user",
354
+ subject: sub,
355
+ clientId: client,
356
+ sessionId: sid,
357
+ authTime,
358
+ credentialVersion: cv ?? null,
359
+ scopes,
360
+ claims
361
+ } : { kind: "service", subject: sub, clientId: client, scopes, claims };
362
+ return { principal: Object.freeze(principal) };
363
+ }
364
+ async function check(state, header, options) {
365
+ const { config } = state;
366
+ if (typeof header !== "string" || !BEARER_SCHEME.test(header)) return refuse("missing_token");
367
+ if (header.length > MAX_JWT_LENGTH + "Bearer ".length) return refuse("malformed_token");
368
+ const token = BEARER_TOKEN.exec(header)?.[1];
369
+ if (token === void 0) return refuse("malformed_token");
370
+ const protectedHeader = decodeHeader(token.slice(0, token.indexOf(".")));
371
+ if (protectedHeader === null) return refuse("malformed_token");
372
+ const { alg, kid, typ } = protectedHeader;
373
+ if (alg !== SIGNING_ALG || !nonEmptyString(kid)) return refuse("unknown_key");
374
+ if (typeof typ !== "string" || !ACCEPTED_TYPES.includes(typ.toLowerCase())) return refuse("invalid_claims");
375
+ const nowMs = options.now ?? Date.now();
376
+ let payload;
377
+ try {
378
+ ({ payload } = await jwtVerify(token, state.keySet, {
379
+ algorithms: [SIGNING_ALG],
380
+ issuer: config.issuer,
381
+ audience: config.audience,
382
+ clockTolerance: config.clockToleranceSeconds,
383
+ requiredClaims: ["exp"],
384
+ currentDate: new Date(nowMs)
385
+ }));
386
+ } catch (error) {
387
+ return refuse(reasonOfVerifyError(error));
388
+ }
389
+ const outcome = principalOf(config, payload, options);
390
+ if (outcome.refusal !== void 0) return outcome;
391
+ const { principal } = outcome;
392
+ const clientId = plainId(principal.clientId);
393
+ if (config.isRevoked !== void 0) {
394
+ const revoked = await config.isRevoked(principal);
395
+ if (typeof revoked !== "boolean") throw new TypeError("isRevoked must return a boolean");
396
+ if (revoked) return refuse("revoked", clientId);
397
+ }
398
+ if (!options.scopes.every((scope) => principal.scopes.includes(scope))) return refuse("insufficient_scope", clientId);
399
+ if (options.maxAuthAge !== null) {
400
+ if (principal.kind !== "user" || Math.floor(nowMs / 1e3) - principal.authTime > options.maxAuthAge) {
401
+ return refuse("stale_auth", clientId);
402
+ }
403
+ }
404
+ return outcome;
405
+ }
406
+ function report(config, refusal, requestId) {
407
+ const { onReject } = config;
408
+ if (onReject === void 0) return;
409
+ const event = Object.freeze({
410
+ environment: config.environment,
411
+ reason: refusal.reason,
412
+ clientId: refusal.clientId,
413
+ requestId: plainId(requestId)
414
+ });
415
+ try {
416
+ Promise.resolve(onReject(event)).catch(() => void 0);
417
+ } catch {
418
+ }
419
+ }
420
+ async function verifyAccessToken(state, header, rawOptions, headerRequestId = null) {
421
+ const options = resolveVerifyOptions(rawOptions);
422
+ const outcome = await check(state, header, options);
423
+ if (outcome.refusal === void 0) return outcome.principal;
424
+ const error = new AuthVerifyError(outcome.refusal.reason, {
425
+ requiredScopes: options.scopes,
426
+ ...options.maxAuthAge !== null ? { maxAuthAge: options.maxAuthAge } : {}
427
+ });
428
+ report(state.config, outcome.refusal, options.requestId !== void 0 ? options.requestId : headerRequestId);
429
+ throw error;
430
+ }
431
+
432
+ // src/core/verifier.ts
433
+ function headersOf(request) {
434
+ const headers = isObject(request) ? request["headers"] : void 0;
435
+ if (!isObject(headers) || typeof headers["get"] !== "function") {
436
+ throw new TypeError("verifyRequest: request must be a Web Request");
437
+ }
438
+ const get = (name) => {
439
+ const value = headers["get"].call(headers, name);
440
+ return typeof value === "string" ? value : null;
441
+ };
442
+ return { authorization: get("authorization"), requestId: get("x-request-id") };
443
+ }
444
+ function createAccessTokenVerifier(options) {
445
+ const config = resolveVerifierConfig(options);
446
+ const state = {
447
+ config,
448
+ keySet: config.jwks !== null ? staticKeySet(config.jwks) : remoteKeySet(config)
449
+ };
450
+ return Object.freeze({
451
+ environment: config.environment,
452
+ issuer: config.issuer,
453
+ audience: config.audience,
454
+ verifyAuthorization: (header, verifyOptions) => verifyAccessToken(state, header, verifyOptions),
455
+ verifyRequest: async (request, verifyOptions) => {
456
+ const { authorization, requestId } = headersOf(request);
457
+ return verifyAccessToken(state, authorization, verifyOptions, requestId);
458
+ }
459
+ });
460
+ }
461
+
462
+ // src/nestjs/guard.ts
463
+ import { AuthVerifyError as AuthVerifyError2 } from "@plasgos/auth-shared";
464
+ import { HttpException, Inject, Injectable } from "@nestjs/common";
465
+ import { Reflector } from "@nestjs/core";
466
+
467
+ // src/core/response.ts
468
+ import { AUTH_VERIFY_REASONS } from "@plasgos/auth-shared";
469
+ var STATUSES = [401, 403, 503];
470
+ var ERROR_CODES = [
471
+ "invalid_token",
472
+ "insufficient_scope",
473
+ "insufficient_user_authentication",
474
+ "temporarily_unavailable"
475
+ ];
476
+ var REASONS = AUTH_VERIFY_REASONS;
477
+ function authRefusalOf(error) {
478
+ const fields = isObject(error) || error instanceof Error ? error : null;
479
+ if (fields === null) return null;
480
+ const challenge = fields["wwwAuthenticate"];
481
+ if (!REASONS.includes(fields["reason"]) || !STATUSES.includes(fields["status"]) || !ERROR_CODES.includes(fields["errorCode"]) || challenge !== null && typeof challenge !== "string") {
482
+ return null;
483
+ }
484
+ return {
485
+ status: fields["status"],
486
+ errorCode: fields["errorCode"],
487
+ wwwAuthenticate: challenge
488
+ };
489
+ }
490
+
491
+ // src/nestjs/tokens.ts
492
+ var PLASGOS_ACCESS_TOKEN_VERIFIER = "PLASGOS_ACCESS_TOKEN_VERIFIER";
493
+ var REQUIRED_SCOPES_KEY = "plasgos:required-scopes";
494
+ var RECENT_AUTH_KEY = "plasgos:recent-auth";
495
+
496
+ // src/nestjs/guard.ts
497
+ function refusalOf(error) {
498
+ const named = error instanceof AuthVerifyError2 || error instanceof Error && error.name === "AuthVerifyError";
499
+ return named ? authRefusalOf(error) : null;
500
+ }
501
+ function setHeader(response, name, value) {
502
+ if (typeof response !== "object" || response === null) return;
503
+ const target = response;
504
+ if (typeof target.setHeader === "function") target.setHeader.call(response, name, value);
505
+ else if (typeof target.header === "function") target.header.call(response, name, value);
506
+ }
507
+ var PlasgosAccessTokenGuard = class {
508
+ constructor(verifier, reflector) {
509
+ this.verifier = verifier;
510
+ this.reflector = reflector;
511
+ }
512
+ verifier;
513
+ reflector;
514
+ /**
515
+ * Verifies the request's token against the route requirements. Resolves `true`, or rejects with an
516
+ * `HttpException` for a refused token, or with the verifier's own non-token error.
517
+ *
518
+ * @example
519
+ * const allowed = await guard.canActivate(context);
520
+ */
521
+ async canActivate(context) {
522
+ const targets = [context.getHandler(), context.getClass()];
523
+ const scopes = this.reflector.getAllAndMerge(REQUIRED_SCOPES_KEY, targets);
524
+ const maxAuthAge = this.reflector.getAllAndOverride(RECENT_AUTH_KEY, targets);
525
+ const http = context.switchToHttp();
526
+ const request = http.getRequest();
527
+ const authorization = request.headers?.["authorization"];
528
+ const requestId = request.headers?.["x-request-id"];
529
+ const options = {
530
+ ...scopes.length > 0 ? { scopes: [...new Set(scopes)] } : {},
531
+ ...maxAuthAge !== void 0 ? { maxAuthAge } : {},
532
+ ...typeof requestId === "string" ? { requestId } : {}
533
+ };
534
+ let principal;
535
+ try {
536
+ principal = await this.verifier.verifyAuthorization(typeof authorization === "string" ? authorization : void 0, options);
537
+ } catch (error) {
538
+ const refusal = refusalOf(error);
539
+ if (refusal === null) throw error;
540
+ const response = http.getResponse();
541
+ setHeader(response, "Cache-Control", "no-store");
542
+ if (refusal.wwwAuthenticate !== null) setHeader(response, "WWW-Authenticate", refusal.wwwAuthenticate);
543
+ throw new HttpException({ error: refusal.errorCode }, refusal.status);
544
+ }
545
+ request.plasgosPrincipal = principal;
546
+ return true;
547
+ }
548
+ };
549
+ Injectable()(PlasgosAccessTokenGuard);
550
+ Inject(PLASGOS_ACCESS_TOKEN_VERIFIER)(PlasgosAccessTokenGuard, void 0, 0);
551
+ Inject(Reflector)(PlasgosAccessTokenGuard, void 0, 1);
552
+
553
+ // src/nestjs/module.ts
554
+ function module(provider, imports) {
555
+ return {
556
+ module: PlasgosAuthModule,
557
+ global: true,
558
+ ...imports !== void 0 ? { imports } : {},
559
+ providers: [...provider ?? [], PlasgosAccessTokenGuard],
560
+ exports: [PLASGOS_ACCESS_TOKEN_VERIFIER, PlasgosAccessTokenGuard]
561
+ };
562
+ }
563
+ var PlasgosAuthModule = class {
564
+ /**
565
+ * The module with fixed options (the options of `createAccessTokenVerifier`). By default the options
566
+ * are user-only and `isRevoked` receives a `UserAccessPrincipal`; to accept service tokens too, name
567
+ * the principal type: `forRoot<AccessPrincipal>({ …, allowServiceTokens: true })`.
568
+ *
569
+ * @example
570
+ * PlasgosAuthModule.forRoot({ environment: "sandbox", issuer, audience, isRevoked: () => false });
571
+ */
572
+ static forRoot(options) {
573
+ return module([
574
+ { provide: PLASGOS_ACCESS_TOKEN_VERIFIER, useFactory: () => createAccessTokenVerifier(options) }
575
+ ]);
576
+ }
577
+ /**
578
+ * The module with options from a factory, for example from a config service. A `ConfigError` from
579
+ * the returned options, or an error of the factory, fails the app's start.
580
+ *
581
+ * @example
582
+ * PlasgosAuthModule.forRootAsync({ inject: [ConfigService], useFactory: (config: ConfigService) => config.get("plasgos") });
583
+ */
584
+ static forRootAsync(options) {
585
+ const { useFactory } = options;
586
+ return module(
587
+ [
588
+ {
589
+ provide: PLASGOS_ACCESS_TOKEN_VERIFIER,
590
+ useFactory: async (...args) => createAccessTokenVerifier(await useFactory(...args)),
591
+ inject: options.inject ?? []
592
+ }
593
+ ],
594
+ options.imports
595
+ );
596
+ }
597
+ };
598
+ Module({})(PlasgosAuthModule);
599
+
600
+ // src/nestjs/decorators.ts
601
+ import { SetMetadata, createParamDecorator } from "@nestjs/common";
602
+ var DEFAULT_RECENT_AUTH_SECONDS = 600;
603
+ function RequireScopes(...scopes) {
604
+ if (scopes.length === 0) throw new TypeError("RequireScopes: give at least one scope");
605
+ const { scopes: checked } = resolveRequirements("RequireScopes", { scopes });
606
+ return SetMetadata(REQUIRED_SCOPES_KEY, checked);
607
+ }
608
+ function RequireRecentAuth(maxAgeSeconds = DEFAULT_RECENT_AUTH_SECONDS) {
609
+ const raw = maxAgeSeconds;
610
+ if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0) {
611
+ throw new TypeError("RequireRecentAuth: maxAgeSeconds must be a positive safe integer");
612
+ }
613
+ return SetMetadata(RECENT_AUTH_KEY, raw);
614
+ }
615
+ var principalParam = createParamDecorator((_data, context) => {
616
+ const request = context.switchToHttp().getRequest();
617
+ const principal = request.plasgosPrincipal;
618
+ if (principal === void 0) {
619
+ throw new Error("PlasgosPrincipal: PlasgosAccessTokenGuard did not run for this request");
620
+ }
621
+ return principal;
622
+ });
623
+ var PlasgosPrincipal = () => principalParam();
624
+
625
+ // src/nestjs/index.ts
626
+ import { AuthVerifyError as AuthVerifyError3, ConfigError as ConfigError2 } from "@plasgos/auth-shared";
627
+ export {
628
+ AuthVerifyError3 as AuthVerifyError,
629
+ ConfigError2 as ConfigError,
630
+ PLASGOS_ACCESS_TOKEN_VERIFIER,
631
+ PlasgosAccessTokenGuard,
632
+ PlasgosAuthModule,
633
+ PlasgosPrincipal,
634
+ RequireRecentAuth,
635
+ RequireScopes
636
+ };
637
+ //# sourceMappingURL=nestjs.js.map