@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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # FalconFrame
2
2
 
3
- A minimal, modular TypeScript web library.
3
+ A minimal, modular TypeScript http server library.
4
4
 
5
5
  ## Features
6
6
 
@@ -10,6 +10,11 @@ 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
+ - HTTPS via environment variables, both servers with `app.l()`
16
+ - Body limits and read timeouts
17
+ - Compression middleware
13
18
 
14
19
  ## Installation
15
20
 
@@ -23,6 +28,7 @@ bun add @wxn0brp/falcon-frame
23
28
  import FalconFrame, { validateBody } from "@wxn0brp/falcon-frame";
24
29
  const app = new FalconFrame();
25
30
 
31
+ app.debug();
26
32
  app.setOrigin("*");
27
33
 
28
34
  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;