@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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/fastify-adapter.ts","../src/security-middleware.ts","../src/rate-limit.ts","../src/server.ts","../src/routes/health.ts","../src/routes/products.ts","../src/routes/ready.ts","../src/storefront-forward.ts"],"sourcesContent":["import Fastify, {\n errorCodes,\n type FastifyInstance,\n type FastifyPluginAsync,\n type FastifyReply,\n type FastifyRequest,\n} from 'fastify'\nimport fastifyCookie from '@fastify/cookie'\nimport fastifyCors from '@fastify/cors'\nimport { v7 as uuidv7 } from 'uuid'\nimport type {\n HttpAdapter,\n HttpMethod,\n Logger,\n MiddlewareHandler,\n RequestContext,\n ResponseEnvelope,\n RouteHandler,\n RouteOptions,\n SseEvent,\n StreamContext,\n StreamHandler,\n} from '@nymbalhq/types'\nimport {\n CORRELATION_ID_HEADER,\n IDEMPOTENT_REPLAYED_HEADER,\n HttpError,\n isValidCorrelationId,\n NymbalError,\n} from '@nymbalhq/types'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport { createSecurityGuard, type SecurityGuard } from './security-middleware.js'\n\nexport interface CorsOptions {\n allowedOrigins: string[]\n credentials: boolean\n}\n\nexport interface FastifyAdapterOptions {\n logger: Logger\n /** The guard every route passes before its middlewares and handler: rate limit, then CSRF on unsafe methods. */\n security: NymbalConfig['security']\n /** Which `X-Forwarded-For` entries set the request IP: a hop count, or every entry (`true`). Off by default. */\n trustProxy?: boolean | number\n cors?: CorsOptions\n}\n\n/** How long a stream ended at shutdown may take to flush before its socket is destroyed regardless. */\nconst STREAM_END_BOUND_MS = 500\n\nexport class FastifyHttpAdapter implements HttpAdapter {\n readonly #app: FastifyInstance\n readonly #logger: Logger\n readonly #guard: SecurityGuard\n readonly #middlewares: MiddlewareHandler[] = []\n readonly #defaultHeaders: Record<string, string> = {}\n /** Ends each open stream for shutdown; a stream removes itself once its close callbacks have run. */\n readonly #openStreams = new Set<() => void>()\n #started = false\n #stopping = false\n #boundPort = 0\n\n constructor(options: FastifyAdapterOptions) {\n this.#logger = options.logger\n this.#guard = createSecurityGuard(options.security)\n this.#app = Fastify({\n logger: false,\n trustProxy: options.trustProxy ?? false,\n disableRequestLogging: true,\n // Fastify's default takes `req.id` from an inbound `request-id` header, unvalidated; the id is always ours.\n requestIdHeader: false,\n genReqId: () => uuidv7(),\n })\n // Hooks rather than #buildContext and #applyEnvelope: Fastify's own 404 and body-parse 400 never reach a route\n // handler, and they carry the id too.\n this.#app.decorateRequest('correlationId', '')\n this.#app.addHook('onRequest', async (req) => {\n const inbound = req.headers[CORRELATION_ID_HEADER]\n if (typeof inbound === 'string' && isValidCorrelationId(inbound)) req.correlationId = inbound\n else req.correlationId = isValidCorrelationId(req.id) ? req.id : uuidv7()\n })\n this.#app.addHook('onSend', async (req, reply, payload) => {\n reply.header(CORRELATION_ID_HEADER, req.correlationId)\n return payload\n })\n // A signed webhook is verified against the bytes sent, so a route registered with `rawBody` keeps them. The\n // body is still parsed by Fastify's own JSON parser, with its poisoning settings and its 400s.\n const parseJson = this.#app.getDefaultJsonParser(\n this.#app.initialConfig.onProtoPoisoning ?? 'error',\n this.#app.initialConfig.onConstructorPoisoning ?? 'error',\n )\n const takesRawBody = (req: FastifyRequest): boolean =>\n (req.routeOptions.config as { routeOptions?: RouteOptions } | undefined)?.routeOptions\n ?.rawBody === true\n this.#app.removeContentTypeParser('application/json')\n this.#app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (req, body, done) => {\n const buffer = body as Buffer\n if (takesRawBody(req)) req.rawBody = buffer\n parseJson(req, buffer.toString('utf8'), done)\n })\n // Providers also post form-encoded, plain-text and other bodies, signing those bytes too, so a `rawBody` route\n // takes every type, its body the UTF-8 text. Every other route answers as Fastify does by default: `text/plain` as\n // a string, anything else (a bodied request with no Content-Type included) 415, and an unknown URL its 404.\n const keepRawBody =\n (elsewhere: 'text' | 'refuse') =>\n (\n req: FastifyRequest,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n ) => {\n const buffer = body as Buffer\n if (takesRawBody(req)) req.rawBody = buffer\n else if (elsewhere === 'refuse' && !req.is404) {\n done(new errorCodes.FST_ERR_CTP_INVALID_MEDIA_TYPE(req.headers['content-type']))\n return\n }\n done(null, buffer.toString('utf8'))\n }\n this.#app.removeContentTypeParser('text/plain')\n this.#app.addContentTypeParser('text/plain', { parseAs: 'buffer' }, keepRawBody('text'))\n this.#app.addContentTypeParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'buffer' },\n keepRawBody('refuse'),\n )\n this.#app.addContentTypeParser('*', { parseAs: 'buffer' }, keepRawBody('refuse'))\n // Fastify's `close()` waits for every open connection, and a stream never ends by itself. `preClose` runs after\n // Fastify answers new requests 503 and before `server.close()`, so no stream can hold the close once it has run.\n this.#app.addHook('preClose', async () => {\n this.#stopping = true\n for (const endStream of this.#openStreams) endStream()\n })\n void this.#app.register(fastifyCookie)\n if (options.cors && options.cors.allowedOrigins.length > 0) {\n void this.#app.register(fastifyCors, {\n origin: options.cors.allowedOrigins,\n credentials: options.cors.credentials,\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],\n // A browser client on an allowed origin reads the request's id and whether a keyed write was a replay.\n exposedHeaders: [CORRELATION_ID_HEADER, IDEMPOTENT_REPLAYED_HEADER],\n })\n }\n // The token a client on another origin of the same site echoes in `x-csrf-token`: it cannot read this cookie.\n this.registerRoute('GET', '/api/csrf', (ctx) => this.#guard.issueToken(ctx))\n }\n\n get boundPort(): number {\n return this.#boundPort\n }\n\n registerRoute(\n method: HttpMethod,\n path: string,\n handler: RouteHandler,\n options?: RouteOptions,\n ): void {\n if (this.#started) {\n throw new Error('Cannot register routes after the server has started')\n }\n const routeConfig: {\n method: HttpMethod\n url: string\n handler: (req: FastifyRequest, reply: FastifyReply) => Promise<FastifyReply>\n config: { routeOptions: RouteOptions }\n bodyLimit?: number\n } = {\n method,\n url: path,\n handler: async (req, reply) => {\n const ctx = this.#buildContext(req, options?.rawBody ?? false)\n const refused = this.#guard.admit(ctx, options)\n if (refused) return this.#applyEnvelope(reply, refused)\n let envelope: ResponseEnvelope\n try {\n envelope = await this.#runMiddlewaresThen(ctx, handler)\n } catch (err) {\n envelope = this.#renderError(err, ctx)\n }\n return this.#applyEnvelope(reply, this.#guard.finish(ctx, envelope))\n },\n config: { routeOptions: options ?? {} },\n }\n this.#app.route(routeConfig)\n }\n\n registerStreamRoute(\n method: 'GET',\n path: string,\n handler: StreamHandler,\n options?: RouteOptions,\n ): void {\n if (this.#started) {\n throw new Error('Cannot register routes after the server has started')\n }\n this.#app.route({\n method,\n url: path,\n handler: async (req, reply) => {\n const ctx = this.#buildContext(req, false)\n const refused = this.#guard.admit(ctx, options)\n if (refused) return this.#applyEnvelope(reply, refused)\n try {\n for (const mw of this.#middlewares) {\n const out = await mw(ctx)\n if (out) {\n return this.#applyEnvelope(reply, out)\n }\n }\n } catch (err) {\n return this.#applyEnvelope(reply, this.#renderError(err, ctx))\n }\n // Routed before Fastify began closing, but its middlewares finished after the open streams were ended.\n if (this.#stopping) {\n return this.#applyEnvelope(reply, {\n status: 503,\n headers: { connection: 'close' },\n body: { error: { code: 'unavailable', message: 'Server is shutting down' } },\n })\n }\n const raw = reply.raw\n // Taken now: a finished response detaches from its socket before `end`'s callback runs.\n const socket = req.raw.socket\n // A hijacked reply skips onSend.\n raw.writeHead(200, {\n ...this.#defaultHeaders,\n [CORRELATION_ID_HEADER]: ctx.correlationId,\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n 'x-accel-buffering': 'no',\n })\n reply.hijack()\n const closeCallbacks: Array<() => void> = []\n let ending = false\n let closed = false\n const end = (then?: () => void): void => {\n if (ending) return\n ending = true\n try {\n raw.end(then)\n } catch {\n // ignore\n }\n }\n // A clean end, so the client sees a complete response, then the keep-alive socket goes too: it would hold\n // `server.close()` open. The bound covers a socket whose end never flushes.\n const endForShutdown = (): void => {\n const bound = setTimeout(() => socket.destroy(), STREAM_END_BOUND_MS)\n bound.unref()\n end(() => {\n clearTimeout(bound)\n socket.destroy()\n })\n }\n const close = (): void => {\n end()\n if (closed) return\n closed = true\n this.#openStreams.delete(endForShutdown)\n for (const cb of closeCallbacks) {\n try {\n cb()\n } catch (err) {\n ctx.logger.error({ err }, 'stream close callback failed')\n }\n }\n }\n req.raw.on('close', close)\n req.raw.on('error', close)\n this.#openStreams.add(endForShutdown)\n const stream: StreamContext = {\n send(event: SseEvent): void {\n if (ending) return\n let line = ''\n if (event.id !== undefined) line += `id: ${event.id}\\n`\n if (event.event !== undefined) line += `event: ${event.event}\\n`\n const data = typeof event.data === 'string' ? event.data : JSON.stringify(event.data)\n line += `data: ${data}\\n\\n`\n raw.write(line)\n },\n close,\n onClose(cb: () => void): void {\n closeCallbacks.push(cb)\n },\n }\n try {\n await handler(ctx, stream)\n } catch (err) {\n ctx.logger.error({ err }, 'stream handler threw')\n close()\n }\n return reply\n },\n config: { routeOptions: options ?? {} },\n })\n }\n\n /** A Fastify plugin on this server, in a context of its own: how the storefront forward is added. */\n registerPlugin(plugin: FastifyPluginAsync): void {\n if (this.#started) {\n throw new Error('Cannot register plugins after the server has started')\n }\n void this.#app.register(plugin)\n }\n\n registerMiddleware(middleware: MiddlewareHandler): void {\n if (this.#started) {\n throw new Error('Cannot register middleware after the server has started')\n }\n this.#middlewares.push(middleware)\n }\n\n setDefaultHeaders(headers: Record<string, string>): void {\n for (const [k, v] of Object.entries(headers)) {\n this.#defaultHeaders[k.toLowerCase()] = v\n }\n }\n\n async start(port: number, host = '0.0.0.0'): Promise<void> {\n await this.#app.listen({ port, host })\n this.#boundPort = (this.#app.server.address() as { port: number }).port\n this.#started = true\n this.#logger.debug({ port: this.#boundPort, host }, 'HTTP server listening')\n }\n\n async stop(): Promise<void> {\n if (!this.#started) return\n await this.#app.close()\n this.#started = false\n }\n\n async #runMiddlewaresThen(ctx: RequestContext, handler: RouteHandler): Promise<ResponseEnvelope> {\n for (const mw of this.#middlewares) {\n const out = await mw(ctx)\n if (out) return out\n }\n return handler(ctx)\n }\n\n #buildContext(req: FastifyRequest, includeRawBody: boolean): RequestContext {\n const { correlationId } = req\n const logger = this.#logger.child({ requestId: req.id, correlationId })\n const ctx: RequestContext = {\n method: req.method as HttpMethod,\n path: req.routeOptions?.url ?? req.url,\n url: req.url,\n params: (req.params ?? {}) as Record<string, string>,\n query: (req.query ?? {}) as Record<string, string | string[] | undefined>,\n body: req.body,\n headers: req.headers,\n cookies: (req.cookies ?? {}) as Record<string, string>,\n requestId: req.id,\n correlationId,\n logger,\n ip: req.ip,\n }\n if (includeRawBody && Buffer.isBuffer(req.rawBody)) {\n ctx.rawBody = req.rawBody\n }\n return ctx\n }\n\n #applyEnvelope(reply: FastifyReply, envelope: ResponseEnvelope): FastifyReply {\n reply.status(envelope.status)\n for (const [name, value] of Object.entries(this.#defaultHeaders)) {\n reply.header(name, value)\n }\n if (envelope.headers) {\n for (const [name, value] of Object.entries(envelope.headers)) {\n reply.header(name, value)\n }\n }\n if (envelope.cookies) {\n for (const cookie of envelope.cookies) {\n reply.setCookie(cookie.name, cookie.value, {\n path: cookie.path ?? '/',\n ...(cookie.domain !== undefined && { domain: cookie.domain }),\n ...(cookie.maxAge !== undefined && { maxAge: cookie.maxAge }),\n httpOnly: cookie.httpOnly ?? false,\n secure: cookie.secure ?? false,\n ...(cookie.sameSite !== undefined && { sameSite: cookie.sameSite }),\n })\n }\n }\n if (envelope.body === undefined) {\n return reply.send()\n }\n return reply.send(envelope.body)\n }\n\n #renderError(err: unknown, ctx: RequestContext): ResponseEnvelope {\n if (err instanceof HttpError) {\n ctx.logger.warn({ err: err.toJSON() }, err.message)\n return {\n status: err.status,\n body: { error: { code: err.code, message: err.message } },\n }\n }\n if (err instanceof NymbalError) {\n ctx.logger.error({ err: err.toJSON() }, err.message)\n return {\n status: 500,\n body: { error: { code: err.code, message: err.message } },\n }\n }\n const message = err instanceof Error ? err.message : String(err)\n ctx.logger.error({ err }, message)\n return {\n status: 500,\n body: { error: { code: 'internal', message: 'Internal server error' } },\n }\n }\n}\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n rawBody?: Buffer\n /** Set by the onRequest hook before anything else runs. */\n correlationId: string\n }\n}\n","import { randomBytes, timingSafeEqual } from 'node:crypto'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport type {\n RequestContext,\n ResponseCookie,\n ResponseEnvelope,\n RouteOptions,\n} from '@nymbalhq/types'\nimport { BUILT_IN_RATE_LIMITS, RateLimiter } from './rate-limit.js'\n\nexport const CSRF_COOKIE = 'nymbal.csrf'\nexport const CSRF_HEADER = 'x-csrf-token'\nconst UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport function buildSecurityHeaders(security: NymbalConfig['security']): Record<string, string> {\n const headers: Record<string, string> = {}\n if (security.headers.hsts) {\n headers['strict-transport-security'] = 'max-age=31536000; includeSubDomains'\n }\n const csp = security.headers.contentSecurityPolicy\n const cspValue =\n csp === 'strict'\n ? \"default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'\"\n : csp === 'relaxed'\n ? \"default-src 'self' https:; img-src * data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'\"\n : csp === 'off'\n ? null\n : csp\n if (cspValue) headers['content-security-policy'] = cspValue\n headers['referrer-policy'] = security.headers.referrerPolicy\n headers['x-frame-options'] = security.headers.xFrameOptions === 'deny' ? 'DENY' : 'SAMEORIGIN'\n headers['x-content-type-options'] = 'nosniff'\n return headers\n}\n\nexport interface SecurityGuard {\n /**\n * Runs before any middleware or handler: the rate limit, then CSRF on unsafe methods unless the route opted out.\n * Returns the refusal, or null when the request may proceed.\n */\n admit(ctx: RequestContext, options?: RouteOptions): ResponseEnvelope | null\n /** Runs on the handler's answer: security headers, the CSRF cookie, and the outcome of a failure-counted login. */\n finish(ctx: RequestContext, envelope: ResponseEnvelope): ResponseEnvelope\n /** `GET /api/csrf`: the request's CSRF cookie, or a new one set on the response. */\n issueToken(ctx: RequestContext): ResponseEnvelope\n reset(): void\n}\n\n/** Counts failures only, keyed by IP and by account, so an office behind one NAT is not blocked by its own logins. */\nconst LOGIN_PATH = '/api/auth/login'\n\nfunction csrfCookie(token: string): ResponseCookie {\n return {\n name: CSRF_COOKIE,\n value: token,\n path: '/',\n httpOnly: false,\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n }\n}\n\nfunction loginKeys(ctx: RequestContext): string[] {\n const email = (ctx.body as { email?: unknown } | undefined)?.email\n return typeof email === 'string' && email !== ''\n ? [ctx.ip, `account:${email.toLowerCase()}`]\n : [ctx.ip]\n}\n\nfunction isLogin(ctx: RequestContext): boolean {\n return ctx.method === 'POST' && ctx.path === LOGIN_PATH\n}\n\nexport function createSecurityGuard(security: NymbalConfig['security']): SecurityGuard {\n const rateLimiter = new RateLimiter({ ...BUILT_IN_RATE_LIMITS, ...security.rateLimit })\n const baseHeaders = buildSecurityHeaders(security)\n\n function applyHeaders(envelope: ResponseEnvelope): ResponseEnvelope {\n return {\n ...envelope,\n headers: { ...baseHeaders, ...(envelope.headers ?? {}) },\n }\n }\n\n return {\n admit(ctx, options = {}) {\n const decision = isLogin(ctx)\n ? rateLimiter.full(ctx.path, loginKeys(ctx))\n : rateLimiter.check(ctx.ip, ctx.path, ctx.headers)\n if (decision && !decision.allowed) {\n return applyHeaders(rateLimitResponse(decision, ctx))\n }\n\n if (security.csrf && options.csrf !== false && UNSAFE_METHODS.has(ctx.method)) {\n if (!verifyCsrf(ctx)) {\n ctx.logger.warn({ method: ctx.method, path: ctx.path }, 'CSRF validation failed')\n return applyHeaders({\n status: 403,\n body: { error: { code: 'csrf.invalid', message: 'Invalid or missing CSRF token' } },\n })\n }\n }\n return null\n },\n\n finish(ctx, envelope) {\n if (isLogin(ctx)) {\n const keys = loginKeys(ctx)\n // Success clears the account only: the IP bucket expires with its window, so logging in to one's own\n // account cannot reset a spray across other accounts.\n if (envelope.status >= 200 && envelope.status < 300) {\n rateLimiter.clear(\n ctx.path,\n keys.filter((key) => key.startsWith('account:')),\n )\n } else rateLimiter.hit(ctx.path, keys)\n }\n const finished = applyHeaders(envelope)\n const setsCsrf = finished.cookies?.some((cookie) => cookie.name === CSRF_COOKIE) ?? false\n if (security.csrf && !ctx.cookies[CSRF_COOKIE] && !setsCsrf) {\n finished.cookies = [...(finished.cookies ?? []), csrfCookie(newToken())]\n }\n return finished\n },\n\n issueToken(ctx) {\n const existing = ctx.cookies[CSRF_COOKIE]\n if (existing) return { status: 200, body: { data: { token: existing } } }\n const token = newToken()\n return { status: 200, body: { data: { token } }, cookies: [csrfCookie(token)] }\n },\n\n reset() {\n rateLimiter.reset()\n },\n }\n}\n\nfunction newToken(): string {\n return randomBytes(32).toString('hex')\n}\n\nfunction verifyCsrf(ctx: RequestContext): boolean {\n const cookieToken = ctx.cookies[CSRF_COOKIE]\n const rawHeader = ctx.headers[CSRF_HEADER]\n const headerToken = Array.isArray(rawHeader) ? rawHeader[0] : rawHeader\n if (!cookieToken || !headerToken) return false\n if (cookieToken.length !== headerToken.length) return false\n try {\n return timingSafeEqual(Buffer.from(cookieToken), Buffer.from(headerToken))\n } catch {\n return false\n }\n}\n\nfunction rateLimitResponse(\n decision: { action: string; retryAfter?: number },\n ctx: RequestContext,\n): ResponseEnvelope {\n ctx.logger.info({ ip: ctx.ip, path: ctx.path, action: decision.action }, 'Rate limit triggered')\n const status = decision.action === 'challenge' ? 403 : 429\n const headers: Record<string, string> = {}\n if (decision.retryAfter) headers['retry-after'] = String(decision.retryAfter)\n return {\n status,\n headers,\n body: {\n error: {\n code: `rate_limit.${decision.action}`,\n message: 'Too many requests',\n ...(decision.retryAfter !== undefined && { retryAfter: decision.retryAfter }),\n },\n },\n }\n}\n","import { ORDER_EMAIL_HEADER, type RateLimitAction } from '@nymbalhq/types'\n\nexport interface ParsedRule {\n pattern: string\n regex: RegExp\n /** The rule counts only requests that carry this header (lower case). */\n header?: string\n requests: number\n windowMs: number\n action: RateLimitAction\n}\n\nexport interface RateLimitDecision {\n allowed: boolean\n action: RateLimitAction\n retryAfter?: number\n}\n\ntype RateLimitRules = Record<\n string,\n { requests: number; window: string; action: RateLimitAction; header?: string | undefined }\n>\n\n/**\n * Applied under the configured rules: a configured key with the same pattern replaces its default, and the defaults\n * stay when other keys are configured.\n */\nexport const BUILT_IN_RATE_LIMITS: RateLimitRules = {\n '/api/auth/login': { requests: 10, window: '15m', action: 'block' },\n '/api/auth/register': { requests: 10, window: '1h', action: 'block' },\n // A record and a list per page view: 300 page views a minute, so shoppers behind one NAT keep their views.\n '/api/recently-viewed': { requests: 600, window: '1m', action: 'block' },\n // Each accepted subscribe mails a confirmation: the bound on how much mail one IP can make the store send.\n '/api/alerts/subscribe': { requests: 10, window: '1h', action: 'block' },\n // Each match mails the order's link. Before the order-read rule, which a request carrying the email would also match.\n '/api/orders/link': { requests: 5, window: '1h', action: 'block' },\n // The email is the second factor of an expired order key: bounded so it cannot be guessed. The key-only poll of a\n // pending order carries no email and is never counted.\n '/api/orders/*': { requests: 10, window: '1h', action: 'block', header: ORDER_EMAIL_HEADER },\n // Every checkout answer can mint an order key.\n '/api/checkout': { requests: 30, window: '1m', action: 'block' },\n}\n\ninterface Bucket {\n count: number\n resetAt: number\n}\n\n/** The map size that triggers the first sweep of expired buckets. */\nconst PRUNE_THRESHOLD = 1024\n\nexport class RateLimiter {\n readonly #rules: ParsedRule[]\n readonly #buckets = new Map<string, Bucket>()\n #pruneAt = PRUNE_THRESHOLD\n\n constructor(rules: RateLimitRules) {\n this.#rules = Object.entries(rules).map(([pattern, rule]) => ({\n pattern,\n regex: compilePathPattern(pattern),\n ...(rule.header !== undefined && { header: rule.header.toLowerCase() }),\n requests: rule.requests,\n windowMs: parseWindow(rule.window),\n action: rule.action,\n }))\n }\n\n check(\n ip: string,\n path: string,\n headers: Readonly<Record<string, unknown>> = {},\n ): RateLimitDecision | null {\n const rule = this.#ruleFor(path, headers)\n if (!rule) return null\n const key = `${rule.pattern}|${ip}`\n const now = Date.now()\n const bucket = this.#buckets.get(key)\n if (!bucket || bucket.resetAt <= now) {\n this.#open(key, now, rule.windowMs)\n return { allowed: true, action: rule.action }\n }\n bucket.count += 1\n if (bucket.count > rule.requests) {\n return { allowed: false, action: rule.action, retryAfter: retryAfter(bucket, now) }\n }\n return { allowed: true, action: rule.action }\n }\n\n /**\n * For a route that counts failures only: refuses when any of `keys` (an IP, an account) already holds the rule's\n * full count, without counting this request. `hit` and `clear` record the outcome once the handler has answered.\n */\n full(path: string, keys: string[]): RateLimitDecision | null {\n const rule = this.#ruleFor(path)\n if (!rule) return null\n const now = Date.now()\n for (const key of keys) {\n const bucket = this.#buckets.get(`${rule.pattern}|${key}`)\n if (bucket && bucket.resetAt > now && bucket.count >= rule.requests) {\n return { allowed: false, action: rule.action, retryAfter: retryAfter(bucket, now) }\n }\n }\n return { allowed: true, action: rule.action }\n }\n\n hit(path: string, keys: string[]): void {\n const rule = this.#ruleFor(path)\n if (!rule) return\n const now = Date.now()\n for (const key of keys) {\n const bucketKey = `${rule.pattern}|${key}`\n const bucket = this.#buckets.get(bucketKey)\n if (!bucket || bucket.resetAt <= now) {\n this.#open(bucketKey, now, rule.windowMs)\n } else {\n bucket.count += 1\n }\n }\n }\n\n clear(path: string, keys: string[]): void {\n const rule = this.#ruleFor(path)\n if (!rule) return\n for (const key of keys) this.#buckets.delete(`${rule.pattern}|${key}`)\n }\n\n reset(): void {\n this.#buckets.clear()\n this.#pruneAt = PRUNE_THRESHOLD\n }\n\n /**\n * Starts a bucket. Keys include caller-chosen values (an account email), so expired buckets are swept once the map\n * reaches `#pruneAt`; the next sweep waits until the map doubles past what survived, which keeps the cost amortised\n * constant per insert even when every bucket is live.\n */\n #open(key: string, now: number, windowMs: number): void {\n if (this.#buckets.size >= this.#pruneAt) {\n for (const [k, b] of this.#buckets) if (b.resetAt <= now) this.#buckets.delete(k)\n this.#pruneAt = Math.max(PRUNE_THRESHOLD, this.#buckets.size * 2)\n }\n this.#buckets.set(key, { count: 1, resetAt: now + windowMs })\n }\n\n #ruleFor(path: string, headers: Readonly<Record<string, unknown>> = {}): ParsedRule | undefined {\n return this.#rules.find(\n (r) => r.regex.test(path) && (r.header === undefined || headers[r.header] !== undefined),\n )\n }\n}\n\nfunction retryAfter(bucket: Bucket, now: number): number {\n return Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))\n}\n\nfunction parseWindow(window: string): number {\n const match = /^(\\d+)(ms|s|m|h)$/.exec(window)\n if (!match) throw new Error(`Invalid rate-limit window: ${window}`)\n const n = Number(match[1])\n switch (match[2]) {\n case 'ms':\n return n\n case 's':\n return n * 1000\n case 'm':\n return n * 60_000\n case 'h':\n return n * 3_600_000\n default:\n throw new Error(`Unreachable unit: ${match[2]}`)\n }\n}\n\nfunction compilePathPattern(pattern: string): RegExp {\n const escaped = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '__DOUBLESTAR__')\n .replace(/\\*/g, '[^/]+')\n .replace(/__DOUBLESTAR__/g, '.*')\n return new RegExp(`^${escaped}$`)\n}\n","import type { NymbalConfig } from '@nymbalhq/config'\nimport {\n ConfigError,\n type DocumentStoreAdapter,\n type HttpAdapter,\n type HttpMethod,\n type Logger,\n type MiddlewareHandler,\n type RouteHandler,\n type RouteOptions,\n} from '@nymbalhq/types'\nimport { FastifyHttpAdapter } from './fastify-adapter.js'\nimport { createHealthRoute } from './routes/health.js'\nimport { createProductsRoute } from './routes/products.js'\n\nexport interface HttpServerDeps {\n config: NymbalConfig\n logger: Logger\n documentStore: DocumentStoreAdapter\n version: string\n}\n\nexport interface HttpServer {\n adapter: HttpAdapter\n registerRoute(\n method: HttpMethod,\n path: string,\n handler: RouteHandler,\n options?: RouteOptions,\n ): void\n registerMiddleware(middleware: MiddlewareHandler): void\n start(): Promise<{ port: number; host: string }>\n stop(): Promise<void>\n}\n\nconst TRUST_PROXY_HOPS_ENV = 'NYMBAL_TRUST_PROXY_HOPS'\n\n/**\n * `http.trustProxy`, with NYMBAL_TRUST_PROXY_HOPS filling it when the config leaves it `false`: the hop count is the\n * platform's, so it is set where the store runs, not in the config the image is built from. A set variable must be an\n * integer of 0 or more, whatever the config holds; Fastify would trust nothing, silently, below 0.\n */\nexport function resolveTrustProxy(config: NymbalConfig, env: NodeJS.ProcessEnv): boolean | number {\n const raw = env[TRUST_PROXY_HOPS_ENV]\n const hops = raw === undefined ? undefined : /^\\d+$/.test(raw.trim()) ? Number(raw) : NaN\n if (hops !== undefined && !Number.isSafeInteger(hops)) {\n throw new ConfigError(`${TRUST_PROXY_HOPS_ENV} must be a whole number of proxy hops, 0 or more`, {\n code: 'config.trust_proxy_hops_invalid',\n context: { variable: TRUST_PROXY_HOPS_ENV },\n })\n }\n const configured = config.http.trustProxy\n return configured === false && hops !== undefined ? hops : configured\n}\n\nexport function createHttpServer(deps: HttpServerDeps): HttpServer {\n const { config, logger, documentStore, version } = deps\n if (config.http.adapter !== 'fastify') {\n throw new Error(`Unsupported http.adapter: ${config.http.adapter}`)\n }\n const adapter = new FastifyHttpAdapter({\n logger,\n cors: config.http.cors,\n security: config.security,\n trustProxy: resolveTrustProxy(config, process.env),\n })\n\n const server: HttpServer = {\n adapter,\n registerRoute(method, path, handler, options) {\n adapter.registerRoute(method, path, handler, options)\n },\n registerMiddleware(middleware) {\n adapter.registerMiddleware(middleware)\n },\n async start() {\n await adapter.start(config.http.port, config.http.host)\n return { port: adapter.boundPort, host: config.http.host }\n },\n async stop() {\n await adapter.stop()\n },\n }\n\n // Default routes — available without any user route registration.\n server.registerRoute('GET', '/health', createHealthRoute(version))\n // The commerce routes (including `/api/products`) are registered by\n // `platform.attachHttp(...)` — we intentionally do not pre-register them\n // here to avoid FST_ERR_DUPLICATED_ROUTE conflicts when the kernel is wired.\n void createProductsRoute\n void documentStore\n void config\n\n return server\n}\n","import type { RouteHandler } from '@nymbalhq/types'\n\nexport function createHealthRoute(version: string): RouteHandler {\n return () => ({\n status: 200,\n body: { status: 'ok', version, timestamp: new Date().toISOString() },\n })\n}\n","import type { DocumentStoreAdapter, RouteHandler } from '@nymbalhq/types'\n\nexport interface ProductListItem {\n id: string\n slug: string\n title: string\n description: string\n priceMinor: number\n currency: string\n categoryId: string\n imageUrl: string\n}\n\nexport function createProductsRoute(\n documentStore: DocumentStoreAdapter,\n storeId: string,\n): RouteHandler {\n return async (ctx) => {\n const rawLimit = ctx.query.limit\n const limitValue = Array.isArray(rawLimit) ? rawLimit[0] : rawLimit\n const limit = limitValue ? Math.min(100, Math.max(1, Number(limitValue) || 20)) : 50\n const rawCursor = ctx.query.cursor\n const cursorValue = Array.isArray(rawCursor) ? rawCursor[0] : rawCursor\n\n const result = await documentStore.query<ProductListItem>('products', {\n partitionKey: { field: 'storeId', value: storeId },\n limit,\n ...(cursorValue !== undefined && { cursor: cursorValue }),\n ascending: true,\n })\n return {\n status: 200,\n body: { items: result.items, nextCursor: result.nextCursor },\n }\n }\n}\n","import type { RouteHandler } from '@nymbalhq/types'\n\nexport type ReadyState = { ready: true } | { ready: false; failing: string[] }\n\n/** GET /ready: 200 when the store can take traffic, else 503 naming what cannot, by name only. */\nexport function createReadyRoute(probe: () => Promise<ReadyState>): RouteHandler {\n return async () => {\n const state = await probe()\n return state.ready\n ? { status: 200, body: { status: 'ready' } }\n : { status: 503, body: { status: 'not-ready', failing: state.failing } }\n }\n}\n","import httpProxy from '@fastify/http-proxy'\nimport type { HTTPMethods } from 'fastify'\nimport type { FastifyHttpAdapter } from './fastify-adapter.js'\n\nexport interface StorefrontForwardOptions {\n /** The storefront's internal port on 127.0.0.1. */\n port: number\n /** The store's public origin: the storefront sees its host and scheme, whatever the client sent. */\n publicUrl: string\n}\n\nexport interface StorefrontForward {\n /** Forwards started and not yet ended or cut. */\n inFlight(): number\n /** From now on a new page request answers 503; forwards in flight go on. */\n refuse(): void\n /** Resolves true once no forward is in flight, false when `timeoutMs` passes first. */\n drained(timeoutMs: number): Promise<boolean>\n}\n\n/** OPTIONS stays the API's: CORS answers a preflight on any path. */\nconst FORWARDED_METHODS: HTTPMethods[] = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT']\n\n/**\n * Forwards every request the API does not route to the storefront on its internal port, body and headers unchanged\n * both ways. A path under /api/ keeps the API's not-found answer and never reaches the storefront. Call before\n * `adapter.start`.\n */\nexport function forwardToStorefront(\n adapter: FastifyHttpAdapter,\n options: StorefrontForwardOptions,\n): StorefrontForward {\n const origin = new URL(options.publicUrl)\n const proto = origin.protocol.slice(0, -1)\n let inFlight = 0\n let refusing = false\n const waiters = new Set<() => void>()\n const settle = (): void => {\n inFlight -= 1\n if (inFlight === 0) for (const wake of [...waiters]) wake()\n }\n\n adapter.registerPlugin(async (api) => {\n // The forward's own context passes every body through as a stream, so this one does too.\n api.removeAllContentTypeParsers()\n api.addContentTypeParser('*', (_req, payload, done) => done(null, payload))\n api.route({\n method: FORWARDED_METHODS,\n url: '/api/*',\n handler: (_req, reply) => reply.callNotFound(),\n })\n })\n\n adapter.registerPlugin(async (pages) => {\n pages.removeAllContentTypeParsers()\n await pages.register(httpProxy, {\n upstream: `http://127.0.0.1:${options.port}`,\n httpMethods: FORWARDED_METHODS,\n internalRewriteLocationHeader: false,\n preHandler: (_req, reply, done) => {\n if (refusing) {\n void reply\n .code(503)\n .header('connection', 'close')\n .send({ error: { code: 'unavailable', message: 'The store is shutting down' } })\n return\n }\n inFlight += 1\n reply.raw.once('close', settle)\n done()\n },\n replyOptions: {\n rewriteRequestHeaders: (req, headers) => {\n const prior = req.headers['x-forwarded-for']\n const peer = req.raw.socket.remoteAddress ?? req.ip\n return {\n ...headers,\n host: origin.host,\n 'x-forwarded-host': origin.host,\n 'x-forwarded-proto': proto,\n 'x-forwarded-for': [prior, peer].flat().filter(Boolean).join(', '),\n }\n },\n // A forward is never retried: a page POST may not be idempotent, and a 503 is the storefront's answer.\n retryDelay: () => null,\n onError: (reply) => {\n void reply\n .code(503)\n .send({ error: { code: 'unavailable', message: 'The storefront is not answering' } })\n },\n },\n })\n })\n\n return {\n inFlight: () => inFlight,\n refuse() {\n refusing = true\n },\n drained(timeoutMs) {\n if (inFlight === 0) return Promise.resolve(true)\n return new Promise<boolean>((resolve) => {\n const finish = (value: boolean): void => {\n clearTimeout(timer)\n waiters.delete(wake)\n resolve(value)\n }\n const wake = (): void => finish(true)\n const timer = setTimeout(() => finish(false), timeoutMs)\n waiters.add(wake)\n })\n },\n }\n}\n"],"mappings":";AAAA,OAAO;AAAA,EACL;AAAA,OAKK;AACP,OAAO,mBAAmB;AAC1B,OAAO,iBAAiB;AACxB,SAAS,MAAM,cAAc;AAc7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC7BP,SAAS,aAAa,uBAAuB;;;ACA7C,SAAS,0BAAgD;AA2BlD,IAAM,uBAAuC;AAAA,EAClD,mBAAmB,EAAE,UAAU,IAAI,QAAQ,OAAO,QAAQ,QAAQ;AAAA,EAClE,sBAAsB,EAAE,UAAU,IAAI,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAEpE,wBAAwB,EAAE,UAAU,KAAK,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAEvE,yBAAyB,EAAE,UAAU,IAAI,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAEvE,oBAAoB,EAAE,UAAU,GAAG,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA;AAAA,EAGjE,iBAAiB,EAAE,UAAU,IAAI,QAAQ,MAAM,QAAQ,SAAS,QAAQ,mBAAmB;AAAA;AAAA,EAE3F,iBAAiB,EAAE,UAAU,IAAI,QAAQ,MAAM,QAAQ,QAAQ;AACjE;AAQA,IAAM,kBAAkB;AAEjB,IAAM,cAAN,MAAkB;AAAA,EACd;AAAA,EAC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,YAC3B,qBAAqB;AAAA,YACrB,mBAAmB,CAAC,OAAO,IAAI,EAAE,KAAK,EAAE,OAAO,OAAO,EAAE,KAAK,IAAI;AAAA,UACnE;AAAA,QACF;AAAA;AAAA,QAEA,YAAY,MAAM;AAAA,QAClB,SAAS,CAAC,UAAU;AAClB,eAAK,MACF,KAAK,GAAG,EACR,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,SAAS,kCAAkC,EAAE,CAAC;AAAA,QACxF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AAAA,IACL,UAAU,MAAM;AAAA,IAChB,SAAS;AACP,iBAAW;AAAA,IACb;AAAA,IACA,QAAQ,WAAW;AACjB,UAAI,aAAa,EAAG,QAAO,QAAQ,QAAQ,IAAI;AAC/C,aAAO,IAAI,QAAiB,CAAC,YAAY;AACvC,cAAM,SAAS,CAAC,UAAyB;AACvC,uBAAa,KAAK;AAClB,kBAAQ,OAAO,IAAI;AACnB,kBAAQ,KAAK;AAAA,QACf;AACA,cAAM,OAAO,MAAY,OAAO,IAAI;AACpC,cAAM,QAAQ,WAAW,MAAM,OAAO,KAAK,GAAG,SAAS;AACvD,gBAAQ,IAAI,IAAI;AAAA,MAClB,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/fastify-adapter.ts","../src/security-middleware.ts","../src/rate-limit.ts","../src/shopper-attestation.ts","../src/index.ts","../src/server.ts","../src/routes/health.ts","../src/routes/products.ts","../src/routes/ready.ts","../src/storefront-forward.ts","../src/mcp-route.ts","../src/agent-surface.ts"],"sourcesContent":["import Fastify, {\n errorCodes,\n type FastifyInstance,\n type InjectOptions,\n type LightMyRequestResponse,\n type FastifyPluginAsync,\n type FastifyReply,\n type FastifyRequest,\n} from 'fastify'\nimport { createHash, timingSafeEqual } from 'node:crypto'\nimport { isIP } from 'node:net'\nimport fastifyCookie from '@fastify/cookie'\nimport fastifyCors from '@fastify/cors'\nimport proxyAddr from '@fastify/proxy-addr'\nimport { v7 as uuidv7 } from 'uuid'\nimport type {\n HttpAdapter,\n HttpMethod,\n Logger,\n MiddlewareHandler,\n RequestContext,\n ResolvedOriginLock,\n ResponseEnvelope,\n RouteHandler,\n RouteOptions,\n SseEvent,\n StreamContext,\n StreamHandler,\n} from '@nymbalhq/types'\nimport {\n CORRELATION_ID_HEADER,\n IDEMPOTENT_REPLAYED_HEADER,\n HttpError,\n isValidCorrelationId,\n NymbalError,\n} from '@nymbalhq/types'\nimport { TRUSTED_PROXIES_ENV, trustSuggestion, type NymbalConfig } from '@nymbalhq/config'\nimport { createSecurityGuard, type SecurityGuard } from './security-middleware.js'\nimport { createShopperAttestation, type ShopperAttestation } from './shopper-attestation.js'\n\nexport interface CorsOptions {\n allowedOrigins: string[]\n credentials: boolean\n}\n\nexport interface FastifyAdapterOptions {\n logger: Logger\n /** The guard every route passes before its middlewares and handler: rate limit, then CSRF on unsafe methods. */\n security: NymbalConfig['security']\n /**\n * The proxies whose `X-Forwarded-For` sets the client address, walked from the socket peer while each hop is listed:\n * `loopback`, `linklocal`, `uniquelocal`, addresses and CIDRs. Default `['loopback']`. The first request from an\n * unlisted peer that carries a forwarded address logs a warning naming the peer.\n */\n trustedProxies?: string[]\n /**\n * One header a listed proxy sets to the client's address; when set, it decides in place of `X-Forwarded-For`, and\n * only when it holds exactly one IP address.\n */\n clientIpHeader?: string\n /**\n * Whether the header counts only on a locked request (one carrying the origin secret), from any peer, and on no\n * other; when false it counts from a listed peer.\n */\n clientIpRequiresLock?: boolean\n /**\n * The origin lock: a request from another machine that does not carry one of the secrets in the header is refused\n * 403 `origin_locked` before anything else sees it, bar the routes `/health` and `/ready`.\n */\n originLock?: ResolvedOriginLock\n /**\n * The header the CDN sends the origin secret in, removed from every request whether or not the lock is on: an edge\n * that sends it to a host without the variable must not hand it to handlers or the storefront.\n */\n originLockHeader?: string\n cors?: CorsOptions\n /** Whether the CSRF cookie carries `Secure`: `secureCookies(config, env)`. */\n secureCookies?: boolean\n}\n\n/** How long a stream ended at shutdown may take to flush before its socket is destroyed regardless. */\nconst STREAM_END_BOUND_MS = 500\n\n/** The platform's health checks reach the API directly, never through the CDN. */\nconst UNLOCKED_ROUTES = new Set(['/health', '/ready'])\nconst isLoopback = proxyAddr.compile('loopback')\n\n/** A fixed-length digest, so comparing it takes the same time whatever the length or content of the value sent. */\nconst digest = (value: string): Buffer => createHash('sha256').update(value).digest()\n\nexport class FastifyHttpAdapter implements HttpAdapter {\n readonly #app: FastifyInstance\n readonly #logger: Logger\n readonly #guard: SecurityGuard\n readonly #attestation: ShopperAttestation = createShopperAttestation()\n readonly #middlewares: MiddlewareHandler[] = []\n readonly #defaultHeaders: Record<string, string> = {}\n /** Ends each open stream for shutdown; a stream removes itself once its close callbacks have run. */\n readonly #openStreams = new Set<() => void>()\n #started = false\n #stopping = false\n #boundPort = 0\n /** Decides both Fastify's walk of X-Forwarded-For and whether the peer may speak for the client. */\n readonly #trusts: (address: string, hop: number) => boolean\n /** Lower-cased, as Node keys request headers. */\n readonly #clientIpHeader: string | undefined\n readonly clientIpRequiresLock: boolean\n /** Lower-cased, as Node keys request headers. */\n readonly #lockHeader: string | undefined\n readonly #lockDigests: readonly Buffer[]\n /** Lower-cased: every header the secret may arrive in, removed from each request. */\n readonly #proofHeaders: readonly string[]\n #warnedUnlistedPeer = false\n #warnedClientIpHeader = false\n #warnedOriginLocked = false\n\n constructor(options: FastifyAdapterOptions) {\n this.#logger = options.logger\n this.#trusts = proxyAddr.compile(options.trustedProxies ?? ['loopback'])\n this.#clientIpHeader = options.clientIpHeader?.toLowerCase()\n this.clientIpRequiresLock = options.clientIpRequiresLock ?? false\n this.#lockHeader = options.originLock?.header.toLowerCase()\n this.#lockDigests = (options.originLock?.secrets ?? []).map(digest)\n this.#proofHeaders = [\n ...new Set(\n [options.originLockHeader?.toLowerCase(), this.#lockHeader].filter(\n (h): h is string => h !== undefined,\n ),\n ),\n ]\n this.#guard = createSecurityGuard(options.security, {\n attestation: this.#attestation,\n secureCookies: options.secureCookies ?? false,\n })\n this.#app = Fastify({\n logger: false,\n trustProxy: this.#trusts,\n disableRequestLogging: true,\n // Fastify's default takes `req.id` from an inbound `request-id` header, unvalidated; the id is always ours.\n requestIdHeader: false,\n genReqId: () => uuidv7(),\n })\n // Hooks rather than #buildContext and #applyEnvelope: Fastify's own 404 and body-parse 400 never reach a route\n // handler, and they carry the id too.\n this.#app.decorateRequest('correlationId', '')\n this.#app.decorateRequest('clientIp', '')\n this.#app.addHook('onRequest', async (req, reply) => {\n const inbound = req.headers[CORRELATION_ID_HEADER]\n if (typeof inbound === 'string' && isValidCorrelationId(inbound)) req.correlationId = inbound\n else req.correlationId = isValidCorrelationId(req.id) ? req.id : uuidv7()\n const locked = this.#takeOriginProof(req)\n if (!locked && this.#refusesUnlocked(req)) {\n req.clientIp = req.raw.socket.remoteAddress ?? req.ip\n return this.#refuseOrigin(req, reply)\n }\n req.clientIp = this.#resolveClientIp(req, locked)\n })\n this.#app.addHook('onSend', async (req, reply, payload) => {\n reply.header(CORRELATION_ID_HEADER, req.correlationId)\n // An API answer that chooses no caching of its own is shopper state: a disk-cached cart would come back on Back.\n if (req.url.startsWith('/api/') && !reply.hasHeader('cache-control')) {\n reply.header('cache-control', 'no-store')\n }\n return payload\n })\n // A signed webhook is verified against the bytes sent, so a route registered with `rawBody` keeps them. The\n // body is still parsed by Fastify's own JSON parser, with its poisoning settings and its 400s.\n const parseJson = this.#app.getDefaultJsonParser(\n this.#app.initialConfig.onProtoPoisoning ?? 'error',\n this.#app.initialConfig.onConstructorPoisoning ?? 'error',\n )\n const takesRawBody = (req: FastifyRequest): boolean =>\n (req.routeOptions.config as { routeOptions?: RouteOptions } | undefined)?.routeOptions\n ?.rawBody === true\n this.#app.removeContentTypeParser('application/json')\n this.#app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (req, body, done) => {\n const buffer = body as Buffer\n if (takesRawBody(req)) req.rawBody = buffer\n parseJson(req, buffer.toString('utf8'), done)\n })\n // Providers also post form-encoded, plain-text and other bodies, signing those bytes too, so a `rawBody` route\n // takes every type, its body the UTF-8 text. Every other route answers as Fastify does by default: `text/plain` as\n // a string, anything else (a bodied request with no Content-Type included) 415, and an unknown URL its 404.\n const keepRawBody =\n (elsewhere: 'text' | 'refuse') =>\n (\n req: FastifyRequest,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n ) => {\n const buffer = body as Buffer\n if (takesRawBody(req)) req.rawBody = buffer\n else if (elsewhere === 'refuse' && !req.is404) {\n done(new errorCodes.FST_ERR_CTP_INVALID_MEDIA_TYPE(req.headers['content-type']))\n return\n }\n done(null, buffer.toString('utf8'))\n }\n this.#app.removeContentTypeParser('text/plain')\n this.#app.addContentTypeParser('text/plain', { parseAs: 'buffer' }, keepRawBody('text'))\n this.#app.addContentTypeParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'buffer' },\n keepRawBody('refuse'),\n )\n this.#app.addContentTypeParser('*', { parseAs: 'buffer' }, keepRawBody('refuse'))\n // Fastify's `close()` waits for every open connection, and a stream never ends by itself. `preClose` runs after\n // Fastify answers new requests 503 and before `server.close()`, so no stream can hold the close once it has run.\n this.#app.addHook('preClose', async () => {\n this.#stopping = true\n for (const endStream of this.#openStreams) endStream()\n })\n void this.#app.register(fastifyCookie)\n if (options.cors && options.cors.allowedOrigins.length > 0) {\n void this.#app.register(fastifyCors, {\n origin: options.cors.allowedOrigins,\n credentials: options.cors.credentials,\n methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],\n // A browser client on an allowed origin reads the request's id and whether a keyed write was a replay.\n exposedHeaders: [CORRELATION_ID_HEADER, IDEMPOTENT_REPLAYED_HEADER],\n })\n }\n // The token a client on another origin of the same site echoes in `x-csrf-token`: it cannot read this cookie.\n this.registerRoute('GET', '/api/csrf', (ctx) => this.#guard.issueToken(ctx))\n }\n\n get boundPort(): number {\n return this.#boundPort\n }\n\n /**\n * A token for `ip` that this adapter's guard, and no other, accepts in `x-nymbal-shopper` for the next minute: the\n * storefront forward's proof of the shopper's address.\n */\n attestShopper(ip: string): string {\n return this.#attestation.mint(ip)\n }\n\n /** Fastify's `inject`: `remoteAddress` sets the socket peer, which a request from loopback cannot. */\n inject(options: InjectOptions): Promise<LightMyRequestResponse> {\n return this.#app.inject(options)\n }\n\n /** The guard every route passes, for a mounted handler that admits a request it serves on a route's behalf. */\n get guard(): SecurityGuard {\n return this.#guard\n }\n\n /**\n * A route whose handler answers a web-standard `Response` (the MCP endpoint's SDK), or an envelope when it refuses.\n * It passes the guard and the middlewares as every route does.\n */\n registerWebRoute(\n method: HttpMethod,\n path: string,\n handler: (ctx: RequestContext) => Promise<Response | ResponseEnvelope>,\n options?: RouteOptions,\n ): void {\n if (this.#started) {\n throw new Error('Cannot register routes after the server has started')\n }\n this.#app.route({\n method,\n url: path,\n handler: async (req, reply) => {\n const ctx = this.#buildContext(req, false)\n const refused = this.#guard.admit(ctx, options)\n if (refused) return this.#applyEnvelope(reply, refused)\n let answer: Response | ResponseEnvelope\n try {\n answer = await this.#runMiddlewaresThen(ctx, handler)\n } catch (err) {\n answer = this.#renderError(err, ctx)\n }\n if (!(answer instanceof Response)) {\n return this.#applyEnvelope(reply, this.#guard.finish(ctx, answer))\n }\n const { headers } = this.#guard.finish(ctx, { status: answer.status })\n for (const [name, value] of Object.entries({ ...this.#defaultHeaders, ...headers })) {\n reply.header(name, value)\n }\n return reply.send(answer)\n },\n config: { routeOptions: options ?? {} },\n })\n }\n\n registerRoute(\n method: HttpMethod,\n path: string,\n handler: RouteHandler,\n options?: RouteOptions,\n ): void {\n if (this.#started) {\n throw new Error('Cannot register routes after the server has started')\n }\n const routeConfig: {\n method: HttpMethod\n url: string\n handler: (req: FastifyRequest, reply: FastifyReply) => Promise<FastifyReply>\n config: { routeOptions: RouteOptions }\n bodyLimit?: number\n } = {\n method,\n url: path,\n handler: async (req, reply) => {\n const ctx = this.#buildContext(req, options?.rawBody ?? false)\n const refused = this.#guard.admit(ctx, options)\n if (refused) return this.#applyEnvelope(reply, refused)\n let envelope: ResponseEnvelope\n try {\n envelope = await this.#runMiddlewaresThen(ctx, handler)\n } catch (err) {\n envelope = this.#renderError(err, ctx)\n }\n return this.#applyEnvelope(reply, this.#guard.finish(ctx, envelope))\n },\n config: { routeOptions: options ?? {} },\n }\n this.#app.route(routeConfig)\n }\n\n registerStreamRoute(\n method: 'GET',\n path: string,\n handler: StreamHandler,\n options?: RouteOptions,\n ): void {\n if (this.#started) {\n throw new Error('Cannot register routes after the server has started')\n }\n this.#app.route({\n method,\n url: path,\n handler: async (req, reply) => {\n const ctx = this.#buildContext(req, false)\n const refused = this.#guard.admit(ctx, options)\n if (refused) return this.#applyEnvelope(reply, refused)\n try {\n for (const mw of this.#middlewares) {\n const out = await mw(ctx)\n if (out) {\n return this.#applyEnvelope(reply, out)\n }\n }\n } catch (err) {\n return this.#applyEnvelope(reply, this.#renderError(err, ctx))\n }\n // Routed before Fastify began closing, but its middlewares finished after the open streams were ended.\n if (this.#stopping) {\n return this.#applyEnvelope(reply, {\n status: 503,\n headers: { connection: 'close' },\n body: { error: { code: 'unavailable', message: 'Server is shutting down' } },\n })\n }\n const raw = reply.raw\n // Taken now: a finished response detaches from its socket before `end`'s callback runs.\n const socket = req.raw.socket\n // A hijacked reply skips onSend.\n raw.writeHead(200, {\n ...this.#defaultHeaders,\n [CORRELATION_ID_HEADER]: ctx.correlationId,\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n 'x-accel-buffering': 'no',\n })\n reply.hijack()\n const closeCallbacks: Array<() => void> = []\n let ending = false\n let closed = false\n const end = (then?: () => void): void => {\n if (ending) return\n ending = true\n try {\n raw.end(then)\n } catch {\n // ignore\n }\n }\n // A clean end, so the client sees a complete response, then the keep-alive socket goes too: it would hold\n // `server.close()` open. The bound covers a socket whose end never flushes.\n const endForShutdown = (): void => {\n const bound = setTimeout(() => socket.destroy(), STREAM_END_BOUND_MS)\n bound.unref()\n end(() => {\n clearTimeout(bound)\n socket.destroy()\n })\n }\n const close = (): void => {\n end()\n if (closed) return\n closed = true\n this.#openStreams.delete(endForShutdown)\n for (const cb of closeCallbacks) {\n try {\n cb()\n } catch (err) {\n ctx.logger.error({ err }, 'stream close callback failed')\n }\n }\n }\n req.raw.on('close', close)\n req.raw.on('error', close)\n this.#openStreams.add(endForShutdown)\n const stream: StreamContext = {\n send(event: SseEvent): void {\n if (ending) return\n let line = ''\n if (event.id !== undefined) line += `id: ${event.id}\\n`\n if (event.event !== undefined) line += `event: ${event.event}\\n`\n const data = typeof event.data === 'string' ? event.data : JSON.stringify(event.data)\n line += `data: ${data}\\n\\n`\n raw.write(line)\n },\n close,\n onClose(cb: () => void): void {\n closeCallbacks.push(cb)\n },\n }\n try {\n await handler(ctx, stream)\n } catch (err) {\n ctx.logger.error({ err }, 'stream handler threw')\n close()\n }\n return reply\n },\n config: { routeOptions: options ?? {} },\n })\n }\n\n /** A Fastify plugin on this server, in a context of its own: how the storefront forward is added. */\n registerPlugin(plugin: FastifyPluginAsync): void {\n if (this.#started) {\n throw new Error('Cannot register plugins after the server has started')\n }\n void this.#app.register(plugin)\n }\n\n registerMiddleware(middleware: MiddlewareHandler): void {\n if (this.#started) {\n throw new Error('Cannot register middleware after the server has started')\n }\n this.#middlewares.push(middleware)\n }\n\n setDefaultHeaders(headers: Record<string, string>): void {\n for (const [k, v] of Object.entries(headers)) {\n this.#defaultHeaders[k.toLowerCase()] = v\n }\n }\n\n async start(port: number, host = '0.0.0.0'): Promise<void> {\n await this.#app.listen({ port, host })\n this.#boundPort = (this.#app.server.address() as { port: number }).port\n this.#started = true\n this.#logger.debug({ port: this.#boundPort, host }, 'HTTP server listening')\n }\n\n async stop(): Promise<void> {\n if (!this.#started) return\n await this.#app.close()\n this.#started = false\n }\n\n async #runMiddlewaresThen<T extends Response | ResponseEnvelope>(\n ctx: RequestContext,\n handler: (ctx: RequestContext) => Promise<T> | T,\n ): Promise<T | ResponseEnvelope> {\n for (const mw of this.#middlewares) {\n const out = await mw(ctx)\n if (out) return out\n }\n return handler(ctx)\n }\n\n /**\n * Whether the request carries one of the origin secrets, compared by digest against every entry. The header is\n * removed whatever the outcome and with the lock off too, so no handler, log line or storefront forward sees it.\n */\n #takeOriginProof(req: FastifyRequest): boolean {\n const name = this.#lockHeader\n const sent = name === undefined ? undefined : req.headers[name]\n for (const header of this.#proofHeaders) delete req.headers[header]\n if (typeof sent !== 'string') return false\n const given = digest(sent)\n let matched = false\n for (const entry of this.#lockDigests) matched = timingSafeEqual(given, entry) || matched\n return matched\n }\n\n /** An unlocked request is refused unless the lock is off, it comes from this machine, or it is a health check. */\n #refusesUnlocked(req: FastifyRequest): boolean {\n if (this.#lockHeader === undefined) return false\n const peer = req.raw.socket.remoteAddress\n if (peer !== undefined && isLoopback(peer, 0)) return false\n return req.is404 || !UNLOCKED_ROUTES.has(req.routeOptions.url ?? '')\n }\n\n #refuseOrigin(req: FastifyRequest, reply: FastifyReply): FastifyReply {\n if (!this.#warnedOriginLocked) {\n this.#warnedOriginLocked = true\n const peer = req.raw.socket.remoteAddress ?? req.ip\n const header = this.#lockHeader!\n this.#requestLogger(req).warn(\n { peer, header },\n `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`,\n )\n }\n return this.#applyEnvelope(reply, {\n status: 403,\n body: {\n error: {\n code: 'origin_locked',\n message: 'This API answers only requests that reach it through the store’s CDN',\n },\n },\n })\n }\n\n /**\n * The one client address a request resolves to. An unlisted peer is the client, whatever it sends. From a listed peer,\n * the client-address header when one is configured (a single IP address, else the peer), otherwise X-Forwarded-For\n * walked by Fastify with the same list. A header that requires the lock counts on a locked request from any peer and\n * is not read on any other.\n */\n #resolveClientIp(req: FastifyRequest, locked: boolean): string {\n const peer = req.raw.socket.remoteAddress\n if (peer === undefined) return req.ip\n const header = this.clientIpRequiresLock && !locked ? undefined : this.#clientIpHeader\n const fromAnyPeer = this.clientIpRequiresLock && header !== undefined\n if (!fromAnyPeer && !this.#trusts(peer, 0)) {\n const carried =\n req.headers['x-forwarded-for'] !== undefined\n ? 'x-forwarded-for'\n : header !== undefined && req.headers[header] !== undefined\n ? header\n : undefined\n if (carried !== undefined && !this.#warnedUnlistedPeer) {\n this.#warnedUnlistedPeer = true\n const suggested = trustSuggestion(peer)\n this.#requestLogger(req).warn(\n { peer, header: carried, variable: TRUSTED_PROXIES_ENV, suggested },\n `${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}`,\n )\n }\n return peer\n }\n if (header === undefined) return req.ip\n const value = req.headers[header]\n if (value === undefined) return peer\n if (typeof value === 'string' && !value.includes(',') && isIP(value) !== 0) return value\n const reason = typeof value !== 'string' || value.includes(',') ? 'multiple' : 'invalid'\n if (!this.#warnedClientIpHeader) {\n this.#warnedClientIpHeader = true\n this.#requestLogger(req).warn(\n { peer, header, reason },\n `${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`,\n )\n }\n return peer\n }\n\n #requestLogger(req: FastifyRequest): Logger {\n return this.#logger.child({ requestId: req.id, correlationId: req.correlationId })\n }\n\n #buildContext(req: FastifyRequest, includeRawBody: boolean): RequestContext {\n const { correlationId } = req\n const logger = this.#logger.child({ requestId: req.id, correlationId })\n const ctx: RequestContext = {\n method: req.method as HttpMethod,\n path: req.routeOptions?.url ?? req.url,\n url: req.url,\n params: (req.params ?? {}) as Record<string, string>,\n query: (req.query ?? {}) as Record<string, string | string[] | undefined>,\n body: req.body,\n headers: req.headers,\n cookies: (req.cookies ?? {}) as Record<string, string>,\n requestId: req.id,\n correlationId,\n logger,\n ip: req.clientIp,\n }\n if (includeRawBody && Buffer.isBuffer(req.rawBody)) {\n ctx.rawBody = req.rawBody\n }\n return ctx\n }\n\n #applyEnvelope(reply: FastifyReply, envelope: ResponseEnvelope): FastifyReply {\n reply.status(envelope.status)\n for (const [name, value] of Object.entries(this.#defaultHeaders)) {\n reply.header(name, value)\n }\n if (envelope.headers) {\n for (const [name, value] of Object.entries(envelope.headers)) {\n reply.header(name, value)\n }\n }\n if (envelope.cookies) {\n for (const cookie of envelope.cookies) {\n reply.setCookie(cookie.name, cookie.value, {\n path: cookie.path ?? '/',\n ...(cookie.domain !== undefined && { domain: cookie.domain }),\n ...(cookie.maxAge !== undefined && { maxAge: cookie.maxAge }),\n httpOnly: cookie.httpOnly ?? false,\n secure: cookie.secure ?? false,\n ...(cookie.sameSite !== undefined && { sameSite: cookie.sameSite }),\n })\n }\n }\n if (envelope.body === undefined) {\n return reply.send()\n }\n return reply.send(envelope.body)\n }\n\n #renderError(err: unknown, ctx: RequestContext): ResponseEnvelope {\n if (err instanceof HttpError) {\n ctx.logger.warn({ err: err.toJSON() }, err.message)\n return {\n status: err.status,\n body: { error: { code: err.code, message: err.message } },\n }\n }\n if (err instanceof NymbalError) {\n ctx.logger.error({ err: err.toJSON() }, err.message)\n return {\n status: 500,\n body: { error: { code: err.code, message: err.message } },\n }\n }\n const message = err instanceof Error ? err.message : String(err)\n ctx.logger.error({ err }, message)\n return {\n status: 500,\n body: { error: { code: 'internal', message: 'Internal server error' } },\n }\n }\n}\n\ndeclare module 'fastify' {\n interface FastifyRequest {\n rawBody?: Buffer\n /** Set by the onRequest hook before anything else runs. */\n correlationId: string\n /** The client address the request resolves to, set by the onRequest hook: what every reader of the address uses. */\n clientIp: string\n }\n}\n","import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'\nimport type { NymbalConfig } from '@nymbalhq/config'\nimport {\n SHOPPER_ATTESTATION_HEADER,\n type RequestContext,\n type ResponseCookie,\n type ResponseEnvelope,\n type RouteOptions,\n} from '@nymbalhq/types'\nimport { BUILT_IN_RATE_LIMITS, CHECKOUT_ADDRESS_CEILING, RateLimiter } from './rate-limit.js'\nimport type { ShopperAttestation } from './shopper-attestation.js'\n\nexport const CSRF_COOKIE = 'nymbal.csrf'\nexport const CSRF_HEADER = 'x-csrf-token'\nconst UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nexport function buildSecurityHeaders(security: NymbalConfig['security']): Record<string, string> {\n const headers: Record<string, string> = {}\n if (security.headers.hsts) {\n headers['strict-transport-security'] = 'max-age=31536000; includeSubDomains'\n }\n const csp = security.headers.contentSecurityPolicy\n const cspValue =\n csp === 'strict'\n ? \"default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'\"\n : csp === 'relaxed'\n ? \"default-src 'self' https:; img-src * data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'\"\n : csp === 'off'\n ? null\n : csp\n if (cspValue) headers['content-security-policy'] = cspValue\n headers['referrer-policy'] = security.headers.referrerPolicy\n headers['x-frame-options'] = security.headers.xFrameOptions === 'deny' ? 'DENY' : 'SAMEORIGIN'\n headers['x-content-type-options'] = 'nosniff'\n return headers\n}\n\nexport interface SecurityGuard {\n /**\n * Runs before any middleware or handler: the rate limit, then CSRF on unsafe methods unless the route opted out.\n * Returns the refusal, or null when the request may proceed.\n */\n admit(ctx: RequestContext, options?: RouteOptions): ResponseEnvelope | null\n /**\n * Runs on the handler's answer: security headers and the outcome of a failure-counted login. It sets no CSRF\n * cookie: parallel first requests would each mint a different one, and the browser would keep whichever came last.\n */\n finish(ctx: RequestContext, envelope: ResponseEnvelope): ResponseEnvelope\n /** `GET /api/csrf`, the only answer that sets the CSRF cookie: the request's own, or a new one set on the response. */\n issueToken(ctx: RequestContext): ResponseEnvelope\n /** The rate-limit buckets held: what a client's requests can make the guard keep. */\n bucketCount(): number\n reset(): void\n}\n\n/**\n * Counts failures only. The address bucket refuses; the account count never does, so failures from elsewhere cannot\n * lock an owner out, and reaching the rule's count logs one warn per window for the operator instead.\n */\nconst LOGIN_PATH = '/api/auth/login'\nconst CHECKOUT_PATH = '/api/checkout'\nconst CART_COOKIE = 'nymbal.cart'\n\nfunction csrfCookie(token: string, secure: boolean): ResponseCookie {\n return {\n name: CSRF_COOKIE,\n value: token,\n path: '/',\n httpOnly: false,\n sameSite: 'lax',\n secure,\n }\n}\n\n/** The lowercased email of a login, or null when the body names none. */\nfunction loginAccount(ctx: RequestContext): string | null {\n const email = (ctx.body as { email?: unknown } | undefined)?.email\n return typeof email === 'string' && email !== '' ? email.toLowerCase() : null\n}\n\n/**\n * A checkout's two buckets: the (address, cart) pair at the rule's count and the address at the ceiling. The cart\n * enters the key as a fixed-length digest, so a cookie's length never reaches the limiter.\n */\nexport function checkoutKeys(\n ctx: RequestContext,\n ip: string = ctx.ip,\n): { pair: string; address: string } {\n const cart = ctx.cookies[CART_COOKIE]\n const digest = cart ? createHash('sha256').update(cart).digest('hex').slice(0, 32) : ''\n return { pair: `${ip}|cart:${digest}`, address: ip }\n}\n\nfunction isLogin(ctx: RequestContext): boolean {\n return ctx.method === 'POST' && ctx.path === LOGIN_PATH\n}\n\nfunction isCheckout(ctx: RequestContext): boolean {\n return ctx.method === 'POST' && ctx.path === CHECKOUT_PATH\n}\n\nexport interface SecurityGuardOptions {\n /** Verifies the storefront forward's `x-nymbal-shopper`: a verified address is the limiter's key for the request. */\n attestation?: ShopperAttestation\n /** Whether the CSRF cookie carries `Secure` (`secureCookies(config, env)` in `@nymbalhq/config`). */\n secureCookies?: boolean\n}\n\nexport function createSecurityGuard(\n security: NymbalConfig['security'],\n options: SecurityGuardOptions = {},\n): SecurityGuard {\n const rateLimiter = new RateLimiter({ ...BUILT_IN_RATE_LIMITS, ...security.rateLimit })\n const { attestation, secureCookies = false } = options\n\n /** The shopper's address the storefront forward attested, or the request's own; a token that fails is ignored. */\n function clientIp(ctx: RequestContext): string {\n return attestation?.verify(ctx.headers[SHOPPER_ATTESTATION_HEADER]) ?? ctx.ip\n }\n\n /** The address bucket first: a request it refuses opens no cart bucket. */\n function checkCheckout(ctx: RequestContext, ip: string) {\n const keys = checkoutKeys(ctx, ip)\n const address = rateLimiter.check(keys.address, ctx.path, ctx.headers, CHECKOUT_ADDRESS_CEILING)\n if (address && !address.allowed) return address\n return rateLimiter.check(keys.pair, ctx.path, ctx.headers)\n }\n\n const baseHeaders = buildSecurityHeaders(security)\n\n function applyHeaders(envelope: ResponseEnvelope): ResponseEnvelope {\n return {\n ...envelope,\n headers: { ...baseHeaders, ...(envelope.headers ?? {}) },\n }\n }\n\n return {\n admit(ctx, options = {}) {\n const ip = clientIp(ctx)\n const decision = isLogin(ctx)\n ? rateLimiter.full(ctx.path, [ip])\n : isCheckout(ctx)\n ? checkCheckout(ctx, ip)\n : rateLimiter.check(ip, ctx.path, ctx.headers)\n if (decision && !decision.allowed) {\n return applyHeaders(rateLimitResponse(decision, ctx))\n }\n\n if (security.csrf && options.csrf !== false && UNSAFE_METHODS.has(ctx.method)) {\n if (!verifyCsrf(ctx)) {\n ctx.logger.warn({ method: ctx.method, path: ctx.path }, 'CSRF validation failed')\n return applyHeaders({\n status: 403,\n body: { error: { code: 'csrf.invalid', message: 'Invalid or missing CSRF token' } },\n })\n }\n }\n return null\n },\n\n finish(ctx, envelope) {\n if (isLogin(ctx)) {\n const account = loginAccount(ctx)\n const accountKey = account === null ? [] : [`account:${account}`]\n // Success clears the account only: the address bucket expires with its window, so logging in to one's own\n // account cannot reset a spray across other accounts.\n if (envelope.status >= 200 && envelope.status < 300) {\n rateLimiter.clear(ctx.path, accountKey)\n } else {\n const [, failures] = rateLimiter.hit(ctx.path, [clientIp(ctx), ...accountKey])\n if (failures !== undefined && failures === rateLimiter.requests(ctx.path)) {\n ctx.logger.warn(\n { account, failures, path: ctx.path },\n 'Failed logins for one account reached the login limit; it is not locked, each address is',\n )\n }\n }\n }\n return applyHeaders(envelope)\n },\n\n issueToken(ctx) {\n const existing = ctx.cookies[CSRF_COOKIE]\n if (existing) return { status: 200, body: { data: { token: existing } } }\n const token = newToken()\n return { status: 200, body: { data: { token } }, cookies: [csrfCookie(token, secureCookies)] }\n },\n\n bucketCount() {\n return rateLimiter.size\n },\n\n reset() {\n rateLimiter.reset()\n },\n }\n}\n\nfunction newToken(): string {\n return randomBytes(32).toString('hex')\n}\n\nfunction verifyCsrf(ctx: RequestContext): boolean {\n const cookieToken = ctx.cookies[CSRF_COOKIE]\n const rawHeader = ctx.headers[CSRF_HEADER]\n const headerToken = Array.isArray(rawHeader) ? rawHeader[0] : rawHeader\n if (!cookieToken || !headerToken) return false\n if (cookieToken.length !== headerToken.length) return false\n try {\n return timingSafeEqual(Buffer.from(cookieToken), Buffer.from(headerToken))\n } catch {\n return false\n }\n}\n\nfunction rateLimitResponse(\n decision: { action: string; retryAfter?: number },\n ctx: RequestContext,\n): ResponseEnvelope {\n ctx.logger.info({ ip: ctx.ip, path: ctx.path, action: decision.action }, 'Rate limit triggered')\n const status = decision.action === 'challenge' ? 403 : 429\n const headers: Record<string, string> = {}\n if (decision.retryAfter) headers['retry-after'] = String(decision.retryAfter)\n return {\n status,\n headers,\n body: {\n error: {\n code: `rate_limit.${decision.action}`,\n message: 'Too many requests',\n ...(decision.retryAfter !== undefined && { retryAfter: decision.retryAfter }),\n },\n },\n }\n}\n","import { ORDER_EMAIL_HEADER, type RateLimitAction } from '@nymbalhq/types'\n\nexport interface ParsedRule {\n pattern: string\n regex: RegExp\n /** The rule counts only requests that carry this header (lower case). */\n header?: string\n requests: number\n windowMs: number\n action: RateLimitAction\n}\n\nexport interface RateLimitDecision {\n allowed: boolean\n action: RateLimitAction\n retryAfter?: number\n}\n\ntype RateLimitRules = Record<\n string,\n { requests: number; window: string; action: RateLimitAction; header?: string | undefined }\n>\n\n/**\n * Applied under the configured rules: a configured key with the same pattern replaces its default, and the defaults\n * stay when other keys are configured.\n */\nexport const BUILT_IN_RATE_LIMITS: RateLimitRules = {\n '/api/auth/login': { requests: 10, window: '15m', action: 'block' },\n '/api/auth/register': { requests: 10, window: '1h', action: 'block' },\n // A record and a list per page view: 300 page views a minute, so shoppers behind one NAT keep their views.\n '/api/recently-viewed': { requests: 600, window: '1m', action: 'block' },\n // Each accepted subscribe mails a confirmation: the bound on how much mail one IP can make the store send.\n '/api/alerts/subscribe': { requests: 10, window: '1h', action: 'block' },\n // Each accepted review waits in the moderation queue: the bound on how much one IP can put there.\n '/api/reviews': { requests: 10, window: '1h', action: 'block' },\n // Each match mails the order's link. Before the order-read rule, which a request carrying the email would also match.\n '/api/orders/link': { requests: 5, window: '1h', action: 'block' },\n // The email is the second factor of an expired order key: bounded so it cannot be guessed. The key-only poll of a\n // pending order carries no email and is never counted.\n '/api/orders/*': { requests: 10, window: '1h', action: 'block', header: ORDER_EMAIL_HEADER },\n // Every checkout answer can mint an order key.\n '/api/checkout': { requests: 30, window: '1m', action: 'block' },\n // Each agent request runs a tool, which is also held to its own route's rule.\n '/api/mcp': { requests: 120, window: '1m', action: 'block' },\n // A UCP tool is not a route: each request counts once here, however many routes its tool runs.\n '/api/ucp/mcp': { requests: 120, window: '1m', action: 'block' },\n // `**`: every ACP path, the session's own and the ones below it, counts in the one bucket.\n '/api/acp/**': { requests: 120, window: '1m', action: 'block' },\n}\n\ninterface Bucket {\n count: number\n resetAt: number\n}\n\n/** The map size that triggers the first sweep of expired buckets. */\nconst PRUNE_THRESHOLD = 1024\n\n/**\n * Checkouts count per (address, cart) at the checkout rule's count, so shoppers behind one proxy do not refuse each\n * other's, and per address at this multiple of it, since carts are free to mint.\n */\nexport const CHECKOUT_ADDRESS_CEILING = 10\n\nexport class RateLimiter {\n readonly #rules: ParsedRule[]\n readonly #buckets = new Map<string, Bucket>()\n #pruneAt = PRUNE_THRESHOLD\n\n constructor(rules: RateLimitRules) {\n this.#rules = Object.entries(rules).map(([pattern, rule]) => ({\n pattern,\n regex: compilePathPattern(pattern),\n ...(rule.header !== undefined && { header: rule.header.toLowerCase() }),\n requests: rule.requests,\n windowMs: parseWindow(rule.window),\n action: rule.action,\n }))\n }\n\n /** Counts this request under `key` and refuses past the rule's count, times `scale` for a key that pools several. */\n check(\n key: string,\n path: string,\n headers: Readonly<Record<string, unknown>> = {},\n scale = 1,\n ): RateLimitDecision | null {\n const rule = this.#ruleFor(path, headers)\n if (!rule) return null\n const bucketKey = `${rule.pattern}|${key}`\n const now = Date.now()\n const bucket = this.#buckets.get(bucketKey)\n if (!bucket || bucket.resetAt <= now) {\n this.#open(bucketKey, now, rule.windowMs)\n return { allowed: true, action: rule.action }\n }\n bucket.count += 1\n if (bucket.count > rule.requests * scale) {\n return { allowed: false, action: rule.action, retryAfter: retryAfter(bucket, now) }\n }\n return { allowed: true, action: rule.action }\n }\n\n /**\n * For a route that counts failures only: refuses when any of `keys` already holds the rule's full count, without\n * counting this request. `hit` and `clear` record the outcome once the handler has answered.\n */\n full(path: string, keys: string[]): RateLimitDecision | null {\n const rule = this.#ruleFor(path)\n if (!rule) return null\n const now = Date.now()\n for (const key of keys) {\n const bucket = this.#buckets.get(`${rule.pattern}|${key}`)\n if (bucket && bucket.resetAt > now && bucket.count >= rule.requests) {\n return { allowed: false, action: rule.action, retryAfter: retryAfter(bucket, now) }\n }\n }\n return { allowed: true, action: rule.action }\n }\n\n /** Counts one under each of `keys`; returns each bucket's count after it, in the order of `keys`. */\n hit(path: string, keys: string[]): number[] {\n const rule = this.#ruleFor(path)\n if (!rule) return []\n const now = Date.now()\n return keys.map((key) => {\n const bucketKey = `${rule.pattern}|${key}`\n const bucket = this.#buckets.get(bucketKey)\n if (!bucket || bucket.resetAt <= now) {\n this.#open(bucketKey, now, rule.windowMs)\n return 1\n }\n bucket.count += 1\n return bucket.count\n })\n }\n\n /** The count the rule for `path` allows per window, or undefined when no rule applies. */\n requests(path: string): number | undefined {\n return this.#ruleFor(path)?.requests\n }\n\n /** The buckets held, expired ones not yet swept included. */\n get size(): number {\n return this.#buckets.size\n }\n\n clear(path: string, keys: string[]): void {\n const rule = this.#ruleFor(path)\n if (!rule) return\n for (const key of keys) this.#buckets.delete(`${rule.pattern}|${key}`)\n }\n\n reset(): void {\n this.#buckets.clear()\n this.#pruneAt = PRUNE_THRESHOLD\n }\n\n /**\n * Starts a bucket. Keys include caller-chosen values (an account email), so expired buckets are swept once the map\n * reaches `#pruneAt`; the next sweep waits until the map doubles past what survived, which keeps the cost amortised\n * constant per insert even when every bucket is live.\n */\n #open(key: string, now: number, windowMs: number): void {\n if (this.#buckets.size >= this.#pruneAt) {\n for (const [k, b] of this.#buckets) if (b.resetAt <= now) this.#buckets.delete(k)\n this.#pruneAt = Math.max(PRUNE_THRESHOLD, this.#buckets.size * 2)\n }\n this.#buckets.set(key, { count: 1, resetAt: now + windowMs })\n }\n\n #ruleFor(path: string, headers: Readonly<Record<string, unknown>> = {}): ParsedRule | undefined {\n return this.#rules.find(\n (r) => r.regex.test(path) && (r.header === undefined || headers[r.header] !== undefined),\n )\n }\n}\n\nfunction retryAfter(bucket: Bucket, now: number): number {\n return Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))\n}\n\nfunction parseWindow(window: string): number {\n const match = /^(\\d+)(ms|s|m|h)$/.exec(window)\n if (!match) throw new Error(`Invalid rate-limit window: ${window}`)\n const n = Number(match[1])\n switch (match[2]) {\n case 'ms':\n return n\n case 's':\n return n * 1000\n case 'm':\n return n * 60_000\n case 'h':\n return n * 3_600_000\n default:\n throw new Error(`Unreachable unit: ${match[2]}`)\n }\n}\n\nfunction compilePathPattern(pattern: string): RegExp {\n const escaped = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '__DOUBLESTAR__')\n .replace(/\\*/g, '[^/]+')\n .replace(/__DOUBLESTAR__/g, '.*')\n return new RegExp(`^${escaped}$`)\n}\n","import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'\n\nexport interface ShopperAttestation {\n /** A token for `ip`, valid until `now + ttl`: `<ip>~<expiresMs>~<base64url mac>`. */\n mint(ip: string, now?: number): string\n /** The address `token` was minted for, or null when it is not a live token under this key. */\n verify(token: unknown, now?: number): string | null\n}\n\n/**\n * The API's proof, on a request it forwards to the storefront, of the shopper's address, so the storefront server's\n * own API calls for that shopper count against the shopper. The key lives only in this process: a token from another\n * process or a previous boot does not verify. `~` appears in no IPv4 or IPv6 address, so the three segments are\n * unambiguous.\n */\nexport function createShopperAttestation(\n key: Buffer = randomBytes(32),\n ttlMs = 60_000,\n): ShopperAttestation {\n const sign = (ip: string, expires: number): string => {\n const body = `${ip}~${expires}`\n return `${body}~${createHmac('sha256', key).update(body).digest('base64url')}`\n }\n return {\n mint(ip, now = Date.now()) {\n return sign(ip, now + ttlMs)\n },\n verify(token, now = Date.now()) {\n if (typeof token !== 'string') return null\n const segments = token.split('~')\n if (segments.length !== 3) return null\n const [ip, expiresText] = segments as [string, string, string]\n if (ip === '' || !/^\\d+$/.test(expiresText)) return null\n const expires = Number(expiresText)\n if (!Number.isSafeInteger(expires) || now >= expires) return null\n // The recomputed text, not the decoded mac: base64url's last character carries spare bits, so two texts can\n // decode to the same bytes.\n const expected = Buffer.from(sign(ip, expires))\n const given = Buffer.from(token)\n if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null\n return ip\n },\n }\n}\n","export {\n FastifyHttpAdapter,\n type CorsOptions,\n type FastifyAdapterOptions,\n} from './fastify-adapter.js'\nexport {\n createSecurityGuard,\n buildSecurityHeaders,\n CSRF_COOKIE,\n CSRF_HEADER,\n type SecurityGuard,\n} from './security-middleware.js'\nexport { SHOPPER_ATTESTATION_HEADER } from '@nymbalhq/types'\nexport { CHECKOUT_ADDRESS_CEILING, RateLimiter } from './rate-limit.js'\nexport { createShopperAttestation, type ShopperAttestation } from './shopper-attestation.js'\nexport { createHttpServer, type HttpServer, type HttpServerDeps } from './server.js'\nexport { createHealthRoute } from './routes/health.js'\nexport { createReadyRoute, type ReadyState } from './routes/ready.js'\nexport {\n forwardToStorefront,\n type StorefrontForward,\n type StorefrontForwardOptions,\n} from './storefront-forward.js'\nexport { createProductsRoute, type ProductListItem } from './routes/products.js'\nexport {\n mountMcp,\n mountToolEndpoint,\n MCP_PATH,\n type MountMcpDeps,\n type ToolEndpointDeps,\n} from './mcp-route.js'\nexport {\n mountAgentSurfaces,\n UCP_MCP_PATH,\n HANDOFF_PATH,\n FEED_PATH,\n type MountAgentSurfacesDeps,\n} from './agent-surface.js'\n","import { secureCookies, type NymbalConfig } from '@nymbalhq/config'\nimport type {\n DocumentStoreAdapter,\n HttpMethod,\n Logger,\n MiddlewareHandler,\n ResolvedNetwork,\n RouteHandler,\n RouteOptions,\n} from '@nymbalhq/types'\nimport { FastifyHttpAdapter } from './fastify-adapter.js'\nimport { createHealthRoute } from './routes/health.js'\nimport { createProductsRoute } from './routes/products.js'\n\nexport interface HttpServerDeps {\n config: NymbalConfig\n logger: Logger\n documentStore: DocumentStoreAdapter\n version: string\n /** The trusted proxies, client-address header and origin lock, resolved once by `createApp`: pass `app.network`. */\n network: ResolvedNetwork\n}\n\nexport interface HttpServer {\n adapter: FastifyHttpAdapter\n registerRoute(\n method: HttpMethod,\n path: string,\n handler: RouteHandler,\n options?: RouteOptions,\n ): void\n registerMiddleware(middleware: MiddlewareHandler): void\n start(): Promise<{ port: number; host: string }>\n stop(): Promise<void>\n}\n\nexport function createHttpServer(deps: HttpServerDeps): HttpServer {\n const { config, logger, documentStore, version, network } = deps\n if (config.http.adapter !== 'fastify') {\n throw new Error(`Unsupported http.adapter: ${config.http.adapter}`)\n }\n const adapter = new FastifyHttpAdapter({\n logger,\n cors: config.http.cors,\n security: config.security,\n trustedProxies: network.trustedProxies,\n ...(network.clientIpHeader !== undefined && { clientIpHeader: network.clientIpHeader }),\n clientIpRequiresLock: network.clientIpRequiresLock,\n ...(network.originLock !== undefined && { originLock: network.originLock }),\n originLockHeader: config.security.originLock.header,\n secureCookies: secureCookies(config, process.env),\n })\n\n const server: HttpServer = {\n adapter,\n registerRoute(method, path, handler, options) {\n adapter.registerRoute(method, path, handler, options)\n },\n registerMiddleware(middleware) {\n adapter.registerMiddleware(middleware)\n },\n async start() {\n await adapter.start(config.http.port, config.http.host)\n return { port: adapter.boundPort, host: config.http.host }\n },\n async stop() {\n await adapter.stop()\n },\n }\n\n // Default routes — available without any user route registration.\n server.registerRoute('GET', '/health', createHealthRoute(version))\n // The commerce routes (including `/api/products`) are registered by\n // `platform.attachHttp(...)` — we intentionally do not pre-register them\n // here to avoid FST_ERR_DUPLICATED_ROUTE conflicts when the kernel is wired.\n void createProductsRoute\n void documentStore\n void config\n\n return server\n}\n","import type { RouteHandler } from '@nymbalhq/types'\n\nexport function createHealthRoute(version: string): RouteHandler {\n return () => ({\n status: 200,\n body: { status: 'ok', version, timestamp: new Date().toISOString() },\n })\n}\n","import type { DocumentStoreAdapter, RouteHandler } from '@nymbalhq/types'\n\nexport interface ProductListItem {\n id: string\n slug: string\n title: string\n description: string\n priceMinor: number\n currency: string\n categoryId: string\n imageUrl: string\n}\n\nexport function createProductsRoute(\n documentStore: DocumentStoreAdapter,\n storeId: string,\n): RouteHandler {\n return async (ctx) => {\n const rawLimit = ctx.query.limit\n const limitValue = Array.isArray(rawLimit) ? rawLimit[0] : rawLimit\n const limit = limitValue ? Math.min(100, Math.max(1, Number(limitValue) || 20)) : 50\n const rawCursor = ctx.query.cursor\n const cursorValue = Array.isArray(rawCursor) ? rawCursor[0] : rawCursor\n\n const result = await documentStore.query<ProductListItem>('products', {\n partitionKey: { field: 'storeId', value: storeId },\n limit,\n ...(cursorValue !== undefined && { cursor: cursorValue }),\n ascending: true,\n })\n return {\n status: 200,\n body: { items: result.items, nextCursor: result.nextCursor },\n }\n }\n}\n","import type { RouteHandler } from '@nymbalhq/types'\n\nexport type ReadyState = { ready: true } | { ready: false; failing: string[] }\n\n/** GET /ready: 200 when the store can take traffic, else 503 naming what cannot, by name only. */\nexport function createReadyRoute(probe: () => Promise<ReadyState>): RouteHandler {\n return async () => {\n const state = await probe()\n return state.ready\n ? { status: 200, body: { status: 'ready' } }\n : { status: 503, body: { status: 'not-ready', failing: state.failing } }\n }\n}\n","import httpProxy from '@fastify/http-proxy'\nimport type { HTTPMethods } from 'fastify'\nimport { securitySchema, type NymbalConfig } from '@nymbalhq/config'\nimport { SHOPPER_ATTESTATION_HEADER } from '@nymbalhq/types'\nimport type { FastifyHttpAdapter } from './fastify-adapter.js'\n\nexport interface StorefrontForwardOptions {\n /** The storefront's internal port on 127.0.0.1. */\n port: number\n /** The store's public origin: the storefront sees its host and scheme, whatever the client sent. */\n publicUrl: string\n /** The security headers a page answer gets where the storefront set none; absent, the config's defaults. */\n headers?: Pick<NymbalConfig['security']['headers'], 'hsts' | 'referrerPolicy' | 'xFrameOptions'>\n}\n\nexport interface StorefrontForward {\n /** Forwards started and not yet ended or cut. */\n inFlight(): number\n /** From now on a new page request answers 503; forwards in flight go on. */\n refuse(): void\n /** Resolves true once no forward is in flight, false when `timeoutMs` passes first. */\n drained(timeoutMs: number): Promise<boolean>\n}\n\n/**\n * The page security headers, each sent only where the storefront's answer has none of its own. The policy is a floor\n * a storefront's own replaces: it does not know the API origin or the payment scripts a page loads.\n */\nfunction pageHeaders(\n origin: URL,\n {\n hsts,\n referrerPolicy,\n xFrameOptions,\n }: NonNullable<StorefrontForwardOptions['headers']> = securitySchema.parse({\n adapter: 'middleware',\n }).headers,\n): Record<string, string> {\n return {\n ...(hsts &&\n origin.protocol === 'https:' && {\n 'strict-transport-security': 'max-age=31536000; includeSubDomains',\n }),\n 'content-security-policy': \"frame-ancestors 'none'; object-src 'none'; base-uri 'self'\",\n 'x-content-type-options': 'nosniff',\n 'x-frame-options': xFrameOptions === 'deny' ? 'DENY' : 'SAMEORIGIN',\n 'referrer-policy': referrerPolicy,\n }\n}\n\n/** OPTIONS stays the API's: CORS answers a preflight on any path. */\nconst FORWARDED_METHODS: HTTPMethods[] = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT']\n\n/**\n * Forwards every request the API does not route to the storefront on its internal port, body and headers unchanged\n * both ways but for the forwarding headers and `x-nymbal-shopper`, the shopper's address attested by this API. A path\n * under /api/ keeps the API's not-found answer and never reaches the storefront. Call before\n * `adapter.start`.\n */\nexport function forwardToStorefront(\n adapter: FastifyHttpAdapter,\n options: StorefrontForwardOptions,\n): StorefrontForward {\n const origin = new URL(options.publicUrl)\n const proto = origin.protocol.slice(0, -1)\n const filled = pageHeaders(origin, options.headers)\n let inFlight = 0\n let refusing = false\n const waiters = new Set<() => void>()\n const settle = (): void => {\n inFlight -= 1\n if (inFlight === 0) for (const wake of [...waiters]) wake()\n }\n\n adapter.registerPlugin(async (api) => {\n // The forward's own context passes every body through as a stream, so this one does too.\n api.removeAllContentTypeParsers()\n api.addContentTypeParser('*', (_req, payload, done) => done(null, payload))\n api.route({\n method: FORWARDED_METHODS,\n url: '/api/*',\n handler: (_req, reply) => reply.callNotFound(),\n })\n })\n\n adapter.registerPlugin(async (pages) => {\n pages.removeAllContentTypeParsers()\n await pages.register(httpProxy, {\n upstream: `http://127.0.0.1:${options.port}`,\n httpMethods: FORWARDED_METHODS,\n internalRewriteLocationHeader: false,\n preHandler: (_req, reply, done) => {\n if (refusing) {\n void reply\n .code(503)\n .header('connection', 'close')\n .send({ error: { code: 'unavailable', message: 'The store is shutting down' } })\n return\n }\n inFlight += 1\n reply.raw.once('close', settle)\n done()\n },\n replyOptions: {\n rewriteRequestHeaders: (req, headers) => {\n const prior = req.headers['x-forwarded-for']\n const peer = req.raw.socket.remoteAddress ?? req.ip\n return {\n ...headers,\n host: origin.host,\n 'x-forwarded-host': origin.host,\n 'x-forwarded-proto': proto,\n 'x-forwarded-for': [prior, peer].flat().filter(Boolean).join(', '),\n // Replaces whatever the client sent: only this API's own attestation of the address it resolved.\n [SHOPPER_ATTESTATION_HEADER]: adapter.attestShopper(req.clientIp),\n }\n },\n rewriteHeaders: (headers) => ({ ...filled, ...headers }),\n // A forward is never retried: a page POST may not be idempotent, and a 503 is the storefront's answer.\n retryDelay: () => null,\n onError: (reply) => {\n void reply\n .code(503)\n .send({ error: { code: 'unavailable', message: 'The storefront is not answering' } })\n },\n },\n })\n })\n\n return {\n inFlight: () => inFlight,\n refuse() {\n refusing = true\n },\n drained(timeoutMs) {\n if (inFlight === 0) return Promise.resolve(true)\n return new Promise<boolean>((resolve) => {\n const finish = (value: boolean): void => {\n clearTimeout(timer)\n waiters.delete(wake)\n resolve(value)\n }\n const wake = (): void => finish(true)\n const timer = setTimeout(() => finish(false), timeoutMs)\n waiters.add(wake)\n })\n },\n }\n}\n","import {\n CLIENT_INFO_META_KEY,\n Server,\n createMcpHandler,\n type AuthInfo,\n type Tool,\n} from '@modelcontextprotocol/server'\nimport type {\n Caller,\n RequestAuth,\n RequestContext,\n ResponseEnvelope,\n ToolDefinition,\n ToolResult,\n ToolSurface,\n} from '@nymbalhq/types'\nimport type { HttpServer } from './server.js'\n\nexport const MCP_PATH = '/api/mcp'\n\nexport interface MountMcpDeps {\n /** The app `attachHttp` ran on: its tool surface. */\n app: { readonly mcp: ToolSurface | undefined }\n /** Verifies a bearer the store signed; rejects one it did not. */\n verify: (token: string) => Promise<{ sub: string; roles?: readonly string[] }>\n /** The origins CORS allows: a request from any other is refused. */\n origins: readonly string[]\n enabled: boolean\n version?: string\n}\n\nexport interface ToolEndpointDeps {\n path: string\n surface: ToolSurface\n verify: MountMcpDeps['verify']\n origins: readonly string[]\n /**\n * Whether each call is also held to its tool's route's rate rule. A tool that is a route says yes; a tool that is\n * not (a UCP tool) counts once, against the endpoint's rule.\n */\n admitTools: boolean\n version?: string\n}\n\n/** What one HTTP request hands the per-request MCP server: who calls, and the rate rule of each tool's route. */\ninterface RequestState {\n auth: RequestAuth | undefined\n ip: string\n admit: (tool: ToolDefinition) => ToolResult | null\n}\n\nfunction refuse(\n status: number,\n code: string,\n message: string,\n headers: Record<string, string> = {},\n): ResponseEnvelope {\n return { status, headers, body: { error: { code, message } } }\n}\n\nfunction textResult(structured: Record<string, unknown>): ToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(structured) }],\n structuredContent: structured,\n isError: true,\n }\n}\n\nfunction bearerOf(ctx: RequestContext): string | undefined {\n const raw = ctx.headers.authorization\n const header = Array.isArray(raw) ? raw[0] : raw\n if (header === undefined || !header.toLowerCase().startsWith('bearer ')) return undefined\n return header.slice('bearer '.length).trim()\n}\n\n/** The SDK lifts the client's `_meta` clientInfo into the request's envelope before a handler sees it. */\nfunction agentOf(envelope: object | undefined, server: Server): Caller['agent'] {\n const meta = envelope as Record<string, unknown> | undefined\n const info = (meta?.[CLIENT_INFO_META_KEY] ?? server.getClientVersion()) as\n | { name?: unknown; version?: unknown }\n | undefined\n return {\n name: typeof info?.name === 'string' ? info.name : 'mcp-client',\n ...(typeof info?.version === 'string' && { version: info.version }),\n }\n}\n\nfunction toolServer(surface: ToolSurface, state: RequestState, version: string): Server {\n const server = new Server({ name: 'nymbal', version }, { capabilities: { tools: {} } })\n const caller = (agent: Caller['agent']): Caller => ({\n ...(state.auth !== undefined && { auth: state.auth }),\n agent,\n ip: state.ip,\n })\n server.setRequestHandler('tools/list', (_request, ctx) => ({\n tools: surface.list(caller(agentOf(ctx.mcpReq.envelope, server))).map((tool) => ({\n name: tool.name,\n title: tool.title,\n description: tool.description,\n // Converted from the route's Zod schema, so every keyword's value is JSON.\n inputSchema: tool.inputSchema as Tool['inputSchema'],\n annotations: { readOnlyHint: tool.kind === 'read' },\n })),\n }))\n server.setRequestHandler('tools/call', async (request, ctx) => {\n const who = caller(agentOf(ctx.mcpReq.envelope, server))\n const tool = surface.list(who).find((listed) => listed.name === request.params.name)\n const result =\n (tool && state.admit(tool)) ??\n (await surface.call(request.params.name, request.params.arguments ?? {}, who))\n return server.projectCallToolResult({ ...result }, undefined)\n })\n return server\n}\n\n/**\n * An MCP endpoint over Streamable HTTP at `deps.path`, serving a tool surface. It reads no cookie, so it takes no CSRF\n * token; in its place an `Origin` other than the store's own is refused, a bearer that does not verify is refused, and\n * the endpoint (and, under `admitTools`, each tool's route) is held to its rate rule.\n */\nexport async function mountToolEndpoint(server: HttpServer, deps: ToolEndpointDeps): Promise<void> {\n const { surface } = deps\n const adapter = server.adapter\n // The SDK hands a request's server factory only what `fetch` was given as `authInfo`, so the verified caller and\n // the request's rate admission ride there; the bearer itself does not.\n const handler = createMcpHandler(({ authInfo }) => {\n const state = authInfo?.extra?.['nymbal'] as RequestState\n return toolServer(surface, state, deps.version ?? '0.0.0')\n })\n const origins = new Set(deps.origins)\n\n const serve = async (ctx: RequestContext): Promise<Response | ResponseEnvelope> => {\n const origin = ctx.headers.origin\n if (typeof origin === 'string' && !origins.has(origin)) {\n return refuse(\n 403,\n 'origin.forbidden',\n `Origin ${origin} may not call this store's agent endpoint`,\n )\n }\n const token = bearerOf(ctx)\n let auth: RequestAuth | undefined\n if (token !== undefined) {\n try {\n const payload = await deps.verify(token)\n auth = { userId: payload.sub, roles: [...(payload.roles ?? [])] }\n } catch {\n return refuse(401, 'auth.unauthorized', 'The bearer token does not verify', {\n 'www-authenticate': 'Bearer error=\"invalid_token\"',\n })\n }\n }\n const state: RequestState = {\n auth,\n ip: ctx.ip,\n admit(tool) {\n if (!deps.admitTools) return null\n const refused = adapter.guard.admit(\n {\n ...ctx,\n method: tool.route.method,\n path: tool.route.path,\n headers: {},\n body: undefined,\n },\n { csrf: false },\n )\n if (refused === null) return null\n const error = (refused.body as { error?: { retryAfter?: number } } | undefined)?.error\n return textResult({\n code: 'rate.limited',\n message: `Too many ${tool.name} calls`,\n ...(error?.retryAfter !== undefined && { retryAfter: error.retryAfter }),\n })\n },\n }\n const headers = new Headers()\n for (const [name, value] of Object.entries(ctx.headers)) {\n if (value === undefined || name === 'authorization' || name === 'cookie') continue\n for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one)\n }\n const host = typeof ctx.headers.host === 'string' ? ctx.headers.host : 'localhost'\n const request = new Request(new URL(ctx.url, `http://${host}`), { method: ctx.method, headers })\n const authInfo: AuthInfo = {\n token: '',\n clientId: auth?.userId ?? 'anonymous',\n scopes: auth?.roles ?? [],\n extra: { nymbal: state },\n }\n return handler.fetch(request, {\n authInfo,\n ...(ctx.method === 'POST' && { parsedBody: ctx.body }),\n })\n }\n\n for (const method of ['POST', 'GET', 'DELETE'] as const) {\n adapter.registerWebRoute(method, deps.path, serve, { csrf: false })\n }\n}\n\n/**\n * `POST /api/mcp`: the app's routes as tools, each call held to its route's rate rule as well as the endpoint's.\n * Mounted after `attachHttp`, beside the routes it registered.\n */\nexport async function mountMcp(server: HttpServer, deps: MountMcpDeps): Promise<void> {\n if (!deps.enabled) return\n const surface = deps.app.mcp\n if (surface === undefined) {\n throw new Error('mountMcp needs the tool surface attachHttp builds: call attachHttp first')\n }\n await mountToolEndpoint(server, {\n path: MCP_PATH,\n surface,\n verify: deps.verify,\n origins: deps.origins,\n admitTools: true,\n ...(deps.version !== undefined && { version: deps.version }),\n })\n}\n","import type {\n AgentSurfaces,\n AgentSurfaceUrls,\n ResponseCookie,\n ResponseEnvelope,\n} from '@nymbalhq/types'\nimport { mountToolEndpoint, type MountMcpDeps } from './mcp-route.js'\nimport type { HttpServer } from './server.js'\n\nexport const UCP_MCP_PATH = '/api/ucp/mcp'\nexport const HANDOFF_PATH = '/api/agents/checkout/:token'\nexport const FEED_PATH = '/agents/products.json'\n\nconst CART_COOKIE = 'nymbal.cart'\n/** Crawl files and the profile change with the catalogue, not per shopper. */\nconst CACHE = { 'cache-control': 'public, max-age=300' }\nconst TEXT = { ...CACHE, 'content-type': 'text/plain; charset=utf-8' }\n\nexport interface MountAgentSurfacesDeps {\n /** The app `attachHttp` ran on: its agent surfaces. */\n app: { readonly agents: AgentSurfaces | undefined }\n verify: MountMcpDeps['verify']\n /** The origins CORS allows: an MCP request from any other is refused. */\n origins: readonly string[]\n /** The API's and the storefront's origins, read per request (`nymbal dev` picks the storefront's port late). */\n urls: () => AgentSurfaceUrls\n version?: string\n}\n\nconst notFound: ResponseEnvelope = {\n status: 404,\n body: { error: { code: 'not_found', message: 'This store does not serve this file' } },\n}\n\n/** The cookie `GET /api/cart` sets on a new cart, so the storefront reads the handed cart as its own. */\nfunction cartCookie(token: string): ResponseCookie {\n return {\n name: CART_COOKIE,\n value: token,\n path: '/',\n httpOnly: true,\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: 60 * 60 * 24 * 30,\n }\n}\n\nfunction queryValue(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value\n}\n\n/**\n * Each agent surface's discovery document, MCP endpoint and REST routes, the crawl files (`/robots.txt`, `/llms.txt`,\n * the product feed) and the checkout handoff. Mounted after `attachHttp` and `mountMcp`, outside the route registry:\n * none of these is an agent tool.\n */\nexport async function mountAgentSurfaces(\n server: HttpServer,\n deps: MountAgentSurfacesDeps,\n): Promise<void> {\n const agents = deps.app.agents\n if (agents === undefined) {\n throw new Error(\n 'mountAgentSurfaces needs the agent surfaces attachHttp builds: call attachHttp first',\n )\n }\n const { adapter } = server\n agents.useUrls(deps.urls)\n\n for (const surface of agents.surfaces) {\n const { wellKnown, endpoint, routes = [] } = surface\n if (wellKnown !== undefined) {\n adapter.registerRoute('GET', wellKnown.path, async () => ({\n status: 200,\n headers: CACHE,\n body: wellKnown.document(deps.urls()),\n }))\n }\n if (endpoint !== undefined) {\n await mountToolEndpoint(server, {\n path: endpoint.path,\n surface: endpoint.tools,\n verify: deps.verify,\n origins: deps.origins,\n admitTools: false,\n ...(deps.version !== undefined && { version: deps.version }),\n })\n }\n // Server to server under the surface's own bearer, with no cookie to ride on: no CSRF token, as for a webhook.\n for (const route of routes) {\n adapter.registerRoute(\n route.method,\n route.path,\n (ctx) =>\n route.handle({\n params: ctx.params,\n query: ctx.query,\n headers: ctx.headers,\n body: ctx.body,\n ip: ctx.ip,\n requestId: ctx.requestId,\n }),\n { csrf: false },\n )\n }\n }\n\n adapter.registerRoute('GET', '/robots.txt', async () => {\n const body = agents.robots(deps.urls())\n return body === null ? notFound : { status: 200, headers: TEXT, body }\n })\n adapter.registerRoute('GET', '/llms.txt', async () => {\n const body = await agents.llms(deps.urls())\n return body === null ? notFound : { status: 200, headers: TEXT, body }\n })\n adapter.registerRoute('GET', FEED_PATH, async (ctx) => {\n const page = await agents.feed(deps.urls(), queryValue(ctx.query.cursor))\n if (page === null) return notFound\n const failed = (page['ucp'] as { status?: unknown } | undefined)?.status === 'error'\n return failed ? { status: 400, body: page } : { status: 200, headers: CACHE, body: page }\n })\n\n // A GET that changes nothing but the browser's cart cookie, so it takes no CSRF token.\n adapter.registerRoute('GET', HANDOFF_PATH, async (ctx) => {\n const token = ctx.params.token ?? ''\n const live = token !== '' && (await agents.handoff(token))\n const storefront = deps.urls().storefront ?? ''\n return {\n status: 303,\n headers: { location: `${storefront}${live ? '/checkout' : '/cart'}` },\n ...(live && { cookies: [cartCookie(token)] }),\n }\n })\n}\n"],"mappings":";AAAA,OAAO;AAAA,EACL;AAAA,OAOK;AACP,SAAS,cAAAA,aAAY,mBAAAC,wBAAuB;AAC5C,SAAS,YAAY;AACrB,OAAO,mBAAmB;AAC1B,OAAO,iBAAiB;AACxB,OAAO,eAAe;AACtB,SAAS,MAAM,cAAc;AAe7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,uBAA0C;;;ACpCxE,SAAS,YAAY,aAAa,uBAAuB;AAEzD;AAAA,EACE;AAAA,OAKK;;;ACRP,SAAS,0BAAgD;AA2BlD,IAAM,uBAAuC;AAAA,EAClD,mBAAmB,EAAE,UAAU,IAAI,QAAQ,OAAO,QAAQ,QAAQ;AAAA,EAClE,sBAAsB,EAAE,UAAU,IAAI,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAEpE,wBAAwB,EAAE,UAAU,KAAK,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAEvE,yBAAyB,EAAE,UAAU,IAAI,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAEvE,gBAAgB,EAAE,UAAU,IAAI,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA,EAE9D,oBAAoB,EAAE,UAAU,GAAG,QAAQ,MAAM,QAAQ,QAAQ;AAAA;AAAA;AAAA,EAGjE,iBA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AAM,KAAK;AAAA,EACvE,CAAC;AACD,UAAQ,cAAc,OAAO,aAAa,YAAY;AACpD,UAAM,OAAO,MAAM,OAAO,KAAK,KAAK,KAAK,CAAC;AAC1C,WAAO,SAAS,OAAO,WAAW,EAAE,QAAQ,KAAK,SAAS,MAAM,KAAK;AAAA,EACvE,CAAC;AACD,UAAQ,cAAc,OAAO,WAAW,OAAO,QAAQ;AACrD,UAAM,OAAO,MAAM,OAAO,KAAK,KAAK,KAAK,GAAG,WAAW,IAAI,MAAM,MAAM,CAAC;AACxE,QAAI,SAAS,KAAM,QAAO;AAC1B,UAAM,SAAU,KAAK,KAAK,GAAwC,WAAW;AAC7E,WAAO,SAAS,EAAE,QAAQ,KAAK,MAAM,KAAK,IAAI,EAAE,QAAQ,KAAK,SAAS,OAAO,MAAM,KAAK;AAAA,EAC1F,CAAC;AAGD,UAAQ,cAAc,OAAO,cAAc,OAAO,QAAQ;AACxD,UAAM,QAAQ,IAAI,OAAO,SAAS;AAClC,UAAM,OAAO,UAAU,MAAO,MAAM,OAAO,QAAQ,KAAK;AACxD,UAAM,aAAa,KAAK,KAAK,EAAE,cAAc;AAC7C,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAS,EAAE,UAAU,GAAG,UAAU,GAAG,OAAO,cAAc,OAAO,GAAG;AAAA,MACpE,GAAI,QAAQ,EAAE,SAAS,CAAC,WAAW,KAAK,CAAC,EAAE;AAAA,IAC7C;AAAA,EACF,CAAC;AACH;","names":["createHash","timingSafeEqual","digest","secureCookies","options","randomBytes","timingSafeEqual","createHash","timingSafeEqual","SHOPPER_ATTESTATION_HEADER","SHOPPER_ATTESTATION_HEADER","CART_COOKIE"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nymbalhq/http",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "Framework-agnostic HTTP abstraction with Fastify adapter",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,16 +27,19 @@
27
27
  "dist"
28
28
  ],
