@nymbalhq/http 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nymbal contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,6 @@
1
+ # @nymbalhq/http
2
+
3
+ The HTTP server under a Nymbal store: Fastify, the security middleware, and the MCP and UCP endpoints agents
4
+ call. The `nymbal` CLI mounts it.
5
+
6
+ See [Agents](https://github.com/nymbalhq/nymbal/blob/main/apps/docs/src/content/docs/agents.md) and [Deploying](https://github.com/nymbalhq/nymbal/blob/main/apps/docs/src/content/docs/deploying.md).
package/dist/index.d.ts CHANGED
@@ -1,6 +1,50 @@
1
- import { Logger, HttpAdapter, HttpMethod, RouteHandler, RouteOptions, StreamHandler, MiddlewareHandler, RequestContext, ResponseEnvelope, RateLimitAction, DocumentStoreAdapter } from '@nymbalhq/types';
1
+ import { InjectOptions, LightMyRequestResponse, FastifyPluginAsync } from 'fastify';
2
+ import { RequestContext, RouteOptions, ResponseEnvelope, Logger, ResolvedOriginLock, HttpAdapter, HttpMethod, RouteHandler, StreamHandler, MiddlewareHandler, RateLimitAction, DocumentStoreAdapter, ResolvedNetwork, ToolSurface, AgentSurfaces, AgentSurfaceUrls } from '@nymbalhq/types';
3
+ export { SHOPPER_ATTESTATION_HEADER } from '@nymbalhq/types';
2
4
  import { NymbalConfig } from '@nymbalhq/config';
3
5
 
6
+ interface ShopperAttestation {
7
+ /** A token for `ip`, valid until `now + ttl`: `<ip>~<expiresMs>~<base64url mac>`. */
8
+ mint(ip: string, now?: number): string;
9
+ /** The address `token` was minted for, or null when it is not a live token under this key. */
10
+ verify(token: unknown, now?: number): string | null;
11
+ }
12
+ /**
13
+ * The API's proof, on a request it forwards to the storefront, of the shopper's address, so the storefront server's
14
+ * own API calls for that shopper count against the shopper. The key lives only in this process: a token from another
15
+ * process or a previous boot does not verify. `~` appears in no IPv4 or IPv6 address, so the three segments are
16
+ * unambiguous.
17
+ */
18
+ declare function createShopperAttestation(key?: Buffer, ttlMs?: number): ShopperAttestation;
19
+
20
+ declare const CSRF_COOKIE = "nymbal.csrf";
21
+ declare const CSRF_HEADER = "x-csrf-token";
22
+ declare function buildSecurityHeaders(security: NymbalConfig['security']): Record<string, string>;
23
+ interface SecurityGuard {
24
+ /**
25
+ * Runs before any middleware or handler: the rate limit, then CSRF on unsafe methods unless the route opted out.
26
+ * Returns the refusal, or null when the request may proceed.
27
+ */
28
+ admit(ctx: RequestContext, options?: RouteOptions): ResponseEnvelope | null;
29
+ /**
30
+ * Runs on the handler's answer: security headers and the outcome of a failure-counted login. It sets no CSRF
31
+ * cookie: parallel first requests would each mint a different one, and the browser would keep whichever came last.
32
+ */
33
+ finish(ctx: RequestContext, envelope: ResponseEnvelope): ResponseEnvelope;
34
+ /** `GET /api/csrf`, the only answer that sets the CSRF cookie: the request's own, or a new one set on the response. */
35
+ issueToken(ctx: RequestContext): ResponseEnvelope;
36
+ /** The rate-limit buckets held: what a client's requests can make the guard keep. */
37
+ bucketCount(): number;
38
+ reset(): void;
39
+ }
40
+ interface SecurityGuardOptions {
41
+ /** Verifies the storefront forward's `x-nymbal-shopper`: a verified address is the limiter's key for the request. */
42
+ attestation?: ShopperAttestation;
43
+ /** Whether the CSRF cookie carries `Secure` (`secureCookies(config, env)` in `@nymbalhq/config`). */
44
+ secureCookies?: boolean;
45
+ }
46
+ declare function createSecurityGuard(security: NymbalConfig['security'], options?: SecurityGuardOptions): SecurityGuard;
47
+
4
48
  interface CorsOptions {
5
49
  allowedOrigins: string[];
6
50
  credentials: boolean;
@@ -9,16 +53,59 @@ interface FastifyAdapterOptions {
9
53
  logger: Logger;
10
54
  /** The guard every route passes before its middlewares and handler: rate limit, then CSRF on unsafe methods. */
11
55
  security: NymbalConfig['security'];
12
- /** Whether `X-Forwarded-For` sets the request IP. Off unless a trusted proxy sits in front. */
13
- trustProxy?: boolean;
56
+ /**
57
+ * The proxies whose `X-Forwarded-For` sets the client address, walked from the socket peer while each hop is listed:
58
+ * `loopback`, `linklocal`, `uniquelocal`, addresses and CIDRs. Default `['loopback']`. The first request from an
59
+ * unlisted peer that carries a forwarded address logs a warning naming the peer.
60
+ */
61
+ trustedProxies?: string[];
62
+ /**
63
+ * One header a listed proxy sets to the client's address; when set, it decides in place of `X-Forwarded-For`, and
64
+ * only when it holds exactly one IP address.
65
+ */
66
+ clientIpHeader?: string;
67
+ /**
68
+ * Whether the header counts only on a locked request (one carrying the origin secret), from any peer, and on no
69
+ * other; when false it counts from a listed peer.
70
+ */
71
+ clientIpRequiresLock?: boolean;
72
+ /**
73
+ * The origin lock: a request from another machine that does not carry one of the secrets in the header is refused
74
+ * 403 `origin_locked` before anything else sees it, bar the routes `/health` and `/ready`.
75
+ */
76
+ originLock?: ResolvedOriginLock;
77
+ /**
78
+ * The header the CDN sends the origin secret in, removed from every request whether or not the lock is on: an edge
79
+ * that sends it to a host without the variable must not hand it to handlers or the storefront.
80
+ */
81
+ originLockHeader?: string;
14
82
  cors?: CorsOptions;
83
+ /** Whether the CSRF cookie carries `Secure`: `secureCookies(config, env)`. */
84
+ secureCookies?: boolean;
15
85
  }
16
86
  declare class FastifyHttpAdapter implements HttpAdapter {
17
87
  #private;
88
+ readonly clientIpRequiresLock: boolean;
18
89
  constructor(options: FastifyAdapterOptions);
19
90
  get boundPort(): number;
91
+ /**
92
+ * A token for `ip` that this adapter's guard, and no other, accepts in `x-nymbal-shopper` for the next minute: the
93
+ * storefront forward's proof of the shopper's address.
94
+ */
95
+ attestShopper(ip: string): string;
96
+ /** Fastify's `inject`: `remoteAddress` sets the socket peer, which a request from loopback cannot. */
97
+ inject(options: InjectOptions): Promise<LightMyRequestResponse>;
98
+ /** The guard every route passes, for a mounted handler that admits a request it serves on a route's behalf. */
99
+ get guard(): SecurityGuard;
100
+ /**
101
+ * A route whose handler answers a web-standard `Response` (the MCP endpoint's SDK), or an envelope when it refuses.
102
+ * It passes the guard and the middlewares as every route does.
103
+ */
104
+ registerWebRoute(method: HttpMethod, path: string, handler: (ctx: RequestContext) => Promise<Response | ResponseEnvelope>, options?: RouteOptions): void;
20
105
  registerRoute(method: HttpMethod, path: string, handler: RouteHandler, options?: RouteOptions): void;
21
106
  registerStreamRoute(method: 'GET', path: string, handler: StreamHandler, options?: RouteOptions): void;
107
+ /** A Fastify plugin on this server, in a context of its own: how the storefront forward is added. */
108
+ registerPlugin(plugin: FastifyPluginAsync): void;
22
109
  registerMiddleware(middleware: MiddlewareHandler): void;
23
110
  setDefaultHeaders(headers: Record<string, string>): void;
24
111
  start(port: number, host?: string): Promise<void>;
@@ -29,26 +116,11 @@ declare module 'fastify' {
29
116
  rawBody?: Buffer;
30
117
  /** Set by the onRequest hook before anything else runs. */
31
118
  correlationId: string;
119
+ /** The client address the request resolves to, set by the onRequest hook: what every reader of the address uses. */
120
+ clientIp: string;
32
121
  }
33
122
  }
34
123
 
35
- declare const CSRF_COOKIE = "nymbal.csrf";
36
- declare const CSRF_HEADER = "x-csrf-token";
37
- declare function buildSecurityHeaders(security: NymbalConfig['security']): Record<string, string>;
38
- interface SecurityGuard {
39
- /**
40
- * Runs before any middleware or handler: the rate limit, then CSRF on unsafe methods unless the route opted out.
41
- * Returns the refusal, or null when the request may proceed.
42
- */
43
- admit(ctx: RequestContext, options?: RouteOptions): ResponseEnvelope | null;
44
- /** Runs on the handler's answer: security headers, the CSRF cookie, and the outcome of a failure-counted login. */
45
- finish(ctx: RequestContext, envelope: ResponseEnvelope): ResponseEnvelope;
46
- /** `GET /api/csrf`: the request's CSRF cookie, or a new one set on the response. */
47
- issueToken(ctx: RequestContext): ResponseEnvelope;
48
- reset(): void;
49
- }
50
- declare function createSecurityGuard(security: NymbalConfig['security']): SecurityGuard;
51
-
52
124
  interface RateLimitDecision {
53
125
  allowed: boolean;
54
126
  action: RateLimitAction;
@@ -58,17 +130,29 @@ type RateLimitRules = Record<string, {
58
130
  requests: number;
59
131
  window: string;
60
132
  action: RateLimitAction;
133
+ header?: string | undefined;
61
134
  }>;
135
+ /**
136
+ * Checkouts count per (address, cart) at the checkout rule's count, so shoppers behind one proxy do not refuse each
137
+ * other's, and per address at this multiple of it, since carts are free to mint.
138
+ */
139
+ declare const CHECKOUT_ADDRESS_CEILING = 10;
62
140
  declare class RateLimiter {
63
141
  #private;
64
142
  constructor(rules: RateLimitRules);
65
- check(ip: string, path: string): RateLimitDecision | null;
143
+ /** Counts this request under `key` and refuses past the rule's count, times `scale` for a key that pools several. */
144
+ check(key: string, path: string, headers?: Readonly<Record<string, unknown>>, scale?: number): RateLimitDecision | null;
66
145
  /**
67
- * For a route that counts failures only: refuses when any of `keys` (an IP, an account) already holds the rule's
68
- * full count, without counting this request. `hit` and `clear` record the outcome once the handler has answered.
146
+ * For a route that counts failures only: refuses when any of `keys` already holds the rule's full count, without
147
+ * counting this request. `hit` and `clear` record the outcome once the handler has answered.
69
148
  */
70
149
  full(path: string, keys: string[]): RateLimitDecision | null;
71
- hit(path: string, keys: string[]): void;
150
+ /** Counts one under each of `keys`; returns each bucket's count after it, in the order of `keys`. */
151
+ hit(path: string, keys: string[]): number[];
152
+ /** The count the rule for `path` allows per window, or undefined when no rule applies. */
153
+ requests(path: string): number | undefined;
154
+ /** The buckets held, expired ones not yet swept included. */
155
+ get size(): number;
72
156
  clear(path: string, keys: string[]): void;
73
157
  reset(): void;
74
158
  }
@@ -78,9 +162,11 @@ interface HttpServerDeps {
78
162
  logger: Logger;
79
163
  documentStore: DocumentStoreAdapter;
80
164
  version: string;
165
+ /** The trusted proxies, client-address header and origin lock, resolved once by `createApp`: pass `app.network`. */
166
+ network: ResolvedNetwork;
81
167
  }
82
168
  interface HttpServer {
83
- adapter: HttpAdapter;
169
+ adapter: FastifyHttpAdapter;
84
170
  registerRoute(method: HttpMethod, path: string, handler: RouteHandler, options?: RouteOptions): void;
85
171
  registerMiddleware(middleware: MiddlewareHandler): void;
86
172
  start(): Promise<{
@@ -93,6 +179,39 @@ declare function createHttpServer(deps: HttpServerDeps): HttpServer;
93
179
 
94
180
  declare function createHealthRoute(version: string): RouteHandler;
95
181
 
182
+ type ReadyState = {
183
+ ready: true;
184
+ } | {
185
+ ready: false;
186
+ failing: string[];
187
+ };
188
+ /** GET /ready: 200 when the store can take traffic, else 503 naming what cannot, by name only. */
189
+ declare function createReadyRoute(probe: () => Promise<ReadyState>): RouteHandler;
190
+
191
+ interface StorefrontForwardOptions {
192
+ /** The storefront's internal port on 127.0.0.1. */
193
+ port: number;
194
+ /** The store's public origin: the storefront sees its host and scheme, whatever the client sent. */
195
+ publicUrl: string;
196
+ /** The security headers a page answer gets where the storefront set none; absent, the config's defaults. */
197
+ headers?: Pick<NymbalConfig['security']['headers'], 'hsts' | 'referrerPolicy' | 'xFrameOptions'>;
198
+ }
199
+ interface StorefrontForward {
200
+ /** Forwards started and not yet ended or cut. */
201
+ inFlight(): number;
202
+ /** From now on a new page request answers 503; forwards in flight go on. */
203
+ refuse(): void;
204
+ /** Resolves true once no forward is in flight, false when `timeoutMs` passes first. */
205
+ drained(timeoutMs: number): Promise<boolean>;
206
+ }
207
+ /**
208
+ * Forwards every request the API does not route to the storefront on its internal port, body and headers unchanged
209
+ * both ways but for the forwarding headers and `x-nymbal-shopper`, the shopper's address attested by this API. A path
210
+ * under /api/ keeps the API's not-found answer and never reaches the storefront. Call before
211
+ * `adapter.start`.
212
+ */
213
+ declare function forwardToStorefront(adapter: FastifyHttpAdapter, options: StorefrontForwardOptions): StorefrontForward;
214
+
96
215
  interface ProductListItem {
97
216
  id: string;
98
217
  slug: string;
@@ -105,5 +224,67 @@ interface ProductListItem {
105
224
  }
106
225
  declare function createProductsRoute(documentStore: DocumentStoreAdapter, storeId: string): RouteHandler;
107
226
 
108
- export { CSRF_COOKIE, CSRF_HEADER, FastifyHttpAdapter, RateLimiter, buildSecurityHeaders, createHealthRoute, createHttpServer, createProductsRoute, createSecurityGuard };
109
- export type { CorsOptions, FastifyAdapterOptions, HttpServer, HttpServerDeps, ProductListItem, SecurityGuard };
227
+ declare const MCP_PATH = "/api/mcp";
228
+ interface MountMcpDeps {
229
+ /** The app `attachHttp` ran on: its tool surface. */
230
+ app: {
231
+ readonly mcp: ToolSurface | undefined;
232
+ };
233
+ /** Verifies a bearer the store signed; rejects one it did not. */
234
+ verify: (token: string) => Promise<{
235
+ sub: string;
236
+ roles?: readonly string[];
237
+ }>;
238
+ /** The origins CORS allows: a request from any other is refused. */
239
+ origins: readonly string[];
240
+ enabled: boolean;
241
+ version?: string;
242
+ }
243
+ interface ToolEndpointDeps {
244
+ path: string;
245
+ surface: ToolSurface;
246
+ verify: MountMcpDeps['verify'];
247
+ origins: readonly string[];
248
+ /**
249
+ * 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
250
+ * not (a UCP tool) counts once, against the endpoint's rule.
251
+ */
252
+ admitTools: boolean;
253
+ version?: string;
254
+ }
255
+ /**
256
+ * An MCP endpoint over Streamable HTTP at `deps.path`, serving a tool surface. It reads no cookie, so it takes no CSRF
257
+ * token; in its place an `Origin` other than the store's own is refused, a bearer that does not verify is refused, and
258
+ * the endpoint (and, under `admitTools`, each tool's route) is held to its rate rule.
259
+ */
260
+ declare function mountToolEndpoint(server: HttpServer, deps: ToolEndpointDeps): Promise<void>;
261
+ /**
262
+ * `POST /api/mcp`: the app's routes as tools, each call held to its route's rate rule as well as the endpoint's.
263
+ * Mounted after `attachHttp`, beside the routes it registered.
264
+ */
265
+ declare function mountMcp(server: HttpServer, deps: MountMcpDeps): Promise<void>;
266
+
267
+ declare const UCP_MCP_PATH = "/api/ucp/mcp";
268
+ declare const HANDOFF_PATH = "/api/agents/checkout/:token";
269
+ declare const FEED_PATH = "/agents/products.json";
270
+ interface MountAgentSurfacesDeps {
271
+ /** The app `attachHttp` ran on: its agent surfaces. */
272
+ app: {
273
+ readonly agents: AgentSurfaces | undefined;
274
+ };
275
+ verify: MountMcpDeps['verify'];
276
+ /** The origins CORS allows: an MCP request from any other is refused. */
277
+ origins: readonly string[];
278
+ /** The API's and the storefront's origins, read per request (`nymbal dev` picks the storefront's port late). */
279
+ urls: () => AgentSurfaceUrls;
280
+ version?: string;
281
+ }
282
+ /**
283
+ * Each agent surface's discovery document, MCP endpoint and REST routes, the crawl files (`/robots.txt`, `/llms.txt`,
284
+ * the product feed) and the checkout handoff. Mounted after `attachHttp` and `mountMcp`, outside the route registry:
285
+ * none of these is an agent tool.
286
+ */
287
+ declare function mountAgentSurfaces(server: HttpServer, deps: MountAgentSurfacesDeps): Promise<void>;
288
+
289
+ export { CHECKOUT_ADDRESS_CEILING, CSRF_COOKIE, CSRF_HEADER, FEED_PATH, FastifyHttpAdapter, HANDOFF_PATH, MCP_PATH, RateLimiter, UCP_MCP_PATH, buildSecurityHeaders, createHealthRoute, createHttpServer, createProductsRoute, createReadyRoute, createSecurityGuard, createShopperAttestation, forwardToStorefront, mountAgentSurfaces, mountMcp, mountToolEndpoint };
290
+ export type { CorsOptions, FastifyAdapterOptions, HttpServer, HttpServerDeps, MountAgentSurfacesDeps, MountMcpDeps, ProductListItem, ReadyState, SecurityGuard, ShopperAttestation, StorefrontForward, StorefrontForwardOptions, ToolEndpointDeps };