@nymbalhq/http 1.4.0 → 1.5.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.d.ts +45 -5
- package/dist/index.js +155 -11
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FastifyPluginAsync } from 'fastify';
|
|
1
2
|
import { Logger, HttpAdapter, HttpMethod, RouteHandler, RouteOptions, StreamHandler, MiddlewareHandler, RequestContext, ResponseEnvelope, RateLimitAction, DocumentStoreAdapter } from '@nymbalhq/types';
|
|
2
3
|
import { NymbalConfig } from '@nymbalhq/config';
|
|
3
4
|
|
|
@@ -9,8 +10,8 @@ interface FastifyAdapterOptions {
|
|
|
9
10
|
logger: Logger;
|
|
10
11
|
/** The guard every route passes before its middlewares and handler: rate limit, then CSRF on unsafe methods. */
|
|
11
12
|
security: NymbalConfig['security'];
|
|
12
|
-
/**
|
|
13
|
-
trustProxy?: boolean;
|
|
13
|
+
/** Which `X-Forwarded-For` entries set the request IP: a hop count, or every entry (`true`). Off by default. */
|
|
14
|
+
trustProxy?: boolean | number;
|
|
14
15
|
cors?: CorsOptions;
|
|
15
16
|
}
|
|
16
17
|
declare class FastifyHttpAdapter implements HttpAdapter {
|
|
@@ -19,6 +20,8 @@ declare class FastifyHttpAdapter implements HttpAdapter {
|
|
|
19
20
|
get boundPort(): number;
|
|
20
21
|
registerRoute(method: HttpMethod, path: string, handler: RouteHandler, options?: RouteOptions): void;
|
|
21
22
|
registerStreamRoute(method: 'GET', path: string, handler: StreamHandler, options?: RouteOptions): void;
|
|
23
|
+
/** A Fastify plugin on this server, in a context of its own: how the storefront forward is added. */
|
|
24
|
+
registerPlugin(plugin: FastifyPluginAsync): void;
|
|
22
25
|
registerMiddleware(middleware: MiddlewareHandler): void;
|
|
23
26
|
setDefaultHeaders(headers: Record<string, string>): void;
|
|
24
27
|
start(port: number, host?: string): Promise<void>;
|
|
@@ -58,11 +61,12 @@ type RateLimitRules = Record<string, {
|
|
|
58
61
|
requests: number;
|
|
59
62
|
window: string;
|
|
60
63
|
action: RateLimitAction;
|
|
64
|
+
header?: string | undefined;
|
|
61
65
|
}>;
|
|
62
66
|
declare class RateLimiter {
|
|
63
67
|
#private;
|
|
64
68
|
constructor(rules: RateLimitRules);
|
|
65
|
-
check(ip: string, path: string): RateLimitDecision | null;
|
|
69
|
+
check(ip: string, path: string, headers?: Readonly<Record<string, unknown>>): RateLimitDecision | null;
|
|
66
70
|
/**
|
|
67
71
|
* For a route that counts failures only: refuses when any of `keys` (an IP, an account) already holds the rule's
|
|
68
72
|
* full count, without counting this request. `hit` and `clear` record the outcome once the handler has answered.
|
|
@@ -89,10 +93,46 @@ interface HttpServer {
|
|
|
89
93
|
}>;
|
|
90
94
|
stop(): Promise<void>;
|
|
91
95
|
}
|
|
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;
|
|
92
102
|
declare function createHttpServer(deps: HttpServerDeps): HttpServer;
|
|
93
103
|
|
|
94
104
|
declare function createHealthRoute(version: string): RouteHandler;
|
|
95
105
|
|
|
106
|
+
type ReadyState = {
|
|
107
|
+
ready: true;
|
|
108
|
+
} | {
|
|
109
|
+
ready: false;
|
|
110
|
+
failing: string[];
|
|
111
|
+
};
|
|
112
|
+
/** GET /ready: 200 when the store can take traffic, else 503 naming what cannot, by name only. */
|
|
113
|
+
declare function createReadyRoute(probe: () => Promise<ReadyState>): RouteHandler;
|
|
114
|
+
|
|
115
|
+
interface StorefrontForwardOptions {
|
|
116
|
+
/** The storefront's internal port on 127.0.0.1. */
|
|
117
|
+
port: number;
|
|
118
|
+
/** The store's public origin: the storefront sees its host and scheme, whatever the client sent. */
|
|
119
|
+
publicUrl: string;
|
|
120
|
+
}
|
|
121
|
+
interface StorefrontForward {
|
|
122
|
+
/** Forwards started and not yet ended or cut. */
|
|
123
|
+
inFlight(): number;
|
|
124
|
+
/** From now on a new page request answers 503; forwards in flight go on. */
|
|
125
|
+
refuse(): void;
|
|
126
|
+
/** Resolves true once no forward is in flight, false when `timeoutMs` passes first. */
|
|
127
|
+
drained(timeoutMs: number): Promise<boolean>;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Forwards every request the API does not route to the storefront on its internal port, body and headers unchanged
|
|
131
|
+
* both ways. A path under /api/ keeps the API's not-found answer and never reaches the storefront. Call before
|
|
132
|
+
* `adapter.start`.
|
|
133
|
+
*/
|
|
134
|
+
declare function forwardToStorefront(adapter: FastifyHttpAdapter, options: StorefrontForwardOptions): StorefrontForward;
|
|
135
|
+
|
|
96
136
|
interface ProductListItem {
|
|
97
137
|
id: string;
|
|
98
138
|
slug: string;
|
|
@@ -105,5 +145,5 @@ interface ProductListItem {
|
|
|
105
145
|
}
|
|
106
146
|
declare function createProductsRoute(documentStore: DocumentStoreAdapter, storeId: string): RouteHandler;
|
|
107
147
|
|
|
108
|
-
export { CSRF_COOKIE, CSRF_HEADER, FastifyHttpAdapter, RateLimiter, buildSecurityHeaders, createHealthRoute, createHttpServer, createProductsRoute, createSecurityGuard };
|
|
109
|
-
export type { CorsOptions, FastifyAdapterOptions, HttpServer, HttpServerDeps, ProductListItem, SecurityGuard };
|
|
148
|
+
export { CSRF_COOKIE, CSRF_HEADER, FastifyHttpAdapter, RateLimiter, buildSecurityHeaders, createHealthRoute, createHttpServer, createProductsRoute, createReadyRoute, createSecurityGuard, forwardToStorefront, resolveTrustProxy };
|
|
149
|
+
export type { CorsOptions, FastifyAdapterOptions, HttpServer, HttpServerDeps, ProductListItem, ReadyState, SecurityGuard, StorefrontForward, StorefrontForwardOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// src/fastify-adapter.ts
|
|
2
|
-
import Fastify
|
|
2
|
+
import Fastify, {
|
|
3
|
+
errorCodes
|
|
4
|
+
} from "fastify";
|
|
3
5
|
import fastifyCookie from "@fastify/cookie";
|
|
4
6
|
import fastifyCors from "@fastify/cors";
|
|
5
7
|
import { v7 as uuidv7 } from "uuid";
|
|
@@ -15,13 +17,21 @@ import {
|
|
|
15
17
|
import { randomBytes, timingSafeEqual } from "crypto";
|
|
16
18
|
|
|
17
19
|
// src/rate-limit.ts
|
|
20
|
+
import { ORDER_EMAIL_HEADER } from "@nymbalhq/types";
|
|
18
21
|
var BUILT_IN_RATE_LIMITS = {
|
|
19
22
|
"/api/auth/login": { requests: 10, window: "15m", action: "block" },
|
|
20
23
|
"/api/auth/register": { requests: 10, window: "1h", action: "block" },
|
|
21
24
|
// A record and a list per page view: 300 page views a minute, so shoppers behind one NAT keep their views.
|
|
22
25
|
"/api/recently-viewed": { requests: 600, window: "1m", action: "block" },
|
|
23
26
|
// Each accepted subscribe mails a confirmation: the bound on how much mail one IP can make the store send.
|
|
24
|
-
"/api/alerts/subscribe": { requests: 10, window: "1h", action: "block" }
|
|
27
|
+
"/api/alerts/subscribe": { requests: 10, window: "1h", action: "block" },
|
|
28
|
+
// Each match mails the order's link. Before the order-read rule, which a request carrying the email would also match.
|
|
29
|
+
"/api/orders/link": { requests: 5, window: "1h", action: "block" },
|
|
30
|
+
// The email is the second factor of an expired order key: bounded so it cannot be guessed. The key-only poll of a
|
|
31
|
+
// pending order carries no email and is never counted.
|
|
32
|
+
"/api/orders/*": { requests: 10, window: "1h", action: "block", header: ORDER_EMAIL_HEADER },
|
|
33
|
+
// Every checkout answer can mint an order key.
|
|
34
|
+
"/api/checkout": { requests: 30, window: "1m", action: "block" }
|
|
25
35
|
};
|
|
26
36
|
var PRUNE_THRESHOLD = 1024;
|
|
27
37
|
var RateLimiter = class {
|
|
@@ -32,13 +42,14 @@ var RateLimiter = class {
|
|
|
32
42
|
this.#rules = Object.entries(rules).map(([pattern, rule]) => ({
|
|
33
43
|
pattern,
|
|
34
44
|
regex: compilePathPattern(pattern),
|
|
45
|
+
...rule.header !== void 0 && { header: rule.header.toLowerCase() },
|
|
35
46
|
requests: rule.requests,
|
|
36
47
|
windowMs: parseWindow(rule.window),
|
|
37
48
|
action: rule.action
|
|
38
49
|
}));
|
|
39
50
|
}
|
|
40
|
-
check(ip, path) {
|
|
41
|
-
const rule = this.#ruleFor(path);
|
|
51
|
+
check(ip, path, headers = {}) {
|
|
52
|
+
const rule = this.#ruleFor(path, headers);
|
|
42
53
|
if (!rule) return null;
|
|
43
54
|
const key = `${rule.pattern}|${ip}`;
|
|
44
55
|
const now = Date.now();
|
|
@@ -104,8 +115,10 @@ var RateLimiter = class {
|
|
|
104
115
|
}
|
|
105
116
|
this.#buckets.set(key, { count: 1, resetAt: now + windowMs });
|
|
106
117
|
}
|
|
107
|
-
#ruleFor(path) {
|
|
108
|
-
return this.#rules.find(
|
|
118
|
+
#ruleFor(path, headers = {}) {
|
|
119
|
+
return this.#rules.find(
|
|
120
|
+
(r) => r.regex.test(path) && (r.header === void 0 || headers[r.header] !== void 0)
|
|
121
|
+
);
|
|
109
122
|
}
|
|
110
123
|
};
|
|
111
124
|
function retryAfter(bucket, now) {
|
|
@@ -179,7 +192,7 @@ function createSecurityGuard(security) {
|
|
|
179
192
|
}
|
|
180
193
|
return {
|
|
181
194
|
admit(ctx, options = {}) {
|
|
182
|
-
const decision = isLogin(ctx) ? rateLimiter.full(ctx.path, loginKeys(ctx)) : rateLimiter.check(ctx.ip, ctx.path);
|
|
195
|
+
const decision = isLogin(ctx) ? rateLimiter.full(ctx.path, loginKeys(ctx)) : rateLimiter.check(ctx.ip, ctx.path, ctx.headers);
|
|
183
196
|
if (decision && !decision.allowed) {
|
|
184
197
|
return applyHeaders(rateLimitResponse(decision, ctx));
|
|
185
198
|
}
|
|
@@ -293,13 +306,30 @@ var FastifyHttpAdapter = class {
|
|
|
293
306
|
this.#app.initialConfig.onProtoPoisoning ?? "error",
|
|
294
307
|
this.#app.initialConfig.onConstructorPoisoning ?? "error"
|
|
295
308
|
);
|
|
309
|
+
const takesRawBody = (req) => req.routeOptions.config?.routeOptions?.rawBody === true;
|
|
296
310
|
this.#app.removeContentTypeParser("application/json");
|
|
297
311
|
this.#app.addContentTypeParser("application/json", { parseAs: "buffer" }, (req, body, done) => {
|
|
298
312
|
const buffer = body;
|
|
299
|
-
|
|
300
|
-
if (config?.routeOptions?.rawBody === true) req.rawBody = buffer;
|
|
313
|
+
if (takesRawBody(req)) req.rawBody = buffer;
|
|
301
314
|
parseJson(req, buffer.toString("utf8"), done);
|
|
302
315
|
});
|
|
316
|
+
const keepRawBody = (elsewhere) => (req, body, done) => {
|
|
317
|
+
const buffer = body;
|
|
318
|
+
if (takesRawBody(req)) req.rawBody = buffer;
|
|
319
|
+
else if (elsewhere === "refuse" && !req.is404) {
|
|
320
|
+
done(new errorCodes.FST_ERR_CTP_INVALID_MEDIA_TYPE(req.headers["content-type"]));
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
done(null, buffer.toString("utf8"));
|
|
324
|
+
};
|
|
325
|
+
this.#app.removeContentTypeParser("text/plain");
|
|
326
|
+
this.#app.addContentTypeParser("text/plain", { parseAs: "buffer" }, keepRawBody("text"));
|
|
327
|
+
this.#app.addContentTypeParser(
|
|
328
|
+
"application/x-www-form-urlencoded",
|
|
329
|
+
{ parseAs: "buffer" },
|
|
330
|
+
keepRawBody("refuse")
|
|
331
|
+
);
|
|
332
|
+
this.#app.addContentTypeParser("*", { parseAs: "buffer" }, keepRawBody("refuse"));
|
|
303
333
|
this.#app.addHook("preClose", async () => {
|
|
304
334
|
this.#stopping = true;
|
|
305
335
|
for (const endStream of this.#openStreams) endStream();
|
|
@@ -446,6 +476,13 @@ var FastifyHttpAdapter = class {
|
|
|
446
476
|
config: { routeOptions: options ?? {} }
|
|
447
477
|
});
|
|
448
478
|
}
|
|
479
|
+
/** A Fastify plugin on this server, in a context of its own: how the storefront forward is added. */
|
|
480
|
+
registerPlugin(plugin) {
|
|
481
|
+
if (this.#started) {
|
|
482
|
+
throw new Error("Cannot register plugins after the server has started");
|
|
483
|
+
}
|
|
484
|
+
void this.#app.register(plugin);
|
|
485
|
+
}
|
|
449
486
|
registerMiddleware(middleware) {
|
|
450
487
|
if (this.#started) {
|
|
451
488
|
throw new Error("Cannot register middleware after the server has started");
|
|
@@ -548,6 +585,11 @@ var FastifyHttpAdapter = class {
|
|
|
548
585
|
}
|
|
549
586
|
};
|
|
550
587
|
|
|
588
|
+
// src/server.ts
|
|
589
|
+
import {
|
|
590
|
+
ConfigError
|
|
591
|
+
} from "@nymbalhq/types";
|
|
592
|
+
|
|
551
593
|
// src/routes/health.ts
|
|
552
594
|
function createHealthRoute(version) {
|
|
553
595
|
return () => ({
|
|
@@ -578,6 +620,19 @@ function createProductsRoute(documentStore, storeId) {
|
|
|
578
620
|
}
|
|
579
621
|
|
|
580
622
|
// src/server.ts
|
|
623
|
+
var TRUST_PROXY_HOPS_ENV = "NYMBAL_TRUST_PROXY_HOPS";
|
|
624
|
+
function resolveTrustProxy(config, env) {
|
|
625
|
+
const raw = env[TRUST_PROXY_HOPS_ENV];
|
|
626
|
+
const hops = raw === void 0 ? void 0 : /^\d+$/.test(raw.trim()) ? Number(raw) : NaN;
|
|
627
|
+
if (hops !== void 0 && !Number.isSafeInteger(hops)) {
|
|
628
|
+
throw new ConfigError(`${TRUST_PROXY_HOPS_ENV} must be a whole number of proxy hops, 0 or more`, {
|
|
629
|
+
code: "config.trust_proxy_hops_invalid",
|
|
630
|
+
context: { variable: TRUST_PROXY_HOPS_ENV }
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
const configured = config.http.trustProxy;
|
|
634
|
+
return configured === false && hops !== void 0 ? hops : configured;
|
|
635
|
+
}
|
|
581
636
|
function createHttpServer(deps) {
|
|
582
637
|
const { config, logger, documentStore, version } = deps;
|
|
583
638
|
if (config.http.adapter !== "fastify") {
|
|
@@ -587,7 +642,7 @@ function createHttpServer(deps) {
|
|
|
587
642
|
logger,
|
|
588
643
|
cors: config.http.cors,
|
|
589
644
|
security: config.security,
|
|
590
|
-
trustProxy: config.
|
|
645
|
+
trustProxy: resolveTrustProxy(config, process.env)
|
|
591
646
|
});
|
|
592
647
|
const server = {
|
|
593
648
|
adapter,
|
|
@@ -611,6 +666,92 @@ function createHttpServer(deps) {
|
|
|
611
666
|
void config;
|
|
612
667
|
return server;
|
|
613
668
|
}
|
|
669
|
+
|
|
670
|
+
// src/routes/ready.ts
|
|
671
|
+
function createReadyRoute(probe) {
|
|
672
|
+
return async () => {
|
|
673
|
+
const state = await probe();
|
|
674
|
+
return state.ready ? { status: 200, body: { status: "ready" } } : { status: 503, body: { status: "not-ready", failing: state.failing } };
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// src/storefront-forward.ts
|
|
679
|
+
import httpProxy from "@fastify/http-proxy";
|
|
680
|
+
var FORWARDED_METHODS = ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"];
|
|
681
|
+
function forwardToStorefront(adapter, options) {
|
|
682
|
+
const origin = new URL(options.publicUrl);
|
|
683
|
+
const proto = origin.protocol.slice(0, -1);
|
|
684
|
+
let inFlight = 0;
|
|
685
|
+
let refusing = false;
|
|
686
|
+
const waiters = /* @__PURE__ */ new Set();
|
|
687
|
+
const settle = () => {
|
|
688
|
+
inFlight -= 1;
|
|
689
|
+
if (inFlight === 0) for (const wake of [...waiters]) wake();
|
|
690
|
+
};
|
|
691
|
+
adapter.registerPlugin(async (api) => {
|
|
692
|
+
api.removeAllContentTypeParsers();
|
|
693
|
+
api.addContentTypeParser("*", (_req, payload, done) => done(null, payload));
|
|
694
|
+
api.route({
|
|
695
|
+
method: FORWARDED_METHODS,
|
|
696
|
+
url: "/api/*",
|
|
697
|
+
handler: (_req, reply) => reply.callNotFound()
|
|
698
|
+
});
|
|
699
|
+
});
|
|
700
|
+
adapter.registerPlugin(async (pages) => {
|
|
701
|
+
pages.removeAllContentTypeParsers();
|
|
702
|
+
await pages.register(httpProxy, {
|
|
703
|
+
upstream: `http://127.0.0.1:${options.port}`,
|
|
704
|
+
httpMethods: FORWARDED_METHODS,
|
|
705
|
+
internalRewriteLocationHeader: false,
|
|
706
|
+
preHandler: (_req, reply, done) => {
|
|
707
|
+
if (refusing) {
|
|
708
|
+
void reply.code(503).header("connection", "close").send({ error: { code: "unavailable", message: "The store is shutting down" } });
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
inFlight += 1;
|
|
712
|
+
reply.raw.once("close", settle);
|
|
713
|
+
done();
|
|
714
|
+
},
|
|
715
|
+
replyOptions: {
|
|
716
|
+
rewriteRequestHeaders: (req, headers) => {
|
|
717
|
+
const prior = req.headers["x-forwarded-for"];
|
|
718
|
+
const peer = req.raw.socket.remoteAddress ?? req.ip;
|
|
719
|
+
return {
|
|
720
|
+
...headers,
|
|
721
|
+
host: origin.host,
|
|
722
|
+
"x-forwarded-host": origin.host,
|
|
723
|
+
"x-forwarded-proto": proto,
|
|
724
|
+
"x-forwarded-for": [prior, peer].flat().filter(Boolean).join(", ")
|
|
725
|
+
};
|
|
726
|
+
},
|
|
727
|
+
// A forward is never retried: a page POST may not be idempotent, and a 503 is the storefront's answer.
|
|
728
|
+
retryDelay: () => null,
|
|
729
|
+
onError: (reply) => {
|
|
730
|
+
void reply.code(503).send({ error: { code: "unavailable", message: "The storefront is not answering" } });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
});
|
|
735
|
+
return {
|
|
736
|
+
inFlight: () => inFlight,
|
|
737
|
+
refuse() {
|
|
738
|
+
refusing = true;
|
|
739
|
+
},
|
|
740
|
+
drained(timeoutMs) {
|
|
741
|
+
if (inFlight === 0) return Promise.resolve(true);
|
|
742
|
+
return new Promise((resolve) => {
|
|
743
|
+
const finish = (value) => {
|
|
744
|
+
clearTimeout(timer);
|
|
745
|
+
waiters.delete(wake);
|
|
746
|
+
resolve(value);
|
|
747
|
+
};
|
|
748
|
+
const wake = () => finish(true);
|
|
749
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
750
|
+
waiters.add(wake);
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
}
|
|
614
755
|
export {
|
|
615
756
|
CSRF_COOKIE,
|
|
616
757
|
CSRF_HEADER,
|
|
@@ -620,6 +761,9 @@ export {
|
|
|
620
761
|
createHealthRoute,
|
|
621
762
|
createHttpServer,
|
|
622
763
|
createProductsRoute,
|
|
623
|
-
|
|
764
|
+
createReadyRoute,
|
|
765
|
+
createSecurityGuard,
|
|
766
|
+
forwardToStorefront,
|
|
767
|
+
resolveTrustProxy
|
|
624
768
|
};
|
|
625
769
|
//# sourceMappingURL=index.js.map
|
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/routes/health.ts","../src/routes/products.ts","../src/server.ts"],"sourcesContent":["import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } 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 /** Whether `X-Forwarded-For` sets the request IP. Off unless a trusted proxy sits in front. */\n trustProxy?: boolean\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 this.#app.removeContentTypeParser('application/json')\n this.#app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (req, body, done) => {\n const buffer = body as Buffer\n const config = req.routeOptions.config as { routeOptions?: RouteOptions } | undefined\n if (config?.routeOptions?.rawBody === true) req.rawBody = buffer\n parseJson(req, buffer.toString('utf8'), done)\n })\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 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)\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 type { RateLimitAction } from '@nymbalhq/types'\n\nexport interface ParsedRule {\n pattern: string\n regex: RegExp\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<string, { requests: number; window: string; action: RateLimitAction }>\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}\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 requests: rule.requests,\n windowMs: parseWindow(rule.window),\n action: rule.action,\n }))\n }\n\n check(ip: string, path: string): RateLimitDecision | null {\n const rule = this.#ruleFor(path)\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): ParsedRule | undefined {\n return this.#rules.find((r) => r.regex.test(path))\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 { 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 { NymbalConfig } from '@nymbalhq/config'\nimport type {\n DocumentStoreAdapter,\n HttpAdapter,\n HttpMethod,\n Logger,\n MiddlewareHandler,\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}\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\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: config.http.trustProxy,\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"],"mappings":";AAAA,OAAO,aAA+E;AACtF,OAAO,mBAAmB;AAC1B,OAAO,iBAAiB;AACxB,SAAS,MAAM,cAAc;AAc7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACvBP,SAAS,aAAa,uBAAuB;;;ACsBtC,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;AACzE;AAQA,IAAM,kBAAkB;AAEjB,IAAM,cAAN,MAAkB;AAAA,EACd;AAAA,EACA,WAAW,oBAAI,IAAoB;AAAA,EAC5C,WAAW;AAAA,EAEX,YAAY,OAAuB;AACjC,SAAK,SAAS,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO;AAAA,MAC5D;AAAA,MACA,OAAO,mBAAmB,OAAO;AAAA,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A,IACzB;AAAA,IACA,cAAc,QAAQ,MAAM,SAAS,SAAS;AAC5C,cAAQ,cAAc,QAAQ,MAAM,SAAS,OAAO;AAAA,IACtD;AAAA,IACA,mBAAmB,YAAY;AAC7B,cAAQ,mBAAmB,UAAU;AAAA,IACvC;AAAA,IACA,MAAM,QAAQ;AACZ,YAAM,QAAQ,MAAM,OAAO,KAAK,MAAM,OAAO,KAAK,IAAI;AACtD,aAAO,EAAE,MAAM,QAAQ,WAAW,MAAM,OAAO,KAAK,KAAK;AAAA,IAC3D;AAAA,IACA,MAAM,OAAO;AACX,YAAM,QAAQ,KAAK;AAAA,IACrB;AAAA,EACF;AAGA,SAAO,cAAc,OAAO,WAAW,kBAAkB,OAAO,CAAC;AAIjE,OAAK;AACL,OAAK;AACL,OAAK;AAEL,SAAO;AACT;","names":[]}
|
|
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;AA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
|
{
|
|
2
2
|
"name": "@nymbalhq/http",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Framework-agnostic HTTP abstraction with Fastify adapter",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -29,8 +29,9 @@
|
|
|
29
29
|
"dependencies": {
|
|
30
30
|
"@fastify/cookie": "^9.4.0",
|
|
31
31
|
"@fastify/cors": "^8.5.0",
|
|
32
|
-
"@
|
|
33
|
-
"@nymbalhq/
|
|
32
|
+
"@fastify/http-proxy": "9.5.0",
|
|
33
|
+
"@nymbalhq/config": "1.5.0",
|
|
34
|
+
"@nymbalhq/types": "1.5.0",
|
|
34
35
|
"fastify": "^4.28.1",
|
|
35
36
|
"uuid": "^10.0.0"
|
|
36
37
|
},
|