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(relay): server host identity that is never silently regenerated
review62b4e902f2ac
diff --git a/src/core/relay/host-key.test.ts b/src/core/relay/host-key.test.tsnew file mode 100644index 000000000..1293db02f--- /dev/null+++ b/src/core/relay/host-key.test.ts@@ -0,0 +1,123 @@+// src/core/relay/host-key.test.ts+import { describe, it, expect, afterEach } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { createHostKey, loadHostKey, rotateHostKey, hostAddress, HostKeyUnreadableError } from './host-key'+import { genKeyPair, publicKeyToB64 } from './e2ee'+import { hostIdFromPublicKeyB64 } from './relay-id'++const made: string[] = []+const tmp = () => {+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'hostkey-'))+ made.push(d)+ return d+}+afterEach(() => {+ for (const d of made.splice(0)) fs.rmSync(d, { recursive: true, force: true })+})+const keyFile = (dir: string) => path.join(dir, 'host-key.json')+const b64 = (u: Uint8Array) => Buffer.from(u).toString('base64')++describe('server host key', () => {+ it('absent → null; create → stable across loads', async () => {+ const dir = tmp()+ expect(await loadHostKey(dir)).toBeNull()+ const k = await createHostKey(dir)+ const again = await loadHostKey(dir)+ expect(publicKeyToB64(again!.publicKey)).toBe(publicKeyToB64(k.publicKey))+ expect(b64(again!.secretKey)).toBe(b64(k.secretKey))+ })++ // POSIX permission bits: Windows reports its own mode bits here, not the 0600/0700 we asked for.+ it.skipIf(process.platform === 'win32')('file is 0600 and a fresh directory 0700, on create and on rotate', async () => {+ const dir = path.join(tmp(), 'relay')+ await createHostKey(dir)+ expect((fs.statSync(keyFile(dir)).mode & 0o777).toString(8)).toBe('600')+ expect((fs.statSync(dir).mode & 0o777).toString(8)).toBe('700')+ await rotateHostKey(dir)+ expect((fs.statSync(keyFile(dir)).mode & 0o777).toString(8)).toBe('600')+ })++ // POSIX permission bits: chmod is skipped on Windows, where the bits do not apply.+ it.skipIf(process.platform === 'win32')('tightens an existing, looser directory to 0700 on write', async () => {+ const dir = path.join(tmp(), 'relay')+ fs.mkdirSync(dir, { mode: 0o755 })+ fs.chmodSync(dir, 0o755) // the umask may have narrowed it; make it genuinely loose+ await createHostKey(dir)+ expect((fs.statSync(dir).mode & 0o777).toString(8)).toBe('700')+ })++ it('corrupt → throws, and the file is NOT replaced (not by load, not by create)', async () => {+ const dir = tmp()+ fs.writeFileSync(keyFile(dir), '{"publicKey":"short"}')+ await expect(loadHostKey(dir)).rejects.toBeInstanceOf(HostKeyUnreadableError)+ await expect(loadHostKey(dir)).rejects.toMatchObject({ code: 'E_HOST_KEY_UNREADABLE' })+ await expect(createHostKey(dir)).rejects.toBeInstanceOf(HostKeyUnreadableError)+ expect(fs.readFileSync(keyFile(dir), 'utf-8')).toBe('{"publicKey":"short"}')+ })++ it('a read error other than "missing" is unreadable, never "none yet"', async () => {+ const dir = tmp()+ fs.mkdirSync(keyFile(dir)) // readFile → EISDIR: present, but cannot be read+ await expect(loadHostKey(dir)).rejects.toBeInstanceOf(HostKeyUnreadableError)+ await expect(createHostKey(dir)).rejects.toBeInstanceOf(HostKeyUnreadableError)+ expect(fs.statSync(keyFile(dir)).isDirectory()).toBe(true)+ })++ it('a keyring-encrypted secret is unreadable here and left intact', async () => {+ const dir = tmp()+ const k = genKeyPair()+ const raw = JSON.stringify({ publicKey: b64(k.publicKey), secretKeyEnc: 'c2VhbGVk' })+ fs.writeFileSync(keyFile(dir), raw)+ await expect(loadHostKey(dir)).rejects.toThrow(/keyring/)+ await expect(createHostKey(dir)).rejects.toBeInstanceOf(HostKeyUnreadableError)+ expect(fs.readFileSync(keyFile(dir), 'utf-8')).toBe(raw)+ })++ it('a public key that does not belong to the secret key is corrupt', async () => {+ const dir = tmp()+ const a = genKeyPair()+ const b = genKeyPair()+ const raw = JSON.stringify({ publicKey: b64(a.publicKey), secretKey: b64(b.secretKey) })+ fs.writeFileSync(keyFile(dir), raw)+ await expect(loadHostKey(dir)).rejects.toThrow(/does not match/)+ expect(fs.readFileSync(keyFile(dir), 'utf-8')).toBe(raw)+ })++ it('create refuses to overwrite an existing key; rotate is the explicit path', async () => {+ const dir = tmp()+ const a = await createHostKey(dir)+ await expect(createHostKey(dir)).rejects.toThrow(/already exists/)+ expect(publicKeyToB64((await loadHostKey(dir))!.publicKey)).toBe(publicKeyToB64(a.publicKey))+ const b = await rotateHostKey(dir)+ expect(publicKeyToB64(b.publicKey)).not.toBe(publicKeyToB64(a.publicKey))+ expect(publicKeyToB64((await loadHostKey(dir))!.publicKey)).toBe(publicKeyToB64(b.publicKey))+ })++ it('two creates racing each other: one key wins, the other is refused, nothing is replaced', async () => {+ const dir = tmp()+ const results = await Promise.allSettled([createHostKey(dir), createHostKey(dir), createHostKey(dir)])+ const won = results.filter((r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof createHostKey>>> => r.status === 'fulfilled')+ const refused = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')+ expect(won).toHaveLength(1)+ expect(refused).toHaveLength(2)+ for (const r of refused) expect(String(r.reason)).toMatch(/already exists/)+ expect(publicKeyToB64((await loadHostKey(dir))!.publicKey)).toBe(publicKeyToB64(won[0].value.publicKey))+ })++ it('rotate is the recovery from a corrupt key', async () => {+ const dir = tmp()+ fs.writeFileSync(keyFile(dir), 'not json')+ const k = await rotateHostKey(dir)+ expect(publicKeyToB64((await loadHostKey(dir))!.publicKey)).toBe(publicKeyToB64(k.publicKey))+ })++ it('hostAddress derives the broker room id', async () => {+ const k = await createHostKey(tmp())+ const addr = hostAddress(k)+ expect(addr.hostPublicKeyB64).toBe(publicKeyToB64(k.publicKey))+ expect(addr.hostId).toBe(hostIdFromPublicKeyB64(addr.hostPublicKeyB64))+ expect(addr.hostId).toHaveLength(22)+ })+})diff --git a/src/core/relay/host-key.ts b/src/core/relay/host-key.tsnew file mode 100644index 000000000..1a6bdf9dc--- /dev/null+++ b/src/core/relay/host-key.ts@@ -0,0 +1,96 @@+// The Server Edition's relay host identity. Its public key IS the team's address (hostId), and+// every joiner pins it — so an unreadable or corrupt key is NEVER silently replaced: a new key+// orphans every bookmark and forces every teammate through first-join approval again. Rotation is+// only the explicit `team rotate-key`. Plaintext secret at 0600: headless Linux has no keyring+// (the same decision the Server Edition's node identity made).+import { promises as fs } from 'node:fs'+import path from 'node:path'+import nacl from 'tweetnacl'+import { writeFileAtomic } from '../fs-atomic'+import { encodeKeyFile, decodeKeyFile, type SafeStorageLike } from './key-file-codec'+import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'+import { hostIdFromPublicKeyB64 } from './relay-id'+import { ensurePrivateDir } from './private-dir'++const NO_KEYRING: SafeStorageLike = {+ isEncryptionAvailable: () => false,+ encryptString: () => { throw new Error('no keyring') },+ decryptString: () => { throw new Error('no keyring') }+}++export class HostKeyUnreadableError extends Error {+ readonly code = 'E_HOST_KEY_UNREADABLE'+ constructor(detail: string) {+ super(`The team host key could not be read (${detail}). It was NOT replaced — a new key would ` ++ `invalidate every teammate's bookmark. Restore it, or run \`team rotate-key\` on purpose.`)+ this.name = 'HostKeyUnreadableError'+ }+}++const file = (dir: string): string => path.join(dir, 'host-key.json')++async function persist(dir: string, keys: KeyPair): Promise<void> {+ ensurePrivateDir(dir)+ await writeFileAtomic(file(dir), encodeKeyFile(keys, NO_KEYRING), { mode: 0o600 })+}++// "Is there a key?" then "write one" is two steps. Two `team init`s arriving together over the+// admin socket would both see none, and the second write would silently replace the first key —+// possibly after its join code was already handed out. Every WRITE to one directory therefore runs+// one at a time. In-process is enough: the server that owns the admin socket is the only writer.+const writeChains = new Map<string, Promise<unknown>>()+function serializeWrite<T>(dir: string, op: () => Promise<T>): Promise<T> {+ const key = path.resolve(dir)+ const run = (writeChains.get(key) ?? Promise.resolve()).then(op)+ const tail = run.catch(() => {})+ writeChains.set(key, tail)+ void tail.then(() => { if (writeChains.get(key) === tail) writeChains.delete(key) })+ return run+}++/** `null` = no key yet. Anything else that is not a usable key throws `HostKeyUnreadableError`. */+export async function loadHostKey(dir: string): Promise<KeyPair | null> {+ let raw: string+ try {+ raw = await fs.readFile(file(dir), 'utf-8')+ } catch (err) {+ // Unreadable is not absent: only a missing file means "none yet".+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw new HostKeyUnreadableError((err as NodeJS.ErrnoException).code ?? 'read failed')+ }+ const decoded = decodeKeyFile(raw, NO_KEYRING)+ if (decoded === 'locked') throw new HostKeyUnreadableError('encrypted with a keyring this host does not have')+ if (!decoded) throw new HostKeyUnreadableError('malformed')+ // The codec checks lengths only. A public key from one pair beside the secret of another (a+ // half-restored backup) would advertise an address whose handshakes can never decrypt.+ const derived = nacl.box.keyPair.fromSecretKey(decoded.keys.secretKey).publicKey+ if (!Buffer.from(derived).equals(Buffer.from(decoded.keys.publicKey))) {+ throw new HostKeyUnreadableError('the public key does not match the secret key')+ }+ return decoded.keys+}++/** Mint the first key. Refuses when one exists, and throws `HostKeyUnreadableError` (without+ * writing) when one exists but cannot be read. */+export function createHostKey(dir: string): Promise<KeyPair> {+ return serializeWrite(dir, async () => {+ if ((await loadHostKey(dir)) !== null) throw new Error('A team host key already exists.')+ const keys = genKeyPair()+ await persist(dir, keys)+ return keys+ })+}++/** Replace the key, whatever is there. Explicit only: every teammate needs a new join code. */+export function rotateHostKey(dir: string): Promise<KeyPair> {+ return serializeWrite(dir, async () => {+ const keys = genKeyPair()+ await persist(dir, keys)+ return keys+ })+}++export function hostAddress(keys: KeyPair): { hostPublicKeyB64: string; hostId: string } {+ const hostPublicKeyB64 = publicKeyToB64(keys.publicKey)+ return { hostPublicKeyB64, hostId: hostIdFromPublicKeyB64(hostPublicKeyB64) }+}diff --git a/src/core/relay/private-dir.ts b/src/core/relay/private-dir.tsnew file mode 100644index 000000000..420ff5ecd--- /dev/null+++ b/src/core/relay/private-dir.ts@@ -0,0 +1,13 @@+// The relay's data directory (`<dataDir>/relay`) holds the team's membership and the host's secret+// key, so it is private to this unix user: 0700.+import { mkdirSync, chmodSync } from 'node:fs'++/** Create `dir` (and parents) at 0700, and tighten it to 0700 if it already existed. */+export function ensurePrivateDir(dir: string): void {+ mkdirSync(dir, { recursive: true, mode: 0o700 })+ // mkdir's mode applies only when it CREATES the directory; tighten one that already existed.+ // Best-effort, and POSIX only: the bits mean nothing on Windows.+ if (process.platform !== 'win32') {+ try { chmodSync(dir, 0o700) } catch { /* not ours to fix: the 0600 files inside are the guard */ }+ }+}diff --git a/src/core/relay/team-store.ts b/src/core/relay/team-store.tsindex cde4dc2ca..c1fcb2a91 100644--- a/src/core/relay/team-store.ts+++ b/src/core/relay/team-store.ts@@ -7,9 +7,10 @@// Corrupt ⇒ CLOSED: the file is set aside and the store starts with no peers, so nobody// auto-reconnects. The owner recovers with `team add-owner` over SSH, which is also the// root of trust.-import { promises as fs, existsSync, mkdirSync, chmodSync } from 'node:fs'+import { promises as fs, existsSync } from 'node:fs'import path from 'node:path'import { writeFileAtomic, renameAtomic } from '../fs-atomic'+import { ensurePrivateDir } from './private-dir'export type TeamRole = 'owner' | 'editor' | 'commenter' | 'viewer'export const TEAM_ROLES: readonly TeamRole[] = ['owner', 'editor', 'commenter', 'viewer']@@ -97,12 +98,7 @@ export class TeamStore {// Never publish what our own reader rejects: the write would land, and the NEXT load would set// the whole team aside as corrupt. Throwing here leaves both the file and `this.doc` as they were.if (!parseTeam(next)) throw new Error('team.json: refusing to write a team doc that fails validation')- mkdirSync(this.dir, { recursive: true, mode: 0o700 })- // mkdir's mode applies only when it CREATES the directory; tighten one that already existed.- // Best-effort, and POSIX only: the bits mean nothing on Windows.- if (process.platform !== 'win32') {- try { chmodSync(this.dir, 0o700) } catch { /* not ours to fix: the 0600 file is the guard */ }- }+ ensurePrivateDir(this.dir)await writeFileAtomic(this.file(), JSON.stringify(next, null, 2) + '\n', { mode: 0o600 })this.doc = nextreturn next