@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 +7 -1
- package/dist/body-utils.d.ts +1 -1
- package/dist/body-utils.js +29 -4
- package/dist/compress.d.ts +2 -2
- package/dist/compress.js +156 -37
- package/dist/config.d.ts +20 -0
- package/dist/config.js +28 -0
- package/dist/debug.d.ts +4 -8
- package/dist/debug.js +207 -39
- package/dist/helpers.d.ts +12 -2
- package/dist/helpers.js +78 -6
- package/dist/https.d.ts +6 -0
- package/dist/https.js +35 -0
- package/dist/index.d.ts +27 -3
- package/dist/index.js +87 -11
- package/dist/req.js +35 -14
- package/dist/res.js +3 -3
- package/dist/router.d.ts +2 -1
- package/dist/router.js +11 -3
- package/dist/static.js +54 -14
- package/dist/types.d.ts +55 -0
- package/dist/types.js +9 -0
- package/package.json +1 -1
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
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
-
|
|
25
|
-
|
|
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(
|
|
29
|
-
|
|
30
|
-
|
|
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(
|
|
34
|
-
|
|
35
|
-
|
|
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
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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,15 @@
|
|
|
1
|
-
import {
|
|
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
|
|
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
|
+
protocol: "http" | "https";
|
|
12
|
+
};
|
|
13
|
+
export declare function getIP(req: FFRequest, proxy?: ProxyMode): string;
|
|
14
|
+
export declare function streamFile(res: FFResponse, filePath: string): void;
|
|
5
15
|
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,84 @@ export function parseCookies(cookieHeader) {
|
|
|
8
9
|
});
|
|
9
10
|
return cookies;
|
|
10
11
|
}
|
|
11
|
-
export function
|
|
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 (
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
42
|
+
return isLoopback(socketIp);
|
|
43
|
+
}
|
|
44
|
+
function forwardedProto(req) {
|
|
45
|
+
const header = req.headers["x-forwarded-proto"];
|
|
46
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
47
|
+
if (!value)
|
|
48
|
+
return undefined;
|
|
49
|
+
const proto = value.split(",")[0]?.trim().toLowerCase();
|
|
50
|
+
return proto === "http" || proto === "https" ? proto : undefined;
|
|
51
|
+
}
|
|
52
|
+
export function resolveRequestInfo(req, proxy = "auto") {
|
|
53
|
+
const socketIp = normalizeIp(req.socket.remoteAddress || "");
|
|
54
|
+
const forwarded = forwardedIp(req);
|
|
55
|
+
const trusted = trustsProxy(proxy, socketIp);
|
|
56
|
+
const isProxied = trusted && !!forwarded;
|
|
57
|
+
const protocol = (trusted ? forwardedProto(req) : undefined) ??
|
|
58
|
+
(req.socket?.encrypted ? "https" : "http");
|
|
59
|
+
return {
|
|
60
|
+
socketIp,
|
|
61
|
+
ip: isProxied ? normalizeIp(forwarded) : socketIp,
|
|
62
|
+
isProxied,
|
|
63
|
+
protocol,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export function getIP(req, proxy = "auto") {
|
|
67
|
+
return resolveRequestInfo(req, proxy).ip;
|
|
68
|
+
}
|
|
69
|
+
export function streamFile(res, filePath) {
|
|
70
|
+
const stream = createReadStream(filePath);
|
|
71
|
+
stream.on("error", (err) => {
|
|
72
|
+
if (res.writableEnded)
|
|
73
|
+
return;
|
|
74
|
+
if (res.headersSent) {
|
|
75
|
+
res.destroy(err);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
res.removeHeader("content-length");
|
|
79
|
+
res.removeHeader("content-encoding");
|
|
80
|
+
if (err.code === "ENOENT") {
|
|
81
|
+
res.status(404);
|
|
82
|
+
res.FF._404(res.req, res);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
res.status(500);
|
|
86
|
+
res.FF._500(err, res.req, res);
|
|
87
|
+
if (!res.writableEnded)
|
|
88
|
+
res.end();
|
|
89
|
+
});
|
|
90
|
+
stream.pipe(res);
|
|
19
91
|
}
|
|
20
92
|
export const ensureLeadingDot = (str) => str.startsWith(".") ? str : "." + str;
|
package/dist/https.d.ts
ADDED
package/dist/https.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { readFileSync } from "fs";
|
|
2
|
+
function readFile(path) {
|
|
3
|
+
try {
|
|
4
|
+
return readFileSync(path);
|
|
5
|
+
}
|
|
6
|
+
catch (err) {
|
|
7
|
+
throw new Error(`[FF] Cannot read TLS file "${path}": ${err?.message ?? err}`);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
function parsePort(value) {
|
|
11
|
+
if (value === undefined)
|
|
12
|
+
return 443;
|
|
13
|
+
return +value;
|
|
14
|
+
}
|
|
15
|
+
export function resolveHTTPSConfig() {
|
|
16
|
+
const key = process.env.HTTPS_KEY;
|
|
17
|
+
const cert = process.env.HTTPS_CERT;
|
|
18
|
+
if (!key && !cert)
|
|
19
|
+
return undefined;
|
|
20
|
+
if (!key || !cert) {
|
|
21
|
+
throw new Error("[FF] HTTPS_KEY and HTTPS_CERT must be set together");
|
|
22
|
+
}
|
|
23
|
+
const options = {
|
|
24
|
+
key: readFile(key),
|
|
25
|
+
cert: readFile(cert),
|
|
26
|
+
};
|
|
27
|
+
if (process.env.HTTPS_CA)
|
|
28
|
+
options.ca = readFile(process.env.HTTPS_CA);
|
|
29
|
+
if (process.env.HTTPS_PASSPHRASE)
|
|
30
|
+
options.passphrase = process.env.HTTPS_PASSPHRASE;
|
|
31
|
+
return {
|
|
32
|
+
port: parsePort(process.env.HTTPS_PORT),
|
|
33
|
+
options,
|
|
34
|
+
};
|
|
35
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,22 +1,39 @@
|
|
|
1
1
|
import { Logger } from "@wxn0brp/lucerna-log";
|
|
2
2
|
import http from "http";
|
|
3
|
+
import https from "https";
|
|
4
|
+
import { type ResolvedConfig } from "./config.js";
|
|
3
5
|
import { renderHTML } from "./render.js";
|
|
4
6
|
import { FFResponse } from "./res.js";
|
|
5
7
|
import { Router } from "./router.js";
|
|
6
|
-
import type { BeforeHandleRequest, BodyParserEntry, CombinedVars, EngineCallback, ErrorHandler, FFOpts, FFRequest, FinalHandler, ParseBodyFunction, RouteHandler, StandardBodyParserOptions, ValidationErrorFormatter } from "./types.js";
|
|
8
|
+
import type { BeforeHandleRequest, BodyParserEntry, CombinedVars, DebugOptions, EngineCallback, ErrorHandler, FFOpts, FFRequest, FinalHandler, ParseBodyFunction, RouteHandler, StandardBodyParserOptions, ValidationErrorFormatter } from "./types.js";
|
|
7
9
|
export declare class FalconFrame<Vars extends Record<string, any> = {}> extends Router {
|
|
8
10
|
logger: Logger;
|
|
11
|
+
httpsServer?: https.Server;
|
|
9
12
|
bodyParsers: Record<string, BodyParserEntry>;
|
|
10
13
|
vars: CombinedVars<Vars>;
|
|
11
14
|
opts: FFOpts;
|
|
15
|
+
config: ResolvedConfig;
|
|
12
16
|
engines: Record<string, EngineCallback>;
|
|
17
|
+
_debug?: {
|
|
18
|
+
path: string;
|
|
19
|
+
pass: string;
|
|
20
|
+
generated: boolean;
|
|
21
|
+
enabled?: boolean;
|
|
22
|
+
};
|
|
13
23
|
_400_formatter: ValidationErrorFormatter;
|
|
14
24
|
_404: FinalHandler;
|
|
15
25
|
_413: FinalHandler;
|
|
26
|
+
_408: FinalHandler;
|
|
16
27
|
_500: ErrorHandler;
|
|
17
28
|
constructor(opts?: Partial<FFOpts>);
|
|
18
29
|
addBodyParser(contentType: string, parser: ParseBodyFunction, opts?: StandardBodyParserOptions): this;
|
|
19
30
|
listen(port: number | string, callback?: (() => void) | boolean, beforeHandleRequest?: BeforeHandleRequest): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
31
|
+
private printDebugUrl;
|
|
32
|
+
/**
|
|
33
|
+
* Mount the debug panel. Without an explicit `pass` a random token is
|
|
34
|
+
* generated and printed together with the URL on `listen()`.
|
|
35
|
+
*/
|
|
36
|
+
debug(opts?: DebugOptions): this;
|
|
20
37
|
getApp(beforeHandleRequest?: BeforeHandleRequest): (req: any, res: any) => Promise<void>;
|
|
21
38
|
engine(ext: string, callback: EngineCallback): this;
|
|
22
39
|
setVar<K extends keyof CombinedVars<Vars>>(key: K, value: CombinedVars<Vars>[K]): this;
|
|
@@ -33,19 +50,26 @@ export declare class FalconFrame<Vars extends Record<string, any> = {}> extends
|
|
|
33
50
|
setOrigin(origin?: string[] | string): void;
|
|
34
51
|
/**
|
|
35
52
|
* Listens to the specified port, or the environment variable PORT if available.
|
|
53
|
+
* HTTPS starts as an additional server when `HTTPS_KEY` and `HTTPS_CERT` are set,
|
|
54
|
+
* on `HTTPS_PORT` (default 443).
|
|
36
55
|
* @param port - The port number to listen to.
|
|
37
|
-
* @returns The server object
|
|
56
|
+
* @returns The HTTP server object. The HTTPS server is available as `httpsServer`.
|
|
38
57
|
*/
|
|
39
58
|
l(port: number): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
40
59
|
set400Formatter(formatter: ValidationErrorFormatter): void;
|
|
41
60
|
set404(handler: FinalHandler): void;
|
|
42
61
|
set413(handler: FinalHandler): void;
|
|
62
|
+
set408(handler: FinalHandler): void;
|
|
43
63
|
set500(handler: ErrorHandler): void;
|
|
44
64
|
}
|
|
45
65
|
export default FalconFrame;
|
|
46
66
|
export { OfflineEngine } from "./engine.js";
|
|
47
67
|
export type { OfflineRequest, OfflineResponse } from "./engine.js";
|
|
68
|
+
export { resolveHTTPSConfig } from "./https.js";
|
|
48
69
|
export * as Helpers from "./helpers.js";
|
|
49
|
-
export
|
|
70
|
+
export { compression, compressionMiddleware } from "./compress.js";
|
|
71
|
+
export { createDebug, generateDebugToken } from "./debug.js";
|
|
72
|
+
export type { DebugOptions } from "./debug.js";
|
|
73
|
+
export type { FFOpts as Opts, ProxyMode, CompressionOptions } from "./types.js";
|
|
50
74
|
export { validateBody } from "./valid.js";
|
|
51
75
|
export { FFRequest, FFResponse, FinalHandler, renderHTML, RouteHandler, Router, };
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
1
|
import { Logger } from "@wxn0brp/lucerna-log";
|
|
2
2
|
import http from "http";
|
|
3
|
+
import https from "https";
|
|
3
4
|
import * as bodyParser from "./body.js";
|
|
4
5
|
import { parseLimit } from "./body-utils.js";
|
|
6
|
+
import { resolveConfig, isDebugEnabled } from "./config.js";
|
|
5
7
|
import { createCORS } from "./cors.js";
|
|
8
|
+
import { createDebug, generateDebugToken } from "./debug.js";
|
|
9
|
+
import { resolveHTTPSConfig } from "./https.js";
|
|
6
10
|
import { renderHTML } from "./render.js";
|
|
7
11
|
import { handleRequest } from "./req.js";
|
|
8
12
|
import { FFResponse } from "./res.js";
|
|
9
13
|
import { Router } from "./router.js";
|
|
10
14
|
export class FalconFrame extends Router {
|
|
11
15
|
logger;
|
|
16
|
+
httpsServer;
|
|
12
17
|
bodyParsers = {};
|
|
13
18
|
vars = {};
|
|
14
19
|
opts = {};
|
|
20
|
+
config;
|
|
15
21
|
engines = {};
|
|
22
|
+
_debug;
|
|
16
23
|
_400_formatter = err => {
|
|
17
24
|
return {
|
|
18
25
|
err: true,
|
|
@@ -26,6 +33,9 @@ export class FalconFrame extends Router {
|
|
|
26
33
|
_413 = (req, res) => {
|
|
27
34
|
res.end("413: Cat is too fat");
|
|
28
35
|
};
|
|
36
|
+
_408 = (req, res) => {
|
|
37
|
+
res.end("408: The request took a nap");
|
|
38
|
+
};
|
|
29
39
|
_500 = (err, req, res) => {
|
|
30
40
|
res.end("500: The code had an existential crisis");
|
|
31
41
|
};
|
|
@@ -40,13 +50,19 @@ export class FalconFrame extends Router {
|
|
|
40
50
|
bodyLimit: "10m",
|
|
41
51
|
...opts,
|
|
42
52
|
};
|
|
43
|
-
|
|
53
|
+
this.config = resolveConfig(this.opts);
|
|
54
|
+
const dp = this.config.disableParser || {};
|
|
44
55
|
const isBun = !!globalThis.Bun;
|
|
45
56
|
const bunOnly = new Set([
|
|
46
57
|
"json5",
|
|
47
58
|
"yaml",
|
|
48
59
|
"toml",
|
|
49
60
|
]);
|
|
61
|
+
const untrusted = new Set([
|
|
62
|
+
"json5",
|
|
63
|
+
"yaml",
|
|
64
|
+
"toml",
|
|
65
|
+
]);
|
|
50
66
|
const parsers = {
|
|
51
67
|
json: {
|
|
52
68
|
fn: bodyParser.json,
|
|
@@ -76,6 +92,8 @@ export class FalconFrame extends Router {
|
|
|
76
92
|
for (const [key, { fn, ct }] of Object.entries(parsers)) {
|
|
77
93
|
if (dp[key])
|
|
78
94
|
continue;
|
|
95
|
+
if (untrusted.has(key) && !this.config.untrustedBodyParsers)
|
|
96
|
+
continue;
|
|
79
97
|
if (bunOnly.has(key) && !isBun)
|
|
80
98
|
continue;
|
|
81
99
|
this.addBodyParser(ct, fn);
|
|
@@ -97,7 +115,9 @@ export class FalconFrame extends Router {
|
|
|
97
115
|
addBodyParser(contentType, parser, opts = {}) {
|
|
98
116
|
this.bodyParsers[contentType] = {
|
|
99
117
|
parse: parser,
|
|
100
|
-
limit:
|
|
118
|
+
limit: opts.limit !== undefined
|
|
119
|
+
? parseLimit(opts.limit)
|
|
120
|
+
: this.config.bodyLimit,
|
|
101
121
|
};
|
|
102
122
|
return this;
|
|
103
123
|
}
|
|
@@ -117,18 +137,53 @@ export class FalconFrame extends Router {
|
|
|
117
137
|
else if (typeof port === "number") {
|
|
118
138
|
parsedPort = port;
|
|
119
139
|
}
|
|
140
|
+
let printUrl = false;
|
|
120
141
|
if (typeof callback === "boolean") {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
console.log(`[FF] Server running on http://${host || "localhost"}:${parsedPort}`);
|
|
124
|
-
};
|
|
125
|
-
else
|
|
126
|
-
callback = () => { };
|
|
142
|
+
printUrl = callback;
|
|
143
|
+
callback = () => { };
|
|
127
144
|
}
|
|
128
145
|
const cb = callback || (() => { });
|
|
129
|
-
server.listen(parsedPort, host || "0.0.0.0",
|
|
146
|
+
server.listen(parsedPort, host || "0.0.0.0", () => {
|
|
147
|
+
const address = server.address();
|
|
148
|
+
const actualPort = address && typeof address === "object" ? address.port : parsedPort;
|
|
149
|
+
if (printUrl) {
|
|
150
|
+
console.log(`[FF] Server running on http://${host || "localhost"}:${actualPort}`);
|
|
151
|
+
}
|
|
152
|
+
this.printDebugUrl("http", host, actualPort);
|
|
153
|
+
cb();
|
|
154
|
+
});
|
|
130
155
|
return server;
|
|
131
156
|
}
|
|
157
|
+
printDebugUrl(scheme, host, port) {
|
|
158
|
+
if (!this._debug || !isDebugEnabled(this._debug.enabled))
|
|
159
|
+
return;
|
|
160
|
+
const urlHost = host && host !== "0.0.0.0" && host !== "::" ? host : "localhost";
|
|
161
|
+
const token = this._debug.generated ? `?pass=${this._debug.pass}` : "";
|
|
162
|
+
console.log(`[FF] Debug panel: ${scheme}://${urlHost}:${port}${this._debug.path}${token}`);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Mount the debug panel. Without an explicit `pass` a random token is
|
|
166
|
+
* generated and printed together with the URL on `listen()`.
|
|
167
|
+
*/
|
|
168
|
+
debug(opts = {}) {
|
|
169
|
+
const resolved = this.config.debug;
|
|
170
|
+
const path = opts.path ?? opts.url ?? resolved.path;
|
|
171
|
+
const explicitPass = opts.pass ?? resolved.pass ?? process.env.FF_DEBUG_PASS;
|
|
172
|
+
const pass = explicitPass ?? generateDebugToken();
|
|
173
|
+
const enabled = opts.enabled ?? resolved.enabled;
|
|
174
|
+
this._debug = {
|
|
175
|
+
path,
|
|
176
|
+
pass,
|
|
177
|
+
generated: !explicitPass,
|
|
178
|
+
enabled,
|
|
179
|
+
};
|
|
180
|
+
this.use(createDebug({
|
|
181
|
+
...opts,
|
|
182
|
+
path,
|
|
183
|
+
pass,
|
|
184
|
+
}, resolved));
|
|
185
|
+
return this;
|
|
186
|
+
}
|
|
132
187
|
getApp(beforeHandleRequest) {
|
|
133
188
|
return async (req, res) => {
|
|
134
189
|
if (beforeHandleRequest) {
|
|
@@ -172,11 +227,26 @@ export class FalconFrame extends Router {
|
|
|
172
227
|
}
|
|
173
228
|
/**
|
|
174
229
|
* Listens to the specified port, or the environment variable PORT if available.
|
|
230
|
+
* HTTPS starts as an additional server when `HTTPS_KEY` and `HTTPS_CERT` are set,
|
|
231
|
+
* on `HTTPS_PORT` (default 443).
|
|
175
232
|
* @param port - The port number to listen to.
|
|
176
|
-
* @returns The server object
|
|
233
|
+
* @returns The HTTP server object. The HTTPS server is available as `httpsServer`.
|
|
177
234
|
*/
|
|
178
235
|
l(port) {
|
|
179
|
-
|
|
236
|
+
const server = this.listen(+process.env.PORT || port, true);
|
|
237
|
+
const httpsConfig = resolveHTTPSConfig();
|
|
238
|
+
if (!httpsConfig)
|
|
239
|
+
return server;
|
|
240
|
+
this.httpsServer = https.createServer(httpsConfig.options, this.getApp());
|
|
241
|
+
this.httpsServer.listen(httpsConfig.port, "0.0.0.0", () => {
|
|
242
|
+
const address = this.httpsServer?.address();
|
|
243
|
+
const actualPort = address && typeof address === "object"
|
|
244
|
+
? address.port
|
|
245
|
+
: httpsConfig.port;
|
|
246
|
+
console.log(`[FF] Server running on https://localhost:${actualPort}`);
|
|
247
|
+
this.printDebugUrl("https", "0.0.0.0", actualPort);
|
|
248
|
+
});
|
|
249
|
+
return server;
|
|
180
250
|
}
|
|
181
251
|
set400Formatter(formatter) {
|
|
182
252
|
this._400_formatter = formatter;
|
|
@@ -187,12 +257,18 @@ export class FalconFrame extends Router {
|
|
|
187
257
|
set413(handler) {
|
|
188
258
|
this._413 = handler;
|
|
189
259
|
}
|
|
260
|
+
set408(handler) {
|
|
261
|
+
this._408 = handler;
|
|
262
|
+
}
|
|
190
263
|
set500(handler) {
|
|
191
264
|
this._500 = handler;
|
|
192
265
|
}
|
|
193
266
|
}
|
|
194
267
|
export default FalconFrame;
|
|
195
268
|
export { OfflineEngine } from "./engine.js";
|
|
269
|
+
export { resolveHTTPSConfig } from "./https.js";
|
|
196
270
|
export * as Helpers from "./helpers.js";
|
|
271
|
+
export { compression, compressionMiddleware } from "./compress.js";
|
|
272
|
+
export { createDebug, generateDebugToken } from "./debug.js";
|
|
197
273
|
export { validateBody } from "./valid.js";
|
|
198
274
|
export { FFResponse, renderHTML, Router, };
|