@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/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();
@@ -0,0 +1,7 @@
1
+ export declare const mimeTypes: Record<string, string>;
2
+ /**
3
+ * Registers a MIME type for a file extension
4
+ */
5
+ export declare function registerMimeType(extension: string, contentType: string): void;
6
+ export declare function isTextualContentType(contentType: string): boolean;
7
+ export declare function getContentType(filePath: string, utf8?: boolean): string;
@@ -0,0 +1,71 @@
1
+ import path from "path";
2
+ export const mimeTypes = {
3
+ ".html": "text/html",
4
+ ".xhtml": "application/xhtml+xml",
5
+ ".css": "text/css",
6
+ ".js": "application/javascript",
7
+ ".mjs": "application/javascript",
8
+ ".cjs": "application/javascript",
9
+ ".json": "application/json",
10
+ ".json5": "application/json5",
11
+ ".yaml": "application/yaml",
12
+ ".yml": "application/yaml",
13
+ ".toml": "application/toml",
14
+ ".xml": "application/xml",
15
+ ".csv": "text/csv",
16
+ ".md": "text/markdown",
17
+ ".vtt": "text/vtt",
18
+ ".map": "application/json",
19
+ ".webmanifest": "application/manifest+json",
20
+ ".png": "image/png",
21
+ ".apng": "image/apng",
22
+ ".jpg": "image/jpeg",
23
+ ".jpeg": "image/jpeg",
24
+ ".gif": "image/gif",
25
+ ".svg": "image/svg+xml",
26
+ ".ico": "image/x-icon",
27
+ ".webp": "image/webp",
28
+ ".avif": "image/avif",
29
+ ".bmp": "image/bmp",
30
+ ".tiff": "image/tiff",
31
+ ".txt": "text/plain",
32
+ ".pdf": "application/pdf",
33
+ ".wasm": "application/wasm",
34
+ ".wav": "audio/wav",
35
+ ".mp3": "audio/mpeg",
36
+ ".ogg": "audio/ogg",
37
+ ".aac": "audio/aac",
38
+ ".weba": "audio/webm",
39
+ ".flac": "audio/flac",
40
+ ".opus": "audio/opus",
41
+ ".m4a": "audio/mp4",
42
+ ".mp4": "video/mp4",
43
+ ".m4v": "video/mp4",
44
+ ".webm": "video/webm",
45
+ ".ogv": "video/ogg",
46
+ ".m3u8": "application/vnd.apple.mpegurl",
47
+ ".woff": "font/woff",
48
+ ".woff2": "font/woff2",
49
+ ".ttf": "font/ttf",
50
+ ".otf": "font/otf",
51
+ ".eot": "application/vnd.ms-fontobject",
52
+ };
53
+ /**
54
+ * Registers a MIME type for a file extension
55
+ */
56
+ export function registerMimeType(extension, contentType) {
57
+ const ext = extension.trim().toLowerCase();
58
+ mimeTypes[ext.startsWith(".") ? ext : "." + ext] = contentType;
59
+ }
60
+ const textualTypeRe = /^(?:text\/|application\/(?:json5?|javascript|xml|yaml|toml)$|[\w.-]+\/[\w.-]+\+(?:json|xml)$)/;
61
+ export function isTextualContentType(contentType) {
62
+ const type = contentType.split(";")[0].trim().toLowerCase();
63
+ return type === "image/svg+xml" || textualTypeRe.test(type);
64
+ }
65
+ export function getContentType(filePath, utf8 = true) {
66
+ let contentType = mimeTypes[path.extname(filePath).toLowerCase()] ??
67
+ "application/octet-stream";
68
+ if (utf8 && !contentType.includes(";") && isTextualContentType(contentType))
69
+ contentType += "; charset=utf-8";
70
+ return contentType;
71
+ }
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";
3
+ export { getContentType } from "./encoding.js";
2
4
  export declare function parseCookies(cookieHeader: string): Cookies;
3
- export declare function getIP(req: FFRequest): string;
4
- export declare function getContentType(filePath: string, utf8?: boolean): 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,4 +1,5 @@
1
- import path from "path";
1
+ import { createReadStream } from "fs";
2
+ export { getContentType } from "./encoding.js";
2
3
  export function parseCookies(cookieHeader) {
3
4
  const cookies = Object.create(null);
4
5
  cookieHeader.split(";").forEach(cookie => {
@@ -8,41 +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 || "";
19
- }
20
- const mimeTypes = {
21
- ".html": "text/html",
22
- ".css": "text/css",
23
- ".js": "application/javascript",
24
- ".json": "application/json",
25
- ".json5": "application/json5",
26
- ".yaml": "application/yaml",
27
- ".yml": "application/yaml",
28
- ".toml": "application/toml",
29
- ".png": "image/png",
30
- ".jpg": "image/jpeg",
31
- ".jpeg": "image/jpeg",
32
- ".gif": "image/gif",
33
- ".svg": "image/svg+xml",
34
- ".ico": "image/x-icon",
35
- ".txt": "text/plain",
36
- ".pdf": "application/pdf",
37
- };
38
- function _getContentType(filePath) {
39
- const ext = path.extname(filePath).toLowerCase();
40
- return mimeTypes[ext] || "application/octet-stream";
41
- }
42
- export function getContentType(filePath, utf8 = false) {
43
- let contentType = _getContentType(filePath);
44
- if (utf8)
45
- contentType += "; charset=utf-8";
46
- return contentType;
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);
47
79
  }
48
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, };