@zudojs/http 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +64 -6
  2. package/dist/httpAdapter/http.adapter.d.ts +34 -3
  3. package/dist/httpAdapter/http.adapter.js +28 -10
  4. package/dist/httpAdapter/http.adapters.js +4 -34
  5. package/dist/httpAdapter/httpAdapter.errorResponse.d.ts +35 -0
  6. package/dist/httpAdapter/httpAdapter.errorResponse.js +137 -0
  7. package/dist/httpAdapter/httpAdapter.logger.d.ts +19 -0
  8. package/dist/httpAdapter/httpAdapter.logger.js +21 -0
  9. package/dist/httpAdapter/node/httpNode.adapter.d.ts +20 -1
  10. package/dist/httpAdapter/node/httpNode.adapter.js +80 -20
  11. package/dist/httpAdapter/node/httpNode.request.d.ts +12 -1
  12. package/dist/httpAdapter/node/httpNode.request.js +23 -16
  13. package/dist/httpAdapter/node/httpNode.server.d.ts +6 -0
  14. package/dist/httpAdapter/node/httpNode.server.js +6 -0
  15. package/dist/httpAdapter/node/httpNode.type.d.ts +2 -1
  16. package/dist/httpClient/httpClient.executor.js +14 -3
  17. package/dist/httpCookies/http.cookies.d.ts +29 -2
  18. package/dist/httpCookies/http.cookies.js +44 -24
  19. package/dist/httpCookies/httpCookies.defaults.d.ts +40 -0
  20. package/dist/httpCookies/httpCookies.defaults.js +42 -0
  21. package/dist/httpCookies/index.d.ts +1 -0
  22. package/dist/httpCookies/index.js +1 -0
  23. package/dist/httpMiddleware/builtin/conditional/httpMiddleware.conditional.d.ts +22 -1
  24. package/dist/httpMiddleware/builtin/conditional/httpMiddleware.conditional.js +19 -4
  25. package/dist/httpMiddleware/builtin/conditional/index.d.ts +1 -0
  26. package/dist/httpMiddleware/builtin/cors/httpMiddleware.cors.d.ts +8 -0
  27. package/dist/httpMiddleware/builtin/cors/httpMiddleware.cors.js +25 -22
  28. package/dist/httpMiddleware/builtin/helpers/httpMiddleware.accessor.js +2 -6
  29. package/dist/httpMiddleware/builtin/helpers/httpMiddleware.media.d.ts +33 -0
  30. package/dist/httpMiddleware/builtin/helpers/httpMiddleware.media.js +59 -0
  31. package/dist/httpMiddleware/builtin/helpers/index.d.ts +1 -0
  32. package/dist/httpMiddleware/builtin/helpers/index.js +1 -0
  33. package/dist/httpMiddleware/builtin/image/httpMiddleware.image.d.ts +13 -0
  34. package/dist/httpMiddleware/builtin/image/httpMiddleware.image.js +31 -53
  35. package/dist/httpMiddleware/builtin/index.d.ts +1 -0
  36. package/dist/httpMiddleware/builtin/index.js +1 -0
  37. package/dist/httpMiddleware/builtin/rateLimit/httpMiddleware.rateLimit.d.ts +47 -0
  38. package/dist/httpMiddleware/builtin/rateLimit/httpMiddleware.rateLimit.js +61 -0
  39. package/dist/httpMiddleware/builtin/rateLimit/index.d.ts +7 -0
  40. package/dist/httpMiddleware/builtin/rateLimit/index.js +7 -0
  41. package/dist/httpMiddleware/builtin/static/httpMiddleware.static.js +30 -4
  42. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.d.ts +19 -1
  43. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.js +38 -59
  44. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.options.d.ts +12 -0
  45. package/dist/httpMiddleware/builtin/video/httpMiddleware.video.options.js +31 -0
  46. package/dist/httpMiddleware/httpMiddleware.error.d.ts +5 -31
  47. package/dist/httpMiddleware/httpMiddleware.error.js +5 -53
  48. package/dist/httpProxy/http.proxy.d.ts +7 -0
  49. package/dist/httpProxy/http.proxy.js +9 -0
  50. package/dist/httpProxy/httpProxy.pathGuard.d.ts +23 -0
  51. package/dist/httpProxy/httpProxy.pathGuard.js +43 -0
  52. package/dist/httpProxy/index.d.ts +1 -0
  53. package/dist/httpProxy/index.js +1 -0
  54. package/dist/httpRequest/httpRequest.context.d.ts +7 -0
  55. package/dist/httpRequest/httpRequest.context.js +15 -16
  56. package/dist/httpRequest/index.d.ts +1 -0
  57. package/dist/httpRequest/index.js +1 -0
  58. package/dist/httpRequest/target/httpRequest.target.d.ts +45 -0
  59. package/dist/httpRequest/target/httpRequest.target.js +93 -0
  60. package/dist/httpRequest/target/index.d.ts +9 -0
  61. package/dist/httpRequest/target/index.js +9 -0
  62. package/dist/httpResponse/httpResponse.context.d.ts +10 -0
  63. package/dist/httpResponse/httpResponse.context.js +13 -1
  64. package/dist/httpResponse/httpResponse.helper.d.ts +22 -0
  65. package/dist/httpResponse/httpResponse.helper.js +94 -24
  66. package/dist/httpRouter/core/registry/core/httpRegistry.helper.js +1 -1
  67. package/dist/httpRouter/core/util/httpRoute.util.d.ts +14 -0
  68. package/dist/httpRouter/core/util/httpRoute.util.js +18 -14
  69. package/dist/httpRouter/dispatch/httpRoute.dispatcher.js +12 -1
  70. package/dist/httpSecurity/httpSecurity.config.d.ts +6 -0
  71. package/dist/httpSecurity/httpSecurity.config.js +1 -0
  72. package/dist/httpSecurity/httpSecurity.guard.d.ts +7 -9
  73. package/dist/httpSecurity/httpSecurity.guard.js +7 -14
  74. package/dist/httpSecurity/httpSecurity.nodeGuard.d.ts +48 -0
  75. package/dist/httpSecurity/httpSecurity.nodeGuard.js +32 -0
  76. package/dist/httpSecurity/httpSecurity.validator.js +4 -2
  77. package/dist/httpSecurity/index.d.ts +2 -0
  78. package/dist/httpSecurity/index.js +1 -0
  79. package/dist/httpServer/core/httpServer.core.d.ts +11 -0
  80. package/dist/httpServer/core/httpServer.core.js +30 -4
  81. package/dist/httpTrustProxy/httpTrustProxy.compilation.d.ts +5 -2
  82. package/dist/httpTrustProxy/httpTrustProxy.compilation.js +19 -2
  83. package/dist/httpTrustProxy/httpTrustProxy.type.d.ts +3 -1
  84. package/dist/index.js +0 -1
  85. package/package.json +9 -5
