zawit 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,179 @@
1
+ import { Router } from './router.js';
2
+ import { Context, HttpError } from './context.js';
3
+ import { compose } from './compose.js';
4
+ import { createNodeServer } from '../adapters/node.js';
5
+ import { loadFileRoutes } from '../routing/file-router.js';
6
+
7
+ /**
8
+ * Zawit Web & API Framework.
9
+ */
10
+ export class Zawit {
11
+ /**
12
+ * @param {{ maxBodyBytes?: number }} [options]
13
+ */
14
+ constructor(options = {}) {
15
+ this.router = new Router();
16
+ /** @type {Array<{ prefix: string | null, fn: Function }>} */
17
+ this.middlewares = [];
18
+ this.options = options;
19
+
20
+ this._notFoundHandler = (ctx) => ctx.json({ error: 'Not Found' }, 404);
21
+ this._errorHandler = (err, ctx) => {
22
+ if (err instanceof HttpError && err.expose) {
23
+ return ctx.json({ error: err.message }, err.status);
24
+ }
25
+ return ctx.json({ error: 'Internal Server Error' }, 500);
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Register middleware globally or scoped to a path prefix.
31
+ * @param {string | Function} pathOrFn
32
+ * @param {Function} [fn]
33
+ * @returns {this}
34
+ */
35
+ use(pathOrFn, fn) {
36
+ if (typeof pathOrFn === 'function') {
37
+ this.middlewares.push({ prefix: null, fn: pathOrFn });
38
+ } else if (typeof pathOrFn === 'string' && typeof fn === 'function') {
39
+ const prefix = pathOrFn.endsWith('/') && pathOrFn.length > 1 ? pathOrFn.slice(0, -1) : pathOrFn;
40
+ this.middlewares.push({ prefix, fn });
41
+ }
42
+ return this;
43
+ }
44
+
45
+ /**
46
+ * Register a route for a given HTTP method.
47
+ * @param {string} method
48
+ * @param {string} path
49
+ * @param {Function} handler
50
+ * @returns {this}
51
+ */
52
+ on(method, path, handler) {
53
+ this.router.add(method, path, handler);
54
+ return this;
55
+ }
56
+
57
+ get(path, handler) { return this.on('GET', path, handler); }
58
+ post(path, handler) { return this.on('POST', path, handler); }
59
+ put(path, handler) { return this.on('PUT', path, handler); }
60
+ patch(path, handler) { return this.on('PATCH', path, handler); }
61
+ delete(path, handler) { return this.on('DELETE', path, handler); }
62
+ options(path, handler) { return this.on('OPTIONS', path, handler); }
63
+ all(path, handler) { return this.on('ALL', path, handler); }
64
+
65
+ /**
66
+ * Group routes under a shared path prefix.
67
+ * @param {string} prefix
68
+ * @param {(group: object) => void} callback
69
+ * @returns {this}
70
+ */
71
+ group(prefix, callback) {
72
+ const cleanPrefix = prefix.endsWith('/') && prefix.length > 1 ? prefix.slice(0, -1) : prefix;
73
+ const join = (p) => (p === '/' ? cleanPrefix : `${cleanPrefix}${p.startsWith('/') ? p : `/${p}`}`);
74
+
75
+ const scoped = {
76
+ on: (m, p, h) => this.on(m, join(p), h),
77
+ get: (p, h) => this.get(join(p), h),
78
+ post: (p, h) => this.post(join(p), h),
79
+ put: (p, h) => this.put(join(p), h),
80
+ patch: (p, h) => this.patch(join(p), h),
81
+ delete: (p, h) => this.delete(join(p), h),
82
+ all: (p, h) => this.all(join(p), h),
83
+ use: (fn) => this.use(cleanPrefix, fn)
84
+ };
85
+
86
+ callback(scoped);
87
+ return this;
88
+ }
89
+
90
+ /**
91
+ * Auto-register Next.js-style file-based routes from a directory.
92
+ * @param {string} dir
93
+ * @returns {Promise<this>}
94
+ */
95
+ async routesDir(dir) {
96
+ await loadFileRoutes(this, dir);
97
+ return this;
98
+ }
99
+
100
+ /**
101
+ * Customize 404 Not Found handler.
102
+ * @param {(ctx: Context) => Response | Promise<Response>} handler
103
+ * @returns {this}
104
+ */
105
+ notFound(handler) {
106
+ this._notFoundHandler = handler;
107
+ return this;
108
+ }
109
+
110
+ /**
111
+ * Customize error handler.
112
+ * @param {(err: Error, ctx: Context) => Response | Promise<Response>} handler
113
+ * @returns {this}
114
+ */
115
+ onError(handler) {
116
+ this._errorHandler = handler;
117
+ return this;
118
+ }
119
+
120
+ /**
121
+ * Web-Standard fetch handler: (Request) => Promise<Response>.
122
+ * @param {Request} request
123
+ * @param {{ rawReq?: any, rawRes?: any }} [meta]
124
+ * @returns {Promise<Response>}
125
+ */
126
+ async fetch(request, meta = {}) {
127
+ const ctx = new Context(request, {
128
+ maxBodyBytes: this.options.maxBodyBytes,
129
+ rawReq: meta.rawReq,
130
+ rawRes: meta.rawRes
131
+ });
132
+
133
+ const activeMiddlewares = this.middlewares
134
+ .filter((m) => !m.prefix || ctx.path === m.prefix || ctx.path.startsWith(`${m.prefix}/`))
135
+ .map((m) => m.fn);
136
+
137
+ const runPipeline = compose(activeMiddlewares);
138
+
139
+ try {
140
+ await runPipeline(ctx, async () => {
141
+ const matched = this.router.match(ctx.method, ctx.path);
142
+ if (!matched) {
143
+ const nf = await this._notFoundHandler(ctx);
144
+ if (nf instanceof Response) ctx.res = nf;
145
+ return;
146
+ }
147
+
148
+ ctx.params = matched.params;
149
+ const result = await matched.handler(ctx);
150
+ if (result instanceof Response) {
151
+ ctx.res = result;
152
+ } else if (!ctx.res && result !== undefined) {
153
+ if (typeof result === 'string') ctx.text(result);
154
+ else ctx.json(result);
155
+ }
156
+ });
157
+
158
+ return ctx.res ?? (await this._notFoundHandler(ctx));
159
+ } catch (err) {
160
+ const handled = await this._errorHandler(err, ctx);
161
+ return handled instanceof Response ? handled : ctx.json({ error: 'Internal Server Error' }, 500);
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Start a Node.js HTTP server.
167
+ * @param {number} [port=3000]
168
+ * @param {string | (() => void)} [hostOrCallback]
169
+ * @param {() => void} [callback]
170
+ * @returns {import('node:http').Server}
171
+ */
172
+ listen(port = 3000, hostOrCallback, callback) {
173
+ const host = typeof hostOrCallback === 'string' ? hostOrCallback : undefined;
174
+ const cb = typeof hostOrCallback === 'function' ? hostOrCallback : callback;
175
+ const server = createNodeServer(this);
176
+ server.listen(port, host, cb);
177
+ return server;
178
+ }
179
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Compose an array of async middlewares into a single onion-model pipeline.
3
+ * @param {Array<(ctx: any, next: () => Promise<void>) => Promise<any> | any>} middlewares
4
+ * @returns {(ctx: any, finalHandler?: () => Promise<any>) => Promise<any>}
5
+ */
6
+ export function compose(middlewares) {
7
+ return function run(ctx, finalHandler) {
8
+ let index = -1;
9
+
10
+ function dispatch(i) {
11
+ if (i <= index) {
12
+ return Promise.reject(new Error('next() called multiple times'));
13
+ }
14
+ index = i;
15
+
16
+ const fn = i < middlewares.length ? middlewares[i] : finalHandler;
17
+ if (!fn) return Promise.resolve();
18
+
19
+ try {
20
+ return Promise.resolve(fn(ctx, () => dispatch(i + 1)));
21
+ } catch (err) {
22
+ return Promise.reject(err);
23
+ }
24
+ }
25
+
26
+ return dispatch(0);
27
+ };
28
+ }
@@ -0,0 +1,187 @@
1
+ import { renderDocument } from '../seo/index.js';
2
+
3
+ const DEFAULT_MAX_BODY_BYTES = 1024 * 1024; // 1MB
4
+ const UNSAFE_REDIRECT_SCHEME = /^\s*(javascript|data|vbscript):/i;
5
+
6
+ /**
7
+ * HTTP-aware error for clean client-safe status responses.
8
+ */
9
+ export class HttpError extends Error {
10
+ constructor(status, message) {
11
+ super(message);
12
+ this.status = status;
13
+ this.expose = true;
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Request/Response context passed to every route handler and middleware.
19
+ */
20
+ export class Context {
21
+ /**
22
+ * @param {Request} request
23
+ * @param {{ maxBodyBytes?: number, rawReq?: any, rawRes?: any }} [options]
24
+ */
25
+ constructor(request, options = {}) {
26
+ this.req = request;
27
+ this.url = new URL(request.url);
28
+ this.method = request.method.toUpperCase();
29
+ this.path = this.url.pathname;
30
+ this.params = {};
31
+ this.state = {};
32
+ this.res = null;
33
+
34
+ this._status = 200;
35
+ this._headers = new Headers();
36
+ this._maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
37
+ this._bodyText = undefined;
38
+ this._rawReq = options.rawReq ?? null;
39
+ this._rawRes = options.rawRes ?? null;
40
+ }
41
+
42
+ /**
43
+ * Parsed URL query parameters as a plain object.
44
+ * @returns {Record<string, string>}
45
+ */
46
+ get query() {
47
+ return Object.fromEntries(this.url.searchParams.entries());
48
+ }
49
+
50
+ /**
51
+ * Read a request header (case-insensitive).
52
+ * @param {string} name
53
+ * @returns {string | null}
54
+ */
55
+ header(name) {
56
+ return this.req.headers.get(name);
57
+ }
58
+
59
+ /**
60
+ * Set the response HTTP status code (chainable).
61
+ * @param {number} code
62
+ * @returns {this}
63
+ */
64
+ status(code) {
65
+ this._status = code;
66
+ return this;
67
+ }
68
+
69
+ /**
70
+ * Set a response header (chainable).
71
+ * @param {string} name
72
+ * @param {string} value
73
+ * @returns {this}
74
+ */
75
+ set(name, value) {
76
+ this._headers.set(name, value);
77
+ return this;
78
+ }
79
+
80
+ /**
81
+ * Read request body as UTF-8 text with size limit enforcement.
82
+ * @returns {Promise<string>}
83
+ */
84
+ async textBody() {
85
+ if (this._bodyText !== undefined) return this._bodyText;
86
+ const buf = await this.req.arrayBuffer();
87
+ if (buf.byteLength > this._maxBodyBytes) {
88
+ throw new HttpError(413, 'Payload Too Large');
89
+ }
90
+ this._bodyText = new TextDecoder().decode(buf);
91
+ return this._bodyText;
92
+ }
93
+
94
+ /**
95
+ * Parse request body as JSON. Rejects malformed JSON with 400 Bad Request.
96
+ * @returns {Promise<any>}
97
+ */
98
+ async body() {
99
+ const raw = await this.textBody();
100
+ if (!raw.trim()) return {};
101
+ try {
102
+ return JSON.parse(raw);
103
+ } catch {
104
+ throw new HttpError(400, 'Invalid JSON body');
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Send a JSON response.
110
+ * @param {unknown} data
111
+ * @param {number} [status]
112
+ * @returns {Response}
113
+ */
114
+ json(data, status = this._status) {
115
+ this._headers.set('Content-Type', 'application/json; charset=utf-8');
116
+ this.res = new Response(JSON.stringify(data), {
117
+ status,
118
+ headers: this._headers
119
+ });
120
+ return this.res;
121
+ }
122
+
123
+ /**
124
+ * Send a plain text response.
125
+ * @param {string} text
126
+ * @param {number} [status]
127
+ * @returns {Response}
128
+ */
129
+ text(text, status = this._status) {
130
+ if (!this._headers.has('Content-Type')) {
131
+ this._headers.set('Content-Type', 'text/plain; charset=utf-8');
132
+ }
133
+ this.res = new Response(String(text), {
134
+ status,
135
+ headers: this._headers
136
+ });
137
+ return this.res;
138
+ }
139
+
140
+ /**
141
+ * Send an HTML response, optionally wrapping in an SEO-ready HTML5 document.
142
+ * @param {string} html
143
+ * @param {number | { status?: number, seo?: object, lang?: string, headExtra?: string }} [statusOrOptions]
144
+ * @returns {Response}
145
+ */
146
+ html(html, statusOrOptions = this._status) {
147
+ let status = this._status;
148
+ let output = String(html);
149
+
150
+ if (typeof statusOrOptions === 'number') {
151
+ status = statusOrOptions;
152
+ } else if (statusOrOptions && typeof statusOrOptions === 'object') {
153
+ status = statusOrOptions.status ?? this._status;
154
+ if (statusOrOptions.seo) {
155
+ output = renderDocument({
156
+ seo: statusOrOptions.seo,
157
+ body: output,
158
+ lang: statusOrOptions.lang,
159
+ headExtra: statusOrOptions.headExtra
160
+ });
161
+ }
162
+ }
163
+
164
+ this._headers.set('Content-Type', 'text/html; charset=utf-8');
165
+ this.res = new Response(output, {
166
+ status,
167
+ headers: this._headers
168
+ });
169
+ return this.res;
170
+ }
171
+
172
+ /**
173
+ * Redirect safely, rejecting CRLF injection and dangerous URI schemes.
174
+ * @param {string} url
175
+ * @param {number} [status]
176
+ * @returns {Response}
177
+ */
178
+ redirect(url, status = 302) {
179
+ const target = String(url);
180
+ if (/[\r\n]/.test(target) || UNSAFE_REDIRECT_SCHEME.test(target)) {
181
+ throw new HttpError(400, 'Invalid redirect URL');
182
+ }
183
+ this._headers.set('Location', target);
184
+ this.res = new Response(null, { status, headers: this._headers });
185
+ return this.res;
186
+ }
187
+ }
@@ -0,0 +1,89 @@
1
+ function normalizePath(path) {
2
+ if (!path || path === '/') return '/';
3
+ const cleaned = path.startsWith('/') ? path : `/${path}`;
4
+ return cleaned.length > 1 && cleaned.endsWith('/') ? cleaned.slice(0, -1) : cleaned;
5
+ }
6
+
7
+ function splitSegments(path) {
8
+ const normalized = normalizePath(path);
9
+ return normalized === '/' ? [] : normalized.slice(1).split('/');
10
+ }
11
+
12
+ /**
13
+ * Lightweight segment-based HTTP router supporting static, :param, and * wildcard routes.
14
+ */
15
+ export class Router {
16
+ constructor() {
17
+ /** @type {Array<{ method: string, path: string, segments: string[], handler: Function }>} */
18
+ this.routes = [];
19
+ }
20
+
21
+ /**
22
+ * Register a route.
23
+ * @param {string} method
24
+ * @param {string} path
25
+ * @param {Function} handler
26
+ */
27
+ add(method, path, handler) {
28
+ const normalized = normalizePath(path);
29
+ this.routes.push({
30
+ method: method.toUpperCase(),
31
+ path: normalized,
32
+ segments: splitSegments(normalized),
33
+ handler
34
+ });
35
+ }
36
+
37
+ /**
38
+ * Match an incoming method + pathname against registered routes.
39
+ * @param {string} method
40
+ * @param {string} pathname
41
+ * @returns {{ handler: Function, params: Record<string, string> } | null}
42
+ */
43
+ match(method, pathname) {
44
+ const upperMethod = method.toUpperCase();
45
+ const reqSegments = splitSegments(pathname);
46
+
47
+ for (const route of this.routes) {
48
+ if (route.method !== 'ALL' && route.method !== upperMethod) continue;
49
+
50
+ const params = matchSegments(route.segments, reqSegments);
51
+ if (params !== null) {
52
+ return { handler: route.handler, params };
53
+ }
54
+ }
55
+
56
+ return null;
57
+ }
58
+ }
59
+
60
+ function matchSegments(routeSegs, reqSegs) {
61
+ const params = {};
62
+
63
+ for (let i = 0; i < routeSegs.length; i++) {
64
+ const seg = routeSegs[i];
65
+
66
+ if (seg === '*') {
67
+ params['*'] = reqSegs.slice(i).map(safeDecode).join('/');
68
+ return params;
69
+ }
70
+
71
+ if (i >= reqSegs.length) return null;
72
+
73
+ if (seg.startsWith(':')) {
74
+ params[seg.slice(1)] = safeDecode(reqSegs[i]);
75
+ } else if (seg !== reqSegs[i]) {
76
+ return null;
77
+ }
78
+ }
79
+
80
+ return routeSegs.length === reqSegs.length ? params : null;
81
+ }
82
+
83
+ function safeDecode(value) {
84
+ try {
85
+ return decodeURIComponent(value);
86
+ } catch {
87
+ return value;
88
+ }
89
+ }
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { Zawit } from './core/app.js';
2
+ export { Context, HttpError } from './core/context.js';
3
+ export { Router } from './core/router.js';
4
+ export { compose } from './core/compose.js';
5
+ export { loadFileRoutes, filePathToRoute } from './routing/file-router.js';
6
+ export { logger, cors, serveStatic, securityHeaders } from './middleware/index.js';
7
+ export { renderHead, renderDocument, sitemap, robotsTxt, escapeHtml } from './seo/index.js';
8
+ export { adaptExpress } from './adapters/express.js';
9
+ export { createNodeServer } from './adapters/node.js';
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Security-hardened CORS middleware.
3
+ * Prevents wildcard '*' + credentials: true and rejects 'null' origin by default.
4
+ *
5
+ * @param {{
6
+ * origin?: string | string[] | ((origin: string, ctx: any) => boolean),
7
+ * methods?: string[],
8
+ * allowedHeaders?: string[],
9
+ * credentials?: boolean,
10
+ * maxAge?: number
11
+ * }} [options]
12
+ */
13
+ export function cors(options = {}) {
14
+ const {
15
+ origin = '*',
16
+ methods = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
17
+ allowedHeaders = ['Content-Type', 'Authorization'],
18
+ credentials = false,
19
+ maxAge = 86400
20
+ } = options;
21
+
22
+ if (origin === '*' && credentials) {
23
+ throw new Error('CORS security error: origin "*" cannot be combined with credentials: true');
24
+ }
25
+
26
+ return async (ctx, next) => {
27
+ const reqOrigin = ctx.header('origin');
28
+ const allowedOrigin = resolveOrigin(origin, reqOrigin, ctx);
29
+
30
+ if (ctx.method === 'OPTIONS') {
31
+ const headers = new Headers();
32
+ if (allowedOrigin) {
33
+ headers.set('Access-Control-Allow-Origin', allowedOrigin);
34
+ if (allowedOrigin !== '*') headers.set('Vary', 'Origin');
35
+ }
36
+ if (credentials && allowedOrigin && allowedOrigin !== '*') {
37
+ headers.set('Access-Control-Allow-Credentials', 'true');
38
+ }
39
+ headers.set('Access-Control-Allow-Methods', methods.join(', '));
40
+ headers.set('Access-Control-Allow-Headers', allowedHeaders.join(', '));
41
+ headers.set('Access-Control-Max-Age', String(maxAge));
42
+ ctx.res = new Response(null, { status: 204, headers });
43
+ return;
44
+ }
45
+
46
+ await next();
47
+
48
+ if (ctx.res && allowedOrigin) {
49
+ ctx.res.headers.set('Access-Control-Allow-Origin', allowedOrigin);
50
+ if (allowedOrigin !== '*') ctx.res.headers.set('Vary', 'Origin');
51
+ if (credentials && allowedOrigin !== '*') {
52
+ ctx.res.headers.set('Access-Control-Allow-Credentials', 'true');
53
+ }
54
+ }
55
+ };
56
+ }
57
+
58
+ function resolveOrigin(configOrigin, reqOrigin, ctx) {
59
+ if (configOrigin === '*') return '*';
60
+ if (!reqOrigin || reqOrigin === 'null') return null;
61
+
62
+ if (typeof configOrigin === 'string') {
63
+ return reqOrigin === configOrigin ? reqOrigin : null;
64
+ }
65
+ if (Array.isArray(configOrigin)) {
66
+ return configOrigin.includes(reqOrigin) ? reqOrigin : null;
67
+ }
68
+ if (typeof configOrigin === 'function') {
69
+ return configOrigin(reqOrigin, ctx) ? reqOrigin : null;
70
+ }
71
+ return null;
72
+ }
@@ -0,0 +1,4 @@
1
+ export { logger } from './logger.js';
2
+ export { cors } from './cors.js';
3
+ export { serveStatic } from './static.js';
4
+ export { securityHeaders } from './security-headers.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Minimal request logger middleware.
3
+ * @returns {(ctx: import('../core/context.js').Context, next: () => Promise<void>) => Promise<void>}
4
+ */
5
+ export function logger() {
6
+ return async (ctx, next) => {
7
+ const start = performance.now();
8
+ await next();
9
+ const ms = (performance.now() - start).toFixed(1);
10
+ const status = ctx.res?.status ?? 404;
11
+ console.log(`${ctx.method} ${ctx.path} -> ${status} (${ms}ms)`);
12
+ };
13
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Built-in security headers middleware.
3
+ * @param {{
4
+ * frameOptions?: 'DENY' | 'SAMEORIGIN' | false,
5
+ * referrerPolicy?: string,
6
+ * coop?: string
7
+ * }} [options]
8
+ */
9
+ export function securityHeaders(options = {}) {
10
+ const {
11
+ frameOptions = 'DENY',
12
+ referrerPolicy = 'no-referrer',
13
+ coop = 'same-origin'
14
+ } = options;
15
+
16
+ return async (ctx, next) => {
17
+ // Apply to ctx._headers before next() so error responses via ctx.json/text inherit them
18
+ ctx.set('X-Content-Type-Options', 'nosniff');
19
+ ctx.set('X-XSS-Protection', '0');
20
+ if (frameOptions) ctx.set('X-Frame-Options', frameOptions);
21
+ if (referrerPolicy) ctx.set('Referrer-Policy', referrerPolicy);
22
+ if (coop) ctx.set('Cross-Origin-Opener-Policy', coop);
23
+
24
+ await next();
25
+ if (!ctx.res) return;
26
+
27
+ if (!ctx.res.headers.has('X-Content-Type-Options')) ctx.res.headers.set('X-Content-Type-Options', 'nosniff');
28
+ if (!ctx.res.headers.has('X-XSS-Protection')) ctx.res.headers.set('X-XSS-Protection', '0');
29
+ if (frameOptions && !ctx.res.headers.has('X-Frame-Options')) ctx.res.headers.set('X-Frame-Options', frameOptions);
30
+ if (referrerPolicy && !ctx.res.headers.has('Referrer-Policy')) ctx.res.headers.set('Referrer-Policy', referrerPolicy);
31
+ if (coop && !ctx.res.headers.has('Cross-Origin-Opener-Policy')) ctx.res.headers.set('Cross-Origin-Opener-Policy', coop);
32
+ };
33
+ }
@@ -0,0 +1,75 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ const MIME_TYPES = {
5
+ '.html': 'text/html; charset=utf-8',
6
+ '.css': 'text/css; charset=utf-8',
7
+ '.js': 'application/javascript; charset=utf-8',
8
+ '.mjs': 'application/javascript; charset=utf-8',
9
+ '.json': 'application/json; charset=utf-8',
10
+ '.xml': 'application/xml; charset=utf-8',
11
+ '.txt': 'text/plain; charset=utf-8',
12
+ '.svg': 'image/svg+xml',
13
+ '.png': 'image/png',
14
+ '.jpg': 'image/jpeg',
15
+ '.jpeg': 'image/jpeg',
16
+ '.webp': 'image/webp',
17
+ '.ico': 'image/x-icon'
18
+ };
19
+
20
+ /**
21
+ * Serve static files safely with path-traversal and dotfile protection.
22
+ * @param {string} rootDir
23
+ * @param {{ prefix?: string, allowDotfiles?: boolean }} [options]
24
+ */
25
+ export function serveStatic(rootDir, options = {}) {
26
+ const resolvedRoot = path.resolve(rootDir);
27
+ const { prefix = '', allowDotfiles = false } = options;
28
+
29
+ return async (ctx, next) => {
30
+ if (ctx.method !== 'GET' && ctx.method !== 'HEAD') return next();
31
+ if (prefix && !ctx.path.startsWith(prefix)) return next();
32
+
33
+ const rawSubPath = prefix ? ctx.path.slice(prefix.length) : ctx.path;
34
+ if (rawSubPath.includes('\0')) return ctx.text('Bad Request', 400);
35
+
36
+ let decoded;
37
+ try {
38
+ decoded = decodeURIComponent(rawSubPath);
39
+ } catch {
40
+ return ctx.text('Bad Request', 400);
41
+ }
42
+
43
+ if (decoded.includes('\0')) return ctx.text('Bad Request', 400);
44
+
45
+ const relativePath = decoded.replace(/^\/+/, '') || 'index.html';
46
+ const segments = relativePath.split(/[\\/]/);
47
+
48
+ if (!allowDotfiles && segments.some((s) => s.startsWith('.'))) {
49
+ return ctx.text('Forbidden', 403);
50
+ }
51
+
52
+ const targetPath = path.resolve(resolvedRoot, relativePath);
53
+ if (targetPath !== resolvedRoot && !targetPath.startsWith(resolvedRoot + path.sep)) {
54
+ return ctx.text('Forbidden', 403);
55
+ }
56
+
57
+ try {
58
+ const stat = await fs.stat(targetPath);
59
+ const filePath = stat.isDirectory() ? path.join(targetPath, 'index.html') : targetPath;
60
+ const data = await fs.readFile(filePath);
61
+ const ext = path.extname(filePath).toLowerCase();
62
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
63
+
64
+ ctx.res = new Response(ctx.method === 'HEAD' ? null : data, {
65
+ status: 200,
66
+ headers: {
67
+ 'Content-Type': contentType,
68
+ 'Content-Length': String(data.byteLength)
69
+ }
70
+ });
71
+ } catch {
72
+ return next();
73
+ }
74
+ };
75
+ }