@wxn0brp/falcon-frame 0.9.9 → 0.9.11

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/index.js CHANGED
@@ -1,41 +1,29 @@
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
- import { resolveConfig, isDebugEnabled } from "./config.js";
6
+ import { isDebugEnabled, resolveConfig } from "./config.js";
6
7
  import { createCORS } from "./cors.js";
7
8
  import { createDebug, generateDebugToken } from "./debug.js";
9
+ import { ErrorHandlers } from "./error-handlers.js";
10
+ import { formatListenHost, parseListenTarget } from "./helpers.js";
11
+ import { resolveHTTPSConfig } from "./https.js";
8
12
  import { renderHTML } from "./render.js";
9
13
  import { handleRequest } from "./req.js";
10
14
  import { FFResponse } from "./res.js";
11
15
  import { Router } from "./router.js";
16
+ import { isEnded } from "./safe.js";
12
17
  export class FalconFrame extends Router {
13
18
  logger;
19
+ httpsServer;
14
20
  bodyParsers = {};
15
21
  vars = {};
16
22
  opts = {};
17
23
  config;
18
24
  engines = {};
19
25
  _debug;
20
- _400_formatter = err => {
21
- return {
22
- err: true,
23
- msg: "Bad request",
24
- errors: err,
25
- };
26
- };
27
- _404 = (req, res) => {
28
- res.end("404: File had second thoughts");
29
- };
30
- _413 = (req, res) => {
31
- res.end("413: Cat is too fat");
32
- };
33
- _408 = (req, res) => {
34
- res.end("408: The request took a nap");
35
- };
36
- _500 = (err, req, res) => {
37
- res.end("500: The code had an existential crisis");
38
- };
26
+ errorHandlers = new ErrorHandlers();
39
27
  constructor(opts = {}) {
40
28
  super();
41
29
  const loggerOpts = opts?.loggerOpts || {};
@@ -120,41 +108,34 @@ export class FalconFrame extends Router {
120
108
  }
121
109
  listen(port, callback, beforeHandleRequest) {
122
110
  const server = http.createServer(this.getApp(beforeHandleRequest));
123
- let parsedPort = 0;
124
- let host = "";
125
- if (typeof port === "string") {
126
- if (port.includes(":")) {
127
- const [h, po] = port.split(":");
128
- host = h;
129
- parsedPort = +po;
130
- }
131
- else
132
- parsedPort = +port;
133
- }
134
- else if (typeof port === "number") {
135
- parsedPort = port;
136
- }
111
+ const { host = "", port: parsedPort } = parseListenTarget(port);
137
112
  let printUrl = false;
138
113
  if (typeof callback === "boolean") {
139
114
  printUrl = callback;
140
115
  callback = () => { };
141
116
  }
142
117
  const cb = callback || (() => { });
143
- server.listen(parsedPort, host || "0.0.0.0", () => {
118
+ server.listen(parsedPort, host || "::", () => {
144
119
  const address = server.address();
145
120
  const actualPort = address && typeof address === "object" ? address.port : parsedPort;
146
121
  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}`);
122
+ const shownHost = host ? formatListenHost(host) : "localhost";
123
+ console.log(`[FF] Server running on http://${shownHost}:${actualPort}`);
153
124
  }
125
+ this.printDebugUrl("http", host, actualPort);
154
126
  cb();
155
127
  });
156
128
  return server;
157
129
  }
130
+ printDebugUrl(scheme, host, port) {
131
+ if (!this._debug || !isDebugEnabled(this._debug.enabled))
132
+ return;
133
+ const urlHost = host && host !== "0.0.0.0" && host !== "::"
134
+ ? formatListenHost(host)
135
+ : "localhost";
136
+ const token = this._debug.generated ? `?pass=${this._debug.pass}` : "";
137
+ console.log(`[FF] Debug panel: ${scheme}://${urlHost}:${port}${this._debug.path}${token}`);
138
+ }
158
139
  /**
159
140
  * Mount the debug panel. Without an explicit `pass` a random token is
160
141
  * generated and printed together with the URL on `listen()`.
@@ -182,7 +163,7 @@ export class FalconFrame extends Router {
182
163
  return async (req, res) => {
183
164
  if (beforeHandleRequest) {
184
165
  const result = await beforeHandleRequest(req, res);
185
- if (result || res._ended)
166
+ if (result || isEnded(res))
186
167
  return;
187
168
  }
188
169
  handleRequest(req, res, this);
@@ -221,32 +202,54 @@ export class FalconFrame extends Router {
221
202
  }
222
203
  /**
223
204
  * Listens to the specified port, or the environment variable PORT if available.
224
- * @param port - The port number to listen to.
225
- * @returns The server object returned by the listen method.
205
+ * HTTPS starts as an additional server when `HTTPS_KEY` and `HTTPS_CERT` are set,
206
+ * on `HTTPS_PORT` (default 443).
207
+ * @param port - Port, `host:port`, `[::1]:port`, `[::]:port`, or `{ host, port }`.
208
+ * @returns The HTTP server object. The HTTPS server is available as `httpsServer`.
226
209
  */
227
210
  l(port) {
228
- return this.listen(+process.env.PORT || port, true);
211
+ const server = this.listen(+process.env.PORT || port, true);
212
+ const httpsConfig = resolveHTTPSConfig();
213
+ if (!httpsConfig)
214
+ return server;
215
+ this.httpsServer = https.createServer(httpsConfig.options, this.getApp());
216
+ this.httpsServer.listen(httpsConfig.port, "::", () => {
217
+ const address = this.httpsServer?.address();
218
+ const actualPort = address && typeof address === "object"
219
+ ? address.port
220
+ : httpsConfig.port;
221
+ console.log(`[FF] Server running on https://localhost:${actualPort}`);
222
+ this.printDebugUrl("https", "::", actualPort);
223
+ });
224
+ return server;
229
225
  }
226
+ /** @deprecated use `app.errorHandlers.set400Formatter` */
230
227
  set400Formatter(formatter) {
231
- this._400_formatter = formatter;
228
+ this.errorHandlers.set400Formatter(formatter);
232
229
  }
230
+ /** @deprecated use `app.errorHandlers.set404` */
233
231
  set404(handler) {
234
- this._404 = handler;
232
+ this.errorHandlers.set404(handler);
235
233
  }
234
+ /** @deprecated use `app.errorHandlers.set413` */
236
235
  set413(handler) {
237
- this._413 = handler;
236
+ this.errorHandlers.set413(handler);
238
237
  }
238
+ /** @deprecated use `app.errorHandlers.set408` */
239
239
  set408(handler) {
240
- this._408 = handler;
240
+ this.errorHandlers.set408(handler);
241
241
  }
242
+ /** @deprecated use `app.errorHandlers.set500` */
242
243
  set500(handler) {
243
- this._500 = handler;
244
+ this.errorHandlers.set500(handler);
244
245
  }
245
246
  }
246
247
  export default FalconFrame;
247
- export { OfflineEngine } from "./engine.js";
248
- export * as Helpers from "./helpers.js";
249
248
  export { compression, compressionMiddleware } from "./compress.js";
250
249
  export { createDebug, generateDebugToken } from "./debug.js";
250
+ export { OfflineEngine } from "./engine.js";
251
+ export { ErrorHandlers } from "./error-handlers.js";
252
+ export * as Helpers from "./helpers.js";
253
+ export { resolveHTTPSConfig } from "./https.js";
251
254
  export { validateBody } from "./valid.js";
252
255
  export { FFResponse, renderHTML, Router, };
@@ -59,7 +59,17 @@ export function getMiddlewares(middlewares, matchUrl, basePath = "") {
59
59
  continue;
60
60
  if (middleware.router) {
61
61
  const nested = getMiddlewares(middleware.router, matchUrl, fullPath);
62
- result.push(...nested);
62
+ if (middleware.api) {
63
+ result.push(...nested.map(m => m.api
64
+ ? m
65
+ : {
66
+ ...m,
67
+ api: true,
68
+ }));
69
+ }
70
+ else {
71
+ result.push(...nested);
72
+ }
63
73
  }
64
74
  else {
65
75
  result.push({
package/dist/req.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { randomUUID } from "crypto";
2
2
  import { URL } from "url";
3
3
  import { getContentType, getRawBody } from "./body-utils.js";
4
+ import { createChain } from "./chain.js";
4
5
  import { parseCookies, resolveRequestInfo } from "./helpers.js";
6
+ import { isEnded, safe404, safe408, safe500 } from "./safe.js";
5
7
  import { extractParams, getMiddlewares, matchMiddleware } from "./middleware.js";
6
8
  import { FFResponse } from "./res.js";
7
9
  import { validate } from "./valid.js";
@@ -10,11 +12,6 @@ export function handleRequest(req, res, FF, reRoute = false) {
10
12
  Object.setPrototypeOf(res, FFResponse.prototype);
11
13
  req.FF = FF;
12
14
  res.FF = FF;
13
- const originalEnd = res.end;
14
- res.end = (...any) => {
15
- res._ended = true;
16
- return originalEnd.call(res, ...any);
17
- };
18
15
  }
19
16
  const { logger } = FF;
20
17
  try {
@@ -34,6 +31,8 @@ export function handleRequest(req, res, FF, reRoute = false) {
34
31
  req.socketIp = requestInfo.socketIp;
35
32
  req.ip = requestInfo.ip;
36
33
  req.isProxied = requestInfo.isProxied;
34
+ req.protocol = requestInfo.protocol;
35
+ req.secure = requestInfo.protocol === "https";
37
36
  req.params = {};
38
37
  req.valid = (schema, regexRules) => validate({
39
38
  schema,
@@ -68,47 +67,39 @@ export function handleRequest(req, res, FF, reRoute = false) {
68
67
  logger.debug("Matched middlewares: " +
69
68
  matchedMiddlewares.map(middleware => middleware.path).join(", "));
70
69
  if (matchedMiddlewares.length === 0) {
71
- res.status(404);
72
- FF._404(req, res);
70
+ safe404(req, res);
73
71
  return;
74
72
  }
75
- let middlewareIndex = 0;
76
- async function next() {
77
- if (middlewareIndex >= matchedMiddlewares.length) {
78
- res.status(404);
79
- FF._404(req, res);
80
- return;
81
- }
82
- const middleware = matchedMiddlewares[middlewareIndex++];
83
- logger.debug(`Executing middleware ${middlewareIndex} of ${matchedMiddlewares.length} matched for path [${middleware.path}]`);
84
- req.params = extractParams(middleware.path, req.path);
85
- req.middleware = middleware;
86
- try {
87
- const result = await middleware.middleware(req, res, next);
88
- if (result && !res._ended) {
89
- if (typeof result === "string") {
90
- return res.end(result);
91
- }
92
- else if (typeof result === "object") {
93
- if (result instanceof FFResponse)
94
- return res.end();
95
- return res.json(result);
96
- }
73
+ let started = 0;
74
+ const next = createChain(req, res, matchedMiddlewares, {
75
+ start(middleware) {
76
+ logger.debug(`Executing middleware ${++started} of ${matchedMiddlewares.length} matched for path [${middleware.path}]`);
77
+ req.params = extractParams(middleware.path, req.path);
78
+ req.middleware = middleware;
79
+ },
80
+ result(result) {
81
+ if (typeof result === "string") {
82
+ return res.end(result);
97
83
  }
98
- }
99
- catch (err) {
100
- logger.error(`Unhandled error in middleware for path [${middleware.path}]:`, err.stack || err);
101
- if (!res.headersSent && !res.writableEnded) {
102
- res.status(500);
103
- FF._500(err, req, res);
84
+ else if (typeof result === "object") {
85
+ if (result instanceof FFResponse)
86
+ return res.end();
87
+ return res.json(result);
104
88
  }
105
- }
106
- }
89
+ },
90
+ error(err, middleware) {
91
+ logger.error(`Unhandled error in middleware for path [${middleware.path}]:`, err.stack || err);
92
+ safe500(err, req, res, middleware);
93
+ },
94
+ exhausted() {
95
+ safe404(req, res);
96
+ },
97
+ });
107
98
  const hasCustomParserEndpoint = matchedMiddlewares.some(middleware => middleware.customParser);
108
99
  if (hasCustomParserEndpoint) {
109
100
  logger.debug("Executing custom parser endpoint");
110
101
  req.body = {};
111
- next();
102
+ void next();
112
103
  return;
113
104
  }
114
105
  if (req.method === "GET" ||
@@ -116,12 +107,12 @@ export function handleRequest(req, res, FF, reRoute = false) {
116
107
  req.method === "OPTIONS") {
117
108
  logger.debug("Method does not require body. Executing middlewares");
118
109
  req.body = {};
119
- next();
110
+ void next();
120
111
  return;
121
112
  }
122
113
  if (reRoute) {
123
114
  logger.debug("Re-route. Executing middlewares");
124
- next();
115
+ void next();
125
116
  return;
126
117
  }
127
118
  req.body = {};
@@ -137,7 +128,7 @@ export function handleRequest(req, res, FF, reRoute = false) {
137
128
  else {
138
129
  logger.debug("No content-type. Executing middlewares");
139
130
  }
140
- next();
131
+ void next();
141
132
  return;
142
133
  }
143
134
  logger.debug(`Executing body parser for content-type: ${ct ?? "default (json)"}`);
@@ -148,22 +139,21 @@ export function handleRequest(req, res, FF, reRoute = false) {
148
139
  req.isBodyParsed = true;
149
140
  }
150
141
  catch (err) {
151
- if (!res._ended)
142
+ if (!isEnded(res))
152
143
  req.body = {};
153
144
  }
154
- next();
145
+ void next();
155
146
  })
156
147
  .catch((err) => {
157
- if (res._ended)
148
+ if (isEnded(res))
158
149
  return;
159
150
  if (err?.statusCode === 408) {
160
- res.status(408);
161
- res.FF._408(req, res);
151
+ safe408(req, res);
162
152
  if (!res.writableEnded)
163
153
  res.end();
164
154
  return;
165
155
  }
166
156
  req.body = {};
167
- next();
157
+ void next();
168
158
  });
169
159
  }
package/dist/res.d.ts CHANGED
@@ -2,7 +2,6 @@ import http from "http";
2
2
  import FalconFrame from "./index.js";
3
3
  import { CookieOptions, RenderOptions } from "./types.js";
4
4
  export declare class FFResponse extends http.ServerResponse {
5
- _ended: boolean;
6
5
  FF: FalconFrame<any>;
7
6
  /**
8
7
  * bind end for compatibility
package/dist/res.js CHANGED
@@ -3,7 +3,6 @@ import path from "path";
3
3
  import { getContentType } from "./encoding.js";
4
4
  import { ensureLeadingDot, streamFile } from "./helpers.js";
5
5
  export class FFResponse extends http.ServerResponse {
6
- _ended = false;
7
6
  FF;
8
7
  /**
9
8
  * bind end for compatibility
@@ -101,7 +100,6 @@ export class FFResponse extends http.ServerResponse {
101
100
  contentType = getContentType(filePath, true);
102
101
  this.ct(contentType || getContentType(filePath));
103
102
  streamFile(this, filePath);
104
- this._ended = true;
105
103
  return this;
106
104
  }
107
105
  /**
package/dist/router.d.ts CHANGED
@@ -5,6 +5,7 @@ export type MiddlewareFn = RouteHandler | Router | {
5
5
  };
6
6
  export declare class Router {
7
7
  middlewares: Middleware[];
8
+ isApi: boolean;
8
9
  addRoute(method: Method, path: string, ...handlers: RouteHandler[]): number;
9
10
  use(path?: string | MiddlewareFn, middlewareFn?: MiddlewareFn, method?: Method): this;
10
11
  get(path: string, ...handlers: RouteHandler[]): this;
@@ -13,9 +14,12 @@ export declare class Router {
13
14
  delete(path: string, ...handlers: RouteHandler[]): this;
14
15
  patch(path: string, ...handlers: RouteHandler[]): this;
15
16
  all(path: string, ...handlers: RouteHandler[]): this;
16
- static(apiPath: string, dirPath?: string, opts?: StaticServeOptions): this;
17
+ static(dirPath: string, opts?: StaticServeOptions): this;
18
+ static(apiPath: string, dirPath: string, opts?: StaticServeOptions): this;
17
19
  file(routePath: string, filePath: string, opts?: StaticFileOptions): this;
18
20
  sse(path: string, ...handlers: RouteHandler[]): SSEManager;
19
21
  customParser(path: string, handler: RouteHandler, method?: Method): this;
20
- router(path?: string): Router;
22
+ router(path?: string, opts?: {
23
+ api?: boolean;
24
+ }): Router;
21
25
  }
package/dist/router.js CHANGED
@@ -2,6 +2,7 @@ import { SSEManager } from "./sse.js";
2
2
  import { handleSingleFile, handleStaticFiles } from "./static.js";
3
3
  export class Router {
4
4
  middlewares = [];
5
+ isApi = true;
5
6
  addRoute(method, path, ...handlers) {
6
7
  const handler = handlers.pop();
7
8
  handlers.forEach(middleware => this.use(path, middleware));
@@ -23,6 +24,8 @@ export class Router {
23
24
  use: true,
24
25
  };
25
26
  if (middlewareFn instanceof Router) {
27
+ if (middlewareFn.isApi)
28
+ middleware.api = true;
26
29
  middleware.router = middlewareFn.middlewares;
27
30
  }
28
31
  else if ("getRouteHandler" in middlewareFn) {
@@ -58,10 +61,18 @@ export class Router {
58
61
  this.addRoute("all", path, ...handlers);
59
62
  return this;
60
63
  }
61
- static(apiPath, dirPath, opts = {}) {
62
- if (!dirPath) {
63
- dirPath = apiPath;
64
+ static(apiPathOrDir, dirOrOpts, maybeOpts = {}) {
65
+ let apiPath = apiPathOrDir;
66
+ let dirPath;
67
+ let opts;
68
+ if (typeof dirOrOpts === "string") {
69
+ dirPath = dirOrOpts;
70
+ opts = maybeOpts;
71
+ }
72
+ else {
73
+ dirPath = apiPathOrDir;
64
74
  apiPath = "/";
75
+ opts = dirOrOpts ?? {};
65
76
  }
66
77
  if (dirPath === "/")
67
78
  throw new Error("Cannot serve root directory");
@@ -84,8 +95,9 @@ export class Router {
84
95
  this.middlewares[index - 1].customParser = true;
85
96
  return this;
86
97
  }
87
- router(path = "/") {
98
+ router(path = "/", opts = {}) {
88
99
  const router = new Router();
100
+ router.isApi = opts.api ?? true;
89
101
  this.use(path, router);
90
102
  return router;
91
103
  }
package/dist/safe.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import type FalconFrame from "./index.js";
2
+ import type { FFResponse } from "./res.js";
3
+ import type { FFRequest, Middleware } from "./types.js";
4
+ export declare function isEnded(res: FFResponse): boolean;
5
+ export declare function isApiRequest(req: FFRequest, ff: FalconFrame<any>, middleware?: Middleware): boolean;
6
+ export declare function safe500(err: Error, req: FFRequest, res: FFResponse, middleware?: Middleware): void;
7
+ export declare function safe404(req: FFRequest, res: FFResponse): void;
8
+ export declare function safe413(req: FFRequest, res: FFResponse): void;
9
+ export declare function safe408(req: FFRequest, res: FFResponse): void;
package/dist/safe.js ADDED
@@ -0,0 +1,79 @@
1
+ export function isEnded(res) {
2
+ return res.writableEnded || res.destroyed || res.headersSent;
3
+ }
4
+ export function isApiRequest(req, ff, middleware) {
5
+ const accept = req.headers["accept"];
6
+ if (typeof accept === "string" && accept.includes("text/html")) {
7
+ return false;
8
+ }
9
+ if (middleware?.api)
10
+ return true;
11
+ if (typeof accept === "string" && accept.includes("application/json")) {
12
+ return true;
13
+ }
14
+ return false;
15
+ }
16
+ export function safe500(err, req, res, middleware) {
17
+ if (isEnded(res))
18
+ return;
19
+ res.status(500);
20
+ const ff = req.FF || res.FF;
21
+ const handler = isApiRequest(req, ff, middleware)
22
+ ? ff.errorHandlers._500Api
23
+ : ff.errorHandlers._500;
24
+ try {
25
+ handler(err, req, res);
26
+ }
27
+ catch (e) {
28
+ ff.logger.error("Error in 500 handler:", e?.stack || e);
29
+ if (!isEnded(res))
30
+ res.end("Internal Server Error");
31
+ }
32
+ }
33
+ export function safe404(req, res) {
34
+ if (isEnded(res))
35
+ return;
36
+ res.status(404);
37
+ const ff = req.FF || res.FF;
38
+ const handler = isApiRequest(req, ff)
39
+ ? ff.errorHandlers._404Api
40
+ : ff.errorHandlers._404;
41
+ try {
42
+ handler(req, res);
43
+ }
44
+ catch (e) {
45
+ ff.logger.error("Error in 404 handler:", e?.stack || e);
46
+ if (!isEnded(res))
47
+ res.end("Not Found");
48
+ }
49
+ }
50
+ export function safe413(req, res) {
51
+ res.status(413);
52
+ const ff = req.FF || res.FF;
53
+ const handler = isApiRequest(req, ff)
54
+ ? ff.errorHandlers._413Api
55
+ : ff.errorHandlers._413;
56
+ try {
57
+ handler(req, res);
58
+ }
59
+ catch (e) {
60
+ ff.logger.error("Error in 413 handler:", e?.stack || e);
61
+ if (!isEnded(res))
62
+ res.end("Payload Too Large");
63
+ }
64
+ }
65
+ export function safe408(req, res) {
66
+ res.status(408);
67
+ const ff = req.FF || res.FF;
68
+ const handler = isApiRequest(req, ff)
69
+ ? ff.errorHandlers._408Api
70
+ : ff.errorHandlers._408;
71
+ try {
72
+ handler(req, res);
73
+ }
74
+ catch (e) {
75
+ ff.logger.error("Error in 408 handler:", e?.stack || e);
76
+ if (!isEnded(res))
77
+ res.end("Request Timeout");
78
+ }
79
+ }
package/dist/static.js CHANGED
@@ -1,7 +1,42 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
3
  import { ensureLeadingDot, streamFile } from "./helpers.js";
4
+ import { safe404 } from "./safe.js";
4
5
  import { getContentType } from "./encoding.js";
6
+ const WELL_KNOWN = ".well-known";
7
+ function normalizeMount(apiPath) {
8
+ const trimmed = apiPath.replace(/\/+$/, "");
9
+ return trimmed === "" ? "/" : trimmed;
10
+ }
11
+ function relativeToMount(mount, requestPath) {
12
+ if (mount === "/")
13
+ return requestPath;
14
+ if (requestPath === mount)
15
+ return "/";
16
+ if (!requestPath.startsWith(`${mount}/`))
17
+ return null;
18
+ return requestPath.slice(mount.length);
19
+ }
20
+ function isAllowedRelative(relative, dotfiles) {
21
+ const segments = relative.split("/").filter(Boolean);
22
+ for (let i = 0; i < segments.length; i++) {
23
+ const segment = segments[i];
24
+ if (segment === "." || segment === "..")
25
+ return false;
26
+ if (segment.includes("\\") || segment.includes("\0"))
27
+ return false;
28
+ if (process.platform === "win32" && segment.includes(":"))
29
+ return false;
30
+ if (dotfiles)
31
+ continue;
32
+ if (!segment.startsWith("."))
33
+ continue;
34
+ if (i === 0 && segment === WELL_KNOWN)
35
+ continue;
36
+ return false;
37
+ }
38
+ return true;
39
+ }
5
40
  export function handleSingleFile(filePath, opts) {
6
41
  opts = {
7
42
  utf8: true,
@@ -19,8 +54,7 @@ export function handleSingleFile(filePath, opts) {
19
54
  stats = fs.statSync(filePath);
20
55
  }
21
56
  catch (e) {
22
- res.statusCode = 404;
23
- res.FF._404(req, res);
57
+ safe404(req, res);
24
58
  return;
25
59
  }
26
60
  if (opts.etag) {
@@ -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 = filePath
63
- .replace(dirPath + "/", "")
64
- .replace(".html", "");
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 apiPath = req.middleware.path;
92
- const unsafePath = req.path.replace(apiPath, "");
93
- const filePath = path.join(dirPath, path.normalize(unsafePath));
94
- const resolvedPath = path.resolve(filePath);
95
- const resolvedDir = path.resolve(dirPath);
96
- if (!resolvedPath.startsWith(resolvedDir))
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);