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 — per-team device id, stable error codes, no trust-state loss
review82d29ef022b4
diff --git a/src/core/relay/join-code.test.ts b/src/core/relay/join-code.test.tsindex 362704d4a..e715ada8b 100644--- a/src/core/relay/join-code.test.ts+++ b/src/core/relay/join-code.test.ts@@ -1,6 +1,6 @@// src/core/relay/join-code.test.tsimport { describe, it, expect } from 'vitest'-import { encodeJoinCode, decodeJoinCode, isJoinCode } from './join-code'+import { encodeJoinCode, decodeJoinCode, isJoinCode, allowedEndpoint } from './join-code'import { genKeyPair, publicKeyToB64 } from './e2ee'import { hostIdFromPublicKeyB64 } from './relay-id'@@ -26,4 +26,8 @@ describe('join code', () => {expect(decodeJoinCode('nodeterm://join?code=%%%')).toBeNull()expect(decodeJoinCode('')).toBeNull()})+ it('allowedEndpoint: wss anywhere, plaintext ws only to loopback', () => {+ for (const ok of ['wss://relay.nodeterm.dev', 'wss://1.2.3.4:443/x', 'ws://127.0.0.1:8080', 'ws://localhost', 'ws://[::1]:9']) expect(allowedEndpoint(ok), ok).toBe(true)+ for (const bad of ['ws://evil.example', 'ws://10.0.0.5', 'http://relay.nodeterm.dev', 'https://relay.nodeterm.dev', 'junk', '']) expect(allowedEndpoint(bad), bad).toBe(false)+ })})diff --git a/src/core/relay/join-code.ts b/src/core/relay/join-code.tsindex 72eaa57ea..38954ebbf 100644--- a/src/core/relay/join-code.ts+++ b/src/core/relay/join-code.ts@@ -7,7 +7,11 @@ import { hostIdFromPublicKeyB64 } from './relay-id'export interface JoinCode { v: 1; relayEndpoint: string; hostId: string; hostPublicKeyB64: string; hostDeviceId: string; label: string }const PREFIX = 'nodeterm://join?code='-function allowedEndpoint(endpoint: string): boolean {+/** A relay endpoint we will dial: `wss:` anywhere, plaintext `ws:` only to loopback. Applied to a+ * code's endpoint AND to the one the join API hands back, so neither can send a client token over+ * plaintext to another machine. */+export function allowedEndpoint(endpoint: string): boolean {+ if (typeof endpoint !== 'string') return falselet u: URLtry { u = new URL(endpoint) } catch { return false }if (u.protocol === 'wss:') return truediff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsindex bd139b8c5..94ca960d5 100644--- a/src/main/remote/hosted-join.test.ts+++ b/src/main/remote/hosted-join.test.ts@@ -7,7 +7,8 @@ import { describe, it, expect, vi, afterEach } 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 } from './hosted-join'+import { joinHostedTeam, connectHostedTeam, 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'import { hostIdFromPublicKeyB64 } from '../../core/relay/relay-id'@@ -82,7 +83,7 @@ function setup(opts: { routes?: Parameters<typeof api>[0]; bookmarks?: RelayBookbookmarks: store, loadKeys: opts.loadKeys ?? (async () => ourKeys), connect: c.connect, fetch: a.f,now: () => Date.parse('2026-09-29T10:00:00Z')}- return { store, api: a, c, deps, ourKeys }+ return { store, file: path.join(dir, 'relay-bookmarks.json'), api: a, c, deps, ourKeys }}const hostKeys = genKeyPair()@@ -96,7 +97,7 @@ describe('joinHostedTeam', () => {const loadKeys = vi.fn(async () => genKeyPair())const s = setup({ loadKeys })const tampered = encodeJoinCode({ ...code, hostId: 'x'.repeat(22) })- await expect(joinHostedTeam(tampered, s.deps, events().ev)).rejects.toMatchObject({ kind: 'invalid-code', message: 'That team code is invalid.' })+ await expect(joinHostedTeam(tampered, s.deps, events().ev)).rejects.toMatchObject({ kind: 'invalid-code', message: '[E_JOIN_BAD_CODE] That team code is invalid.' })expect(s.api.calls).toEqual([])expect(loadKeys).not.toHaveBeenCalled()expect(s.c.opened).toEqual([])@@ -107,7 +108,8 @@ describe('joinHostedTeam', () => {const e = events()const session = await joinHostedTeam(codeText, s.deps, e.ev)expect(s.api.calls).toEqual([- { route: 'device', body: { deviceId: 'my-device', hostDeviceId: 'host-dev', hostPublicKeyB64: code.hostPublicKeyB64, label: 'laptop' } },+ // R34: one device id PER TEAM, so joining a second team never re-registers the first's row.+ { route: 'device', body: { deviceId: `my-device:${code.hostId}`, hostDeviceId: 'host-dev', hostPublicKeyB64: code.hostPublicKeyB64, label: 'laptop' } },{ route: 'join', body: { deviceToken: 'DT' } }])const o = s.c.last()@@ -210,7 +212,7 @@ describe('joinHostedTeam', () => {it('revoked: the honest message, and no re-mint', async () => {const s = setup({ bookmarks: [bookmark()], routes: { join: [[403, { error: 'revoked' }]] } })- await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'revoked', message: "This device's relay access was revoked." })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'revoked', message: "[E_JOIN_REVOKED] This device's relay access was revoked." })expect(s.api.count('device')).toBe(0)})@@ -237,10 +239,87 @@ describe('joinHostedTeam', () => {it('a locked keyring rejects before any mint is spent', async () => {const s = setup({ loadKeys: async () => { throw Object.assign(new Error('keyring locked'), { code: 'E_PEER_KEY_LOCKED' }) } })- await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toThrow('keyring locked')+ const err = await joinHostedTeam(codeText, s.deps, events().ev).catch((e: Error) => e)+ // The loader's own sentence is kept (it tells the human to unlock and reconnect), behind the code.+ expect((err as Error).message).toBe('[E_JOIN_KEY_LOCKED] keyring locked')expect(s.api.calls).toEqual([])})+ it('R34: two teams get two device ids, both derived from this machine\'s', async () => {+ const other = codeFor(genKeyPair(), { hostDeviceId: 'other-host-dev' })+ const s = setup()+ await joinHostedTeam(codeText, s.deps, events().ev)+ await joinHostedTeam(encodeJoinCode(other), s.deps, events().ev)+ const ids = s.api.calls.filter((c) => c.route === 'device').map((c) => c.body.deviceId)+ expect(ids).toEqual([`my-device:${code.hostId}`, `my-device:${other.hostId}`])+ expect(ids[0]).not.toBe(ids[1])+ expect(String(ids[0]).length).toBeLessThanOrEqual(200) // the backend's deviceId limit+ })++ it('R35: every failure kind carries its stable code, readable through Electron\'s wrapper', () => {+ const expected: Record<HostedJoinFailure, string> = {+ 'invalid-code': 'E_JOIN_BAD_CODE',+ 'rate-limited': 'E_JOIN_RATE',+ refused: 'E_JOIN_REFUSED',+ // A token the service will not accept even fresh: retrying only spends mints, so it stops.+ 'bad-token': 'E_JOIN_REFUSED',+ network: 'E_JOIN_NETWORK',+ revoked: 'E_JOIN_REVOKED',+ 'key-locked': 'E_JOIN_KEY_LOCKED'+ }+ for (const [kind, codeName] of Object.entries(expected) as Array<[HostedJoinFailure, string]>) {+ const e = new HostedJoinError(kind)+ expect(e.message.startsWith(`[${codeName}] `)).toBe(true)+ expect(e.code).toBe(codeName)+ expect(joinErrorCode(`Error invoking remote method 'relay:client:connect': Error: ${e.message}`)).toBe(codeName)+ }+ })++ it('R35: a connect that throws synchronously is a network failure', async () => {+ const s = setup()+ const connect = () => { throw new Error('Invalid URL') }+ await expect(joinHostedTeam(codeText, { ...s.deps, connect }, events().ev)).rejects.toMatchObject({ message: '[E_JOIN_NETWORK] Invalid URL' })+ })++ it('R36(4): a relay endpoint from the API that is not wss (or loopback ws) is never dialed', async () => {+ const s = setup({ routes: { device: [DEVICE_OK()], join: [[200, { pairingToken: 'PT', hostId: 'H', relayEndpoint: 'ws://evil.example', exp: 1 }]] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'network', message: expect.stringMatching(/^\[E_JOIN_NETWORK\] /) })+ expect(s.c.opened).toEqual([])+ })++ it('R36(3): an approval never overwrites a token a concurrent attempt re-minted meanwhile', async () => {+ const s = setup({ bookmarks: [bookmark()] })+ await joinHostedTeam(codeText, s.deps, events().ev) // this session uses 'OLD'+ await s.store.upsert(bookmark({ deviceToken: 'REMINTED' })) // another attempt's fresh token+ s.c.last().onApproved(s.c.sessions[0])+ await vi.waitFor(async () => expect((await s.store.list())[0].approvedAt).toBe('2026-09-29T10:00:00.000Z'))+ expect((await s.store.list())[0].deviceToken).toBe('REMINTED')+ })++ it('R36(2): a bookmark write that fails is logged once, naming the host and never a token or the code', async () => {+ 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.+ fs.writeFileSync(s.file, '[{"deviceToken": SECRET-TOKEN}]')+ await joinHostedTeam(codeText, s.deps, events().ev)+ s.c.last().onApproved(s.c.sessions[0])+ s.c.last().onDenied?.('removed')+ await vi.waitFor(() => expect(warn.mock.calls.length).toBeGreaterThanOrEqual(3))+ 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('nodeterm://join')+ expect(line).not.toContain(codeText.slice('nodeterm://join?code='.length, 40))+ }+ } finally {+ warn.mockRestore()+ }+ })+it('a denial is passed to onClosed and withdraws the joiner-side pin', async () => {for (const reason of ['denied', 'removed', 'expired'] as const) {const s = setup({ bookmarks: [bookmark({ approvedAt: '2026-09-01T00:00:00Z' })] })@@ -323,10 +402,18 @@ describe('connectHostedTeam (the relay:client:connect leg for a join code)', ()expect(x.sent).toEqual([[IPC.relayClientClosed('c1'), undefined]])})+ it('R35: a failure that is not ours still leaves with a stable code', async () => {+ const s = setup()+ const x = io()+ const deviceId = () => { throw new Error('platform not initialised') }+ await expect(connectHostedTeam(codeText, { ...s.deps, deviceId }, x.io)).rejects.toThrow(/^\[E_JOIN_NETWORK\] platform not initialised$/)+ expect(x.sessions.size).toBe(0)+ })+it('a failed join registers nothing and rejects with the human message', async () => {const s = setup({ routes: { device: [[429, {}]] } })const x = io()- await expect(connectHostedTeam(codeText, s.deps, x.io)).rejects.toThrow('Too many join attempts for this team today. Try again tomorrow.')+ await expect(connectHostedTeam(codeText, s.deps, x.io)).rejects.toThrow('[E_JOIN_RATE] Too many join attempts for this team today. Try again tomorrow.')expect(x.sessions.size).toBe(0)expect(x.sent).toEqual([])})diff --git a/src/main/remote/hosted-join.ts b/src/main/remote/hosted-join.tsindex 120ee4d7f..3eb6b8e01 100644--- a/src/main/remote/hosted-join.ts+++ b/src/main/remote/hosted-join.ts@@ -16,7 +16,13 @@// token is persisted the moment it is minted (a join that then fails does not throw it away), a// bookmarked token earns one re-mint on `bad-token` and nothing more, and `revoked` earns none.// - The keys are loaded before anything is minted: a locked keyring must not cost a mint.-import { decodeJoinCode, encodeJoinCode } from '../../core/relay/join-code'+// - 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.+// - 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 { mintDeviceToken, mintJoinToken, type DeviceMintResult, type JoinMintResult } from '../../core/relay/join-token'import {connectRelayClient,@@ -28,11 +34,24 @@ import type { KeyPair } from '../../core/relay/e2ee'import type { BookmarkStore, RelayBookmark } from './relay-bookmarks'import { IPC } from '../../shared/ipc'import type { RelayClosedReason } from '../../shared/types'+import type { JoinErrorCode } from '../../shared/relay-join-errors'/** What a hosted join hands the relay client: never a pin store. */export type HostedConnectOptions = Omit<ConnectRelayClientOptions, 'pins' | 'transport'>-export type HostedJoinFailure = 'invalid-code' | 'rate-limited' | 'refused' | 'network' | 'bad-token' | 'revoked'+export type HostedJoinFailure = 'invalid-code' | 'rate-limited' | 'refused' | 'network' | 'bad-token' | 'revoked' | 'key-locked'++/** Each failure's stable code. `bad-token` is a refusal: a token the service will not accept even+ * freshly minted cannot be fixed by retrying, which would only spend damped mints. */+const CODES: Record<HostedJoinFailure, JoinErrorCode> = {+ 'invalid-code': 'E_JOIN_BAD_CODE',+ 'rate-limited': 'E_JOIN_RATE',+ refused: 'E_JOIN_REFUSED',+ 'bad-token': 'E_JOIN_REFUSED',+ network: 'E_JOIN_NETWORK',+ revoked: 'E_JOIN_REVOKED',+ 'key-locked': 'E_JOIN_KEY_LOCKED'+}const MESSAGES: Record<HostedJoinFailure, string> = {'invalid-code': 'That team code is invalid.',@@ -40,17 +59,23 @@ const MESSAGES: Record<HostedJoinFailure, string> = {refused: 'The nodeterm service refused to register this device for that team.',network: 'Could not reach the nodeterm service. Check the connection and try again.','bad-token': "The nodeterm service did not accept this device's token for that team.",- revoked: "This device's relay access was revoked."+ revoked: "This device's relay access was revoked.",+ 'key-locked': 'This device identity could not be loaded.'}-/** A join that did not reach the relay. `kind` says why; the message is for the human. */+/** A join that did not reach the relay. `kind` says why; the message is `[<code>] <for the human>`,+ * with `detail` in place of the stock sentence when the failing step said something better. */export class HostedJoinError extends Error {- constructor(readonly kind: HostedJoinFailure) {- super(MESSAGES[kind])+ readonly code: JoinErrorCode+ constructor(readonly kind: HostedJoinFailure, detail?: string) {+ super(`[${CODES[kind]}] ${detail ?? MESSAGES[kind]}`)+ this.code = CODES[kind]this.name = 'HostedJoinError'}}+const messageOf = (e: unknown): string => (e instanceof Error ? e.message : String(e))+export interface HostedJoinDeps {apiBase: string/** This machine's stable device id. */@@ -85,10 +110,17 @@ 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 keys = await deps.loadKeys()+ let keys: KeyPair+ try {+ keys = await deps.loadKeys()+ } catch (e) {+ // The loader's own sentence (a locked keyring says to unlock and reconnect) is the useful one.+ throw new HostedJoinError('key-locked', messageOf(e))+ }const found = (await deps.bookmarks.list()).find((b) => b.hostId === code.hostId)// A bookmark is trusted only for the exact key it was made with; otherwise this is a new host.- const existing = found && bookmarkedKey(found) === code.hostPublicKeyB64 ? found : undefined+ const sameKey = (b: RelayBookmark): boolean => bookmarkedKey(b) === code.hostPublicKeyB64+ const existing = found && sameKey(found) ? found : undefinedlet deviceToken = existing?.deviceToken ?? nulllet approvedAt = existing?.approvedAt ?? null@@ -101,10 +133,29 @@ export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev:source: existing?.source ?? 'code'})// A bookmark that could not be written costs a mint and a SAS dialog next time, never access, so a- // failed write does not fail the join.- const persist = (): Promise<void> => deps.bookmarks.upsert(record()).catch(() => {})+ // failed write does not fail the join. It is said, once per failure: the host and why, never the+ // code or a token.+ const saveFailed = (e: unknown): void => {+ console.warn(`[hosted-join] could not save the bookmark for host ${code.hostId}: ${messageOf(e)}`)+ }+ let saved = found ? JSON.stringify(found) : null+ const persist = async (): Promise<void> => {+ const next = record()+ try {+ await deps.bookmarks.upsert(next)+ saved = JSON.stringify(next)+ } catch (e) {+ saveFailed(e)+ }+ }const mintDevice = async (): Promise<string> => {- const d: DeviceMintResult = await mintDeviceToken({ apiBase: deps.apiBase, deviceId: deps.deviceId(), code, label: deps.label, fetch: deps.fetch })+ const d: DeviceMintResult = await mintDeviceToken({+ apiBase: deps.apiBase,+ deviceId: `${deps.deviceId()}:${code.hostId}`,+ code,+ label: deps.label,+ fetch: deps.fetch+ })if (!d.ok) throw new HostedJoinError(d.kind)deviceToken = d.deviceTokenawait persist()@@ -122,37 +173,48 @@ export async function joinHostedTeam(codeText: string, deps: HostedJoinDeps, ev:j = await mintJoinToken({ apiBase: deps.apiBase, deviceToken: await mintDevice(), fetch: deps.fetch })}if (!j.ok) throw new HostedJoinError(j.kind)- if (JSON.stringify(record()) !== JSON.stringify(found ?? null)) await persist()+ // The client token is a bearer for the relay: never send it over plaintext to another machine,+ // whoever named the endpoint. Same rule a join code's own endpoint is held to.+ if (!allowedEndpoint(j.relayEndpoint)) {+ throw new HostedJoinError('network', 'The nodeterm service named a relay this device will not use.')+ }+ if (JSON.stringify(record()) !== saved) await persist()let deniedReason: TrustDeniedReason | undefinedconst connect = deps.connect ?? connectRelayClientconst now = deps.now ?? Date.now- return connect({- url: j.relayEndpoint,- token: j.pairingToken,- hostKeyB64: code.hostPublicKeyB64,- ourKeys: keys,- autoApprove: approvedAt !== null,- onSas: (s) => ev.onSas(s.sas()),- onApproved: () => {- if (approvedAt === null) {- approvedAt = new Date(now()).toISOString()- void deps.bookmarks.update(code.hostId, { approvedAt, deviceToken }).catch(() => {})- }- ev.onApproved()- },- onFrame: (json) => ev.onFrame(json),- onPtyData: (sessionId, data) => ev.onPtyData(sessionId, data),- onDenied: (reason) => {- deniedReason = reason- // The host no longer counts this device as approved: the next attempt shows the SAS again.- if (approvedAt !== null) {- approvedAt = null- void deps.bookmarks.update(code.hostId, { approvedAt: null }).catch(() => {})- }- },- onClose: () => ev.onClosed(deniedReason)- })+ try {+ return connect({+ url: j.relayEndpoint,+ token: j.pairingToken,+ hostKeyB64: code.hostPublicKeyB64,+ ourKeys: keys,+ autoApprove: approvedAt !== null,+ onSas: (s) => ev.onSas(s.sas()),+ onApproved: () => {+ if (approvedAt === null) {+ approvedAt = new Date(now()).toISOString()+ // The approval ONLY: a concurrent attempt may have re-minted the token since this one read+ // it, and the approval is about this device's key on that host, not about a token.+ void deps.bookmarks.update(code.hostId, { approvedAt }, sameKey).catch(saveFailed)+ }+ ev.onApproved()+ },+ onFrame: (json) => ev.onFrame(json),+ onPtyData: (sessionId, data) => ev.onPtyData(sessionId, data),+ onDenied: (reason) => {+ deniedReason = reason+ // The host no longer counts this device as approved: the next attempt shows the SAS again.+ if (approvedAt !== null) {+ approvedAt = null+ void deps.bookmarks.update(code.hostId, { approvedAt: null }, sameKey).catch(saveFailed)+ }+ },+ onClose: () => ev.onClosed(deniedReason)+ })+ } catch (e) {+ throw new HostedJoinError('network', messageOf(e))+ }}/** How `connectHostedTeam` reaches the renderer and the handler's connection registry. */@@ -167,23 +229,30 @@ export interface HostedConnectIo {/*** The `relay:client:connect` leg for a join code: run the join, route its events to the same* per-connection channels a pairing offer uses, and register the session. Resolves with the- * connection id; rejects (with the human message) when the join never reached the relay.+ * connection id; rejects when the join never reached the relay, ALWAYS with a HostedJoinError, so+ * 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 ended = false- const session = await joinHostedTeam(codeText, deps, {- onSas: (sas) => io.send(IPC.relayClientSas(connectionId), sas),- onApproved: () => io.send(IPC.relayClientApproved(connectionId)),- onFrame: (json) => io.send(IPC.relayClientFrame(connectionId), json),- // pty output arrives on the SAME per-session channel a local pty uses.- onPtyData: (sessionId, data) => io.send(IPC.ptyData(sessionId), data),- onClosed: (reason) => {- ended = true- io.sessions.delete(connectionId)- io.send(IPC.relayClientClosed(connectionId), reason)- }- })+ let session: RelayClientSession+ try {+ session = await joinHostedTeam(codeText, deps, {+ onSas: (sas) => io.send(IPC.relayClientSas(connectionId), sas),+ onApproved: () => io.send(IPC.relayClientApproved(connectionId)),+ onFrame: (json) => io.send(IPC.relayClientFrame(connectionId), json),+ // pty output arrives on the SAME per-session channel a local pty uses.+ onPtyData: (sessionId, data) => io.send(IPC.ptyData(sessionId), data),+ onClosed: (reason) => {+ ended = true+ io.sessions.delete(connectionId)+ io.send(IPC.relayClientClosed(connectionId), reason)+ }+ })+ } catch (e) {+ // Not one of ours (a bug, an environment surprise): say it, under the one code that may retry.+ throw e instanceof HostedJoinError ? e : new HostedJoinError('network', messageOf(e))+ }// A socket that already closed must not leave a dead session behind in the registry.if (!ended) io.sessions.set(connectionId, session)return connectionIddiff --git a/src/main/remote/relay-bookmarks.test.ts b/src/main/remote/relay-bookmarks.test.tsindex 8f3be9559..3e092f47e 100644--- a/src/main/remote/relay-bookmarks.test.ts+++ b/src/main/remote/relay-bookmarks.test.ts@@ -29,13 +29,50 @@ describe('relay bookmarks', () => {expect((fs.statSync(file).mode & 0o777).toString(8)).toBe('600')})- it('a corrupt file reads as empty and is not overwritten until the next write', async () => {+ it('a corrupt file reads as empty for display, and no write ever replaces it', async () => {+ // A corrupt file may still hold other teams' tokens and approvals: unknown trust state is never+ // overwritten, so every write refuses until the file is readable again.const file = tmpFile()fs.writeFileSync(file, 'nope')- expect(await new BookmarkStore(file).list()).toEqual([])+ const s = new BookmarkStore(file)+ expect(await s.list()).toEqual([])+ await expect(s.upsert(b)).rejects.toThrow()+ await expect(s.update('H', { approvedAt: 'now' })).rejects.toThrow()+ await expect(s.remove('H')).rejects.toThrow()expect(fs.readFileSync(file, 'utf8')).toBe('nope')})+ it('a file with a malformed entry is refused for writes too (that entry would be dropped)', async () => {+ const file = tmpFile()+ const raw = JSON.stringify([b, { hostId: 'X' }])+ fs.writeFileSync(file, raw)+ const s = new BookmarkStore(file)+ await expect(s.upsert({ ...b, hostId: 'H2' })).rejects.toThrow()+ fs.writeFileSync(file, JSON.stringify({ not: 'a list' }))+ await expect(s.upsert(b)).rejects.toThrow()+ fs.writeFileSync(file, raw)+ await expect(s.remove('H')).rejects.toThrow()+ expect(fs.readFileSync(file, 'utf8')).toBe(raw)+ })++ it('readForWrite: none on a missing file; a refusal never quotes the file (it holds tokens)', async () => {+ const file = tmpFile()+ const s = new BookmarkStore(file)+ expect(await s.readForWrite()).toEqual([])+ // An unquoted token: V8's JSON.parse error QUOTES the text around it ('..."ceToken": SECRET-TOK"...').+ fs.writeFileSync(file, '[{"deviceToken": SECRET-TOKEN}]')+ const err = await s.readForWrite().catch((e: Error) => e)+ expect(err).toBeInstanceOf(Error)+ expect((err as Error).message).not.toContain('SECRET')+ })++ it.skipIf(process.platform === 'win32')('an unreadable file (not a missing one) is refused for writes', async () => {+ // A directory where the file should be: reading it fails with EISDIR, which is not absence.+ const file = tmpFile()+ fs.mkdirSync(file)+ await expect(new BookmarkStore(file).upsert(b)).rejects.toThrow()+ })+it('drops malformed entries on read', async () => {const file = tmpFile()fs.writeFileSync(file, JSON.stringify([b, { hostId: 'X' }, null, { ...b, hostId: 'Y', source: 'phone' }, { ...b, hostId: 'Z', deviceToken: 5 }]))@@ -48,6 +85,15 @@ describe('relay bookmarks', () => {expect((await s.list()).map((x) => x.hostId).sort()).toEqual(['A', 'B', 'C', 'D'])})+ it('update applies only when the stored bookmark still satisfies the caller\'s condition', async () => {+ const s = new BookmarkStore(tmpFile())+ await s.upsert({ ...b, deviceToken: 'NEWER' })+ await s.update('H', { approvedAt: 'now' }, (x) => x.deviceToken === 'OLDER')+ expect((await s.list())[0].approvedAt).toBeNull()+ await s.update('H', { approvedAt: 'now' }, (x) => x.deviceToken === 'NEWER')+ expect((await s.list())[0].approvedAt).toBe('now')+ })+it('update patches an existing bookmark and never creates one', async () => {const s = new BookmarkStore(tmpFile())await s.update('H', { approvedAt: 'now' })diff --git a/src/main/remote/relay-bookmarks.ts b/src/main/remote/relay-bookmarks.tsindex 9bdf01127..a269ed631 100644--- a/src/main/remote/relay-bookmarks.ts+++ b/src/main/remote/relay-bookmarks.ts@@ -50,8 +50,8 @@ export class BookmarkStore {constructor(private readonly file: string) {}- /** The bookmarks on disk. A missing or unreadable file reads as none; malformed entries are- * dropped. Reading never writes, so a corrupt file stays as it is until the next write. */+ /** 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`. */async list(): Promise<RelayBookmark[]> {try {const j = JSON.parse(await fs.readFile(this.file, 'utf-8')) as unknown@@ -61,9 +61,33 @@ export class BookmarkStore {}}+ /**+ * The bookmarks every write starts from. Only a MISSING file is "none". A file that cannot be read,+ * or does not parse, or holds an entry this build does not understand, rejects: rewriting it from+ * a guess would silently drop other teams' device tokens and approvals (unknown trust state is+ * never overwritten). The refusal names the file, never its contents: they hold tokens.+ */+ async readForWrite(): Promise<RelayBookmark[]> {+ let raw: string+ try {+ raw = await fs.readFile(this.file, 'utf-8')+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return []+ throw new Error(`relay bookmarks could not be read (${(err as NodeJS.ErrnoException)?.code ?? 'unknown error'}); not rewriting them`)+ }+ let j: unknown+ try {+ j = JSON.parse(raw)+ } catch {+ throw new Error('relay bookmarks file is not valid JSON; not rewriting it')+ }+ if (!Array.isArray(j) || !j.every(valid)) throw new Error('relay bookmarks file holds entries this build cannot read; not rewriting it')+ return j+ }+private write(fn: (l: RelayBookmark[]) => RelayBookmark[] | null): Promise<void> {const run = this.tail.then(async () => {- const next = fn(await this.list())+ const next = fn(await this.readForWrite())if (next) await writeFileAtomic(this.file, JSON.stringify(next, null, 2), { mode: 0o600 })})this.tail = run.catch(() => {})@@ -75,10 +99,19 @@ export class BookmarkStore {return this.write((l) => [...l.filter((x) => x.hostId !== b.hostId), b])}- /** Change fields of an EXISTING bookmark; a no-op when there is none. For updates that follow a- * connection's events, so a bookmark the user removed meanwhile is not brought back. */- update(hostId: string, patch: Partial<Pick<RelayBookmark, 'deviceToken' | 'approvedAt'>>): Promise<void> {- return this.write((l) => (l.some((x) => x.hostId === hostId) ? l.map((x) => (x.hostId === hostId ? { ...x, ...patch } : x)) : null))+ /** Change fields of an EXISTING bookmark; a no-op when there is none, or when the stored one no+ * longer satisfies `onlyIf`. For updates that follow a connection's events: a bookmark the user+ * removed meanwhile is not brought back, and one another attempt rewrote is not clobbered. */+ update(+ hostId: string,+ patch: Partial<Pick<RelayBookmark, 'deviceToken' | 'approvedAt'>>,+ onlyIf: (current: RelayBookmark) => boolean = () => true+ ): Promise<void> {+ return this.write((l) => {+ const current = l.find((x) => x.hostId === hostId)+ if (!current || !onlyIf(current)) return null+ return l.map((x) => (x === current ? { ...x, ...patch } : x))+ })}remove(hostId: string): Promise<void> {diff --git a/src/shared/relay-join-errors.test.ts b/src/shared/relay-join-errors.test.tsnew file mode 100644index 000000000..7ef64acab--- /dev/null+++ b/src/shared/relay-join-errors.test.ts@@ -0,0 +1,26 @@+// src/shared/relay-join-errors.test.ts+import { describe, it, expect } from 'vitest'+import { JOIN_ERROR_CODES, joinErrorCode, joinErrorRetries } from './relay-join-errors'++describe('hosted join error codes', () => {+ it('reads each code off the message main threw, and off the one Electron hands the renderer', () => {+ for (const code of JOIN_ERROR_CODES) {+ expect(joinErrorCode(`[${code}] something happened`)).toBe(code)+ // ipcRenderer.invoke rejects with main's message wrapped in its own prefix.+ expect(joinErrorCode(`Error invoking remote method 'relay:client:connect': Error: [${code}] something happened`)).toBe(code)+ }+ })++ it('answers null for anything that is not one of ours', () => {+ expect(joinErrorCode('That pairing code is invalid or incomplete.')).toBeNull()+ expect(joinErrorCode('[E_JOIN_SOMETHING_NEW] x')).toBeNull()+ expect(joinErrorCode('[e_join_network] x')).toBeNull()+ expect(joinErrorCode('')).toBeNull()+ expect(joinErrorCode(undefined as unknown as string)).toBeNull()+ })++ it('only a network failure is worth retrying', () => {+ expect(JOIN_ERROR_CODES.filter(joinErrorRetries)).toEqual(['E_JOIN_NETWORK'])+ expect(joinErrorRetries(null)).toBe(false)+ })+})diff --git a/src/shared/relay-join-errors.ts b/src/shared/relay-join-errors.tsnew file mode 100644index 000000000..5fdfb2136--- /dev/null+++ b/src/shared/relay-join-errors.ts@@ -0,0 +1,34 @@+// Stable codes for a hosted-team join that failed before it reached the relay.+//+// The main process throws with a message that starts with `[E_JOIN_…]`; that code is the only part+// of the failure that survives Electron IPC (an `ipcMain.handle` rejection reaches the renderer as+// its message, wrapped in Electron's own prefix). A renderer that reconnects on its own reads the+// code with `joinErrorCode` and decides whether trying again can help: only a network failure can.+// Every other code needs a human (a new code, an unlocked keyring, an owner) or a new day, and+// retrying it would at best repeat the refusal and at worst spend damped device-token mints.++export const JOIN_ERROR_CODES = [+ 'E_JOIN_REVOKED',+ 'E_JOIN_REFUSED',+ 'E_JOIN_RATE',+ 'E_JOIN_BAD_CODE',+ 'E_JOIN_NETWORK',+ 'E_JOIN_KEY_LOCKED'+] as const++export type JoinErrorCode = (typeof JOIN_ERROR_CODES)[number]++const CODE_RE = /\[(E_JOIN_[A-Z_]+)\]/++/** The join error code in `message` (anywhere: Electron prefixes it), or null when there is none. */+export function joinErrorCode(message: string): JoinErrorCode | null {+ if (typeof message !== 'string') return null+ const m = CODE_RE.exec(message)+ const code = m?.[1]+ return code && (JOIN_ERROR_CODES as readonly string[]).includes(code) ? (code as JoinErrorCode) : null+}++/** Whether a failed join is worth retrying unattended. */+export function joinErrorRetries(code: JoinErrorCode | null): boolean {+ return code === 'E_JOIN_NETWORK'+}