@nymbalhq/http 1.5.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 +21 -0
- package/README.md +6 -0
- package/dist/index.d.ts +176 -35
- package/dist/index.js +576 -59
- package/dist/index.js.map +1 -1
- package/package.json +12 -9
package/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,7 +1,50 @@
|
|
|
1
|
-
import { FastifyPluginAsync } from 'fastify';
|
|
2
|
-
import { Logger, HttpAdapter, HttpMethod, RouteHandler,
|
|
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';
|
|
3
4
|
import { NymbalConfig } from '@nymbalhq/config';
|
|
4
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
|
+
|
|
5
48
|
interface CorsOptions {
|
|
6
49
|
allowedOrigins: string[];
|
|
7
50
|
credentials: boolean;
|
|
@@ -10,14 +53,55 @@ interface FastifyAdapterOptions {
|
|
|
10
53
|
logger: Logger;
|
|
11
54
|
/** The guard every route passes before its middlewares and handler: rate limit, then CSRF on unsafe methods. */
|
|
12
55
|
security: NymbalConfig['security'];
|
|
13
|
-
/**
|
|
14
|
-
|
|
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;
|
|
15
82
|
cors?: CorsOptions;
|
|
83
|
+
/** Whether the CSRF cookie carries `Secure`: `secureCookies(config, env)`. */
|
|
84
|
+
secureCookies?: boolean;
|
|
16
85
|
}
|
|
17
86
|
declare class FastifyHttpAdapter implements HttpAdapter {
|
|
18
87
|
#private;
|
|
88
|
+
readonly clientIpRequiresLock: boolean;
|
|
19
89
|
constructor(options: FastifyAdapterOptions);
|
|
20
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;
|
|
21
105
|
registerRoute(method: HttpMethod, path: string, handler: RouteHandler, options?: RouteOptions): void;
|
|
22
106
|
registerStreamRoute(method: 'GET', path: string, handler: StreamHandler, options?: RouteOptions): void;
|
|
23
107
|
/** A Fastify plugin on this server, in a context of its own: how the storefront forward is added. */
|
|
@@ -32,26 +116,11 @@ declare module 'fastify' {
|
|
|
32
116
|
rawBody?: Buffer;
|
|
33
117
|
/** Set by the onRequest hook before anything else runs. */
|
|
34
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;
|
|
35
121
|
}
|
|
36
122
|
}
|
|
37
123
|
|
|
38
|
-
declare const CSRF_COOKIE = "nymbal.csrf";
|
|
39
|
-
declare const CSRF_HEADER = "x-csrf-token";
|
|
40
|
-
declare function buildSecurityHeaders(security: NymbalConfig['security']): Record<string, string>;
|
|
41
|
-
interface SecurityGuard {
|
|
42
|
-
/**
|
|
43
|
-
* Runs before any middleware or handler: the rate limit, then CSRF on unsafe methods unless the route opted out.
|
|
44
|
-
* Returns the refusal, or null when the request may proceed.
|
|
45
|
-
*/
|
|
46
|
-
admit(ctx: RequestContext, options?: RouteOptions): ResponseEnvelope | null;
|
|
47
|
-
/** Runs on the handler's answer: security headers, the CSRF cookie, and the outcome of a failure-counted login. */
|
|
48
|
-
finish(ctx: RequestContext, envelope: ResponseEnvelope): ResponseEnvelope;
|
|
49
|
-
/** `GET /api/csrf`: the request's CSRF cookie, or a new one set on the response. */
|
|
50
|
-
issueToken(ctx: RequestContext): ResponseEnvelope;
|
|
51
|
-
reset(): void;
|
|
52
|
-
}
|
|
53
|
-
declare function createSecurityGuard(security: NymbalConfig['security']): SecurityGuard;
|
|
54
|
-
|
|
55
124
|
interface RateLimitDecision {
|
|
56
125
|
allowed: boolean;
|
|
57
126
|
action: RateLimitAction;
|
|
@@ -63,16 +132,27 @@ type RateLimitRules = Record<string, {
|
|
|
63
132
|
action: RateLimitAction;
|
|
64
133
|
header?: string | undefined;
|
|
65
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;
|
|
66
140
|
declare class RateLimiter {
|
|
67
141
|
#private;
|
|
68
142
|
constructor(rules: RateLimitRules);
|
|
69
|
-
|
|
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;
|
|
70
145
|
/**
|
|
71
|
-
* For a route that counts failures only: refuses when any of `keys`
|
|
72
|
-
*
|
|
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.
|
|
73
148
|
*/
|
|
74
149
|
full(path: string, keys: string[]): RateLimitDecision | null;
|
|
75
|
-
|
|
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;
|
|
76
156
|
clear(path: string, keys: string[]): void;
|
|
77
157
|
reset(): void;
|
|
78
158
|
}
|
|
@@ -82,9 +162,11 @@ interface HttpServerDeps {
|
|
|
82
162
|
logger: Logger;
|
|
83
163
|
documentStore: DocumentStoreAdapter;
|
|
84
164
|
version: string;
|
|
165
|
+
/** The trusted proxies, client-address header and origin lock, resolved once by `createApp`: pass `app.network`. */
|
|
166
|
+
network: ResolvedNetwork;
|
|
85
167
|
}
|
|
86
168
|
interface HttpServer {
|
|
87
|
-
adapter:
|
|
169
|
+
adapter: FastifyHttpAdapter;
|
|
88
170
|
registerRoute(method: HttpMethod, path: string, handler: RouteHandler, options?: RouteOptions): void;
|
|
89
171
|
registerMiddleware(middleware: MiddlewareHandler): void;
|
|
90
172
|
start(): Promise<{
|
|
@@ -93,12 +175,6 @@ interface HttpServer {
|
|
|
93
175
|
}>;
|
|
94
176
|
stop(): Promise<void>;
|
|
95
177
|
}
|
|
96
|
-
/**
|
|
97
|
-
* `http.trustProxy`, with NYMBAL_TRUST_PROXY_HOPS filling it when the config leaves it `false`: the hop count is the
|
|
98
|
-
* 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
|
|
99
|
-
* integer of 0 or more, whatever the config holds; Fastify would trust nothing, silently, below 0.
|
|
100
|
-
*/
|
|
101
|
-
declare function resolveTrustProxy(config: NymbalConfig, env: NodeJS.ProcessEnv): boolean | number;
|
|
102
178
|
declare function createHttpServer(deps: HttpServerDeps): HttpServer;
|
|
103
179
|
|
|
104
180
|
declare function createHealthRoute(version: string): RouteHandler;
|
|
@@ -117,6 +193,8 @@ interface StorefrontForwardOptions {
|
|
|
117
193
|
port: number;
|
|
118
194
|
/** The store's public origin: the storefront sees its host and scheme, whatever the client sent. */
|
|
119
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'>;
|
|
120
198
|
}
|
|
121
199
|
interface StorefrontForward {
|
|
122
200
|
/** Forwards started and not yet ended or cut. */
|
|
@@ -128,7 +206,8 @@ interface StorefrontForward {
|
|
|
128
206
|
}
|
|
129
207
|
/**
|
|
130
208
|
* Forwards every request the API does not route to the storefront on its internal port, body and headers unchanged
|
|
131
|
-
* both ways
|
|
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
|
|
132
211
|
* `adapter.start`.
|
|
133
212
|
*/
|
|
134
213
|
declare function forwardToStorefront(adapter: FastifyHttpAdapter, options: StorefrontForwardOptions): StorefrontForward;
|
|
@@ -145,5 +224,67 @@ interface ProductListItem {
|
|
|
145
224
|
}
|
|
146
225
|
declare function createProductsRoute(documentStore: DocumentStoreAdapter, storeId: string): RouteHandler;
|
|
147
226
|
|
|
148
|
-
|
|
149
|
-
|
|
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 };
|