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>
This commit is contained in:
chrnxandClaude Opus 5.5 committed 2026-10-22 23:55:31 -05:00
1 parent e565b1d4c9
commit 82767eabd2
24 files changed
+781 -34

No files matched your search

+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
@@ -138,7 +150,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_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 + body limits 413/413/200/413 + WS echo:hi + ws limits — 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();
}
});
});