@nymbalhq/http 1.4.0 → 1.6.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.
package/dist/index.js CHANGED
@@ -1,7 +1,12 @@
1
1
  // src/fastify-adapter.ts
2
- import Fastify from "fastify";
2
+ import Fastify, {
3
+ errorCodes
4
+ } from "fastify";
5
+ import { createHash as createHash2, timingSafeEqual as timingSafeEqual3 } from "crypto";
6
+ import { isIP } from "net";
3
7
  import fastifyCookie from "@fastify/cookie";
4
8
  import fastifyCors from "@fastify/cors";
9
+ import proxyAddr from "@fastify/proxy-addr";
5
10
  import { v7 as uuidv7 } from "uuid";
6
11
  import {
7
12
  CORRELATION_ID_HEADER,
@@ -10,20 +15,41 @@ import {
10
15
  isValidCorrelationId,
11
16
  NymbalError
12
17
  } from "@nymbalhq/types";
18
+ import { TRUSTED_PROXIES_ENV, trustSuggestion } from "@nymbalhq/config";
13
19
 
14
20
  // src/security-middleware.ts
15
- import { randomBytes, timingSafeEqual } from "crypto";
21
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
22
+ import {
23
+ SHOPPER_ATTESTATION_HEADER
24
+ } from "@nymbalhq/types";
16
25
 
17
26
  // src/rate-limit.ts
27
+ import { ORDER_EMAIL_HEADER } from "@nymbalhq/types";
18
28
  var BUILT_IN_RATE_LIMITS = {
19
29
  "/api/auth/login": { requests: 10, window: "15m", action: "block" },
20
30
  "/api/auth/register": { requests: 10, window: "1h", action: "block" },
21
31
  // A record and a list per page view: 300 page views a minute, so shoppers behind one NAT keep their views.
22
32
  "/api/recently-viewed": { requests: 600, window: "1m", action: "block" },
23
33
  // Each accepted subscribe mails a confirmation: the bound on how much mail one IP can make the store send.
24
- "/api/alerts/subscribe": { requests: 10, window: "1h", action: "block" }
34
+ "/api/alerts/subscribe": { requests: 10, window: "1h", action: "block" },
35
+ // Each accepted review waits in the moderation queue: the bound on how much one IP can put there.
36
+ "/api/reviews": { requests: 10, window: "1h", action: "block" },
37
+ // Each match mails the order's link. Before the order-read rule, which a request carrying the email would also match.
38
+ "/api/orders/link": { requests: 5, window: "1h", action: "block" },
39
+ // The email is the second factor of an expired order key: bounded so it cannot be guessed. The key-only poll of a
40
+ // pending order carries no email and is never counted.
41
+ "/api/orders/*": { requests: 10, window: "1h", action: "block", header: ORDER_EMAIL_HEADER },
42
+ // Every checkout answer can mint an order key.
43
+ "/api/checkout": { requests: 30, window: "1m", action: "block" },
44
+ // Each agent request runs a tool, which is also held to its own route's rule.
45
+ "/api/mcp": { requests: 120, window: "1m", action: "block" },
46
+ // A UCP tool is not a route: each request counts once here, however many routes its tool runs.
47
+ "/api/ucp/mcp": { requests: 120, window: "1m", action: "block" },
48
+ // `**`: every ACP path, the session's own and the ones below it, counts in the one bucket.
49
+ "/api/acp/**": { requests: 120, window: "1m", action: "block" }
25
50
  };
26
51
  var PRUNE_THRESHOLD = 1024;
52
+ var CHECKOUT_ADDRESS_CEILING = 10;
27
53
  var RateLimiter = class {
28
54
  #rules;
29
55
  #buckets = /* @__PURE__ */ new Map();
@@ -32,30 +58,32 @@ var RateLimiter = class {
32
58
  this.#rules = Object.entries(rules).map(([pattern, rule]) => ({
33
59
  pattern,
34
60
  regex: compilePathPattern(pattern),
61
+ ...rule.header !== void 0 && { header: rule.header.toLowerCase() },
35
62
  requests: rule.requests,
36
63
  windowMs: parseWindow(rule.window),
37
64
  action: rule.action
38
65
  }));
39
66
  }
40
- check(ip, path) {
41
- const rule = this.#ruleFor(path);
67
+ /** Counts this request under `key` and refuses past the rule's count, times `scale` for a key that pools several. */
68
+ check(key, path, headers = {}, scale = 1) {
69
+ const rule = this.#ruleFor(path, headers);
42
70
  if (!rule) return null;
43
- const key = `${rule.pattern}|${ip}`;
71
+ const bucketKey = `${rule.pattern}|${key}`;
44
72
  const now = Date.now();
45
- const bucket = this.#buckets.get(key);
73
+ const bucket = this.#buckets.get(bucketKey);
46
74
  if (!bucket || bucket.resetAt <= now) {
47
- this.#open(key, now, rule.windowMs);
75
+ this.#open(bucketKey, now, rule.windowMs);
48
76
  return { allowed: true, action: rule.action };
49
77
  }
50
78
  bucket.count += 1;
51
- if (bucket.count > rule.requests) {
79
+ if (bucket.count > rule.requests * scale) {
52
80
  return { allowed: false, action: rule.action, retryAfter: retryAfter(bucket, now) };
53
81
  }
54
82
  return { allowed: true, action: rule.action };
55
83
  }
56
84
  /**
57
- * For a route that counts failures only: refuses when any of `keys` (an IP, an account) already holds the rule's
58
- * full count, without counting this request. `hit` and `clear` record the outcome once the handler has answered.
85
+ * For a route that counts failures only: refuses when any of `keys` already holds the rule's full count, without
86
+ * counting this request. `hit` and `clear` record the outcome once the handler has answered.
59
87
  */
60
88
  full(path, keys) {
61
89
  const rule = this.#ruleFor(path);
@@ -69,19 +97,29 @@ var RateLimiter = class {
69
97
  }
70
98
  return { allowed: true, action: rule.action };
71
99
  }
100
+ /** Counts one under each of `keys`; returns each bucket's count after it, in the order of `keys`. */
72
101
  hit(path, keys) {
73
102
  const rule = this.#ruleFor(path);
74
- if (!rule) return;
103
+ if (!rule) return [];
75
104
  const now = Date.now();
76
- for (const key of keys) {
105
+ return keys.map((key) => {
77
106
  const bucketKey = `${rule.pattern}|${key}`;
78
107
  const bucket = this.#buckets.get(bucketKey);
79
108
  if (!bucket || bucket.resetAt <= now) {
80
109
  this.#open(bucketKey, now, rule.windowMs);
81
- } else {
82
- bucket.count += 1;
110
+ return 1;
83
111
  }
84
- }
112
+ bucket.count += 1;
113
+ return bucket.count;
114
+ });
115
+ }
116
+ /** The count the rule for `path` allows per window, or undefined when no rule applies. */
117
+ requests(path) {
118
+ return this.#ruleFor(path)?.requests;
119
+ }
120
+ /** The buckets held, expired ones not yet swept included. */
121
+ get size() {
122
+ return this.#buckets.size;
85
123
  }
86
124
  clear(path, keys) {
87
125
  const rule = this.#ruleFor(path);
@@ -104,8 +142,10 @@ var RateLimiter = class {
104
142
  }
105
143
  this.#buckets.set(key, { count: 1, resetAt: now + windowMs });
106
144
  }
107
- #ruleFor(path) {
108
- return this.#rules.find((r) => r.regex.test(path));
145
+ #ruleFor(path, headers = {}) {
146
+ return this.#rules.find(
147
+ (r) => r.regex.test(path) && (r.header === void 0 || headers[r.header] !== void 0)
148
+ );
109
149
  }
