@valbuild/next 0.116.0 → 0.117.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.
@@ -9,6 +9,8 @@ var objectSpread2 = require('../../dist/objectSpread2-13f847a9.cjs.prod.js');
9
9
  var core = require('@valbuild/core');
10
10
  var server = require('@valbuild/server');
11
11
  var server$1 = require('next/server');
12
+ var _typeof = require('../../dist/typeof-16428c61.cjs.prod.js');
13
+ var node_crypto = require('node:crypto');
12
14
  require('../../dist/unsupportedIterableToArray-0d2087a2.cjs.prod.js');
13
15
  require('../../dist/defineProperty-8951f469.cjs.prod.js');
14
16
 
@@ -120,6 +122,578 @@ function initValServer(valModules, config, nextConfig) {
120
122
  };
121
123
  }
122
124
 
125
+ /**
126
+ * Verifying an OAuth access token, which is the whole of what makes this app a
127
+ * resource server rather than a relay.
128
+ *
129
+ * The token is issued by Val's authorization server and presented by an MCP
130
+ * client. This app holds no signing key for it and cannot mint one — it fetches
131
+ * the issuer's *public* keys and checks a signature. That asymmetry is the
132
+ * point: a verified `sub` is a fact about the token rather than a claim by
133
+ * whoever sent it, which is what lets the tools attribute a patch to that
134
+ * profile at all.
135
+ *
136
+ * ## Why this is not `jose`
137
+ *
138
+ * `jose` was the first choice and was rejected on a fact rather than a
139
+ * preference: version 6 is ESM-only (`"type": "module"`, no CJS export). This
140
+ * package is built by preconstruct and `require`d by Next.js server code, so an
141
+ * ESM-only dependency here is a runtime failure in consumers' apps, not a build
142
+ * inconvenience. Adding it would also put a dependency in every install of
143
+ * `@valbuild/next` for one function.
144
+ *
145
+ * The actual cryptography is still not hand-rolled — `node:crypto` does the
146
+ * ECDSA and the JWK import. What is written here is the JWS envelope and the
147
+ * claim checks, and the rules that keep that safe are worth stating because
148
+ * this repository has already shipped the counterexample (`decodeJwt`: `exp`
149
+ * never checked, a non-constant-time compare, verification skippable):
150
+ *
151
+ * - **`alg` is pinned**, not read from the token. The header is only consulted
152
+ * for `kid`. A verifier that honours the token's own `alg` can be handed
153
+ * `HS256` and will treat the *published* public key as a shared secret.
154
+ * - **Nothing is read from the payload before the signature verifies.** Claims
155
+ * from an unverified token are attacker input.
156
+ * - **Keys come only from the configured issuer's JWKS**, never from the token.
157
+ * - **ECDSA JWS signatures are raw `r||s`** (RFC 7518), not DER, which is what
158
+ * `dsaEncoding: "ieee-p1363"` below is for. Omit it and every valid signature
159
+ * is rejected — or worse, a future change makes it accept the wrong thing.
160
+ */
161
+
162
+ var DEFAULT_CLOCK_TOLERANCE_SECONDS = 60;
163
+ /** How long a fetched key set is reused before it is fetched again. */
164
+ var JWKS_TTL_MS = 5 * 60 * 1000;
165
+ /**
166
+ * How long to wait before re-fetching after a failure.
167
+ *
168
+ * Shorter than the success TTL so a key rotation recovers quickly, but not zero:
169
+ * an unreachable issuer must not turn every tool call into another request to
170
+ * it.
171
+ */
172
+ var JWKS_ERROR_TTL_MS = 30 * 1000;
173
+ /**
174
+ * One cache per issuer, and it has to outlive the request or it is not a cache:
175
+ * a fetch per tool call would put a network round trip in front of every read.
176
+ */
177
+ var jwksCache = new Map();
178
+ /** Concurrent misses share one fetch rather than starting several. */
179
+ var inFlight = new Map();
180
+ function jwksUrl(issuer) {
181
+ // Not discovered from the issuer's metadata document, deliberately:
182
+ // discovery would mean one more request on the hot path and one more thing
183
+ // that can be pointed elsewhere. The location is fixed by convention and by
184
+ // Val's own authorization server.
185
+ return new URL("/.well-known/jwks.json", issuer).toString();
186
+ }
187
+ function loadJwks(_x, _x2) {
188
+ return _loadJwks.apply(this, arguments);
189
+ }
190
+ function _loadJwks() {
191
+ _loadJwks = version._asyncToGenerator(/*#__PURE__*/version._regenerator().m(function _callee2(config, nowMs) {
192
+ var _config$fetchImpl;
193
+ var url, cached, age, ttl, existing, fetchImpl, pending, entry;
194
+ return version._regenerator().w(function (_context2) {
195
+ while (1) switch (_context2.p = _context2.n) {
196
+ case 0:
197
+ url = jwksUrl(config.issuer);
198
+ cached = jwksCache.get(url);
199
+ if (!cached) {
200
+ _context2.n = 1;
201
+ break;
202
+ }
203
+ age = cached.status === "keys" ? nowMs - cached.fetchedAtMs : nowMs - cached.failedAtMs;
204
+ ttl = cached.status === "keys" ? JWKS_TTL_MS : JWKS_ERROR_TTL_MS;
205
+ if (!(age < ttl)) {
206
+ _context2.n = 1;
207
+ break;
208
+ }
209
+ return _context2.a(2, cached);
210
+ case 1:
211
+ existing = inFlight.get(url);
212
+ if (!existing) {
213
+ _context2.n = 2;
214
+ break;
215
+ }
216
+ return _context2.a(2, existing);
217
+ case 2:
218
+ fetchImpl = (_config$fetchImpl = config.fetchImpl) !== null && _config$fetchImpl !== void 0 ? _config$fetchImpl : fetch;
219
+ pending = version._asyncToGenerator(/*#__PURE__*/version._regenerator().m(function _callee() {
220
+ var res, body, keys;
221
+ return version._regenerator().w(function (_context) {
222
+ while (1) switch (_context.p = _context.n) {
223
+ case 0:
224
+ _context.p = 0;
225
+ _context.n = 1;
226
+ return fetchImpl(url, {
227
+ headers: {
228
+ accept: "application/json"
229
+ }
230
+ });
231
+ case 1:
232
+ res = _context.v;
233
+ if (res.ok) {
234
+ _context.n = 2;
235
+ break;
236
+ }
237
+ return _context.a(2, {
238
+ status: "error",
239
+ failedAtMs: nowMs
240
+ });
241
+ case 2:
242
+ _context.n = 3;
243
+ return res.json();
244
+ case 3:
245
+ body = _context.v;
246
+ keys = readKeys(body);
247
+ if (!(keys === null)) {
248
+ _context.n = 4;
249
+ break;
250
+ }
251
+ return _context.a(2, {
252
+ status: "error",
253
+ failedAtMs: nowMs
254
+ });
255
+ case 4:
256
+ return _context.a(2, {
257
+ status: "keys",
258
+ keys: keys,
259
+ fetchedAtMs: nowMs
260
+ });
261
+ case 5:
262
+ _context.p = 5;
263
+ _context.v;
264
+ return _context.a(2, {
265
+ status: "error",
266
+ failedAtMs: nowMs
267
+ });
268
+ }
269
+ }, _callee, null, [[0, 5]]);
270
+ }))();
271
+ inFlight.set(url, pending);
272
+ _context2.p = 3;
273
+ _context2.n = 4;
274
+ return pending;
275
+ case 4:
276
+ entry = _context2.v;
277
+ jwksCache.set(url, entry);
278
+ return _context2.a(2, entry);
279
+ case 5:
280
+ _context2.p = 5;
281
+ inFlight["delete"](url);
282
+ return _context2.f(5);
283
+ case 6:
284
+ return _context2.a(2);
285
+ }
286
+ }, _callee2, null, [[3,, 5, 6]]);
287
+ }));
288
+ return _loadJwks.apply(this, arguments);
289
+ }
290
+ function readKeys(body) {
291
+ if (_typeof._typeof(body) !== "object" || body === null || !("keys" in body)) {
292
+ return null;
293
+ }
294
+ // `in` narrows the property into the type, so no assertion is needed to read
295
+ // it — and the `Array.isArray` below is what actually establishes the shape.
296
+ var keys = body.keys;
297
+ if (!Array.isArray(keys)) {
298
+ return null;
299
+ }
300
+ return keys.filter(function (key) {
301
+ return _typeof._typeof(key) === "object" && key !== null;
302
+ });
303
+ }
304
+
305
+ /**
306
+ * Read `Authorization: Bearer …`.
307
+ *
308
+ * Exported because the refusal needs to know whether a token was presented at
309
+ * all: RFC 6750 distinguishes "no credential" — a bare `401`, which is an
310
+ * invitation to authenticate — from "a bad credential", and a client that gets
311
+ * the second when it deserved the first will not start the authorization flow.
312
+ */
313
+ function readBearerToken(request) {
314
+ var _match$;
315
+ var header = request.headers.get("authorization");
316
+ if (!header) {
317
+ return null;
318
+ }
319
+ var match = /^Bearer\s+(.+)$/i.exec(header.trim());
320
+ var token = match === null || match === void 0 || (_match$ = match[1]) === null || _match$ === void 0 ? void 0 : _match$.trim();
321
+ return token ? token : null;
322
+ }
323
+ function verifyValAccessToken(_x3, _x4) {
324
+ return _verifyValAccessToken.apply(this, arguments);
325
+ }
326
+ function _verifyValAccessToken() {
327
+ _verifyValAccessToken = version._asyncToGenerator(/*#__PURE__*/version._regenerator().m(function _callee3(request, config) {
328
+ var _config$clockToleranc;
329
+ var token, parts, _parts, encodedHeader, encodedPayload, encodedSignature, header, kid, nowMs, jwks, candidates, signature, signedData, verified, payload, tolerance, nowSeconds, subject, scopes;
330
+ return version._regenerator().w(function (_context3) {
331
+ while (1) switch (_context3.n) {
332
+ case 0:
333
+ token = readBearerToken(request);
334
+ if (!(token === null)) {
335
+ _context3.n = 1;
336
+ break;
337
+ }
338
+ return _context3.a(2, {
339
+ status: "refused",
340
+ error: "invalid_request",
341
+ description: "This Val MCP endpoint needs an access token. Authorize with the Val authorization server and present it as `Authorization: Bearer`."
342
+ });
343
+ case 1:
344
+ parts = token.split(".");
345
+ if (!(parts.length !== 3)) {
346
+ _context3.n = 2;
347
+ break;
348
+ }
349
+ return _context3.a(2, invalidToken("The access token is not a JWS."));
350
+ case 2:
351
+ _parts = slicedToArray._slicedToArray(parts, 3), encodedHeader = _parts[0], encodedPayload = _parts[1], encodedSignature = _parts[2];
352
+ header = decodeJsonSegment(encodedHeader);
353
+ if (!(header === null)) {
354
+ _context3.n = 3;
355
+ break;
356
+ }
357
+ return _context3.a(2, invalidToken("The access token's header could not be read."));
358
+ case 3:
359
+ if (!(header.alg !== "ES256")) {
360
+ _context3.n = 4;
361
+ break;
362
+ }
363
+ return _context3.a(2, invalidToken("The access token is not signed with ES256, which is the only algorithm this server accepts."));
364
+ case 4:
365
+ kid = typeof header.kid === "string" ? header.kid : null;
366
+ nowMs = Date.now();
367
+ _context3.n = 5;
368
+ return loadJwks(config, nowMs);
369
+ case 5:
370
+ jwks = _context3.v;
371
+ if (!(jwks.status === "error")) {
372
+ _context3.n = 6;
373
+ break;
374
+ }
375
+ return _context3.a(2, invalidToken("The access token could not be verified because the Val authorization server's keys could not be fetched. This may be temporary."));
376
+ case 6:
377
+ candidates = jwks.keys.filter(function (key) {
378
+ return isVerifyingP256Key(key, kid);
379
+ });
380
+ if (!(candidates.length === 0)) {
381
+ _context3.n = 7;
382
+ break;
383
+ }
384
+ return _context3.a(2, invalidToken("The access token was signed with a key the Val authorization server does not publish."));
385
+ case 7:
386
+ signature = decodeBase64Url(encodedSignature);
387
+ if (!(signature === null)) {
388
+ _context3.n = 8;
389
+ break;
390
+ }
391
+ return _context3.a(2, invalidToken("The access token's signature could not be read."));
392
+ case 8:
393
+ signedData = Buffer.from("".concat(encodedHeader, ".").concat(encodedPayload), "ascii"); // Every published key is tried when the token names no `kid`, so a rotation
394
+ // that has not yet propagated to clients still verifies. With a `kid` the
395
+ // filter above leaves one.
396
+ verified = candidates.some(function (key) {
397
+ return verifyWithJwk(key, signedData, signature);
398
+ });
399
+ if (verified) {
400
+ _context3.n = 9;
401
+ break;
402
+ }
403
+ return _context3.a(2, invalidToken("The access token's signature could not be verified."));
404
+ case 9:
405
+ // Only now: everything below reads the payload, and before this line it was
406
+ // attacker input.
407
+ payload = decodeJsonSegment(encodedPayload);
408
+ if (!(payload === null)) {
409
+ _context3.n = 10;
410
+ break;
411
+ }
412
+ return _context3.a(2, invalidToken("The access token's payload could not be read."));
413
+ case 10:
414
+ tolerance = (_config$clockToleranc = config.clockToleranceSeconds) !== null && _config$clockToleranc !== void 0 ? _config$clockToleranc : DEFAULT_CLOCK_TOLERANCE_SECONDS;
415
+ nowSeconds = Math.floor(nowMs / 1000);
416
+ if (!(typeof payload.exp !== "number")) {
417
+ _context3.n = 11;
418
+ break;
419
+ }
420
+ return _context3.a(2, invalidToken("The access token has no expiry."));
421
+ case 11:
422
+ if (!(payload.exp + tolerance <= nowSeconds)) {
423
+ _context3.n = 12;
424
+ break;
425
+ }
426
+ return _context3.a(2, invalidToken("The access token has expired. Refresh it and try again."));
427
+ case 12:
428
+ if (!(typeof payload.nbf === "number" && payload.nbf - tolerance > nowSeconds)) {
429
+ _context3.n = 13;
430
+ break;
431
+ }
432
+ return _context3.a(2, invalidToken("The access token is not valid yet."));
433
+ case 13:
434
+ if (!(payload.iss !== config.issuer)) {
435
+ _context3.n = 14;
436
+ break;
437
+ }
438
+ return _context3.a(2, invalidToken("The access token was not issued by this server's authorization server (iss claim)."));
439
+ case 14:
440
+ if (audienceMatches(payload.aud, config.resource)) {
441
+ _context3.n = 15;
442
+ break;
443
+ }
444
+ return _context3.a(2, invalidToken("The access token is not valid for this server (aud claim)."));
445
+ case 15:
446
+ subject = payload.sub;
447
+ if (!(typeof subject !== "string" || subject.length === 0)) {
448
+ _context3.n = 16;
449
+ break;
450
+ }
451
+ return _context3.a(2, invalidToken("The access token has no subject."));
452
+ case 16:
453
+ scopes = readScopes(payload.scope);
454
+ if (scopes.includes(server.VAL_SCOPE_READ)) {
455
+ _context3.n = 17;
456
+ break;
457
+ }
458
+ return _context3.a(2, {
459
+ status: "refused",
460
+ error: "insufficient_scope",
461
+ description: "The access token does not have the ".concat(server.VAL_SCOPE_READ, " scope, so it cannot read any content.")
462
+ });
463
+ case 17:
464
+ return _context3.a(2, {
465
+ status: "ok",
466
+ auth: {
467
+ type: "verified-profile",
468
+ profileId: server.authorIdFromVerifiedSubject(subject),
469
+ scopes: scopes
470
+ }
471
+ });
472
+ }
473
+ }, _callee3);
474
+ }));
475
+ return _verifyValAccessToken.apply(this, arguments);
476
+ }
477
+ function invalidToken(description) {
478
+ // Described by class, never by echoing the token or a raw error: a
479
+ // verification failure message is a place credentials leak into logs.
480
+ return {
481
+ status: "refused",
482
+ error: "invalid_token",
483
+ description: description
484
+ };
485
+ }
486
+
487
+ /**
488
+ * `aud` is a string or an array of strings (RFC 7519 section 4.1.3).
489
+ *
490
+ * A match on any member is a match, which is the spec's own rule — a token may
491
+ * legitimately be addressed to several resources.
492
+ */
493
+ function audienceMatches(claim, resource) {
494
+ if (typeof claim === "string") {
495
+ return claim === resource;
496
+ }
497
+ if (Array.isArray(claim)) {
498
+ return claim.some(function (entry) {
499
+ return entry === resource;
500
+ });
501
+ }
502
+ return false;
503
+ }
504
+
505
+ /**
506
+ * `scope` is a space-delimited string (RFC 6749 section 3.3).
507
+ *
508
+ * Anything else is read as no scopes rather than coerced. A token whose scope
509
+ * claim is the wrong shape is a token we do not understand, and understanding
510
+ * it generously is how a write gets authorized by an array someone sent.
511
+ */
512
+ function readScopes(claim) {
513
+ if (typeof claim !== "string") {
514
+ return [];
515
+ }
516
+ return claim.split(" ").filter(function (scope) {
517
+ return scope.length > 0;
518
+ });
519
+ }
520
+ function isVerifyingP256Key(key, kid) {
521
+ if (key.kty !== "EC" || key.crv !== "P-256") {
522
+ return false;
523
+ }
524
+ if (typeof key.x !== "string" || typeof key.y !== "string") {
525
+ return false;
526
+ }
527
+ // A key published for encryption is not a key to verify signatures with, and
528
+ // an `alg` that disagrees with what we verify is a key meant for something
529
+ // else.
530
+ if (key.use !== undefined && key.use !== "sig") {
531
+ return false;
532
+ }
533
+ if (key.alg !== undefined && key.alg !== "ES256") {
534
+ return false;
535
+ }
536
+ if (kid !== null && typeof key.kid === "string" && key.kid !== kid) {
537
+ return false;
538
+ }
539
+ return true;
540
+ }
541
+ function verifyWithJwk(key, signedData, signature) {
542
+ try {
543
+ var publicKey = node_crypto.createPublicKey({
544
+ key: {
545
+ kty: "EC",
546
+ crv: "P-256",
547
+ x: String(key.x),
548
+ y: String(key.y)
549
+ },
550
+ format: "jwk"
551
+ });
552
+ return node_crypto.verify("sha256", signedData,
553
+ // `ieee-p1363` because a JWS ECDSA signature is the raw `r||s` pair, while
554
+ // node defaults to DER for EC keys. Getting this wrong rejects every
555
+ // valid signature.
556
+ {
557
+ key: publicKey,
558
+ dsaEncoding: "ieee-p1363"
559
+ }, signature);
560
+ } catch (_unused) {
561
+ // A malformed key in an otherwise good key set should not take down
562
+ // verification against the other keys.
563
+ return false;
564
+ }
565
+ }
566
+ function decodeBase64Url(segment) {
567
+ if (segment === undefined || !/^[A-Za-z0-9_-]*$/.test(segment)) {
568
+ return null;
569
+ }
570
+ try {
571
+ return Buffer.from(segment, "base64url");
572
+ } catch (_unused2) {
573
+ return null;
574
+ }
575
+ }
576
+ function decodeJsonSegment(segment) {
577
+ var decoded = decodeBase64Url(segment);
578
+ if (decoded === null) {
579
+ return null;
580
+ }
581
+ try {
582
+ var parsed = JSON.parse(decoded.toString("utf8"));
583
+ if (_typeof._typeof(parsed) !== "object" || parsed === null || Array.isArray(parsed)) {
584
+ return null;
585
+ }
586
+ return objectSpread2._objectSpread2({}, parsed);
587
+ } catch (_unused3) {
588
+ return null;
589
+ }
590
+ }
591
+
592
+ /**
593
+ * The one document an MCP client needs before it can authorize: RFC 9728
594
+ * Protected Resource Metadata, served by the *resource* server.
595
+ *
596
+ * This is how a client discovers where to authorize. It asks the resource — this
597
+ * app — and the resource names its authorization server. Which is why this
598
+ * belongs here and the RFC 8414 *authorization server* metadata does not: that
599
+ * document lives at the issuer, describes the issuer's own endpoints, and is
600
+ * served by the issuer. An app serving a copy would be asserting the issuer's
601
+ * configuration on its behalf, and would be wrong the moment the issuer changed
602
+ * anything.
603
+ *
604
+ * The flow, so the split reads as a whole:
605
+ *
606
+ * 1. client → `{app}/api/mcp` with no token → `401` naming this document
607
+ * 2. client → `{app}/.well-known/oauth-protected-resource` → the issuer
608
+ * 3. client → `{issuer}/.well-known/oauth-authorization-server` → endpoints
609
+ * 4. client → issuer's `/authorize`, then `/token`
610
+ * 5. client → `{app}/api/mcp` with the token
611
+ */
612
+
613
+ var CORS_HEADERS = {
614
+ // The document is public and contains no secrets — it exists to be read by
615
+ // clients whose origin we cannot know in advance, so `*` is the correct value
616
+ // rather than a lazy one. Note there is no `Access-Control-Allow-Credentials`:
617
+ // with it, `*` would be rejected by browsers, and this document is never
618
+ // fetched with credentials.
619
+ "Access-Control-Allow-Origin": "*",
620
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
621
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, MCP-Protocol-Version",
622
+ "Access-Control-Max-Age": "3600"
623
+ };
624
+ function createValMcpMetadata(oauth, scopesSupported) {
625
+ var document = {
626
+ // The resource identifier, which MUST be the value clients send as
627
+ // `resource` and the value that arrives back in `aud`. Same string as the
628
+ // audience this app verifies against — one value, so the two cannot drift.
629
+ resource: oauth.resource,
630
+ authorization_servers: [oauth.issuer],
631
+ scopes_supported: scopesSupported,
632
+ bearer_methods_supported: ["header"]
633
+ };
634
+ var body = JSON.stringify(document);
635
+ return {
636
+ GET: function GET() {
637
+ return new Response(body, {
638
+ status: 200,
639
+ headers: objectSpread2._objectSpread2({
640
+ "Content-Type": "application/json",
641
+ // Cacheable: it changes only when the app is reconfigured, and a
642
+ // client that re-reads it on every authorization costs a round trip
643
+ // for nothing.
644
+ "Cache-Control": "public, max-age=3600"
645
+ }, CORS_HEADERS)
646
+ });
647
+ },
648
+ OPTIONS: function OPTIONS() {
649
+ return new Response(null, {
650
+ status: 204,
651
+ headers: CORS_HEADERS
652
+ });
653
+ }
654
+ };
655
+ }
656
+
657
+ /**
658
+ * The `WWW-Authenticate` value for a refusal (RFC 6750 section 3, RFC 9728
659
+ * section 5.1).
660
+ *
661
+ * `resource_metadata` is the load-bearing parameter: it is how a client that has
662
+ * never seen this server learns where to authorize. A `401` without it is a dead
663
+ * end — the client knows it needs a token and has no way to find out from where.
664
+ */
665
+ function wwwAuthenticate(oauth, scopesSupported, refusal) {
666
+ var metadataUrl = new URL("/.well-known/oauth-protected-resource", oauth.resource).toString();
667
+ var params = ["resource_metadata=\"".concat(metadataUrl, "\""), "scope=\"".concat(scopesSupported.join(" "), "\"")];
668
+ if (refusal) {
669
+ params.push("error=\"".concat(refusal.error, "\""));
670
+ params.push("error_description=\"".concat(headerSafe(refusal.description), "\""));
671
+ }
672
+ return "Bearer ".concat(params.join(", "));
673
+ }
674
+
675
+ /**
676
+ * Make a string safe to put inside a quoted header parameter.
677
+ *
678
+ * Three classes go, and the third is the one that matters most:
679
+ *
680
+ * - a **quote** would close the parameter early;
681
+ * - a **backslash** would start an escape the rest of the value does not
682
+ * finish;
683
+ * - a **CR or LF** would end the header line, which is response splitting — an
684
+ * attacker-influenced description could inject a header of their own, or a
685
+ * whole second response.
686
+ *
687
+ * The descriptions passed here today are all literals from this package and
688
+ * contain none of it. That is a property of today's callers rather than of the
689
+ * type, and this function exists so it stays true when a future one interpolates
690
+ * something from a request.
691
+ */
692
+ function headerSafe(value) {
693
+ // eslint-disable-next-line no-control-regex -- the point is to remove them
694
+ return value.replace(/["\\]/g, "").replace(/[\u0000-\u001f\u007f]/g, " ");
695
+ }
696
+
123
697
  /**
124
698
  * Val's tools over MCP, and the two checks that have to happen before a request
125
699
  * gets to them.
@@ -174,7 +748,10 @@ function initValMcp(valModules, config, opts) {
174
748
  setupPromise["catch"](function () {
175
749
  // handled per request
176
750
  });
751
+ var oauth = opts === null || opts === void 0 ? void 0 : opts.oauth;
752
+ var scopesSupported = [server.VAL_SCOPE_READ, server.VAL_SCOPE_WRITE];
177
753
  return {
754
+ valMcpMetadata: oauth ? createValMcpMetadata(oauth, scopesSupported) : null,
178
755
  valMcpTools: function valMcpTools() {
179
756
  return version._asyncToGenerator(/*#__PURE__*/version._regenerator().m(function _callee2() {
180
757
  return version._regenerator().w(function (_context2) {
@@ -190,7 +767,7 @@ function initValMcp(valModules, config, opts) {
190
767
  },
191
768
  valMcpAuthorize: function valMcpAuthorize(request) {
192
769
  return version._asyncToGenerator(/*#__PURE__*/version._regenerator().m(function _callee3() {
193
- var setup, refusal, pat, _t;
770
+ var setup, refusal, sessionId, verified, status, pat, _t;
194
771
  return version._regenerator().w(function (_context3) {
195
772
  while (1) switch (_context3.p = _context3.n) {
196
773
  case 0:
@@ -233,21 +810,66 @@ function initValMcp(valModules, config, opts) {
233
810
  response: refusal
234
811
  });
235
812
  case 5:
813
+ // Not the MCP session id, in either branch below. Val's patch `sessionId`
814
+ // names a Val AI session, and putting an unrelated id in it would claim a
815
+ // relationship that does not exist.
816
+ sessionId = null;
817
+ if (!oauth) {
818
+ _context3.n = 8;
819
+ break;
820
+ }
821
+ _context3.n = 6;
822
+ return verifyValAccessToken(request, oauth);
823
+ case 6:
824
+ verified = _context3.v;
825
+ if (!(verified.status === "refused")) {
826
+ _context3.n = 7;
827
+ break;
828
+ }
829
+ // 401 for a missing or bad token, 403 once the token is good but does
830
+ // not carry the scope: RFC 6750 section 3.1, and the distinction is
831
+ // what tells a client whether to authorize again or to give up.
832
+ status = verified.error === "insufficient_scope" ? 403 : 401;
833
+ return _context3.a(2, {
834
+ status: "refused",
835
+ response: new Response(JSON.stringify({
836
+ error: verified.error,
837
+ error_description: verified.description
838
+ }), {
839
+ status: status,
840
+ headers: {
841
+ "Content-Type": "application/json",
842
+ "WWW-Authenticate": wwwAuthenticate(oauth, scopesSupported, {
843
+ error: verified.error,
844
+ description: verified.description
845
+ })
846
+ }
847
+ })
848
+ });
849
+ case 7:
850
+ return _context3.a(2, {
851
+ status: "ok",
852
+ tools: setup.tools,
853
+ ctx: {
854
+ auth: verified.auth,
855
+ sessionId: sessionId
856
+ }
857
+ });
858
+ case 8:
236
859
  pat = readBearerToken(request);
237
860
  return _context3.a(2, {
238
861
  status: "ok",
239
862
  tools: setup.tools,
240
863
  ctx: {
241
- // Passed through unverified, deliberately: this app is not the
242
- // authority on what a token may do, and the registry sends it to the
864
+ // Passed through unverified, deliberately: without an `oauth` config
865
+ // this app has no key to check anything against, so it is not the
866
+ // authority on what the token may do and the registry sends it to the
243
867
  // backend that is. See `docs/plans/mcp.md` D.2.
244
868
  auth: pat === null ? null : {
869
+ type: "pat",
245
870
  pat: pat
246
871
  },
247
- // Not the MCP session id. Val's patch `sessionId` names a Val AI
248
- // session, and putting an unrelated id in it would claim a
249
- // relationship that does not exist.
250
- sessionId: null
872
+ sessionId: sessionId
251
873
  }
252
874
  });
253
875
  }
@@ -358,16 +980,6 @@ function hostnameOf(host) {
358
980
  var colon = host.indexOf(":");
359
981
  return colon === -1 ? host : host.slice(0, colon);
360
982
  }
361
- function readBearerToken(request) {
362
- var _match$;
363
- var header = request.headers.get("authorization");
364
- if (!header) {
365
- return null;
366
- }
367
- var match = /^Bearer\s+(.+)$/i.exec(header.trim());
368
- var token = match === null || match === void 0 || (_match$ = match[1]) === null || _match$ === void 0 ? void 0 : _match$.trim();
369
- return token ? token : null;
370
- }
371
983
  function jsonResponse(status, body) {
372
984
  return new Response(JSON.stringify(body), {
373
985
  status: status,