Files
core/src/http/headers.ts
T
chrnxandClaude Opus 5.5 82767eabd2
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
feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
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

88 lines
3.8 KiB
TypeScript

import { mergeVary } from '../security';
const hasOwn = Object.prototype.hasOwnProperty;
/**
* Merges a handler's response headers with authoritative `injected` headers
* (security + CORS). Injected keys win case-insensitively; `vary` is merged.
* Extracted from the Node writeHead patch so app.fetch shares the exact logic.
*/
export function mergeInjectedHeaders(
handlerHeaders: Record<string, any> | undefined,
injected: Record<string, string>,
): Record<string, any> {
const merged: Record<string, any> = {};
let handlerVary: string | undefined;
if (handlerHeaders)
for (const key of Object.keys(handlerHeaders)) {
const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') {
// 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;
}
// `injected` is looked up directly instead of through a lowercased Set rebuilt per response.
// Every key it can hold is written as a lowercase literal in `src/security.ts` — both
// `buildSecurityHeaders` and `resolveCors`, which are its only sources — so lowercasing them
// again produced a copy of the keys it already had. Three allocations per response (an array,
// a mapped array, a Set) to answer a question the object answers itself: 146.4 ns against
// 55.9 ns.
//
// `hasOwnProperty` rather than `in`: a handler is free to send a header called `constructor`
// or `toString`, and `in` would find those on Object.prototype and silently drop them.
if (!hasOwn.call(injected, lowerKey)) merged[key] = handlerHeaders[key];
}
Object.assign(merged, injected);
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
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;
}