Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 513766c25a test(relay): cover repeated protected handshake replies
Repeat the real client hello over the relay and identify the repeated ready by its exact text. This keeps the binary framing assertion focused on application records.
2026-12-05 07:17:36 +01:00
Mohamed Boudra 0d7d002315 perf(relay): send ProtectedChannel text records as binary frames 2026-12-05 07:09:20 +01:00
4 changed files with 254 additions and 16 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ wire record = (u16 BE ciphertextLength || ciphertext)+
The receiver rejects a record whose metadata disagrees between chunks, whose non-final chunks are not full, whose byte total differs from `totalLength`, or that has zero chunks, trailing bytes, reserved flags, or an invalid kind. Partial plaintext never reaches the application. Transport AD is empty, as the Noise spec writes it; framing authenticity comes from the metadata being inside the ciphertext. `packages/relay/src/protected-records.ts` owns this.
Frame kind is preserved on the wire the same way as legacy: text records are base64 WebSocket text, binary records are WebSocket binary when `binaryCiphertext` was negotiated.
When `binaryCiphertext` is negotiated, both text and binary records travel as WebSocket binary frames, because the authenticated `kind` byte inside the record carries the frame kind. Base64 WebSocket text records remain accepted on receive for older peers and when `binaryCiphertext` is not negotiated.
## Retries and failures
+207 -8
View File
@@ -12,7 +12,13 @@ import {
type TransportMessage,
} from "./encrypted-channel.js";
import { exportPublicKey, generateKeyPair } from "./crypto.js";
import { MAX_CHUNK_DATA_BYTES } from "./protected-records.js";
import { createNoiseInitiator } from "./noise/index.js";
import {
decodeProtectedRecord,
encodeProtectedRecord,
MAX_CHUNK_DATA_BYTES,
protectedRecordByteLength,
} from "./protected-records.js";
interface Frame {
data: string | ArrayBuffer;
@@ -159,16 +165,209 @@ describe("secure channel: protected mode", () => {
expect(new Uint8Array(pair.clientReceived[1] as ArrayBuffer)).toEqual(new Uint8Array(bytes(7)));
});
it("keeps text as base64 text frames and binary as binary frames when negotiated", async () => {
it("sends both text and binary records as binary frames without base64 overhead when negotiated", async () => {
const pair = await openProtectedPair();
pair.link.recordedToDaemon.length = 0;
await pair.client.send("text");
await pair.client.send(bytes(3));
pair.link.recordedToClient.length = 0;
const jsonText = JSON.stringify({
type: "session",
message: { text: "héllo ".repeat(200) },
});
const textBytes = new TextEncoder().encode(jsonText).byteLength;
const expectedTextWireBytes = protectedRecordByteLength(textBytes);
const legacyBase64WireBytes = 4 * Math.ceil(expectedTextWireBytes / 3);
const binaryPayload = bytes(3);
const expectedBinaryWireBytes = protectedRecordByteLength(binaryPayload.byteLength);
await pair.client.send(jsonText);
await pair.client.send(binaryPayload);
await pair.daemon.send(jsonText);
await pair.daemon.send(binaryPayload);
await settle();
expect(pair.link.recordedToDaemon.map((frame) => frame.isBinary)).toEqual([false, true]);
expect(pair.link.recordedToDaemon[0].data).not.toContain("text");
expect(pair.client.outboundWireByteLength(bytes(3))).toBe(3 + 2 + 6 + 16);
expect(pair.client.outboundWireByteLength("text")).toBe(4 * Math.ceil((4 + 24) / 3));
expect(pair.link.recordedToDaemon.map((frame) => frame.isBinary)).toEqual([true, true]);
expect(pair.link.recordedToClient.map((frame) => frame.isBinary)).toEqual([true, true]);
const clientTextWire = pair.link.recordedToDaemon[0].data as ArrayBuffer;
const daemonTextWire = pair.link.recordedToClient[0].data as ArrayBuffer;
expect(clientTextWire).toBeInstanceOf(ArrayBuffer);
expect(daemonTextWire).toBeInstanceOf(ArrayBuffer);
expect(clientTextWire.byteLength).toBe(expectedTextWireBytes);
expect(daemonTextWire.byteLength).toBe(expectedTextWireBytes);
expect(clientTextWire.byteLength).toBeLessThan(legacyBase64WireBytes * 0.76);
expect(Buffer.from(clientTextWire).toString("utf8")).not.toContain("héllo");
expect(pair.client.outboundWireByteLength(jsonText)).toBe(expectedTextWireBytes);
expect(pair.daemon.outboundWireByteLength(jsonText)).toBe(expectedTextWireBytes);
expect(pair.client.outboundWireByteLength(binaryPayload)).toBe(expectedBinaryWireBytes);
expect(pair.daemon.outboundWireByteLength(binaryPayload)).toBe(expectedBinaryWireBytes);
expect(pair.daemonReceived[0]).toBe(jsonText);
expect(new Uint8Array(pair.daemonReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(binaryPayload),
);
expect(pair.clientReceived[0]).toBe(jsonText);
expect(new Uint8Array(pair.clientReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(binaryPayload),
);
});
it("interoperates with older peers sending base64 text frames in both directions", async () => {
const toBase64TextFrame = (frame: Frame): Frame => {
if (!frame.isBinary) return frame;
return {
data: Buffer.from(frame.data as ArrayBuffer).toString("base64"),
isBinary: false,
};
};
// Old client (base64 text frames for text, binary for binary) <-> New daemon (binary for both).
const oldClientPair = await openProtectedPair();
oldClientPair.link.recordedToDaemon.length = 0;
oldClientPair.link.recordedToClient.length = 0;
let clientSentCount = 0;
oldClientPair.link.setToDaemon((frame) => {
clientSentCount += 1;
// Convert text frames (#1 and #3) to v0.13-v0.19 base64 text wire format; keep binary (#2) binary.
return clientSentCount === 2 ? frame : toBase64TextFrame(frame);
});
const largeText = "a".repeat(MAX_CHUNK_DATA_BYTES + 123);
await oldClientPair.client.send("from old client");
await oldClientPair.client.send(bytes(9));
await oldClientPair.client.send(largeText);
await oldClientPair.daemon.send("from new daemon");
await oldClientPair.daemon.send(bytes(11));
await settle(100);
expect(oldClientPair.link.recordedToClient.map((f) => f.isBinary)).toEqual([true, true]);
expect(oldClientPair.daemonReceived[0]).toBe("from old client");
expect(new Uint8Array(oldClientPair.daemonReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(9)),
);
expect(oldClientPair.daemonReceived[2]).toBe(largeText);
expect(oldClientPair.clientReceived[0]).toBe("from new daemon");
expect(new Uint8Array(oldClientPair.clientReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(11)),
);
// New client (binary for both) <-> Old daemon (base64 text frames for text, binary for binary).
const oldDaemonPair = await openProtectedPair();
oldDaemonPair.link.recordedToDaemon.length = 0;
oldDaemonPair.link.recordedToClient.length = 0;
let daemonSentCount = 0;
oldDaemonPair.link.setToClient((frame) => {
daemonSentCount += 1;
return daemonSentCount === 2 ? frame : toBase64TextFrame(frame);
});
await oldDaemonPair.client.send("from new client");
await oldDaemonPair.client.send(bytes(6));
await oldDaemonPair.daemon.send("from old daemon");
await oldDaemonPair.daemon.send(bytes(8));
await oldDaemonPair.daemon.send(largeText);
await settle(100);
expect(oldDaemonPair.link.recordedToDaemon.map((f) => f.isBinary)).toEqual([true, true]);
expect(oldDaemonPair.daemonReceived[0]).toBe("from new client");
expect(new Uint8Array(oldDaemonPair.daemonReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(6)),
);
expect(oldDaemonPair.clientReceived[0]).toBe("from old daemon");
expect(new Uint8Array(oldDaemonPair.clientReceived[1] as ArrayBuffer)).toEqual(
new Uint8Array(bytes(8)),
);
expect(oldDaemonPair.clientReceived[2]).toBe(largeText);
});
it("falls back to base64 text frames when a peer negotiates binaryCiphertext=false", async () => {
const link = createLink();
const daemonKeyPair = generateKeyPair();
const daemonReceived: Array<string | ArrayBuffer> = [];
const daemonPromise = openDaemonSecureChannel(link.daemon, {
daemonKeyPair,
events: { onmessage: (data) => daemonReceived.push(data) },
});
const prologue = new TextEncoder().encode("paseo-relay-e2ee/1");
const initiator = createNoiseInitiator({
remoteStatic: daemonKeyPair.publicKey,
prologue,
});
const msg1 = initiator.writeMessage(new Uint8Array([0x01, 0x00]));
const legacyKeyPair = generateKeyPair();
const hello = JSON.stringify({
type: "e2ee_hello",
key: exportPublicKey(legacyKeyPair.publicKey),
protected: { v: 1, message: Buffer.from(msg1).toString("base64") },
});
const readyPromise = new Promise<string>((resolve) => {
Object.assign(link.client, {
onmessage: (message: TransportMessage) => {
if (!message.isBinary && typeof message.data === "string") {
resolve(message.data);
}
},
});
});
link.client.send(hello);
const readyText = await readyPromise;
const daemon = await daemonPromise;
const ready = JSON.parse(readyText) as { protected: { v: number; message: string } };
const selectedPayload = initiator.readMessage(
new Uint8Array(Buffer.from(ready.protected.message, "base64")),
);
expect(selectedPayload).toEqual(new Uint8Array([0x01, 0x00]));
const { send: clientSend, receive: clientReceive } = initiator.split();
const daemonWireFrames: Frame[] = [];
Object.assign(link.client, {
onmessage: (message: TransportMessage) => {
daemonWireFrames.push({ data: message.data, isBinary: message.isBinary });
},
});
const textPayload = "base64 fallback text";
const binaryPayload = bytes(5);
await daemon.send(textPayload);
await daemon.send(binaryPayload);
await settle();
expect(daemonWireFrames.map((f) => f.isBinary)).toEqual([false, false]);
expect(daemon.outboundWireByteLength(textPayload)).toBe(
4 *
Math.ceil(protectedRecordByteLength(new TextEncoder().encode(textPayload).byteLength) / 3),
);
expect(daemon.outboundWireByteLength(binaryPayload)).toBe(
4 * Math.ceil(protectedRecordByteLength(binaryPayload.byteLength) / 3),
);
const decodedText = decodeProtectedRecord(
new Uint8Array(Buffer.from(daemonWireFrames[0].data as string, "base64")),
clientReceive,
);
expect(decodedText.kind).toBe("text");
expect(new TextDecoder().decode(decodedText.data)).toBe(textPayload);
const decodedBinary = decodeProtectedRecord(
new Uint8Array(Buffer.from(daemonWireFrames[1].data as string, "base64")),
clientReceive,
);
expect(decodedBinary.kind).toBe("binary");
expect(decodedBinary.data).toEqual(new Uint8Array(binaryPayload));
// Daemon still accepts base64-encoded records from the client.
const clientRecord = encodeProtectedRecord(
"text",
new TextEncoder().encode("client fallback"),
clientSend,
);
link.client.send(Buffer.from(clientRecord).toString("base64"));
await settle();
expect(daemonReceived).toEqual(["client fallback"]);
});
it("carries frames larger than one Noise message", async () => {
+2 -2
View File
@@ -653,7 +653,7 @@ class ProtectedChannel implements InnerChannel {
this.fail(this.role.failureCloseCode, err.message);
throw err;
}
if (this.params.binaryCiphertext && kind === "binary") {
if (this.params.binaryCiphertext) {
await this.transport.send(toArrayBuffer(wire));
return;
}
@@ -663,7 +663,7 @@ class ProtectedChannel implements InnerChannel {
outboundWireByteLength(data: string | ArrayBuffer): number {
const plaintextBytes = typeof data === "string" ? utf8ByteLength(data) : data.byteLength;
const wireBytes = protectedRecordByteLength(plaintextBytes);
if (this.params.binaryCiphertext && typeof data !== "string") return wireBytes;
if (this.params.binaryCiphertext) return wireBytes;
return 4 * Math.ceil(wireBytes / 3);
}
@@ -114,6 +114,9 @@ async function openUpdatedRelayClient(args: {
channel: SecureChannel;
serverInfo: { features?: Record<string, unknown> };
messages: unknown[];
wireOutbound: Array<{ isBinary: boolean; byteLength: number }>;
wireInbound: Array<{ isBinary: boolean; text: string | null }>;
retryHello: () => void;
waitFor: (predicate: (message: unknown) => boolean) => Promise<unknown>;
close: () => void;
}> {
@@ -125,8 +128,18 @@ async function openUpdatedRelayClient(args: {
role: "client",
}),
);
const wireOutbound: Array<{ isBinary: boolean; byteLength: number }> = [];
const wireInbound: Array<{ isBinary: boolean; text: string | null }> = [];
let helloText: string | undefined;
const transport: Transport = {
send: (data) => ws.send(data),
send: (data) => {
if (typeof data === "string") helloText ??= data;
wireOutbound.push({
isBinary: typeof data !== "string",
byteLength: typeof data === "string" ? Buffer.byteLength(data, "utf8") : data.byteLength,
});
ws.send(data);
},
close: (code?: number, reason?: string) => ws.close(code, reason),
onmessage: null,
onclose: null,
@@ -134,10 +147,10 @@ async function openUpdatedRelayClient(args: {
};
ws.on("message", (data, isBinary) => {
const buffer = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data as Buffer);
const text = isBinary ? null : buffer.toString("utf8");
wireInbound.push({ isBinary, text });
transport.onmessage?.({
data: isBinary
? buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
: buffer.toString("utf8"),
data: text ?? buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength),
isBinary,
});
});
@@ -202,6 +215,12 @@ async function openUpdatedRelayClient(args: {
channel,
serverInfo: serverInfoMessage.message.payload,
messages,
wireOutbound,
wireInbound,
retryHello: () => {
if (helloText === undefined) throw new Error("Missing relay handshake hello");
transport.send(helloText);
},
waitFor,
close: () => ws.close(),
};
@@ -987,11 +1006,31 @@ async function waitForCapturedLog(
expect(client.channel.securityMode()).toBe("protected");
expect(client.serverInfo.features?.relayProtectedSecurity).toBe(true);
await client.channel.send(JSON.stringify({ type: "ping" }));
const pingPayload = JSON.stringify({ type: "ping" });
const inboundBeforeRetry = client.wireInbound.length;
client.retryHello();
const outboundBeforePing = client.wireOutbound.length;
await client.channel.send(pingPayload);
const pong = await client.waitFor(
(message) => (message as { type?: string }).type === "pong",
);
expect(pong).toEqual({ type: "pong" });
// Handshake frames (e2ee_hello / e2ee_ready) are text; every protected
// application JSON frame (hello, server_info, ping, pong) crosses as binary.
expect(client.wireOutbound[0]?.isBinary).toBe(false);
const readyText = client.wireInbound[0]?.text;
if (readyText == null) throw new Error("Missing text relay handshake ready");
expect(JSON.parse(readyText)).toMatchObject({ type: "e2ee_ready" });
expect(client.wireInbound.slice(inboundBeforeRetry)).toContainEqual({
isBinary: false,
text: readyText,
});
const pingWire = client.wireOutbound[outboundBeforePing];
expect(pingWire?.isBinary).toBe(true);
expect(pingWire?.byteLength).toBe(client.channel.outboundWireByteLength(pingPayload));
const applicationFrames = client.wireInbound.filter((frame) => frame.text !== readyText);
expect(applicationFrames.length).toBeGreaterThanOrEqual(2);
expect(applicationFrames.every((frame) => frame.isBinary)).toBe(true);
await waitForCapturedLog(
lines,
(line) => line.includes('"securityMode":"protected"'),