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
fix(relay): hosted join never mints a device token it cannot keep (R38)
review3750b88146c9
diff --git a/src/main/index.ts b/src/main/index.tsindex 33493226e..43c42ae98 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -325,7 +325,7 @@ import { publicKeyToB64 } from './remote/e2ee'import { connectRelayClient, type RelayClientSession } from './remote/relay-client'import { decodeOffer } from './remote/pairing'import { isJoinCode } from '../core/relay/join-code'-import { connectHostedTeam } from './remote/hosted-join'+import { connectHostedTeam, removeHostedBookmark } from './remote/hosted-join'import { BookmarkStore, publicBookmark } from './remote/relay-bookmarks'import { loadOrCreatePeerKeyPair } from './remote/peer-identity'import { initSshProject } from './remote-ssh/ssh-project'@@ -4203,7 +4203,8 @@ app.whenReady().then(async () => {})// Raw ipcMain handlers, deliberately not on the platform: a relay peer can never reach them.ipcMain.handle(IPC.relayHostedBookmarks, async () => (await bookmarks.list()).map(publicBookmark))- ipcMain.handle(IPC.relayHostedBookmarkRemove, async (_e, hostId: string) => bookmarks.remove(String(hostId)))+ // Forgetting a team also forgets the device token this app run holds for it in memory.+ ipcMain.handle(IPC.relayHostedBookmarkRemove, async (_e, hostId: string) => removeHostedBookmark(String(hostId), bookmarks))}sshProjectManager = initSshProject((projectId) => {diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsindex 94ca960d5..c60b23620 100644--- a/src/main/remote/hosted-join.test.ts+++ b/src/main/remote/hosted-join.test.ts@@ -3,11 +3,11 @@// function: mint discipline, the joiner-side pin, auto-confirm, and the denial reason. The first// block drives a fake connect so every option handed to the relay client is observable; the second// runs the real core client against the real hosted service over an in-process transport.-import { describe, it, expect, vi, afterEach } from 'vitest'+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'-import { joinHostedTeam, connectHostedTeam, HostedJoinError, type HostedJoinDeps, type HostedJoinEvents, type HostedConnectOptions, type HostedJoinFailure } from './hosted-join'+import { joinHostedTeam, connectHostedTeam, removeHostedBookmark, createHostedJoinState, HostedJoinError, type HostedJoinDeps, type HostedJoinEvents, type HostedConnectOptions, type HostedJoinFailure } from './hosted-join'import { joinErrorCode } from '../../shared/relay-join-errors'import { BookmarkStore, type RelayBookmark } from './relay-bookmarks'import { encodeJoinCode, type JoinCode } from '../../core/relay/join-code'@@ -71,19 +71,30 @@ function events() {return { ev, log, closed }}-function setup(opts: { routes?: Parameters<typeof api>[0]; bookmarks?: RelayBookmark[]; loadKeys?: () => Promise<KeyPair> } = {}) {+function setup(opts: { routes?: Parameters<typeof api>[0]; bookmarks?: RelayBookmark[]; loadKeys?: () => Promise<KeyPair>; failWrites?: boolean } = {}) {const dir = tmpDir()const store = new BookmarkStore(path.join(dir, 'relay-bookmarks.json'))if (opts.bookmarks) fs.writeFileSync(path.join(dir, 'relay-bookmarks.json'), JSON.stringify(opts.bookmarks))const a = api(opts.routes ?? { device: [DEVICE_OK()], join: [JOIN_OK] })const c = fakeConnect()const ourKeys = genKeyPair()+ // A disk that reads fine and then refuses every write: the probe passes, the persist does not.+ const bookmarks = opts.failWrites+ ? {+ file: store.file,+ list: () => store.list(),+ readForWrite: () => store.readForWrite(),+ upsert: async () => { throw Object.assign(new Error('ENOSPC: no space left on device, write'), { code: 'ENOSPC' }) },+ update: async () => { throw Object.assign(new Error('ENOSPC: no space left on device, write'), { code: 'ENOSPC' }) }+ }+ : store+ const state = createHostedJoinState()const deps: HostedJoinDeps = {apiBase: 'https://api', deviceId: () => 'my-device', label: 'laptop',- bookmarks: store, loadKeys: opts.loadKeys ?? (async () => ourKeys), connect: c.connect, fetch: a.f,- now: () => Date.parse('2026-09-29T10:00:00Z')+ bookmarks, loadKeys: opts.loadKeys ?? (async () => ourKeys), connect: c.connect, fetch: a.f,+ now: () => Date.parse('2026-09-29T10:00:00Z'), state}- return { store, file: path.join(dir, 'relay-bookmarks.json'), api: a, c, deps, ourKeys }+ return { store, state, file: path.join(dir, 'relay-bookmarks.json'), api: a, c, deps, ourKeys }}const hostKeys = genKeyPair()@@ -300,18 +311,21 @@ describe('joinHostedTeam', () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})try {const s = setup({ routes: { device: [DEVICE_OK('MINTED-TOKEN-XYZ')], join: [JOIN_OK] } })- // A corrupt file holding a token: writes refuse it (its trust state is unknown).- // Shaped so that V8's JSON.parse error would quote the token, were it ever passed through.+ await joinHostedTeam(codeText, s.deps, events().ev) // the token is now held in memory too+ // A corrupt file holding a token, shaped so that V8's JSON.parse error would quote it were it+ // ever passed through. R38: no mint may happen now, but the in-memory token still joins.fs.writeFileSync(s.file, '[{"deviceToken": SECRET-TOKEN}]')+ warn.mockClear()await joinHostedTeam(codeText, s.deps, events().ev)- s.c.last().onApproved(s.c.sessions[0])+ s.c.last().onApproved(s.c.sessions[1])s.c.last().onDenied?.('removed')await vi.waitFor(() => expect(warn.mock.calls.length).toBeGreaterThanOrEqual(3))+ expect(s.api.count('device')).toBe(1)for (const call of warn.mock.calls) {const line = call.map(String).join(' ')expect(line).toContain(code.hostId)expect(line).not.toContain('SECRET')- expect(line).not.toContain('MINTED-TOKEN') // the device token minted in this attempt+ expect(line).not.toContain('MINTED-TOKEN') // the device token minted by this processexpect(line).not.toContain('nodeterm://join')expect(line).not.toContain(codeText.slice('nodeterm://join?code='.length, 40))}@@ -419,6 +433,132 @@ describe('connectHostedTeam (the relay:client:connect leg for a join code)', ()})})+describe('R38: never mint a device token the joiner cannot keep', () => {+ const joinTokens = (s: ReturnType<typeof setup>) => s.api.calls.filter((c) => c.route === 'join').map((c) => c.body.deviceToken)+ let warn: ReturnType<typeof vi.spyOn>+ beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) })+ afterEach(() => { warn.mockRestore() })++ it('a bookmarks file that cannot be rewritten refuses BEFORE any mint, on every attempt', async () => {+ const s = setup({ routes: { device: [DEVICE_OK('MINTED-1')], join: [[503, {}]] } })+ fs.writeFileSync(s.file, 'nope')+ for (let attempt = 0; attempt < 2; attempt++) {+ const err = (await joinHostedTeam(codeText, s.deps, events().ev).catch((e: Error) => e)) as HostedJoinError+ expect(err).toBeInstanceOf(HostedJoinError)+ expect(joinErrorCode(err.message)).toBe('E_JOIN_REFUSED')+ // Names the file and what to do; says nothing of a token or the code.+ expect(err.message).toContain(s.file)+ expect(err.message).toMatch(/fix or remove it/)+ expect(err.message).not.toContain('nodeterm://join')+ }+ expect(s.api.count('device')).toBe(0)+ expect(s.api.count('join')).toBe(0)+ expect(s.c.opened).toEqual([])+ expect(fs.readFileSync(s.file, 'utf8')).toBe('nope')+ })++ it('a persist that fails AFTER the probe keeps the token in memory: the retry presents it, no second mint', async () => {+ const s = setup({ failWrites: true, routes: { device: [DEVICE_OK('MINTED-1'), DEVICE_OK('MINTED-2')], join: [[503, {}], JOIN_OK] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'network' })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.count('device')).toBe(1)+ expect(joinTokens(s)).toEqual(['MINTED-1', 'MINTED-1'])+ // The failed writes were said, and never with the token.+ expect(warn).toHaveBeenCalled()+ for (const call of warn.mock.calls) expect(call.map(String).join(' ')).not.toContain('MINTED')+ })++ it('two connects for the same team at once mint exactly once; the duplicate is refused, not retried', async () => {+ const s = setup()+ let release!: () => void+ const gate = new Promise<void>((r) => { release = r })+ const calls: string[] = []+ const gated = (async (url: string, init: RequestInit) => {+ if (url.endsWith('/v1/relay/device')) {+ calls.push('device')+ await gate+ return new Response(JSON.stringify({ deviceToken: 'DT', hostId: 'H', exp: 1 }), { status: 200 })+ }+ calls.push(`join:${JSON.parse(String(init.body)).deviceToken}`)+ return new Response(JSON.stringify({ pairingToken: 'PT', hostId: 'H', relayEndpoint: 'wss://r', exp: 1 }), { status: 200 })+ }) as unknown as typeof fetch+ const deps = { ...s.deps, fetch: gated }+ const io = (id: string) => ({ newId: () => id, send: () => {}, sessions: new Map<string, RelayClientSession>() })+ const first = connectHostedTeam(codeText, deps, io('a'))+ await vi.waitFor(() => expect(calls).toEqual(['device']))+ // A boot reconnect racing a manual connect (or a double click): refused, with a code that stops a retry loop.+ const dup = await connectHostedTeam(codeText, deps, io('b')).catch((e: Error) => e)+ expect(joinErrorCode((dup as Error).message)).toBe('E_JOIN_REFUSED')+ expect((dup as Error).message).toMatch(/already joining this team/i)+ release()+ expect(await first).toBe('a')+ expect(calls).toEqual(['device', 'join:DT'])+ // Released once the first finished: a later connect goes ahead (and reuses the kept token).+ expect(await connectHostedTeam(codeText, deps, io('c'))).toBe('c')+ expect(calls.filter((c) => c === 'device')).toHaveLength(1)+ })++ it('revoked forgets the in-memory token: the next attempt mints fresh', async () => {+ const s = setup({ failWrites: true, routes: { device: [DEVICE_OK('MINTED-1'), DEVICE_OK('MINTED-2')], join: [[403, {}], JOIN_OK] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'revoked' })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.count('device')).toBe(2)+ expect(joinTokens(s)).toEqual(['MINTED-1', 'MINTED-2'])+ })++ it('bad-token forgets the in-memory token: the next attempt mints fresh', async () => {+ const s = setup({ failWrites: true, routes: { device: [DEVICE_OK('MINTED-1'), DEVICE_OK('MINTED-2')], join: [[401, {}], JOIN_OK] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'bad-token' })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.count('device')).toBe(2)+ expect(joinTokens(s)).toEqual(['MINTED-1', 'MINTED-2'])+ })++ it('the re-mint path still works from an in-memory token: 401 on it earns exactly one fresh mint', async () => {+ const s = setup({ failWrites: true, routes: { device: [DEVICE_OK('MINTED-1'), DEVICE_OK('MINTED-2')], join: [[503, {}], [401, {}], JOIN_OK] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'network' })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.count('device')).toBe(2)+ expect(joinTokens(s)).toEqual(['MINTED-1', 'MINTED-1', 'MINTED-2'])+ })++ it('a kept in-memory token wins over the older one still in the bookmark', async () => {+ // Bookmark holds OLD; OLD earns a 401 and one re-mint (NEW), whose persist fails; the join then+ // drops (503). The retry must present NEW, not the rejected OLD.+ const s = setup({ failWrites: true, bookmarks: [bookmark()], routes: { device: [DEVICE_OK('NEW')], join: [[401, {}], [503, {}], JOIN_OK] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'network' })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.count('device')).toBe(1)+ expect(joinTokens(s)).toEqual(['OLD', 'NEW', 'NEW'])+ })++ it('forgetting a team through the bookmark-remove path forgets its in-memory token too', async () => {+ const s = setup({ routes: { device: [DEVICE_OK('MINTED-1'), DEVICE_OK('MINTED-2')], join: [JOIN_OK] } })+ await joinHostedTeam(codeText, s.deps, events().ev)+ await removeHostedBookmark(code.hostId, s.store, s.state)+ expect(await s.store.list()).toEqual([])+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.count('device')).toBe(2)+ expect(joinTokens(s)).toEqual(['MINTED-1', 'MINTED-2'])+ })++ it('the in-memory token is forgotten even when the bookmarks file refuses the removal', async () => {+ const s = setup({ failWrites: true, routes: { device: [DEVICE_OK('MINTED-1'), DEVICE_OK('MINTED-2')], join: [JOIN_OK] } })+ await joinHostedTeam(codeText, s.deps, events().ev) // token held in memory only+ fs.writeFileSync(s.file, 'nope')+ await expect(removeHostedBookmark(code.hostId, s.store, s.state)).rejects.toThrow()+ fs.rmSync(s.file)+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(joinTokens(s)).toEqual(['MINTED-1', 'MINTED-2'])+ })++ it('an id that cannot be minted still leaves with a stable code', async () => {+ const s = setup()+ const io = { newId: () => { throw new Error('no entropy') }, send: () => {}, sessions: new Map<string, RelayClientSession>() }+ await expect(connectHostedTeam(codeText, s.deps, io)).rejects.toThrow(/^\[E_JOIN_NETWORK\] no entropy$/)+ })+})+// ── End to end: the real core relay client against the real hosted service. ──────────────────────const live: Array<{ svc: HostedService; dir: string }> = []diff --git a/src/main/remote/hosted-join.ts b/src/main/remote/hosted-join.tsindex 3eb6b8e01..947621be9 100644--- a/src/main/remote/hosted-join.ts+++ b/src/main/remote/hosted-join.ts@@ -19,10 +19,15 @@// - One device id PER TEAM (`<machine id>:<hostId>`). The relay's device record is keyed by the id// alone and re-registering one for a different host needs proof this device cannot give on the// free tier, so a single id per machine would make every team after the first unjoinable.+// - Never mint a token this device cannot keep (R38). Before any mint the bookmarks file must be+// one a write could land in (`readForWrite`), else the join refuses and says to fix the file:+// a mint whose token only lives until the next retry spends the team's shared daily budget one+// retry at a time. A write that fails AFTER that check is covered by an in-process cache of the+// minted token, and a second join for the same team while one is still minting is refused.// - Every failure leaves with a stable `[E_JOIN_…]` code at the head of its message (the only part// of it Electron IPC carries to the renderer), so an unattended reconnect can tell a network// blip (retry) from anything a retry cannot fix (stop) — see @shared/relay-join-errors.-import { allowedEndpoint, decodeJoinCode, encodeJoinCode } from '../../core/relay/join-code'+import { allowedEndpoint, decodeJoinCode, encodeJoinCode, type JoinCode } from '../../core/relay/join-code'import { mintDeviceToken, mintJoinToken, type DeviceMintResult, type JoinMintResult } from '../../core/relay/join-token'import {connectRelayClient,@@ -76,19 +81,65 @@ export class HostedJoinError extends Error {const messageOf = (e: unknown): string => (e instanceof Error ? e.message : String(e))+/**+ * Device tokens minted by this process, per team, for exactly the host key they were minted for.+ * The bookmark is the durable copy; this is what keeps a retry from minting again when writing the+ * bookmark failed. In memory only: never logged, never sent to the renderer.+ */+export class DeviceTokenCache {+ private readonly byHost = new Map<string, { hostKeyB64: string; token: string }>()+ get(hostId: string, hostKeyB64: string): string | null {+ const e = this.byHost.get(hostId)+ return e && e.hostKeyB64 === hostKeyB64 ? e.token : null+ }+ set(hostId: string, hostKeyB64: string, token: string): void {+ this.byHost.set(hostId, { hostKeyB64, token })+ }+ forget(hostId: string): void {+ this.byHost.delete(hostId)+ }+}++/** Process-lifetime join state: the token cache, and the teams a join is currently minting or+ * joining for. One instance per app run; tests make their own. */+export interface HostedJoinState {+ tokens: DeviceTokenCache+ inflight: Set<string>+}++export function createHostedJoinState(): HostedJoinState {+ return { tokens: new DeviceTokenCache(), inflight: new Set() }+}++/** The app run's join state. */+export const hostedJoinState: HostedJoinState = createHostedJoinState()++/** Forget a team: its in-memory token first (so it is gone even if the file refuses the write), then+ * its bookmark. */+export function removeHostedBookmark(+ hostId: string,+ bookmarks: Pick<BookmarkStore, 'remove'>,+ state: HostedJoinState = hostedJoinState+): Promise<void> {+ state.tokens.forget(hostId)+ return bookmarks.remove(hostId)+}+export interface HostedJoinDeps {apiBase: string/** This machine's stable device id. */deviceId(): string/** This device's name as the host will see it next to the request. */label: string- bookmarks: Pick<BookmarkStore, 'list' | 'upsert' | 'update'>+ bookmarks: Pick<BookmarkStore, 'file' | 'list' | 'readForWrite' | 'upsert' | 'update'>/** Our long-lived peer identity (the key the team pins). May reject (a locked keyring). */loadKeys(): Promise<KeyPair>/** Defaults to the core relay client. Tests pass their own. */connect?(opts: HostedConnectOptions): RelayClientSessionfetch?: typeof fetchnow?(): number+ /** Defaults to the app run's state. */+ state?: HostedJoinState}export interface HostedJoinEvents {@@ -110,6 +161,23 @@ function bookmarkedKey(b: RelayBookmark): string | null {export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev: HostedJoinEvents): Promise<RelayClientSession> {const code = decodeJoinCode(codeText)if (!code) throw new HostedJoinError('invalid-code')+ const state = deps.state ?? hostedJoinState+ // One join per team at a time, from the first line to the moment the relay client exists. A second+ // one (a boot reconnect racing a manual connect, a double click) would mint a second token, and+ // its pending request would replace the first at the host. Refused, with a code that stops a+ // retry loop: the attempt already running is the one that should finish.+ if (state.inflight.has(code.hostId)) {+ throw new HostedJoinError('refused', 'Already joining this team; wait for that attempt to finish.')+ }+ state.inflight.add(code.hostId)+ try {+ return await joinWithCode(code, deps, ev, state)+ } finally {+ state.inflight.delete(code.hostId)+ }+}++async function joinWithCode(code: JoinCode, deps: HostedJoinDeps, ev: HostedJoinEvents, state: HostedJoinState): Promise<RelayClientSession> {let keys: KeyPairtry {keys = await deps.loadKeys()@@ -122,7 +190,8 @@ export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev:const sameKey = (b: RelayBookmark): boolean => bookmarkedKey(b) === code.hostPublicKeyB64const existing = found && sameKey(found) ? found : undefined- let deviceToken = existing?.deviceToken ?? null+ // A token this process minted and could not write down is newer than any bookmark.+ let deviceToken = state.tokens.get(code.hostId, code.hostPublicKeyB64) ?? existing?.deviceToken ?? nulllet approvedAt = existing?.approvedAt ?? nullconst record = (): RelayBookmark => ({hostId: code.hostId,@@ -149,6 +218,15 @@ export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev:}}const mintDevice = async (): Promise<string> => {+ // Only mint a token that can be kept: a file no write could land in would lose it at once.+ try {+ await deps.bookmarks.readForWrite()+ } catch {+ throw new HostedJoinError(+ 'refused',+ `The hosted-team bookmarks file ${deps.bookmarks.file} cannot be read or safely rewritten; fix or remove it, then join again.`+ )+ }const d: DeviceMintResult = await mintDeviceToken({apiBase: deps.apiBase,deviceId: `${deps.deviceId()}:${code.hostId}`,@@ -158,6 +236,7 @@ export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev:})if (!d.ok) throw new HostedJoinError(d.kind)deviceToken = d.deviceToken+ state.tokens.set(code.hostId, code.hostPublicKeyB64, d.deviceToken)await persist()return d.deviceToken}@@ -167,10 +246,16 @@ export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev:await mintDevice()mintedNow = true}- let j: JoinMintResult = await mintJoinToken({ apiBase: deps.apiBase, deviceToken: deviceToken!, fetch: deps.fetch })+ // A token the service rejects (401) or whose device it revoked (403) must not be offered again.+ const join = async (token: string): Promise<JoinMintResult> => {+ const r = await mintJoinToken({ apiBase: deps.apiBase, deviceToken: token, fetch: deps.fetch })+ if (!r.ok && (r.kind === 'bad-token' || r.kind === 'revoked')) state.tokens.forget(code.hostId)+ return r+ }+ let j: JoinMintResult = await join(deviceToken!)if (!j.ok && j.kind === 'bad-token' && !mintedNow) {- // The bookmarked token no longer verifies (it expired, or the service forgot it): one fresh mint.- j = await mintJoinToken({ apiBase: deps.apiBase, deviceToken: await mintDevice(), fetch: deps.fetch })+ // The kept token no longer verifies (it expired, or the service forgot it): one fresh mint.+ j = await join(await mintDevice())}if (!j.ok) throw new HostedJoinError(j.kind)// The client token is a bearer for the relay: never send it over plaintext to another machine,@@ -233,10 +318,11 @@ export interface HostedConnectIo {* the message the renderer sees starts with a stable code whatever went wrong.*/export async function connectHostedTeam(codeText: string, deps: HostedJoinDeps, io: HostedConnectIo): Promise<string> {- const connectionId = io.newId()+ let connectionId = ''let ended = falselet session: RelayClientSessiontry {+ connectionId = io.newId()session = await joinHostedTeam(codeText, deps, {onSas: (sas) => io.send(IPC.relayClientSas(connectionId), sas),onApproved: () => io.send(IPC.relayClientApproved(connectionId)),diff --git a/src/main/remote/relay-bookmarks.ts b/src/main/remote/relay-bookmarks.tsindex a269ed631..3a517d14b 100644--- a/src/main/remote/relay-bookmarks.ts+++ b/src/main/remote/relay-bookmarks.ts@@ -48,7 +48,8 @@ export class BookmarkStore {// (a join persisting its token while an earlier join records its approval) never lose each other.private tail: Promise<unknown> = Promise.resolve()- constructor(private readonly file: string) {}+ /** @param file the bookmarks file; public so a refusal can name it (a path, never contents). */+ constructor(readonly file: string) {}/** The bookmarks on disk, for DISPLAY. A missing or unreadable file reads as none; malformed* entries are dropped. Reading never writes. Never build a write on this: see `readForWrite`. */