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 } 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 6060cf7..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, @@ -114,4 +115,147 @@ 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}') + }) + + 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) + }) +}) + +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 576125d..52771f7 100644 --- a/src/core/runtime.ts +++ b/src/core/runtime.ts @@ -208,8 +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`). + * 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. @@ -236,24 +238,45 @@ 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 - const arrayBuffer = (): Promise => (buffer ??= req.arrayBuffer()) - const text = async (): Promise => - new TextDecoder().decode(await arrayBuffer()) - 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(), + // 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 ??= readOnce()), { + headers: req.headers, + }) + return { + arrayBuffer: async () => (await body()).arrayBuffer(), + bytes: async () => new Uint8Array(await (await body()).arrayBuffer()), + blob: async () => (await body()).blob(), + text: async () => (await body()).text(), + 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)) { @@ -270,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() }) + }, }