@wxn0brp/falcon-frame 0.9.8 → 0.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/req.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "crypto";
2
2
  import { URL } from "url";
3
3
  import { getContentType, getRawBody } from "./body-utils.js";
4
- import { getIP, parseCookies } from "./helpers.js";
4
+ import { parseCookies, resolveRequestInfo } from "./helpers.js";
5
5
  import { extractParams, getMiddlewares, matchMiddleware } from "./middleware.js";
6
6
  import { FFResponse } from "./res.js";
7
7
  import { validate } from "./valid.js";
@@ -30,7 +30,12 @@ export function handleRequest(req, res, FF, reRoute = false) {
30
30
  res.status(400).end("400: Bad request");
31
31
  return;
32
32
  }
33
- req.ip = getIP(req);
33
+ const requestInfo = resolveRequestInfo(req, FF.config.proxy);
34
+ req.socketIp = requestInfo.socketIp;
35
+ req.ip = requestInfo.ip;
36
+ req.isProxied = requestInfo.isProxied;
37
+ req.protocol = requestInfo.protocol;
38
+ req.secure = requestInfo.protocol === "https";
34
39
  req.params = {};
35
40
  req.valid = (schema, regexRules) => validate({
36
41
  schema,
@@ -44,17 +49,18 @@ export function handleRequest(req, res, FF, reRoute = false) {
44
49
  };
45
50
  req.header = (name) => req.headers[name.toLowerCase()] || "";
46
51
  req.isBodyParsed = false;
47
- if (FF.opts.xRequestId !== "disable") {
52
+ if (FF.config.xRequestId !== "disable") {
48
53
  if (req.headers["x-request-id"]) {
49
54
  req.id = req.headers["x-request-id"];
50
55
  res.setHeader("x-request-id", req.id);
51
56
  }
52
- else if (FF.opts.xRequestId === "auto") {
57
+ else if (FF.config.xRequestId === "auto") {
53
58
  req.id = randomUUID();
54
59
  res.setHeader("x-request-id", req.id);
55
60
  }
56
61
  }
57
- logger.info(`Incoming request: ${req.method} ${req.url}` +
62
+ const logUrl = (req.url || "").replace(/([?&]pass=)[^&]*/i, "$1***");
63
+ logger.info(`Incoming request: ${req.method} ${logUrl}` +
58
64
  (req.id ? ` [${req.id}]` : ""));
59
65
  const middlewaresPath = req.path + "/";
60
66
  const middlewares = getMiddlewares(FF.middlewares, middlewaresPath.replace(/\/+/g, "/"));
@@ -121,15 +127,23 @@ export function handleRequest(req, res, FF, reRoute = false) {
121
127
  return;
122
128
  }
123
129
  req.body = {};
124
- const ct = getContentType(req) || "application/json";
125
- const entry = FF.bodyParsers[ct];
130
+ const ct = getContentType(req);
131
+ let entry = ct ? FF.bodyParsers[ct] : undefined;
132
+ if (!ct && FF.config.defaultBodyParser === "json") {
133
+ entry = FF.bodyParsers["application/json"];
134
+ }
126
135
  if (!entry) {
127
- logger.debug("No body parser found for content-type. Executing middlewares");
136
+ if (ct) {
137
+ logger.debug(`No body parser found for content-type ${ct}. Executing middlewares`);
138
+ }
139
+ else {
140
+ logger.debug("No content-type. Executing middlewares");
141
+ }
128
142
  next();
129
143
  return;
130
144
  }
131
- logger.debug(`Executing body parser for content-type: ${ct}`);
132
- getRawBody(req, res, entry.limit)
145
+ logger.debug(`Executing body parser for content-type: ${ct ?? "default (json)"}`);
146
+ getRawBody(req, res, entry.limit, FF.config.bodyTimeout)
133
147
  .then(async (rawBody) => {
134
148
  try {
135
149
  req.body = (await entry.parse(rawBody, req, res)) ?? {};
@@ -141,10 +155,17 @@ export function handleRequest(req, res, FF, reRoute = false) {
141
155
  }
142
156
  next();
143
157
  })
144
- .catch(() => {
145
- if (!res._ended) {
146
- req.body = {};
147
- next();
158
+ .catch((err) => {
159
+ if (res._ended)
160
+ return;
161
+ if (err?.statusCode === 408) {
162
+ res.status(408);
163
+ res.FF._408(req, res);
164
+ if (!res.writableEnded)
165
+ res.end();
166
+ return;
148
167
  }
168
+ req.body = {};
169
+ next();
149
170
  });
150
171
  }
package/dist/res.js CHANGED
@@ -1,8 +1,7 @@
1
- import { createReadStream } from "fs";
2
1
  import http from "http";
3
2
  import path from "path";
4
- import { ensureLeadingDot } from "./helpers.js";
5
3
  import { getContentType } from "./encoding.js";
4
+ import { ensureLeadingDot, streamFile } from "./helpers.js";
6
5
  export class FFResponse extends http.ServerResponse {
7
6
  _ended = false;
8
7
  FF;
@@ -101,7 +100,7 @@ export class FFResponse extends http.ServerResponse {
101
100
  if (contentType === "utf8")
102
101
  contentType = getContentType(filePath, true);
103
102
  this.ct(contentType || getContentType(filePath));
104
- createReadStream(filePath).pipe(this);
103
+ streamFile(this, filePath);
105
104
  this._ended = true;
106
105
  return this;
107
106
  }
@@ -168,6 +167,7 @@ export class FFResponse extends http.ServerResponse {
168
167
  this.setHeader("Content-Type", "text/event-stream");
169
168
  this.setHeader("Cache-Control", "no-cache");
170
169
  this.setHeader("Connection", "keep-alive");
170
+ this.flushHeaders();
171
171
  return this;
172
172
  }
173
173
  /**
package/dist/router.d.ts CHANGED
@@ -13,7 +13,8 @@ export declare class Router {
13
13
  delete(path: string, ...handlers: RouteHandler[]): this;
14
14
  patch(path: string, ...handlers: RouteHandler[]): this;
15
15
  all(path: string, ...handlers: RouteHandler[]): this;
16
- static(apiPath: string, dirPath?: string, opts?: StaticServeOptions): this;
16
+ static(dirPath: string, opts?: StaticServeOptions): this;
17
+ static(apiPath: string, dirPath: string, opts?: StaticServeOptions): this;
17
18
  file(routePath: string, filePath: string, opts?: StaticFileOptions): this;
18
19
  sse(path: string, ...handlers: RouteHandler[]): SSEManager;
19
20
  customParser(path: string, handler: RouteHandler, method?: Method): this;
package/dist/router.js CHANGED
@@ -58,10 +58,18 @@ export class Router {
58
58
  this.addRoute("all", path, ...handlers);
59
59
  return this;
60
60
  }
61
- static(apiPath, dirPath, opts = {}) {
62
- if (!dirPath) {
63
- dirPath = apiPath;
61
+ static(apiPathOrDir, dirOrOpts, maybeOpts = {}) {
62
+ let apiPath = apiPathOrDir;
63
+ let dirPath;
64
+ let opts;
65
+ if (typeof dirOrOpts === "string") {
66
+ dirPath = dirOrOpts;
67
+ opts = maybeOpts;
68
+ }
69
+ else {
70
+ dirPath = apiPathOrDir;
64
71
  apiPath = "/";
72
+ opts = dirOrOpts ?? {};
65
73
  }
66
74
  if (dirPath === "/")
67
75
  throw new Error("Cannot serve root directory");
package/dist/static.js CHANGED
@@ -1,7 +1,41 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
- import { ensureLeadingDot } from "./helpers.js";
3
+ import { ensureLeadingDot, streamFile } from "./helpers.js";
4
4
  import { getContentType } from "./encoding.js";
5
+ const WELL_KNOWN = ".well-known";
6
+ function normalizeMount(apiPath) {
7
+ const trimmed = apiPath.replace(/\/+$/, "");
8
+ return trimmed === "" ? "/" : trimmed;
9
+ }
10
+ function relativeToMount(mount, requestPath) {
11
+ if (mount === "/")
12
+ return requestPath;
13
+ if (requestPath === mount)
14
+ return "/";
15
+ if (!requestPath.startsWith(`${mount}/`))
16
+ return null;
17
+ return requestPath.slice(mount.length);
18
+ }
19
+ function isAllowedRelative(relative, dotfiles) {
20
+ const segments = relative.split("/").filter(Boolean);
21
+ for (let i = 0; i < segments.length; i++) {
22
+ const segment = segments[i];
23
+ if (segment === "." || segment === "..")
24
+ return false;
25
+ if (segment.includes("\\") || segment.includes("\0"))
26
+ return false;
27
+ if (process.platform === "win32" && segment.includes(":"))
28
+ return false;
29
+ if (dotfiles)
30
+ continue;
31
+ if (!segment.startsWith("."))
32
+ continue;
33
+ if (i === 0 && segment === WELL_KNOWN)
34
+ continue;
35
+ return false;
36
+ }
37
+ return true;
38
+ }
5
39
  export function handleSingleFile(filePath, opts) {
6
40
  opts = {
7
41
  utf8: true,
@@ -32,12 +66,12 @@ export function handleSingleFile(filePath, opts) {
32
66
  res.setHeader("ETag", etag);
33
67
  }
34
68
  res.ct(getContentType(filePath, opts.utf8));
69
+ res.setHeader("Content-Length", stats.size);
35
70
  if (req.method === "HEAD") {
36
- res.setHeader("Content-Length", stats.size);
37
71
  res.end();
38
72
  return;
39
73
  }
40
- fs.createReadStream(filePath).pipe(res);
74
+ streamFile(res, filePath);
41
75
  };
42
76
  }
43
77
  export function handleStaticFiles(dirPath, opts) {
@@ -47,6 +81,7 @@ export function handleStaticFiles(dirPath, opts) {
47
81
  renderData: {},
48
82
  etag: true,
49
83
  errorIfDirNotFound: true,
84
+ dotfiles: false,
50
85
  ...opts,
51
86
  };
52
87
  if (opts.errorIfDirNotFound && !fs.existsSync(dirPath)) {
@@ -59,9 +94,10 @@ export function handleStaticFiles(dirPath, opts) {
59
94
  filePath.endsWith(ensureLeadingDot(defaultRenderer))) ||
60
95
  (!opts.notRenderHtml && filePath.endsWith(".html"));
61
96
  if (renderStatement) {
62
- const relativePath = filePath
63
- .replace(dirPath + "/", "")
64
- .replace(".html", "");
97
+ const relativePath = path
98
+ .relative(path.resolve(dirPath), filePath)
99
+ .replaceAll(path.sep, "/")
100
+ .replace(/\.html$/, "");
65
101
  res.render(filePath, opts.renderData?.[relativePath] || {}, {
66
102
  notUseViews: true,
67
103
  });
@@ -77,23 +113,27 @@ export function handleStaticFiles(dirPath, opts) {
77
113
  res.setHeader("ETag", etag);
78
114
  }
79
115
  res.ct(getContentType(filePath, opts.utf8));
116
+ res.setHeader("Content-Length", stats.size);
80
117
  if (req.method === "HEAD") {
81
- res.setHeader("Content-Length", stats.size);
82
118
  res.end();
83
119
  return true;
84
120
  }
85
- fs.createReadStream(filePath).pipe(res);
121
+ streamFile(res, filePath);
86
122
  return true;
87
123
  };
88
124
  return (req, res, next) => {
89
125
  if (req.method !== "GET" && req.method !== "HEAD")
90
126
  return next();
91
- const apiPath = req.middleware.path;
92
- const unsafePath = req.path.replace(apiPath, "");
93
- const filePath = path.join(dirPath, path.normalize(unsafePath));
94
- const resolvedPath = path.resolve(filePath);
95
- const resolvedDir = path.resolve(dirPath);
96
- if (!resolvedPath.startsWith(resolvedDir))
127
+ const mount = normalizeMount(req.middleware.path);
128
+ const relative = relativeToMount(mount, req.path);
129
+ if (relative === null)
130
+ return next();
131
+ if (!isAllowedRelative(relative, !!opts.dotfiles))
132
+ return next();
133
+ const root = path.resolve(dirPath);
134
+ const filePath = path.resolve(root, `.${relative === "/" ? "" : relative}`);
135
+ const rel = path.relative(root, filePath);
136
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
97
137
  return next();
98
138
  try {
99
139
  const stats = fs.statSync(filePath);
package/dist/types.d.ts CHANGED
@@ -6,6 +6,32 @@ export type RouteHandler = (req: FFRequest, res: FFResponse, next: () => void) =
6
6
  export type FinalHandler = (req: FFRequest, res: FFResponse) => void | any;
7
7
  export type ErrorHandler = (err: Error, req: FFRequest, res: FFResponse) => void | any;
8
8
  export type Method = "get" | "post" | "put" | "delete" | "patch" | "all";
9
+ /**
10
+ * How the client IP is resolved behind a proxy.
11
+ * - `"auto"` (default): trust proxy headers only when the TCP peer is loopback,
12
+ * which covers local tunnels (`cloudflared`, nginx, caddy) without trusting
13
+ * spoofable headers from remote peers.
14
+ * - `true`: trust proxy headers from any peer.
15
+ * - `false`: never trust proxy headers.
16
+ * - `string[]`: trust proxy headers only from the listed proxy addresses.
17
+ */
18
+ export type ProxyMode = "auto" | boolean | string[];
19
+ export interface DebugOptions {
20
+ /** URL path of the debug panel. Defaults to `/debug`. */
21
+ path?: string;
22
+ /** @deprecated use `path` */
23
+ url?: string;
24
+ /** Extra allowlist of client IPs. Empty by default, the token is the gate. */
25
+ hosts?: string[];
26
+ /** Enable the endpoint. Defaults to `NODE_ENV !== "production"`. */
27
+ enabled?: boolean;
28
+ /** Stable secret. If omitted, a random token is generated at startup. */
29
+ pass?: string;
30
+ /** Throttle failed token attempts. Defaults to `true`. */
31
+ rateLimit?: boolean;
32
+ /** @deprecated */
33
+ logs?: boolean;
34
+ }
9
35
  export interface Params {
10
36
  [key: string]: string;
11
37
  }
@@ -26,6 +52,14 @@ export interface BodyParserEntry {
26
52
  export interface StandardBodyParserOptions {
27
53
  limit?: string | number;
28
54
  }
55
+ export interface CompressionOptions {
56
+ /** Responses smaller than this (in bytes) are sent uncompressed. Defaults to 1024. */
57
+ threshold?: number;
58
+ /** Brotli quality, 0-11. Defaults to 4. */
59
+ brotliQuality?: number;
60
+ /** gzip/deflate level, 0-9. Defaults to 6. */
61
+ gzipLevel?: number;
62
+ }
29
63
  export declare class FFRequest extends http.IncomingMessage {
30
64
  FF: FalconFrame<any>;
31
65
  path: string;
@@ -33,7 +67,16 @@ export declare class FFRequest extends http.IncomingMessage {
33
67
  params: Params;
34
68
  cookies: Cookies;
35
69
  body: Body;
70
+ /** Raw TCP peer address. */
71
+ socketIp: string;
72
+ /** Resolved client address (respects the `proxy` option). */
36
73
  ip: string;
74
+ /** True when proxy headers were used to resolve `ip`. */
75
+ isProxied: boolean;
76
+ /** Request protocol, respects `x-forwarded-proto` from a trusted proxy. */
77
+ protocol: "http" | "https";
78
+ /** True when the request came over HTTPS, directly or via a trusted proxy. */
79
+ secure: boolean;
37
80
  header: (name: string) => string;
38
81
  valid: (schema: ValidationSchema, regexRules?: Record<string, RegExp | string>) => ValidationResult;
39
82
  middleware: Middleware;
@@ -76,6 +119,8 @@ export interface StaticServeOptions {
76
119
  etag?: boolean;
77
120
  errorIfDirNotFound?: boolean;
78
121
  notRenderHtml?: boolean;
122
+ /** Allow serving dotfiles. `.well-known` is always allowed as the first segment. Defaults to false. */
123
+ dotfiles?: boolean;
79
124
  }
80
125
  export interface StaticFileOptions {
81
126
  utf8?: boolean;
@@ -94,6 +139,16 @@ export interface RenderOptions {
94
139
  export interface FFOpts {
95
140
  loggerOpts?: LoggerOptions;
96
141
  bodyLimit?: string;
142
+ /** Client IP resolution behind a proxy. Defaults to `"auto"`. */
143
+ proxy?: ProxyMode;
144
+ /** Body parser used when the request has no `Content-Type`. Defaults to `"json"`. */
145
+ defaultBodyParser?: "json" | false;
146
+ /** Enable parsing of YAML, TOML and JSON5 request bodies. Defaults to `false`. */
147
+ untrustedBodyParsers?: boolean;
148
+ /** Request body read timeout in milliseconds. Defaults to 60000. */
149
+ bodyTimeout?: number;
150
+ /** Debug panel. `true`/`false` or an options object. */
151
+ debug?: boolean | DebugOptions;
97
152
  disableParser?: {
98
153
  json?: boolean;
99
154
  urlencoded?: boolean;
package/dist/types.js CHANGED
@@ -6,7 +6,16 @@ export class FFRequest extends http.IncomingMessage {
6
6
  params;
7
7
  cookies;
8
8
  body;
9
+ /** Raw TCP peer address. */
10
+ socketIp;
11
+ /** Resolved client address (respects the `proxy` option). */
9
12
  ip;
13
+ /** True when proxy headers were used to resolve `ip`. */
14
+ isProxied;
15
+ /** Request protocol, respects `x-forwarded-proto` from a trusted proxy. */
16
+ protocol;
17
+ /** True when the request came over HTTPS, directly or via a trusted proxy. */
18
+ secure;
10
19
  header;
11
20
  valid;
12
21
  middleware;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wxn0brp/falcon-frame",
3
- "version": "0.9.8",
3
+ "version": "0.9.10",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "wxn0brP",