Skip to content
Merged
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
6 changes: 4 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,14 @@ jobs:
steps:
- uses: actions/checkout@v7

- uses: actions/setup-node@v7
with:
node-version: 22

- uses: pnpm/action-setup@v6

- run: pnpm i

- run: pnpm runtime set node 22

- run: pnpm run test:coverage
env:
REDIS_URL: redis://localhost:6379
Expand Down
59 changes: 59 additions & 0 deletions packages/server/src/plugins/request-headers.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RequestHeadersPluginContext } from './request-headers'
import { OpenAPIHandler } from '../../../openapi/src/adapters/fetch/openapi-handler'
import { os } from '../builder'
import { BatchHandlerPlugin } from './batch'
import { RequestHeadersPlugin } from './request-headers'

describe('requestHeadersPlugin', () => {
Expand Down Expand Up @@ -111,4 +112,62 @@ describe('requestHeadersPlugin', () => {
// The existing reqHeaders should be preserved
expect(interceptor.mock.calls[0]![0].context.reqHeaders).toBe(existingHeaders)
})

it('leaves out invalid batch subrequest headers instead of throwing', async () => {
let capturedHeaders: Headers | undefined

const router = os
.$context<RequestHeadersPluginContext>()
.use(({ context, next }) => {
capturedHeaders = context.reqHeaders
return next()
})
.route({
method: 'GET',
path: '/ping',
})
.handler(() => 'pong')

const handler = new OpenAPIHandler(router, {
plugins: [
new RequestHeadersPlugin(),
new BatchHandlerPlugin(),
],
})

const { response } = await handler.handle(new Request('https://example.com/ping', {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-orpc-batch': 'buffered',
},
body: JSON.stringify([
{
url: 'https://example.com/ping',
method: 'GET',
headers: {
'a b': '1',
'': '2',
'x-newline': 'a\nb',
'x-non-latin1': '中',
'x-object': { toString: 1 },
'x-mixed': ['valid', 'a\nb'],
'x-valid': 'value',
},
},
]),
}))

expect(response?.status).toBe(207)
await expect(response?.json()).resolves.toEqual([
expect.objectContaining({ index: 0, status: 200, body: 'pong' }),
])

expect(Object.fromEntries(capturedHeaders!)).toEqual({
'content-type': 'application/json',
'x-mixed': 'valid',
'x-orpc-batch': 'buffered',
'x-valid': 'value',
})
})
})
38 changes: 37 additions & 1 deletion packages/server/src/plugins/request-headers.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,46 @@
import type { StandardHeaders } from '@orpc/standard-server'
import type { StandardHandlerOptions, StandardHandlerPlugin } from '../adapters/standard'
import { toFetchHeaders } from '@orpc/standard-server-fetch'

export interface RequestHeadersPluginContext {
reqHeaders?: Headers
}

function appendValidHeader(headers: Headers, name: string, value: string): void {
try {
headers.append(name, value)
}
catch {}
}

/**
* Not every request passes through an HTTP parser: batch subrequests carry their headers
* in the request body, so a client can send any header name or value.
*/
function toSafeFetchHeaders(standardHeaders: StandardHeaders): Headers {
try {
return toFetchHeaders(standardHeaders)
}
catch {
const headers = new Headers()

for (const name of Object.keys(standardHeaders)) {
const value = standardHeaders[name]

if (Array.isArray(value)) {
for (const item of value) {
appendValidHeader(headers, name, item)
}
}
else if (value !== undefined) {
appendValidHeader(headers, name, value)
}
}

return headers
}
}
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved

/**
* The Request Headers Plugin injects a `reqHeaders` instance into the context,
* allowing access to request headers in oRPC.
Expand All @@ -16,7 +52,7 @@ export class RequestHeadersPlugin<T extends RequestHeadersPluginContext> impleme
options.rootInterceptors ??= []

options.rootInterceptors.push((interceptorOptions) => {
const reqHeaders = interceptorOptions.context.reqHeaders ?? toFetchHeaders(interceptorOptions.request.headers)
const reqHeaders = interceptorOptions.context.reqHeaders ?? toSafeFetchHeaders(interceptorOptions.request.headers)

return interceptorOptions.next({
...interceptorOptions,
Expand Down
Loading