@plasgos/auth-verify 0.0.0-stage → 0.1.0-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/LICENSE +15 -0
- package/README.md +122 -2
- package/THIRD_PARTY_NOTICES.md +31 -0
- package/dist/express.cjs +157 -0
- package/dist/express.cjs.map +1 -0
- package/dist/express.d.cts +90 -0
- package/dist/express.d.ts +90 -0
- package/dist/express.js +127 -0
- package/dist/express.js.map +1 -0
- package/dist/index.cjs +1254 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +67 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +499 -0
- package/dist/index.js.map +1 -0
- package/dist/nestjs.cjs +1395 -0
- package/dist/nestjs.cjs.map +1 -0
- package/dist/nestjs.d.cts +153 -0
- package/dist/nestjs.d.ts +153 -0
- package/dist/nestjs.js +637 -0
- package/dist/nestjs.js.map +1 -0
- package/dist/types-CGtRnj59.d.cts +193 -0
- package/dist/types-CGtRnj59.d.ts +193 -0
- package/dist/webhook.cjs +296 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +196 -0
- package/dist/webhook.d.ts +196 -0
- package/dist/webhook.js +265 -0
- package/dist/webhook.js.map +1 -0
- package/docs/bff-express.md +1314 -0
- package/docs/consumers.md +98 -0
- package/docs/contoh-hitungcuan.md +255 -0
- package/docs/contoh-plaslink.md +244 -0
- package/docs/error.md +613 -0
- package/docs/examples/auth-verify-readme.ts +42 -0
- package/docs/examples/bff-express.ts +370 -0
- package/docs/examples/bff-proxy.ts +335 -0
- package/docs/examples/bff-redis-lock.ts +187 -0
- package/docs/examples/bff-revocation.ts +136 -0
- package/docs/examples/config-error.ts +24 -0
- package/docs/examples/env.ts +150 -0
- package/docs/examples/failure-log.ts +18 -0
- package/docs/examples/login-client.ts +46 -0
- package/docs/examples/login-flow.ts +186 -0
- package/docs/examples/plaslink-connect.ts +48 -0
- package/docs/examples/readme.ts +60 -0
- package/docs/examples/service-client.ts +105 -0
- package/docs/examples/session-store.ts +53 -0
- package/docs/examples/token-commonjs.cjs +95 -0
- package/docs/examples/token-express.ts +56 -0
- package/docs/examples/token-fetch.ts +24 -0
- package/docs/examples/token-nestjs-jest.ts +77 -0
- package/docs/examples/token-nestjs.ts +127 -0
- package/docs/examples/token-socket.ts +59 -0
- package/docs/examples/token-testing.ts +100 -0
- package/docs/examples/token-verifier.ts +132 -0
- package/docs/examples/user-events.ts +110 -0
- package/docs/examples/webhook-express.ts +46 -0
- package/docs/examples/webhook-fetch.ts +60 -0
- package/docs/examples/webhook-nestjs.ts +59 -0
- package/docs/examples/webhook-testing.ts +60 -0
- package/docs/examples/webhook-verifier.ts +197 -0
- package/docs/login-web.md +650 -0
- package/docs/memulai.md +419 -0
- package/docs/server-ke-server.md +287 -0
- package/docs/verifikasi-token.md +1219 -0
- package/docs/webhook.md +810 -0
- package/package.json +101 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1254 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
AUTH_VERIFY_REASONS: () => import_auth_shared5.AUTH_VERIFY_REASONS,
|
|
24
|
+
AuthVerifyError: () => import_auth_shared5.AuthVerifyError,
|
|
25
|
+
ConfigError: () => import_auth_shared5.ConfigError,
|
|
26
|
+
authErrorResponse: () => authErrorResponse,
|
|
27
|
+
createAccessTokenVerifier: () => createAccessTokenVerifier
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(src_exports);
|
|
30
|
+
|
|
31
|
+
// src/config.ts
|
|
32
|
+
var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
33
|
+
var isBlank = (value) => typeof value === "string" && value.trim() === "";
|
|
34
|
+
function integerInRange(problems, raw, field2, range) {
|
|
35
|
+
if (raw === void 0) return range.fallback;
|
|
36
|
+
if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;
|
|
37
|
+
problems.push(`${field2} must be an integer from ${String(range.min)} to ${String(range.max)}`);
|
|
38
|
+
return range.fallback;
|
|
39
|
+
}
|
|
40
|
+
function optionalFunction(problems, raw, field2) {
|
|
41
|
+
if (raw === void 0) return void 0;
|
|
42
|
+
if (typeof raw === "function") return raw;
|
|
43
|
+
problems.push(`${field2} must be a function`);
|
|
44
|
+
return void 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/core/config.ts
|
|
48
|
+
var import_auth_shared = require("@plasgos/auth-shared");
|
|
49
|
+
var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
|
|
50
|
+
var MAX_CLOCK_TOLERANCE_SECONDS = 60;
|
|
51
|
+
var DEFAULT_JWKS_MS = 5e3;
|
|
52
|
+
var MAX_TIMEOUT_MS = 6e4;
|
|
53
|
+
var MAX_REQUIRED_CLAIMS = 16;
|
|
54
|
+
var CLAIM_NAME = /^[A-Za-z0-9_]{1,64}$/;
|
|
55
|
+
var CREDENTIAL_VERSION_PATH = "/crm";
|
|
56
|
+
var PROBLEM = {
|
|
57
|
+
https: 'backchannelUrl must use https: when environment is "production" unless allowInsecureBackchannel is true',
|
|
58
|
+
isRevokedRequired: "isRevoked is required for a crm audience",
|
|
59
|
+
requireClaims: `requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`,
|
|
60
|
+
jwks: "jwks must be a JSON Web Key Set",
|
|
61
|
+
jwksSandboxOnly: 'jwks is only allowed when environment is "sandbox"'
|
|
62
|
+
};
|
|
63
|
+
var RESOURCE_PROBLEM = 'environment is "production" but resource is not a production audience';
|
|
64
|
+
var AUDIENCE_PROBLEM = 'environment is "production" but audience is not a production audience';
|
|
65
|
+
var globalFetch = (input, init) => globalThis.fetch(input, init);
|
|
66
|
+
function needsCredentialVersion(audience) {
|
|
67
|
+
return new URL(audience).pathname.replace(/\/+$/, "") === CREDENTIAL_VERSION_PATH;
|
|
68
|
+
}
|
|
69
|
+
function parsed(problems, parse) {
|
|
70
|
+
try {
|
|
71
|
+
return parse();
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (!(error instanceof import_auth_shared.ConfigError)) throw error;
|
|
74
|
+
problems.push(...error.problems);
|
|
75
|
+
return void 0;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function requiredClaimsOf(problems, raw) {
|
|
79
|
+
if (raw === void 0) return Object.freeze([]);
|
|
80
|
+
if (!Array.isArray(raw) || raw.length > MAX_REQUIRED_CLAIMS || !raw.every((name) => typeof name === "string" && CLAIM_NAME.test(name))) {
|
|
81
|
+
problems.push(PROBLEM.requireClaims);
|
|
82
|
+
return Object.freeze([]);
|
|
83
|
+
}
|
|
84
|
+
return Object.freeze([...new Set(raw)]);
|
|
85
|
+
}
|
|
86
|
+
function jwksOf(problems, raw) {
|
|
87
|
+
const keys = isObject(raw) ? raw["keys"] : void 0;
|
|
88
|
+
if (!Array.isArray(keys) || keys.length === 0 || !keys.every((key) => isObject(key))) {
|
|
89
|
+
problems.push(PROBLEM.jwks);
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
return Object.freeze({ keys: Object.freeze(keys.map((key) => Object.freeze({ ...key }))) });
|
|
93
|
+
}
|
|
94
|
+
function timeoutsOf(problems, raw) {
|
|
95
|
+
if (raw === void 0) return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });
|
|
96
|
+
if (!isObject(raw)) {
|
|
97
|
+
problems.push("timeouts must be an object");
|
|
98
|
+
return Object.freeze({ jwksMs: DEFAULT_JWKS_MS });
|
|
99
|
+
}
|
|
100
|
+
const jwksMs = integerInRange(problems, raw["jwksMs"], "timeouts.jwksMs", {
|
|
101
|
+
min: 1,
|
|
102
|
+
max: MAX_TIMEOUT_MS,
|
|
103
|
+
fallback: DEFAULT_JWKS_MS
|
|
104
|
+
});
|
|
105
|
+
return Object.freeze({ jwksMs });
|
|
106
|
+
}
|
|
107
|
+
function resolveVerifierConfig(raw) {
|
|
108
|
+
if (!isObject(raw)) throw new import_auth_shared.ConfigError(["options must be an object"]);
|
|
109
|
+
const problems = [];
|
|
110
|
+
const text = (field2) => {
|
|
111
|
+
const value = raw[field2];
|
|
112
|
+
if (value === void 0 || typeof value === "string") return value;
|
|
113
|
+
problems.push(`${field2} must be a string`);
|
|
114
|
+
return void 0;
|
|
115
|
+
};
|
|
116
|
+
const given = (field2) => raw[field2] !== void 0;
|
|
117
|
+
const flag = (field2) => {
|
|
118
|
+
const value = raw[field2];
|
|
119
|
+
if (value === void 0 || typeof value === "boolean") return value === true;
|
|
120
|
+
problems.push(`${field2} must be a boolean`);
|
|
121
|
+
return false;
|
|
122
|
+
};
|
|
123
|
+
const environment = raw["environment"];
|
|
124
|
+
const allowInsecureHttp = raw["allowInsecureHttp"] === true;
|
|
125
|
+
const issuerRaw = text("issuer");
|
|
126
|
+
const issuer = given("issuer") && issuerRaw === void 0 ? void 0 : parsed(problems, () => (0, import_auth_shared.parseIssuer)(issuerRaw, { field: "issuer", allowInsecureHttp }));
|
|
127
|
+
const audienceRaw = text("audience");
|
|
128
|
+
const audience = given("audience") && audienceRaw === void 0 ? void 0 : parsed(problems, () => (0, import_auth_shared.parseAudience)(audienceRaw, { field: "audience", allowInsecureHttp }));
|
|
129
|
+
const backchannelRaw = given("backchannelUrl") && !isBlank(raw["backchannelUrl"]) ? text("backchannelUrl") : void 0;
|
|
130
|
+
const backchannelUrl = backchannelRaw === void 0 ? void 0 : parsed(problems, () => (0, import_auth_shared.parseIssuer)(backchannelRaw, { field: "backchannelUrl", allowInsecureHttp: true }));
|
|
131
|
+
const insecureBackchannelRaw = raw["allowInsecureBackchannel"];
|
|
132
|
+
if (environment === "production" && backchannelUrl !== void 0 && new URL(backchannelUrl).protocol === "http:" && insecureBackchannelRaw !== true) {
|
|
133
|
+
problems.push(PROBLEM.https);
|
|
134
|
+
}
|
|
135
|
+
const allowInsecureBackchannel = flag("allowInsecureBackchannel");
|
|
136
|
+
const allowServiceTokens = flag("allowServiceTokens");
|
|
137
|
+
const requiredClaims = requiredClaimsOf(problems, raw["requireClaims"]);
|
|
138
|
+
const clockToleranceSeconds = integerInRange(problems, raw["clockToleranceSeconds"], "clockToleranceSeconds", {
|
|
139
|
+
min: 0,
|
|
140
|
+
max: MAX_CLOCK_TOLERANCE_SECONDS,
|
|
141
|
+
fallback: DEFAULT_CLOCK_TOLERANCE_SECONDS
|
|
142
|
+
});
|
|
143
|
+
const timeouts = timeoutsOf(problems, raw["timeouts"]);
|
|
144
|
+
const jwks = given("jwks") ? jwksOf(problems, raw["jwks"]) : null;
|
|
145
|
+
if (given("jwks") && environment === "production") problems.push(PROBLEM.jwksSandboxOnly);
|
|
146
|
+
flag("allowInsecureHttp");
|
|
147
|
+
const fetch2 = optionalFunction(problems, raw["fetch"], "fetch");
|
|
148
|
+
const requireCredentialVersion = audience !== void 0 && needsCredentialVersion(audience);
|
|
149
|
+
const isRevoked = optionalFunction(problems, raw["isRevoked"], "isRevoked");
|
|
150
|
+
if (requireCredentialVersion && !given("isRevoked")) problems.push(PROBLEM.isRevokedRequired);
|
|
151
|
+
const onReject = optionalFunction(problems, raw["onReject"], "onReject");
|
|
152
|
+
const guard = (0, import_auth_shared.environmentProblems)({
|
|
153
|
+
environment,
|
|
154
|
+
issuer: issuer ?? (environment === "production" ? import_auth_shared.PRODUCTION_ISSUER : ""),
|
|
155
|
+
allowInsecureHttp: raw["allowInsecureHttp"],
|
|
156
|
+
...audience !== void 0 ? { audiences: [audience] } : {},
|
|
157
|
+
...backchannelUrl !== void 0 ? { backchannelUrl } : {}
|
|
158
|
+
});
|
|
159
|
+
const named = guard.map((problem) => problem === RESOURCE_PROBLEM ? AUDIENCE_PROBLEM : problem);
|
|
160
|
+
if (named.length > 0 || problems.length > 0) throw new import_auth_shared.ConfigError([...named, ...problems]);
|
|
161
|
+
return Object.freeze({
|
|
162
|
+
environment,
|
|
163
|
+
issuer,
|
|
164
|
+
audience,
|
|
165
|
+
backchannelUrl: backchannelUrl ?? null,
|
|
166
|
+
allowInsecureBackchannel,
|
|
167
|
+
allowServiceTokens,
|
|
168
|
+
requiredClaims,
|
|
169
|
+
requireCredentialVersion,
|
|
170
|
+
clockToleranceSeconds,
|
|
171
|
+
timeouts,
|
|
172
|
+
jwks,
|
|
173
|
+
fetch: fetch2 ?? globalFetch,
|
|
174
|
+
isRevoked,
|
|
175
|
+
onReject
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/core/jwks.ts
|
|
180
|
+
var import_auth_shared2 = require("@plasgos/auth-shared");
|
|
181
|
+
|
|
182
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/buffer_utils.js
|
|
183
|
+
var encoder = new TextEncoder();
|
|
184
|
+
var decoder = new TextDecoder();
|
|
185
|
+
var strictDecoder = new TextDecoder("utf-8", { fatal: true });
|
|
186
|
+
var UINT32_RANGE = 2 ** 32;
|
|
187
|
+
function concat(...buffers) {
|
|
188
|
+
const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);
|
|
189
|
+
let i = 0;
|
|
190
|
+
for (const buffer of buffers)
|
|
191
|
+
buf.set(buffer, i), i += buffer.length;
|
|
192
|
+
return buf;
|
|
193
|
+
}
|
|
194
|
+
var NON_ASCII = /[^\x00-\x7f]/;
|
|
195
|
+
function encode(string) {
|
|
196
|
+
if (typeof string == "string" && string.length >= 128) {
|
|
197
|
+
if (NON_ASCII.test(string))
|
|
198
|
+
throw new TypeError("non-ASCII string encountered in encode()");
|
|
199
|
+
return encoder.encode(string);
|
|
200
|
+
}
|
|
201
|
+
const bytes = new Uint8Array(string.length);
|
|
202
|
+
for (let i = 0; i < string.length; i++) {
|
|
203
|
+
const code = string.charCodeAt(i);
|
|
204
|
+
if (code > 127)
|
|
205
|
+
throw new TypeError("non-ASCII string encountered in encode()");
|
|
206
|
+
bytes[i] = code;
|
|
207
|
+
}
|
|
208
|
+
return bytes;
|
|
209
|
+
}
|
|
210
|
+
function decodeBase64(encoded, url = false) {
|
|
211
|
+
if (Uint8Array.fromBase64)
|
|
212
|
+
return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
|
|
213
|
+
if (url) {
|
|
214
|
+
if (encoded.includes("+") || encoded.includes("/"))
|
|
215
|
+
throw new TypeError("Invalid base64url");
|
|
216
|
+
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
217
|
+
}
|
|
218
|
+
const binary = atob(encoded), bytes = new Uint8Array(binary.length);
|
|
219
|
+
for (let i = 0; i < binary.length; i++)
|
|
220
|
+
bytes[i] = binary.charCodeAt(i);
|
|
221
|
+
return bytes;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/util/errors.js
|
|
225
|
+
var JOSEError = class extends Error {
|
|
226
|
+
static code = "ERR_JOSE_GENERIC";
|
|
227
|
+
code = "ERR_JOSE_GENERIC";
|
|
228
|
+
constructor(message2, options) {
|
|
229
|
+
super(message2, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
var JWTClaimValidationFailed = class extends JOSEError {
|
|
233
|
+
static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
234
|
+
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
235
|
+
claim;
|
|
236
|
+
reason;
|
|
237
|
+
payload;
|
|
238
|
+
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
239
|
+
super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
var JWTExpired = class extends JOSEError {
|
|
243
|
+
static code = "ERR_JWT_EXPIRED";
|
|
244
|
+
code = "ERR_JWT_EXPIRED";
|
|
245
|
+
claim;
|
|
246
|
+
reason;
|
|
247
|
+
payload;
|
|
248
|
+
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
249
|
+
super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
var JOSEAlgNotAllowed = class extends JOSEError {
|
|
253
|
+
static code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
254
|
+
code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
255
|
+
};
|
|
256
|
+
var JOSENotSupported = class extends JOSEError {
|
|
257
|
+
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
258
|
+
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
259
|
+
};
|
|
260
|
+
var JWSInvalid = class extends JOSEError {
|
|
261
|
+
static code = "ERR_JWS_INVALID";
|
|
262
|
+
code = "ERR_JWS_INVALID";
|
|
263
|
+
};
|
|
264
|
+
var JWTInvalid = class extends JOSEError {
|
|
265
|
+
static code = "ERR_JWT_INVALID";
|
|
266
|
+
code = "ERR_JWT_INVALID";
|
|
267
|
+
};
|
|
268
|
+
var JWKSInvalid = class extends JOSEError {
|
|
269
|
+
static code = "ERR_JWKS_INVALID";
|
|
270
|
+
code = "ERR_JWKS_INVALID";
|
|
271
|
+
};
|
|
272
|
+
var JWKSNoMatchingKey = class extends JOSEError {
|
|
273
|
+
static code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
274
|
+
code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
275
|
+
constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
|
|
276
|
+
super(message2, options);
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
var JWKSMultipleMatchingKeys = class extends JOSEError {
|
|
280
|
+
[Symbol.asyncIterator] = async function* () {
|
|
281
|
+
};
|
|
282
|
+
static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
283
|
+
code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
284
|
+
constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
|
|
285
|
+
super(message2, options);
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
var JWKSTimeout = class extends JOSEError {
|
|
289
|
+
static code = "ERR_JWKS_TIMEOUT";
|
|
290
|
+
code = "ERR_JWKS_TIMEOUT";
|
|
291
|
+
constructor(message2 = "request timed out", options) {
|
|
292
|
+
super(message2, options);
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
var JWSSignatureVerificationFailed = class extends JOSEError {
|
|
296
|
+
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
297
|
+
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
298
|
+
constructor(message2 = "signature verification failed", options) {
|
|
299
|
+
super(message2, options);
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/util/base64url.js
|
|
304
|
+
var invalid = "The input to be decoded is not correctly encoded.";
|
|
305
|
+
function decode(input) {
|
|
306
|
+
try {
|
|
307
|
+
return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true);
|
|
308
|
+
} catch (cause) {
|
|
309
|
+
throw new TypeError(invalid, { cause });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/validate.js
|
|
314
|
+
function isObject2(input) {
|
|
315
|
+
if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]")
|
|
316
|
+
return false;
|
|
317
|
+
const prototype = Object.getPrototypeOf(input);
|
|
318
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
319
|
+
}
|
|
320
|
+
function isJwkSet(input) {
|
|
321
|
+
return isObject2(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject2);
|
|
322
|
+
}
|
|
323
|
+
function isDisjoint(...headers) {
|
|
324
|
+
const parameters = /* @__PURE__ */ new Set();
|
|
325
|
+
for (const header of headers)
|
|
326
|
+
if (header)
|
|
327
|
+
for (const parameter of Object.keys(header)) {
|
|
328
|
+
if (parameters.has(parameter))
|
|
329
|
+
return false;
|
|
330
|
+
parameters.add(parameter);
|
|
331
|
+
}
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
function decodeBase64url(value, label, ErrorClass) {
|
|
335
|
+
try {
|
|
336
|
+
return decode(value);
|
|
337
|
+
} catch (cause) {
|
|
338
|
+
throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function encodeAsciiMember(value, label, ErrorClass) {
|
|
342
|
+
try {
|
|
343
|
+
return encode(value);
|
|
344
|
+
} catch (cause) {
|
|
345
|
+
throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
function parseJoseHeader(encodedProtectedHeader, ErrorClass, message2) {
|
|
349
|
+
let parsed2;
|
|
350
|
+
try {
|
|
351
|
+
parsed2 = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));
|
|
352
|
+
} catch (cause) {
|
|
353
|
+
throw new ErrorClass(message2, { cause });
|
|
354
|
+
}
|
|
355
|
+
if (!isObject2(parsed2))
|
|
356
|
+
throw new ErrorClass(message2);
|
|
357
|
+
return parsed2;
|
|
358
|
+
}
|
|
359
|
+
var JWS_RECOGNIZED = { __proto__: null, b64: true };
|
|
360
|
+
function validateAlgorithms(option, algorithms) {
|
|
361
|
+
if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string")))
|
|
362
|
+
throw new TypeError(`"${option}" option must be an array of strings`);
|
|
363
|
+
return algorithms === void 0 ? void 0 : new Set(algorithms);
|
|
364
|
+
}
|
|
365
|
+
function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
|
|
366
|
+
if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)
|
|
367
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
|
|
368
|
+
if (!protectedHeader || protectedHeader.crit === void 0)
|
|
369
|
+
return [];
|
|
370
|
+
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0))
|
|
371
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
|
|
372
|
+
const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
|
|
373
|
+
for (const parameter of protectedHeader.crit) {
|
|
374
|
+
if (!(parameter in recognized))
|
|
375
|
+
throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
376
|
+
if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)
|
|
377
|
+
throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
378
|
+
if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))
|
|
379
|
+
throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
380
|
+
}
|
|
381
|
+
return protectedHeader.crit;
|
|
382
|
+
}
|
|
383
|
+
function validateB64(protectedHeader, extensions) {
|
|
384
|
+
if (extensions.includes("b64")) {
|
|
385
|
+
const b64 = protectedHeader.b64;
|
|
386
|
+
if (typeof b64 != "boolean")
|
|
387
|
+
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
|
388
|
+
return b64;
|
|
389
|
+
}
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/key.js
|
|
394
|
+
var tag = (key) => key[Symbol.toStringTag];
|
|
395
|
+
var jwkMatchesOp = (entry, key, usage) => {
|
|
396
|
+
const { alg } = entry;
|
|
397
|
+
if (key.use !== void 0) {
|
|
398
|
+
const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
|
|
399
|
+
if (key.use !== expected)
|
|
400
|
+
throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
401
|
+
}
|
|
402
|
+
if (key.alg !== void 0 && key.alg !== alg)
|
|
403
|
+
throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
404
|
+
if (Array.isArray(key.key_ops)) {
|
|
405
|
+
const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
|
|
406
|
+
if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))
|
|
407
|
+
throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
async function prepareKey(entry, key, usage) {
|
|
411
|
+
const { alg, secret } = entry, requiresPrivateKey = usage === "decrypt" || usage === "sign";
|
|
412
|
+
if (secret && key instanceof Uint8Array)
|
|
413
|
+
return key;
|
|
414
|
+
let normalized, keyObject;
|
|
415
|
+
if (isObject2(key)) {
|
|
416
|
+
if (normalized = normalizeJwk(key), typeof normalized.kty != "string")
|
|
417
|
+
throw invalidKeyType(alg, key, secret);
|
|
418
|
+
if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (requiresPrivateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0)))
|
|
419
|
+
throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present' : `JSON Web Key for this operation must be a ${requiresPrivateKey ? "private" : "public"} JWK`);
|
|
420
|
+
if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct")
|
|
421
|
+
return decode(normalized.k);
|
|
422
|
+
if (!Object.isFrozen(key)) {
|
|
423
|
+
const { key_ops } = key;
|
|
424
|
+
Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
|
|
425
|
+
}
|
|
426
|
+
} else {
|
|
427
|
+
if (!isKeyLike(key))
|
|
428
|
+
throw invalidKeyType(alg, key, secret);
|
|
429
|
+
const expectedType = secret ? "secret" : requiresPrivateKey ? "private" : "public";
|
|
430
|
+
if (key.type !== expectedType && (secret || ["secret", "public", "private"].includes(key.type)))
|
|
431
|
+
throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
|
|
432
|
+
if (isCryptoKey(key))
|
|
433
|
+
return key;
|
|
434
|
+
if (keyObject = key, keyObject.type === "secret")
|
|
435
|
+
return keyObject.export();
|
|
436
|
+
}
|
|
437
|
+
cache ||= /* @__PURE__ */ new WeakMap();
|
|
438
|
+
const cacheKey = key;
|
|
439
|
+
let cached = cache.get(cacheKey);
|
|
440
|
+
if (cached?.[alg])
|
|
441
|
+
return cached[alg];
|
|
442
|
+
if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
|
|
443
|
+
const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;
|
|
444
|
+
return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
|
|
445
|
+
}
|
|
446
|
+
return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
|
|
447
|
+
}
|
|
448
|
+
var cache;
|
|
449
|
+
var nist = {
|
|
450
|
+
__proto__: null,
|
|
451
|
+
prime256v1: "P-256",
|
|
452
|
+
secp384r1: "P-384",
|
|
453
|
+
secp521r1: "P-521"
|
|
454
|
+
};
|
|
455
|
+
var isCryptoKey = (key) => {
|
|
456
|
+
if (key?.[Symbol.toStringTag] === "CryptoKey")
|
|
457
|
+
return true;
|
|
458
|
+
try {
|
|
459
|
+
return key instanceof CryptoKey;
|
|
460
|
+
} catch {
|
|
461
|
+
return false;
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
465
|
+
var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
466
|
+
function message(msg, actual, ...types) {
|
|
467
|
+
if (types.length > 2) {
|
|
468
|
+
const last = types.pop();
|
|
469
|
+
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
470
|
+
} else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
|
|
471
|
+
return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;
|
|
472
|
+
}
|
|
473
|
+
function invalidKeyType(alg, actual, secret) {
|
|
474
|
+
const types = ["CryptoKey", "KeyObject", "JSON Web Key"];
|
|
475
|
+
return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
|
|
476
|
+
}
|
|
477
|
+
var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
478
|
+
function checkUsage(key, usage) {
|
|
479
|
+
if (usage && !key.usages.includes(usage))
|
|
480
|
+
throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
481
|
+
}
|
|
482
|
+
function checkModulusLength(alg, key) {
|
|
483
|
+
const { modulusLength } = key.algorithm;
|
|
484
|
+
if (typeof modulusLength != "number" || modulusLength < 2048)
|
|
485
|
+
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
486
|
+
}
|
|
487
|
+
function checkCryptoKey(key, expected, usage) {
|
|
488
|
+
const algorithm = key.algorithm;
|
|
489
|
+
if (algorithm.name !== expected.name)
|
|
490
|
+
throw unusable(expected.name);
|
|
491
|
+
if (expected.hash && algorithm.hash?.name !== expected.hash)
|
|
492
|
+
throw unusable(expected.hash, "algorithm.hash");
|
|
493
|
+
if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)
|
|
494
|
+
throw unusable(expected.namedCurve, "algorithm.namedCurve");
|
|
495
|
+
if (expected.length !== void 0 && algorithm.length !== expected.length)
|
|
496
|
+
throw unusable(expected.length, "algorithm.length");
|
|
497
|
+
checkUsage(key, usage);
|
|
498
|
+
}
|
|
499
|
+
function snapshotJwk(jwk) {
|
|
500
|
+
return { __proto__: null, ...jwk };
|
|
501
|
+
}
|
|
502
|
+
function normalizeJwk(jwk) {
|
|
503
|
+
const normalized = snapshotJwk(jwk);
|
|
504
|
+
if (normalized.ext !== void 0 && typeof normalized.ext != "boolean")
|
|
505
|
+
throw new TypeError('"ext" (Extractable) Parameter must be a boolean');
|
|
506
|
+
if (normalized.key_ops !== void 0) {
|
|
507
|
+
const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
|
|
508
|
+
if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length)
|
|
509
|
+
throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');
|
|
510
|
+
normalized.key_ops = keyOps;
|
|
511
|
+
}
|
|
512
|
+
return normalized;
|
|
513
|
+
}
|
|
514
|
+
async function jwkToKey(entry, jwk, extractable) {
|
|
515
|
+
if (!entry.kty.includes(jwk.kty))
|
|
516
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
517
|
+
const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };
|
|
518
|
+
return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
|
|
519
|
+
}
|
|
520
|
+
async function rawKey(key, expected, usage, extractable = false) {
|
|
521
|
+
return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/key_descriptor.js
|
|
525
|
+
function table(entries) {
|
|
526
|
+
const out = { __proto__: null };
|
|
527
|
+
for (const alg in entries)
|
|
528
|
+
out[alg] = { ...entries[alg], alg };
|
|
529
|
+
return out;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/jws_algorithms.js
|
|
533
|
+
var sig = [["verify"], ["sign"]];
|
|
534
|
+
function hmac(bits) {
|
|
535
|
+
const subtle = { name: "HMAC", hash: `SHA-${bits}` };
|
|
536
|
+
return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
|
|
537
|
+
}
|
|
538
|
+
function rsa(bits, saltLength) {
|
|
539
|
+
const subtle = { name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash: `SHA-${bits}` };
|
|
540
|
+
return {
|
|
541
|
+
kty: ["RSA"],
|
|
542
|
+
subtle,
|
|
543
|
+
signing: saltLength ? { ...subtle, saltLength } : subtle,
|
|
544
|
+
usages: sig,
|
|
545
|
+
minRsaBits: 2048
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
function ecdsa(crv, bits) {
|
|
549
|
+
return {
|
|
550
|
+
kty: ["EC"],
|
|
551
|
+
crv,
|
|
552
|
+
subtle: { name: "ECDSA", namedCurve: crv },
|
|
553
|
+
signing: { name: "ECDSA", hash: `SHA-${bits}` },
|
|
554
|
+
usages: sig
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
function eddsa() {
|
|
558
|
+
const subtle = { name: "Ed25519" };
|
|
559
|
+
return {
|
|
560
|
+
kty: ["OKP"],
|
|
561
|
+
crv: "Ed25519",
|
|
562
|
+
subtle,
|
|
563
|
+
signing: subtle,
|
|
564
|
+
usages: sig
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
function mldsa(parameterSet) {
|
|
568
|
+
const subtle = { name: `ML-DSA-${parameterSet}` };
|
|
569
|
+
return {
|
|
570
|
+
kty: ["AKP"],
|
|
571
|
+
subtle,
|
|
572
|
+
signing: subtle,
|
|
573
|
+
usages: sig
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
var JWS = table({
|
|
577
|
+
HS256: hmac(256),
|
|
578
|
+
HS384: hmac(384),
|
|
579
|
+
HS512: hmac(512),
|
|
580
|
+
RS256: rsa(256),
|
|
581
|
+
RS384: rsa(384),
|
|
582
|
+
RS512: rsa(512),
|
|
583
|
+
PS256: rsa(256, 32),
|
|
584
|
+
PS384: rsa(384, 48),
|
|
585
|
+
PS512: rsa(512, 64),
|
|
586
|
+
ES256: ecdsa("P-256", 256),
|
|
587
|
+
ES384: ecdsa("P-384", 384),
|
|
588
|
+
ES512: ecdsa("P-521", 512),
|
|
589
|
+
EdDSA: eddsa(),
|
|
590
|
+
Ed25519: eddsa(),
|
|
591
|
+
"ML-DSA-44": mldsa(44),
|
|
592
|
+
"ML-DSA-65": mldsa(65),
|
|
593
|
+
"ML-DSA-87": mldsa(87)
|
|
594
|
+
});
|
|
595
|
+
function jwsAlgorithm(alg) {
|
|
596
|
+
const entry = typeof alg == "string" ? JWS[alg] : void 0;
|
|
597
|
+
if (!entry)
|
|
598
|
+
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
599
|
+
return entry;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/jws_verify.js
|
|
603
|
+
function prepareVerify(options) {
|
|
604
|
+
return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
|
|
605
|
+
}
|
|
606
|
+
function parseProtectedHeader(encodedProtectedHeader) {
|
|
607
|
+
return encodedProtectedHeader === void 0 ? {} : parseJoseHeader(encodedProtectedHeader, JWSInvalid, "JWS Protected Header is invalid");
|
|
608
|
+
}
|
|
609
|
+
function encodeCompactUnencodedPayload(payload) {
|
|
610
|
+
try {
|
|
611
|
+
return encode(payload);
|
|
612
|
+
} catch (cause) {
|
|
613
|
+
throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters", {
|
|
614
|
+
cause
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
|
|
619
|
+
const { protected: encodedProtectedHeader, header, payload: inputPayload } = jws, protectedHeader = parsedProtected ?? parseProtectedHeader(encodedProtectedHeader);
|
|
620
|
+
if (!isDisjoint(protectedHeader, header))
|
|
621
|
+
throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
622
|
+
const joseHeader = { ...protectedHeader, ...header }, b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], protectedHeader, joseHeader)), { alg } = joseHeader;
|
|
623
|
+
if (typeof alg != "string" || !alg)
|
|
624
|
+
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
625
|
+
if (shared[0] && !shared[0].has(alg))
|
|
626
|
+
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
|
627
|
+
if (b64) {
|
|
628
|
+
if (typeof inputPayload != "string")
|
|
629
|
+
throw new JWSInvalid("JWS Payload must be a string");
|
|
630
|
+
} else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array))
|
|
631
|
+
throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
|
|
632
|
+
const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
|
|
633
|
+
let resolvedKey = false;
|
|
634
|
+
typeof key == "function" && (key = await key(protectedHeader, jws), resolvedKey = true);
|
|
635
|
+
const entry = jwsAlgorithm(alg), signingInput = concat(encodedProtectedHeader !== void 0 ? encode(encodedProtectedHeader) : new Uint8Array(), encode("."), typeof signingPayload == "string" ? shared[2] ??= encodeAsciiMember(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), verificationKey = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(verificationKey, entry.subtle, "verify");
|
|
636
|
+
entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
|
|
637
|
+
let verified = false;
|
|
638
|
+
try {
|
|
639
|
+
verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, signingInput);
|
|
640
|
+
} catch (cause) {
|
|
641
|
+
throw new JWSSignatureVerificationFailed(void 0, { cause });
|
|
642
|
+
}
|
|
643
|
+
if (!verified)
|
|
644
|
+
throw new JWSSignatureVerificationFailed();
|
|
645
|
+
const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
|
|
646
|
+
return encodedProtectedHeader !== void 0 && (result.protectedHeader = protectedHeader), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: verificationKey }, b64] : [result, b64];
|
|
647
|
+
}
|
|
648
|
+
async function verifyCompact(jws, shared, key) {
|
|
649
|
+
if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string")
|
|
650
|
+
throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
|
|
651
|
+
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
|
|
652
|
+
if (length !== 3)
|
|
653
|
+
throw new JWSInvalid("Invalid Compact JWS");
|
|
654
|
+
return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
|
|
658
|
+
var epoch = (date) => Math.floor(date.getTime() / 1e3);
|
|
659
|
+
var multipliers = {
|
|
660
|
+
s: 1,
|
|
661
|
+
m: 60,
|
|
662
|
+
h: 3600,
|
|
663
|
+
d: 86400,
|
|
664
|
+
w: 604800,
|
|
665
|
+
y: 31557600
|
|
666
|
+
};
|
|
667
|
+
var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
|
668
|
+
var checkFailed = "check_failed";
|
|
669
|
+
function invalidDuration() {
|
|
670
|
+
throw new TypeError("Invalid time period format");
|
|
671
|
+
}
|
|
672
|
+
function secs(str) {
|
|
673
|
+
typeof str != "string" && invalidDuration();
|
|
674
|
+
const matched = REGEX.exec(str);
|
|
675
|
+
(!matched || matched[4] && matched[1]) && invalidDuration();
|
|
676
|
+
const value = parseFloat(matched[2]), durationSeconds = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
|
|
677
|
+
return Number.isFinite(durationSeconds) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -durationSeconds : durationSeconds;
|
|
678
|
+
}
|
|
679
|
+
function validateInput(label, input) {
|
|
680
|
+
if (!Number.isFinite(input))
|
|
681
|
+
throw new TypeError(`Invalid ${label} input`);
|
|
682
|
+
return input;
|
|
683
|
+
}
|
|
684
|
+
var normalizeTyp = (value) => {
|
|
685
|
+
const normalized = value.toLowerCase();
|
|
686
|
+
return value.includes("/") ? normalized : `application/${normalized}`;
|
|
687
|
+
};
|
|
688
|
+
var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false;
|
|
689
|
+
function validateNumericDate(claimsSet, claim, required = false) {
|
|
690
|
+
const value = claimsSet[claim];
|
|
691
|
+
if (!(value === void 0 && !required)) {
|
|
692
|
+
if (typeof value != "number")
|
|
693
|
+
throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, claimsSet, claim, "invalid");
|
|
694
|
+
return value;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
function unexpectedClaim(claimsSet, claim) {
|
|
698
|
+
throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, claimsSet, claim, checkFailed);
|
|
699
|
+
}
|
|
700
|
+
function validateClaimsSet(protectedHeader, claimsSetBytes, options = {}) {
|
|
701
|
+
let claimsSet;
|
|
702
|
+
try {
|
|
703
|
+
claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
|
|
704
|
+
} catch (cause) {
|
|
705
|
+
throw new JWTInvalid("JWT Claims Set must be a top-level JSON object", { cause });
|
|
706
|
+
}
|
|
707
|
+
if (!isObject2(claimsSet))
|
|
708
|
+
throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
|
|
709
|
+
const { typ } = options;
|
|
710
|
+
if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))
|
|
711
|
+
throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', claimsSet, "typ", checkFailed);
|
|
712
|
+
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
|
|
713
|
+
maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
|
|
714
|
+
for (const claim of new Set(presenceCheck.reverse()))
|
|
715
|
+
if (!Object.hasOwn(claimsSet, claim))
|
|
716
|
+
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claimsSet, claim, "missing");
|
|
717
|
+
issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(claimsSet.iss) && unexpectedClaim(claimsSet, "iss"), subject !== void 0 && claimsSet.sub !== subject && unexpectedClaim(claimsSet, "sub"), audience !== void 0 && !checkAudiencePresence(claimsSet.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(claimsSet, "aud");
|
|
718
|
+
const { clockTolerance } = options;
|
|
719
|
+
let tolerance = 0;
|
|
720
|
+
if (typeof clockTolerance == "string")
|
|
721
|
+
tolerance = secs(clockTolerance);
|
|
722
|
+
else if (clockTolerance !== void 0) {
|
|
723
|
+
if (typeof clockTolerance != "number")
|
|
724
|
+
throw new TypeError("Invalid clockTolerance option type");
|
|
725
|
+
tolerance = clockTolerance;
|
|
726
|
+
}
|
|
727
|
+
if (validateInput("clockTolerance option", tolerance), tolerance < 0)
|
|
728
|
+
throw new TypeError("Invalid clockTolerance option input");
|
|
729
|
+
const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(claimsSet, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(claimsSet, "nbf");
|
|
730
|
+
if (nbf !== void 0 && nbf > now + tolerance)
|
|
731
|
+
throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', claimsSet, "nbf", checkFailed);
|
|
732
|
+
const exp = validateNumericDate(claimsSet, "exp");
|
|
733
|
+
if (exp !== void 0 && exp <= now - tolerance)
|
|
734
|
+
throw new JWTExpired('"exp" claim timestamp check failed', claimsSet, "exp", checkFailed);
|
|
735
|
+
if (maxTokenAge !== void 0) {
|
|
736
|
+
const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
|
|
737
|
+
if (age - tolerance > max)
|
|
738
|
+
throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', claimsSet, "iat", checkFailed);
|
|
739
|
+
if (age < -tolerance)
|
|
740
|
+
throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', claimsSet, "iat", checkFailed);
|
|
741
|
+
}
|
|
742
|
+
return claimsSet;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/jwt/verify.js
|
|
746
|
+
async function jwtVerify(jwt, key, options) {
|
|
747
|
+
const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
|
|
748
|
+
if (!b64)
|
|
749
|
+
throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
750
|
+
const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
|
|
751
|
+
return { ...verified, payload };
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/jwks/local.js
|
|
755
|
+
function isUsableJWK(jwk, entry, alg, kid) {
|
|
756
|
+
const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;
|
|
757
|
+
return (ext === void 0 || typeof ext == "boolean") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == "string" && keyOps.indexOf(operation) === index) && keyOps.includes("verify")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == "string" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== "AKP" : alg === jwkAlg) && (use === void 0 || use === "sig") && (!entry.crv || crv === entry.crv);
|
|
758
|
+
}
|
|
759
|
+
async function importWithAlgCache(cache2, jwk, entry) {
|
|
760
|
+
const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk), { alg } = entry;
|
|
761
|
+
if (cached[alg] === void 0) {
|
|
762
|
+
const pending = jwkToKey(entry, jwk, true).then((key) => {
|
|
763
|
+
if (key.type !== "public")
|
|
764
|
+
throw new JWKSInvalid("JSON Web Key Set members must be public keys");
|
|
765
|
+
return cached[alg] = key, key;
|
|
766
|
+
}).catch((error) => {
|
|
767
|
+
throw cached[alg] === pending && delete cached[alg], error;
|
|
768
|
+
});
|
|
769
|
+
cached[alg] = pending;
|
|
770
|
+
}
|
|
771
|
+
return cached[alg];
|
|
772
|
+
}
|
|
773
|
+
function createLocalJWKSet(jwks) {
|
|
774
|
+
let snapshot;
|
|
775
|
+
try {
|
|
776
|
+
snapshot = structuredClone(jwks);
|
|
777
|
+
} catch (cause) {
|
|
778
|
+
throw new JWKSInvalid("JSON Web Key Set malformed", { cause });
|
|
779
|
+
}
|
|
780
|
+
if (!isJwkSet(snapshot))
|
|
781
|
+
throw new JWKSInvalid("JSON Web Key Set malformed");
|
|
782
|
+
const metadata = snapshot.keys.map((jwk) => {
|
|
783
|
+
const normalized = snapshotJwk(jwk);
|
|
784
|
+
return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;
|
|
785
|
+
}), cached = /* @__PURE__ */ new WeakMap();
|
|
786
|
+
return Object.defineProperty(async (protectedHeader, token) => {
|
|
787
|
+
const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == "string" ? JWS[alg] : void 0;
|
|
788
|
+
if (!entry || entry.secret)
|
|
789
|
+
throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
|
|
790
|
+
const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;
|
|
791
|
+
if (!length)
|
|
792
|
+
throw new JWKSNoMatchingKey();
|
|
793
|
+
if (length !== 1) {
|
|
794
|
+
const error = new JWKSMultipleMatchingKeys();
|
|
795
|
+
throw error[Symbol.asyncIterator] = async function* () {
|
|
796
|
+
for (const jwk2 of candidates)
|
|
797
|
+
try {
|
|
798
|
+
yield await importWithAlgCache(cached, jwk2, entry);
|
|
799
|
+
} catch {
|
|
800
|
+
}
|
|
801
|
+
}, error;
|
|
802
|
+
}
|
|
803
|
+
return importWithAlgCache(cached, jwk, entry);
|
|
804
|
+
}, "jwks", {
|
|
805
|
+
value: () => structuredClone(snapshot)
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// ../../node_modules/.pnpm/jose@6.2.15/node_modules/jose/dist/webapi/jwks/remote.js
|
|
810
|
+
function isCloudflareWorkers() {
|
|
811
|
+
return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
|
|
812
|
+
}
|
|
813
|
+
var USER_AGENT;
|
|
814
|
+
(typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.15");
|
|
815
|
+
var customFetch = /* @__PURE__ */ Symbol();
|
|
816
|
+
async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
|
|
817
|
+
const response = await fetchImpl(url, {
|
|
818
|
+
method: "GET",
|
|
819
|
+
signal,
|
|
820
|
+
redirect: "manual",
|
|
821
|
+
headers
|
|
822
|
+
}).catch((err) => {
|
|
823
|
+
throw err.name === "TimeoutError" ? new JWKSTimeout(void 0, { cause: err }) : err;
|
|
824
|
+
});
|
|
825
|
+
if (response.status !== 200)
|
|
826
|
+
throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
|
|
827
|
+
try {
|
|
828
|
+
return await response.json();
|
|
829
|
+
} catch (cause) {
|
|
830
|
+
throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON", { cause });
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
var jwksCache = /* @__PURE__ */ Symbol();
|
|
834
|
+
function isFreshFor(timestamp, duration) {
|
|
835
|
+
return Number.isFinite(timestamp) && Date.now() < timestamp + duration;
|
|
836
|
+
}
|
|
837
|
+
function validateDuration(value, fallback, option) {
|
|
838
|
+
if (Number.isNaN(value))
|
|
839
|
+
throw new TypeError(`"${option}" option must not be NaN`);
|
|
840
|
+
if (typeof value == "number" && value < 0)
|
|
841
|
+
throw new TypeError(`"${option}" option must not be negative`);
|
|
842
|
+
return typeof value == "number" ? value : fallback;
|
|
843
|
+
}
|
|
844
|
+
function createRemoteJWKSet(url, options) {
|
|
845
|
+
if (!(url instanceof URL))
|
|
846
|
+
throw new TypeError("url must be an instance of URL");
|
|
847
|
+
const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;
|
|
848
|
+
if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0))
|
|
849
|
+
throw new TypeError('"timeoutDuration" option must be a non-negative integer');
|
|
850
|
+
const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers);
|
|
851
|
+
USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json");
|
|
852
|
+
const fetchImpl = opts[customFetch], cache2 = opts[jwksCache];
|
|
853
|
+
let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;
|
|
854
|
+
if (cache2 && typeof cache2 == "object") {
|
|
855
|
+
const { uat, jwks } = cache2;
|
|
856
|
+
isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));
|
|
857
|
+
}
|
|
858
|
+
const reload = async () => {
|
|
859
|
+
if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {
|
|
860
|
+
const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
|
|
861
|
+
const next = createLocalJWKSet(json);
|
|
862
|
+
if (sequence <= appliedSequence)
|
|
863
|
+
return;
|
|
864
|
+
local = next;
|
|
865
|
+
const updatedAt = Date.now();
|
|
866
|
+
cache2 && (cache2.uat = updatedAt, cache2.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;
|
|
867
|
+
}).finally(() => {
|
|
868
|
+
pendingFetch === current && (pendingFetch = void 0);
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
await pendingFetch;
|
|
872
|
+
};
|
|
873
|
+
return Object.defineProperties(async (protectedHeader, token) => {
|
|
874
|
+
(!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
|
|
875
|
+
try {
|
|
876
|
+
return await local(protectedHeader, token);
|
|
877
|
+
} catch (err) {
|
|
878
|
+
if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration))
|
|
879
|
+
return await reload(), local(protectedHeader, token);
|
|
880
|
+
throw err;
|
|
881
|
+
}
|
|
882
|
+
}, {
|
|
883
|
+
coolingDown: {
|
|
884
|
+
get: () => isFreshFor(jwksTimestamp, cooldownDuration),
|
|
885
|
+
enumerable: true
|
|
886
|
+
},
|
|
887
|
+
fresh: {
|
|
888
|
+
get: () => isFreshFor(jwksTimestamp, cacheMaxAge),
|
|
889
|
+
enumerable: true
|
|
890
|
+
},
|
|
891
|
+
reload: {
|
|
892
|
+
value: reload,
|
|
893
|
+
enumerable: true
|
|
894
|
+
},
|
|
895
|
+
reloading: {
|
|
896
|
+
get: () => !!pendingFetch,
|
|
897
|
+
enumerable: true
|
|
898
|
+
},
|
|
899
|
+
jwks: {
|
|
900
|
+
value: () => local?.jwks(),
|
|
901
|
+
enumerable: true
|
|
902
|
+
}
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// src/core/jwks.ts
|
|
907
|
+
var COOLDOWN_MS = 3e4;
|
|
908
|
+
var MAX_JWKS_BYTES = 65536;
|
|
909
|
+
var KEY_SET_UNAVAILABLE = "ERR_PLASGOS_JWKS_UNAVAILABLE";
|
|
910
|
+
var JOSE_UNAVAILABLE_CODES = /* @__PURE__ */ new Set([KEY_SET_UNAVAILABLE, "ERR_JWKS_TIMEOUT", "ERR_JWKS_INVALID"]);
|
|
911
|
+
function unavailable() {
|
|
912
|
+
return Object.assign(new Error("Plasgos key set unavailable"), { code: KEY_SET_UNAVAILABLE });
|
|
913
|
+
}
|
|
914
|
+
function isKeySetUnavailable(error) {
|
|
915
|
+
if (typeof error !== "object" || error === null || !("code" in error)) return false;
|
|
916
|
+
const { code } = error;
|
|
917
|
+
return typeof code === "string" && JOSE_UNAVAILABLE_CODES.has(code);
|
|
918
|
+
}
|
|
919
|
+
var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
920
|
+
async function readCapped(response) {
|
|
921
|
+
const length = response.headers.get("content-length");
|
|
922
|
+
if (length !== null && Number(length) > MAX_JWKS_BYTES) throw unavailable();
|
|
923
|
+
if (response.body === null) return new Uint8Array(0);
|
|
924
|
+
const reader = response.body.getReader();
|
|
925
|
+
const chunks = [];
|
|
926
|
+
let total = 0;
|
|
927
|
+
for (; ; ) {
|
|
928
|
+
const result = await reader.read();
|
|
929
|
+
if (result.done) break;
|
|
930
|
+
const chunk = result.value;
|
|
931
|
+
if (!(chunk instanceof Uint8Array)) throw unavailable();
|
|
932
|
+
total += chunk.byteLength;
|
|
933
|
+
if (total > MAX_JWKS_BYTES) {
|
|
934
|
+
void reader.cancel().catch(() => void 0);
|
|
935
|
+
throw unavailable();
|
|
936
|
+
}
|
|
937
|
+
chunks.push(chunk);
|
|
938
|
+
}
|
|
939
|
+
const bytes = new Uint8Array(total);
|
|
940
|
+
let offset = 0;
|
|
941
|
+
for (const chunk of chunks) {
|
|
942
|
+
bytes.set(chunk, offset);
|
|
943
|
+
offset += chunk.byteLength;
|
|
944
|
+
}
|
|
945
|
+
return bytes;
|
|
946
|
+
}
|
|
947
|
+
function isKeySetJson(bytes) {
|
|
948
|
+
try {
|
|
949
|
+
const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
950
|
+
return isObject3(json) && Array.isArray(json["keys"]) && json["keys"].every((key) => isObject3(key));
|
|
951
|
+
} catch {
|
|
952
|
+
return false;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
function boundedFetch(fetchImpl, jwksMs) {
|
|
956
|
+
return async (url, init) => {
|
|
957
|
+
const controller = new AbortController();
|
|
958
|
+
const abort = () => {
|
|
959
|
+
controller.abort();
|
|
960
|
+
};
|
|
961
|
+
const outer = init.signal;
|
|
962
|
+
if (outer?.aborted === true) abort();
|
|
963
|
+
outer?.addEventListener("abort", abort, { once: true });
|
|
964
|
+
const timer = setTimeout(abort, jwksMs);
|
|
965
|
+
const aborted = new Promise((_, reject) => {
|
|
966
|
+
const fail = () => {
|
|
967
|
+
reject(unavailable());
|
|
968
|
+
};
|
|
969
|
+
if (controller.signal.aborted) fail();
|
|
970
|
+
else controller.signal.addEventListener("abort", fail, { once: true });
|
|
971
|
+
});
|
|
972
|
+
aborted.catch(() => void 0);
|
|
973
|
+
try {
|
|
974
|
+
const response = await Promise.race([
|
|
975
|
+
fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal }),
|
|
976
|
+
aborted
|
|
977
|
+
]);
|
|
978
|
+
if (response.status !== 200) {
|
|
979
|
+
void response.body?.cancel().catch(() => void 0);
|
|
980
|
+
throw unavailable();
|
|
981
|
+
}
|
|
982
|
+
const bytes = await Promise.race([readCapped(response), aborted]);
|
|
983
|
+
if (!isKeySetJson(bytes)) throw unavailable();
|
|
984
|
+
return new Response(bytes, { status: 200, headers: { "content-type": "application/json" } });
|
|
985
|
+
} catch {
|
|
986
|
+
throw unavailable();
|
|
987
|
+
} finally {
|
|
988
|
+
clearTimeout(timer);
|
|
989
|
+
outer?.removeEventListener("abort", abort);
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
function remoteKeySet(source) {
|
|
994
|
+
const url = new URL(`${source.backchannelUrl ?? source.issuer}${import_auth_shared2.OIDC_PATHS.jwks}`);
|
|
995
|
+
return createRemoteJWKSet(url, {
|
|
996
|
+
timeoutDuration: source.timeouts.jwksMs,
|
|
997
|
+
cooldownDuration: COOLDOWN_MS,
|
|
998
|
+
[customFetch]: boundedFetch(source.fetch, source.timeouts.jwksMs)
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
function staticKeySet(jwks) {
|
|
1002
|
+
return createLocalJWKSet(jwks);
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// src/core/verify.ts
|
|
1006
|
+
var import_auth_shared3 = require("@plasgos/auth-shared");
|
|
1007
|
+
|
|
1008
|
+
// src/core/requirements.ts
|
|
1009
|
+
var SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/;
|
|
1010
|
+
function resolveRequirements(label, raw) {
|
|
1011
|
+
if (raw === void 0) return { scopes: [], requireClaims: [], maxAuthAge: null };
|
|
1012
|
+
if (!isObject(raw)) throw new TypeError(`${label}: options must be an object`);
|
|
1013
|
+
const { scopes, requireClaims, maxAuthAge } = raw;
|
|
1014
|
+
if (scopes !== void 0 && (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === "string" && SCOPE_TOKEN.test(scope)))) {
|
|
1015
|
+
throw new TypeError(`${label}: scopes must be a list of scope tokens`);
|
|
1016
|
+
}
|
|
1017
|
+
if (requireClaims !== void 0 && (!Array.isArray(requireClaims) || requireClaims.length > MAX_REQUIRED_CLAIMS || !requireClaims.every((name) => typeof name === "string" && CLAIM_NAME.test(name)))) {
|
|
1018
|
+
throw new TypeError(`${label}: requireClaims must be a list of at most ${String(MAX_REQUIRED_CLAIMS)} claim names`);
|
|
1019
|
+
}
|
|
1020
|
+
if (maxAuthAge !== void 0 && (typeof maxAuthAge !== "number" || !Number.isSafeInteger(maxAuthAge) || maxAuthAge <= 0)) {
|
|
1021
|
+
throw new TypeError(`${label}: maxAuthAge must be a positive safe integer`);
|
|
1022
|
+
}
|
|
1023
|
+
return {
|
|
1024
|
+
scopes: Object.freeze([...new Set(scopes ?? [])]),
|
|
1025
|
+
requireClaims: Object.freeze([...new Set(requireClaims ?? [])]),
|
|
1026
|
+
maxAuthAge: maxAuthAge ?? null
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
function resolveVerifyOptions(raw) {
|
|
1030
|
+
const requirements = resolveRequirements("verify", raw);
|
|
1031
|
+
const fields = isObject(raw) ? raw : {};
|
|
1032
|
+
const { requestId, now } = fields;
|
|
1033
|
+
if (requestId !== void 0 && requestId !== null && typeof requestId !== "string") {
|
|
1034
|
+
throw new TypeError("verify: requestId must be a string");
|
|
1035
|
+
}
|
|
1036
|
+
if (now !== void 0 && (typeof now !== "number" || !Number.isFinite(now))) {
|
|
1037
|
+
throw new TypeError("verify: now must be a finite number");
|
|
1038
|
+
}
|
|
1039
|
+
return { ...requirements, requestId, now: now ?? null };
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// src/core/verify.ts
|
|
1043
|
+
var BEARER_SCHEME = /^Bearer /i;
|
|
1044
|
+
var BEARER_TOKEN = /^Bearer +([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)$/i;
|
|
1045
|
+
var PLAIN_ID = /^[\w.:-]{1,128}$/;
|
|
1046
|
+
var MAX_PUBLIC_ID_LENGTH = 128;
|
|
1047
|
+
var ACCEPTED_TYPES = import_auth_shared3.ACCESS_TOKEN_TYPES;
|
|
1048
|
+
var refuse = (reason, clientId = null) => ({ refusal: { reason, clientId } });
|
|
1049
|
+
var nonEmptyString = (value) => typeof value === "string" && value !== "";
|
|
1050
|
+
var plainId = (value) => typeof value === "string" && PLAIN_ID.test(value) ? value : null;
|
|
1051
|
+
function decodeHeader(segment) {
|
|
1052
|
+
try {
|
|
1053
|
+
const json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(segment, "base64url")));
|
|
1054
|
+
return isObject(json) ? json : null;
|
|
1055
|
+
} catch {
|
|
1056
|
+
return null;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
function field(error, name) {
|
|
1060
|
+
return isObject(error) || error instanceof Error ? error[name] : void 0;
|
|
1061
|
+
}
|
|
1062
|
+
function reasonOfVerifyError(error) {
|
|
1063
|
+
if (isKeySetUnavailable(error)) return "unavailable";
|
|
1064
|
+
switch (field(error, "code")) {
|
|
1065
|
+
case "ERR_JWKS_NO_MATCHING_KEY":
|
|
1066
|
+
return "unknown_key";
|
|
1067
|
+
case "ERR_JWT_EXPIRED":
|
|
1068
|
+
return "expired_token";
|
|
1069
|
+
case "ERR_JWT_INVALID":
|
|
1070
|
+
return "malformed_token";
|
|
1071
|
+
case "ERR_JWT_CLAIM_VALIDATION_FAILED": {
|
|
1072
|
+
const claim = field(error, "claim");
|
|
1073
|
+
if (claim === "nbf" && field(error, "reason") === "check_failed") return "expired_token";
|
|
1074
|
+
if (claim === "exp") return "invalid_claims";
|
|
1075
|
+
return "invalid_token";
|
|
1076
|
+
}
|
|
1077
|
+
default:
|
|
1078
|
+
return "invalid_token";
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
var hasClaim = (payload, name) => Object.hasOwn(payload, name) && payload[name] !== null && payload[name] !== "";
|
|
1082
|
+
function principalOf(config, payload, options) {
|
|
1083
|
+
const clientId = plainId(payload["client_id"]);
|
|
1084
|
+
const invalid2 = () => refuse("invalid_claims", clientId);
|
|
1085
|
+
const { aud, sub, client_id: client, scope, sid, auth_time: authTime, cv } = payload;
|
|
1086
|
+
const publicId = payload["plasgos_public_id"];
|
|
1087
|
+
if (aud !== config.audience || !nonEmptyString(sub) || !nonEmptyString(client)) return invalid2();
|
|
1088
|
+
if (scope !== void 0 && typeof scope !== "string") return invalid2();
|
|
1089
|
+
if (publicId !== void 0 && !(nonEmptyString(publicId) && publicId.length <= MAX_PUBLIC_ID_LENGTH)) return invalid2();
|
|
1090
|
+
const isUser = sid !== void 0;
|
|
1091
|
+
if (isUser) {
|
|
1092
|
+
if (!nonEmptyString(sid)) return invalid2();
|
|
1093
|
+
if (typeof authTime !== "number" || !Number.isSafeInteger(authTime) || authTime < 0) return invalid2();
|
|
1094
|
+
if (cv !== void 0 && !Number.isSafeInteger(cv)) return invalid2();
|
|
1095
|
+
} else if (!config.allowServiceTokens || sub !== client || typeof scope !== "string") {
|
|
1096
|
+
return invalid2();
|
|
1097
|
+
}
|
|
1098
|
+
const required = [...config.requiredClaims, ...options.requireClaims];
|
|
1099
|
+
if (isUser && config.requireCredentialVersion) required.push("cv");
|
|
1100
|
+
if (!required.every((name) => hasClaim(payload, name))) return invalid2();
|
|
1101
|
+
const scopes = Object.freeze(typeof scope === "string" ? scope.split(" ").filter((item) => item !== "") : []);
|
|
1102
|
+
const claims = Object.freeze({ ...payload });
|
|
1103
|
+
const principal = isUser ? {
|
|
1104
|
+
kind: "user",
|
|
1105
|
+
subject: sub,
|
|
1106
|
+
clientId: client,
|
|
1107
|
+
sessionId: sid,
|
|
1108
|
+
authTime,
|
|
1109
|
+
credentialVersion: cv ?? null,
|
|
1110
|
+
scopes,
|
|
1111
|
+
claims
|
|
1112
|
+
} : { kind: "service", subject: sub, clientId: client, scopes, claims };
|
|
1113
|
+
return { principal: Object.freeze(principal) };
|
|
1114
|
+
}
|
|
1115
|
+
async function check(state, header, options) {
|
|
1116
|
+
const { config } = state;
|
|
1117
|
+
if (typeof header !== "string" || !BEARER_SCHEME.test(header)) return refuse("missing_token");
|
|
1118
|
+
if (header.length > import_auth_shared3.MAX_JWT_LENGTH + "Bearer ".length) return refuse("malformed_token");
|
|
1119
|
+
const token = BEARER_TOKEN.exec(header)?.[1];
|
|
1120
|
+
if (token === void 0) return refuse("malformed_token");
|
|
1121
|
+
const protectedHeader = decodeHeader(token.slice(0, token.indexOf(".")));
|
|
1122
|
+
if (protectedHeader === null) return refuse("malformed_token");
|
|
1123
|
+
const { alg, kid, typ } = protectedHeader;
|
|
1124
|
+
if (alg !== import_auth_shared3.SIGNING_ALG || !nonEmptyString(kid)) return refuse("unknown_key");
|
|
1125
|
+
if (typeof typ !== "string" || !ACCEPTED_TYPES.includes(typ.toLowerCase())) return refuse("invalid_claims");
|
|
1126
|
+
const nowMs = options.now ?? Date.now();
|
|
1127
|
+
let payload;
|
|
1128
|
+
try {
|
|
1129
|
+
({ payload } = await jwtVerify(token, state.keySet, {
|
|
1130
|
+
algorithms: [import_auth_shared3.SIGNING_ALG],
|
|
1131
|
+
issuer: config.issuer,
|
|
1132
|
+
audience: config.audience,
|
|
1133
|
+
clockTolerance: config.clockToleranceSeconds,
|
|
1134
|
+
requiredClaims: ["exp"],
|
|
1135
|
+
currentDate: new Date(nowMs)
|
|
1136
|
+
}));
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
return refuse(reasonOfVerifyError(error));
|
|
1139
|
+
}
|
|
1140
|
+
const outcome = principalOf(config, payload, options);
|
|
1141
|
+
if (outcome.refusal !== void 0) return outcome;
|
|
1142
|
+
const { principal } = outcome;
|
|
1143
|
+
const clientId = plainId(principal.clientId);
|
|
1144
|
+
if (config.isRevoked !== void 0) {
|
|
1145
|
+
const revoked = await config.isRevoked(principal);
|
|
1146
|
+
if (typeof revoked !== "boolean") throw new TypeError("isRevoked must return a boolean");
|
|
1147
|
+
if (revoked) return refuse("revoked", clientId);
|
|
1148
|
+
}
|
|
1149
|
+
if (!options.scopes.every((scope) => principal.scopes.includes(scope))) return refuse("insufficient_scope", clientId);
|
|
1150
|
+
if (options.maxAuthAge !== null) {
|
|
1151
|
+
if (principal.kind !== "user" || Math.floor(nowMs / 1e3) - principal.authTime > options.maxAuthAge) {
|
|
1152
|
+
return refuse("stale_auth", clientId);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
return outcome;
|
|
1156
|
+
}
|
|
1157
|
+
function report(config, refusal, requestId) {
|
|
1158
|
+
const { onReject } = config;
|
|
1159
|
+
if (onReject === void 0) return;
|
|
1160
|
+
const event = Object.freeze({
|
|
1161
|
+
environment: config.environment,
|
|
1162
|
+
reason: refusal.reason,
|
|
1163
|
+
clientId: refusal.clientId,
|
|
1164
|
+
requestId: plainId(requestId)
|
|
1165
|
+
});
|
|
1166
|
+
try {
|
|
1167
|
+
Promise.resolve(onReject(event)).catch(() => void 0);
|
|
1168
|
+
} catch {
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
async function verifyAccessToken(state, header, rawOptions, headerRequestId = null) {
|
|
1172
|
+
const options = resolveVerifyOptions(rawOptions);
|
|
1173
|
+
const outcome = await check(state, header, options);
|
|
1174
|
+
if (outcome.refusal === void 0) return outcome.principal;
|
|
1175
|
+
const error = new import_auth_shared3.AuthVerifyError(outcome.refusal.reason, {
|
|
1176
|
+
requiredScopes: options.scopes,
|
|
1177
|
+
...options.maxAuthAge !== null ? { maxAuthAge: options.maxAuthAge } : {}
|
|
1178
|
+
});
|
|
1179
|
+
report(state.config, outcome.refusal, options.requestId !== void 0 ? options.requestId : headerRequestId);
|
|
1180
|
+
throw error;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// src/core/verifier.ts
|
|
1184
|
+
function headersOf(request) {
|
|
1185
|
+
const headers = isObject(request) ? request["headers"] : void 0;
|
|
1186
|
+
if (!isObject(headers) || typeof headers["get"] !== "function") {
|
|
1187
|
+
throw new TypeError("verifyRequest: request must be a Web Request");
|
|
1188
|
+
}
|
|
1189
|
+
const get = (name) => {
|
|
1190
|
+
const value = headers["get"].call(headers, name);
|
|
1191
|
+
return typeof value === "string" ? value : null;
|
|
1192
|
+
};
|
|
1193
|
+
return { authorization: get("authorization"), requestId: get("x-request-id") };
|
|
1194
|
+
}
|
|
1195
|
+
function createAccessTokenVerifier(options) {
|
|
1196
|
+
const config = resolveVerifierConfig(options);
|
|
1197
|
+
const state = {
|
|
1198
|
+
config,
|
|
1199
|
+
keySet: config.jwks !== null ? staticKeySet(config.jwks) : remoteKeySet(config)
|
|
1200
|
+
};
|
|
1201
|
+
return Object.freeze({
|
|
1202
|
+
environment: config.environment,
|
|
1203
|
+
issuer: config.issuer,
|
|
1204
|
+
audience: config.audience,
|
|
1205
|
+
verifyAuthorization: (header, verifyOptions) => verifyAccessToken(state, header, verifyOptions),
|
|
1206
|
+
verifyRequest: async (request, verifyOptions) => {
|
|
1207
|
+
const { authorization, requestId } = headersOf(request);
|
|
1208
|
+
return verifyAccessToken(state, authorization, verifyOptions, requestId);
|
|
1209
|
+
}
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// src/core/response.ts
|
|
1214
|
+
var import_auth_shared4 = require("@plasgos/auth-shared");
|
|
1215
|
+
var STATUSES = [401, 403, 503];
|
|
1216
|
+
var ERROR_CODES = [
|
|
1217
|
+
"invalid_token",
|
|
1218
|
+
"insufficient_scope",
|
|
1219
|
+
"insufficient_user_authentication",
|
|
1220
|
+
"temporarily_unavailable"
|
|
1221
|
+
];
|
|
1222
|
+
var REASONS = import_auth_shared4.AUTH_VERIFY_REASONS;
|
|
1223
|
+
function authRefusalOf(error) {
|
|
1224
|
+
const fields = isObject(error) || error instanceof Error ? error : null;
|
|
1225
|
+
if (fields === null) return null;
|
|
1226
|
+
const challenge = fields["wwwAuthenticate"];
|
|
1227
|
+
if (!REASONS.includes(fields["reason"]) || !STATUSES.includes(fields["status"]) || !ERROR_CODES.includes(fields["errorCode"]) || challenge !== null && typeof challenge !== "string") {
|
|
1228
|
+
return null;
|
|
1229
|
+
}
|
|
1230
|
+
return {
|
|
1231
|
+
status: fields["status"],
|
|
1232
|
+
errorCode: fields["errorCode"],
|
|
1233
|
+
wwwAuthenticate: challenge
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
function authErrorResponse(error) {
|
|
1237
|
+
const refusal = authRefusalOf(error);
|
|
1238
|
+
if (refusal === null) throw new TypeError("authErrorResponse: error must be an AuthVerifyError");
|
|
1239
|
+
const headers = new Headers({ "content-type": "application/json", "cache-control": "no-store" });
|
|
1240
|
+
if (refusal.wwwAuthenticate !== null) headers.set("www-authenticate", refusal.wwwAuthenticate);
|
|
1241
|
+
return new Response(JSON.stringify({ error: refusal.errorCode }), { status: refusal.status, headers });
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
// src/index.ts
|
|
1245
|
+
var import_auth_shared5 = require("@plasgos/auth-shared");
|
|
1246
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1247
|
+
0 && (module.exports = {
|
|
1248
|
+
AUTH_VERIFY_REASONS,
|
|
1249
|
+
AuthVerifyError,
|
|
1250
|
+
ConfigError,
|
|
1251
|
+
authErrorResponse,
|
|
1252
|
+
createAccessTokenVerifier
|
|
1253
|
+
});
|
|
1254
|
+
//# sourceMappingURL=index.cjs.map
|