Skip to content

Commit ed3ae90

Browse files
NgobBenoit Ngopi0
authored
fix(proxy): avoid decoding request body as utf8 (#440)
Co-authored-by: Benoit Ngo <b.ngo@thecodingmachine.com> Co-authored-by: Pooya Parsa <pooya@pi0.io>
1 parent 57dcba8 commit ed3ae90

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

src/utils/proxy.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export async function proxyRequest(
3636
// Body
3737
let body;
3838
if (PayloadMethods.has(method)) {
39-
body = await readRawBody(event).catch(() => undefined);
39+
body = await readRawBody(event, false).catch(() => undefined);
4040
}
4141

4242
// Headers

test/assets/dummy.pdf

13 KB
Binary file not shown.

test/proxy.test.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Server } from "node:http";
2+
import { readFile } from "node:fs/promises";
23
import supertest, { SuperTest, Test } from "supertest";
34
import { describe, it, expect, beforeEach, afterEach } from "vitest";
45
import { fetch } from "node-fetch-native";
@@ -12,6 +13,7 @@ import {
1213
setHeader,
1314
readRawBody,
1415
setCookie,
16+
setResponseHeader,
1517
} from "../src";
1618
import { sendProxy, proxyRequest } from "../src/utils/proxy";
1719

@@ -106,6 +108,44 @@ describe("", () => {
106108
}
107109
`);
108110
});
111+
112+
it("can proxy binary request", async () => {
113+
app.use(
114+
"/debug",
115+
eventHandler(async (event) => {
116+
const body = await readRawBody(event, false);
117+
return {
118+
headers: getHeaders(event),
119+
bytes: body!.length,
120+
};
121+
})
122+
);
123+
124+
app.use(
125+
"/",
126+
eventHandler((event) => {
127+
setResponseHeader(event, "x-res-header", "works");
128+
return proxyRequest(event, url + "/debug", { fetch });
129+
})
130+
);
131+
132+
const dummyFile = await readFile(
133+
new URL("assets/dummy.pdf", import.meta.url)
134+
);
135+
136+
const res = await fetch(url + "/", {
137+
method: "POST",
138+
body: dummyFile,
139+
headers: {
140+
"x-req-header": "works",
141+
},
142+
});
143+
const resBody = await res.json();
144+
145+
expect(res.headers.get("x-res-header")).toEqual("works");
146+
expect(resBody.headers["x-req-header"]).toEqual("works");
147+
expect(resBody.bytes).toEqual(dummyFile.length);
148+
});
109149
});
110150

111151
describe("multipleCookies", () => {

0 commit comments

Comments
 (0)