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 27s
CI / runtimes (deno) (pull_request) Successful in 20s
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[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-23 01:00:43 -05:00
1 parent 1da6bf2f99
commit 88945b0b1f
24 files changed
+781 -34

No files matched your search

+20
View File
@@ -10,6 +10,15 @@ npm treats versions as semver and semver forbids leading zeros.
### 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
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
@@ -112,6 +121,17 @@ npm treats versions as semver and semver forbids leading zeros.
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
reports `draining` there.
- **`@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
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
+4
View File
@@ -244,6 +244,10 @@ The handler signature declares exactly what it wants — in any order, nothing m
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(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)` |
| `@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.
+11 -1
View File
@@ -884,7 +884,17 @@ function assertNeedsSatisfiable(
...providerNodes.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 need of plan.needs) {
+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. */
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. */
+3 -3
View File
@@ -85,10 +85,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. */
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';
headers: Record<string, string>;
headers: Record<string, string | string[]>;
stream: AsyncIterable<unknown>;
encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */
@@ -126,7 +126,7 @@ function errorOutcome(
req: NeutralRequest,
injected: Record<string, string>,
opts: HttpOptions | undefined,
headers: Record<string, string> = {},
headers: Record<string, string | string[]> = {},
): HandleResult {
const rendered = renderError(error, req, opts?.onError, opts?.logger);
return {
+46 -1
View File
@@ -19,7 +19,10 @@ export function mergeInjectedHeaders(
const lowerKey = key.toLowerCase();
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;
}
@@ -40,3 +43,45 @@ export function mergeInjectedHeaders(
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
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 { pipeStream } from './stream';
import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers';
import { mergeInjectedHeaders, joinListHeaders } from './headers';
import {
handle,
correlateRequest,
@@ -285,7 +285,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
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);
};
}
+11 -9
View File
@@ -10,7 +10,7 @@ import {
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import { mergeInjectedHeaders, toWebHeaders } from './headers';
import { peerOf, trustedProxyClient } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals';
@@ -203,7 +203,7 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
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') {
const body = asReadableStream(
@@ -273,12 +273,14 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503,
headers: mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
headers: toWebHeaders(
mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
),
),
});
}
@@ -320,7 +322,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
if ('preflight' in result) {
return new Response(null, {
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';
// 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';
// Cookies
export { setCookie, parseCookies } from './cookies';
export type { CookieOptions } from './cookies';
// Observability
export { createDefaultLogger, logRequests, withConsoleFallback } 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. */
export type Ctor = new (...args: any[]) => any;
/** 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. */
export interface HtmlMeta {
+11 -4
View File
@@ -26,7 +26,7 @@ export interface OpenApiDoc {
type Parameter = {
name: string;
in: 'path' | 'query' | 'header';
in: 'path' | 'query' | 'header' | 'cookie';
required: boolean;
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[] {
const params: Parameter[] = [];
for (const arg of args) {
if (arg.source !== 'query' && arg.source !== 'headers') continue;
const location = arg.source === 'query' ? 'query' : 'header';
const location = ARG_LOCATION[arg.source];
if (!location) continue;
const names = arg.keys ?? (arg.key ? [arg.key] : []);
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 { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
import { ValidationError } from './signals';
import { parseCookies } from './cookies';
/** Parsed URL query string as flat key/value pairs. */
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. */
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. */
export interface ArgSpec {
index: number;
@@ -71,6 +72,14 @@ export const body: ArgDecorator = envelope('body');
export const headers: ArgDecorator = envelope('headers');
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
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. */
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 {
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 === '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
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];
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. */
export interface ResponseShape {
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;
}
/** 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;
message: string;
body?: unknown;
headers?: Record<string, string>;
headers?: Record<string, string | string[]>;
}
/**
@@ -35,7 +35,7 @@ export class HttpError extends Error {
readonly status: number,
message?: string,
readonly body?: unknown,
readonly headers?: Record<string, string>,
readonly headers?: Record<string, string | string[]>,
) {
super(message ?? `HTTP ${status}`);
this.name = new.target.name;
+2 -1
View File
@@ -6,7 +6,8 @@ import type { Logger } from './logger';
/** A ready-to-send HTTP response. */
export interface ErrorResponse {
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;
}
+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 });
}
});
+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 });
}
});
+13 -1
View File
@@ -66,6 +66,18 @@ async function main() {
assert.equal(httpRes.status, 200);
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' });
// 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.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
@@ -191,7 +203,7 @@ async function main() {
assert.equal(ready.headers.get('cache-control'), 'no-store');
console.log(
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
'edge (workerd via miniflare): HTTP 200 + cookies + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
);
} finally {
await mf.dispose();
+18 -1
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test.
// 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).
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';
@Route('/rt')
@@ -11,6 +11,23 @@ class Rt {
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
// 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.
+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 {}
+25 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { mergeInjectedHeaders } from '../src/http/headers';
import { mergeInjectedHeaders, joinListHeaders, toWebHeaders } from '../src/http/headers';
describe('mergeInjectedHeaders', () => {
it('makes injected keys authoritative regardless of handler casing', () => {
@@ -23,3 +23,27 @@ describe('mergeInjectedHeaders', () => {
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 { createApp, Step, Route, Get, Module, needs } from '../../src/index';
import { createApp, Step, Route, Get, Module, Transformer, needs } from '../../src/index';
const SECRET = 's3cr3t';
@@ -281,3 +281,33 @@ describe('mesh skeleton integration', () => {
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();
}
});
});