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
4 changes: 2 additions & 2 deletions src/utils/body.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import destr from "destr";
import type { Encoding, HTTPMethod } from "../types";
import type { H3Event } from "../event";
import { parse as parseMultipartData } from "./_multipart";
import { parse as parseMultipartData } from "./internal/multipart";
import { assertMethod, getRequestHeader } from "./request";

export type { MultiPartData } from "./_multipart";
export type { MultiPartData } from "./internal/multipart";

const RawBodySymbol = Symbol.for("h3RawBody");
const ParsedBodySymbol = Symbol.for("h3ParsedBody");
Expand Down
78 changes: 78 additions & 0 deletions src/utils/internal/cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
* that are within a single set-cookie field-value, such as in the Expires portion.
* This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
* Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
* Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
* Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
* @source https://github.com/nfriedly/set-cookie-parser/blob/3eab8b7d5d12c8ed87832532861c1a35520cf5b3/lib/set-cookie.js#L144
*/
export default function splitCookiesString(cookiesString: string) {
if (typeof cookiesString !== "string") {
return [];
}

const cookiesStrings: string[] = [];
let pos = 0;
let start;
let ch;
let lastComma: number;
let nextStart;
let cookiesSeparatorFound;

function skipWhitespace() {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
pos += 1;
}
return pos < cookiesString.length;
}

function notSpecialChar() {
ch = cookiesString.charAt(pos);

return ch !== "=" && ch !== ";" && ch !== ",";
}

while (pos < cookiesString.length) {
start = pos;
cookiesSeparatorFound = false;

while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
// ',' is a cookie separator if we have later first '=', not ';' or ','
lastComma = pos;
pos += 1;

skipWhitespace();
nextStart = pos;

while (pos < cookiesString.length && notSpecialChar()) {
pos += 1;
}

// currently special character
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
// we found cookies separator
cookiesSeparatorFound = true;
// pos is inside the next cookie, so back up and return it.
pos = nextStart;
cookiesStrings.push(cookiesString.slice(start, lastComma));
start = pos;
} else {
// in param ',' or param separator ';',
// we continue from that comma
pos = lastComma + 1;
}
} else {
pos += 1;
}
}

if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.slice(start, cookiesString.length));
}
}

return cookiesStrings;
}
File renamed without changes.
5 changes: 5 additions & 0 deletions src/utils/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { H3Event } from "../event";
import type { RequestHeaders } from "../types";
import { getMethod, getRequestHeaders } from "./request";
import { readRawBody } from "./body";
import splitCookiesString from "./internal/cookies";

export interface ProxyOptions {
headers?: RequestHeaders | HeadersInit;
Expand Down Expand Up @@ -73,6 +74,10 @@ export async function sendProxy(
if (key === "content-length") {
continue;
}
if (key === "set-cookie") {
event.node.res.setHeader("set-cookie", splitCookiesString(value));
continue;
}
event.node.res.setHeader(key, value);
}

Expand Down
47 changes: 44 additions & 3 deletions test/proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
getHeaders,
getMethod,
readRawBody,
setCookie,
} from "../src";
import { sendProxy, proxyRequest } from "../src/utils/proxy";

Expand Down Expand Up @@ -82,11 +83,51 @@ describe("", () => {
const result = await fetch(url + "/", {
method: "POST",
body: "hello",
}).then((r) => r.text());
headers: {
"content-type": "text/custom",
"x-custom": "hello",
},
}).then((r) => r.json());

expect(result).toMatchInlineSnapshot(
'"{\\"method\\":\\"POST\\",\\"headers\\":{\\"accept\\":\\"*/*\\",\\"accept-encoding\\":\\"gzip, deflate, br\\",\\"connection\\":\\"close\\",\\"content-length\\":\\"5\\",\\"content-type\\":\\"text/plain;charset=UTF-8\\",\\"user-agent\\":\\"node-fetch\\"},\\"body\\":\\"hello\\"}"'
const { headers, ...data } = result;
expect(headers["content-type"]).toEqual("text/custom");
expect(headers["x-custom"]).toEqual("hello");
expect(data).toMatchInlineSnapshot(`
{
"body": "hello",
"method": "POST",
}
`);
});
});

describe("multipleCookies", () => {
it("can split multiple cookies", async () => {
app.use(
"/setcookies",
eventHandler((event) => {
setCookie(event, "user", "alice", {
expires: new Date("Thu, 01 Jun 2023 10:00:00 GMT"),
httpOnly: true,
});
setCookie(event, "role", "guest");
return {};
})
);

app.use(
"/",
eventHandler((event) => {
return sendProxy(event, url + "/setcookies", { fetch });
})
);

const result = await request.get("/");
const cookies = result.header["set-cookie"];
expect(cookies).toEqual([
"user=alice; Path=/; Expires=Thu, 01 Jun 2023 10:00:00 GMT; HttpOnly",
"role=guest; Path=/",
]);
});
});
});