29
29
  "dependencies": {
30
- "@fastify/cookie": "^9.4.0",
31
- "@fastify/cors": "^8.5.0",
32
- "@fastify/http-proxy": "9.5.0",
33
- "@nymbalhq/config": "1.5.0",
34
- "@nymbalhq/types": "1.5.0",
35
- "fastify": "^4.28.1",
36
- "uuid": "^10.0.0"
30
+ "@fastify/cookie": "^11.1.5",
31
+ "@fastify/cors": "^11.4.0",
32
+ "@fastify/http-proxy": "^11.6.6",
33
+ "@fastify/proxy-addr": "^5.1.2",
34
+ "@modelcontextprotocol/node": "^2.1.2",
35
+ "@modelcontextprotocol/server": "^2.4.0",
36
+ "@nymbalhq/config": "1.7.0",
37
+ "@nymbalhq/types": "1.7.0",
38
+ "fastify": "^5.12.7",
39
+ "uuid": "^11.1.1"
37
40
  },
38
41
  "devDependencies": {
39
- "@types/uuid": "^10.0.0",
42
+ "@modelcontextprotocol/client": "^2.4.0",
40
43
  "@typescript/native": "npm:typescript@^7.0.2",
41
44
  "tsup": "^9.0.0",
42
45
  "typescript": "npm:@typescript/typescript6@^6.0.2"