From 14fcf4ec6bb09a9939f10add2db17ec181d28968 Mon Sep 17 00:00:00 2001 From: Matt Johnston Date: Wed, 25 Nov 2026 07:10:17 -0400 Subject: [PATCH 1/4] fix: give each buffered body read its own copy of the bytes bufferRequest handed every arrayBuffer() caller the same cached ArrayBuffer, and bytes() a view over it, so a middleware that wrote into its read changed the body every later layer saw, and one that transferred it left the handler reading an empty body. Each read now goes through a fresh Response over the cached bytes, whose constructor copies them. --- src/core/runtime.test.ts | 37 +++++++++++++++++++++++++++++++++++++ src/core/runtime.ts | 29 ++++++++++++++++------------- 2 files changed, 53 insertions(+), 13 deletions(-) diff --git a/src/core/runtime.test.ts b/src/core/runtime.test.ts index 6060cf7..55dc549 100644 --- a/src/core/runtime.test.ts +++ b/src/core/runtime.test.ts @@ -114,4 +114,41 @@ describe('bufferRequest (host entry points)', () => { const res = await app(post()) expect(await res.json()).toEqual({ peek: '{"a":1}', handler: '{"a":1}' }) }) + + it('gives each reader its own bytes: writing into one read leaves later reads intact', async () => { + // e.g. zeroing a secret in place after verifying a signature over it + const scrub = defineMiddleware<'scrub', void, Record, true>({ + key: 'scrub', + run: () => async (req) => { + new Uint8Array(await req.arrayBuffer()).fill(0) + return { scrub: true } + }, + }) + + const app = pipeline( + [scrub()], + async (req) => new Response(await req.text()), + ) + const res = await app(post()) + expect(await res.text()).toBe('{"a":1}') + }) + + it('gives each reader its own buffer: detaching one read leaves later reads intact', async () => { + // e.g. transferring the bytes to a worker + const hand = defineMiddleware<'hand', void, Record, true>({ + key: 'hand', + run: () => async (req) => { + const buf = await req.arrayBuffer() + structuredClone(buf, { transfer: [buf] }) + return { hand: true } + }, + }) + + const app = pipeline( + [hand()], + async (req) => new Response(await req.text()), + ) + const res = await app(post()) + expect(await res.text()).toBe('{"a":1}') + }) }) diff --git a/src/core/runtime.ts b/src/core/runtime.ts index 576125d..0eaa9ae 100644 --- a/src/core/runtime.ts +++ b/src/core/runtime.ts @@ -209,7 +209,8 @@ const BUFFERED_METHODS = new Set([ * * - `arrayBuffer` / `bytes` / `blob` / `text` / `json` / **`formData`** all read * from the one cached read (`formData` is parsed from the cached bytes using - * the request's `content-type`). + * the request's `content-type`). Each call returns its own copy, so a reader + * that writes into or detaches its bytes leaves every later read intact. * - **`clone()`** returns another handle over the same cache — reading either * yields the same body; `headers` / `url` / `method` / `signal` / … forward to * the real request, and `proxy instanceof Request` stays true. @@ -240,19 +241,21 @@ const BUFFERED_METHODS = new Set([ */ export function bufferRequest(req: Request): Request { let buffer: Promise | undefined - const arrayBuffer = (): Promise => (buffer ??= req.arrayBuffer()) - const text = async (): Promise => - new TextDecoder().decode(await arrayBuffer()) + // Every read goes through a fresh `Response` over the cached bytes. Its + // constructor copies them, so no reader can write into or detach the cache, + // and with the request's headers each form decodes as the native `Request` + // would (form parsing, the UTF-8 BOM). + const body = async (): Promise => + new Response(await (buffer ??= req.arrayBuffer()), { + headers: req.headers, + }) const cached: Record Promise> = { - arrayBuffer, - text, - json: async () => JSON.parse(await text()) as unknown, - bytes: async () => new Uint8Array(await arrayBuffer()), - blob: async () => new Blob([await arrayBuffer()]), - // Parse the cached bytes with the request's content-type (multipart / - // urlencoded), so a form body survives an upstream read. - formData: async () => - new Response(await arrayBuffer(), { headers: req.headers }).formData(), + arrayBuffer: async () => (await body()).arrayBuffer(), + bytes: async () => new Uint8Array(await (await body()).arrayBuffer()), + blob: async () => new Blob([await (await body()).arrayBuffer()]), + text: async () => (await body()).text(), + json: async () => (await body()).json(), + formData: async () => (await body()).formData(), } const handler: ProxyHandler = { get(target, prop) { From 729d77e217d0e0bdc34009ca1480f455b4100028 Mon Sep 17 00:00:00 2001 From: Matt Johnston Date: Wed, 25 Nov 2026 07:10:26 -0400 Subject: [PATCH 2/4] fix: carry the content-type on buffered blob() reads The buffered request built its blob from the raw bytes, so blob().type was always empty where a native Request takes it from the Content-Type, and forwarding `await req.blob()` dropped it. blob() now reads through the same Response as the other forms, which applies the request's headers. --- src/core/runtime.test.ts | 14 ++++++++++++++ src/core/runtime.ts | 11 ++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/core/runtime.test.ts b/src/core/runtime.test.ts index 55dc549..a92a077 100644 --- a/src/core/runtime.test.ts +++ b/src/core/runtime.test.ts @@ -151,4 +151,18 @@ describe('bufferRequest (host entry points)', () => { const res = await app(post()) expect(await res.text()).toBe('{"a":1}') }) + + it('blob() carries the content-type, as a native Request does', async () => { + const init = { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{"a":1}', + } + const native = await new Request('http://localhost/', init).blob() + const buffered = await bufferRequest( + new Request('http://localhost/', init), + ).blob() + expect(native.type).toBe('application/json') + expect(buffered.type).toBe(native.type) + }) }) diff --git a/src/core/runtime.ts b/src/core/runtime.ts index 0eaa9ae..bb259f2 100644 --- a/src/core/runtime.ts +++ b/src/core/runtime.ts @@ -208,9 +208,10 @@ const BUFFERED_METHODS = new Set([ * any form: * * - `arrayBuffer` / `bytes` / `blob` / `text` / `json` / **`formData`** all read - * from the one cached read (`formData` is parsed from the cached bytes using - * the request's `content-type`). Each call returns its own copy, so a reader - * that writes into or detaches its bytes leaves every later read intact. + * from the one cached read and return what the native `Request` would (the + * request's `content-type` gives the blob's type and parses a form). Each call + * returns its own copy, so a reader that writes into or detaches its bytes + * leaves every later read intact. * - **`clone()`** returns another handle over the same cache — reading either * yields the same body; `headers` / `url` / `method` / `signal` / … forward to * the real request, and `proxy instanceof Request` stays true. @@ -244,7 +245,7 @@ export function bufferRequest(req: Request): Request { // Every read goes through a fresh `Response` over the cached bytes. Its // constructor copies them, so no reader can write into or detach the cache, // and with the request's headers each form decodes as the native `Request` - // would (form parsing, the UTF-8 BOM). + // would (the blob's type, form parsing, the UTF-8 BOM). const body = async (): Promise => new Response(await (buffer ??= req.arrayBuffer()), { headers: req.headers, @@ -252,7 +253,7 @@ export function bufferRequest(req: Request): Request { const cached: Record Promise> = { arrayBuffer: async () => (await body()).arrayBuffer(), bytes: async () => new Uint8Array(await (await body()).arrayBuffer()), - blob: async () => new Blob([await (await body()).arrayBuffer()]), + blob: async () => (await body()).blob(), text: async () => (await body()).text(), json: async () => (await body()).json(), formData: async () => (await body()).formData(), From d42c9993be6f01a77ad343a3785fda5c2bb6dbab Mon Sep 17 00:00:00 2001 From: Matt Johnston Date: Wed, 25 Nov 2026 07:10:34 -0400 Subject: [PATCH 3/4] fix: run a generator middleware's finally when catch yields a Response When a downstream layer threw and the middleware's catch recovered with `yield new Response(...)`, the runtime returned that response without closing the generator, so its finally block never ran. It now calls gen.return() when gen.throw() leaves the generator suspended, as the other paths that receive a yielded Response already do. --- src/core/define-middleware.test.ts | 31 ++++++++++++++++++++++++++++++ src/core/define-middleware.ts | 1 + 2 files changed, 32 insertions(+) diff --git a/src/core/define-middleware.test.ts b/src/core/define-middleware.test.ts index 44c1736..6b3383e 100644 --- a/src/core/define-middleware.test.ts +++ b/src/core/define-middleware.test.ts @@ -444,6 +444,37 @@ describe('defineMiddleware — generator (response seam)', () => { expect(await res.text()).toBe('handled') }) + it('runs `finally` when a try/catch recovers a downstream throw by yielding a Response', async () => { + // Yielding a Response short-circuits like returning one, so the generator + // must still be closed and its cleanup run. + const order: string[] = [] + const withYieldCatch = defineMiddleware< + 'guard', + void, + Record, + { ok: true } + >({ + key: 'guard', + run: () => + async function* () { + try { + return yield { guard: { ok: true } } + } catch { + yield new Response('handled', { status: 500 }) + } finally { + order.push('release') + } + }, + }) + + const handler = withYieldCatch(async () => { + throw new Error('kaboom') + }) + const res = await handler(new Request('http://localhost/')) + expect(res.status).toBe(500) + expect(order).toEqual(['release']) + }) + it('composes a generator middleware under a plain one, accumulating ctx', async () => { const handler = withFeatureFlag( { name: 'beta', evaluate: () => true }, diff --git a/src/core/define-middleware.ts b/src/core/define-middleware.ts index 8e6d295..6872a3c 100644 --- a/src/core/define-middleware.ts +++ b/src/core/define-middleware.ts @@ -211,6 +211,7 @@ export function defineMiddleware< // Let a `try/catch` around the middleware's `yield` observe the failure. // If it doesn't handle it, `gen.throw` rethrows and we propagate. const recovered = await gen.throw(err) + if (!recovered.done) await gen.return(undefined) // it yielded from `catch`; run `finally` if (recovered.value instanceof Response) return recovered.value throw err } From 31f98eb19168c4c5f0d24ebc64f254b47c1dcda4 Mon Sep 17 00:00:00 2001 From: Martijn van Dijk Date: Tue, 1 Dec 2026 23:19:58 +0100 Subject: [PATCH 4/4] feat: export bufferRequestInPlace for frameworks that keep the same Request bufferRequest returns a proxy, which only helps when the caller can hand it on. TanStack Start, SvelteKit and React Router give the route the same Request their middleware saw. bufferRequestInPlace redefines the body readers on the request itself, sharing the readers bufferRequest uses. Closes #63 Co-Authored-By: Claude Opus 5.5 --- src/core/index.ts | 1 + src/core/runtime.test.ts | 93 +++++++++++++++++++++++++++ src/core/runtime.ts | 66 ++++++++++++++++++- src/exports.test.ts | 2 + src/index.ts | 1 + test/runtimes/workers/runtime.test.ts | 8 +++ test/runtimes/workers/worker.ts | 39 ++++++++--- 7 files changed, 198 insertions(+), 12 deletions(-) diff --git a/src/core/index.ts b/src/core/index.ts index 17d055a..2715c0d 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -27,6 +27,7 @@ export { pipeline } from './pipeline.js' export type { ValidateEntries } from './pipeline.js' export { bufferRequest, + bufferRequestInPlace, getEnv, isContext, runtimeName, diff --git a/src/core/runtime.test.ts b/src/core/runtime.test.ts index a92a077..c0a6cdb 100644 --- a/src/core/runtime.test.ts +++ b/src/core/runtime.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import { bufferRequest, + bufferRequestInPlace, getEnv, isContext, runtimeName, @@ -166,3 +167,95 @@ describe('bufferRequest (host entry points)', () => { expect(buffered.type).toBe(native.type) }) }) + +describe('bufferRequestInPlace (frameworks that keep the same Request)', () => { + const post = (init: RequestInit = {}) => + new Request('http://localhost/', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{"a":1}', + ...init, + }) + + it('returns the same request, readable more than once in every form', async () => { + const req = post() + expect(bufferRequestInPlace(req)).toBe(req) + + expect(await req.text()).toBe('{"a":1}') + expect(await req.json()).toEqual({ a: 1 }) + expect(new TextDecoder().decode(await req.arrayBuffer())).toBe('{"a":1}') + // `bytes` is newer than the TypeScript floor's lib, hence the cast. + const bytes = await ( + req as unknown as { bytes(): Promise } + ).bytes() + expect(new TextDecoder().decode(bytes)).toBe('{"a":1}') + const blob = await req.blob() + expect(blob.type).toBe('application/json') + expect(await blob.text()).toBe('{"a":1}') + expect(req instanceof Request).toBe(true) + expect(Object.keys(req)).toEqual([]) + }) + + it('lets a stack and the route read the body of the same object', async () => { + // A framework bridge: the stack sees the request, and the route then reads + // the very same object, with no way to hand it a replacement. + const req = post() + const peek = defineMiddleware<'peek', void, Record, string>({ + key: 'peek', + run: () => async (r) => ({ peek: await r.text() }), + }) + const stack = pipeline([peek()], async (_r, ctx) => new Response(ctx.peek)) + + bufferRequestInPlace(req) + expect(await (await stack(req)).text()).toBe('{"a":1}') + expect(await req.json()).toEqual({ a: 1 }) + }) + + it('without it, the route finds the body already read', async () => { + const req = post() + await req.text() + await expect(req.json()).rejects.toThrow() + }) + + it('parses a form body from the cache', async () => { + const req = new Request('http://localhost/', { + method: 'POST', + body: new URLSearchParams({ a: '1' }), + }) + bufferRequestInPlace(req) + await req.text() + expect((await req.formData()).get('a')).toBe('1') + }) + + it('gives each reader its own bytes', async () => { + const req = bufferRequestInPlace(post()) + new Uint8Array(await req.arrayBuffer()).fill(0) + expect(await req.text()).toBe('{"a":1}') + }) + + it('clone() is another handle over the same cache', async () => { + const req = bufferRequestInPlace(post()) + expect(await req.text()).toBe('{"a":1}') + const copy = req.clone() + expect(copy instanceof Request).toBe(true) + expect(await copy.text()).toBe('{"a":1}') + expect(copy.headers.get('content-type')).toBe('application/json') + }) + + it('is a no-op without a body, after the body was used, and when repeated', async () => { + const get = new Request('http://localhost/') + expect(bufferRequestInPlace(get)).toBe(get) + expect(Object.getOwnPropertyNames(get)).toEqual([]) + + const used = post() + await used.text() + bufferRequestInPlace(used) + expect(Object.getOwnPropertyNames(used)).toEqual([]) + + const twice = post() + bufferRequestInPlace(twice) + const text = twice.text + bufferRequestInPlace(twice) + expect(twice.text).toBe(text) + }) +}) diff --git a/src/core/runtime.ts b/src/core/runtime.ts index bb259f2..52771f7 100644 --- a/src/core/runtime.ts +++ b/src/core/runtime.ts @@ -238,19 +238,34 @@ const BUFFERED_METHODS = new Set([ * const request = isContext(arg) || !req.body ? req : bufferRequest(req) * ``` * + * Use this when the caller can hand the returned proxy on (the entry call, or a + * framework that lets middleware replace the request, such as Hono's + * `c.req.raw` or H3's `event.req`). When the framework hands the route the same + * `Request` object its middleware saw, use {@link bufferRequestInPlace}. + * * @category Composition */ export function bufferRequest(req: Request): Request { + return bufferedProxy(req, bufferedReaders(req, req.arrayBuffer.bind(req))) +} + +type BufferedReaders = Record Promise> + +/** The body readers {@link bufferRequest} and {@link bufferRequestInPlace} share. */ +function bufferedReaders( + req: Request, + readOnce: () => Promise, +): BufferedReaders { let buffer: Promise | undefined // Every read goes through a fresh `Response` over the cached bytes. Its // constructor copies them, so no reader can write into or detach the cache, // and with the request's headers each form decodes as the native `Request` // would (the blob's type, form parsing, the UTF-8 BOM). const body = async (): Promise => - new Response(await (buffer ??= req.arrayBuffer()), { + new Response(await (buffer ??= readOnce()), { headers: req.headers, }) - const cached: Record Promise> = { + return { arrayBuffer: async () => (await body()).arrayBuffer(), bytes: async () => new Uint8Array(await (await body()).arrayBuffer()), blob: async () => (await body()).blob(), @@ -258,6 +273,10 @@ export function bufferRequest(req: Request): Request { json: async () => (await body()).json(), formData: async () => (await body()).formData(), } +} + +/** A proxy over `req` whose body readers and `clone()` share `cached`. */ +function bufferedProxy(req: Request, cached: BufferedReaders): Request { const handler: ProxyHandler = { get(target, prop) { if (typeof prop === 'string' && BUFFERED_METHODS.has(prop)) { @@ -274,3 +293,46 @@ export function bufferRequest(req: Request): Request { } return new Proxy(req, handler) } + +/** Marks a request whose readers {@link bufferRequestInPlace} already replaced. */ +const BUFFERED_IN_PLACE = Symbol.for('@supabase/middleware:buffered-in-place') + +/** + * Make a `Request` body readable more than once by redefining its body readers + * on the request object itself, and return the same request. + * + * {@link bufferRequest} returns a new proxy, which only helps when the caller + * can hand that proxy on. Some frameworks hand the route the same `Request` + * object their middleware saw, with no supported way to swap it: TanStack Start + * server routes and server functions, SvelteKit's `event.request`, and React + * Router's `request` in loaders and actions. A bridge for those calls this + * before running the stack, so an entry that reads the body (such as a webhook + * signature check) and the route's own `request.json()` both see it. + * + * The readers are the ones {@link bufferRequest} uses: the first read drains the + * stream into a cache, and each `arrayBuffer` / `bytes` / `blob` / `text` / + * `json` / `formData` call returns its own copy, decoded as the native + * `Request` would. `clone()` returns a {@link bufferRequest} proxy over the same + * cache. The same limit applies: reading the raw `req.body` stream bypasses the + * cache. + * + * A no-op when the request has no body, its body was already used, or it was + * already buffered in place. + * + * @category Composition + */ +export function bufferRequestInPlace(req: Request): Request { + if (!req.body || req.bodyUsed || BUFFERED_IN_PLACE in req) return req + // Bind the native reader before it is shadowed below. + const cached = bufferedReaders(req, req.arrayBuffer.bind(req)) + const define = (name: PropertyKey, value: unknown) => + Object.defineProperty(req, name, { + value, + configurable: true, + writable: true, + }) + for (const [name, read] of Object.entries(cached)) define(name, read) + define('clone', () => bufferedProxy(req, cached)) + define(BUFFERED_IN_PLACE, true) + return req +} diff --git a/src/exports.test.ts b/src/exports.test.ts index 2d187bb..6fe6ed4 100644 --- a/src/exports.test.ts +++ b/src/exports.test.ts @@ -14,6 +14,7 @@ describe('public API surface', () => { it('package root', () => { expect(Object.keys(root).sort()).toEqual([ 'bufferRequest', + 'bufferRequestInPlace', 'defineComposite', 'defineMiddleware', 'getEnv', @@ -27,6 +28,7 @@ describe('public API surface', () => { it('core subpath', () => { expect(Object.keys(core).sort()).toEqual([ 'bufferRequest', + 'bufferRequestInPlace', 'defineComposite', 'defineMiddleware', 'getEnv', diff --git a/src/index.ts b/src/index.ts index 4655eb7..06a60e5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,7 @@ export { pipeline } from './core/pipeline.js' export type { ValidateEntries } from './core/pipeline.js' export { bufferRequest, + bufferRequestInPlace, getEnv, isContext, runtimeName, diff --git a/test/runtimes/workers/runtime.test.ts b/test/runtimes/workers/runtime.test.ts index 4f7ab4c..80bdb78 100644 --- a/test/runtimes/workers/runtime.test.ts +++ b/test/runtimes/workers/runtime.test.ts @@ -12,3 +12,11 @@ it('the built engine serves a pipeline inside workerd', async () => { isCtx: true, }) }) + +it('bufferRequestInPlace makes a workerd Request body readable twice', async () => { + const res = await SELF.fetch('http://example.com/in-place', { + method: 'POST', + body: '{"a":1}', + }) + expect(await res.json()).toEqual({ peeked: '{"a":1}', route: { a: 1 } }) +}) diff --git a/test/runtimes/workers/worker.ts b/test/runtimes/workers/worker.ts index 7c76ff5..d55fd2e 100644 --- a/test/runtimes/workers/worker.ts +++ b/test/runtimes/workers/worker.ts @@ -1,6 +1,7 @@ // Runs the built dist inside workerd. Bindings arrive per request as the second // `fetch` argument; there is no ambient `process.env` without `nodejs_compat`. import { + bufferRequestInPlace, defineMiddleware, getEnv, isContext, @@ -23,15 +24,33 @@ const probe = defineMiddleware< }), }) +const stack = pipeline([probe()], async (_req, ctx) => + Response.json({ + runtime: runtimeName, + atModuleLoad, + env: getEnv('WM_RUNTIME_TEST') ?? null, + upstreamKeys: ctx.probe.upstreamKeys, + handlerKeys: Object.keys(ctx), + isCtx: ctx.probe.isCtx, + }), +) + +const peek = defineMiddleware<'peek', void, Record, string>({ + key: 'peek', + run: () => async (req) => ({ peek: await req.text() }), +}) +const peekStack = pipeline( + [peek()], + async (_req, ctx) => new Response(ctx.peek), +) + export default { - fetch: pipeline([probe()], async (_req, ctx) => - Response.json({ - runtime: runtimeName, - atModuleLoad, - env: getEnv('WM_RUNTIME_TEST') ?? null, - upstreamKeys: ctx.probe.upstreamKeys, - handlerKeys: Object.keys(ctx), - isCtx: ctx.probe.isCtx, - }), - ), + async fetch(req: Request, env: unknown) { + if (new URL(req.url).pathname !== '/in-place') return stack(req, env) + // A bridge that keeps the same Request: the stack reads the body, then the + // route reads it again from the same object. + bufferRequestInPlace(req) + const peeked = await (await peekStack(req, env)).text() + return Response.json({ peeked, route: await req.json() }) + }, }