Skip to content

Commit d3d7f39

Browse files
pi0claude
andcommitted
feat(web-incoming): implement native followRedirects support
Add redirect following (301/302/303/307/308) directly in the stream pass without external dependencies. Supports `true` (max 5) or numeric limit. 301/302/303 change method to GET; 307/308 preserve method and body. Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent 9e2d155 commit d3d7f39

5 files changed

Lines changed: 348 additions & 48 deletions

File tree

‎AGENTS.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ proxyFetch(addr, request) → http.request to addr → Web Response
6666
- `proxyReq` event is intentionally skipped when request has `expect` header (`100-continue` advisory coverage).
6767
- `selfHandleResponse: true` skips outgoing passes and auto-pipe; callers must finish the response in `proxyRes`.
6868
- `proxyTimeout` aborts upstream request and surfaces timeout errors (tested as `ECONNRESET`).
69+
- `followRedirects: true | number` enables native redirect following (301/302/303/307/308). `true` = max 5 hops, number = custom max.
70+
- On 301/302/303 redirects, method changes to GET and request body is dropped.
71+
- On 307/308 redirects, original method and body are preserved (body is buffered on first request for replay).
72+
- `proxyRes` event fires only for the final (non-redirect) response; `proxyReq` fires for each request including redirects.
73+
- Sensitive headers (`authorization`, `cookie`) are stripped on cross-origin redirects.
74+
- When `followRedirects` is enabled, the request body is tee'd (written to proxy request and buffered simultaneously) rather than piped.
6975

7076
### WebSocket middleware semantics
7177

@@ -126,7 +132,7 @@ pnpm test # Lint + typecheck + tests with coverage
126132
### Test expectations and parity
127133

128134
- The suite includes legacy parity tests ported from `http-party/node-http-proxy` plus project-specific tests (`test/server.test.ts`, `test/fetch.test.ts`, `test/types.test-d.ts`).
129-
- `followRedirects` parity is intentionally pending/todo and currently unsupported.
135+
- `followRedirects` is natively implemented (no external dependency). See behavioral notes below.
130136
- HTTPS tests rely on local fixtures in `test/fixtures/agent2-*.pem`.
131137

132138
## Tooling

