Skip to content

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

Add the phone side of the end-to-end session on WebCrypto

Bugfixer 26a9867ec16ba
diff --git a/src/lib/e2e/bytes.ts b/src/lib/e2e/bytes.ts
new file mode 100644
index 0000000000..fcf91e4031
--- /dev/null
+++ b/src/lib/e2e/bytes.ts
@@ -0,0 +1,34 @@
+// 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>;
+
+const B64U = /^[A-Za-z0-9_-]*$/;
+
+export const utf8 = (text: string): Bytes => new TextEncoder().encode(text);
+
+export function concat(...parts: Uint8Array[]): Bytes {
+ const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
+ let offset = 0;
+ for (const part of parts) {
+ out.set(part, offset);
+ offset += part.length;
+ }
+ return out;
+}
+
+export function b64u(bytes: Uint8Array): string {
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+/** Strict: unpadded URL-safe alphabet only, and canonical (re-encoding gives the same text), so two spellings
+ * never mean one value. */
+export function fromB64u(text: string): Bytes | null {
+ if (!B64U.test(text) || text.length % 4 === 1) return null;
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
+ return b64u(bytes) === text ? bytes : null;
+}
diff --git a/src/lib/e2e/credentials.ts b/src/lib/e2e/credentials.ts
new file mode 100644
index 0000000000..070c7f4e46
--- /dev/null
+++ b/src/lib/e2e/credentials.ts
@@ -0,0 +1,29 @@
+// 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;
+
+const PSK_LABEL = utf8("omb-e2e psk v1");
+const ADMISSION_LABEL = utf8("omb-relay admission v1");
+
+export async function sha256(bytes: Bytes): Promise<Bytes> {
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
+}
+
+export async function hmacSha256(key: Bytes, message: Bytes): Promise<Bytes> {
+ const hmacKey = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ return new Uint8Array(await crypto.subtle.sign("HMAC", hmacKey, message));
+}
+
+/** `SHA256(cred)` of the token's UTF-8 bytes. */
+export const credentialHash = (token: string): Promise<Bytes> => sha256(utf8(token));
+
+export const keyId = async (transportPublicKey: Bytes): Promise<Bytes> =>
+ (await sha256(transportPublicKey)).subarray(0, KEY_ID_BYTES);
+
+export const psk = (credHash: Bytes, transportKeyId: Bytes): Promise<Bytes> =>
+ hmacSha256(credHash, concat(PSK_LABEL, transportKeyId));
+
+export const admission = (credHash: Bytes, hostId: Bytes): Promise<Bytes> =>
+ hmacSha256(credHash, concat(ADMISSION_LABEL, hostId));
diff --git a/src/lib/e2e/interop.test.ts b/src/lib/e2e/interop.test.ts
new file mode 100644
index 0000000000..e655478ab2
--- /dev/null
+++ b/src/lib/e2e/interop.test.ts
@@ -0,0 +1,137 @@
+import { spawn, type ChildProcess } from "node:child_process";
+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 { credentialHash, keyId, psk } from "./credentials.ts";
+import { encodePayload1, newConn, phoneHello, TRANSPORT_DIRECT, TRANSPORT_RELAY, type SessionKeys, type TransportByte } from "./noise.ts";
+
+const SERVER = fileURLToPath(new URL("../../../companion/src/e2e/interop-server.ts", import.meta.url));
+const BOUND_MS = 10_000;
+
+interface Ready {
+ direct: string;
+ relayTransport: string;
+ wrongKey: string;
+ k: string;
+ deviceToken: string;
+ pairingToken: string;
+}
+
+let child: ChildProcess;
+let ready: Ready;
+
+beforeAll(async () => {
+ child = spawn(process.execPath, [SERVER, "--port", "0"], { stdio: ["ignore", "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 = "";
+ 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) as Ready);
+ }
+ });
+ child.once("error", reject);
+ child.once("exit", (code) => reject(new Error(`interop server exited ${code}`)));
+ });
+});
+
+afterAll(() => {
+ child?.kill("SIGTERM");
+});
+
+/** A WebSocket's binary messages as a queue, each wait bounded. */
+function open(url: string) {
+ const socket = new WebSocket(url, "omb-e2e.v1");
+ socket.binaryType = "arraybuffer";
+ const queue: Bytes[] = [];
+ const waiting: Array<(message: Bytes) => 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);
+ else queue.push(message);
+ });
+ socket.addEventListener("close", (event) => {
+ closed = event.code;
+ for (const waiter of closeWaiters.splice(0)) waiter(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);
+ });
+ });
+ 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))),
+ closedWith: () => bounded<number>("close", (resolve) => (closed !== null ? resolve(closed) : closeWaiters.push(resolve))),
+ close: () => socket.close(),
+ };
+}
+
+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 ws = open(url);
+ await ws.opened;
+ ws.send(hello.message1);
+ return { ws, finish: async () => hello.finish(await ws.next()) };
+}
+
+/** One HTTP request on stream 1, read until the origin closes the stream. */
+async function get(ws: ReturnType<typeof open>, keys: SessionKeys, path: string): Promise<string> {
+ const request = utf8(`GET ${path} HTTP/1.1\r\nHost: companion\r\nConnection: close\r\n\r\n`);
+ const sealed = await Promise.all([
+ keys.send.seal(new Uint8Array(encodeFrame({ type: TYPE.windowUpdate, flags: FLAG.syn, streamId: 1, length: OPEN_WINDOW_DELTA }))),
+ keys.send.seal(new Uint8Array(encodeFrame({ type: TYPE.data, flags: 0, streamId: 1, length: request.length, data: request }))),
+ ]);
+ for (const record of sealed) ws.send(record);
+ const body: Uint8Array[] = [];
+ for (;;) {
+ 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));
+ }
+}
+
+describe("the browser phone side against the Node computer", () => {
+ it.each([
+ ["direct, device token", () => ready.direct, () => ready.deviceToken, TRANSPORT_DIRECT],
+ ["relay prologue, pairing token", () => ready.relayTransport, () => ready.pairingToken, TRANSPORT_RELAY],
+ ] as const)("%s: handshakes and carries a request both ways", async (_name, url, token, transport) => {
+ const { ws, finish } = await handshake(url(), token(), transport);
+ const keys = await finish();
+ const reply = await get(ws, keys, "/api/health");
+ expect(reply.startsWith("HTTP/1.1 200")).toBe(true);
+ expect(reply).toContain('{"ok":true}');
+ ws.close();
+ });
+
+ 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);
+ });
+
+ 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);
+ });
+
+ 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: /);
+ ws.close();
+ });
+});
diff --git a/src/lib/e2e/noise.ts b/src/lib/e2e/noise.ts
new file mode 100644
index 0000000000..33ab7c7e0f
--- /dev/null
+++ b/src/lib/e2e/noise.ts
@@ -0,0 +1,305 @@
+// 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";
+
+const PROTOCOL_NAME = "Noise_NKpsk0_P256_AESGCM_SHA256";
+export const PUBLIC_KEY_BYTES = 65;
+export const TAG_BYTES = 16;
+export const MAX_RECORD_BYTES = 65_535;
+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;
+/** A sender closes the session (1000) before a direction's counter reaches this. */
+const NONCE_LIMIT = 2 ** 32;
+
+export const TRANSPORT_RELAY = 0x01;
+export const TRANSPORT_DIRECT = 0x02;
+export type TransportByte = typeof TRANSPORT_RELAY | typeof TRANSPORT_DIRECT;
+
+/** Every handshake or record failure. The reason is for tests and local logs; it never goes on the wire. */
+export class NoiseError extends Error {
+ readonly reason: string;
+ constructor(reason: string) {
+ super(`e2e: ${reason}`);
+ this.reason = reason;
+ }
+}
+
+const EC = { name: "ECDH", namedCurve: "P-256" } as const;
+const EMPTY = new Uint8Array(0);
+const hex = (bytes: Bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
+
+export const prologue = (transport: TransportByte): Bytes => concat(utf8("omb-e2e/1"), Uint8Array.of(0x00, transport));
+
+export interface KeyPair {
+ privateKey: CryptoKey;
+ /** 65 bytes, uncompressed. */
+ publicKey: Bytes;
+}
+
+/** The private half can't be exported. */
+export async function generateKeyPair(): Promise<KeyPair> {
+ const pair = await crypto.subtle.generateKey(EC, false, ["deriveBits"]);
+ return { privateKey: pair.privateKey, publicKey: new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)) };
+}
+
+/** A fixed key pair, for the vectors: WebCrypto takes a bare scalar only with its public point. */
+export async function importKeyPair(privateKey: Bytes, publicKey: Bytes): Promise<KeyPair> {
+ if (privateKey.length !== 32 || publicKey.length !== PUBLIC_KEY_BYTES || publicKey[0] !== 0x04) throw new NoiseError("bad_key_pair");
+ const jwk: JsonWebKey = { kty: "EC", crv: "P-256", d: b64u(privateKey), x: b64u(publicKey.subarray(1, 33)), y: b64u(publicKey.subarray(33)) };
+ return { privateKey: await crypto.subtle.importKey("jwk", jwk, EC, false, ["deriveBits"]), publicKey };
+}
+
+/** Only the 65-byte uncompressed form: WebCrypto also takes compressed points, which the wire forbids. The import
+ * refuses off-curve points and coordinates at or above p. */
+async function publicKey(bytes: Bytes): Promise<CryptoKey> {
+ if (bytes.length !== PUBLIC_KEY_BYTES || bytes[0] !== 0x04) throw new NoiseError("bad_point");
+ try {
+ return await crypto.subtle.importKey("raw", bytes, EC, false, []);
+ } catch {
+ throw new NoiseError("bad_point");
+ }
+}
+
+export const isPublicKey = (bytes: Bytes): Promise<boolean> => publicKey(bytes).then(() => true, () => false);
+
+/** The 32-byte X coordinate of the shared point. */
+async function dh(privateKey: CryptoKey, peer: CryptoKey): Promise<Bytes> {
+ return new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: peer }, privateKey, 256));
+}
+
+/** HKDF as Noise defines it: HMAC-SHA256 chained from the chaining key, which is RFC 5869 with empty info. */
+async function hkdf(chainingKey: Bytes, ikm: Bytes, outputs: 2 | 3): Promise<Bytes[]> {
+ const temp = await hmacSha256(chainingKey, ikm);
+ const out: Bytes[] = [];
+ for (let index = 1; index <= outputs; index += 1) out.push(await hmacSha256(temp, concat(out[index - 2] ?? EMPTY, Uint8Array.of(index))));
+ return out;
+}
+
+function nonceBytes(n: number): Bytes {
+ const nonce = new Uint8Array(12);
+ new DataView(nonce.buffer).setBigUint64(4, BigInt(n));
+ return nonce;
+}
+
+class CipherState {
+ readonly keyBytes: Bytes | null;
+ #key: Promise<CryptoKey> | null = null;
+ #n = 0;
+
+ constructor(key: Bytes | null = null) {
+ this.keyBytes = key;
+ }
+
+ get nonce(): number {
+ return this.#n;
+ }
+
+ /** Each call takes its counter when it is made, so records get counters in call order however the awaits
+ * resolve. A failure ends the session, so a counter spent on one is never needed again. */
+ #params(ad: Bytes): AesGcmParams {
+ if (this.#n >= NONCE_LIMIT) throw new NoiseError("nonce_exhausted");
+ return { name: "AES-GCM", iv: nonceBytes(this.#n++), additionalData: ad, tagLength: TAG_BYTES * 8 };
+ }
+
+ /** Imported on first use: most handshake keys are replaced before they encrypt anything. */
+ #aes(keyBytes: Bytes): Promise<CryptoKey> {
+ return (this.#key ??= crypto.subtle.importKey("raw", keyBytes, "AES-GCM", false, ["encrypt", "decrypt"]));
+ }
+
+ async encryptWithAd(ad: Bytes, plaintext: Bytes): Promise<Bytes> {
+ if (!this.keyBytes) return plaintext.slice();
+ const params = this.#params(ad);
+ return new Uint8Array(await crypto.subtle.encrypt(params, await this.#aes(this.keyBytes), plaintext));
+ }
+
+ async decryptWithAd(ad: Bytes, ciphertext: Bytes): Promise<Bytes> {
+ if (!this.keyBytes) return ciphertext.slice();
+ if (ciphertext.length < TAG_BYTES) throw new NoiseError("short_ciphertext");
+ const params = this.#params(ad);
+ try {
+ return new Uint8Array(await crypto.subtle.decrypt(params, await this.#aes(this.keyBytes), ciphertext));
+ } catch {
+ throw new NoiseError("aead");
+ }
+ }
+}
+
+export interface TraceStep {
+ step: string;
+ h: string;
+ ck: string;
+ /** The cipher key after this step, or null before the first MixKey. */
+ k: string | null;
+}
+
+class SymmetricState {
+ h: Bytes;
+ ck: Bytes;
+ cipher = new CipherState();
+ readonly #trace: TraceStep[] | null;
+
+ /** The protocol name is 31 bytes, so Noise pads it to 32 instead of hashing it. */
+ constructor(trace: TraceStep[] | null) {
+ this.h = new Uint8Array(32);
+ this.h.set(utf8(PROTOCOL_NAME));
+ this.ck = this.h.slice();
+ this.#trace = trace;
+ }
+
+ mark(step: string): void {
+ this.#trace?.push({ step, h: hex(this.h), ck: hex(this.ck), k: this.cipher.keyBytes ? hex(this.cipher.keyBytes) : null });
+ }
+
+ async mixHash(data: Bytes): Promise<void> {
+ this.h = await sha256(concat(this.h, data));
+ }
+
+ async mixKey(ikm: Bytes): Promise<void> {
+ const [ck, key] = await hkdf(this.ck, ikm, 2);
+ this.ck = ck;
+ this.cipher = new CipherState(key);
+ }
+
+ async mixKeyAndHash(ikm: Bytes): Promise<void> {
+ const [ck, tempH, key] = await hkdf(this.ck, ikm, 3);
+ this.ck = ck;
+ await this.mixHash(tempH);
+ this.cipher = new CipherState(key);
+ }
+
+ async encryptAndHash(plaintext: Bytes): Promise<Bytes> {
+ const out = await this.cipher.encryptWithAd(this.h, plaintext);
+ await this.mixHash(out);
+ return out;
+ }
+
+ async decryptAndHash(ciphertext: Bytes): Promise<Bytes> {
+ const out = await this.cipher.decryptWithAd(this.h, ciphertext);
+ await this.mixHash(ciphertext);
+ return out;
+ }
+}
+
+/** One direction's records. Each binary WebSocket message after the handshake is exactly one; seal or open them in
+ * the order they go on or come off the wire. */
+export class RecordCipher {
+ readonly #state: CipherState;
+ #failed = false;
+
+ constructor(state: CipherState) {
+ this.#state = state;
+ }
+
+ get nonce(): number {
+ return this.#state.nonce;
+ }
+
+ async seal(plaintext: Bytes): Promise<Bytes> {
+ if (plaintext.length > MAX_RECORD_PLAINTEXT) throw new NoiseError("record_too_large");
+ 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> {
+ if (this.#failed) throw new NoiseError("failed");
+ try {
+ if (record.length > MAX_RECORD_BYTES) throw new NoiseError("record_too_large");
+ return await this.#state.decryptWithAd(EMPTY, record);
+ } catch (error) {
+ this.#failed = true;
+ throw error;
+ }
+ }
+}
+
+export interface SessionKeys {
+ send: RecordCipher;
+ receive: RecordCipher;
+ handshakeHash: Bytes;
+ /** For the vectors. */
+ kPc: Bytes;
+ kCp: Bytes;
+}
+
+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 }));
+
+/** 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;
+ }
+ }
+ 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";
+}
+
+export interface PhoneHandshakeOptions {
+ /** The pinned transport key `T.pub`. */
+ remoteStatic: Bytes;
+ psk: Bytes;
+ transport: TransportByte;
+ /** Fixed in tests and vectors; fresh otherwise. */
+ ephemeral?: KeyPair;
+ trace?: TraceStep[];
+}
+
+export interface PhoneHello {
+ message1: Bytes;
+ /** Rejects with a NoiseError on any failure: every one is a hard stop. */
+ 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> {
+ 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 state = new SymmetricState(options.trace ?? null);
+ state.mark("init");
+ await state.mixHash(prologue(options.transport));
+ state.mark("prologue");
+ await state.mixHash(options.remoteStatic);
+ state.mark("s");
+ await state.mixKeyAndHash(options.psk);
+ state.mark("msg1.psk");
+ const e = options.ephemeral ?? (await generateKeyPair());
+ await state.mixHash(e.publicKey);
+ await state.mixKey(e.publicKey);
+ state.mark("msg1.e");
+ await state.mixKey(await dh(e.privateKey, remoteStatic));
+ state.mark("msg1.es");
+ const message1 = concat(e.publicKey, await state.encryptAndHash(payload1));
+ state.mark("msg1.payload");
+ let done = false;
+ return {
+ message1,
+ async finish(message2) {
+ if (done) throw new NoiseError("finished");
+ done = true;
+ 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));
+ await state.mixHash(re);
+ await state.mixKey(re);
+ state.mark("msg2.e");
+ await state.mixKey(ee);
+ state.mark("msg2.ee");
+ const payload2 = await state.decryptAndHash(message2.subarray(PUBLIC_KEY_BYTES));
+ state.mark("msg2.payload");
+ 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 };
+ },
+ };
+}
diff --git a/src/lib/e2e/vectors.test.ts b/src/lib/e2e/vectors.test.ts
new file mode 100644
index 0000000000..e32d501242
--- /dev/null
+++ b/src/lib/e2e/vectors.test.ts
@@ -0,0 +1,154 @@
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+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";
+
+const VECTORS = new URL("../../../companion/src/e2e/vectors/", import.meta.url);
+const text = readFileSync(new URL("v1.json", VECTORS), "utf8");
+const v = JSON.parse(text);
+const bytes = (hex: string) => Uint8Array.from(Buffer.from(hex, "hex"));
+const hex = (data: Uint8Array) => Buffer.from(data).toString("hex");
+
+const T_PUB = bytes(v.V1.transportPublic);
+const pskOf = (name: string) => bytes(v.V1.credentials.find((c: { name: string }) => c.name === name).psk);
+const PSKS: Record<string, Bytes> = { device: pskOf("device"), pairing: pskOf("pairing") };
+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);
+}
+
+async function v2Session(): Promise<SessionKeys> {
+ const hello = await phone(1, "device");
+ return hello.finish(bytes(v.V2.message2));
+}
+
+describe("the shared vectors", () => {
+ it("are the pinned file", () => {
+ const [digest] = readFileSync(new URL("v1.sha256", VECTORS), "utf8").trim().split(/\s+/);
+ expect(createHash("sha256").update(text, "utf8").digest("hex")).toBe(digest);
+ });
+});
+
+describe("the browser modules", () => {
+ it.each(["bytes.ts", "credentials.ts", "noise.ts"])("%s uses no Node-only API", (name) => {
+ const source = readFileSync(new URL(name, import.meta.url), "utf8");
+ expect(source).not.toMatch(/from "node:|\bBuffer\b|\bprocess\./);
+ });
+});
+
+describe("V1 derivations", () => {
+ it("give keyId and every credential value", async () => {
+ expect(hex(await keyId(T_PUB))).toBe(v.V1.keyId);
+ expect(b64u(T_PUB)).toBe(v.V1.transportPublicB64u);
+ expect(v.V1.credentials.length).toBeGreaterThan(0);
+ for (const credential of v.V1.credentials) {
+ const hash = await credentialHash(credential.token);
+ expect(hex(hash)).toBe(credential.credHash);
+ expect(hex(await psk(hash, bytes(v.V1.keyId)))).toBe(credential.psk);
+ const adm = await admission(hash, bytes(v.inputs.hostId));
+ expect(hex(adm)).toBe(credential.adm);
+ expect(b64u(adm)).toBe(credential.admB64u);
+ }
+ });
+
+ it("accept only the canonical uncompressed point", async () => {
+ expect(v.V1.points.length).toBeGreaterThan(0);
+ for (const point of v.V1.points) expect(await isPublicKey(bytes(point.hex)), point.name).toBe(point.valid);
+ });
+});
+
+describe("strict b64u", () => {
+ it("round-trips and refuses padding, other alphabets and non-canonical spellings", () => {
+ expect(hex(fromB64u(v.inputs.connB64u)!)).toBe(v.inputs.conn);
+ expect(b64u(bytes(v.inputs.conn))).toBe(v.inputs.connB64u);
+ expect(fromB64u("")).toEqual(new Uint8Array(0));
+ expect(fromB64u("AA")).toEqual(new Uint8Array([0]));
+ expect(fromB64u("AAE")).toEqual(new Uint8Array([0, 1]));
+ expect(fromB64u("-_8")).toEqual(new Uint8Array([0xfb, 0xff]));
+ for (const bad of ["AA==", "AA=", "A", "AB+/", "AB c", "AB", "AAB", "AAAAA"]) expect(fromB64u(bad), bad).toBeNull();
+ });
+});
+
+describe.each([
+ ["V2", 1 as TransportByte, "device"],
+ ["V3", 2 as TransportByte, "pairing"],
+])("%s handshake, phone side", (name, transport, pskName) => {
+ const vector = v[name];
+
+ it("gives the pinned bytes and the pinned state at every step", async () => {
+ expect(hex(prologue(transport))).toBe(vector.prologue);
+ const trace: TraceStep[] = [];
+ const hello = await phone(transport, pskName, trace);
+ expect(hex(hello.message1)).toBe(vector.message1);
+ const keys = await hello.finish(bytes(vector.message2));
+ expect(trace).toEqual(vector.trace);
+ expect(hex(keys.kPc)).toBe(vector.kPc);
+ expect(hex(keys.kCp)).toBe(vector.kCp);
+ expect(hex(keys.handshakeHash)).toBe(vector.handshakeHash);
+ });
+});
+
+describe("V4 transport records, phone side", () => {
+ it("seals what the phone sends and opens what the computer sends, counter by counter", async () => {
+ const keys = await v2Session();
+ expect(v.V4.records.some((r: { direction: string }) => r.direction === "cp")).toBe(true);
+ for (const record of v.V4.records) {
+ if (record.direction === "pc") {
+ expect(keys.send.nonce).toBe(record.n);
+ expect(hex(await keys.send.seal(bytes(record.frame)))).toBe(record.record);
+ } else {
+ expect(keys.receive.nonce).toBe(record.n);
+ expect(hex(await keys.receive.open(bytes(record.record)))).toBe(record.frame);
+ }
+ }
+ });
+});
+
+describe("V6 must fail, phone side", () => {
+ const phoneCases = (v.V6.handshake as Array<{ name: string; side: string; message2: string }>).filter((c) => c.side === "phone");
+
+ it("has phone cases", () => expect(phoneCases.length).toBeGreaterThan(0));
+
+ it.each(phoneCases)("handshake: $name is a hard stop", async (c) => {
+ const hello = await phone(1, "device");
+ await expect(hello.finish(bytes(c.message2))).rejects.toThrow(/^e2e: /);
+ });
+
+ it.each((v.V6.records as Array<{ name: string; receiver: string; records: string[]; failsAt: number }>).filter((c) => c.receiver === "phone"))(
+ "record: $name",
+ async (c) => {
+ const keys = await v2Session();
+ let failedAt = -1;
+ for (const [index, record] of c.records.entries()) {
+ try {
+ await keys.receive.open(bytes(record));
+ } catch {
+ failedAt = index;
+ break;
+ }
+ }
+ expect(failedAt).toBe(c.failsAt);
+ },
+ );
+
+ it("refuses every record after a failed one, even a genuine one", async () => {
+ const keys = await v2Session();
+ const first = v.V4.records.find((r: { direction: string }) => r.direction === "cp");
+ const forged = bytes(first.record);
+ forged[0] ^= 1;
+ await expect(keys.receive.open(forged)).rejects.toThrow("e2e: aead");
+ await expect(keys.receive.open(bytes(first.record))).rejects.toThrow("e2e: failed");
+ });
+
+ it("refuses a second finish", async () => {
+ const hello = await phone(1, "device");
+ await hello.finish(bytes(v.V2.message2));
+ await expect(hello.finish(bytes(v.V2.message2))).rejects.toThrow("e2e: finished");
+ });
+});