Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Phone web app HTTP client: refuse an oversized head at once, keep header bytes both ways

Bugfixer 25e06d1a0c767
diff --git a/src/lib/e2e/http.test.ts b/src/lib/e2e/http.test.ts
index f7d5cbcd25..ded10028fa 100644
--- a/src/lib/e2e/http.test.ts
+++ b/src/lib/e2e/http.test.ts
@@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { fromB64u, utf8 } from "./bytes.ts";
import { credentialHash, keyId, psk } from "./credentials.ts";
-import { HttpError, streamFetch } from "./http.ts";
+import { HttpError, MAX_HEAD, streamFetch } from "./http.ts";
import { dial, type E2EStream, type PhoneSession } from "./session.ts";
const SERVER = fileURLToPath(new URL("../../../companion/src/e2e/interop-server.ts", import.meta.url));
@@ -191,6 +191,27 @@ describe("streamFetch framing (fake computer)", () => {
expect(fake.sent().startsWith("GET /a%23b?q=%23&r=1 HTTP/1.1\r\n")).toBe(true);
});
+ it("writes header values as their bytes and percent-encodes a path's non-ASCII as UTF-8, as fetch does", async () => {
+ const fake = fakeStream(["HTTP/1.1 204 No Content\r\n\r\n"]);
+ await streamFetch(fake.open, { path: "/\u00e9?q=\u65e5", headers: { "X-Label": "\u00e9" } });
+ const head = Uint8Array.from(fake.state.written.flatMap((part) => [...part]));
+ expect(String.fromCharCode(...head)).toBe("GET /%C3%A9?q=%E6%97%A5 HTTP/1.1\r\nHost: companion\r\nx-label: \u00e9\r\nConnection: close\r\n\r\n");
+ });
+
+ it("strips only spaces and tabs around a reply header value, keeping its 0xA0 bytes", async () => {
+ const wire = "HTTP/1.1 204 No Content\r\nX-Label: \t\u00a0v\u00a0 \t\r\n\r\n";
+ const res = await streamFetch(fakeStream([Uint8Array.from(wire, (char) => char.charCodeAt(0))]).open, { path: "/" });
+ expect(res.headers.get("x-label")).toBe("\u00a0v\u00a0");
+ });
+
+ it("refuses a head the moment no ending can still fit, without waiting for more bytes", async () => {
+ const line = "HTTP/1.1 200 OK\r\nX-Big: ";
+ const fake = fakeStream([line + "a".repeat(MAX_HEAD + 4 - line.length)], { endAfter: false });
+ const tooLate = new Promise<string>((resolve) => setTimeout(() => resolve("still waiting"), 500));
+ expect(await Promise.race([streamFetch(fake.open, { path: "/" }).catch((error: Error) => error.message), tooLate])).toContain("reply head is over");
+ expect(fake.state.reset).toBe(true);
+ });
+
it.each([
["a trailer with no colon", "0\r\nno colon\r\n\r\n"],
["a trailer with a NUL", "0\r\nX-T: a\0b\r\n\r\n"],
diff --git a/src/lib/e2e/http.ts b/src/lib/e2e/http.ts
index 51945d6ce4..c0c336afcd 100644
--- a/src/lib/e2e/http.ts
+++ b/src/lib/e2e/http.ts
@@ -36,7 +36,9 @@ export function requestHead(method: string, path: string, headers: Headers, leng
if (!path.startsWith("/") || [...path].some((char) => char <= " " || char === "\x7f" || char === "#")) {
throw new TypeError("e2e http: path must be origin-form with no spaces, controls or fragment");
}
- let head = `${method} ${path} HTTP/1.1\r\nHost: companion\r\n`;
+ // A path's non-ASCII goes out percent-encoded UTF-8, as fetch's URL parser sends it.
+ const target = path.replace(/[\u0080-\uffff]+/g, (run) => Array.from(utf8(run), (byte) => `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join(""));
+ let head = `${method} ${target} HTTP/1.1\r\nHost: companion\r\n`;
// Headers already refuses names that are not tokens and values with CR, LF or NUL.
for (const [name, value] of headers) {
if (OWN.has(name)) throw new TypeError(`e2e http: ${name} is set by the stream client`);
@@ -73,7 +75,7 @@ class ByteReader {
this.#held = this.#held.subarray(at + delimiter.length);
return line;
}
- if (this.#held.length > max + delimiter.length) throw new HttpError(`${what} is over ${max} bytes`);
+ if (this.#held.length >= max + delimiter.length) throw new HttpError(`${what} is over ${max} bytes`);
from = Math.max(0, this.#held.length - delimiter.length + 1);
if (!(await this.#more())) throw new HttpError(`the stream ended inside the ${what}`);
}
@@ -100,6 +102,9 @@ function indexOf(bytes: Uint8Array, delimiter: number[], from: number): number {
return -1;
}
+/** Head characters as bytes, the way fetch writes header values: one character, one byte (Headers holds only 0-255). */
+const latin1 = (text: string): Uint8Array => Uint8Array.from(text, (char) => char.charCodeAt(0));
+
/** Header bytes as fetch reads them: one byte, one character. */
const byteString = (bytes: Uint8Array): string => {
let text = "";
@@ -119,7 +124,7 @@ function appendField(headers: Headers, line: string): void {
const name = line.slice(0, colon);
if (colon < 1 || !TOKEN.test(name)) throw new HttpError("bad header line");
try {
- headers.append(name, line.slice(colon + 1).trim());
+ headers.append(name, line.slice(colon + 1).replace(/^[ \t]+|[ \t]+$/g, ""));
} catch {
throw new HttpError(`bad value for ${name}`);
}
@@ -194,7 +199,7 @@ export async function streamFetch(open: () => E2EStream, request: StreamRequest)
signal?.addEventListener("abort", abort, { once: true });
// No FIN after the request: Node's HTTP server cuts a reply short when the client half-closes first.
- const sent = Promise.all([stream.write(utf8(head)), body?.length ? stream.write(Uint8Array.from(body)) : undefined]);
+ const sent = Promise.all([stream.write(latin1(head)), body?.length ? stream.write(Uint8Array.from(body)) : undefined]);
try {
const received = (async () => {
for (;;) {