@plasgos/auth-verify 0.1.0-next.2 → 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 +14 -0
- package/README.md +51 -15
- 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 +8 -6
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +9 -3
- package/dist/webhook.d.ts +9 -3
- package/dist/webhook.js +8 -6
- package/dist/webhook.js.map +1 -1
- package/docs/bff-express.md +1314 -0
- package/docs/consumers.md +10 -2
- package/docs/error.md +195 -10
- package/docs/examples/auth-verify-readme.ts +24 -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/env.ts +52 -1
- 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-verifier.ts +54 -0
- package/docs/login-web.md +39 -7
- package/docs/memulai.md +94 -14
- package/docs/server-ke-server.md +12 -0
- package/docs/verifikasi-token.md +1219 -0
- package/docs/webhook.md +191 -6
- package/package.json +61 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
// src/config.ts
|
|
2
|
+
var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3
|
+
var isBlank = (value) => typeof value === "string" && value.trim() === "";
|
|
4
|
+
function integerInRange(problems, raw, field2, range) {
|
|
5
|
+
if (raw === void 0) return range.fallback;
|
|
6
|
+
if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;
|
|
7
|
+
problems.push(`${field2} must be an integer from ${String(range.min)} to ${String(range.max)}`);
|
|
8
|
+
return range.fallback;
|
|
9
|
+
}
|
|
10
|
+
function optionalFunction(problems, raw, field2) {
|
|
11
|
+
if (raw === void 0) return void 0;
|
|
12
|
+
if (typeof raw === "function") return raw;
|
|
13
|
+
problems.push(`${field2} must be a function`);
|
|
14
|
+
return void 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// src/core/config.ts
|
|
18
|
+
import { ConfigError, PRODUCTION_ISSUER, environmentProblems, parseAudience, parseIssuer } from "@plasgos/auth-shared";
|
|
19
|
+
var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
|
|
20
|
+
var MAX_CLOCK_TOLERANCE_SECONDS = 60;
|
|
21
|
+
var DEFAULT_JWKS_MS = 5e3;
|
|
22
|
+
var MAX_TIMEOUT_MS = 6e4;
|
|
23
|
+
var MAX_REQUIRED_CLAIMS = 16;
|
|
24
|
+
var CLAIM_NAME = /^[A-Za-z0-9_]{1,64}$/;
|
|
25
|
+
var CREDENTIAL_VERSION_PATH = "/crm";
|
|
26
|
+
var PROBLEM = {
|
|
27
|
+
https: 'backchannelUrl must use https: when environment is "production" unless allowInsecureBackchannel is true',
|
|
28
|
+
isRevokedRequired: "isRevoked is required for a crm audience",
|
|
29
|
+
requireClaims: `requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`,
|
|
30
|
+
jwks: "jwks must be a JSON Web Key Set",
|
|
31
|
+
jwksSandboxOnly: 'jwks is only allowed when environment is "sandbox"'
|
|
32
|
+
};
|
|
33
|
+
var RESOURCE_PROBLEM = 'environment is "production" but resource is not a production audience';
|
|
34
|
+
var AUDIENCE_PROBLEM = 'environment is "production" but audience is not a production audience';
|
|
35
|
+
var globalFetch = (input, init) => globalThis.fetch(input, init);
|
|
36
|
+
function needsCredentialVersion(audience) {
|
|
37
|
+
return new URL(audience).pathname.replace(/\/+$/, "") === CREDENTIAL_VERSION_PATH;
|
|
38
|
+
}
|
|
39
|
+
function parsed(problems, parse) {
|
|
40
|
+
try {
|
|
41
|
+
return parse();
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (!(error instanceof ConfigError)) throw error;
|
|
44
|
+
problems.push(...error.problems);
|
|
45
|
+
return void 0;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function requiredClaimsOf(problems, raw) {
|
|
49
|
+
if (raw === void 0) return Object.freeze([]);
|
|
50
|
+
if (!Array.isArray(raw) || raw.length > MAX_REQUIRED_CLAIMS || !raw.every((name) => typeof name === "string" && CLAIM_NAME.test(name))) {
|
|
51
|
+
problems.push(PROBLEM.requireClaims);
|
|
52
|
+
return Object.freeze([]);
|
|
53
|
+
}
|
|
54
|
+
return Object.freeze([...new Set(raw)]);
|
|
55
|
+
}
|
|
56
|
+
function jwksOf(problems, raw) {
|
|
57
|
+
const keys = isObject(raw) ? raw["keys"] : void 0;
|
|
58
|
+
if (!Array.isArray(keys) || keys.length === 0 || !keys.every((key) => isObject(key))) {
|
|
59
|
+
problems.push(PROBLEM.jwks);
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
return Object.freeze({ keys: Object.freeze(keys.map((key) => Object.freeze({ ...key }))) });
|
|
63
|
+
}
|
|
64
|
+
function timeoutsOf(problems, raw) {
|
|
65
|
+
if (raw === void 0) return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });
|
|
66
|
+
if (!isObject(raw)) {
|
|
67
|
+
problems.push("timeouts must be an object");
|
|
68
|
+
return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });
|
|
69
|
+
}
|
|
70
|
+
const jwksMs = integerInRange(problems, raw["jwksMs"], "timeouts.jwksMs", {
|
|
71
|
+
min: 1,
|
|
72
|
+
max: MAX_TIMEOUT_MS,
|
|
73
|
+
fallback: DEFAULT_JWKS_MS
|
|
74
|
+
});
|
|
75
|
+
return Object.freeze({ jwksMs });
|
|
76
|
+
}
|
|
77
|
+
function resolveVerifierConfig(raw) {
|
|
78
|
+
if (!isObject(raw)) throw new ConfigError(["options must be an object"]);
|
|
79
|
+
const problems = [];
|
|
80
|
+
const text = (field2) => {
|
|
81
|
+
const value = raw[field2];
|
|
82
|
+
if (value === void 0 || typeof value === "string") return value;
|
|
83
|
+
problems.push(`${field2} must be a string`);
|
|
84
|
+
return void 0;
|
|
85
|
+
};
|
|
86
|
+
const given = (field2) => raw[field2] !== void 0;
|
|
87
|
+
const flag = (field2) => {
|
|
88
|
+
const value = raw[field2];
|
|
89
|
+
if (value === void 0 || typeof value === "boolean") return value === true;
|
|
90
|
+
problems.push(`${field2} must be a boolean`);
|
|
91
|
+
return false;
|
|
92
|
+
};
|
|
93
|
+
const environment = raw["environment"];
|
|
94
|
+
const allowInsecureHttp = raw["allowInsecureHttp"] === true;
|
|
95
|
+
const issuerRaw = text("issuer");
|
|
96
|
+
const issuer = given("issuer") && issuerRaw === void 0 ? void 0 : parsed(problems, () => parseIssuer(issuerRaw, { field: "issuer", allowInsecureHttp }));
|
|
97
|
+
const audienceRaw = text("audience");
|
|
98
|
+
const audience = given("audience") && audienceRaw === void 0 ? void 0 : parsed(problems, () => parseAudience(audienceRaw, { field: "audience", allowInsecureHttp }));
|
|
99
|
+
const backchannelRaw = given("backchannelUrl") && !isBlank(raw["backchannelUrl"]) ? text("backchannelUrl") : void 0;
|
|
100
|
+
const backchannelUrl = backchannelRaw === void 0 ? void 0 : parsed(problems, () => parseIssuer(backchannelRaw, { field: "backchannelUrl", allowInsecureHttp: true }));
|
|
101
|
+
const insecureBackchannelRaw = raw["allowInsecureBackchannel"];
|
|
102
|
+
if (environment === "production" && backchannelUrl !== void 0 && new URL(backchannelUrl).protocol === "http:" && insecureBackchannelRaw !== true) {
|
|
103
|
+
problems.push(PROBLEM.https);
|
|
104
|
+
}
|
|
105
|
+
const allowInsecureBackchannel = flag("allowInsecureBackchannel");
|
|
106
|
+
const allowServiceTokens = flag("allowServiceTokens");
|
|
107
|
+
const requiredClaims = requiredClaimsOf(problems, raw["requireClaims"]);
|
|
108
|
+
const clockToleranceSeconds = integerInRange(problems, raw["clockToleranceSeconds"], "clockToleranceSeconds", {
|
|
109
|
+
min: 0,
|
|
110
|
+
max: MAX_CLOCK_TOLERANCE_SECONDS,
|
|
111
|
+
fallback: DEFAULT_CLOCK_TOLERANCE_SECONDS
|
|
112
|
+
});
|
|
113
|
+
const timeouts = timeoutsOf(problems, raw["timeouts"]);
|
|
114
|
+
const jwks = given("jwks") ? jwksOf(problems, raw["jwks"]) : null;
|
|
115
|
+
if (given("jwks") && environment === "production") problems.push(PROBLEM.jwksSandboxOnly);
|
|
116
|
+
flag("allowInsecureHttp");
|
|
117
|
+
const fetch = optionalFunction(problems, raw["fetch"], "fetch");
|
|
118
|
+
const requireCredentialVersion = audience !== void 0 && needsCredentialVersion(audience);
|
|
119
|
+
const isRevoked = optionalFunction(problems, raw["isRevoked"], "isRevoked");
|
|
120
|
+
if (requireCredentialVersion && !given("isRevoked")) problems.push(PROBLEM.isRevokedRequired);
|
|
121
|
+
const onReject = optionalFunction(problems, raw["onReject"], "onReject");
|
|
122
|
+
const guard = environmentProblems({
|
|
123
|
+
environment,
|
|
124
|
+
issuer: issuer ?? (environment === "production" ? PRODUCTION_ISSUER : ""),
|
|
125
|
+
allowInsecureHttp: raw["allowInsecureHttp"],
|
|
126
|
+
...audience !== void 0 ? { audiences: [audience] } : {},
|
|
127
|
+
...backchannelUrl !== void 0 ? { backchannelUrl } : {}
|
|
128
|
+
});
|
|
129
|
+
const named = guard.map((problem) => problem === RESOURCE_PROBLEM ? AUDIENCE_PROBLEM : problem);
|
|
130
|
+
if (named.length > 0 || problems.length > 0) throw new ConfigError([...named, ...problems]);
|
|
131
|
+
return Object.freeze({
|
|
132
|
+
environment,
|
|
133
|
+
issuer,
|
|
134
|
+
audience,
|
|
135
|
+
backchannelUrl: backchannelUrl ?? null,
|
|
136
|
+
allowInsecureBackchannel,
|
|
137
|
+
allowServiceTokens,
|
|
138
|
+
requiredClaims,
|
|
139
|
+
requireCredentialVersion,
|
|
140
|
+
clockToleranceSeconds,
|
|
141
|
+
timeouts,
|
|
142
|
+
jwks,
|
|
143
|
+
fetch: fetch ?? globalFetch,
|
|
144
|
+
isRevoked,
|
|
145
|
+
onReject
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/core/jwks.ts
|
|
150
|
+
import { OIDC_PATHS } from "@plasgos/auth-shared";
|
|
151
|
+
import { createLocalJWKSet, createRemoteJWKSet, customFetch } from "jose";
|
|
152
|
+
var COOLDOWN_MS = 3e4;
|
|
153
|
+
var MAX_JWKS_BYTES = 65536;
|
|
154
|
+
var KEY_SET_UNAVAILABLE = "ERR_PLASGOS_JWKS_UNAVAILABLE";
|
|
155
|
+
var JOSE_UNAVAILABLE_CODES = /* @__PURE__ */ new Set([KEY_SET_UNAVAILABLE, "ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID"]);
|
|
156
|
+
function unavailable() {
|
|
157
|
+
return Object.assign(new Error("Plasgos key set unavailable"), { code: KEY_SET_UNAVAILABLE });
|
|
158
|
+
}
|
|
159
|
+
function isKeySetUnavailable(error) {
|
|
160
|
+
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
|
161
|
+
const { code } = error;
|
|
162
|
+
return typeof code === "string" && JOSE_UNAVAILABLE_CODES.has(code);
|
|
163
|
+
}
|
|
164
|
+
var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
165
|
+
async function readCapped(response) {
|
|
166
|
+
const length = response.headers.get("content-length");
|
|
167
|
+
if (length !== null && Number(length) > MAX_JWKS_BYTES) throw unavailable();
|
|
168
|
+
if (response.body === null) return new Uint8Array(0);
|
|
169
|
+
const reader = response.body.getReader();
|
|
170
|
+
const chunks = [];
|
|
171
|
+
let total = 0;
|
|
172
|
+
for (; ; ) {
|
|
173
|
+
const result = await reader.read();
|
|
174
|
+
if (result.done) break;
|
|
175
|
+
const chunk = result.value;
|
|
176
|
+
if (!(chunk instanceof Uint8Array)) throw unavailable();
|
|
177
|
+
total += chunk.byteLength;
|
|
178
|
+
if (total > MAX_JWKS_BYTES) {
|
|
179
|
+
void reader.cancel().catch(() => void 0);
|
|
180
|
+
throw unavailable();
|
|
181
|
+
}
|
|
182
|
+
chunks.push(chunk);
|
|
183
|
+
}
|
|
184
|
+
const bytes = new Uint8Array(total);
|
|
185
|
+
let offset = 0;
|
|
186
|
+
for (const chunk of chunks) {
|
|
187
|
+
bytes.set(chunk, offset);
|
|
188
|
+
offset += chunk.byteLength;
|
|
189
|
+
}
|
|
190
|
+
return bytes;
|
|
191
|
+
}
|
|
192
|
+
function isKeySetJson(bytes) {
|
|
193
|
+
try {
|
|
194
|
+
const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
195
|
+
return isObject2(json) && Array.isArray(json["keys"]) && json["keys"].every((key) => isObject2(key));
|
|
196
|
+
} catch {
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function boundedFetch(fetchImpl, jwksMs) {
|
|
201
|
+
return async (url, init) => {
|
|
202
|
+
const controller = new AbortController();
|
|
203
|
+
const abort = () => {
|
|
204
|
+
controller.abort();
|
|
205
|
+
};
|
|
206
|
+
const outer = init.signal;
|
|
207
|
+
if (outer?.aborted === true) abort();
|
|
208
|
+
outer?.addEventListener("abort", abort, { once: true });
|
|
209
|
+
const timer = setTimeout(abort, jwksMs);
|
|
210
|
+
const aborted = new Promise((_, reject) => {
|
|
211
|
+
const fail = () => {
|
|
212
|
+
reject(unavailable());
|
|
213
|
+
};
|
|
214
|
+
if (controller.signal.aborted) fail();
|
|
215
|
+
else controller.signal.addEventListener("abort", fail, { once: true });
|
|
216
|
+
});
|
|
217
|
+
aborted.catch(() => void 0);
|
|
218
|
+
try {
|
|
219
|
+
const response = await Promise.race([
|
|
220
|
+
fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal }),
|
|
221
|
+
aborted
|
|
222
|
+
]);
|
|
223
|
+
if (response.status !== 200) {
|
|
224
|
+
void response.body?.cancel().catch(() => void 0);
|
|
225
|
+
throw unavailable();
|
|
226
|
+
}
|
|
227
|
+
const bytes = await Promise.race([readCapped(response), aborted]);
|
|
228
|
+
if (!isKeySetJson(bytes)) throw unavailable();
|
|
229
|
+
return new Response(bytes, { status: 200, headers: { "content-type": "application/json" } });
|
|
230
|
+
} catch {
|
|
231
|
+
throw unavailable();
|
|
232
|
+
} finally {
|
|
233
|
+
clearTimeout(timer);
|
|
234
|
+
outer?.removeEventListener("abort", abort);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function remoteKeySet(source) {
|
|
239
|
+
const url = new URL(`${source.backchannelUrl ?? source.issuer}${OIDC_PATHS.jwks}`);
|
|
240
|
+
return createRemoteJWKSet(url, {
|
|
241
|
+
timeoutDuration: source.timeouts.jwksMs,
|
|
242
|
+
cooldownDuration: COOLDOWN_MS,
|
|
243
|
+
[customFetch]: boundedFetch(source.fetch, source.timeouts.jwksMs)
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
function staticKeySet(jwks) {
|
|
247
|
+
return createLocalJWKSet(jwks);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// src/core/verify.ts
|
|
251
|
+
import { ACCESS_TOKEN_TYPES, AuthVerifyError, MAX_JWT_LENGTH, SIGNING_ALG } from "@plasgos/auth-shared";
|
|
252
|
+
import { jwtVerify } from "jose";
|
|
253
|
+
|
|
254
|
+
// src/core/requirements.ts
|
|
255
|
+
var SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
|
|
256
|
+
function resolveRequirements(label, raw) {
|
|
257
|
+
if (raw === void 0) return { scopes: [], requireClaims: [], maxAuthAge: null };
|
|
258
|
+
if (!isObject(raw)) throw new TypeError(`${label}: options must be an object`);
|
|
259
|
+
const { scopes, requireClaims, maxAuthAge } = raw;
|
|
260
|
+
if (scopes !== void 0 && (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === "string" && SCOPE_TOKEN.test(scope)))) {
|
|
261
|
+
throw new TypeError(`${label}: scopes must be a list of scope tokens`);
|
|
262
|
+
}
|
|
263
|
+
if (requireClaims !== void 0 && (!Array.isArray(requireClaims) || requireClaims.length > MAX_REQUIRED_CLAIMS || !requireClaims.every((name) => typeof name === "string" && CLAIM_NAME.test(name)))) {
|
|
264
|
+
throw new TypeError(`${label}: requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`);
|
|
265
|
+
}
|
|
266
|
+
if (maxAuthAge !== void 0 && (typeof maxAuthAge !== "number" || !Number.isSafeInteger(maxAuthAge) || maxAuthAge <= 0)) {
|
|
267
|
+
throw new TypeError(`${label}: maxAuthAge must be a positive safe integer`);
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
scopes: Object.freeze([...new Set(scopes ?? [])]),
|
|
271
|
+
requireClaims: Object.freeze([...new Set(requireClaims ?? [])]),
|
|
272
|
+
maxAuthAge: maxAuthAge ?? null
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function resolveVerifyOptions(raw) {
|
|
276
|
+
const requirements = resolveRequirements("verify", raw);
|
|
277
|
+
const fields = isObject(raw) ? raw : {};
|
|
278
|
+
const { requestId, now } = fields;
|
|
279
|
+
if (requestId !== void 0 && requestId !== null && typeof requestId !== "string") {
|
|
280
|
+
throw new TypeError("verify: requestId must be a string");
|
|
281
|
+
}
|
|
282
|
+
if (now !== void 0 && (typeof now !== "number" || !Number.isFinite(now))) {
|
|
283
|
+
throw new TypeError("verify: now must be a finite number");
|
|
284
|
+
}
|
|
285
|
+
return { ...requirements, requestId, now: now ?? null };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// src/core/verify.ts
|
|
289
|
+
var BEARER_SCHEME = /^Bearer /i;
|
|
290
|
+
var BEARER_TOKEN = /^Bearer +([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)$/i;
|
|
291
|
+
var PLAIN_ID = /^[\w.:-]{1,128}$/;
|
|
292
|
+
var MAX_PUBLIC_ID_LENGTH = 128;
|
|
293
|
+
var ACCEPTED_TYPES = ACCESS_TOKEN_TYPES;
|
|
294
|
+
var refuse = (reason, clientId = null) => ({ refusal: { reason, clientId } });
|
|
295
|
+
var nonEmptyString = (value) => typeof value === "string" && value !== "";
|
|
296
|
+
var plainId = (value) => typeof value === "string" && PLAIN_ID.test(value) ? value : null;
|
|
297
|
+
function decodeHeader(segment) {
|
|
298
|
+
try {
|
|
299
|
+
const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(segment, "base64url")));
|
|
300
|
+
return isObject(json) ? json : null;
|
|
301
|
+
} catch {
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function field(error, name) {
|
|
306
|
+
return isObject(error) || error instanceof Error ? error[name] : void 0;
|
|
307
|
+
}
|
|
308
|
+
function reasonOfVerifyError(error) {
|
|
309
|
+
if (isKeySetUnavailable(error)) return "unavailable";
|
|
310
|
+
switch (field(error, "code")) {
|
|
311
|
+
case "ERR_JWKS_NO_MATCHING_KEY":
|
|
312
|
+
return "unknown_key";
|
|
313
|
+
case "ERR_JWT_EXPIRED":
|
|
314
|
+
return "expired_token";
|
|
315
|
+
case "ERR_JWT_INVALID":
|
|
316
|
+
return "malformed_token";
|
|
317
|
+
case "ERR_JWT_CLAIM_VALIDATION_FAILED": {
|
|
318
|
+
const claim = field(error, "claim");
|
|
319
|
+
if (claim === "nbf" && field(error, "reason") === "check_failed") return "expired_token";
|
|
320
|
+
if (claim === "exp") return "invalid_claims";
|
|
321
|
+
return "invalid_token";
|
|
322
|
+
}
|
|
323
|
+
default:
|
|
324
|
+
return "invalid_token";
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
var hasClaim = (payload, name) => Object.hasOwn(payload, name) && payload[name] !== null && payload[name] !== "";
|
|
328
|
+
function principalOf(config, payload, options) {
|
|
329
|
+
const clientId = plainId(payload["client_id"]);
|
|
330
|
+
const invalid = () => refuse("invalid_claims", clientId);
|
|
331
|
+
const { aud, sub, client_id: client, scope, sid, auth_time: authTime, cv } = payload;
|
|
332
|
+
const publicId = payload["plasgos_public_id"];
|
|
333
|
+
if (aud !== config.audience || !nonEmptyString(sub) || !nonEmptyString(client)) return invalid();
|
|
334
|
+
if (scope !== void 0 && typeof scope !== "string") return invalid();
|
|
335
|
+
if (publicId !== void 0 && !(nonEmptyString(publicId) && publicId.length <= MAX_PUBLIC_ID_LENGTH)) return invalid();
|
|
336
|
+
const isUser = sid !== void 0;
|
|
337
|
+
if (isUser) {
|
|
338
|
+
if (!nonEmptyString(sid)) return invalid();
|
|
339
|
+
if (typeof authTime !== "number" || !Number.isSafeInteger(authTime) || authTime < 0) return invalid();
|
|
340
|
+
if (cv !== void 0 && !Number.isSafeInteger(cv)) return invalid();
|
|
341
|
+
} else if (!config.allowServiceTokens || sub !== client || typeof scope !== "string") {
|
|
342
|
+
return invalid();
|
|
343
|
+
}
|
|
344
|
+
const required = [...config.requiredClaims, ...options.requireClaims];
|
|
345
|
+
if (isUser && config.requireCredentialVersion) required.push("cv");
|
|
346
|
+
if (!required.every((name) => hasClaim(payload, name))) return invalid();
|
|
347
|
+
const scopes = Object.freeze(typeof scope === "string" ? scope.split(" ").filter((item) => item !== "") : []);
|
|
348
|
+
const claims = Object.freeze({ ...payload });
|
|
349
|
+
const principal = isUser ? {
|
|
350
|
+
kind: "user",
|
|
351
|
+
subject: sub,
|
|
352
|
+
clientId: client,
|
|
353
|
+
sessionId: sid,
|
|
354
|
+
authTime,
|
|
355
|
+
credentialVersion: cv ?? null,
|
|
356
|
+
scopes,
|
|
357
|
+
claims
|
|
358
|
+
} : { kind: "service", subject: sub, clientId: client, scopes, claims };
|
|
359
|
+
return { principal: Object.freeze(principal) };
|
|
360
|
+
}
|
|
361
|
+
async function check(state, header, options) {
|
|
362
|
+
const { config } = state;
|
|
363
|
+
if (typeof header !== "string" || !BEARER_SCHEME.test(header)) return refuse("missing_token");
|
|
364
|
+
if (header.length > MAX_JWT_LENGTH + "Bearer ".length) return refuse("malformed_token");
|
|
365
|
+
const token = BEARER_TOKEN.exec(header)?.[1];
|
|
366
|
+
if (token === void 0) return refuse("malformed_token");
|
|
367
|
+
const protectedHeader = decodeHeader(token.slice(0, token.indexOf(".")));
|
|
368
|
+
if (protectedHeader === null) return refuse("malformed_token");
|
|
369
|
+
const { alg, kid, typ } = protectedHeader;
|
|
370
|
+
if (alg !== SIGNING_ALG || !nonEmptyString(kid)) return refuse("unknown_key");
|
|
371
|
+
if (typeof typ !== "string" || !ACCEPTED_TYPES.includes(typ.toLowerCase())) return refuse("invalid_claims");
|
|
372
|
+
const nowMs = options.now ?? Date.now();
|
|
373
|
+
let payload;
|
|
374
|
+
try {
|
|
375
|
+
({ payload } = await jwtVerify(token, state.keySet, {
|
|
376
|
+
algorithms: [SIGNING_ALG],
|
|
377
|
+
issuer: config.issuer,
|
|
378
|
+
audience: config.audience,
|
|
379
|
+
clockTolerance: config.clockToleranceSeconds,
|
|
380
|
+
requiredClaims: ["exp"],
|
|
381
|
+
currentDate: new Date(nowMs)
|
|
382
|
+
}));
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return refuse(reasonOfVerifyError(error));
|
|
385
|
+
}
|
|
386
|
+
const outcome = principalOf(config, payload, options);
|
|
387
|
+
if (outcome.refusal !== void 0) return outcome;
|
|
388
|
+
const { principal } = outcome;
|
|
389
|
+
const clientId = plainId(principal.clientId);
|
|
390
|
+
if (config.isRevoked !== void 0) {
|
|
391
|
+
const revoked = await config.isRevoked(principal);
|
|
392
|
+
if (typeof revoked !== "boolean") throw new TypeError("isRevoked must return a boolean");
|
|
393
|
+
if (revoked) return refuse("revoked", clientId);
|
|
394
|
+
}
|
|
395
|
+
if (!options.scopes.every((scope) => principal.scopes.includes(scope))) return refuse("insufficient_scope", clientId);
|
|
396
|
+
if (options.maxAuthAge !== null) {
|
|
397
|
+
if (principal.kind !== "user" || Math.floor(nowMs / 1e3) - principal.authTime > options.maxAuthAge) {
|
|
398
|
+
return refuse("stale_auth", clientId);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return outcome;
|
|
402
|
+
}
|
|
403
|
+
function report(config, refusal, requestId) {
|
|
404
|
+
const { onReject } = config;
|
|
405
|
+
if (onReject === void 0) return;
|
|
406
|
+
const event = Object.freeze({
|
|
407
|
+
environment: config.environment,
|
|
408
|
+
reason: refusal.reason,
|
|
409
|
+
clientId: refusal.clientId,
|
|
410
|
+
requestId: plainId(requestId)
|
|
411
|
+
});
|
|
412
|
+
try {
|
|
413
|
+
Promise.resolve(onReject(event)).catch(() => void 0);
|
|
414
|
+
} catch {
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
async function verifyAccessToken(state, header, rawOptions, headerRequestId = null) {
|
|
418
|
+
const options = resolveVerifyOptions(rawOptions);
|
|
419
|
+
const outcome = await check(state, header, options);
|
|
420
|
+
if (outcome.refusal === void 0) return outcome.principal;
|
|
421
|
+
const error = new AuthVerifyError(outcome.refusal.reason, {
|
|
422
|
+
requiredScopes: options.scopes,
|
|
423
|
+
...options.maxAuthAge !== null ? { maxAuthAge: options.maxAuthAge } : {}
|
|
424
|
+
});
|
|
425
|
+
report(state.config, outcome.refusal, options.requestId !== void 0 ? options.requestId : headerRequestId);
|
|
426
|
+
throw error;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// src/core/verifier.ts
|
|
430
|
+
function headersOf(request) {
|
|
431
|
+
const headers = isObject(request) ? request["headers"] : void 0;
|
|
432
|
+
if (!isObject(headers) || typeof headers["get"] !== "function") {
|
|
433
|
+
throw new TypeError("verifyRequest: request must be a Web Request");
|
|
434
|
+
}
|
|
435
|
+
const get = (name) => {
|
|
436
|
+
const value = headers["get"].call(headers, name);
|
|
437
|
+
return typeof value === "string" ? value : null;
|
|
438
|
+
};
|
|
439
|
+
return { authorization: get("authorization"), requestId: get("x-request-id") };
|
|
440
|
+
}
|
|
441
|
+
function createAccessTokenVerifier(options) {
|
|
442
|
+
const config = resolveVerifierConfig(options);
|
|
443
|
+
const state = {
|
|
444
|
+
config,
|
|
445
|
+
keySet: config.jwks !== null ? staticKeySet(config.jwks) : remoteKeySet(config)
|
|
446
|
+
};
|
|
447
|
+
return Object.freeze({
|
|
448
|
+
environment: config.environment,
|
|
449
|
+
issuer: config.issuer,
|
|
450
|
+
audience: config.audience,
|
|
451
|
+
verifyAuthorization: (header, verifyOptions) => verifyAccessToken(state, header, verifyOptions),
|
|
452
|
+
verifyRequest: async (request, verifyOptions) => {
|
|
453
|
+
const { authorization, requestId } = headersOf(request);
|
|
454
|
+
return verifyAccessToken(state, authorization, verifyOptions, requestId);
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// src/core/response.ts
|
|
460
|
+
import { AUTH_VERIFY_REASONS } from "@plasgos/auth-shared";
|
|
461
|
+
var STATUSES = [401, 403, 503];
|
|
462
|
+
var ERROR_CODES = [
|
|
463
|
+
"invalid_token",
|
|
464
|
+
"insufficient_scope",
|
|
465
|
+
"insufficient_user_authentication",
|
|
466
|
+
"temporarily_unavailable"
|
|
467
|
+
];
|
|
468
|
+
var REASONS = AUTH_VERIFY_REASONS;
|
|
469
|
+
function authRefusalOf(error) {
|
|
470
|
+
const fields = isObject(error) || error instanceof Error ? error : null;
|
|
471
|
+
if (fields === null) return null;
|
|
472
|
+
const challenge = fields["wwwAuthenticate"];
|
|
473
|
+
if (!REASONS.includes(fields["reason"]) || !STATUSES.includes(fields["status"]) || !ERROR_CODES.includes(fields["errorCode"]) || challenge !== null && typeof challenge !== "string") {
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
return {
|
|
477
|
+
status: fields["status"],
|
|
478
|
+
errorCode: fields["errorCode"],
|
|
479
|
+
wwwAuthenticate: challenge
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function authErrorResponse(error) {
|
|
483
|
+
const refusal = authRefusalOf(error);
|
|
484
|
+
if (refusal === null) throw new TypeError("authErrorResponse: error must be an AuthVerifyError");
|
|
485
|
+
const headers = new Headers({ "content-type": "application/json", "cache-control": "no-store" });
|
|
486
|
+
if (refusal.wwwAuthenticate !== null) headers.set("www-authenticate", refusal.wwwAuthenticate);
|
|
487
|
+
return new Response(JSON.stringify({ error: refusal.errorCode }), { status: refusal.status, headers });
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// src/index.ts
|
|
491
|
+
import { AUTH_VERIFY_REASONS as AUTH_VERIFY_REASONS2, AuthVerifyError as AuthVerifyError2, ConfigError as ConfigError2 } from "@plasgos/auth-shared";
|
|
492
|
+
export {
|
|
493
|
+
AUTH_VERIFY_REASONS2 as AUTH_VERIFY_REASONS,
|
|
494
|
+
AuthVerifyError2 as AuthVerifyError,
|
|
495
|
+
ConfigError2 as ConfigError,
|
|
496
|
+
authErrorResponse,
|
|
497
|
+
createAccessTokenVerifier
|
|
498
|
+
};
|
|
499
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/core/config.ts","../src/core/jwks.ts","../src/core/verify.ts","../src/core/requirements.ts","../src/core/verifier.ts","../src/core/response.ts","../src/index.ts"],"sourcesContent":["// 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 { 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","export { createAccessTokenVerifier } from \"./core/verifier.js\";\nexport { authErrorResponse } from \"./core/response.js\";\nexport type {\n AccessPrincipal,\n AccessTokenVerifier,\n AccessTokenVerifierOptions,\n AuthRejectEvent,\n JsonWebKeySet,\n JwksFetch,\n ServiceAccessPrincipal,\n UserAccessPrincipal,\n VerifiedAccessTokenClaims,\n VerifyOptions,\n} from \"./core/types.js\";\n// The classes this entry throws, and the shared types of its options and principal: the same classes\n// as in @plasgos/auth-shared, so `instanceof` holds across the packages.\nexport { AUTH_VERIFY_REASONS, AuthVerifyError, ConfigError } from \"@plasgos/auth-shared\";\nexport type { AccessTokenClaims, AuthVerifyReason, Environment } from \"@plasgos/auth-shared\";\n"],"mappings":";AASO,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,KAAcA,QAA4D;AAC7H,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI,OAAO,QAAQ,WAAY,QAAO;AACtC,WAAS,KAAK,GAAGA,MAAK,qBAAqB;AAC3C,SAAO;AACT;;;ACjEA,SAAS,aAAa,mBAAmB,qBAAqB,eAAe,mBAAmB;AAOhG,IAAM,kCAAkC;AACxC,IAAM,8BAA8B;AACpC,IAAM,kBAAkB;AACxB,IAAM,iBAAiB;AAEhB,IAAM,sBAAsB;AAE5B,IAAM,aAAa;AAE1B,IAAM,0BAA0B;AAEhC,IAAM,UAAU;AAAA,EACd,OAAO;AAAA,EACP,mBAAmB;AAAA,EACnB,eAAe,2CAA2C,OAAO,mBAAmB,CAAC;AAAA,EACrF,MAAM;AAAA,EACN,iBAAiB;AACnB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