@valbuild/next 0.122.0 → 0.123.1

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.
@@ -3,10 +3,9 @@ import { _ as _slicedToArray } from '../../dist/slicedToArray-aa291011.esm.js';
3
3
  import { _ as _asyncToGenerator, a as _regenerator, V as VERSION } from '../../dist/version-4d7b692c.esm.js';
4
4
  import { _ as _objectSpread2 } from '../../dist/objectSpread2-60d1bd93.esm.js';
5
5
  import { Internal } from '@valbuild/core';
6
- import { createValApiRouter, createValServer, authorIdFromVerifiedSubject, VAL_SCOPE_READ, createValTools, initHandlerOptions, VAL_SCOPE_WRITE } from '@valbuild/server';
6
+ import { createValApiRouter, createValServer } from '@valbuild/server';
7
7
  import { NextResponse } from 'next/server';
8
- import { _ as _typeof } from '../../dist/typeof-a1531d8f.esm.js';
9
- import { createPublicKey, verify } from 'node:crypto';
8
+ import { initValMcp as initValMcp$1 } from '@valbuild/mcp';
10
9
  import '../../dist/unsupportedIterableToArray-5baabfdc.esm.js';
11
10
  import '../../dist/defineProperty-cca5affa.esm.js';
12
11
 
@@ -119,1042 +118,28 @@ function initValServer(valModules, config, nextConfig) {
119
118
  }
120
119
 