110
150
  };
111
151
  function retryAfter(bucket, now) {
@@ -151,25 +191,45 @@ function buildSecurityHeaders(security) {
151
191
  return headers;
152
192
  }
153
193
  var LOGIN_PATH = "/api/auth/login";
154
- function csrfCookie(token) {
194
+ var CHECKOUT_PATH = "/api/checkout";
195
+ var CART_COOKIE = "nymbal.cart";
196
+ function csrfCookie(token, secure) {
155
197
  return {
156
198
  name: CSRF_COOKIE,
157
199
  value: token,
158
200
  path: "/",
159
201
  httpOnly: false,
160
202
  sameSite: "lax",
161
- secure: process.env.NODE_ENV === "production"
203
+ secure
162
204
  };
163
205
  }
164
- function loginKeys(ctx) {
206
+ function loginAccount(ctx) {
165
207
  const email = ctx.body?.email;
166
- return typeof email === "string" && email !== "" ? [ctx.ip, `account:${email.toLowerCase()}`] : [ctx.ip];
208
+ return typeof email === "string" && email !== "" ? email.toLowerCase() : null;
209
+ }
210
+ function checkoutKeys(ctx, ip = ctx.ip) {
211
+ const cart = ctx.cookies[CART_COOKIE];
212
+ const digest2 = cart ? createHash("sha256").update(cart).digest("hex").slice(0, 32) : "";
213
+ return { pair: `${ip}|cart:${digest2}`, address: ip };
167
214
  }
168
215
  function isLogin(ctx) {
169
216
  return ctx.method === "POST" && ctx.path === LOGIN_PATH;
170
217
  }
171
- function createSecurityGuard(security) {
218
+ function isCheckout(ctx) {
219
+ return ctx.method === "POST" && ctx.path === CHECKOUT_PATH;
220
+ }
221
+ function createSecurityGuard(security, options = {}) {
172
222
  const rateLimiter = new RateLimiter({ ...BUILT_IN_RATE_LIMITS, ...security.rateLimit });
223
+ const { attestation, secureCookies: secureCookies2 = false } = options;
224
+ function clientIp(ctx) {
225
+ return attestation?.verify(ctx.headers[SHOPPER_ATTESTATION_HEADER]) ?? ctx.ip;
226
+ }
227
+ function checkCheckout(ctx, ip) {
228
+ const keys = checkoutKeys(ctx, ip);
229
+ const address = rateLimiter.check(keys.address, ctx.path, ctx.headers, CHECKOUT_ADDRESS_CEILING);
230
+ if (address && !address.allowed) return address;
231
+ return rateLimiter.check(keys.pair, ctx.path, ctx.headers);
232
+ }
173
233
  const baseHeaders = buildSecurityHeaders(security);
174
234
  function applyHeaders(envelope) {
175
235
  return {
@@ -178,12 +238,13 @@ function createSecurityGuard(security) {
178
238
  };
179
239
  }
180
240
  return {
181
- admit(ctx, options = {}) {
182
- const decision = isLogin(ctx) ? rateLimiter.full(ctx.path, loginKeys(ctx)) : rateLimiter.check(ctx.ip, ctx.path);
241
+ admit(ctx, options2 = {}) {
242
+ const ip = clientIp(ctx);
243
+ const decision = isLogin(ctx) ? rateLimiter.full(ctx.path, [ip]) : isCheckout(ctx) ? checkCheckout(ctx, ip) : rateLimiter.check(ip, ctx.path, ctx.headers);
183
244
  if (decision && !decision.allowed) {
184
245
  return applyHeaders(rateLimitResponse(decision, ctx));
185
246
  }
186
- if (security.csrf && options.csrf !== false && UNSAFE_METHODS.has(ctx.method)) {
247
+ if (security.csrf && options2.csrf !== false && UNSAFE_METHODS.has(ctx.method)) {
187
248
  if (!verifyCsrf(ctx)) {
188
249
  ctx.logger.warn({ method: ctx.method, path: ctx.path }, "CSRF validation failed");
189
250
  return applyHeaders({
@@ -196,26 +257,30 @@ function createSecurityGuard(security) {
196
257
  },
197
258
  finish(ctx, envelope) {
198
259
  if (isLogin(ctx)) {
199
- const keys = loginKeys(ctx);
260
+ const account = loginAccount(ctx);
261
+ const accountKey = account === null ? [] : [`account:${account}`];
200
262
  if (envelope.status >= 200 && envelope.status < 300) {
201
- rateLimiter.clear(
202
- ctx.path,
203
- keys.filter((key) => key.startsWith("account:"))
204
- );
205
- } else rateLimiter.hit(ctx.path, keys);
206
- }
207
- const finished = applyHeaders(envelope);
208
- const setsCsrf = finished.cookies?.some((cookie) => cookie.name === CSRF_COOKIE) ?? false;
209
- if (security.csrf && !ctx.cookies[CSRF_COOKIE] && !setsCsrf) {
210
- finished.cookies = [...finished.cookies ?? [], csrfCookie(newToken())];
263
+ rateLimiter.clear(ctx.path, accountKey);
264
+ } else {
265
+ const [, failures] = rateLimiter.hit(ctx.path, [clientIp(ctx), ...accountKey]);
266
+ if (failures !== void 0 && failures === rateLimiter.requests(ctx.path)) {
267
+ ctx.logger.warn(
268
+ { account, failures, path: ctx.path },
269
+ "Failed logins for one account reached the login limit; it is not locked, each address is"
270
+ );
271
+ }
272
+ }
211
273
  }
212
- return finished;
274
+ return applyHeaders(envelope);
213
275
  },
214
276
  issueToken(ctx) {
215
277
  const existing = ctx.cookies[CSRF_COOKIE];
216
278
  if (existing) return { status: 200, body: { data: { token: existing } } };
217
279
  const token = newToken();
218
- return { status: 200, body: { data: { token } }, cookies: [csrfCookie(token)] };
280
+ return { status: 200, body: { data: { token } }, cookies: [csrfCookie(token, secureCookies2)] };
281
+ },
282
+ bucketCount() {
283
+ return rateLimiter.size;
219
284
  },
220
285
  reset() {
221
286
  rateLimiter.reset();
@@ -255,12 +320,43 @@ function rateLimitResponse(decision, ctx) {
255
320
  };
256
321
  }
257
322
 
323
+ // src/shopper-attestation.ts
324
+ import { createHmac, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2 } from "crypto";
325
+ function createShopperAttestation(key = randomBytes2(32), ttlMs = 6e4) {
326
+ const sign = (ip, expires) => {
327
+ const body = `${ip}~${expires}`;
328
+ return `${body}~${createHmac("sha256", key).update(body).digest("base64url")}`;
329
+ };
330
+ return {
331
+ mint(ip, now = Date.now()) {
332
+ return sign(ip, now + ttlMs);
333
+ },
334
+ verify(token, now = Date.now()) {
335
+ if (typeof token !== "string") return null;
336
+ const segments = token.split("~");
337
+ if (segments.length !== 3) return null;
338
+ const [ip, expiresText] = segments;
339
+ if (ip === "" || !/^\d+$/.test(expiresText)) return null;
340
+ const expires = Number(expiresText);
341
+ if (!Number.isSafeInteger(expires) || now >= expires) return null;
342
+ const expected = Buffer.from(sign(ip, expires));
343
+ const given = Buffer.from(token);
344
+ if (expected.length !== given.length || !timingSafeEqual2(expected, given)) return null;
345
+ return ip;
346
+ }
347
+ };
348
+ }
349
+
258
350
  // src/fastify-adapter.ts
259
351
  var STREAM_END_BOUND_MS = 500;
352
+ var UNLOCKED_ROUTES = /* @__PURE__ */ new Set(["/health", "/ready"]);
353
+ var isLoopback = proxyAddr.compile("loopback");
354
+ var digest = (value) => createHash2("sha256").update(value).digest();
260
355
  var FastifyHttpAdapter = class {
261
356
  #app;
262
357
  #logger;
263
358
  #guard;
359
+ #attestation = createShopperAttestation();
264
360
  #middlewares = [];
265
361
  #defaultHeaders = {};
266
362
  /** Ends each open stream for shutdown; a stream removes itself once its close callbacks have run. */
@@ -268,38 +364,93 @@ var FastifyHttpAdapter = class {
268
364
  #started = false;
269
365
  #stopping = false;
270
366
  #boundPort = 0;
367
+ /** Decides both Fastify's walk of X-Forwarded-For and whether the peer may speak for the client. */
368
+ #trusts;
369
+ /** Lower-cased, as Node keys request headers. */
370
+ #clientIpHeader;
371
+ clientIpRequiresLock;
372
+ /** Lower-cased, as Node keys request headers. */
373
+ #lockHeader;
374
+ #lockDigests;
375
+ /** Lower-cased: every header the secret may arrive in, removed from each request. */
376
+ #proofHeaders;
377
+ #warnedUnlistedPeer = false;
378
+ #warnedClientIpHeader = false;
379
+ #warnedOriginLocked = false;
271
380
  constructor(options) {
272
381
  this.#logger = options.logger;
273
- this.#guard = createSecurityGuard(options.security);
382
+ this.#trusts = proxyAddr.compile(options.trustedProxies ?? ["loopback"]);
383
+ this.#clientIpHeader = options.clientIpHeader?.toLowerCase();
384
+ this.clientIpRequiresLock = options.clientIpRequiresLock ?? false;
385
+ this.#lockHeader = options.originLock?.header.toLowerCase();
386
+ this.#lockDigests = (options.originLock?.secrets ?? []).map(digest);
387
+ this.#proofHeaders = [
388
+ ...new Set(
389
+ [options.originLockHeader?.toLowerCase(), this.#lockHeader].filter(
390
+ (h) => h !== void 0
391
+ )
392
+ )
393
+ ];
394
+ this.#guard = createSecurityGuard(options.security, {
395
+ attestation: this.#attestation,
396
+ secureCookies: options.secureCookies ?? false
397
+ });
274
398
  this.#app = Fastify({
275
399
  logger: false,
276
- trustProxy: options.trustProxy ?? false,
400
+ trustProxy: this.#trusts,
277
401
  disableRequestLogging: true,
278
402
  // Fastify's default takes `req.id` from an inbound `request-id` header, unvalidated; the id is always ours.
279
403
  requestIdHeader: false,
280
404
  genReqId: () => uuidv7()
281
405
  });
282
406
  this.#app.decorateRequest("correlationId", "");
283
- this.#app.addHook("onRequest", async (req) => {
407
+ this.#app.decorateRequest("clientIp", "");
408
+ this.#app.addHook("onRequest", async (req, reply) => {
284
409
  const inbound = req.headers[CORRELATION_ID_HEADER];
285
410
  if (typeof inbound === "string" && isValidCorrelationId(inbound)) req.correlationId = inbound;
286
411
  else req.correlationId = isValidCorrelationId(req.id) ? req.id : uuidv7();
412
+ const locked = this.#takeOriginProof(req);
413
+ if (!locked && this.#refusesUnlocked(req)) {
414
+ req.clientIp = req.raw.socket.remoteAddress ?? req.ip;
415
+ return this.#refuseOrigin(req, reply);
416
+ }
417
+ req.clientIp = this.#resolveClientIp(req, locked);
287
418
  });
288
419
  this.#app.addHook("onSend", async (req, reply, payload) => {
289
420
  reply.header(CORRELATION_ID_HEADER, req.correlationId);
421
+ if (req.url.startsWith("/api/") && !reply.hasHeader("cache-control")) {
422
+ reply.header("cache-control", "no-store");
423
+ }
290
424
  return payload;
291
425
  });
292
426
  const parseJson = this.#app.getDefaultJsonParser(
293
427
  this.#app.initialConfig.onProtoPoisoning ?? "error",
294
428
  this.#app.initialConfig.onConstructorPoisoning ?? "error"
295
429
  );
430
+ const takesRawBody = (req) => req.routeOptions.config?.routeOptions?.rawBody === true;
296
431
  this.#app.removeContentTypeParser("application/json");
297
432
  this.#app.addContentTypeParser("application/json", { parseAs: "buffer" }, (req, body, done) => {
298
433
  const buffer = body;
299
- const config = req.routeOptions.config;
300
- if (config?.routeOptions?.rawBody === true) req.rawBody = buffer;
434
+ if (takesRawBody(req)) req.rawBody = buffer;
301
435
  parseJson(req, buffer.toString("utf8"), done);
302
436
  });
437
+ const keepRawBody = (elsewhere) => (req, body, done) => {
438
+ const buffer = body;
439
+ if (takesRawBody(req)) req.rawBody = buffer;
440
+ else if (elsewhere === "refuse" && !req.is404) {
441
+ done(new errorCodes.FST_ERR_CTP_INVALID_MEDIA_TYPE(req.headers["content-type"]));
442
+ return;
443
+ }
444
+ done(null, buffer.toString("utf8"));
445
+ };
446
+ this.#app.removeContentTypeParser("text/plain");
447
+ this.#app.addContentTypeParser("text/plain", { parseAs: "buffer" }, keepRawBody("text"));
448
+ this.#app.addContentTypeParser(
449
+ "application/x-www-form-urlencoded",
450
+ { parseAs: "buffer" },
451
+ keepRawBody("refuse")
452
+ );
453
+ this.#app.addContentTypeParser("*", { parseAs: "buffer" }, keepRawBody("refuse"));
303
454
  this.#app.addHook("preClose", async () => {
304
455
  this.#stopping = true;
305
456
  for (const endStream of this.#openStreams) endStream();
@@ -319,6 +470,54 @@ var FastifyHttpAdapter = class {
319
470
  get boundPort() {
320
471
  return this.#boundPort;
321
472
  }
473
+ /**
474
+ * A token for `ip` that this adapter's guard, and no other, accepts in `x-nymbal-shopper` for the next minute: the
475
+ * storefront forward's proof of the shopper's address.
476
+ */
477
+ attestShopper(ip) {
478
+ return this.#attestation.mint(ip);
479
+ }
480
+ /** Fastify's `inject`: `remoteAddress` sets the socket peer, which a request from loopback cannot. */
481
+ inject(options) {
482
+ return this.#app.inject(options);
483
+ }
484
+ /** The guard every route passes, for a mounted handler that admits a request it serves on a route's behalf. */
485
+ get guard() {
486
+ return this.#guard;
487
+ }
488
+ /**
489
+ * A route whose handler answers a web-standard `Response` (the MCP endpoint's SDK), or an envelope when it refuses.
490
+ * It passes the guard and the middlewares as every route does.
491
+ */
492
+ registerWebRoute(method, path, handler, options) {
493
+ if (this.#started) {
494
+ throw new Error("Cannot register routes after the server has started");
495
+ }
496
+ this.#app.route({
497
+ method,
498
+ url: path,
499
+ handler: async (req, reply) => {
500
+ const ctx = this.#buildContext(req, false);
501
+ const refused = this.#guard.admit(ctx, options);
502
+ if (refused) return this.#applyEnvelope(reply, refused);
503
+ let answer;
504
+ try {
505
+ answer = await this.#runMiddlewaresThen(ctx, handler);
506
+ } catch (err) {
507
+ answer = this.#renderError(err, ctx);
508
+ }
509
+ if (!(answer instanceof Response)) {
510
+ return this.#applyEnvelope(reply, this.#guard.finish(ctx, answer));
511
+ }
512
+ const { headers } = this.#guard.finish(ctx, { status: answer.status });
513
+ for (const [name, value] of Object.entries({ ...this.#defaultHeaders, ...headers })) {
514
+ reply.header(name, value);
515
+ }
516
+ return reply.send(answer);
517
+ },
518
+ config: { routeOptions: options ?? {} }
519
+ });
520
+ }
322
521
  registerRoute(method, path, handler, options) {
323
522
  if (this.#started) {
324
523
  throw new Error("Cannot register routes after the server has started");
@@ -446,6 +645,13 @@ var FastifyHttpAdapter = class {
446
645
  config: { routeOptions: options ?? {} }
447
646
  });
448
647
  }
648
+ /** A Fastify plugin on this server, in a context of its own: how the storefront forward is added. */
649
+ registerPlugin(plugin) {
650
+ if (this.#started) {
651
+ throw new Error("Cannot register plugins after the server has started");
652
+ }
653
+ void this.#app.register(plugin);
654
+ }
449
655
  registerMiddleware(middleware) {
450
656
  if (this.#started) {
451
657
  throw new Error("Cannot register middleware after the server has started");
@@ -475,6 +681,87 @@ var FastifyHttpAdapter = class {
475
681
  }
476
682
  return handler(ctx);
477
683
  }
684
+ /**
685
+ * Whether the request carries one of the origin secrets, compared by digest against every entry. The header is
686
+ * removed whatever the outcome and with the lock off too, so no handler, log line or storefront forward sees it.
687
+ */
688
+ #takeOriginProof(req) {
689
+ const name = this.#lockHeader;
690
+ const sent = name === void 0 ? void 0 : req.headers[name];
691
+ for (const header of this.#proofHeaders) delete req.headers[header];
692
+ if (typeof sent !== "string") return false;
693
+ const given = digest(sent);
694
+ let matched = false;
695
+ for (const entry of this.#lockDigests) matched = timingSafeEqual3(given, entry) || matched;
696
+ return matched;
697
+ }
698
+ /** An unlocked request is refused unless the lock is off, it comes from this machine, or it is a health check. */
699
+ #refusesUnlocked(req) {
700
+ if (this.#lockHeader === void 0) return false;
701
+ const peer = req.raw.socket.remoteAddress;
702
+ if (peer !== void 0 && isLoopback(peer, 0)) return false;
703
+ return req.is404 || !UNLOCKED_ROUTES.has(req.routeOptions.url ?? "");
704
+ }
705
+ #refuseOrigin(req, reply) {
706
+ if (!this.#warnedOriginLocked) {
707
+ this.#warnedOriginLocked = true;
708
+ const peer = req.raw.socket.remoteAddress ?? req.ip;
709
+ const header = this.#lockHeader;
710
+ this.#requestLogger(req).warn(
711
+ { peer, header },
712
+ `A request from ${peer} without the origin secret in ${header} was refused: requests must cross the CDN. If the CDN does send it, check it holds an entry of NYMBAL_ORIGIN_SECRET (nymbal doctor); later refusals are not logged`
713
+ );
714
+ }
715
+ return this.#applyEnvelope(reply, {
716
+ status: 403,
717
+ body: {
718
+ error: {
719
+ code: "origin_locked",
720
+ message: "This API answers only requests that reach it through the store\u2019s CDN"
721
+ }
722
+ }
723
+ });
724
+ }
725
+ /**
726
+ * The one client address a request resolves to. An unlisted peer is the client, whatever it sends. From a listed peer,
727
+ * the client-address header when one is configured (a single IP address, else the peer), otherwise X-Forwarded-For
728
+ * walked by Fastify with the same list. A header that requires the lock counts on a locked request from any peer and
729
+ * is not read on any other.
730
+ */
731
+ #resolveClientIp(req, locked) {
732
+ const peer = req.raw.socket.remoteAddress;
733
+ if (peer === void 0) return req.ip;
734
+ const header = this.clientIpRequiresLock && !locked ? void 0 : this.#clientIpHeader;
735
+ const fromAnyPeer = this.clientIpRequiresLock && header !== void 0;
736
+ if (!fromAnyPeer && !this.#trusts(peer, 0)) {
737
+ const carried = req.headers["x-forwarded-for"] !== void 0 ? "x-forwarded-for" : header !== void 0 && req.headers[header] !== void 0 ? header : void 0;
738
+ if (carried !== void 0 && !this.#warnedUnlistedPeer) {
739
+ this.#warnedUnlistedPeer = true;
740
+ const suggested = trustSuggestion(peer);
741
+ this.#requestLogger(req).warn(
742
+ { peer, header: carried, variable: TRUSTED_PROXIES_ENV, suggested },
743
+ `${carried} from ${peer} is ignored: ${peer} is not a listed proxy, so it is the client address. If ${peer} is your proxy, set ${TRUSTED_PROXIES_ENV}=${suggested}`
744
+ );
745
+ }
746
+ return peer;
747
+ }
748
+ if (header === void 0) return req.ip;
749
+ const value = req.headers[header];
750
+ if (value === void 0) return peer;
751
+ if (typeof value === "string" && !value.includes(",") && isIP(value) !== 0) return value;
752
+ const reason = typeof value !== "string" || value.includes(",") ? "multiple" : "invalid";
753
+ if (!this.#warnedClientIpHeader) {
754
+ this.#warnedClientIpHeader = true;
755
+ this.#requestLogger(req).warn(
756
+ { peer, header, reason },
757
+ `${header} from ${peer} does not hold one IP address (${reason}), so the address is the peer; the proxy should set it to the client's address alone`
758
+ );
759
+ }
760
+ return peer;
761
+ }
762
+ #requestLogger(req) {
763
+ return this.#logger.child({ requestId: req.id, correlationId: req.correlationId });
764
+ }
478
765
  #buildContext(req, includeRawBody) {
