Skip to content

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

Copy every caller-owned input before the first await, keep a payload 1 BOM, fail bad records in queue order

Bugfixer 2a14ef4541197
diff --git a/src/lib/e2e/noise.ts b/src/lib/e2e/noise.ts
index e80ae75371..34f8288162 100644
--- a/src/lib/e2e/noise.ts
+++ b/src/lib/e2e/noise.ts
@@ -199,23 +199,23 @@ export class RecordCipher {
async seal(plaintext: Bytes): Promise<Bytes> {
if (plaintext.length > MAX_RECORD_PLAINTEXT) throw new NoiseError("record_too_large");
- return this.#state.encryptWithAd(EMPTY, plaintext);
+ return this.#state.encryptWithAd(EMPTY, new Uint8Array(plaintext));
}
/** 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 bytes = record.length > MAX_RECORD_BYTES ? null : new Uint8Array(record);
- const opened = this.#opening.then(() => this.#openNext(bytes));
+ const copy = copyRecord(record);
+ const opened = this.#opening.then(() => this.#openNext(copy));
this.#opening = opened.catch(() => undefined);
return opened;
}
- /** `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> {
+ /** `record` is the caller's bytes copied at the call, or why they could not be copied. */
+ async #openNext(record: Bytes | NoiseError): Promise<Bytes> {
if (this.#failed) throw new NoiseError("failed");
try {
- if (!record) throw new NoiseError("record_too_large");
+ if (record instanceof NoiseError) throw record;
return await this.#state.decryptWithAd(EMPTY, record);
} catch (error) {
this.#failed = true;
@@ -224,6 +224,16 @@ export class RecordCipher {
}
}
+/** A failed copy (too large, or a detached buffer) is returned, not thrown, so it fails in its place in the queue. */
+function copyRecord(record: Bytes): Bytes | NoiseError {
+ if (record.length > MAX_RECORD_BYTES) return new NoiseError("record_too_large");
+ try {
+ return new Uint8Array(record);
+ } catch {
+ return new NoiseError("bad_record");
+ }
+}
+
export interface SessionKeys {
send: RecordCipher;
receive: RecordCipher;
@@ -243,7 +253,8 @@ export function encodePayload1(conn: Bytes, app: string): Bytes {
const parseJson = (bytes: Bytes): unknown => {
try {
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
+ // ignoreBOM keeps a leading BOM, which JSON.parse refuses, as the computer side does.
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes));
} catch {
return null;
}
@@ -283,22 +294,27 @@ export interface PhoneHello {
finish(message2: Bytes): Promise<SessionKeys>;
}
-/** `payload1` is exact bytes so vectors can pin them, read once at the call; message 2 must echo its `conn`. */
+/** `payload1` is exact bytes so vectors can pin them; it and every option are read once at the call, before the
+ * first await. Message 2 must echo payload 1's `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 pinned = new Uint8Array(options.remoteStatic);
+ const pskBytes = new Uint8Array(options.psk);
+ const { transport, trace, ephemeral } = options;
+ const fixedEphemeral = ephemeral && { privateKey: ephemeral.privateKey, publicKey: new Uint8Array(ephemeral.publicKey) };
const conn = payload1Conn(payload1);
- const remoteStatic = await publicKey(options.remoteStatic);
- if (options.psk.length !== 32) throw new NoiseError("bad_psk");
- const state = new SymmetricState(options.trace ?? null);
+ const remoteStatic = await publicKey(pinned);
+ if (pskBytes.length !== 32) throw new NoiseError("bad_psk");
+ const state = new SymmetricState(trace ?? null);
state.mark("init");
- await state.mixHash(prologue(options.transport));
+ await state.mixHash(prologue(transport));
state.mark("prologue");
- await state.mixHash(options.remoteStatic);
+ await state.mixHash(pinned);
state.mark("s");
- await state.mixKeyAndHash(options.psk);
+ await state.mixKeyAndHash(pskBytes);
state.mark("msg1.psk");
- const e = options.ephemeral ?? (await generateKeyPair());
+ const e = fixedEphemeral ?? (await generateKeyPair());
await state.mixHash(e.publicKey);
await state.mixKey(e.publicKey);
state.mark("msg1.e");
diff --git a/src/lib/e2e/vectors.test.ts b/src/lib/e2e/vectors.test.ts
index 29f64c5a7c..c1cd162a12 100644
--- a/src/lib/e2e/vectors.test.ts
+++ b/src/lib/e2e/vectors.test.ts
@@ -169,6 +169,30 @@ describe("V6 must fail, phone side", () => {
await expect(pending).resolves.toBeDefined();
});
+ it("fails an oversized record in its place in the queue: earlier ones open, later ones are refused", async () => {
+ const keys = await v2Session();
+ const [first, second] = v.V4.records.filter((r: { direction: string }) => r.direction === "cp");
+ const results = await Promise.allSettled([
+ keys.receive.open(bytes(first.record)),
+ keys.receive.open(new Uint8Array(65_536)),
+ keys.receive.open(bytes(second.record)),
+ ]);
+ expect(results.map((r) => (r.status === "rejected" ? (r.reason as Error).message : "opened"))).toEqual(["opened", "e2e: record_too_large", "e2e: failed"]);
+ });
+
+ it("fails a record whose buffer was transferred in its place in the queue, without throwing from open", async () => {
+ const keys = await v2Session();
+ const [first, second] = v.V4.records.filter((r: { direction: string }) => r.direction === "cp");
+ const detached = bytes(second.record);
+ structuredClone(detached.buffer, { transfer: [detached.buffer] });
+ const results = await Promise.allSettled([
+ keys.receive.open(bytes(first.record)),
+ keys.receive.open(detached),
+ keys.receive.open(bytes(second.record)),
+ ]);
+ expect(results.map((r) => (r.status === "rejected" ? (r.reason as Error).message : "opened"))).toEqual(["opened", "e2e: bad_record", "e2e: failed"]);
+ });
+
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");
@@ -204,6 +228,11 @@ describe("payload 1, phone side", () => {
await expect(phoneHello({ remoteStatic: T_PUB, psk: PSKS.device, transport: 1 }, utf8(json))).rejects.toThrow("e2e: bad_payload1");
});
+ it("is refused as raw bytes with a leading UTF-8 BOM, which the computer side refuses too", async () => {
+ const withBom = Uint8Array.from([0xef, 0xbb, 0xbf, ...utf8('{"v":1,"conn":"XkCuA2LSB-yRqiCTmMwKqQ"}')]);
+ await expect(phoneHello({ remoteStatic: T_PUB, psk: PSKS.device, transport: 1 }, withBom)).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();
});
@@ -218,6 +247,28 @@ describe("payload 1, phone side", () => {
});
});
+describe("caller-owned bytes, phone side", () => {
+ it("seals the frame as it was when seal was called, even if the caller changes it afterwards", async () => {
+ const keys = await v2Session();
+ const record = v.V4.records.find((r: { direction: string }) => r.direction === "pc");
+ const frame = bytes(record.frame);
+ const pending = keys.send.seal(frame);
+ frame.fill(0);
+ expect(hex(await pending)).toBe(record.record);
+ });
+
+ it("hashes and uses the pinned key and PSK as they were when phoneHello was called", async () => {
+ const remoteStatic = T_PUB.slice();
+ const secret = PSKS.device.slice();
+ const pending = phoneHello({ remoteStatic, psk: secret, transport: 1, ephemeral: await phoneEphemeral() }, PAYLOAD1);
+ remoteStatic.fill(0);
+ secret.fill(0);
+ 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", () => {
it("are copies: clearing the returned key bytes leaves the cipher working", async () => {
const keys = await v2Session();