@daloyjs/core 1.0.0-beta.6 → 1.0.0-beta.7

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.
Files changed (99) hide show
  1. package/README.md +2 -2
  2. package/dist/adapters/bun.d.ts +13 -1
  3. package/dist/adapters/bun.js +8 -1
  4. package/dist/adapters/cloudflare.d.ts +7 -1
  5. package/dist/adapters/cloudflare.js +6 -1
  6. package/dist/adapters/deno.d.ts +11 -1
  7. package/dist/adapters/deno.js +8 -1
  8. package/dist/adapters/fastly.d.ts +12 -2
  9. package/dist/adapters/fastly.js +12 -2
  10. package/dist/adapters/lambda.d.ts +37 -1
  11. package/dist/adapters/lambda.js +6 -1
  12. package/dist/adapters/node.d.ts +12 -1
  13. package/dist/adapters/node.js +7 -1
  14. package/dist/adapters/vercel.d.ts +13 -1
  15. package/dist/adapters/vercel.js +12 -1
  16. package/dist/app.d.ts +67 -17
  17. package/dist/app.js +97 -31
  18. package/dist/banner.d.ts +6 -0
  19. package/dist/banner.js +6 -0
  20. package/dist/cli.d.ts +35 -0
  21. package/dist/cli.js +23 -1
  22. package/dist/combine.d.ts +8 -0
  23. package/dist/combine.js +8 -0
  24. package/dist/compression.d.ts +3 -0
  25. package/dist/compression.js +3 -0
  26. package/dist/config.d.ts +4 -0
  27. package/dist/config.js +4 -0
  28. package/dist/conn-info.d.ts +35 -2
  29. package/dist/conn-info.js +35 -2
  30. package/dist/contract.d.ts +2 -0
  31. package/dist/contract.js +2 -0
  32. package/dist/cookie.d.ts +12 -0
  33. package/dist/cookie.js +12 -0
  34. package/dist/dependency.d.ts +4 -0
  35. package/dist/dependency.js +3 -0
  36. package/dist/discriminator.d.ts +13 -0
  37. package/dist/discriminator.js +23 -1
  38. package/dist/docs.d.ts +78 -0
  39. package/dist/docs.js +21 -0
  40. package/dist/errors.d.ts +16 -0
  41. package/dist/errors.js +14 -0
  42. package/dist/etag.d.ts +2 -0
  43. package/dist/etag.js +2 -0
  44. package/dist/fetch-guard.d.ts +7 -0
  45. package/dist/fetch-guard.js +7 -0
  46. package/dist/fetch-resilience.d.ts +4 -0
  47. package/dist/fetch-resilience.js +4 -0
  48. package/dist/http-signatures.d.ts +32 -0
  49. package/dist/http-signatures.js +30 -0
  50. package/dist/index.d.ts +1 -1
  51. package/dist/ip-restriction.d.ts +40 -3
  52. package/dist/ip-restriction.js +35 -3
  53. package/dist/jwk.d.ts +12 -1
  54. package/dist/jwk.js +6 -0
  55. package/dist/jwt.d.ts +14 -0
  56. package/dist/jwt.js +10 -0
  57. package/dist/load-shedding.d.ts +3 -0
  58. package/dist/load-shedding.js +3 -0
  59. package/dist/logger.d.ts +13 -0
  60. package/dist/logger.js +3 -0
  61. package/dist/mcp.d.ts +152 -10
  62. package/dist/mcp.js +223 -19
  63. package/dist/middleware.d.ts +68 -0
  64. package/dist/middleware.js +17 -0
  65. package/dist/mtls.d.ts +19 -2
  66. package/dist/mtls.js +12 -2
  67. package/dist/multipart.d.ts +42 -5
  68. package/dist/multipart.js +41 -5
  69. package/dist/openapi.d.ts +15 -9
  70. package/dist/openapi.js +6 -9
  71. package/dist/rate-limit-redis.d.ts +21 -2
  72. package/dist/rate-limit-redis.js +17 -2
  73. package/dist/safe-redirect.d.ts +6 -0
  74. package/dist/safe-redirect.js +6 -0
  75. package/dist/sbom.cdx.json +9 -9
  76. package/dist/sbom.spdx.json +5 -5
  77. package/dist/scheduler.d.ts +4 -0
  78. package/dist/schema.d.ts +25 -0
  79. package/dist/security-schemes.d.ts +50 -0
  80. package/dist/security-schemes.js +6 -0
  81. package/dist/security.d.ts +33 -0
  82. package/dist/security.js +28 -10
  83. package/dist/session.d.ts +34 -5
  84. package/dist/session.js +31 -5
  85. package/dist/streaming.d.ts +19 -0
  86. package/dist/streaming.js +16 -0
  87. package/dist/subdomains.d.ts +4 -0
  88. package/dist/subdomains.js +4 -0
  89. package/dist/time-claims.d.ts +22 -2
  90. package/dist/time-claims.js +6 -0
  91. package/dist/tracing.d.ts +12 -0
  92. package/dist/tracing.js +6 -0
  93. package/dist/types.d.ts +70 -1
  94. package/dist/waf.js +21 -1
  95. package/dist/webhook-delivery.d.ts +6 -0
  96. package/dist/webhook-delivery.js +5 -0
  97. package/dist/websocket.d.ts +137 -4
  98. package/dist/websocket.js +105 -4
  99. package/package.json +1 -1
