Skip to content

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

Harden the browser phone side after review

Bugfixer 2746a8c924629
diff --git a/src/lib/e2e/bytes.ts b/src/lib/e2e/bytes.ts
index fcf91e4031..f34d92f61f 100644
--- a/src/lib/e2e/bytes.ts
+++ b/src/lib/e2e/bytes.ts
@@ -1,6 +1,3 @@
-// Byte helpers for the browser side of the end-to-end wire (spec: companion/src/e2e/README.md), on plain typed arrays
-// so the same code runs in a page and under Node.
-
/** Backed by a plain ArrayBuffer, which is what WebCrypto takes. */
export type Bytes = Uint8Array<ArrayBuffer>;
diff --git a/src/lib/e2e/credentials.ts b/src/lib/e2e/credentials.ts
index 070c7f4e46..ced20d43f3 100644
--- a/src/lib/e2e/credentials.ts
+++ b/src/lib/e2e/credentials.ts
@@ -1,5 +1,3 @@
-// What the phone side derives from its device or pairing token, on WebCrypto. Wire spec: companion/src/e2e/README.md,
-// "Identities and derived secrets".
import { concat, utf8, type Bytes } from "./bytes.ts";
const KEY_ID_BYTES = 16;
diff --git a/src/lib/e2e/interop.test.ts b/src/lib/e2e/interop.test.ts
index e655478ab2..370da48ebc 100644
--- a/src/lib/e2e/interop.test.ts
+++ b/src/lib/e2e/interop.test.ts
@@ -3,7 +3,7 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { decodeFrame, encodeFrame, FLAG, OPEN_WINDOW_DELTA, TYPE } from "../../../companion/src/e2e/yamux.ts";
-import { b64u, concat, fromB64u, utf8, type Bytes } from "./bytes.ts";
+import { concat, fromB64u, utf8, type Bytes } from "./bytes.ts";
import { credentialHash, keyId, psk } from "./credentials.ts";
import { encodePayload1, newConn, phoneHello, TRANSPORT_DIRECT, TRANSPORT_RELAY, type SessionKeys, type TransportByte } from "./noise.ts";
@@ -23,7 +23,7 @@ let child: ChildProcess;
let ready: Ready;
beforeAll(async () => {
- child = spawn(process.execPath, [SERVER, "--port", "0"], { stdio: ["ignore", "pipe", "ignore"] });
+ child = spawn(process.execPath, [SERVER, "--port", "0", "--exit-with-stdin"], { stdio: ["pipe", "pipe", "ignore"] });
ready = await new Promise<Ready>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("interop server did not say ready in 10 s")), BOUND_MS);
let out = "";
@@ -49,31 +49,36 @@ function open(url: string) {
const socket = new WebSocket(url, "omb-e2e.v1");
socket.binaryType = "arraybuffer";
const queue: Bytes[] = [];
- const waiting: Array<(message: Bytes) => void> = [];
+ const waiting: Array<{ resolve: (message: Bytes) => void; reject: (error: Error) => void }> = [];
let closed: number | null = null;
const closeWaiters: Array<(code: number) => void> = [];
socket.addEventListener("message", (event) => {
const message = new Uint8Array(event.data as ArrayBuffer);
const next = waiting.shift();
- if (next) next(message);
+ if (next) next.resolve(message);
else queue.push(message);
});
socket.addEventListener("close", (event) => {
closed = event.code;
for (const waiter of closeWaiters.splice(0)) waiter(event.code);
+ for (const reader of waiting.splice(0)) reader.reject(new Error(`socket closed with ${event.code}`));
});
- const bounded = <T>(what: string, start: (resolve: (value: T) => void) => void) =>
- new Promise<T>((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error(`no ${what} in 10 s`)), BOUND_MS);
- start((value) => {
- clearTimeout(timer);
- resolve(value);
- });
- });
+ const bounded = <T>(what: string, start: (resolve: (value: T) => void, reject: (error: Error) => void) => void) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ return new Promise<T>((resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(`no ${what} in 10 s`)), BOUND_MS);
+ start(resolve, reject);
+ }).finally(() => clearTimeout(timer));
+ };
return {
opened: bounded<void>("open", (resolve) => socket.addEventListener("open", () => resolve())),
send: (bytes: Bytes) => socket.send(bytes),
- next: () => bounded<Bytes>("message", (resolve) => (queue.length ? resolve(queue.shift()!) : waiting.push(resolve))),
+ next: () =>
+ bounded<Bytes>("message", (resolve, reject) => {
+ if (queue.length) resolve(queue.shift()!);
+ else if (closed !== null) reject(new Error(`socket closed with ${closed}`));
+ else waiting.push({ resolve, reject });
+ }),
closedWith: () => bounded<number>("close", (resolve) => (closed !== null ? resolve(closed) : closeWaiters.push(resolve))),
close: () => socket.close(),
};
@@ -81,8 +86,7 @@ function open(url: string) {
async function handshake(url: string, token: string, transport: TransportByte) {
const remoteStatic = fromB64u(ready.k)!;
- const conn = newConn();
- const hello = await phoneHello({ remoteStatic, psk: await psk(await credentialHash(token), await keyId(remoteStatic)), transport }, encodePayload1(conn, "web-test/1"), b64u(conn));
+ const hello = await phoneHello({ remoteStatic, psk: await psk(await credentialHash(token), await keyId(remoteStatic)), transport }, encodePayload1(newConn(), "web-test/1"));
const ws = open(url);
await ws.opened;
ws.send(hello.message1);
@@ -102,7 +106,8 @@ async function get(ws: ReturnType<typeof open>, keys: SessionKeys, path: string)
const frame = decodeFrame(await keys.receive.open(await ws.next()));
if (frame.streamId !== 1) continue;
if (frame.type === TYPE.data && frame.data) body.push(frame.data);
- if (frame.flags & (FLAG.fin | FLAG.rst)) return new TextDecoder().decode(concat(...body));
+ if (frame.flags & FLAG.rst) throw new Error("stream 1 was reset");
+ if (frame.flags & FLAG.fin) return new TextDecoder().decode(concat(...body));
}
}
@@ -131,7 +136,7 @@ describe("the browser phone side against the Node computer", () => {
it("stops hard on a message 2 from a party without the key", async () => {
const { ws, finish } = await handshake(ready.wrongKey, ready.deviceToken, TRANSPORT_DIRECT);
- await expect(finish()).rejects.toThrow(/^e2e: /);
+ await expect(finish()).rejects.toThrow("e2e: aead");
ws.close();
});
});
diff --git a/src/lib/e2e/noise.ts b/src/lib/e2e/noise.ts
index 33ab7c7e0f..3e1f6dd53c 100644
--- a/src/lib/e2e/noise.ts
+++ b/src/lib/e2e/noise.ts
@@ -1,6 +1,3 @@
-// The phone (initiator) side of Noise_NKpsk0_P256_AESGCM_SHA256 and the transport records after it, on WebCrypto so
-// a browser can run it. Wire spec: companion/src/e2e/README.md, "Handshake" and "Transport messages"; the Node
-// reference is companion/src/e2e/noise.ts, and both must give the bytes in vectors/v1.json.
import { b64u, concat, utf8, type Bytes } from "./bytes.ts";
import { hmacSha256, sha256 } from "./credentials.ts";
@@ -12,6 +9,7 @@ const MAX_RECORD_PLAINTEXT = MAX_RECORD_BYTES - TAG_BYTES;
export const MAX_HANDSHAKE_PAYLOAD = 512;
const MAX_HANDSHAKE_MESSAGE = PUBLIC_KEY_BYTES + MAX_HANDSHAKE_PAYLOAD + TAG_BYTES;
export const CONN_BYTES = 16;
+const MAX_APP_CHARS = 40;
/** A sender closes the session (1000) before a direction's counter reaches this. */
const NONCE_LIMIT = 2 ** 32;
@@ -189,6 +187,7 @@ class SymmetricState {
export class RecordCipher {
readonly #state: CipherState;
#failed = false;
+ #opening: Promise<unknown> = Promise.resolve();
constructor(state: CipherState) {
this.#state = state;
@@ -203,8 +202,15 @@ export class RecordCipher {
return this.#state.encryptWithAd(EMPTY, plaintext);
}
- /** Any failure is a hard stop: after one, every later record is refused too. */
- async open(record: Bytes): Promise<Bytes> {
+ /** 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));
+ this.#opening = opened.catch(() => undefined);
+ return opened;
+ }
+
+ async #openNext(record: Bytes): Promise<Bytes> {
if (this.#failed) throw new NoiseError("failed");
try {
if (record.length > MAX_RECORD_BYTES) throw new NoiseError("record_too_large");
@@ -227,18 +233,31 @@ export interface SessionKeys {
export const newConn = (): Bytes => crypto.getRandomValues(new Uint8Array(CONN_BYTES));
-export const encodePayload1 = (conn: Bytes, app: string): Bytes => utf8(JSON.stringify({ v: 1, conn: b64u(conn), app }));
+export function encodePayload1(conn: Bytes, app: string): Bytes {
+ if (conn.length !== CONN_BYTES) throw new NoiseError("bad_conn");
+ if (app.length > MAX_APP_CHARS) throw new NoiseError("app_too_long");
+ return utf8(JSON.stringify({ v: 1, conn: b64u(conn), app }));
+}
+
+const parseJson = (bytes: Bytes): unknown => {
+ try {
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
+ } catch {
+ return null;
+ }
+};
+
+/** The `conn` that message 2 must echo, read from the payload 1 bytes actually sent. */
+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");
+ return conn;
+}
/** Key order and whitespace are free; `v` and `conn` are not. */
function checkPayload2(bytes: Bytes, conn: string): "ok" | "version" | "conn" {
- let value: unknown = null;
- if (bytes.length <= MAX_HANDSHAKE_PAYLOAD) {
- try {
- value = JSON.parse(new TextDecoder().decode(bytes));
- } catch {
- value = null;
- }
- }
+ const value = bytes.length <= MAX_HANDSHAKE_PAYLOAD ? parseJson(bytes) : null;
if (!value || typeof value !== "object" || Array.isArray(value) || (value as { v?: unknown }).v !== 1) return "version";
return (value as { conn?: unknown }).conn === conn ? "ok" : "conn";
}
@@ -259,11 +278,12 @@ export interface PhoneHello {
finish(message2: Bytes): Promise<SessionKeys>;
}
-/** `payload1` is exact bytes so vectors can pin them; `conn` (b64u) is what message 2 must echo. */
-export async function phoneHello(options: PhoneHandshakeOptions, payload1: Bytes, conn: string): Promise<PhoneHello> {
+/** `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> {
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));
@@ -283,9 +303,10 @@ export async function phoneHello(options: PhoneHandshakeOptions, payload1: Bytes
let done = false;
return {
message1,
- async finish(message2) {
+ async 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");
const re = message2.subarray(0, PUBLIC_KEY_BYTES);
const ee = await dh(e.privateKey, await publicKey(re));
@@ -299,7 +320,13 @@ export async function phoneHello(options: PhoneHandshakeOptions, payload1: Bytes
const check = checkPayload2(payload2, conn);
if (check !== "ok") throw new NoiseError(`payload2_${check}`);
const [kPc, kCp] = await hkdf(state.ck, EMPTY, 2);
- return { send: new RecordCipher(new CipherState(kPc)), receive: new RecordCipher(new CipherState(kCp)), handshakeHash: state.h, kPc, kCp };
+ return {
+ send: new RecordCipher(new CipherState(kPc)),
+ receive: new RecordCipher(new CipherState(kCp)),
+ handshakeHash: state.h,
+ kPc: kPc.slice(),
+ kCp: kCp.slice(),
+ };
},
};
}
diff --git a/src/lib/e2e/vectors.test.ts b/src/lib/e2e/vectors.test.ts
index e32d501242..307d26d01f 100644
--- a/src/lib/e2e/vectors.test.ts
+++ b/src/lib/e2e/vectors.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest";
import { b64u, fromB64u, utf8, type Bytes } from "./bytes.ts";
import { admission, credentialHash, keyId, psk } from "./credentials.ts";
-import { importKeyPair, isPublicKey, phoneHello, prologue, type SessionKeys, type TraceStep, type TransportByte } from "./noise.ts";
+import { CONN_BYTES, encodePayload1, importKeyPair, isPublicKey, phoneHello, prologue, type SessionKeys, type TraceStep, type TransportByte } from "./noise.ts";
const VECTORS = new URL("../../../companion/src/e2e/vectors/", import.meta.url);
const text = readFileSync(new URL("v1.json", VECTORS), "utf8");
@@ -20,7 +20,7 @@ const PAYLOAD1 = utf8(v.inputs.payload1);
const phoneEphemeral = () => importKeyPair(bytes(v.inputs.phoneEphemeralPrivate), bytes(v.V1.phoneEphemeralPublic));
async function phone(transport: TransportByte, pskName: string, trace?: TraceStep[]) {
- return phoneHello({ remoteStatic: T_PUB, psk: PSKS[pskName], transport, ephemeral: await phoneEphemeral(), trace }, PAYLOAD1, v.inputs.connB64u);
+ return phoneHello({ remoteStatic: T_PUB, psk: PSKS[pskName], transport, ephemeral: await phoneEphemeral(), trace }, PAYLOAD1);
}
async function v2Session(): Promise<SessionKeys> {
@@ -151,4 +151,37 @@ describe("V6 must fail, phone side", () => {
await hello.finish(bytes(v.V2.message2));
await expect(hello.finish(bytes(v.V2.message2))).rejects.toThrow("e2e: finished");
});
+
+ 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");
+ const forged = bytes(first.record);
+ forged[0] ^= 1;
+ const results = await Promise.allSettled([keys.receive.open(forged), keys.receive.open(bytes(second.record))]);
+ expect(results.map((r) => (r.status === "rejected" ? (r.reason as Error).message : "opened"))).toEqual(["e2e: aead", "e2e: failed"]);
+ });
+});
+
+describe("payload 1, phone side", () => {
+ it("is refused with a connection ID that is not 16 bytes", () => {
+ expect(() => encodePayload1(new Uint8Array(CONN_BYTES - 1), "web/1")).toThrow("e2e: bad_conn");
+ });
+
+ it("takes an app of up to 40 characters", () => {
+ expect(() => encodePayload1(new Uint8Array(CONN_BYTES), "a".repeat(40))).not.toThrow();
+ expect(() => encodePayload1(new Uint8Array(CONN_BYTES), "a".repeat(41))).toThrow("e2e: app_too_long");
+ });
+
+ 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");
+ });
+});
+
+describe("the session keys", () => {
+ it("are copies: clearing the returned key bytes leaves the cipher working", async () => {
+ const keys = await v2Session();
+ keys.kPc.fill(0);
+ const record = v.V4.records.find((r: { direction: string }) => r.direction === "pc");
+ expect(hex(await keys.send.seal(bytes(record.frame)))).toBe(record.record);
+ });
});