Skip to content

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

e2e web: HTTP/1.1 client over one E2E stream

Bugfixer 25ffbd5463612
diff --git a/src/lib/e2e/http.test.ts b/src/lib/e2e/http.test.ts
new file mode 100644
index 0000000000..158068450a
--- /dev/null
+++ b/src/lib/e2e/http.test.ts
@@ -0,0 +1,191 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { fileURLToPath } from "node:url";
+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 { dial, type E2EStream, type PhoneSession } from "./session.ts";
+
+const SERVER = fileURLToPath(new URL("../../../companion/src/e2e/interop-server.ts", import.meta.url));
+
+let child: ChildProcess;
+let session: PhoneSession;
+
+beforeAll(async () => {
+ child = spawn(process.execPath, [SERVER, "--port", "0", "--exit-with-stdin"], { stdio: ["pipe", "pipe", "ignore"] });
+ const ready = await new Promise<{ direct: string; k: string; deviceToken: string }>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("interop server did not say ready in 10 s")), 10_000);
+ let out = "";
+ child.stdout!.on("data", (chunk: Buffer) => {
+ out += chunk.toString();
+ const line = out.split("\n").slice(0, -1).find((candidate) => candidate.startsWith("{"));
+ if (line) {
+ clearTimeout(timer);
+ resolve(JSON.parse(line));
+ }
+ });
+ child.once("error", reject);
+ child.once("exit", (code) => reject(new Error(`interop server exited ${code}`)));
+ });
+ const remoteStatic = fromB64u(ready.k)!;
+ const key = await psk(await credentialHash(ready.deviceToken), await keyId(remoteStatic));
+ session = await dial({ url: ready.direct, remoteStatic, psk: key, app: "web-test/1" });
+});
+
+afterAll(() => {
+ session?.close(1000);
+ child?.kill("SIGTERM");
+});
+
+const fetchOver = (request: Parameters<typeof streamFetch>[1]) => streamFetch(() => session.open(), request);
+
+/** A stream the test plays the computer for: what the client wrote, and a reply fed in parts. */
+function fakeStream(reply: (string | Uint8Array)[], { endAfter = true } = {}) {
+ const written: Uint8Array[] = [];
+ const state = { ended: false, reset: false, written };
+ const parts = reply.map((part) => (typeof part === "string" ? utf8(part) : part));
+ let source!: ReadableStreamDefaultController<Uint8Array>;
+ const stream: E2EStream = {
+ id: 1,
+ readable: new ReadableStream<Uint8Array>({
+ start(controller) {
+ source = controller;
+ },
+ pull(controller) {
+ const next = parts.shift();
+ if (next) controller.enqueue(next);
+ else if (endAfter) controller.close();
+ },
+ }),
+ write: async (bytes) => void written.push(bytes),
+ end: () => void (state.ended = true),
+ reset: () => {
+ // As a real stream does: a reset errors what is still unread.
+ state.reset = true;
+ try {
+ source.error(new Error("stream reset"));
+ } catch {
+ /* already closed */
+ }
+ },
+ };
+ return { open: () => stream, state, sent: () => new TextDecoder().decode(Uint8Array.from(written.flatMap((part) => [...part]))) };
+}
+
+const pattern = (n: number, from = 0) => Uint8Array.from({ length: n }, (_, i) => (from + i) % 251);
+
+describe("streamFetch over a real session (interop computer)", () => {
+ it("reads a JSON reply", async () => {
+ const res = await fetchOver({ path: "/api/health" });
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe("application/json");
+ expect(await res.json()).toEqual({ ok: true });
+ });
+
+ it("sends a 200 KB body and reads it back whole", async () => {
+ const body = pattern(200_000);
+ const res = await fetchOver({ method: "POST", path: "/echo", body });
+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(body);
+ });
+
+ it("reads 300 KB byte for byte, and one Range as 206", async () => {
+ expect(new Uint8Array(await (await fetchOver({ path: "/bytes?n=300000" })).arrayBuffer())).toEqual(pattern(300_000));
+ const part = await fetchOver({ path: "/bytes?n=1000", headers: { Range: "bytes=500-509" } });
+ expect(part.status).toBe(206);
+ expect(new Uint8Array(await part.arrayBuffer())).toEqual(pattern(10, 500));
+ });
+
+ it("streams server-sent events to the end", async () => {
+ const res = await fetchOver({ path: "/sse?events=5&size=100&gapMs=5" });
+ const text = await res.text();
+ expect(text.match(/^id: /gm)).toHaveLength(5);
+ expect(text).toContain("event: end");
+ });
+
+ it("gives the first event of an endless reply, and abort resets the stream", async () => {
+ 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");
+ const pending = reader.read();
+ abort.abort(new Error("left the page"));
+ await expect(pending).rejects.toThrow("left the page");
+ expect((await fetchOver({ path: "/api/health" })).status).toBe(200);
+ });
+});
+
+describe("streamFetch framing (fake computer)", () => {
+ it("writes one closed request with its own Host, length and no FIN until the reply is read", async () => {
+ const fake = fakeStream(["HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"]);
+ const res = await streamFetch(fake.open, { method: "post", path: "/api/x?y=1", headers: { "X-Thing": "a" }, body: "héllo" });
+ expect(fake.sent()).toBe("POST /api/x?y=1 HTTP/1.1\r\nHost: companion\r\nx-thing: a\r\nContent-Length: 6\r\nConnection: close\r\n\r\nhéllo");
+ expect(fake.state.ended).toBe(false);
+ expect(await res.text()).toBe("hi");
+ expect(fake.state.ended).toBe(true);
+ expect(fake.state.reset).toBe(false);
+ });
+
+ it("decodes chunks split at odd places, with extensions and trailers", async () => {
+ const wire = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5;x=1\r\nhello\r\n1\r\n \r\nA\r\n0123456789\r\n0\r\nX-T: 1\r\n\r\n";
+ const parts = wire.match(/[\s\S]{1,3}/g)!;
+ expect(await (await streamFetch(fakeStream(parts).open, { path: "/" })).text()).toBe("hello 0123456789");
+ });
+
+ it("skips 100 Continue and gives 204 a null body", async () => {
+ const res = await streamFetch(fakeStream(["HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 204 No Content\r\n\r\n"]).open, { path: "/" });
+ expect(res.status).toBe(204);
+ expect(res.body).toBeNull();
+ });
+
+ it("reads to the end of the stream when the reply has no length", async () => {
+ expect(await (await streamFetch(fakeStream(["HTTP/1.0 200 OK\r\n\r\nab", "cd"]).open, { path: "/" })).text()).toBe("abcd");
+ });
+
+ it("errors a reply cut short of its content-length, and resets the stream", async () => {
+ const fake = fakeStream(["HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc"]);
+ const res = await streamFetch(fake.open, { path: "/" });
+ await expect(res.text()).rejects.toThrow(HttpError);
+ expect(fake.state.reset).toBe(true);
+ });
+
+ it("errors a chunked reply that ends inside a chunk", async () => {
+ const res = await streamFetch(fakeStream(["HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nA\r\nabc"]).open, { path: "/" });
+ await expect(res.text()).rejects.toThrow("ended inside a chunk");
+ });
+
+ it.each([
+ ["a head over the limit", ["HTTP/1.1 200 OK\r\n", `X-Big: ${"a".repeat(20_000)}\r\n\r\n`], "reply head is over"],
+ ["a folded header", ["HTTP/1.1 200 OK\r\nX-A: 1\r\n 2\r\n\r\n"], "bad header line"],
+ ["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"],
+ ["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) => {
+ const fake = fakeStream(reply as string[]);
+ await expect(streamFetch(fake.open, { path: "/" })).rejects.toThrow(message);
+ expect(fake.state.reset).toBe(true);
+ });
+
+ it.each([
+ [{ path: "/", headers: { Host: "elsewhere" } }, "host is set by the stream client"],
+ [{ path: "/", headers: { "Content-Length": "5" } }, "content-length is set by the stream client"],
+ [{ path: "/a b" }, "origin-form"],
+ [{ path: "http://x/" }, "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;
+ await expect(streamFetch(() => ((opened = true), fakeStream([]).open()), request)).rejects.toThrow(message);
+ expect(opened).toBe(false);
+ });
+
+ it("rejects with the abort reason when aborted before the head arrives", async () => {
+ const fake = fakeStream([], { endAfter: false });
+ const abort = new AbortController();
+ const pending = streamFetch(fake.open, { path: "/", signal: abort.signal });
+ abort.abort(new Error("gone"));
+ await expect(pending).rejects.toThrow("gone");
+ expect(fake.state.reset).toBe(true);
+ });
+});
diff --git a/src/lib/e2e/http.ts b/src/lib/e2e/http.ts
new file mode 100644
index 0000000000..0dbbcb8875
--- /dev/null
+++ b/src/lib/e2e/http.ts
@@ -0,0 +1,252 @@
+// HTTP/1.1 over one E2E stream, the bytes the computer's origin listener reads (README section 8: the E2E layer never
+// parses them). One request per stream with Connection: close: a stream costs one frame to open, so nothing is pooled.
+import { concat, utf8 } from "./bytes.ts";
+import type { E2EStream } from "./session.ts";
+
+/** Status line plus headers of one reply, the same ceiling Node's HTTP server puts on a request head. */
+export const MAX_HEAD = 16 * 1024;
+const MAX_CHUNK_LINE = 1024;
+const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
+/** Framing and connection headers this client writes itself; a caller's own would contradict them. */
+const OWN = new Set(["host", "connection", "content-length", "transfer-encoding", "upgrade", "keep-alive", "te", "trailer", "accept-encoding"]);
+/** Statuses whose Response must have a null body. */
+const NULL_BODY = new Set([204, 205, 304]);
+const CRLF2 = [13, 10, 13, 10];
+
+export class HttpError extends Error {
+ constructor(message: string) {
+ super(`e2e http: ${message}`);
+ this.name = "HttpError";
+ }
+}
+
+export interface StreamRequest {
+ /** Default GET. */
+ method?: string;
+ /** Origin form: "/api/bots?x=1". */
+ path: string;
+ headers?: HeadersInit;
+ body?: Uint8Array | string | null;
+ signal?: AbortSignal;
+}
+
+/** 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");
+ 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) {
+ if (OWN.has(name)) throw new TypeError(`e2e http: ${name} is set by the stream client`);
+ head += `${name}: ${value}\r\n`;
+ }
+ if (length !== null) head += `Content-Length: ${length}\r\n`;
+ return `${head}Connection: close\r\n\r\n`;
+}
+
+/** Reads a stream's bytes with the leftover of the last read kept for the next parse. */
+class ByteReader {
+ readonly #reader: ReadableStreamDefaultReader<Uint8Array>;
+ #held: Uint8Array = new Uint8Array(0);
+
+ constructor(readable: ReadableStream<Uint8Array>) {
+ this.#reader = readable.getReader();
+ }
+
+ /** False at the end of the stream. */
+ async #more(): Promise<boolean> {
+ const { done, value } = await this.#reader.read();
+ if (done) return false;
+ this.#held = this.#held.length ? concat(this.#held, value) : value;
+ return true;
+ }
+
+ /** Bytes up to and without the delimiter, which is consumed. */
+ async until(delimiter: number[], max: number, what: string): Promise<Uint8Array> {
+ let from = 0;
+ for (;;) {
+ const at = indexOf(this.#held, delimiter, from);
+ if (at !== -1 && at <= max) {
+ const line = this.#held.subarray(0, at);
+ 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`);
+ from = Math.max(0, this.#held.length - delimiter.length + 1);
+ if (!(await this.#more())) throw new HttpError(`the stream ended inside the ${what}`);
+ }
+ }
+
+ /** Up to `max` bytes, or null at the end of the stream. */
+ async some(max: number): Promise<Uint8Array | null> {
+ if (!this.#held.length && !(await this.#more())) return null;
+ const part = this.#held.subarray(0, max);
+ this.#held = this.#held.subarray(part.length);
+ return part;
+ }
+
+ release(): void {
+ this.#reader.releaseLock();
+ }
+}
+
+function indexOf(bytes: Uint8Array, delimiter: number[], from: number): number {
+ outer: for (let i = from; i + delimiter.length <= bytes.length; i++) {
+ for (let j = 0; j < delimiter.length; j++) if (bytes[i + j] !== delimiter[j]) continue outer;
+ return i;
+ }
+ return -1;
+}
+
+/** Header bytes as fetch reads them: one byte, one character. */
+const byteString = (bytes: Uint8Array): string => {
+ let text = "";
+ for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192));
+ return text;
+};
+
+interface Head {
+ status: number;
+ statusText: string;
+ headers: Headers;
+}
+
+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);
+ 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}`);
+ }
+ }
+ return { status: Number(status[1]), statusText: status[2] ?? "", headers };
+}
+
+type Framing = { kind: "none" } | { kind: "length"; left: number } | { kind: "chunked" } | { kind: "close" };
+
+function framing(method: string, head: Head): Framing {
+ if (method === "HEAD" || NULL_BODY.has(head.status)) return { kind: "none" };
+ 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) };
+}
+
+async function chunkSize(reader: ByteReader): Promise<number> {
+ const line = byteString(await reader.until([13, 10], MAX_CHUNK_LINE, "chunk size line"));
+ const size = /^([0-9A-Fa-f]{1,12})[ \t]*(?:;.*)?$/.exec(line);
+ if (!size) throw new HttpError("bad chunk size");
+ return parseInt(size[1], 16);
+}
+
+/** One request on a fresh stream from `open`. Resolves with the reply once its head is in; the body streams after. */
+export async function streamFetch(open: () => E2EStream, request: StreamRequest): Promise<Response> {
+ const method = (request.method ?? "GET").toUpperCase();
+ const body = typeof request.body === "string" ? utf8(request.body) : request.body ?? null;
+ const head = requestHead(method, request.path, new Headers(request.headers), body ? body.length : method === "POST" || method === "PUT" || method === "PATCH" ? 0 : null);
+ const signal = request.signal;
+ signal?.throwIfAborted();
+
+ const stream = open();
+ const reader = new ByteReader(stream.readable);
+ let finished = false;
+ const abort = () => {
+ if (!finished) stream.reset();
+ };
+ signal?.addEventListener("abort", abort, { once: true });
+ const done = () => {
+ finished = true;
+ signal?.removeEventListener("abort", abort);
+ reader.release();
+ stream.end();
+ };
+ const failed = (error: unknown): unknown => {
+ finished = true;
+ signal?.removeEventListener("abort", abort);
+ stream.reset();
+ return signal?.aborted ? signal.reason : error;
+ };
+
+ let reply: Head;
+ let frame: Framing;
+ 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"));
+ if (next.status === 101) throw new HttpError("the computer switched protocols on a plain request");
+ 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);
+ 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;
+ }
+ }
+ 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));
+ }
+ },
+ cancel() {
+ failed(null);
+ },
+ });
+ return new Response(readable, reply);
+}