@@ -24,5 +24,13 @@ export interface CorsMiddlewareOptions {
24
24
  */
25
25
  readonly optionsSuccessStatus?: number;
26
26
  }
27
+ /**
28
+ * Creates the CORS middleware.
29
+ *
30
+ * @throws {ConfigurationError} At construction when a wildcard origin
31
+ * (including the default `"*"`) is combined with `credentials: true`.
32
+ * This used to be accepted and then fail every cross-origin request with a
33
+ * 500, which tests that send no `Origin` never noticed.
34
+ */
27
35
  export declare function createCorsMiddleware(options?: CorsMiddlewareOptions): HttpMiddleware;
28
36
  //# sourceMappingURL=httpMiddleware.cors.d.ts.map
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * @module httpMiddleware/builtin/cors
5
5
  */
6
+ import { isOriginAllowed } from "@zudojs/security";
6
7
  import { applyHeadersToResponse } from "../helpers/index.js";
7
8
  function getRequestHeader(context, name) {
8
9
  const headers = context.request.headers;
@@ -13,30 +14,23 @@ function getRequestMethod(context) {
13
14
  return (context.request.method ?? "GET").toUpperCase();
14
15
  }
15
16
  /**
16
- * Decides whether an origin is allowed.
17
- *
18
- * The previous implementation ignored the request origin entirely and wrote
19
- * `Access-Control-Allow-Origin: *` on every response, so the documented
20
- * "reflect the origin" pattern allowed every origin on the internet.
17
+ * The `@zudojs/security` CORS configuration for this middleware's origin
18
+ * policy. `allowOrigin` defaults to `"*"`; a predicate is bound to the
19
+ * request context because `@zudojs/security` predicates take the origin only.
21
20
  */
22
- function resolveAllowedOrigin(origin, context, options) {
21
+ function toSecurityCorsConfig(options, context) {
23
22
  const configured = options.allowOrigin ?? "*";
24
- if (typeof configured === "function") {
25
- return configured(origin, context) ? origin : undefined;
26
- }
27
- const list = typeof configured === "string" ? [configured] : configured;
28
- if (list.includes("*")) {
29
- if (options.credentials) {
30
- /*
31
- * A wildcard origin with credentials is forbidden by the spec, and
32
- * reflecting the request origin instead would authorise every origin
33
- * to read authenticated responses.
34
- */
35
- throw new TypeError("CORS: a wildcard allowOrigin cannot be combined with credentials.");
36
- }
37
- return "*";
38
- }
39
- return list.includes(origin) ? origin : undefined;
23
+ const origin = typeof configured === "function"
24
+ ? (value) => context !== undefined && configured(value, context)
25
+ : configured;
26
+ return { origin, credentials: options.credentials === true };
27
+ }
28
+ /**
29
+ * Decides whether an origin is allowed, delegating to `@zudojs/security`'s
30
+ * `isOriginAllowed` so origin matching has one implementation.
31
+ */
32
+ function resolveAllowedOrigin(origin, context, options) {
33
+ return isOriginAllowed(origin, toSecurityCorsConfig(options, context));
40
34
  }
41
35
  function appendVary(headers, value) {
42
36
  const existing = headers.get("vary");
@@ -51,7 +45,16 @@ function appendVary(headers, value) {
51
45
  headers.set("vary", `${existing}, ${value}`);
52
46
  }
53
47
  }
48
+ /**
49
+ * Creates the CORS middleware.
50
+ *
51
+ * @throws {ConfigurationError} At construction when a wildcard origin
52
+ * (including the default `"*"`) is combined with `credentials: true`.
53
+ * This used to be accepted and then fail every cross-origin request with a
54
+ * 500, which tests that send no `Origin` never noticed.
55
+ */
54
56
  export function createCorsMiddleware(options = {}) {
57
+ isOriginAllowed(undefined, toSecurityCorsConfig(options));
55
58
  return async (context, next) => {
56
59
  const origin = getRequestHeader(context, "origin");
57
60
  /*
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * @module httpMiddleware/builtin/helpers/accessors
5
5
  */
6
+ import { getCanonicalPath } from "../../../httpRequest/target/httpRequest.target.js";
6
7
  export function getRequestMethod(request) {
7
8
  const value = request.method;
8
9
  return value ?? "GET";
@@ -32,12 +33,7 @@ export function getContextSignal(request) {
32
33
  return value;
33
34
  }
34
35
  export function extractPathname(value) {
35
- try {
36
- return new URL(value, "http://zudojs.local").pathname;
37
- }
38
- catch {
39
- return value.split("?")[0] ?? value;
40
- }
36
+ return getCanonicalPath(value);
41
37
  }
42
38
  export function performanceNow() {
43
39
  if (typeof performance !== "undefined" &&
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Shared helpers for the media (image / video) compression middleware.
3
+ *
4
+ * Both middleware used to read the stale `context.response` instead of the
5
+ * response `next()` returned, so a handler that returned a fresh response
6
+ * context (the documented style) was never compressed. These helpers read
7
+ * everything from the returned response.
8
+ *
9
+ * @module httpMiddleware/builtin/helpers/media
10
+ */
11
+ import type { HttpResponseContext as ResponseContext } from "../../../httpResponse/httpResponse.context.js";
12
+ /**
13
+ * Reports a compression failure. The uncompressed response is still served.
14
+ */
15
+ export type MediaCompressionErrorHandler = (error: unknown, response: ResponseContext) => void;
16
+ /**
17
+ * The media type of a response (`image/png; q=1` → `image/png`), lowercased.
18
+ */
19
+ export declare function getResponseMediaType(response: ResponseContext): string | undefined;
20
+ /**
21
+ * The response body as a Buffer, or `undefined` for a body that is not held
22
+ * in memory (streams, JSON values).
23
+ */
24
+ export declare function getResponseBytes(response: ResponseContext): Buffer | undefined;
25
+ /**
26
+ * Loads an optional peer module's callable default export.
27
+ */
28
+ export declare function loadOptionalModule<T>(specifier: string, install: string): Promise<T>;
29
+ /**
30
+ * Replaces the body and content type of a compressed response.
31
+ */
32
+ export declare function applyCompressedBody(response: ResponseContext, body: Buffer, contentType: string): ResponseContext;
33
+ //# sourceMappingURL=httpMiddleware.media.d.ts.map
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Shared helpers for the media (image / video) compression middleware.
3
+ *
4
+ * Both middleware used to read the stale `context.response` instead of the
5
+ * response `next()` returned, so a handler that returned a fresh response
6
+ * context (the documented style) was never compressed. These helpers read
7
+ * everything from the returned response.
8
+ *
9
+ * @module httpMiddleware/builtin/helpers/media
10
+ */
11
+ /**
12
+ * The media type of a response (`image/png; q=1` → `image/png`), lowercased.
13
+ */
14
+ export function getResponseMediaType(response) {
15
+ const raw = response.headers["content-type"];
16
+ if (typeof raw !== "string") {
17
+ return undefined;
18
+ }
19
+ const mediaType = raw.split(";", 1)[0]?.trim().toLowerCase();
20
+ return mediaType ? mediaType : undefined;
21
+ }
22
+ /**
23
+ * The response body as a Buffer, or `undefined` for a body that is not held
24
+ * in memory (streams, JSON values).
25
+ */
26
+ export function getResponseBytes(response) {
27
+ const body = response.body;
28
+ if (Buffer.isBuffer(body)) {
29
+ return body;
30
+ }
31
+ if (body instanceof Uint8Array) {
32
+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
33
+ }
34
+ return undefined;
35
+ }
36
+ /**
37
+ * Loads an optional peer module's callable default export.
38
+ */
39
+ export async function loadOptionalModule(specifier, install) {
40
+ try {
41
+ const mod = (await import(specifier));
42
+ return (mod.default ?? mod);
43
+ }
44
+ catch {
45
+ throw new Error(`${specifier} is not installed. Run: ${install}`);
46
+ }
47
+ }
48
+ /**
49
+ * Replaces the body and content type of a compressed response.
50
+ */
51
+ export function applyCompressedBody(response, body, contentType) {
52
+ response.setHeader("content-type", contentType);
53
+ if (response.headers["cache-control"] === undefined) {
54
+ response.setHeader("cache-control", "public, max-age=86400");
55
+ }
56
+ response.removeHeader("content-length");
57
+ return response.setBody(body);
58
+ }
59
+ //# sourceMappingURL=httpMiddleware.media.js.map
@@ -6,4 +6,5 @@
6
6
  export * from "./httpMiddleware.contextHelper.js";
7
7
  export * from "./httpMiddleware.accessor.js";
8
8
  export * from "./httpMiddleware.response.js";
9
+ export * from "./httpMiddleware.media.js";
9
10
  //# sourceMappingURL=index.d.ts.map
@@ -6,4 +6,5 @@
6
6
  export * from "./httpMiddleware.contextHelper.js";
7
7
  export * from "./httpMiddleware.accessor.js";
8
8
  export * from "./httpMiddleware.response.js";
9
+ export * from "./httpMiddleware.media.js";
9
10
  //# sourceMappingURL=index.js.map
@@ -6,6 +6,7 @@
6
6
  * Requires: npm install sharp
7
7
  */
8
8
  import type { HttpMiddleware } from "../../httpMiddleware.type.js";
9
+ import { type MediaCompressionErrorHandler } from "../helpers/index.js";
9
10
  export interface ImageCompressionOptions {
10
11
  readonly quality?: number;
11
12
  readonly format?: "jpeg" | "png" | "webp" | "avif";
@@ -17,10 +18,22 @@ export interface ImageCompressionMiddlewareOptions {
17
18
  readonly enabled?: boolean;
18
19
  readonly defaultQuality?: number;
19
20
  readonly defaultFormat?: "jpeg" | "png" | "webp" | "avif";
21
+ /** Upper bound on the output width; applied to every image. */
20
22
  readonly maxWidth?: number;
23
+ /** Upper bound on the output height; applied to every image. */
21
24
  readonly maxHeight?: number;
22
25
  readonly contentTypeMap?: Record<string, ImageCompressionOptions>;
26
+ /**
27
+ * Called when compression fails. The original response is still served.
28
+ * Defaults to a no-op.
29
+ */
30
+ readonly onError?: MediaCompressionErrorHandler;
23
31
  }
24
32
  export declare function compressImage(buffer: Buffer, options?: ImageCompressionOptions): Promise<Buffer>;
33
+ /**
34
+ * Compresses `image/*` responses. Status, headers and body are read from the
35
+ * response returned by `next()`, and `maxWidth` / `maxHeight` cap every
36
+ * output.
37
+ */
25
38
  export declare function createImageCompressionMiddleware(options?: ImageCompressionMiddlewareOptions): HttpMiddleware;
26
39
  //# sourceMappingURL=httpMiddleware.image.d.ts.map
@@ -5,23 +5,14 @@
5
5
  *
6
6
  * Requires: npm install sharp
7
7
  */
8
- import { applyHeadersToResponse } from "../helpers/index.js";
8
+ import { applyCompressedBody, getResponseBytes, getResponseMediaType, loadOptionalModule, } from "../helpers/index.js";
9
9
  const DEFAULT_QUALITY = 80;
10
10
  const DEFAULT_FORMAT = "jpeg";
11
- async function getSharp() {
12
- try {
13
- const mod = await import("sharp");
14
- return mod.default ?? mod;
15
- }
16
- catch {
17
- throw new Error("Sharp is not installed. Run: npm install sharp");
18
- }
19
- }
20
11
  export async function compressImage(buffer, options = {}) {
21
- const sharpInstance = await getSharp();
12
+ const sharp = await loadOptionalModule("sharp", "npm install sharp");
22
13
  const quality = options.quality ?? DEFAULT_QUALITY;
23
14
  const format = options.format ?? DEFAULT_FORMAT;
24
- let pipeline = sharpInstance(buffer);
15
+ let pipeline = sharp(buffer);
25
16
  if (options.width || options.height) {
26
17
  pipeline = pipeline.resize({
27
18
  width: options.width,
@@ -30,59 +21,46 @@ export async function compressImage(buffer, options = {}) {
30
21
  withoutEnlargement: true,
31
22
  });
32
23
  }
33
- switch (format) {
34
- case "jpeg":
35
- return pipeline.jpeg({ quality }).toBuffer();
36
- case "png":
37
- return pipeline.png({ quality }).toBuffer();
38
- case "webp":
39
- return pipeline.webp({ quality }).toBuffer();
40
- case "avif":
41
- return pipeline.avif({ quality }).toBuffer();
42
- default:
43
- return pipeline.toBuffer();
24
+ return pipeline[format]({ quality }).toBuffer();
25
+ }
26
+ function capDimension(requested, max) {
27
+ if (max === undefined) {
28
+ return requested;
44
29
  }
30
+ return requested === undefined ? max : Math.min(requested, max);
45
31
  }
32
+ /**
33
+ * Compresses `image/*` responses. Status, headers and body are read from the
34
+ * response returned by `next()`, and `maxWidth` / `maxHeight` cap every
35
+ * output.
36
+ */
46
37
  export function createImageCompressionMiddleware(options = {}) {
47
38
  const enabled = options.enabled ?? true;
48
- const defaultQuality = options.defaultQuality ?? DEFAULT_QUALITY;
49
- const defaultFormat = options.defaultFormat ?? DEFAULT_FORMAT;
50
39
  const contentTypeMap = options.contentTypeMap ?? {};
51
- return async (context, next) => {
52
- if (!enabled) {
53
- return next();
54
- }
40
+ return async (_context, next) => {
55
41
  const response = await next();
56
- const contentType = context.response.headers["content-type"];
57
- if (!contentType || !contentType.startsWith("image/")) {
42
+ const mediaType = getResponseMediaType(response);
43
+ if (!enabled || !mediaType?.startsWith("image/")) {
58
44
  return response;
59
45
  }
60
- const body = context.response.body;
61
- if (!Buffer.isBuffer(body) && typeof body !== "string") {
46
+ const buffer = getResponseBytes(response);
47
+ if (!buffer || buffer.length === 0) {
62
48
  return response;
63
49
  }
64
- const buffer = Buffer.isBuffer(body) ? body : Buffer.from(body);
65
- const compressionOptions = contentTypeMap[contentType] ?? {
66
- quality: defaultQuality,
67
- format: defaultFormat,
68
- };
50
+ const mapped = contentTypeMap[mediaType] ?? {};
51
+ const format = mapped.format ?? options.defaultFormat ?? DEFAULT_FORMAT;
69
52
  try {
70
- const compressed = await compressImage(buffer, compressionOptions);
71
- const newContentType = compressionOptions.format === "jpeg"
72
- ? "image/jpeg"
73
- : compressionOptions.format === "png"
74
- ? "image/png"
75
- : compressionOptions.format === "webp"
76
- ? "image/webp"
77
- : compressionOptions.format === "avif"
78
- ? "image/avif"
79
- : contentType;
80
- const headers = new Headers(response.headers);
81
- headers.set("content-type", newContentType);
82
- headers.set("cache-control", headers.get("cache-control") ?? "public, max-age=86400");
83
- return applyHeadersToResponse(response, headers).setBody(compressed);
53
+ const compressed = await compressImage(buffer, {
54
+ ...mapped,
55
+ quality: mapped.quality ?? options.defaultQuality ?? DEFAULT_QUALITY,
56
+ format,
57
+ width: capDimension(mapped.width, options.maxWidth),
58
+ height: capDimension(mapped.height, options.maxHeight),
59
+ });
60
+ return applyCompressedBody(response, compressed, `image/${format}`);
84
61
  }
85
- catch {
62
+ catch (error) {
63
+ options.onError?.(error, response);
86
64
  return response;
87
65
  }
88
66
  };
@@ -13,6 +13,7 @@ export * from "./helpers/index.js";
13
13
  export * from "./static/index.js";
14
14
  export * from "./image/index.js";
15
15
  export * from "./video/index.js";
16
+ export * from "./rateLimit/index.js";
16
17
  /** State middleware — identity pass-through. */
17
18
  export declare function createStateMiddleware(): import("../httpMiddleware.type.js").HttpMiddleware;
18
19
  //# sourceMappingURL=index.d.ts.map
@@ -13,6 +13,7 @@ export * from "./helpers/index.js";
13
13
  export * from "./static/index.js";
14
14
  export * from "./image/index.js";
15
15
  export * from "./video/index.js";
16
+ export * from "./rateLimit/index.js";
16
17
  /** State middleware — identity pass-through. */
17
18
  export function createStateMiddleware() {
18
19
  return async (_context, next) => {
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Rate limiting middleware built on `@zudojs/security`.
3
+ *
4
+ * AGENTS.md requires public endpoints to be rate limited with
5
+ * `createRateLimiter` from `@zudojs/security`, and `@zudojs/http` offered no
6
+ * way to do that. This wraps the shared limiter; it does not re-implement it.
7
+ *
8
+ * The client key is `request.remoteAddress`, which the Node adapter has
9
+ * already resolved through its `trustProxy` setting, so forwarded headers
10
+ * only count when the adapter trusts the peer that sent them.
11
+ *
12
+ * A request with no usable client address (a Unix-socket peer, a context
13
+ * built without `remoteAddress`, a destroyed socket) is counted in one
14
+ * shared bucket, {@link UNKNOWN_CLIENT_RATE_LIMIT_IP}. The `@zudojs/security`
15
+ * default key generator refuses such a request with a `ConfigurationError`,
16
+ * which would otherwise surface as a 500, and skipping the limiter for it
17
+ * would give it unlimited requests.
18
+ *
19
+ * @module httpMiddleware/builtin/rateLimit
20
+ */
21
+ import { createRateLimiter, type RateLimiterOptions } from "@zudojs/security";
22
+ import type { HttpMiddleware } from "../../httpMiddleware.type.js";
23
+ /**
24
+ * The `ip` given to the limiter for a request whose `remoteAddress` is
25
+ * missing or is not an IP address. `0.0.0.0` is never a real peer address,
26
+ * so these requests share one bucket without colliding with a client.
27
+ */
28
+ export declare const UNKNOWN_CLIENT_RATE_LIMIT_IP = "0.0.0.0";
29
+ /**
30
+ * The limiter instance returned by `@zudojs/security`'s `createRateLimiter`.
31
+ */
32
+ export type HttpRateLimiter = ReturnType<typeof createRateLimiter>;
33
+ /**
34
+ * Options for {@link createRateLimitMiddleware}: either the
35
+ * `@zudojs/security` limiter options, or an existing `limiter` to share
36
+ * between routes.
37
+ */
38
+ export type RateLimitMiddlewareOptions = RateLimiterOptions | {
39
+ readonly limiter: HttpRateLimiter;
40
+ };
41
+ /**
42
+ * Creates middleware that answers `429 Too Many Requests` (with
43
+ * `Retry-After`, from the `@zudojs/security` handler) once a client exceeds
44
+ * its allowance, and otherwise passes the request on.
45
+ */
46
+ export declare function createRateLimitMiddleware(options: RateLimitMiddlewareOptions): HttpMiddleware;
47
+ //# sourceMappingURL=httpMiddleware.rateLimit.d.ts.map
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Rate limiting middleware built on `@zudojs/security`.
3
+ *
4
+ * AGENTS.md requires public endpoints to be rate limited with
5
+ * `createRateLimiter` from `@zudojs/security`, and `@zudojs/http` offered no
6
+ * way to do that. This wraps the shared limiter; it does not re-implement it.
7
+ *
8
+ * The client key is `request.remoteAddress`, which the Node adapter has
9
+ * already resolved through its `trustProxy` setting, so forwarded headers
10
+ * only count when the adapter trusts the peer that sent them.
11
+ *
12
+ * A request with no usable client address (a Unix-socket peer, a context
13
+ * built without `remoteAddress`, a destroyed socket) is counted in one
14
+ * shared bucket, {@link UNKNOWN_CLIENT_RATE_LIMIT_IP}. The `@zudojs/security`
15
+ * default key generator refuses such a request with a `ConfigurationError`,
16
+ * which would otherwise surface as a 500, and skipping the limiter for it
17
+ * would give it unlimited requests.
18
+ *
19
+ * @module httpMiddleware/builtin/rateLimit
20
+ */
21
+ import { createRateLimiter, parseClientIp, } from "@zudojs/security";
22
+ import { createResponseContext } from "../../../httpResponse/httpResponse.context.js";
23
+ /**
24
+ * The `ip` given to the limiter for a request whose `remoteAddress` is
25
+ * missing or is not an IP address. `0.0.0.0` is never a real peer address,
26
+ * so these requests share one bucket without colliding with a client.
27
+ */
28
+ export const UNKNOWN_CLIENT_RATE_LIMIT_IP = "0.0.0.0";
29
+ /**
30
+ * Creates middleware that answers `429 Too Many Requests` (with
31
+ * `Retry-After`, from the `@zudojs/security` handler) once a client exceeds
32
+ * its allowance, and otherwise passes the request on.
33
+ */
34
+ export function createRateLimitMiddleware(options) {
35
+ const limiter = "limiter" in options ? options.limiter : createRateLimiter(options);
36
+ return async (context, next) => {
37
+ const request = context.request;
38
+ const limitRequest = {
39
+ ip: clientIpOf(request.remoteAddress),
40
+ method: request.method,
41
+ path: request.path,
42
+ headers: request.headers,
43
+ };
44
+ const rejection = { statusCode: 429, headers: {} };
45
+ if (limiter.middleware(limitRequest, rejection).allowed) {
46
+ return next();
47
+ }
48
+ const response = createResponseContext().setStatus(rejection.statusCode);
49
+ for (const [name, value] of Object.entries(rejection.headers)) {
50
+ response.setHeader(name.toLowerCase(), value);
51
+ }
52
+ return response.setBody(rejection.body ?? "Too Many Requests");
53
+ };
54
+ }
55
+ function clientIpOf(remoteAddress) {
56
+ return typeof remoteAddress === "string" &&
57
+ parseClientIp(remoteAddress) !== undefined
58
+ ? remoteAddress
59
+ : UNKNOWN_CLIENT_RATE_LIMIT_IP;
60
+ }
61
+ //# sourceMappingURL=httpMiddleware.rateLimit.js.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @zudojs/http/httpMiddleware/builtin/rateLimit
3
+ *
4
+ * Rate limiting middleware wrapping `@zudojs/security`'s `createRateLimiter`.
5
+ */
6
+ export { createRateLimitMiddleware, UNKNOWN_CLIENT_RATE_LIMIT_IP, type HttpRateLimiter, type RateLimitMiddlewareOptions, } from "./httpMiddleware.rateLimit.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @zudojs/http/httpMiddleware/builtin/rateLimit
3
+ *
4
+ * Rate limiting middleware wrapping `@zudojs/security`'s `createRateLimiter`.
5
+ */
6
+ export { createRateLimitMiddleware, UNKNOWN_CLIENT_RATE_LIMIT_IP, } from "./httpMiddleware.rateLimit.js";
7
+ //# sourceMappingURL=index.js.map
@@ -7,6 +7,8 @@ import { readFile, stat } from "node:fs/promises";
7
7
  import { createHash } from "node:crypto";
8
8
  import { extname, join, resolve, sep } from "node:path";
9
9
  import { applyHeadersToResponse } from "../helpers/index.js";
10
+ import { parseRequestTarget } from "../../../httpRequest/target/httpRequest.target.js";
11
+ import { evaluateConditionalRequest } from "../../../httpConditional/httpConditional.core.js";
10
12
  const DEFAULT_INDEX = "index.html";
11
13
  const DEFAULT_MAX_AGE = 3600;
12
14
  const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
@@ -133,7 +135,19 @@ export function createStaticMiddleware(options) {
133
135
  if (method !== undefined && method !== "GET" && method !== "HEAD") {
134
136
  return next();
135
137
  }
136
- const url = new URL(context.request.url);
138
+ /*
139
+ * `context.request.url` is the request-target as the adapter received
140
+ * it — `/pub/app.js`, not an absolute URL — so it must be parsed against
141
+ * a base. `new URL(url)` alone threw `Invalid URL` for every request the
142
+ * Node adapter delivered, and the middleware answered 500 to all of them.
143
+ */
144
+ let url;
145
+ try {
146
+ url = parseRequestTarget(context.request.url);
147
+ }
148
+ catch {
149
+ return next();
150
+ }
137
151
  const decodedPathname = decodePathname(url.pathname);
138
152
  if (decodedPathname === undefined) {
139
153
  return next();
@@ -188,9 +202,21 @@ export function createStaticMiddleware(options) {
188
202
  * returns the whole body and has no 206 path, so advertising range
189
203
  * support makes range-aware clients misbehave.
190
204
  */
191
- const ifNoneMatch = context.request.headers["if-none-match"];
192
- if (ifNoneMatch === etag) {
193
- return applyHeadersToResponse(context.response, responseHeaders).setStatus(304);
205
+ /*
206
+ * RFC 9110 section 13.2.2 evaluation: `If-None-Match` lists, weak tags
207
+ * and `*`, then `If-Modified-Since`, plus `If-Match` /
208
+ * `If-Unmodified-Since` (412). An exact string compare missed all of
209
+ * those and re-sent the whole file.
210
+ */
211
+ const headers = context.request.headers;
212
+ const conditional = evaluateConditionalRequest(context.request.method, {
213
+ ifMatch: headers["if-match"],
214
+ ifNoneMatch: headers["if-none-match"],
215
+ ifModifiedSince: headers["if-modified-since"],
216
+ ifUnmodifiedSince: headers["if-unmodified-since"],
217
+ }, { etag, lastModified });
218
+ if (conditional.statusCode !== undefined) {
219
+ return applyHeadersToResponse(context.response, responseHeaders).setStatus(conditional.statusCode);
194
220
  }
195
221
  return applyHeadersToResponse(context.response, responseHeaders).setBody(fileData);
196
222
  };
@@ -3,14 +3,17 @@
3
3
  *
4
4
  * @module httpMiddleware/builtin/video
5
5
  *
6
- * Requires: npm install fluent-ffmpeg
6
+ * Requires: npm install fluent-ffmpeg (and an ffmpeg binary)
7
7
  */
8
8
  import type { HttpMiddleware } from "../../httpMiddleware.type.js";
9
+ import { type MediaCompressionErrorHandler } from "../helpers/index.js";
9
10
  export interface VideoCompressionOptions {
10
11
  readonly bitrate?: string;
11
12
  readonly preset?: "ultrafast" | "superfast" | "veryfast" | "faster" | "fast" | "medium" | "slow" | "slower" | "veryslow";
12
13
  readonly crf?: number;
13
14
  readonly format?: "mp4" | "webm" | "mov";
15
+ /** Input container; defaults to `mp4`. */
16
+ readonly inputFormat?: string;
14
17
  readonly scale?: {
15
18
  readonly width?: number;
16
19
  readonly height?: number;
@@ -20,7 +23,22 @@ export interface VideoCompressionMiddlewareOptions {
20
23
  readonly enabled?: boolean;
21
24
  readonly contentTypeMap?: Record<string, VideoCompressionOptions>;
22
25
  readonly tempDir?: string;
26
+ /**
27
+ * Called when compression fails. The original response is still served.
28
+ */
29
+ readonly onError?: MediaCompressionErrorHandler;
23
30
  }
31
+ /**
32
+ * Transcodes a video held in memory.
33
+ *
34
+ * `fluent-ffmpeg`'s export is a factory: `input()` exists only on the
35
+ * command it returns. Calling it on the module (as this did) threw
36
+ * `ffmpegInstance.input is not a function` on every call.
37
+ */
24
38
  export declare function compressVideo(inputBuffer: Buffer, options?: VideoCompressionOptions): Promise<Buffer>;
39
+ /**
40
+ * Compresses `video/*` responses, reading status, headers and body from the
41
+ * response returned by `next()`.
42
+ */
25
43
  export declare function createVideoCompressionMiddleware(options?: VideoCompressionMiddlewareOptions): HttpMiddleware;
26
44
  //# sourceMappingURL=httpMiddleware.video.d.ts.map