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:08:24 -05:00
1 parent 037e695a31
commit 7f9a0eef0f
24 files changed
+781 -34

No files matched your search

+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,
@@ -286,7 +286,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';
@@ -204,7 +204,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(
@@ -274,12 +274,14 @@ export function buildFetch(routes: RouteTable, 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,
),
),
});
}
@@ -323,7 +325,7 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
if ('preflight' in result) {
return new Response(null, {
status: 204,
headers: mergeInjectedHeaders(result.preflight, injected),
headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
});
}