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): desktop joins hosted teams by code, with bookmarks and pinned reconnect
review2b0e7d145985
diff --git a/src/core/relay/hosted-service.test.ts b/src/core/relay/hosted-service.test.tsindex 39414f3b8..0de28f378 100644--- a/src/core/relay/hosted-service.test.ts+++ b/src/core/relay/hosted-service.test.ts@@ -892,7 +892,11 @@ describe('hosted service — lifecycle', () => {it('every hosted channel lives under the one prefix the access hook refuses outside the interceptor', () => {const hosted = Object.entries(IPC).filter(([k]) => k.startsWith('relayHosted')).map(([, v]) => v)- expect(hosted).toHaveLength(7)+ // Seven relay-tunnel verbs plus the desktop's two bookmark channels. Those two are raw ipcMain+ // handlers that never ride the relay; living under the prefix means a relay peer that asks for+ // one is refused by the access hook here, which is the right answer for them.+ expect(hosted).toHaveLength(9)+ expect(hosted).toEqual(expect.arrayContaining([IPC.relayHostedBookmarks, IPC.relayHostedBookmarkRemove]))for (const ch of hosted) expect(ch).toMatch(/^relay:hosted:/)})})diff --git a/src/core/relay/join-token.test.ts b/src/core/relay/join-token.test.tsnew file mode 100644index 000000000..228cc1473--- /dev/null+++ b/src/core/relay/join-token.test.ts@@ -0,0 +1,72 @@+// src/core/relay/join-token.test.ts+import { describe, it, expect } from 'vitest'+import { mintDeviceToken, mintJoinToken } from './join-token'++const code = { v: 1 as const, relayEndpoint: 'wss://r', hostId: 'H', hostPublicKeyB64: 'K', hostDeviceId: 'HD', label: 'box' }++/** A fetch that answers `status` + `body` and records what it was asked. */+function fake(status: number, body: unknown) {+ const calls: Array<{ url: string; method?: string; body: unknown }> = []+ const f = (async (url: string, init: RequestInit) => {+ calls.push({ url, method: init.method, body: JSON.parse(String(init.body)) })+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status })+ }) as unknown as typeof fetch+ return { f, calls }+}+const throwing = (async () => { throw new Error('ECONNRESET') }) as unknown as typeof fetch++describe('joiner tokens', () => {+ it('device mint sends exactly the free-tier body to <apiBase>/v1/relay/device', async () => {+ const { f, calls } = fake(200, { deviceToken: 'DT', hostId: 'H', exp: 1 })+ expect(await mintDeviceToken({ apiBase: 'https://api/', deviceId: 'me', code, label: 'laptop', fetch: f }))+ .toEqual({ ok: true, deviceToken: 'DT' })+ expect(calls).toEqual([{+ url: 'https://api/v1/relay/device',+ method: 'POST',+ body: { deviceId: 'me', hostDeviceId: 'HD', hostPublicKeyB64: 'K', label: 'laptop' }+ }])+ })++ it('device mint: 429 is rate-limited, a 4xx is refused, 5xx and a throw are network, a bad body is refused', async () => {+ const mint = (f: typeof fetch) => mintDeviceToken({ apiBase: 'a', deviceId: 'me', code, label: 'l', fetch: f })+ expect(await mint(fake(429, { error: 'rate_limited' }).f)).toEqual({ ok: false, kind: 'rate-limited' })+ expect(await mint(fake(403, { error: 'reauth_required' }).f)).toEqual({ ok: false, kind: 'refused' })+ expect(await mint(fake(402, { error: 'not_entitled' }).f)).toEqual({ ok: false, kind: 'refused' })+ expect(await mint(fake(503, 'bad gateway').f)).toEqual({ ok: false, kind: 'network' })+ expect(await mint(throwing)).toEqual({ ok: false, kind: 'network' })+ expect(await mint(fake(200, 'not json').f)).toEqual({ ok: false, kind: 'refused' })+ expect(await mint(fake(200, { deviceToken: '' }).f)).toEqual({ ok: false, kind: 'refused' })+ })++ it('join posts {deviceToken} and maps 401 → bad-token and 403 → revoked', async () => {+ const ok = fake(200, { pairingToken: 'P', hostId: 'H', relayEndpoint: 'wss://r', exp: 1 })+ expect(await mintJoinToken({ apiBase: 'https://api', deviceToken: 'x', fetch: ok.f }))+ .toEqual({ ok: true, pairingToken: 'P', relayEndpoint: 'wss://r' })+ expect(ok.calls).toEqual([{ url: 'https://api/v1/relay/join', method: 'POST', body: { deviceToken: 'x' } }])+ expect(await mintJoinToken({ apiBase: 'a', deviceToken: 'x', fetch: fake(401, {}).f })).toEqual({ ok: false, kind: 'bad-token' })+ expect(await mintJoinToken({ apiBase: 'a', deviceToken: 'x', fetch: fake(403, {}).f })).toEqual({ ok: false, kind: 'revoked' })+ })++ it('join: any other failure is network, never a token verdict', async () => {+ const join = (f: typeof fetch) => mintJoinToken({ apiBase: 'a', deviceToken: 'x', fetch: f })+ expect(await join(fake(500, {}).f)).toEqual({ ok: false, kind: 'network' })+ expect(await join(fake(429, {}).f)).toEqual({ ok: false, kind: 'network' })+ expect(await join(throwing)).toEqual({ ok: false, kind: 'network' })+ expect(await join(fake(200, 'nope').f)).toEqual({ ok: false, kind: 'network' })+ expect(await join(fake(200, { pairingToken: 'P' }).f)).toEqual({ ok: false, kind: 'network' })+ expect(await join(fake(200, { pairingToken: '', relayEndpoint: 'wss://r' }).f)).toEqual({ ok: false, kind: 'network' })+ })++ it('the timeout covers a body that never finishes', async () => {+ const stalled = (async (_u: string, init: RequestInit) => ({+ ok: true,+ status: 200,+ json: () => new Promise((_resolve, reject) => {+ init.signal?.addEventListener('abort', () => reject(new Error('aborted')))+ })+ })) as unknown as typeof fetch+ expect(await mintJoinToken({ apiBase: 'a', deviceToken: 'x', fetch: stalled, timeoutMs: 20 })).toEqual({ ok: false, kind: 'network' })+ expect(await mintDeviceToken({ apiBase: 'a', deviceId: 'me', code, label: 'l', fetch: stalled, timeoutMs: 20 }))+ .toEqual({ ok: false, kind: 'network' })+ })+})diff --git a/src/core/relay/join-token.ts b/src/core/relay/join-token.tsnew file mode 100644index 000000000..39eeb34f7--- /dev/null+++ b/src/core/relay/join-token.ts@@ -0,0 +1,93 @@+// The joiner's two API legs: the phone's relay flow, for a desktop joining a hosted team.+// 1. `POST /v1/relay/device {deviceId, hostDeviceId, hostPublicKeyB64, label}` → a device token+// for THIS device and THAT host (about 90 days). Free-tier mints are damped server-side+// (a few per day), so the caller keeps the token and never mints in a loop.+// 2. `POST /v1/relay/join {deviceToken}` → a short-lived client pairing token and the relay to use.+// Neither leg grants anything on its own: the host still decides who gets in.+//+// Each result says WHICH failure it was, because the caller reacts differently to each: only a+// `bad-token` join earns one fresh device mint, a `revoked` one never does, and `rate-limited`+// means waiting until tomorrow rather than retrying.+import type { JoinCode } from './join-code'++const TIMEOUT_MS = 8000++export type DeviceMintResult = { ok: true; deviceToken: string } | { ok: false; kind: 'network' | 'refused' | 'rate-limited' }+export type JoinMintResult =+ | { ok: true; pairingToken: string; relayEndpoint: string }+ | { ok: false; kind: 'bad-token' | 'revoked' | 'network' }++/** A reply: its status and its parsed JSON body (`null` when the body is not JSON). */+interface Reply { status: number; ok: boolean; body: unknown }++/** POST `body` and read the JSON reply under ONE timeout that covers the body too: a reply whose+ * body stalls would otherwise leave the join pending forever. `null` = no usable response (the+ * request failed, or the timeout cut it short), which is the network's fault either way. */+async function post(apiBase: string, p: string, body: unknown, f: typeof fetch, timeoutMs: number): Promise<Reply | null> {+ const ctrl = new AbortController()+ const timer = setTimeout(() => ctrl.abort(), timeoutMs)+ try {+ const res = await f(`${apiBase.replace(/\/+$/, '')}${p}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal: ctrl.signal+ })+ let parsed: unknown = null+ try {+ parsed = await res.json()+ } catch {+ if (ctrl.signal.aborted) return null+ }+ return { status: res.status, ok: res.ok, body: parsed }+ } catch {+ return null+ } finally {+ clearTimeout(timer)+ }+}++export async function mintDeviceToken(d: {+ apiBase: string+ deviceId: string+ code: JoinCode+ label: string+ fetch?: typeof fetch+ timeoutMs?: number+}): Promise<DeviceMintResult> {+ const res = await post(+ d.apiBase,+ '/v1/relay/device',+ // EXACTLY these four fields: the free-tier body the production endpoint was verified against.+ { deviceId: d.deviceId, hostDeviceId: d.code.hostDeviceId, hostPublicKeyB64: d.code.hostPublicKeyB64, label: d.label },+ d.fetch ?? fetch,+ d.timeoutMs ?? TIMEOUT_MS+ )+ if (!res) return { ok: false, kind: 'network' }+ if (res.status === 429) return { ok: false, kind: 'rate-limited' }+ // A 5xx is the service being down, not a verdict on this device.+ if (res.status >= 500) return { ok: false, kind: 'network' }+ if (!res.ok) return { ok: false, kind: 'refused' }+ const token = (res.body as { deviceToken?: unknown } | null)?.deviceToken+ return typeof token === 'string' && token ? { ok: true, deviceToken: token } : { ok: false, kind: 'refused' }+}++export async function mintJoinToken(d: {+ apiBase: string+ deviceToken: string+ fetch?: typeof fetch+ timeoutMs?: number+}): Promise<JoinMintResult> {+ const res = await post(d.apiBase, '/v1/relay/join', { deviceToken: d.deviceToken }, d.fetch ?? fetch, d.timeoutMs ?? TIMEOUT_MS)+ if (!res) return { ok: false, kind: 'network' }+ // 401 = the token did not verify (expired, or never ours); 403 = the device row is revoked.+ // Everything else says nothing about the token, so it must not cost a device mint.+ if (res.status === 401) return { ok: false, kind: 'bad-token' }+ if (res.status === 403) return { ok: false, kind: 'revoked' }+ if (!res.ok) return { ok: false, kind: 'network' }+ const j = res.body as { pairingToken?: unknown; relayEndpoint?: unknown } | null+ if (typeof j?.pairingToken !== 'string' || !j.pairingToken || typeof j.relayEndpoint !== 'string' || !j.relayEndpoint) {+ return { ok: false, kind: 'network' }+ }+ return { ok: true, pairingToken: j.pairingToken, relayEndpoint: j.relayEndpoint }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 2bb6e5fcf..33493226e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -324,6 +324,9 @@ import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } fromimport { 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 { BookmarkStore, publicBookmark } from './remote/relay-bookmarks'import { loadOrCreatePeerKeyPair } from './remote/peer-identity'import { initSshProject } from './remote-ssh/ssh-project'import { resyncProjectAgents, RESYNC_TRANSCRIPT_TAIL_BYTES } from './remote-ssh/agent-resync'@@ -4118,6 +4121,9 @@ app.whenReady().then(async () => {// Inert until `relay:client:connect` — a solo user pays nothing.{const relayClients = new Map<string, RelayClientSession>()+ // The hosted teams this desktop has joined by join code; each bookmark holds this device's relay+ // token for that host and is the joiner-side pin (src/main/remote/hosted-join.ts).+ const bookmarks = new BookmarkStore(join(app.getPath('userData'), 'relay-bookmarks.json'))const sendTo = (channel: string, ...args: unknown[]): void => {if (!win.isDestroyed()) win.webContents.send(channel, ...args)}@@ -4127,6 +4133,23 @@ app.whenReady().then(async () => {if (!relayAllowed()) {throw new Error('Remote access is unavailable in development builds (set NODETERM_RELAY_URL).')}+ // A hosted team's join code (a Server Edition hosting over the relay). It runs the CORE relay+ // client with no pin store, so the host key never reaches approved-devices; the pairing-offer+ // path below is unchanged.+ if (isJoinCode(String(offerCode ?? ''))) {+ return connectHostedTeam(+ String(offerCode),+ {+ apiBase: RELAY_API_BASE,+ deviceId: getDeviceId,+ label: hostname().slice(0, 60),+ bookmarks,+ // A locked keyring rejects here (E_PEER_KEY_LOCKED) before any token is minted.+ loadKeys: loadOrCreatePeerKeyPair+ },+ { newId: randomUUID, send: sendTo, sessions: relayClients }+ )+ }const offer = decodeOffer(String(offerCode ?? ''))if (!offer) {throw new Error('That pairing code is invalid or incomplete.')@@ -4178,6 +4201,9 @@ app.whenReady().then(async () => {relayClients.get(id)?.close()relayClients.delete(id)})+ // 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)))}sshProjectManager = initSshProject((projectId) => {diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsnew file mode 100644index 000000000..bd139b8c5--- /dev/null+++ b/src/main/remote/hosted-join.test.ts@@ -0,0 +1,417 @@+// src/main/remote/hosted-join.test.ts+// The desktop joiner's whole sequence (join code → device token → client token → connect) as a pure+// 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 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 { BookmarkStore, type RelayBookmark } from './relay-bookmarks'+import { encodeJoinCode, type JoinCode } from '../../core/relay/join-code'+import { hostIdFromPublicKeyB64 } from '../../core/relay/relay-id'+import { genKeyPair, publicKeyToB64, type KeyPair } from '../../core/relay/e2ee'+import { connectRelayClient, type RelayClientSession } from '../../core/relay/relay-client'+import { createHostedService, type HostedService } from '../../core/relay/hosted-service'+import { transportPair } from '../../core/relay/transport-pair'+import type { PeerAttach } from '../../core/relay/relay-host'+import type { RelayTransport } from '../../core/relay/relay-socket'+import { IPC } from '../../shared/ipc'++const tmpDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'hosted-join-'))+const pub = (k: KeyPair) => publicKeyToB64(k.publicKey)++function codeFor(hostKeys: KeyPair, over: Partial<JoinCode> = {}): JoinCode {+ const k = pub(hostKeys)+ return { v: 1, relayEndpoint: 'wss://relay.example', hostId: hostIdFromPublicKeyB64(k), hostPublicKeyB64: k, hostDeviceId: 'host-dev', label: 'box', ...over }+}++/** An API that answers each route from its own queue (last answer repeats) and records every call. */+function api(routes: { device?: Array<[number, unknown]>; join?: Array<[number, unknown]> }) {+ const calls: Array<{ route: 'device' | 'join'; body: Record<string, unknown> }> = []+ const queues = { device: [...(routes.device ?? [])], join: [...(routes.join ?? [])] }+ const f = (async (url: string, init: RequestInit) => {+ const route = url.endsWith('/v1/relay/device') ? 'device' : url.endsWith('/v1/relay/join') ? 'join' : null+ if (!route) throw new Error(`unexpected ${url}`)+ calls.push({ route, body: JSON.parse(String(init.body)) })+ const q = queues[route]+ const [status, body] = (q.length > 1 ? q.shift() : q[0]) ?? [500, {}]+ return new Response(JSON.stringify(body), { status })+ }) as unknown as typeof fetch+ return { f, calls, count: (r: 'device' | 'join') => calls.filter((c) => c.route === r).length }+}+const DEVICE_OK = (t = 'DT'): [number, unknown] => [200, { deviceToken: t, hostId: 'H', exp: 1 }]+const JOIN_OK: [number, unknown] = [200, { pairingToken: 'PT', hostId: 'H', relayEndpoint: 'wss://relay.from-api', exp: 1 }]++/** A connect that records what it was given and hands back a session the test can inspect. */+function fakeConnect() {+ const opened: HostedConnectOptions[] = []+ const sessions: Array<RelayClientSession & { closed: boolean }> = []+ const connect = (o: HostedConnectOptions): RelayClientSession => {+ opened.push(o)+ const s = { closed: false, sas: () => '123 456', peerKeyB64: () => o.hostKeyB64, confirm: () => {}, send: () => true, isOpen: () => false, close() { this.closed = true } }+ sessions.push(s)+ return s+ }+ return { connect, opened, sessions, last: () => opened[opened.length - 1] }+}++function events() {+ const log: string[] = []+ const closed: Array<string | undefined> = []+ const ev: HostedJoinEvents = {+ onSas: (s) => log.push(`sas:${s}`),+ onApproved: () => log.push('approved'),+ onFrame: (j) => log.push(`frame:${j}`),+ onPtyData: (id, d) => log.push(`pty:${id}:${d}`),+ onClosed: (r) => closed.push(r)+ }+ return { ev, log, closed }+}++function setup(opts: { routes?: Parameters<typeof api>[0]; bookmarks?: RelayBookmark[]; loadKeys?: () => Promise<KeyPair> } = {}) {+ 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()+ 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')+ }+ return { store, api: a, c, deps, ourKeys }+}++const hostKeys = genKeyPair()+const code = codeFor(hostKeys)+const codeText = encodeJoinCode(code)+const bookmark = (over: Partial<RelayBookmark> = {}): RelayBookmark =>+ ({ hostId: code.hostId, code: codeText, label: 'box', deviceToken: 'OLD', approvedAt: null, source: 'code', ...over })++describe('joinHostedTeam', () => {+ it('refuses an invalid code before touching the network or the keys', async () => {+ 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.' })+ expect(s.api.calls).toEqual([])+ expect(loadKeys).not.toHaveBeenCalled()+ expect(s.c.opened).toEqual([])+ })++ it('first join: mints once with the free-tier body, connects with the host key pinned and NO pin store', async () => {+ const s = setup()+ 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' } },+ { route: 'join', body: { deviceToken: 'DT' } }+ ])+ const o = s.c.last()+ expect(o.url).toBe('wss://relay.from-api')+ expect(o.token).toBe('PT')+ expect(o.hostKeyB64).toBe(code.hostPublicKeyB64)+ expect(o.ourKeys).toBe(s.ourKeys)+ expect(o.autoApprove).toBe(false)+ // R33: a hosted host key never reaches the desktop's approved-devices store.+ expect('pins' in o).toBe(false)+ expect(session).toBe(s.c.sessions[0])+ // The bookmark keeps the token (so the next connect spends no mint) and is not yet approved.+ expect(await s.store.list()).toEqual([{ hostId: code.hostId, code: codeText, label: 'box', deviceToken: 'DT', approvedAt: null, source: 'code' }])+ })++ it('forwards the SAS, frames, pty data and a plain close (no reason)', async () => {+ const s = setup()+ const e = events()+ await joinHostedTeam(codeText, s.deps, e.ev)+ const o = s.c.last()+ o.onSas(s.c.sessions[0])+ o.onFrame('{"t":"ev"}')+ o.onPtyData('p1', 'hi')+ o.onClose()+ expect(e.log).toEqual(['sas:123 456', 'frame:{"t":"ev"}', 'pty:p1:hi'])+ expect(e.closed).toEqual([undefined])+ })++ it('records the approval as the joiner-side pin, once', async () => {+ const s = setup()+ const e = events()+ await joinHostedTeam(codeText, s.deps, e.ev)+ 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(e.log).toEqual(['approved'])+ })++ it('reuses a bookmarked device token: no device mint', async () => {+ const s = setup({ bookmarks: [bookmark()] })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.calls).toEqual([{ route: 'join', body: { deviceToken: 'OLD' } }])+ expect(s.c.last().autoApprove).toBe(false)+ })++ it('auto-confirms only when the bookmark is approved AND carries the same host key', async () => {+ const s = setup({ bookmarks: [bookmark({ approvedAt: '2026-09-01T00:00:00Z' })] })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.c.last().autoApprove).toBe(true)+ // The recorded approval is kept, not rewritten, on a pinned reconnect.+ s.c.last().onApproved(s.c.sessions[0])+ await new Promise((r) => setTimeout(r, 20))+ expect((await s.store.list())[0].approvedAt).toBe('2026-09-01T00:00:00Z')+ })++ it('a known hostId whose code now carries a different key string never auto-approves, and its token is not reused', async () => {+ // A non-canonical base64 spelling of the same 32 bytes: same hostId, different key string. The+ // rule compares the key the code carries with the key the bookmark was approved for, exactly.+ // 32 bytes encode as 43 characters + '=', and the last of those carries 2 unused low bits.+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'+ const k = code.hostPublicKeyB64+ const alt = k.slice(0, -2) + B64[B64.indexOf(k[k.length - 2]) ^ 1] + k.slice(-1)+ expect(hostIdFromPublicKeyB64(alt)).toBe(code.hostId)+ expect(alt).not.toBe(k)+ const s = setup({ bookmarks: [bookmark({ approvedAt: '2026-09-01T00:00:00Z' })] })+ await joinHostedTeam(encodeJoinCode({ ...code, hostPublicKeyB64: alt }), s.deps, events().ev)+ expect(s.c.last().autoApprove).toBe(false)+ expect(s.api.count('device')).toBe(1)+ expect((await s.store.list())[0]).toMatchObject({ deviceToken: 'DT', approvedAt: null })+ })++ it('a bookmark whose stored code no longer decodes is not trusted either', async () => {+ const s = setup({ bookmarks: [bookmark({ code: 'nodeterm://join?code=junk', approvedAt: '2026-09-01T00:00:00Z' })] })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.c.last().autoApprove).toBe(false)+ })++ it('bad-token on a bookmarked token: re-mints ONCE, persists it, and joins with it', async () => {+ const s = setup({ bookmarks: [bookmark()], routes: { device: [DEVICE_OK('NEW')], join: [[401, {}], JOIN_OK] } })+ await joinHostedTeam(codeText, s.deps, events().ev)+ expect(s.api.calls.map((c) => `${c.route}:${c.body.deviceToken ?? ''}`)).toEqual(['join:OLD', 'device:', 'join:NEW'])+ expect((await s.store.list())[0].deviceToken).toBe('NEW')+ })++ it('bad-token again after the re-mint: gives up with no second re-mint', async () => {+ const s = setup({ bookmarks: [bookmark()], routes: { device: [DEVICE_OK('NEW')], join: [[401, {}]] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'bad-token' })+ expect(s.api.count('device')).toBe(1)+ expect(s.api.count('join')).toBe(2)+ expect(s.c.opened).toEqual([])+ // The fresh token is kept: a later attempt starts from it rather than minting again first.+ expect((await s.store.list())[0].deviceToken).toBe('NEW')+ })++ it('bad-token on a token minted in THIS attempt: no re-mint at all (at most one mint per attempt)', async () => {+ const s = setup({ routes: { device: [DEVICE_OK()], join: [[401, {}]] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'bad-token' })+ expect(s.api.count('device')).toBe(1)+ expect(s.api.count('join')).toBe(1)+ })++ 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." })+ expect(s.api.count('device')).toBe(0)+ })++ it('device mint failures each say what happened and connect nothing', async () => {+ for (const [status, kind] of [[429, 'rate-limited'], [403, 'refused'], [502, 'network']] as const) {+ const s = setup({ routes: { device: [[status, {}]] } })+ const err = await joinHostedTeam(codeText, s.deps, events().ev).catch((e: unknown) => e)+ expect(err).toBeInstanceOf(HostedJoinError)+ expect(err).toMatchObject({ kind })+ expect(s.api.count('join')).toBe(0)+ expect(s.c.opened).toEqual([])+ expect(await s.store.list()).toEqual([])+ }+ })++ it('a join that fails after a fresh mint keeps the minted token, so the retry spends no second mint', async () => {+ const s = setup({ routes: { device: [DEVICE_OK()], join: [[503, {}]] } })+ await expect(joinHostedTeam(codeText, s.deps, events().ev)).rejects.toMatchObject({ kind: 'network' })+ expect((await s.store.list())[0].deviceToken).toBe('DT')+ const retry = setup({ bookmarks: await s.store.list() })+ await joinHostedTeam(codeText, retry.deps, events().ev)+ expect(retry.api.count('device')).toBe(0)+ })++ 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')+ expect(s.api.calls).toEqual([])+ })++ 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' })] })+ const e = events()+ await joinHostedTeam(codeText, s.deps, e.ev)+ const o = s.c.last()+ o.onDenied?.(reason)+ o.onClose()+ expect(e.closed).toEqual([reason])+ await vi.waitFor(async () => expect((await s.store.list())[0].approvedAt).toBeNull())+ // The device token survives: a denial is about this approval, not the relay credential.+ expect((await s.store.list())[0].deviceToken).toBe('OLD')+ }+ })++ it('an approval or denial never brings back a bookmark the user removed meanwhile', async () => {+ const s = setup()+ await joinHostedTeam(codeText, s.deps, events().ev)+ await s.store.remove(code.hostId)+ s.c.last().onApproved(s.c.sessions[0])+ s.c.last().onDenied?.('removed')+ await new Promise((r) => setTimeout(r, 20))+ expect(await s.store.list()).toEqual([])+ })+})++describe('connectHostedTeam (the relay:client:connect leg for a join code)', () => {+ function io() {+ const sent: Array<[string, ...unknown[]]> = []+ const sessions = new Map<string, RelayClientSession>()+ return { sent, sessions, io: { newId: () => 'c1', send: (ch: string, ...args: unknown[]) => { sent.push([ch, ...args]) }, sessions } }+ }++ it('routes every event to the connection\'s channels and registers the session', async () => {+ const s = setup()+ const x = io()+ expect(await connectHostedTeam(codeText, s.deps, x.io)).toBe('c1')+ expect(x.sessions.get('c1')).toBe(s.c.sessions[0])+ const o = s.c.last()+ o.onSas(s.c.sessions[0])+ o.onApproved(s.c.sessions[0])+ o.onFrame('{"t":"res"}')+ o.onPtyData('p1', 'out')+ expect(x.sent).toEqual([+ [IPC.relayClientSas('c1'), '123 456'],+ [IPC.relayClientApproved('c1')],+ [IPC.relayClientFrame('c1'), '{"t":"res"}'],+ [IPC.ptyData('p1'), 'out']+ ])+ })++ it('a close carries the host\'s refusal reason and unregisters the session', async () => {+ const s = setup()+ const x = io()+ await connectHostedTeam(codeText, s.deps, x.io)+ s.c.last().onDenied?.('expired')+ s.c.last().onClose()+ expect(x.sent).toEqual([[IPC.relayClientClosed('c1'), 'expired']])+ expect(x.sessions.has('c1')).toBe(false)+ })++ it('a plain close sends no reason', async () => {+ const s = setup()+ const x = io()+ await connectHostedTeam(codeText, s.deps, x.io)+ s.c.last().onClose()+ expect(x.sent).toEqual([[IPC.relayClientClosed('c1'), undefined]])+ })++ it('a session that closed before the join returned is never registered', async () => {+ const s = setup()+ const x = io()+ const connect = (o: HostedConnectOptions): RelayClientSession => {+ const session = s.c.connect(o)+ o.onClose()+ return session+ }+ await connectHostedTeam(codeText, { ...s.deps, connect }, x.io)+ expect(x.sessions.size).toBe(0)+ expect(x.sent).toEqual([[IPC.relayClientClosed('c1'), undefined]])+ })++ 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.')+ expect(x.sessions.size).toBe(0)+ expect(x.sent).toEqual([])+ })+})++// ── End to end: the real core relay client against the real hosted service. ──────────────────────++const live: Array<{ svc: HostedService; dir: string }> = []+afterEach(() => {+ for (const w of live.splice(0)) {+ w.svc.stop()+ fs.rmSync(w.dir, { recursive: true, force: true })+ }+})++function hostedWorld() {+ const dir = tmpDir()+ const peersT: RelayTransport[] = []+ let next = 1+ const attach: PeerAttach = {+ attach: () => next++,+ detach: () => {},+ dispatch: async (_id, req) => ({ t: 'res', id: req.id, ok: true, result: null }),+ cast: () => {}+ }+ const svc = createHostedService({+ dataDir: dir, apiBase: 'https://api', relayUrl: 'ws://127.0.0.1/r', deviceId: 'host-dev', hostLabel: 'box',+ attach, projectOfNode: () => 'P', projectCwd: () => '/srv/app',+ fetch: (async () => new Response(JSON.stringify({ pairingToken: 'T', hostId: 'H', exp: 0 }), { status: 200 })) as typeof fetch,+ transport: () => { const { hostT, peerT } = transportPair(); peersT.push(peerT); return hostT }+ })+ live.push({ svc, dir })+ // The real core client, over the next listener's in-process transport.+ const connect = (o: HostedConnectOptions) => connectRelayClient({ ...o, transport: peersT.shift()! })+ return { svc, dir, connect }+}++describe('joinHostedTeam against the hosted service', () => {+ it('first join asks both humans; the reconnect confirms itself; a removal reaches onClosed and drops the pin', async () => {+ const w = hostedWorld()+ const ownerKeys = genKeyPair()+ await w.svc.init()+ await w.svc.addOwner(pub(ownerKeys), 'Enes')+ await w.svc.share('P', true)+ expect(await w.svc.start()).toBe('started')+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))++ const ownerFrames: string[] = []+ let ownerOpen = false+ const owner = w.connect({+ url: 'ws://127.0.0.1/r', token: 'T', hostKeyB64: w.svc.info()!.hostPublicKeyB64, ourKeys: ownerKeys, autoApprove: true,+ onSas: () => {}, onApproved: () => { ownerOpen = true }, onFrame: (j) => ownerFrames.push(j), onPtyData: () => {}, onClose: () => {}+ })+ await vi.waitFor(() => expect(ownerOpen).toBe(true))++ const joinerKeys = genKeyPair()+ const store = new BookmarkStore(path.join(w.dir, 'relay-bookmarks.json'))+ const a = api({ device: [DEVICE_OK()], join: [[200, { pairingToken: 'T', hostId: 'H', relayEndpoint: 'ws://127.0.0.1/r', exp: 1 }]] })+ const deps: HostedJoinDeps = { apiBase: 'https://api', deviceId: () => 'joiner-dev', label: 'laptop', bookmarks: store, loadKeys: async () => joinerKeys, connect: w.connect, fetch: a.f }+ const joinCode = w.svc.joinCode()!++ // 1. First join: the SAS is shown, the human confirms, an owner approves.+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))+ const e1 = events()+ const s1 = await joinHostedTeam(joinCode, deps, e1.ev)+ expect(e1.log.some((l) => l.startsWith('sas:'))).toBe(true)+ s1.confirm()+ await vi.waitFor(() => expect(w.svc.status().pending.some((p) => p.peerKeyB64 === pub(joinerKeys))).toBe(true))+ const pendingId = w.svc.status().pending.find((p) => p.peerKeyB64 === pub(joinerKeys))!.pendingId+ owner.send(JSON.stringify({ t: 'req', id: 1, method: IPC.relayHostedApprove, args: [pendingId, 'viewer'] }))+ await vi.waitFor(() => expect(e1.log).toContain('approved'))+ await vi.waitFor(async () => expect((await store.list())[0]?.approvedAt).not.toBeNull())+ s1.close()++ // 2. Reconnect: no SAS for this human, no device mint, and it opens on the host's pin alone.+ await vi.waitFor(() => expect(w.svc.status().scheduler?.idle).toBe(1))+ const e2 = events()+ await joinHostedTeam(joinCode, deps, e2.ev)+ await vi.waitFor(() => expect(e2.log).toContain('approved'))+ expect(e2.log.some((l) => l.startsWith('sas:'))).toBe(false)+ expect(a.count('device')).toBe(1)++ // 3. An owner removes this device: the reason reaches onClosed, and the pin is withdrawn.+ expect(await w.svc.remove(pub(joinerKeys), false)).toBe('removed')+ await vi.waitFor(() => expect(e2.closed).toEqual(['removed']))+ await vi.waitFor(async () => expect((await store.list())[0].approvedAt).toBeNull())+ })+})diff --git a/src/main/remote/hosted-join.ts b/src/main/remote/hosted-join.tsnew file mode 100644index 000000000..120ee4d7f--- /dev/null+++ b/src/main/remote/hosted-join.ts@@ -0,0 +1,190 @@+// Joining a hosted team (a Server Edition hosting over the E2EE relay) from the desktop, as one pure+// sequence the `relay:client:connect` handler calls for a `nodeterm://join?code=…` code:+// 1. decode the code (public: the relay, the host key, the host's device id);+// 2. a device token for this device and that host — the bookmarked one, else ONE fresh mint;+// 3. trade it for a short-lived client token (`/v1/relay/join`);+// 4. connect with the host key from the code pinned.+//+// Rules this file exists to keep:+// - The CORE relay client, with NO pin store. The desktop wrapper pins every mutual approval into+// approved-devices, which the desktop counts as paired phones; a hosted host key has no business+// there. The joiner-side pin is the bookmark's `approvedAt` instead.+// - Auto-confirm only when the bookmark was approved AND was approved for exactly the key this code+// carries. Anything else shows this human the SAS again. A host that refuses us (denied, removed,+// expired) withdraws the pin, so the next attempt asks again rather than confirming blind.+// - Free-tier device mints are damped server-side, so at most ONE device mint per attempt: a fresh+// 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'+import { mintDeviceToken, mintJoinToken, type DeviceMintResult, type JoinMintResult } from '../../core/relay/join-token'+import {+ connectRelayClient,+ type ConnectRelayClientOptions,+ type RelayClientSession+} from '../../core/relay/relay-client'+import type { TrustDeniedReason } from '../../core/relay/relay-trust'+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'++/** 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'++const MESSAGES: Record<HostedJoinFailure, string> = {+ 'invalid-code': 'That team code is invalid.',+ 'rate-limited': 'Too many join attempts for this team today. Try again tomorrow.',+ 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."+}++/** A join that did not reach the relay. `kind` says why; the message is for the human. */+export class HostedJoinError extends Error {+ constructor(readonly kind: HostedJoinFailure) {+ super(MESSAGES[kind])+ this.name = 'HostedJoinError'+ }+}++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'>+ /** 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): RelayClientSession+ fetch?: typeof fetch+ now?(): number+}++export interface HostedJoinEvents {+ /** The SAS this human compares (a first join, or one whose pin was withdrawn). */+ onSas(sas: string | null): void+ onApproved(): void+ onFrame(json: string): void+ onPtyData(sessionId: string, data: string): void+ /** The connection ended; `reason` is set only when the host refused us over the tunnel. Typed with+ * the renderer's union, so a denial reason the core gains without it fails to compile here. */+ onClosed(reason?: RelayClosedReason): void+}++/** The host key a bookmark was recorded for, read back out of its own code. */+function bookmarkedKey(b: RelayBookmark): string | null {+ return decodeJoinCode(b.code)?.hostPublicKeyB64 ?? 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()+ 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++ let deviceToken = existing?.deviceToken ?? null+ let approvedAt = existing?.approvedAt ?? null+ const record = (): RelayBookmark => ({+ hostId: code.hostId,+ code: encodeJoinCode(code),+ label: code.label,+ deviceToken,+ approvedAt,+ 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(() => {})+ const mintDevice = async (): Promise<string> => {+ const d: DeviceMintResult = await mintDeviceToken({ apiBase: deps.apiBase, deviceId: deps.deviceId(), code, label: deps.label, fetch: deps.fetch })+ if (!d.ok) throw new HostedJoinError(d.kind)+ deviceToken = d.deviceToken+ await persist()+ return d.deviceToken+ }++ let mintedNow = false+ if (!deviceToken) {+ await mintDevice()+ mintedNow = true+ }+ let j: JoinMintResult = await mintJoinToken({ apiBase: deps.apiBase, deviceToken: deviceToken!, fetch: deps.fetch })+ 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 })+ }+ if (!j.ok) throw new HostedJoinError(j.kind)+ if (JSON.stringify(record()) !== JSON.stringify(found ?? null)) await persist()++ let deniedReason: TrustDeniedReason | undefined+ const connect = deps.connect ?? connectRelayClient+ const 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)+ })+}++/** How `connectHostedTeam` reaches the renderer and the handler's connection registry. */+export interface HostedConnectIo {+ newId(): string+ /** Send to the renderer (the main window). */+ send(channel: string, ...args: unknown[]): void+ /** The handler's live relay client sessions, by connection id. */+ sessions: Map<string, RelayClientSession>+}++/**+ * 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.+ */+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)+ }+ })+ // A socket that already closed must not leave a dead session behind in the registry.+ if (!ended) io.sessions.set(connectionId, session)+ return connectionId+}diff --git a/src/main/remote/relay-bookmarks.test.ts b/src/main/remote/relay-bookmarks.test.tsnew file mode 100644index 000000000..8f3be9559--- /dev/null+++ b/src/main/remote/relay-bookmarks.test.ts@@ -0,0 +1,66 @@+// src/main/remote/relay-bookmarks.test.ts+import { describe, it, expect } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { BookmarkStore, publicBookmark, type RelayBookmark } from './relay-bookmarks'++const tmpFile = () => path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'bm-')), 'relay-bookmarks.json')+const b: RelayBookmark = { hostId: 'H', code: 'nodeterm://join?code=x', label: 'box', deviceToken: null, approvedAt: null, source: 'code' }++describe('relay bookmarks', () => {+ it('upserts by hostId and removes', async () => {+ const s = new BookmarkStore(tmpFile())+ await s.upsert(b)+ await s.upsert({ ...b, approvedAt: '2026-09-28T00:00:00Z' })+ expect(await s.list()).toEqual([{ ...b, approvedAt: '2026-09-28T00:00:00Z' }])+ await s.remove('H')+ expect(await s.list()).toEqual([])+ })++ // POSIX permission bits: Windows has no 0600 (ACLs decide there), so the mode is not observable.+ it.skipIf(process.platform === 'win32')('persists 0600, because a bookmark holds a device token', async () => {+ const file = tmpFile()+ const s = new BookmarkStore(file)+ await s.upsert({ ...b, deviceToken: 'DT' })+ expect((fs.statSync(file).mode & 0o777).toString(8)).toBe('600')+ // Rewrites keep it (each write is a fresh temp file renamed over the old one).+ await s.upsert({ ...b, hostId: 'H2' })+ 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 () => {+ const file = tmpFile()+ fs.writeFileSync(file, 'nope')+ expect(await new BookmarkStore(file).list()).toEqual([])+ expect(fs.readFileSync(file, 'utf8')).toBe('nope')+ })++ 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 }]))+ expect(await new BookmarkStore(file).list()).toEqual([b])+ })++ it('concurrent writes are serialized, none is lost', async () => {+ const s = new BookmarkStore(tmpFile())+ await Promise.all(['A', 'B', 'C', 'D'].map((hostId) => s.upsert({ ...b, hostId })))+ expect((await s.list()).map((x) => x.hostId).sort()).toEqual(['A', 'B', 'C', 'D'])+ })++ it('update patches an existing bookmark and never creates one', async () => {+ const s = new BookmarkStore(tmpFile())+ await s.update('H', { approvedAt: 'now' })+ expect(await s.list()).toEqual([])+ await s.upsert(b)+ await s.update('H', { approvedAt: 'now', deviceToken: 'DT' })+ expect(await s.list()).toEqual([{ ...b, approvedAt: 'now', deviceToken: 'DT' }])+ })++ it('the renderer\'s view of a bookmark never carries its device token', () => {+ const shown = publicBookmark({ ...b, deviceToken: 'SECRET', approvedAt: '2026-09-28T00:00:00Z' })+ expect(shown).toEqual({ hostId: 'H', label: 'box', approved: true, code: 'nodeterm://join?code=x' })+ expect(JSON.stringify(shown)).not.toContain('SECRET')+ expect(publicBookmark(b).approved).toBe(false)+ })+})diff --git a/src/main/remote/relay-bookmarks.ts b/src/main/remote/relay-bookmarks.tsnew file mode 100644index 000000000..9bdf01127--- /dev/null+++ b/src/main/remote/relay-bookmarks.ts@@ -0,0 +1,87 @@+// Hosted teams this desktop has joined, one bookmark per host (keyed by hostId).+//+// The join code is PUBLIC material. The device token is a relay credential scoped to this device+// and that host: it lets us ASK to join (the host still decides who gets in), and minting a new one+// spends a damped free-tier mint, so it is kept rather than re-minted. It is a credential all the+// same, so the file is written 0600.+//+// `approvedAt` is the JOINER-SIDE pin: set once both humans approved this device on that host, it is+// what lets a reconnect confirm our half without a SAS dialog — but only for the exact host key it+// was recorded against (see hosted-join.ts). It deliberately does NOT live in the desktop's+// approved-devices store, which counts paired phones.+import { promises as fs } from 'node:fs'+import { writeFileAtomic } from '../../core/fs-atomic'++export interface RelayBookmark {+ hostId: string+ /** The team's `nodeterm://join?code=…` string (public). */+ code: string+ /** The host's own label, from the code. */+ label: string+ /** This device's relay device token for that host, or null before the first mint. */+ deviceToken: string | null+ /** ISO time both humans first approved this device on that host, or null. */+ approvedAt: string | null+ source: 'code' | 'ssh'+}++/** What the renderer is shown of a bookmark: never its device token. */+export function publicBookmark(b: RelayBookmark): { hostId: string; label: string; approved: boolean; code: string } {+ return { hostId: b.hostId, label: b.label, approved: b.approvedAt !== null, code: b.code }+}++function valid(b: unknown): b is RelayBookmark {+ if (!b || typeof b !== 'object') return false+ const o = b as Record<string, unknown>+ return (+ typeof o.hostId === 'string' &&+ typeof o.code === 'string' &&+ typeof o.label === 'string' &&+ (o.deviceToken === null || typeof o.deviceToken === 'string') &&+ (o.approvedAt === null || typeof o.approvedAt === 'string') &&+ (o.source === 'code' || o.source === 'ssh')+ )+}++export class BookmarkStore {+ // Every write re-reads the file and is queued behind the previous one, so two concurrent writes+ // (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) {}++ /** 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. */+ async list(): Promise<RelayBookmark[]> {+ try {+ const j = JSON.parse(await fs.readFile(this.file, 'utf-8')) as unknown+ return Array.isArray(j) ? j.filter(valid) : []+ } catch {+ return []+ }+ }++ private write(fn: (l: RelayBookmark[]) => RelayBookmark[] | null): Promise<void> {+ const run = this.tail.then(async () => {+ const next = fn(await this.list())+ if (next) await writeFileAtomic(this.file, JSON.stringify(next, null, 2), { mode: 0o600 })+ })+ this.tail = run.catch(() => {})+ return run+ }++ /** Insert or replace the bookmark for `b.hostId`. */+ upsert(b: RelayBookmark): Promise<void> {+ 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))+ }++ remove(hostId: string): Promise<void> {+ return this.write((l) => l.filter((x) => x.hostId !== hostId))+ }+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 403b3345b..037e20755 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -11,6 +11,7 @@ import type {PtyPressure,LogRecord,RecycledInfo,+ RelayClosedReason,RelayPeerPending,RemoteUsageQuery,SessionMemoryQuery,@@ -651,12 +652,17 @@ const api: NodeTerminalApi = {},onClosed: (connectionId, listener) => {const channel = IPC.relayClientClosed(connectionId)- const handler = () => listener()+ // A hosted host's refusal reason rides the close; a legacy pairing offer sends none.+ const handler = (_e: unknown, reason?: RelayClosedReason) => listener(reason)ipcRenderer.on(channel, handler)return () => ipcRenderer.removeListener(channel, handler)},disconnect: (connectionId) => ipcRenderer.send(IPC.relayClientDisconnect, connectionId)},+ relayHosted: {+ bookmarks: () => ipcRenderer.invoke(IPC.relayHostedBookmarks),+ removeBookmark: (hostId) => ipcRenderer.invoke(IPC.relayHostedBookmarkRemove, hostId)+ },handoff: {build: (sessionId, agentId, sourceNodeId, cwd, accountId) =>ipcRenderer.invoke(IPC.handoffBuild, sessionId, agentId, sourceNodeId, cwd, accountId)diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.tsindex 8087cabdd..b8451dec4 100644--- a/src/renderer/bridge/stubs.test.ts+++ b/src/renderer/bridge/stubs.test.ts@@ -59,6 +59,12 @@ describe('bridge stubs', () => {}).not.toThrow()})+ it('hosted-team bookmarks answer an empty list: a browser cannot join a relay host', async () => {+ const s = buildStubApi()+ await expect(s.relayHosted.bookmarks()).resolves.toEqual([])+ await expect(s.relayHosted.removeBookmark('H')).resolves.toBeUndefined()+ })+it('boot-path promise members resolve benignly', async () => {const s = buildStubApi()await expect(s.announcements.fetch()).resolves.toEqual([])diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex ea8f065c7..dad1e8b02 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -450,6 +450,12 @@ export function buildStubApi(): Omit<onClosed: noopUnsub,disconnect: noop},+ // A browser cannot join a relay host (only the desktop's main process holds a relay client),+ // so it has joined no hosted team: an empty list is the true answer, not a degrade.+ relayHosted: {+ bookmarks: async () => [],+ removeBookmark: async () => {}+ },handoff: {build: U('handoff.build')},diff --git a/src/shared/ipc.test.ts b/src/shared/ipc.test.tsindex d613ca6fd..636d7c88a 100644--- a/src/shared/ipc.test.ts+++ b/src/shared/ipc.test.ts@@ -48,4 +48,9 @@ describe('IPC channels', () => {expect(IPC.relayClientFrame('abc')).toBe('relay:client:frame:abc')expect(IPC.relayClientClosed('abc')).toBe('relay:client:closed:abc')})++ it('exposes the desktop-local hosted-team bookmark channels', () => {+ expect(IPC.relayHostedBookmarks).toBe('relay:hosted:bookmarks')+ expect(IPC.relayHostedBookmarkRemove).toBe('relay:hosted:bookmark-remove')+ })})diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex e7d57e22a..6c17addd0 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -608,6 +608,12 @@ export const IPC = {relayHostedDeny: 'relay:hosted:deny',relayHostedInviteCode: 'relay:hosted:invite-code',relayHostedSelf: 'relay:hosted:self',+ // The hosted teams THIS desktop has joined (src/main/remote/relay-bookmarks.ts). Unlike the+ // hosted verbs above, these two never ride the relay: they are raw `ipcMain` handlers in the+ // desktop main process, invisible to any relay peer. `relayHostedBookmarks` () lists them without+ // their device tokens; `relayHostedBookmarkRemove` (hostId) forgets one.+ relayHostedBookmarks: 'relay:hosted:bookmarks',+ relayHostedBookmarkRemove: 'relay:hosted:bookmark-remove',handoffBuild: 'handoff:build',// Phone pairing (nodeterm iOS "scan a QR" flow): renderer starts/stops the one-shot LAN// listener; main pushes the completion result back over `pairing:done`. The per-devicediff --git a/src/shared/types.ts b/src/shared/types.tsindex a5deef469..2edeaebf6 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3515,12 +3515,30 @@ export interface RelayClientApi {send(connectionId: string, frame: string): void/** Listen for an inbound rpc frame (a JSON string) from the host. Returns an unsubscribe. */onFrame(connectionId: string, listener: (frame: string) => void): () => void- /** Fires when the connection's relay socket drops (host/relay gone). Returns unsubscribe. */- onClosed(connectionId: string, listener: () => void): () => void+ /** Fires when the connection's relay socket drops (host/relay gone). `reason` is set only when+ * the host refused this device over the tunnel first (a hosted team: an owner declined, removed+ * it, or nobody answered in time). Returns unsubscribe. */+ onClosed(connectionId: string, listener: (reason?: RelayClosedReason) => void): () => void/** Close a connection: end the relay socket and drop access to the host. */disconnect(connectionId: string): void}+/** Why a host refused a relay client before closing it (the core relay's `TrustDeniedReason`). */+export type RelayClosedReason = 'denied' | 'removed' | 'expired'++/**+ * The hosted teams this desktop has joined by `nodeterm://join` code. A join code is passed to+ * `relayClient.connect` like a pairing offer; these are the bookmarks that connect leaves behind.+ * Desktop-only: a browser cannot join a relay host, so the Server Edition answers an empty list.+ */+export interface RelayHostedApi {+ /** The bookmarks, never their device tokens. `approved` = both humans approved this device on+ * that host, so a reconnect needs no SAS comparison on this side. */+ bookmarks(): Promise<Array<{ hostId: string; label: string; approved: boolean; code: string }>>+ /** Forget a bookmark (its device token and its approval). */+ removeBookmark(hostId: string): Promise<void>+}+/** A paired device as exposed to the renderer — the bearer token is never included. */export interface PairedDevice {id: string@@ -3717,6 +3735,7 @@ export interface NodeTerminalApi {remoteHost: RemoteHostApirelayHost: RelayHostApirelayClient: RelayClientApi+ relayHosted: RelayHostedApihandoff: HandoffApipairing: PairingApipresence: PresenceApi