package/dist/errors.js CHANGED
@@ -37,6 +37,7 @@ export const SAFE_CUSTOM_ERROR_RESPONSE_HEADERS = new Set([
37
37
  * @since 0.32.0
38
38
  */
39
39
  export class MessageLeakError extends Error {
40
+ /** The refused headers, each with its name and the reason it was disallowed. */
40
41
  offendingHeaders;
41
42
  constructor(offendingHeaders) {
42
43
  const summary = offendingHeaders
@@ -53,6 +54,10 @@ export class MessageLeakError extends Error {
53
54
  /**
54
55
  * @internal — header-safety check applied by {@link httpError} when a custom
55
56
  * `res` is supplied. Exported for audits and tests.
57
+ *
58
+ * @param headers Headers of the caller-supplied custom error `Response`.
59
+ * @returns The disallowed headers (name plus refusal reason); an empty array
60
+ * means every header passed the safe-error-response allowlist.
56
61
  */
57
62
  export function checkCustomErrorResponseHeaders(headers) {
58
63
  const offending = [];
@@ -111,6 +116,12 @@ function shouldCopyCustomErrorHeader(name, value) {
111
116
  * Build an {@link HttpError} with optional safe-header extraction from a
112
117
  * custom `Response`. See {@link HttpErrorOptions}.
113
118
  *
119
+ * @param opts Status, problem document, plain headers, and the optional
120
+ * custom `res` whose safe headers are merged (never overwriting
121
+ * caller-supplied headers; `Content-Length` is always dropped).
122
+ * @returns The constructed {@link HttpError}, ready to be thrown.
123
+ * @throws MessageLeakError in production under `secureDefaults` when the
124
+ * custom `res` carries headers outside the safe allowlist.
114
125
  * @since 0.32.0
115
126
  */
116
127
  export function httpError(opts) {
@@ -173,8 +184,11 @@ export function httpError(opts) {
173
184
  * @since 0.1.0
174
185
  */
175
186
  export class HttpError extends Error {
187
+ /** HTTP status code of the rendered response. */
176
188
  status;
189
+ /** RFC 9457 problem document; `type` defaults to `https://httpstatuses.io/<status>`. */
177
190
  problem;
191
+ /** Extra response headers (e.g. `Retry-After`, `Allow`) merged onto the response. */
178
192
  headers;
179
193
  constructor(status, problem, headers) {
180
194
  super(problem.title);
package/dist/etag.d.ts CHANGED
@@ -42,6 +42,8 @@ export interface ETagOptions {
42
42
  * app.use(etag());
43
43
  * ```
44
44
  *
45
+ * @param opts - `weak: true` emits `W/"..."` weak validators (default strong); `generator` replaces the default SHA-1 body digest.
46
+ * @returns A {@link Hooks} bundle (an `onSend` hook) to compose via `app.use()`.
45
47
  * @since 0.21.0
46
48
  */
47
49
  export declare function etag(opts?: ETagOptions): Hooks;
package/dist/etag.js CHANGED
@@ -71,6 +71,8 @@ function inmMatches(headerValue, candidate) {
71
71
  * app.use(etag());
72
72
  * ```
73
73
  *
74
+ * @param opts - `weak: true` emits `W/"..."` weak validators (default strong); `generator` replaces the default SHA-1 body digest.
75
+ * @returns A {@link Hooks} bundle (an `onSend` hook) to compose via `app.use()`.
74
76
  * @since 0.21.0
75
77
  */
76
78
  export function etag(opts = {}) {
@@ -102,8 +102,11 @@ export type SsrfBlockReason = "protocol-not-allowed" | "host-not-allowed" | "dns
102
102
  * @since 0.34.0
103
103
  */
104
104
  export declare class SsrfBlockedError extends Error {
105
+ /** The request URL (or redirect target) that was refused. */
105
106
  readonly url: string;
107
+ /** Machine-readable {@link SsrfBlockReason} explaining the refusal. */
106
108
  readonly reason: SsrfBlockReason;
109
+ /** The resolved IP that tripped the guard, when the block was address-based. */
107
110
  readonly address?: string;
108
111
  constructor(url: string, reason: SsrfBlockReason, address?: string);
109
112
  }
@@ -240,6 +243,10 @@ export interface FetchGuardOptions {
240
243
  * });
241
244
  * ```
242
245
  *
246
+ * @param options - Guard configuration; see {@link FetchGuardOptions}. Omit
247
+ * for the strict default posture (public IPs over `http:`/`https:` only).
248
+ * @returns A `fetch`-compatible function that validates every hop (including
249
+ * redirects) and throws {@link SsrfBlockedError} on refusal.
243
250
  * @since 0.34.0
244
251
  */
245
252
  export declare function fetchGuard(options?: FetchGuardOptions): typeof fetch;
@@ -96,8 +96,11 @@ import { compileCidrMatcher, matchesMatcher, parseIp } from "./ip-restriction.js
96
96
  * @since 0.34.0
97
97
  */
98
98
  export class SsrfBlockedError extends Error {
99
+ /** The request URL (or redirect target) that was refused. */
99
100
  url;
101
+ /** Machine-readable {@link SsrfBlockReason} explaining the refusal. */
100
102
  reason;
103
+ /** The resolved IP that tripped the guard, when the block was address-based. */
101
104
  address;
102
105
  constructor(url, reason, address) {
103
106
  const where = address ? ` -> ${address}` : "";
@@ -155,6 +158,10 @@ const UNIQUE_LOCAL = ["fc00::/7"];
155
158
  * });
156
159
  * ```
157
160
  *
161
+ * @param options - Guard configuration; see {@link FetchGuardOptions}. Omit
162
+ * for the strict default posture (public IPs over `http:`/`https:` only).
163
+ * @returns A `fetch`-compatible function that validates every hop (including
164
+ * redirects) and throws {@link SsrfBlockedError} on refusal.
158
165
  * @since 0.34.0
159
166
  */
160
167
  export function fetchGuard(options = {}) {
@@ -290,6 +290,10 @@ export interface ResilientFetchOptions {
290
290
  * const safeFetch = resilientFetch({ fetch: fetchGuard(), timeoutMs: 2_000 });
291
291
  * ```
292
292
  *
293
+ * @param options - Timeout (default 10000 ms), retry policy (default 2 retries, exponential backoff with jitter, `Retry-After` respected), circuit-breaker config (`false` disables), and the base `fetch`.
294
+ * @returns A drop-in `fetch` replacement applying the configured resilience layers.
295
+ * @throws {Error} When no global `fetch` exists and `options.fetch` is not provided.
296
+ * @throws {RangeError} When `timeoutMs` is negative/non-finite or `retries` is not a non-negative integer.
293
297
  * @since 0.37.0
294
298
  */
295
299
  export declare function resilientFetch(options?: ResilientFetchOptions): typeof fetch;
@@ -355,6 +355,10 @@ function isAbortError(err) {
355
355
  * const safeFetch = resilientFetch({ fetch: fetchGuard(), timeoutMs: 2_000 });
356
356
  * ```
357
357
  *
358
+ * @param options - Timeout (default 10000 ms), retry policy (default 2 retries, exponential backoff with jitter, `Retry-After` respected), circuit-breaker config (`false` disables), and the base `fetch`.
359
+ * @returns A drop-in `fetch` replacement applying the configured resilience layers.
360
+ * @throws {Error} When no global `fetch` exists and `options.fetch` is not provided.
361
+ * @throws {RangeError} When `timeoutMs` is negative/non-finite or `retries` is not a non-negative integer.
358
362
  * @since 0.37.0
359
363
  */
360
364
  export function resilientFetch(options = {}) {
@@ -129,6 +129,10 @@ export interface MessageSignature {
129
129
  * Compute HTTP Message Signature header values (RFC 9421) over the described
130
130
  * message.
131
131
  *
132
+ * @param opts - Message description, covered components, algorithm, and key;
133
+ * see {@link SignMessageOptions}.
134
+ * @returns The `Signature-Input` / `Signature` header values plus the exact
135
+ * signature base that was signed.
132
136
  * @throws {TypeError} for unsupported algorithms, weak HMAC keys, or
133
137
  * unserializable parameter values.
134
138
  * @throws {Error} when a covered component cannot be resolved (e.g. a covered
@@ -148,6 +152,11 @@ export type SignRequestOptions = Omit<SignMessageOptions, "method" | "url" | "he
148
152
  * `Signature` and `Signature-Input` headers attached. The original request is
149
153
  * not mutated.
150
154
  *
155
+ * @param request - The outbound request to sign; its method, URL, and headers
156
+ * form the signature base.
157
+ * @param opts - Signing options minus the per-message fields; see
158
+ * {@link SignRequestOptions}.
159
+ * @returns A new `Request` carrying the signature headers.
151
160
  * @since 0.37.0
152
161
  */
153
162
  export declare function signRequest(request: Request, opts: SignRequestOptions): Promise<Request>;
@@ -164,6 +173,7 @@ export interface KeyResolutionInfo {
164
173
  }
165
174
  /** Successful verification result. */
166
175
  export interface VerifySuccess {
176
+ /** Discriminant: always `true` on success. */
167
177
  valid: true;
168
178
  /** The verified signature label. */
169
179
  label: string;
@@ -184,6 +194,7 @@ export interface VerifySuccess {
184
194
  }
185
195
  /** Failed verification result. Never throws on a bad signature. */
186
196
  export interface VerifyFailure {
197
+ /** Discriminant: always `false` on failure. */
187
198
  valid: false;
188
199
  /** Stable machine-readable reason code. */
189
200
  reason: string;
@@ -242,6 +253,13 @@ export interface VerifyMessageOptions {
242
253
  * structured result and never throws on a bad/forged signature — only on a
243
254
  * programming error (e.g. WebCrypto unavailable).
244
255
  *
256
+ * @param opts - Received message plus verification policy (algorithm
257
+ * allowlist, key resolver, freshness / replay checks); see
258
+ * {@link VerifyMessageOptions}.
259
+ * @returns A {@link VerifySuccess} with the verified parameters, or a
260
+ * {@link VerifyFailure} with a stable `reason` code.
261
+ * @throws {TypeError} when the `algorithms` allowlist is missing or empty;
262
+ * there is no implicit "accept any" mode.
245
263
  * @since 0.37.0
246
264
  */
247
265
  export declare function verifyMessage(opts: VerifyMessageOptions): Promise<VerifyResult>;
@@ -250,6 +268,9 @@ export declare function verifyMessage(opts: VerifyMessageOptions): Promise<Verif
250
268
  * over {@link verifyMessage} that pulls the method, URL, and headers from the
251
269
  * request.
252
270
  *
271
+ * @param request - The inbound request carrying `Signature` / `Signature-Input`.
272
+ * @param opts - Verification policy minus the per-message fields.
273
+ * @returns The {@link VerifyResult}; never rejects on a bad signature.
253
274
  * @since 0.37.0
254
275
  */
255
276
  export declare function verifyRequest(request: Request, opts: Omit<VerifyMessageOptions, "method" | "url" | "headers" | "status">): Promise<VerifyResult>;
@@ -277,6 +298,9 @@ export interface HttpSignatureAuthOptions extends Omit<VerifyMessageOptions, "me
277
298
  * a missing (unless `optional`) or invalid signature it throws
278
299
  * {@link UnauthorizedError} (`401` + `Cache-Control: no-store`).
279
300
  *
301
+ * @param opts - Verification policy plus middleware knobs; see
302
+ * {@link HttpSignatureAuthOptions}.
303
+ * @returns A {@link Hooks} object to pass to `app.use()` or a route's `hooks`.
280
304
  * @since 0.37.0
281
305
  */
282
306
  export declare function httpSignatureAuth(opts: HttpSignatureAuthOptions): Hooks;
@@ -288,6 +312,10 @@ export type ContentDigestAlgorithm = "sha-256" | "sha-512";
288
312
  * bind the request body into the signature, then re-check it against the
289
313
  * received body with {@link verifyContentDigest}.
290
314
  *
315
+ * @param body - Raw body bytes, or a string encoded as UTF-8.
316
+ * @param opts - Optional `algorithm` choice. Defaults to `"sha-256"`.
317
+ * @returns The structured-field header value, e.g. `sha-256=:<base64>:`.
318
+ * @throws {TypeError} for an unsupported digest algorithm.
291
319
  * @since 0.37.0
292
320
  */
293
321
  export declare function contentDigest(body: Uint8Array | string, opts?: {
@@ -298,6 +326,10 @@ export declare function contentDigest(body: Uint8Array | string, opts?: {
298
326
  * Returns `false` for any malformed header or mismatch (never throws on bad
299
327
  * input). Only `sha-256` / `sha-512` members are considered.
300
328
  *
329
+ * @param header - The received `Content-Digest` header value.
330
+ * @param body - Raw body bytes, or a string encoded as UTF-8.
331
+ * @returns `true` only when at least one supported digest member matched
332
+ * (compared in constant time); `false` for mismatch or malformed input.
301
333
  * @since 0.37.0
302
334
  */
303
335
  export declare function verifyContentDigest(header: string, body: Uint8Array | string): Promise<boolean>;
@@ -471,6 +471,10 @@ function parseComponentSpec(spec) {
471
471
  * Compute HTTP Message Signature header values (RFC 9421) over the described
472
472
  * message.
473
473
  *
474
+ * @param opts - Message description, covered components, algorithm, and key;
475
+ * see {@link SignMessageOptions}.
476
+ * @returns The `Signature-Input` / `Signature` header values plus the exact
477
+ * signature base that was signed.
474
478
  * @throws {TypeError} for unsupported algorithms, weak HMAC keys, or
475
479
  * unserializable parameter values.
476
480
  * @throws {Error} when a covered component cannot be resolved (e.g. a covered
@@ -513,6 +517,11 @@ export async function signMessage(opts) {
513
517
  * `Signature` and `Signature-Input` headers attached. The original request is
514
518
  * not mutated.
515
519
  *
520
+ * @param request - The outbound request to sign; its method, URL, and headers
521
+ * form the signature base.
522
+ * @param opts - Signing options minus the per-message fields; see
523
+ * {@link SignRequestOptions}.
524
+ * @returns A new `Request` carrying the signature headers.
516
525
  * @since 0.37.0
517
526
  */
518
527
  export async function signRequest(request, opts) {
@@ -535,6 +544,13 @@ function fail(reason) {
535
544
  * structured result and never throws on a bad/forged signature — only on a
536
545
  * programming error (e.g. WebCrypto unavailable).
537
546
  *
547
+ * @param opts - Received message plus verification policy (algorithm
548
+ * allowlist, key resolver, freshness / replay checks); see
549
+ * {@link VerifyMessageOptions}.
550
+ * @returns A {@link VerifySuccess} with the verified parameters, or a
551
+ * {@link VerifyFailure} with a stable `reason` code.
552
+ * @throws {TypeError} when the `algorithms` allowlist is missing or empty;
553
+ * there is no implicit "accept any" mode.
538
554
  * @since 0.37.0
539
555
  */
540
556
  export async function verifyMessage(opts) {
@@ -688,6 +704,9 @@ export async function verifyMessage(opts) {
688
704
  * over {@link verifyMessage} that pulls the method, URL, and headers from the
689
705
  * request.
690
706
  *
707
+ * @param request - The inbound request carrying `Signature` / `Signature-Input`.
708
+ * @param opts - Verification policy minus the per-message fields.
709
+ * @returns The {@link VerifyResult}; never rejects on a bad signature.
691
710
  * @since 0.37.0
692
711
  */
693
712
  export function verifyRequest(request, opts) {
@@ -704,6 +723,9 @@ export function verifyRequest(request, opts) {
704
723
  * a missing (unless `optional`) or invalid signature it throws
705
724
  * {@link UnauthorizedError} (`401` + `Cache-Control: no-store`).
706
725
  *
726
+ * @param opts - Verification policy plus middleware knobs; see
727
+ * {@link HttpSignatureAuthOptions}.
728
+ * @returns A {@link Hooks} object to pass to `app.use()` or a route's `hooks`.
707
729
  * @since 0.37.0
708
730
  */
709
731
  export function httpSignatureAuth(opts) {
@@ -736,6 +758,10 @@ function toBytes(body) {
736
758
  * bind the request body into the signature, then re-check it against the
737
759
  * received body with {@link verifyContentDigest}.
738
760
  *
761
+ * @param body - Raw body bytes, or a string encoded as UTF-8.
762
+ * @param opts - Optional `algorithm` choice. Defaults to `"sha-256"`.
763
+ * @returns The structured-field header value, e.g. `sha-256=:<base64>:`.
764
+ * @throws {TypeError} for an unsupported digest algorithm.
739
765
  * @since 0.37.0
740
766
  */
741
767
  export async function contentDigest(body, opts = {}) {
@@ -752,6 +778,10 @@ export async function contentDigest(body, opts = {}) {
752
778
  * Returns `false` for any malformed header or mismatch (never throws on bad
753
779
  * input). Only `sha-256` / `sha-512` members are considered.
754
780
  *
781
+ * @param header - The received `Content-Digest` header value.
782
+ * @param body - Raw body bytes, or a string encoded as UTF-8.
783
+ * @returns `true` only when at least one supported digest member matched
784
+ * (compared in constant time); `false` for mismatch or malformed input.
755
785
  * @since 0.37.0
756
786
  */
757
787
  export async function verifyContentDigest(header, body) {
package/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ export { validate, isStandardSchema } from "./schema.js";
20
20
  export { diffOpenAPI, hasBreakingChanges } from "./openapi-diff.js";
21
21
  export type { ChangeSeverity, OpenAPIChange, OpenAPIDiffResult } from "./openapi-diff.js";
22
22
  export { MCP_DEFAULT_MAX_BODY_BYTES, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSIONS, McpToolError, createMcpHandler, mcpRoutes, } from "./mcp.js";
23
- export type { McpContent, McpEmbeddedResourceContent, McpHandler, McpHandlerOptions, McpImageContent, McpJsonObject, McpJsonRpcId, McpJsonSchema, McpJsonValue, McpPrompt, McpPromptArgument, McpPromptDefinition, McpPromptMessage, McpPromptResult, McpRequestContext, McpResource, McpResourceContents, McpResourceDefinition, McpServerInfo, McpTextContent, McpTool, McpToolHandler, McpToolResult, } from "./mcp.js";
23
+ export type { McpContent, McpEmbeddedResourceContent, McpHandler, McpHandlerOptions, McpIcon, McpImageContent, McpJsonObject, McpJsonRpcId, McpJsonSchema, McpJsonValue, McpPrompt, McpPromptArgument, McpPromptDefinition, McpPromptMessage, McpPromptResult, McpRequestContext, McpResource, McpResourceContents, McpResourceDefinition, McpResourceTemplate, McpResourceTemplateDefinition, McpServerInfo, McpTextContent, McpTool, McpToolAnnotations, McpToolHandler, McpToolResult, } from "./mcp.js";
24
24
  export { readBodyLimited, safeJsonParse, isForbiddenObjectKey, sanitizeHeaderName, sanitizeHeaderValue, timingSafeEqual, randomId, assertNoDuplicateSingletonHeaders, assertNoReservedInternalHeaders, assertHeaderCountWithinLimit, DEFAULT_MAX_HEADER_COUNT, RESERVED_INBOUND_HEADER_PREFIXES, SMUGGLING_SINGLETON_HEADERS, verifyWebhookSignature, signWebhookPayload, WEBHOOK_DEFAULT_TOLERANCE_SECONDS, assertStrongSecret, MIN_PROD_SECRET_BYTES, WEAK_SECRET_STRINGS, sanitizeFilename, assertSafeRelativePath, hasMongoOperatorKeys, assertNoMongoOperators, } from "./security.js";
25
25
  export type { WebhookHmacAlgorithm } from "./security.js";
26
26
  export { requestId, secureHeaders, SECURE_HEADERS_MARKER, cors, CORS_HOOK_MARKER, CORS_ORIGIN_ALLOW_MARKER, CORS_WILDCARD_ORIGIN_MARKER, rateLimit, loginThrottle, timing, bearerAuth, basicAuth, csrf, CSRF_HOOK_MARKER, fetchMetadata, requireScopes, REQUIRE_SCOPES_AGGREGATE_KEY, REQUIRE_SCOPES_HOOK_MARKER, _resetSharedRateLimitStoresForTests, } from "./middleware.js";
@@ -53,13 +53,18 @@ export interface IpRestrictionOptions {
53
53
  }
54
54
  /** @internal Parsed IP address (shared with `fetchGuard()`). */
55
55
  export interface ParsedIp {
56
+ /** Big-endian address bytes: 4 bytes for IPv4, 16 for IPv6. */
56
57
  bytes: Uint8Array;
58
+ /** Address family: `4` for IPv4, `6` for IPv6. */
57
59
  family: 4 | 6;
58
60
  }
59
61
  /** @internal Compiled CIDR matcher (shared with `fetchGuard()`). */
60
62
  export interface IpMatcher {
63
+ /** Address family the matcher applies to: `4` or `6`. */
61
64
  family: 4 | 6;
65
+ /** CIDR prefix length in bits (0-32 for IPv4, 0-128 for IPv6). */
62
66
  prefix: number;
67
+ /** Network address bytes with all host bits masked to zero. */
63
68
  bytes: Uint8Array;
64
69
  }
65
70
  /**
@@ -80,12 +85,44 @@ export interface IpMatcher {
80
85
  * On reject the middleware throws a {@link ForbiddenError}, which Daloy
81
86
  * renders as RFC 9457 `application/problem+json`.
82
87
  *
88
+ * @param opts Allow/deny lists plus IP-resolution options; see
89
+ * {@link IpRestrictionOptions}. Deny matches always win over allow.
90
+ * @returns A {@link Hooks} object whose `beforeHandle` enforces the lists,
91
+ * failing closed (403) when the client IP cannot be resolved or parsed.
92
+ * @throws Error at setup time when neither `allow` nor `deny` is provided,
93
+ * or when a pattern is not a valid IP/CIDR.
83
94
  * @since 0.19.0
84
95
  */
85
96
  export declare function ipRestriction(opts: IpRestrictionOptions): Hooks;
86
- /** @internal */
97
+ /**
98
+ * Test whether a parsed IP falls inside a compiled CIDR matcher, comparing
99
+ * only the matcher's prefix bits. IPv4-mapped IPv6 addresses
100
+ * (`::ffff:a.b.c.d`) are normalized so they match IPv4 matchers.
101
+ *
102
+ * @param ip Parsed client address from {@link parseIp}.
103
+ * @param m Compiled matcher from {@link compileCidrMatcher}.
104
+ * @returns `true` when the address is within the matcher's range.
105
+ * @internal
106
+ */
87
107
  export declare function matchesMatcher(ip: ParsedIp, m: IpMatcher): boolean;
88
- /** @internal */
108
+ /**
109
+ * Compile an IP or CIDR pattern (e.g. `"10.0.0.0/8"`, `"::1"`) into an
110
+ * {@link IpMatcher}. A bare address gets a full-length prefix (/32 or /128);
111
+ * host bits beyond the prefix are masked to zero.
112
+ *
113
+ * @param input IPv4/IPv6 address, optionally with a `/prefix` suffix.
114
+ * @returns The compiled matcher used by {@link matchesMatcher}.
115
+ * @throws Error when the address or CIDR prefix is invalid.
116
+ * @internal
117
+ */
89
118
  export declare function compileCidrMatcher(input: string): IpMatcher;
90
- /** @internal */
119
+ /**
120
+ * Parse an IPv4 or IPv6 address string into raw bytes. Supports IPv6 `::`
121
+ * compression and IPv4-mapped tails (`::ffff:1.2.3.4`).
122
+ *
123
+ * @param input Address string; surrounding whitespace is trimmed.
124
+ * @returns The parsed address, or `undefined` when the input is not a valid
125
+ * IP (callers treat unparseable addresses as a rejection, failing closed).
126
+ * @internal
127
+ */
91
128
  export declare function parseIp(input: string): ParsedIp | undefined;
@@ -26,6 +26,12 @@ import { ForbiddenError } from "./errors.js";
26
26
  * On reject the middleware throws a {@link ForbiddenError}, which Daloy
27
27
  * renders as RFC 9457 `application/problem+json`.
28
28
  *
29
+ * @param opts Allow/deny lists plus IP-resolution options; see
30
+ * {@link IpRestrictionOptions}. Deny matches always win over allow.
31
+ * @returns A {@link Hooks} object whose `beforeHandle` enforces the lists,
32
+ * failing closed (403) when the client IP cannot be resolved or parsed.
33
+ * @throws Error at setup time when neither `allow` nor `deny` is provided,
34
+ * or when a pattern is not a valid IP/CIDR.
29
35
  * @since 0.19.0
30
36
  */
31
37
  export function ipRestriction(opts) {
@@ -64,7 +70,16 @@ function forwardedIpResolver(ctx) {
64
70
  return forwarded.split(",")[0]?.trim();
65
71
  return headers.get("x-real-ip") ?? undefined;
66
72
  }
67
- /** @internal */
73
+ /**
74
+ * Test whether a parsed IP falls inside a compiled CIDR matcher, comparing
75
+ * only the matcher's prefix bits. IPv4-mapped IPv6 addresses
76
+ * (`::ffff:a.b.c.d`) are normalized so they match IPv4 matchers.
77
+ *
78
+ * @param ip Parsed client address from {@link parseIp}.
79
+ * @param m Compiled matcher from {@link compileCidrMatcher}.
80
+ * @returns `true` when the address is within the matcher's range.
81
+ * @internal
82
+ */
68
83
  export function matchesMatcher(ip, m) {
69
84
  const candidate = normalizeFamily(ip, m.family);
70
85
  if (!candidate)
@@ -83,7 +98,16 @@ export function matchesMatcher(ip, m) {
83
98
  const mask = 0xff << (8 - remaining);
84
99
  return ((candidate[fullBytes] ^ expected[fullBytes]) & mask) === 0;
85
100
  }
86
- /** @internal */
101
+ /**
102
+ * Compile an IP or CIDR pattern (e.g. `"10.0.0.0/8"`, `"::1"`) into an
103
+ * {@link IpMatcher}. A bare address gets a full-length prefix (/32 or /128);
104
+ * host bits beyond the prefix are masked to zero.
105
+ *
106
+ * @param input IPv4/IPv6 address, optionally with a `/prefix` suffix.
107
+ * @returns The compiled matcher used by {@link matchesMatcher}.
108
+ * @throws Error when the address or CIDR prefix is invalid.
109
+ * @internal
110
+ */
87
111
  export function compileCidrMatcher(input) {
88
112
  let addr = input;
89
113
  let prefixStr;
@@ -135,7 +159,15 @@ function applyPrefixMask(bytes, prefix) {
135
159
  }
136
160
  return out;
137
161
  }
138
- /** @internal */
162
+ /**
163
+ * Parse an IPv4 or IPv6 address string into raw bytes. Supports IPv6 `::`
164
+ * compression and IPv4-mapped tails (`::ffff:1.2.3.4`).
165
+ *
166
+ * @param input Address string; surrounding whitespace is trimmed.
167
+ * @returns The parsed address, or `undefined` when the input is not a valid
168
+ * IP (callers treat unparseable addresses as a rejection, failing closed).
169
+ * @internal
170
+ */
139
171
  export function parseIp(input) {
140
172
  const trimmed = input.trim();
141
173
  if (trimmed.includes(":"))
package/dist/jwk.d.ts CHANGED
@@ -4,6 +4,7 @@ import type { BaseContext, Hooks } from "./types.js";
4
4
  export type JwkAlgorithm = Exclude<JwtAlgorithm, "HS256" | "HS384" | "HS512">;
5
5
  /** Minimal JWKS document shape (RFC 7517 §5). */
6
6
  export interface JwkSet {
7
+ /** Public JWKs; each entry should carry a `kid` so tokens can select their key. */
7
8
  keys: JsonWebKey[];
8
9
  }
9
10
  /**
@@ -13,7 +14,11 @@ export interface JwkSet {
13
14
  export type JwkSource = JwkSet | string | (() => JwkSet | Promise<JwkSet>);
14
15
  /** Per-request payload-revalidation hook. */
15
16
  export type JwkVerifyHook = (payload: Record<string, unknown>, ctx: BaseContext<any, any>) => boolean | void | Promise<boolean | void>;
16
- /** Options for {@link jwk}. */
17
+ /**
18
+ * Options for {@link jwk}: the JWKS source and asymmetric algorithm allowlist
19
+ * are required; issuer / audience / clock-skew checks, JWKS fetch caching,
20
+ * and a per-request revalidation hook are opt-in.
21
+ */
17
22
  export interface JwkOptions {
18
23
  /** JWKS source (object, URL, or resolver). */
19
24
  jwks: JwkSource;
@@ -91,6 +96,12 @@ export interface JwkOptions {
91
96
  * });
92
97
  * ```
93
98
  *
99
+ * @param opts - JWKS source, algorithm allowlist, and claim checks; see
100
+ * {@link JwkOptions}.
101
+ * @returns A {@link Hooks} object to pass to `app.use()` or a route's `hooks`;
102
+ * failed auth yields a `401` problem+json with `WWW-Authenticate`.
103
+ * @throws {Error} at construction for missing options, an empty or
104
+ * symmetric-containing allowlist, invalid TTLs, or a malformed realm.
94
105
  * @since 0.22.0
95
106
  */
96
107
  export declare function jwk(opts: JwkOptions): Hooks;
package/dist/jwk.js CHANGED
@@ -161,6 +161,12 @@ function makeJwksLoader(source, fetchImpl, ttlSeconds, maxStaleSeconds) {
161
161
  * });
162
162
  * ```
163
163
  *
164
+ * @param opts - JWKS source, algorithm allowlist, and claim checks; see
165
+ * {@link JwkOptions}.
166
+ * @returns A {@link Hooks} object to pass to `app.use()` or a route's `hooks`;
167
+ * failed auth yields a `401` problem+json with `WWW-Authenticate`.
168
+ * @throws {Error} at construction for missing options, an empty or
169
+ * symmetric-containing allowlist, invalid TTLs, or a malformed realm.
164
170
  * @since 0.22.0
165
171
  */
166
172
  export function jwk(opts) {
package/dist/jwt.d.ts CHANGED
@@ -23,19 +23,24 @@ export type JwtAlgorithm = "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS
23
23
  export declare const DEFAULT_JWT_MAX_LIFETIME_SECONDS: number;
24
24
  /** Structured error thrown by every JWT helper. */
25
25
  export declare class JwtError extends Error {
26
+ /** Stable machine-readable error code (e.g. `"alg_none_refused"`, `"weak_hs_secret"`). */
26
27
  readonly code: string;
27
28
  constructor(code: string, message: string);
28
29
  }
29
30
  /** Result of a successful verify. */
30
31
  export interface JwtVerified {
32
+ /** Decoded JOSE header (`alg`, `kid`, `typ`, ...). */
31
33
  readonly header: Record<string, unknown>;
34
+ /** Decoded claims payload after signature and time-claim checks passed. */
32
35
  readonly payload: Record<string, unknown>;
33
36
  }
34
37
  /** Key material accepted by the signer/verifier. */
35
38
  export type JwtKeyMaterial = CryptoKey | Uint8Array | JsonWebKey;
36
39
  /** Options for {@link createJwtSigner}. */
37
40
  export interface JwtSignerOptions {
41
+ /** Signing algorithm. `"none"` is always refused. */
38
42
  alg: JwtAlgorithm;
43
+ /** Signing key. HS* secrets shorter than 32 bytes and RSA keys under 2048 bits are refused. */
39
44
  key: JwtKeyMaterial;
40
45
  /**
41
46
  * Maximum allowed `exp - iat` window in seconds. Required: refuse-at-
@@ -98,6 +103,10 @@ export interface JwtVerifierOptions {
98
103
  * `acknowledgeNoExp: true` was set at construction outside production) and
99
104
  * refuses payloads whose `exp - (iat | now)` exceeds `maxLifetimeSeconds`.
100
105
  *
106
+ * @param opts - Algorithm, key, and lifetime policy; see {@link JwtSignerOptions}.
107
+ * @returns An object whose `sign(payload)` resolves to the compact JWS string.
108
+ * @throws {JwtError} for `alg: "none"`, unknown algorithms, weak keys, a
109
+ * missing/invalid `maxLifetimeSeconds`, or `acknowledgeNoExp` in production.
101
110
  * @since 0.21.0
102
111
  */
103
112
  export declare function createJwtSigner(opts: JwtSignerOptions): {
@@ -110,6 +119,11 @@ export declare function createJwtSigner(opts: JwtSignerOptions): {
110
119
  * refuses-at-construction when a symmetric algorithm (`HS*`) is mixed with
111
120
  * a JWK / JWKS-shaped key source (the documented confused-deputy attack).
112
121
  *
122
+ * @param opts - Allowlist, key source, and claim checks; see {@link JwtVerifierOptions}.
123
+ * @returns An object whose `verify(token)` resolves to the decoded
124
+ * {@link JwtVerified} or rejects with {@link JwtError}.
125
+ * @throws {JwtError} at construction for an empty/invalid allowlist, `"none"`
126
+ * in the allowlist, weak HS* secrets, or HS* mixed with a JWK source.
113
127
  * @since 0.21.0
114
128
  */
115
129
  export declare function createJwtVerifier(opts: JwtVerifierOptions): {
package/dist/jwt.js CHANGED
@@ -60,6 +60,7 @@ const MIN_RSA_KEY_BITS = 2048;
60
60
  export const DEFAULT_JWT_MAX_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
61
61
  /** Structured error thrown by every JWT helper. */
62
62
  export class JwtError extends Error {
63
+ /** Stable machine-readable error code (e.g. `"alg_none_refused"`, `"weak_hs_secret"`). */
63
64
  code;
64
65
  constructor(code, message) {
65
66
  super(`[${code}] ${message}`);
@@ -228,6 +229,10 @@ function buildSignAlgorithm(alg) {
228
229
  * `acknowledgeNoExp: true` was set at construction outside production) and
229
230
  * refuses payloads whose `exp - (iat | now)` exceeds `maxLifetimeSeconds`.
230
231
  *
232
+ * @param opts - Algorithm, key, and lifetime policy; see {@link JwtSignerOptions}.
233
+ * @returns An object whose `sign(payload)` resolves to the compact JWS string.
234
+ * @throws {JwtError} for `alg: "none"`, unknown algorithms, weak keys, a
235
+ * missing/invalid `maxLifetimeSeconds`, or `acknowledgeNoExp` in production.
231
236
  * @since 0.21.0
232
237
  */
233
238
  export function createJwtSigner(opts) {
@@ -326,6 +331,11 @@ function normalizeStringSet(value) {
326
331
  * refuses-at-construction when a symmetric algorithm (`HS*`) is mixed with
327
332
  * a JWK / JWKS-shaped key source (the documented confused-deputy attack).
328
333
  *
334
+ * @param opts - Allowlist, key source, and claim checks; see {@link JwtVerifierOptions}.
335
+ * @returns An object whose `verify(token)` resolves to the decoded
336
+ * {@link JwtVerified} or rejects with {@link JwtError}.
337
+ * @throws {JwtError} at construction for an empty/invalid allowlist, `"none"`
338
+ * in the allowlist, weak HS* secrets, or HS* mixed with a JWK source.
329
339
  * @since 0.21.0
330
340
  */
331
341
  export function createJwtVerifier(opts) {
@@ -65,6 +65,9 @@ export interface LoadSheddingSnapshot {
65
65
  * retryAfterSeconds: 5,
66
66
  * }));
67
67
  * ```
68
+ *
69
+ * @param opts - Pressure thresholds (event-loop delay default 1000 ms, ELU default 0.98, optional heap/RSS byte caps), sampling interval, `Retry-After` seconds, and an optional custom `healthCheck`.
70
+ * @returns A {@link Hooks} bundle that sheds requests with `503` + `Retry-After` while pressure thresholds are exceeded.
68
71
  */
69
72
  export declare function loadShedding(opts?: LoadSheddingOptions): Hooks;
70
73
  /**
@@ -37,6 +37,9 @@ async function tryLoadPerfHooks() {
37
37
  * retryAfterSeconds: 5,
38
38
  * }));
39
39
  * ```
40
+ *
41
+ * @param opts - Pressure thresholds (event-loop delay default 1000 ms, ELU default 0.98, optional heap/RSS byte caps), sampling interval, `Retry-After` seconds, and an optional custom `healthCheck`.
42
+ * @returns A {@link Hooks} bundle that sheds requests with `503` + `Retry-After` while pressure thresholds are exceeded.
40
43
  */
41
44
  export function loadShedding(opts = {}) {
42
45
  const maxDelay = opts.maxEventLoopDelayMs ?? 1000;
package/dist/logger.d.ts CHANGED
@@ -10,13 +10,21 @@ export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
10
10
  * thin adapter; the default implementation is {@link createLogger}.
11
11
  */
12
12
  export interface Logger {
13
+ /** Minimum level emitted; records below this level are dropped. */
13
14
  level: LogLevel;
15
+ /** Log at `trace` level. Pass a fields object plus optional message, or a message string. */
14
16
  trace(obj: object | string, msg?: string): void;
17
+ /** Log at `debug` level. Pass a fields object plus optional message, or a message string. */
15
18
  debug(obj: object | string, msg?: string): void;
19
+ /** Log at `info` level. Pass a fields object plus optional message, or a message string. */
16
20
  info(obj: object | string, msg?: string): void;
21
+ /** Log at `warn` level. Pass a fields object plus optional message, or a message string. */
17
22
  warn(obj: object | string, msg?: string): void;
23
+ /** Log at `error` level. Pass a fields object plus optional message, or a message string. */
18
24
  error(obj: object | string, msg?: string): void;
25
+ /** Log at `fatal` level. Pass a fields object plus optional message, or a message string. */
19
26
  fatal(obj: object | string, msg?: string): void;
27
+ /** Return a derived logger whose records always include `bindings` merged into each record. */
20
28
  child(bindings: Record<string, unknown>): Logger;
21
29
  }
22
30
  /**
@@ -63,7 +71,9 @@ export interface LoggerRedactionOptions {
63
71
  export declare const DEFAULT_REDACT_KEYS: readonly string[];
64
72
  /** Options for {@link createLogger}. */
65
73
  export interface ConsoleLoggerOptions {
74
+ /** Minimum level to emit. Defaults to `"info"`. */
66
75
  level?: LogLevel;
76
+ /** Fields merged into every record emitted by this logger and its children. */
67
77
  bindings?: Record<string, unknown>;
68
78
  /** Where to write. Defaults to process.stdout.write or console.log. */
69
79
  write?: (line: string) => void;
@@ -89,6 +99,9 @@ interface ResolvedRedaction {
89
99
  * `cfg.redactJwt` is on) with `cfg.censor`. Exported for direct use by
90
100
  * custom logger implementations that want the same defaults.
91
101
  *
102
+ * @param record - Log record to redact. Mutated in place (cycle-safe, depth-capped).
103
+ * @param cfg - Resolved redaction settings (key set, censor, JWT/credential toggles, max depth).
104
+ * @returns The same `record` object, for chaining.
92
105
  * @since 0.15.0
93
106
  */
94
107
  export declare function redactRecord(record: Record<string, unknown>, cfg: ResolvedRedaction): Record<string, unknown>;
package/dist/logger.js CHANGED
@@ -123,6 +123,9 @@ function redactString(value, cfg) {
123
123
  * `cfg.redactJwt` is on) with `cfg.censor`. Exported for direct use by
124
124
  * custom logger implementations that want the same defaults.
125
125
  *
126
+ * @param record - Log record to redact. Mutated in place (cycle-safe, depth-capped).
127
+ * @param cfg - Resolved redaction settings (key set, censor, JWT/credential toggles, max depth).
128
+ * @returns The same `record` object, for chaining.
126
129
  * @since 0.15.0
127
130
  */
128
131
  export function redactRecord(record, cfg) {