121
120
  /**
122
- * Verifying an OAuth access token, which is the whole of what makes this app a
123
- * resource server rather than a relay.
121
+ * Val's tools over MCP, bound to Next.
124
122
  *
125
- * The token is issued by Val's authorization server and presented by an MCP
126
- * client. This app holds no signing key for it and cannot mint one — it fetches
127
- * the issuer's *public* keys and checks a signature. That asymmetry is the
128
- * point: a verified `sub` is a fact about the token rather than a claim by
129
- * whoever sent it, which is what lets the tools attribute a patch to that
130
- * profile at all.
123
+ * The MCP endpoint itself — the tools, the request guards, the access-token
124
+ * verification — lives in `@valbuild/mcp`, which knows nothing about Next. All
125
+ * that is left here is the one thing this package can answer and that one
126
+ * cannot: which version of `@valbuild/next` is running, which
127
+ * `initHandlerOptions` insists on before it will build a proxy-mode config.
131
128
  *
132
- * ## Why this is not `jose`
133
- *
134
- * `jose` was the first choice and was rejected on a fact rather than a
135
- * preference: version 6 is ESM-only (`"type": "module"`, no CJS export). This
136
- * package is built by preconstruct and `require`d by Next.js server code, so an
137
- * ESM-only dependency here is a runtime failure in consumers' apps, not a build
138
- * inconvenience. Adding it would also put a dependency in every install of
139
- * `@valbuild/next` for one function.
140
- *
141
- * The actual cryptography is still not hand-rolled — `node:crypto` does the
142
- * ECDSA and the JWK import. What is written here is the JWS envelope and the
143
- * claim checks, and the rules that keep that safe are worth stating because
144
- * this repository has already shipped the counterexample (`decodeJwt`: `exp`
145
- * never checked, a non-constant-time compare, verification skippable):
146
- *
147
- * - **`alg` is pinned**, not read from the token. The header is only consulted
148
- * for `kid`. A verifier that honours the token's own `alg` can be handed
149
- * `HS256` and will treat the *published* public key as a shared secret.
150
- * - **Nothing is read from the payload before the signature verifies.** Claims
151
- * from an unverified token are attacker input.
152
- * - **Keys come only from the configured issuer's JWKS**, never from the token.
153
- * The key set is cached, but a token naming a `kid` the cache does not hold
154
- * provokes one rate-limited refetch rather than a refusal — see
155
- * {@link UNKNOWN_KID_REFETCH_INTERVAL_MS}. Without that, this server's own
156
- * cache turns any key rotation into an outage lasting the rest of the TTL.
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
- * The floor between two refetches provoked by an unknown `kid`.
175
- *
176
- * A token naming a key this process has not seen is the one case where the TTL
177
- * is the wrong answer: the issuer may have just rotated, and refusing for the
178
- * rest of the five minutes turns a rotation into an outage. So an unknown `kid`
179
- * bypasses the TTL — but only this often, because the `kid` comes from the
180
- * token and the token comes from whoever is calling. Without a floor, a stream
181
- * of random `kid`s would be a way to make this server hammer its own issuer.
182
- *
183
- * Note what the floor costs when it bites: a refusal, for a token that would
184
- * have verified, for at most this long. That is the same failure the TTL used
185
- * to guarantee for five minutes, so the trade only ever improves.
186
- */
187
- var UNKNOWN_KID_REFETCH_INTERVAL_MS = 30 * 1000;
188
- /**
189
- * One cache per issuer, and it has to outlive the request or it is not a cache:
190
- * a fetch per tool call would put a network round trip in front of every read.
191
- */
192
- var jwksCache = new Map();
193
- /** Concurrent misses share one fetch rather than starting several. */
194
- var inFlight = new Map();
195
- /**
196
- * When an unknown `kid` last made us go back to the issuer, per issuer.
197
- *
198
- * Separate from the cache because it is a rate limit rather than a cache: it
199
- * records an *attempt*, so a refetch that found nothing new still spends the
200
- * window. Keyed by issuer, not by `kid`, or an attacker would simply use a new
201
- * one each time.
202
- */
203
- var unknownKidRefetchAtMs = new Map();
204
- function jwksUrl(issuer) {
205
- // Not discovered from the issuer's metadata document, deliberately:
206
- // discovery would mean one more request on the hot path and one more thing
207
- // that can be pointed elsewhere. The location is fixed by convention and by
208
- // Val's own authorization server.
209
- return new URL("/.well-known/jwks.json", issuer).toString();
210
- }
211
- function loadJwks(_x, _x2) {
212
- return _loadJwks.apply(this, arguments);
213
- }
214
- /**
215
- * Go back to the issuer because the token named a key we do not have.
216
- *
217
- * Rate-limited, and the limit is the whole reason this is not just a call to
218
- * {@link fetchJwks}: the `kid` that triggers it is attacker-controlled. Returns
219
- * `null` when the window has not elapsed, which the caller reads as "nothing
220
- * new to try" rather than as a failure.
221
- *
222
- * The limit is on *starting* a fetch, not on benefiting from one. A fetch
223
- * already in flight is joined whatever the window says, because joining it
224
- * costs the issuer nothing — and the case that matters is precisely a burst:
225
- * at a rotation, many requests arrive at once carrying the same new `kid`, and
226
- * refusing all but the first would be the outage this whole path exists to
227
- * prevent, merely shortened from five minutes to thirty seconds.
228
- *
229
- * Only ever called with a successfully-fetched key set in hand. An error entry
230
- * has its own, shorter TTL and its own recovery, and letting an unknown `kid`
231
- * shortcut it would hand an unreachable issuer a retry storm.
232
- */
233
- function _loadJwks() {
234
- _loadJwks = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config, nowMs) {
235
- var url, cached, age, ttl, _t;
236
- return _regenerator().w(function (_context) {
237
- while (1) switch (_context.n) {
238
- case 0:
239
- url = jwksUrl(config.issuer);
240
- cached = jwksCache.get(url);
241
- if (!cached) {
242
- _context.n = 1;
243
- break;
244
- }
245
- age = cached.status === "keys" ? nowMs - cached.fetchedAtMs : nowMs - cached.failedAtMs;
246
- ttl = cached.status === "keys" ? JWKS_TTL_MS : JWKS_ERROR_TTL_MS;
247
- if (!(age < ttl)) {
248
- _context.n = 1;
249
- break;
250
- }
251
- return _context.a(2, {
252
- entry: cached,
253
- fromCache: true
254
- });
255
- case 1:
256
- _context.n = 2;
257
- return fetchJwks(config, nowMs);
258
- case 2:
259
- _t = _context.v;
260
- return _context.a(2, {
261
- entry: _t,
262
- fromCache: false
263
- });
264
- }
265
- }, _callee);
266
- }));
267
- return _loadJwks.apply(this, arguments);
268
- }
269
- function refetchForUnknownKid(_x3, _x4) {
270
- return _refetchForUnknownKid.apply(this, arguments);
271
- }
272
- /**
273
- * Fetch the key set, ignoring whatever is cached, and cache the result.
274
- *
275
- * Shares {@link inFlight} with every other caller, so a forced refetch that
276
- * lands during an ordinary miss joins it rather than opening a second request.
277
- * Only the caller that *starts* a fetch writes the cache — a joiner returns the
278
- * shared promise above — so `keepCacheOnError` is a property of the fetch, not a
279
- * race between callers.
280
- */
281
- function _refetchForUnknownKid() {
282
- _refetchForUnknownKid = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(config, nowMs) {
283
- var url, existing, lastAttemptMs;
284
- return _regenerator().w(function (_context2) {
285
- while (1) switch (_context2.n) {
286
- case 0:
287
- url = jwksUrl(config.issuer);
288
- existing = inFlight.get(url);
289
- if (!existing) {
290
- _context2.n = 1;
291
- break;
292
- }
293
- return _context2.a(2, existing);
294
- case 1:
295
- lastAttemptMs = unknownKidRefetchAtMs.get(url);
296
- if (!(lastAttemptMs !== undefined && nowMs - lastAttemptMs < UNKNOWN_KID_REFETCH_INTERVAL_MS)) {
297
- _context2.n = 2;
298
- break;
299
- }
300
- return _context2.a(2, null);
301
- case 2:
302
- // Recorded before the await, so that once this fetch has finished the window
303
- // is already closed against the next unknown `kid`.
304
- unknownKidRefetchAtMs.set(url, nowMs);
305
- return _context2.a(2, fetchJwks(config, nowMs, {
306
- keepCacheOnError: true
307
- }));
308
- }
309
- }, _callee2);
310
- }));
311
- return _refetchForUnknownKid.apply(this, arguments);
312
- }
313
- function fetchJwks(_x5, _x6) {
314
- return _fetchJwks.apply(this, arguments);
315
- }
316
- function _fetchJwks() {
317
- _fetchJwks = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(config, nowMs) {
318
- var _config$fetchImpl;
319
- var _ref,
320
- _ref$keepCacheOnError,
321
- keepCacheOnError,
322
- url,
323
- existing,
324
- fetchImpl,
325
- pending,
326
- entry,
327
- cached,
328
- _args4 = arguments;
329
- return _regenerator().w(function (_context4) {
330
- while (1) switch (_context4.p = _context4.n) {
331
- case 0:
332
- _ref = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : {}, _ref$keepCacheOnError = _ref.keepCacheOnError, keepCacheOnError = _ref$keepCacheOnError === void 0 ? false : _ref$keepCacheOnError;
333
- url = jwksUrl(config.issuer);
334
- existing = inFlight.get(url);
335
- if (!existing) {
336
- _context4.n = 1;
337
- break;
338
- }
339
- return _context4.a(2, existing);
340
- case 1:
341
- fetchImpl = (_config$fetchImpl = config.fetchImpl) !== null && _config$fetchImpl !== void 0 ? _config$fetchImpl : fetch;
342
- pending = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
343
- var res, body, keys;
344
- return _regenerator().w(function (_context3) {
345
- while (1) switch (_context3.p = _context3.n) {
346
- case 0:
347
- _context3.p = 0;
348
- _context3.n = 1;
349
- return fetchImpl(url, {
350
- headers: {
351
- accept: "application/json"
352
- }
353
- });
354
- case 1:
355
- res = _context3.v;
356
- if (res.ok) {
357
- _context3.n = 2;
358
- break;
359
- }
360
- return _context3.a(2, {
361
- status: "error",
362
- failedAtMs: nowMs
363
- });
364
- case 2:
365
- _context3.n = 3;
366
- return res.json();
367
- case 3:
368
- body = _context3.v;
369
- keys = readKeys(body);
370
- if (!(keys === null)) {
371
- _context3.n = 4;
372
- break;
373
- }
374
- return _context3.a(2, {
375
- status: "error",
376
- failedAtMs: nowMs
377
- });
378
- case 4:
379
- return _context3.a(2, {
380
- status: "keys",
381
- keys: keys,
382
- fetchedAtMs: nowMs
383
- });
384
- case 5:
385
- _context3.p = 5;
386
- _context3.v;
387
- return _context3.a(2, {
388
- status: "error",
389
- failedAtMs: nowMs
390
- });
391
- }
392
- }, _callee3, null, [[0, 5]]);
393
- }))();
394
- inFlight.set(url, pending);
395
- _context4.p = 2;
396
- _context4.n = 3;
397
- return pending;
398
- case 3:
399
- entry = _context4.v;
400
- cached = jwksCache.get(url);
401
- if (!(entry.status === "error" && keepCacheOnError && (cached === null || cached === void 0 ? void 0 : cached.status) === "keys")) {
402
- _context4.n = 4;
403
- break;
404
- }
405
- return _context4.a(2, entry);
406
- case 4:
407
- jwksCache.set(url, entry);
408
- return _context4.a(2, entry);
409
- case 5:
410
- _context4.p = 5;
411
- inFlight["delete"](url);
412
- return _context4.f(5);
413
- case 6:
414
- return _context4.a(2);
415
- }
416
- }, _callee4, null, [[2,, 5, 6]]);
417
- }));
418
- return _fetchJwks.apply(this, arguments);
419
- }
420
- function readKeys(body) {
421
- if (_typeof(body) !== "object" || body === null || !("keys" in body)) {
422
- return null;
423
- }
424
- // `in` narrows the property into the type, so no assertion is needed to read
425
- // it — and the `Array.isArray` below is what actually establishes the shape.
426
- var keys = body.keys;
427
- if (!Array.isArray(keys)) {
428
- return null;
429
- }
430
- return keys.filter(function (key) {
431
- return _typeof(key) === "object" && key !== null;
432
- });
433
- }
434
-
435
- /**
436
- * Read `Authorization: Bearer …`.
437
- *
438
- * Exported because the refusal needs to know whether a token was presented at
439
- * all: RFC 6750 distinguishes "no credential" — a bare `401`, which is an
440
- * invitation to authenticate — from "a bad credential", and a client that gets
441
- * the second when it deserved the first will not start the authorization flow.
442
- */
443
- function readBearerToken(request) {
444
- var _match$;
445
- var header = request.headers.get("authorization");
446
- if (!header) {
447
- return null;
448
- }
449
- var match = /^Bearer\s+(.+)$/i.exec(header.trim());
450
- var token = match === null || match === void 0 || (_match$ = match[1]) === null || _match$ === void 0 ? void 0 : _match$.trim();
451
- return token ? token : null;
452
- }
453
- function verifyValAccessToken(_x7, _x8) {
454
- return _verifyValAccessToken.apply(this, arguments);
455
- }
456
- function _verifyValAccessToken() {
457
- _verifyValAccessToken = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(request, config) {
458
- var _config$clockToleranc;
459
- var token, parts, _parts, encodedHeader, encodedPayload, encodedSignature, header, kid, nowMs, loaded, candidates, refetched, signature, signedData, verified, payload, tolerance, nowSeconds, subject, scopes;
460
- return _regenerator().w(function (_context5) {
461
- while (1) switch (_context5.n) {
462
- case 0:
463
- token = readBearerToken(request);
464
- if (!(token === null)) {
465
- _context5.n = 1;
466
- break;
467
- }
468
- return _context5.a(2, {
469
- status: "refused",
470
- error: "invalid_request",
471
- description: "This Val MCP endpoint needs an access token. Authorize with the Val authorization server and present it as `Authorization: Bearer`."
472
- });
473
- case 1:
474
- parts = token.split(".");
475
- if (!(parts.length !== 3)) {
476
- _context5.n = 2;
477
- break;
478
- }
479
- return _context5.a(2, invalidToken("The access token is not a JWS."));
480
- case 2:
481
- _parts = _slicedToArray(parts, 3), encodedHeader = _parts[0], encodedPayload = _parts[1], encodedSignature = _parts[2];
482
- header = decodeJsonSegment(encodedHeader);
483
- if (!(header === null)) {
484
- _context5.n = 3;
485
- break;
486
- }
487
- return _context5.a(2, invalidToken("The access token's header could not be read."));
488
- case 3:
489
- if (!(header.alg !== "ES256")) {
490
- _context5.n = 4;
491
- break;
492
- }
493
- return _context5.a(2, invalidToken("The access token is not signed with ES256, which is the only algorithm this server accepts."));
494
- case 4:
495
- kid = typeof header.kid === "string" ? header.kid : null;
496
- nowMs = Date.now();
497
- _context5.n = 5;
498
- return loadJwks(config, nowMs);
499
- case 5:
500
- loaded = _context5.v;
501
- if (!(loaded.entry.status === "error")) {
502
- _context5.n = 6;
503
- break;
504
- }
505
- return _context5.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."));
506
- case 6:
507
- candidates = loaded.entry.keys.filter(function (key) {
508
- return isVerifyingP256Key(key, kid);
509
- });
510
- if (!(candidates.length === 0 && kid !== null && loaded.fromCache)) {
511
- _context5.n = 9;
512
- break;
513
- }
514
- _context5.n = 7;
515
- return refetchForUnknownKid(config, nowMs);
516
- case 7:
517
- refetched = _context5.v;
518
- if (!(refetched !== null)) {
519
- _context5.n = 9;
520
- break;
521
- }
522
- if (!(refetched.status === "error")) {
523
- _context5.n = 8;
524
- break;
525
- }
526
- return _context5.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."));
527
- case 8:
528
- candidates = refetched.keys.filter(function (key) {
529
- return isVerifyingP256Key(key, kid);
530
- });
531
- case 9:
532
- if (!(candidates.length === 0)) {
533
- _context5.n = 10;
534
- break;
535
- }
536
- return _context5.a(2, invalidToken("The access token was signed with a key the Val authorization server does not publish."));
537
- case 10:
538
- signature = decodeBase64Url(encodedSignature);
539
- if (!(signature === null)) {
540
- _context5.n = 11;
541
- break;
542
- }
543
- return _context5.a(2, invalidToken("The access token's signature could not be read."));
544
- case 11:
545
- signedData = Buffer.from("".concat(encodedHeader, ".").concat(encodedPayload), "ascii"); // Every published key is tried when the token names no `kid`, so a rotation
546
- // that has not yet propagated to clients still verifies. With a `kid` the
547
- // filter above leaves one — or, if this process had not yet seen that key,
548
- // the one the refetch just found.
549
- verified = candidates.some(function (key) {
550
- return verifyWithJwk(key, signedData, signature);
551
- });
552
- if (verified) {
553
- _context5.n = 12;
554
- break;
555
- }
556
- return _context5.a(2, invalidToken("The access token's signature could not be verified."));
557
- case 12:
558
- // Only now: everything below reads the payload, and before this line it was
559
- // attacker input.
560
- payload = decodeJsonSegment(encodedPayload);
561
- if (!(payload === null)) {
562
- _context5.n = 13;
563
- break;
564
- }
565
- return _context5.a(2, invalidToken("The access token's payload could not be read."));
566
- case 13:
567
- tolerance = (_config$clockToleranc = config.clockToleranceSeconds) !== null && _config$clockToleranc !== void 0 ? _config$clockToleranc : DEFAULT_CLOCK_TOLERANCE_SECONDS;
568
- nowSeconds = Math.floor(nowMs / 1000);
569
- if (!(typeof payload.exp !== "number")) {
570
- _context5.n = 14;
571
- break;
572
- }
573
- return _context5.a(2, invalidToken("The access token has no expiry."));
574
- case 14:
575
- if (!(payload.exp + tolerance <= nowSeconds)) {
576
- _context5.n = 15;
577
- break;
578
- }
579
- return _context5.a(2, invalidToken("The access token has expired. Refresh it and try again."));
580
- case 15:
581
- if (!(typeof payload.nbf === "number" && payload.nbf - tolerance > nowSeconds)) {
582
- _context5.n = 16;
583
- break;
584
- }
585
- return _context5.a(2, invalidToken("The access token is not valid yet."));
586
- case 16:
587
- if (!(payload.iss !== config.issuer)) {
588
- _context5.n = 17;
589
- break;
590
- }
591
- return _context5.a(2, invalidToken("The access token was not issued by this server's authorization server (iss claim)."));
592
- case 17:
593
- if (audienceMatches(payload.aud, config.resource)) {
594
- _context5.n = 18;
595
- break;
596
- }
597
- return _context5.a(2, invalidToken("The access token is not valid for this server (aud claim)."));
598
- case 18:
599
- subject = payload.sub;
600
- if (!(typeof subject !== "string" || subject.length === 0)) {
601
- _context5.n = 19;
602
- break;
603
- }
604
- return _context5.a(2, invalidToken("The access token has no subject."));
605
- case 19:
606
- scopes = readScopes(payload.scope);
607
- if (scopes.includes(VAL_SCOPE_READ)) {
608
- _context5.n = 20;
609
- break;
610
- }
611
- return _context5.a(2, {
612
- status: "refused",
613
- error: "insufficient_scope",
614
- description: "The access token does not have the ".concat(VAL_SCOPE_READ, " scope, so it cannot read any content.")
615
- });
616
- case 20:
617
- return _context5.a(2, {
618
- status: "ok",
619
- auth: {
620
- type: "verified-profile",
621
- profileId: authorIdFromVerifiedSubject(subject),
622
- scopes: scopes
623
- }
624
- });
625
- }
626
- }, _callee5);
627
- }));
628
- return _verifyValAccessToken.apply(this, arguments);
629
- }
630
- function invalidToken(description) {
631
- // Described by class, never by echoing the token or a raw error: a
632
- // verification failure message is a place credentials leak into logs.
633
- return {
634
- status: "refused",
635
- error: "invalid_token",
636
- description: description
637
- };
638
- }
639
-
640
- /**
641
- * `aud` is a string or an array of strings (RFC 7519 section 4.1.3).
642
- *
643
- * A match on any member is a match, which is the spec's own rule — a token may
644
- * legitimately be addressed to several resources.
645
- */
646
- function audienceMatches(claim, resource) {
647
- if (typeof claim === "string") {
648
- return claim === resource;
649
- }
650
- if (Array.isArray(claim)) {
651
- return claim.some(function (entry) {
652
- return entry === resource;
653
- });
654
- }
655
- return false;
656
- }
657
-
658
- /**
659
- * `scope` is a space-delimited string (RFC 6749 section 3.3).
660
- *
661
- * Anything else is read as no scopes rather than coerced. A token whose scope
662
- * claim is the wrong shape is a token we do not understand, and understanding
663
- * it generously is how a write gets authorized by an array someone sent.
664
- */
665
- function readScopes(claim) {
666
- if (typeof claim !== "string") {
667
- return [];
668
- }
669
- return claim.split(" ").filter(function (scope) {
670
- return scope.length > 0;
671
- });
672
- }
673
- function isVerifyingP256Key(key, kid) {
674
- if (key.kty !== "EC" || key.crv !== "P-256") {
675
- return false;
676
- }
677
- if (typeof key.x !== "string" || typeof key.y !== "string") {
678
- return false;
679
- }
680
- // A key published for encryption is not a key to verify signatures with, and
681
- // an `alg` that disagrees with what we verify is a key meant for something
682
- // else.
683
- if (key.use !== undefined && key.use !== "sig") {
684
- return false;
685
- }
686
- if (key.alg !== undefined && key.alg !== "ES256") {
687
- return false;
688
- }
689
- if (kid !== null && typeof key.kid === "string" && key.kid !== kid) {
690
- return false;
691
- }
692
- return true;
693
- }
694
- function verifyWithJwk(key, signedData, signature) {
695
- try {
696
- var publicKey = createPublicKey({
697
- key: {
698
- kty: "EC",
699
- crv: "P-256",
700
- x: String(key.x),
701
- y: String(key.y)
702
- },
703
- format: "jwk"
704
- });
705
- return verify("sha256", signedData,
706
- // `ieee-p1363` because a JWS ECDSA signature is the raw `r||s` pair, while
707
- // node defaults to DER for EC keys. Getting this wrong rejects every
708
- // valid signature.
709
- {
710
- key: publicKey,
711
- dsaEncoding: "ieee-p1363"
712
- }, signature);
713
- } catch (_unused) {
714
- // A malformed key in an otherwise good key set should not take down
715
- // verification against the other keys.
716
- return false;
717
- }
718
- }
719
- function decodeBase64Url(segment) {
720
- if (segment === undefined || !/^[A-Za-z0-9_-]*$/.test(segment)) {
721
- return null;
722
- }
723
- try {
724
- return Buffer.from(segment, "base64url");
725
- } catch (_unused2) {
726
- return null;
727
- }
728
- }
729
- function decodeJsonSegment(segment) {
730
- var decoded = decodeBase64Url(segment);
731
- if (decoded === null) {
732
- return null;
733
- }
734
- try {
735
- var parsed = JSON.parse(decoded.toString("utf8"));
736
- if (_typeof(parsed) !== "object" || parsed === null || Array.isArray(parsed)) {
737
- return null;
738
- }
739
- return _objectSpread2({}, parsed);
740
- } catch (_unused3) {
741
- return null;
742
- }
743
- }
744
-
745
- /**
746
- * The one document an MCP client needs before it can authorize: RFC 9728
747
- * Protected Resource Metadata, served by the *resource* server.
748
- *
749
- * This is how a client discovers where to authorize. It asks the resource — this
750
- * app — and the resource names its authorization server. Which is why this
751
- * belongs here and the RFC 8414 *authorization server* metadata does not: that
752
- * document lives at the issuer, describes the issuer's own endpoints, and is
753
- * served by the issuer. An app serving a copy would be asserting the issuer's
754
- * configuration on its behalf, and would be wrong the moment the issuer changed
755
- * anything.
756
- *
757
- * The flow, so the split reads as a whole:
758
- *
759
- * 1. client → `{app}/api/mcp` with no token → `401` naming this document
760
- * 2. client → `{app}/.well-known/oauth-protected-resource` → the issuer
761
- * 3. client → `{issuer}/.well-known/oauth-authorization-server` → endpoints
762
- * 4. client → issuer's `/authorize`, then `/token`
763
- * 5. client → `{app}/api/mcp` with the token
129
+ * Kept exported from `@valbuild/next/server` because that is where it has
130
+ * always been. New code can import `initValMcp` from `@valbuild/mcp` directly
131
+ * and pass `versions: { next }` itself; there is no difference in behaviour.
764
132
  */
