Merge branch 'plan/e2ee' - End-to-end encryption for relay connections
Implements E2EE for relay connections only, keeping direct connections and CLI plaintext. The relay acts as a dumb byte forwarder with no access to decrypted messages. Key changes: - Daemon keypair persistence in $PASEO_HOME/daemon-keypair.json - Encrypted relay transport using ECDH P-256 + AES-256-GCM - Client-side E2EE using daemon's public key from pairing offer - WebCrypto compatibility for React Native
This commit is contained in:
@@ -53,6 +53,12 @@ import type {
|
||||
AgentSessionConfig,
|
||||
} from "../server/agent/agent-sdk-types.js";
|
||||
import { getAgentProviderDefinition } from "../server/agent/provider-manifest.js";
|
||||
import {
|
||||
createClientChannel,
|
||||
type EncryptedChannel,
|
||||
type Transport as RelayTransport,
|
||||
} from "@paseo/relay/e2ee";
|
||||
import { isRelayClientWebSocketUrl } from "../shared/daemon-endpoints.js";
|
||||
|
||||
export interface Logger {
|
||||
debug(obj: object, msg?: string): void;
|
||||
@@ -146,6 +152,10 @@ export type DaemonClientConfig = {
|
||||
transportFactory?: DaemonTransportFactory;
|
||||
webSocketFactory?: WebSocketFactory;
|
||||
logger?: Logger;
|
||||
e2ee?: {
|
||||
enabled?: boolean;
|
||||
daemonPublicKeyB64?: string;
|
||||
};
|
||||
reconnect?: {
|
||||
enabled?: boolean;
|
||||
baseDelayMs?: number;
|
||||
@@ -328,11 +338,27 @@ export class DaemonClient {
|
||||
|
||||
try {
|
||||
this.cleanupTransport();
|
||||
const transportFactory =
|
||||
const baseTransportFactory =
|
||||
this.config.transportFactory ??
|
||||
createWebSocketTransportFactory(
|
||||
this.config.webSocketFactory ?? defaultWebSocketFactory
|
||||
);
|
||||
const shouldUseRelayE2ee =
|
||||
this.config.e2ee?.enabled === true &&
|
||||
isRelayClientWebSocketUrl(this.config.url);
|
||||
|
||||
let transportFactory = baseTransportFactory;
|
||||
if (shouldUseRelayE2ee) {
|
||||
const daemonPublicKeyB64 = this.config.e2ee?.daemonPublicKeyB64;
|
||||
if (!daemonPublicKeyB64) {
|
||||
throw new Error("daemonPublicKeyB64 is required for relay E2EE");
|
||||
}
|
||||
transportFactory = createRelayE2eeTransportFactory({
|
||||
baseFactory: baseTransportFactory,
|
||||
daemonPublicKeyB64,
|
||||
logger: this.logger,
|
||||
});
|
||||
}
|
||||
const transport = transportFactory({ url: this.config.url, headers });
|
||||
this.transport = transport;
|
||||
|
||||
@@ -2549,6 +2575,202 @@ function createWebSocketTransportFactory(
|
||||
};
|
||||
}
|
||||
|
||||
function createRelayE2eeTransportFactory(args: {
|
||||
baseFactory: DaemonTransportFactory;
|
||||
daemonPublicKeyB64: string;
|
||||
logger: Logger;
|
||||
}): DaemonTransportFactory {
|
||||
return ({ url, headers }) => {
|
||||
const base = args.baseFactory({ url, headers });
|
||||
return createEncryptedTransport(base, args.daemonPublicKeyB64, args.logger);
|
||||
};
|
||||
}
|
||||
|
||||
function createEncryptedTransport(
|
||||
base: DaemonTransport,
|
||||
daemonPublicKeyB64: string,
|
||||
logger: Logger
|
||||
): DaemonTransport {
|
||||
let channel: EncryptedChannel | null = null;
|
||||
let opened = false;
|
||||
let closed = false;
|
||||
|
||||
const openHandlers = new Set<() => void>();
|
||||
const closeHandlers = new Set<(event?: unknown) => void>();
|
||||
const errorHandlers = new Set<(event?: unknown) => void>();
|
||||
const messageHandlers = new Set<(data: unknown) => void>();
|
||||
|
||||
const emitOpen = () => {
|
||||
if (opened || closed) return;
|
||||
opened = true;
|
||||
for (const handler of openHandlers) {
|
||||
try {
|
||||
handler();
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const emitClose = (event?: unknown) => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
for (const handler of closeHandlers) {
|
||||
try {
|
||||
handler(event);
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const emitError = (event?: unknown) => {
|
||||
if (closed) return;
|
||||
for (const handler of errorHandlers) {
|
||||
try {
|
||||
handler(event);
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const emitMessage = (data: unknown) => {
|
||||
if (closed) return;
|
||||
for (const handler of messageHandlers) {
|
||||
try {
|
||||
handler(data);
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const relayTransport: RelayTransport = {
|
||||
send: (data) => {
|
||||
if (typeof data === "string") {
|
||||
base.send(data);
|
||||
return;
|
||||
}
|
||||
if (data instanceof ArrayBuffer) {
|
||||
if (typeof TextDecoder !== "undefined") {
|
||||
base.send(new TextDecoder().decode(data));
|
||||
return;
|
||||
}
|
||||
if (typeof Buffer !== "undefined") {
|
||||
base.send(Buffer.from(data).toString("utf8"));
|
||||
return;
|
||||
}
|
||||
base.send(String(data));
|
||||
return;
|
||||
}
|
||||
base.send(String(data));
|
||||
},
|
||||
close: (code?: number, reason?: string) => base.close(code, reason),
|
||||
onmessage: null,
|
||||
onclose: null,
|
||||
onerror: null,
|
||||
};
|
||||
|
||||
const startHandshake = async () => {
|
||||
try {
|
||||
channel = await createClientChannel(relayTransport, daemonPublicKeyB64, {
|
||||
onopen: emitOpen,
|
||||
onmessage: (data) => emitMessage(data),
|
||||
onclose: (code, reason) => emitClose({ code, reason }),
|
||||
onerror: (error) => emitError(error),
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn({ err: error }, "relay_e2ee_handshake_failed");
|
||||
emitError(error);
|
||||
base.close(1011, "E2EE handshake failed");
|
||||
}
|
||||
};
|
||||
|
||||
base.onOpen(() => {
|
||||
void startHandshake();
|
||||
});
|
||||
base.onMessage((event) => {
|
||||
relayTransport.onmessage?.(extractRelayMessageData(event));
|
||||
});
|
||||
base.onClose((event) => {
|
||||
const record = event as { code?: number; reason?: string } | undefined;
|
||||
relayTransport.onclose?.(record?.code ?? 0, record?.reason ?? "");
|
||||
emitClose(event);
|
||||
});
|
||||
base.onError((event) => {
|
||||
relayTransport.onerror?.(
|
||||
event instanceof Error ? event : new Error(String(event))
|
||||
);
|
||||
emitError(event);
|
||||
});
|
||||
|
||||
return {
|
||||
send: (data) => {
|
||||
if (!channel) {
|
||||
throw new Error("Encrypted channel not ready");
|
||||
}
|
||||
void channel.send(data).catch((error) => {
|
||||
emitError(error);
|
||||
});
|
||||
},
|
||||
close: (code?: number, reason?: string) => {
|
||||
if (channel) {
|
||||
channel.close(code, reason);
|
||||
} else {
|
||||
base.close(code, reason);
|
||||
}
|
||||
emitClose({ code, reason });
|
||||
},
|
||||
onMessage: (handler) => {
|
||||
messageHandlers.add(handler);
|
||||
return () => messageHandlers.delete(handler);
|
||||
},
|
||||
onOpen: (handler) => {
|
||||
openHandlers.add(handler);
|
||||
if (opened) {
|
||||
try {
|
||||
handler();
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
return () => openHandlers.delete(handler);
|
||||
},
|
||||
onClose: (handler) => {
|
||||
closeHandlers.add(handler);
|
||||
if (closed) {
|
||||
try {
|
||||
handler();
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
return () => closeHandlers.delete(handler);
|
||||
},
|
||||
onError: (handler) => {
|
||||
errorHandlers.add(handler);
|
||||
return () => errorHandlers.delete(handler);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function extractRelayMessageData(event: unknown): string | ArrayBuffer {
|
||||
const raw =
|
||||
event && typeof event === "object" && "data" in event
|
||||
? (event as { data: unknown }).data
|
||||
: event;
|
||||
if (typeof raw === "string") return raw;
|
||||
if (raw instanceof ArrayBuffer) return raw;
|
||||
if (ArrayBuffer.isView(raw)) {
|
||||
const view = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||
const out = new Uint8Array(view.byteLength);
|
||||
out.set(view);
|
||||
return out.buffer;
|
||||
}
|
||||
return String(raw ?? "");
|
||||
}
|
||||
|
||||
function bindWsHandler(
|
||||
ws: WebSocketLike,
|
||||
event: "open" | "close" | "error" | "message",
|
||||
|
||||
@@ -53,6 +53,7 @@ import {
|
||||
createConnectionOfferV1,
|
||||
encodeOfferToFragmentUrl,
|
||||
} from "./connection-offer.js";
|
||||
import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js";
|
||||
import { printPairingQrIfEnabled } from "./pairing-qr.js";
|
||||
import { startRelayTransport, type RelayTransportController } from "./relay-transport.js";
|
||||
import type {
|
||||
@@ -105,6 +106,7 @@ export async function createPaseoDaemon(
|
||||
): Promise<PaseoDaemon> {
|
||||
const logger = rootLogger.child({ module: "bootstrap" });
|
||||
const connectionSessionId = randomUUID();
|
||||
const daemonKeyPair = await loadOrCreateDaemonKeyPair(config.paseoHome, logger);
|
||||
let relayTransport: RelayTransportController | null = null;
|
||||
|
||||
const staticDir = config.staticDir;
|
||||
@@ -460,13 +462,13 @@ export async function createPaseoDaemon(
|
||||
const endpoints = buildOfferEndpoints({
|
||||
listenHost: listenTarget.host,
|
||||
port: listenTarget.port,
|
||||
relayEnabled,
|
||||
relayEndpoint,
|
||||
});
|
||||
|
||||
const offer = await createConnectionOfferV1({
|
||||
sessionId: connectionSessionId,
|
||||
endpoints,
|
||||
daemonPublicKeyB64: daemonKeyPair.publicKeyB64,
|
||||
relay: relayEnabled ? { endpoint: relayEndpoint } : null,
|
||||
});
|
||||
|
||||
const url = encodeOfferToFragmentUrl({ offer, appBaseUrl });
|
||||
@@ -480,6 +482,7 @@ export async function createPaseoDaemon(
|
||||
attachSocket: (ws) => wsServer.attachExternalSocket(ws),
|
||||
relayEndpoint,
|
||||
sessionId: connectionSessionId,
|
||||
daemonKeyPair: daemonKeyPair.keyPair,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -1,28 +1,18 @@
|
||||
import os from "node:os";
|
||||
import { webcrypto } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
|
||||
export const ConnectionOfferV1Schema = z.object({
|
||||
v: z.literal(1),
|
||||
sessionId: z.string().min(1),
|
||||
endpoints: z.array(z.string().min(1)).min(1),
|
||||
daemonPublicKeyB64: z.string().min(1),
|
||||
});
|
||||
|
||||
export type ConnectionOfferV1 = z.infer<typeof ConnectionOfferV1Schema>;
|
||||
import {
|
||||
ConnectionOfferV1Schema,
|
||||
type ConnectionOfferV1,
|
||||
} from "../shared/connection-offer.js";
|
||||
|
||||
type BuildOfferEndpointsArgs = {
|
||||
listenHost: string;
|
||||
port: number;
|
||||
relayEnabled: boolean;
|
||||
relayEndpoint: string;
|
||||
};
|
||||
|
||||
export function buildOfferEndpoints({
|
||||
listenHost,
|
||||
port,
|
||||
relayEnabled,
|
||||
relayEndpoint,
|
||||
}: BuildOfferEndpointsArgs): string[] {
|
||||
const endpoints: string[] = [];
|
||||
|
||||
@@ -42,24 +32,21 @@ export function buildOfferEndpoints({
|
||||
endpoints.push(`localhost:${port}`);
|
||||
endpoints.push(`127.0.0.1:${port}`);
|
||||
|
||||
if (relayEnabled) {
|
||||
endpoints.push(relayEndpoint);
|
||||
}
|
||||
|
||||
return dedupePreserveOrder(endpoints);
|
||||
}
|
||||
|
||||
export async function createConnectionOfferV1(args: {
|
||||
sessionId: string;
|
||||
endpoints: string[];
|
||||
daemonPublicKeyB64: string;
|
||||
relay?: { endpoint: string } | null;
|
||||
}): Promise<ConnectionOfferV1> {
|
||||
const daemonPublicKeyB64 = await generateDaemonPublicKeyB64();
|
||||
|
||||
return ConnectionOfferV1Schema.parse({
|
||||
v: 1,
|
||||
sessionId: args.sessionId,
|
||||
endpoints: args.endpoints,
|
||||
daemonPublicKeyB64,
|
||||
daemonPublicKeyB64: args.daemonPublicKeyB64,
|
||||
relay: args.relay ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -90,17 +77,6 @@ function getPrimaryLanIp(): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function generateDaemonPublicKeyB64(): Promise<string> {
|
||||
const keyPair = await webcrypto.subtle.generateKey(
|
||||
{ name: "ECDH", namedCurve: "P-256" },
|
||||
true,
|
||||
["deriveBits"]
|
||||
);
|
||||
|
||||
const raw = await webcrypto.subtle.exportKey("raw", keyPair.publicKey);
|
||||
return Buffer.from(new Uint8Array(raw)).toString("base64");
|
||||
}
|
||||
|
||||
function dedupePreserveOrder(values: string[]): string[] {
|
||||
const out: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
@@ -89,6 +89,7 @@ describe("ConnectionOfferV1 (daemon E2E)", () => {
|
||||
sessionId: string;
|
||||
endpoints: string[];
|
||||
daemonPublicKeyB64: string;
|
||||
relay?: { endpoint: string } | null;
|
||||
};
|
||||
|
||||
expect(offer.v).toBe(1);
|
||||
@@ -97,7 +98,8 @@ describe("ConnectionOfferV1 (daemon E2E)", () => {
|
||||
expect(Array.isArray(offer.endpoints)).toBe(true);
|
||||
expect(offer.endpoints).toContain(`192.168.1.12:${daemon.port}`);
|
||||
expect(offer.endpoints).toContain(`localhost:${daemon.port}`);
|
||||
expect(offer.endpoints).toContain("relay.paseo.sh:443");
|
||||
expect(offer.endpoints).not.toContain("relay.paseo.sh:443");
|
||||
expect(offer.relay?.endpoint).toBe("relay.paseo.sh:443");
|
||||
expect(typeof offer.daemonPublicKeyB64).toBe("string");
|
||||
expect(offer.daemonPublicKeyB64.length).toBeGreaterThan(0);
|
||||
expect(() => Buffer.from(offer.daemonPublicKeyB64, "base64")).not.toThrow();
|
||||
@@ -167,9 +169,11 @@ describe("ConnectionOfferV1 (daemon E2E)", () => {
|
||||
|
||||
const offer = decodeOfferFromFragmentUrl(offerUrl) as {
|
||||
endpoints: string[];
|
||||
relay?: { endpoint: string } | null;
|
||||
};
|
||||
|
||||
expect(offer.endpoints).not.toContain("relay.paseo.sh:443");
|
||||
expect(offer.relay).toBe(null);
|
||||
expect(offer.endpoints).toContain(`localhost:${port}`);
|
||||
expect(offer.endpoints).toContain(`192.168.1.12:${port}`);
|
||||
} catch (err) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Writable } from "node:stream";
|
||||
import net from "node:net";
|
||||
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { createClientChannel, type Transport } from "@paseo/relay/e2ee";
|
||||
import { createRelayServer } from "@paseo/relay/node";
|
||||
|
||||
function createCapturingLogger() {
|
||||
@@ -34,7 +35,10 @@ function parseOfferUrlFromLogs(lines: string[]): string {
|
||||
throw new Error(`pairing_offer log not found. saw ${lines.length} lines`);
|
||||
}
|
||||
|
||||
function decodeOfferFromFragmentUrl(url: string): { sessionId: string } {
|
||||
function decodeOfferFromFragmentUrl(url: string): {
|
||||
sessionId: string;
|
||||
daemonPublicKeyB64: string;
|
||||
} {
|
||||
const marker = "#offer=";
|
||||
const idx = url.indexOf(marker);
|
||||
if (idx === -1) {
|
||||
@@ -42,9 +46,10 @@ function decodeOfferFromFragmentUrl(url: string): { sessionId: string } {
|
||||
}
|
||||
const encoded = url.slice(idx + marker.length);
|
||||
const json = Buffer.from(encoded, "base64url").toString("utf8");
|
||||
const offer = JSON.parse(json) as { sessionId?: string };
|
||||
const offer = JSON.parse(json) as { sessionId?: string; daemonPublicKeyB64?: string };
|
||||
if (!offer.sessionId) throw new Error("offer.sessionId missing");
|
||||
return { sessionId: offer.sessionId };
|
||||
if (!offer.daemonPublicKeyB64) throw new Error("offer.daemonPublicKeyB64 missing");
|
||||
return { sessionId: offer.sessionId, daemonPublicKeyB64: offer.daemonPublicKeyB64 };
|
||||
}
|
||||
|
||||
async function getAvailablePort(): Promise<number> {
|
||||
@@ -62,7 +67,7 @@ async function getAvailablePort(): Promise<number> {
|
||||
});
|
||||
}
|
||||
|
||||
describe("Relay transport (plaintext) - daemon E2E", () => {
|
||||
describe("Relay transport (E2EE) - daemon E2E", () => {
|
||||
test(
|
||||
"daemon connects to relay and client ping/pong works through relay",
|
||||
async () => {
|
||||
@@ -82,7 +87,7 @@ describe("Relay transport (plaintext) - daemon E2E", () => {
|
||||
|
||||
try {
|
||||
const offerUrl = parseOfferUrlFromLogs(lines);
|
||||
const { sessionId } = decodeOfferFromFragmentUrl(offerUrl);
|
||||
const { sessionId, daemonPublicKeyB64 } = decodeOfferFromFragmentUrl(offerUrl);
|
||||
|
||||
const ws = new WebSocket(
|
||||
`ws://127.0.0.1:${relayPort}/ws?session=${encodeURIComponent(
|
||||
@@ -96,28 +101,63 @@ describe("Relay transport (plaintext) - daemon E2E", () => {
|
||||
reject(new Error("timed out waiting for pong"));
|
||||
}, 20000);
|
||||
|
||||
ws.on("open", () => {
|
||||
ws.send(JSON.stringify({ type: "ping" }));
|
||||
});
|
||||
const transport: Transport = {
|
||||
send: (data) => ws.send(data),
|
||||
close: (code?: number, reason?: string) => ws.close(code, reason),
|
||||
onmessage: null,
|
||||
onclose: null,
|
||||
onerror: null,
|
||||
};
|
||||
|
||||
ws.on("message", (data) => {
|
||||
clearTimeout(timeout);
|
||||
try {
|
||||
resolve(JSON.parse(data.toString()));
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
} finally {
|
||||
ws.close();
|
||||
}
|
||||
transport.onmessage?.(typeof data === "string" ? data : data.toString());
|
||||
});
|
||||
ws.on("close", (code, reason) => {
|
||||
transport.onclose?.(code, reason.toString());
|
||||
});
|
||||
ws.on("error", (err) => {
|
||||
transport.onerror?.(err);
|
||||
});
|
||||
|
||||
ws.on("error", (err) => {
|
||||
clearTimeout(timeout);
|
||||
reject(err);
|
||||
ws.on("open", async () => {
|
||||
try {
|
||||
const channel = await createClientChannel(
|
||||
transport,
|
||||
daemonPublicKeyB64,
|
||||
{
|
||||
onmessage: (data) => {
|
||||
clearTimeout(timeout);
|
||||
try {
|
||||
const payload =
|
||||
typeof data === "string" ? JSON.parse(data) : data;
|
||||
resolve(payload);
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
} finally {
|
||||
ws.close();
|
||||
}
|
||||
},
|
||||
onerror: (err) => {
|
||||
clearTimeout(timeout);
|
||||
reject(err);
|
||||
},
|
||||
}
|
||||
);
|
||||
await channel.send(JSON.stringify({ type: "ping" }));
|
||||
} catch (err) {
|
||||
clearTimeout(timeout);
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
expect(received).toEqual({ type: "pong" });
|
||||
} catch (err) {
|
||||
const tail = lines.slice(-50).join("");
|
||||
// Only prints on failure to help diagnose relay handshake issues.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("daemon logs (tail):\n", tail);
|
||||
throw err;
|
||||
} finally {
|
||||
await daemon.close();
|
||||
await relay.stop();
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/// <reference lib="dom" />
|
||||
import { webcrypto } from "node:crypto";
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import type pino from "pino";
|
||||
|
||||
const KeyPairSchema = z.object({
|
||||
v: z.literal(1),
|
||||
publicKeyJwk: z.record(z.any()),
|
||||
privateKeyJwk: z.record(z.any()),
|
||||
});
|
||||
|
||||
type StoredKeyPair = z.infer<typeof KeyPairSchema>;
|
||||
|
||||
const KEYPAIR_FILENAME = "daemon-keypair.json";
|
||||
const ECDH_ALGORITHM = { name: "ECDH", namedCurve: "P-256" };
|
||||
|
||||
export type DaemonKeyPairBundle = {
|
||||
keyPair: CryptoKeyPair;
|
||||
publicKeyB64: string;
|
||||
};
|
||||
|
||||
export async function loadOrCreateDaemonKeyPair(
|
||||
paseoHome: string,
|
||||
logger?: pino.Logger
|
||||
): Promise<DaemonKeyPairBundle> {
|
||||
const log = logger?.child({ module: "daemon-keypair" });
|
||||
const filePath = path.join(paseoHome, KEYPAIR_FILENAME);
|
||||
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
const raw = readFileSync(filePath, "utf8");
|
||||
const parsed = KeyPairSchema.parse(JSON.parse(raw)) as StoredKeyPair;
|
||||
const [publicKey, privateKey] = await Promise.all([
|
||||
webcrypto.subtle.importKey("jwk", parsed.publicKeyJwk, ECDH_ALGORITHM, true, []),
|
||||
webcrypto.subtle.importKey("jwk", parsed.privateKeyJwk, ECDH_ALGORITHM, true, [
|
||||
"deriveBits",
|
||||
]),
|
||||
]);
|
||||
const publicKeyB64 = await exportPublicKeyB64(publicKey);
|
||||
log?.info({ filePath }, "Loaded daemon keypair");
|
||||
return { keyPair: { publicKey, privateKey }, publicKeyB64 };
|
||||
} catch (error) {
|
||||
log?.warn({ err: error, filePath }, "Failed to load daemon keypair, regenerating");
|
||||
}
|
||||
}
|
||||
|
||||
const keyPair = (await webcrypto.subtle.generateKey(ECDH_ALGORITHM, true, [
|
||||
"deriveBits",
|
||||
])) as CryptoKeyPair;
|
||||
const [publicKeyJwk, privateKeyJwk, publicKeyB64] = await Promise.all([
|
||||
webcrypto.subtle.exportKey("jwk", keyPair.publicKey),
|
||||
webcrypto.subtle.exportKey("jwk", keyPair.privateKey),
|
||||
exportPublicKeyB64(keyPair.publicKey),
|
||||
]);
|
||||
|
||||
const payload: StoredKeyPair = {
|
||||
v: 1,
|
||||
publicKeyJwk: publicKeyJwk as Record<string, unknown>,
|
||||
privateKeyJwk: privateKeyJwk as Record<string, unknown>,
|
||||
};
|
||||
|
||||
writeFileSync(filePath, JSON.stringify(payload, null, 2) + "\n", { mode: 0o600 });
|
||||
log?.info({ filePath }, "Saved daemon keypair");
|
||||
|
||||
return { keyPair, publicKeyB64 };
|
||||
}
|
||||
|
||||
async function exportPublicKeyB64(publicKey: CryptoKey): Promise<string> {
|
||||
const raw = await webcrypto.subtle.exportKey("raw", publicKey);
|
||||
return Buffer.from(new Uint8Array(raw)).toString("base64");
|
||||
}
|
||||
@@ -1,22 +1,40 @@
|
||||
/// <reference lib="dom" />
|
||||
import { EventEmitter } from "node:events";
|
||||
import WebSocket from "ws";
|
||||
import type pino from "pino";
|
||||
import {
|
||||
createDaemonChannel,
|
||||
type EncryptedChannel,
|
||||
type Transport as RelayTransport,
|
||||
} from "@paseo/relay/e2ee";
|
||||
import { buildRelayWebSocketUrl } from "../shared/daemon-endpoints.js";
|
||||
|
||||
type RelayTransportOptions = {
|
||||
logger: pino.Logger;
|
||||
attachSocket: (ws: WebSocket) => Promise<void>;
|
||||
attachSocket: (ws: RelaySocketLike) => Promise<void>;
|
||||
relayEndpoint: string; // "host:port"
|
||||
sessionId: string;
|
||||
daemonKeyPair?: CryptoKeyPair;
|
||||
};
|
||||
|
||||
export type RelayTransportController = {
|
||||
stop: () => Promise<void>;
|
||||
};
|
||||
|
||||
type RelaySocketLike = {
|
||||
readyState: number;
|
||||
send: (data: string) => void;
|
||||
close: (code?: number, reason?: string) => void;
|
||||
on: (event: "message" | "close" | "error", listener: (...args: any[]) => void) => void;
|
||||
once: (event: "close" | "error", listener: (...args: any[]) => void) => void;
|
||||
};
|
||||
|
||||
export function startRelayTransport({
|
||||
logger,
|
||||
attachSocket,
|
||||
relayEndpoint,
|
||||
sessionId,
|
||||
daemonKeyPair,
|
||||
}: RelayTransportOptions): RelayTransportController {
|
||||
const relayLogger = logger.child({ module: "relay-transport" });
|
||||
|
||||
@@ -44,7 +62,11 @@ export function startRelayTransport({
|
||||
const connect = (): void => {
|
||||
if (stopped) return;
|
||||
|
||||
const url = buildRelayWebSocketUrl(relayEndpoint, sessionId, "server");
|
||||
const url = buildRelayWebSocketUrl({
|
||||
endpoint: relayEndpoint,
|
||||
sessionId,
|
||||
role: "server",
|
||||
});
|
||||
const socket = new WebSocket(url);
|
||||
ws = socket;
|
||||
|
||||
@@ -56,7 +78,11 @@ export function startRelayTransport({
|
||||
|
||||
if (attached) return;
|
||||
attached = true;
|
||||
void attachSocket(socket);
|
||||
if (daemonKeyPair) {
|
||||
void attachEncryptedSocket(socket, daemonKeyPair, relayLogger, attachSocket);
|
||||
} else {
|
||||
void attachSocket(socket);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("close", (code, reason) => {
|
||||
@@ -90,46 +116,140 @@ export function startRelayTransport({
|
||||
return { stop };
|
||||
}
|
||||
|
||||
function buildRelayWebSocketUrl(
|
||||
relayEndpoint: string,
|
||||
sessionId: string,
|
||||
role: "server" | "client"
|
||||
): string {
|
||||
const { host, port } = parseHostPort(relayEndpoint);
|
||||
const protocol = port === 443 ? "wss" : "ws";
|
||||
return `${protocol}://${host}:${port}/ws?session=${encodeURIComponent(
|
||||
sessionId
|
||||
)}&role=${role}`;
|
||||
async function attachEncryptedSocket(
|
||||
socket: WebSocket,
|
||||
daemonKeyPair: CryptoKeyPair,
|
||||
logger: pino.Logger,
|
||||
attachSocket: (ws: RelaySocketLike) => Promise<void>
|
||||
): Promise<void> {
|
||||
try {
|
||||
const relayTransport = createRelayTransportAdapter(socket);
|
||||
const emitter = new EventEmitter();
|
||||
const channel = await createDaemonChannel(relayTransport, daemonKeyPair, {
|
||||
onmessage: (data) => emitter.emit("message", data),
|
||||
onclose: (code, reason) => emitter.emit("close", code, reason),
|
||||
onerror: (error) => {
|
||||
logger.warn({ err: error }, "relay_e2ee_error");
|
||||
emitter.emit("error", error);
|
||||
},
|
||||
});
|
||||
const encryptedSocket = createEncryptedSocket(channel, emitter);
|
||||
await attachSocket(encryptedSocket);
|
||||
} catch (error) {
|
||||
logger.warn({ err: error }, "relay_e2ee_handshake_failed");
|
||||
try {
|
||||
socket.close(1011, "E2EE handshake failed");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseHostPort(input: string): { host: string; port: number } {
|
||||
const trimmed = input.trim();
|
||||
function createRelayTransportAdapter(socket: WebSocket): RelayTransport {
|
||||
const relayTransport: RelayTransport = {
|
||||
send: (data) => socket.send(data),
|
||||
close: (code?: number, reason?: string) => socket.close(code, reason),
|
||||
onmessage: null,
|
||||
onclose: null,
|
||||
onerror: null,
|
||||
};
|
||||
|
||||
if (trimmed.startsWith("[")) {
|
||||
const endIdx = trimmed.indexOf("]");
|
||||
if (endIdx === -1) {
|
||||
throw new Error(`Invalid relay endpoint: ${input}`);
|
||||
}
|
||||
const host = trimmed.slice(1, endIdx);
|
||||
const rest = trimmed.slice(endIdx + 1);
|
||||
if (!rest.startsWith(":")) {
|
||||
throw new Error(`Invalid relay endpoint: ${input}`);
|
||||
}
|
||||
const port = Number.parseInt(rest.slice(1), 10);
|
||||
if (!Number.isFinite(port)) {
|
||||
throw new Error(`Invalid relay port: ${input}`);
|
||||
}
|
||||
return { host: `[${host}]`, port };
|
||||
}
|
||||
socket.on("message", (data, isBinary) => {
|
||||
relayTransport.onmessage?.(normalizeMessageData(data, isBinary));
|
||||
});
|
||||
socket.on("close", (code, reason) => {
|
||||
relayTransport.onclose?.(code, reason.toString());
|
||||
});
|
||||
socket.on("error", (err) => {
|
||||
relayTransport.onerror?.(err instanceof Error ? err : new Error(String(err)));
|
||||
});
|
||||
|
||||
const idx = trimmed.lastIndexOf(":");
|
||||
if (idx === -1) {
|
||||
throw new Error(`Invalid relay endpoint (expected host:port): ${input}`);
|
||||
}
|
||||
const host = trimmed.slice(0, idx);
|
||||
const port = Number.parseInt(trimmed.slice(idx + 1), 10);
|
||||
if (!host || !Number.isFinite(port)) {
|
||||
throw new Error(`Invalid relay endpoint: ${input}`);
|
||||
}
|
||||
return { host, port };
|
||||
return relayTransport;
|
||||
}
|
||||
|
||||
function createEncryptedSocket(
|
||||
channel: EncryptedChannel,
|
||||
emitter: EventEmitter
|
||||
): RelaySocketLike {
|
||||
let readyState = 1;
|
||||
|
||||
channel.setState("open");
|
||||
|
||||
const close = (code?: number, reason?: string) => {
|
||||
if (readyState === 3) return;
|
||||
readyState = 3;
|
||||
channel.close(code, reason);
|
||||
};
|
||||
|
||||
emitter.on("close", () => {
|
||||
if (readyState === 3) return;
|
||||
readyState = 3;
|
||||
});
|
||||
|
||||
return {
|
||||
get readyState() {
|
||||
return readyState;
|
||||
},
|
||||
send: (data) => {
|
||||
void channel.send(data).catch((error) => {
|
||||
emitter.emit("error", error);
|
||||
});
|
||||
},
|
||||
close,
|
||||
on: (event, listener) => {
|
||||
emitter.on(event, listener);
|
||||
},
|
||||
once: (event, listener) => {
|
||||
emitter.once(event, listener);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeMessageData(data: unknown, isBinary: boolean): string | ArrayBuffer {
|
||||
if (!isBinary) {
|
||||
if (typeof data === "string") return data;
|
||||
const buffer = bufferFromWsData(data);
|
||||
if (buffer) return buffer.toString("utf8");
|
||||
return String(data);
|
||||
}
|
||||
|
||||
if (data instanceof ArrayBuffer) return data;
|
||||
|
||||
const buffer = bufferFromWsData(data);
|
||||
if (buffer) {
|
||||
const view = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
||||
const out = new Uint8Array(view.byteLength);
|
||||
out.set(view);
|
||||
return out.buffer;
|
||||
}
|
||||
|
||||
return String(data);
|
||||
}
|
||||
|
||||
function bufferFromWsData(data: unknown): Buffer | null {
|
||||
if (Buffer.isBuffer(data)) return data;
|
||||
if (Array.isArray(data)) {
|
||||
const buffers: Buffer[] = [];
|
||||
for (const part of data) {
|
||||
if (Buffer.isBuffer(part)) {
|
||||
buffers.push(part);
|
||||
} else if (part instanceof ArrayBuffer) {
|
||||
buffers.push(Buffer.from(part));
|
||||
} else if (ArrayBuffer.isView(part)) {
|
||||
buffers.push(Buffer.from(part.buffer, part.byteOffset, part.byteLength));
|
||||
} else if (typeof part === "string") {
|
||||
buffers.push(Buffer.from(part, "utf8"));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return Buffer.concat(buffers);
|
||||
}
|
||||
if (data instanceof ArrayBuffer) return Buffer.from(data);
|
||||
if (ArrayBuffer.isView(data)) {
|
||||
return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// buildRelayWebSocketUrl + parseHostPort live in ../shared/daemon-endpoints.ts
|
||||
|
||||
@@ -99,7 +99,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
this.bridge.broadcast(message);
|
||||
}
|
||||
|
||||
public async attachExternalSocket(ws: Parameters<WebSocketSessionBridge["attach"]>[0]): Promise<void> {
|
||||
public async attachExternalSocket(
|
||||
ws: Parameters<WebSocketSessionBridge["attach"]>[0]
|
||||
): Promise<void> {
|
||||
const fakeRequest = {
|
||||
url: "/ws",
|
||||
headers: {},
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { IncomingMessage } from "http";
|
||||
import type { WebSocket } from "ws";
|
||||
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { join } from "path";
|
||||
import {
|
||||
@@ -22,9 +21,30 @@ import type pino from "pino";
|
||||
|
||||
export type AgentMcpTransportFactory = () => Promise<Transport>;
|
||||
|
||||
function bufferFromWsData(data: Buffer | ArrayBuffer | Buffer[] | string): Buffer {
|
||||
if (typeof data === "string") return Buffer.from(data, "utf8");
|
||||
if (Array.isArray(data)) {
|
||||
return Buffer.concat(
|
||||
data.map((item) =>
|
||||
Buffer.isBuffer(item) ? item : Buffer.from(item as ArrayBuffer)
|
||||
)
|
||||
);
|
||||
}
|
||||
if (Buffer.isBuffer(data)) return data;
|
||||
return Buffer.from(data as ArrayBuffer);
|
||||
}
|
||||
|
||||
type WebSocketLike = {
|
||||
readyState: number;
|
||||
send: (data: string) => void;
|
||||
close: (code?: number, reason?: string) => void;
|
||||
on: (event: "message" | "close" | "error", listener: (...args: any[]) => void) => void;
|
||||
once: (event: "close" | "error", listener: (...args: any[]) => void) => void;
|
||||
};
|
||||
|
||||
export class WebSocketSessionBridge {
|
||||
private readonly logger: pino.Logger;
|
||||
private readonly sessions: Map<WebSocket, Session> = new Map();
|
||||
private readonly sessions: Map<WebSocketLike, Session> = new Map();
|
||||
private clientIdCounter = 0;
|
||||
private readonly agentManager: AgentManager;
|
||||
private readonly agentStorage: AgentStorage;
|
||||
@@ -95,7 +115,7 @@ export class WebSocketSessionBridge {
|
||||
return this.sessions.size;
|
||||
}
|
||||
|
||||
public async attach(ws: WebSocket, _request: IncomingMessage): Promise<void> {
|
||||
public async attach(ws: WebSocketLike, _request: IncomingMessage): Promise<void> {
|
||||
const clientId = `client-${++this.clientIdCounter}`;
|
||||
const connectionLogger = this.logger.child({ clientId });
|
||||
|
||||
@@ -141,7 +161,7 @@ export class WebSocketSessionBridge {
|
||||
});
|
||||
}
|
||||
|
||||
private async detach(ws: WebSocket, connectionLogger: pino.Logger, clientId: string): Promise<void> {
|
||||
private async detach(ws: WebSocketLike, connectionLogger: pino.Logger, clientId: string): Promise<void> {
|
||||
const session = this.sessions.get(ws);
|
||||
if (!session) return;
|
||||
|
||||
@@ -154,9 +174,13 @@ export class WebSocketSessionBridge {
|
||||
this.sessions.delete(ws);
|
||||
}
|
||||
|
||||
private async handleRawMessage(ws: WebSocket, data: Buffer | ArrayBuffer | Buffer[]): Promise<void> {
|
||||
private async handleRawMessage(
|
||||
ws: WebSocketLike,
|
||||
data: Buffer | ArrayBuffer | Buffer[] | string
|
||||
): Promise<void> {
|
||||
try {
|
||||
const parsed = JSON.parse(data.toString());
|
||||
const buffer = bufferFromWsData(data);
|
||||
const parsed = JSON.parse(buffer.toString());
|
||||
const parsedMessage = WSInboundMessageSchema.safeParse(parsed);
|
||||
if (!parsedMessage.success) {
|
||||
const requestInfo = extractRequestInfoFromUnknownWsInbound(parsed);
|
||||
@@ -252,13 +276,7 @@ export class WebSocketSessionBridge {
|
||||
let parsedPayload: unknown = null;
|
||||
|
||||
try {
|
||||
const buffer = Array.isArray(data)
|
||||
? Buffer.concat(
|
||||
data.map((item) => (Buffer.isBuffer(item) ? item : Buffer.from(item as ArrayBuffer)))
|
||||
)
|
||||
: Buffer.isBuffer(data)
|
||||
? data
|
||||
: Buffer.from(data as ArrayBuffer);
|
||||
const buffer = bufferFromWsData(data);
|
||||
rawPayload = buffer.toString();
|
||||
parsedPayload = JSON.parse(rawPayload);
|
||||
} catch (payloadError) {
|
||||
@@ -313,7 +331,7 @@ export class WebSocketSessionBridge {
|
||||
}
|
||||
}
|
||||
|
||||
private sendToClient(ws: WebSocket, message: WSOutboundMessage): void {
|
||||
private sendToClient(ws: WebSocketLike, message: WSOutboundMessage): void {
|
||||
// WebSocket.OPEN = 1
|
||||
if (ws.readyState === 1) {
|
||||
ws.send(JSON.stringify(message));
|
||||
@@ -442,7 +460,7 @@ export class WebSocketSessionBridge {
|
||||
reason: "finished" | "error" | "permission";
|
||||
}): void {
|
||||
const clientEntries: Array<{
|
||||
ws: WebSocket;
|
||||
ws: WebSocketLike;
|
||||
state: {
|
||||
deviceType: "web" | "mobile" | null;
|
||||
focusedAgentId: string | null;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ConnectionOfferV1Schema = z.object({
|
||||
v: z.literal(1),
|
||||
sessionId: z.string().min(1),
|
||||
endpoints: z.array(z.string().min(1)).min(1),
|
||||
daemonPublicKeyB64: z.string().min(1),
|
||||
relay: z
|
||||
.object({
|
||||
endpoint: z.string().min(1),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type ConnectionOfferV1 = z.infer<typeof ConnectionOfferV1Schema>;
|
||||
@@ -0,0 +1,117 @@
|
||||
export type HostPortParts = {
|
||||
host: string;
|
||||
port: number;
|
||||
isIpv6: boolean;
|
||||
};
|
||||
|
||||
export type RelayRole = "server" | "client";
|
||||
|
||||
function parsePort(portStr: string, context: string): number {
|
||||
const port = Number(portStr);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error(`${context}: port must be between 1 and 65535`);
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
export function parseHostPort(input: string): HostPortParts {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error("Host is required");
|
||||
}
|
||||
|
||||
// IPv6: [::1]:6767
|
||||
if (trimmed.startsWith("[")) {
|
||||
const match = trimmed.match(/^\[([^\]]+)\]:(\d{1,5})$/);
|
||||
if (!match) {
|
||||
throw new Error("Invalid host:port (expected [::1]:6767)");
|
||||
}
|
||||
const host = match[1].trim();
|
||||
if (!host) throw new Error("Host is required");
|
||||
const port = parsePort(match[2], "Invalid host:port");
|
||||
return { host, port, isIpv6: true };
|
||||
}
|
||||
|
||||
const match = trimmed.match(/^(.+):(\d{1,5})$/);
|
||||
if (!match) {
|
||||
throw new Error("Invalid host:port (expected localhost:6767)");
|
||||
}
|
||||
const host = match[1].trim();
|
||||
if (!host) throw new Error("Host is required");
|
||||
const port = parsePort(match[2], "Invalid host:port");
|
||||
return { host, port, isIpv6: false };
|
||||
}
|
||||
|
||||
export function normalizeHostPort(input: string): string {
|
||||
const { host, port, isIpv6 } = parseHostPort(input);
|
||||
return isIpv6 ? `[${host}]:${port}` : `${host}:${port}`;
|
||||
}
|
||||
|
||||
export function deriveLabelFromEndpoint(endpoint: string): string {
|
||||
try {
|
||||
const { host } = parseHostPort(endpoint);
|
||||
return host || "Unnamed Host";
|
||||
} catch {
|
||||
return "Unnamed Host";
|
||||
}
|
||||
}
|
||||
|
||||
function shouldUseSecureWebSocket(port: number): boolean {
|
||||
return port === 443;
|
||||
}
|
||||
|
||||
export function buildDaemonWebSocketUrl(endpoint: string): string {
|
||||
const { host, port, isIpv6 } = parseHostPort(endpoint);
|
||||
const protocol = shouldUseSecureWebSocket(port) ? "wss" : "ws";
|
||||
const hostPart = isIpv6 ? `[${host}]` : host;
|
||||
return `${protocol}://${hostPart}:${port}/ws`;
|
||||
}
|
||||
|
||||
export function buildRelayWebSocketUrl(params: {
|
||||
endpoint: string;
|
||||
sessionId: string;
|
||||
role: RelayRole;
|
||||
}): string {
|
||||
const { host, port, isIpv6 } = parseHostPort(params.endpoint);
|
||||
const protocol = shouldUseSecureWebSocket(port) ? "wss" : "ws";
|
||||
const hostPart = isIpv6 ? `[${host}]` : host;
|
||||
const url = new URL(`${protocol}://${hostPart}:${port}/ws`);
|
||||
url.searchParams.set("session", params.sessionId);
|
||||
url.searchParams.set("role", params.role);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function extractHostPortFromWebSocketUrl(wsUrl: string): string {
|
||||
const parsed = new URL(wsUrl);
|
||||
if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
|
||||
throw new Error("Invalid WebSocket URL protocol");
|
||||
}
|
||||
if (parsed.pathname.replace(/\/+$/, "") !== "/ws") {
|
||||
throw new Error("Invalid WebSocket URL (expected /ws path)");
|
||||
}
|
||||
|
||||
const host = parsed.hostname;
|
||||
const port = parsed.port ? Number(parsed.port) : parsed.protocol === "wss:" ? 443 : 80;
|
||||
if (!host) {
|
||||
throw new Error("Invalid WebSocket URL (missing hostname)");
|
||||
}
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error("Invalid WebSocket URL (invalid port)");
|
||||
}
|
||||
|
||||
const isIpv6 = host.includes(":") && !host.startsWith("[") && !host.endsWith("]");
|
||||
return isIpv6 ? `[${host}]:${port}` : `${host}:${port}`;
|
||||
}
|
||||
|
||||
export function isRelayClientWebSocketUrl(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return (
|
||||
parsed.searchParams.get("role") === "client" &&
|
||||
parsed.searchParams.has("session")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user