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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(b4): port NaCl e2ee + terminal framing + pairing codec
enes05a552080e8a
diff --git a/package-lock.json b/package-lock.jsonindex 0dc67b9f5..23f54d3e7 100644--- a/package-lock.json+++ b/package-lock.json@@ -15,10 +15,12 @@"marked": "^12.0.2","monaco-editor": "^0.52.2","node-pty": "^1.0.0",+ "tweetnacl": "^1.0.3","zustand": "^4.5.7"},"devDependencies": {"@electron/rebuild": "^3.6.0",+ "@types/node": "^26.0.0","@types/react": "^18.3.31","@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.3.1",@@ -2301,13 +2303,13 @@"license": "MIT"},"node_modules/@types/node": {- "version": "20.19.43",- "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",- "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",+ "version": "26.0.0",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.0.0.tgz",+ "integrity": "sha512-vf2YFi1iY9lHGwNJMs01biZFbKJkrZR1T6/MlzjhJLPdntOHLhTrDSnSVcdtvjihi4VQNlrFRIxLsDBlQpAipA==","dev": true,"license": "MIT","dependencies": {- "undici-types": "~6.21.0"+ "undici-types": "~8.3.0"}},"node_modules/@types/plist": {@@ -4259,6 +4261,23 @@}}},+ "node_modules/electron/node_modules/@types/node": {+ "version": "20.19.43",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/electron/node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/emoji-regex": {"version": "8.0.0","resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",@@ -7055,6 +7074,12 @@"license": "0BSD","optional": true},+ "node_modules/tweetnacl": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",+ "license": "Unlicense"+ },"node_modules/type-fest": {"version": "0.13.1","resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",@@ -7084,9 +7109,9 @@}},"node_modules/undici-types": {- "version": "6.21.0",- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",- "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",+ "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==","dev": true,"license": "MIT"},diff --git a/package.json b/package.jsonindex b0004cbf0..d64c5d5ac 100644--- a/package.json+++ b/package.json@@ -13,6 +13,7 @@"start": "electron-vite preview","typecheck": "tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json","test": "vitest run",+ "test:unit": "vitest run test/remote","rebuild": "electron-rebuild -f -w node-pty","make-icon": "node scripts/make-icon.mjs","make-social": "node scripts/make-social.mjs",@@ -70,10 +71,12 @@"marked": "^12.0.2","monaco-editor": "^0.52.2","node-pty": "^1.0.0",+ "tweetnacl": "^1.0.3","zustand": "^4.5.7"},"devDependencies": {"@electron/rebuild": "^3.6.0",+ "@types/node": "^26.0.0","@types/react": "^18.3.31","@types/react-dom": "^18.3.7","@vitejs/plugin-react": "^4.3.1",diff --git a/src/main/remote/e2ee.ts b/src/main/remote/e2ee.tsnew file mode 100644index 000000000..15cc9d237--- /dev/null+++ b/src/main/remote/e2ee.ts@@ -0,0 +1,57 @@+// End-to-end encryption primitives for the relay transport.+//+// Ported from REF (src/shared/e2ee-crypto.ts). Pure functions over NaCl box+// (Curve25519 + XSalsa20-Poly1305): no sockets, no Electron. The box format is+// `nonce ‖ ciphertext ‖ mac` so a future REF-compatible peer interoperates.+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+}++// Derive the shared secret (ECDH precompute) from the peer's base64 public key+// and our secret key. Both sides arrive at the same value.+export function deriveSharedKey(theirPubB64: string, ourSecret: Uint8Array): Uint8Array {+ const theirPub = publicKeyFromB64(theirPubB64)+ return nacl.box.before(theirPub, ourSecret)+}++// 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+}++// 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/main/remote/framing.ts b/src/main/remote/framing.tsnew file mode 100644index 000000000..22ba4e1e5--- /dev/null+++ b/src/main/remote/framing.ts@@ -0,0 +1,88 @@+// Terminal-stream binary framing for the relay transport.+//+// Ported from REF (src/shared/terminal-stream-protocol.ts). The 16-byte header+// layout and opcode numbers are kept verbatim so a future REF-compatible peer+// interoperates. 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 MUST match REF's TerminalStreamOpcode for interop.+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/main/remote/pairing.ts b/src/main/remote/pairing.tsnew file mode 100644index 000000000..babc3cda8--- /dev/null+++ b/src/main/remote/pairing.ts@@ -0,0 +1,81 @@+// Pairing-offer codec for the relay transport.+//+// Ported from REF (src/shared/pairing.ts), adapted to nodeterm's offer shape+// and `nodeterm://pair` scheme. Pure functions: no sockets, no Electron, and no+// zod — validation is hand-rolled so decode never throws (returns null instead).++export type PairingOffer = {+ // The relay WebSocket endpoint the client connects to.+ relayEndpoint: string+ // Single-use token authorizing this pairing on the relay.+ pairingToken: string+ // The host's Curve25519 public key, base64-encoded. The client uses this to+ // derive the shared secret via ECDH for end-to-end encryption.+ hostPublicKeyB64: string+}++const SCHEME_PREFIX = 'nodeterm://pair?code='++export function encodeOffer(offer: PairingOffer): string {+ const json = JSON.stringify(offer)+ const code = Buffer.from(json, 'utf-8').toString('base64url')+ // Why: query params survive custom-scheme deep links / camera intents more+ // reliably than URL fragments.+ return `${SCHEME_PREFIX}${code}`+}++// Decode either a full `nodeterm://pair?code=…` URL or a bare base64url code.+// Returns null on any malformed / incomplete input — never throws.+export function decodeOffer(code: string): PairingOffer | null {+ const trimmed = code.trim()+ if (!trimmed) {+ return null+ }+ const raw = extractCode(trimmed)+ if (raw === null) {+ return null+ }+ try {+ const json = Buffer.from(raw, 'base64url').toString('utf-8')+ const parsed = JSON.parse(json) as unknown+ return isPairingOffer(parsed) ? parsed : null+ } catch {+ return null+ }+}++// Pull the base64url code out of a `nodeterm://pair?code=…` URL, or treat the+// input as a bare code if it carries no scheme.+function extractCode(input: string): string | null {+ if (input.includes('://')) {+ let parsed: URL+ try {+ parsed = new URL(input)+ } catch {+ return null+ }+ if (parsed.protocol !== 'nodeterm:' || parsed.hostname !== 'pair') {+ return null+ }+ if (parsed.pathname !== '' && parsed.pathname !== '/') {+ return null+ }+ return parsed.searchParams.get('code')+ }+ return input+}++function isPairingOffer(value: unknown): value is PairingOffer {+ if (typeof value !== 'object' || value === null) {+ return false+ }+ const o = value as Record<string, unknown>+ return (+ typeof o.relayEndpoint === 'string' &&+ o.relayEndpoint.length > 0 &&+ typeof o.pairingToken === 'string' &&+ o.pairingToken.length > 0 &&+ typeof o.hostPublicKeyB64 === 'string' &&+ o.hostPublicKeyB64.length > 0+ )+}diff --git a/test/remote/e2ee.test.ts b/test/remote/e2ee.test.tsnew file mode 100644index 000000000..c211c1707--- /dev/null+++ b/test/remote/e2ee.test.ts@@ -0,0 +1,41 @@+import { describe, it, expect } from 'vitest'+import { genKeyPair, deriveSharedKey, encrypt, decrypt } from '../../src/main/remote/e2ee'+import { publicKeyToB64 } from '../../src/main/remote/e2ee'++describe('e2ee', () => {+ it('two keypairs derive the same shared key', () => {+ const a = genKeyPair()+ const b = genKeyPair()+ const aShared = deriveSharedKey(publicKeyToB64(b.publicKey), a.secretKey)+ const bShared = deriveSharedKey(publicKeyToB64(a.publicKey), b.secretKey)+ expect(Buffer.from(aShared).toString('hex')).toEqual(Buffer.from(bShared).toString('hex'))+ })++ it('decrypt(encrypt(m)) === m', () => {+ const a = genKeyPair()+ const b = genKeyPair()+ const shared = deriveSharedKey(publicKeyToB64(b.publicKey), a.secretKey)+ const msg = new TextEncoder().encode('hello, remote world 🌍')+ const box = encrypt(msg, shared)+ const out = decrypt(box, shared)+ expect(out).not.toBeNull()+ expect(Buffer.from(out!).toString('utf8')).toEqual('hello, remote world 🌍')+ })++ it('decrypt(tampered) === null', () => {+ const a = genKeyPair()+ const b = genKeyPair()+ const shared = deriveSharedKey(publicKeyToB64(b.publicKey), a.secretKey)+ const box = encrypt(new TextEncoder().encode('secret'), shared)+ // Flip a byte in the ciphertext/MAC region.+ const tampered = box.slice()+ tampered[tampered.length - 1] ^= 0xff+ expect(decrypt(tampered, shared)).toBeNull()+ })++ it('decrypt of too-short input === null', () => {+ const a = genKeyPair()+ const shared = deriveSharedKey(publicKeyToB64(a.publicKey), a.secretKey)+ expect(decrypt(new Uint8Array(3), shared)).toBeNull()+ })+})diff --git a/test/remote/framing.test.ts b/test/remote/framing.test.tsnew file mode 100644index 000000000..7e22fa173--- /dev/null+++ b/test/remote/framing.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from 'vitest'+import { encodeFrame, decodeFrame, OP } from '../../src/main/remote/framing'++describe('framing', () => {+ it('round-trips op, streamId, seq, payload', () => {+ const payload = new TextEncoder().encode('terminal output')+ const buf = encodeFrame(OP.Output, 42, 7, payload)+ const f = decodeFrame(buf)+ expect(f).not.toBeNull()+ expect(f!.op).toEqual(OP.Output)+ expect(f!.streamId).toEqual(42)+ expect(f!.seq).toEqual(7)+ expect(Buffer.from(f!.payload).toString('utf8')).toEqual('terminal output')+ })++ it('round-trips a 64-bit seq beyond 2^32', () => {+ const seq = 0x1_0000_0005 // > 2^32+ const buf = encodeFrame(OP.Input, 1, seq, new Uint8Array([1, 2, 3]))+ const f = decodeFrame(buf)+ expect(f).not.toBeNull()+ expect(f!.seq).toEqual(seq)+ })++ it('round-trips an empty payload', () => {+ const buf = encodeFrame(OP.Subscribe, 9, 0, new Uint8Array())+ const f = decodeFrame(buf)+ expect(f).not.toBeNull()+ expect(f!.op).toEqual(OP.Subscribe)+ expect(f!.payload.length).toEqual(0)+ })++ it('exposes REF-compatible opcode numbers', () => {+ expect(OP.Output).toEqual(1)+ expect(OP.Input).toEqual(7)+ expect(OP.Resize).toEqual(8)+ expect(OP.Subscribe).toEqual(9)+ expect(OP.Unsubscribe).toEqual(10)+ })++ it('decodeFrame returns null for too-short buffers', () => {+ expect(decodeFrame(new Uint8Array(4))).toBeNull()+ })++ it('decodeFrame returns null for a bad header / unknown opcode', () => {+ const buf = encodeFrame(OP.Output, 1, 1, new Uint8Array())+ const bad = buf.slice()+ bad[0] = 0x00 // corrupt the stream kind byte+ expect(decodeFrame(bad)).toBeNull()+ })+})diff --git a/test/remote/pairing.test.ts b/test/remote/pairing.test.tsnew file mode 100644index 000000000..fb6a69984--- /dev/null+++ b/test/remote/pairing.test.ts@@ -0,0 +1,37 @@+import { describe, it, expect } from 'vitest'+import { encodeOffer, decodeOffer, type PairingOffer } from '../../src/main/remote/pairing'++const sample: PairingOffer = {+ relayEndpoint: 'wss://relay.nodeterm.dev/socket',+ pairingToken: 'tok_abc123',+ hostPublicKeyB64: 'aGVsbG8td29ybGQtcHVibGljLWtleQ=='+}++describe('pairing', () => {+ it('round-trips decodeOffer(encodeOffer(o))', () => {+ const url = encodeOffer(sample)+ expect(url.startsWith('nodeterm://pair?code=')).toBe(true)+ const out = decodeOffer(url)+ expect(out).toEqual(sample)+ })++ it('decodeOffer accepts the bare base64url code too', () => {+ const url = encodeOffer(sample)+ const code = url.slice('nodeterm://pair?code='.length)+ expect(decodeOffer(code)).toEqual(sample)+ })++ it('decodeOffer("garbage") === null', () => {+ expect(decodeOffer('garbage')).toBeNull()+ })++ it('decodeOffer of a wrong-scheme URL === null', () => {+ expect(decodeOffer('https://example.com/pair?code=abc')).toBeNull()+ })++ it('decodeOffer of an incomplete offer === null', () => {+ const json = JSON.stringify({ relayEndpoint: 'wss://x' })+ const code = Buffer.from(json, 'utf-8').toString('base64url')+ expect(decodeOffer(`nodeterm://pair?code=${code}`)).toBeNull()+ })+})diff --git a/vitest.config.ts b/vitest.config.tsindex 543975127..f4a8e5c89 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -2,6 +2,6 @@ import { defineConfig } from 'vitest/config'import { resolve } from 'path'export default defineConfig({- test: { include: ['src/shared/**/*.test.ts'], environment: 'node' },+ test: { include: ['src/shared/**/*.test.ts', 'test/remote/**/*.test.ts'], environment: 'node' },resolve: { alias: { '@shared': resolve(__dirname, 'src/shared') } }})