@wxn0brp/falcon-frame 0.9.7 → 0.9.9

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/index.js CHANGED
@@ -2,7 +2,9 @@ import { Logger } from "@wxn0brp/lucerna-log";
2
2
  import http from "http";
3
3
  import * as bodyParser from "./body.js";
4
4
  import { parseLimit } from "./body-utils.js";
5
+ import { resolveConfig, isDebugEnabled } from "./config.js";
5
6
  import { createCORS } from "./cors.js";
7
+ import { createDebug, generateDebugToken } from "./debug.js";
6
8
  import { renderHTML } from "./render.js";
7
9
  import { handleRequest } from "./req.js";
8
10
  import { FFResponse } from "./res.js";
@@ -12,7 +14,9 @@ export class FalconFrame extends Router {
12
14
  bodyParsers = {};
13
15
  vars = {};
14
16
  opts = {};
17
+ config;
15
18
  engines = {};
19
+ _debug;
16
20
  _400_formatter = err => {
17
21
  return {
18
22
  err: true,
@@ -26,6 +30,9 @@ export class FalconFrame extends Router {
26
30
  _413 = (req, res) => {
27
31
  res.end("413: Cat is too fat");
28
32
  };
33
+ _408 = (req, res) => {
34
+ res.end("408: The request took a nap");
35
+ };
29
36
  _500 = (err, req, res) => {
30
37
  res.end("500: The code had an existential crisis");
31
38
  };
@@ -40,13 +47,19 @@ export class FalconFrame extends Router {
40
47
  bodyLimit: "10m",
41
48
  ...opts,
42
49
  };
43
- const dp = this.opts.disableParser || {};
50
+ this.config = resolveConfig(this.opts);
51
+ const dp = this.config.disableParser || {};
44
52
  const isBun = !!globalThis.Bun;
45
53
  const bunOnly = new Set([
46
54
  "json5",
47
55
  "yaml",
48
56
  "toml",
49
57
  ]);
58
+ const untrusted = new Set([
59
+ "json5",
60
+ "yaml",
61
+ "toml",
62
+ ]);
50
63
  const parsers = {
51
64
  json: {
52
65
  fn: bodyParser.json,
@@ -76,6 +89,8 @@ export class FalconFrame extends Router {
76
89
  for (const [key, { fn, ct }] of Object.entries(parsers)) {
77
90
  if (dp[key])
78
91
  continue;
92
+ if (untrusted.has(key) && !this.config.untrustedBodyParsers)
93
+ continue;
79
94
  if (bunOnly.has(key) && !isBun)
80
95
  continue;
81
96
  this.addBodyParser(ct, fn);
@@ -97,7 +112,9 @@ export class FalconFrame extends Router {
97
112
  addBodyParser(contentType, parser, opts = {}) {
98
113
  this.bodyParsers[contentType] = {
99
114
  parse: parser,
100
- limit: parseLimit(opts.limit || this.opts.bodyLimit || "10m"),
115
+ limit: opts.limit !== undefined
116
+ ? parseLimit(opts.limit)
117
+ : this.config.bodyLimit,
101
118
  };
102
119
  return this;
103
120
  }
@@ -117,18 +134,50 @@ export class FalconFrame extends Router {
117
134
  else if (typeof port === "number") {
118
135
  parsedPort = port;
119
136
  }
137
+ let printUrl = false;
120
138
  if (typeof callback === "boolean") {
121
- if (callback)
122
- callback = () => {
123
- console.log(`[FF] Server running on http://${host || "localhost"}:${parsedPort}`);
124
- };
125
- else
126
- callback = () => { };
139
+ printUrl = callback;
140
+ callback = () => { };
127
141
  }
128
142
  const cb = callback || (() => { });
129
- server.listen(parsedPort, host || "0.0.0.0", cb);
143
+ server.listen(parsedPort, host || "0.0.0.0", () => {
144
+ const address = server.address();
145
+ const actualPort = address && typeof address === "object" ? address.port : parsedPort;
146
+ if (printUrl) {
147
+ console.log(`[FF] Server running on http://${host || "localhost"}:${actualPort}`);
148
+ }
149
+ if (this._debug && isDebugEnabled(this._debug.enabled)) {
150
+ const urlHost = host && host !== "0.0.0.0" && host !== "::" ? host : "localhost";
151
+ const token = this._debug.generated ? `?pass=${this._debug.pass}` : "";
152
+ console.log(`[FF] Debug panel: http://${urlHost}:${actualPort}${this._debug.path}${token}`);
153
+ }
154
+ cb();
155
+ });
130
156
  return server;
131
157
  }
158
+ /**
159
+ * Mount the debug panel. Without an explicit `pass` a random token is
160
+ * generated and printed together with the URL on `listen()`.
161
+ */
162
+ debug(opts = {}) {
163
+ const resolved = this.config.debug;
164
+ const path = opts.path ?? opts.url ?? resolved.path;
165
+ const explicitPass = opts.pass ?? resolved.pass ?? process.env.FF_DEBUG_PASS;
166
+ const pass = explicitPass ?? generateDebugToken();
167
+ const enabled = opts.enabled ?? resolved.enabled;
168
+ this._debug = {
169
+ path,
170
+ pass,
171
+ generated: !explicitPass,
172
+ enabled,
173
+ };
174
+ this.use(createDebug({
175
+ ...opts,
176
+ path,
177
+ pass,
178
+ }, resolved));
179
+ return this;
180
+ }
132
181
  getApp(beforeHandleRequest) {
133
182
  return async (req, res) => {
134
183
  if (beforeHandleRequest) {
@@ -187,6 +236,9 @@ export class FalconFrame extends Router {
187
236
  set413(handler) {
188
237
  this._413 = handler;
189
238
  }
239
+ set408(handler) {
240
+ this._408 = handler;
241
+ }
190
242
  set500(handler) {
191
243
  this._500 = handler;
192
244
  }
@@ -194,5 +246,7 @@ export class FalconFrame extends Router {
194
246
  export default FalconFrame;
195
247
  export { OfflineEngine } from "./engine.js";
196
248
  export * as Helpers from "./helpers.js";
249
+ export { compression, compressionMiddleware } from "./compress.js";
250
+ export { createDebug, generateDebugToken } from "./debug.js";
197
251
  export { validateBody } from "./valid.js";
198
252
  export { FFResponse, renderHTML, Router, };
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,10 @@ 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;
34
37
  req.params = {};
35
38
  req.valid = (schema, regexRules) => validate({
36
39
  schema,
@@ -44,17 +47,18 @@ export function handleRequest(req, res, FF, reRoute = false) {
44
47
  };
45
48
  req.header = (name) => req.headers[name.toLowerCase()] || "";
46
49
  req.isBodyParsed = false;
47
- if (FF.opts.xRequestId !== "disable") {
50
+ if (FF.config.xRequestId !== "disable") {
48
51
  if (req.headers["x-request-id"]) {
49
52
  req.id = req.headers["x-request-id"];
50
53
  res.setHeader("x-request-id", req.id);
51
54
  }
52
- else if (FF.opts.xRequestId === "auto") {
55
+ else if (FF.config.xRequestId === "auto") {
53
56
  req.id = randomUUID();
54
57
  res.setHeader("x-request-id", req.id);
55
58
  }
56
59
  }
57
- logger.info(`Incoming request: ${req.method} ${req.url}` +
60
+ const logUrl = (req.url || "").replace(/([?&]pass=)[^&]*/i, "$1***");
61
+ logger.info(`Incoming request: ${req.method} ${logUrl}` +
58
62
  (req.id ? ` [${req.id}]` : ""));
59
63
  const middlewaresPath = req.path + "/";
60
64
  const middlewares = getMiddlewares(FF.middlewares, middlewaresPath.replace(/\/+/g, "/"));
@@ -121,15 +125,23 @@ export function handleRequest(req, res, FF, reRoute = false) {
121
125
  return;
122
126
  }
123
127
  req.body = {};
124
- const ct = getContentType(req) || "application/json";
125
- const entry = FF.bodyParsers[ct];
128
+ const ct = getContentType(req);
129
+ let entry = ct ? FF.bodyParsers[ct] : undefined;
130
+ if (!ct && FF.config.defaultBodyParser === "json") {
131
+ entry = FF.bodyParsers["application/json"];
132
+ }
126
133
  if (!entry) {
127
- logger.debug("No body parser found for content-type. Executing middlewares");
134
+ if (ct) {
135
+ logger.debug(`No body parser found for content-type ${ct}. Executing middlewares`);
136
+ }
137
+ else {
138
+ logger.debug("No content-type. Executing middlewares");
139
+ }
128
140
  next();
129
141
  return;
130
142
  }
131
- logger.debug(`Executing body parser for content-type: ${ct}`);
132
- getRawBody(req, res, entry.limit)
143
+ logger.debug(`Executing body parser for content-type: ${ct ?? "default (json)"}`);
144
+ getRawBody(req, res, entry.limit, FF.config.bodyTimeout)
133
145
  .then(async (rawBody) => {
134
146
  try {
135
147
  req.body = (await entry.parse(rawBody, req, res)) ?? {};
@@ -141,10 +153,17 @@ export function handleRequest(req, res, FF, reRoute = false) {
141
153
  }
142
154
  next();
143
155
  })
144
- .catch(() => {
145
- if (!res._ended) {
146
- req.body = {};
147
- next();
156
+ .catch((err) => {
157
+ if (res._ended)
158
+ return;
159
+ if (err?.statusCode === 408) {
160
+ res.status(408);
161
+ res.FF._408(req, res);
162
+ if (!res.writableEnded)
163
+ res.end();
164
+ return;
148
165
  }
166
+ req.body = {};
167
+ next();
149
168
  });
150
169
  }
package/dist/res.js CHANGED
@@ -1,7 +1,7 @@
1
- import { createReadStream } from "fs";
2
1
  import http from "http";
3
2
  import path from "path";
4
- import { ensureLeadingDot, getContentType } from "./helpers.js";
3
+ import { getContentType } from "./encoding.js";
4
+ import { ensureLeadingDot, streamFile } from "./helpers.js";
5
5
  export class FFResponse extends http.ServerResponse {
6
6
  _ended = false;
7
7
  FF;
@@ -98,9 +98,9 @@ export class FFResponse extends http.ServerResponse {
98
98
  */
99
99
  sendFile(filePath, contentType) {
100
100
  if (contentType === "utf8")
101
- contentType = getContentType(filePath);
101
+ contentType = getContentType(filePath, true);
102
102
  this.ct(contentType || getContentType(filePath));
103
- createReadStream(filePath).pipe(this);
103
+ streamFile(this, filePath);
104
104
  this._ended = true;
105
105
  return this;
106
106
  }
@@ -167,6 +167,7 @@ export class FFResponse extends http.ServerResponse {
167
167
  this.setHeader("Content-Type", "text/event-stream");
168
168
  this.setHeader("Cache-Control", "no-cache");
169
169
  this.setHeader("Connection", "keep-alive");
170
+ this.flushHeaders();
170
171
  return this;
171
172
  }
172
173
  /**
package/dist/static.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
- import { ensureLeadingDot, getContentType } from "./helpers.js";
3
+ import { ensureLeadingDot, streamFile } from "./helpers.js";
4
+ import { getContentType } from "./encoding.js";
4
5
  export function handleSingleFile(filePath, opts) {
5
6
  opts = {
6
7
  utf8: true,
@@ -31,12 +32,12 @@ export function handleSingleFile(filePath, opts) {
31
32
  res.setHeader("ETag", etag);
32
33
  }
33
34
  res.ct(getContentType(filePath, opts.utf8));
35
+ res.setHeader("Content-Length", stats.size);
34
36
  if (req.method === "HEAD") {
35
- res.setHeader("Content-Length", stats.size);
36
37
  res.end();
37
38
  return;
38
39
  }
39
- fs.createReadStream(filePath).pipe(res);
40
+ streamFile(res, filePath);
40
41
  };
41
42
  }
42
43
  export function handleStaticFiles(dirPath, opts) {
@@ -76,12 +77,12 @@ export function handleStaticFiles(dirPath, opts) {
76
77
  res.setHeader("ETag", etag);
77
78
  }
78
79
  res.ct(getContentType(filePath, opts.utf8));
80
+ res.setHeader("Content-Length", stats.size);
79
81
  if (req.method === "HEAD") {
80
- res.setHeader("Content-Length", stats.size);
81
82
  res.end();
82
83
  return true;
83
84
  }
84
- fs.createReadStream(filePath).pipe(res);
85
+ streamFile(res, filePath);
85
86
  return true;
86
87
  };
87
88
  return (req, res, next) => {
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,12 @@ 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;
37
76
  header: (name: string) => string;
38
77
  valid: (schema: ValidationSchema, regexRules?: Record<string, RegExp | string>) => ValidationResult;
39
78
  middleware: Middleware;
@@ -94,6 +133,16 @@ export interface RenderOptions {
94
133
  export interface FFOpts {
95
134
  loggerOpts?: LoggerOptions;
96
135
  bodyLimit?: string;
136
+ /** Client IP resolution behind a proxy. Defaults to `"auto"`. */
137
+ proxy?: ProxyMode;
138
+ /** Body parser used when the request has no `Content-Type`. Defaults to `"json"`. */
139
+ defaultBodyParser?: "json" | false;
140
+ /** Enable parsing of YAML, TOML and JSON5 request bodies. Defaults to `false`. */
141
+ untrustedBodyParsers?: boolean;
142
+ /** Request body read timeout in milliseconds. Defaults to 60000. */
143
+ bodyTimeout?: number;
144
+ /** Debug panel. `true`/`false` or an options object. */
145
+ debug?: boolean | DebugOptions;
97
146
  disableParser?: {
98
147
  json?: boolean;
99
148
  urlencoded?: boolean;
package/dist/types.js CHANGED
@@ -6,7 +6,12 @@ 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;
10
15
  header;
11
16
  valid;
12
17
  middleware;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wxn0brp/falcon-frame",
3
- "version": "0.9.7",
3
+ "version": "0.9.9",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "wxn0brP",