@daloyjs/core 1.0.0-rc.4 → 1.0.0-rc.5
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/README.md +14 -12
- package/dist/adapters/bun.d.ts +20 -2
- package/dist/adapters/bun.js +41 -5
- package/dist/adapters/deno.js +24 -7
- package/dist/adapters/lambda.d.ts +59 -2
- package/dist/adapters/lambda.js +136 -20
- package/dist/adapters/node.d.ts +8 -1
- package/dist/adapters/node.js +104 -19
- package/dist/app.d.ts +25 -3
- package/dist/app.js +113 -39
- package/dist/bot-guard.js +30 -3
- package/dist/client.d.ts +36 -7
- package/dist/client.js +7 -0
- package/dist/compression.d.ts +9 -0
- package/dist/compression.js +72 -1
- package/dist/conn-info.d.ts +5 -2
- package/dist/conn-info.js +5 -2
- package/dist/errors.d.ts +12 -3
- package/dist/errors.js +12 -3
- package/dist/fetch-guard.d.ts +27 -19
- package/dist/fetch-guard.js +50 -8
- package/dist/http-signatures.d.ts +4 -1
- package/dist/http-signatures.js +13 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/logger.d.ts +45 -0
- package/dist/logger.js +137 -0
- package/dist/mcp.js +10 -9
- package/dist/middleware.js +33 -3
- package/dist/mtls.js +6 -1
- package/dist/router.d.ts +2 -2
- package/dist/router.js +24 -9
- package/dist/safe-redirect.d.ts +5 -1
- package/dist/safe-redirect.js +25 -3
- package/dist/sbom.cdx.json +9 -9
- package/dist/sbom.spdx.json +5 -5
- package/dist/security.d.ts +41 -0
- package/dist/security.js +131 -15
- package/dist/session.d.ts +13 -2
- package/dist/session.js +111 -17
- package/dist/time-claims.js +3 -1
- package/dist/waf.js +86 -26
- package/package.json +5 -4
package/dist/client.d.ts
CHANGED
|
@@ -10,13 +10,15 @@
|
|
|
10
10
|
* can still be generated from the OpenAPI doc for non-TS clients).
|
|
11
11
|
*/
|
|
12
12
|
import type { App } from "./app.js";
|
|
13
|
-
import type { HandlerReturn, InferRequest, RequestSchemas, ResponsesMap, RouteDefinition } from "./types.js";
|
|
13
|
+
import type { HandlerReturn, InferRequest, ParamsOf, RequestSchemas, ResponsesMap, RouteDefinition } from "./types.js";
|
|
14
14
|
/** Union of every {@link RouteDefinition} registered on an `App`. */
|
|
15
15
|
export type RoutesOf<A extends App> = A["routes"][number];
|
|
16
16
|
/**
|
|
17
17
|
* Typed client surface generated from an `App`. The result is a record keyed
|
|
18
18
|
* by each route's `operationId` whose values are async methods inferred from
|
|
19
|
-
* the route's request and response schemas.
|
|
19
|
+
* the route's request and response schemas. Required query and header fields
|
|
20
|
+
* remain required on the client input, while schemas that accept an empty
|
|
21
|
+
* object keep their corresponding client field optional.
|
|
20
22
|
*
|
|
21
23
|
* The per-method types are recovered from the `App`'s accumulated route tuple,
|
|
22
24
|
* built by chained registrations or `app.registerRoutes([...])`. If the result
|
|
@@ -28,18 +30,38 @@ export type ClientFor<A extends App> = {
|
|
|
28
30
|
operationId: string;
|
|
29
31
|
}> as R["operationId"]]: ClientMethod<R>;
|
|
30
32
|
};
|
|
31
|
-
type ClientMethod<R> = R extends RouteDefinition<infer P, infer _M, infer Req, infer Res> ? (input: ClientInput<P, Req>) => Promise<ClientOutput<Res>> : never;
|
|
32
|
-
type ClientInput<P extends string, Req extends RequestSchemas | undefined> =
|
|
33
|
+
type ClientMethod<R> = R extends RouteDefinition<infer P, infer _M, infer Req, infer Res> ? {} extends ClientInput<P, Req> ? (input?: ClientInput<P, Req>) => Promise<ClientOutput<Res>> : (input: ClientInput<P, Req>) => Promise<ClientOutput<Res>> : never;
|
|
34
|
+
type ClientInput<P extends string, Req extends RequestSchemas | undefined> = ([
|
|
35
|
+
ParamsOf<P>
|
|
36
|
+
] extends [never] ? {
|
|
37
|
+
params?: Record<string, never>;
|
|
38
|
+
} : {
|
|
33
39
|
params: InferRequest<Req, P>["params"];
|
|
34
|
-
|
|
35
|
-
headers?: Record<string, string>;
|
|
36
|
-
} & (Req extends {
|
|
40
|
+
}) & ClientQueryInput<P, Req> & ClientHeadersInput<P, Req> & (Req extends {
|
|
37
41
|
body: infer _B;
|
|
38
42
|
} ? {
|
|
39
43
|
body: InferRequest<Req, P>["body"];
|
|
40
44
|
} : {
|
|
41
45
|
body?: undefined;
|
|
42
46
|
});
|
|
47
|
+
type ClientQueryInput<P extends string, Req extends RequestSchemas | undefined> = Req extends {
|
|
48
|
+
query: infer _Query;
|
|
49
|
+
} ? {} extends NonNullable<InferRequest<Req, P>["query"]> ? {
|
|
50
|
+
query?: NonNullable<InferRequest<Req, P>["query"]>;
|
|
51
|
+
} : {
|
|
52
|
+
query: NonNullable<InferRequest<Req, P>["query"]>;
|
|
53
|
+
} : {
|
|
54
|
+
query?: Record<string, string | string[] | number | boolean | undefined>;
|
|
55
|
+
};
|
|
56
|
+
type ClientHeadersInput<P extends string, Req extends RequestSchemas | undefined> = Req extends {
|
|
57
|
+
headers: infer _Headers;
|
|
58
|
+
} ? {} extends NonNullable<InferRequest<Req, P>["headers"]> ? {
|
|
59
|
+
headers?: NonNullable<InferRequest<Req, P>["headers"]>;
|
|
60
|
+
} : {
|
|
61
|
+
headers: NonNullable<InferRequest<Req, P>["headers"]>;
|
|
62
|
+
} : {
|
|
63
|
+
headers?: Record<string, string>;
|
|
64
|
+
};
|
|
43
65
|
type ClientOutput<Res extends ResponsesMap> = HandlerReturn<Res>;
|
|
44
66
|
/** Options for {@link createClient}. */
|
|
45
67
|
export interface ClientOptions {
|
|
@@ -62,6 +84,9 @@ export interface InProcessClientOptions {
|
|
|
62
84
|
* `operationId`. Parameters and response types are inferred from the same
|
|
63
85
|
* route definitions registered on `app`, so the client and server cannot
|
|
64
86
|
* drift apart at the type level.
|
|
87
|
+
* Required `params`, `query`, `headers`, and `body` inputs are preserved from
|
|
88
|
+
* the route contract; query or header schemas that accept an empty object keep
|
|
89
|
+
* those top-level fields optional.
|
|
65
90
|
*
|
|
66
91
|
* The returned object is a plain `Record<operationId, (input) => Promise<...>>`
|
|
67
92
|
* — each call serializes `params`/`query`/`headers`/`body` and dispatches
|
|
@@ -69,6 +94,8 @@ export interface InProcessClientOptions {
|
|
|
69
94
|
*
|
|
70
95
|
* For non-TypeScript consumers, run `pnpm gen` to emit a fully-typed SDK
|
|
71
96
|
* from the OpenAPI document instead.
|
|
97
|
+
* Routes without path parameters omit the `params` input, and routes with no
|
|
98
|
+
* required request inputs may be called without an argument.
|
|
72
99
|
*
|
|
73
100
|
* @remarks
|
|
74
101
|
* The method signatures are inferred from the `App`'s accumulated route tuple.
|
|
@@ -106,6 +133,8 @@ export declare function createClient<A extends App>(app: A, opts: ClientOptions)
|
|
|
106
133
|
*
|
|
107
134
|
* Requests still traverse the complete validation, middleware, security, and
|
|
108
135
|
* serialization pipeline through {@link "./app.js".App.fetch}.
|
|
136
|
+
* Routes without path parameters omit the `params` input, and routes with no
|
|
137
|
+
* required request inputs may be called without an argument.
|
|
109
138
|
*
|
|
110
139
|
* @param app - App whose registered route tuple drives the client surface.
|
|
111
140
|
* @param opts - Optional synthetic origin and default request headers.
|
package/dist/client.js
CHANGED
|
@@ -14,6 +14,9 @@
|
|
|
14
14
|
* `operationId`. Parameters and response types are inferred from the same
|
|
15
15
|
* route definitions registered on `app`, so the client and server cannot
|
|
16
16
|
* drift apart at the type level.
|
|
17
|
+
* Required `params`, `query`, `headers`, and `body` inputs are preserved from
|
|
18
|
+
* the route contract; query or header schemas that accept an empty object keep
|
|
19
|
+
* those top-level fields optional.
|
|
17
20
|
*
|
|
18
21
|
* The returned object is a plain `Record<operationId, (input) => Promise<...>>`
|
|
19
22
|
* — each call serializes `params`/`query`/`headers`/`body` and dispatches
|
|
@@ -21,6 +24,8 @@
|
|
|
21
24
|
*
|
|
22
25
|
* For non-TypeScript consumers, run `pnpm gen` to emit a fully-typed SDK
|
|
23
26
|
* from the OpenAPI document instead.
|
|
27
|
+
* Routes without path parameters omit the `params` input, and routes with no
|
|
28
|
+
* required request inputs may be called without an argument.
|
|
24
29
|
*
|
|
25
30
|
* @remarks
|
|
26
31
|
* The method signatures are inferred from the `App`'s accumulated route tuple.
|
|
@@ -98,6 +103,8 @@ export function createClient(app, opts) {
|
|
|
98
103
|
*
|
|
99
104
|
* Requests still traverse the complete validation, middleware, security, and
|
|
100
105
|
* serialization pipeline through {@link "./app.js".App.fetch}.
|
|
106
|
+
* Routes without path parameters omit the `params` input, and routes with no
|
|
107
|
+
* required request inputs may be called without an argument.
|
|
101
108
|
*
|
|
102
109
|
* @param app - App whose registered route tuple drives the client surface.
|
|
103
110
|
* @param opts - Optional synthetic origin and default request headers.
|
package/dist/compression.d.ts
CHANGED
|
@@ -38,6 +38,15 @@ export interface CompressionOptions {
|
|
|
38
38
|
* below `0` or above `2 ** 31 - 1` are refused at construction.
|
|
39
39
|
*/
|
|
40
40
|
minimumSize?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Maximum response body size (in bytes) the middleware will buffer for
|
|
43
|
+
* compression. Larger (or unknown-and-growing) bodies are left uncompressed
|
|
44
|
+
* so a large GET cannot force unbounded heap growth. Default: `1_048_576`
|
|
45
|
+
* (1 MiB). Must be a positive integer.
|
|
46
|
+
*
|
|
47
|
+
* @since 1.0.0
|
|
48
|
+
*/
|
|
49
|
+
maxCompressibleBytes?: number;
|
|
41
50
|
/**
|
|
42
51
|
* Allowed encodings, in caller-preferred order. Defaults to
|
|
43
52
|
* `["br", "gzip", "deflate"]` — the middleware will pick the
|
package/dist/compression.js
CHANGED
|
@@ -217,6 +217,57 @@ function normalizeOptionTokens(values, optionName) {
|
|
|
217
217
|
}
|
|
218
218
|
return Object.freeze(normalized);
|
|
219
219
|
}
|
|
220
|
+
/**
|
|
221
|
+
* Read a response body up to `maxBytes`. Returns `null` if the stream
|
|
222
|
+
* exceeds the cap (body is cancelled; caller should leave the response
|
|
223
|
+
* uncompressed). Returns an empty buffer when there is no body.
|
|
224
|
+
*
|
|
225
|
+
* @param res - Response whose body will be consumed (pass a clone).
|
|
226
|
+
* @param maxBytes - Inclusive upper bound on buffered size.
|
|
227
|
+
*/
|
|
228
|
+
async function readBodyUpTo(res, maxBytes) {
|
|
229
|
+
if (!res.body)
|
|
230
|
+
return new Uint8Array(0);
|
|
231
|
+
const reader = res.body.getReader();
|
|
232
|
+
const chunks = [];
|
|
233
|
+
let total = 0;
|
|
234
|
+
try {
|
|
235
|
+
// eslint-disable-next-line no-constant-condition
|
|
236
|
+
while (true) {
|
|
237
|
+
const { done, value } = await reader.read();
|
|
238
|
+
if (done)
|
|
239
|
+
break;
|
|
240
|
+
if (!value || value.byteLength === 0)
|
|
241
|
+
continue;
|
|
242
|
+
total += value.byteLength;
|
|
243
|
+
if (total > maxBytes) {
|
|
244
|
+
await reader.cancel();
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
chunks.push(value);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
try {
|
|
252
|
+
await reader.cancel();
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
/* ignore */
|
|
256
|
+
}
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
if (chunks.length === 0)
|
|
260
|
+
return new Uint8Array(0);
|
|
261
|
+
if (chunks.length === 1)
|
|
262
|
+
return chunks[0];
|
|
263
|
+
const out = new Uint8Array(total);
|
|
264
|
+
let offset = 0;
|
|
265
|
+
for (const c of chunks) {
|
|
266
|
+
out.set(c, offset);
|
|
267
|
+
offset += c.byteLength;
|
|
268
|
+
}
|
|
269
|
+
return out;
|
|
270
|
+
}
|
|
220
271
|
async function compressBytes(bytes, encoding) {
|
|
221
272
|
const Stream = globalThis.CompressionStream;
|
|
222
273
|
const cs = new Stream(encoding);
|
|
@@ -297,6 +348,16 @@ export function compression(opts = {}) {
|
|
|
297
348
|
minimumSize > 2 ** 31 - 1) {
|
|
298
349
|
throw new TypeError("compression(): `minimumSize` must be a finite non-negative integer.");
|
|
299
350
|
}
|
|
351
|
+
const maxCompressibleBytes = opts.maxCompressibleBytes === undefined ? 1_048_576 : opts.maxCompressibleBytes;
|
|
352
|
+
if (!Number.isFinite(maxCompressibleBytes) ||
|
|
353
|
+
!Number.isInteger(maxCompressibleBytes) ||
|
|
354
|
+
maxCompressibleBytes <= 0 ||
|
|
355
|
+
maxCompressibleBytes > 2 ** 31 - 1) {
|
|
356
|
+
throw new TypeError("compression(): `maxCompressibleBytes` must be a positive integer <= 2**31-1.");
|
|
357
|
+
}
|
|
358
|
+
if (minimumSize > maxCompressibleBytes) {
|
|
359
|
+
throw new TypeError("compression(): `minimumSize` must not exceed `maxCompressibleBytes`.");
|
|
360
|
+
}
|
|
300
361
|
const serverPreferred = opts.encodings && opts.encodings.length > 0
|
|
301
362
|
? Object.freeze([...opts.encodings])
|
|
302
363
|
: Object.freeze(["br", "gzip", "deflate"]);
|
|
@@ -338,7 +399,17 @@ export function compression(opts = {}) {
|
|
|
338
399
|
const chosen = pickEncoding(accept, serverPreferred, runtimeSupported);
|
|
339
400
|
if (!chosen)
|
|
340
401
|
return undefined;
|
|
341
|
-
|
|
402
|
+
// Fast-path skip when Content-Length already exceeds the compress cap
|
|
403
|
+
// (avoids buffering a known-huge body just to discard it).
|
|
404
|
+
const declaredLength = res.headers.get("content-length");
|
|
405
|
+
if (declaredLength !== null) {
|
|
406
|
+
const n = Number(declaredLength);
|
|
407
|
+
if (Number.isFinite(n) && n > maxCompressibleBytes)
|
|
408
|
+
return undefined;
|
|
409
|
+
}
|
|
410
|
+
const original = await readBodyUpTo(res.clone(), maxCompressibleBytes);
|
|
411
|
+
if (original === null)
|
|
412
|
+
return undefined; // exceeded cap while streaming
|
|
342
413
|
if (original.byteLength < minimumSize)
|
|
343
414
|
return undefined;
|
|
344
415
|
const compressed = await compressBytes(original, chosen);
|
package/dist/conn-info.d.ts
CHANGED
|
@@ -67,8 +67,11 @@ interface MutableConnInfo {
|
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
69
|
* @internal Adapter helper — attach {@link ConnInfo} to a `Request`. Called
|
|
70
|
-
* by the Node / Bun / Deno /
|
|
71
|
-
*
|
|
70
|
+
* by the Node / Bun / Deno / Lambda adapters before `app.fetch(request)`.
|
|
71
|
+
* The pure edge delegators (Cloudflare, Vercel, Fastly) expose no peer
|
|
72
|
+
* socket to attach — on those platforms the client address arrives via
|
|
73
|
+
* platform-set headers, which are governed by the `behindProxy` /
|
|
74
|
+
* `trustProxyHeaders` policies instead.
|
|
72
75
|
*
|
|
73
76
|
* @param request - Incoming request to tag (stored under a private symbol).
|
|
74
77
|
* @param info - Connection metadata gathered by the adapter.
|
package/dist/conn-info.js
CHANGED
|
@@ -21,8 +21,11 @@
|
|
|
21
21
|
const CONN_INFO_SYMBOL = Symbol.for("daloyjs.connInfo");
|
|
22
22
|
/**
|
|
23
23
|
* @internal Adapter helper — attach {@link ConnInfo} to a `Request`. Called
|
|
24
|
-
* by the Node / Bun / Deno /
|
|
25
|
-
*
|
|
24
|
+
* by the Node / Bun / Deno / Lambda adapters before `app.fetch(request)`.
|
|
25
|
+
* The pure edge delegators (Cloudflare, Vercel, Fastly) expose no peer
|
|
26
|
+
* socket to attach — on those platforms the client address arrives via
|
|
27
|
+
* platform-set headers, which are governed by the `behindProxy` /
|
|
28
|
+
* `trustProxyHeaders` policies instead.
|
|
26
29
|
*
|
|
27
30
|
* @param request - Incoming request to tag (stored under a private symbol).
|
|
28
31
|
* @param info - Connection metadata gathered by the adapter.
|
package/dist/errors.d.ts
CHANGED
|
@@ -364,9 +364,18 @@ export declare class TooManyRequestsError extends HttpError {
|
|
|
364
364
|
}
|
|
365
365
|
/**
|
|
366
366
|
* `408 Request Timeout` — thrown when a handler exceeds
|
|
367
|
-
* {@link AppOptions.requestTimeoutMs}.
|
|
368
|
-
*
|
|
369
|
-
* `ctx.request.signal`
|
|
367
|
+
* {@link AppOptions.requestTimeoutMs}.
|
|
368
|
+
*
|
|
369
|
+
* When the timeout fires the framework aborts `ctx.request.signal` (with a
|
|
370
|
+
* `TimeoutError` reason) so a handler that forwarded that signal to downstream
|
|
371
|
+
* I/O — `fetch`, a DB driver — sees those calls reject and can unwind. It does
|
|
372
|
+
* **not** forcibly terminate the handler: single-threaded JS cannot preempt
|
|
373
|
+
* running code, so CPU-bound or non-cooperative work continues in the
|
|
374
|
+
* background until it observes the aborted signal or finishes. Forward
|
|
375
|
+
* `ctx.request.signal` into every cancellable downstream call to get the
|
|
376
|
+
* benefit. (Signal firing is wired on the Node adapter and any runtime whose
|
|
377
|
+
* request shim honors the abort hook; direct `app.fetch()` callers still get
|
|
378
|
+
* the `408` but no signal abort.)
|
|
370
379
|
*
|
|
371
380
|
* @param ms - The configured timeout that was exceeded.
|
|
372
381
|
* @since 0.1.0
|
package/dist/errors.js
CHANGED
|
@@ -483,9 +483,18 @@ export class TooManyRequestsError extends HttpError {
|
|
|
483
483
|
}
|
|
484
484
|
/**
|
|
485
485
|
* `408 Request Timeout` — thrown when a handler exceeds
|
|
486
|
-
* {@link AppOptions.requestTimeoutMs}.
|
|
487
|
-
*
|
|
488
|
-
* `ctx.request.signal`
|
|
486
|
+
* {@link AppOptions.requestTimeoutMs}.
|
|
487
|
+
*
|
|
488
|
+
* When the timeout fires the framework aborts `ctx.request.signal` (with a
|
|
489
|
+
* `TimeoutError` reason) so a handler that forwarded that signal to downstream
|
|
490
|
+
* I/O — `fetch`, a DB driver — sees those calls reject and can unwind. It does
|
|
491
|
+
* **not** forcibly terminate the handler: single-threaded JS cannot preempt
|
|
492
|
+
* running code, so CPU-bound or non-cooperative work continues in the
|
|
493
|
+
* background until it observes the aborted signal or finishes. Forward
|
|
494
|
+
* `ctx.request.signal` into every cancellable downstream call to get the
|
|
495
|
+
* benefit. (Signal firing is wired on the Node adapter and any runtime whose
|
|
496
|
+
* request shim honors the abort hook; direct `app.fetch()` callers still get
|
|
497
|
+
* the `408` but no signal abort.)
|
|
489
498
|
*
|
|
490
499
|
* @param ms - The configured timeout that was exceeded.
|
|
491
500
|
* @since 0.1.0
|
package/dist/fetch-guard.d.ts
CHANGED
|
@@ -54,13 +54,14 @@
|
|
|
54
54
|
* a `127.0.0.1` / `169.254.169.254` at connect time, slipping past the
|
|
55
55
|
* library-level check. To close the window:
|
|
56
56
|
*
|
|
57
|
-
* 0. **Built-in, `http:` only** (
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
57
|
+
* 0. **Built-in, `http:` only** (default on Node):
|
|
58
|
+
* {@link FetchGuardOptions.pinDns} defaults to `true` on Node-like
|
|
59
|
+
* runtimes (and `false` elsewhere). On Node, `http:` requests are
|
|
60
|
+
* then dispatched through `node:http` with the socket pinned to the
|
|
61
|
+
* validated IP (and the original `Host` header preserved), so there
|
|
62
|
+
* is no connect-time re-resolution to rebind. Set `pinDns: false` to
|
|
63
|
+
* opt out. `https:` is not pinned by this knob — see its docs — so
|
|
64
|
+
* the items below still matter for TLS upstreams.
|
|
64
65
|
* 1. **Operator-side** (recommended): block egress to RFC1918 /
|
|
65
66
|
* loopback / link-local at the VPC / firewall layer. This neutralises
|
|
66
67
|
* the rebinding even if the application is naïve.
|
|
@@ -93,7 +94,7 @@
|
|
|
93
94
|
*
|
|
94
95
|
* @since 0.34.0
|
|
95
96
|
*/
|
|
96
|
-
export type SsrfBlockReason = "protocol-not-allowed" | "host-not-allowed" | "dns-resolution-failed" | "address-not-allowed" | "too-many-redirects" | "invalid-url";
|
|
97
|
+
export type SsrfBlockReason = "protocol-not-allowed" | "host-not-allowed" | "dns-resolution-failed" | "address-not-allowed" | "too-many-redirects" | "credentials-in-url" | "invalid-url";
|
|
97
98
|
/**
|
|
98
99
|
* Thrown by {@link fetchGuard} when an outbound request is refused. Never
|
|
99
100
|
* thrown for ordinary network failures — those bubble through unchanged
|
|
@@ -188,14 +189,20 @@ export interface FetchGuardOptions {
|
|
|
188
189
|
* by connecting the socket to the exact IP that was validated, instead of
|
|
189
190
|
* letting the underlying client re-resolve the hostname at connect time.
|
|
190
191
|
*
|
|
191
|
-
* When `true
|
|
192
|
-
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
192
|
+
* When `true`, a request to a hostname that resolves to a validated address
|
|
193
|
+
* is dispatched through Node's built-in `node:http` with the connection
|
|
194
|
+
* pinned to that address and the original `Host` header preserved — so
|
|
195
|
+
* virtual-host routing still works while an attacker's TTL=0 rebinding to
|
|
196
|
+
* `127.0.0.1` / `169.254.169.254` can no longer take effect between
|
|
197
|
+
* validation and connect.
|
|
197
198
|
*
|
|
198
|
-
* **
|
|
199
|
+
* **Default:** `true` on Node-like runtimes (`process.versions.node` is a
|
|
200
|
+
* non-empty string), `false` elsewhere (Workers / edge sandboxes without
|
|
201
|
+
* `node:http`). Pass `pinDns: false` to opt out on Node, or `pinDns: true`
|
|
202
|
+
* on a non-Node runtime only if you can tolerate the loud error when the
|
|
203
|
+
* pin path cannot load `node:http`.
|
|
204
|
+
*
|
|
205
|
+
* **Scope and caveats** (read before changing the default):
|
|
199
206
|
*
|
|
200
207
|
* - **`http:` only.** `https:` is intentionally NOT pinned here: pinning a
|
|
201
208
|
* TLS connection to an IP while keeping hostname-based SNI / certificate
|
|
@@ -204,16 +211,17 @@ export interface FetchGuardOptions {
|
|
|
204
211
|
* the documented TOCTOU caveat. The prime rebinding target — cloud
|
|
205
212
|
* metadata at `http://169.254.169.254` — is `http:`, so this still closes
|
|
206
213
|
* the highest-value vector.
|
|
207
|
-
* - **Node only.** It uses `node:http`;
|
|
208
|
-
*
|
|
209
|
-
* the misconfiguration is loud rather than a
|
|
214
|
+
* - **Node only for the pin path.** It uses `node:http`; when `pinDns` is
|
|
215
|
+
* explicitly `true` on a runtime without it, an `http:` pinned dispatch
|
|
216
|
+
* throws a clear error so the misconfiguration is loud rather than a
|
|
217
|
+
* silent no-op.
|
|
210
218
|
* - **Bypasses `options.fetch`** for the pinned `http:` path (it must own the
|
|
211
219
|
* socket), and negotiates no response compression (`Accept-Encoding:
|
|
212
220
|
* identity`) so body semantics match a plain `fetch`.
|
|
213
221
|
*
|
|
214
222
|
* Requests to a literal-IP host or an `allowHosts` entry are never pinned
|
|
215
223
|
* (the former already connects to an exact IP; the latter is an explicit
|
|
216
|
-
* operator trust).
|
|
224
|
+
* operator trust).
|
|
217
225
|
*
|
|
218
226
|
* @since 0.44.0
|
|
219
227
|
*/
|
package/dist/fetch-guard.js
CHANGED
|
@@ -54,13 +54,14 @@
|
|
|
54
54
|
* a `127.0.0.1` / `169.254.169.254` at connect time, slipping past the
|
|
55
55
|
* library-level check. To close the window:
|
|
56
56
|
*
|
|
57
|
-
* 0. **Built-in, `http:` only** (
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
57
|
+
* 0. **Built-in, `http:` only** (default on Node):
|
|
58
|
+
* {@link FetchGuardOptions.pinDns} defaults to `true` on Node-like
|
|
59
|
+
* runtimes (and `false` elsewhere). On Node, `http:` requests are
|
|
60
|
+
* then dispatched through `node:http` with the socket pinned to the
|
|
61
|
+
* validated IP (and the original `Host` header preserved), so there
|
|
62
|
+
* is no connect-time re-resolution to rebind. Set `pinDns: false` to
|
|
63
|
+
* opt out. `https:` is not pinned by this knob — see its docs — so
|
|
64
|
+
* the items below still matter for TLS upstreams.
|
|
64
65
|
* 1. **Operator-side** (recommended): block egress to RFC1918 /
|
|
65
66
|
* loopback / link-local at the VPC / firewall layer. This neutralises
|
|
66
67
|
* the rebinding even if the application is naïve.
|
|
@@ -112,6 +113,20 @@ export class SsrfBlockedError extends Error {
|
|
|
112
113
|
this.address = address;
|
|
113
114
|
}
|
|
114
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Whether this runtime looks like Node (or a Node-compatible host such as Bun)
|
|
118
|
+
* where `node:http` DNS pinning is available.
|
|
119
|
+
*
|
|
120
|
+
* Used as the default for {@link FetchGuardOptions.pinDns} so Node apps get
|
|
121
|
+
* rebinding defense without an opt-in, while Workers / pure edge runtimes keep
|
|
122
|
+
* the non-pinning path.
|
|
123
|
+
*/
|
|
124
|
+
function defaultPinDnsEnabled() {
|
|
125
|
+
return (typeof process !== "undefined" &&
|
|
126
|
+
process.versions != null &&
|
|
127
|
+
typeof process.versions.node === "string" &&
|
|
128
|
+
process.versions.node.length > 0);
|
|
129
|
+
}
|
|
115
130
|
// Always-on deny matchers. No option flips these.
|
|
116
131
|
const ALWAYS_DENY = [
|
|
117
132
|
"0.0.0.0/8", // "this network"
|
|
@@ -185,7 +200,11 @@ export function fetchGuard(options = {}) {
|
|
|
185
200
|
throw new Error("fetchGuard(): no global fetch available; pass options.fetch.");
|
|
186
201
|
}
|
|
187
202
|
const resolveFn = options.resolve ?? createDefaultResolver();
|
|
188
|
-
|
|
203
|
+
// Secure default on Node when using the built-in fetch: pin http: sockets
|
|
204
|
+
// to the validated IP. A custom `options.fetch` owns its own socket / DNS
|
|
205
|
+
// policy, so pinDns stays off unless the caller opts in. Non-Node runtimes
|
|
206
|
+
// default off (no node:http). Opt out on Node with `pinDns: false`.
|
|
207
|
+
const pinDns = options.pinDns ?? (options.fetch === undefined && defaultPinDnsEnabled());
|
|
189
208
|
for (const c of ALWAYS_DENY)
|
|
190
209
|
hardDenyMatchers.push(compileCidrMatcher(c));
|
|
191
210
|
for (const c of options.denyAddresses ?? [])
|
|
@@ -269,6 +288,29 @@ export function fetchGuard(options = {}) {
|
|
|
269
288
|
return addrs[0];
|
|
270
289
|
}
|
|
271
290
|
const guarded = async (input, init) => {
|
|
291
|
+
// A URL carrying userinfo (`http://user:pass@internal/`) is a classic SSRF
|
|
292
|
+
// obfuscation — the real host hides after the `@`. undici's `Request`
|
|
293
|
+
// constructor refuses such URLs with a raw `TypeError`, which would fire
|
|
294
|
+
// *before* our host validation and escape the `SsrfBlockedError` contract,
|
|
295
|
+
// so callers misclassify a blocked SSRF attempt as an ordinary upstream
|
|
296
|
+
// failure. Detect and refuse it ourselves with a typed error first. The
|
|
297
|
+
// credentials are stripped from the URL recorded on the error so a
|
|
298
|
+
// caller-supplied secret never leaks into logs. Malformed URLs fall
|
|
299
|
+
// through to the handling below, which raises `SsrfBlockedError("invalid-url")`.
|
|
300
|
+
if (typeof input === "string" || input instanceof URL) {
|
|
301
|
+
let pre;
|
|
302
|
+
try {
|
|
303
|
+
pre = new URL(input);
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
pre = undefined;
|
|
307
|
+
}
|
|
308
|
+
if (pre && (pre.username !== "" || pre.password !== "")) {
|
|
309
|
+
pre.username = "";
|
|
310
|
+
pre.password = "";
|
|
311
|
+
throw new SsrfBlockedError(pre.toString(), "credentials-in-url");
|
|
312
|
+
}
|
|
313
|
+
}
|
|
272
314
|
let request = new Request(input, init);
|
|
273
315
|
const userRedirect = (init?.redirect ?? request.redirect);
|
|
274
316
|
// Always dispatch underlying calls with redirect: "manual" so we can
|
|
@@ -229,7 +229,10 @@ export interface VerifyMessageOptions {
|
|
|
229
229
|
label?: string;
|
|
230
230
|
/**
|
|
231
231
|
* Component identifiers that MUST be covered. Defaults to
|
|
232
|
-
* `["@method", "@
|
|
232
|
+
* `["@method", "@target-uri"]` so the verifier binds scheme, authority,
|
|
233
|
+
* path, **and query** (matching {@link signMessage}'s default covered set).
|
|
234
|
+
* Prefer this over bare `@path`, which leaves query parameters unsigned.
|
|
235
|
+
* Pass `[]` to disable the check (not recommended).
|
|
233
236
|
*/
|
|
234
237
|
requiredComponents?: string[];
|
|
235
238
|
/** Require the `created` parameter. Defaults to `true`. */
|
package/dist/http-signatures.js
CHANGED
|
@@ -435,6 +435,15 @@ function resolveComponentValue(c, msg) {
|
|
|
435
435
|
if (values.length === 0) {
|
|
436
436
|
throw new ComponentError(`@query-param;name="${c.paramName}" is not present in the query`);
|
|
437
437
|
}
|
|
438
|
+
// Reject multi-value params: signing only the first value while an app
|
|
439
|
+
// or intermediary uses the last value (or the full array) is a classic
|
|
440
|
+
// HTTP parameter-pollution differential. Prefer `@query` / `@target-uri`
|
|
441
|
+
// when multiple values are legitimate.
|
|
442
|
+
if (values.length > 1) {
|
|
443
|
+
throw new ComponentError(`@query-param;name="${c.paramName}" appears ${values.length} times; ` +
|
|
444
|
+
"duplicate query parameters are not supported (parameter pollution risk). " +
|
|
445
|
+
"Cover `@query` or `@target-uri` instead, or send a single value.");
|
|
446
|
+
}
|
|
438
447
|
return values[0];
|
|
439
448
|
}
|
|
440
449
|
case "@status":
|
|
@@ -631,7 +640,10 @@ export async function verifyMessage(opts) {
|
|
|
631
640
|
...(params.tag !== undefined ? { tag: params.tag } : {}),
|
|
632
641
|
};
|
|
633
642
|
// Required components.
|
|
634
|
-
|
|
643
|
+
// Align with signMessage()'s default covered components so a default sign
|
|
644
|
+
// is accepted by a default verify, and so query/authority cannot be swapped
|
|
645
|
+
// out under a signature that only bound `@path`.
|
|
646
|
+
const requiredComponents = opts.requiredComponents ?? ["@method", "@target-uri"];
|
|
635
647
|
const coveredIds = input.components.map(serializeComponentId);
|
|
636
648
|
for (const req of requiredComponents) {
|
|
637
649
|
const wanted = serializeComponentId(parseComponentSpec(req));
|
package/dist/index.d.ts
CHANGED
|
@@ -74,7 +74,7 @@ export { defineConfig, ConfigValidationError } from "./config.js";
|
|
|
74
74
|
export type { ConfigSource, DefineConfigOptions } from "./config.js";
|
|
75
75
|
export type { RequestIdOptions, SecureHeadersOptions, CspDirectivesOptions, CorsOptions, CorsOriginAllow, RateLimitOptions, RateLimitContext, RateLimitStore, LoginThrottleOptions, CsrfOptions, CsrfCookieOptions, FetchMetadataOptions, BasicAuthOptions, } from "./middleware.js";
|
|
76
76
|
export type { BearerAuthOptions, BearerAuthVerifyHook } from "./middleware.js";
|
|
77
|
-
export { createLogger, noopLogger, DEFAULT_REDACT_KEYS } from "./logger.js";
|
|
77
|
+
export { createLogger, noopLogger, DEFAULT_REDACT_KEYS, SENSITIVE_URL_QUERY_KEYS, sanitizeUrlForLog, } from "./logger.js";
|
|
78
78
|
export type { Logger, LogLevel, ConsoleLoggerOptions, LoggerRedactionOptions } from "./logger.js";
|
|
79
79
|
export type { ScalarJsonPrimitive, ScalarJsonValue, ScalarReferenceConfiguration, ScalarTheme, RedocConfiguration, RedocHtmlOptions, SwaggerUiConfiguration, SwaggerUiHtmlOptions, AsyncApiHtmlOptions, DocsAssetOptions, DocsAuthLauncherOptions, } from "./docs.js";
|
|
80
80
|
export { formatStartupBanner, printStartupBanner } from "./banner.js";
|
package/dist/index.js
CHANGED
|
@@ -38,7 +38,7 @@ export { waf } from "./waf.js";
|
|
|
38
38
|
export { safeRedirect, OpenRedirectBlockedError } from "./safe-redirect.js";
|
|
39
39
|
export { loadShedding, LOAD_SHEDDING_MARKER } from "./load-shedding.js";
|
|
40
40
|
export { defineConfig, ConfigValidationError } from "./config.js";
|
|
41
|
-
export { createLogger, noopLogger, DEFAULT_REDACT_KEYS } from "./logger.js";
|
|
41
|
+
export { createLogger, noopLogger, DEFAULT_REDACT_KEYS, SENSITIVE_URL_QUERY_KEYS, sanitizeUrlForLog, } from "./logger.js";
|
|
42
42
|
export { formatStartupBanner, printStartupBanner } from "./banner.js";
|
|
43
43
|
export { sseStream, sseResponse, ndjsonStream, ndjsonResponse } from "./streaming.js";
|
|
44
44
|
export { httpBearerScheme, httpBasicScheme, apiKeyScheme, oauth2Scheme, openIdConnectScheme, REQUIRE_PAYLOAD_AUTH_EXTENSION, securitySchemeRequiresPayloadAuth, toOpenAPISecurityScheme, } from "./security-schemes.js";
|
package/dist/logger.d.ts
CHANGED
|
@@ -133,4 +133,49 @@ export declare function createLogger(opts?: ConsoleLoggerOptions): Logger;
|
|
|
133
133
|
* @since 0.1.0
|
|
134
134
|
*/
|
|
135
135
|
export declare const noopLogger: Logger;
|
|
136
|
+
/**
|
|
137
|
+
* Query parameter names whose values are redacted when a request URL is
|
|
138
|
+
* bound into a log record. Case-insensitive. Covers OAuth redirect params,
|
|
139
|
+
* API keys in query strings, signed-URL tokens, session identifiers, and the
|
|
140
|
+
* exact-named parameters of AWS SigV4 / GCS V4 presigned URLs (the `x-amz-*`
|
|
141
|
+
* and `x-goog-*` families are additionally matched by prefix — see
|
|
142
|
+
* {@link SENSITIVE_URL_QUERY_KEY_PREFIXES}).
|
|
143
|
+
*
|
|
144
|
+
* @since 1.0.0
|
|
145
|
+
*/
|
|
146
|
+
export declare const SENSITIVE_URL_QUERY_KEYS: readonly string[];
|
|
147
|
+
/**
|
|
148
|
+
* Case-insensitive query-key prefixes whose values are always redacted in a
|
|
149
|
+
* logged URL. Covers the full AWS SigV4 (`X-Amz-*`) and GCS V4 (`X-Goog-*`)
|
|
150
|
+
* presigned-URL parameter families so a signature never leaks even if a
|
|
151
|
+
* provider adds a new signed parameter name. Redacting the non-secret members
|
|
152
|
+
* of the bundle (`X-Amz-Date`, `X-Amz-Expires`, …) is harmless in a log line.
|
|
153
|
+
*
|
|
154
|
+
* @since 1.0.0
|
|
155
|
+
*/
|
|
156
|
+
export declare const SENSITIVE_URL_QUERY_KEY_PREFIXES: readonly string[];
|
|
157
|
+
/**
|
|
158
|
+
* Produce a log-safe form of a request URL.
|
|
159
|
+
*
|
|
160
|
+
* Keeps scheme, host, and path for operability. Redacts values of
|
|
161
|
+
* {@link SENSITIVE_URL_QUERY_KEYS} / {@link SENSITIVE_URL_QUERY_KEY_PREFIXES}
|
|
162
|
+
* (and JWT-like / credential-like query values) so OAuth `?code=`,
|
|
163
|
+
* `?access_token=`, and presigned-URL signatures (`?X-Amz-Signature=`,
|
|
164
|
+
* `?X-Goog-Signature=`) never land in durable error logs under the field name
|
|
165
|
+
* `url` (which the structured redactor does not rename-match).
|
|
166
|
+
*
|
|
167
|
+
* Malformed URLs fall back to the path-only prefix before `?` / `#`.
|
|
168
|
+
*
|
|
169
|
+
* This runs once per request on the logging path, so it fast-paths the common
|
|
170
|
+
* case: a URL with no query, no fragment, and no userinfo (`@`) delimiter is
|
|
171
|
+
* already log-safe and is returned verbatim without the WHATWG URL parse (about
|
|
172
|
+
* an order of magnitude cheaper). The `@` guard preserves userinfo stripping
|
|
173
|
+
* for the rare inputs that carry credentials in the authority — `request.url`
|
|
174
|
+
* itself never does, but this is a public utility.
|
|
175
|
+
*
|
|
176
|
+
* @param url - Absolute or relative request URL (typically `request.url`).
|
|
177
|
+
* @returns A string safe to attach as a logger binding.
|
|
178
|
+
* @since 1.0.0
|
|
179
|
+
*/
|
|
180
|
+
export declare function sanitizeUrlForLog(url: string): string;
|
|
136
181
|
export {};
|