Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

refactor(relay): move the pure relay modules into src/core/relay

review1f65c9cd64d5
diff --git a/src/core/relay/approved-devices-core.ts b/src/core/relay/approved-devices-core.ts
new file mode 100644
index 000000000..7715eebe8
--- /dev/null
+++ b/src/core/relay/approved-devices-core.ts
@@ -0,0 +1,52 @@
+// Pure pin/lookup logic for the standing (phone) host's "pin once" device approval.
+//
+// The FIRST time a phone (identified by its NaCl box public key, base64) connects over the relay
+// the host human approves it via the SAS dialog; on approval its pubkey is pinned here so future
+// connects auto-approve with no prompt. These are PUBLIC keys, not credentials — safe to persist.
+//
+// Kept pure (no I/O) so it can be unit-tested; the disk read/write wrapper lives in
+// `approved-devices.ts`.
+
+/** The persisted shape of <userData>/remote-approved-devices.json. */
+export interface ApprovedDevices {
+ /** Base64 NaCl box public keys of phones the host has approved at least once. */
+ pubkeys: string[]
+}
+
+export function emptyApprovedDevices(): ApprovedDevices {
+ return { pubkeys: [] }
+}
+
+/** Coerce arbitrary parsed JSON into a well-formed ApprovedDevices (drops non-string / empty entries). */
+export function parseApprovedDevices(raw: unknown): ApprovedDevices {
+ if (!raw || typeof raw !== 'object') return emptyApprovedDevices()
+ const pubkeys = (raw as { pubkeys?: unknown }).pubkeys
+ if (!Array.isArray(pubkeys)) return emptyApprovedDevices()
+ // De-dupe while preserving order; keep only non-empty strings.
+ const seen = new Set<string>()
+ const out: string[] = []
+ for (const k of pubkeys) {
+ if (typeof k === 'string' && k.length > 0 && !seen.has(k)) {
+ seen.add(k)
+ out.push(k)
+ }
+ }
+ return { pubkeys: out }
+}
+
+/** True when `pubkeyB64` has been pinned before. Empty input is never pinned. */
+export function isPinned(store: ApprovedDevices, pubkeyB64: string): boolean {
+ return pubkeyB64.length > 0 && store.pubkeys.includes(pubkeyB64)
+}
+
+/** Return a store with `pubkeyB64` pinned. Idempotent; returns the same object when already present. */
+export function pinDevice(store: ApprovedDevices, pubkeyB64: string): ApprovedDevices {
+ if (pubkeyB64.length === 0 || store.pubkeys.includes(pubkeyB64)) return store
+ return { pubkeys: [...store.pubkeys, pubkeyB64] }
+}
+
+/** Return a store with `pubkeyB64` unpinned (revoke). Idempotent. */
+export function unpinDevice(store: ApprovedDevices, pubkeyB64: string): ApprovedDevices {
+ if (!store.pubkeys.includes(pubkeyB64)) return store
+ return { pubkeys: store.pubkeys.filter((k) => k !== pubkeyB64) }
+}
diff --git a/src/core/relay/e2ee.ts b/src/core/relay/e2ee.ts
new file mode 100644
index 000000000..11e986d86
--- /dev/null
+++ b/src/core/relay/e2ee.ts
@@ -0,0 +1,107 @@
+// End-to-end encryption primitives for the relay transport.
+//
+// Pure functions over NaCl box (Curve25519 + XSalsa20-Poly1305): no sockets, no
+// Electron. The box format is `nonce ‖ ciphertext ‖ mac` so an interoperable peer
+// can be implemented against the same wire format.
+import { hkdfSync } from 'node:crypto'
+import nacl from 'tweetnacl'
+
+export type KeyPair = {
+ publicKey: Uint8Array
+ secretKey: Uint8Array
+}
+
+export function genKeyPair(): KeyPair {
+ return nacl.box.keyPair()
+}
+
+export function publicKeyToB64(key: Uint8Array): string {
+ return Buffer.from(key).toString('base64')
+}
+
+export function publicKeyFromB64(b64: string): Uint8Array {
+ const key = Uint8Array.from(Buffer.from(b64, 'base64'))
+ if (key.length !== nacl.box.publicKeyLength) {
+ throw new Error(`Invalid public key: expected ${nacl.box.publicKeyLength} bytes, got ${key.length}`)
+ }
+ return key
+}
+
+// Same strictness for a secret key: `Buffer.from(x, 'base64')` silently drops non-alphabet
+// characters and truncates, so a corrupt/short blob would otherwise decode to a short-but-accepted
+// key that only blows up ("bad secret key size") deep inside a later nacl.box call.
+export function secretKeyFromB64(b64: string): Uint8Array {
+ const key = Uint8Array.from(Buffer.from(b64, 'base64'))
+ if (key.length !== nacl.box.secretKeyLength) {
+ throw new Error(`Invalid secret key: expected ${nacl.box.secretKeyLength} bytes, got ${key.length}`)
+ }
+ return key
+}
+
+// Derive the shared secret (ECDH precompute) from the peer's base64 public key
+// and our secret key. Both sides arrive at the same value. This is the STABLE
+// per-device-pair key (both endpoints use static keys for pin-once), so it must
+// NOT be used directly to encrypt traffic — see deriveSessionKey.
+export function deriveSharedKey(theirPubB64: string, ourSecret: Uint8Array): Uint8Array {
+ const theirPub = publicKeyFromB64(theirPubB64)
+ return nacl.box.before(theirPub, ourSecret)
+}
+
+// A fresh 16-byte session nonce, exchanged in the handshake.
+export function randomSessionNonce(): Uint8Array {
+ return nacl.randomBytes(16)
+}
+
+// Per-SESSION traffic key = HKDF-SHA256(baseShared, salt = hostNonce ‖ clientNonce).
+// Because both endpoints hold STATIC keys (stable pin-once identity), the raw ECDH
+// `baseShared` is identical on every reconnect — encrypting with it lets a malicious
+// relay replay a whole recorded session's boxes against a fresh connection (the seq
+// counter resets per connection, so it can't stop this). Mixing in fresh per-session
+// nonces makes the traffic key unique to each session, so recorded boxes never decrypt
+// under a later session's key. RFC 5869 HKDF; matches iOS CryptoKit HKDF<SHA256>.
+export function deriveSessionKey(
+ baseShared: Uint8Array,
+ hostNonce: Uint8Array,
+ clientNonce: Uint8Array
+): Uint8Array {
+ const salt = new Uint8Array(hostNonce.length + clientNonce.length)
+ salt.set(hostNonce)
+ salt.set(clientNonce, hostNonce.length)
+ const info = new TextEncoder().encode('nodeterm-relay-session-v2')
+ const out = hkdfSync('sha256', baseShared, salt, info, 32)
+ return new Uint8Array(out)
+}
+
+// Encrypt with the precomputed shared key. Returns `nonce ‖ ciphertext ‖ mac`.
+export function encrypt(plain: Uint8Array, shared: Uint8Array): Uint8Array {
+ const nonce = nacl.randomBytes(nacl.box.nonceLength)
+ const ciphertext = nacl.box.after(plain, nonce, shared)
+
+ const box = new Uint8Array(nonce.length + ciphertext.length)
+ box.set(nonce)
+ box.set(ciphertext, nonce.length)
+ return box
+}
+
+// Short Authentication String: a 6-digit code derived from the ECDH shared key. Both peers
+// compute the SAME value (same shared key), so the two humans can compare it out-of-band to
+// confirm they're on the same channel before the host approves a connection. Formatted "NNN NNN".
+export function sasFromSharedKey(shared: Uint8Array): string {
+ const h = nacl.hash(shared) // SHA-512
+ // Fold the first 4 bytes into a 32-bit int, then take 6 decimal digits.
+ const n = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0
+ const code = (n % 1_000_000).toString().padStart(6, '0')
+ return `${code.slice(0, 3)} ${code.slice(3)}`
+}
+
+// Decrypt a `nonce ‖ ciphertext ‖ mac` box. Returns null on malformed input or
+// a failed MAC check — never throws.
+export function decrypt(box: Uint8Array, shared: Uint8Array): Uint8Array | null {
+ if (box.length < nacl.box.nonceLength + nacl.box.overheadLength) {
+ return null
+ }
+ const nonce = box.slice(0, nacl.box.nonceLength)
+ const ciphertext = box.slice(nacl.box.nonceLength)
+ const plain = nacl.box.open.after(ciphertext, nonce, shared)
+ return plain ?? null
+}
diff --git a/src/core/relay/framing.ts b/src/core/relay/framing.ts
new file mode 100644
index 000000000..b56d16512
--- /dev/null
+++ b/src/core/relay/framing.ts
@@ -0,0 +1,88 @@
+// Terminal-stream binary framing for the relay transport.
+//
+// The 16-byte header layout and opcode numbers are stable wire constants so an
+// interoperable peer can be implemented against them. Pure functions: no sockets,
+// no Electron.
+//
+// Header (16 bytes, little-endian where multi-byte):
+// [0] kind = 0x74
+// [1] version = 1
+// [2] opcode
+// [3] reserved (0)
+// [4..8) streamId (uint32 LE)
+// [8..12) seq high (uint32 LE)
+// [12..16) seq low (uint32 LE)
+// followed by the raw payload.
+
+const STREAM_KIND = 0x74
+const STREAM_VERSION = 1
+const HEADER_BYTES = 16
+
+// Opcode numbers are part of the stable wire contract — do not renumber.
+export const OP = {
+ Output: 1,
+ SnapshotStart: 2,
+ SnapshotChunk: 3,
+ SnapshotEnd: 4,
+ Resized: 5,
+ Error: 6,
+ Input: 7,
+ Resize: 8,
+ Subscribe: 9,
+ Unsubscribe: 10,
+ SnapshotRequest: 11
+} as const
+
+export type Opcode = (typeof OP)[keyof typeof OP]
+
+export type Frame = {
+ op: number
+ streamId: number
+ seq: number
+ payload: Uint8Array
+}
+
+// Max bytes we let buffer on a binary channel before applying backpressure.
+// Kept here so the host/client transports share one threshold.
+export const MAX_BINARY_BUFFERED_AMOUNT = 8 * 1024 * 1024
+
+const KNOWN_OPCODES = new Set<number>(Object.values(OP))
+
+export function encodeFrame(op: number, streamId: number, seq: number, payload: Uint8Array): Uint8Array {
+ const out = new Uint8Array(HEADER_BYTES + payload.length)
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength)
+ view.setUint8(0, STREAM_KIND)
+ view.setUint8(1, STREAM_VERSION)
+ view.setUint8(2, op)
+ view.setUint8(3, 0)
+ view.setUint32(4, streamId, true)
+ const s = Math.max(0, Math.floor(seq))
+ view.setUint32(8, Math.floor(s / 0x100000000), true)
+ view.setUint32(12, s >>> 0, true)
+ out.set(payload, HEADER_BYTES)
+ return out
+}
+
+// Decode a frame. Returns null for short buffers, a bad kind/version, or an
+// unknown opcode — never throws.
+export function decodeFrame(buf: Uint8Array): Frame | null {
+ if (buf.length < HEADER_BYTES) {
+ return null
+ }
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
+ if (view.getUint8(0) !== STREAM_KIND || view.getUint8(1) !== STREAM_VERSION) {
+ return null
+ }
+ const op = view.getUint8(2)
+ if (!KNOWN_OPCODES.has(op)) {
+ return null
+ }
+ const high = view.getUint32(8, true)
+ const low = view.getUint32(12, true)
+ return {
+ op,
+ streamId: view.getUint32(4, true),
+ seq: high * 0x100000000 + low,
+ payload: buf.slice(HEADER_BYTES)
+ }
+}
diff --git a/src/core/relay/key-file-codec.ts b/src/core/relay/key-file-codec.ts
new file mode 100644
index 000000000..82a993e71
--- /dev/null
+++ b/src/core/relay/key-file-codec.ts
@@ -0,0 +1,89 @@
+// Pure encode/decode for a persisted NaCl box keypair file, with encrypt-at-rest and a legacy
+// plaintext fallback + in-place migration. The Electron `safeStorage` is injected as `SafeStorageLike`
+// so this stays free of `electron` and unit-tests without a keychain. The on-disk byte format mirrors
+// host-service.ts's persistKeyPair/loadOrCreateKeyPair exactly (public key always plaintext base64 —
+// it is a pinned identity, not a secret — the secret key either safeStorage-encrypted or 0600 plaintext).
+//
+// NOTE (intentional duplication): host-service.ts still inlines the same format. We do NOT refactor it
+// to use this codec — that file is Stage 4c's to rewrite, and editing it here would collide. 4c may
+// adopt this codec when it rewrites the handshake.
+import { publicKeyFromB64, secretKeyFromB64, type KeyPair } from './e2ee'
+
+export interface SafeStorageLike {
+ isEncryptionAvailable(): boolean
+ encryptString(plaintext: string): Buffer
+ decryptString(ciphertext: Buffer): string
+}
+
+interface KeyFileBody {
+ publicKey?: string
+ secretKey?: string // legacy plaintext base64
+ secretKeyEnc?: string // safeStorage ciphertext, base64
+}
+
+/** Serialize a keypair to the on-disk JSON string; encrypted when safeStorage is available. */
+export function encodeKeyFile(keys: KeyPair, safe: SafeStorageLike): string {
+ const publicKey = Buffer.from(keys.publicKey).toString('base64')
+ const secretB64 = Buffer.from(keys.secretKey).toString('base64')
+ const body: KeyFileBody = safe.isEncryptionAvailable()
+ ? { publicKey, secretKeyEnc: safe.encryptString(secretB64).toString('base64') }
+ : { publicKey, secretKey: secretB64 }
+ return JSON.stringify(body)
+}
+
+/**
+ * The three outcomes of reading a key file. They are NOT interchangeable — the caller must branch:
+ *
+ * - `{ keys, migrate }` — usable. `migrate:true` means the file is legacy plaintext but encryption
+ * is now available: re-persist to upgrade in place, KEEPING the identity.
+ * - `null` — unusable: malformed JSON, a wrong-length key, or an encrypted blob the (available)
+ * keychain cannot decrypt (keychain reset ⇒ the secret is gone for good). Regenerating is the
+ * only way forward and is CORRECT here.
+ * - `'locked'` — the file is well-formed and holds an ENCRYPTED secret, but `isEncryptionAvailable()`
+ * is false RIGHT NOW (keyring not yet unlocked, no session bus, safeStorage backend down). The
+ * identity is intact on disk, merely unreadable at this moment. The caller MUST NOT write:
+ * regenerating would replace a pinned identity with a fresh (plaintext) one, forcing re-approval
+ * on every host that pinned it — unrecoverably. Fail the operation and tell the user to unlock.
+ */
+export type KeyFileDecoded = { keys: KeyPair; migrate: boolean } | null | 'locked'
+
+/** Parse a key file. See `KeyFileDecoded` — the three outcomes must not be collapsed into one. */
+export function decodeKeyFile(raw: string, safe: SafeStorageLike): KeyFileDecoded {
+ let body: unknown
+ try {
+ body = JSON.parse(raw)
+ } catch {
+ return null
+ }
+ // `JSON.parse` happily yields null / arrays / numbers for a truncated or aborted write; only a
+ // plain object can be a key file. (Without this, the literal `null` threw a TypeError below.)
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return null
+ const file = body as KeyFileBody
+ if (!file.publicKey) return null
+
+ // Both key parsers are STRICT about the 32-byte length and throw otherwise — base64 decoding is
+ // lenient (drops junk chars, truncates), so a corrupt file would otherwise decode to a
+ // short/empty "identity" that the caller accepts and only fails much later inside nacl.
+ try {
+ const publicKey = publicKeyFromB64(file.publicKey)
+ if (file.secretKeyEnc) {
+ // An encrypted secret is AUTHORITATIVE: never silently fall back to a (possibly stale)
+ // plaintext one, and never mistake "no keyring right now" for corruption.
+ if (!safe.isEncryptionAvailable()) return 'locked'
+ // decryptString may throw (keychain reset) OR return junk — either way the secret is
+ // genuinely gone, so that is `null` (regenerate), not `'locked'`.
+ const secretB64 = safe.decryptString(Buffer.from(file.secretKeyEnc, 'base64'))
+ return { keys: { publicKey, secretKey: secretKeyFromB64(secretB64) }, migrate: false }
+ }
+ if (file.secretKey) {
+ return {
+ keys: { publicKey, secretKey: secretKeyFromB64(file.secretKey) },
+ // Legacy plaintext but a keyring now exists → the caller should re-persist encrypted.
+ migrate: safe.isEncryptionAvailable()
+ }
+ }
+ } catch {
+ return null
+ }
+ return null
+}
diff --git a/src/core/relay/mutual-approval-core.ts b/src/core/relay/mutual-approval-core.ts
new file mode 100644
index 000000000..ece719178
--- /dev/null
+++ b/src/core/relay/mutual-approval-core.ts
@@ -0,0 +1,98 @@
+// Pure state for SYMMETRIC pairing approval: both ends verify the same 6-digit SAS out of band and
+// both pin the other's key. Today approval is one-way (only the host pins the client). This adds the
+// second confirmation direction + the pin-both-ends bookkeeping as pure logic — no sockets, no
+// Electron — so it unit-tests directly and 4c can wire it into either end's handshake.
+//
+// The SAS digits themselves are already identical on both ends (both derive from the same ECDH shared
+// key via sasFromSharedKey); "mutual" means BOTH humans must confirm before the session opens, and
+// EACH end independently pins the other's stable box public key. A man-in-the-middle on the relay
+// terminates two DIFFERENT ECDH exchanges, so the two humans read out different digits and refuse —
+// which is exactly why neither confirmation alone may unlock the session.
+//
+// SECURITY — this module is a correct latch ONLY if 4c (host-service / client-service) honours two
+// obligations it cannot express in this pure file. Both are security-FATAL if broken, because pinning
+// a key grants the peer SHELL ACCESS on this machine:
+//
+// (a) `confirmRemote` MUST be driven ONLY by a frame received over the ENCRYPTED, session-keyed
+// channel (the box under deriveSessionKey), never from a plaintext/relay-visible message. The
+// relay is untrusted: if the peer's "I confirmed" signal can be forged or replayed by a relay
+// MITM, mutual approval silently degrades back to ONE-WAY — the attacker supplies the remote
+// confirmation the second human never gave, and a single local confirm then pins the attacker.
+// Only a frame that decrypts under THIS session's key proves the real peer sent it.
+//
+// (b) There must be EXACTLY ONE `MutualApproval` per pairing attempt, created via
+// `emptyMutualApproval(peerKeyB64, sessionId)` from THIS session's ECDH peer key (the same key
+// whose shared secret produced the SAS the humans compared). Reusing a state across attempts,
+// or seeding it with a key other than this session's, re-opens the "confirm-for-a-different-
+// session" / "pin-the-wrong-key" holes this module's binding was built to close.
+//
+// This file makes the SAFE usage the ONLY compilable usage — the peer key + session identity are
+// bound INTO the state at construction and the branded type has no other constructor — but it cannot
+// reach across the seam to enforce (a) and (b). 4c owns those.
+import { sasFromSharedKey } from './e2ee'
+import { pinDevice, type ApprovedDevices } from './approved-devices-core'
+
+/**
+ * Approval state for ONE pairing attempt, BOUND at creation to the peer + session it approves.
+ *
+ * Opaque/branded: the `__brand` field has no runtime value and cannot be written by hand, so the
+ * ONLY way to obtain a `MutualApproval` is `emptyMutualApproval()`, and the only way to mutate one is
+ * `confirmLocal`/`confirmRemote`. A hand-forged `{ localConfirmed: true, remoteConfirmed: true, … }`
+ * is a COMPILE ERROR. This turns "safe if every caller is disciplined" into "safe by construction":
+ * you cannot fabricate an already-approved state, nor move a confirmation onto a different pairing,
+ * because every state carries the one peer key + session it belongs to.
+ */
+export type MutualApproval = {
+ /** This human confirmed the SAS on THIS device. */
+ readonly localConfirmed: boolean
+ /** The peer signalled (over the ENCRYPTED, session-keyed channel — see obligation (a)) that its human confirmed too. */
+ readonly remoteConfirmed: boolean
+ /** The peer's stable box public key (base64) from THIS session's ECDH — the ONLY key this state can ever pin. */
+ readonly peerKeyB64: string
+ /** Identity of the pairing attempt (session id or shared-key fingerprint) this state is bound to. */
+ readonly sessionId: string
+} & { readonly __brand: unique symbol }
+
+/**
+ * The sole constructor. Binds the peer's box public key + the session identity INTO the state, so a
+ * confirmation can never be moved to a different pairing and `recordApproval` can only ever pin THIS
+ * peer's key. Starts unconfirmed on both sides.
+ */
+export function emptyMutualApproval(peerKeyB64: string, sessionId: string): MutualApproval {
+ return { localConfirmed: false, remoteConfirmed: false, peerKeyB64, sessionId } as MutualApproval
+}
+
+export function confirmLocal(s: MutualApproval): MutualApproval {
+ return s.localConfirmed ? s : ({ ...s, localConfirmed: true } as MutualApproval)
+}
+
+export function confirmRemote(s: MutualApproval): MutualApproval {
+ return s.remoteConfirmed ? s : ({ ...s, remoteConfirmed: true } as MutualApproval)
+}
+
+/**
+ * Approved only when BOTH ends have confirmed the SAS. There is deliberately no other way to reach
+ * this state: the two confirmations live on separate fields, each set by its own one-way transition,
+ * so re-playing one side's confirmation (calling confirmLocal/confirmRemote twice) can never stand in
+ * for the other's.
+ */
+export function isMutuallyApproved(s: MutualApproval): boolean {
+ return s.localConfirmed && s.remoteConfirmed
+}
+
+/** The 6-digit code ("NNN NNN") BOTH ends compute + confirm. Thin alias so 4c reads clearly. */
+export function mutualSas(shared: Uint8Array): string {
+ return sasFromSharedKey(shared)
+}
+
+/**
+ * Pin the peer's stable box public key locally — but ONLY once the SAS is mutually confirmed, so a
+ * half-finished handshake never leaves a pinned identity. The key pinned is the one CARRIED BY the
+ * state (`s.peerKeyB64`, bound at construction): there is no separate key argument, so a caller cannot
+ * pin a key different from the one the two humans confirmed. Idempotent (pinDevice is). Each end calls
+ * this against its OWN store; the state each end holds carries the OTHER end's key, so both ends pin.
+ */
+export function recordApproval(store: ApprovedDevices, s: MutualApproval): ApprovedDevices {
+ if (!isMutuallyApproved(s)) return store
+ return pinDevice(store, s.peerKeyB64)
+}
diff --git a/src/core/relay/relay-id.ts b/src/core/relay/relay-id.ts
new file mode 100644
index 000000000..59f0c652f
--- /dev/null
+++ b/src/core/relay/relay-id.ts
@@ -0,0 +1,21 @@
+// Host-id derivation for the standing (phone) relay path.
+//
+// The relay broker matches a host and its clients by a short `hostId` derived from the host's
+// NaCl box public key. This MUST match the server's `src/lib/relay-id.ts` byte-for-byte:
+// hostId = base64url(sha256(rawPublicKeyBytes)).slice(0, 22) (base64url, no padding)
+// where the raw bytes are the 32-byte Curve25519 public key (the same bytes `publicKeyToB64`
+// standard-base64-encodes). Keep this in sync with the server — a mismatch means the phone and
+// this host would register under different rooms and never bridge.
+
+import { createHash } from 'node:crypto'
+
+/** Derive the broker host id from the raw 32-byte NaCl box public key. */
+export function hostIdFromPublicKey(pub: Uint8Array): string {
+ // Node's 'base64url' digest is already unpadded RFC 4648 §5, matching the server.
+ return createHash('sha256').update(pub).digest('base64url').slice(0, 22)
+}
+
+/** Derive the broker host id from a standard-base64 NaCl box public key (what publicKeyToB64 emits). */
+export function hostIdFromPublicKeyB64(b64: string): string {
+ return hostIdFromPublicKey(Uint8Array.from(Buffer.from(b64, 'base64')))
+}
diff --git a/src/core/relay/relay-project-scope.ts b/src/core/relay/relay-project-scope.ts
new file mode 100644
index 000000000..ec0195d44
--- /dev/null
+++ b/src/core/relay/relay-project-scope.ts
@@ -0,0 +1,75 @@
+// Which relay-guest methods name a PROJECT, and which project — the one table behind the scope jail
+// in `relay-host.ts` (a session bound to one shared project must never let the guest reach another).
+//
+// The jail used to be a per-feature switch with a `default: not project-scoped` arm, so a method the
+// switch did not list was waved through. That is safe only for as long as every project-naming
+// channel is remembered in every switch, and it failed OPEN for the next one nobody added: a new
+// `githubIssues:*` verb would have reached another project's repository with no refusal anywhere.
+// So membership is by CLASS (channel prefix), and a method inside a class that this table cannot
+// read a projectId out of is answered as "names an unknown project" — which a scoped session
+// refuses. Adding a channel to a class therefore costs one table row to become reachable, rather
+// than one forgotten row to become a hole.
+//
+// `projects.*` is in the class although no IPC channel carries that prefix today: it is the phone
+// dialect's board verbs (`projects.ensureBoard` / `setCardColumn` / `editCardLabels`, served by
+// host-service to an approved PHONE, never on this tunnel). Classifying it here means that if a
+// relay guest ever sends one — or a future channel is named after it — it is judged by the shared
+// project rather than passed to a router on the assumption that nothing answers.
+//
+// Unscoped sessions are not affected at all: with no shared project the jail is off, exactly as
+// before (the host registry is then the only gate, as it is for the host's own renderer).
+
+import { IPC } from '../../shared/ipc'
+
+export interface ProjectScope {
+ /** The method belongs to a project-scoped channel class. */
+ scoped: boolean
+ /** The projectId it names — `undefined` when the class is known but the method is not, which
+ * the jail treats as "not the shared project" (fail closed). */
+ projectId: unknown
+}
+
+/** Channel prefixes whose every method acts on ONE project. */
+export const PROJECT_SCOPED_PREFIXES = ['githubIssues:', 'board-log:', 'projects.'] as const
+
+const fromFirstArg = (args: unknown[]): unknown => args[0]
+const fromFirstArgField = (args: unknown[]): unknown =>
+ args[0] && typeof args[0] === 'object' ? (args[0] as { projectId?: unknown }).projectId : undefined
+
+/** Methods whose projectId we know how to read. Everything else in a scoped class fails closed. */
+const EXTRACTORS: Record<string, (args: unknown[]) => unknown> = {
+ [IPC.githubIssuesSubscribe]: fromFirstArgField,
+ [IPC.githubIssuesQuery]: fromFirstArgField,
+ [IPC.githubIssuesMove]: fromFirstArgField,
+ [IPC.githubIssuesRefresh]: fromFirstArg,
+ [IPC.githubIssuesCreateLabels]: fromFirstArg,
+ [IPC.githubIssuesClearCache]: fromFirstArg,
+ [IPC.githubIssuesUnsubscribe]: fromFirstArg,
+ [IPC.boardLogAppend]: fromFirstArg,
+ [IPC.boardLogRead]: fromFirstArg,
+ [IPC.boardLogSubscribe]: fromFirstArg,
+ [IPC.boardLogUnsubscribe]: fromFirstArg,
+ // The phone dialect's params object, should one ever arrive as the first arg.
+ 'projects.ensureBoard': fromFirstArgField,
+ 'projects.setCardColumn': fromFirstArgField,
+ 'projects.editCardLabels': fromFirstArgField
+}
+
+export function projectScopeOf(method: string, args: unknown[]): ProjectScope {
+ if (!PROJECT_SCOPED_PREFIXES.some((p) => method.startsWith(p))) {
+ return { scoped: false, projectId: undefined }
+ }
+ const extract = EXTRACTORS[method]
+ return { scoped: true, projectId: extract ? extract(Array.isArray(args) ? args : []) : undefined }
+}
+
+/** True when a session bound to `sharedProjectId` must refuse this method. Unscoped ⇒ never. */
+export function outOfProjectScope(
+ sharedProjectId: string | undefined,
+ method: string,
+ args: unknown[]
+): boolean {
+ if (!sharedProjectId) return false
+ const scope = projectScopeOf(method, args)
+ return scope.scoped && scope.projectId !== sharedProjectId
+}
diff --git a/src/core/relay/relay-socket.ts b/src/core/relay/relay-socket.ts
new file mode 100644
index 000000000..227be28f4
--- /dev/null
+++ b/src/core/relay/relay-socket.ts
@@ -0,0 +1,750 @@
+// Relay socket + E2EE handshake + RPC/frame state machine (main process).
+//
+// A single connection to the dumb relay server (a separate repo). The relay
+// forwards opaque bytes between a host and a client matched by a pairing token;
+// it never decrypts. So the end-to-end-encrypted handshake and all traffic run
+// HOST<->CLIENT *through* the relay — the relay is not a handshake participant.
+//
+// The handshake/RPC state machine, in brief:
+// - The token gates entry at the relay via a `?token=<token>` QUERY PARAM on
+// the wss URL (matching what the relay expects). It is NOT
+// interleaved as a data frame — every frame on the wire is opaque peer
+// traffic.
+// - Handshake `e2ee_hello -> e2ee_ready -> e2ee_auth -> e2ee_authenticated`:
+// * client (knows the host pubkey) sends `e2ee_hello {publicKeyB64}` and
+// derives the shared key from the host pubkey;
+// * host learns the client pubkey from `e2ee_hello`, derives the same
+// shared key, replies `e2ee_ready`;
+// * client then sends an ENCRYPTED `e2ee_auth` (the relay already verified
+// the token and the offer pins the host pubkey, so for MVP a simple
+// authenticated marker is sufficient — no extra secret to prove);
+// * host replies an ENCRYPTED `e2ee_authenticated`. Both sides fire onReady
+// once their side of the auth exchange is complete.
+// - After authentication every peer message is an E2EE box (sent as binary).
+// The decrypted plaintext is tagged: 0x01 = JSON RPC envelope, 0x02 = a
+// binary terminal frame (framing.ts). Handshake control frames (`e2ee_hello`
+// / `e2ee_ready`) are sent as plaintext JSON strings so the receiver can tell
+// them apart from the encrypted binary boxes.
+//
+// Pure-ish: no IPC, no renderer. The WebSocket is INJECTED as a `RelayTransport`
+// so tests drive two RelaySockets via in-process fakes with no real network;
+// production passes a `ws` WebSocket wrapped via `wrapWebSocket`.
+
+import {
+ decrypt,
+ deriveSessionKey,
+ deriveSharedKey,
+ encrypt,
+ publicKeyToB64,
+ randomSessionNonce,
+ sasFromSharedKey,
+ type KeyPair
+} from './e2ee'
+import { decodeFrame, encodeFrame, type Frame, MAX_BINARY_BUFFERED_AMOUNT } from './framing'
+
+// A minimal duplex transport. `send` accepts a string (handshake control) or a
+// Uint8Array (encrypted box). `bufferedAmount` drives backpressure on frames.
+export interface RelayTransport {
+ readonly bufferedAmount: number
+ send(data: string | Uint8Array): void
+ close(): void
+ onMessage(cb: (data: unknown) => void): void
+ onClose(cb: () => void): void
+}
+
+// An RPC request envelope as seen by the peer's onRpc handler. `id` correlates a
+// later `respond`.
+export type RpcRequest = {
+ id: string
+ method: string
+ params: unknown
+}
+
+export type RelaySocket = {
+ // Send an RPC request to the peer; resolves with the peer's response body (or
+ // rejects on a non-ok response / timeout / closed connection).
+ rpc(method: string, params?: unknown): Promise<unknown>
+ // Fire a one-way notification to the peer (no response expected, never rejects).
+ // The peer receives it in `onRpc` with an empty `id` — answering it is a no-op
+ // (notifications carry no correlation id). Returns false if not connected.
+ notify(method: string, params?: unknown): boolean
+ // Answer a received RPC request (from onRpc) by its id.
+ respond(id: string, ok: boolean, body: unknown): void
+ // Send a terminal frame to the peer. Returns false when the transport is over
+ // its buffered-amount threshold (backpressure) or not connected.
+ sendFrame(op: number, streamId: number, seq: number, payload: Uint8Array): boolean
+ // The Short Authentication String for this channel (derived from the shared key), or null
+ // before the handshake has derived a key. Both peers compute the same value.
+ sas(): string | null
+ // The peer's NaCl box public key (base64) once known: for a client it is the pinned host key
+ // passed in; for a host it is learned from the client's `e2ee_hello`. Null before then. Used by
+ // the standing (phone) host to look the connecting device up in its pin-once approval list.
+ peerPublicKeyB64(): string | null
+ // --- 4c tunnel: the Server Edition's rpc.ts protocol, carried inside the E2EE box ------------
+ // Send one rpc.ts TEXT frame (a JSON RpcMessage). False if the channel is not ready — a tunnel
+ // frame is NEVER sent in the clear.
+ sendTunnelText(json: string): boolean
+ // Send one rpc.ts BINARY frame (encodePtyData bytes). False if the channel is not ready.
+ sendTunnelBinary(bytes: Uint8Array): boolean
+ // Bytes handed to the underlying socket but not yet flushed (ws.bufferedAmount + anything still
+ // sitting in the pre-open queue). This is the number Stage 2's per-client backpressure and the
+ // 8 MB WS_DROP_WATER drop-and-redraw ceiling key on (see src/core/ui-sink-registry.ts): a sink
+ // that reports 0 silently disables the ceiling, and a slow peer then queues pty output without
+ // bound until the host process dies. It must stay honest.
+ bufferedAmount(): number
+ // Tear down: stops reconnects and closes the transport.
+ close(): void
+}
+
+export type ConnectRelayOptions = {
+ // The relay wss URL. `?token=` is appended automatically when opening a socket.
+ url: string
+ // Single-use pairing token; gates entry at the relay (query param).
+ token: string
+ role: 'host' | 'client'
+ // Our long-lived (host) or ephemeral (client) NaCl keypair.
+ ourKeys: KeyPair
+ // The peer's public key, base64. REQUIRED for the client (it must know the
+ // host's pubkey up front); for the host it is learned from `e2ee_hello`.
+ theirPubB64?: string
+ // Injected transport. Tests pass an in-process fake; production passes a `ws`
+ // WebSocket wrapped via `wrapWebSocket`. When omitted, a `ws` socket is opened
+ // from `url` (production default).
+ transport?: RelayTransport
+ onReady(): void
+ onRpc(msg: RpcRequest): void
+ onFrame(f: Frame): void
+ onClose(): void
+ // An rpc.ts frame arrived over the ENCRYPTED, session-keyed, role-tagged, replay-checked
+ // channel. This is the ONLY inbound path 4c's trust + RPC layers may trust: anything that did
+ // not come out of the E2EE box never reaches here.
+ onTunnel?(kind: 'text' | 'binary', payload: Uint8Array): void
+}
+
+// Plaintext-tag bytes for decrypted peer payloads.
+const TAG_RPC = 0x01
+const TAG_FRAME = 0x02
+// 4c tunnel: the Server Edition's rpc.ts protocol, carried verbatim inside the E2EE box. Text = a
+// JSON RpcMessage; binary = an encodePtyData frame. Both ride the SAME encrypted stream as
+// everything else — same sendSeq counter, same FIFO delivery — because Stage 3's canvas
+// convergence needs a single ordered channel per client.
+const TAG_TUNNEL_TEXT = 0x03
+const TAG_TUNNEL_BIN = 0x04
+
+const RPC_TIMEOUT_MS = 30_000
+const KEEPALIVE_INTERVAL_MS = 25_000
+const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000, 15_000]
+
+type RpcEnvelope =
+ | { kind: 'req'; id: string; method: string; params: unknown }
+ | { kind: 'notify'; method: string; params: unknown }
+ | { kind: 'res'; id: string; ok: boolean; body: unknown }
+ | { kind: 'keepalive' }
+
+type HandshakeControl =
+ | { type: 'e2ee_hello'; publicKeyB64: string; nonceB64: string }
+ | { type: 'e2ee_ready'; nonceB64: string }
+
+function nonceToB64(n: Uint8Array): string {
+ return Buffer.from(n).toString('base64')
+}
+function nonceFromB64(b64: unknown): Uint8Array | null {
+ if (typeof b64 !== 'string') return null
+ const n = Uint8Array.from(Buffer.from(b64, 'base64'))
+ return n.length === 16 ? n : null
+}
+
+type State = 'connecting' | 'handshaking' | 'ready' | 'closed'
+
+const textEncoder = new TextEncoder()
+const textDecoder = new TextDecoder()
+
+export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
+ if (opts.role === 'client' && !opts.theirPubB64) {
+ throw new Error('connectRelay: client role requires theirPubB64 (the host public key)')
+ }
+
+ let transport: RelayTransport | null = null
+ // baseKey = the stable ECDH precompute (for the SAS, which represents the pinned identity).
+ // sessionKey = HKDF(baseKey, hostNonce‖clientNonce) = the fresh per-session traffic key.
+ let baseKey: Uint8Array | null = null
+ let sessionKey: Uint8Array | null = null
+ let ourNonce: Uint8Array | null = null
+ // Role byte prefixed to every sealed plaintext, so a relay can't REFLECT a box back to its
+ // sender (same sessionKey both directions): each side only accepts boxes tagged with the peer's
+ // role. host=1, client=2.
+ const OUR_ROLE = opts.role === 'host' ? 1 : 2
+ const PEER_ROLE = opts.role === 'host' ? 2 : 1
+ // The peer's base64 public key. Known up front for a client (the pinned host key); learned from
+ // `e2ee_hello` for a host. Exposed via peerPublicKeyB64() for the standing host's pin-once check.
+ let peerPubB64: string | null = opts.role === 'client' ? opts.theirPubB64 ?? null : null
+ let state: State = 'connecting'
+ let intentionallyClosed = false
+ let reconnectAttempt = 0
+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null
+ let keepaliveTimer: ReturnType<typeof setInterval> | null = null
+ let requestCounter = 0
+ let readyFired = false
+ // Replay/reorder protection: every encrypted message carries a strictly-increasing per-
+ // direction counter inside the authenticated plaintext. The receiver rejects any message whose
+ // counter is not greater than the last accepted one, so a relay (or on-path attacker) cannot
+ // replay a captured box (e.g. re-injecting an OP.Input keystroke frame or a pty.kill RPC) nor
+ // reorder traffic. Counters reset per (re)connection — a fresh handshake is a fresh stream.
+ let sendSeq = 0
+ let recvSeq = -1
+
+ const pending = new Map<
+ string,
+ { resolve: (body: unknown) => void; reject: (err: Error) => void; timer: ReturnType<typeof setTimeout> }
+ >()
+
+ function buildUrl(): string {
+ // Append `?token=` so the relay can read the pairing token from the query
+ // string. Preserve any existing query.
+ const sep = opts.url.includes('?') ? '&' : '?'
+ return `${opts.url}${sep}token=${encodeURIComponent(opts.token)}`
+ }
+
+ function openConnection(): void {
+ if (intentionallyClosed) {
+ return
+ }
+ state = 'connecting'
+ baseKey = null
+ sessionKey = null
+ ourNonce = randomSessionNonce()
+ readyFired = false
+ sendSeq = 0
+ recvSeq = -1
+
+ if (opts.transport) {
+ // Injected transport (tests). It is already "open"; treat that as the
+ // open event. A re-open after a drop is not supported for injected
+ // transports — production reconnect goes through the real ws path.
+ transport = opts.transport
+ } else {
+ transport = openWebSocketTransport(buildUrl())
+ }
+
+ transport.onMessage((data) => handleMessage(data))
+ transport.onClose(() => handleClose())
+
+ state = 'handshaking'
+ if (opts.role === 'client') {
+ // Client knows the host pubkey: derive the base (identity) key now and greet with our
+ // session nonce. The traffic key is derived once the host's nonce arrives in e2ee_ready.
+ baseKey = deriveSharedKey(opts.theirPubB64!, opts.ourKeys.secretKey)
+ sendControl({
+ type: 'e2ee_hello',
+ publicKeyB64: publicKeyToB64(opts.ourKeys.publicKey),
+ nonceB64: nonceToB64(ourNonce!)
+ })
+ }
+ // Host waits passively for `e2ee_hello` to learn the client pubkey.
+ }
+
+ function sendControl(control: HandshakeControl): void {
+ transport?.send(JSON.stringify(control))
+ }
+
+ // Prepend the outbound monotonic counter (8 bytes LE) to the plaintext before sealing, so the
+ // peer can reject replays/reorders. Mirrors framing.ts's 64-bit split to stay within safe ints.
+ // Authenticated plaintext layout: [role:1][seq:8][payload…]. The role defeats reflection; the
+ // strictly-increasing seq defeats in-session replay/reorder.
+ const SEQ_BYTES = 8
+ const HEADER_BYTES = 1 + SEQ_BYTES
+ function withHeader(plaintext: Uint8Array): Uint8Array {
+ const seq = sendSeq++
+ const out = new Uint8Array(HEADER_BYTES + plaintext.length)
+ out[0] = OUR_ROLE
+ const view = new DataView(out.buffer)
+ view.setUint32(1, Math.floor(seq / 0x100000000), true)
+ view.setUint32(5, seq >>> 0, true)
+ out.set(plaintext, HEADER_BYTES)
+ return out
+ }
+
+ function sendEncrypted(plaintext: Uint8Array): boolean {
+ if (!transport || !sessionKey || state !== 'ready') {
+ return false
+ }
+ transport.send(encrypt(withHeader(plaintext), sessionKey))
+ return true
+ }
+
+ // During the handshake the auth control frames must be sent before `state`
+ // flips to 'ready', so this variant does not gate on state.
+ function sendEncryptedHandshake(plaintext: Uint8Array): void {
+ if (!transport || !sessionKey) {
+ return
+ }
+ transport.send(encrypt(withHeader(plaintext), sessionKey))
+ }
+
+ function tagged(tag: number, body: Uint8Array): Uint8Array {
+ const out = new Uint8Array(body.length + 1)
+ out[0] = tag
+ out.set(body, 1)
+ return out
+ }
+
+ function fireReadyOnce(): void {
+ if (readyFired) {
+ return
+ }
+ readyFired = true
+ reconnectAttempt = 0
+ startKeepalive()
+ opts.onReady()
+ }
+
+ function handleMessage(data: unknown): void {
+ if (state === 'closed') {
+ return
+ }
+
+ const asString = stringFromData(data)
+ if (asString !== null) {
+ // Plaintext JSON => a handshake control frame.
+ handleControl(asString)
+ return
+ }
+
+ const bytes = bytesFromData(data)
+ if (!bytes) {
+ return
+ }
+
+ // Everything binary is an E2EE box, sealed under the fresh session key.
+ if (!sessionKey) {
+ return
+ }
+ const sealed = decrypt(bytes, sessionKey)
+ if (!sealed || sealed.length < HEADER_BYTES) {
+ return
+ }
+ // Reject a box tagged with our OWN role (a reflected message) — only the peer's role is valid.
+ if (sealed[0] !== PEER_ROLE) {
+ return
+ }
+ // Enforce the strictly-increasing per-direction counter inside the authenticated plaintext.
+ // A non-increasing counter means a replayed or reordered box — drop it.
+ const seqView = new DataView(sealed.buffer, sealed.byteOffset, sealed.byteLength)
+ const seq = seqView.getUint32(1, true) * 0x100000000 + seqView.getUint32(5, true)
+ if (seq <= recvSeq) {
+ return
+ }
+ recvSeq = seq
+ const plain = sealed.subarray(HEADER_BYTES)
+
+ if (state === 'handshaking') {
+ handleHandshakeEncrypted(plain)
+ return
+ }
+ if (state !== 'ready') {
+ return
+ }
+ handlePeerPlaintext(plain)
+ }
+
+ function handleControl(raw: string): void {
+ // SECURITY: a handshake control frame (`e2ee_hello` / `e2ee_ready`) is legitimate ONLY during the
+ // one handshake, i.e. before the session goes ready. Once ready, re-processing one would let a
+ // relay MITM RE-KEY a live session under its own keypair (re-deriving baseKey/sessionKey and
+ // overwriting peerPubB64) and then forge the peer's encrypted `trust:confirm` under the swapped
+ // key — degrading mutual approval to one-way (see docs/remote-sessions.md, obligation (a)). The
+ // real peer never re-sends a hello on an established session, so such a frame is an attack or a
+ // bug, never legitimate. Drop it WITHOUT re-keying: the derived session identity (SAS + peer key)
+ // stays frozen. We do NOT close the socket — the relay already fully controls the transport
+ // (it can drop us at will), so closing would add no real protection while handing a MITM a
+ // trivial way to tear down an established, mutually-approved session with one plaintext frame.
+ // Ignoring keeps the good session robust; layer 2 (relay-host key binding) independently
+ // guarantees no traffic or approval can advance under a swapped key even if this check regressed.
+ if (readyFired) {
+ return
+ }
+ let control: HandshakeControl
+ try {
+ control = JSON.parse(raw) as HandshakeControl
+ } catch {
+ return
+ }
+ if (control.type === 'e2ee_hello' && opts.role === 'host') {
+ // Host learns the client pubkey + its session nonce, derives the base identity key and the
+ // fresh session traffic key, replies ready with its own nonce.
+ const clientNonce = nonceFromB64(control.nonceB64)
+ if (typeof control.publicKeyB64 !== 'string' || !clientNonce || !ourNonce) {
+ return
+ }
+ peerPubB64 = control.publicKeyB64
+ baseKey = deriveSharedKey(control.publicKeyB64, opts.ourKeys.secretKey)
+ // salt = hostNonce ‖ clientNonce (host's nonce first, both roles agree on the order).
+ sessionKey = deriveSessionKey(baseKey, ourNonce, clientNonce)
+ sendControl({ type: 'e2ee_ready', nonceB64: nonceToB64(ourNonce) })
+ return
+ }
+ if (control.type === 'e2ee_ready' && opts.role === 'client') {
+ // Client learns the host's nonce, derives the same session key, and proves the pairing with
+ // an encrypted auth marker. The marker is sealed under the SESSION key (which mixes in this
+ // session's fresh nonces), so a recorded auth box from an earlier session can't be replayed
+ // to silently authenticate a new one.
+ const hostNonce = nonceFromB64(control.nonceB64)
+ if (!hostNonce || !baseKey || !ourNonce) {
+ return
+ }
+ sessionKey = deriveSessionKey(baseKey, hostNonce, ourNonce)
+ sendEncryptedHandshake(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ type: 'e2ee_auth' }))))
+ }
+ }
+
+ function handleHandshakeEncrypted(plain: Uint8Array): void {
+ // Tag byte distinguishes control vs payload; during handshake we only expect
+ // control JSON (auth / authenticated).
+ if (plain.length < 1 || plain[0] !== TAG_RPC) {
+ return
+ }
+ let msg: { type?: string }
+ try {
+ msg = JSON.parse(textDecoder.decode(plain.subarray(1))) as { type?: string }
+ } catch {
+ return
+ }
+ if (msg.type === 'e2ee_auth' && opts.role === 'host') {
+ // Host accepts the client's authenticated marker, confirms, becomes ready.
+ sendEncryptedHandshake(
+ tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ type: 'e2ee_authenticated' })))
+ )
+ state = 'ready'
+ fireReadyOnce()
+ return
+ }
+ if (msg.type === 'e2ee_authenticated' && opts.role === 'client') {
+ state = 'ready'
+ fireReadyOnce()
+ }
+ }
+
+ function handlePeerPlaintext(plain: Uint8Array): void {
+ if (plain.length < 1) {
+ return
+ }
+ const tag = plain[0]
+ const body = plain.subarray(1)
+ if (tag === TAG_TUNNEL_TEXT) {
+ opts.onTunnel?.('text', body)
+ return
+ }
+ if (tag === TAG_TUNNEL_BIN) {
+ opts.onTunnel?.('binary', body)
+ return
+ }
+ if (tag === TAG_FRAME) {
+ const frame = decodeFrame(body)
+ if (frame) {
+ opts.onFrame(frame)
+ }
+ return
+ }
+ if (tag !== TAG_RPC) {
+ return
+ }
+ let env: RpcEnvelope
+ try {
+ env = JSON.parse(textDecoder.decode(body)) as RpcEnvelope
+ } catch {
+ return
+ }
+ if (env.kind === 'keepalive') {
+ return
+ }
+ if (env.kind === 'req') {
+ opts.onRpc({ id: env.id, method: env.method, params: env.params })
+ return
+ }
+ if (env.kind === 'notify') {
+ // One-way notification: surface it like an RPC but with an empty id, so a
+ // `respond` (if any) is a no-op (no matching pending request on our side).
+ opts.onRpc({ id: '', method: env.method, params: env.params })
+ return
+ }
+ if (env.kind === 'res') {
+ const waiter = pending.get(env.id)
+ if (!waiter) {
+ return
+ }
+ pending.delete(env.id)
+ clearTimeout(waiter.timer)
+ if (env.ok) {
+ waiter.resolve(env.body)
+ } else {
+ waiter.reject(new Error(rpcErrorMessage(env.body)))
+ }
+ }
+ }
+
+ function startKeepalive(): void {
+ stopKeepalive()
+ keepaliveTimer = setInterval(() => {
+ sendEncrypted(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'keepalive' }))))
+ }, KEEPALIVE_INTERVAL_MS)
+ // Don't keep the event loop alive purely for keepalives.
+ keepaliveTimer.unref?.()
+ }
+
+ function stopKeepalive(): void {
+ if (keepaliveTimer) {
+ clearInterval(keepaliveTimer)
+ keepaliveTimer = null
+ }
+ }
+
+ function handleClose(): void {
+ stopKeepalive()
+ transport = null
+ baseKey = null
+ sessionKey = null
+ const wasReady = state === 'ready'
+ rejectAllPending('Relay connection closed.')
+ if (intentionallyClosed) {
+ state = 'closed'
+ return
+ }
+ state = 'closed'
+ // Reconnect is the CALLER's responsibility (via onClose), NOT this socket's. Re-dialing here
+ // would reuse the same pairing token, which the relay rejects after its short TTL — and worse,
+ // for a standing host it fights the caller's fresh-token reconnect, repeatedly clobbering the
+ // new session so the connection never restabilises. So we fire onClose once and stop; the
+ // standing host mints a fresh token and reconnects cleanly.
+ void wasReady
+ opts.onClose()
+ }
+
+ // (Internal same-token reconnect removed — see handleClose. The caller reconnects with a fresh
+ // token.)
+ function scheduleReconnect(): void {
+ if (reconnectTimer || intentionallyClosed) {
+ return
+ }
+ const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]
+ reconnectAttempt += 1
+ reconnectTimer = setTimeout(() => {
+ reconnectTimer = null
+ openConnection()
+ }, delay)
+ reconnectTimer.unref?.()
+ }
+
+ function rejectAllPending(reason: string): void {
+ const err = new Error(reason)
+ for (const [id, waiter] of pending) {
+ pending.delete(id)
+ clearTimeout(waiter.timer)
+ waiter.reject(err)
+ }
+ }
+
+ function nextId(): string {
+ requestCounter += 1
+ return `${opts.role}-rpc-${requestCounter}-${Date.now()}`
+ }
+
+ openConnection()
+
+ return {
+ rpc(method, params) {
+ return new Promise((resolve, reject) => {
+ const id = nextId()
+ const timer = setTimeout(() => {
+ pending.delete(id)
+ reject(new Error(`RPC timed out: ${method}`))
+ }, RPC_TIMEOUT_MS)
+ timer.unref?.()
+ pending.set(id, { resolve, reject, timer })
+ const sent = sendEncrypted(
+ tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'req', id, method, params })))
+ )
+ if (!sent) {
+ pending.delete(id)
+ clearTimeout(timer)
+ reject(new Error('Relay socket is not connected.'))
+ }
+ })
+ },
+ notify(method, params) {
+ return sendEncrypted(
+ tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'notify', method, params })))
+ )
+ },
+ respond(id, ok, body) {
+ sendEncrypted(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'res', id, ok, body }))))
+ },
+ sendFrame(op, streamId, seq, payload) {
+ if (!transport || state !== 'ready') {
+ return false
+ }
+ if (transport.bufferedAmount > MAX_BINARY_BUFFERED_AMOUNT) {
+ return false
+ }
+ return sendEncrypted(tagged(TAG_FRAME, encodeFrame(op, streamId, seq, payload)))
+ },
+ sendTunnelText(json) {
+ return sendEncrypted(tagged(TAG_TUNNEL_TEXT, textEncoder.encode(json)))
+ },
+ sendTunnelBinary(bytes) {
+ return sendEncrypted(tagged(TAG_TUNNEL_BIN, bytes))
+ },
+ bufferedAmount() {
+ // Honest by construction: the transport reports what it has been handed and has not yet
+ // flushed. No backpressure decision is made here — the caller (ui-sink-registry) owns the
+ // thresholds; this only has to tell the truth. Not connected => nothing is queued => 0.
+ return transport?.bufferedAmount ?? 0
+ },
+ sas() {
+ return baseKey ? sasFromSharedKey(baseKey) : null
+ },
+ peerPublicKeyB64() {
+ return peerPubB64
+ },
+ close() {
+ intentionallyClosed = true
+ if (reconnectTimer) {
+ clearTimeout(reconnectTimer)
+ reconnectTimer = null
+ }
+ stopKeepalive()
+ rejectAllPending('Relay socket closed.')
+ state = 'closed'
+ transport?.close()
+ transport = null
+ baseKey = null
+ sessionKey = null
+ }
+ }
+}
+
+function rpcErrorMessage(body: unknown): string {
+ if (body && typeof body === 'object') {
+ const maybe = body as { message?: unknown; error?: unknown }
+ if (typeof maybe.message === 'string') {
+ return maybe.message
+ }
+ if (typeof maybe.error === 'string') {
+ return maybe.error
+ }
+ }
+ return 'RPC failed.'
+}
+
+// --- transport payload coercion ---------------------------------------------
+
+function stringFromData(data: unknown): string | null {
+ if (typeof data === 'string') {
+ return data
+ }
+ return null
+}
+
+function bytesFromData(data: unknown): Uint8Array | null {
+ if (data instanceof Uint8Array) {
+ return data
+ }
+ if (data instanceof ArrayBuffer) {
+ return new Uint8Array(data)
+ }
+ // `ws` may deliver a Node Buffer (which is a Uint8Array) or an array of
+ // Buffers when fragmented; handle the array case defensively.
+ if (Array.isArray(data) && data.every((d) => d instanceof Uint8Array)) {
+ const total = data.reduce((n, d) => n + (d as Uint8Array).length, 0)
+ const out = new Uint8Array(total)
+ let offset = 0
+ for (const d of data as Uint8Array[]) {
+ out.set(d, offset)
+ offset += d.length
+ }
+ return out
+ }
+ return null
+}
+
+// --- production ws wrapper ----------------------------------------------------
+
+// Wrap a connected `ws` WebSocket as a RelayTransport. Kept here so the host
+// (Task 6) and client (Task 7) share one ws adapter. Imported lazily so the
+// pure module + its tests never load `ws`.
+export function wrapWebSocket(ws: import('ws').WebSocket): RelayTransport {
+ ws.binaryType = 'nodebuffer'
+ return {
+ get bufferedAmount() {
+ return ws.bufferedAmount
+ },
+ // Strings (handshake control) go out as ws *text* frames; Uint8Array (E2EE boxes) as ws
+ // *binary*. The relay preserves that text/binary-ness end to end.
+ send: (data) => ws.send(data, { binary: typeof data !== 'string' }),
+ close: () => ws.close(),
+ // Deliver ws *text* frames as JS strings and *binary* frames as bytes, so relay-socket's
+ // type-based control-vs-box discrimination works. (`ws` hands us a Buffer for both unless we
+ // consult `isBinary`.)
+ onMessage: (cb) =>
+ ws.on('message', (data: Buffer, isBinary: boolean) =>
+ cb(isBinary ? data : data.toString('utf-8'))
+ ),
+ onClose: (cb) => {
+ // Fire `cb` on EITHER a close OR an error, exactly once. A ws `error` (a 504 upgrade timeout,
+ // a TLS/DNS failure, connection refused) is otherwise an UNHANDLED 'error' event, which Node
+ // re-throws as an uncaught exception that crashes the whole app. Treat it as a close so the
+ // caller tears the session down / reconnects gracefully instead. The caller registers this
+ // synchronously right after opening (relay-socket connectRelay), before any async error fires.
+ let fired = false
+ const fire = (): void => {
+ if (fired) return
+ fired = true
+ cb()
+ }
+ ws.on('close', fire)
+ ws.on('error', fire)
+ }
+ }
+}
+
+// Open a `ws` WebSocket to `url` and return it wrapped. Sends start only once
+// the socket is open; messages before open are dropped (the handshake retries on
+// reconnect). Used as the production default when no transport is injected.
+function openWebSocketTransport(url: string): RelayTransport {
+ // Lazy require so test/pure consumers don't pull in the native-ish dep.
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const WS = require('ws') as typeof import('ws')
+ const ws = new WS.WebSocket(url)
+ ws.binaryType = 'nodebuffer'
+ const wrapped = wrapWebSocket(ws)
+ // Buffer sends issued before 'open'.
+ const queue: (string | Uint8Array)[] = []
+ let open = false
+ // Bytes sitting in `queue`. They are real, un-flushed bytes that `ws.bufferedAmount` cannot see
+ // (the socket has not been handed them yet), so leaving them out would make bufferedAmount lie
+ // during exactly the window in which a burst can pile up — and a backpressure ceiling that
+ // believes the lie stops capping, letting the host queue pty output without bound.
+ let queuedBytes = 0
+ ws.on('open', () => {
+ open = true
+ for (const item of queue.splice(0)) {
+ ws.send(item)
+ }
+ queuedBytes = 0
+ })
+ return {
+ get bufferedAmount() {
+ return ws.bufferedAmount + queuedBytes
+ },
+ send: (data) => {
+ if (open) {
+ ws.send(data)
+ } else {
+ queue.push(data)
+ queuedBytes += typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength
+ }
+ },
+ close: () => ws.close(),
+ onMessage: wrapped.onMessage,
+ onClose: wrapped.onClose
+ }
+}
diff --git a/src/main/remote/approved-devices-core.ts b/src/main/remote/approved-devices-core.ts
index 7715eebe8..07ce8ab7c 100644
--- a/src/main/remote/approved-devices-core.ts
+++ b/src/main/remote/approved-devices-core.ts
@@ -1,52 +1,4 @@
-// Pure pin/lookup logic for the standing (phone) host's "pin once" device approval.
-//
-// The FIRST time a phone (identified by its NaCl box public key, base64) connects over the relay
-// the host human approves it via the SAS dialog; on approval its pubkey is pinned here so future
-// connects auto-approve with no prompt. These are PUBLIC keys, not credentials — safe to persist.
-//
-// Kept pure (no I/O) so it can be unit-tested; the disk read/write wrapper lives in
-// `approved-devices.ts`.
-
-/** The persisted shape of <userData>/remote-approved-devices.json. */
-export interface ApprovedDevices {
- /** Base64 NaCl box public keys of phones the host has approved at least once. */
- pubkeys: string[]
-}
-
-export function emptyApprovedDevices(): ApprovedDevices {
- return { pubkeys: [] }
-}
-
-/** Coerce arbitrary parsed JSON into a well-formed ApprovedDevices (drops non-string / empty entries). */
-export function parseApprovedDevices(raw: unknown): ApprovedDevices {
- if (!raw || typeof raw !== 'object') return emptyApprovedDevices()
- const pubkeys = (raw as { pubkeys?: unknown }).pubkeys
- if (!Array.isArray(pubkeys)) return emptyApprovedDevices()
- // De-dupe while preserving order; keep only non-empty strings.
- const seen = new Set<string>()
- const out: string[] = []
- for (const k of pubkeys) {
- if (typeof k === 'string' && k.length > 0 && !seen.has(k)) {
- seen.add(k)
- out.push(k)
- }
- }
- return { pubkeys: out }
-}
-
-/** True when `pubkeyB64` has been pinned before. Empty input is never pinned. */
-export function isPinned(store: ApprovedDevices, pubkeyB64: string): boolean {
- return pubkeyB64.length > 0 && store.pubkeys.includes(pubkeyB64)
-}
-
-/** Return a store with `pubkeyB64` pinned. Idempotent; returns the same object when already present. */
-export function pinDevice(store: ApprovedDevices, pubkeyB64: string): ApprovedDevices {
- if (pubkeyB64.length === 0 || store.pubkeys.includes(pubkeyB64)) return store
- return { pubkeys: [...store.pubkeys, pubkeyB64] }
-}
-
-/** Return a store with `pubkeyB64` unpinned (revoke). Idempotent. */
-export function unpinDevice(store: ApprovedDevices, pubkeyB64: string): ApprovedDevices {
- if (!store.pubkeys.includes(pubkeyB64)) return store
- return { pubkeys: store.pubkeys.filter((k) => k !== pubkeyB64) }
-}
+// Moved to src/core/relay/approved-devices-core.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./approved-devices-core') in the existing tests — working unchanged.
+export * from '../../core/relay/approved-devices-core'
diff --git a/src/main/remote/e2ee.ts b/src/main/remote/e2ee.ts
index 11e986d86..43b4a1ae1 100644
--- a/src/main/remote/e2ee.ts
+++ b/src/main/remote/e2ee.ts
@@ -1,107 +1,4 @@
-// End-to-end encryption primitives for the relay transport.
-//
-// Pure functions over NaCl box (Curve25519 + XSalsa20-Poly1305): no sockets, no
-// Electron. The box format is `nonce ‖ ciphertext ‖ mac` so an interoperable peer
-// can be implemented against the same wire format.
-import { hkdfSync } from 'node:crypto'
-import nacl from 'tweetnacl'
-
-export type KeyPair = {
- publicKey: Uint8Array
- secretKey: Uint8Array
-}
-
-export function genKeyPair(): KeyPair {
- return nacl.box.keyPair()
-}
-
-export function publicKeyToB64(key: Uint8Array): string {
- return Buffer.from(key).toString('base64')
-}
-
-export function publicKeyFromB64(b64: string): Uint8Array {
- const key = Uint8Array.from(Buffer.from(b64, 'base64'))
- if (key.length !== nacl.box.publicKeyLength) {
- throw new Error(`Invalid public key: expected ${nacl.box.publicKeyLength} bytes, got ${key.length}`)
- }
- return key
-}
-
-// Same strictness for a secret key: `Buffer.from(x, 'base64')` silently drops non-alphabet
-// characters and truncates, so a corrupt/short blob would otherwise decode to a short-but-accepted
-// key that only blows up ("bad secret key size") deep inside a later nacl.box call.
-export function secretKeyFromB64(b64: string): Uint8Array {
- const key = Uint8Array.from(Buffer.from(b64, 'base64'))
- if (key.length !== nacl.box.secretKeyLength) {
- throw new Error(`Invalid secret key: expected ${nacl.box.secretKeyLength} bytes, got ${key.length}`)
- }
- return key
-}
-
-// Derive the shared secret (ECDH precompute) from the peer's base64 public key
-// and our secret key. Both sides arrive at the same value. This is the STABLE
-// per-device-pair key (both endpoints use static keys for pin-once), so it must
-// NOT be used directly to encrypt traffic — see deriveSessionKey.
-export function deriveSharedKey(theirPubB64: string, ourSecret: Uint8Array): Uint8Array {
- const theirPub = publicKeyFromB64(theirPubB64)
- return nacl.box.before(theirPub, ourSecret)
-}
-
-// A fresh 16-byte session nonce, exchanged in the handshake.
-export function randomSessionNonce(): Uint8Array {
- return nacl.randomBytes(16)
-}
-
-// Per-SESSION traffic key = HKDF-SHA256(baseShared, salt = hostNonce ‖ clientNonce).
-// Because both endpoints hold STATIC keys (stable pin-once identity), the raw ECDH
-// `baseShared` is identical on every reconnect — encrypting with it lets a malicious
-// relay replay a whole recorded session's boxes against a fresh connection (the seq
-// counter resets per connection, so it can't stop this). Mixing in fresh per-session
-// nonces makes the traffic key unique to each session, so recorded boxes never decrypt
-// under a later session's key. RFC 5869 HKDF; matches iOS CryptoKit HKDF<SHA256>.
-export function deriveSessionKey(
- baseShared: Uint8Array,
- hostNonce: Uint8Array,
- clientNonce: Uint8Array
-): Uint8Array {
- const salt = new Uint8Array(hostNonce.length + clientNonce.length)
- salt.set(hostNonce)
- salt.set(clientNonce, hostNonce.length)
- const info = new TextEncoder().encode('nodeterm-relay-session-v2')
- const out = hkdfSync('sha256', baseShared, salt, info, 32)
- return new Uint8Array(out)
-}
-
-// Encrypt with the precomputed shared key. Returns `nonce ‖ ciphertext ‖ mac`.
-export function encrypt(plain: Uint8Array, shared: Uint8Array): Uint8Array {
- const nonce = nacl.randomBytes(nacl.box.nonceLength)
- const ciphertext = nacl.box.after(plain, nonce, shared)
-
- const box = new Uint8Array(nonce.length + ciphertext.length)
- box.set(nonce)
- box.set(ciphertext, nonce.length)
- return box
-}
-
-// Short Authentication String: a 6-digit code derived from the ECDH shared key. Both peers
-// compute the SAME value (same shared key), so the two humans can compare it out-of-band to
-// confirm they're on the same channel before the host approves a connection. Formatted "NNN NNN".
-export function sasFromSharedKey(shared: Uint8Array): string {
- const h = nacl.hash(shared) // SHA-512
- // Fold the first 4 bytes into a 32-bit int, then take 6 decimal digits.
- const n = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0
- const code = (n % 1_000_000).toString().padStart(6, '0')
- return `${code.slice(0, 3)} ${code.slice(3)}`
-}
-
-// Decrypt a `nonce ‖ ciphertext ‖ mac` box. Returns null on malformed input or
-// a failed MAC check — never throws.
-export function decrypt(box: Uint8Array, shared: Uint8Array): Uint8Array | null {
- if (box.length < nacl.box.nonceLength + nacl.box.overheadLength) {
- return null
- }
- const nonce = box.slice(0, nacl.box.nonceLength)
- const ciphertext = box.slice(nacl.box.nonceLength)
- const plain = nacl.box.open.after(ciphertext, nonce, shared)
- return plain ?? null
-}
+// Moved to src/core/relay/e2ee.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./e2ee') in the existing tests — working unchanged.
+export * from '../../core/relay/e2ee'
diff --git a/src/main/remote/framing.ts b/src/main/remote/framing.ts
index b56d16512..d3bb1f7a8 100644
--- a/src/main/remote/framing.ts
+++ b/src/main/remote/framing.ts
@@ -1,88 +1,4 @@
-// Terminal-stream binary framing for the relay transport.
-//
-// The 16-byte header layout and opcode numbers are stable wire constants so an
-// interoperable peer can be implemented against them. Pure functions: no sockets,
-// no Electron.
-//
-// Header (16 bytes, little-endian where multi-byte):
-// [0] kind = 0x74
-// [1] version = 1
-// [2] opcode
-// [3] reserved (0)
-// [4..8) streamId (uint32 LE)
-// [8..12) seq high (uint32 LE)
-// [12..16) seq low (uint32 LE)
-// followed by the raw payload.
-
-const STREAM_KIND = 0x74
-const STREAM_VERSION = 1
-const HEADER_BYTES = 16
-
-// Opcode numbers are part of the stable wire contract — do not renumber.
-export const OP = {
- Output: 1,
- SnapshotStart: 2,
- SnapshotChunk: 3,
- SnapshotEnd: 4,
- Resized: 5,
- Error: 6,
- Input: 7,
- Resize: 8,
- Subscribe: 9,
- Unsubscribe: 10,
- SnapshotRequest: 11
-} as const
-
-export type Opcode = (typeof OP)[keyof typeof OP]
-
-export type Frame = {
- op: number
- streamId: number
- seq: number
- payload: Uint8Array
-}
-
-// Max bytes we let buffer on a binary channel before applying backpressure.
-// Kept here so the host/client transports share one threshold.
-export const MAX_BINARY_BUFFERED_AMOUNT = 8 * 1024 * 1024
-
-const KNOWN_OPCODES = new Set<number>(Object.values(OP))
-
-export function encodeFrame(op: number, streamId: number, seq: number, payload: Uint8Array): Uint8Array {
- const out = new Uint8Array(HEADER_BYTES + payload.length)
- const view = new DataView(out.buffer, out.byteOffset, out.byteLength)
- view.setUint8(0, STREAM_KIND)
- view.setUint8(1, STREAM_VERSION)
- view.setUint8(2, op)
- view.setUint8(3, 0)
- view.setUint32(4, streamId, true)
- const s = Math.max(0, Math.floor(seq))
- view.setUint32(8, Math.floor(s / 0x100000000), true)
- view.setUint32(12, s >>> 0, true)
- out.set(payload, HEADER_BYTES)
- return out
-}
-
-// Decode a frame. Returns null for short buffers, a bad kind/version, or an
-// unknown opcode — never throws.
-export function decodeFrame(buf: Uint8Array): Frame | null {
- if (buf.length < HEADER_BYTES) {
- return null
- }
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
- if (view.getUint8(0) !== STREAM_KIND || view.getUint8(1) !== STREAM_VERSION) {
- return null
- }
- const op = view.getUint8(2)
- if (!KNOWN_OPCODES.has(op)) {
- return null
- }
- const high = view.getUint32(8, true)
- const low = view.getUint32(12, true)
- return {
- op,
- streamId: view.getUint32(4, true),
- seq: high * 0x100000000 + low,
- payload: buf.slice(HEADER_BYTES)
- }
-}
+// Moved to src/core/relay/framing.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./framing') in the existing tests — working unchanged.
+export * from '../../core/relay/framing'
diff --git a/src/main/remote/key-file-codec.ts b/src/main/remote/key-file-codec.ts
index 82a993e71..2f862e38d 100644
--- a/src/main/remote/key-file-codec.ts
+++ b/src/main/remote/key-file-codec.ts
@@ -1,89 +1,4 @@
-// Pure encode/decode for a persisted NaCl box keypair file, with encrypt-at-rest and a legacy
-// plaintext fallback + in-place migration. The Electron `safeStorage` is injected as `SafeStorageLike`
-// so this stays free of `electron` and unit-tests without a keychain. The on-disk byte format mirrors
-// host-service.ts's persistKeyPair/loadOrCreateKeyPair exactly (public key always plaintext base64 —
-// it is a pinned identity, not a secret — the secret key either safeStorage-encrypted or 0600 plaintext).
-//
-// NOTE (intentional duplication): host-service.ts still inlines the same format. We do NOT refactor it
-// to use this codec — that file is Stage 4c's to rewrite, and editing it here would collide. 4c may
-// adopt this codec when it rewrites the handshake.
-import { publicKeyFromB64, secretKeyFromB64, type KeyPair } from './e2ee'
-
-export interface SafeStorageLike {
- isEncryptionAvailable(): boolean
- encryptString(plaintext: string): Buffer
- decryptString(ciphertext: Buffer): string
-}
-
-interface KeyFileBody {
- publicKey?: string
- secretKey?: string // legacy plaintext base64
- secretKeyEnc?: string // safeStorage ciphertext, base64
-}
-
-/** Serialize a keypair to the on-disk JSON string; encrypted when safeStorage is available. */
-export function encodeKeyFile(keys: KeyPair, safe: SafeStorageLike): string {
- const publicKey = Buffer.from(keys.publicKey).toString('base64')
- const secretB64 = Buffer.from(keys.secretKey).toString('base64')
- const body: KeyFileBody = safe.isEncryptionAvailable()
- ? { publicKey, secretKeyEnc: safe.encryptString(secretB64).toString('base64') }
- : { publicKey, secretKey: secretB64 }
- return JSON.stringify(body)
-}
-
-/**
- * The three outcomes of reading a key file. They are NOT interchangeable — the caller must branch:
- *
- * - `{ keys, migrate }` — usable. `migrate:true` means the file is legacy plaintext but encryption
- * is now available: re-persist to upgrade in place, KEEPING the identity.
- * - `null` — unusable: malformed JSON, a wrong-length key, or an encrypted blob the (available)
- * keychain cannot decrypt (keychain reset ⇒ the secret is gone for good). Regenerating is the
- * only way forward and is CORRECT here.
- * - `'locked'` — the file is well-formed and holds an ENCRYPTED secret, but `isEncryptionAvailable()`
- * is false RIGHT NOW (keyring not yet unlocked, no session bus, safeStorage backend down). The
- * identity is intact on disk, merely unreadable at this moment. The caller MUST NOT write:
- * regenerating would replace a pinned identity with a fresh (plaintext) one, forcing re-approval
- * on every host that pinned it — unrecoverably. Fail the operation and tell the user to unlock.
- */
-export type KeyFileDecoded = { keys: KeyPair; migrate: boolean } | null | 'locked'
-
-/** Parse a key file. See `KeyFileDecoded` — the three outcomes must not be collapsed into one. */
-export function decodeKeyFile(raw: string, safe: SafeStorageLike): KeyFileDecoded {
- let body: unknown
- try {
- body = JSON.parse(raw)
- } catch {
- return null
- }
- // `JSON.parse` happily yields null / arrays / numbers for a truncated or aborted write; only a
- // plain object can be a key file. (Without this, the literal `null` threw a TypeError below.)
- if (!body || typeof body !== 'object' || Array.isArray(body)) return null
- const file = body as KeyFileBody
- if (!file.publicKey) return null
-
- // Both key parsers are STRICT about the 32-byte length and throw otherwise — base64 decoding is
- // lenient (drops junk chars, truncates), so a corrupt file would otherwise decode to a
- // short/empty "identity" that the caller accepts and only fails much later inside nacl.
- try {
- const publicKey = publicKeyFromB64(file.publicKey)
- if (file.secretKeyEnc) {
- // An encrypted secret is AUTHORITATIVE: never silently fall back to a (possibly stale)
- // plaintext one, and never mistake "no keyring right now" for corruption.
- if (!safe.isEncryptionAvailable()) return 'locked'
- // decryptString may throw (keychain reset) OR return junk — either way the secret is
- // genuinely gone, so that is `null` (regenerate), not `'locked'`.
- const secretB64 = safe.decryptString(Buffer.from(file.secretKeyEnc, 'base64'))
- return { keys: { publicKey, secretKey: secretKeyFromB64(secretB64) }, migrate: false }
- }
- if (file.secretKey) {
- return {
- keys: { publicKey, secretKey: secretKeyFromB64(file.secretKey) },
- // Legacy plaintext but a keyring now exists → the caller should re-persist encrypted.
- migrate: safe.isEncryptionAvailable()
- }
- }
- } catch {
- return null
- }
- return null
-}
+// Moved to src/core/relay/key-file-codec.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./key-file-codec') in the existing tests — working unchanged.
+export * from '../../core/relay/key-file-codec'
diff --git a/src/main/remote/mutual-approval-core.ts b/src/main/remote/mutual-approval-core.ts
index ece719178..0886a5e35 100644
--- a/src/main/remote/mutual-approval-core.ts
+++ b/src/main/remote/mutual-approval-core.ts
@@ -1,98 +1,4 @@
-// Pure state for SYMMETRIC pairing approval: both ends verify the same 6-digit SAS out of band and
-// both pin the other's key. Today approval is one-way (only the host pins the client). This adds the
-// second confirmation direction + the pin-both-ends bookkeeping as pure logic — no sockets, no
-// Electron — so it unit-tests directly and 4c can wire it into either end's handshake.
-//
-// The SAS digits themselves are already identical on both ends (both derive from the same ECDH shared
-// key via sasFromSharedKey); "mutual" means BOTH humans must confirm before the session opens, and
-// EACH end independently pins the other's stable box public key. A man-in-the-middle on the relay
-// terminates two DIFFERENT ECDH exchanges, so the two humans read out different digits and refuse —
-// which is exactly why neither confirmation alone may unlock the session.
-//
-// SECURITY — this module is a correct latch ONLY if 4c (host-service / client-service) honours two
-// obligations it cannot express in this pure file. Both are security-FATAL if broken, because pinning
-// a key grants the peer SHELL ACCESS on this machine:
-//
-// (a) `confirmRemote` MUST be driven ONLY by a frame received over the ENCRYPTED, session-keyed
-// channel (the box under deriveSessionKey), never from a plaintext/relay-visible message. The
-// relay is untrusted: if the peer's "I confirmed" signal can be forged or replayed by a relay
-// MITM, mutual approval silently degrades back to ONE-WAY — the attacker supplies the remote
-// confirmation the second human never gave, and a single local confirm then pins the attacker.
-// Only a frame that decrypts under THIS session's key proves the real peer sent it.
-//
-// (b) There must be EXACTLY ONE `MutualApproval` per pairing attempt, created via
-// `emptyMutualApproval(peerKeyB64, sessionId)` from THIS session's ECDH peer key (the same key
-// whose shared secret produced the SAS the humans compared). Reusing a state across attempts,
-// or seeding it with a key other than this session's, re-opens the "confirm-for-a-different-
-// session" / "pin-the-wrong-key" holes this module's binding was built to close.
-//
-// This file makes the SAFE usage the ONLY compilable usage — the peer key + session identity are
-// bound INTO the state at construction and the branded type has no other constructor — but it cannot
-// reach across the seam to enforce (a) and (b). 4c owns those.
-import { sasFromSharedKey } from './e2ee'
-import { pinDevice, type ApprovedDevices } from './approved-devices-core'
-
-/**
- * Approval state for ONE pairing attempt, BOUND at creation to the peer + session it approves.
- *
- * Opaque/branded: the `__brand` field has no runtime value and cannot be written by hand, so the
- * ONLY way to obtain a `MutualApproval` is `emptyMutualApproval()`, and the only way to mutate one is
- * `confirmLocal`/`confirmRemote`. A hand-forged `{ localConfirmed: true, remoteConfirmed: true, … }`
- * is a COMPILE ERROR. This turns "safe if every caller is disciplined" into "safe by construction":
- * you cannot fabricate an already-approved state, nor move a confirmation onto a different pairing,
- * because every state carries the one peer key + session it belongs to.
- */
-export type MutualApproval = {
- /** This human confirmed the SAS on THIS device. */
- readonly localConfirmed: boolean
- /** The peer signalled (over the ENCRYPTED, session-keyed channel — see obligation (a)) that its human confirmed too. */
- readonly remoteConfirmed: boolean
- /** The peer's stable box public key (base64) from THIS session's ECDH — the ONLY key this state can ever pin. */
- readonly peerKeyB64: string
- /** Identity of the pairing attempt (session id or shared-key fingerprint) this state is bound to. */
- readonly sessionId: string
-} & { readonly __brand: unique symbol }
-
-/**
- * The sole constructor. Binds the peer's box public key + the session identity INTO the state, so a
- * confirmation can never be moved to a different pairing and `recordApproval` can only ever pin THIS
- * peer's key. Starts unconfirmed on both sides.
- */
-export function emptyMutualApproval(peerKeyB64: string, sessionId: string): MutualApproval {
- return { localConfirmed: false, remoteConfirmed: false, peerKeyB64, sessionId } as MutualApproval
-}
-
-export function confirmLocal(s: MutualApproval): MutualApproval {
- return s.localConfirmed ? s : ({ ...s, localConfirmed: true } as MutualApproval)
-}
-
-export function confirmRemote(s: MutualApproval): MutualApproval {
- return s.remoteConfirmed ? s : ({ ...s, remoteConfirmed: true } as MutualApproval)
-}
-
-/**
- * Approved only when BOTH ends have confirmed the SAS. There is deliberately no other way to reach
- * this state: the two confirmations live on separate fields, each set by its own one-way transition,
- * so re-playing one side's confirmation (calling confirmLocal/confirmRemote twice) can never stand in
- * for the other's.
- */
-export function isMutuallyApproved(s: MutualApproval): boolean {
- return s.localConfirmed && s.remoteConfirmed
-}
-
-/** The 6-digit code ("NNN NNN") BOTH ends compute + confirm. Thin alias so 4c reads clearly. */
-export function mutualSas(shared: Uint8Array): string {
- return sasFromSharedKey(shared)
-}
-
-/**
- * Pin the peer's stable box public key locally — but ONLY once the SAS is mutually confirmed, so a
- * half-finished handshake never leaves a pinned identity. The key pinned is the one CARRIED BY the
- * state (`s.peerKeyB64`, bound at construction): there is no separate key argument, so a caller cannot
- * pin a key different from the one the two humans confirmed. Idempotent (pinDevice is). Each end calls
- * this against its OWN store; the state each end holds carries the OTHER end's key, so both ends pin.
- */
-export function recordApproval(store: ApprovedDevices, s: MutualApproval): ApprovedDevices {
- if (!isMutuallyApproved(s)) return store
- return pinDevice(store, s.peerKeyB64)
-}
+// Moved to src/core/relay/mutual-approval-core.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./mutual-approval-core') in the existing tests — working unchanged.
+export * from '../../core/relay/mutual-approval-core'
diff --git a/src/main/remote/relay-id.ts b/src/main/remote/relay-id.ts
index 59f0c652f..9066b6f3f 100644
--- a/src/main/remote/relay-id.ts
+++ b/src/main/remote/relay-id.ts
@@ -1,21 +1,4 @@
-// Host-id derivation for the standing (phone) relay path.
-//
-// The relay broker matches a host and its clients by a short `hostId` derived from the host's
-// NaCl box public key. This MUST match the server's `src/lib/relay-id.ts` byte-for-byte:
-// hostId = base64url(sha256(rawPublicKeyBytes)).slice(0, 22) (base64url, no padding)
-// where the raw bytes are the 32-byte Curve25519 public key (the same bytes `publicKeyToB64`
-// standard-base64-encodes). Keep this in sync with the server — a mismatch means the phone and
-// this host would register under different rooms and never bridge.
-
-import { createHash } from 'node:crypto'
-
-/** Derive the broker host id from the raw 32-byte NaCl box public key. */
-export function hostIdFromPublicKey(pub: Uint8Array): string {
- // Node's 'base64url' digest is already unpadded RFC 4648 §5, matching the server.
- return createHash('sha256').update(pub).digest('base64url').slice(0, 22)
-}
-
-/** Derive the broker host id from a standard-base64 NaCl box public key (what publicKeyToB64 emits). */
-export function hostIdFromPublicKeyB64(b64: string): string {
- return hostIdFromPublicKey(Uint8Array.from(Buffer.from(b64, 'base64')))
-}
+// Moved to src/core/relay/relay-id.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./relay-id') in the existing tests — working unchanged.
+export * from '../../core/relay/relay-id'
diff --git a/src/main/remote/relay-project-scope.ts b/src/main/remote/relay-project-scope.ts
index ec0195d44..c7409f480 100644
--- a/src/main/remote/relay-project-scope.ts
+++ b/src/main/remote/relay-project-scope.ts
@@ -1,75 +1,4 @@
-// Which relay-guest methods name a PROJECT, and which project — the one table behind the scope jail
-// in `relay-host.ts` (a session bound to one shared project must never let the guest reach another).
-//
-// The jail used to be a per-feature switch with a `default: not project-scoped` arm, so a method the
-// switch did not list was waved through. That is safe only for as long as every project-naming
-// channel is remembered in every switch, and it failed OPEN for the next one nobody added: a new
-// `githubIssues:*` verb would have reached another project's repository with no refusal anywhere.
-// So membership is by CLASS (channel prefix), and a method inside a class that this table cannot
-// read a projectId out of is answered as "names an unknown project" — which a scoped session
-// refuses. Adding a channel to a class therefore costs one table row to become reachable, rather
-// than one forgotten row to become a hole.
-//
-// `projects.*` is in the class although no IPC channel carries that prefix today: it is the phone
-// dialect's board verbs (`projects.ensureBoard` / `setCardColumn` / `editCardLabels`, served by
-// host-service to an approved PHONE, never on this tunnel). Classifying it here means that if a
-// relay guest ever sends one — or a future channel is named after it — it is judged by the shared
-// project rather than passed to a router on the assumption that nothing answers.
-//
-// Unscoped sessions are not affected at all: with no shared project the jail is off, exactly as
-// before (the host registry is then the only gate, as it is for the host's own renderer).
-
-import { IPC } from '../../shared/ipc'
-
-export interface ProjectScope {
- /** The method belongs to a project-scoped channel class. */
- scoped: boolean
- /** The projectId it names — `undefined` when the class is known but the method is not, which
- * the jail treats as "not the shared project" (fail closed). */
- projectId: unknown
-}
-
-/** Channel prefixes whose every method acts on ONE project. */
-export const PROJECT_SCOPED_PREFIXES = ['githubIssues:', 'board-log:', 'projects.'] as const
-
-const fromFirstArg = (args: unknown[]): unknown => args[0]
-const fromFirstArgField = (args: unknown[]): unknown =>
- args[0] && typeof args[0] === 'object' ? (args[0] as { projectId?: unknown }).projectId : undefined
-
-/** Methods whose projectId we know how to read. Everything else in a scoped class fails closed. */
-const EXTRACTORS: Record<string, (args: unknown[]) => unknown> = {
- [IPC.githubIssuesSubscribe]: fromFirstArgField,
- [IPC.githubIssuesQuery]: fromFirstArgField,
- [IPC.githubIssuesMove]: fromFirstArgField,
- [IPC.githubIssuesRefresh]: fromFirstArg,
- [IPC.githubIssuesCreateLabels]: fromFirstArg,
- [IPC.githubIssuesClearCache]: fromFirstArg,
- [IPC.githubIssuesUnsubscribe]: fromFirstArg,
- [IPC.boardLogAppend]: fromFirstArg,
- [IPC.boardLogRead]: fromFirstArg,
- [IPC.boardLogSubscribe]: fromFirstArg,
- [IPC.boardLogUnsubscribe]: fromFirstArg,
- // The phone dialect's params object, should one ever arrive as the first arg.
- 'projects.ensureBoard': fromFirstArgField,
- 'projects.setCardColumn': fromFirstArgField,
- 'projects.editCardLabels': fromFirstArgField
-}
-
-export function projectScopeOf(method: string, args: unknown[]): ProjectScope {
- if (!PROJECT_SCOPED_PREFIXES.some((p) => method.startsWith(p))) {
- return { scoped: false, projectId: undefined }
- }
- const extract = EXTRACTORS[method]
- return { scoped: true, projectId: extract ? extract(Array.isArray(args) ? args : []) : undefined }
-}
-
-/** True when a session bound to `sharedProjectId` must refuse this method. Unscoped ⇒ never. */
-export function outOfProjectScope(
- sharedProjectId: string | undefined,
- method: string,
- args: unknown[]
-): boolean {
- if (!sharedProjectId) return false
- const scope = projectScopeOf(method, args)
- return scope.scoped && scope.projectId !== sharedProjectId
-}
+// Moved to src/core/relay/relay-project-scope.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./relay-project-scope') in the existing tests — working unchanged.
+export * from '../../core/relay/relay-project-scope'
diff --git a/src/main/remote/relay-shims.test.ts b/src/main/remote/relay-shims.test.ts
new file mode 100644
index 000000000..17291502b
--- /dev/null
+++ b/src/main/remote/relay-shims.test.ts
@@ -0,0 +1,21 @@
+// src/main/remote/relay-shims.test.ts
+// The move must be invisible to the desktop: the old paths re-export the SAME objects, so a
+// vi.mock of an old path still intercepts desktop callers and nothing is duplicated.
+import { describe, it, expect } from 'vitest'
+import * as coreE2ee from '../../core/relay/e2ee'
+import * as mainE2ee from './e2ee'
+import * as coreSocket from '../../core/relay/relay-socket'
+import * as mainSocket from './relay-socket'
+import * as coreScope from '../../core/relay/relay-project-scope'
+import * as mainScope from './relay-project-scope'
+import * as coreCore from '../../core/relay/approved-devices-core'
+import * as mainCore from './approved-devices-core'
+
+describe('relay module move', () => {
+ it('old paths re-export the identical core functions', () => {
+ expect(mainE2ee.deriveSharedKey).toBe(coreE2ee.deriveSharedKey)
+ expect(mainSocket.connectRelay).toBe(coreSocket.connectRelay)
+ expect(mainScope.outOfProjectScope).toBe(coreScope.outOfProjectScope)
+ expect(mainCore.pinDevice).toBe(coreCore.pinDevice)
+ })
+})
diff --git a/src/main/remote/relay-socket.ts b/src/main/remote/relay-socket.ts
index 227be28f4..a42521d68 100644
--- a/src/main/remote/relay-socket.ts
+++ b/src/main/remote/relay-socket.ts
@@ -1,750 +1,4 @@
-// Relay socket + E2EE handshake + RPC/frame state machine (main process).
-//
-// A single connection to the dumb relay server (a separate repo). The relay
-// forwards opaque bytes between a host and a client matched by a pairing token;
-// it never decrypts. So the end-to-end-encrypted handshake and all traffic run
-// HOST<->CLIENT *through* the relay — the relay is not a handshake participant.
-//
-// The handshake/RPC state machine, in brief:
-// - The token gates entry at the relay via a `?token=<token>` QUERY PARAM on
-// the wss URL (matching what the relay expects). It is NOT
-// interleaved as a data frame — every frame on the wire is opaque peer
-// traffic.
-// - Handshake `e2ee_hello -> e2ee_ready -> e2ee_auth -> e2ee_authenticated`:
-// * client (knows the host pubkey) sends `e2ee_hello {publicKeyB64}` and
-// derives the shared key from the host pubkey;
-// * host learns the client pubkey from `e2ee_hello`, derives the same
-// shared key, replies `e2ee_ready`;
-// * client then sends an ENCRYPTED `e2ee_auth` (the relay already verified
-// the token and the offer pins the host pubkey, so for MVP a simple
-// authenticated marker is sufficient — no extra secret to prove);
-// * host replies an ENCRYPTED `e2ee_authenticated`. Both sides fire onReady
-// once their side of the auth exchange is complete.
-// - After authentication every peer message is an E2EE box (sent as binary).
-// The decrypted plaintext is tagged: 0x01 = JSON RPC envelope, 0x02 = a
-// binary terminal frame (framing.ts). Handshake control frames (`e2ee_hello`
-// / `e2ee_ready`) are sent as plaintext JSON strings so the receiver can tell
-// them apart from the encrypted binary boxes.
-//
-// Pure-ish: no IPC, no renderer. The WebSocket is INJECTED as a `RelayTransport`
-// so tests drive two RelaySockets via in-process fakes with no real network;
-// production passes a `ws` WebSocket wrapped via `wrapWebSocket`.
-
-import {
- decrypt,
- deriveSessionKey,
- deriveSharedKey,
- encrypt,
- publicKeyToB64,
- randomSessionNonce,
- sasFromSharedKey,
- type KeyPair
-} from './e2ee'
-import { decodeFrame, encodeFrame, type Frame, MAX_BINARY_BUFFERED_AMOUNT } from './framing'
-
-// A minimal duplex transport. `send` accepts a string (handshake control) or a
-// Uint8Array (encrypted box). `bufferedAmount` drives backpressure on frames.
-export interface RelayTransport {
- readonly bufferedAmount: number
- send(data: string | Uint8Array): void
- close(): void
- onMessage(cb: (data: unknown) => void): void
- onClose(cb: () => void): void
-}
-
-// An RPC request envelope as seen by the peer's onRpc handler. `id` correlates a
-// later `respond`.
-export type RpcRequest = {
- id: string
- method: string
- params: unknown
-}
-
-export type RelaySocket = {
- // Send an RPC request to the peer; resolves with the peer's response body (or
- // rejects on a non-ok response / timeout / closed connection).
- rpc(method: string, params?: unknown): Promise<unknown>
- // Fire a one-way notification to the peer (no response expected, never rejects).
- // The peer receives it in `onRpc` with an empty `id` — answering it is a no-op
- // (notifications carry no correlation id). Returns false if not connected.
- notify(method: string, params?: unknown): boolean
- // Answer a received RPC request (from onRpc) by its id.
- respond(id: string, ok: boolean, body: unknown): void
- // Send a terminal frame to the peer. Returns false when the transport is over
- // its buffered-amount threshold (backpressure) or not connected.
- sendFrame(op: number, streamId: number, seq: number, payload: Uint8Array): boolean
- // The Short Authentication String for this channel (derived from the shared key), or null
- // before the handshake has derived a key. Both peers compute the same value.
- sas(): string | null
- // The peer's NaCl box public key (base64) once known: for a client it is the pinned host key
- // passed in; for a host it is learned from the client's `e2ee_hello`. Null before then. Used by
- // the standing (phone) host to look the connecting device up in its pin-once approval list.
- peerPublicKeyB64(): string | null
- // --- 4c tunnel: the Server Edition's rpc.ts protocol, carried inside the E2EE box ------------
- // Send one rpc.ts TEXT frame (a JSON RpcMessage). False if the channel is not ready — a tunnel
- // frame is NEVER sent in the clear.
- sendTunnelText(json: string): boolean
- // Send one rpc.ts BINARY frame (encodePtyData bytes). False if the channel is not ready.
- sendTunnelBinary(bytes: Uint8Array): boolean
- // Bytes handed to the underlying socket but not yet flushed (ws.bufferedAmount + anything still
- // sitting in the pre-open queue). This is the number Stage 2's per-client backpressure and the
- // 8 MB WS_DROP_WATER drop-and-redraw ceiling key on (see src/core/ui-sink-registry.ts): a sink
- // that reports 0 silently disables the ceiling, and a slow peer then queues pty output without
- // bound until the host process dies. It must stay honest.
- bufferedAmount(): number
- // Tear down: stops reconnects and closes the transport.
- close(): void
-}
-
-export type ConnectRelayOptions = {
- // The relay wss URL. `?token=` is appended automatically when opening a socket.
- url: string
- // Single-use pairing token; gates entry at the relay (query param).
- token: string
- role: 'host' | 'client'
- // Our long-lived (host) or ephemeral (client) NaCl keypair.
- ourKeys: KeyPair
- // The peer's public key, base64. REQUIRED for the client (it must know the
- // host's pubkey up front); for the host it is learned from `e2ee_hello`.
- theirPubB64?: string
- // Injected transport. Tests pass an in-process fake; production passes a `ws`
- // WebSocket wrapped via `wrapWebSocket`. When omitted, a `ws` socket is opened
- // from `url` (production default).
- transport?: RelayTransport
- onReady(): void
- onRpc(msg: RpcRequest): void
- onFrame(f: Frame): void
- onClose(): void
- // An rpc.ts frame arrived over the ENCRYPTED, session-keyed, role-tagged, replay-checked
- // channel. This is the ONLY inbound path 4c's trust + RPC layers may trust: anything that did
- // not come out of the E2EE box never reaches here.
- onTunnel?(kind: 'text' | 'binary', payload: Uint8Array): void
-}
-
-// Plaintext-tag bytes for decrypted peer payloads.
-const TAG_RPC = 0x01
-const TAG_FRAME = 0x02
-// 4c tunnel: the Server Edition's rpc.ts protocol, carried verbatim inside the E2EE box. Text = a
-// JSON RpcMessage; binary = an encodePtyData frame. Both ride the SAME encrypted stream as
-// everything else — same sendSeq counter, same FIFO delivery — because Stage 3's canvas
-// convergence needs a single ordered channel per client.
-const TAG_TUNNEL_TEXT = 0x03
-const TAG_TUNNEL_BIN = 0x04
-
-const RPC_TIMEOUT_MS = 30_000
-const KEEPALIVE_INTERVAL_MS = 25_000
-const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000, 15_000]
-
-type RpcEnvelope =
- | { kind: 'req'; id: string; method: string; params: unknown }
- | { kind: 'notify'; method: string; params: unknown }
- | { kind: 'res'; id: string; ok: boolean; body: unknown }
- | { kind: 'keepalive' }
-
-type HandshakeControl =
- | { type: 'e2ee_hello'; publicKeyB64: string; nonceB64: string }
- | { type: 'e2ee_ready'; nonceB64: string }
-
-function nonceToB64(n: Uint8Array): string {
- return Buffer.from(n).toString('base64')
-}
-function nonceFromB64(b64: unknown): Uint8Array | null {
- if (typeof b64 !== 'string') return null
- const n = Uint8Array.from(Buffer.from(b64, 'base64'))
- return n.length === 16 ? n : null
-}
-
-type State = 'connecting' | 'handshaking' | 'ready' | 'closed'
-
-const textEncoder = new TextEncoder()
-const textDecoder = new TextDecoder()
-
-export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
- if (opts.role === 'client' && !opts.theirPubB64) {
- throw new Error('connectRelay: client role requires theirPubB64 (the host public key)')
- }
-
- let transport: RelayTransport | null = null
- // baseKey = the stable ECDH precompute (for the SAS, which represents the pinned identity).
- // sessionKey = HKDF(baseKey, hostNonce‖clientNonce) = the fresh per-session traffic key.
- let baseKey: Uint8Array | null = null
- let sessionKey: Uint8Array | null = null
- let ourNonce: Uint8Array | null = null
- // Role byte prefixed to every sealed plaintext, so a relay can't REFLECT a box back to its
- // sender (same sessionKey both directions): each side only accepts boxes tagged with the peer's
- // role. host=1, client=2.
- const OUR_ROLE = opts.role === 'host' ? 1 : 2
- const PEER_ROLE = opts.role === 'host' ? 2 : 1
- // The peer's base64 public key. Known up front for a client (the pinned host key); learned from
- // `e2ee_hello` for a host. Exposed via peerPublicKeyB64() for the standing host's pin-once check.
- let peerPubB64: string | null = opts.role === 'client' ? opts.theirPubB64 ?? null : null
- let state: State = 'connecting'
- let intentionallyClosed = false
- let reconnectAttempt = 0
- let reconnectTimer: ReturnType<typeof setTimeout> | null = null
- let keepaliveTimer: ReturnType<typeof setInterval> | null = null
- let requestCounter = 0
- let readyFired = false
- // Replay/reorder protection: every encrypted message carries a strictly-increasing per-
- // direction counter inside the authenticated plaintext. The receiver rejects any message whose
- // counter is not greater than the last accepted one, so a relay (or on-path attacker) cannot
- // replay a captured box (e.g. re-injecting an OP.Input keystroke frame or a pty.kill RPC) nor
- // reorder traffic. Counters reset per (re)connection — a fresh handshake is a fresh stream.
- let sendSeq = 0
- let recvSeq = -1
-
- const pending = new Map<
- string,
- { resolve: (body: unknown) => void; reject: (err: Error) => void; timer: ReturnType<typeof setTimeout> }
- >()
-
- function buildUrl(): string {
- // Append `?token=` so the relay can read the pairing token from the query
- // string. Preserve any existing query.
- const sep = opts.url.includes('?') ? '&' : '?'
- return `${opts.url}${sep}token=${encodeURIComponent(opts.token)}`
- }
-
- function openConnection(): void {
- if (intentionallyClosed) {
- return
- }
- state = 'connecting'
- baseKey = null
- sessionKey = null
- ourNonce = randomSessionNonce()
- readyFired = false
- sendSeq = 0
- recvSeq = -1
-
- if (opts.transport) {
- // Injected transport (tests). It is already "open"; treat that as the
- // open event. A re-open after a drop is not supported for injected
- // transports — production reconnect goes through the real ws path.
- transport = opts.transport
- } else {
- transport = openWebSocketTransport(buildUrl())
- }
-
- transport.onMessage((data) => handleMessage(data))
- transport.onClose(() => handleClose())
-
- state = 'handshaking'
- if (opts.role === 'client') {
- // Client knows the host pubkey: derive the base (identity) key now and greet with our
- // session nonce. The traffic key is derived once the host's nonce arrives in e2ee_ready.
- baseKey = deriveSharedKey(opts.theirPubB64!, opts.ourKeys.secretKey)
- sendControl({
- type: 'e2ee_hello',
- publicKeyB64: publicKeyToB64(opts.ourKeys.publicKey),
- nonceB64: nonceToB64(ourNonce!)
- })
- }
- // Host waits passively for `e2ee_hello` to learn the client pubkey.
- }
-
- function sendControl(control: HandshakeControl): void {
- transport?.send(JSON.stringify(control))
- }
-
- // Prepend the outbound monotonic counter (8 bytes LE) to the plaintext before sealing, so the
- // peer can reject replays/reorders. Mirrors framing.ts's 64-bit split to stay within safe ints.
- // Authenticated plaintext layout: [role:1][seq:8][payload…]. The role defeats reflection; the
- // strictly-increasing seq defeats in-session replay/reorder.
- const SEQ_BYTES = 8
- const HEADER_BYTES = 1 + SEQ_BYTES
- function withHeader(plaintext: Uint8Array): Uint8Array {
- const seq = sendSeq++
- const out = new Uint8Array(HEADER_BYTES + plaintext.length)
- out[0] = OUR_ROLE
- const view = new DataView(out.buffer)
- view.setUint32(1, Math.floor(seq / 0x100000000), true)
- view.setUint32(5, seq >>> 0, true)
- out.set(plaintext, HEADER_BYTES)
- return out
- }
-
- function sendEncrypted(plaintext: Uint8Array): boolean {
- if (!transport || !sessionKey || state !== 'ready') {
- return false
- }
- transport.send(encrypt(withHeader(plaintext), sessionKey))
- return true
- }
-
- // During the handshake the auth control frames must be sent before `state`
- // flips to 'ready', so this variant does not gate on state.
- function sendEncryptedHandshake(plaintext: Uint8Array): void {
- if (!transport || !sessionKey) {
- return
- }
- transport.send(encrypt(withHeader(plaintext), sessionKey))
- }
-
- function tagged(tag: number, body: Uint8Array): Uint8Array {
- const out = new Uint8Array(body.length + 1)
- out[0] = tag
- out.set(body, 1)
- return out
- }
-
- function fireReadyOnce(): void {
- if (readyFired) {
- return
- }
- readyFired = true
- reconnectAttempt = 0
- startKeepalive()
- opts.onReady()
- }
-
- function handleMessage(data: unknown): void {
- if (state === 'closed') {
- return
- }
-
- const asString = stringFromData(data)
- if (asString !== null) {
- // Plaintext JSON => a handshake control frame.
- handleControl(asString)
- return
- }
-
- const bytes = bytesFromData(data)
- if (!bytes) {
- return
- }
-
- // Everything binary is an E2EE box, sealed under the fresh session key.
- if (!sessionKey) {
- return
- }
- const sealed = decrypt(bytes, sessionKey)
- if (!sealed || sealed.length < HEADER_BYTES) {
- return
- }
- // Reject a box tagged with our OWN role (a reflected message) — only the peer's role is valid.
- if (sealed[0] !== PEER_ROLE) {
- return
- }
- // Enforce the strictly-increasing per-direction counter inside the authenticated plaintext.
- // A non-increasing counter means a replayed or reordered box — drop it.
- const seqView = new DataView(sealed.buffer, sealed.byteOffset, sealed.byteLength)
- const seq = seqView.getUint32(1, true) * 0x100000000 + seqView.getUint32(5, true)
- if (seq <= recvSeq) {
- return
- }
- recvSeq = seq
- const plain = sealed.subarray(HEADER_BYTES)
-
- if (state === 'handshaking') {
- handleHandshakeEncrypted(plain)
- return
- }
- if (state !== 'ready') {
- return
- }
- handlePeerPlaintext(plain)
- }
-
- function handleControl(raw: string): void {
- // SECURITY: a handshake control frame (`e2ee_hello` / `e2ee_ready`) is legitimate ONLY during the
- // one handshake, i.e. before the session goes ready. Once ready, re-processing one would let a
- // relay MITM RE-KEY a live session under its own keypair (re-deriving baseKey/sessionKey and
- // overwriting peerPubB64) and then forge the peer's encrypted `trust:confirm` under the swapped
- // key — degrading mutual approval to one-way (see docs/remote-sessions.md, obligation (a)). The
- // real peer never re-sends a hello on an established session, so such a frame is an attack or a
- // bug, never legitimate. Drop it WITHOUT re-keying: the derived session identity (SAS + peer key)
- // stays frozen. We do NOT close the socket — the relay already fully controls the transport
- // (it can drop us at will), so closing would add no real protection while handing a MITM a
- // trivial way to tear down an established, mutually-approved session with one plaintext frame.
- // Ignoring keeps the good session robust; layer 2 (relay-host key binding) independently
- // guarantees no traffic or approval can advance under a swapped key even if this check regressed.
- if (readyFired) {
- return
- }
- let control: HandshakeControl
- try {
- control = JSON.parse(raw) as HandshakeControl
- } catch {
- return
- }
- if (control.type === 'e2ee_hello' && opts.role === 'host') {
- // Host learns the client pubkey + its session nonce, derives the base identity key and the
- // fresh session traffic key, replies ready with its own nonce.
- const clientNonce = nonceFromB64(control.nonceB64)
- if (typeof control.publicKeyB64 !== 'string' || !clientNonce || !ourNonce) {
- return
- }
- peerPubB64 = control.publicKeyB64
- baseKey = deriveSharedKey(control.publicKeyB64, opts.ourKeys.secretKey)
- // salt = hostNonce ‖ clientNonce (host's nonce first, both roles agree on the order).
- sessionKey = deriveSessionKey(baseKey, ourNonce, clientNonce)
- sendControl({ type: 'e2ee_ready', nonceB64: nonceToB64(ourNonce) })
- return
- }
- if (control.type === 'e2ee_ready' && opts.role === 'client') {
- // Client learns the host's nonce, derives the same session key, and proves the pairing with
- // an encrypted auth marker. The marker is sealed under the SESSION key (which mixes in this
- // session's fresh nonces), so a recorded auth box from an earlier session can't be replayed
- // to silently authenticate a new one.
- const hostNonce = nonceFromB64(control.nonceB64)
- if (!hostNonce || !baseKey || !ourNonce) {
- return
- }
- sessionKey = deriveSessionKey(baseKey, hostNonce, ourNonce)
- sendEncryptedHandshake(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ type: 'e2ee_auth' }))))
- }
- }
-
- function handleHandshakeEncrypted(plain: Uint8Array): void {
- // Tag byte distinguishes control vs payload; during handshake we only expect
- // control JSON (auth / authenticated).
- if (plain.length < 1 || plain[0] !== TAG_RPC) {
- return
- }
- let msg: { type?: string }
- try {
- msg = JSON.parse(textDecoder.decode(plain.subarray(1))) as { type?: string }
- } catch {
- return
- }
- if (msg.type === 'e2ee_auth' && opts.role === 'host') {
- // Host accepts the client's authenticated marker, confirms, becomes ready.
- sendEncryptedHandshake(
- tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ type: 'e2ee_authenticated' })))
- )
- state = 'ready'
- fireReadyOnce()
- return
- }
- if (msg.type === 'e2ee_authenticated' && opts.role === 'client') {
- state = 'ready'
- fireReadyOnce()
- }
- }
-
- function handlePeerPlaintext(plain: Uint8Array): void {
- if (plain.length < 1) {
- return
- }
- const tag = plain[0]
- const body = plain.subarray(1)
- if (tag === TAG_TUNNEL_TEXT) {
- opts.onTunnel?.('text', body)
- return
- }
- if (tag === TAG_TUNNEL_BIN) {
- opts.onTunnel?.('binary', body)
- return
- }
- if (tag === TAG_FRAME) {
- const frame = decodeFrame(body)
- if (frame) {
- opts.onFrame(frame)
- }
- return
- }
- if (tag !== TAG_RPC) {
- return
- }
- let env: RpcEnvelope
- try {
- env = JSON.parse(textDecoder.decode(body)) as RpcEnvelope
- } catch {
- return
- }
- if (env.kind === 'keepalive') {
- return
- }
- if (env.kind === 'req') {
- opts.onRpc({ id: env.id, method: env.method, params: env.params })
- return
- }
- if (env.kind === 'notify') {
- // One-way notification: surface it like an RPC but with an empty id, so a
- // `respond` (if any) is a no-op (no matching pending request on our side).
- opts.onRpc({ id: '', method: env.method, params: env.params })
- return
- }
- if (env.kind === 'res') {
- const waiter = pending.get(env.id)
- if (!waiter) {
- return
- }
- pending.delete(env.id)
- clearTimeout(waiter.timer)
- if (env.ok) {
- waiter.resolve(env.body)
- } else {
- waiter.reject(new Error(rpcErrorMessage(env.body)))
- }
- }
- }
-
- function startKeepalive(): void {
- stopKeepalive()
- keepaliveTimer = setInterval(() => {
- sendEncrypted(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'keepalive' }))))
- }, KEEPALIVE_INTERVAL_MS)
- // Don't keep the event loop alive purely for keepalives.
- keepaliveTimer.unref?.()
- }
-
- function stopKeepalive(): void {
- if (keepaliveTimer) {
- clearInterval(keepaliveTimer)
- keepaliveTimer = null
- }
- }
-
- function handleClose(): void {
- stopKeepalive()
- transport = null
- baseKey = null
- sessionKey = null
- const wasReady = state === 'ready'
- rejectAllPending('Relay connection closed.')
- if (intentionallyClosed) {
- state = 'closed'
- return
- }
- state = 'closed'
- // Reconnect is the CALLER's responsibility (via onClose), NOT this socket's. Re-dialing here
- // would reuse the same pairing token, which the relay rejects after its short TTL — and worse,
- // for a standing host it fights the caller's fresh-token reconnect, repeatedly clobbering the
- // new session so the connection never restabilises. So we fire onClose once and stop; the
- // standing host mints a fresh token and reconnects cleanly.
- void wasReady
- opts.onClose()
- }
-
- // (Internal same-token reconnect removed — see handleClose. The caller reconnects with a fresh
- // token.)
- function scheduleReconnect(): void {
- if (reconnectTimer || intentionallyClosed) {
- return
- }
- const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]
- reconnectAttempt += 1
- reconnectTimer = setTimeout(() => {
- reconnectTimer = null
- openConnection()
- }, delay)
- reconnectTimer.unref?.()
- }
-
- function rejectAllPending(reason: string): void {
- const err = new Error(reason)
- for (const [id, waiter] of pending) {
- pending.delete(id)
- clearTimeout(waiter.timer)
- waiter.reject(err)
- }
- }
-
- function nextId(): string {
- requestCounter += 1
- return `${opts.role}-rpc-${requestCounter}-${Date.now()}`
- }
-
- openConnection()
-
- return {
- rpc(method, params) {
- return new Promise((resolve, reject) => {
- const id = nextId()
- const timer = setTimeout(() => {
- pending.delete(id)
- reject(new Error(`RPC timed out: ${method}`))
- }, RPC_TIMEOUT_MS)
- timer.unref?.()
- pending.set(id, { resolve, reject, timer })
- const sent = sendEncrypted(
- tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'req', id, method, params })))
- )
- if (!sent) {
- pending.delete(id)
- clearTimeout(timer)
- reject(new Error('Relay socket is not connected.'))
- }
- })
- },
- notify(method, params) {
- return sendEncrypted(
- tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'notify', method, params })))
- )
- },
- respond(id, ok, body) {
- sendEncrypted(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'res', id, ok, body }))))
- },
- sendFrame(op, streamId, seq, payload) {
- if (!transport || state !== 'ready') {
- return false
- }
- if (transport.bufferedAmount > MAX_BINARY_BUFFERED_AMOUNT) {
- return false
- }
- return sendEncrypted(tagged(TAG_FRAME, encodeFrame(op, streamId, seq, payload)))
- },
- sendTunnelText(json) {
- return sendEncrypted(tagged(TAG_TUNNEL_TEXT, textEncoder.encode(json)))
- },
- sendTunnelBinary(bytes) {
- return sendEncrypted(tagged(TAG_TUNNEL_BIN, bytes))
- },
- bufferedAmount() {
- // Honest by construction: the transport reports what it has been handed and has not yet
- // flushed. No backpressure decision is made here — the caller (ui-sink-registry) owns the
- // thresholds; this only has to tell the truth. Not connected => nothing is queued => 0.
- return transport?.bufferedAmount ?? 0
- },
- sas() {
- return baseKey ? sasFromSharedKey(baseKey) : null
- },
- peerPublicKeyB64() {
- return peerPubB64
- },
- close() {
- intentionallyClosed = true
- if (reconnectTimer) {
- clearTimeout(reconnectTimer)
- reconnectTimer = null
- }
- stopKeepalive()
- rejectAllPending('Relay socket closed.')
- state = 'closed'
- transport?.close()
- transport = null
- baseKey = null
- sessionKey = null
- }
- }
-}
-
-function rpcErrorMessage(body: unknown): string {
- if (body && typeof body === 'object') {
- const maybe = body as { message?: unknown; error?: unknown }
- if (typeof maybe.message === 'string') {
- return maybe.message
- }
- if (typeof maybe.error === 'string') {
- return maybe.error
- }
- }
- return 'RPC failed.'
-}
-
-// --- transport payload coercion ---------------------------------------------
-
-function stringFromData(data: unknown): string | null {
- if (typeof data === 'string') {
- return data
- }
- return null
-}
-
-function bytesFromData(data: unknown): Uint8Array | null {
- if (data instanceof Uint8Array) {
- return data
- }
- if (data instanceof ArrayBuffer) {
- return new Uint8Array(data)
- }
- // `ws` may deliver a Node Buffer (which is a Uint8Array) or an array of
- // Buffers when fragmented; handle the array case defensively.
- if (Array.isArray(data) && data.every((d) => d instanceof Uint8Array)) {
- const total = data.reduce((n, d) => n + (d as Uint8Array).length, 0)
- const out = new Uint8Array(total)
- let offset = 0
- for (const d of data as Uint8Array[]) {
- out.set(d, offset)
- offset += d.length
- }
- return out
- }
- return null
-}
-
-// --- production ws wrapper ----------------------------------------------------
-
-// Wrap a connected `ws` WebSocket as a RelayTransport. Kept here so the host
-// (Task 6) and client (Task 7) share one ws adapter. Imported lazily so the
-// pure module + its tests never load `ws`.
-export function wrapWebSocket(ws: import('ws').WebSocket): RelayTransport {
- ws.binaryType = 'nodebuffer'
- return {
- get bufferedAmount() {
- return ws.bufferedAmount
- },
- // Strings (handshake control) go out as ws *text* frames; Uint8Array (E2EE boxes) as ws
- // *binary*. The relay preserves that text/binary-ness end to end.
- send: (data) => ws.send(data, { binary: typeof data !== 'string' }),
- close: () => ws.close(),
- // Deliver ws *text* frames as JS strings and *binary* frames as bytes, so relay-socket's
- // type-based control-vs-box discrimination works. (`ws` hands us a Buffer for both unless we
- // consult `isBinary`.)
- onMessage: (cb) =>
- ws.on('message', (data: Buffer, isBinary: boolean) =>
- cb(isBinary ? data : data.toString('utf-8'))
- ),
- onClose: (cb) => {
- // Fire `cb` on EITHER a close OR an error, exactly once. A ws `error` (a 504 upgrade timeout,
- // a TLS/DNS failure, connection refused) is otherwise an UNHANDLED 'error' event, which Node
- // re-throws as an uncaught exception that crashes the whole app. Treat it as a close so the
- // caller tears the session down / reconnects gracefully instead. The caller registers this
- // synchronously right after opening (relay-socket connectRelay), before any async error fires.
- let fired = false
- const fire = (): void => {
- if (fired) return
- fired = true
- cb()
- }
- ws.on('close', fire)
- ws.on('error', fire)
- }
- }
-}
-
-// Open a `ws` WebSocket to `url` and return it wrapped. Sends start only once
-// the socket is open; messages before open are dropped (the handshake retries on
-// reconnect). Used as the production default when no transport is injected.
-function openWebSocketTransport(url: string): RelayTransport {
- // Lazy require so test/pure consumers don't pull in the native-ish dep.
- // eslint-disable-next-line @typescript-eslint/no-var-requires
- const WS = require('ws') as typeof import('ws')
- const ws = new WS.WebSocket(url)
- ws.binaryType = 'nodebuffer'
- const wrapped = wrapWebSocket(ws)
- // Buffer sends issued before 'open'.
- const queue: (string | Uint8Array)[] = []
- let open = false
- // Bytes sitting in `queue`. They are real, un-flushed bytes that `ws.bufferedAmount` cannot see
- // (the socket has not been handed them yet), so leaving them out would make bufferedAmount lie
- // during exactly the window in which a burst can pile up — and a backpressure ceiling that
- // believes the lie stops capping, letting the host queue pty output without bound.
- let queuedBytes = 0
- ws.on('open', () => {
- open = true
- for (const item of queue.splice(0)) {
- ws.send(item)
- }
- queuedBytes = 0
- })
- return {
- get bufferedAmount() {
- return ws.bufferedAmount + queuedBytes
- },
- send: (data) => {
- if (open) {
- ws.send(data)
- } else {
- queue.push(data)
- queuedBytes += typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength
- }
- },
- close: () => ws.close(),
- onMessage: wrapped.onMessage,
- onClose: wrapped.onClose
- }
-}
+// Moved to src/core/relay/relay-socket.ts so the Server Edition can host relay sessions
+// (docs/superpowers/specs/2026-09-28-hosted-team-relay-design.md). This shim keeps every desktop
+// import path — and every vi.mock('./relay-socket') in the existing tests — working unchanged.
+export * from '../../core/relay/relay-socket'