-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathindex.ts
More file actions
3317 lines (3129 loc) · 103 KB
/
Copy pathindex.ts
File metadata and controls
3317 lines (3129 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
import { createRequire } from "node:module";
import express, { type NextFunction, type Request, type Response } from "express";
import cors from "cors";
import helmet from "helmet";
import { logger } from "./logger";
import { openApiSpec } from "./openapi";
import { isSafeWebhookUrl } from "./utils/webhookUrl";
import { resolveClientIp } from "./utils/clientIp";
import { getStoreAdapter } from "./persistence";
import {
isPaused,
isReadOnly,
pairRegistry,
pairMeta,
apiKeyStore,
webhookStore,
eventLog,
rateBuckets,
config,
setPaused,
setReadOnly,
pairKey,
defaultMeta,
recordEvent,
trimEventLog,
EVENT_LOG_CAP,
EVENT_LOG_CAP_MAX,
RATE_BUCKETS_MAX_IPS,
HEALTH_PROBE_KEY,
KNOWN_EVENT_TYPES,
hydrateFromSnapshot,
setHydrating,
apiKeyPrefix,
generateApiKeySalt,
hashApiKeySecret,
verifyApiKeySecret,
type PairMeta,
type AppEvent,
type ApiKeyRecord,
type EventType,
} from "./stores";
import { applySlippage, checkQuoteBounds, priceQuote, priceReverseQuote } from "./pricing";
interface CacheEntry {
value: {
source_asset: string;
dest_asset: string;
amount: string;
estimated_rate: string;
route: string[];
feeBps: number;
feeAmount: string;
netAmount: string;
slippage_bps: number;
min_received: string;
rate: string;
};
expiresAt: number;
}
export const quoteCache = new Map<string, CacheEntry>();
export const pairMetaVersions = new Map<string, number>();
export let cacheHits = 0;
export let cacheMisses = 0;
export function resetQuoteCache() {
quoteCache.clear();
pairMetaVersions.clear();
cacheHits = 0;
cacheMisses = 0;
}
export function invalidateQuoteCache(k: string): void {
const current = pairMetaVersions.get(k) ?? 0;
pairMetaVersions.set(k, current + 1);
for (const cacheKey of quoteCache.keys()) {
if (cacheKey.startsWith(`${k}::`)) {
quoteCache.delete(cacheKey);
}
}
}
// Monkeypatch Set.prototype.clear and Map.prototype.clear for the store registry/meta instances
const origRegistryClear = pairRegistry.clear;
pairRegistry.clear = function (this: Set<string>) {
const res = origRegistryClear.apply(this);
resetQuoteCache();
return res;
};
const origMetaClear = pairMeta.clear;
pairMeta.clear = function (this: Map<string, PairMeta>) {
const res = origMetaClear.apply(this);
resetQuoteCache();
return res;
};
/** Maximum number of event-type entries per webhook subscription. */
const WEBHOOK_MAX_EVENTS = 20;
/** Maximum length of a single event-type name string. */
const WEBHOOK_MAX_EVENT_LENGTH = 128;
/** Event name prefixes reserved for internal use. */
const WEBHOOK_RESERVED_PREFIXES = ["internal.", "system.", "admin."];
/** Absolute ceiling for bulk item counts — operators cannot raise beyond this. */
const BULK_ABSOLUTE_MAX = 10_000;
/** Default cap for bulk endpoints when the config value is not set. */
const DEFAULT_BULK_MAX_ITEMS = 100;
/** Minimum length of an event `type` field accepted by POST /api/v1/events. */
const EVENT_TYPE_MIN_LENGTH = 1;
/** Maximum length of an event `type` field accepted by POST /api/v1/events. */
const EVENT_TYPE_MAX_LENGTH = 128;
/** Maximum number of keys allowed in the top-level `payload` object. */
const EVENT_PAYLOAD_MAX_KEYS = 32;
/** Maximum byte-length of a single string value within a `payload`. */
const EVENT_PAYLOAD_MAX_STRING_LENGTH = 256;
/** Maximum number of entries allowed in a single `payload` array. */
const EVENT_PAYLOAD_MAX_ARRAY_ITEMS = 32;
/** Maximum nesting depth allowed for the recursive `payload` shape. */
const EVENT_PAYLOAD_MAX_DEPTH = 3;
const app = express();
// --- Persistence Hydration on startup ---
export const hydrationPromise = (async () => {
try {
const adapter = getStoreAdapter();
setHydrating(true);
const snapshot = await adapter.load();
if (snapshot) {
hydrateFromSnapshot(snapshot);
logger.info("[persistence] hydrated stores successfully from adapter");
} else {
logger.info("[persistence] no snapshot found or hydration skipped");
}
} catch (err) {
logger.error({ err }, "[persistence] hydration failed");
} finally {
setHydrating(false);
}
})();
const DEFAULT_CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://localhost:3001",
"http://127.0.0.1:3000",
"http://127.0.0.1:3001",
];
/** Parse a comma-separated CORS origin allowlist, falling back to localhost-only development origins. */
export const parseCorsAllowedOrigins = (
value: string | undefined,
): Set<string> => {
const source =
value === undefined || value.trim() === ""
? DEFAULT_CORS_ALLOWED_ORIGINS.join(",")
: value;
return new Set(
source
.split(",")
.map((origin) => origin.trim())
.filter(Boolean),
);
};
/**
* Resolve whether an inbound Origin is allowed.
*
* Requests without an Origin header are same-origin/server-to-server traffic and
* are passed through without reflecting arbitrary browser origins.
*/
export const isCorsOriginAllowed = (
origin: string | undefined,
allowedOrigins: Set<string>,
): boolean => origin === undefined || allowedOrigins.has(origin);
const corsAllowedOrigins = parseCorsAllowedOrigins(
process.env.CORS_ALLOWED_ORIGINS,
);
app.use(
cors({
credentials: false,
origin: (origin, callback) => {
callback(null, isCorsOriginAllowed(origin, corsAllowedOrigins));
},
}),
);
type RequestWithId = Request & { id?: string };
type ErrorResponseExtra = Record<string, unknown>;
/** Union of all error codes used in API responses. */
export type ApiErrorCode =
| "not_found"
| "invalid_request"
| "invalid_json"
| "unauthorized"
| "forbidden"
| "rate_limited"
| "service_paused"
| "internal_error"
| "not_acceptable"
| "payload_too_large"
| "conflict"
| "method_not_allowed"
| "read_only_mode"
| "pair_not_registered"
| "idempotency_conflict"
| "unsupported_media_type"
| "insufficient_liquidity"
| "request_timeout";
export type ApiErrorDefinition = {
readonly status: number;
readonly safeMessage: string;
readonly expose: boolean;
};
/**
* Single status/message taxonomy for API errors. Explicit route handlers and
* the final Express error middleware both resolve through this map so clients
* can rely on stable codes and statuses.
*/
export const API_ERROR_DEFINITIONS: Record<ApiErrorCode, ApiErrorDefinition> = {
not_found: {
status: 404,
safeMessage: "resource not found",
expose: true,
},
invalid_request: {
status: 400,
safeMessage: "request is invalid",
expose: true,
},
invalid_json: {
status: 400,
safeMessage: "request body is not valid JSON",
expose: true,
},
unauthorized: {
status: 401,
safeMessage: "authentication is required",
expose: true,
},
forbidden: {
status: 403,
safeMessage: "permission denied",
expose: true,
},
rate_limited: {
status: 429,
safeMessage: "too many requests",
expose: true,
},
service_paused: {
status: 503,
safeMessage: "service is paused",
expose: true,
},
internal_error: {
status: 500,
safeMessage: "An unexpected error occurred",
expose: false,
},
not_acceptable: {
status: 406,
safeMessage: "requested response format is not acceptable",
expose: true,
},
payload_too_large: {
status: 413,
safeMessage: "request body exceeds the 100 KiB limit",
expose: true,
},
conflict: {
status: 409,
safeMessage: "resource conflict",
expose: true,
},
method_not_allowed: {
status: 405,
safeMessage: "method not allowed",
expose: true,
},
read_only_mode: {
status: 503,
safeMessage: "service is in read-only mode",
expose: true,
},
pair_not_registered: {
status: 404,
safeMessage: "pair not registered",
expose: true,
},
idempotency_conflict: {
status: 409,
safeMessage: "idempotency key conflicts with a different request body",
expose: true,
},
unsupported_media_type: {
status: 415,
safeMessage: "unsupported media type",
expose: true,
},
insufficient_liquidity: {
status: 422,
safeMessage: "insufficient liquidity",
expose: true,
},
request_timeout: {
status: 503,
safeMessage: "Request timed out",
expose: true,
},
};
export class ApiError extends Error {
readonly code: ApiErrorCode;
readonly status: number;
readonly expose: boolean;
readonly extra: ErrorResponseExtra;
constructor(
code: ApiErrorCode,
message?: string,
extra: ErrorResponseExtra = {},
) {
const definition = API_ERROR_DEFINITIONS[code];
super(message ?? definition.safeMessage);
this.name = "ApiError";
this.code = code;
this.status = definition.status;
this.expose = definition.expose;
this.extra = extra;
}
}
/**
* Validates an inbound X-Request-Id value.
*
* Accepted format: 1–200 characters drawn exclusively from the conservative
* token charset `[A-Za-z0-9._-]`. This deliberately excludes control
* characters, CR, LF, and other non-token bytes that could be used for
* header-injection or log-injection attacks.
*
* @param value - The raw header value to validate.
* @returns `true` when the value is safe to echo; `false` otherwise.
*/
export const isValidRequestId = (value: string): boolean =>
value.length > 0 && value.length <= 200 && /^[A-Za-z0-9._-]+$/.test(value);
/**
* Read the request id attached by the correlation middleware.
*/
const getRequestId = (req: Request): string | undefined =>
(req as RequestWithId).id;
const writeApiErrorResponse = (
res: Response,
req: Request,
apiError: ApiError,
) => {
const definition = API_ERROR_DEFINITIONS[apiError.code];
const body: Record<string, unknown> = {
code: apiError.code,
error: apiError.code,
message: apiError.expose ? apiError.message : definition.safeMessage,
...apiError.extra,
};
const requestId = getRequestId(req);
if (requestId !== undefined) {
body.requestId = requestId;
}
return res.status(apiError.status).json(body);
};
/**
* Send the canonical API error body used by explicit handlers. The status
* argument is retained for call-site readability, while the emitted status
* comes from API_ERROR_DEFINITIONS so code-to-status mapping lives in one place.
*/
const sendError = (
res: Response,
req: Request,
status: number,
error: ApiErrorCode,
message: string,
extra: ErrorResponseExtra = {},
) => {
const apiError = new ApiError(error, message, extra);
if (status !== apiError.status) {
logger.warn(
{
code: error,
requestedStatus: status,
mappedStatus: apiError.status,
requestId: getRequestId(req),
},
"api error status resolved from taxonomy",
);
}
return writeApiErrorResponse(res, req, apiError);
};
const hasParserType = (err: unknown, type: string): boolean =>
Boolean(
err &&
typeof err === "object" &&
"type" in err &&
(err as { type: unknown }).type === type,
);
const toApiError = (err: unknown): ApiError | undefined => {
if (err instanceof ApiError) {
return err;
}
if (hasParserType(err, "entity.too.large")) {
return new ApiError("payload_too_large");
}
if (hasParserType(err, "entity.parse.failed") || err instanceof SyntaxError) {
return new ApiError("invalid_json");
}
return undefined;
};
export const apiErrorHandler = (
err: unknown,
req: Request,
res: Response,
next: NextFunction,
) => {
if (res.headersSent) {
next(err);
return;
}
const apiError =
toApiError(err) ??
new ApiError("internal_error", undefined, {
method: req.method,
path: req.path,
});
if (apiError.code === "internal_error") {
logger.error(
{
err,
requestId: getRequestId(req),
method: req.method,
path: req.path,
},
"unhandled request error",
);
}
writeApiErrorResponse(res, req, apiError);
};
/**
* Helper to retrieve the active request timeout in milliseconds.
* Checks `config.requestTimeoutMs` first, falls back to `process.env.REQUEST_TIMEOUT_MS`
* if it is a valid number, and defaults to 10 seconds (10,000 ms).
*/
const getRequestTimeoutMs = (): number => {
if (config.requestTimeoutMs !== undefined) {
return config.requestTimeoutMs;
}
if (process.env.REQUEST_TIMEOUT_MS !== undefined) {
const parsed = Number(process.env.REQUEST_TIMEOUT_MS);
if (!Number.isNaN(parsed)) return parsed;
}
return 10000;
};
/**
* Express middleware that enforces a per-request timeout.
* Arms a timer based on the configured deadline (from `config.requestTimeoutMs` or
* `process.env.REQUEST_TIMEOUT_MS`, defaulting to 10s).
* If the response does not complete in time, it sends a `503 request_timeout`
* canonical error response. The timer is cleared upon request completion ('finish')
* or connection close ('close') to avoid resource/timer leaks.
*
* Checks `res.headersSent` to prevent a double-send / crash if headers are already sent.
*/
export const requestTimeoutGuard = (
req: Request,
res: Response,
next: NextFunction,
): void => {
const timeoutMs = getRequestTimeoutMs();
const timer = setTimeout(() => {
if (res.headersSent) {
logger.warn(
{ requestId: getRequestId(req), method: req.method, path: req.path },
"Request timeout triggered but headers were already sent.",
);
return;
}
sendError(res, req, 503, "request_timeout", "Request timed out");
}, timeoutMs);
const clearTimer = () => {
clearTimeout(timer);
};
res.on("finish", clearTimer);
res.on("close", clearTimer);
next();
};
/**
* Helper to retrieve the current idempotency TTL in milliseconds.
* Always resolves dynamically from `process.env.IDEMPOTENCY_TTL_MS`
* to allow test overrides, falling back to 24 hours.
*/
const getIdempotencyTtlMs = (): number =>
Number(process.env.IDEMPOTENCY_TTL_MS ?? 24 * 60 * 60 * 1000);
/**
* Helper to retrieve the maximum number of entries kept in the idempotency cache.
* Always resolves dynamically from `process.env.IDEMPOTENCY_CACHE_MAX`
* to allow test overrides, falling back to 10,000.
*/
const getIdempotencyCacheMax = (): number =>
Number(process.env.IDEMPOTENCY_CACHE_MAX ?? 10_000);
interface IdempotencyCacheEntry {
status: number;
body: unknown;
bodyHash: string;
expiresAt: number;
}
/**
* In-memory idempotency cache keyed by `"METHOD:path:idempotency-key"`.
* Entries are TTL-expiring and the map is bounded to IDEMPOTENCY_CACHE_MAX
* entries (oldest-first eviction).
*/
const idempotencyCache = new Map<string, IdempotencyCacheEntry>();
/**
* Clear the internal idempotency cache.
* Exposes the store for test isolation to prevent cross-test state bleed.
*/
export const clearIdempotencyCache = (): void => {
idempotencyCache.clear();
};
/**
* Evict all expired entries. When the cache is still at capacity after
* expiry-based eviction, drop the oldest insertion-order entry.
*/
const pruneIdempotencyCache = (): void => {
const now = Date.now();
for (const [k, entry] of idempotencyCache) {
if (entry.expiresAt <= now) idempotencyCache.delete(k);
}
if (idempotencyCache.size >= getIdempotencyCacheMax()) {
const oldest = idempotencyCache.keys().next().value;
if (oldest !== undefined) idempotencyCache.delete(oldest);
}
};
/**
* Express middleware that implements Idempotency-Key semantics for create
* (POST) endpoints.
*
* @param req - Express Request object
* @param res - Express Response object
* @param next - Express NextFunction
*
* @remarks
* Behaviour:
* - No Idempotency-Key header: passes through unchanged.
* - Key present but outside 1-200 chars: passes through unchanged.
* - First request with a key: executes the handler, captures the response,
* and stores `{ status, body, bodyHash, expiresAt }` in the cache.
* - Repeat request with matching key + matching body hash: replays cached
* response verbatim (no handler invocation).
* - Repeat request with matching key but different body: 409 idempotency_conflict.
*
* Cache entries expire after dynamic TTL (default 24 h).
*/
const idempotencyGuard = (
req: Request,
res: Response,
next: NextFunction,
): void => {
const idempotencyKey = req.header("idempotency-key");
if (
!idempotencyKey ||
idempotencyKey.length < 1 ||
idempotencyKey.length > 200
) {
return next();
}
const cacheKey = `${req.method}:${req.path}:${idempotencyKey}`;
const bodyHash = createHash("sha256")
.update(JSON.stringify(req.body ?? null))
.digest("hex");
const existing = idempotencyCache.get(cacheKey);
if (existing) {
if (existing.expiresAt > Date.now()) {
if (existing.bodyHash !== bodyHash) {
sendError(
res,
req,
409,
"idempotency_conflict",
"Idempotency-Key reused with a different request body",
);
return;
}
// Replay cached response verbatim.
res.status(existing.status).json(existing.body);
return;
}
// Expired entry - remove it and fall through to execute the handler.
idempotencyCache.delete(cacheKey);
}
// Wrap res.json to capture the response before it is sent.
const originalJson = res.json.bind(res);
res.json = (body: unknown): Response => {
pruneIdempotencyCache();
idempotencyCache.set(cacheKey, {
status: res.statusCode,
body,
bodyHash,
expiresAt: Date.now() + getIdempotencyTtlMs(),
});
return originalJson(body);
};
next();
};
/**
* Strict body-key guard.
*
* Enforces that a JSON request body contains only keys from `allowed`. When the
* body carries any extra top-level key, a `400 invalid_request` is sent listing
* the offending keys (with the canonical `requestId`) and the function returns
* `true` so the caller can `return` immediately.
*
* An absent or non-object body is treated as having no keys to reject. Own
* enumerable keys are read via `Object.keys`, so inherited / prototype-pollution
* keys like `__proto__` (which arrive as own enumerable keys when present in the
* raw JSON) are surfaced as unknown rather than silently honoured.
*
* @param req - The incoming request (used for the body and request id).
* @param res - The response used to emit the canonical error.
* @param allowed - The exhaustive set of permitted top-level body keys.
* @returns `true` when an error was sent (unknown keys present), else `false`.
*/
const rejectUnknownKeys = (
req: Request,
res: Response,
allowed: string[],
): boolean => {
const body = req.body;
if (
body === undefined ||
body === null ||
typeof body !== "object" ||
Array.isArray(body)
) {
return false;
}
const allow = new Set(allowed);
const unknown = Object.keys(body).filter((k) => !allow.has(k));
if (unknown.length > 0) {
sendError(
res,
req,
400,
"invalid_request",
`unknown field(s): ${unknown.join(", ")}`,
{
unknownKeys: unknown,
},
);
return true;
}
return false;
};
/**
* Correlation middleware.
*
* Attaches a sanitized `X-Request-Id` to the request (`req.id`) and sets the `X-Request-Id` response header.
* If the client provides an `X-Request-Id` header:
* - It is echoed verbatim if it matches a strict pattern: 1-200 characters from `[A-Za-z0-9._-]`.
* - If it contains control characters, CRLF, spaces, or is over-length, it is silently replaced with a fresh UUID v4 to prevent header splitting and log injection.
* - If no header is provided, a fresh UUID v4 is generated.
*/
app.use((req: Request, res: Response, next: NextFunction) => {
const incoming = req.header("x-request-id");
const id =
incoming !== undefined && isValidRequestId(incoming)
? incoming
: randomUUID();
(req as RequestWithId).id = id;
res.setHeader("X-Request-Id", id);
next();
});
app.use(requestTimeoutGuard);
app.use(express.json({ limit: "100kb" }));
/**
* Content-Type guard for body-bearing HTTP methods.
*
* Mutating requests (`POST`, `PATCH`, `PUT`) that include a payload **must**
* declare `Content-Type: application/json` (the `charset` parameter is
* permitted, e.g. `application/json; charset=utf-8`). Any other media type —
* or an absent `Content-Type` — is rejected immediately with
* `415 unsupported_media_type` and the canonical `{ error, message, requestId }`
* body.
*
* @remarks
* **Placement rationale** — this middleware is registered *after*
* `express.json({ limit: "100kb" })` intentionally:
* 1. `express.json()` runs first. A request that declares
* `Content-Type: application/json` but exceeds the 100 kB limit is
* rejected by the body parser **before** this guard even fires, so a
* forged content-type cannot be used to smuggle an oversized body into
* a route handler.
* 2. `express.json()` only parses bodies whose declared type is JSON; it
* leaves `req.body` undefined for any other type. This guard then
* catches those cases and returns a human-readable 415 instead of
* allowing the missing `req.body` to fall through to handler-level
* validation and produce a confusing 400.
*
* **Skipped for safe methods and empty bodies** — `GET`, `HEAD`, `DELETE`,
* and `OPTIONS` are passed through unconditionally. For body-bearing methods,
* the check is skipped when both `Content-Length` is absent (or zero) *and*
* `Transfer-Encoding` is absent, because there is no payload to validate.
*
* @param req - Incoming Express request.
* @param res - Outgoing Express response.
* @param next - Express next-function; called when the request may proceed.
*/
export const requireJsonContentType = (
req: Request,
res: Response,
next: NextFunction,
): void => {
const method = req.method.toUpperCase();
if (
method === "GET" ||
method === "HEAD" ||
method === "DELETE" ||
method === "OPTIONS"
) {
next();
return;
}
const hasBody =
(req.headers["content-length"] !== undefined &&
req.headers["content-length"] !== "0") ||
req.headers["transfer-encoding"] !== undefined;
if (!hasBody) {
next();
return;
}
const contentType = (req.headers["content-type"] ?? "").toLowerCase();
if (contentType.includes("application/json")) {
next();
return;
}
sendError(
res,
req,
415,
"unsupported_media_type",
"Content-Type must be application/json",
);
};
app.use(requireJsonContentType);
// Pause guard: refuses non-idempotent methods with 503 except
// /admin/unpause, so an operator can always recover.
app.use((req: Request, res: Response, next: NextFunction) => {
if (!isPaused()) return next();
const m = req.method.toUpperCase();
if (m === "GET" || m === "HEAD" || m === "OPTIONS") return next();
if (req.path === "/api/v1/admin/unpause") return next();
sendError(res, req, 503, "service_paused", "StableRoute backend is paused");
});
/**
* Read-only maintenance guard.
*
* When `readOnly` is enabled (and the service is not paused — `paused` is
* strictly stronger and its guard runs first), this middleware keeps reads and
* quotes flowing while rejecting other mutating writes with
* `503 read_only_mode`.
*
* Allowed while read-only:
* - idempotent methods `GET` / `HEAD` / `OPTIONS`;
* - the quote endpoints (`/api/v1/quote`, `/api/v1/quote/reverse`,
* `/api/v1/quote/bulk`), including the POST bulk-quote;
* - `POST /api/v1/admin/read-write`, so an operator can always recover
* (mirroring the unpause carve-out).
*
* All other mutating requests receive the canonical `503 read_only_mode` body.
*/
const QUOTE_PATHS = new Set([
"/api/v1/quote",
"/api/v1/quote/reverse",
"/api/v1/quote/bulk",
]);
app.use((req: Request, res: Response, next: NextFunction) => {
if (!isReadOnly()) return next();
const m = req.method.toUpperCase();
if (m === "GET" || m === "HEAD" || m === "OPTIONS") return next();
if (QUOTE_PATHS.has(req.path)) return next();
// Recovery path must always be reachable, like /admin/unpause.
if (req.path === "/api/v1/admin/read-write") return next();
sendError(
res,
req,
503,
"read_only_mode",
"StableRoute backend is in read-only mode",
);
});
// Per-IP sliding-window rate limiter.
// Reads config.rateLimitPerWindow and config.rateLimitWindowMs at request time
// so PATCH /api/v1/config changes take effect immediately.
// Disabled in test mode so the test suite can make many requests without hitting the limit.
const RATE_LIMIT_WINDOW_MS = 60_000;
export type TrustProxySetting = boolean | number | string | string[];
/** Parse a trust proxy setting string from the environment. */
export const parseTrustProxy = (
value: string | undefined,
): TrustProxySetting => {
if (value === undefined || value.trim() === "") return false;
const normalized = value.trim().toLowerCase();
if (normalized === "true") return true;
if (normalized === "false") return false;
const numeric = Number(normalized);
if (Number.isInteger(numeric) && numeric >= 0) return numeric;
if (value.includes(",")) {
return value
.split(",")
.map((part) => part.trim())
.filter(Boolean);
}
return value.trim();
};
app.set("trust proxy", parseTrustProxy(process.env.TRUST_PROXY));
let lastRateBucketGcAt = 0;
const RATE_BUCKET_GC_INTERVAL_MS = 60_000;
/** Prune IP rate limit buckets that have not had any requests within the window. */
export const pruneExpiredRateBuckets = (
now: number,
windowMs: number,
): number => {
if (now - lastRateBucketGcAt < RATE_BUCKET_GC_INTERVAL_MS) return 0;
lastRateBucketGcAt = now;
let removed = 0;
for (const [ip, bucket] of rateBuckets) {
const live = bucket.filter((t) => now - t < windowMs);
if (live.length === 0) {
rateBuckets.delete(ip);
removed++;
} else if (live.length !== bucket.length) {
rateBuckets.set(ip, live);
}
}
return removed;
};
/**
* Evict stale timestamps from the rate-bucket for `ip` and return the live
* (within-window) entries.
*
* Side effects:
* - Removes the map entry for `ip` when all its timestamps are stale.
* - Enforces the IP-count ceiling: when the map holds
* {@link RATE_BUCKETS_MAX_IPS} entries and a new IP is admitted, the
* oldest entry is deleted first so cardinality never exceeds the cap.
*/
export const evictRateBuckets = (
ip: string,
now: number,
windowMs: number,
): number[] => {
// Enforce IP-count ceiling for new IPs.
if (!rateBuckets.has(ip) && rateBuckets.size >= RATE_BUCKETS_MAX_IPS) {
const oldestKey = rateBuckets.keys().next().value as string;
rateBuckets.delete(oldestKey);
}
const existing = rateBuckets.get(ip) ?? [];
const live = existing.filter((t) => now - t < windowMs);
// Delete empty buckets to keep memory bounded and avoid stale map entries.
if (existing.length > 0 && live.length === 0) {
rateBuckets.delete(ip);
}
return live;
};
app.use((req: Request, res: Response, next: NextFunction) => {
if (process.env.NODE_ENV === "test") return next();
const ip = resolveClientIp(
req.headers["x-forwarded-for"],
req.ip ?? req.socket.remoteAddress,
);
const now = Date.now();
const windowMs = config.rateLimitWindowMs ?? RATE_LIMIT_WINDOW_MS;
pruneExpiredRateBuckets(now, windowMs);
const limitPerWindow = config.rateLimitPerWindow ?? 60;
const bucket = evictRateBuckets(ip, now, windowMs);
if (bucket.length >= limitPerWindow) {
res.setHeader("Retry-After", String(Math.ceil(windowMs / 1000)));
sendError(
res,
req,
429,
"rate_limited",
`more than ${limitPerWindow} requests per ${windowMs / 1000}s`,
);
return;
}
bucket.push(now);
rateBuckets.set(ip, bucket);
next();
});
// Request timing — emits a single structured log per finished request
// and sets Server-Timing.
app.use((req: Request, res: Response, next: NextFunction) => {
const startNs = process.hrtime.bigint();
res.on("finish", () => {
const ms = Number(process.hrtime.bigint() - startNs) / 1_000_000;
logger
.child({
requestId: getRequestId(req),
method: req.method,
path: req.path,
})
.info(
{
status: res.statusCode,
durationMs: Math.round(ms * 10) / 10,
},
"request completed",
);
});
next();
});
app.use(
helmet({
// This API only returns JSON/text, so the tightest useful CSP is no ambient sources.
contentSecurityPolicy: {
useDefaults: false,
directives: {
"default-src": ["'none'"],
},
},
crossOriginEmbedderPolicy: { policy: "require-corp" },
crossOriginOpenerPolicy: { policy: "same-origin" },
crossOriginResourcePolicy: { policy: "same-origin" },
referrerPolicy: { policy: "no-referrer" },
strictTransportSecurity: {
maxAge: 31536000,
includeSubDomains: true,
},
xFrameOptions: { action: "deny" },
}),
);
/**