Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Read payload 1, message 2 and records once, and check payload 1 as the spec says
Bugfixer 2d24316e72838
diff --git a/src/lib/e2e/interop.test.ts b/src/lib/e2e/interop.test.tsindex 370da48ebc..afc242068d 100644--- a/src/lib/e2e/interop.test.ts+++ b/src/lib/e2e/interop.test.ts@@ -127,11 +127,13 @@ describe("the browser phone side against the Node computer", () => {it("is refused with 4001 when the token is not one the computer knows", async () => {const { ws } = await handshake(ready.direct, "not-a-token-the-computer-knows", TRANSPORT_DIRECT);expect(await ws.closedWith()).toBe(4001);+ await expect(ws.next()).rejects.toThrow("socket closed with 4001");});it("is refused when the prologue says relay but the route is direct", async () => {const { ws } = await handshake(ready.direct, ready.deviceToken, TRANSPORT_RELAY);expect(await ws.closedWith()).toBe(4001);+ await expect(ws.next()).rejects.toThrow("socket closed with 4001");});it("stops hard on a message 2 from a party without the key", async () => {diff --git a/src/lib/e2e/noise.ts b/src/lib/e2e/noise.tsindex 3e1f6dd53c..e80ae75371 100644--- a/src/lib/e2e/noise.ts+++ b/src/lib/e2e/noise.ts@@ -1,4 +1,4 @@-import { b64u, concat, utf8, type Bytes } from "./bytes.ts";+import { b64u, concat, fromB64u, utf8, type Bytes } from "./bytes.ts";import { hmacSha256, sha256 } from "./credentials.ts";const PROTOCOL_NAME = "Noise_NKpsk0_P256_AESGCM_SHA256";@@ -205,15 +205,17 @@ export class RecordCipher {/** Any failure is a hard stop: after one, every later record is refused too. Opens run one at a time in call* order, so a record never opens while an earlier one could still fail. */open(record: Bytes): Promise<Bytes> {- const opened = this.#opening.then(() => this.#openNext(record));+ const bytes = record.length > MAX_RECORD_BYTES ? null : new Uint8Array(record);+ const opened = this.#opening.then(() => this.#openNext(bytes));this.#opening = opened.catch(() => undefined);return opened;}- async #openNext(record: Bytes): Promise<Bytes> {+ /** `record` is the caller's bytes copied at the call, or null when they were too large to copy. */+ async #openNext(record: Bytes | null): Promise<Bytes> {if (this.#failed) throw new NoiseError("failed");try {- if (record.length > MAX_RECORD_BYTES) throw new NoiseError("record_too_large");+ if (!record) throw new NoiseError("record_too_large");return await this.#state.decryptWithAd(EMPTY, record);} catch (error) {this.#failed = true;@@ -247,11 +249,14 @@ const parseJson = (bytes: Bytes): unknown => {}};-/** The `conn` that message 2 must echo, read from the payload 1 bytes actually sent. */+/** The `conn` that message 2 must echo, from payload 1 checked as the wire spec says (the computer refuses+ * anything else). */function payload1Conn(bytes: Bytes): string {const value = parseJson(bytes);- const conn = value && typeof value === "object" ? (value as { conn?: unknown }).conn : undefined;- if (typeof conn !== "string") throw new NoiseError("bad_payload1");+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new NoiseError("bad_payload1");+ const { v, conn, app } = value as { v?: unknown; conn?: unknown; app?: unknown };+ if (v !== 1 || typeof conn !== "string" || fromB64u(conn)?.length !== CONN_BYTES) throw new NoiseError("bad_payload1");+ if (app !== undefined && (typeof app !== "string" || app.length > MAX_APP_CHARS)) throw new NoiseError("bad_payload1");return conn;}@@ -278,12 +283,13 @@ export interface PhoneHello {finish(message2: Bytes): Promise<SessionKeys>;}-/** `payload1` is exact bytes so vectors can pin them; message 2 must echo its `conn`. */-export async function phoneHello(options: PhoneHandshakeOptions, payload1: Bytes): Promise<PhoneHello> {+/** `payload1` is exact bytes so vectors can pin them, read once at the call; message 2 must echo its `conn`. */+export async function phoneHello(options: PhoneHandshakeOptions, payload1Bytes: Bytes): Promise<PhoneHello> {+ if (payload1Bytes.length > MAX_HANDSHAKE_PAYLOAD) throw new NoiseError("payload_too_large");+ const payload1 = new Uint8Array(payload1Bytes);+ const conn = payload1Conn(payload1);const remoteStatic = await publicKey(options.remoteStatic);if (options.psk.length !== 32) throw new NoiseError("bad_psk");- if (payload1.length > MAX_HANDSHAKE_PAYLOAD) throw new NoiseError("payload_too_large");- const conn = payload1Conn(payload1);const state = new SymmetricState(options.trace ?? null);state.mark("init");await state.mixHash(prologue(options.transport));@@ -306,8 +312,8 @@ export async function phoneHello(options: PhoneHandshakeOptions, payload1: Bytesasync finish(reply) {if (done) throw new NoiseError("finished");done = true;- const message2 = reply.slice();- if (message2.length < PUBLIC_KEY_BYTES + TAG_BYTES || message2.length > MAX_HANDSHAKE_MESSAGE) throw new NoiseError("message2_size");+ if (reply.length < PUBLIC_KEY_BYTES + TAG_BYTES || reply.length > MAX_HANDSHAKE_MESSAGE) throw new NoiseError("message2_size");+ const message2 = new Uint8Array(reply);const re = message2.subarray(0, PUBLIC_KEY_BYTES);const ee = await dh(e.privateKey, await publicKey(re));await state.mixHash(re);diff --git a/src/lib/e2e/vectors.test.ts b/src/lib/e2e/vectors.test.tsindex 307d26d01f..29f64c5a7c 100644--- a/src/lib/e2e/vectors.test.ts+++ b/src/lib/e2e/vectors.test.ts@@ -152,6 +152,23 @@ describe("V6 must fail, phone side", () => {await expect(hello.finish(bytes(v.V2.message2))).rejects.toThrow("e2e: finished");});+ it("opens the record as it was when open was called, even if the caller changes it afterwards", async () => {+ const keys = await v2Session();+ const first = v.V4.records.find((r: { direction: string }) => r.direction === "cp");+ const record = bytes(first.record);+ const pending = keys.receive.open(record);+ record.fill(0);+ expect(hex(await pending)).toBe(first.frame);+ });++ it("reads message 2 once when finish is called, even from a Buffer the caller changes afterwards", async () => {+ const hello = await phone(1, "device");+ const reply = Buffer.from(v.V2.message2, "hex");+ const pending = hello.finish(reply as unknown as Uint8Array<ArrayBuffer>);+ reply.fill(0);+ await expect(pending).resolves.toBeDefined();+ });+it("refuses a genuine record opened before an earlier failed one settled", async () => {const keys = await v2Session();const [first, second] = v.V4.records.filter((r: { direction: string }) => r.direction === "cp");@@ -175,6 +192,30 @@ describe("payload 1, phone side", () => {it("is refused when it carries no connection ID for message 2 to echo", async () => {await expect(phoneHello({ remoteStatic: T_PUB, psk: PSKS.device, transport: 1 }, utf8('{"v":1,"app":"web/1"}'))).rejects.toThrow("e2e: bad_payload1");});++ it.each([+ ["v is not 1", '{"v":2,"conn":"XkCuA2LSB-yRqiCTmMwKqQ"}'],+ ["it is an array", '[{"v":1,"conn":"XkCuA2LSB-yRqiCTmMwKqQ"}]'],+ ["conn is 15 bytes", '{"v":1,"conn":"XkCuA2LSB-yRqiCTmMwK"}'],+ ["conn is not canonical base64url", '{"v":1,"conn":"XkCuA2LSB-yRqiCTmMwKqR"}'],+ ["app is not a string", '{"v":1,"conn":"XkCuA2LSB-yRqiCTmMwKqQ","app":7}'],+ ["app is 41 characters", `{"v":1,"conn":"XkCuA2LSB-yRqiCTmMwKqQ","app":"${"a".repeat(41)}"}`],+ ])("is refused as raw bytes when %s", async (_name, json) => {+ await expect(phoneHello({ remoteStatic: T_PUB, psk: PSKS.device, transport: 1 }, utf8(json))).rejects.toThrow("e2e: bad_payload1");+ });++ it("takes raw bytes without app", async () => {+ await expect(phoneHello({ remoteStatic: T_PUB, psk: PSKS.device, transport: 1 }, utf8('{"v":1,"conn":"XkCuA2LSB-yRqiCTmMwKqQ"}'))).resolves.toBeDefined();+ });++ it("is read once when the call is made: changing the caller's bytes afterwards changes nothing", async () => {+ const payload1 = PAYLOAD1.slice();+ const pending = phoneHello({ remoteStatic: T_PUB, psk: PSKS.device, transport: 1, ephemeral: await phoneEphemeral() }, payload1);+ payload1.fill(0x20);+ const hello = await pending;+ expect(hex(hello.message1)).toBe(v.V2.message1);+ await expect(hello.finish(bytes(v.V2.message2))).resolves.toBeDefined();+ });});describe("the session keys", () => {