@nymbalhq/http 1.5.0 → 1.7.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/LICENSE +21 -0
- package/README.md +6 -0
- package/dist/index.d.ts +176 -35
- package/dist/index.js +576 -59
- package/dist/index.js.map +1 -1
- package/package.json +12 -9
package/dist/index.js
CHANGED
|
@@ -2,8 +2,11 @@
|
|
|
2
2
|
import Fastify, {
|
|
3
3
|
errorCodes
|
|
4
4
|
} from "fastify";
|
|
5
|
+
import { createHash as createHash2, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
6
|
+
import { isIP } from "net";
|
|
5
7
|
import fastifyCookie from "@fastify/cookie";
|
|
6
8
|
import fastifyCors from "@fastify/cors";
|
|
9
|
+
import proxyAddr from "@fastify/proxy-addr";
|
|
7
10
|
import { v7 as uuidv7 } from "uuid";
|
|
8
11
|
import {
|
|
9
12
|
CORRELATION_ID_HEADER,
|
|
@@ -12,9 +15,13 @@ import {
|
|
|
12
15
|
isValidCorrelationId,
|
|
13
16
|
NymbalError
|
|
14
17
|
} from "@nymbalhq/types";
|
|
18
|
+
import { TRUSTED_PROXIES_ENV, trustSuggestion } from "@nymbalhq/config";
|
|
15
19
|
|
|
16
20
|
// src/security-middleware.ts
|
|
17
|
-
import { randomBytes, timingSafeEqual } from "crypto";
|
|
21
|
+
import { createHash, randomBytes, timingSafeEqual } from "crypto";
|
|
22
|
+
import {
|
|
23
|
+
SHOPPER_ATTESTATION_HEADER
|
|
24
|
+
} from "@nymbalhq/types";
|
|
18
25
|
|
|
19
26
|
// src/rate-limit.ts
|
|
20
27
|
import { ORDER_EMAIL_HEADER } from "@nymbalhq/types";
|
|
@@ -25,15 +32,24 @@ var BUILT_IN_RATE_LIMITS = {
|
|
|
25
32
|
"/api/recently-viewed": { requests: 600, window: "1m", action: "block" },
|
|
26
33
|
// Each accepted subscribe mails a confirmation: the bound on how much mail one IP can make the store send.
|
|
27
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" },
|
|
28
37
|
// Each match mails the order's link. Before the order-read rule, which a request carrying the email would also match.
|
|
29
38
|
"/api/orders/link": { requests: 5, window: "1h", action: "block" },
|
|
30
39
|
// The email is the second factor of an expired order key: bounded so it cannot be guessed. The key-only poll of a
|
|
31
40
|
// pending order carries no email and is never counted.
|
|
32
41
|
"/api/orders/*": { requests: 10, window: "1h", action: "block", header: ORDER_EMAIL_HEADER },
|
|
33
42
|
// Every checkout answer can mint an order key.
|
|
34
|
-
"/api/checkout": { requests: 30, window: "1m", action: "block" }
|
|
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" }
|
|
35
50
|
};
|
|
36
51
|
var PRUNE_THRESHOLD = 1024;
|
|
52
|
+
var CHECKOUT_ADDRESS_CEILING = 10;
|
|
37
53
|
var RateLimiter = class {
|
|
38
54
|
#rules;
|
|
39
55
|
#buckets = /* @__PURE__ */ new Map();
|
|
@@ -48,25 +64,26 @@ var RateLimiter = class {
|
|
|
48
64
|
action: rule.action
|
|
49
65
|
}));
|
|
50
66
|
}
|
|
51
|
-
|
|
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) {
|
|
52
69
|
const rule = this.#ruleFor(path, headers);
|
|
53
70
|
if (!rule) return null;
|
|
54
|
-
const
|
|
71
|
+
const bucketKey = `${rule.pattern}|${key}`;
|
|
55
72
|
const now = Date.now();
|
|
56
|
-
const bucket = this.#buckets.get(
|
|
73
|
+
const bucket = this.#buckets.get(bucketKey);
|
|
57
74
|
if (!bucket || bucket.resetAt <= now) {
|
|
58
|
-
this.#open(
|
|
75
|
+
this.#open(bucketKey, now, rule.windowMs);
|
|
59
76
|
return { allowed: true, action: rule.action };
|
|
60
77
|
}
|
|
61
78
|
bucket.count += 1;
|
|
62
|
-
if (bucket.count > rule.requests) {
|
|
79
|
+
if (bucket.count > rule.requests * scale) {
|
|
63
80
|
return { allowed: false, action: rule.action, retryAfter: retryAfter(bucket, now) };
|
|
64
81
|
}
|
|
65
82
|
return { allowed: true, action: rule.action };
|
|
66
83
|
}
|
|
67
84
|
/**
|
|
68
|
-
* For a route that counts failures only: refuses when any of `keys`
|
|
69
|
-
*
|
|
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.
|
|
70
87
|
*/
|
|
71
88
|
full(path, keys) {
|
|
72
89
|
const rule = this.#ruleFor(path);
|
|
@@ -80,19 +97,29 @@ var RateLimiter = class {
|
|
|
80
97
|
}
|
|
81
98
|
return { allowed: true, action: rule.action };
|
|
82
99
|
}
|
|
100
|
+
/** Counts one under each of `keys`; returns each bucket's count after it, in the order of `keys`. */
|
|
83
101
|
hit(path, keys) {
|
|
84
102
|
const rule = this.#ruleFor(path);
|
|
85
|
-
if (!rule) return;
|
|
103
|
+
if (!rule) return [];
|
|
86
104
|
const now = Date.now();
|
|
87
|
-
|
|
105
|
+
return keys.map((key) => {
|
|
88
106
|
const bucketKey = `${rule.pattern}|${key}`;
|
|
89
107
|
const bucket = this.#buckets.get(bucketKey);
|
|
90
108
|
if (!bucket || bucket.resetAt <= now) {
|
|
91
109
|
this.#open(bucketKey, now, rule.windowMs);
|
|
92
|
-
|
|
93
|
-
bucket.count += 1;
|
|
110
|
+
return 1;
|
|
94
111
|
}
|
|
95
|
-
|
|
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;
|
|
96
123
|
}
|
|
97
124
|
clear(path, keys) {
|
|
98
125
|
const rule = this.#ruleFor(path);
|
|
@@ -164,25 +191,45 @@ function buildSecurityHeaders(security) {
|
|
|
164
191
|
return headers;
|
|
165
192
|
}
|
|
166
193
|
var LOGIN_PATH = "/api/auth/login";
|
|
167
|
-
|
|
194
|
+
var CHECKOUT_PATH = "/api/checkout";
|
|
195
|
+
var CART_COOKIE = "nymbal.cart";
|
|
196
|
+
function csrfCookie(token, secure) {
|
|
168
197
|
return {
|
|
169
198
|
name: CSRF_COOKIE,
|
|
170
199
|
value: token,
|
|
171
200
|
path: "/",
|
|
172
201
|
httpOnly: false,
|
|
173
202
|
sameSite: "lax",
|
|
174
|
-
secure
|
|
203
|
+
secure
|
|
175
204
|
};
|
|
176
205
|
}
|
|
177
|
-
function
|
|
206
|
+
function loginAccount(ctx) {
|
|
178
207
|
const email = ctx.body?.email;
|
|
179
|
-
return typeof email === "string" && email !== "" ?
|
|
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 };
|
|
180
214
|
}
|
|
181
215
|
function isLogin(ctx) {
|
|
182
216
|
return ctx.method === "POST" && ctx.path === LOGIN_PATH;
|
|
183
217
|
}
|
|
184
|
-
function
|
|
218
|
+
function isCheckout(ctx) {
|
|
219
|
+
return ctx.method === "POST" && ctx.path === CHECKOUT_PATH;
|
|
220
|
+
}
|
|
221
|
+
function createSecurityGuard(security, options = {}) {
|
|
185
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
|
+
}
|
|
186
233
|
const baseHeaders = buildSecurityHeaders(security);
|
|
187
234
|
function applyHeaders(envelope) {
|
|
188
235
|
return {
|
|
@@ -191,12 +238,13 @@ function createSecurityGuard(security) {
|
|
|
191
238
|
};
|
|
192
239
|
}
|
|
193
240
|
return {
|
|
194
|
-
admit(ctx,
|
|
195
|
-
const
|
|
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);
|
|
196
244
|
if (decision && !decision.allowed) {
|
|
197
245
|
return applyHeaders(rateLimitResponse(decision, ctx));
|
|
198
246
|
}
|
|
199
|
-
if (security.csrf &&
|
|
247
|
+
if (security.csrf && options2.csrf !== false && UNSAFE_METHODS.has(ctx.method)) {
|
|
200
248
|
if (!verifyCsrf(ctx)) {
|
|
201
249
|
ctx.logger.warn({ method: ctx.method, path: ctx.path }, "CSRF validation failed");
|
|
202
250
|
return applyHeaders({
|
|
@@ -209,26 +257,30 @@ function createSecurityGuard(security) {
|
|
|
209
257
|
},
|
|
210
258
|
finish(ctx, envelope) {
|
|
211
259
|
if (isLogin(ctx)) {
|
|
212
|
-
const
|
|
260
|
+
const account = loginAccount(ctx);
|
|
261
|
+
const accountKey = account === null ? [] : [`account:${account}`];
|
|
213
262
|
if (envelope.status >= 200 && envelope.status < 300) {
|
|
214
|
-
rateLimiter.clear(
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
)
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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
|
+
}
|
|
224
273
|
}
|
|
225
|
-
return
|
|
274
|
+
return applyHeaders(envelope);
|
|
226
275
|
},
|
|
227
276
|
issueToken(ctx) {
|
|
228
277
|
const existing = ctx.cookies[CSRF_COOKIE];
|
|
229
278
|
if (existing) return { status: 200, body: { data: { token: existing } } };
|
|
230
279
|
const token = newToken();
|
|
231
|
-
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;
|
|
232
284
|
},
|
|
233
285
|
reset() {
|
|
234
286
|
rateLimiter.reset();
|
|
@@ -268,12 +320,43 @@ function rateLimitResponse(decision, ctx) {
|
|
|
268
320
|
};
|
|
269
321
|
}
|
|
270
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
|
+
|
|
271
350
|
// src/fastify-adapter.ts
|
|
272
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();
|
|
273
355
|
var FastifyHttpAdapter = class {
|
|
274
356
|
#app;
|
|
275
357
|
#logger;
|
|
276
358
|
#guard;
|
|
359
|
+
#attestation = createShopperAttestation();
|
|
277
360
|
#middlewares = [];
|
|
278
361
|
#defaultHeaders = {};
|
|
279
362
|
/** Ends each open stream for shutdown; a stream removes itself once its close callbacks have run. */
|
|
@@ -281,25 +364,63 @@ var FastifyHttpAdapter = class {
|
|
|
281
364
|
#started = false;
|
|
282
365
|
#stopping = false;
|
|
283
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;
|
|
284
380
|
constructor(options) {
|
|
285
381
|
this.#logger = options.logger;
|
|
286
|
-
this.#
|
|
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
|
+
});
|
|
287
398
|
this.#app = Fastify({
|
|
288
399
|
logger: false,
|
|
289
|
-
trustProxy:
|
|
400
|
+
trustProxy: this.#trusts,
|
|
290
401
|
disableRequestLogging: true,
|
|
291
402
|
// Fastify's default takes `req.id` from an inbound `request-id` header, unvalidated; the id is always ours.
|
|
292
403
|
requestIdHeader: false,
|
|
293
404
|
genReqId: () => uuidv7()
|
|
294
405
|
});
|
|
295
406
|
this.#app.decorateRequest("correlationId", "");
|
|
296
|
-
this.#app.
|
|
407
|
+
this.#app.decorateRequest("clientIp", "");
|
|
408
|
+
this.#app.addHook("onRequest", async (req, reply) => {
|
|
297
409
|
const inbound = req.headers[CORRELATION_ID_HEADER];
|
|
298
410
|
if (typeof inbound === "string" && isValidCorrelationId(inbound)) req.correlationId = inbound;
|
|
299
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);
|
|
300
418
|
});
|
|
301
419
|
this.#app.addHook("onSend", async (req, reply, payload) => {
|
|
302
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
|
+
}
|
|
303
424
|
return payload;
|
|
304
425
|
});
|
|
305
426
|
const parseJson = this.#app.getDefaultJsonParser(
|
|
@@ -349,6 +470,54 @@ var FastifyHttpAdapter = class {
|
|
|
349
470
|
get boundPort() {
|
|
350
471
|
return this.#boundPort;
|
|
351
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
|
+
}
|
|
352
521
|
registerRoute(method, path, handler, options) {
|
|
353
522
|
if (this.#started) {
|
|
354
523
|
throw new Error("Cannot register routes after the server has started");
|
|
@@ -512,6 +681,87 @@ var FastifyHttpAdapter = class {
|
|
|
512
681
|
}
|
|
513
682
|
return handler(ctx);
|
|
514
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
|
+
}
|
|
515
765
|
#buildContext(req, includeRawBody) {
|
|
516
766
|
const { correlationId } = req;
|
|
517
767
|
const logger = this.#logger.child({ requestId: req.id, correlationId });
|
|
@@ -527,7 +777,7 @@ var FastifyHttpAdapter = class {
|
|
|
527
777
|
requestId: req.id,
|
|
528
778
|
correlationId,
|
|
529
779
|
logger,
|
|
530
|
-
ip: req.
|
|
780
|
+
ip: req.clientIp
|
|
531
781
|
};
|
|
532
782
|
if (includeRawBody && Buffer.isBuffer(req.rawBody)) {
|
|
533
783
|
ctx.rawBody = req.rawBody;
|
|
@@ -585,10 +835,11 @@ var FastifyHttpAdapter = class {
|
|
|
585
835
|
}
|
|
586
836
|
};
|
|
587
837
|
|
|
838
|
+
// src/index.ts
|
|
839
|
+
import { SHOPPER_ATTESTATION_HEADER as SHOPPER_ATTESTATION_HEADER3 } from "@nymbalhq/types";
|
|
840
|
+
|
|
588
841
|
// src/server.ts
|
|
589
|
-
import {
|
|
590
|
-
ConfigError
|
|
591
|
-
} from "@nymbalhq/types";
|
|
842
|
+
import { secureCookies } from "@nymbalhq/config";
|
|
592
843
|
|
|
593
844
|
// src/routes/health.ts
|
|
594
845
|
function createHealthRoute(version) {
|
|
@@ -620,21 +871,8 @@ function createProductsRoute(documentStore, storeId) {
|
|
|
620
871
|
}
|
|
621
872
|
|
|
622
873
|
// src/server.ts
|
|
623
|
-
var TRUST_PROXY_HOPS_ENV = "NYMBAL_TRUST_PROXY_HOPS";
|
|
624
|
-
function resolveTrustProxy(config, env) {
|
|
625
|
-
const raw = env[TRUST_PROXY_HOPS_ENV];
|
|
626
|
-
const hops = raw === void 0 ? void 0 : /^\d+$/.test(raw.trim()) ? Number(raw) : NaN;
|
|
627
|
-
if (hops !== void 0 && !Number.isSafeInteger(hops)) {
|
|
628
|
-
throw new ConfigError(`${TRUST_PROXY_HOPS_ENV} must be a whole number of proxy hops, 0 or more`, {
|
|
629
|
-
code: "config.trust_proxy_hops_invalid",
|
|
630
|
-
context: { variable: TRUST_PROXY_HOPS_ENV }
|
|
631
|
-
});
|
|
632
|
-
}
|
|
633
|
-
const configured = config.http.trustProxy;
|
|
634
|
-
return configured === false && hops !== void 0 ? hops : configured;
|
|
635
|
-
}
|
|
636
874
|
function createHttpServer(deps) {
|
|
637
|
-
const { config, logger, documentStore, version } = deps;
|
|
875
|
+
const { config, logger, documentStore, version, network } = deps;
|
|
638
876
|
if (config.http.adapter !== "fastify") {
|
|
639
877
|
throw new Error(`Unsupported http.adapter: ${config.http.adapter}`);
|
|
640
878
|
}
|
|
@@ -642,7 +880,12 @@ function createHttpServer(deps) {
|
|
|
642
880
|
logger,
|
|
643
881
|
cors: config.http.cors,
|
|
644
882
|
security: config.security,
|
|
645
|
-
|
|
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)
|
|
646
889
|
});
|
|
647
890
|
const server = {
|
|
648
891
|
adapter,
|
|
@@ -677,10 +920,30 @@ function createReadyRoute(probe) {
|
|
|
677
920
|
|
|
678
921
|
// src/storefront-forward.ts
|
|
679
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
|
+
}
|
|
680
942
|
var FORWARDED_METHODS = ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"];
|
|
681
943
|
function forwardToStorefront(adapter, options) {
|
|
682
944
|
const origin = new URL(options.publicUrl);
|
|
683
945
|
const proto = origin.protocol.slice(0, -1);
|
|
946
|
+
const filled = pageHeaders(origin, options.headers);
|
|
684
947
|
let inFlight = 0;
|
|
685
948
|
let refusing = false;
|
|
686
949
|
const waiters = /* @__PURE__ */ new Set();
|
|
@@ -721,9 +984,12 @@ function forwardToStorefront(adapter, options) {
|
|
|
721
984
|
host: origin.host,
|
|
722
985
|
"x-forwarded-host": origin.host,
|
|
723
986
|
"x-forwarded-proto": proto,
|
|
724
|
-
"x-forwarded-for": [prior, peer].flat().filter(Boolean).join(", ")
|
|
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)
|
|
725
990
|
};
|
|
726
991
|
},
|
|
992
|
+
rewriteHeaders: (headers) => ({ ...filled, ...headers }),
|
|
727
993
|
// A forward is never retried: a page POST may not be idempotent, and a 503 is the storefront's answer.
|
|
728
994
|
retryDelay: () => null,
|
|
729
995
|
onError: (reply) => {
|
|
@@ -752,18 +1018,269 @@ function forwardToStorefront(adapter, options) {
|
|
|
752
1018
|
}
|
|
753
1019
|
};
|
|
754
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
|
+
}
|
|
755
1263
|
export {
|
|
1264
|
+
CHECKOUT_ADDRESS_CEILING,
|
|
756
1265
|
CSRF_COOKIE,
|
|
757
1266
|
CSRF_HEADER,
|
|
1267
|
+
FEED_PATH,
|
|
758
1268
|
FastifyHttpAdapter,
|
|
1269
|
+
HANDOFF_PATH,
|
|
1270
|
+
MCP_PATH,
|
|
759
1271
|
RateLimiter,
|
|
1272
|
+
SHOPPER_ATTESTATION_HEADER3 as SHOPPER_ATTESTATION_HEADER,
|
|
1273
|
+
UCP_MCP_PATH,
|
|
760
1274
|
buildSecurityHeaders,
|
|
761
1275
|
createHealthRoute,
|
|
762
1276
|
createHttpServer,
|
|
763
1277
|
createProductsRoute,
|
|
764
1278
|
createReadyRoute,
|
|
765
1279
|
createSecurityGuard,
|
|
1280
|
+
createShopperAttestation,
|
|
766
1281
|
forwardToStorefront,
|
|
767
|
-
|
|
1282
|
+
mountAgentSurfaces,
|
|
1283
|
+
mountMcp,
|
|
1284
|
+
mountToolEndpoint
|
|
768
1285
|
};
|
|
769
1286
|
//# sourceMappingURL=index.js.map
|