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.

feat(watch-link): persist active links, sealed, never adopting a raw secret on the desktop

review046786cd10ae
diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.ts
new file mode 100644
index 000000000..54a3266c2
--- /dev/null
+++ b/src/core/watch-link/store.test.ts
@@ -0,0 +1,100 @@
+import { describe, it, expect, vi } from 'vitest'
+import { readFileSync, statSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { testTmpDir } from '../test-tmp'
+import { writeFileAtomic } from '../fs-atomic'
+import { WatchLinkStore, type WatchLinkRecord } from './store'
+
+// A pass-through spy, so a test can hold one write open (ordering) or fail one (chain recovery).
+vi.mock('../fs-atomic', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../fs-atomic')>()
+ return { ...actual, writeFileAtomic: vi.fn(actual.writeFileAtomic) }
+})
+
+const file = () => join(testTmpDir('wl-'), 'watch-links.json')
+// Computed once: two `rec()` calls a millisecond apart must still compare equal.
+const EXPIRES_AT = Date.now() + 3600_000
+const rec = (over: Partial<WatchLinkRecord> = {}): WatchLinkRecord => ({
+ linkId: 'AbCdEfGhIjKlMnOpQrStUv', nodeId: 'n1', role: 'viewer', label: 'Ada', title: 'build',
+ createdAt: 1, expiresAt: EXPIRES_AT, secret: new Uint8Array(32).fill(7), ...over
+})
+const seal = (b: Buffer) => Buffer.from(b.toString('hex'))
+const unseal = (b: Buffer) => Buffer.from(b.toString(), 'hex')
+
+describe('WatchLinkStore', () => {
+ it('round-trips sealed records and writes 0600', async () => {
+ const f = file()
+ const s = new WatchLinkStore({ file: f, seal, unseal })
+ expect(await s.save([rec()])).toBe('saved')
+ expect(await s.load()).toEqual([rec()])
+ expect(readFileSync(f, 'utf8')).not.toContain(Buffer.from(new Uint8Array(32).fill(7)).toString('base64'))
+ if (process.platform !== 'win32') expect(statSync(f).mode & 0o777).toBe(0o600)
+ })
+
+ it('stores raw secrets where the platform has no seal (Server Edition)', async () => {
+ const f = file()
+ const s = new WatchLinkStore({ file: f })
+ expect(await s.save([rec()])).toBe('saved')
+ expect(await s.load()).toEqual([rec()])
+ })
+
+ it('writes an empty file and reports memory-only when sealing throws', async () => {
+ const f = file()
+ const s = new WatchLinkStore({ file: f, seal: () => { throw new Error('locked') }, unseal })
+ expect(await s.save([rec()])).toBe('memory-only')
+ expect(JSON.parse(readFileSync(f, 'utf8'))).toEqual({ v: 1, links: [] })
+ })
+
+ it('an unsealable secret is skipped, and a desktop never accepts a raw one', async () => {
+ const f = file()
+ await new WatchLinkStore({ file: f }).save([rec()]) // raw on disk
+ const desktop = new WatchLinkStore({ file: f, seal, unseal: () => { throw new Error('keychain reset') } })
+ expect(await desktop.load()).toEqual([])
+ const f2 = file()
+ await new WatchLinkStore({ file: f2, seal, unseal }).save([rec()])
+ expect(await new WatchLinkStore({ file: f2, seal, unseal: () => { throw new Error('reset') } }).load()).toEqual([])
+ })
+
+ it('tolerates a missing or corrupt file and drops malformed entries', async () => {
+ const f = file()
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([])
+ writeFileSync(f, '{nope')
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([])
+ writeFileSync(f, JSON.stringify({ v: 1, links: [{ linkId: 'bad', nodeId: 'n', role: 'viewer', secret: 'AA==', sealed: false }] }))
+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([])
+ })
+
+ it('serializes saves: an older snapshot never lands after a newer one', async () => {
+ // A revoke is a save of the smaller list. If two writes overlap and finish out of order, the
+ // OLDER snapshot is what stays on disk — and the revoked link comes back at the next boot.
+ const f = file()
+ const s = new WatchLinkStore({ file: f })
+ const { writeFileAtomic: realWrite } = await vi.importActual<typeof import('../fs-atomic')>('../fs-atomic')
+ let release!: () => void
+ const gate = new Promise<void>((r) => { release = r })
+ vi.mocked(writeFileAtomic).mockImplementationOnce(async (...args) => {
+ await gate // hold the FIRST write open
+ return realWrite(...args)
+ })
+ const a = s.save([rec()])
+ const b = s.save([])
+ // Unserialized, `b` lands while `a` is held; serialized, it is still waiting behind `a`.
+ await Promise.race([b, new Promise((r) => setTimeout(r, 100))])
+ release()
+ expect(await a).toBe('saved')
+ expect(await b).toBe('saved')
+ expect(JSON.parse(readFileSync(f, 'utf8'))).toEqual({ v: 1, links: [] })
+ expect(await s.load()).toEqual([])
+ })
+
+ it('a failed save does not break the chain for the next one', async () => {
+ const f = file()
+ const s = new WatchLinkStore({ file: f })
+ vi.mocked(writeFileAtomic).mockRejectedValueOnce(new Error('EPERM'))
+ const a = s.save([rec()])
+ const b = s.save([rec({ label: 'Bob' })])
+ expect(await a).toBe('failed')
+ expect(await b).toBe('saved')
+ expect(await s.load()).toEqual([rec({ label: 'Bob' })])
+ })
+})
diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.ts
new file mode 100644
index 000000000..710b8e322
--- /dev/null
+++ b/src/core/watch-link/store.ts
@@ -0,0 +1,104 @@
+// Active live links survive an app restart (spec D8). The secret is sealed through the platform's
+// secret seam: Electron safeStorage on the desktop, and ABSENT on the Server Edition by design
+// (headless, no keychain: raw bytes in a 0600 file, the same rule as its node secrets). On the
+// desktop there is no plaintext fallback: if sealing throws, the file is written EMPTY and links
+// live in memory for this run; a raw secret found on a desktop is refused, never adopted.
+//
+// Saves are SERIALIZED: each write waits for the previous one to finish. Two overlapping atomic
+// writes can still complete out of order, and the older snapshot would then be what stays on disk —
+// a revoked link resurrected at the next boot. The snapshot is taken (and sealed) when `save` is
+// CALLED, so disk order is call order; a failed write never breaks the chain for the next save.
+import { promises as fs } from 'node:fs'
+import { writeFileAtomic } from '../fs-atomic'
+import { LINK_ID_RE } from '../../shared/watch-link/link'
+import type { WatchLinkRole } from '../../shared/watch-link/protocol'
+
+export interface WatchLinkRecord {
+ linkId: string
+ nodeId: string
+ role: WatchLinkRole
+ label: string
+ title: string
+ createdAt: number
+ expiresAt: number
+ secret: Uint8Array
+}
+export type SaveOutcome = 'saved' | 'memory-only' | 'failed'
+
+interface FileEntry {
+ linkId: string
+ nodeId: string
+ role: WatchLinkRole
+ label: string
+ title: string
+ createdAt: number
+ expiresAt: number
+ secret: string
+ sealed: boolean
+}
+
+const str = (v: unknown, max: number): v is string => typeof v === 'string' && v.length <= max
+const num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
+
+export class WatchLinkStore {
+ /** The previous save's write, settled either way: the next write starts only after it. */
+ private writing: Promise<void> = Promise.resolve()
+
+ constructor(private readonly o: { file: string; seal?: (b: Buffer) => Buffer; unseal?: (b: Buffer) => Buffer }) {}
+
+ async load(): Promise<WatchLinkRecord[]> {
+ let body: { links?: unknown }
+ try {
+ body = JSON.parse((await fs.readFile(this.o.file, 'utf8')).replace(/\r\n/g, '\n'))
+ } catch {
+ return []
+ }
+ const out: WatchLinkRecord[] = []
+ for (const e of Array.isArray(body?.links) ? (body.links as Partial<FileEntry>[]) : []) {
+ if (!e || !str(e.linkId, 22) || !LINK_ID_RE.test(e.linkId) || !str(e.nodeId, 200) || !e.nodeId) continue
+ if (e.role !== 'viewer' && e.role !== 'commenter') continue
+ if (!str(e.label, 40) || !str(e.title, 80) || !num(e.createdAt) || !num(e.expiresAt) || typeof e.secret !== 'string') continue
+ const secret = this.readSecret(e.secret, e.sealed === true)
+ if (!secret || secret.length !== 32) continue
+ out.push({ linkId: e.linkId, nodeId: e.nodeId, role: e.role, label: e.label, title: e.title, createdAt: e.createdAt, expiresAt: e.expiresAt, secret })
+ }
+ return out
+ }
+
+ private readSecret(b64: string, sealed: boolean): Uint8Array | null {
+ try {
+ const raw = Buffer.from(b64, 'base64')
+ if (sealed) return this.o.unseal ? new Uint8Array(this.o.unseal(raw)) : null
+ // A desktop (it can seal) never adopts a raw secret it finds on disk.
+ return this.o.seal ? null : new Uint8Array(raw)
+ } catch {
+ return null
+ }
+ }
+
+ async save(records: readonly WatchLinkRecord[]): Promise<SaveOutcome> {
+ let links: FileEntry[]
+ let outcome: SaveOutcome = 'saved'
+ try {
+ links = records.map((r) => ({
+ linkId: r.linkId, nodeId: r.nodeId, role: r.role, label: r.label, title: r.title,
+ createdAt: r.createdAt, expiresAt: r.expiresAt,
+ secret: (this.o.seal ? this.o.seal(Buffer.from(r.secret)) : Buffer.from(r.secret)).toString('base64'),
+ sealed: !!this.o.seal
+ }))
+ } catch {
+ links = []
+ outcome = 'memory-only'
+ }
+ const data = JSON.stringify({ v: 1, links })
+ // Everything above ran synchronously at call time, so the chain is extended in call order.
+ const write = this.writing.then(() => writeFileAtomic(this.o.file, data, { mode: 0o600 }))
+ this.writing = write.catch(() => {})
+ try {
+ await write
+ return outcome
+ } catch {
+ return 'failed'
+ }
+ }
+}