@vitemcp/server 1.0.0

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.
@@ -0,0 +1,3119 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;// src/auth/helpers.ts
2
+ function getAuthSession(session) {
3
+ if (!session) {
4
+ throw new Error("Session is not authenticated");
5
+ }
6
+ return session;
7
+ }
8
+ function requireAll(...checks) {
9
+ return (auth) => checks.every(
10
+ (check) => typeof check === "function" ? check(auth) : check
11
+ );
12
+ }
13
+ function requireAny(...checks) {
14
+ return (auth) => checks.some((check) => typeof check === "function" ? check(auth) : check);
15
+ }
16
+ function requireAuth(auth) {
17
+ return auth !== void 0 && auth !== null;
18
+ }
19
+ function requireRole(...allowedRoles) {
20
+ return (auth) => {
21
+ if (!auth) return false;
22
+ const role = auth.role;
23
+ return typeof role === "string" && allowedRoles.includes(role);
24
+ };
25
+ }
26
+ function requireScopes(...requiredScopes) {
27
+ return (auth) => {
28
+ if (!auth) return false;
29
+ const authScopes = auth.scopes;
30
+ if (!authScopes) return false;
31
+ const scopeSet = Array.isArray(authScopes) ? new Set(authScopes) : authScopes instanceof Set ? authScopes : /* @__PURE__ */ new Set();
32
+ return requiredScopes.every((scope) => scopeSet.has(scope));
33
+ };
34
+ }
35
+
36
+ // src/auth/OAuthProxy.ts
37
+ var _crypto = require('crypto');
38
+ var _zod = require('zod');
39
+
40
+ // src/auth/clientIdMetadata.ts
41
+ var _dns = require('dns');
42
+ var _net = require('net');
43
+ var _undici = require('undici');
44
+ var DEFAULTS = {
45
+ defaultCacheTtlMs: 5 * 60 * 1e3,
46
+ fetchTimeoutMs: 5e3,
47
+ maxDocumentBytes: 64 * 1024
48
+ };
49
+ var isBlockedIpv4 = (ip) => {
50
+ const parts = ip.split(".").map(Number);
51
+ if (parts.length !== 4 || parts.some((p) => Number.isNaN(p))) {
52
+ return true;
53
+ }
54
+ const [a, b] = parts;
55
+ return a === 0 || // "this network"
56
+ a === 10 || // private
57
+ a === 127 || // loopback
58
+ a === 100 && b >= 64 && b <= 127 || // CGNAT
59
+ a === 169 && b === 254 || // link-local, incl. cloud metadata
60
+ a === 172 && b >= 16 && b <= 31 || // private
61
+ a === 192 && b === 0 || // IETF protocol assignments
62
+ a === 192 && b === 168 || // private
63
+ a === 198 && b >= 18 && b <= 19 || // benchmarking
64
+ a >= 224;
65
+ };
66
+ var isBlockedIpv6 = (ip) => {
67
+ const address = ip.toLowerCase().split("%")[0];
68
+ const mapped = address.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
69
+ if (mapped) {
70
+ return isBlockedIpv4(mapped[1]);
71
+ }
72
+ return address === "::" || address === "::1" || address.startsWith("fc") || // unique local
73
+ address.startsWith("fd") || // unique local
74
+ address.startsWith("fe8") || // link-local
75
+ address.startsWith("fe9") || address.startsWith("fea") || address.startsWith("feb") || address.startsWith("ff");
76
+ };
77
+ var isBlockedAddress = (ip, family) => family === 4 ? isBlockedIpv4(ip) : isBlockedIpv6(ip);
78
+ var stripBrackets = (host) => host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
79
+ var ssrfSafeAgent = new (0, _undici.Agent)({
80
+ connect: {
81
+ lookup: (hostname, options, callback) => {
82
+ _dns.lookup.call(void 0, hostname, { ...options, all: true }, (error, addresses) => {
83
+ if (error) {
84
+ callback(error, "", 0);
85
+ return;
86
+ }
87
+ const resolved = Array.isArray(addresses) ? addresses : [addresses];
88
+ const blocked = resolved.find(
89
+ (entry) => isBlockedAddress(entry.address, entry.family)
90
+ );
91
+ if (blocked || resolved.length === 0) {
92
+ callback(
93
+ new Error(
94
+ `Refusing to fetch client metadata from an internal address (${_nullishCoalesce(_optionalChain([blocked, 'optionalAccess', _ => _.address]), () => ( "unresolved"))})`
95
+ ),
96
+ "",
97
+ 0
98
+ );
99
+ return;
100
+ }
101
+ if (options.all) {
102
+ callback(null, resolved, 0);
103
+ } else {
104
+ callback(null, resolved[0].address, resolved[0].family);
105
+ }
106
+ });
107
+ }
108
+ }
109
+ });
110
+ var ClientIdMetadataError = class extends Error {
111
+ constructor(message) {
112
+ super(message);
113
+ this.name = "ClientIdMetadataError";
114
+ }
115
+ };
116
+ var isClientIdMetadataUrl = (clientId) => {
117
+ try {
118
+ const url = new URL(clientId);
119
+ return url.protocol === "https:" && url.pathname.length > 1;
120
+ } catch (e) {
121
+ return false;
122
+ }
123
+ };
124
+ var hostAllowed = (host, allowed) => {
125
+ if (!_optionalChain([allowed, 'optionalAccess', _2 => _2.length])) {
126
+ return true;
127
+ }
128
+ return allowed.some(
129
+ (entry) => entry.startsWith(".") ? host.endsWith(entry) : host === entry
130
+ );
131
+ };
132
+ var cacheTtlFromHeaders = (headers) => {
133
+ const control = headers["cache-control"];
134
+ const value = Array.isArray(control) ? control[0] : control;
135
+ if (!value) {
136
+ return null;
137
+ }
138
+ if (/\bno-store\b|\bno-cache\b/i.test(value)) {
139
+ return 0;
140
+ }
141
+ const maxAge = value.match(/\bmax-age=(\d+)/i);
142
+ return maxAge ? Number(maxAge[1]) * 1e3 : null;
143
+ };
144
+ var validateClientIdMetadata = (body, clientId) => {
145
+ let parsed;
146
+ try {
147
+ parsed = JSON.parse(body);
148
+ } catch (e2) {
149
+ throw new ClientIdMetadataError("Client metadata is not valid JSON");
150
+ }
151
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
152
+ throw new ClientIdMetadataError("Client metadata must be a JSON object");
153
+ }
154
+ const doc = parsed;
155
+ if (doc.client_id !== clientId) {
156
+ throw new ClientIdMetadataError(
157
+ "Client metadata client_id does not match the document URL"
158
+ );
159
+ }
160
+ if (typeof doc.client_name !== "string" || !doc.client_name) {
161
+ throw new ClientIdMetadataError("Client metadata is missing client_name");
162
+ }
163
+ if (!Array.isArray(doc.redirect_uris) || doc.redirect_uris.length === 0 || !doc.redirect_uris.every((uri) => typeof uri === "string")) {
164
+ throw new ClientIdMetadataError("Client metadata is missing redirect_uris");
165
+ }
166
+ return doc;
167
+ };
168
+ var ClientIdMetadataResolver = class {
169
+ get enabled() {
170
+ return this.#options.enabled;
171
+ }
172
+ #cache = /* @__PURE__ */ new Map();
173
+ #options;
174
+ constructor(options = {}) {
175
+ this.#options = {
176
+ allowedDomains: options.allowedDomains,
177
+ defaultCacheTtlMs: _nullishCoalesce(options.defaultCacheTtlMs, () => ( DEFAULTS.defaultCacheTtlMs)),
178
+ enabled: _nullishCoalesce(options.enabled, () => ( true)),
179
+ fetchTimeoutMs: _nullishCoalesce(options.fetchTimeoutMs, () => ( DEFAULTS.fetchTimeoutMs)),
180
+ maxDocumentBytes: _nullishCoalesce(options.maxDocumentBytes, () => ( DEFAULTS.maxDocumentBytes))
181
+ };
182
+ }
183
+ /** Drops cached documents (mainly for tests). */
184
+ clearCache() {
185
+ this.#cache.clear();
186
+ }
187
+ /**
188
+ * Fetches and validates the metadata document for a client_id URL.
189
+ *
190
+ * @throws {ClientIdMetadataError} on a bad URL, refused fetch, or invalid
191
+ * document.
192
+ */
193
+ async resolve(clientId) {
194
+ if (!this.#options.enabled) {
195
+ throw new ClientIdMetadataError(
196
+ "Client ID Metadata Documents are not enabled"
197
+ );
198
+ }
199
+ if (!isClientIdMetadataUrl(clientId)) {
200
+ throw new ClientIdMetadataError(
201
+ "client_id must be an https URL with a path component"
202
+ );
203
+ }
204
+ const cached = this.#cache.get(clientId);
205
+ if (cached && cached.expiresAt > Date.now()) {
206
+ return cached.metadata;
207
+ }
208
+ const url = new URL(clientId);
209
+ if (!hostAllowed(url.hostname, this.#options.allowedDomains)) {
210
+ throw new ClientIdMetadataError(
211
+ `Client metadata host is not allowed: ${url.hostname}`
212
+ );
213
+ }
214
+ const literalFamily = _net.isIP.call(void 0, stripBrackets(url.hostname));
215
+ if (literalFamily !== 0 && isBlockedAddress(stripBrackets(url.hostname), literalFamily)) {
216
+ throw new ClientIdMetadataError(
217
+ `Refusing to fetch client metadata from an internal address (${url.hostname})`
218
+ );
219
+ }
220
+ const { body, headers } = await this.#fetchDocument(url);
221
+ const metadata = validateClientIdMetadata(body, clientId);
222
+ const ttl = _nullishCoalesce(cacheTtlFromHeaders(headers), () => ( this.#options.defaultCacheTtlMs));
223
+ if (ttl > 0) {
224
+ this.#cache.set(clientId, {
225
+ expiresAt: Date.now() + ttl,
226
+ metadata
227
+ });
228
+ }
229
+ return metadata;
230
+ }
231
+ async #fetchDocument(url) {
232
+ let response;
233
+ try {
234
+ response = await _undici.request.call(void 0, url, {
235
+ dispatcher: ssrfSafeAgent,
236
+ headers: { accept: "application/json" },
237
+ headersTimeout: this.#options.fetchTimeoutMs,
238
+ // No redirect interceptor is installed, so redirects are not
239
+ // followed: a hop to an internal address is the classic SSRF bypass.
240
+ method: "GET",
241
+ signal: AbortSignal.timeout(this.#options.fetchTimeoutMs)
242
+ });
243
+ } catch (error) {
244
+ throw new ClientIdMetadataError(
245
+ `Could not fetch client metadata: ${error instanceof Error ? error.message : String(error)}`
246
+ );
247
+ }
248
+ if (response.statusCode >= 300) {
249
+ response.body.destroy();
250
+ throw new ClientIdMetadataError(
251
+ `Client metadata returned HTTP ${response.statusCode}`
252
+ );
253
+ }
254
+ let size = 0;
255
+ const chunks = [];
256
+ for await (const chunk of response.body) {
257
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
258
+ size += buf.byteLength;
259
+ if (size > this.#options.maxDocumentBytes) {
260
+ response.body.destroy();
261
+ throw new ClientIdMetadataError(
262
+ `Client metadata exceeds ${this.#options.maxDocumentBytes} bytes`
263
+ );
264
+ }
265
+ chunks.push(buf);
266
+ }
267
+ return {
268
+ body: Buffer.concat(chunks).toString("utf8"),
269
+ headers: response.headers
270
+ };
271
+ }
272
+ };
273
+
274
+ // src/auth/OAuthProxyStateStore.ts
275
+
276
+
277
+ var STORAGE_KEY_PREFIX = {
278
+ client: "client:",
279
+ code: "code:",
280
+ transaction: "transaction:"
281
+ };
282
+ var issuerNamespace = (issuer) => _crypto.createHash.call(void 0, "sha256").update(issuer).digest("hex").slice(0, 16);
283
+ var storedDateSchema = _zod.z.union([_zod.z.date(), _zod.z.string()]).transform((value, context) => {
284
+ const date = value instanceof Date ? value : new Date(value);
285
+ if (Number.isNaN(date.getTime())) {
286
+ context.addIssue({
287
+ code: "custom",
288
+ message: "Invalid stored date"
289
+ });
290
+ return _zod.z.NEVER;
291
+ }
292
+ return date;
293
+ });
294
+ var dcrClientMetadataSchema = _zod.z.object({
295
+ client_name: _zod.z.string().optional(),
296
+ client_uri: _zod.z.string().optional(),
297
+ contacts: _zod.z.array(_zod.z.string()).optional(),
298
+ jwks: _zod.z.record(_zod.z.string(), _zod.z.unknown()).optional(),
299
+ jwks_uri: _zod.z.string().optional(),
300
+ logo_uri: _zod.z.string().optional(),
301
+ policy_uri: _zod.z.string().optional(),
302
+ scope: _zod.z.string().optional(),
303
+ software_id: _zod.z.string().optional(),
304
+ software_version: _zod.z.string().optional(),
305
+ tos_uri: _zod.z.string().optional()
306
+ });
307
+ var proxyDcrClientStorageSchema = _zod.z.object({
308
+ callbackUrl: _zod.z.string(),
309
+ clientId: _zod.z.string(),
310
+ clientSecret: _zod.z.string().optional(),
311
+ metadata: dcrClientMetadataSchema.optional(),
312
+ redirectUris: _zod.z.array(_zod.z.string()),
313
+ registeredAt: storedDateSchema
314
+ });
315
+ var upstreamTokenSetStorageSchema = _zod.z.object({
316
+ accessToken: _zod.z.string(),
317
+ expiresIn: _zod.z.number(),
318
+ idToken: _zod.z.string().optional(),
319
+ issuedAt: storedDateSchema,
320
+ refreshExpiresIn: _zod.z.number().optional(),
321
+ refreshToken: _zod.z.string().optional(),
322
+ scope: _zod.z.array(_zod.z.string()),
323
+ tokenType: _zod.z.string()
324
+ });
325
+ var clientCodeStorageSchema = _zod.z.object({
326
+ clientId: _zod.z.string(),
327
+ code: _zod.z.string(),
328
+ codeChallenge: _zod.z.string(),
329
+ codeChallengeMethod: _zod.z.string(),
330
+ createdAt: storedDateSchema,
331
+ expiresAt: storedDateSchema,
332
+ transactionId: _zod.z.string(),
333
+ upstreamTokens: upstreamTokenSetStorageSchema,
334
+ used: _zod.z.boolean().optional()
335
+ });
336
+ var spentClientCodeStorageSchema = _zod.z.object({
337
+ expiresAt: storedDateSchema,
338
+ used: _zod.z.literal(true)
339
+ });
340
+ var oauthTransactionStorageSchema = _zod.z.object({
341
+ clientCallbackUrl: _zod.z.string(),
342
+ clientCodeChallenge: _zod.z.string(),
343
+ clientCodeChallengeMethod: _zod.z.string(),
344
+ clientId: _zod.z.string(),
345
+ consentGiven: _zod.z.boolean().optional(),
346
+ createdAt: storedDateSchema,
347
+ expiresAt: storedDateSchema,
348
+ id: _zod.z.string(),
349
+ metadata: _zod.z.record(_zod.z.string(), _zod.z.unknown()).optional(),
350
+ proxyCodeChallenge: _zod.z.string(),
351
+ proxyCodeVerifier: _zod.z.string(),
352
+ scope: _zod.z.array(_zod.z.string()),
353
+ state: _zod.z.string(),
354
+ upstreamIssuer: _zod.z.string()
355
+ });
356
+ var OAuthProxyStateStore = class {
357
+
358
+
359
+
360
+ constructor(config) {
361
+ this.registeredClientsByClientId = config.registeredClientsByClientId;
362
+ this.tokenStorage = config.tokenStorage;
363
+ this.namespace = issuerNamespace(config.issuer);
364
+ }
365
+ cacheRegisteredClient(client) {
366
+ this.registeredClientsByClientId.set(client.clientId, client);
367
+ }
368
+ /**
369
+ * Atomically consume an authorization code. At most one caller — across all
370
+ * processes sharing the storage — can receive a given code, which is what
371
+ * makes single use enforceable (RFC 6749 §4.1.2).
372
+ *
373
+ * Spent codes are taken too, so the caller must write the tombstone back
374
+ * with `markClientCodeSpent` to keep reporting the precise error on the
375
+ * attempt after this one.
376
+ */
377
+ async consumeClientCode(code) {
378
+ const stored = await this.takeFromStorage(
379
+ this.key(STORAGE_KEY_PREFIX.code, code)
380
+ );
381
+ const spent = spentClientCodeStorageSchema.safeParse(stored);
382
+ if (spent.success) {
383
+ return this.isExpired(spent.data.expiresAt) ? null : { expiresAt: spent.data.expiresAt, status: "spent" };
384
+ }
385
+ const parsed = clientCodeStorageSchema.safeParse(stored);
386
+ if (!parsed.success || this.isExpired(parsed.data.expiresAt)) {
387
+ return null;
388
+ }
389
+ return {
390
+ clientCode: parsed.data,
391
+ expiresAt: parsed.data.expiresAt,
392
+ status: "active"
393
+ };
394
+ }
395
+ /**
396
+ * Atomically consume a transaction, so a callback can only be redeemed once
397
+ * no matter which instance it lands on.
398
+ */
399
+ async consumeTransaction(transactionId) {
400
+ const stored = await this.takeFromStorage(
401
+ this.key(STORAGE_KEY_PREFIX.transaction, transactionId)
402
+ );
403
+ const parsed = oauthTransactionStorageSchema.safeParse(stored);
404
+ if (!parsed.success || this.isExpired(parsed.data.expiresAt)) {
405
+ return null;
406
+ }
407
+ return parsed.data;
408
+ }
409
+ async deleteTransaction(transactionId) {
410
+ await this.tokenStorage.delete(
411
+ this.key(STORAGE_KEY_PREFIX.transaction, transactionId)
412
+ );
413
+ }
414
+ async getRegisteredClientByClientId(clientId) {
415
+ const cached = this.registeredClientsByClientId.get(clientId);
416
+ if (cached) {
417
+ return cached;
418
+ }
419
+ const stored = await this.tokenStorage.get(
420
+ this.key(STORAGE_KEY_PREFIX.client, clientId)
421
+ );
422
+ const parsed = proxyDcrClientStorageSchema.safeParse(stored);
423
+ if (!parsed.success) {
424
+ return null;
425
+ }
426
+ this.cacheRegisteredClient(parsed.data);
427
+ return parsed.data;
428
+ }
429
+ /**
430
+ * Read a transaction without consuming it. Used by the consent screen, which
431
+ * has to hand the same transaction back to the upstream redirect.
432
+ */
433
+ async getTransaction(transactionId) {
434
+ const stored = await this.tokenStorage.get(
435
+ this.key(STORAGE_KEY_PREFIX.transaction, transactionId)
436
+ );
437
+ const parsed = oauthTransactionStorageSchema.safeParse(stored);
438
+ if (!parsed.success) {
439
+ return null;
440
+ }
441
+ if (this.isExpired(parsed.data.expiresAt)) {
442
+ await this.deleteTransaction(transactionId);
443
+ return null;
444
+ }
445
+ return parsed.data;
446
+ }
447
+ async isTransactionCallbackRegistered(transaction) {
448
+ const registeredClient = await this.getRegisteredClientByClientId(
449
+ transaction.clientId
450
+ );
451
+ return _nullishCoalesce(_optionalChain([registeredClient, 'optionalAccess', _3 => _3.redirectUris, 'access', _4 => _4.includes, 'call', _5 => _5(transaction.clientCallbackUrl)]), () => ( false));
452
+ }
453
+ /**
454
+ * Record that an authorization code has been redeemed, so a later attempt
455
+ * gets "already used" rather than looking like an unknown code. Keyed and
456
+ * expiring exactly like the code it replaces, so it cannot outlive it.
457
+ */
458
+ async markClientCodeSpent(code, expiresAt) {
459
+ await this.tokenStorage.save(
460
+ this.key(STORAGE_KEY_PREFIX.code, code),
461
+ { expiresAt, used: true },
462
+ this.getTtlSeconds(expiresAt)
463
+ );
464
+ }
465
+ async saveClientCode(clientCode) {
466
+ await this.tokenStorage.save(
467
+ this.key(STORAGE_KEY_PREFIX.code, clientCode.code),
468
+ clientCode,
469
+ this.getTtlSeconds(clientCode.expiresAt)
470
+ );
471
+ }
472
+ async saveRegisteredClient(client) {
473
+ await this.tokenStorage.save(
474
+ this.key(STORAGE_KEY_PREFIX.client, client.clientId),
475
+ client
476
+ );
477
+ }
478
+ async saveTransaction(transaction) {
479
+ await this.tokenStorage.save(
480
+ this.key(STORAGE_KEY_PREFIX.transaction, transaction.id),
481
+ transaction,
482
+ this.getTtlSeconds(transaction.expiresAt)
483
+ );
484
+ }
485
+ getTtlSeconds(expiresAt) {
486
+ const millisecondsUntilExpiry = expiresAt.getTime() - Date.now();
487
+ return Math.max(Math.ceil(millisecondsUntilExpiry / 1e3), 1);
488
+ }
489
+ isExpired(expiresAt) {
490
+ return expiresAt.getTime() < Date.now();
491
+ }
492
+ /**
493
+ * Builds a storage key. The record type leads so keys stay groupable by
494
+ * prefix; the issuer namespace sits between type and id so records from
495
+ * different authorization servers can never collide.
496
+ */
497
+ key(prefix, id) {
498
+ return `${prefix}${this.namespace}:${id}`;
499
+ }
500
+ /**
501
+ * Prefer the storage's atomic take. Falling back to get + delete leaves a
502
+ * window in which two processes can both observe the same value, so
503
+ * multi-process deployments should implement `TokenStorage.take`.
504
+ */
505
+ async takeFromStorage(key) {
506
+ if (this.tokenStorage.take) {
507
+ return this.tokenStorage.take(key);
508
+ }
509
+ const stored = await this.tokenStorage.get(key);
510
+ if (stored === null) {
511
+ return null;
512
+ }
513
+ await this.tokenStorage.delete(key);
514
+ return stored;
515
+ }
516
+ };
517
+
518
+ // src/auth/types.ts
519
+ var DEFAULT_ACCESS_TOKEN_TTL = 3600;
520
+ var DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH = 31536e3;
521
+ var DEFAULT_REFRESH_TOKEN_TTL = 2592e3;
522
+ var DEFAULT_AUTHORIZATION_CODE_TTL = 300;
523
+ var DEFAULT_TRANSACTION_TTL = 600;
524
+ var DEFAULT_UPSTREAM_REQUEST_TIMEOUT_MS = 1e4;
525
+
526
+ // src/auth/utils/claimsExtractor.ts
527
+ var ClaimsExtractor = (_class = class {
528
+
529
+ // Claims that MUST NOT be copied from upstream (protect proxy's JWT integrity)
530
+ __init() {this.PROTECTED_CLAIMS = /* @__PURE__ */ new Set([
531
+ "aud",
532
+ "client_id",
533
+ "exp",
534
+ "iat",
535
+ "iss",
536
+ "jti",
537
+ "nbf"
538
+ ])}
539
+ constructor(config) {;_class.prototype.__init.call(this);
540
+ if (typeof config === "boolean") {
541
+ config = config ? {} : { fromAccessToken: false, fromIdToken: false };
542
+ }
543
+ this.config = {
544
+ allowComplexClaims: config.allowComplexClaims || false,
545
+ allowedClaims: config.allowedClaims,
546
+ blockedClaims: config.blockedClaims || [],
547
+ claimPrefix: config.claimPrefix !== void 0 ? config.claimPrefix : false,
548
+ // Default: no prefix
549
+ fromAccessToken: config.fromAccessToken !== false,
550
+ // Default: true
551
+ fromIdToken: config.fromIdToken !== false,
552
+ // Default: true
553
+ maxClaimValueSize: config.maxClaimValueSize || 2e3
554
+ };
555
+ }
556
+ /**
557
+ * Extract claims from a token (access token or ID token)
558
+ */
559
+ async extract(token, tokenType) {
560
+ if (tokenType === "access" && !this.config.fromAccessToken) {
561
+ return null;
562
+ }
563
+ if (tokenType === "id" && !this.config.fromIdToken) {
564
+ return null;
565
+ }
566
+ if (!this.isJWT(token)) {
567
+ return null;
568
+ }
569
+ const payload = this.decodeJWTPayload(token);
570
+ if (!payload) {
571
+ return null;
572
+ }
573
+ const filtered = this.filterClaims(payload);
574
+ return this.applyPrefix(filtered);
575
+ }
576
+ /**
577
+ * Apply prefix to claim names (if configured)
578
+ */
579
+ applyPrefix(claims) {
580
+ const prefix = this.config.claimPrefix;
581
+ if (prefix === false || prefix === "" || prefix === void 0) {
582
+ return claims;
583
+ }
584
+ const result = {};
585
+ for (const [key, value] of Object.entries(claims)) {
586
+ result[`${prefix}${key}`] = value;
587
+ }
588
+ return result;
589
+ }
590
+ /**
591
+ * Decode JWT payload without signature verification
592
+ * Safe because token came from trusted upstream via server-to-server exchange
593
+ */
594
+ decodeJWTPayload(token) {
595
+ try {
596
+ const parts = token.split(".");
597
+ if (parts.length !== 3) {
598
+ return null;
599
+ }
600
+ const payload = Buffer.from(parts[1], "base64url").toString("utf-8");
601
+ return JSON.parse(payload);
602
+ } catch (error) {
603
+ console.warn(`Failed to decode JWT payload: ${error}`);
604
+ return null;
605
+ }
606
+ }
607
+ /**
608
+ * Filter claims based on security rules
609
+ */
610
+ filterClaims(claims) {
611
+ const result = {};
612
+ for (const [key, value] of Object.entries(claims)) {
613
+ if (this.PROTECTED_CLAIMS.has(key)) {
614
+ continue;
615
+ }
616
+ if (_optionalChain([this, 'access', _6 => _6.config, 'access', _7 => _7.blockedClaims, 'optionalAccess', _8 => _8.includes, 'call', _9 => _9(key)])) {
617
+ continue;
618
+ }
619
+ if (this.config.allowedClaims && !this.config.allowedClaims.includes(key)) {
620
+ continue;
621
+ }
622
+ if (!this.isValidClaimValue(value)) {
623
+ console.warn(`Skipping claim '${key}' due to invalid value`);
624
+ continue;
625
+ }
626
+ result[key] = value;
627
+ }
628
+ return result;
629
+ }
630
+ /**
631
+ * Check if a token is in JWT format
632
+ */
633
+ isJWT(token) {
634
+ return token.split(".").length === 3;
635
+ }
636
+ /**
637
+ * Validate a claim value (type and size checks)
638
+ */
639
+ isValidClaimValue(value) {
640
+ if (value === null || value === void 0) {
641
+ return false;
642
+ }
643
+ const type = typeof value;
644
+ if (type === "string") {
645
+ const maxSize = _nullishCoalesce(this.config.maxClaimValueSize, () => ( 2e3));
646
+ return value.length <= maxSize;
647
+ }
648
+ if (type === "number" || type === "boolean") {
649
+ return true;
650
+ }
651
+ if (Array.isArray(value) || type === "object") {
652
+ if (!this.config.allowComplexClaims) {
653
+ return false;
654
+ }
655
+ try {
656
+ const stringified = JSON.stringify(value);
657
+ const maxSize = _nullishCoalesce(this.config.maxClaimValueSize, () => ( 2e3));
658
+ return stringified.length <= maxSize;
659
+ } catch (e3) {
660
+ return false;
661
+ }
662
+ }
663
+ return false;
664
+ }
665
+ }, _class);
666
+
667
+ // src/auth/utils/consent.ts
668
+
669
+ var ConsentManager = class {
670
+
671
+ constructor(signingKey) {
672
+ this.signingKey = signingKey || this.generateDefaultKey();
673
+ }
674
+ /**
675
+ * Create HTTP response with consent screen
676
+ */
677
+ createConsentResponse(transaction, provider) {
678
+ const consentData = {
679
+ clientName: "MCP Client",
680
+ provider,
681
+ scope: transaction.scope,
682
+ timestamp: Date.now(),
683
+ transactionId: transaction.id
684
+ };
685
+ const html = this.generateConsentScreen(consentData);
686
+ return new Response(html, {
687
+ headers: {
688
+ "Content-Type": "text/html; charset=utf-8"
689
+ },
690
+ status: 200
691
+ });
692
+ }
693
+ /**
694
+ * Generate HTML for consent screen
695
+ */
696
+ generateConsentScreen(data) {
697
+ const { clientName, provider, scope, transactionId } = data;
698
+ return `
699
+ <!DOCTYPE html>
700
+ <html lang="en">
701
+ <head>
702
+ <meta charset="UTF-8">
703
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
704
+ <title>Authorization Request</title>
705
+ <style>
706
+ * {
707
+ margin: 0;
708
+ padding: 0;
709
+ box-sizing: border-box;
710
+ }
711
+
712
+ body {
713
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
714
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
715
+ min-height: 100vh;
716
+ display: flex;
717
+ justify-content: center;
718
+ align-items: center;
719
+ padding: 20px;
720
+ }
721
+
722
+ .consent-container {
723
+ background: white;
724
+ border-radius: 12px;
725
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
726
+ max-width: 480px;
727
+ width: 100%;
728
+ padding: 40px;
729
+ }
730
+
731
+ .header {
732
+ text-align: center;
733
+ margin-bottom: 30px;
734
+ }
735
+
736
+ .header h1 {
737
+ color: #1a202c;
738
+ font-size: 24px;
739
+ margin-bottom: 8px;
740
+ }
741
+
742
+ .header p {
743
+ color: #718096;
744
+ font-size: 14px;
745
+ }
746
+
747
+ .app-info {
748
+ background: #f7fafc;
749
+ border-radius: 8px;
750
+ padding: 20px;
751
+ margin-bottom: 24px;
752
+ }
753
+
754
+ .app-info h2 {
755
+ color: #2d3748;
756
+ font-size: 18px;
757
+ margin-bottom: 12px;
758
+ }
759
+
760
+ .app-name {
761
+ color: #667eea;
762
+ font-weight: 600;
763
+ }
764
+
765
+ .permissions {
766
+ margin-top: 16px;
767
+ }
768
+
769
+ .permissions h3 {
770
+ color: #4a5568;
771
+ font-size: 14px;
772
+ margin-bottom: 8px;
773
+ font-weight: 600;
774
+ }
775
+
776
+ .permissions ul {
777
+ list-style: none;
778
+ }
779
+
780
+ .permissions li {
781
+ color: #718096;
782
+ font-size: 14px;
783
+ padding: 6px 0;
784
+ padding-left: 24px;
785
+ position: relative;
786
+ }
787
+
788
+ .permissions li:before {
789
+ content: "\u2713";
790
+ position: absolute;
791
+ left: 0;
792
+ color: #48bb78;
793
+ font-weight: bold;
794
+ }
795
+
796
+ .warning {
797
+ background: #fffaf0;
798
+ border-left: 4px solid #ed8936;
799
+ padding: 12px 16px;
800
+ margin-bottom: 24px;
801
+ border-radius: 4px;
802
+ }
803
+
804
+ .warning p {
805
+ color: #744210;
806
+ font-size: 13px;
807
+ line-height: 1.5;
808
+ }
809
+
810
+ .actions {
811
+ display: flex;
812
+ gap: 12px;
813
+ }
814
+
815
+ button {
816
+ flex: 1;
817
+ padding: 14px 24px;
818
+ border: none;
819
+ border-radius: 6px;
820
+ font-size: 16px;
821
+ font-weight: 600;
822
+ cursor: pointer;
823
+ transition: all 0.2s;
824
+ }
825
+
826
+ .approve {
827
+ background: #667eea;
828
+ color: white;
829
+ }
830
+
831
+ .approve:hover {
832
+ background: #5a67d8;
833
+ transform: translateY(-1px);
834
+ box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
835
+ }
836
+
837
+ .deny {
838
+ background: #e2e8f0;
839
+ color: #4a5568;
840
+ }
841
+
842
+ .deny:hover {
843
+ background: #cbd5e0;
844
+ }
845
+
846
+ .footer {
847
+ margin-top: 24px;
848
+ text-align: center;
849
+ color: #a0aec0;
850
+ font-size: 12px;
851
+ }
852
+ </style>
853
+ </head>
854
+ <body>
855
+ <div class="consent-container">
856
+ <div class="header">
857
+ <h1>\u{1F510} Authorization Request</h1>
858
+ <p>via ${this.escapeHtml(provider)}</p>
859
+ </div>
860
+
861
+ <div class="app-info">
862
+ <h2>
863
+ <span class="app-name">${this.escapeHtml(clientName || "An application")}</span>
864
+ requests access
865
+ </h2>
866
+
867
+ <div class="permissions">
868
+ <h3>This will allow the app to:</h3>
869
+ <ul>
870
+ ${scope.map((s) => `<li>${this.escapeHtml(this.formatScope(s))}</li>`).join("")}
871
+ </ul>
872
+ </div>
873
+ </div>
874
+
875
+ <div class="warning">
876
+ <p>
877
+ <strong>\u26A0\uFE0F Important:</strong> Only approve if you trust this application.
878
+ By approving, you authorize it to access your account information.
879
+ </p>
880
+ </div>
881
+
882
+ <form method="POST" action="/oauth/consent">
883
+ <input type="hidden" name="transaction_id" value="${this.escapeHtml(transactionId)}">
884
+ <div class="actions">
885
+ <button type="submit" name="action" value="deny" class="deny">
886
+ Deny
887
+ </button>
888
+ <button type="submit" name="action" value="approve" class="approve">
889
+ Approve
890
+ </button>
891
+ </div>
892
+ </form>
893
+
894
+ <div class="footer">
895
+ <p>This consent is required to prevent unauthorized access.</p>
896
+ </div>
897
+ </div>
898
+ </body>
899
+ </html>
900
+ `.trim();
901
+ }
902
+ /**
903
+ * Sign consent data for cookie
904
+ */
905
+ signConsentCookie(data) {
906
+ const payload = JSON.stringify(data);
907
+ const signature = this.sign(payload);
908
+ return `${Buffer.from(payload).toString("base64")}.${signature}`;
909
+ }
910
+ /**
911
+ * Validate and parse consent cookie
912
+ */
913
+ validateConsentCookie(cookie) {
914
+ try {
915
+ const [payloadB64, signature] = cookie.split(".");
916
+ if (!payloadB64 || !signature) {
917
+ return null;
918
+ }
919
+ const payload = Buffer.from(payloadB64, "base64").toString("utf8");
920
+ const expectedSignature = this.sign(payload);
921
+ const actualBuf = Buffer.from(signature);
922
+ const expectedBuf = Buffer.from(expectedSignature);
923
+ if (actualBuf.length !== expectedBuf.length || !_crypto.timingSafeEqual.call(void 0, actualBuf, expectedBuf)) {
924
+ return null;
925
+ }
926
+ const data = JSON.parse(payload);
927
+ const age = Date.now() - data.timestamp;
928
+ if (age > 5 * 60 * 1e3) {
929
+ return null;
930
+ }
931
+ return data;
932
+ } catch (e4) {
933
+ return null;
934
+ }
935
+ }
936
+ /**
937
+ * Escape HTML to prevent XSS
938
+ */
939
+ escapeHtml(text) {
940
+ const map = {
941
+ "'": "&#x27;",
942
+ '"': "&quot;",
943
+ "/": "&#x2F;",
944
+ "&": "&amp;",
945
+ "<": "&lt;",
946
+ ">": "&gt;"
947
+ };
948
+ return text.replace(/[&<>"'/]/g, (char) => map[char] || char);
949
+ }
950
+ /**
951
+ * Format scope for display
952
+ */
953
+ formatScope(scope) {
954
+ const scopeMap = {
955
+ email: "Access your email address",
956
+ openid: "Verify your identity",
957
+ profile: "View your basic profile information",
958
+ "read:user": "Read your user information",
959
+ "write:user": "Modify your user information"
960
+ };
961
+ return scopeMap[scope] || scope.replace(/_/g, " ").replace(/:/g, " - ");
962
+ }
963
+ /**
964
+ * Generate default signing key if none provided
965
+ */
966
+ generateDefaultKey() {
967
+ return `vitemcp-consent-${Date.now()}-${Math.random()}`;
968
+ }
969
+ /**
970
+ * Sign a payload using HMAC-SHA256
971
+ */
972
+ sign(payload) {
973
+ return _crypto.createHmac.call(void 0, "sha256", this.signingKey).update(payload).digest("hex");
974
+ }
975
+ };
976
+
977
+ // src/auth/utils/jwtIssuer.ts
978
+
979
+ var _util = require('util');
980
+ var pbkdf2Async = _util.promisify.call(void 0, _crypto.pbkdf2);
981
+ var JWTIssuer = class {
982
+
983
+
984
+
985
+
986
+
987
+ constructor(config) {
988
+ this.issuer = config.issuer;
989
+ this.audience = config.audience;
990
+ this.accessTokenTtl = config.accessTokenTtl || DEFAULT_ACCESS_TOKEN_TTL;
991
+ this.refreshTokenTtl = config.refreshTokenTtl || DEFAULT_REFRESH_TOKEN_TTL;
992
+ this.signingKey = Buffer.from(config.signingKey);
993
+ }
994
+ /**
995
+ * Derive a signing key from a secret
996
+ * Uses PBKDF2 for key derivation
997
+ */
998
+ static async deriveKey(secret, iterations = 1e5) {
999
+ const salt = Buffer.from("vitemcp-oauth-proxy");
1000
+ const key = await pbkdf2Async(secret, salt, iterations, 32, "sha256");
1001
+ return key.toString("base64");
1002
+ }
1003
+ /**
1004
+ * Issue an access token
1005
+ */
1006
+ issueAccessToken(clientId, scope, additionalClaims, expiresIn) {
1007
+ const now = Math.floor(Date.now() / 1e3);
1008
+ const jti = this.generateJti();
1009
+ const claims = {
1010
+ aud: this.audience,
1011
+ client_id: clientId,
1012
+ exp: now + (_nullishCoalesce(expiresIn, () => ( this.accessTokenTtl))),
1013
+ iat: now,
1014
+ iss: this.issuer,
1015
+ jti,
1016
+ scope,
1017
+ // Merge additional claims (custom claims from upstream)
1018
+ ...additionalClaims || {}
1019
+ };
1020
+ return this.signToken(claims);
1021
+ }
1022
+ /**
1023
+ * Issue a refresh token
1024
+ */
1025
+ issueRefreshToken(clientId, scope, additionalClaims, expiresIn) {
1026
+ const now = Math.floor(Date.now() / 1e3);
1027
+ const jti = this.generateJti();
1028
+ const claims = {
1029
+ aud: this.audience,
1030
+ client_id: clientId,
1031
+ exp: now + (_nullishCoalesce(expiresIn, () => ( this.refreshTokenTtl))),
1032
+ iat: now,
1033
+ iss: this.issuer,
1034
+ jti,
1035
+ scope,
1036
+ // Merge additional claims (custom claims from upstream)
1037
+ ...additionalClaims || {}
1038
+ };
1039
+ return this.signToken(claims);
1040
+ }
1041
+ /**
1042
+ * Validate a JWT token
1043
+ */
1044
+ async verify(token) {
1045
+ try {
1046
+ const parts = token.split(".");
1047
+ if (parts.length !== 3) {
1048
+ return {
1049
+ error: "Invalid token format",
1050
+ valid: false
1051
+ };
1052
+ }
1053
+ const [headerB64, payloadB64, signatureB64] = parts;
1054
+ const expectedSignature = this.sign(`${headerB64}.${payloadB64}`);
1055
+ const actualBuf = Buffer.from(signatureB64);
1056
+ const expectedBuf = Buffer.from(expectedSignature);
1057
+ if (actualBuf.length !== expectedBuf.length || !_crypto.timingSafeEqual.call(void 0, actualBuf, expectedBuf)) {
1058
+ return {
1059
+ error: "Invalid signature",
1060
+ valid: false
1061
+ };
1062
+ }
1063
+ const claims = JSON.parse(
1064
+ Buffer.from(payloadB64, "base64url").toString("utf-8")
1065
+ );
1066
+ const now = Math.floor(Date.now() / 1e3);
1067
+ if (claims.exp <= now) {
1068
+ return {
1069
+ claims,
1070
+ error: "Token expired",
1071
+ valid: false
1072
+ };
1073
+ }
1074
+ if (claims.iss !== this.issuer) {
1075
+ return {
1076
+ claims,
1077
+ error: "Invalid issuer",
1078
+ valid: false
1079
+ };
1080
+ }
1081
+ if (claims.aud !== this.audience) {
1082
+ return {
1083
+ claims,
1084
+ error: "Invalid audience",
1085
+ valid: false
1086
+ };
1087
+ }
1088
+ return {
1089
+ claims,
1090
+ valid: true
1091
+ };
1092
+ } catch (error) {
1093
+ return {
1094
+ error: error instanceof Error ? error.message : "Validation failed",
1095
+ valid: false
1096
+ };
1097
+ }
1098
+ }
1099
+ /**
1100
+ * Generate unique JWT ID
1101
+ */
1102
+ generateJti() {
1103
+ return _crypto.randomBytes.call(void 0, 16).toString("base64url");
1104
+ }
1105
+ /**
1106
+ * Sign data with HMAC-SHA256
1107
+ */
1108
+ sign(data) {
1109
+ const hmac = _crypto.createHmac.call(void 0, "sha256", this.signingKey);
1110
+ hmac.update(data);
1111
+ return hmac.digest("base64url");
1112
+ }
1113
+ /**
1114
+ * Sign a JWT token
1115
+ */
1116
+ signToken(claims) {
1117
+ const header = {
1118
+ alg: "HS256",
1119
+ typ: "JWT"
1120
+ };
1121
+ const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url");
1122
+ const payloadB64 = Buffer.from(JSON.stringify(claims)).toString(
1123
+ "base64url"
1124
+ );
1125
+ const signature = this.sign(`${headerB64}.${payloadB64}`);
1126
+ return `${headerB64}.${payloadB64}.${signature}`;
1127
+ }
1128
+ };
1129
+
1130
+ // src/auth/utils/pkce.ts
1131
+
1132
+ var PKCEUtils = class _PKCEUtils {
1133
+ /**
1134
+ * Generate a code challenge from a verifier
1135
+ * @param verifier The code verifier
1136
+ * @param method Challenge method: 'S256' or 'plain' (default: 'S256')
1137
+ * @returns Base64URL-encoded challenge string
1138
+ */
1139
+ static generateChallenge(verifier, method = "S256") {
1140
+ if (method === "plain") {
1141
+ return verifier;
1142
+ }
1143
+ if (method === "S256") {
1144
+ const hash = _crypto.createHash.call(void 0, "sha256");
1145
+ hash.update(verifier);
1146
+ return _PKCEUtils.base64URLEncode(hash.digest());
1147
+ }
1148
+ throw new Error(`Unsupported challenge method: ${method}`);
1149
+ }
1150
+ /**
1151
+ * Generate a complete PKCE pair (verifier + challenge)
1152
+ * @param method Challenge method: 'S256' or 'plain' (default: 'S256')
1153
+ * @returns Object containing verifier and challenge
1154
+ */
1155
+ static generatePair(method = "S256") {
1156
+ const verifier = _PKCEUtils.generateVerifier();
1157
+ const challenge = _PKCEUtils.generateChallenge(verifier, method);
1158
+ return {
1159
+ challenge,
1160
+ verifier
1161
+ };
1162
+ }
1163
+ /**
1164
+ * Generate a cryptographically secure code verifier
1165
+ * @param length Length of verifier (43-128 characters, default: 128)
1166
+ * @returns Base64URL-encoded verifier string
1167
+ */
1168
+ static generateVerifier(length = 128) {
1169
+ if (length < 43 || length > 128) {
1170
+ throw new Error("PKCE verifier length must be between 43 and 128");
1171
+ }
1172
+ const byteLength = Math.ceil(length * 3 / 4);
1173
+ const randomBytesBuffer = _crypto.randomBytes.call(void 0, byteLength);
1174
+ return _PKCEUtils.base64URLEncode(randomBytesBuffer).slice(0, length);
1175
+ }
1176
+ /**
1177
+ * Validate a code verifier against a challenge
1178
+ * @param verifier The code verifier to validate
1179
+ * @param challenge The expected challenge
1180
+ * @param method The challenge method used
1181
+ * @returns True if verifier matches challenge
1182
+ */
1183
+ static validateChallenge(verifier, challenge, method) {
1184
+ if (!verifier || !challenge) {
1185
+ return false;
1186
+ }
1187
+ if (method === "plain") {
1188
+ return verifier === challenge;
1189
+ }
1190
+ if (method === "S256") {
1191
+ const computedChallenge = _PKCEUtils.generateChallenge(verifier, "S256");
1192
+ return computedChallenge === challenge;
1193
+ }
1194
+ return false;
1195
+ }
1196
+ /**
1197
+ * Encode a buffer as base64url (RFC 4648)
1198
+ * @param buffer Buffer to encode
1199
+ * @returns Base64URL-encoded string
1200
+ */
1201
+ static base64URLEncode(buffer) {
1202
+ return buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1203
+ }
1204
+ };
1205
+
1206
+ // src/auth/utils/tokenStore.ts
1207
+
1208
+
1209
+
1210
+
1211
+
1212
+
1213
+ var EncryptedTokenStorage = (_class2 = class {
1214
+ __init2() {this.algorithm = "aes-256-gcm"}
1215
+
1216
+
1217
+ constructor(backend, encryptionKey) {;_class2.prototype.__init2.call(this);
1218
+ this.backend = backend;
1219
+ const salt = Buffer.from("vitemcp-oauth-proxy-salt");
1220
+ this.encryptionKey = _crypto.scryptSync.call(void 0, encryptionKey, salt, 32);
1221
+ }
1222
+ async cleanup() {
1223
+ await this.backend.cleanup();
1224
+ }
1225
+ async delete(key) {
1226
+ await this.backend.delete(key);
1227
+ }
1228
+ async get(key) {
1229
+ return this.decryptStored(await this.backend.get(key));
1230
+ }
1231
+ async save(key, value, ttl) {
1232
+ const encrypted = await this.encrypt(
1233
+ JSON.stringify(value),
1234
+ this.encryptionKey
1235
+ );
1236
+ await this.backend.save(key, encrypted, ttl);
1237
+ }
1238
+ /**
1239
+ * Delegates to the backend so that the atomicity of the underlying store is
1240
+ * preserved; falls back to get + delete when the backend cannot do better.
1241
+ */
1242
+ async take(key) {
1243
+ if (this.backend.take) {
1244
+ return this.decryptStored(await this.backend.take(key));
1245
+ }
1246
+ const value = await this.get(key);
1247
+ if (value === null) {
1248
+ return null;
1249
+ }
1250
+ await this.backend.delete(key);
1251
+ return value;
1252
+ }
1253
+ async decrypt(ciphertext, key) {
1254
+ const parts = ciphertext.split(":");
1255
+ if (parts.length !== 3) {
1256
+ throw new Error("Invalid encrypted data format");
1257
+ }
1258
+ const [ivHex, authTagHex, encrypted] = parts;
1259
+ const iv = Buffer.from(ivHex, "hex");
1260
+ const authTag = Buffer.from(authTagHex, "hex");
1261
+ const decipher = _crypto.createDecipheriv.call(void 0, this.algorithm, key, iv, {
1262
+ authTagLength: 16
1263
+ });
1264
+ decipher.setAuthTag(
1265
+ authTag
1266
+ );
1267
+ let decrypted = decipher.update(encrypted, "hex", "utf8");
1268
+ decrypted += decipher.final("utf8");
1269
+ return decrypted;
1270
+ }
1271
+ async decryptStored(encrypted) {
1272
+ if (!encrypted) {
1273
+ return null;
1274
+ }
1275
+ try {
1276
+ const decrypted = await this.decrypt(
1277
+ encrypted,
1278
+ this.encryptionKey
1279
+ );
1280
+ return JSON.parse(decrypted);
1281
+ } catch (error) {
1282
+ console.error("Failed to decrypt value:", error);
1283
+ return null;
1284
+ }
1285
+ }
1286
+ async encrypt(plaintext, key) {
1287
+ const iv = _crypto.randomBytes.call(void 0, 16);
1288
+ const cipher = _crypto.createCipheriv.call(void 0, this.algorithm, key, iv, {
1289
+ authTagLength: 16
1290
+ });
1291
+ let encrypted = cipher.update(plaintext, "utf8", "hex");
1292
+ encrypted += cipher.final("hex");
1293
+ const authTag = cipher.getAuthTag();
1294
+ return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
1295
+ }
1296
+ }, _class2);
1297
+ var MemoryTokenStorage = (_class3 = class {
1298
+ __init3() {this.cleanupInterval = null}
1299
+ __init4() {this.store = /* @__PURE__ */ new Map()}
1300
+ constructor(cleanupIntervalMs = 6e4) {;_class3.prototype.__init3.call(this);_class3.prototype.__init4.call(this);
1301
+ this.cleanupInterval = setInterval(
1302
+ () => void this.cleanup(),
1303
+ cleanupIntervalMs
1304
+ );
1305
+ }
1306
+ async cleanup() {
1307
+ const now = Date.now();
1308
+ const keysToDelete = [];
1309
+ for (const [key, entry] of this.store.entries()) {
1310
+ if (entry.expiresAt < now) {
1311
+ keysToDelete.push(key);
1312
+ }
1313
+ }
1314
+ for (const key of keysToDelete) {
1315
+ this.store.delete(key);
1316
+ }
1317
+ }
1318
+ async delete(key) {
1319
+ this.store.delete(key);
1320
+ }
1321
+ /**
1322
+ * Destroy the storage and clear cleanup interval
1323
+ */
1324
+ destroy() {
1325
+ if (this.cleanupInterval) {
1326
+ clearInterval(this.cleanupInterval);
1327
+ this.cleanupInterval = null;
1328
+ }
1329
+ this.store.clear();
1330
+ }
1331
+ async get(key) {
1332
+ const entry = this.store.get(key);
1333
+ if (!entry) {
1334
+ return null;
1335
+ }
1336
+ if (entry.expiresAt < Date.now()) {
1337
+ this.store.delete(key);
1338
+ return null;
1339
+ }
1340
+ return entry.value;
1341
+ }
1342
+ async save(key, value, ttl) {
1343
+ const expiresAt = ttl ? Date.now() + ttl * 1e3 : Number.MAX_SAFE_INTEGER;
1344
+ this.store.set(key, {
1345
+ expiresAt,
1346
+ value
1347
+ });
1348
+ }
1349
+ /**
1350
+ * Get the number of stored items
1351
+ */
1352
+ size() {
1353
+ return this.store.size;
1354
+ }
1355
+ /**
1356
+ * Atomic by construction: the read and the delete happen in a single
1357
+ * synchronous block, so no other task can observe the value in between.
1358
+ */
1359
+ async take(key) {
1360
+ const entry = this.store.get(key);
1361
+ this.store.delete(key);
1362
+ if (!entry || entry.expiresAt < Date.now()) {
1363
+ return null;
1364
+ }
1365
+ return entry.value;
1366
+ }
1367
+ }, _class3);
1368
+
1369
+ // src/auth/OAuthProxy.ts
1370
+ var RESERVED_AUTHORIZATION_PARAMS = /* @__PURE__ */ new Set([
1371
+ "client_id",
1372
+ "code_challenge",
1373
+ "code_challenge_method",
1374
+ "redirect_uri",
1375
+ "response_type",
1376
+ "scope",
1377
+ "state"
1378
+ ]);
1379
+ var OAuthProxy = (_class4 = class {
1380
+ __init5() {this.claimsExtractor = null}
1381
+ __init6() {this.cleanupInterval = null}
1382
+
1383
+
1384
+
1385
+
1386
+
1387
+ /**
1388
+ * Keyed by proxy-issued client_id for authorize/token-exchange lookups and
1389
+ * for the defence-in-depth callback checks. A registration never changes
1390
+ * after it is written, so caching it locally cannot go stale; it is also
1391
+ * persisted, so another instance can hydrate it.
1392
+ */
1393
+ __init7() {this.registeredClientsByClientId = /* @__PURE__ */ new Map()}
1394
+
1395
+
1396
+ constructor(config) {;_class4.prototype.__init5.call(this);_class4.prototype.__init6.call(this);_class4.prototype.__init7.call(this);
1397
+ this.config = {
1398
+ authorizationCodeTtl: DEFAULT_AUTHORIZATION_CODE_TTL,
1399
+ consentRequired: true,
1400
+ enableTokenSwap: true,
1401
+ // Enabled by default for security
1402
+ redirectPath: "/oauth/callback",
1403
+ transactionTtl: DEFAULT_TRANSACTION_TTL,
1404
+ upstreamRequestTimeoutMs: DEFAULT_UPSTREAM_REQUEST_TIMEOUT_MS,
1405
+ upstreamTokenEndpointAuthMethod: "client_secret_basic",
1406
+ ...config
1407
+ };
1408
+ let storage = config.tokenStorage || new MemoryTokenStorage();
1409
+ const isAlreadyEncrypted = storage.constructor.name === "EncryptedTokenStorage";
1410
+ if (!isAlreadyEncrypted && config.encryptionKey !== false) {
1411
+ const encryptionKey = typeof config.encryptionKey === "string" ? config.encryptionKey : this.generateSigningKey();
1412
+ storage = new EncryptedTokenStorage(storage, encryptionKey);
1413
+ }
1414
+ this.tokenStorage = storage;
1415
+ this.clientIdMetadata = new ClientIdMetadataResolver(
1416
+ this.config.clientIdMetadata
1417
+ );
1418
+ this.issuerNs = issuerNamespace(this.getUpstreamIssuer());
1419
+ this.stateStore = new OAuthProxyStateStore({
1420
+ issuer: this.getUpstreamIssuer(),
1421
+ registeredClientsByClientId: this.registeredClientsByClientId,
1422
+ tokenStorage: this.tokenStorage
1423
+ });
1424
+ this.consentManager = new ConsentManager(
1425
+ config.consentSigningKey || this.generateSigningKey()
1426
+ );
1427
+ if (this.config.enableTokenSwap) {
1428
+ const signingKey = this.config.jwtSigningKey || this.generateSigningKey();
1429
+ this.jwtIssuer = new JWTIssuer({
1430
+ audience: this.config.baseUrl,
1431
+ issuer: this.config.baseUrl,
1432
+ signingKey
1433
+ });
1434
+ }
1435
+ const claimsConfig = config.customClaimsPassthrough !== void 0 ? config.customClaimsPassthrough : true;
1436
+ if (claimsConfig !== false) {
1437
+ this.claimsExtractor = new ClaimsExtractor(claimsConfig);
1438
+ }
1439
+ this.startCleanup();
1440
+ }
1441
+ /**
1442
+ * OAuth authorization endpoint
1443
+ */
1444
+ async authorize(params) {
1445
+ if (!params.client_id || !params.redirect_uri || !params.response_type) {
1446
+ throw new OAuthProxyError(
1447
+ "invalid_request",
1448
+ "Missing required parameters"
1449
+ );
1450
+ }
1451
+ if (params.response_type !== "code") {
1452
+ throw new OAuthProxyError(
1453
+ "unsupported_response_type",
1454
+ "Only 'code' response type is supported"
1455
+ );
1456
+ }
1457
+ const registeredUris = await this.resolveClientRedirectUris(
1458
+ params.client_id
1459
+ );
1460
+ if (!registeredUris.includes(params.redirect_uri)) {
1461
+ throw new OAuthProxyError(
1462
+ "invalid_request",
1463
+ "redirect_uri is not registered for this client"
1464
+ );
1465
+ }
1466
+ if (params.code_challenge && !params.code_challenge_method) {
1467
+ throw new OAuthProxyError(
1468
+ "invalid_request",
1469
+ "code_challenge_method required when code_challenge is present"
1470
+ );
1471
+ }
1472
+ const transaction = await this.createTransaction(params);
1473
+ if (this.config.consentRequired && !transaction.consentGiven) {
1474
+ return this.consentManager.createConsentResponse(
1475
+ transaction,
1476
+ this.getProviderName()
1477
+ );
1478
+ }
1479
+ return this.redirectToUpstream(transaction);
1480
+ }
1481
+ /**
1482
+ * Stop cleanup interval and destroy resources
1483
+ */
1484
+ destroy() {
1485
+ if (this.cleanupInterval) {
1486
+ clearInterval(this.cleanupInterval);
1487
+ this.cleanupInterval = null;
1488
+ }
1489
+ this.registeredClientsByClientId.clear();
1490
+ }
1491
+ /**
1492
+ * Token endpoint - exchange authorization code for tokens
1493
+ */
1494
+ async exchangeAuthorizationCode(request2) {
1495
+ if (request2.grant_type !== "authorization_code") {
1496
+ throw new OAuthProxyError(
1497
+ "unsupported_grant_type",
1498
+ "Only authorization_code grant type is supported"
1499
+ );
1500
+ }
1501
+ const registeredClient = await this.stateStore.getRegisteredClientByClientId(request2.client_id);
1502
+ if (!registeredClient) {
1503
+ throw new OAuthProxyError("invalid_client", "Unknown client_id");
1504
+ }
1505
+ const consumed = await this.stateStore.consumeClientCode(request2.code);
1506
+ if (!consumed) {
1507
+ throw new OAuthProxyError(
1508
+ "invalid_grant",
1509
+ "Invalid or expired authorization code"
1510
+ );
1511
+ }
1512
+ await this.stateStore.markClientCodeSpent(request2.code, consumed.expiresAt);
1513
+ if (consumed.status === "spent") {
1514
+ throw new OAuthProxyError(
1515
+ "invalid_grant",
1516
+ "Authorization code already used"
1517
+ );
1518
+ }
1519
+ const clientCode = consumed.clientCode;
1520
+ if (clientCode.clientId !== request2.client_id) {
1521
+ throw new OAuthProxyError("invalid_client", "Client ID mismatch");
1522
+ }
1523
+ if (clientCode.codeChallenge) {
1524
+ if (!request2.code_verifier) {
1525
+ throw new OAuthProxyError(
1526
+ "invalid_request",
1527
+ "code_verifier required for PKCE"
1528
+ );
1529
+ }
1530
+ const valid = PKCEUtils.validateChallenge(
1531
+ request2.code_verifier,
1532
+ clientCode.codeChallenge,
1533
+ clientCode.codeChallengeMethod
1534
+ );
1535
+ if (!valid) {
1536
+ throw new OAuthProxyError("invalid_grant", "Invalid PKCE verifier");
1537
+ }
1538
+ }
1539
+ if (this.config.enableTokenSwap && this.jwtIssuer) {
1540
+ return await this.issueSwappedTokens(
1541
+ clientCode.clientId,
1542
+ clientCode.upstreamTokens
1543
+ );
1544
+ } else {
1545
+ const response = {
1546
+ access_token: clientCode.upstreamTokens.accessToken,
1547
+ expires_in: clientCode.upstreamTokens.expiresIn,
1548
+ token_type: clientCode.upstreamTokens.tokenType
1549
+ };
1550
+ if (clientCode.upstreamTokens.refreshToken) {
1551
+ response.refresh_token = clientCode.upstreamTokens.refreshToken;
1552
+ }
1553
+ if (clientCode.upstreamTokens.idToken) {
1554
+ response.id_token = clientCode.upstreamTokens.idToken;
1555
+ }
1556
+ if (clientCode.upstreamTokens.scope.length > 0) {
1557
+ response.scope = clientCode.upstreamTokens.scope.join(" ");
1558
+ }
1559
+ return response;
1560
+ }
1561
+ }
1562
+ /**
1563
+ * Token endpoint - refresh access token
1564
+ */
1565
+ async exchangeRefreshToken(request2) {
1566
+ if (request2.grant_type !== "refresh_token") {
1567
+ throw new OAuthProxyError(
1568
+ "unsupported_grant_type",
1569
+ "Only refresh_token grant type is supported"
1570
+ );
1571
+ }
1572
+ if (this.config.enableTokenSwap && this.jwtIssuer) {
1573
+ return await this.handleSwapModeRefresh(request2);
1574
+ }
1575
+ return await this.handlePassthroughRefresh(request2);
1576
+ }
1577
+ /**
1578
+ * Get OAuth discovery metadata
1579
+ */
1580
+ getAuthorizationServerMetadata() {
1581
+ return {
1582
+ authorizationEndpoint: `${this.config.baseUrl}/oauth/authorize`,
1583
+ // RFC 9207 §3: advertise that responses carry `iss`, so clients know to
1584
+ // validate it.
1585
+ authorizationResponseIssParameterSupported: true,
1586
+ // Clients prefer CIMD over DCR when both are offered.
1587
+ clientIdMetadataDocumentSupported: this.clientIdMetadata.enabled,
1588
+ codeChallengeMethodsSupported: ["S256", "plain"],
1589
+ grantTypesSupported: ["authorization_code", "refresh_token"],
1590
+ issuer: this.config.baseUrl,
1591
+ registrationEndpoint: `${this.config.baseUrl}/oauth/register`,
1592
+ responseTypesSupported: ["code"],
1593
+ scopesSupported: this.config.scopes || [],
1594
+ tokenEndpoint: `${this.config.baseUrl}/oauth/token`,
1595
+ tokenEndpointAuthMethodsSupported: [
1596
+ "client_secret_basic",
1597
+ "client_secret_post"
1598
+ ]
1599
+ };
1600
+ }
1601
+ /**
1602
+ * Handle OAuth callback from upstream provider
1603
+ */
1604
+ async handleCallback(request2) {
1605
+ const url = new URL(request2.url);
1606
+ const code = url.searchParams.get("code");
1607
+ const state = url.searchParams.get("state");
1608
+ const error = url.searchParams.get("error");
1609
+ if (error) {
1610
+ const errorDescription = url.searchParams.get("error_description");
1611
+ throw new OAuthProxyError(error, errorDescription || void 0);
1612
+ }
1613
+ if (!code || !state) {
1614
+ throw new OAuthProxyError(
1615
+ "invalid_request",
1616
+ "Missing code or state parameter"
1617
+ );
1618
+ }
1619
+ const transaction = await this.stateStore.consumeTransaction(state);
1620
+ if (!transaction) {
1621
+ throw new OAuthProxyError("invalid_request", "Invalid or expired state");
1622
+ }
1623
+ if (!await this.stateStore.isTransactionCallbackRegistered(transaction)) {
1624
+ throw new OAuthProxyError(
1625
+ "invalid_request",
1626
+ "Transaction callback URL is not registered"
1627
+ );
1628
+ }
1629
+ const responseIssuer = url.searchParams.get("iss");
1630
+ if (responseIssuer && responseIssuer !== transaction.upstreamIssuer) {
1631
+ throw new OAuthProxyError(
1632
+ "invalid_request",
1633
+ "Authorization response issuer does not match the request issuer"
1634
+ );
1635
+ }
1636
+ const upstreamTokens = await this.exchangeUpstreamCode(code, transaction);
1637
+ const clientCode = await this.generateAuthorizationCode(
1638
+ transaction,
1639
+ upstreamTokens
1640
+ );
1641
+ const redirectUrl = new URL(transaction.clientCallbackUrl);
1642
+ redirectUrl.searchParams.set("code", clientCode);
1643
+ redirectUrl.searchParams.set("state", transaction.state);
1644
+ redirectUrl.searchParams.set("iss", this.config.baseUrl);
1645
+ return new Response(null, {
1646
+ headers: {
1647
+ Location: redirectUrl.toString()
1648
+ },
1649
+ status: 302
1650
+ });
1651
+ }
1652
+ /**
1653
+ * Handle consent form submission
1654
+ */
1655
+ async handleConsent(request2) {
1656
+ const formData = await request2.formData();
1657
+ const transactionId = formData.get("transaction_id");
1658
+ const action = formData.get("action");
1659
+ if (typeof transactionId !== "string" || !transactionId) {
1660
+ throw new OAuthProxyError("invalid_request", "Missing transaction_id");
1661
+ }
1662
+ if (action !== "approve" && action !== "deny") {
1663
+ throw new OAuthProxyError(
1664
+ "invalid_request",
1665
+ "action must be 'approve' or 'deny'"
1666
+ );
1667
+ }
1668
+ const transaction = await this.stateStore.getTransaction(transactionId);
1669
+ if (!transaction) {
1670
+ throw new OAuthProxyError(
1671
+ "invalid_request",
1672
+ "Invalid or expired transaction"
1673
+ );
1674
+ }
1675
+ if (action === "deny") {
1676
+ await this.stateStore.deleteTransaction(transactionId);
1677
+ if (!await this.stateStore.isTransactionCallbackRegistered(transaction)) {
1678
+ throw new OAuthProxyError(
1679
+ "invalid_request",
1680
+ "Transaction callback URL is not registered"
1681
+ );
1682
+ }
1683
+ const redirectUrl = new URL(transaction.clientCallbackUrl);
1684
+ redirectUrl.searchParams.set("error", "access_denied");
1685
+ redirectUrl.searchParams.set(
1686
+ "error_description",
1687
+ "User denied authorization"
1688
+ );
1689
+ redirectUrl.searchParams.set("state", transaction.state);
1690
+ redirectUrl.searchParams.set("iss", this.config.baseUrl);
1691
+ return new Response(null, {
1692
+ headers: {
1693
+ Location: redirectUrl.toString()
1694
+ },
1695
+ status: 302
1696
+ });
1697
+ }
1698
+ const approvedTransaction = {
1699
+ ...transaction,
1700
+ consentGiven: true
1701
+ };
1702
+ await this.stateStore.saveTransaction(approvedTransaction);
1703
+ return this.redirectToUpstream(approvedTransaction);
1704
+ }
1705
+ /**
1706
+ * Load upstream tokens from a ViteMCP JWT
1707
+ */
1708
+ async loadUpstreamTokens(vitemcpToken) {
1709
+ if (!this.jwtIssuer) {
1710
+ return null;
1711
+ }
1712
+ const result = await this.jwtIssuer.verify(vitemcpToken);
1713
+ if (!result.valid || !_optionalChain([result, 'access', _10 => _10.claims, 'optionalAccess', _11 => _11.jti])) {
1714
+ return null;
1715
+ }
1716
+ const mapping = await this.tokenStorage.get(
1717
+ `mapping:${this.issuerNs}:${result.claims.jti}`
1718
+ );
1719
+ if (!mapping) {
1720
+ return null;
1721
+ }
1722
+ const upstreamTokens = await this.tokenStorage.get(
1723
+ `upstream:${this.issuerNs}:${mapping.upstreamTokenKey}`
1724
+ );
1725
+ return upstreamTokens;
1726
+ }
1727
+ /**
1728
+ * RFC 7591 Dynamic Client Registration
1729
+ */
1730
+ async registerClient(request2) {
1731
+ if (!request2.redirect_uris || request2.redirect_uris.length === 0) {
1732
+ throw new OAuthProxyError(
1733
+ "invalid_client_metadata",
1734
+ "redirect_uris is required"
1735
+ );
1736
+ }
1737
+ for (const uri of request2.redirect_uris) {
1738
+ if (!this.validateRedirectUri(uri)) {
1739
+ throw new OAuthProxyError(
1740
+ "invalid_redirect_uri",
1741
+ `Invalid redirect URI: ${uri}`
1742
+ );
1743
+ }
1744
+ }
1745
+ const applicationType = _nullishCoalesce(request2.application_type, () => ( (request2.redirect_uris.every((uri) => isLoopbackRedirectUri(uri)) ? "native" : "web")));
1746
+ if (request2.application_type && request2.application_type !== "native" && request2.application_type !== "web") {
1747
+ throw new OAuthProxyError(
1748
+ "invalid_client_metadata",
1749
+ 'application_type must be "native" or "web"'
1750
+ );
1751
+ }
1752
+ const proxyClientId = _crypto.randomBytes.call(void 0, 16).toString("hex");
1753
+ const proxyClientSecret = _crypto.randomBytes.call(void 0, 32).toString("base64url");
1754
+ const client = {
1755
+ callbackUrl: request2.redirect_uris[0],
1756
+ clientId: proxyClientId,
1757
+ clientSecret: proxyClientSecret,
1758
+ metadata: {
1759
+ application_type: request2.application_type,
1760
+ client_name: request2.client_name,
1761
+ client_uri: request2.client_uri,
1762
+ contacts: request2.contacts,
1763
+ jwks: request2.jwks,
1764
+ jwks_uri: request2.jwks_uri,
1765
+ logo_uri: request2.logo_uri,
1766
+ policy_uri: request2.policy_uri,
1767
+ scope: request2.scope,
1768
+ software_id: request2.software_id,
1769
+ software_version: request2.software_version,
1770
+ tos_uri: request2.tos_uri
1771
+ },
1772
+ redirectUris: request2.redirect_uris,
1773
+ registeredAt: /* @__PURE__ */ new Date()
1774
+ };
1775
+ this.stateStore.cacheRegisteredClient(client);
1776
+ await this.stateStore.saveRegisteredClient(client);
1777
+ const response = {
1778
+ // Echoed so a client can detect a server that silently dropped it.
1779
+ application_type: applicationType,
1780
+ client_id: proxyClientId,
1781
+ client_id_issued_at: Math.floor(Date.now() / 1e3),
1782
+ // Echo back optional metadata
1783
+ client_name: request2.client_name,
1784
+ client_secret: proxyClientSecret,
1785
+ client_secret_expires_at: 0,
1786
+ // Never expires
1787
+ client_uri: request2.client_uri,
1788
+ contacts: request2.contacts,
1789
+ grant_types: request2.grant_types || [
1790
+ "authorization_code",
1791
+ "refresh_token"
1792
+ ],
1793
+ jwks: request2.jwks,
1794
+ jwks_uri: request2.jwks_uri,
1795
+ logo_uri: request2.logo_uri,
1796
+ policy_uri: request2.policy_uri,
1797
+ redirect_uris: request2.redirect_uris,
1798
+ response_types: request2.response_types || ["code"],
1799
+ scope: request2.scope,
1800
+ software_id: request2.software_id,
1801
+ software_version: request2.software_version,
1802
+ token_endpoint_auth_method: request2.token_endpoint_auth_method || "client_secret_basic",
1803
+ tos_uri: request2.tos_uri
1804
+ };
1805
+ return response;
1806
+ }
1807
+ /**
1808
+ * Calculate access token TTL from upstream tokens
1809
+ */
1810
+ calculateAccessTokenTtl(upstreamTokens) {
1811
+ if (upstreamTokens.expiresIn > 0) {
1812
+ return upstreamTokens.expiresIn;
1813
+ } else if (this.config.accessTokenTtl) {
1814
+ return this.config.accessTokenTtl;
1815
+ } else if (upstreamTokens.refreshToken) {
1816
+ return DEFAULT_ACCESS_TOKEN_TTL;
1817
+ } else {
1818
+ return DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH;
1819
+ }
1820
+ }
1821
+ /**
1822
+ * Periodic maintenance hook. Expiry is enforced by the token storage.
1823
+ */
1824
+ cleanup() {
1825
+ void this.tokenStorage.cleanup().catch((error) => {
1826
+ console.error(
1827
+ "[ViteMCP] OAuth proxy token storage cleanup failed:",
1828
+ error instanceof Error ? error.message : String(error)
1829
+ );
1830
+ });
1831
+ }
1832
+ /**
1833
+ * Create a new OAuth transaction
1834
+ */
1835
+ async createTransaction(params) {
1836
+ const transactionId = this.generateId();
1837
+ const proxyPkce = PKCEUtils.generatePair("S256");
1838
+ const transaction = {
1839
+ clientCallbackUrl: params.redirect_uri,
1840
+ clientCodeChallenge: params.code_challenge || "",
1841
+ clientCodeChallengeMethod: params.code_challenge_method || "plain",
1842
+ clientId: params.client_id,
1843
+ createdAt: /* @__PURE__ */ new Date(),
1844
+ expiresAt: new Date(
1845
+ Date.now() + (this.config.transactionTtl || 600) * 1e3
1846
+ ),
1847
+ id: transactionId,
1848
+ proxyCodeChallenge: proxyPkce.challenge,
1849
+ proxyCodeVerifier: proxyPkce.verifier,
1850
+ scope: params.scope ? params.scope.split(" ") : this.config.scopes || [],
1851
+ state: params.state || this.generateId(),
1852
+ upstreamIssuer: this.getUpstreamIssuer()
1853
+ };
1854
+ await this.stateStore.saveTransaction(transaction);
1855
+ return transaction;
1856
+ }
1857
+ /**
1858
+ * Exchange authorization code with upstream provider
1859
+ */
1860
+ async exchangeUpstreamCode(code, transaction) {
1861
+ const useBasicAuth = this.config.upstreamTokenEndpointAuthMethod === "client_secret_basic";
1862
+ const bodyParams = {
1863
+ code,
1864
+ code_verifier: transaction.proxyCodeVerifier,
1865
+ grant_type: "authorization_code",
1866
+ redirect_uri: `${this.config.baseUrl}${this.config.redirectPath}`
1867
+ };
1868
+ if (!useBasicAuth) {
1869
+ bodyParams.client_id = this.config.upstreamClientId;
1870
+ bodyParams.client_secret = this.config.upstreamClientSecret;
1871
+ }
1872
+ const headers = {
1873
+ "Content-Type": "application/x-www-form-urlencoded"
1874
+ };
1875
+ if (useBasicAuth) {
1876
+ headers["Authorization"] = this.getBasicAuthHeader();
1877
+ }
1878
+ const tokenResponse = await this.fetchUpstream(bodyParams, headers);
1879
+ if (!tokenResponse.ok) {
1880
+ let errorCode = "server_error";
1881
+ let errorDescription;
1882
+ try {
1883
+ const error = await tokenResponse.json();
1884
+ errorCode = error.error || "server_error";
1885
+ errorDescription = error.error_description;
1886
+ } catch (e5) {
1887
+ errorDescription = `Upstream returned HTTP ${tokenResponse.status} ${tokenResponse.statusText}`;
1888
+ }
1889
+ throw new OAuthProxyError(errorCode, errorDescription);
1890
+ }
1891
+ const tokens = await this.parseTokenResponse(tokenResponse);
1892
+ return {
1893
+ accessToken: tokens.access_token,
1894
+ expiresIn: tokens.expires_in || 3600,
1895
+ idToken: tokens.id_token,
1896
+ issuedAt: /* @__PURE__ */ new Date(),
1897
+ refreshExpiresIn: tokens.refresh_expires_in,
1898
+ refreshToken: tokens.refresh_token,
1899
+ scope: tokens.scope ? tokens.scope.split(" ") : transaction.scope,
1900
+ tokenType: tokens.token_type || "Bearer"
1901
+ };
1902
+ }
1903
+ /**
1904
+ * Extract JTI from a JWT token
1905
+ */
1906
+ async extractJti(token) {
1907
+ if (!this.jwtIssuer) {
1908
+ throw new Error("JWT issuer not initialized");
1909
+ }
1910
+ const result = await this.jwtIssuer.verify(token);
1911
+ if (!result.valid || !_optionalChain([result, 'access', _12 => _12.claims, 'optionalAccess', _13 => _13.jti])) {
1912
+ throw new Error("Failed to extract JTI from token");
1913
+ }
1914
+ return result.claims.jti;
1915
+ }
1916
+ /**
1917
+ * Extract custom claims from upstream tokens
1918
+ * Combines claims from access token and ID token (if present)
1919
+ */
1920
+ async extractUpstreamClaims(upstreamTokens) {
1921
+ if (!this.claimsExtractor) {
1922
+ return null;
1923
+ }
1924
+ const allClaims = {};
1925
+ const accessClaims = await this.claimsExtractor.extract(
1926
+ upstreamTokens.accessToken,
1927
+ "access"
1928
+ );
1929
+ if (accessClaims) {
1930
+ Object.assign(allClaims, accessClaims);
1931
+ }
1932
+ if (upstreamTokens.idToken) {
1933
+ const idClaims = await this.claimsExtractor.extract(
1934
+ upstreamTokens.idToken,
1935
+ "id"
1936
+ );
1937
+ if (idClaims) {
1938
+ for (const [key, value] of Object.entries(idClaims)) {
1939
+ if (!(key in allClaims)) {
1940
+ allClaims[key] = value;
1941
+ }
1942
+ }
1943
+ }
1944
+ }
1945
+ return Object.keys(allClaims).length > 0 ? allClaims : null;
1946
+ }
1947
+ /**
1948
+ * POST to the upstream token endpoint with a bounded wait.
1949
+ *
1950
+ * Maps an abort of the configured timeout signal to a clean OAuth error
1951
+ * instead of letting the raw `TimeoutError`/`AbortError` propagate.
1952
+ */
1953
+ async fetchUpstream(bodyParams, headers) {
1954
+ let tokenResponse;
1955
+ try {
1956
+ tokenResponse = await fetch(this.config.upstreamTokenEndpoint, {
1957
+ body: new URLSearchParams(bodyParams),
1958
+ headers,
1959
+ method: "POST",
1960
+ signal: AbortSignal.timeout(
1961
+ _nullishCoalesce(this.config.upstreamRequestTimeoutMs, () => ( DEFAULT_UPSTREAM_REQUEST_TIMEOUT_MS))
1962
+ )
1963
+ });
1964
+ } catch (error) {
1965
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
1966
+ throw new OAuthProxyError("server_error", "Upstream request timed out");
1967
+ }
1968
+ throw error;
1969
+ }
1970
+ return tokenResponse;
1971
+ }
1972
+ /**
1973
+ * Generate authorization code for client
1974
+ */
1975
+ async generateAuthorizationCode(transaction, upstreamTokens) {
1976
+ const code = this.generateId();
1977
+ const clientCode = {
1978
+ clientId: transaction.clientId,
1979
+ code,
1980
+ codeChallenge: transaction.clientCodeChallenge,
1981
+ codeChallengeMethod: transaction.clientCodeChallengeMethod,
1982
+ createdAt: /* @__PURE__ */ new Date(),
1983
+ expiresAt: new Date(
1984
+ Date.now() + (this.config.authorizationCodeTtl || 300) * 1e3
1985
+ ),
1986
+ transactionId: transaction.id,
1987
+ upstreamTokens
1988
+ };
1989
+ await this.stateStore.saveClientCode(clientCode);
1990
+ return code;
1991
+ }
1992
+ /**
1993
+ * Generate secure random ID
1994
+ */
1995
+ generateId() {
1996
+ return _crypto.randomBytes.call(void 0, 32).toString("base64url");
1997
+ }
1998
+ /**
1999
+ * Generate signing key for consent cookies
2000
+ */
2001
+ generateSigningKey() {
2002
+ return _crypto.randomBytes.call(void 0, 32).toString("hex");
2003
+ }
2004
+ /**
2005
+ * Generate Basic auth header value for upstream token endpoint
2006
+ * Per RFC 6749 Section 2.3.1, credentials must be URL-encoded before base64 encoding
2007
+ */
2008
+ getBasicAuthHeader() {
2009
+ const encodedClientId = encodeURIComponent(this.config.upstreamClientId);
2010
+ const encodedClientSecret = encodeURIComponent(
2011
+ this.config.upstreamClientSecret
2012
+ );
2013
+ return `Basic ${Buffer.from(`${encodedClientId}:${encodedClientSecret}`).toString("base64")}`;
2014
+ }
2015
+ /**
2016
+ * Get provider name for display
2017
+ */
2018
+ getProviderName() {
2019
+ const url = new URL(this.config.upstreamAuthorizationEndpoint);
2020
+ return url.hostname;
2021
+ }
2022
+ /**
2023
+ * Issuer identifier of the upstream authorization server.
2024
+ *
2025
+ * Defaults to the origin of the configured authorization endpoint, which is
2026
+ * what RFC 8414 issuers look like in practice; override with
2027
+ * `upstreamIssuer` when the provider's issuer differs from its endpoint host
2028
+ * (e.g. a tenant-scoped path).
2029
+ */
2030
+ getUpstreamIssuer() {
2031
+ if (this.config.upstreamIssuer) {
2032
+ return this.config.upstreamIssuer;
2033
+ }
2034
+ return new URL(this.config.upstreamAuthorizationEndpoint).origin;
2035
+ }
2036
+ /**
2037
+ * Handle passthrough mode refresh - forward refresh token directly to upstream
2038
+ */
2039
+ async handlePassthroughRefresh(request2) {
2040
+ const useBasicAuth = this.config.upstreamTokenEndpointAuthMethod === "client_secret_basic";
2041
+ const bodyParams = {
2042
+ grant_type: "refresh_token",
2043
+ refresh_token: request2.refresh_token,
2044
+ ...request2.scope && { scope: request2.scope }
2045
+ };
2046
+ if (!useBasicAuth) {
2047
+ bodyParams.client_id = this.config.upstreamClientId;
2048
+ bodyParams.client_secret = this.config.upstreamClientSecret;
2049
+ }
2050
+ const headers = {
2051
+ "Content-Type": "application/x-www-form-urlencoded"
2052
+ };
2053
+ if (useBasicAuth) {
2054
+ headers["Authorization"] = this.getBasicAuthHeader();
2055
+ }
2056
+ const tokenResponse = await this.fetchUpstream(bodyParams, headers);
2057
+ if (!tokenResponse.ok) {
2058
+ let errorCode = "invalid_grant";
2059
+ let errorDescription;
2060
+ try {
2061
+ const error = await tokenResponse.json();
2062
+ errorCode = error.error || "invalid_grant";
2063
+ errorDescription = error.error_description;
2064
+ } catch (e6) {
2065
+ errorDescription = `Upstream returned HTTP ${tokenResponse.status} ${tokenResponse.statusText}`;
2066
+ }
2067
+ throw new OAuthProxyError(errorCode, errorDescription);
2068
+ }
2069
+ const tokens = await this.parseTokenResponse(tokenResponse);
2070
+ return {
2071
+ access_token: tokens.access_token,
2072
+ expires_in: tokens.expires_in || 3600,
2073
+ id_token: tokens.id_token,
2074
+ refresh_token: tokens.refresh_token,
2075
+ scope: tokens.scope,
2076
+ token_type: tokens.token_type || "Bearer"
2077
+ };
2078
+ }
2079
+ /**
2080
+ * Handle swap mode refresh - verify ViteMCP JWT and issue new tokens
2081
+ */
2082
+ async handleSwapModeRefresh(request2) {
2083
+ if (!this.jwtIssuer) {
2084
+ throw new Error("JWT issuer not initialized");
2085
+ }
2086
+ const verifyResult = await this.jwtIssuer.verify(request2.refresh_token);
2087
+ if (!verifyResult.valid) {
2088
+ throw new OAuthProxyError(
2089
+ "invalid_grant",
2090
+ "Invalid or expired refresh token"
2091
+ );
2092
+ }
2093
+ const jti = _optionalChain([verifyResult, 'access', _14 => _14.claims, 'optionalAccess', _15 => _15.jti]);
2094
+ if (!jti) {
2095
+ throw new OAuthProxyError("invalid_grant", "Refresh token missing JTI");
2096
+ }
2097
+ const mapping = await this.takeMapping(jti);
2098
+ if (!mapping) {
2099
+ throw new OAuthProxyError(
2100
+ "invalid_grant",
2101
+ "Refresh token already used or expired"
2102
+ );
2103
+ }
2104
+ try {
2105
+ const upstreamTokens = await this.tokenStorage.get(
2106
+ `upstream:${this.issuerNs}:${mapping.upstreamTokenKey}`
2107
+ );
2108
+ if (!upstreamTokens) {
2109
+ throw new OAuthProxyError(
2110
+ "invalid_grant",
2111
+ "Upstream tokens not found or expired"
2112
+ );
2113
+ }
2114
+ if (!upstreamTokens.refreshToken) {
2115
+ throw new OAuthProxyError(
2116
+ "invalid_grant",
2117
+ "No upstream refresh token available"
2118
+ );
2119
+ }
2120
+ const refreshedUpstreamTokens = await this.refreshUpstreamTokens(
2121
+ upstreamTokens.refreshToken,
2122
+ request2.scope
2123
+ );
2124
+ if (refreshedUpstreamTokens.scope.length === 0) {
2125
+ refreshedUpstreamTokens.scope = upstreamTokens.scope;
2126
+ }
2127
+ const refreshTokenTtl = _nullishCoalesce(_nullishCoalesce(refreshedUpstreamTokens.refreshExpiresIn, () => ( this.config.refreshTokenTtl)), () => ( DEFAULT_REFRESH_TOKEN_TTL));
2128
+ const accessTokenTtl = this.calculateAccessTokenTtl(
2129
+ refreshedUpstreamTokens
2130
+ );
2131
+ const upstreamStorageTtl = Math.max(accessTokenTtl, refreshTokenTtl, 1);
2132
+ await this.tokenStorage.save(
2133
+ `upstream:${this.issuerNs}:${mapping.upstreamTokenKey}`,
2134
+ refreshedUpstreamTokens,
2135
+ upstreamStorageTtl
2136
+ );
2137
+ return await this.issueSwappedTokensForRefresh(
2138
+ mapping.clientId,
2139
+ refreshedUpstreamTokens,
2140
+ mapping.upstreamTokenKey
2141
+ );
2142
+ } catch (error) {
2143
+ try {
2144
+ await this.restoreMapping(jti, mapping);
2145
+ } catch (restoreError) {
2146
+ console.error(
2147
+ `Failed to restore refresh token mapping ${jti}:`,
2148
+ restoreError
2149
+ );
2150
+ }
2151
+ throw error;
2152
+ }
2153
+ }
2154
+ /**
2155
+ * Issue swapped tokens (JWT pattern)
2156
+ * Issues short-lived ViteMCP JWTs and stores upstream tokens securely
2157
+ */
2158
+ async issueSwappedTokens(clientId, upstreamTokens) {
2159
+ if (!this.jwtIssuer) {
2160
+ throw new Error("JWT issuer not initialized");
2161
+ }
2162
+ const customClaims = await this.extractUpstreamClaims(upstreamTokens);
2163
+ let accessTokenTtl;
2164
+ if (upstreamTokens.expiresIn > 0) {
2165
+ accessTokenTtl = upstreamTokens.expiresIn;
2166
+ } else if (this.config.accessTokenTtl) {
2167
+ accessTokenTtl = this.config.accessTokenTtl;
2168
+ } else if (upstreamTokens.refreshToken) {
2169
+ accessTokenTtl = DEFAULT_ACCESS_TOKEN_TTL;
2170
+ } else {
2171
+ accessTokenTtl = DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH;
2172
+ }
2173
+ const refreshTokenTtl = upstreamTokens.refreshToken ? _nullishCoalesce(_nullishCoalesce(upstreamTokens.refreshExpiresIn, () => ( this.config.refreshTokenTtl)), () => ( DEFAULT_REFRESH_TOKEN_TTL)) : 0;
2174
+ const upstreamStorageTtl = Math.max(accessTokenTtl, refreshTokenTtl, 1);
2175
+ const upstreamTokenKey = this.generateId();
2176
+ await this.tokenStorage.save(
2177
+ `upstream:${this.issuerNs}:${upstreamTokenKey}`,
2178
+ upstreamTokens,
2179
+ upstreamStorageTtl
2180
+ );
2181
+ const accessToken = this.jwtIssuer.issueAccessToken(
2182
+ clientId,
2183
+ upstreamTokens.scope,
2184
+ customClaims || void 0,
2185
+ accessTokenTtl
2186
+ );
2187
+ const accessJti = await this.extractJti(accessToken);
2188
+ await this.tokenStorage.save(
2189
+ `mapping:${this.issuerNs}:${accessJti}`,
2190
+ {
2191
+ clientId,
2192
+ createdAt: /* @__PURE__ */ new Date(),
2193
+ expiresAt: new Date(Date.now() + accessTokenTtl * 1e3),
2194
+ jti: accessJti,
2195
+ scope: upstreamTokens.scope,
2196
+ upstreamTokenKey
2197
+ },
2198
+ accessTokenTtl
2199
+ );
2200
+ const response = {
2201
+ access_token: accessToken,
2202
+ expires_in: accessTokenTtl,
2203
+ scope: upstreamTokens.scope.join(" "),
2204
+ token_type: "Bearer"
2205
+ };
2206
+ if (upstreamTokens.refreshToken) {
2207
+ const refreshToken = this.jwtIssuer.issueRefreshToken(
2208
+ clientId,
2209
+ upstreamTokens.scope,
2210
+ customClaims || void 0,
2211
+ refreshTokenTtl
2212
+ );
2213
+ const refreshJti = await this.extractJti(refreshToken);
2214
+ await this.tokenStorage.save(
2215
+ `mapping:${this.issuerNs}:${refreshJti}`,
2216
+ {
2217
+ clientId,
2218
+ createdAt: /* @__PURE__ */ new Date(),
2219
+ expiresAt: new Date(Date.now() + refreshTokenTtl * 1e3),
2220
+ jti: refreshJti,
2221
+ scope: upstreamTokens.scope,
2222
+ upstreamTokenKey
2223
+ },
2224
+ refreshTokenTtl
2225
+ );
2226
+ response.refresh_token = refreshToken;
2227
+ }
2228
+ return response;
2229
+ }
2230
+ /**
2231
+ * Issue swapped tokens for refresh flow
2232
+ */
2233
+ async issueSwappedTokensForRefresh(clientId, upstreamTokens, upstreamTokenKey) {
2234
+ if (!this.jwtIssuer) {
2235
+ throw new Error("JWT issuer not initialized");
2236
+ }
2237
+ const customClaims = await this.extractUpstreamClaims(upstreamTokens);
2238
+ const accessTokenTtl = this.calculateAccessTokenTtl(upstreamTokens);
2239
+ const refreshTokenTtl = upstreamTokens.refreshToken ? _nullishCoalesce(_nullishCoalesce(upstreamTokens.refreshExpiresIn, () => ( this.config.refreshTokenTtl)), () => ( DEFAULT_REFRESH_TOKEN_TTL)) : 0;
2240
+ const accessToken = this.jwtIssuer.issueAccessToken(
2241
+ clientId,
2242
+ upstreamTokens.scope,
2243
+ customClaims || void 0,
2244
+ accessTokenTtl
2245
+ );
2246
+ const accessJti = await this.extractJti(accessToken);
2247
+ await this.tokenStorage.save(
2248
+ `mapping:${this.issuerNs}:${accessJti}`,
2249
+ {
2250
+ clientId,
2251
+ createdAt: /* @__PURE__ */ new Date(),
2252
+ expiresAt: new Date(Date.now() + accessTokenTtl * 1e3),
2253
+ jti: accessJti,
2254
+ scope: upstreamTokens.scope,
2255
+ upstreamTokenKey
2256
+ },
2257
+ accessTokenTtl
2258
+ );
2259
+ const response = {
2260
+ access_token: accessToken,
2261
+ expires_in: accessTokenTtl,
2262
+ scope: upstreamTokens.scope.join(" "),
2263
+ token_type: "Bearer"
2264
+ };
2265
+ if (upstreamTokens.refreshToken) {
2266
+ const refreshToken = this.jwtIssuer.issueRefreshToken(
2267
+ clientId,
2268
+ upstreamTokens.scope,
2269
+ customClaims || void 0,
2270
+ refreshTokenTtl
2271
+ );
2272
+ const refreshJti = await this.extractJti(refreshToken);
2273
+ await this.tokenStorage.save(
2274
+ `mapping:${this.issuerNs}:${refreshJti}`,
2275
+ {
2276
+ clientId,
2277
+ createdAt: /* @__PURE__ */ new Date(),
2278
+ expiresAt: new Date(Date.now() + refreshTokenTtl * 1e3),
2279
+ jti: refreshJti,
2280
+ scope: upstreamTokens.scope,
2281
+ upstreamTokenKey
2282
+ },
2283
+ refreshTokenTtl
2284
+ );
2285
+ response.refresh_token = refreshToken;
2286
+ }
2287
+ return response;
2288
+ }
2289
+ /**
2290
+ * Match URI against pattern (supports wildcards)
2291
+ */
2292
+ matchesPattern(uri, pattern) {
2293
+ const regex = new RegExp(
2294
+ "^" + pattern.replace(/\*/g, ".*").replace(/\?/g, ".") + "$"
2295
+ );
2296
+ return regex.test(uri);
2297
+ }
2298
+ /**
2299
+ * Parse token response that can be either JSON or URL-encoded
2300
+ * GitHub Apps return URL-encoded format, most providers return JSON
2301
+ */
2302
+ async parseTokenResponse(response) {
2303
+ const contentType = (response.headers.get("content-type") || "").toLowerCase();
2304
+ const tokenResponseSchema = _zod.z.object({
2305
+ access_token: _zod.z.string().min(1, "access_token cannot be empty"),
2306
+ expires_in: _zod.z.coerce.number().int().positive().optional(),
2307
+ id_token: _zod.z.string().optional(),
2308
+ refresh_expires_in: _zod.z.coerce.number().int().positive().optional(),
2309
+ refresh_token: _zod.z.string().optional(),
2310
+ scope: _zod.z.string().optional(),
2311
+ token_type: _zod.z.string().optional()
2312
+ });
2313
+ if (contentType.includes("application/x-www-form-urlencoded")) {
2314
+ const text = await response.text();
2315
+ const params = new URLSearchParams(text);
2316
+ const rawData = {
2317
+ access_token: params.get("access_token") || "",
2318
+ expires_in: params.get("expires_in") ? parseInt(params.get("expires_in")) : void 0,
2319
+ id_token: params.get("id_token") || void 0,
2320
+ refresh_expires_in: params.get("refresh_expires_in") ? parseInt(params.get("refresh_expires_in")) : void 0,
2321
+ refresh_token: params.get("refresh_token") || void 0,
2322
+ scope: params.get("scope") || void 0,
2323
+ token_type: params.get("token_type") || void 0
2324
+ };
2325
+ return tokenResponseSchema.parse(rawData);
2326
+ }
2327
+ const rawJson = await response.json();
2328
+ return tokenResponseSchema.parse(rawJson);
2329
+ }
2330
+ /**
2331
+ * Redirect to upstream OAuth provider
2332
+ */
2333
+ redirectToUpstream(transaction) {
2334
+ const authUrl = new URL(this.config.upstreamAuthorizationEndpoint);
2335
+ if (this.config.extraAuthorizationParams) {
2336
+ for (const [key, value] of Object.entries(
2337
+ this.config.extraAuthorizationParams
2338
+ )) {
2339
+ if (!RESERVED_AUTHORIZATION_PARAMS.has(key)) {
2340
+ authUrl.searchParams.set(key, value);
2341
+ }
2342
+ }
2343
+ }
2344
+ authUrl.searchParams.set("client_id", this.config.upstreamClientId);
2345
+ authUrl.searchParams.set(
2346
+ "redirect_uri",
2347
+ `${this.config.baseUrl}${this.config.redirectPath}`
2348
+ );
2349
+ authUrl.searchParams.set("response_type", "code");
2350
+ authUrl.searchParams.set("state", transaction.id);
2351
+ if (transaction.scope.length > 0) {
2352
+ authUrl.searchParams.set("scope", transaction.scope.join(" "));
2353
+ }
2354
+ if (!this.config.forwardPkce) {
2355
+ authUrl.searchParams.set(
2356
+ "code_challenge",
2357
+ transaction.proxyCodeChallenge
2358
+ );
2359
+ authUrl.searchParams.set("code_challenge_method", "S256");
2360
+ }
2361
+ return new Response(null, {
2362
+ headers: {
2363
+ Location: authUrl.toString()
2364
+ },
2365
+ status: 302
2366
+ });
2367
+ }
2368
+ /**
2369
+ * Refresh upstream tokens with provider
2370
+ */
2371
+ async refreshUpstreamTokens(upstreamRefreshToken, requestedScope) {
2372
+ const useBasicAuth = this.config.upstreamTokenEndpointAuthMethod === "client_secret_basic";
2373
+ const bodyParams = {
2374
+ grant_type: "refresh_token",
2375
+ refresh_token: upstreamRefreshToken,
2376
+ ...requestedScope && { scope: requestedScope }
2377
+ };
2378
+ if (!useBasicAuth) {
2379
+ bodyParams.client_id = this.config.upstreamClientId;
2380
+ bodyParams.client_secret = this.config.upstreamClientSecret;
2381
+ }
2382
+ const headers = {
2383
+ "Content-Type": "application/x-www-form-urlencoded"
2384
+ };
2385
+ if (useBasicAuth) {
2386
+ headers["Authorization"] = this.getBasicAuthHeader();
2387
+ }
2388
+ const tokenResponse = await this.fetchUpstream(bodyParams, headers);
2389
+ if (!tokenResponse.ok) {
2390
+ let errorCode = "invalid_grant";
2391
+ let errorDescription = "Upstream refresh failed";
2392
+ try {
2393
+ const error = await tokenResponse.json();
2394
+ errorCode = error.error || "invalid_grant";
2395
+ errorDescription = error.error_description || "Upstream refresh failed";
2396
+ } catch (e7) {
2397
+ errorDescription = `Upstream returned HTTP ${tokenResponse.status} ${tokenResponse.statusText}`;
2398
+ }
2399
+ throw new OAuthProxyError(errorCode, errorDescription);
2400
+ }
2401
+ const tokens = await this.parseTokenResponse(tokenResponse);
2402
+ return {
2403
+ accessToken: tokens.access_token,
2404
+ expiresIn: tokens.expires_in || 3600,
2405
+ idToken: tokens.id_token,
2406
+ issuedAt: /* @__PURE__ */ new Date(),
2407
+ refreshExpiresIn: tokens.refresh_expires_in,
2408
+ refreshToken: tokens.refresh_token || upstreamRefreshToken,
2409
+ scope: tokens.scope ? tokens.scope.split(" ") : [],
2410
+ tokenType: tokens.token_type || "Bearer"
2411
+ };
2412
+ }
2413
+ /**
2414
+ * Redirect URIs the given client is allowed to use.
2415
+ *
2416
+ * A URL-formatted client_id is resolved as a Client ID Metadata Document
2417
+ * (the preferred mechanism on this revision); anything else must have been
2418
+ * registered through DCR.
2419
+ */
2420
+ async resolveClientRedirectUris(clientId) {
2421
+ if (this.clientIdMetadata.enabled && isClientIdMetadataUrl(clientId)) {
2422
+ try {
2423
+ const metadata = await this.clientIdMetadata.resolve(clientId);
2424
+ return metadata.redirect_uris;
2425
+ } catch (error) {
2426
+ throw new OAuthProxyError(
2427
+ "invalid_client",
2428
+ error instanceof ClientIdMetadataError ? error.message : "Could not resolve client metadata"
2429
+ );
2430
+ }
2431
+ }
2432
+ const registeredClient = await this.stateStore.getRegisteredClientByClientId(clientId);
2433
+ if (!registeredClient) {
2434
+ throw new OAuthProxyError("invalid_client", "Unknown client_id");
2435
+ }
2436
+ return registeredClient.redirectUris;
2437
+ }
2438
+ /**
2439
+ * Put a claimed refresh-token mapping back after a rotation failed, keeping
2440
+ * whatever lifetime it had left.
2441
+ *
2442
+ * A mapping that is already expired, or that carries no usable expiry, is
2443
+ * dropped instead. Inventing a TTL here would extend the lifetime of a
2444
+ * credential in a security path, and every mapping this proxy writes records
2445
+ * `expiresAt`.
2446
+ */
2447
+ async restoreMapping(jti, mapping) {
2448
+ if (!mapping.expiresAt) {
2449
+ return;
2450
+ }
2451
+ const expiresAt = new Date(mapping.expiresAt).getTime();
2452
+ if (Number.isNaN(expiresAt)) {
2453
+ return;
2454
+ }
2455
+ const ttl = Math.ceil((expiresAt - Date.now()) / 1e3);
2456
+ if (ttl <= 0) {
2457
+ return;
2458
+ }
2459
+ await this.tokenStorage.save(
2460
+ `mapping:${this.issuerNs}:${jti}`,
2461
+ mapping,
2462
+ ttl
2463
+ );
2464
+ }
2465
+ /**
2466
+ * Start periodic cleanup of expired transactions and codes
2467
+ */
2468
+ startCleanup() {
2469
+ this.cleanupInterval = setInterval(() => {
2470
+ this.cleanup();
2471
+ }, 6e4);
2472
+ }
2473
+ /**
2474
+ * Atomically claim a token mapping, mirroring `OAuthProxyStateStore`: at most
2475
+ * one caller — across all processes sharing the storage — can receive a given
2476
+ * mapping, which is what makes single use enforceable. Falls back to a
2477
+ * non-atomic get + delete for storages that do not implement `take`.
2478
+ */
2479
+ async takeMapping(jti) {
2480
+ const key = `mapping:${this.issuerNs}:${jti}`;
2481
+ if (this.tokenStorage.take) {
2482
+ return await this.tokenStorage.take(key);
2483
+ }
2484
+ const stored = await this.tokenStorage.get(key);
2485
+ if (stored === null) {
2486
+ return null;
2487
+ }
2488
+ await this.tokenStorage.delete(key);
2489
+ return stored;
2490
+ }
2491
+ /**
2492
+ * Validate a redirect URI against the configured allow-list.
2493
+ *
2494
+ * Behaviour by configuration value:
2495
+ * - `undefined` (not set): allow localhost/127.0.0.1 only — safe default
2496
+ * that covers the common MCP use-case of dynamic loopback ports without
2497
+ * opening the proxy to arbitrary redirect URIs.
2498
+ * - `[]` (empty array): reject every URI — opt-in strict mode for deployments
2499
+ * that want full control and will configure patterns explicitly.
2500
+ * - `["pattern", ...]`: accept URIs matching any of the glob patterns.
2501
+ *
2502
+ * Prior versions defaulted to `["https://*", "http://localhost:*"]` which
2503
+ * matched any https URL, enabling CWE-601 open-redirect / authorization-code
2504
+ * theft. Do not loosen the default beyond loopback addresses.
2505
+ */
2506
+ validateRedirectUri(uri) {
2507
+ try {
2508
+ new URL(uri);
2509
+ } catch (e8) {
2510
+ return false;
2511
+ }
2512
+ const patterns = this.config.allowedRedirectUriPatterns;
2513
+ if (Array.isArray(patterns) && patterns.length === 0) {
2514
+ return false;
2515
+ }
2516
+ const effectivePatterns = _nullishCoalesce(patterns, () => ( [
2517
+ "http://localhost:*",
2518
+ "http://127.0.0.1:*"
2519
+ ]));
2520
+ return effectivePatterns.some(
2521
+ (pattern) => this.matchesPattern(uri, pattern)
2522
+ );
2523
+ }
2524
+ }, _class4);
2525
+ var isLoopbackRedirectUri = (uri) => {
2526
+ try {
2527
+ const url = new URL(uri);
2528
+ if (url.protocol === "http:" || url.protocol === "https:") {
2529
+ return ["::1", "127.0.0.1", "localhost"].includes(url.hostname);
2530
+ }
2531
+ return url.protocol !== "";
2532
+ } catch (e9) {
2533
+ return false;
2534
+ }
2535
+ };
2536
+ var OAuthProxyError = class extends Error {
2537
+ constructor(code, description, statusCode = 400) {
2538
+ super(code);
2539
+ this.code = code;
2540
+ this.description = description;
2541
+ this.statusCode = statusCode;
2542
+ this.name = "OAuthProxyError";
2543
+ }
2544
+ toJSON() {
2545
+ return {
2546
+ error: this.code,
2547
+ error_description: this.description
2548
+ };
2549
+ }
2550
+ toResponse() {
2551
+ return new Response(JSON.stringify(this.toJSON()), {
2552
+ headers: { "Content-Type": "application/json" },
2553
+ status: this.statusCode
2554
+ });
2555
+ }
2556
+ };
2557
+
2558
+ // src/auth/providers/AuthProvider.ts
2559
+ var AuthProvider = class {
2560
+
2561
+ /**
2562
+ * Get the proxy, creating it lazily if needed.
2563
+ */
2564
+ get proxy() {
2565
+ if (!this._proxy) {
2566
+ this._proxy = this.createProxy();
2567
+ }
2568
+ return this._proxy;
2569
+ }
2570
+
2571
+ constructor(config) {
2572
+ this.config = config;
2573
+ }
2574
+ /**
2575
+ * Authenticate function to be used by ViteMCP.
2576
+ * Extracts Bearer token, validates it, and returns session with upstream access token.
2577
+ */
2578
+ async authenticate(request2) {
2579
+ if (!request2) {
2580
+ return void 0;
2581
+ }
2582
+ const authHeader = request2.headers.get("authorization");
2583
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
2584
+ return void 0;
2585
+ }
2586
+ const token = authHeader.slice(7);
2587
+ const upstreamTokens = await this.proxy.loadUpstreamTokens(token);
2588
+ if (!upstreamTokens) {
2589
+ return void 0;
2590
+ }
2591
+ return this.createSession(upstreamTokens);
2592
+ }
2593
+ /**
2594
+ * Get the OAuth configuration object for ViteMCP ServerOptions.
2595
+ */
2596
+ getOAuthConfig() {
2597
+ return {
2598
+ authorizationServer: this.proxy.getAuthorizationServerMetadata(),
2599
+ enabled: true,
2600
+ protectedResource: {
2601
+ authorizationServers: [this.config.baseUrl],
2602
+ resource: this.config.baseUrl,
2603
+ scopesSupported: _nullishCoalesce(this.config.scopes, () => ( this.getDefaultScopes()))
2604
+ },
2605
+ proxy: this.proxy
2606
+ };
2607
+ }
2608
+ /**
2609
+ * Get the OAuthProxy instance (for advanced use cases).
2610
+ */
2611
+ getProxy() {
2612
+ return this.proxy;
2613
+ }
2614
+ /**
2615
+ * Create a session object from upstream tokens.
2616
+ * Override in subclasses to add provider-specific session data.
2617
+ */
2618
+ createSession(upstreamTokens) {
2619
+ return {
2620
+ accessToken: upstreamTokens.accessToken,
2621
+ expiresAt: upstreamTokens.expiresIn ? Math.floor(Date.now() / 1e3) + upstreamTokens.expiresIn : void 0,
2622
+ idToken: upstreamTokens.idToken,
2623
+ refreshToken: upstreamTokens.refreshToken,
2624
+ scopes: upstreamTokens.scope
2625
+ };
2626
+ }
2627
+ };
2628
+
2629
+ // src/auth/providers/AzureProvider.ts
2630
+ var AzureProvider = class extends AuthProvider {
2631
+
2632
+ constructor(config) {
2633
+ super(config);
2634
+ this.tenantId = _nullishCoalesce(config.tenantId, () => ( "common"));
2635
+ }
2636
+ createProxy() {
2637
+ return new OAuthProxy({
2638
+ // No fallback default: framework users must explicitly list the URIs
2639
+ // they trust. A previous default of ["http://localhost:*", "https://*"]
2640
+ // enabled CWE-601 open-redirect / code-theft via /oauth/authorize.
2641
+ allowedRedirectUriPatterns: this.config.allowedRedirectUriPatterns,
2642
+ baseUrl: this.config.baseUrl,
2643
+ consentRequired: _nullishCoalesce(this.config.consentRequired, () => ( true)),
2644
+ encryptionKey: this.config.encryptionKey,
2645
+ jwtSigningKey: this.config.jwtSigningKey,
2646
+ scopes: _nullishCoalesce(this.config.scopes, () => ( this.getDefaultScopes())),
2647
+ tokenStorage: this.config.tokenStorage,
2648
+ upstreamAuthorizationEndpoint: this.getAuthorizationEndpoint(),
2649
+ upstreamClientId: this.config.clientId,
2650
+ upstreamClientSecret: this.config.clientSecret,
2651
+ upstreamTokenEndpoint: this.getTokenEndpoint()
2652
+ });
2653
+ }
2654
+ getAuthorizationEndpoint() {
2655
+ return `https://login.microsoftonline.com/${this.tenantId}/oauth2/v2.0/authorize`;
2656
+ }
2657
+ getDefaultScopes() {
2658
+ return ["openid", "profile", "email"];
2659
+ }
2660
+ getTokenEndpoint() {
2661
+ return `https://login.microsoftonline.com/${this.tenantId}/oauth2/v2.0/token`;
2662
+ }
2663
+ };
2664
+
2665
+ // src/auth/providers/GitHubProvider.ts
2666
+ var GitHubProvider = class extends AuthProvider {
2667
+ constructor(config) {
2668
+ super(config);
2669
+ }
2670
+ createProxy() {
2671
+ return new OAuthProxy({
2672
+ // No fallback default: framework users must explicitly list the URIs
2673
+ // they trust. A previous default of ["http://localhost:*", "https://*"]
2674
+ // enabled CWE-601 open-redirect / code-theft via /oauth/authorize.
2675
+ allowedRedirectUriPatterns: this.config.allowedRedirectUriPatterns,
2676
+ baseUrl: this.config.baseUrl,
2677
+ consentRequired: _nullishCoalesce(this.config.consentRequired, () => ( true)),
2678
+ encryptionKey: this.config.encryptionKey,
2679
+ jwtSigningKey: this.config.jwtSigningKey,
2680
+ scopes: _nullishCoalesce(this.config.scopes, () => ( this.getDefaultScopes())),
2681
+ tokenStorage: this.config.tokenStorage,
2682
+ upstreamAuthorizationEndpoint: this.getAuthorizationEndpoint(),
2683
+ upstreamClientId: this.config.clientId,
2684
+ upstreamClientSecret: this.config.clientSecret,
2685
+ upstreamTokenEndpoint: this.getTokenEndpoint()
2686
+ });
2687
+ }
2688
+ getAuthorizationEndpoint() {
2689
+ return "https://github.com/login/oauth/authorize";
2690
+ }
2691
+ getDefaultScopes() {
2692
+ return ["read:user", "user:email"];
2693
+ }
2694
+ getTokenEndpoint() {
2695
+ return "https://github.com/login/oauth/access_token";
2696
+ }
2697
+ };
2698
+
2699
+ // src/auth/providers/GoogleProvider.ts
2700
+ var GoogleProvider = class extends AuthProvider {
2701
+ constructor(config) {
2702
+ super(config);
2703
+ }
2704
+ createProxy() {
2705
+ return new OAuthProxy({
2706
+ // No fallback default: framework users must explicitly list the URIs
2707
+ // they trust. A previous default of ["http://localhost:*", "https://*"]
2708
+ // enabled CWE-601 open-redirect / code-theft via /oauth/authorize.
2709
+ allowedRedirectUriPatterns: this.config.allowedRedirectUriPatterns,
2710
+ baseUrl: this.config.baseUrl,
2711
+ consentRequired: _nullishCoalesce(this.config.consentRequired, () => ( true)),
2712
+ encryptionKey: this.config.encryptionKey,
2713
+ jwtSigningKey: this.config.jwtSigningKey,
2714
+ scopes: _nullishCoalesce(this.config.scopes, () => ( this.getDefaultScopes())),
2715
+ tokenStorage: this.config.tokenStorage,
2716
+ upstreamAuthorizationEndpoint: this.getAuthorizationEndpoint(),
2717
+ upstreamClientId: this.config.clientId,
2718
+ upstreamClientSecret: this.config.clientSecret,
2719
+ upstreamTokenEndpoint: this.getTokenEndpoint()
2720
+ });
2721
+ }
2722
+ getAuthorizationEndpoint() {
2723
+ return "https://accounts.google.com/o/oauth2/v2/auth";
2724
+ }
2725
+ getDefaultScopes() {
2726
+ return ["openid", "profile", "email"];
2727
+ }
2728
+ getTokenEndpoint() {
2729
+ return "https://oauth2.googleapis.com/token";
2730
+ }
2731
+ };
2732
+
2733
+ // src/auth/providers/OAuthProvider.ts
2734
+ var OAuthProvider = class extends AuthProvider {
2735
+
2736
+ constructor(config) {
2737
+ super(config);
2738
+ this.genericConfig = config;
2739
+ }
2740
+ createProxy() {
2741
+ return new OAuthProxy({
2742
+ // No fallback default: framework users must explicitly list the URIs
2743
+ // they trust. A previous default of ["http://localhost:*", "https://*"]
2744
+ // enabled CWE-601 open-redirect / code-theft via /oauth/authorize.
2745
+ allowedRedirectUriPatterns: this.config.allowedRedirectUriPatterns,
2746
+ baseUrl: this.config.baseUrl,
2747
+ consentRequired: _nullishCoalesce(this.config.consentRequired, () => ( true)),
2748
+ encryptionKey: this.config.encryptionKey,
2749
+ jwtSigningKey: this.config.jwtSigningKey,
2750
+ scopes: _nullishCoalesce(this.config.scopes, () => ( this.getDefaultScopes())),
2751
+ tokenStorage: this.config.tokenStorage,
2752
+ upstreamAuthorizationEndpoint: this.getAuthorizationEndpoint(),
2753
+ upstreamClientId: this.config.clientId,
2754
+ upstreamClientSecret: this.config.clientSecret,
2755
+ upstreamTokenEndpoint: this.getTokenEndpoint(),
2756
+ upstreamTokenEndpointAuthMethod: _nullishCoalesce(this.genericConfig.tokenEndpointAuthMethod, () => ( "client_secret_basic"))
2757
+ });
2758
+ }
2759
+ getAuthorizationEndpoint() {
2760
+ return this.genericConfig.authorizationEndpoint;
2761
+ }
2762
+ getDefaultScopes() {
2763
+ return ["openid"];
2764
+ }
2765
+ getTokenEndpoint() {
2766
+ return this.genericConfig.tokenEndpoint;
2767
+ }
2768
+ };
2769
+
2770
+ // src/auth/utils/diskStore.ts
2771
+
2772
+
2773
+
2774
+
2775
+
2776
+
2777
+
2778
+
2779
+
2780
+ var _promises = require('fs/promises');
2781
+ var _path = require('path');
2782
+ var DiskStore = (_class5 = class {
2783
+ __init8() {this.cleanupInterval = null}
2784
+
2785
+
2786
+ constructor(options) {;_class5.prototype.__init8.call(this);
2787
+ this.directory = options.directory;
2788
+ this.fileExtension = options.fileExtension || ".json";
2789
+ void this.ensureDirectory();
2790
+ const cleanupIntervalMs = options.cleanupIntervalMs || 6e4;
2791
+ this.cleanupInterval = setInterval(() => {
2792
+ void this.cleanup();
2793
+ }, cleanupIntervalMs);
2794
+ }
2795
+ /**
2796
+ * Clean up expired entries
2797
+ */
2798
+ async cleanup() {
2799
+ try {
2800
+ await this.ensureDirectory();
2801
+ const files = await _promises.readdir.call(void 0, this.directory);
2802
+ const now = Date.now();
2803
+ for (const file of files) {
2804
+ if (!file.endsWith(this.fileExtension)) {
2805
+ continue;
2806
+ }
2807
+ try {
2808
+ const filePath = _path.join.call(void 0, this.directory, file);
2809
+ const content = await _promises.readFile.call(void 0, filePath, "utf-8");
2810
+ const entry = JSON.parse(content);
2811
+ if (entry.expiresAt < now) {
2812
+ await _promises.rm.call(void 0, filePath);
2813
+ }
2814
+ } catch (error) {
2815
+ console.warn(`Failed to read/parse file ${file}, deleting:`, error);
2816
+ try {
2817
+ await _promises.rm.call(void 0, _path.join.call(void 0, this.directory, file));
2818
+ } catch (e10) {
2819
+ }
2820
+ }
2821
+ }
2822
+ } catch (error) {
2823
+ console.error("Cleanup failed:", error);
2824
+ }
2825
+ }
2826
+ /**
2827
+ * Delete a value
2828
+ */
2829
+ async delete(key) {
2830
+ const filePath = this.getFilePath(key);
2831
+ try {
2832
+ await _promises.rm.call(void 0, filePath);
2833
+ } catch (error) {
2834
+ if (error.code !== "ENOENT") {
2835
+ console.error(`Failed to delete key ${key}:`, error);
2836
+ }
2837
+ }
2838
+ }
2839
+ /**
2840
+ * Destroy the storage and clear cleanup interval
2841
+ */
2842
+ destroy() {
2843
+ if (this.cleanupInterval) {
2844
+ clearInterval(this.cleanupInterval);
2845
+ this.cleanupInterval = null;
2846
+ }
2847
+ }
2848
+ /**
2849
+ * Retrieve a value
2850
+ */
2851
+ async get(key) {
2852
+ const filePath = this.getFilePath(key);
2853
+ try {
2854
+ const content = await _promises.readFile.call(void 0, filePath, "utf-8");
2855
+ const entry = JSON.parse(content);
2856
+ if (entry.expiresAt < Date.now()) {
2857
+ await _promises.rm.call(void 0, filePath);
2858
+ return null;
2859
+ }
2860
+ return entry.value;
2861
+ } catch (error) {
2862
+ if (error.code === "ENOENT") {
2863
+ return null;
2864
+ }
2865
+ console.error(`Failed to read key ${key}:`, error);
2866
+ return null;
2867
+ }
2868
+ }
2869
+ /**
2870
+ * Save a value with optional TTL
2871
+ */
2872
+ async save(key, value, ttl) {
2873
+ await this.ensureDirectory();
2874
+ const filePath = this.getFilePath(key);
2875
+ const expiresAt = ttl ? Date.now() + ttl * 1e3 : Number.MAX_SAFE_INTEGER;
2876
+ const entry = {
2877
+ expiresAt,
2878
+ value
2879
+ };
2880
+ try {
2881
+ await _promises.writeFile.call(void 0, filePath, JSON.stringify(entry, null, 2), "utf-8");
2882
+ } catch (error) {
2883
+ console.error(`Failed to save key ${key}:`, error);
2884
+ throw error;
2885
+ }
2886
+ }
2887
+ /**
2888
+ * Get the number of stored items
2889
+ */
2890
+ async size() {
2891
+ try {
2892
+ await this.ensureDirectory();
2893
+ const files = await _promises.readdir.call(void 0, this.directory);
2894
+ return files.filter((f) => f.endsWith(this.fileExtension)).length;
2895
+ } catch (e11) {
2896
+ return 0;
2897
+ }
2898
+ }
2899
+ /**
2900
+ * Atomically retrieve a value and delete it.
2901
+ *
2902
+ * rename() is atomic on POSIX filesystems, so when several processes race
2903
+ * for the same key exactly one rename succeeds and the losers see ENOENT.
2904
+ * That is what makes single-use authorization codes safe when more than one
2905
+ * process shares the directory.
2906
+ */
2907
+ async take(key) {
2908
+ const filePath = this.getFilePath(key);
2909
+ const claimPath = `${filePath}.${_crypto.randomUUID.call(void 0, )}.claim${this.fileExtension}`;
2910
+ try {
2911
+ await _promises.rename.call(void 0, filePath, claimPath);
2912
+ } catch (error) {
2913
+ if (error.code !== "ENOENT") {
2914
+ console.error(`Failed to take key ${key}:`, error);
2915
+ }
2916
+ return null;
2917
+ }
2918
+ try {
2919
+ const content = await _promises.readFile.call(void 0, claimPath, "utf-8");
2920
+ const entry = JSON.parse(content);
2921
+ return entry.expiresAt < Date.now() ? null : entry.value;
2922
+ } catch (error) {
2923
+ console.error(`Failed to read key ${key}:`, error);
2924
+ return null;
2925
+ } finally {
2926
+ await _promises.rm.call(void 0, claimPath, { force: true });
2927
+ }
2928
+ }
2929
+ /**
2930
+ * Ensure storage directory exists
2931
+ */
2932
+ async ensureDirectory() {
2933
+ try {
2934
+ const stats = await _promises.stat.call(void 0, this.directory);
2935
+ if (!stats.isDirectory()) {
2936
+ throw new Error(`Path ${this.directory} exists but is not a directory`);
2937
+ }
2938
+ } catch (error) {
2939
+ if (error.code === "ENOENT") {
2940
+ await _promises.mkdir.call(void 0, this.directory, { recursive: true });
2941
+ } else {
2942
+ throw error;
2943
+ }
2944
+ }
2945
+ }
2946
+ /**
2947
+ * Get file path for a key
2948
+ */
2949
+ getFilePath(key) {
2950
+ const sanitizedKey = key.replace(/[^a-zA-Z0-9_-]/g, "_");
2951
+ return _path.join.call(void 0, this.directory, `${sanitizedKey}${this.fileExtension}`);
2952
+ }
2953
+ }, _class5);
2954
+
2955
+ // src/auth/utils/jwks.ts
2956
+ var JWKSVerifier = (_class6 = class {
2957
+
2958
+
2959
+ __init9() {this.joseLoaded = false}
2960
+
2961
+ constructor(config) {;_class6.prototype.__init9.call(this);
2962
+ this.config = {
2963
+ cacheDuration: 36e5,
2964
+ // 1 hour
2965
+ cooldownDuration: 3e4,
2966
+ // 30 seconds
2967
+ ...config,
2968
+ audience: config.audience || "",
2969
+ issuer: config.issuer || ""
2970
+ };
2971
+ }
2972
+ /**
2973
+ * Get the JWKS URI being used
2974
+ */
2975
+ getJwksUri() {
2976
+ return this.config.jwksUri;
2977
+ }
2978
+ /**
2979
+ * Refresh the JWKS cache
2980
+ * Useful if you need to force a key refresh
2981
+ */
2982
+ async refreshKeys() {
2983
+ await this.loadJose();
2984
+ this.jwksCache = this.jose.createRemoteJWKSet(
2985
+ new URL(this.config.jwksUri),
2986
+ {
2987
+ cacheMaxAge: this.config.cacheDuration,
2988
+ cooldownDuration: this.config.cooldownDuration
2989
+ }
2990
+ );
2991
+ }
2992
+ /**
2993
+ * Verify a JWT token using JWKS
2994
+ *
2995
+ * @param token - The JWT token to verify
2996
+ * @returns Verification result with claims if valid
2997
+ *
2998
+ * @example
2999
+ * ```typescript
3000
+ * const result = await verifier.verify(token);
3001
+ * if (result.valid) {
3002
+ * console.log('User:', result.claims?.client_id);
3003
+ * } else {
3004
+ * console.error('Invalid token:', result.error);
3005
+ * }
3006
+ * ```
3007
+ */
3008
+ async verify(token) {
3009
+ try {
3010
+ await this.loadJose();
3011
+ const verifyOptions = {};
3012
+ if (this.config.audience) {
3013
+ verifyOptions.audience = this.config.audience;
3014
+ }
3015
+ if (this.config.issuer) {
3016
+ verifyOptions.issuer = this.config.issuer;
3017
+ }
3018
+ const { payload } = await this.jose.jwtVerify(
3019
+ token,
3020
+ this.jwksCache,
3021
+ verifyOptions
3022
+ );
3023
+ const claims = {
3024
+ ...payload,
3025
+ // Include all other claims
3026
+ aud: payload.aud,
3027
+ client_id: payload.client_id || payload.sub,
3028
+ exp: payload.exp,
3029
+ iat: payload.iat,
3030
+ iss: payload.iss,
3031
+ jti: payload.jti || "",
3032
+ scope: this.parseScope(payload.scope)
3033
+ };
3034
+ return {
3035
+ claims,
3036
+ valid: true
3037
+ };
3038
+ } catch (error) {
3039
+ return {
3040
+ error: error.message || "Token verification failed",
3041
+ valid: false
3042
+ };
3043
+ }
3044
+ }
3045
+ /**
3046
+ * Lazy load the jose library
3047
+ * Only loads when verification is first attempted
3048
+ */
3049
+ async loadJose() {
3050
+ if (this.joseLoaded) {
3051
+ return;
3052
+ }
3053
+ try {
3054
+ this.jose = await Promise.resolve().then(() => _interopRequireWildcard(require("jose")));
3055
+ this.joseLoaded = true;
3056
+ this.jwksCache = this.jose.createRemoteJWKSet(
3057
+ new URL(this.config.jwksUri),
3058
+ {
3059
+ cacheMaxAge: this.config.cacheDuration,
3060
+ cooldownDuration: this.config.cooldownDuration
3061
+ }
3062
+ );
3063
+ } catch (error) {
3064
+ throw new Error(
3065
+ `JWKS verification requires the 'jose' package.
3066
+ Install it with: npm install jose
3067
+
3068
+ If you don't need JWKS support, use HS256 signing instead (default).
3069
+
3070
+ Original error: ${error.message}`
3071
+ );
3072
+ }
3073
+ }
3074
+ /**
3075
+ * Parse scope from token payload
3076
+ * Handles both string (space-separated) and array formats
3077
+ */
3078
+ parseScope(scope) {
3079
+ if (!scope) {
3080
+ return [];
3081
+ }
3082
+ if (typeof scope === "string") {
3083
+ return scope.split(" ").filter(Boolean);
3084
+ }
3085
+ if (Array.isArray(scope)) {
3086
+ return scope;
3087
+ }
3088
+ return [];
3089
+ }
3090
+ }, _class6);
3091
+
3092
+
3093
+
3094
+
3095
+
3096
+
3097
+
3098
+
3099
+
3100
+
3101
+
3102
+
3103
+
3104
+
3105
+
3106
+
3107
+
3108
+
3109
+
3110
+
3111
+
3112
+
3113
+
3114
+
3115
+
3116
+
3117
+
3118
+ exports.getAuthSession = getAuthSession; exports.requireAll = requireAll; exports.requireAny = requireAny; exports.requireAuth = requireAuth; exports.requireRole = requireRole; exports.requireScopes = requireScopes; exports.DEFAULT_ACCESS_TOKEN_TTL = DEFAULT_ACCESS_TOKEN_TTL; exports.DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH = DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH; exports.DEFAULT_REFRESH_TOKEN_TTL = DEFAULT_REFRESH_TOKEN_TTL; exports.DEFAULT_AUTHORIZATION_CODE_TTL = DEFAULT_AUTHORIZATION_CODE_TTL; exports.DEFAULT_TRANSACTION_TTL = DEFAULT_TRANSACTION_TTL; exports.ConsentManager = ConsentManager; exports.JWTIssuer = JWTIssuer; exports.PKCEUtils = PKCEUtils; exports.EncryptedTokenStorage = EncryptedTokenStorage; exports.MemoryTokenStorage = MemoryTokenStorage; exports.OAuthProxy = OAuthProxy; exports.OAuthProxyError = OAuthProxyError; exports.AuthProvider = AuthProvider; exports.AzureProvider = AzureProvider; exports.GitHubProvider = GitHubProvider; exports.GoogleProvider = GoogleProvider; exports.OAuthProvider = OAuthProvider; exports.DiskStore = DiskStore; exports.JWKSVerifier = JWKSVerifier;
3119
+ //# sourceMappingURL=chunk-57MXTIW7.cjs.map