765
-
766
- var CORS_HEADERS = {
767
- // The document is public and contains no secrets — it exists to be read by
768
- // clients whose origin we cannot know in advance, so `*` is the correct value
769
- // rather than a lazy one. Note there is no `Access-Control-Allow-Credentials`:
770
- // with it, `*` would be rejected by browsers, and this document is never
771
- // fetched with credentials.
772
- "Access-Control-Allow-Origin": "*",
773
- "Access-Control-Allow-Methods": "GET, OPTIONS",
774
- "Access-Control-Allow-Headers": "Content-Type, Authorization, MCP-Protocol-Version",
775
- "Access-Control-Max-Age": "3600"
776
- };
777
- function createValMcpMetadata(oauth, scopesSupported) {
778
- var document = {
779
- // The resource identifier, which MUST be the value clients send as
780
- // `resource` and the value that arrives back in `aud`. Same string as the
781
- // audience this app verifies against — one value, so the two cannot drift.
782
- resource: oauth.resource,
783
- authorization_servers: [oauth.issuer],
784
- scopes_supported: scopesSupported,
785
- bearer_methods_supported: ["header"]
786
- };
787
- var body = JSON.stringify(document);
788
- return {
789
- GET: function GET() {
790
- return new Response(body, {
791
- status: 200,
792
- headers: _objectSpread2({
793
- "Content-Type": "application/json",
794
- // Cacheable: it changes only when the app is reconfigured, and a
795
- // client that re-reads it on every authorization costs a round trip
796
- // for nothing.
797
- "Cache-Control": "public, max-age=3600"
798
- }, CORS_HEADERS)
799
- });
800
- },
801
- OPTIONS: function OPTIONS() {
802
- return new Response(null, {
803
- status: 204,
804
- headers: CORS_HEADERS
805
- });
806
- }
807
- };
808
- }
809
-
810
- /**
811
- * The `WWW-Authenticate` value for a refusal (RFC 6750 section 3, RFC 9728
812
- * section 5.1).
813
- *
814
- * `resource_metadata` is the load-bearing parameter: it is how a client that has
815
- * never seen this server learns where to authorize. A `401` without it is a dead
816
- * end — the client knows it needs a token and has no way to find out from where.
817
- */
818
- function wwwAuthenticate(oauth, scopesSupported, refusal) {
819
- var metadataUrl = new URL("/.well-known/oauth-protected-resource", oauth.resource).toString();
820
- var params = ["resource_metadata=\"".concat(metadataUrl, "\""), "scope=\"".concat(scopesSupported.join(" "), "\"")];
821
- if (refusal) {
822
- params.push("error=\"".concat(refusal.error, "\""));
823
- params.push("error_description=\"".concat(headerSafe(refusal.description), "\""));
824
- }
825
- return "Bearer ".concat(params.join(", "));
826
- }
827
-
828
- /**
829
- * Make a string safe to put inside a quoted header parameter.
830
- *
831
- * Three classes go, and the third is the one that matters most:
832
- *
833
- * - a **quote** would close the parameter early;
834
- * - a **backslash** would start an escape the rest of the value does not
835
- * finish;
836
- * - a **CR or LF** would end the header line, which is response splitting — an
837
- * attacker-influenced description could inject a header of their own, or a
838
- * whole second response.
839
- *
840
- * The descriptions passed here today are all literals from this package and
841
- * contain none of it. That is a property of today's callers rather than of the
842
- * type, and this function exists so it stays true when a future one interpolates
843
- * something from a request.
844
- */
845
- function headerSafe(value) {
846
- // eslint-disable-next-line no-control-regex -- the point is to remove them
847
- return value.replace(/["\\]/g, "").replace(/[\u0000-\u001f\u007f]/g, " ");
848
- }
849
-
850
- /**
851
- * Val's tools over MCP, and the two checks that have to happen before a request
852
- * gets to them.
853
- *
854
- * Nothing here imports an MCP SDK. The app owns the transport — which SDK, which
855
- * route, which framework — and this owns the parts that must not be re-decided
856
- * per app: whether the request is allowed to reach the tools at all, and whose
857
- * credential it carries. `docs/plans/mcp.md` Part A has the reasoning; the short
858
- * version is that the SDK reorganised itself once already, and the security
859
- * checks should not move when it does again.
860
- */
861
-
862
133
  function initValMcp(valModules, config, opts) {
863
- var route = "/api/val"; // TODO: get from config, as initValServer does
864
- var coreVersion = Internal.VERSION.core;
865
- if (!coreVersion) {
866
- throw new Error("Could not get @valbuild/core package version");
867
- }
868
134
  var nextVersion = VERSION;
869
135
  if (!nextVersion) {
870
136
  throw new Error("Could not get @valbuild/next package version");
871
137
  }
872
-
873
- // Resolved once at module-eval time, awaited per request. The no-op catch is
874
- // load bearing for the same reason it is in createValApiRouter: a config error
875
- // on a promise with no handler attached becomes an unhandledRejection and
876
- // takes the dev server down, and the error is reported per request below
877
- // anyway.
878
- var setupPromise = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
879
- var options;
880
- return _regenerator().w(function (_context) {
881
- while (1) switch (_context.n) {
882
- case 0:
883
- _context.n = 1;
884
- return initHandlerOptions(route, _objectSpread2(_objectSpread2({}, config), {}, {
885
- versions: {
886
- core: coreVersion,
887
- next: nextVersion
888
- }
889
- }), config);
890
- case 1:
891
- options = _context.v;
892
- return _context.a(2, {
893
- mode: options.mode,
894
- tools: createValTools(valModules, _objectSpread2(_objectSpread2({}, options), {}, {
895
- formatter: opts === null || opts === void 0 ? void 0 : opts.formatter
896
- }))
897
- });
898
- }
899
- }, _callee);
900
- }))();
901
- setupPromise["catch"](function () {
902
- // handled per request
903
- });
904
- var oauth = opts === null || opts === void 0 ? void 0 : opts.oauth;
905
- var scopesSupported = [VAL_SCOPE_READ, VAL_SCOPE_WRITE];
906
- return {
907
- valMcpMetadata: oauth ? createValMcpMetadata(oauth, scopesSupported) : null,
908
- valMcpTools: function valMcpTools() {
909
- return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
910
- return _regenerator().w(function (_context2) {
911
- while (1) switch (_context2.n) {
912
- case 0:
913
- _context2.n = 1;
914
- return setupPromise;
915
- case 1:
916
- return _context2.a(2, _context2.v.tools);
917
- }
918
- }, _callee2);
919
- }))();
920
- },
921
- valMcpAuthorize: function valMcpAuthorize(request) {
922
- return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
923
- var setup, refusal, sessionId, verified, status, _t;
924
- return _regenerator().w(function (_context3) {
925
- while (1) switch (_context3.p = _context3.n) {
926
- case 0:
927
- _context3.p = 0;
928
- _context3.n = 1;
929
- return setupPromise;
930
- case 1:
931
- setup = _context3.v;
932
- _context3.n = 3;
933
- break;
934
- case 2:
935
- _context3.p = 2;
936
- _t = _context3.v;
937
- return _context3.a(2, {
938
- status: "refused",
939
- response: jsonResponse(500, {
940
- error: "Val: could not start the Val MCP server",
941
- details: _t instanceof Error ? _t.message : String(_t)
942
- })
943
- });
944
- case 3:
945
- if (!(request === undefined)) {
946
- _context3.n = 4;
947
- break;
948
- }
949
- return _context3.a(2, {
950
- status: "refused",
951
- response: jsonResponse(401, {
952
- error: "Val: this MCP server needs the HTTP request to authorize a call, and none was available."
953
- })
954
- });
955
- case 4:
956
- refusal = refuseUnsafeRequest(request, setup.mode);
957
- if (!refusal) {
958
- _context3.n = 5;
959
- break;
960
- }
961
- return _context3.a(2, {
962
- status: "refused",
963
- response: refusal
964
- });
965
- case 5:
966
- // Not the MCP session id, in any branch below. Val's patch `sessionId`
967
- // names a Val AI session, and putting an unrelated id in it would claim a
968
- // relationship that does not exist.
969
- sessionId = null;
970
- if (oauth) {
971
- _context3.n = 8;
972
- break;
973
- }
974
- if (!(setup.mode !== "fs")) {
975
- _context3.n = 6;
976
- break;
977
- }
978
- return _context3.a(2, {
979
- status: "refused",
980
- response: jsonResponse(500, {
981
- error: "Val: this MCP endpoint has no `oauth` config, and this project is configured to talk to the Val content backend. Pass `oauth` to `initValMcp` with the authorization server's URL and this endpoint's own URL, so callers authorize as themselves."
982
- })
983
- });
984
- case 6:
985
- if (!(readBearerToken(request) !== null)) {
986
- _context3.n = 7;
987
- break;
988
- }
989
- return _context3.a(2, {
990
- status: "refused",
991
- response: jsonResponse(400, {
992
- error: "Val: this project is running in local filesystem mode, where there is nothing to authenticate against — the tools read and write this working tree directly. Remove the credential from this MCP client's configuration: a token sent here is checked by nothing."
993
- })
994
- });
995
- case 7:
996
- return _context3.a(2, {
997
- status: "ok",
998
- tools: setup.tools,
999
- ctx: {
1000
- auth: null,
1001
- sessionId: sessionId
1002
- }
1003
- });
1004
- case 8:
1005
- _context3.n = 9;
1006
- return verifyValAccessToken(request, oauth);
1007
- case 9:
1008
- verified = _context3.v;
1009
- if (!(verified.status === "refused")) {
1010
- _context3.n = 10;
1011
- break;
1012
- }
1013
- // 401 for a missing or bad token, 403 once the token is good but does
1014
- // not carry the scope: RFC 6750 section 3.1, and the distinction is
1015
- // what tells a client whether to authorize again or to give up.
1016
- status = verified.error === "insufficient_scope" ? 403 : 401;
1017
- return _context3.a(2, {
1018
- status: "refused",
1019
- response: new Response(JSON.stringify({
1020
- error: verified.error,
1021
- error_description: verified.description
1022
- }), {
1023
- status: status,
1024
- headers: {
1025
- "Content-Type": "application/json",
1026
- "WWW-Authenticate": wwwAuthenticate(oauth, scopesSupported, {
1027
- error: verified.error,
1028
- description: verified.description
1029
- })
1030
- }
1031
- })
1032
- });
1033
- case 10:
1034
- return _context3.a(2, {
1035
- status: "ok",
1036
- tools: setup.tools,
1037
- ctx: {
1038
- auth: verified.auth,
1039
- sessionId: sessionId
1040
- }
1041
- });
1042
- }
1043
- }, _callee3, null, [[0, 2]]);
1044
- }))();
1045
- }
1046
- };
1047
- }
1048
-
1049
- /**
1050
- * The two ways this route is dangerous, both refused here.
1051
- *
1052
- * 1. **Local filesystem mode outside development.** In fs mode there is no
1053
- * credential and no backend: the tools read and write the running process's
1054
- * own working tree, and every permission check Val has lives on the other
1055
- * side of a backend that is not in this path. Exposed on a deployed host,
1056
- * that is unauthenticated write access to the site's content for anyone who
1057
- * can reach the port. There is no configuration that makes it safe, so there
1058
- * is no flag to turn this off — a project that wants MCP in production wants
1059
- * proxy mode with an `oauth` config, where every call carries an access
1060
- * token this app verified itself.
1061
- *
1062
- * 2. **A browser driving the local server.** A page on any origin can `fetch`
1063
- * `http://localhost:3000/api/mcp` while a developer has the app running, and
1064
- * with DNS rebinding it can do so with a `Host` of its own choosing. Neither
1065
- * needs a credential in fs mode. So a cross-origin `Origin` is refused, and
1066
- * in fs mode the request must actually be addressed to a loopback host.
1067
- *
1068
- * MCP clients are not browsers and send no `Origin`, so the check costs them
1069
- * nothing.
1070
- */
1071
- function refuseUnsafeRequest(request, mode) {
1072
- if (mode === "fs" && process.env.NODE_ENV !== "development") {
1073
- return jsonResponse(403, {
1074
- error: "Val: the MCP endpoint is disabled. This project is running in local filesystem mode, where MCP calls are unauthenticated and write directly to the working tree, so it is only served in development. Configure Val for proxy mode to use MCP on a deployed host."
1075
- });
1076
- }
1077
- var host = requestHost(request);
1078
- var origin = request.headers.get("origin");
1079
- if (origin !== null) {
1080
- // `Origin: null` is refused along with the rest. It is the *opaque* origin —
1081
- // a sandboxed iframe, a `file://` page, some redirects — so it cannot be
1082
- // compared to anything, and "cannot be compared" has to mean refuse: a page
1083
- // that would fail the check can otherwise pass it by arranging to have no
1084
- // origin at all. Absent entirely is the case that is allowed, and that is
1085
- // the one MCP clients produce.
1086
- var originHost = origin === "null" ? null : hostOf(origin);
1087
- if (originHost === null || host === null || originHost !== host) {
1088
- return jsonResponse(403, {
1089
- error: "Val: refusing a cross-origin MCP request from ".concat(JSON.stringify(origin), ". MCP clients do not send an Origin header; a browser does.")
1090
- });
1091
- }
1092
- }
1093
- if (mode === "fs") {
1094
- var hostname = host === null ? null : hostnameOf(host);
1095
- if (hostname === null || !LOOPBACK_HOSTNAMES.has(hostname)) {
1096
- return jsonResponse(403, {
1097
- error: "Val: refusing an MCP request addressed to ".concat(JSON.stringify(host !== null && host !== void 0 ? host : "an unknown host"), ". In local filesystem mode this endpoint only answers on localhost, because a name that resolves to 127.0.0.1 is how a web page reaches a developer's own machine.")
1098
- });
1099
- }
1100
- }
1101
- return null;
1102
- }
1103
- var LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1104
-
1105
- /**
1106
- * Which host the request was addressed to, as `hostname:port`.
1107
- *
1108
- * `Host` only, and deliberately **not** `X-Forwarded-Host`. The forwarded header
1109
- * is what a client asked for behind a proxy, but nothing stops a client sending
1110
- * it directly — so preferring it hands an attacker the value both checks below
1111
- * are decided on. `Host`, by contrast, a browser sets from the URL and page
1112
- * script cannot override, which is exactly the property the loopback check
1113
- * depends on.
1114
- *
1115
- * The cost is that behind a proxy that rewrites `Host`, a *browser* request
1116
- * whose `Origin` is the public name no longer matches. That is acceptable: such
1117
- * a request carries no access token, so proxy mode refuses it anyway, and a
1118
- * non-browser MCP client sends no `Origin` and never reaches the comparison.
1119
- * Trusting the forwarded header would need an explicit trusted-proxy
1120
- * configuration, which is a bigger thing than this needs.
1121
- */
1122
- function requestHost(request) {
1123
- var host = request.headers.get("host");
1124
- if (host) {
1125
- return host.trim().toLowerCase();
1126
- }
1127
- // Last resort: the URL the framework saw.
1128
- try {
1129
- return new URL(request.url).host.toLowerCase();
1130
- } catch (_unused) {
1131
- return null;
1132
- }
1133
- }
1134
- function hostOf(origin) {
1135
- try {
1136
- return new URL(origin).host.toLowerCase();
1137
- } catch (_unused2) {
1138
- return null;
1139
- }
1140
- }
1141
-
1142
- /** Strips the port, keeping IPv6 brackets — `[::1]:3000` is hostname `[::1]`. */
1143
- function hostnameOf(host) {
1144
- if (host.startsWith("[")) {
1145
- var end = host.indexOf("]");
1146
- return end === -1 ? host : host.slice(0, end + 1);
1147
- }
1148
- var colon = host.indexOf(":");
1149
- return colon === -1 ? host : host.slice(0, colon);
1150
- }
1151
- function jsonResponse(status, body) {
1152
- return new Response(JSON.stringify(body), {
1153
- status: status,
1154
- headers: {
1155
- "Content-Type": "application/json"
138
+ return initValMcp$1(valModules, config, _objectSpread2(_objectSpread2({}, opts), {}, {
139
+ versions: {
140
+ next: nextVersion
1156
141
  }
1157
- });
142
+ }));
1158
143
  }
1159
144
 
1160
145
  export { initValMcp, initValServer };