2 Commits
Author SHA1 Message Date
chrnxandClaude Opus 5.5 c86d298fd4 feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:01:54 -05:00
chrnxandClaude Opus 5.5 82767eabd2 feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-22 23:55:31 -05:00
32 changed files with 1482 additions and 65 deletions

No files matched your search

+40
View File
@@ -10,6 +10,15 @@ npm treats versions as semver and semver forbids leading zeros.
### Breaking ### Breaking
- **Response header values are `string | string[]`** (#113, D11). `TransformerFn`, `ErrorResponse.headers`,
`HttpError.headers` / `HttpErrorLike.headers` and the pipeline's `ResponseShape.headers` widen from
`Record<string, string>`, so a response can carry several `Set-Cookie` lines. Code that *produces*
headers is unaffected; code that *reads* `headers[k]` from one of these types as a `string` stops
compiling and must handle the array. A `set-cookie` array is sent as one header line per element
on Node, Deno, Bun and the edge — before, the fetch adapters stringified it into one broken
`a,b` cookie. Any other array is sent as one line joined with `, `. Injected security and CORS
headers stay authoritative, and a handler's `vary` array is merged with the injected one.
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life - **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
@@ -60,6 +69,27 @@ npm treats versions as semver and semver forbids leading zeros.
### Added ### Added
- **`createApp({ etag: true })`** (#114, D12): weak ETags for buffered `200` responses to `GET` and
`HEAD`, from a 32-bit FNV-1a hash of the body plus its length. A matching `If-None-Match` (weak
comparison, lists, `*`) gets a `304` with no body. A handler that sets its own `etag` keeps it, and
that tag drives the comparison. Streams, non-200 responses and other methods are never tagged.
The handler still runs. Off by default; anything but a boolean throws at `createApp`.
- **`static: { dir?, cacheControl? }`** (#114): the object form of `static` sets the
`Cache-Control` sent with static files and their `304`s (for example
`'public, max-age=31536000, immutable'` for hashed assets). `static: true` and `static: '<dir>'`
keep working. An unknown key, or a `cacheControl` with CR/LF, throws at `createApp`.
- **`@cookie('name')` / `@cookies()` argument decorators and `setCookie()`** (#113). Cookies are
parsed from the request's `Cookie` header on first use per request (RFC 6265: first value wins,
`%`-sequences decoded, malformed pairs skipped rather than answered with a 400), on HTTP and
WebSocket routes; `@needs('cookies')` gives the same map. OpenAPI lists a cookie argument as an
`in: cookie` parameter. `setCookie(name, value, options?)` returns a `Set-Cookie` value with
`HttpOnly`, `SameSite=Lax`, `Path=/` and `Secure` by default (D10; `secure: false` opts out), and
throws, naming the field, on a name outside the token set, a value with CR, LF, `;`, `,`,
whitespace or a control character, an attribute with CR/LF, `;` or a control character, and on
`sameSite: 'none'` or `partitioned` without `secure`. `parseCookies()` and `CookieOptions` are
exported too. No dependency: signing and sessions stay out of core.
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound - **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp` WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
@@ -71,6 +101,16 @@ npm treats versions as semver and semver forbids leading zeros.
### Changed ### Changed
- **Static files are revalidated, not re-downloaded** (#114, D12). Every static hit carries a weak
`ETag` (`W/"<size>-<mtime>"`), `Last-Modified` and `Cache-Control: no-cache`. A matching
`If-None-Match`, or `If-Modified-Since` when there is no `If-None-Match`, answers `304` from the
file's `stat` without reading it. A `HEAD` no longer reads the file either. `no-cache` stops
browsers from reusing a file for a lifetime they guessed from `Last-Modified`. To keep the old
behaviour, set `static: { cacheControl }` to whatever your proxy expects.
- **Every `304` is bodiless** (#114). A `304` has no body and no `content-*` headers on any adapter,
including one from `throw new NotModified()`, which used to go out with the default JSON
envelope's `content-type`.
- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted - **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted
list per method, and on every 404 and 405 it recompiled and matched every route to build `Allow`. list per method, and on every 404 and 405 it recompiled and matched every route to build `Allow`.
It now walks a tree per method, built once from the route table, with mesh routes from teapots It now walks a tree per method, built once from the route table, with mesh routes from teapots
+5 -1
View File
@@ -140,7 +140,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed.
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
@@ -243,6 +243,10 @@ The handler signature declares exactly what it wants — in any order, nothing m
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` | | `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` | | `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` | | `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
| `@cookies(...)` | request cookies, parsed from `Cookie` (whole map or picked) | `()` · `('sid')` · `(['a','b'])` · `(schema)` |
| `@cookie('name')` | one request cookie (singular alias of `@cookies`) | `('sid')` · `('sid', schema)` |
To send cookies, `setCookie(name, value, options?)` returns a `Set-Cookie` value with safe defaults (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure`) and throws on anything that could inject a header. Response header values are `string | string[]`: a `set-cookie` array is sent as one line per cookie on every runtime, any other array as one line joined with `, `. Pass `secure: false` where the browser will not keep a `Secure` cookie over plain HTTP (Safari, a LAN IP). Signing and sessions are not in core.
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it. `@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
+44 -5
View File
@@ -37,7 +37,7 @@ import {
type RouteMeta, type RouteMeta,
type TransformerFn, type TransformerFn,
} from '../metadata'; } from '../metadata';
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views'; import { buildHtmlTransformer, buildStaticResolver, normalizeStatic, type ViewsContext } from '../views';
import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
@@ -132,8 +132,27 @@ export function createApp(opts: {
views?: string; views?: string;
/** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */ /** Bring-your-own template engine for `@Html(..., { template: true })`; defaults to the built-in `render`. */
viewEngine?: (source: string, data: unknown) => string; 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 * 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 * (default: 10s). `close({ timeoutMs })` still wins per call. Set it here when `close()` is
@@ -207,6 +226,7 @@ export function createApp(opts: {
} }
validateWsLimits(opts.limits); validateWsLimits(opts.limits);
assertEtagOption(opts.etag);
const bus = new Bus(); const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger(); const logger = opts.logger ?? createDefaultLogger();
@@ -309,7 +329,8 @@ export function createApp(opts: {
ready, ready,
); );
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 = { const fetchOpts: HttpOptions = {
bus, bus,
@@ -322,6 +343,7 @@ export function createApp(opts: {
bodyDuplicates: opts.bodyDuplicates, bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError, onError: opts.onError,
static: staticResolver, static: staticResolver,
etag: opts.etag,
}; };
const fetchFn = buildAppFetch( const fetchFn = buildAppFetch(
routePlans, routePlans,
@@ -355,6 +377,7 @@ export function createApp(opts: {
bodyDuplicates: opts.bodyDuplicates, bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError, onError: opts.onError,
static: staticResolver, static: staticResolver,
etag: opts.etag,
}); });
server.on('close', () => closeLinks(meshLinks)); server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve)); await new Promise<void>((resolve) => server!.listen(port, resolve));
@@ -804,7 +827,17 @@ function assertNeedsSatisfiable(
...providerNodes.flatMap((node) => node.provides), ...providerNodes.flatMap((node) => node.provides),
...stepNodes.flatMap((node) => node.provides), ...stepNodes.flatMap((node) => node.provides),
]); ]);
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']); const allowed = new Set<string>([
...producedKeys,
'req',
'params',
'query',
'body',
'headers',
'cookies',
'inbound',
'abort',
]);
for (const plan of routePlans) { for (const plan of routePlans) {
for (const need of plan.needs) { for (const need of plan.needs) {
@@ -1655,6 +1688,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). */ /** 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>> { async function seedProviders(container: Container, plan: RoutePlan): Promise<Record<string, unknown>> {
const provided: Record<string, unknown> = {}; const provided: Record<string, unknown> = {};
+150
View File
@@ -0,0 +1,150 @@
// src/cookies.ts — request cookie parsing and `Set-Cookie` serialisation (RFC 6265), dependency-free.
/**
* Options for {@link setCookie}. Every attribute is optional; the defaults are the safe ones
* (`httpOnly: true`, `sameSite: 'lax'`, `path: '/'`, `secure: true`).
*/
export interface CookieOptions {
/** `Max-Age` in seconds. An integer; `0` or a negative value tells the browser to drop the cookie. */
maxAge?: number;
/** `Expires`, written as an HTTP date. `maxAge` wins in browsers when both are set. */
expires?: Date;
/** `Path`. Default `'/'`. */
path?: string;
/** `Domain`. Omitted by default, which scopes the cookie to the exact host that set it. */
domain?: string;
/**
* `Secure`. Default `true`: Chrome, Edge and Firefox accept a `Secure` cookie on
* `http://localhost`. Safari, a LAN IP or a plain-HTTP dev hostname do not — pass `false` there
* (for example `secure: !isDev`).
*/
secure?: boolean;
/** `HttpOnly`. Default `true`, so page scripts cannot read the cookie. */
httpOnly?: boolean;
/** `SameSite`. Default `'lax'`. `'none'` requires `secure`. */
sameSite?: 'strict' | 'lax' | 'none';
/** `Partitioned` (CHIPS). Requires `secure`. */
partitioned?: boolean;
}
/** RFC 6265 §4.1.1 cookie-name: an RFC 7230 token. */
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/** What a cookie value may not contain: CR, LF, `;`, `,`, whitespace and every control character. */
// eslint-disable-next-line no-control-regex
const BAD_VALUE = /[\u0000- ;,\u007f]/;
/**
* What an attribute value may not contain. CR/LF is the header-injection case the card names; `;`
* and the other control characters are refused too, because a `;` inside `Path` would start a new
* attribute and change what the cookie means without breaking the header.
*/
// eslint-disable-next-line no-control-regex
const BAD_ATTRIBUTE = /[\u0000-\u001f;\u007f]/;
const SAME_SITE = { strict: 'Strict', lax: 'Lax', none: 'None' } as const;
/**
* Serialises one `Set-Cookie` header value.
*
* Throws, naming the field, rather than producing a header that would split or reshape the
* response: a name outside the RFC 6265 token set, a value carrying CR, LF, `;`, `,`, whitespace or a
* control character, an attribute carrying CR/LF, `;` or a control character, a non-integer
* `maxAge`, an invalid `expires`, and `sameSite: 'none'` or `partitioned` without `secure`.
*
* The value is written as given. Encode it yourself (`encodeURIComponent`) if it can hold any of the
* refused characters; the cookie decorators decode `%`-sequences on the way back in.
*
* Several cookies on one response go in an array: `headers: { 'set-cookie': [a, b] }`, and each
* element is sent as its own `Set-Cookie` line on every adapter.
*
* @example
* setCookie('session', id, { maxAge: 3600 })
* // 'session=<id>; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax'
*/
export function setCookie(name: string, value: string, options: CookieOptions = {}): string {
if (typeof name !== 'string' || !TOKEN.test(name))
throw new TypeError(`setCookie: name ${JSON.stringify(name)} is not a valid cookie name (RFC 6265 token)`);
if (typeof value !== 'string' || BAD_VALUE.test(value))
throw new TypeError(
`setCookie: value for '${name}' contains a character a cookie value cannot carry (CR, LF, ';', ',', whitespace or a control character)`,
);
const secure = options.secure ?? true;
const sameSite = options.sameSite ?? 'lax';
const parts = [`${name}=${value}`];
if (options.maxAge !== undefined) {
if (!Number.isInteger(options.maxAge)) throw new TypeError(`setCookie: maxAge for '${name}' must be an integer`);
parts.push(`Max-Age=${options.maxAge}`);
}
if (options.expires !== undefined) {
if (!(options.expires instanceof Date) || Number.isNaN(options.expires.getTime()))
throw new TypeError(`setCookie: expires for '${name}' must be a valid Date`);
parts.push(`Expires=${options.expires.toUTCString()}`);
}
if (options.domain !== undefined) parts.push(`Domain=${attribute(name, 'domain', options.domain)}`);
parts.push(`Path=${attribute(name, 'path', options.path ?? '/')}`);
if (secure) parts.push('Secure');
if (options.httpOnly ?? true) parts.push('HttpOnly');
if (!Object.prototype.hasOwnProperty.call(SAME_SITE, sameSite))
throw new TypeError(`setCookie: sameSite for '${name}' must be 'strict', 'lax' or 'none'`);
if (sameSite === 'none' && !secure)
throw new TypeError(`setCookie: sameSite 'none' for '${name}' requires secure (browsers reject it otherwise)`);
parts.push(`SameSite=${SAME_SITE[sameSite]}`);
if (options.partitioned) {
if (!secure) throw new TypeError(`setCookie: partitioned for '${name}' requires secure`);
parts.push('Partitioned');
}
return parts.join('; ');
}
function attribute(name: string, field: string, value: string): string {
if (typeof value !== 'string' || value === '' || BAD_ATTRIBUTE.test(value))
throw new TypeError(
`setCookie: ${field} for '${name}' must be a non-empty string without CR, LF, ';' or control characters`,
);
return value;
}
/**
* Parses a request `Cookie` header into a name → value map (RFC 6265 §5.2 / §4.2).
*
* - The first value wins for a repeated name — the browser sends the most specific cookie first.
* - `%`-sequences are decoded; a value that fails to decode is kept raw rather than rejected.
* - A malformed pair (no `=`, or an empty name) is skipped. A broken cookie never becomes a 400:
* the header is client state the server did not choose and the request may not even need it.
* - Several `cookie` lines (HTTP/2, some proxies) arrive as an array and are joined with `; `.
*
* The map has no prototype, so a cookie named `__proto__` or `constructor` is just a key.
*/
export function parseCookies(header: string | string[] | undefined): Record<string, string> {
const out: Record<string, string> = Object.create(null);
if (header === undefined) return out;
const raw = Array.isArray(header) ? header.join('; ') : header;
for (const pair of raw.split(';')) {
const eq = pair.indexOf('=');
if (eq === -1) continue;
const key = pair.slice(0, eq).trim();
if (key === '' || key in out) continue;
out[key] = decode(pair.slice(eq + 1).trim());
}
return out;
}
function decode(value: string): string {
if (!value.includes('%')) return value;
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ import type { MatchedRoute, HttpOptions } from './types';
/** A ready-to-send error response produced while acquiring the request body. */ /** A ready-to-send error response produced while acquiring the request body. */
export interface BodyFailure { export interface BodyFailure {
fail: { status: number; headers: Record<string, string>; body: string }; fail: { status: number; headers: Record<string, string | string[]>; body: string };
} }
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */ /** A value, or a promise of one. Readers that have nothing to await return the value directly. */
+121
View File
@@ -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;
}
+67 -19
View File
@@ -6,6 +6,8 @@ import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../secu
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router'; import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream'; import { pickEncoder } from './stream';
import { acquireBody, type BodyReader } from './body'; 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 { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
@@ -85,10 +87,10 @@ export function correlateRequest(headers: Record<string, string | string[] | und
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */ /** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome = export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer } | { kind: 'buffered'; status: number; headers: Record<string, string | string[]>; body: string | Buffer }
| { | {
kind: 'stream'; kind: 'stream';
headers: Record<string, string>; headers: Record<string, string | string[]>;
stream: AsyncIterable<unknown>; stream: AsyncIterable<unknown>;
encoder: StreamEncoder; encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */ /** The matched route's pattern, for naming the stream lifecycle events. */
@@ -126,20 +128,74 @@ function errorOutcome(
req: NeutralRequest, req: NeutralRequest,
injected: Record<string, string>, injected: Record<string, string>,
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
headers: Record<string, string> = {}, headers: Record<string, string | string[]> = {},
): HandleResult { ): HandleResult {
const rendered = renderError(error, req, opts?.onError, opts?.logger); const rendered = renderError(error, req, opts?.onError, opts?.logger);
return { return {
injected, injected,
outcome: { outcome: bodyless({
kind: 'buffered', kind: 'buffered',
status: rendered.status, status: rendered.status,
headers: { ...rendered.headers, ...headers }, headers: { ...rendered.headers, ...headers },
body: req.method === 'HEAD' ? '' : rendered.body, 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( async function unmatchedOutcome(
routes: RouteDef[], routes: RouteDef[],
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
@@ -149,18 +205,7 @@ async function unmatchedOutcome(
): Promise<HandleResult> { ): Promise<HandleResult> {
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) { if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path); const hit = await opts.static(path);
if (hit) return { injected, outcome: await staticOutcome(hit, req) };
if (hit) {
return {
injected,
outcome: {
kind: 'buffered',
status: 200,
headers: { 'content-type': hit.contentType },
body: req.method === 'HEAD' ? '' : hit.body,
},
};
}
} }
const allow = allowedMethods(routes, path); 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 { return {
injected, injected,
outcome: { outcome: bodyless({
kind: 'buffered', kind: 'buffered',
status: result.status, status: result.status,
headers: result.headers, headers: result.headers,
body: req.method === 'HEAD' ? '' : result.body, body: req.method === 'HEAD' ? '' : result.body,
}, }),
}; };
} }
+46 -1
View File
@@ -19,7 +19,10 @@ export function mergeInjectedHeaders(
const lowerKey = key.toLowerCase(); const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') { if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key]; // A header value may be an array (D11). `mergeVary` splits on commas, so joining first keeps
// every token a handler listed instead of stringifying the array by accident.
const value = handlerHeaders[key];
handlerVary = Array.isArray(value) ? value.join(', ') : value;
continue; continue;
} }
@@ -40,3 +43,45 @@ export function mergeInjectedHeaders(
else if (handlerVary !== undefined) merged['vary'] = handlerVary; else if (handlerVary !== undefined) merged['vary'] = handlerVary;
return merged; return merged;
} }
/**
* Prepares merged headers for Node's `writeHead`, which writes one header line per array element
* for *any* header. That is right for `set-cookie`, the one header whose values cannot be
* comma-joined (an `Expires` date carries a comma), and wrong for every other: RFC 9110 §5.3 makes a
* list header's repeated lines equivalent to one comma-joined line, and joining keeps all four
* adapters sending the same bytes. So every other array is joined with `, ` here, before
* `writeHead`. Returns the input untouched when it holds no array, which is nearly every response.
*/
export function joinListHeaders<T extends Record<string, unknown>>(headers: T): T {
let out: Record<string, unknown> | undefined;
for (const key of Object.keys(headers)) {
const value = headers[key];
if (!Array.isArray(value) || key.toLowerCase() === 'set-cookie') continue;
out ??= { ...headers };
out[key] = value.join(', ');
}
return (out as T | undefined) ?? headers;
}
/**
* Builds a web `Headers` from merged headers. A plain record cannot be handed to `new Response`:
* the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie.
* `set-cookie` elements are appended one by one, so each reaches the client as its own line;
* every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node.
*/
export function toWebHeaders(headers: Record<string, unknown>): Headers {
const out = new Headers();
for (const key of Object.keys(headers)) {
const value = headers[key];
if (value === undefined) continue;
if (!Array.isArray(value)) out.set(key, String(value));
else if (key.toLowerCase() === 'set-cookie') for (const cookie of value) out.append(key, String(cookie));
else out.set(key, value.join(', '));
}
return out;
}
+2 -2
View File
@@ -6,7 +6,7 @@ import type { Bus } from '../bus';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request'; import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream'; import { pipeStream } from './stream';
import { attachWs } from './ws'; import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders, joinListHeaders } from './headers';
import { import {
handle, handle,
correlateRequest, correlateRequest,
@@ -268,7 +268,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => { (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined; const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
const merged = mergeInjectedHeaders(handlerHeaders, injected); const merged = joinListHeaders(mergeInjectedHeaders(handlerHeaders, injected));
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
}; };
} }
+2
View File
@@ -62,6 +62,8 @@ export interface HttpOptions {
bodyDuplicates?: 'array' | 'last'; bodyDuplicates?: 'array' | 'last';
onError?: ErrorRenderer; onError?: ErrorRenderer;
static?: StaticResolver; static?: StaticResolver;
/** 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. */ /** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */
+6 -4
View File
@@ -10,7 +10,7 @@ import {
type HandleResult, type HandleResult,
type Preflight, type Preflight,
} from './core'; } from './core';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders, toWebHeaders } from './headers';
import { peerOf } from './peer'; import { peerOf } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body'; import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
@@ -202,7 +202,7 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */ /** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response { function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>; const headers = toWebHeaders(mergeInjectedHeaders(result.outcome.headers, result.injected));
if (result.outcome.kind === 'stream') { if (result.outcome.kind === 'stream') {
const body = asReadableStream( const body = asReadableStream(
@@ -272,13 +272,15 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
return new Response(JSON.stringify({ error: 'Service Unavailable' }), { return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503, status: 503,
headers: mergeInjectedHeaders( headers: toWebHeaders(
mergeInjectedHeaders(
{ {
'content-type': 'application/json', 'content-type': 'application/json',
'retry-after': '1', 'retry-after': '1',
}, },
injected, injected,
), ),
),
}); });
} }
@@ -316,7 +318,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
if ('preflight' in result) { if ('preflight' in result) {
return new Response(null, { return new Response(null, {
status: 204, status: 204,
headers: mergeInjectedHeaders(result.preflight, injected), headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
}); });
} }
+5 -1
View File
@@ -78,9 +78,13 @@ export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow'; export type { StepFn, CompiledFlow } from './flow';
// Parameter decorators // Parameter decorators
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params'; export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params'; export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
// Cookies
export { setCookie, parseCookies } from './cookies';
export type { CookieOptions } from './cookies';
// Observability // Observability
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger'; export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger'; export type { Logger, LogLevel, LogFields } from './logger';
+5 -1
View File
@@ -3,7 +3,11 @@ import 'reflect-metadata';
/** Any class constructor. Kept `any` because decorators must accept every target shape. */ /** Any class constructor. Kept `any` because decorators must accept every target shape. */
export type Ctor = new (...args: any[]) => any; export type Ctor = new (...args: any[]) => any;
/** Serializes a handler's return value into an HTTP response envelope. */ /** Serializes a handler's return value into an HTTP response envelope. */
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string }; export type TransformerFn = (value: unknown) => {
status?: number;
headers?: Record<string, string | string[]>;
body: string;
};
/** Metadata attached by `@Html`: optional file path and whether it is a template. */ /** Metadata attached by `@Html`: optional file path and whether it is a template. */
export interface HtmlMeta { export interface HtmlMeta {
+11 -4
View File
@@ -26,7 +26,7 @@ export interface OpenApiDoc {
type Parameter = { type Parameter = {
name: string; name: string;
in: 'path' | 'query' | 'header'; in: 'path' | 'query' | 'header' | 'cookie';
required: boolean; required: boolean;
schema: { type: 'string'; pattern?: string }; schema: { type: 'string'; pattern?: string };
}; };
@@ -57,13 +57,20 @@ function pathParams(pattern: string): Parameter[] {
}); });
} }
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */ /** Where each argument source sits in an OpenAPI parameter list; sources absent here are not parameters. */
const ARG_LOCATION: Partial<Record<ArgSpec['source'], Parameter['in']>> = {
query: 'query',
headers: 'header',
cookies: 'cookie',
};
/** Query, header and cookie parameters declared by `@query` / `@headers` / `@header` / `@cookies` / `@cookie`. */
function argParams(args: ArgSpec[]): Parameter[] { function argParams(args: ArgSpec[]): Parameter[] {
const params: Parameter[] = []; const params: Parameter[] = [];
for (const arg of args) { for (const arg of args) {
if (arg.source !== 'query' && arg.source !== 'headers') continue; const location = ARG_LOCATION[arg.source];
const location = arg.source === 'query' ? 'query' : 'header'; if (!location) continue;
const names = arg.keys ?? (arg.key ? [arg.key] : []); const names = arg.keys ?? (arg.key ? [arg.key] : []);
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } }); for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
} }
+27 -3
View File
@@ -2,6 +2,7 @@ import 'reflect-metadata';
import type { Ctor } from './metadata'; import type { Ctor } from './metadata';
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema'; import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
import { ValidationError } from './signals'; import { ValidationError } from './signals';
import { parseCookies } from './cookies';
/** Parsed URL query string as flat key/value pairs. */ /** Parsed URL query string as flat key/value pairs. */
export type Query = Record<string, string>; export type Query = Record<string, string>;
@@ -10,7 +11,7 @@ export type Headers = Record<string, string | string[] | undefined>;
/** Per-request bag that accumulates values produced by steps and providers. */ /** Per-request bag that accumulates values produced by steps and providers. */
export type Context = Record<string, unknown>; export type Context = Record<string, unknown>;
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort'; type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort';
/** Describes how a single handler parameter is sourced and (optionally) validated. */ /** Describes how a single handler parameter is sourced and (optionally) validated. */
export interface ArgSpec { export interface ArgSpec {
index: number; index: number;
@@ -71,6 +72,14 @@ export const body: ArgDecorator = envelope('body');
export const headers: ArgDecorator = envelope('headers'); export const headers: ArgDecorator = envelope('headers');
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */ /** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
export const header: ArgDecorator = envelope('headers'); export const header: ArgDecorator = envelope('headers');
/**
* Inject request cookies, parsed from the `Cookie` header: no arg for the whole map (`{}` when the
* request has none), a key to pick one, an array to pick several. Accepts a schema to validate.
* First value wins for a repeated name, `%`-sequences are decoded, malformed pairs are skipped.
*/
export const cookies: ArgDecorator = envelope('cookies');
/** Inject a single request cookie by name (singular alias of {@link cookies}); `undefined` when absent. */
export const cookie: ArgDecorator = envelope('cookies');
/** Inject a value produced upstream by a step or provider, addressed by key. */ /** Inject a value produced upstream by a step or provider, addressed by key. */
export function needs(key: string): ParameterDecorator { export function needs(key: string): ParameterDecorator {
@@ -126,10 +135,11 @@ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<u
function resolveOne(spec: ArgSpec, context: Context): unknown { function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.source === 'ctx') return context; if (spec.source === 'ctx') return context;
if (spec.source === 'needs') return context[spec.key as string]; // `cookies` is a seed token like `headers`, but parsed on demand rather than seeded on every request.
if (spec.source === 'needs') return spec.key === 'cookies' ? cookiesOf(context) : context[spec.key as string];
if (spec.source === 'inbound') return context.inbound; if (spec.source === 'inbound') return context.inbound;
if (spec.source === 'abort') return context.abort; if (spec.source === 'abort') return context.abort;
const bag = context[spec.source]; const bag = spec.source === 'cookies' ? cookiesOf(context) : context[spec.source];
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
const values = bag as Record<string, unknown>; const values = bag as Record<string, unknown>;
@@ -142,3 +152,17 @@ function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.key !== undefined) return values[spec.key]; if (spec.key !== undefined) return values[spec.key];
return values; return values;
} }
/**
* The request's cookie map, parsed on first use and cached on the context, so a route that never
* declares a cookie argument never parses the header and one that declares several parses it once.
* Serves `@cookie`, `@cookies` and `@needs('cookies')` alike.
*/
function cookiesOf(context: Context): unknown {
if (context.cookies === undefined) {
const headers = context.headers as Headers | undefined;
context.cookies = parseCookies(headers?.cookie);
}
return context.cookies;
}
+2 -1
View File
@@ -14,7 +14,8 @@ export interface PipelineStep {
/** A fully materialized HTTP response produced by a transformer. */ /** A fully materialized HTTP response produced by a transformer. */
export interface ResponseShape { export interface ResponseShape {
status: number; status: number;
headers: Record<string, string>; /** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string; body: string;
} }
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */ /** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
+2 -2
View File
@@ -20,7 +20,7 @@ export interface HttpErrorLike {
status: number; status: number;
message: string; message: string;
body?: unknown; body?: unknown;
headers?: Record<string, string>; headers?: Record<string, string | string[]>;
} }
/** /**
@@ -35,7 +35,7 @@ export class HttpError extends Error {
readonly status: number, readonly status: number,
message?: string, message?: string,
readonly body?: unknown, readonly body?: unknown,
readonly headers?: Record<string, string>, readonly headers?: Record<string, string | string[]>,
) { ) {
super(message ?? `HTTP ${status}`); super(message ?? `HTTP ${status}`);
this.name = new.target.name; this.name = new.target.name;
+2 -1
View File
@@ -6,7 +6,8 @@ import type { Logger } from './logger';
/** A ready-to-send HTTP response. */ /** A ready-to-send HTTP response. */
export interface ErrorResponse { export interface ErrorResponse {
status: number; status: number;
headers: Record<string, string>; /** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string; body: string;
} }
+73 -12
View File
@@ -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 { export interface StaticHit {
body: Buffer;
contentType: string; 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. */ /** 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>; 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 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`. */ * 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) { 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; 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`. */ /** Stats `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
async function readConfined( async function statConfined(
fs: typeof import('node:fs'), fs: typeof import('node:fs'),
nodePath: typeof import('node:path'), nodePath: typeof import('node:path'),
root: string, root: string,
full: string, full: string,
cacheControl: string,
): Promise<StaticHit | undefined> { ): Promise<StaticHit | undefined> {
let real = await confine(fs, nodePath.sep, root, full); let real = await confine(fs, nodePath.sep, root, full);
if (!real) return undefined; 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. // `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 (isDir) {
real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
if (!real) return undefined; 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 {
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 // 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` // 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. // on every path component, which Node, Deno and Bun do not offer portably.
const body = await fs.promises.readFile(real); read: () => fs.promises.readFile(path),
// 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)) };
} }
/** /**
@@ -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 * 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". * (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 fs: typeof import('node:fs');
let nodePath: typeof import('node:path'); let nodePath: typeof import('node:path');
@@ -165,7 +226,7 @@ export function buildStaticResolver(root: string | true): StaticResolver {
if (!rootReal) return undefined; if (!rootReal) return undefined;
try { try {
return await readConfined(fs, nodePath, rootReal, full); return await statConfined(fs, nodePath, rootReal, full, cacheControl);
} catch { } catch {
return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
} }
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Bun runtime: Set-Cookie arrays leave `Bun.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
test('T7/T8/T11 on Bun.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveBun(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0 });
try {
const base = `http://127.0.0.1:${server.port}`;
const two = await fetch(`${base}/c/two`);
await two.arrayBuffer();
expect(two.headers.getSetCookie()).toEqual([C1, C2]);
expect(two.headers.get('x-custom')).toBe('a, b');
const error = await fetch(`${base}/c/error`);
await error.arrayBuffer();
expect(error.status).toBe(401);
expect(error.headers.getSetCookie()).toEqual([C1, C2]);
const one = await fetch(`${base}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
expect(await one.json()).toEqual({ a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+37
View File
@@ -0,0 +1,37 @@
// CARD-15 (#114) under the real Bun runtime: static 304 without reading the file (T1), and a
// handler ETag round-trip under `etag: true` (T5). Run with: npm run test:bun
import 'reflect-metadata';
import fs from 'node:fs';
import { test, expect, spyOn } from 'bun:test';
import { createApp } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { EtagModule, STATIC_DIR } from '../fixtures/etag-app.ts';
test('T1/T5 on Bun.serve: static and handler 304s, readFile once', async () => {
const readFile = spyOn(fs.promises, 'readFile');
const server = await serveBun(createApp({ modules: [EtagModule], etag: true, static: STATIC_DIR }), {
hostname: '127.0.0.1',
port: 0,
});
const base = `http://127.0.0.1:${server.port}`;
try {
const s1 = await fetch(`${base}/asset.txt`);
expect(await s1.text()).toBe('served');
const etag = s1.headers.get('etag')!;
expect(etag).toMatch(/^W\/"\d+-[0-9a-z]+"$/);
expect(s1.headers.get('cache-control')).toBe('no-cache');
const s2 = await fetch(`${base}/asset.txt`, { headers: { 'if-none-match': etag } });
expect([s2.status, await s2.text(), s2.headers.get('etag'), s2.headers.get('content-type')]).toEqual([304, '', etag, null]);
expect(readFile).toHaveBeenCalledTimes(1);
const h1 = await fetch(`${base}/h/json`);
await h1.text();
const tag = h1.headers.get('etag')!;
const h2 = await fetch(`${base}/h/json`, { headers: { 'if-none-match': tag } });
expect([h2.status, await h2.text(), h2.headers.get('etag')]).toEqual([304, '', tag]);
} finally {
readFile.mockRestore();
await server.close({ timeoutMs: 1000 });
}
});
+306
View File
@@ -0,0 +1,306 @@
// CARD-14 (#113): reading cookies with @cookie/@cookies, writing them with setCookie, and more than
// one Set-Cookie line per response on the Node adapter and app.fetch. Deno, Bun and edge repeat the
// two-line cases in test/deno/cookies.test.ts, test/bun/cookies.test.ts and test/edge/run.ts.
import 'reflect-metadata';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import WebSocket from 'ws';
import { describe, expect, it, afterAll } from 'vitest';
import {
createApp,
Route,
Get,
Ws,
Module,
Transformer,
HttpError,
needs,
cookie,
cookies,
setCookie,
parseCookies,
type TransformerFn,
} from '../src/index';
const C1 = setCookie('a', '1');
const C2 = setCookie('b', '2', { maxAge: 60 });
const twoCookies: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'application/json', 'set-cookie': [C1, C2] },
body: JSON.stringify(value),
});
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/all')
all(@cookies() all: Record<string, string>) {
return { all, keys: Object.keys(all) };
}
@Get('/pick')
pick(@cookies(['d', 'e']) picked: Record<string, string>) {
return picked;
}
@Get('/needs')
viaNeeds(@needs('cookies') jar: Record<string, string>) {
return { sid: jar.sid ?? null };
}
@Get('/transformer')
@Transformer(twoCookies)
transformer() {
return { ok: true };
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
@Get('/custom')
@Transformer((v) => ({ headers: { 'x-custom': ['a', 'b'], vary: ['Accept', 'Accept-Language'] }, body: String(v) }))
custom() {
return 'x';
}
@Get('/renderer')
renderer() {
throw new Error('render me');
}
@Ws('/ws')
ws(@cookie('a') a: string | undefined) {
return (async function* () {
yield `a=${a}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
class M {}
const app = createApp({
modules: [M],
cors: { origins: ['http://ok.test'] },
onError: (error) =>
error instanceof Error && error.message === 'render me'
? { status: 418, headers: { 'content-type': 'text/plain', 'set-cookie': [C1, C2] }, body: 'teapot' }
: undefined,
});
let server: http.Server;
let port: number;
afterAll(() => server?.close());
async function boot(): Promise<void> {
if (server) return;
server = await app.listen(0);
port = (server.address() as AddressInfo).port;
}
/** A raw request, so repeated header lines are visible as they came off the socket. */
async function raw(
path: string,
headers: Record<string, string> = {},
): Promise<{ status: number; lines: [string, string][]; body: string }> {
await boot();
return new Promise((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path, headers }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => {
const lines: [string, string][] = [];
for (let i = 0; i < res.rawHeaders.length; i += 2)
lines.push([res.rawHeaders[i].toLowerCase(), res.rawHeaders[i + 1]]);
resolve({ status: res.statusCode!, lines, body });
});
})
.on('error', reject);
});
}
const valuesOf = (lines: [string, string][], name: string) => lines.filter(([k]) => k === name).map(([, v]) => v);
const fetchVia = (path: string, headers: Record<string, string> = {}) =>
app.fetch(new Request(`http://x${path}`, { headers }));
describe('parseCookies', () => {
it('T1: first value wins, %-sequences decode', () => {
expect(parseCookies('a=1; a=2; b=%41')).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs are skipped, an undecodable value is kept raw', () => {
expect({ ...parseCookies('=x; c; d=%ZZ; e=5') }).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no header is an empty map', () => {
expect({ ...parseCookies(undefined) }).toEqual({});
});
it('joins several cookie lines (HTTP/2, proxies) with "; "', () => {
expect({ ...parseCookies(['a=1', 'b=2; a=3']) }).toEqual({ a: '1', b: '2' });
});
it('treats __proto__ as an ordinary key, never a prototype write', () => {
const map = parseCookies('__proto__=x; constructor=y');
expect(map['__proto__']).toBe('x');
expect(map['constructor']).toBe('y');
expect(({} as any).x).toBeUndefined();
});
});
describe('setCookie', () => {
it('T4: documented defaults, Secure per D10', () => {
expect(setCookie('s', 'v')).toBe('s=v; Path=/; Secure; HttpOnly; SameSite=Lax');
});
it('serialises every option', () => {
const expires = new Date(Date.UTC(2030, 0, 1));
expect(
setCookie('s', 'v', {
maxAge: 10,
expires,
domain: 'example.com',
path: '/app',
httpOnly: false,
sameSite: 'none',
partitioned: true,
}),
).toBe(
's=v; Max-Age=10; Expires=Tue, 01 Jan 2030 00:00:00 GMT; Domain=example.com; Path=/app; Secure; SameSite=None; Partitioned',
);
expect(setCookie('s', 'v', { secure: false, sameSite: 'strict' })).toBe('s=v; Path=/; HttpOnly; SameSite=Strict');
});
it('T5: refuses header injection and bad names, naming the field', () => {
expect(() => setCookie('s', 'v\r\nX: y')).toThrow(/value for 's'/);
expect(() => setCookie('a b', 'v')).toThrow(/name "a b"/);
for (const bad of ['a;b', 'a,b', 'a b', 'a\tb', 'a\u0001b'])
expect(() => setCookie('s', bad), JSON.stringify(bad)).toThrow(/value/);
expect(() => setCookie('s', 'v', { path: '/\r\nX: y' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { domain: 'a.com\nX' })).toThrow(/domain/);
expect(() => setCookie('s', 'v', { path: '/; Domain=evil' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { maxAge: 1.5 })).toThrow(/maxAge/);
expect(() => setCookie('s', 'v', { expires: new Date('nope') })).toThrow(/expires/);
expect(() => setCookie('s', 'v', { sameSite: 'loose' as never })).toThrow(/sameSite/);
});
it('T6: sameSite none and partitioned both require secure', () => {
expect(() => setCookie('s', 'v', { sameSite: 'none', secure: false })).toThrow(/sameSite 'none'.*secure/);
expect(() => setCookie('s', 'v', { partitioned: true, secure: false })).toThrow(/partitioned.*secure/);
});
});
describe('@cookie / @cookies on a live Node server', () => {
it('T1: first wins and decodes', async () => {
const res = await raw('/c/one', { cookie: 'a=1; a=2; b=%41' });
expect(JSON.parse(res.body)).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs never 400', async () => {
const res = await raw('/c/all', { cookie: '=x; c; d=%ZZ; e=5' });
expect(res.status).toBe(200);
expect(JSON.parse(res.body).all).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no Cookie header', async () => {
expect(JSON.parse((await raw('/c/all')).body).all).toEqual({});
expect(JSON.parse((await raw('/c/one')).body)).toEqual({ a: null, b: null });
});
it('picks a key list', async () => {
expect(JSON.parse((await raw('/c/pick', { cookie: 'd=4; e=5; f=6' })).body)).toEqual({ d: '4', e: '5' });
});
it('@needs("cookies") resolves the same map', async () => {
expect(JSON.parse((await raw('/c/needs', { cookie: 'sid=abc' })).body)).toEqual({ sid: 'abc' });
});
it('resolves on a WebSocket route', async () => {
await boot();
const client = new WebSocket(`ws://127.0.0.1:${port}/c/ws`, { headers: { cookie: 'a=hello' } });
const message = await new Promise<string>((resolve, reject) => {
client.on('message', (data) => resolve(String(data)));
client.on('error', reject);
});
client.close();
expect(message).toBe('a=hello');
});
});
describe('several Set-Cookie lines', () => {
it('T7: custom @Transformer, Node: two lines', async () => {
const res = await raw('/c/transformer');
expect(valuesOf(res.lines, 'set-cookie')).toEqual([C1, C2]);
});
it('T7: custom @Transformer, app.fetch: two lines', async () => {
const res = await fetchVia('/c/transformer');
expect(res.headers.getSetCookie()).toEqual([C1, C2]);
});
it('T8: HttpError.headers and an onError renderer: two lines on both adapters', async () => {
for (const path of ['/c/error', '/c/renderer']) {
const res = await raw(path);
expect(valuesOf(res.lines, 'set-cookie'), path).toEqual([C1, C2]);
expect((await fetchVia(path)).headers.getSetCookie(), path).toEqual([C1, C2]);
}
});
it('T9: array kept, injected vary merged with a handler vary array', async () => {
const res = await raw('/c/custom', { origin: 'http://ok.test' });
const vary = valuesOf(res.lines, 'vary');
expect(vary).toHaveLength(1);
expect(vary[0].split(', ')).toEqual(['Accept', 'Accept-Language', 'Origin']);
const viaFetch = await fetchVia('/c/custom', { origin: 'http://ok.test' });
expect(viaFetch.headers.get('vary')).toBe('Accept, Accept-Language, Origin');
const cookieRes = await raw('/c/transformer', { origin: 'http://ok.test' });
expect(valuesOf(cookieRes.lines, 'set-cookie')).toEqual([C1, C2]);
expect(valuesOf(cookieRes.lines, 'vary')).toEqual(['Origin']);
});
it('T11: any other array header is one line joined with ", "', async () => {
const res = await raw('/c/custom');
expect(valuesOf(res.lines, 'x-custom')).toEqual(['a, b']);
expect((await fetchVia('/c/custom')).headers.get('x-custom')).toBe('a, b');
});
it('injected security headers stay authoritative over a handler array', async () => {
@Route('/s')
class Spoof {
@Get('/')
@Transformer(() => ({ headers: { 'x-content-type-options': ['sniff', 'me'] }, body: '' }))
get() {
return null;
}
}
@Module({ mountpoint: '/', controllers: [Spoof] })
class SM {}
const res = await createApp({ modules: [SM] }).fetch(new Request('http://x/s'));
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
});
describe('OpenAPI', () => {
it('lists a @cookie arg as an in: cookie parameter', () => {
const doc = app.openapi();
const params = (doc.paths['/c/one'].get as any).parameters;
expect(params).toEqual(
expect.arrayContaining([
{ name: 'a', in: 'cookie', required: false, schema: { type: 'string' } },
{ name: 'b', in: 'cookie', required: false, schema: { type: 'string' } },
]),
);
});
});
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Deno runtime: Set-Cookie arrays leave `Deno.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
Deno.test('T7/T8/T11 on Deno.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveDeno(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0, onListen: () => {} });
const port = (server as unknown as { addr: { port: number } }).addr.port;
try {
const two = await fetch(`http://127.0.0.1:${port}/c/two`);
await two.body?.cancel();
assertEquals(two.headers.getSetCookie(), [C1, C2]);
assertEquals(two.headers.get('x-custom'), 'a, b');
const error = await fetch(`http://127.0.0.1:${port}/c/error`);
await error.body?.cancel();
assertEquals(error.status, 401);
assertEquals(error.headers.getSetCookie(), [C1, C2]);
const one = await fetch(`http://127.0.0.1:${port}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
assertEquals(await one.json(), { a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+45
View File
@@ -0,0 +1,45 @@
// CARD-15 (#114) under the real Deno runtime: static 304 without reading the file (T1), and a
// handler ETag round-trip under `etag: true` (T5). Run with: npm run test:deno
import 'npm:reflect-metadata';
import fs from 'node:fs';
import { assertEquals, assertMatch } from 'jsr:@std/assert';
import { createApp } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { EtagModule, STATIC_DIR } from '../fixtures/etag-app.ts';
Deno.test('T1/T5 on Deno.serve: static and handler 304s, readFile once', async () => {
const original = fs.promises.readFile;
let reads = 0;
// deno-lint-ignore no-explicit-any
(fs.promises as any).readFile = (...args: unknown[]) => {
// Deno's own readFile re-enters this function with a file descriptor (FileHandle.readFile), so
// only calls naming a path are reads by core.
if (typeof args[0] === 'string') reads++;
// deno-lint-ignore no-explicit-any
return (original as any).apply(fs.promises, args);
};
const app = createApp({ modules: [EtagModule], etag: true, static: STATIC_DIR });
const server = await serveDeno(app, { hostname: '127.0.0.1', port: 0, onListen: () => {} });
const base = `http://127.0.0.1:${(server as unknown as { addr: { port: number } }).addr.port}`;
try {
const s1 = await fetch(`${base}/asset.txt`);
assertEquals(await s1.text(), 'served');
const etag = s1.headers.get('etag')!;
assertMatch(etag, /^W\/"\d+-[0-9a-z]+"$/);
assertEquals(s1.headers.get('cache-control'), 'no-cache');
const s2 = await fetch(`${base}/asset.txt`, { headers: { 'if-none-match': etag } });
assertEquals([s2.status, await s2.text(), s2.headers.get('etag'), s2.headers.get('content-type')], [304, '', etag, null]);
assertEquals(reads, 1);
const h1 = await fetch(`${base}/h/json`);
await h1.text();
const tag = h1.headers.get('etag')!;
const h2 = await fetch(`${base}/h/json`, { headers: { 'if-none-match': tag } });
assertEquals([h2.status, await h2.text(), h2.headers.get('etag')], [304, '', tag]);
} finally {
(fs.promises as { readFile: unknown }).readFile = original;
await server.close({ timeoutMs: 1000 });
}
});
+27 -1
View File
@@ -66,6 +66,32 @@ async function main() {
assert.equal(httpRes.status, 200); assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true }); assert.deepEqual(await httpRes.json(), { ok: true });
// CARD-14 (#113): a Set-Cookie array leaves workerd as one line per cookie; other arrays join.
const cookieRes = await mf.dispatchFetch('http://localhost/rt/cookies');
await cookieRes.arrayBuffer();
assert.deepEqual(cookieRes.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
assert.equal(cookieRes.headers.get('x-custom'), 'a, b');
const cookieErr = await mf.dispatchFetch('http://localhost/rt/cookie-error');
await cookieErr.arrayBuffer();
assert.equal(cookieErr.status, 401);
assert.deepEqual(cookieErr.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
const readCookie = await mf.dispatchFetch('http://localhost/rt/cookie', { headers: { cookie: 'a=1; b=%41' } });
assert.deepEqual(await readCookie.json(), { b: 'A' });
// CARD-15 (#114), T5/T11: handler ETag round-trip on workerd. Static is a boot error there (N/A).
const tag1 = await mf.dispatchFetch('http://etag/rt/hello');
await tag1.arrayBuffer();
const etag = tag1.headers.get('etag');
assert.match(String(etag), /^W\/"\w+-\w+"$/);
const tag2 = await mf.dispatchFetch('http://etag/rt/hello', { headers: { 'if-none-match': String(etag) } });
assert.equal(tag2.status, 304);
assert.equal(await tag2.text(), '');
assert.equal(tag2.headers.get('etag'), etag);
assert.equal(tag2.headers.get('content-type'), null);
const untagged = await mf.dispatchFetch('http://localhost/rt/hello');
await untagged.arrayBuffer();
assert.equal(untagged.headers.get('etag'), null, 'etag off: no ETag');
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a // Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
// chunked upload's content-length, so the streamed case is enforced by the read count alone. // chunked upload's content-length, so the streamed case is enforced by the read count alone.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
@@ -138,7 +164,7 @@ async function main() {
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1); assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009); assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS'); console.log('edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
} finally { } finally {
await mf.dispose(); await mf.dispose();
} }
+23 -3
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test. // Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven // Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts). // identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index'; import { createApp, Route, Get, Post, Ws, body, ctx, cookie, Module, Transformer, HttpError } from '../../src/index';
import { edgeHandler } from '../../src/edge'; import { edgeHandler } from '../../src/edge';
@Route('/rt') @Route('/rt')
@@ -11,6 +11,23 @@ class Rt {
return { ok: true }; return { ok: true };
} }
// CARD-14 (#113): two Set-Cookie lines from workerd, and @cookie on the request side.
@Get('/cookies')
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'], 'x-custom': ['a', 'b'] }, body: '{}' }))
cookies() {
return null;
}
@Get('/cookie-error')
cookieError() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] });
}
@Get('/cookie')
readCookie(@cookie('b') b: string | undefined) {
return { b: b ?? null };
}
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still // #105: the body limit, read from workerd's own request stream. Small, so every refused body still
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET // fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
// instead, which is the transport racing the answer rather than a different answer. // instead, which is the transport racing the answer rather than a different answer.
@@ -49,9 +66,12 @@ class M {}
const app = createApp({ modules: [M] }); const app = createApp({ modules: [M] });
// #107: the same graph with tight ws limits, reached through the `limited` host. // #107: the same graph with tight ws limits, reached through the `limited` host.
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } }); const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) }; // CARD-15 (#114): the same graph with handler ETags on, reached through the `etag` host.
const tagged = createApp({ modules: [M], etag: true });
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited), etag: edgeHandler(tagged) };
const hosts: Record<string, typeof handlers.default> = { limited: handlers.limited, etag: handlers.etag };
export default { export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) => fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx), (hosts[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx),
}; };
+273
View File
@@ -0,0 +1,273 @@
// CARD-15 (#114): weak ETags and conditional GET for static files (always, D12) and buffered handler
// responses (`createApp({ etag: true })`). Deno, Bun and edge repeat T1/T5 in their own suites.
import 'reflect-metadata';
import fs, { mkdtempSync, writeFileSync, utimesSync } from 'node:fs';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { describe, expect, it, vi, afterEach } from 'vitest';
import { createApp, Route, Get, Post, Sse, Module, Transformer, NotModified } from '../src/index';
import { ifNoneMatchMatches, bodyEtag, notModifiedSince } from '../src/http/conditional';
const root = mkdtempSync(join(tmpdir(), 'gt-etag-'));
const file = join(root, 'a.txt');
writeFileSync(file, 'hello static');
const mtime = new Date(Date.UTC(2026, 0, 2, 3, 4, 5));
utimesSync(file, mtime, mtime);
@Route('/h')
class Handlers {
@Get('/json')
json() {
return { n: 1 };
}
@Get('/own')
@Transformer(() => ({ headers: { 'content-type': 'text/plain', ETag: '"v7"' }, body: 'v7' }))
own() {
return null;
}
@Post('/post')
post() {
return { n: 1 };
}
@Sse('/sse')
sse() {
return (async function* () {
yield 'x';
})();
}
@Get('/skip')
skip() {
throw new NotModified();
}
}
@Module({ mountpoint: '/', controllers: [Handlers] })
class M {}
const staticApp = createApp({ modules: [], static: root });
const etagApp = createApp({ modules: [M], etag: true });
const plainApp = createApp({ modules: [M] });
const req = (app: typeof staticApp, path: string, init: RequestInit = {}) =>
app.fetch(new Request(`http://x${path}`, init));
afterEach(() => vi.restoreAllMocks());
describe('comparison (RFC 9110 §13.1.2)', () => {
it('is weak, splits lists outside quotes, and honours *', () => {
expect(ifNoneMatchMatches('W/"v7"', '"v7"')).toBe(true);
expect(ifNoneMatchMatches('"v7"', 'W/"v7"')).toBe(true);
expect(ifNoneMatchMatches('"a", W/"b", "c"', 'W/"b"')).toBe(true);
expect(ifNoneMatchMatches('"a,b"', '"b"')).toBe(false);
expect(ifNoneMatchMatches('"x", "a,b"', '"a,b"')).toBe(true);
expect(ifNoneMatchMatches('*', '"anything"')).toBe(true);
expect(ifNoneMatchMatches('"nope"', '"v7"')).toBe(false);
});
it('If-Modified-Since compares at one-second resolution and ignores a bad date', () => {
expect(notModifiedSince(new Date(1000).toUTCString(), 1400)).toBe(true);
expect(notModifiedSince(new Date(1000).toUTCString(), 2000)).toBe(false);
expect(notModifiedSince('not a date', 0)).toBe(false);
});
it('a body tag is weak, deterministic and length-prefixed', () => {
expect(bodyEtag('abc')).toBe(bodyEtag(Buffer.from('abc')));
expect(bodyEtag('abc')).toMatch(/^W\/"3-[0-9a-z]+"$/);
expect(bodyEtag('abc')).not.toBe(bodyEtag('abd'));
expect(bodyEtag('é')).toMatch(/^W\/"2-/); // UTF-8 bytes, not UTF-16 units
});
});
describe('static (D12: always on)', () => {
it('T1: 200 with ETag + Last-Modified + no-cache, then 304 without reading the file', async () => {
const readFile = vi.spyOn(fs.promises, 'readFile');
const first = await req(staticApp, '/a.txt');
expect(first.status).toBe(200);
expect(await first.text()).toBe('hello static');
const etag = first.headers.get('etag')!;
expect(etag).toMatch(/^W\/"12-[0-9a-z]+"$/);
expect(first.headers.get('last-modified')).toBe(mtime.toUTCString());
expect(first.headers.get('cache-control')).toBe('no-cache');
const second = await req(staticApp, '/a.txt', { headers: { 'if-none-match': etag } });
expect(second.status).toBe(304);
expect(await second.text()).toBe('');
expect(second.headers.get('etag')).toBe(etag);
expect(second.headers.get('cache-control')).toBe('no-cache');
expect(second.headers.get('last-modified')).toBe(mtime.toUTCString());
expect(second.headers.get('content-type')).toBeNull();
expect(second.headers.get('x-content-type-options')).toBe('nosniff');
expect(readFile).toHaveBeenCalledTimes(1);
});
it('T2: If-Modified-Since at or after mtime, no If-None-Match → 304', async () => {
const res = await req(staticApp, '/a.txt', { headers: { 'if-modified-since': mtime.toUTCString() } });
expect(res.status).toBe(304);
const older = await req(staticApp, '/a.txt', {
headers: { 'if-modified-since': new Date(mtime.getTime() - 5000).toUTCString() },
});
expect(older.status).toBe(200);
});
it('T3: If-None-Match wins over a matching If-Modified-Since', async () => {
const res = await req(staticApp, '/a.txt', {
headers: { 'if-none-match': '"other"', 'if-modified-since': mtime.toUTCString() },
});
expect(res.status).toBe(200);
});
it('T4: a touched file gets a new ETag and a 200', async () => {
const touched = join(root, 'b.txt');
writeFileSync(touched, 'b');
utimesSync(touched, mtime, mtime);
const before = (await req(staticApp, '/b.txt')).headers.get('etag')!;
const later = new Date(mtime.getTime() + 60_000);
utimesSync(touched, later, later);
const res = await req(staticApp, '/b.txt', { headers: { 'if-none-match': before } });
expect(res.status).toBe(200);
expect(res.headers.get('etag')).not.toBe(before);
});
it('HEAD with a matching tag is a 304 too, and never reads', async () => {
const etag = (await req(staticApp, '/a.txt')).headers.get('etag')!;
const readFile = vi.spyOn(fs.promises, 'readFile');
const res = await req(staticApp, '/a.txt', { method: 'HEAD', headers: { 'if-none-match': etag } });
expect(res.status).toBe(304);
const head = await req(staticApp, '/a.txt', { method: 'HEAD' });
expect(head.status).toBe(200);
expect(head.headers.get('etag')).toBe(etag);
expect(readFile).not.toHaveBeenCalled();
});
it('static: { dir, cacheControl } replaces no-cache on 200 and 304', async () => {
const app = createApp({ modules: [], static: { dir: root, cacheControl: 'public, max-age=31536000, immutable' } });
const res = await req(app, '/a.txt');
expect(res.headers.get('cache-control')).toBe('public, max-age=31536000, immutable');
const nm = await req(app, '/a.txt', { headers: { 'if-none-match': res.headers.get('etag')! } });
expect(nm.status).toBe(304);
expect(nm.headers.get('cache-control')).toBe('public, max-age=31536000, immutable');
});
it('static object validation throws at createApp', () => {
expect(() => createApp({ modules: [], static: { dir: root, cachecontrol: 'x' } as never })).toThrow(
/unknown key 'cachecontrol'/,
);
expect(() => createApp({ modules: [], static: { cacheControl: 'no-cache\r\nX-Evil: 1' } })).toThrow(/CR or LF/);
expect(() => createApp({ modules: [], static: { cacheControl: 5 as never } })).toThrow(/cacheControl/);
});
});
describe('handlers (etag: true)', () => {
it('T5: a buffered JSON GET twice → 304, empty body, same ETag', async () => {
const first = await req(etagApp, '/h/json');
const etag = first.headers.get('etag')!;
expect(etag).toBe(bodyEtag(JSON.stringify({ n: 1 })));
const second = await req(etagApp, '/h/json', { headers: { 'if-none-match': etag } });
expect(second.status).toBe(304);
expect(await second.text()).toBe('');
expect(second.headers.get('etag')).toBe(etag);
expect(second.headers.get('content-type')).toBeNull();
});
it('T6: a handler-set ETag is kept and drives the comparison', async () => {
const first = await req(etagApp, '/h/own');
expect(first.headers.get('etag')).toBe('"v7"');
const res = await req(etagApp, '/h/own', { headers: { 'if-none-match': 'W/"v7"' } });
expect(res.status).toBe(304);
expect(res.headers.get('etag')).toBe('"v7"');
});
it('T7/T8: a list containing the tag, and *', async () => {
const etag = (await req(etagApp, '/h/json')).headers.get('etag')!;
const list = await req(etagApp, '/h/json', { headers: { 'if-none-match': `"a", ${etag}, "c"` } });
expect(list.status).toBe(304);
const star = await req(etagApp, '/h/json', { headers: { 'if-none-match': '*' } });
expect(star.status).toBe(304);
});
it('T9: POST, SSE and 404 get no ETag and no 304', async () => {
const post = await req(etagApp, '/h/post', { method: 'POST', headers: { 'if-none-match': '*' } });
expect(post.status).toBe(200);
expect(post.headers.get('etag')).toBeNull();
const sse = await req(etagApp, '/h/sse', { headers: { 'if-none-match': '*' } });
expect(sse.status).toBe(200);
expect(sse.headers.get('etag')).toBeNull();
await sse.body?.cancel();
const missing = await req(etagApp, '/h/nope', { headers: { 'if-none-match': '*' } });
expect(missing.status).toBe(404);
expect(missing.headers.get('etag')).toBeNull();
});
it('T10: HEAD with a matching tag → 304; HEAD and GET carry the same tag', async () => {
const etag = (await req(etagApp, '/h/json')).headers.get('etag')!;
const head = await req(etagApp, '/h/json', { method: 'HEAD' });
expect(head.headers.get('etag')).toBe(etag);
const res = await req(etagApp, '/h/json', { method: 'HEAD', headers: { 'if-none-match': etag } });
expect(res.status).toBe(304);
});
it('etag absent: no ETag on a handler response and no 304, even for a handler-set tag', async () => {
const res = await req(plainApp, '/h/json', { headers: { 'if-none-match': '*' } });
expect(res.status).toBe(200);
expect(res.headers.get('etag')).toBeNull();
const own = await req(plainApp, '/h/own', { headers: { 'if-none-match': '"v7"' } });
expect(own.status).toBe(200);
});
it('NotModified still works, and its 304 has no body or content-type', async () => {
for (const app of [plainApp, etagApp]) {
const res = await req(app, '/h/skip');
expect(res.status).toBe(304);
expect(await res.text()).toBe('');
expect(res.headers.get('content-type')).toBeNull();
}
});
it('createApp({ etag }) accepts only a boolean', () => {
expect(() => createApp({ modules: [], etag: 'yes' as never })).toThrow(/etag.*boolean/);
expect(() => createApp({ modules: [], etag: false })).not.toThrow();
});
});
describe('Node adapter (T11)', () => {
const raw = (port: number, path: string, headers: Record<string, string> = {}) =>
new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path, headers }, (res) => {
let body = '';
res.on('data', (c) => (body += c));
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, body }));
})
.on('error', reject);
});
it('T1 and T5 over a real socket: 304s carry the tag and no body', async () => {
const app = createApp({ modules: [M], etag: true, static: root });
const server = await app.listen(0);
const { port } = server.address() as AddressInfo;
try {
const readFile = vi.spyOn(fs.promises, 'readFile');
const s1 = await raw(port, '/a.txt');
const s2 = await raw(port, '/a.txt', { 'if-none-match': String(s1.headers.etag) });
expect([s1.status, s2.status]).toEqual([200, 304]);
expect(s2.body).toBe('');
expect(s2.headers.etag).toBe(s1.headers.etag);
expect(s2.headers['content-type']).toBeUndefined();
expect(readFile).toHaveBeenCalledTimes(1);
const h1 = await raw(port, '/h/json');
const h2 = await raw(port, '/h/json', { 'if-none-match': String(h1.headers.etag) });
expect([h1.status, h2.status]).toEqual([200, 304]);
expect(h2.body).toBe('');
expect(h2.headers['content-length']).toBeUndefined();
} finally {
server.close();
}
});
});
+28
View File
@@ -0,0 +1,28 @@
// CARD-14 (#113): one graph for the Deno and Bun cookie suites, so both prove the same thing the
// Node suite (test/cookies.test.ts) does — two cookies on one response arrive as two lines.
import { Route, Get, Module, Transformer, HttpError, cookie, setCookie } from '../../src/index';
export const C1 = setCookie('a', '1');
export const C2 = setCookie('b', '2', { maxAge: 60 });
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/two')
@Transformer(() => ({ headers: { 'set-cookie': [C1, C2], 'x-custom': ['a', 'b'] }, body: '{}' }))
two() {
return null;
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
export class CookieModule {}
+17
View File
@@ -0,0 +1,17 @@
// CARD-15 (#114): one graph for the Deno, Bun and edge ETag checks (T11), so each runtime answers
// the same T1/T5 the Node suite (test/etag.test.ts) does.
import { Route, Get, Module } from '../../src/index';
@Route('/h')
class EtagCtl {
@Get('/json')
json() {
return { n: 1 };
}
}
@Module({ mountpoint: '/', controllers: [EtagCtl] })
export class EtagModule {}
/** A committed file the static checks can serve: `asset.txt` under `test/fixtures/views`. */
export const STATIC_DIR = 'test/fixtures/views';
+25 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { mergeInjectedHeaders } from '../src/http/headers'; import { mergeInjectedHeaders, joinListHeaders, toWebHeaders } from '../src/http/headers';
describe('mergeInjectedHeaders', () => { describe('mergeInjectedHeaders', () => {
it('makes injected keys authoritative regardless of handler casing', () => { it('makes injected keys authoritative regardless of handler casing', () => {
@@ -23,3 +23,27 @@ describe('mergeInjectedHeaders', () => {
expect(out['vary']).toBe('Accept'); expect(out['vary']).toBe('Accept');
}); });
}); });
describe('array header values (D11)', () => {
it('keeps a handler array intact and still merges vary', () => {
const cookies = ['a=1', 'b=2'];
const out = mergeInjectedHeaders({ 'set-cookie': cookies, Vary: ['Accept', 'Accept-Language'] }, { vary: 'Origin' });
expect(out['set-cookie']).toEqual(['a=1', 'b=2']);
expect(out['vary']).toBe('Accept, Accept-Language, Origin');
});
it('joinListHeaders joins every array but set-cookie, and returns the input when there is none', () => {
const plain = { a: '1' };
expect(joinListHeaders(plain)).toBe(plain);
expect(joinListHeaders({ 'Set-Cookie': ['a=1', 'b=2'], 'x-list': ['a', 'b'] })).toEqual({
'Set-Cookie': ['a=1', 'b=2'],
'x-list': 'a, b',
});
});
it('toWebHeaders appends one set-cookie per element', () => {
const h = toWebHeaders({ 'set-cookie': ['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2'], 'x-list': ['a', 'b'] });
expect(h.getSetCookie()).toEqual(['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2']);
expect(h.get('x-list')).toBe('a, b');
});
});
+31 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; import { createApp, Step, Route, Get, Module, Transformer, needs } from '../../src/index';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
@@ -281,3 +281,33 @@ describe('mesh skeleton integration', () => {
tServer.close(); tServer.close();
}); });
}); });
describe('mesh: Set-Cookie arrays (CARD-14, T10)', () => {
it('a remote route that returns two cookies reaches the teacup client as two lines', async () => {
@Route('/jar')
class JarCtl {
@Get('/two', { export: true })
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] }, body: '{}' }))
two() {
return null;
}
}
@Module({ mountpoint: '/api', controllers: [JarCtl] })
class JarTeapotModule {}
const teapot = createApp({ modules: [JarTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({ modules: [PlainTeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } });
const cServer = await teacup.listen(0);
try {
const res = await fetch(`http://127.0.0.1:${(cServer.address() as any).port}/api/jar/two`);
expect(res.status).toBe(200);
expect(res.headers.getSetCookie()).toEqual(['a=1; Path=/', 'b=2; Path=/']);
} finally {
tServer.close();
cServer.close();
}
});
});
+1 -1
View File
@@ -172,5 +172,5 @@ it('a root created after the first request starts serving without a restart', as
expect(await resolve('/a.txt')).toBeUndefined(); expect(await resolve('/a.txt')).toBeUndefined();
mkdirSync(late); mkdirSync(late);
writeFileSync(join(late, 'a.txt'), 'late'); writeFileSync(join(late, 'a.txt'), 'late');
expect((await resolve('/a.txt'))?.body.toString()).toBe('late'); expect((await (await resolve('/a.txt'))?.read())?.toString()).toBe('late');
}); });