Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/core/define-middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<never, never>,
{ 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 },
Expand Down
1 change: 1 addition & 0 deletions src/core/define-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
1 change: 1 addition & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export { pipeline } from './pipeline.js'
export type { ValidateEntries } from './pipeline.js'
export {
bufferRequest,
bufferRequestInPlace,
getEnv,
isContext,
runtimeName,
Expand Down
144 changes: 144 additions & 0 deletions src/core/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'

import {
bufferRequest,
bufferRequestInPlace,
getEnv,
isContext,
runtimeName,
Expand Down Expand Up @@ -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<never, never>, 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<never, never>, 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<Uint8Array> }
).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<never, never>, 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)
})
})
96 changes: 81 additions & 15 deletions src/core/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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<string, () => Promise<unknown>>

/** The body readers {@link bufferRequest} and {@link bufferRequestInPlace} share. */
function bufferedReaders(
req: Request,
readOnce: () => Promise<ArrayBuffer>,
): BufferedReaders {
let buffer: Promise<ArrayBuffer> | undefined
const arrayBuffer = (): Promise<ArrayBuffer> => (buffer ??= req.arrayBuffer())
const text = async (): Promise<string> =>
new TextDecoder().decode(await arrayBuffer())
const cached: Record<string, () => Promise<unknown>> = {
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<Response> =>
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<Request> = {
get(target, prop) {
if (typeof prop === 'string' && BUFFERED_METHODS.has(prop)) {
Expand All @@ -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
}
2 changes: 2 additions & 0 deletions src/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ describe('public API surface', () => {
it('package root', () => {
expect(Object.keys(root).sort()).toEqual([
'bufferRequest',
'bufferRequestInPlace',
'defineComposite',
'defineMiddleware',
'getEnv',
Expand All @@ -27,6 +28,7 @@ describe('public API surface', () => {
it('core subpath', () => {
expect(Object.keys(core).sort()).toEqual([
'bufferRequest',
'bufferRequestInPlace',
'defineComposite',
'defineMiddleware',
'getEnv',
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export { pipeline } from './core/pipeline.js'
export type { ValidateEntries } from './core/pipeline.js'
export {
bufferRequest,
bufferRequestInPlace,
getEnv,
isContext,
runtimeName,
Expand Down
8 changes: 8 additions & 0 deletions test/runtimes/workers/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } })
})
Loading