‎README.md‎

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -75,35 +75,33 @@ server.listen(3000, () => {
7575

7676
## Options
7777

78-
| Option | Type | Default | Description |
79-
| ----------------------- | -------------------------------------- | -------- | ------------------------------------------------------------------- |
80-
| `target` | `string \| URL \| ProxyTargetDetailed` | — | Target server URL |
81-
| `forward` | `string \| URL` | — | Forward server URL (pipes request without the target's response) |
82-
| `agent` | `http.Agent` | — | Object passed to `http(s).request` for connection pooling |
83-
| `ssl` | `https.ServerOptions` | — | Object passed to `https.createServer()` |
84-
| `ws` | `boolean` | `false` | Enable WebSocket proxying |
85-
| `xfwd` | `boolean` | `false` | Add `x-forwarded-*` headers |
86-
| `secure` | `boolean` | — | Verify SSL certificates |
87-
| `toProxy` | `boolean` | `false` | Pass absolute URL as path (proxy-to-proxy) |
88-
| `prependPath` | `boolean` | `true` | Prepend the target's path to the proxy path |
89-
| `ignorePath` | `boolean` | `false` | Ignore the incoming request path |
90-
| `localAddress` | `string` | — | Local interface to bind for outgoing connections |
91-
| `changeOrigin` | `boolean` | `false` | Change the `Host` header to match the target URL |
92-
| `preserveHeaderKeyCase` | `boolean` | `false` | Keep original letter case of response header keys |
93-
| `auth` | `string` | — | Basic authentication (`'user:password'`) for `Authorization` header |
94-
| `hostRewrite` | `string` | — | Rewrite the `Location` hostname on redirects (301/302/307/308) |
95-
| `autoRewrite` | `boolean` | `false` | Rewrite `Location` host/port on redirects based on the request |
96-
| `protocolRewrite` | `string` | — | Rewrite `Location` protocol on redirects (`'http'` or `'https'`) |
97-
| `cookieDomainRewrite` | `false \| string \| object` | `false` | Rewrite domain of `Set-Cookie` headers |
98-
| `cookiePathRewrite` | `false \| string \| object` | `false` | Rewrite path of `Set-Cookie` headers |
99-
| `headers` | `object` | — | Extra headers to add to target requests |
100-
| `proxyTimeout` | `number` | `120000` | Timeout (ms) for the proxy request to the target |
101-
| `timeout` | `number` | — | Timeout (ms) for the incoming request |
102-
| `selfHandleResponse` | `boolean` | `false` | Disable automatic response piping (handle `proxyRes` yourself) |
103-
| `buffer` | `stream.Stream` | — | Stream to use as request body instead of the incoming request |
104-
105-
> [!NOTE]
106-
> `followRedirects` from [node-http-proxy](https://github.com/http-party/node-http-proxy) is **not** supported.
78+
| Option | Type | Default | Description |
79+
| ----------------------- | -------------------------------------- | -------- | --------------------------------------------------------------------------- |
80+
| `target` | `string \| URL \| ProxyTargetDetailed` | — | Target server URL |
81+
| `forward` | `string \| URL` | — | Forward server URL (pipes request without the target's response) |
82+
| `agent` | `http.Agent` | — | Object passed to `http(s).request` for connection pooling |
83+
| `ssl` | `https.ServerOptions` | — | Object passed to `https.createServer()` |
84+
| `ws` | `boolean` | `false` | Enable WebSocket proxying |
85+
| `xfwd` | `boolean` | `false` | Add `x-forwarded-*` headers |
86+
| `secure` | `boolean` | — | Verify SSL certificates |
87+
| `toProxy` | `boolean` | `false` | Pass absolute URL as path (proxy-to-proxy) |
88+
| `prependPath` | `boolean` | `true` | Prepend the target's path to the proxy path |
89+
| `ignorePath` | `boolean` | `false` | Ignore the incoming request path |
90+
| `localAddress` | `string` | — | Local interface to bind for outgoing connections |
91+
| `changeOrigin` | `boolean` | `false` | Change the `Host` header to match the target URL |
92+
| `preserveHeaderKeyCase` | `boolean` | `false` | Keep original letter case of response header keys |
93+
| `auth` | `string` | — | Basic authentication (`'user:password'`) for `Authorization` header |
94+
| `hostRewrite` | `string` | — | Rewrite the `Location` hostname on redirects (301/302/307/308) |
95+
| `autoRewrite` | `boolean` | `false` | Rewrite `Location` host/port on redirects based on the request |
96+
| `protocolRewrite` | `string` | — | Rewrite `Location` protocol on redirects (`'http'` or `'https'`) |
97+
| `cookieDomainRewrite` | `false \| string \| object` | `false` | Rewrite domain of `Set-Cookie` headers |
98+
| `cookiePathRewrite` | `false \| string \| object` | `false` | Rewrite path of `Set-Cookie` headers |
99+
| `headers` | `object` | — | Extra headers to add to target requests |
100+
| `proxyTimeout` | `number` | `120000` | Timeout (ms) for the proxy request to the target |
101+
| `timeout` | `number` | — | Timeout (ms) for the incoming request |
102+
| `selfHandleResponse` | `boolean` | `false` | Disable automatic response piping (handle `proxyRes` yourself) |
103+
| `followRedirects` | `boolean \| number` | `false` | Follow HTTP redirects from target. `true` = max 5 hops; number = custom max |
104+
| `buffer` | `stream.Stream` | — | Stream to use as request body instead of the incoming request |
107105

108106
## Events
109107

‎src/middleware/web-incoming.ts‎

Lines changed: 118 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ClientRequest, ServerResponse } from "node:http";
1+
import type { ClientRequest, IncomingMessage, ServerResponse } from "node:http";
22
import type { ProxyTargetDetailed } from "../types.ts";
33
import nodeHTTP from "node:http";
44
import nodeHTTPS from "node:https";
@@ -7,6 +7,7 @@ import { webOutgoingMiddleware } from "./web-outgoing.ts";
77
import { type ProxyMiddleware, defineProxyMiddleware } from "./_utils.ts";
88

99
const nativeAgents = { http: nodeHTTP, https: nodeHTTPS };
10+
const redirectStatuses = new Set([301, 302, 303, 307, 308]);
1011

1112
/**
1213
* Sets `content-length` to '0' if request is of DELETE type.
@@ -64,10 +65,15 @@ export const stream = defineProxyMiddleware((req, res, options, server, head, ca
6465
// And we begin!
6566
server.emit("start", req, res, options.target || options.forward);
6667

67-
// const agents = options.followRedirects ? followRedirects : nativeAgents;
68-
const agents = nativeAgents;
69-
const http = agents.http;
70-
const https = agents.https;
68+
const http = nativeAgents.http;
69+
const https = nativeAgents.https;
70+
71+
const maxRedirects =
72+
typeof options.followRedirects === "number"
73+
? options.followRedirects
74+
: options.followRedirects
75+
? 5
76+
: 0;
7177

7278
if (options.forward) {
7379
// If forward enable, so just pipe the request
@@ -133,9 +139,110 @@ export const stream = defineProxyMiddleware((req, res, options, server, head, ca
133139
};
134140
}
135141

136-
(options.buffer || req).pipe(proxyReq);
142+
// Buffer request body when following redirects (needed for 307/308 replay)
143+
let bodyBuffer: Buffer | undefined;
144+
if (maxRedirects > 0) {
145+
const chunks: Buffer[] = [];
146+
const source = options.buffer || req;
147+
source.on("data", (chunk: Buffer) => {
148+
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
149+
proxyReq.write(chunk);
150+
});
151+
source.on("end", () => {
152+
bodyBuffer = Buffer.concat(chunks);
153+
proxyReq.end();
154+
});
155+
source.on("error", (err: Error) => {
156+
proxyReq.destroy(err);
157+
});
158+
} else {
159+
(options.buffer || req).pipe(proxyReq);
160+
}
161+
162+
function handleResponse(proxyRes: IncomingMessage, redirectCount: number, currentUrl: URL) {
163+
const statusCode = proxyRes.statusCode!;
137164

138-
proxyReq.on("response", function (proxyRes) {
165+
if (
166+
maxRedirects > 0 &&
167+
redirectStatuses.has(statusCode) &&
168+
redirectCount < maxRedirects &&
169+
proxyRes.headers.location
170+
) {
171+
// Drain the redirect response body
172+
proxyRes.resume();
173+
174+
const location = new URL(proxyRes.headers.location, currentUrl);
175+
176+
// 301/302/303 → GET without body; 307/308 → preserve method and body
177+
const preserveMethod = statusCode === 307 || statusCode === 308;
178+
const redirectMethod = preserveMethod ? req.method || "GET" : "GET";
179+
180+
const isHTTPS = location.protocol === "https:";
181+
const agent = isHTTPS ? https : http;
182+
183+
// Build headers from original request
184+
const redirectHeaders: Record<string, string | string[] | undefined> = { ...req.headers };
185+
if (options.headers) {
186+
Object.assign(redirectHeaders, options.headers);
187+
}
188+
redirectHeaders.host = location.host;
189+
190+
// Strip sensitive headers on cross-origin redirects
191+
if (location.host !== currentUrl.host) {
192+
delete redirectHeaders.authorization;
193+
delete redirectHeaders.cookie;
194+
}
195+
196+
// Drop body-related headers when method changes to GET
197+
if (!preserveMethod) {
198+
delete redirectHeaders["content-length"];
199+
delete redirectHeaders["content-type"];
200+
delete redirectHeaders["transfer-encoding"];
201+
}
202+
203+
const redirectOpts: nodeHTTP.RequestOptions = {
204+
hostname: location.hostname,
205+
port: location.port || (isHTTPS ? 443 : 80),
206+
path: location.pathname + location.search,
207+
method: redirectMethod,
208+
headers: redirectHeaders,
209+
agent: options.agent || false,
210+
};
211+
212+
if (isHTTPS) {
213+
(redirectOpts as nodeHTTPS.RequestOptions).rejectUnauthorized =
214+
options.secure === undefined ? true : options.secure;
215+
}
216+
217+
const redirectReq = agent.request(redirectOpts);
218+
219+
if (server && !redirectReq.getHeader("expect")) {
220+
server.emit("proxyReq", redirectReq, req, res, options);
221+
}
222+
223+
if (options.proxyTimeout) {
224+
redirectReq.setTimeout(options.proxyTimeout, () => {
225+
redirectReq.abort();
226+
});
227+
}
228+
229+
const redirectError = createErrorHandler(redirectReq, location);
230+
redirectReq.on("error", redirectError);
231+
232+
redirectReq.on("response", (nextRes: IncomingMessage) => {
233+
handleResponse(nextRes, redirectCount + 1, location);
234+
});
235+
236+
if (preserveMethod && bodyBuffer && bodyBuffer.length > 0) {
237+
redirectReq.end(bodyBuffer);
238+
} else {
239+
redirectReq.end();
240+
}
241+
242+
return;
243+
}
244+
245+
// Non-redirect response (or max redirects exceeded)
139246
if (server) {
140247
server.emit("proxyRes", proxyRes, req, res);
141248
}
@@ -153,21 +260,22 @@ export const stream = defineProxyMiddleware((req, res, options, server, head, ca
153260
server.emit("end", req, res, proxyRes);
154261
}
155262
} else {
156-
// EventSource close
157263
res.on("close", function () {
158264
proxyRes.destroy();
159265
});
160-
// Allow us to listen when the proxy has completed
161266
proxyRes.on("end", function () {
162267
if (server) {
163268
server.emit("end", req, res, proxyRes);
164269
}
165270
});
166-
// We pipe to the response unless its expected to be handled by the user
167271
if (!options.selfHandleResponse) {
168272
proxyRes.pipe(res);
169273
}
170274
}
275+
}
276+
277+
proxyReq.on("response", function (proxyRes) {
278+
handleResponse(proxyRes, 0, options.target as URL);
171279
});
172280
});
173281

‎src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ export interface ProxyServerOptions {
6565
timeout?: number;
6666
/** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */
6767
selfHandleResponse?: boolean;
68+
/** Follow HTTP redirects from target. `true` = max 5 hops; number = custom max. */
69+
followRedirects?: boolean | number;
6870
/** Buffer */
6971
buffer?: stream.Stream;
7072
}

0 commit comments

Comments
 (0)