@wxn0brp/falcon-frame 0.9.8 → 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/README.md CHANGED
@@ -10,6 +10,10 @@ A minimal, modular TypeScript web library.
10
10
  - Request validation via inline schemas
11
11
  - Cookie management
12
12
  - Debuggable logger
13
+ - Debug panel
14
+ - Proxy-aware client IP resolution
15
+ - Body limits and read timeouts
16
+ - Compression middleware
13
17
 
14
18
  ## Installation
15
19
 
@@ -23,6 +27,7 @@ bun add @wxn0brp/falcon-frame
23
27
  import FalconFrame, { validateBody } from "@wxn0brp/falcon-frame";
24
28
  const app = new FalconFrame();
25
29
 
30
+ app.debug();
26
31
  app.setOrigin("*");
27
32
 
28
33
  const USERS = {
@@ -2,4 +2,4 @@ import { FFResponse } from "./res.js";
2
2
  import type { FFRequest } from "./types.js";
3
3
  export declare function parseLimit(limit: string | number): number;
4
4
  export declare function getContentType(req: FFRequest): string | undefined;
5
- export declare function getRawBody(req: FFRequest, res: FFResponse, limit: number): Promise<string>;
5
+ export declare function getRawBody(req: FFRequest, res: FFResponse, limit: number, timeout?: number): Promise<string>;
@@ -27,26 +27,51 @@ export function parseLimit(limit) {
27
27
  export function getContentType(req) {
28
28
  return req.headers["content-type"]?.split(";")[0].toLowerCase();
29
29
  }
30
- export function getRawBody(req, res, limit) {
30
+ export function getRawBody(req, res, limit, timeout = 60_000) {
31
31
  return new Promise((resolve, reject) => {
32
32
  const chunks = [];
33
33
  let total = 0;
34
+ let settled = false;
35
+ const timer = setTimeout(() => {
36
+ if (settled)
37
+ return;
38
+ settled = true;
39
+ res.status(408);
40
+ res.setHeader("Connection", "close");
41
+ res.FF._408(req, res);
42
+ if (!res.writableEnded)
43
+ res.end();
44
+ res.once("finish", () => req.destroy());
45
+ reject(Object.assign(new Error("Request body timeout"), {
46
+ statusCode: 408,
47
+ }));
48
+ }, timeout);
49
+ const finish = (fn) => {
50
+ if (settled)
51
+ return;
52
+ settled = true;
53
+ clearTimeout(timer);
54
+ fn();
55
+ };
34
56
  req.on("data", chunk => {
57
+ if (settled)
58
+ return;
35
59
  const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
36
60
  total += buf.length;
37
61
  if (limit && total > limit) {
38
62
  res.status(413);
39
63
  res.FF._413(req, res);
64
+ finish(() => reject(new Error("Payload Too Large")));
40
65
  req.destroy();
41
- return reject(new Error("Payload Too Large"));
66
+ return;
42
67
  }
43
68
  chunks.push(buf);
44
69
  });
45
70
  req.on("end", () => {
46
- resolve(Buffer.concat(chunks).toString());
71
+ finish(() => resolve(Buffer.concat(chunks).toString()));
47
72
  });
48
73
  req.on("error", err => {
49
- reject(err);
74
+ finish(() => reject(err));
50
75
  });
51
76
  });
52
77
  }
@@ -1,4 +1,4 @@
1
1
  import { FFResponse } from "./res.js";
2
- import { FFRequest, RouteHandler } from "./types.js";
3
- export declare function compression(req: FFRequest, res: FFResponse): void;
2
+ import { CompressionOptions, FFRequest, RouteHandler } from "./types.js";
3
+ export declare function compression(req: FFRequest, res: FFResponse, opts?: CompressionOptions): void;
4
4
  export declare const compressionMiddleware: RouteHandler;
package/dist/compress.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createBrotliCompress, createDeflate, createGzip } from "zlib";
1
+ import { constants as zlibConstants, createBrotliCompress, createDeflate, createGzip, } from "zlib";
2
2
  function isCompressible(contentType) {
3
3
  if (!contentType)
4
4
  return true;
@@ -7,47 +7,130 @@ function isCompressible(contentType) {
7
7
  return false;
8
8
  if (/^(video|audio)\//.test(type))
9
9
  return false;
10
+ if (/^font\//.test(type))
11
+ return false;
10
12
  if (type === "text/event-stream")
11
13
  return false;
14
+ if (type === "application/octet-stream" || type === "application/pdf")
15
+ return false;
12
16
  if (/^application\/(zip|gzip|x-gzip|x-bzip|x-bzip2|x-xz|x-rar|x-7z|x-tar|x-compress|wasm)$/.test(type))
13
17
  return false;
14
18
  return true;
15
19
  }
16
- export function compression(req, res) {
17
- if (req._compression)
18
- return;
19
- req._compression = true;
20
- const encoding = req.headers["accept-encoding"];
21
- if (!encoding || typeof encoding !== "string" || res.headersSent) {
22
- return;
23
- }
24
- let createCompressor;
25
- let encodingType;
26
- if (/\bbr\b/.test(encoding)) {
27
- encodingType = "br";
28
- createCompressor = createBrotliCompress;
20
+ const preference = {
21
+ br: 0,
22
+ gzip: 1,
23
+ deflate: 2,
24
+ };
25
+ function pickEncoding(header) {
26
+ if (typeof header !== "string" || !header)
27
+ return null;
28
+ const encodings = new Map();
29
+ let wildcardQ = -1;
30
+ for (const part of header.split(",")) {
31
+ const [rawName, ...params] = part.trim().split(";");
32
+ const name = rawName.trim().toLowerCase();
33
+ let q = 1;
34
+ for (const param of params) {
35
+ const [key, value] = param.trim().split("=");
36
+ if (key?.toLowerCase() === "q") {
37
+ const parsed = Number.parseFloat(value);
38
+ q = Number.isNaN(parsed) ? 0 : parsed;
39
+ }
40
+ }
41
+ if (name === "*") {
42
+ wildcardQ = q;
43
+ }
44
+ else if (name === "br" || name === "gzip" || name === "deflate") {
45
+ encodings.set(name, q);
46
+ }
29
47
  }
30
- else if (/\bgzip\b/.test(encoding)) {
31
- encodingType = "gzip";
32
- createCompressor = createGzip;
48
+ if (wildcardQ >= 0) {
49
+ if (!encodings.has("br"))
50
+ encodings.set("br", wildcardQ);
51
+ if (!encodings.has("gzip"))
52
+ encodings.set("gzip", wildcardQ);
53
+ if (!encodings.has("deflate"))
54
+ encodings.set("deflate", wildcardQ);
33
55
  }
34
- else if (/\bdeflate\b/.test(encoding)) {
35
- encodingType = "deflate";
36
- createCompressor = createDeflate;
56
+ let best = null;
57
+ let bestQ = 0;
58
+ let bestRank = Number.POSITIVE_INFINITY;
59
+ for (const [name, q] of encodings) {
60
+ if (q <= 0)
61
+ continue;
62
+ const rank = preference[name];
63
+ if (q > bestQ || (q === bestQ && rank < bestRank)) {
64
+ best = name;
65
+ bestQ = q;
66
+ bestRank = rank;
67
+ }
37
68
  }
38
- else {
69
+ return best;
70
+ }
71
+ function appendVary(res, value) {
72
+ const current = res.getHeader("vary");
73
+ if (!current) {
74
+ res.setHeader("vary", value);
39
75
  return;
40
76
  }
77
+ const values = String(current)
78
+ .split(",")
79
+ .map(item => item.trim().toLowerCase());
80
+ if (!values.includes(value.toLowerCase())) {
81
+ res.setHeader("vary", `${current}, ${value}`);
82
+ }
83
+ }
84
+ export function compression(req, res, opts = {}) {
85
+ if (req._compression)
86
+ return;
87
+ req._compression = true;
88
+ if (res.headersSent)
89
+ return;
90
+ const threshold = opts.threshold ?? 1024;
91
+ const cacheControl = String(res.getHeader("cache-control") || "").toLowerCase();
92
+ if (cacheControl.includes("no-transform"))
93
+ return;
94
+ const encodingType = pickEncoding(req.headers["accept-encoding"]);
95
+ if (!encodingType)
96
+ return;
97
+ appendVary(res, "Accept-Encoding");
98
+ const createCompressor = () => {
99
+ if (encodingType === "br") {
100
+ return createBrotliCompress({
101
+ params: {
102
+ [zlibConstants.BROTLI_PARAM_QUALITY]: opts.brotliQuality ?? 4,
103
+ },
104
+ });
105
+ }
106
+ const level = opts.gzipLevel ?? 6;
107
+ return encodingType === "gzip"
108
+ ? createGzip({
109
+ level,
110
+ })
111
+ : createDeflate({
112
+ level,
113
+ });
114
+ };
41
115
  const originalWrite = res.write;
42
116
  const originalEnd = res.end;
43
117
  let compressionStream = null;
44
118
  let initialized = false;
45
- function init() {
119
+ const usable = () => {
120
+ if (res.statusCode === 204 || res.statusCode === 304)
121
+ return false;
122
+ if (!isCompressible(String(res.getHeader("content-type") || "")))
123
+ return false;
124
+ const length = res.getHeader("content-length");
125
+ if (length !== undefined && Number(length) < threshold)
126
+ return false;
127
+ return true;
128
+ };
129
+ const init = () => {
46
130
  if (initialized)
47
131
  return compressionStream !== null;
48
132
  initialized = true;
49
- const contentType = res.getHeader("content-type");
50
- if (!isCompressible(contentType))
133
+ if (!usable())
51
134
  return false;
52
135
  compressionStream = createCompressor();
53
136
  res.setHeader("Content-Encoding", encodingType);
@@ -59,19 +142,26 @@ export function compression(req, res) {
59
142
  originalEnd.call(res);
60
143
  });
61
144
  compressionStream.on("error", err => {
62
- if (!res.headersSent) {
63
- res.statusCode = 500;
64
- originalEnd.call(res);
65
- }
66
- else {
145
+ res.write = originalWrite;
146
+ res.end = originalEnd;
147
+ if (res.headersSent) {
67
148
  res.destroy(err);
149
+ return;
68
150
  }
151
+ res.status(500);
152
+ res.FF._500(err, req, res);
153
+ if (!res.writableEnded)
154
+ res.end();
69
155
  });
70
156
  res.on("close", () => {
71
- compressionStream.destroy();
157
+ compressionStream?.destroy();
72
158
  });
73
159
  return true;
74
- }
160
+ };
161
+ const restore = () => {
162
+ res.write = originalWrite;
163
+ res.end = originalEnd;
164
+ };
75
165
  // @ts-ignore
76
166
  res.write = (...args) => {
77
167
  const [chunk, encoding, cb] = args;
@@ -79,13 +169,16 @@ export function compression(req, res) {
79
169
  const enc = typeof encoding === "function" ? undefined : encoding;
80
170
  if (!res.headersSent) {
81
171
  if (!init()) {
82
- res.write = originalWrite;
83
- res.end = originalEnd;
172
+ restore();
84
173
  res.writeHead(res.statusCode);
85
174
  return originalWrite.call(res, chunk, enc, callback);
86
175
  }
87
176
  res.writeHead(res.statusCode);
88
177
  }
178
+ if (!compressionStream) {
179
+ restore();
180
+ return originalWrite.call(res, chunk, enc, callback);
181
+ }
89
182
  return compressionStream.write(chunk, enc, callback);
90
183
  };
91
184
  // @ts-ignore
@@ -104,21 +197,47 @@ export function compression(req, res) {
104
197
  finalCb = encoding;
105
198
  finalEncoding = undefined;
106
199
  }
200
+ // Single-shot response: honour the threshold before compressing.
201
+ if (!res.headersSent && !initialized && finalChunk !== undefined) {
202
+ const buffer = Buffer.isBuffer(finalChunk)
203
+ ? finalChunk
204
+ : Buffer.from(finalChunk, finalEncoding);
205
+ const length = res.getHeader("content-length");
206
+ const tooSmall = buffer.length < threshold &&
207
+ (length === undefined || Number(length) < threshold);
208
+ if (tooSmall || !init()) {
209
+ restore();
210
+ if (finalCb)
211
+ res.once("finish", finalCb);
212
+ return originalEnd.call(res, buffer, finalEncoding);
213
+ }
214
+ if (finalCb)
215
+ res.once("finish", finalCb);
216
+ res.writeHead(res.statusCode);
217
+ compressionStream.write(buffer);
218
+ compressionStream.end();
219
+ return res;
220
+ }
107
221
  if (!res.headersSent) {
108
222
  if (!init()) {
109
- res.write = originalWrite;
110
- res.end = originalEnd;
223
+ restore();
111
224
  if (finalCb)
112
225
  res.once("finish", finalCb);
113
- if (finalChunk)
226
+ if (finalChunk !== undefined) {
114
227
  originalWrite.call(res, finalChunk, finalEncoding);
228
+ }
115
229
  originalEnd.call(res);
116
230
  return res;
117
231
  }
232
+ res.writeHead(res.statusCode);
118
233
  }
119
234
  if (finalCb)
120
235
  res.once("finish", finalCb);
121
- if (finalChunk) {
236
+ if (!compressionStream) {
237
+ restore();
238
+ return originalEnd.call(res, finalChunk, finalEncoding);
239
+ }
240
+ if (finalChunk !== undefined) {
122
241
  res.write(finalChunk, finalEncoding);
123
242
  }
124
243
  compressionStream.end();
@@ -0,0 +1,20 @@
1
+ import type { FFOpts, ProxyMode } from "./types.js";
2
+ export interface ResolvedDebugConfig {
3
+ enabled?: boolean;
4
+ pass?: string;
5
+ path: string;
6
+ rateLimit: boolean;
7
+ hosts: string[];
8
+ }
9
+ export interface ResolvedConfig {
10
+ proxy: ProxyMode;
11
+ bodyLimit: number;
12
+ bodyTimeout: number;
13
+ defaultBodyParser: "json" | false;
14
+ untrustedBodyParsers: boolean;
15
+ xRequestId?: "auto" | "disable" | "manual";
16
+ disableParser: FFOpts["disableParser"];
17
+ debug: ResolvedDebugConfig;
18
+ }
19
+ export declare function isDebugEnabled(enabled: boolean | undefined): boolean;
20
+ export declare function resolveConfig(opts?: FFOpts): ResolvedConfig;
package/dist/config.js ADDED
@@ -0,0 +1,28 @@
1
+ import { parseLimit } from "./body-utils.js";
2
+ export function isDebugEnabled(enabled) {
3
+ if (enabled !== undefined)
4
+ return enabled;
5
+ return !(process.env.NODE_ENV === "production" &&
6
+ !process.env.FF_DEBUG_PRODUCTION_ENABLED);
7
+ }
8
+ export function resolveConfig(opts = {}) {
9
+ const debugOption = opts.debug;
10
+ const debug = typeof debugOption === "object" && debugOption !== null ? debugOption : {};
11
+ const enabled = debugOption === false ? false : debugOption === true ? true : debug.enabled;
12
+ return {
13
+ proxy: opts.proxy ?? "auto",
14
+ bodyLimit: parseLimit(opts.bodyLimit ?? "10m"),
15
+ bodyTimeout: opts.bodyTimeout ?? 60_000,
16
+ defaultBodyParser: opts.defaultBodyParser ?? "json",
17
+ untrustedBodyParsers: opts.untrustedBodyParsers ?? false,
18
+ xRequestId: opts.xRequestId,
19
+ disableParser: opts.disableParser,
20
+ debug: {
21
+ enabled,
22
+ pass: debug.pass ?? process.env.FF_DEBUG_PASS,
23
+ path: debug.path ?? debug.url ?? "/debug",
24
+ rateLimit: debug.rateLimit ?? true,
25
+ hosts: debug.hosts ?? [],
26
+ },
27
+ };
28
+ }
package/dist/debug.d.ts CHANGED
@@ -1,9 +1,5 @@
1
1
  import { Router } from "./router.js";
2
- import { RouteHandler } from "./types.js";
3
- export interface DebugOptions {
4
- url?: string;
5
- hosts?: string[];
6
- /** @deprecated */
7
- logs?: boolean;
8
- }
9
- export declare function createDebug(opts?: DebugOptions): Router | RouteHandler;
2
+ import type { DebugOptions } from "./types.js";
3
+ export type { DebugOptions };
4
+ export declare function generateDebugToken(): string;
5
+ export declare function createDebug(opts?: DebugOptions, preset?: DebugOptions): Router;
package/dist/debug.js CHANGED
@@ -1,56 +1,224 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
1
2
  import { join } from "path";
3
+ import { isDebugEnabled } from "./config.js";
4
+ import { isLoopback, normalizeIp } from "./helpers.js";
2
5
  import { Router } from "./router.js";
3
- export function createDebug(opts = {}) {
4
- const { url = "/debug", hosts = [
5
- "localhost",
6
- "127.0.0.1",
7
- "::1",
8
- ], } = opts;
9
- if (process.env.NODE_ENV === "production" &&
10
- !process.env.FF_DEBUG_PRODUCTION_ENABLED)
11
- return (req, res, next) => {
12
- next();
13
- };
14
- const pass = process.env.FF_DEBUG_PASS;
15
- function isHostAllowed(req) {
16
- const ip = req.ip || req.socket.remoteAddress || "";
17
- return hosts.some(h => h === ip);
6
+ const COOKIE_NAME = "ff_debug";
7
+ const SESSION_TTL = 8 * 60 * 60 * 1000;
8
+ const RATE_WINDOW = 15 * 60 * 1000;
9
+ const RATE_MAX_FAILURES = 5;
10
+ const sessions = new Map();
11
+ const failures = new Map();
12
+ let sweepTimer = null;
13
+ const SWEEP_INTERVAL = 5 * 60 * 1000; // 5 minutes
14
+ function startSweep() {
15
+ if (sweepTimer !== null)
16
+ return;
17
+ sweepTimer = setInterval(() => {
18
+ const now = Date.now();
19
+ for (const [sid, expires] of sessions) {
20
+ if (expires < now)
21
+ sessions.delete(sid);
22
+ }
23
+ for (const [ip, times] of failures) {
24
+ const recent = times.filter(time => now - time < RATE_WINDOW);
25
+ if (recent.length)
26
+ failures.set(ip, recent);
27
+ else
28
+ failures.delete(ip);
29
+ }
30
+ if (sessions.size === 0 && failures.size === 0) {
31
+ if (sweepTimer !== null) {
32
+ clearInterval(sweepTimer);
33
+ sweepTimer = null;
34
+ }
35
+ }
36
+ }, SWEEP_INTERVAL);
37
+ sweepTimer.unref();
38
+ }
39
+ export function generateDebugToken() {
40
+ return randomBytes(24).toString("base64url");
41
+ }
42
+ function hash(value) {
43
+ return createHash("sha256").update(value).digest();
44
+ }
45
+ function sameSecret(given, expected) {
46
+ if (!given)
47
+ return false;
48
+ return timingSafeEqual(hash(given), hash(expected));
49
+ }
50
+ function isSecure(req) {
51
+ if (req.socket?.encrypted)
52
+ return true;
53
+ return req.headers["x-forwarded-proto"] === "https";
54
+ }
55
+ function providedToken(req) {
56
+ const header = req.headers.authorization;
57
+ if (typeof header === "string" && header.startsWith("Bearer ")) {
58
+ return header.slice(7);
59
+ }
60
+ const query = req.query?.pass;
61
+ return typeof query === "string" ? query : "";
62
+ }
63
+ function tokenSource(req) {
64
+ const header = req.headers.authorization;
65
+ if (typeof header === "string" && header.startsWith("Bearer ")) {
66
+ return header.length > 7 ? "header" : null;
18
67
  }
19
- function checkAuth(req) {
20
- if (!pass)
21
- return true;
22
- return req.query?.pass === pass;
68
+ const query = req.query?.pass;
69
+ return typeof query === "string" && query ? "query" : null;
70
+ }
71
+ function createSession() {
72
+ const sid = randomBytes(24).toString("base64url");
73
+ sessions.set(sid, Date.now() + SESSION_TTL);
74
+ startSweep();
75
+ return sid;
76
+ }
77
+ function hasSession(req) {
78
+ const sid = req.cookies?.[COOKIE_NAME];
79
+ if (!sid)
80
+ return false;
81
+ const expires = sessions.get(sid);
82
+ if (expires === undefined)
83
+ return false;
84
+ if (expires < Date.now()) {
85
+ sessions.delete(sid);
86
+ return false;
23
87
  }
24
- function isAllowed(req) {
25
- return isHostAllowed(req) && checkAuth(req);
88
+ return true;
89
+ }
90
+ function throttled(ip) {
91
+ const now = Date.now();
92
+ const recent = (failures.get(ip) || []).filter(time => now - time < RATE_WINDOW);
93
+ if (recent.length)
94
+ failures.set(ip, recent);
95
+ else
96
+ failures.delete(ip);
97
+ return recent.length >= RATE_MAX_FAILURES;
98
+ }
99
+ function recordFailure(ip) {
100
+ const now = Date.now();
101
+ const recent = (failures.get(ip) || []).filter(time => now - time < RATE_WINDOW);
102
+ recent.push(now);
103
+ failures.set(ip, recent);
104
+ startSweep();
105
+ }
106
+ function hostAllowed(hosts, ip) {
107
+ const target = normalizeIp(ip);
108
+ return hosts.some(host => {
109
+ if (host === "localhost")
110
+ return isLoopback(target);
111
+ return normalizeIp(host) === target;
112
+ });
113
+ }
114
+ function notFound(req, res) {
115
+ res.status(404);
116
+ req.FF._404(req, res);
117
+ }
118
+ function attempt(req, config) {
119
+ if (!config.enabled)
120
+ return "disabled";
121
+ const ip = normalizeIp(req.ip || req.socket.remoteAddress || "");
122
+ if (config.hosts.length && !hostAllowed(config.hosts, ip))
123
+ return "denied";
124
+ if (hasSession(req))
125
+ return "session";
126
+ if (config.rateLimit && throttled(ip))
127
+ return "denied";
128
+ if (sameSecret(providedToken(req), config.pass))
129
+ return "token";
130
+ if (config.rateLimit)
131
+ recordFailure(ip);
132
+ return "denied";
133
+ }
134
+ function grantSession(req, res, config) {
135
+ if (hasSession(req))
136
+ return;
137
+ res.cookie(COOKIE_NAME, createSession(), {
138
+ httpOnly: true,
139
+ sameSite: "Strict",
140
+ secure: isSecure(req),
141
+ path: config.path,
142
+ maxAge: SESSION_TTL / 1000,
143
+ });
144
+ }
145
+ export function createDebug(opts = {}, preset = {}) {
146
+ const config = {
147
+ ...preset,
148
+ ...opts,
149
+ };
150
+ const path = config.path ?? config.url ?? "/debug";
151
+ const staticPass = config.pass ?? process.env.FF_DEBUG_PASS;
152
+ const generatedPass = generateDebugToken();
153
+ if (!staticPass && isDebugEnabled(config.enabled)) {
154
+ console.log(`[FF] Debug endpoint: ${path}?pass=${generatedPass}`);
26
155
  }
156
+ const effective = (req) => {
157
+ const app = req.FF?.config?.debug ?? {};
158
+ return {
159
+ enabled: isDebugEnabled(config.enabled ?? app.enabled),
160
+ pass: staticPass ?? generatedPass,
161
+ path,
162
+ rateLimit: config.rateLimit ?? app.rateLimit ?? true,
163
+ hosts: config.hosts ?? app.hosts ?? [],
164
+ };
165
+ };
27
166
  const router = new Router();
28
- router.get(url, (req, res) => {
29
- if (!isAllowed(req))
30
- return req.FF._404(req, res);
167
+ router.get(path, (req, res, next) => {
168
+ const settings = effective(req);
169
+ const result = attempt(req, settings);
170
+ if (result === "disabled")
171
+ return next();
172
+ if (result === "denied")
173
+ return notFound(req, res);
174
+ if (result === "token") {
175
+ grantSession(req, res, settings);
176
+ if (tokenSource(req) === "query")
177
+ return res.redirect(path);
178
+ return res.sendFile(join(import.meta.dirname, "debug.html"));
179
+ }
31
180
  res.sendFile(join(import.meta.dirname, "debug.html"));
32
181
  });
33
- const sse = router.sse(url + "/sse", (req, res, next) => {
34
- if (!isAllowed(req))
35
- return req.FF._404(req, res);
182
+ const sse = router.sse(`${path}/sse`, (req, res, next) => {
183
+ const settings = effective(req);
184
+ const result = attempt(req, settings);
185
+ if (result === "disabled")
186
+ return next();
187
+ if (result === "denied")
188
+ return notFound(req, res);
189
+ if (result === "token")
190
+ grantSession(req, res, settings);
36
191
  next();
37
192
  }, () => { });
38
193
  router.use("/", (req, res, next) => {
194
+ if (!effective(req).enabled)
195
+ return next();
39
196
  const start = Date.now();
40
197
  const hook = res.end.bind(res);
41
198
  res.end = (...args) => {
42
- const entry = {
43
- method: req.method,
44
- url: req.url,
45
- headers: req.headers,
46
- query: req.query || {},
47
- cookies: req.cookies || {},
48
- body: req.body || {},
49
- status: res.statusCode,
50
- duration: Date.now() - start,
51
- time: new Date().toISOString(),
52
- };
53
- sse.sendAll(entry);
199
+ const contentType = String(res.getHeader("content-type") || "");
200
+ const binary = /^(image|video|audio|font)\//i.test(contentType) ||
201
+ /octet-stream/i.test(contentType);
202
+ const debugRequest = req.path === path || req.path?.startsWith(`${path}/`);
203
+ if (!binary && !debugRequest) {
204
+ const entry = {
205
+ method: req.method,
206
+ url: (req.url || "").replace(/([?&]pass=)[^&]*/i, "$1***"),
207
+ headers: req.headers,
208
+ query: req.query || {},
209
+ cookies: req.cookies || {},
210
+ body: req.body || {},
211
+ status: res.statusCode,
212
+ duration: Date.now() - start,
213
+ time: new Date().toISOString(),
214
+ };
215
+ try {
216
+ sse.sendAll(entry);
217
+ }
218
+ catch {
219
+ /* a disconnected debug client must not break the app */
220
+ }
221
+ }
54
222
  return hook(...args);
55
223
  };
56
224
  next();
package/dist/helpers.d.ts CHANGED
@@ -1,5 +1,14 @@
1
- import { Cookies, FFRequest } from "./types.js";
1
+ import type { FFResponse } from "./res.js";
2
+ import { Cookies, FFRequest, ProxyMode } from "./types.js";
2
3
  export { getContentType } from "./encoding.js";
3
4
  export declare function parseCookies(cookieHeader: string): Cookies;
4
- export declare function getIP(req: FFRequest): string;
5
+ export declare function normalizeIp(ip: string): string;
6
+ export declare function isLoopback(ip: string): boolean;
7
+ export declare function resolveRequestInfo(req: FFRequest, proxy?: ProxyMode): {
8
+ socketIp: string;
9
+ ip: string;
10
+ isProxied: boolean;
11
+ };
12
+ export declare function getIP(req: FFRequest, proxy?: ProxyMode): string;
13
+ export declare function streamFile(res: FFResponse, filePath: string): void;
5
14
  export declare const ensureLeadingDot: (str: string) => string;
package/dist/helpers.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createReadStream } from "fs";
1
2
  export { getContentType } from "./encoding.js";
2
3
  export function parseCookies(cookieHeader) {
3
4
  const cookies = Object.create(null);
@@ -8,13 +9,72 @@ export function parseCookies(cookieHeader) {
8
9
  });
9
10
  return cookies;
10
11
  }
11
- export function getIP(req) {
12
+ export function normalizeIp(ip) {
13
+ const trimmed = ip.trim();
14
+ return trimmed.startsWith("::ffff:") ? trimmed.slice(7) : trimmed;
15
+ }
16
+ export function isLoopback(ip) {
17
+ const value = normalizeIp(ip);
18
+ return value === "::1" || value.startsWith("127.");
19
+ }
20
+ function forwardedIp(req) {
21
+ const cf = req.headers["cf-connecting-ip"];
22
+ if (typeof cf === "string" && cf)
23
+ return cf;
24
+ const trueClient = req.headers["true-client-ip"];
25
+ if (typeof trueClient === "string" && trueClient)
26
+ return trueClient;
12
27
  const forwarded = req.headers["x-forwarded-for"];
13
- if (forwarded) {
14
- return (typeof forwarded === "string" ? forwarded : forwarded[0])
15
- .split(",")[0]
16
- .trim();
28
+ if (typeof forwarded === "string")
29
+ return forwarded.split(",")[0];
30
+ if (Array.isArray(forwarded))
31
+ return forwarded[0]?.split(",")[0];
32
+ return undefined;
33
+ }
34
+ function trustsProxy(proxy, socketIp) {
35
+ if (proxy === true)
36
+ return true;
37
+ if (proxy === false)
38
+ return false;
39
+ if (Array.isArray(proxy)) {
40
+ return proxy.some(entry => normalizeIp(entry) === socketIp);
17
41
  }
18
- return req.socket.remoteAddress || "";
42
+ return isLoopback(socketIp);
43
+ }
44
+ export function resolveRequestInfo(req, proxy = "auto") {
45
+ const socketIp = normalizeIp(req.socket.remoteAddress || "");
46
+ const forwarded = forwardedIp(req);
47
+ const isProxied = trustsProxy(proxy, socketIp) && !!forwarded;
48
+ return {
49
+ socketIp,
50
+ ip: isProxied ? normalizeIp(forwarded) : socketIp,
51
+ isProxied,
52
+ };
53
+ }
54
+ export function getIP(req, proxy = "auto") {
55
+ return resolveRequestInfo(req, proxy).ip;
56
+ }
57
+ export function streamFile(res, filePath) {
58
+ const stream = createReadStream(filePath);
59
+ stream.on("error", (err) => {
60
+ if (res.writableEnded)
61
+ return;
62
+ if (res.headersSent) {
63
+ res.destroy(err);
64
+ return;
65
+ }
66
+ res.removeHeader("content-length");
67
+ res.removeHeader("content-encoding");
68
+ if (err.code === "ENOENT") {
69
+ res.status(404);
70
+ res.FF._404(res.req, res);
71
+ return;
72
+ }
73
+ res.status(500);
74
+ res.FF._500(err, res.req, res);
75
+ if (!res.writableEnded)
76
+ res.end();
77
+ });
78
+ stream.pipe(res);
19
79
  }
20
80
  export const ensureLeadingDot = (str) => str.startsWith(".") ? str : "." + str;
package/dist/index.d.ts CHANGED
@@ -1,22 +1,36 @@
1
1
  import { Logger } from "@wxn0brp/lucerna-log";
2
2
  import http from "http";
3
+ import { type ResolvedConfig } from "./config.js";
3
4
  import { renderHTML } from "./render.js";
4
5
  import { FFResponse } from "./res.js";
5
6
  import { Router } from "./router.js";
6
- import type { BeforeHandleRequest, BodyParserEntry, CombinedVars, EngineCallback, ErrorHandler, FFOpts, FFRequest, FinalHandler, ParseBodyFunction, RouteHandler, StandardBodyParserOptions, ValidationErrorFormatter } from "./types.js";
7
+ import type { BeforeHandleRequest, BodyParserEntry, CombinedVars, DebugOptions, EngineCallback, ErrorHandler, FFOpts, FFRequest, FinalHandler, ParseBodyFunction, RouteHandler, StandardBodyParserOptions, ValidationErrorFormatter } from "./types.js";
7
8
  export declare class FalconFrame<Vars extends Record<string, any> = {}> extends Router {
8
9
  logger: Logger;
9
10
  bodyParsers: Record<string, BodyParserEntry>;
10
11
  vars: CombinedVars<Vars>;
11
12
  opts: FFOpts;
13
+ config: ResolvedConfig;
12
14
  engines: Record<string, EngineCallback>;
15
+ _debug?: {
16
+ path: string;
17
+ pass: string;
18
+ generated: boolean;
19
+ enabled?: boolean;
20
+ };
13
21
  _400_formatter: ValidationErrorFormatter;
14
22
  _404: FinalHandler;
15
23
  _413: FinalHandler;
24
+ _408: FinalHandler;
16
25
  _500: ErrorHandler;
17
26
  constructor(opts?: Partial<FFOpts>);
18
27
  addBodyParser(contentType: string, parser: ParseBodyFunction, opts?: StandardBodyParserOptions): this;
19
28
  listen(port: number | string, callback?: (() => void) | boolean, beforeHandleRequest?: BeforeHandleRequest): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
29
+ /**
30
+ * Mount the debug panel. Without an explicit `pass` a random token is
31
+ * generated and printed together with the URL on `listen()`.
32
+ */
33
+ debug(opts?: DebugOptions): this;
20
34
  getApp(beforeHandleRequest?: BeforeHandleRequest): (req: any, res: any) => Promise<void>;
21
35
  engine(ext: string, callback: EngineCallback): this;
22
36
  setVar<K extends keyof CombinedVars<Vars>>(key: K, value: CombinedVars<Vars>[K]): this;
@@ -40,12 +54,16 @@ export declare class FalconFrame<Vars extends Record<string, any> = {}> extends
40
54
  set400Formatter(formatter: ValidationErrorFormatter): void;
41
55
  set404(handler: FinalHandler): void;
42
56
  set413(handler: FinalHandler): void;
57
+ set408(handler: FinalHandler): void;
43
58
  set500(handler: ErrorHandler): void;
44
59
  }
45
60
  export default FalconFrame;
46
61
  export { OfflineEngine } from "./engine.js";
47
62
  export type { OfflineRequest, OfflineResponse } from "./engine.js";
48
63
  export * as Helpers from "./helpers.js";
49
- export type { FFOpts as Opts } from "./types.js";
64
+ export { compression, compressionMiddleware } from "./compress.js";
65
+ export { createDebug, generateDebugToken } from "./debug.js";
66
+ export type { DebugOptions } from "./debug.js";
67
+ export type { FFOpts as Opts, ProxyMode, CompressionOptions } from "./types.js";
50
68
  export { validateBody } from "./valid.js";
51
69
  export { FFRequest, FFResponse, FinalHandler, renderHTML, RouteHandler, Router, };
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,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/static.js CHANGED
@@ -1,6 +1,6 @@
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
5
  export function handleSingleFile(filePath, opts) {
6
6
  opts = {
@@ -32,12 +32,12 @@ export function handleSingleFile(filePath, opts) {
32
32
  res.setHeader("ETag", etag);
33
33
  }
34
34
  res.ct(getContentType(filePath, opts.utf8));
35
+ res.setHeader("Content-Length", stats.size);
35
36
  if (req.method === "HEAD") {
36
- res.setHeader("Content-Length", stats.size);
37
37
  res.end();
38
38
  return;
39
39
  }
40
- fs.createReadStream(filePath).pipe(res);
40
+ streamFile(res, filePath);
41
41
  };
42
42
  }
43
43
  export function handleStaticFiles(dirPath, opts) {
@@ -77,12 +77,12 @@ export function handleStaticFiles(dirPath, opts) {
77
77
  res.setHeader("ETag", etag);
78
78
  }
79
79
  res.ct(getContentType(filePath, opts.utf8));
80
+ res.setHeader("Content-Length", stats.size);
80
81
  if (req.method === "HEAD") {
81
- res.setHeader("Content-Length", stats.size);
82
82
  res.end();
83
83
  return true;
84
84
  }
85
- fs.createReadStream(filePath).pipe(res);
85
+ streamFile(res, filePath);
86
86
  return true;
87
87
  };
88
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.8",
3
+ "version": "0.9.9",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "wxn0brP",