@wxn0brp/falcon-frame 0.9.9 → 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 +2 -1
- package/dist/helpers.d.ts +1 -0
- package/dist/helpers.js +13 -1
- package/dist/https.d.ts +6 -0
- package/dist/https.js +35 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +29 -7
- package/dist/req.js +2 -0
- package/dist/router.d.ts +2 -1
- package/dist/router.js +11 -3
- package/dist/static.js +49 -9
- package/dist/types.d.ts +6 -0
- package/dist/types.js +4 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# FalconFrame
|
|
2
2
|
|
|
3
|
-
A minimal, modular TypeScript
|
|
3
|
+
A minimal, modular TypeScript http server library.
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
@@ -12,6 +12,7 @@ A minimal, modular TypeScript web library.
|
|
|
12
12
|
- Debuggable logger
|
|
13
13
|
- Debug panel
|
|
14
14
|
- Proxy-aware client IP resolution
|
|
15
|
+
- HTTPS via environment variables, both servers with `app.l()`
|
|
15
16
|
- Body limits and read timeouts
|
|
16
17
|
- Compression middleware
|
|
17
18
|
|
package/dist/helpers.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export declare function resolveRequestInfo(req: FFRequest, proxy?: ProxyMode): {
|
|
|
8
8
|
socketIp: string;
|
|
9
9
|
ip: string;
|
|
10
10
|
isProxied: boolean;
|
|
11
|
+
protocol: "http" | "https";
|
|
11
12
|
};
|
|
12
13
|
export declare function getIP(req: FFRequest, proxy?: ProxyMode): string;
|
|
13
14
|
export declare function streamFile(res: FFResponse, filePath: string): void;
|
package/dist/helpers.js
CHANGED
|
@@ -41,14 +41,26 @@ function trustsProxy(proxy, socketIp) {
|
|
|
41
41
|
}
|
|
42
42
|
return isLoopback(socketIp);
|
|
43
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
|
+
}
|
|
44
52
|
export function resolveRequestInfo(req, proxy = "auto") {
|
|
45
53
|
const socketIp = normalizeIp(req.socket.remoteAddress || "");
|
|
46
54
|
const forwarded = forwardedIp(req);
|
|
47
|
-
const
|
|
55
|
+
const trusted = trustsProxy(proxy, socketIp);
|
|
56
|
+
const isProxied = trusted && !!forwarded;
|
|
57
|
+
const protocol = (trusted ? forwardedProto(req) : undefined) ??
|
|
58
|
+
(req.socket?.encrypted ? "https" : "http");
|
|
48
59
|
return {
|
|
49
60
|
socketIp,
|
|
50
61
|
ip: isProxied ? normalizeIp(forwarded) : socketIp,
|
|
51
62
|
isProxied,
|
|
63
|
+
protocol,
|
|
52
64
|
};
|
|
53
65
|
}
|
|
54
66
|
export function getIP(req, proxy = "auto") {
|
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,5 +1,6 @@
|
|
|
1
1
|
import { Logger } from "@wxn0brp/lucerna-log";
|
|
2
2
|
import http from "http";
|
|
3
|
+
import https from "https";
|
|
3
4
|
import { type ResolvedConfig } from "./config.js";
|
|
4
5
|
import { renderHTML } from "./render.js";
|
|
5
6
|
import { FFResponse } from "./res.js";
|
|
@@ -7,6 +8,7 @@ import { Router } from "./router.js";
|
|
|
7
8
|
import type { BeforeHandleRequest, BodyParserEntry, CombinedVars, DebugOptions, EngineCallback, ErrorHandler, FFOpts, FFRequest, FinalHandler, ParseBodyFunction, RouteHandler, StandardBodyParserOptions, ValidationErrorFormatter } from "./types.js";
|
|
8
9
|
export declare class FalconFrame<Vars extends Record<string, any> = {}> extends Router {
|
|
9
10
|
logger: Logger;
|
|
11
|
+
httpsServer?: https.Server;
|
|
10
12
|
bodyParsers: Record<string, BodyParserEntry>;
|
|
11
13
|
vars: CombinedVars<Vars>;
|
|
12
14
|
opts: FFOpts;
|
|
@@ -26,6 +28,7 @@ export declare class FalconFrame<Vars extends Record<string, any> = {}> extends
|
|
|
26
28
|
constructor(opts?: Partial<FFOpts>);
|
|
27
29
|
addBodyParser(contentType: string, parser: ParseBodyFunction, opts?: StandardBodyParserOptions): this;
|
|
28
30
|
listen(port: number | string, callback?: (() => void) | boolean, beforeHandleRequest?: BeforeHandleRequest): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
31
|
+
private printDebugUrl;
|
|
29
32
|
/**
|
|
30
33
|
* Mount the debug panel. Without an explicit `pass` a random token is
|
|
31
34
|
* generated and printed together with the URL on `listen()`.
|
|
@@ -47,8 +50,10 @@ export declare class FalconFrame<Vars extends Record<string, any> = {}> extends
|
|
|
47
50
|
setOrigin(origin?: string[] | string): void;
|
|
48
51
|
/**
|
|
49
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).
|
|
50
55
|
* @param port - The port number to listen to.
|
|
51
|
-
* @returns The server object
|
|
56
|
+
* @returns The HTTP server object. The HTTPS server is available as `httpsServer`.
|
|
52
57
|
*/
|
|
53
58
|
l(port: number): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
|
54
59
|
set400Formatter(formatter: ValidationErrorFormatter): void;
|
|
@@ -60,6 +65,7 @@ export declare class FalconFrame<Vars extends Record<string, any> = {}> extends
|
|
|
60
65
|
export default FalconFrame;
|
|
61
66
|
export { OfflineEngine } from "./engine.js";
|
|
62
67
|
export type { OfflineRequest, OfflineResponse } from "./engine.js";
|
|
68
|
+
export { resolveHTTPSConfig } from "./https.js";
|
|
63
69
|
export * as Helpers from "./helpers.js";
|
|
64
70
|
export { compression, compressionMiddleware } from "./compress.js";
|
|
65
71
|
export { createDebug, generateDebugToken } from "./debug.js";
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
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";
|
|
5
6
|
import { resolveConfig, isDebugEnabled } from "./config.js";
|
|
6
7
|
import { createCORS } from "./cors.js";
|
|
7
8
|
import { createDebug, generateDebugToken } from "./debug.js";
|
|
9
|
+
import { resolveHTTPSConfig } from "./https.js";
|
|
8
10
|
import { renderHTML } from "./render.js";
|
|
9
11
|
import { handleRequest } from "./req.js";
|
|
10
12
|
import { FFResponse } from "./res.js";
|
|
11
13
|
import { Router } from "./router.js";
|
|
12
14
|
export class FalconFrame extends Router {
|
|
13
15
|
logger;
|
|
16
|
+
httpsServer;
|
|
14
17
|
bodyParsers = {};
|
|
15
18
|
vars = {};
|
|
16
19
|
opts = {};
|
|
@@ -146,15 +149,18 @@ export class FalconFrame extends Router {
|
|
|
146
149
|
if (printUrl) {
|
|
147
150
|
console.log(`[FF] Server running on http://${host || "localhost"}:${actualPort}`);
|
|
148
151
|
}
|
|
149
|
-
|
|
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
|
-
}
|
|
152
|
+
this.printDebugUrl("http", host, actualPort);
|
|
154
153
|
cb();
|
|
155
154
|
});
|
|
156
155
|
return server;
|
|
157
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
|
+
}
|
|
158
164
|
/**
|
|
159
165
|
* Mount the debug panel. Without an explicit `pass` a random token is
|
|
160
166
|
* generated and printed together with the URL on `listen()`.
|
|
@@ -221,11 +227,26 @@ export class FalconFrame extends Router {
|
|
|
221
227
|
}
|
|
222
228
|
/**
|
|
223
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).
|
|
224
232
|
* @param port - The port number to listen to.
|
|
225
|
-
* @returns The server object
|
|
233
|
+
* @returns The HTTP server object. The HTTPS server is available as `httpsServer`.
|
|
226
234
|
*/
|
|
227
235
|
l(port) {
|
|
228
|
-
|
|
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;
|
|
229
250
|
}
|
|
230
251
|
set400Formatter(formatter) {
|
|
231
252
|
this._400_formatter = formatter;
|
|
@@ -245,6 +266,7 @@ export class FalconFrame extends Router {
|
|
|
245
266
|
}
|
|
246
267
|
export default FalconFrame;
|
|
247
268
|
export { OfflineEngine } from "./engine.js";
|
|
269
|
+
export { resolveHTTPSConfig } from "./https.js";
|
|
248
270
|
export * as Helpers from "./helpers.js";
|
|
249
271
|
export { compression, compressionMiddleware } from "./compress.js";
|
|
250
272
|
export { createDebug, generateDebugToken } from "./debug.js";
|
package/dist/req.js
CHANGED
|
@@ -34,6 +34,8 @@ export function handleRequest(req, res, FF, reRoute = false) {
|
|
|
34
34
|
req.socketIp = requestInfo.socketIp;
|
|
35
35
|
req.ip = requestInfo.ip;
|
|
36
36
|
req.isProxied = requestInfo.isProxied;
|
|
37
|
+
req.protocol = requestInfo.protocol;
|
|
38
|
+
req.secure = requestInfo.protocol === "https";
|
|
37
39
|
req.params = {};
|
|
38
40
|
req.valid = (schema, regexRules) => validate({
|
|
39
41
|
schema,
|
package/dist/router.d.ts
CHANGED
|
@@ -13,7 +13,8 @@ export declare class Router {
|
|
|
13
13
|
delete(path: string, ...handlers: RouteHandler[]): this;
|
|
14
14
|
patch(path: string, ...handlers: RouteHandler[]): this;
|
|
15
15
|
all(path: string, ...handlers: RouteHandler[]): this;
|
|
16
|
-
static(
|
|
16
|
+
static(dirPath: string, opts?: StaticServeOptions): this;
|
|
17
|
+
static(apiPath: string, dirPath: string, opts?: StaticServeOptions): this;
|
|
17
18
|
file(routePath: string, filePath: string, opts?: StaticFileOptions): this;
|
|
18
19
|
sse(path: string, ...handlers: RouteHandler[]): SSEManager;
|
|
19
20
|
customParser(path: string, handler: RouteHandler, method?: Method): this;
|
package/dist/router.js
CHANGED
|
@@ -58,10 +58,18 @@ export class Router {
|
|
|
58
58
|
this.addRoute("all", path, ...handlers);
|
|
59
59
|
return this;
|
|
60
60
|
}
|
|
61
|
-
static(
|
|
62
|
-
|
|
63
|
-
|
|
61
|
+
static(apiPathOrDir, dirOrOpts, maybeOpts = {}) {
|
|
62
|
+
let apiPath = apiPathOrDir;
|
|
63
|
+
let dirPath;
|
|
64
|
+
let opts;
|
|
65
|
+
if (typeof dirOrOpts === "string") {
|
|
66
|
+
dirPath = dirOrOpts;
|
|
67
|
+
opts = maybeOpts;
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
dirPath = apiPathOrDir;
|
|
64
71
|
apiPath = "/";
|
|
72
|
+
opts = dirOrOpts ?? {};
|
|
65
73
|
}
|
|
66
74
|
if (dirPath === "/")
|
|
67
75
|
throw new Error("Cannot serve root directory");
|
package/dist/static.js
CHANGED
|
@@ -2,6 +2,40 @@ import fs from "fs";
|
|
|
2
2
|
import path from "path";
|
|
3
3
|
import { ensureLeadingDot, streamFile } from "./helpers.js";
|
|
4
4
|
import { getContentType } from "./encoding.js";
|
|
5
|
+
const WELL_KNOWN = ".well-known";
|
|
6
|
+
function normalizeMount(apiPath) {
|
|
7
|
+
const trimmed = apiPath.replace(/\/+$/, "");
|
|
8
|
+
return trimmed === "" ? "/" : trimmed;
|
|
9
|
+
}
|
|
10
|
+
function relativeToMount(mount, requestPath) {
|
|
11
|
+
if (mount === "/")
|
|
12
|
+
return requestPath;
|
|
13
|
+
if (requestPath === mount)
|
|
14
|
+
return "/";
|
|
15
|
+
if (!requestPath.startsWith(`${mount}/`))
|
|
16
|
+
return null;
|
|
17
|
+
return requestPath.slice(mount.length);
|
|
18
|
+
}
|
|
19
|
+
function isAllowedRelative(relative, dotfiles) {
|
|
20
|
+
const segments = relative.split("/").filter(Boolean);
|
|
21
|
+
for (let i = 0; i < segments.length; i++) {
|
|
22
|
+
const segment = segments[i];
|
|
23
|
+
if (segment === "." || segment === "..")
|
|
24
|
+
return false;
|
|
25
|
+
if (segment.includes("\\") || segment.includes("\0"))
|
|
26
|
+
return false;
|
|
27
|
+
if (process.platform === "win32" && segment.includes(":"))
|
|
28
|
+
return false;
|
|
29
|
+
if (dotfiles)
|
|
30
|
+
continue;
|
|
31
|
+
if (!segment.startsWith("."))
|
|
32
|
+
continue;
|
|
33
|
+
if (i === 0 && segment === WELL_KNOWN)
|
|
34
|
+
continue;
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
5
39
|
export function handleSingleFile(filePath, opts) {
|
|
6
40
|
opts = {
|
|
7
41
|
utf8: true,
|
|
@@ -47,6 +81,7 @@ export function handleStaticFiles(dirPath, opts) {
|
|
|
47
81
|
renderData: {},
|
|
48
82
|
etag: true,
|
|
49
83
|
errorIfDirNotFound: true,
|
|
84
|
+
dotfiles: false,
|
|
50
85
|
...opts,
|
|
51
86
|
};
|
|
52
87
|
if (opts.errorIfDirNotFound && !fs.existsSync(dirPath)) {
|
|
@@ -59,9 +94,10 @@ export function handleStaticFiles(dirPath, opts) {
|
|
|
59
94
|
filePath.endsWith(ensureLeadingDot(defaultRenderer))) ||
|
|
60
95
|
(!opts.notRenderHtml && filePath.endsWith(".html"));
|
|
61
96
|
if (renderStatement) {
|
|
62
|
-
const relativePath =
|
|
63
|
-
.
|
|
64
|
-
.
|
|
97
|
+
const relativePath = path
|
|
98
|
+
.relative(path.resolve(dirPath), filePath)
|
|
99
|
+
.replaceAll(path.sep, "/")
|
|
100
|
+
.replace(/\.html$/, "");
|
|
65
101
|
res.render(filePath, opts.renderData?.[relativePath] || {}, {
|
|
66
102
|
notUseViews: true,
|
|
67
103
|
});
|
|
@@ -88,12 +124,16 @@ export function handleStaticFiles(dirPath, opts) {
|
|
|
88
124
|
return (req, res, next) => {
|
|
89
125
|
if (req.method !== "GET" && req.method !== "HEAD")
|
|
90
126
|
return next();
|
|
91
|
-
const
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
127
|
+
const mount = normalizeMount(req.middleware.path);
|
|
128
|
+
const relative = relativeToMount(mount, req.path);
|
|
129
|
+
if (relative === null)
|
|
130
|
+
return next();
|
|
131
|
+
if (!isAllowedRelative(relative, !!opts.dotfiles))
|
|
132
|
+
return next();
|
|
133
|
+
const root = path.resolve(dirPath);
|
|
134
|
+
const filePath = path.resolve(root, `.${relative === "/" ? "" : relative}`);
|
|
135
|
+
const rel = path.relative(root, filePath);
|
|
136
|
+
if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
|
|
97
137
|
return next();
|
|
98
138
|
try {
|
|
99
139
|
const stats = fs.statSync(filePath);
|
package/dist/types.d.ts
CHANGED
|
@@ -73,6 +73,10 @@ export declare class FFRequest extends http.IncomingMessage {
|
|
|
73
73
|
ip: string;
|
|
74
74
|
/** True when proxy headers were used to resolve `ip`. */
|
|
75
75
|
isProxied: boolean;
|
|
76
|
+
/** Request protocol, respects `x-forwarded-proto` from a trusted proxy. */
|
|
77
|
+
protocol: "http" | "https";
|
|
78
|
+
/** True when the request came over HTTPS, directly or via a trusted proxy. */
|
|
79
|
+
secure: boolean;
|
|
76
80
|
header: (name: string) => string;
|
|
77
81
|
valid: (schema: ValidationSchema, regexRules?: Record<string, RegExp | string>) => ValidationResult;
|
|
78
82
|
middleware: Middleware;
|
|
@@ -115,6 +119,8 @@ export interface StaticServeOptions {
|
|
|
115
119
|
etag?: boolean;
|
|
116
120
|
errorIfDirNotFound?: boolean;
|
|
117
121
|
notRenderHtml?: boolean;
|
|
122
|
+
/** Allow serving dotfiles. `.well-known` is always allowed as the first segment. Defaults to false. */
|
|
123
|
+
dotfiles?: boolean;
|
|
118
124
|
}
|
|
119
125
|
export interface StaticFileOptions {
|
|
120
126
|
utf8?: boolean;
|
package/dist/types.js
CHANGED
|
@@ -12,6 +12,10 @@ export class FFRequest extends http.IncomingMessage {
|
|
|
12
12
|
ip;
|
|
13
13
|
/** True when proxy headers were used to resolve `ip`. */
|
|
14
14
|
isProxied;
|
|
15
|
+
/** Request protocol, respects `x-forwarded-proto` from a trusted proxy. */
|
|
16
|
+
protocol;
|
|
17
|
+
/** True when the request came over HTTPS, directly or via a trusted proxy. */
|
|
18
|
+
secure;
|
|
15
19
|
header;
|
|
16
20
|
valid;
|
|
17
21
|
middleware;
|