Skip to content
Myr

index.ts

This file

Path

src/helper/proxy/index.ts

202 lines · 6.1 KiB · TypeScript

Last changed by

docs: fix typos in code comments and link third-party middleware section (#5343)Aidanbefore adoptione7b38ee

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–118why, one step back
1/**
2 * @module3 * Proxy Helper for Hono.4 */56import { HTTPException } from '../../http-exception'7import type { RequestHeader } from '../../utils/headers'89// https://datatracker.ietf.org/doc/html/rfc2616#section-13.5.110const hopByHopHeaders = [11 'connection',12 'keep-alive',13 'proxy-authenticate',14 'proxy-authorization',15 'te',16 'trailer',17 'transfer-encoding',18 'upgrade',19]2021// https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.222const ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/2324interface ProxyRequestInit extends Omit<RequestInit, 'headers'> {25 raw?: Request26 headers?:27 | HeadersInit28 | [string, string][]29 | Record<RequestHeader, string | undefined>30 | Record<string, string | undefined>31 customFetch?: (request: Request) => Promise<Response>32 /**33 * Enable strict RFC 9110 compliance for Connection header processing.34 *35 * - `false` (default): Ignores Connection header to prevent potential36 * Hop-by-Hop Header Injection attacks. Recommended for untrusted clients.37 * - `true`: Processes Connection header per RFC 9110 and removes listed headers.38 * Only use in trusted environments.39 *40 * @default false41 * @see https://datatracker.ietf.org/doc/html/rfc9110#section-7.6.142 */43 strictConnectionProcessing?: boolean44}4546interface ProxyFetch {47 (input: string | URL | Request, init?: ProxyRequestInit): Promise<Response>48}4950const buildRequestInitFromRequest = (51 request: Request | undefined,52 strictConnectionProcessing: boolean53): RequestInit & { duplex?: 'half' } => {54 if (!request) {55 return {}56 }5758 const headers = new Headers(request.headers)5960 if (strictConnectionProcessing) {61 // https://datatracker.ietf.org/doc/html/rfc9110#section-7.6.162 // Parse Connection header and remove listed headers (MUST per RFC 9110)63 const connectionValue = headers.get('connection')64 if (connectionValue) {65 const headerNames = connectionValue.split(',').map((h) => h.trim())66 // Validate header names per RFC 9110 Section 5.6.2 (token syntax)67 const invalidHeaders = headerNames.filter((h) => !ALLOWED_TOKEN_PATTERN.test(h))6869 if (invalidHeaders.length > 0) {70 throw new HTTPException(400, {71 message: `Invalid Connection header value: ${invalidHeaders.join(', ')}`,72 })73 }74 headerNames.forEach((headerName) => {75 headers.delete(headerName)76 })77 }78 }7980 hopByHopHeaders.forEach((header) => {81 headers.delete(header)82 })8384 return {85 method: request.method,86 body: request.body,87 duplex: request.body ? 'half' : undefined,88 headers,89 signal: request.signal,90 }91}9293const preprocessRequestInit = (requestInit: RequestInit): RequestInit => {94 if (95 !requestInit.headers ||96 Array.isArray(requestInit.headers) ||97 requestInit.headers instanceof Headers98 ) {99 return requestInit100 }101102 const headers = new Headers()103 for (const [key, value] of Object.entries(requestInit.headers)) {104 if (value == null) {105 // delete header if value is null or undefined106 headers.delete(key)107 } else {108 headers.set(key, value)109 }110 }111 requestInit.headers = headers112 return requestInit113}114115/**116 * Fetch API wrapper for proxy.117 * The parameters and return value are the same as for `fetch` (except for the proxy-specific options).118 *

docs: fix typos in code comments and link third-party middleware section (#5343)Aidanbefore adoptione7b38ee

line 119why, one step back
119 * The "Accept-Encoding" header is replaced with an encoding that the current runtime can handle.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 120–175why, one step back
120 * Unnecessary response headers are deleted and a Response object is returned that can be returned
121 * as is as a response from the handler.122 *123 * @example124 * ```ts125 * app.get('/proxy/:path', (c) => {126 * return proxy(`http://${originServer}/${c.req.param('path')}`, {127 * headers: {128 * ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary.129 * 'X-Forwarded-For': '127.0.0.1',130 * 'X-Forwarded-Host': c.req.header('host'),131 * Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')132 * },133 * }).then((res) => {134 * res.headers.delete('Set-Cookie')135 * return res136 * })137 * })138 *139 * app.all('/proxy/:path', (c) => {140 * return proxy(`http://${originServer}/${c.req.param('path')}`, {141 * ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary.142 * headers: {143 * ...c.req.header(),144 * 'X-Forwarded-For': '127.0.0.1',145 * 'X-Forwarded-Host': c.req.header('host'),146 * Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')147 * },148 * })149 * })150 *151 * // Strict RFC compliance mode (use only in trusted environments)152 * app.get('/internal-proxy/:path', (c) => {153 * return proxy(`http://${internalServer}/${c.req.param('path')}`, {154 * ...c.req,155 * strictConnectionProcessing: true,156 * })157 * })158 * ```159 */160export const proxy: ProxyFetch = async (input, proxyInit) => {161 const {162 raw,163 customFetch,164 strictConnectionProcessing = false,165 ...requestInit166 } = proxyInit instanceof Request ? { raw: proxyInit } : (proxyInit ?? {})167168 const req = new Request(input, {169 ...buildRequestInitFromRequest(raw, strictConnectionProcessing),170 ...preprocessRequestInit(requestInit as RequestInit),171 })172 req.headers.delete('accept-encoding')173174 const res = await (customFetch || fetch)(req)175 const resHeaders = new Headers(res.headers)

Merge commit from forkYusuke Wadabefore adoption720b566

lines 176–187why, one step back
176
177 // https://datatracker.ietf.org/doc/html/rfc9110#section-7.6.1178 // Remove headers listed in the response's own Connection header (MUST per RFC 9110)179 const connectionValue = resHeaders.get('connection')180 if (connectionValue) {181 connectionValue182 .split(',')183 .map((h) => h.trim())184 .filter((h) => ALLOWED_TOKEN_PATTERN.test(h))185 .forEach((h) => resHeaders.delete(h))186 }187

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 188–202why, one step back
188 hopByHopHeaders.forEach((header) => {
189 resHeaders.delete(header)190 })191 if (resHeaders.has('content-encoding')) {192 resHeaders.delete('content-encoding')193 // Content-Length is the size of the compressed content, not the size of the original content194 resHeaders.delete('content-length')195 }196197 return new Response(res.body, {198 status: res.status,199 statusText: res.statusText,200 headers: resHeaders,201 })202}