Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Phone web app HTTP client: reply once the head is in; stricter framing, trailers and paths
Bugfixer 25be68a48441d
diff --git a/src/lib/e2e/http.test.ts b/src/lib/e2e/http.test.tsindex 158068450a..f7d5cbcd25 100644--- a/src/lib/e2e/http.test.ts+++ b/src/lib/e2e/http.test.ts@@ -107,7 +107,9 @@ describe("streamFetch over a real session (interop computer)", () => {const abort = new AbortController();const res = await fetchOver({ path: "/hang", signal: abort.signal });const reader = res.body!.getReader();- expect(new TextDecoder().decode((await reader.read()).value)).toContain("start");+ // Chunk edges need not match events: read until the first whole one is in.+ let seen = "";+ while (!seen.includes("data: start\n\n")) seen += new TextDecoder().decode((await reader.read()).value);const pending = reader.read();abort.abort(new Error("left the page"));await expect(pending).rejects.toThrow("left the page");@@ -160,6 +162,8 @@ describe("streamFetch framing (fake computer)", () => {["a bad status line", ["HTTP/2 200\r\n\r\n"], "bad status line"],["an unknown transfer coding", ["HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip, chunked\r\n\r\n"], "unsupported transfer-encoding"],["two different lengths", ["HTTP/1.1 200 OK\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\n"], "bad content-length"],+ ["chunked with two different lengths", ["HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\n"], "bad content-length"],+ ["a NUL in the reason phrase", ["HTTP/1.1 200 O\0K\r\nContent-Length: 0\r\n\r\n"], "bad status line"],["a switch of protocols", ["HTTP/1.1 101 Switching Protocols\r\n\r\n"], "switched protocols"],["a stream that ends inside the head", ["HTTP/1.1 200 OK\r\n"], "ended inside the reply head"],])("refuses %s and resets the stream", async (_what, reply, message) => {@@ -173,6 +177,7 @@ describe("streamFetch framing (fake computer)", () => {[{ path: "/", headers: { "Content-Length": "5" } }, "content-length is set by the stream client"],[{ path: "/a b" }, "origin-form"],[{ path: "http://x/" }, "origin-form"],+ [{ path: "/a#b" }, "origin-form"],[{ method: "GE T", path: "/" }, "bad method"],])("refuses a request that could split or reframe, before opening a stream (%#)", async (request, message) => {let opened = false;@@ -180,6 +185,58 @@ describe("streamFetch framing (fake computer)", () => {expect(opened).toBe(false);});+ it("keeps %23 and the query in the path", async () => {+ const fake = fakeStream(["HTTP/1.1 204 No Content\r\n\r\n"]);+ await streamFetch(fake.open, { path: "/a%23b?q=%23&r=1" });+ expect(fake.sent().startsWith("GET /a%23b?q=%23&r=1 HTTP/1.1\r\n")).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"],+ ])("errors the body on %s, and resets the stream", async (_what, end) => {+ const fake = fakeStream([`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nhi\r\n${end}`]);+ const res = await streamFetch(fake.open, { path: "/" });+ await expect(res.text()).rejects.toThrow(HttpError);+ expect(fake.state.reset).toBe(true);+ });++ it("errors the body with the abort reason, even for bytes already read past the head", async () => {+ const fake = fakeStream(["HTTP/1.1 200 OK\r\n\r\nabc"], { endAfter: false });+ const abort = new AbortController();+ const res = await streamFetch(fake.open, { path: "/", signal: abort.signal });+ abort.abort(new Error("gone"));+ await expect(res.body!.getReader().read()).rejects.toThrow("gone");+ expect(fake.state.reset).toBe(true);+ });++ it("gives the reply once its head is in, while the upload waits for the reply to be read (an echo past both windows)", async () => {+ // The computer takes no more upload until this side reads what it echoed: waiting for the upload first never ends.+ const fake = fakeStream(["HTTP/1.1 200 OK\r\n\r\n", "echo"]);+ let taken!: () => void;+ const upload = new Promise<void>((resolve) => (taken = resolve));+ const open = () => ({ ...fake.open(), write: (bytes: Uint8Array) => (bytes.length === 4 ? upload : Promise.resolve()) });+ const tooLate = new Promise<null>((resolve) => setTimeout(() => resolve(null), 1_000));+ const res = await Promise.race([streamFetch(open, { method: "POST", path: "/echo", body: "abcd" }), tooLate]);+ expect(res).not.toBeNull();+ const reader = res!.body!.getReader();+ expect(new TextDecoder().decode((await reader.read()).value)).toBe("echo");+ taken();+ expect((await reader.read()).done).toBe(true);+ expect(fake.state.reset).toBe(false);+ });++ it("errors the body when the upload fails after the head is in", async () => {+ const fake = fakeStream(["HTTP/1.1 200 OK\r\n\r\n"], { endAfter: false });+ let failUpload!: (error: Error) => void;+ const open = () => ({ ...fake.open(), write: (bytes: Uint8Array) => (bytes.length === 3 ? new Promise<void>((_, reject) => (failUpload = reject)) : Promise.resolve()) });+ const res = await streamFetch(open, { method: "POST", path: "/", body: "abc" });+ expect(res.status).toBe(200);+ failUpload(new Error("stream reset"));+ await expect(res.text()).rejects.toThrow("stream reset");+ expect(fake.state.reset).toBe(true);+ });+it("rejects with the abort reason when aborted before the head arrives", async () => {const fake = fakeStream([], { endAfter: false });const abort = new AbortController();diff --git a/src/lib/e2e/http.ts b/src/lib/e2e/http.tsindex 0dbbcb8875..51945d6ce4 100644--- a/src/lib/e2e/http.ts+++ b/src/lib/e2e/http.ts@@ -33,7 +33,9 @@ export interface StreamRequest {/** The request head, refused before anything is sent when a part could split or reframe the request. */export function requestHead(method: string, path: string, headers: Headers, length: number | null): string {if (!TOKEN.test(method)) throw new TypeError(`e2e http: bad method ${JSON.stringify(method)}`);- if (!path.startsWith("/") || [...path].some((char) => char <= " " || char === "\x7f")) throw new TypeError("e2e http: path must be origin-form with no spaces or controls");+ 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`;// Headers already refuses names that are not tokens and values with CR, LF or NUL.for (const [name, value] of headers) {@@ -111,21 +113,25 @@ interface Head {headers: Headers;}+/** One `name: value` line of a head or the trailers. */+function appendField(headers: Headers, line: string): void {+ const colon = line.indexOf(":");+ 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());+ } catch {+ throw new HttpError(`bad value for ${name}`);+ }+}+function parseHead(bytes: Uint8Array): Head {const [statusLine, ...lines] = byteString(bytes).split("\r\n");- const status = /^HTTP\/1\.[01] ([1-5]\d\d)(?: ([^\r\n]*))?$/.exec(statusLine);+ // The reason phrase as Response takes it: tab, space, visible and obs-text bytes.+ const status = /^HTTP\/1\.[01] ([1-5]\d\d)(?: ([\t\x20-\x7e\x80-\xff]*))?$/.exec(statusLine);if (!status) throw new HttpError("bad status line");const headers = new Headers();- for (const line of lines) {- const colon = line.indexOf(":");- 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());- } catch {- throw new HttpError(`bad value for ${name}`);- }- }+ for (const line of lines) appendField(headers, line);return { status: Number(status[1]), statusText: status[2] ?? "", headers };}@@ -133,17 +139,17 @@ type Framing = { kind: "none" } | { kind: "length"; left: number } | { kind: "chfunction framing(method: string, head: Head): Framing {if (method === "HEAD" || NULL_BODY.has(head.status)) return { kind: "none" };+ // Checked even beside chunked: lengths that disagree mean the reply's framing can't be trusted.+ const length = head.headers.get("content-length");+ const values = new Set(length?.split(",").map((value) => value.trim()));+ const [only] = values;+ if (length !== null && (values.size !== 1 || !/^\d{1,15}$/.test(only))) throw new HttpError("bad content-length");const coding = head.headers.get("transfer-encoding");if (coding !== null) {if (coding.trim().toLowerCase() !== "chunked") throw new HttpError(`unsupported transfer-encoding ${coding}`);return { kind: "chunked" };}- const length = head.headers.get("content-length");- if (length === null) return { kind: "close" };- const values = new Set(length.split(",").map((value) => value.trim()));- const [only] = values;- if (values.size !== 1 || !/^\d{1,15}$/.test(only)) throw new HttpError("bad content-length");- return { kind: "length", left: Number(only) };+ return length === null ? { kind: "close" } : { kind: "length", left: Number(only) };}async function chunkSize(reader: ByteReader): Promise<number> {@@ -164,10 +170,8 @@ export async function streamFetch(open: () => E2EStream, request: StreamRequest)const stream = open();const reader = new ByteReader(stream.readable);let finished = false;- const abort = () => {- if (!finished) stream.reset();- };- signal?.addEventListener("abort", abort, { once: true });+ /** The reply body's controller, once the head is in. */+ let output: ReadableStreamDefaultController<Uint8Array> | null = null;const done = () => {finished = true;signal?.removeEventListener("abort", abort);@@ -180,15 +184,18 @@ export async function streamFetch(open: () => E2EStream, request: StreamRequest)stream.reset();return signal?.aborted ? signal.reason : error;};+ /** Resets the stream; a body already given out errors at once, bytes held for it or not. */+ const fail = (error: unknown) => {+ if (finished) return;+ const reason = failed(error);+ output?.error(reason);+ };+ const abort = () => fail(null);+ signal?.addEventListener("abort", abort, { once: true });- let reply: Head;- let frame: Framing;+ // 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]);try {- // No FIN after the request: Node's HTTP server cuts a reply short when the client half-closes first.- const sent = (async () => {- await stream.write(utf8(head));- if (body?.length) await stream.write(Uint8Array.from(body));- })();const received = (async () => {for (;;) {const next = parseHead(await reader.until(CRLF2, MAX_HEAD, "reply head"));@@ -196,57 +203,68 @@ export async function streamFetch(open: () => E2EStream, request: StreamRequest)if (next.status >= 200) return next;}})();- [, reply] = await Promise.all([sent, received]);- frame = framing(method, reply);- } catch (error) {- throw failed(error);- }-- if (frame.kind === "none") {- done();- return new Response(null, reply);- }- let chunkLeft = 0;- const readable = new ReadableStream<Uint8Array>({- async pull(controller) {- try {- for (;;) {- if (frame.kind === "length") {- if (frame.left === 0) break;- const part = await reader.some(frame.left);- if (!part) throw new HttpError("the reply ended before its content-length");- frame.left -= part.length;- return controller.enqueue(Uint8Array.from(part));- }- if (frame.kind === "close") {- const part = await reader.some(64 * 1024);- if (!part) break;- return controller.enqueue(Uint8Array.from(part));- }- if (chunkLeft === 0) {- chunkLeft = await chunkSize(reader);+ // The reply is given once its head is in, upload or not: a computer that answers as it reads (an echo) waits on+ // this side reading. An upload that fails before the head fails the request; one that fails after errors the body.+ const reply = await Promise.race([received, sent.then(() => received)]);+ sent.catch(fail);+ let frame = framing(method, reply);+ if (frame.kind === "none") {+ const response = new Response(null, reply);+ done();+ return response;+ }+ let chunkLeft = 0;+ const readable = new ReadableStream<Uint8Array>({+ start(controller) {+ output = controller;+ },+ async pull(controller) {+ try {+ for (;;) {+ if (frame.kind === "length") {+ if (frame.left === 0) break;+ const part = await reader.some(frame.left);+ if (!part) throw new HttpError("the reply ended before its content-length");+ frame.left -= part.length;+ return controller.enqueue(Uint8Array.from(part));+ }+ if (frame.kind === "close") {+ const part = await reader.some(64 * 1024);+ if (!part) break;+ return controller.enqueue(Uint8Array.from(part));+ }if (chunkLeft === 0) {- // Trailers are read and dropped, up to the blank line that ends the reply.- while ((await reader.until([13, 10], MAX_HEAD, "trailer")).length) { /* next trailer line */ }- break;+ chunkLeft = await chunkSize(reader);+ if (chunkLeft === 0) {+ // Trailers are checked and dropped, up to the blank line that ends the reply.+ const trailers = new Headers();+ for (;;) {+ const line = await reader.until([13, 10], MAX_HEAD, "trailer");+ if (!line.length) break;+ appendField(trailers, byteString(line));+ }+ break;+ }}+ const part = await reader.some(chunkLeft);+ if (!part) throw new HttpError("the reply ended inside a chunk");+ chunkLeft -= part.length;+ if (chunkLeft === 0 && (await reader.until([13, 10], 0, "chunk end")).length) throw new HttpError("bad chunk end");+ return controller.enqueue(Uint8Array.from(part));}- const part = await reader.some(chunkLeft);- if (!part) throw new HttpError("the reply ended inside a chunk");- chunkLeft -= part.length;- if (chunkLeft === 0 && (await reader.until([13, 10], 0, "chunk end")).length) throw new HttpError("bad chunk end");- return controller.enqueue(Uint8Array.from(part));+ frame = { kind: "none" };+ done();+ controller.close();+ } catch (error) {+ controller.error(failed(error));}- frame = { kind: "none" };- done();- controller.close();- } catch (error) {- controller.error(failed(error));- }- },- cancel() {- failed(null);- },- });- return new Response(readable, reply);+ },+ cancel() {+ failed(null);+ },+ });+ return new Response(readable, reply);+ } catch (error) {+ throw failed(error);+ }}