feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
Conditional GETs were never answered: every revalidation re-downloaded
the file or response.
- Static (D12, always on): a hit carries W/"<size>-<mtimeMs base36>",
Last-Modified and Cache-Control from the stat the resolver already did.
A matching If-None-Match, or If-Modified-Since when If-None-Match is
absent, answers 304 before the file is read. StaticHit now carries the
stat and a read() for the bytes, and HEAD no longer reads either.
- static: { dir?, cacheControl? } (rule 1a): Cache-Control defaults to
no-cache so browsers revalidate rather than reuse a file for a lifetime
guessed from Last-Modified. An unknown key or CR/LF throws at boot.
- createApp({ etag: true }) (off by default, boolean only): a buffered 200
to GET/HEAD gets a weak tag from a 32-bit FNV-1a hash of its UTF-8 bytes
plus its length, computed before HEAD blanks the body. A handler-set
etag is kept and only compared. Weak comparison, lists split outside
quotes, and * are supported.
- Every buffered 304 leaves dispatch bodiless, with its content-* headers
dropped, so NotModified matches the ETag path on every adapter.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
14 files changed
+706
-37
No files matched your search
+33
-4
@@ -38,7 +38,7 @@ import {
|
||||
type RouteMeta,
|
||||
type TransformerFn,
|
||||
} from '../metadata';
|
||||
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
|
||||
import { buildHtmlTransformer, buildStaticResolver, normalizeStatic, type ViewsContext } from '../views';
|
||||
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
|
||||
import { buildOpenApi, type OpenApiInfo } from '../openapi';
|
||||
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
|
||||
@@ -156,8 +156,27 @@ 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;
|
||||
/**
|
||||
* Serve a static directory as a GET/HEAD fallback (after declared routes, before 404). `true` →
|
||||
* `./public`; a string is the directory; `{ dir?, cacheControl? }` also sets `Cache-Control`.
|
||||
*
|
||||
* Every hit carries a weak `ETag` and `Last-Modified` from the file's `stat`, and a matching
|
||||
* `If-None-Match` (or `If-Modified-Since` when there is no `If-None-Match`) answers `304` without
|
||||
* reading the file. `Cache-Control` is `no-cache` unless `cacheControl` says otherwise, so browsers
|
||||
* revalidate instead of guessing a lifetime from `Last-Modified`; use
|
||||
* `'public, max-age=31536000, immutable'` for content-hashed assets. An unknown key, or a
|
||||
* `cacheControl` with CR/LF, throws here. Unavailable on the edge (no filesystem).
|
||||
*/
|
||||
static?: boolean | string | { dir?: string; cacheControl?: string };
|
||||
/**
|
||||
* Weak ETags for handler responses (default: off). A buffered `200` to GET or HEAD gets
|
||||
* `ETag: W/"<length>-<hash>"` computed from its body, and a request whose `If-None-Match` matches
|
||||
* gets a bodiless `304`. A handler that sets its own `etag` header keeps it, and that tag drives the
|
||||
* comparison. Streams, non-200 responses and other methods are never tagged. The handler still
|
||||
* runs: this saves bandwidth, not work. Static files are tagged regardless of this option.
|
||||
* Anything but a boolean throws.
|
||||
*/
|
||||
etag?: boolean;
|
||||
/**
|
||||
* How long `close()` gives in-flight work before forcing remaining connections shut, in ms
|
||||
* (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is
|
||||
@@ -232,6 +251,7 @@ export function createApp(opts: {
|
||||
|
||||
validateWsLimits(opts.limits);
|
||||
const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs);
|
||||
assertEtagOption(opts.etag);
|
||||
|
||||
const bus = new Bus();
|
||||
const logger = opts.logger ?? createDefaultLogger();
|
||||
@@ -338,7 +358,8 @@ export function createApp(opts: {
|
||||
|
||||
const { bootApp, healthProbe, drain } = trackHealth(health, bootGraph, () => [...degradedProviders]);
|
||||
|
||||
const staticResolver = opts.static ? buildStaticResolver(opts.static) : undefined;
|
||||
const staticConfig = normalizeStatic(opts.static);
|
||||
const staticResolver = staticConfig ? buildStaticResolver(staticConfig.root, staticConfig.cacheControl) : undefined;
|
||||
|
||||
const fetchOpts: HttpOptions = {
|
||||
bus,
|
||||
@@ -352,6 +373,7 @@ export function createApp(opts: {
|
||||
onError: opts.onError,
|
||||
static: staticResolver,
|
||||
health: healthProbe,
|
||||
etag: opts.etag,
|
||||
};
|
||||
const fetchFn = buildAppFetch(
|
||||
routePlans,
|
||||
@@ -389,6 +411,7 @@ export function createApp(opts: {
|
||||
onError: opts.onError,
|
||||
static: staticResolver,
|
||||
health: healthProbe,
|
||||
etag: opts.etag,
|
||||
});
|
||||
server.on('close', () => closeLinks(meshLinks));
|
||||
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||
@@ -1770,6 +1793,12 @@ function closeLinks(links: Link[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** `createApp({ etag })` is a boolean or absent; a truthy string doing something would be silent partial behaviour. */
|
||||
function assertEtagOption(etag: unknown): void {
|
||||
if (etag !== undefined && typeof etag !== 'boolean')
|
||||
throw new TypeError(`createApp({ etag }): expected a boolean, got ${typeof etag}`);
|
||||
}
|
||||
|
||||
/** Merges every app-scope provider bound to a route into a request seed (skips unresolved providers). */
|
||||
async function seedProviders(container: Container, plan: RoutePlan): Promise<Record<string, unknown>> {
|
||||
const provided: Record<string, unknown> = {};
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// src/http/conditional.ts — ETags and conditional GET (RFC 9110 §8.8.3, §13.1.2, §13.1.3, §15.4.5).
|
||||
|
||||
type HeaderBag = Record<string, string | string[] | undefined>;
|
||||
|
||||
/** The first value of a request header, or `undefined`. */
|
||||
function single(value: string | string[] | undefined): string | undefined {
|
||||
return Array.isArray(value) ? value.join(', ') : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits an `If-None-Match` list on the commas that sit outside quotes. An entity-tag may legally
|
||||
* contain a comma inside its quotes (`"a,b"`), so a plain `split(',')` would cut one tag in two.
|
||||
*/
|
||||
function splitTags(header: string): string[] {
|
||||
const tags: string[] = [];
|
||||
let start = 0;
|
||||
let quoted = false;
|
||||
|
||||
for (let i = 0; i < header.length; i++) {
|
||||
const ch = header[i];
|
||||
|
||||
if (ch === '"') quoted = !quoted;
|
||||
else if (ch === ',' && !quoted) {
|
||||
tags.push(header.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
tags.push(header.slice(start).trim());
|
||||
return tags.filter(Boolean);
|
||||
}
|
||||
|
||||
/** The opaque part of an entity-tag: `W/"x"` and `"x"` both become `"x"` (weak comparison). */
|
||||
const opaque = (tag: string): string => (tag.startsWith('W/') ? tag.slice(2) : tag);
|
||||
|
||||
/**
|
||||
* Whether `If-None-Match` matches `etag` under the weak comparison GET and HEAD use
|
||||
* (RFC 9110 §13.1.2): `W/"x"` matches `"x"`, and `*` matches any current representation.
|
||||
*/
|
||||
export function ifNoneMatchMatches(header: string, etag: string): boolean {
|
||||
const own = opaque(etag.trim());
|
||||
|
||||
for (const tag of splitTags(header)) if (tag === '*' || opaque(tag) === own) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a resource last modified at `mtimeMs` is unchanged since an `If-Modified-Since` date.
|
||||
* HTTP dates have one-second resolution, so the modification time is truncated to the second first;
|
||||
* otherwise a file written at 12:00:00.400 would never match the `Last-Modified` it was served with.
|
||||
* An unparseable date is ignored, as RFC 9110 §13.1.3 requires.
|
||||
*/
|
||||
export function notModifiedSince(header: string, mtimeMs: number): boolean {
|
||||
const since = Date.parse(header);
|
||||
if (Number.isNaN(since)) return false;
|
||||
return Math.floor(mtimeMs / 1000) * 1000 <= since;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides a conditional GET/HEAD: `If-None-Match` when present, else `If-Modified-Since` when the
|
||||
* caller has a modification time to compare (static files only — handler responses have none).
|
||||
*/
|
||||
export function isNotModified(headers: HeaderBag, etag: string, mtimeMs?: number): boolean {
|
||||
const inm = single(headers['if-none-match']);
|
||||
if (inm !== undefined) return ifNoneMatchMatches(inm, etag);
|
||||
|
||||
const ims = single(headers['if-modified-since']);
|
||||
return ims !== undefined && mtimeMs !== undefined && notModifiedSince(ims, mtimeMs);
|
||||
}
|
||||
|
||||
/** Weak validator for a static file, from the `stat` the resolver already does: `W/"<size>-<mtimeMs base36>"`. */
|
||||
export function staticEtag(size: number, mtimeMs: number): string {
|
||||
return `W/"${size}-${Math.floor(mtimeMs).toString(36)}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Weak validator for a buffered body: its byte length plus a 32-bit FNV-1a hash of its bytes, in
|
||||
* base 36. FNV rather than `crypto.subtle.digest`: it is synchronous and dependency-free, where
|
||||
* `subtle` costs a promise per response. It is not collision-resistant and need not be — an ETag
|
||||
* detects change, it does not authenticate. The length narrows a collision to equal-length bodies.
|
||||
*
|
||||
* Weak, so one tag can describe every content-coding of the same body (CARD-16 hashes before it
|
||||
* encodes). Strings are hashed as UTF-8, so the tag matches what goes on the wire.
|
||||
*/
|
||||
export function bodyEtag(body: string | Uint8Array): string {
|
||||
const bytes = typeof body === 'string' ? Buffer.from(body, 'utf8') : body;
|
||||
let hash = 0x811c9dc5;
|
||||
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
hash ^= bytes[i];
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
|
||||
return `W/"${bytes.length.toString(36)}-${(hash >>> 0).toString(36)}"`;
|
||||
}
|
||||
|
||||
/** The key under which `headers` holds `name`, case-insensitively, or `undefined`. */
|
||||
export function findHeader(headers: Record<string, unknown>, name: string): string | undefined {
|
||||
for (const key of Object.keys(headers)) if (key.toLowerCase() === name) return key;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The headers of a `304` built from the `200` it stands for: everything but the `content-*`
|
||||
* headers that describe a body (`content-type`, `content-length`, `content-encoding`, …), plus
|
||||
* `transfer-encoding`. `content-location` is kept: §15.4.5 lists it among the fields a 304 sends. `ETag`, `Vary`, `Cache-Control`, `Last-Modified` and anything else a cache
|
||||
* would update stay (RFC 9110 §15.4.5). Injected security headers are merged later by the adapter,
|
||||
* exactly as on a `200`.
|
||||
*/
|
||||
export function notModifiedHeaders(headers: Record<string, string | string[]>): Record<string, string | string[]> {
|
||||
const out: Record<string, string | string[]> = {};
|
||||
|
||||
for (const key of Object.keys(headers)) {
|
||||
const lower = key.toLowerCase();
|
||||
if ((lower.startsWith('content-') && lower !== 'content-location') || lower === 'transfer-encoding') continue;
|
||||
out[key] = headers[key];
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
+64
-16
@@ -6,6 +6,8 @@ import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../secu
|
||||
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
|
||||
import { pickEncoder } from './stream';
|
||||
import { acquireBody, type BodyReader } from './body';
|
||||
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
|
||||
import type { StaticHit } from '../views';
|
||||
import type { RouteDef, HttpOptions } from './types';
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import type { Bus } from '../bus';
|
||||
@@ -131,15 +133,69 @@ function errorOutcome(
|
||||
const rendered = renderError(error, req, opts?.onError, opts?.logger);
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
outcome: bodyless({
|
||||
kind: 'buffered',
|
||||
status: rendered.status,
|
||||
headers: { ...rendered.headers, ...headers },
|
||||
body: req.method === 'HEAD' ? '' : rendered.body,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
|
||||
|
||||
/**
|
||||
* A `304` has no body on any adapter, and none of the headers that describe one. This is the one
|
||||
* place every buffered outcome passes through on its way out, so a handler that throws
|
||||
* `NotModified` — rendered by the default renderer as a JSON envelope — answers the same bodiless
|
||||
* `304` the ETag path does. Node would drop the body of a 304 by itself; the fetch adapters already
|
||||
* null it; the `content-type` would still have gone out on both.
|
||||
*/
|
||||
function bodyless(outcome: Buffered): Buffered {
|
||||
if (outcome.status !== 304) return outcome;
|
||||
return { kind: 'buffered', status: 304, headers: notModifiedHeaders(outcome.headers), body: '' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a static hit: `ETag` + `Last-Modified` from the resolver's `stat`, `Cache-Control` from the
|
||||
* `static` option, and a `304` — decided before the file is read, so a revalidation costs a `stat`
|
||||
* and nothing more. HEAD never reads either.
|
||||
*/
|
||||
async function staticOutcome(hit: StaticHit, req: NeutralRequest): Promise<Buffered> {
|
||||
const etag = staticEtag(hit.size, hit.mtimeMs);
|
||||
const headers: Record<string, string> = {
|
||||
'content-type': hit.contentType,
|
||||
etag,
|
||||
'last-modified': new Date(hit.mtimeMs).toUTCString(),
|
||||
'cache-control': hit.cacheControl,
|
||||
};
|
||||
|
||||
if (isNotModified(req.headers, etag, hit.mtimeMs))
|
||||
return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
|
||||
|
||||
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : await hit.read() };
|
||||
}
|
||||
|
||||
/**
|
||||
* `createApp({ etag: true })` for a handler response: a buffered `200` to GET/HEAD gets a weak ETag
|
||||
* from its body — computed before HEAD blanks the body, so HEAD and GET carry the same tag — unless
|
||||
* the handler set one, which is kept and only compared. A match becomes a bodiless `304`. The
|
||||
* handler has already run: this saves bandwidth, not work.
|
||||
*/
|
||||
function tagged(
|
||||
result: { status: number; headers: Record<string, string | string[]>; body: string },
|
||||
req: NeutralRequest,
|
||||
): Buffered {
|
||||
const key = findHeader(result.headers, 'etag');
|
||||
const existing = key === undefined ? undefined : result.headers[key];
|
||||
const etag = typeof existing === 'string' ? existing : bodyEtag(result.body);
|
||||
const headers = key === undefined ? { ...result.headers, etag } : result.headers;
|
||||
|
||||
if (isNotModified(req.headers, etag)) return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
|
||||
|
||||
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : result.body };
|
||||
}
|
||||
|
||||
async function unmatchedOutcome(
|
||||
routes: RouteDef[],
|
||||
opts: HttpOptions | undefined,
|
||||
@@ -149,18 +205,7 @@ async function unmatchedOutcome(
|
||||
): Promise<HandleResult> {
|
||||
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
|
||||
const hit = await opts.static(path);
|
||||
|
||||
if (hit) {
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
kind: 'buffered',
|
||||
status: 200,
|
||||
headers: { 'content-type': hit.contentType },
|
||||
body: req.method === 'HEAD' ? '' : hit.body,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (hit) return { injected, outcome: await staticOutcome(hit, req) };
|
||||
}
|
||||
|
||||
const allow = allowedMethods(routes, path);
|
||||
@@ -411,13 +456,16 @@ async function dispatch(
|
||||
};
|
||||
}
|
||||
|
||||
if (opts?.etag && result.status === 200 && (req.method === 'GET' || req.method === 'HEAD'))
|
||||
return { injected, outcome: tagged(result, req) };
|
||||
|
||||
return {
|
||||
injected,
|
||||
outcome: {
|
||||
outcome: bodyless({
|
||||
kind: 'buffered',
|
||||
status: result.status,
|
||||
headers: result.headers,
|
||||
body: req.method === 'HEAD' ? '' : result.body,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -68,6 +68,8 @@ export interface HttpOptions {
|
||||
* Absent when health is off, so no path is intercepted.
|
||||
*/
|
||||
health?: HealthProbe;
|
||||
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
|
||||
etag?: boolean;
|
||||
}
|
||||
|
||||
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
|
||||
|
||||
+75
-14
@@ -77,15 +77,63 @@ function readViewFile(views: string | undefined, path: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** A static-file hit: the raw bytes and the content-type to send. */
|
||||
/**
|
||||
* A static-file hit: what the `stat` already knows, and a `read()` for the bytes.
|
||||
*
|
||||
* The bytes are behind a function so the caller can answer a conditional request from `size` and
|
||||
* `mtimeMs` alone: a `304` never reads the file (CARD-15). `read()` reads the confined real path the
|
||||
* resolver checked, so deferring it does not reopen the path to a different target.
|
||||
*/
|
||||
export interface StaticHit {
|
||||
body: Buffer;
|
||||
contentType: string;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
/** `Cache-Control` for this hit (and its `304`): `no-cache` unless `static.cacheControl` says otherwise. */
|
||||
cacheControl: string;
|
||||
read(): Promise<Buffer>;
|
||||
}
|
||||
|
||||
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
|
||||
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
|
||||
|
||||
/**
|
||||
* The public `static` option: `true` (→ `./public`), a directory, or `{ dir?, cacheControl? }`.
|
||||
* `cacheControl` defaults to `'no-cache'`, so a browser always revalidates — cheap, since a match is a
|
||||
* `304` that never reads the file — and never reuses a file heuristically from `Last-Modified`
|
||||
* (RFC 9111 §4.2.2). Hashed assets can opt into `'public, max-age=31536000, immutable'`.
|
||||
*/
|
||||
export type StaticOption = boolean | string | { dir?: string; cacheControl?: string };
|
||||
|
||||
const STATIC_KEYS = new Set(['dir', 'cacheControl']);
|
||||
|
||||
/**
|
||||
* Validates and normalises the `static` option at boot. Throws on an unknown key in the object form
|
||||
* (a misspelt `cachecontrol` silently doing nothing is the bug this prevents), on a non-string
|
||||
* `dir`/`cacheControl`, and on a `cacheControl` carrying CR or LF (header injection).
|
||||
*/
|
||||
export function normalizeStatic(
|
||||
option: StaticOption | undefined,
|
||||
): { root: string | true; cacheControl: string } | undefined {
|
||||
if (option === undefined || option === false) return undefined;
|
||||
if (option === true || typeof option === 'string') return { root: option, cacheControl: 'no-cache' };
|
||||
|
||||
if (typeof option !== 'object' || option === null)
|
||||
throw new TypeError('createApp({ static }): expected a boolean, a directory string or { dir?, cacheControl? }');
|
||||
|
||||
for (const key of Object.keys(option))
|
||||
if (!STATIC_KEYS.has(key))
|
||||
throw new TypeError(`createApp({ static }): unknown key '${key}' — expected 'dir' and/or 'cacheControl'`);
|
||||
|
||||
const { dir, cacheControl = 'no-cache' } = option;
|
||||
if (dir !== undefined && typeof dir !== 'string')
|
||||
throw new TypeError('createApp({ static: { dir } }): expected a string');
|
||||
|
||||
if (typeof cacheControl !== 'string' || /[\r\n]/.test(cacheControl))
|
||||
throw new TypeError('createApp({ static: { cacheControl } }): expected a string without CR or LF');
|
||||
|
||||
return { root: dir ?? true, cacheControl };
|
||||
}
|
||||
|
||||
/** The real path of `path` when it is `root` or lies beneath it, else `undefined`. Rejects on ENOENT.
|
||||
* The separator suffix keeps a sibling such as `root-evil` out of `root`. */
|
||||
async function confine(fs: typeof import('node:fs'), sep: string, root: string, path: string) {
|
||||
@@ -93,26 +141,39 @@ async function confine(fs: typeof import('node:fs'), sep: string, root: string,
|
||||
return real === root || real.startsWith(root + sep) ? real : undefined;
|
||||
}
|
||||
|
||||
/** Reads `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
|
||||
async function readConfined(
|
||||
/** Stats `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
|
||||
async function statConfined(
|
||||
fs: typeof import('node:fs'),
|
||||
nodePath: typeof import('node:path'),
|
||||
root: string,
|
||||
full: string,
|
||||
cacheControl: string,
|
||||
): Promise<StaticHit | undefined> {
|
||||
let real = await confine(fs, nodePath.sep, root, full);
|
||||
if (!real) return undefined;
|
||||
const isDir = (await fs.promises.stat(real)).isDirectory();
|
||||
let stat = await fs.promises.stat(real);
|
||||
const isDir = stat.isDirectory();
|
||||
|
||||
// `index.html` is a second resolution and can itself be a link, so it is confined on its own.
|
||||
if (isDir) real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
|
||||
if (!real) return undefined;
|
||||
// ponytail: a link swapped between `realpath` and `readFile` can still escape. Exploiting it needs
|
||||
// write access inside the served root, which already owns the app; closing it needs `O_NOFOLLOW`
|
||||
// on every path component, which Node, Deno and Bun do not offer portably.
|
||||
const body = await fs.promises.readFile(real);
|
||||
if (isDir) {
|
||||
real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
|
||||
if (!real) return undefined;
|
||||
stat = await fs.promises.stat(real);
|
||||
}
|
||||
|
||||
const path = real;
|
||||
// The content-type follows the requested name, not the link target (`app.js -> app.3f2a.js`).
|
||||
const target = isDir ? nodePath.join(full, 'index.html') : full;
|
||||
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
|
||||
return {
|
||||
contentType: contentTypeFor(nodePath.extname(target)),
|
||||
size: stat.size,
|
||||
mtimeMs: stat.mtimeMs,
|
||||
cacheControl,
|
||||
// ponytail: a link swapped between `realpath` and `readFile` can still escape. Exploiting it needs
|
||||
// write access inside the served root, which already owns the app; closing it needs `O_NOFOLLOW`
|
||||
// on every path component, which Node, Deno and Bun do not offer portably.
|
||||
read: () => fs.promises.readFile(path),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,7 +182,7 @@ async function readConfined(
|
||||
* and so is a symlink whose real target lies outside the root's real path (#106). Escapes are misses
|
||||
* (404), not 403, so a probe cannot tell "exists outside the root" from "does not exist".
|
||||
*/
|
||||
export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
export function buildStaticResolver(root: string | true, cacheControl = 'no-cache'): StaticResolver {
|
||||
let fs: typeof import('node:fs');
|
||||
let nodePath: typeof import('node:path');
|
||||
|
||||
@@ -165,7 +226,7 @@ export function buildStaticResolver(root: string | true): StaticResolver {
|
||||
if (!rootReal) return undefined;
|
||||
|
||||
try {
|
||||
return await readConfined(fs, nodePath, rootReal, full);
|
||||
return await statConfined(fs, nodePath, rootReal, full, cacheControl);
|
||||
} catch {
|
||||
return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user