479
766
  const { correlationId } = req;
480
767
  const logger = this.#logger.child({ requestId: req.id, correlationId });
@@ -490,7 +777,7 @@ var FastifyHttpAdapter = class {
490
777
  requestId: req.id,
491
778
  correlationId,
492
779
  logger,
493
- ip: req.ip
780
+ ip: req.clientIp
494
781
  };
495
782
  if (includeRawBody && Buffer.isBuffer(req.rawBody)) {
496
783
  ctx.rawBody = req.rawBody;
@@ -548,6 +835,12 @@ var FastifyHttpAdapter = class {
548
835
  }
549
836
  };
550
837
 
838
+ // src/index.ts
839
+ import { SHOPPER_ATTESTATION_HEADER as SHOPPER_ATTESTATION_HEADER3 } from "@nymbalhq/types";
840
+
841
+ // src/server.ts
842
+ import { secureCookies } from "@nymbalhq/config";
843
+
551
844
  // src/routes/health.ts
552
845
  function createHealthRoute(version) {
553
846
  return () => ({
@@ -579,7 +872,7 @@ function createProductsRoute(documentStore, storeId) {
579
872
 
580
873
  // src/server.ts
581
874
  function createHttpServer(deps) {
582
- const { config, logger, documentStore, version } = deps;
875
+ const { config, logger, documentStore, version, network } = deps;
583
876
  if (config.http.adapter !== "fastify") {
584
877
  throw new Error(`Unsupported http.adapter: ${config.http.adapter}`);
585
878
  }
@@ -587,7 +880,12 @@ function createHttpServer(deps) {
587
880
  logger,
588
881
  cors: config.http.cors,
589
882
  security: config.security,
590
- trustProxy: config.http.trustProxy
883
+ trustedProxies: network.trustedProxies,
884
+ ...network.clientIpHeader !== void 0 && { clientIpHeader: network.clientIpHeader },
885
+ clientIpRequiresLock: network.clientIpRequiresLock,
886
+ ...network.originLock !== void 0 && { originLock: network.originLock },
887
+ originLockHeader: config.security.originLock.header,
888
+ secureCookies: secureCookies(config, process.env)
591
889
  });
592
890
  const server = {
593
891
  adapter,
@@ -611,15 +909,378 @@ function createHttpServer(deps) {
611
909
  void config;
612
910
  return server;
613
911
  }
912
+
913
+ // src/routes/ready.ts
914
+ function createReadyRoute(probe) {
915
+ return async () => {
916
+ const state = await probe();
917
+ return state.ready ? { status: 200, body: { status: "ready" } } : { status: 503, body: { status: "not-ready", failing: state.failing } };
918
+ };
919
+ }
920
+
921
+ // src/storefront-forward.ts
922
+ import httpProxy from "@fastify/http-proxy";
923
+ import { securitySchema } from "@nymbalhq/config";
924
+ import { SHOPPER_ATTESTATION_HEADER as SHOPPER_ATTESTATION_HEADER2 } from "@nymbalhq/types";
925
+ function pageHeaders(origin, {
926
+ hsts,
927
+ referrerPolicy,
928
+ xFrameOptions
929
+ } = securitySchema.parse({
930
+ adapter: "middleware"
931
+ }).headers) {
932
+ return {
933
+ ...hsts && origin.protocol === "https:" && {
934
+ "strict-transport-security": "max-age=31536000; includeSubDomains"
935
+ },
936
+ "content-security-policy": "frame-ancestors 'none'; object-src 'none'; base-uri 'self'",
937
+ "x-content-type-options": "nosniff",
938
+ "x-frame-options": xFrameOptions === "deny" ? "DENY" : "SAMEORIGIN",
939
+ "referrer-policy": referrerPolicy
940
+ };
941
+ }
942
+ var FORWARDED_METHODS = ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"];
943
+ function forwardToStorefront(adapter, options) {
944
+ const origin = new URL(options.publicUrl);
945
+ const proto = origin.protocol.slice(0, -1);
946
+ const filled = pageHeaders(origin, options.headers);
947
+ let inFlight = 0;
948
+ let refusing = false;
949
+ const waiters = /* @__PURE__ */ new Set();
950
+ const settle = () => {
951
+ inFlight -= 1;
952
+ if (inFlight === 0) for (const wake of [...waiters]) wake();
953
+ };
954
+ adapter.registerPlugin(async (api) => {
955
+ api.removeAllContentTypeParsers();
956
+ api.addContentTypeParser("*", (_req, payload, done) => done(null, payload));
957
+ api.route({
958
+ method: FORWARDED_METHODS,
959
+ url: "/api/*",
960
+ handler: (_req, reply) => reply.callNotFound()
961
+ });
962
+ });
963
+ adapter.registerPlugin(async (pages) => {
964
+ pages.removeAllContentTypeParsers();
965
+ await pages.register(httpProxy, {
966
+ upstream: `http://127.0.0.1:${options.port}`,
967
+ httpMethods: FORWARDED_METHODS,
968
+ internalRewriteLocationHeader: false,
969
+ preHandler: (_req, reply, done) => {
970
+ if (refusing) {
971
+ void reply.code(503).header("connection", "close").send({ error: { code: "unavailable", message: "The store is shutting down" } });
972
+ return;
973
+ }
974
+ inFlight += 1;
975
+ reply.raw.once("close", settle);
976
+ done();
977
+ },
978
+ replyOptions: {
979
+ rewriteRequestHeaders: (req, headers) => {
980
+ const prior = req.headers["x-forwarded-for"];
981
+ const peer = req.raw.socket.remoteAddress ?? req.ip;
982
+ return {
983
+ ...headers,
984
+ host: origin.host,
985
+ "x-forwarded-host": origin.host,
986
+ "x-forwarded-proto": proto,
987
+ "x-forwarded-for": [prior, peer].flat().filter(Boolean).join(", "),
988
+ // Replaces whatever the client sent: only this API's own attestation of the address it resolved.
989
+ [SHOPPER_ATTESTATION_HEADER2]: adapter.attestShopper(req.clientIp)
990
+ };
991
+ },
992
+ rewriteHeaders: (headers) => ({ ...filled, ...headers }),
993
+ // A forward is never retried: a page POST may not be idempotent, and a 503 is the storefront's answer.
994
+ retryDelay: () => null,
995
+ onError: (reply) => {
996
+ void reply.code(503).send({ error: { code: "unavailable", message: "The storefront is not answering" } });
997
+ }
998
+ }
999
+ });
1000
+ });
1001
+ return {
1002
+ inFlight: () => inFlight,
1003
+ refuse() {
1004
+ refusing = true;
1005
+ },
1006
+ drained(timeoutMs) {
1007
+ if (inFlight === 0) return Promise.resolve(true);
1008
+ return new Promise((resolve) => {
1009
+ const finish = (value) => {
1010
+ clearTimeout(timer);
1011
+ waiters.delete(wake);
1012
+ resolve(value);
1013
+ };
1014
+ const wake = () => finish(true);
1015
+ const timer = setTimeout(() => finish(false), timeoutMs);
1016
+ waiters.add(wake);
1017
+ });
1018
+ }
1019
+ };
1020
+ }
1021
+
1022
+ // src/mcp-route.ts
1023
+ import {
1024
+ CLIENT_INFO_META_KEY,
1025
+ Server,
1026
+ createMcpHandler
1027
+ } from "@modelcontextprotocol/server";
1028
+ var MCP_PATH = "/api/mcp";
1029
+ function refuse(status, code, message, headers = {}) {
1030
+ return { status, headers, body: { error: { code, message } } };
1031
+ }
1032
+ function textResult(structured) {
1033
+ return {
1034
+ content: [{ type: "text", text: JSON.stringify(structured) }],
1035
+ structuredContent: structured,
1036
+ isError: true
1037
+ };
1038
+ }
1039
+ function bearerOf(ctx) {
1040
+ const raw = ctx.headers.authorization;
1041
+ const header = Array.isArray(raw) ? raw[0] : raw;
1042
+ if (header === void 0 || !header.toLowerCase().startsWith("bearer ")) return void 0;
1043
+ return header.slice("bearer ".length).trim();
1044
+ }
1045
+ function agentOf(envelope, server) {
1046
+ const meta = envelope;
1047
+ const info = meta?.[CLIENT_INFO_META_KEY] ?? server.getClientVersion();
1048
+ return {
1049
+ name: typeof info?.name === "string" ? info.name : "mcp-client",
1050
+ ...typeof info?.version === "string" && { version: info.version }
1051
+ };
1052
+ }
1053
+ function toolServer(surface, state, version) {
1054
+ const server = new Server({ name: "nymbal", version }, { capabilities: { tools: {} } });
1055
+ const caller = (agent) => ({
1056
+ ...state.auth !== void 0 && { auth: state.auth },
1057
+ agent,
1058
+ ip: state.ip
1059
+ });
1060
+ server.setRequestHandler("tools/list", (_request, ctx) => ({
1061
+ tools: surface.list(caller(agentOf(ctx.mcpReq.envelope, server))).map((tool) => ({
1062
+ name: tool.name,
1063
+ title: tool.title,
1064
+ description: tool.description,
1065
+ // Converted from the route's Zod schema, so every keyword's value is JSON.
1066
+ inputSchema: tool.inputSchema,
1067
+ annotations: { readOnlyHint: tool.kind === "read" }
1068
+ }))
1069
+ }));
1070
+ server.setRequestHandler("tools/call", async (request, ctx) => {
1071
+ const who = caller(agentOf(ctx.mcpReq.envelope, server));
1072
+ const tool = surface.list(who).find((listed) => listed.name === request.params.name);
1073
+ const result = (tool && state.admit(tool)) ?? await surface.call(request.params.name, request.params.arguments ?? {}, who);
1074
+ return server.projectCallToolResult({ ...result }, void 0);
1075
+ });
1076
+ return server;
1077
+ }
1078
+ async function mountToolEndpoint(server, deps) {
1079
+ const { surface } = deps;
1080
+ const adapter = server.adapter;
1081
+ const handler = createMcpHandler(({ authInfo }) => {
1082
+ const state = authInfo?.extra?.["nymbal"];
1083
+ return toolServer(surface, state, deps.version ?? "0.0.0");
1084
+ });
1085
+ const origins = new Set(deps.origins);
1086
+ const serve = async (ctx) => {
1087
+ const origin = ctx.headers.origin;
1088
+ if (typeof origin === "string" && !origins.has(origin)) {
1089
+ return refuse(
1090
+ 403,
1091
+ "origin.forbidden",
1092
+ `Origin ${origin} may not call this store's agent endpoint`
1093
+ );
1094
+ }
1095
+ const token = bearerOf(ctx);
1096
+ let auth;
1097
+ if (token !== void 0) {
1098
+ try {
1099
+ const payload = await deps.verify(token);
1100
+ auth = { userId: payload.sub, roles: [...payload.roles ?? []] };
1101
+ } catch {
1102
+ return refuse(401, "auth.unauthorized", "The bearer token does not verify", {
1103
+ "www-authenticate": 'Bearer error="invalid_token"'
1104
+ });
1105
+ }
1106
+ }
1107
+ const state = {
1108
+ auth,
1109
+ ip: ctx.ip,
1110
+ admit(tool) {
1111
+ if (!deps.admitTools) return null;
1112
+ const refused = adapter.guard.admit(
1113
+ {
1114
+ ...ctx,
1115
+ method: tool.route.method,
1116
+ path: tool.route.path,
1117
+ headers: {},
1118
+ body: void 0
1119
+ },
1120
+ { csrf: false }
1121
+ );
1122
+ if (refused === null) return null;
1123
+ const error = refused.body?.error;
1124
+ return textResult({
1125
+ code: "rate.limited",
1126
+ message: `Too many ${tool.name} calls`,
1127
+ ...error?.retryAfter !== void 0 && { retryAfter: error.retryAfter }
1128
+ });
1129
+ }
1130
+ };
1131
+ const headers = new Headers();
1132
+ for (const [name, value] of Object.entries(ctx.headers)) {
1133
+ if (value === void 0 || name === "authorization" || name === "cookie") continue;
1134
+ for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one);
1135
+ }
1136
+ const host = typeof ctx.headers.host === "string" ? ctx.headers.host : "localhost";
1137
+ const request = new Request(new URL(ctx.url, `http://${host}`), { method: ctx.method, headers });
1138
+ const authInfo = {
1139
+ token: "",
1140
+ clientId: auth?.userId ?? "anonymous",
1141
+ scopes: auth?.roles ?? [],
1142
+ extra: { nymbal: state }
1143
+ };
1144
+ return handler.fetch(request, {
1145
+ authInfo,
1146
+ ...ctx.method === "POST" && { parsedBody: ctx.body }
1147
+ });
1148
+ };
1149
+ for (const method of ["POST", "GET", "DELETE"]) {
1150
+ adapter.registerWebRoute(method, deps.path, serve, { csrf: false });
1151
+ }
1152
+ }
1153
+ async function mountMcp(server, deps) {
1154
+ if (!deps.enabled) return;
1155
+ const surface = deps.app.mcp;
1156
+ if (surface === void 0) {
1157
+ throw new Error("mountMcp needs the tool surface attachHttp builds: call attachHttp first");
1158
+ }
1159
+ await mountToolEndpoint(server, {
1160
+ path: MCP_PATH,
1161
+ surface,
1162
+ verify: deps.verify,
1163
+ origins: deps.origins,
1164
+ admitTools: true,
1165
+ ...deps.version !== void 0 && { version: deps.version }
1166
+ });
1167
+ }
1168
+
1169
+ // src/agent-surface.ts
1170
+ var UCP_MCP_PATH = "/api/ucp/mcp";
1171
+ var HANDOFF_PATH = "/api/agents/checkout/:token";
1172
+ var FEED_PATH = "/agents/products.json";
1173
+ var CART_COOKIE2 = "nymbal.cart";
1174
+ var CACHE = { "cache-control": "public, max-age=300" };
1175
+ var TEXT = { ...CACHE, "content-type": "text/plain; charset=utf-8" };
1176
+ var notFound = {
1177
+ status: 404,
1178
+ body: { error: { code: "not_found", message: "This store does not serve this file" } }
1179
+ };
1180
+ function cartCookie(token) {
1181
+ return {
1182
+ name: CART_COOKIE2,
1183
+ value: token,
1184
+ path: "/",
1185
+ httpOnly: true,
1186
+ sameSite: "lax",
1187
+ secure: process.env.NODE_ENV === "production",
1188
+ maxAge: 60 * 60 * 24 * 30
1189
+ };
1190
+ }
1191
+ function queryValue(value) {
1192
+ return Array.isArray(value) ? value[0] : value;
1193
+ }
1194
+ async function mountAgentSurfaces(server, deps) {
1195
+ const agents = deps.app.agents;
1196
+ if (agents === void 0) {
1197
+ throw new Error(
1198
+ "mountAgentSurfaces needs the agent surfaces attachHttp builds: call attachHttp first"
1199
+ );
1200
+ }
1201
+ const { adapter } = server;
1202
+ agents.useUrls(deps.urls);
1203
+ for (const surface of agents.surfaces) {
1204
+ const { wellKnown, endpoint, routes = [] } = surface;
1205
+ if (wellKnown !== void 0) {
1206
+ adapter.registerRoute("GET", wellKnown.path, async () => ({
1207
+ status: 200,
1208
+ headers: CACHE,
1209
+ body: wellKnown.document(deps.urls())
1210
+ }));
1211
+ }
1212
+ if (endpoint !== void 0) {
1213
+ await mountToolEndpoint(server, {
1214
+ path: endpoint.path,
1215
+ surface: endpoint.tools,
1216
+ verify: deps.verify,
1217
+ origins: deps.origins,
1218
+ admitTools: false,
1219
+ ...deps.version !== void 0 && { version: deps.version }
1220
+ });
1221
+ }
1222
+ for (const route of routes) {
1223
+ adapter.registerRoute(
1224
+ route.method,
1225
+ route.path,
1226
+ (ctx) => route.handle({
1227
+ params: ctx.params,
1228
+ query: ctx.query,
1229
+ headers: ctx.headers,
1230
+ body: ctx.body,
1231
+ ip: ctx.ip,
1232
+ requestId: ctx.requestId
1233
+ }),
1234
+ { csrf: false }
1235
+ );
1236
+ }
1237
+ }
1238
+ adapter.registerRoute("GET", "/robots.txt", async () => {
1239
+ const body = agents.robots(deps.urls());
1240
+ return body === null ? notFound : { status: 200, headers: TEXT, body };
1241
+ });
1242
+ adapter.registerRoute("GET", "/llms.txt", async () => {
1243
+ const body = await agents.llms(deps.urls());
1244
+ return body === null ? notFound : { status: 200, headers: TEXT, body };
1245
+ });
1246
+ adapter.registerRoute("GET", FEED_PATH, async (ctx) => {
1247
+ const page = await agents.feed(deps.urls(), queryValue(ctx.query.cursor));
1248
+ if (page === null) return notFound;
1249
+ const failed = page["ucp"]?.status === "error";
1250
+ return failed ? { status: 400, body: page } : { status: 200, headers: CACHE, body: page };
1251
+ });
1252
+ adapter.registerRoute("GET", HANDOFF_PATH, async (ctx) => {
1253
+ const token = ctx.params.token ?? "";
1254
+ const live = token !== "" && await agents.handoff(token);
1255
+ const storefront = deps.urls().storefront ?? "";
1256
+ return {
1257
+ status: 303,
1258
+ headers: { location: `${storefront}${live ? "/checkout" : "/cart"}` },
1259
+ ...live && { cookies: [cartCookie(token)] }
1260
+ };
1261
+ });
1262
+ }
614
1263
  export {
1264
+ CHECKOUT_ADDRESS_CEILING,
615
1265
  CSRF_COOKIE,
616
1266
  CSRF_HEADER,
1267
+ FEED_PATH,
617
1268
  FastifyHttpAdapter,
1269
+ HANDOFF_PATH,
1270
+ MCP_PATH,
618
1271
  RateLimiter,
1272
+ SHOPPER_ATTESTATION_HEADER3 as SHOPPER_ATTESTATION_HEADER,
1273
+ UCP_MCP_PATH,
619
1274
  buildSecurityHeaders,
620
1275
  createHealthRoute,
621
1276
  createHttpServer,
622
1277
  createProductsRoute,
623
- createSecurityGuard
1278
+ createReadyRoute,
1279
+ createSecurityGuard,
1280
+ createShopperAttestation,
1281
+ forwardToStorefront,
1282
+ mountAgentSurfaces,
1283
+ mountMcp,
1284
+ mountToolEndpoint
624
1285
  };
625
1286
  //# sourceMappingURL=index.js.map