diff --git a/src/app/index.ts b/src/app/index.ts index 27b7c2e..18ce2a1 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -23,7 +23,7 @@ import { type RouteMeta, type TransformerFn, } from '../metadata'; -import { buildHtmlTransformer, type ViewsContext } from '../views'; +import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views'; import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, type Link } from '../mesh/link'; @@ -85,6 +85,8 @@ export function createApp(opts: { views?: string; /** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */ viewEngine?: (source: string, data: unknown) => string; + /** Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` → `./public`. */ + static?: boolean | string; /** Opt in to alpha features whose API may still change. Currently gates `mesh`. */ experimental?: boolean; }): App { @@ -158,6 +160,8 @@ export function createApp(opts: { degradedProviders, ); + const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined; + const fetchOpts: HttpOptions = { limits: opts.limits, tls: opts.tls, @@ -166,6 +170,7 @@ export function createApp(opts: { cors: opts.cors, bodyDuplicates: opts.bodyDuplicates, onError: opts.onError, + static: staticResolver, }; const fetchFn = buildAppFetch( () => booted, @@ -218,6 +223,7 @@ export function createApp(opts: { cors: opts.cors, bodyDuplicates: opts.bodyDuplicates, onError: opts.onError, + static: staticResolver, }); server.on('close', () => closeLinks(meshLinks)); await new Promise((resolve) => server!.listen(port, resolve)); diff --git a/src/http/core.ts b/src/http/core.ts index a6771bb..0a4c4fe 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -69,6 +69,18 @@ export async function handle( const matched = matchRoute(routes, req.method, path); if (!matched) { + if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) { + const hit = await opts.static(path); + + if (hit) { + const body = req.method === 'HEAD' ? '' : hit.body; + return { + injected, + outcome: { kind: 'buffered', status: 200, headers: { 'content-type': hit.contentType }, body }, + }; + } + } + // Path matches a route under a different method → 405 with Allow; otherwise 404. const allow = allowedMethods(routes, path); const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found'); diff --git a/src/http/types.ts b/src/http/types.ts index a12c1e4..5e5f444 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -4,6 +4,7 @@ import type { PipelineResult } from '../pipeline'; import type { ErrorRenderer } from '../transformers'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import type { WsRequest } from './ws-core'; +import type { StaticResolver } from '../views'; /** Per-request size and timeout ceilings applied by the server. */ export interface RequestLimits { @@ -24,6 +25,7 @@ export interface HttpOptions { cors?: CorsOptions; bodyDuplicates?: 'array' | 'last'; onError?: ErrorRenderer; + static?: StaticResolver; } /** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */ diff --git a/src/views.ts b/src/views.ts index 436c8b2..210ab9c 100644 --- a/src/views.ts +++ b/src/views.ts @@ -76,6 +76,60 @@ function readViewFile(views: string | undefined, path: string): string { } } +/** A static-file hit: the raw bytes and the content-type to send. */ +export interface StaticHit { + body: Buffer; + contentType: string; +} + +/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */ +export type StaticResolver = (urlPath: string) => Promise; + +/** + * Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at + * boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss. + */ +export function buildStaticResolver(root: string | true): StaticResolver { + let fs: typeof import('node:fs'); + let nodePath: typeof import('node:path'); + + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + fs = require('node:fs'); + // eslint-disable-next-line @typescript-eslint/no-require-imports + nodePath = require('node:path'); + } catch { + throw new Error( + '`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.', + ); + } + + const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root); + + return async (urlPath) => { + let rel: string; + + try { + rel = decodeURIComponent(urlPath.split('?')[0]); + } catch { + return undefined; + } + + if (rel === '' || rel.endsWith('/')) rel += 'index.html'; + const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel)); + if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard + + try { + const stat = await fs.promises.stat(full); + const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full; + const body = await fs.promises.readFile(target); + return { body, contentType: contentTypeFor(nodePath.extname(target)) }; + } catch { + return undefined; + } + }; +} + /** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */ export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn { if (!meta.path) { diff --git a/test/views-static.test.ts b/test/views-static.test.ts new file mode 100644 index 0000000..80be5ba --- /dev/null +++ b/test/views-static.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; +import { writeFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createApp, Route, Get, Module } from '../src/index'; +import { buildStaticResolver } from '../src/views'; + +const root = join(tmpdir(), 'gt-static-test'); +mkdirSync(root, { recursive: true }); +writeFileSync(join(root, 'index.html'), '

Home

'); +writeFileSync(join(root, 'app.css'), 'body{}'); +writeFileSync(join(tmpdir(), 'gt-secret.txt'), 'TOP SECRET'); + +@Route('/api') +class Api { + @Get('/ping') + ping() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [Api] }) +class M {} +const app = createApp({ modules: [M], static: root }); + +describe('static serving', () => { + it('serves a file by path with its content-type', async () => { + const res = await app.fetch(new Request('http://x/app.css')); + expect(res.status).toBe(200); + expect(res.headers.get('content-type')).toBe('text/css; charset=utf-8'); + expect(await res.text()).toBe('body{}'); + }); + it('serves index.html for /', async () => { + expect(await (await app.fetch(new Request('http://x/'))).text()).toBe('

Home

'); + }); + it('declared routes win over static', async () => { + expect(await (await app.fetch(new Request('http://x/api/ping'))).json()).toEqual({ ok: true }); + }); + it('returns 404 for a missing file', async () => { + expect((await app.fetch(new Request('http://x/nope.html'))).status).toBe(404); + }); + it('rejects path traversal', async () => { + const res = await app.fetch(new Request('http://x/../gt-secret.txt')); + expect(res.status).toBe(404); + }); + it('answers HEAD with headers and no body', async () => { + const res = await app.fetch(new Request('http://x/app.css', { method: 'HEAD' })); + expect(res.status).toBe(200); + expect(await res.text()).toBe(''); + }); + it('resolver refuses to escape its root', async () => { + const resolve = buildStaticResolver(root); + expect(await resolve('/../gt-secret.txt')).toBeUndefined(); + expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined(); + }); +});