Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(pairing): removing a device now revokes its Pro, and admits when it cannot

enesf51ee545a3a2
diff --git a/src/main/pairing-revoke.test.ts b/src/main/pairing-revoke.test.ts
new file mode 100644
index 000000000..3c3133302
--- /dev/null
+++ b/src/main/pairing-revoke.test.ts
@@ -0,0 +1,260 @@
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest'
+import { promises as fs, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import path from 'path'
+
+const TEMP_HOME_MARKER = 'nt-revoke-'
+
+// Same hoisted redirect as pairing-service.test.ts: the service resolves AGENT_JSON_PATH /
+// AUTH_KEYS_PATH from `os.homedir()` at MODULE LOAD, so the temp home has to exist before the
+// import. Everything else about `os` stays real.
+vi.mock('os', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('os')>()
+ const { mkdtempSync } = await import('node:fs')
+ const { join } = await import('node:path')
+ // Literal, not TEMP_HOME_MARKER: this factory is hoisted above every module-level binding.
+ const home = mkdtempSync(join(actual.tmpdir(), 'nt-revoke-'))
+ const homedir = (): string => home
+ const base = (actual as unknown as { default?: typeof actual }).default ?? actual
+ return { ...actual, homedir, default: { ...base, homedir } }
+})
+
+vi.mock('../core/device-id', () => ({ getDeviceId: () => 'test-host-device-id' }))
+
+import os from 'os'
+import {
+ createPairingService,
+ revokeRelayDevice,
+ type PairingRelayDeps
+} from './pairing-service'
+import { rewriteKeyComment, type DeviceEntry } from './pairing-core'
+import type { Settings } from '../shared/types'
+
+const HOME = os.homedir()
+const AGENT_JSON = path.join(HOME, '.nodeterm', 'agent.json')
+const AUTH_KEYS = path.join(HOME, '.ssh', 'authorized_keys')
+
+/** Refuse to run (and to delete anything) unless HOME is demonstrably our mkdtemp dir. */
+function assertTempHome(): void {
+ if (!path.basename(HOME).startsWith(TEMP_HOME_MARKER)) {
+ throw new Error(
+ `pairing-revoke.test refuses to run: homedir() is "${HOME}", not a ${TEMP_HOME_MARKER}* ` +
+ 'temp dir. The os mock is not in effect and this file would delete the real ~/.ssh.'
+ )
+ }
+}
+assertTempHome()
+
+const KEY_A = rewriteKeyComment('ssh-ed25519 AAAAblobAAAA phone-a@ios', 'dev-a')
+const KEY_OTHER = 'ssh-rsa AAAAlaptopblob jdub@laptop'
+
+const device = (id: string, relayDeviceId?: string): DeviceEntry => ({
+ id,
+ name: `Phone ${id}`,
+ token: `agent-token-${id}`,
+ pairedAt: 1_700_000_000_000,
+ lastSeenAt: 0,
+ relayDeviceId
+})
+
+/** Seed a registry holding ONE device; `relayDeviceId` is what the phone called itself. */
+const seed = (relayDeviceId?: string): void => {
+ rmSync(path.join(HOME, '.nodeterm'), { recursive: true, force: true })
+ rmSync(path.join(HOME, '.ssh'), { recursive: true, force: true })
+ mkdirSync(path.join(HOME, '.nodeterm'), { recursive: true, mode: 0o700 })
+ mkdirSync(path.join(HOME, '.ssh'), { recursive: true, mode: 0o700 })
+ writeFileSync(
+ AGENT_JSON,
+ JSON.stringify({ hostId: 'host-keep-me', devices: [device('dev-a', relayDeviceId)] }, null, 2) +
+ '\n',
+ { mode: 0o600 }
+ )
+ writeFileSync(AUTH_KEYS, `${KEY_OTHER}\n${KEY_A}\n`, { mode: 0o600 })
+}
+
+const agentJson = (): { devices?: DeviceEntry[] } => JSON.parse(readFileSync(AGENT_JSON, 'utf8'))
+const deviceIds = (): string[] => (agentJson().devices ?? []).map((d) => d.id)
+const authKeys = (): string => readFileSync(AUTH_KEYS, 'utf8')
+
+/** Relay deps carrying an entitlement, i.e. a Pro desktop that CAN authorize a revoke. */
+const relayDeps = (entitlement: string | null): PairingRelayDeps => ({
+ getSettings: () => ({ phoneAccessEnabled: true }) as unknown as Settings,
+ getEntitlement: () => entitlement,
+ loadHostKeyPair: async () => {
+ throw new Error('not used by revoke')
+ },
+ relayEndpoint: 'wss://relay.example',
+ apiBase: 'https://api.x',
+ relayAllowed: () => true
+})
+
+const fetchBody = (mock: ReturnType<typeof vi.fn>): unknown =>
+ JSON.parse((mock.mock.calls[0][1] as { body: string }).body)
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+})
+
+afterAll(() => {
+ assertTempHome()
+ rmSync(HOME, { recursive: true, force: true })
+})
+
+describe('revokeRelayDevice', () => {
+ it('posts the phone id with the host entitlement and reports ok on 204', async () => {
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 204 }))
+ vi.stubGlobal('fetch', fetchMock)
+
+ expect(await revokeRelayDevice('https://api.x', 'phone-1', 'TOKEN')).toBe('ok')
+
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [
+ string,
+ { method: string; body: string }
+ ]
+ // The deviceId is phone-supplied, unvalidated text: it rides the JSON BODY, never a URL.
+ expect(String(url)).toBe('https://api.x/v1/relay/device/revoke')
+ expect(init.method).toBe('POST')
+ expect(JSON.parse(init.body)).toEqual({ deviceId: 'phone-1', entitlement: 'TOKEN' })
+ })
+
+ // 403 is the route's only real refusal ("that row is someone else's"), 401 a token that did not
+ // verify. Both are things we TRIED and were told no — never 'skipped', which claims we didn't ask.
+ it.each([403, 401, 500])('reports failed — never a silent success — on %i', async (status) => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status })))
+ expect(await revokeRelayDevice('https://api.x', 'phone-1', 'TOKEN')).toBe('failed')
+ })
+
+ it('reports failed when the request throws (offline)', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new Error('down')
+ })
+ )
+ expect(await revokeRelayDevice('https://api.x', 'phone-1', 'TOKEN')).toBe('failed')
+ })
+
+ it('gives up on a hung server rather than hanging the revoke forever', async () => {
+ vi.useFakeTimers()
+ const fetchMock = vi.fn(
+ (_url: string, init: { signal: AbortSignal }) =>
+ new Promise((_resolve, reject) => {
+ init.signal.addEventListener('abort', () => reject(new Error('aborted')))
+ })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ const pending = revokeRelayDevice('https://api.x', 'phone-1', 'TOKEN')
+ await vi.advanceTimersByTimeAsync(9000)
+ expect(await pending).toBe('failed')
+ })
+
+ // 'skipped' means "we did not ask, and that is fine" — a free-tier desktop holds no entitlement
+ // to sign the request with, and has no Pro of ours on that phone to reclaim.
+ it('skips — without calling the server — when there is no entitlement to sign with', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ expect(await revokeRelayDevice('https://api.x', 'phone-1', null)).toBe('skipped')
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('skips when there is no relay device id to name', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ expect(await revokeRelayDevice('https://api.x', '', 'TOKEN')).toBe('skipped')
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('skips when there is no API base, instead of fetching a relative URL', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ expect(await revokeRelayDevice('', 'phone-1', 'TOKEN')).toBe('skipped')
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
+
+describe('createPairingService().revokeDevice', () => {
+ beforeEach(() => {
+ seed('phone-relay-1')
+ })
+
+ it('names the PHONE’s relay device id, not our local one, and reports both legs', async () => {
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 204 }))
+ vi.stubGlobal('fetch', fetchMock)
+ const service = createPairingService(relayDeps('TOKEN'))
+
+ expect(await service.revokeDevice('dev-a')).toEqual({ local: true, server: 'ok' })
+
+ // 'dev-a' is OUR id; the backend keys its row on the id the phone sent.
+ expect(fetchBody(fetchMock)).toEqual({ deviceId: 'phone-relay-1', entitlement: 'TOKEN' })
+ expect(deviceIds()).toEqual([])
+ expect(authKeys()).toBe(`${KEY_OTHER}\n`)
+ })
+
+ it('skips the server when the device predates relayDeviceId (nothing we can name)', async () => {
+ seed(undefined)
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 204 }))
+ vi.stubGlobal('fetch', fetchMock)
+ const service = createPairingService(relayDeps('TOKEN'))
+
+ expect(await service.revokeDevice('dev-a')).toEqual({ local: true, server: 'skipped' })
+ // Falling back to our own id would ask the backend about a row that cannot exist.
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(deviceIds()).toEqual([])
+ })
+
+ it('skips the server on a free-tier desktop, and still removes the device locally', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const service = createPairingService(relayDeps(null))
+
+ expect(await service.revokeDevice('dev-a')).toEqual({ local: true, server: 'skipped' })
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(deviceIds()).toEqual([])
+ })
+
+ it('skips the server when the service has no relay deps at all', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const service = createPairingService()
+
+ expect(await service.revokeDevice('dev-a')).toEqual({ local: true, server: 'skipped' })
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('reports the server leg as failed while the local removal still stuck', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 403 })))
+ const service = createPairingService(relayDeps('TOKEN'))
+
+ expect(await service.revokeDevice('dev-a')).toEqual({ local: true, server: 'failed' })
+ expect(deviceIds()).toEqual([])
+ expect(authKeys()).toBe(`${KEY_OTHER}\n`)
+ })
+
+ // A half-finished revoke must never render as a clean one (the discipline remote/revocation.ts
+ // states in its header), and the Pro is still worth reclaiming when the local files would not
+ // budge — the entitlement is what authorizes the server leg, not the local write's success.
+ it('reports local:false when the registry write fails, and still reclaims the Pro', async () => {
+ const fetchMock = vi.fn(async () => ({ ok: true, status: 204 }))
+ vi.stubGlobal('fetch', fetchMock)
+ const service = createPairingService(relayDeps('TOKEN'))
+ vi.spyOn(fs, 'rename').mockImplementation(async (_from, to) => {
+ if (String(to).includes('agent.json')) {
+ throw Object.assign(new Error('EXDEV: cross-device link'), { code: 'EXDEV' })
+ }
+ })
+
+ expect(await service.revokeDevice('dev-a')).toEqual({ local: false, server: 'ok' })
+ expect(fetchBody(fetchMock)).toEqual({ deviceId: 'phone-relay-1', entitlement: 'TOKEN' })
+ })
+
+ it('skips the server for an id that is not in the registry', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ const service = createPairingService(relayDeps('TOKEN'))
+
+ expect(await service.revokeDevice('never-paired')).toEqual({ local: true, server: 'skipped' })
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/pairing-service.atomic-write.test.ts b/src/main/pairing-service.atomic-write.test.ts
index 98dae87eb..ff9f6d449 100644
--- a/src/main/pairing-service.atomic-write.test.ts
+++ b/src/main/pairing-service.atomic-write.test.ts
@@ -122,7 +122,7 @@ describe('pairing-service revoke: atomic writes', () => {
expect(await tmpsIn(sshDir())).toEqual([])
})
- it('a failed agent.json rename removes its own temp, rejects, and leaves the old device list intact', async () => {
+ it('a failed agent.json rename removes its own temp, reports local:false, and leaves the old device list intact', async () => {
const svc = await service()
const before = await fs.readFile(agentJson(), 'utf-8')
// EXDEV is the realistic one: ~/.nodeterm on another filesystem than the temp.
@@ -130,7 +130,9 @@ describe('pairing-service revoke: atomic writes', () => {
Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })
)
- await expect(svc.revokeDevice('a')).rejects.toThrow(/EXDEV/)
+ // Reported rather than thrown since the revoke grew its server leg — `local:false` is the
+ // caller-visible failure now, and it must never come back `true` on an unpublished write.
+ expect((await svc.revokeDevice('a')).local).toBe(false)
// A leaked temp here is a leaked credential: it holds every device's `agentToken`, at 0600,
// under a unique name nothing will ever write again.
@@ -141,7 +143,7 @@ describe('pairing-service revoke: atomic writes', () => {
expect(await fs.readFile(authKeys(), 'utf-8')).toContain('nodeterm-ios-a')
})
- it('a failed authorized_keys rename removes its own temp and still rejects', async () => {
+ it('a failed authorized_keys rename removes its own temp and still reports local:false', async () => {
const svc = await service()
const before = await fs.readFile(authKeys(), 'utf-8')
const realRename = fs.rename
@@ -154,7 +156,7 @@ describe('pairing-service revoke: atomic writes', () => {
return (realRename as any)(from, to)
}) as any)
- await expect(svc.revokeDevice('a')).rejects.toThrow(/EACCES/)
+ expect((await svc.revokeDevice('a')).local).toBe(false)
vi.restoreAllMocks()
expect(await tmpsIn(sshDir())).toEqual([])
diff --git a/src/main/pairing-service.test.ts b/src/main/pairing-service.test.ts
index 1b1b7856c..5ca650742 100644
--- a/src/main/pairing-service.test.ts
+++ b/src/main/pairing-service.test.ts
@@ -222,14 +222,16 @@ describe('revokeDevice', () => {
expect(results.map((r) => r.status)).toEqual(['fulfilled', 'fulfilled'])
})
- it('a failed revoke rejects to its caller and does not block the next one', async () => {
+ it('a failed revoke reports local:false to its caller and does not block the next one', async () => {
const service = createPairingService()
// First rename is agent.json's, inside the failing revoke.
vi.spyOn(fs, 'rename').mockRejectedValueOnce(
Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })
)
- await expect(service.revokeDevice('dev-a')).rejects.toThrow(/EXDEV/)
+ // The failure is REPORTED, not thrown (the server leg still has to run, and the UI turns
+ // `local:false` into a retry note — a rejection here reached nobody).
+ expect((await service.revokeDevice('dev-a')).local).toBe(false)
// A serializer that chains failures onto its successors would strand every later revoke.
await service.revokeDevice('dev-b')
@@ -254,7 +256,8 @@ describe('revokeDevice', () => {
return realRename(from, to)
})
- await expect(service.revokeDevice('dev-a')).rejects.toThrow(/EXDEV/)
+ // …and the half-finished revoke says so (`local:false`) instead of resolving like a clean one.
+ expect((await service.revokeDevice('dev-a')).local).toBe(false)
expect(authKeys()).not.toContain('nodeterm-ios-dev-a') // SSH access really was cut
expect(deviceIds()).toContain('dev-a') // still listed, so the owner can retry
diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.ts
index 119582e00..9b319401c 100644
--- a/src/main/pairing-service.ts
+++ b/src/main/pairing-service.ts
@@ -34,7 +34,7 @@ import {
type PublicDevice,
type RelayPairingBlock
} from './pairing-core'
-import type { Settings } from '../shared/types'
+import type { DeviceRevokeResult, DeviceRevokeServerOutcome, Settings } from '../shared/types'
import { publicKeyToB64, deriveSharedKey, encrypt, decrypt, type KeyPair } from './remote/e2ee'
import { hostIdFromPublicKeyB64 } from './remote/relay-id'
import { getDeviceId } from '../core/device-id'
@@ -114,6 +114,51 @@ async function mintRelayDevice(
}
}
+/** How long a revoke waits for the backend before calling it unreachable. */
+const REVOKE_TIMEOUT_MS = 8000
+
+/**
+ * Take a paired phone's Pro entitlement back. Until this existed, Remove was purely local — the
+ * peer key was unpinned and the socket cut, while the server kept minting Pro for that phone
+ * forever.
+ *
+ * Three outcomes, because two cannot tell the truth here:
+ * - 'ok' the route answered 204. It is deliberately idempotent and reveals nothing about
+ * WHICH of its four cases applied (revoked it / unknown device / the row carries a
+ * 'free:'/'apple:' id so there was nothing of ours on it / already revoked) — all
+ * four mean the phone holds no entitlement of ours, which is what we asked for.
+ * - 'failed' we asked and were refused (403 = someone else's row, 401 = the token did not
+ * verify) or could not reach the server. The caller must NOT report a clean removal.
+ * - 'skipped' we did not ask, and that is a normal state: a free-tier desktop holds no
+ * entitlement to sign the request with (and has no Pro of ours on that phone to
+ * reclaim), and a device paired before `relayDeviceId` existed has no row we can name.
+ *
+ * `relayDeviceId` is phone-supplied, unvalidated text, so it rides the JSON body — never a URL.
+ */
+export async function revokeRelayDevice(
+ apiBase: string,
+ relayDeviceId: string,
+ entitlement: string | null
+): Promise<DeviceRevokeServerOutcome> {
+ // Authorization for anything that moves a license is the signed entitlement, never a deviceId.
+ if (!entitlement || !relayDeviceId || !apiBase) return 'skipped'
+ const ctrl = new AbortController()
+ const timer = setTimeout(() => ctrl.abort(), REVOKE_TIMEOUT_MS)
+ try {
+ const res = await fetch(`${apiBase}/v1/relay/device/revoke`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ deviceId: relayDeviceId, entitlement }),
+ signal: ctrl.signal
+ })
+ return res.ok ? 'ok' : 'failed'
+ } catch {
+ return 'failed'
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
/**
* Compute this host's relay reachability block WITHOUT any network call (just the host key →
* hostId), so the QR renders instantly. Returns null (LAN-only) when phone access is off or
@@ -179,8 +224,13 @@ export interface PairingService {
stop(): void
/** All paired devices (token stripped) from ~/.nodeterm/agent.json. */
listDevices(): Promise<PublicDevice[]>
- /** Revoke a device: drop its agent.json entry AND delete its authorized_keys line. */
- revokeDevice(id: string): Promise<void>
+ /**
+ * Revoke a device: drop its agent.json entry, delete its authorized_keys line, AND take its Pro
+ * entitlement back on the relay backend. The two legs are reported separately — see
+ * `DeviceRevokeResult`; this never throws, because a failure the caller cannot see is exactly
+ * how the server leg went missing in the first place.
+ */
+ revokeDevice(id: string): Promise<DeviceRevokeResult>
/** Live re-probe of sshd (127.0.0.1:22), for the Remote Login warning's auto-clear. */
probeSsh(): Promise<boolean>
}
@@ -666,13 +716,38 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
// device still listed — visible to its owner, with the Revoke button still there to finish the
// job. The reverse order fails the other way: the device disappears from the list while its key
// is still live, so the owner believes it revoked and has no way left to retry.
- const revokeDevice = (id: string): Promise<void> =>
- serialize(async () => {
- await removeAuthorizedKeysForDevice(id)
- const obj = await readAgentJson()
- const devices = removeDevice(readDevices(obj), id)
- await writeAgentJson({ ...obj, devices })
+ //
+ // The relay device id is read BEFORE either write and kept even when the local leg fails: the
+ // entitlement is what authorizes the server leg, not the local write's success, and a phone the
+ // user asked to remove should stop being minted Pro either way.
+ const revokeDevice = async (id: string): Promise<DeviceRevokeResult> => {
+ const { local, relayId } = await serialize(async () => {
+ const relayId = readDevices(await readAgentJson()).find((d) => d.id === id)?.relayDeviceId
+ try {
+ await removeAuthorizedKeysForDevice(id)
+ const obj = await readAgentJson()
+ const devices = removeDevice(readDevices(obj), id)
+ await writeAgentJson({ ...obj, devices })
+ return { local: true, relayId }
+ } catch (err) {
+ // Reported, not thrown: `local:false` is what the UI turns into "try again", and the
+ // server leg below is still worth running. The detail belongs in the log.
+ console.warn('[pairing] local revoke failed:', err)
+ return { local: false, relayId }
+ }
})
+ // Deliberately OUTSIDE the mutation chain: this is a network round trip, and holding the
+ // agent.json/authorized_keys queue open for it would stall a concurrent pairing POST behind
+ // an unreachable backend. No local state depends on the answer.
+ const server = relayId
+ ? await revokeRelayDevice(
+ relayDeps?.apiBase ?? '',
+ relayId,
+ relayDeps?.getEntitlement() ?? null
+ )
+ : 'skipped'
+ return { local, server }
+ }
return { start, stop, listDevices, revokeDevice, probeSsh }
}
diff --git a/src/renderer/components/settings/sections/PhoneSection.revoke.test.tsx b/src/renderer/components/settings/sections/PhoneSection.revoke.test.tsx
new file mode 100644
index 000000000..11f4d0fab
--- /dev/null
+++ b/src/renderer/components/settings/sections/PhoneSection.revoke.test.tsx
@@ -0,0 +1,142 @@
+// @vitest-environment jsdom
+//
+// Settings → Phone, the Revoke button: which of the three revoke outcomes the user is TOLD about.
+// The rule is asymmetric on purpose — 'skipped' is a normal state (a free-tier desktop holds no
+// entitlement to revoke with, and a phone paired before we recorded its relay id has no row we can
+// name), so warning there would tell a free user their phone's Pro is stuck when it never had any.
+// Only a leg that actually failed may warn, and a failed one always must.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import type { DeviceRevokeResult, PairedDevice } from '@shared/types'
+import { PhoneSection } from './PhoneSection'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const DEVICE: PairedDevice = {
+ id: 'dev-a',
+ name: 'Enes’ iPhone',
+ pairedAt: 1_700_000_000_000,
+ lastSeenAt: 0,
+ relayDeviceId: 'phone-relay-1'
+}
+
+let root: Root
+let host: HTMLElement
+let revokeDevice: ReturnType<typeof vi.fn>
+
+/** The narrow slice of `window.nodeTerminal` this section touches on mount + revoke. */
+function stubBridge(result: DeviceRevokeResult | Error): void {
+ revokeDevice = vi.fn(async () => {
+ if (result instanceof Error) throw result
+ return result
+ })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ pairing: {
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ onDone: vi.fn(() => () => undefined),
+ probeSsh: vi.fn(async () => true),
+ openRemoteLoginSettings: vi.fn(),
+ listDevices: vi.fn(async () => [DEVICE]),
+ revokeDevice
+ },
+ remoteHost: { setPhoneAccess: vi.fn() },
+ shell: { openExternal: vi.fn() }
+ }
+}
+
+function button(label: string): HTMLButtonElement {
+ const el = [...document.body.querySelectorAll('button')].find(
+ (b) => b.textContent?.trim() === label
+ )
+ expect(el, `a rendered "${label}" button`).toBeTruthy()
+ return el as HTMLButtonElement
+}
+
+/** Click Revoke → confirm → let the (async) revoke settle. Returns the section's visible text. */
+async function revokeFlow(): Promise<string> {
+ await act(async () => {
+ button('Revoke').click()
+ })
+ await act(async () => {
+ // The ConfirmDialog's own confirm button carries the same label; it portals onto body last.
+ const confirms = [...document.body.querySelectorAll('button')].filter(
+ (b) => b.textContent?.trim() === 'Revoke'
+ )
+ confirms[confirms.length - 1].click()
+ })
+ await act(async () => undefined)
+ return host.textContent ?? ''
+}
+
+beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ vi.restoreAllMocks()
+})
+
+function mount(): void {
+ act(() => root.render(<PhoneSection isActive />))
+}
+
+describe('PhoneSection revoke feedback', () => {
+ it('says nothing when the server leg was skipped — there was nothing of ours to revoke', async () => {
+ stubBridge({ local: true, server: 'skipped' })
+ mount()
+ await act(async () => undefined) // the mount-time listDevices
+
+ const text = await revokeFlow()
+ expect(revokeDevice).toHaveBeenCalledWith('dev-a')
+ expect(text).not.toMatch(/Pro access/i)
+ expect(text).not.toMatch(/try again/i)
+ })
+
+ it('says nothing on a clean revoke', async () => {
+ stubBridge({ local: true, server: 'ok' })
+ mount()
+ await act(async () => undefined)
+
+ const text = await revokeFlow()
+ expect(text).not.toMatch(/Pro access/i)
+ expect(text).not.toMatch(/try again/i)
+ })
+
+ it('warns that the phone kept its Pro when the server leg failed', async () => {
+ stubBridge({ local: true, server: 'failed' })
+ mount()
+ await act(async () => undefined)
+
+ const text = await revokeFlow()
+ expect(text).toMatch(/Pro access/i)
+ expect(text).toMatch(/try again/i)
+ })
+
+ it('warns about the local removal when that is the leg that failed', async () => {
+ stubBridge({ local: false, server: 'ok' })
+ mount()
+ await act(async () => undefined)
+
+ const text = await revokeFlow()
+ // The device is still on this machine — saying "its Pro could not be revoked" would be a
+ // different (and here untrue) story.
+ expect(text).toMatch(/remove/i)
+ expect(text).toMatch(/try again/i)
+ expect(text).not.toMatch(/Pro access/i)
+ })
+
+ it('warns when the call itself never answered', async () => {
+ stubBridge(new Error('E_UNSUPPORTED'))
+ mount()
+ await act(async () => undefined)
+
+ const text = await revokeFlow()
+ expect(text).toMatch(/try again/i)
+ })
+})
diff --git a/src/renderer/components/settings/sections/PhoneSection.tsx b/src/renderer/components/settings/sections/PhoneSection.tsx
index 9c625880b..4aff2a301 100644
--- a/src/renderer/components/settings/sections/PhoneSection.tsx
+++ b/src/renderer/components/settings/sections/PhoneSection.tsx
@@ -41,6 +41,7 @@ const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Element {
const [devices, setDevices] = useState<PairedDevice[]>([])
const [pendingRevoke, setPendingRevoke] = useState<PairedDevice | null>(null)
+ const [revokeNote, setRevokeNote] = useState('')
const phoneAccessEnabled = useSettings((s) => s.settings.phoneAccessEnabled)
const updateSettings = useSettings((s) => s.update)
@@ -75,10 +76,30 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele
void refreshDevices()
}, [refreshDevices])
+ // Removing local access and taking the phone's Pro back are DIFFERENT facts, and the second one
+ // used to be missing entirely — Remove unpinned the key here while the server kept minting Pro
+ // for that phone forever. So both legs are surfaced, and only a leg that actually FAILED warns:
+ // 'skipped' means we had nothing to revoke (a free-tier desktop, or a device paired before we
+ // recorded the phone's relay id), and warning there would tell a free user their phone is stuck.
const revokeDevice = async (device: PairedDevice): Promise<void> => {
setPendingRevoke(null)
+ setRevokeNote('')
try {
- await window.nodeTerminal.pairing.revokeDevice(device.id)
+ const result = await window.nodeTerminal.pairing.revokeDevice(device.id)
+ if (!result.local) {
+ setRevokeNote(`Couldn’t remove “${device.name}” from this machine — try again.`)
+ } else if (result.server === 'failed') {
+ // Not "try again" on its own: the row is already gone from the list, so there is no button
+ // left to press. Name the one thing that does re-run the server leg.
+ setRevokeNote(
+ `Removed “${device.name}” from this machine, but its Pro access couldn’t be revoked, ` +
+ 'so that phone may keep Pro. Once this machine is back online, pair it and remove it ' +
+ 'again to try again.'
+ )
+ }
+ } catch {
+ // The call itself never got an answer (main is gone, or the surface doesn't support it).
+ setRevokeNote(`Couldn’t remove “${device.name}” — try again.`)
} finally {
void refreshDevices()
}
@@ -260,6 +281,11 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele
))}
</ul>
)}
+ {revokeNote ? (
+ <p className="text-sm" style={{ color: '#ff9f0a' }}>
+ {revokeNote}
+ </p>
+ ) : null}
</div>
</SearchableRow>
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 206078f57..bec2458a2 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2313,6 +2313,26 @@ export interface PairedDevice {
relayDeviceId?: string
}
+/**
+ * The server leg of a device revoke — three states, because two cannot tell the truth apart.
+ * 'ok' = the backend confirmed; 'failed' = we asked and were refused or could not reach it;
+ * 'skipped' = we did not ask and that is fine (no entitlement to sign with — a free-tier desktop
+ * has no Pro of ours on that phone to reclaim — or no relay device id to name). Only 'failed' is
+ * a warning: reporting 'skipped' as a failure would tell a free user their phone's Pro is stuck.
+ */
+export type DeviceRevokeServerOutcome = 'ok' | 'failed' | 'skipped'
+
+/**
+ * Both legs of a device revoke, reported independently so a half-finished removal can never render
+ * as a clean one (the same discipline as remote/revocation.ts's persisted/killed).
+ */
+export interface DeviceRevokeResult {
+ /** The agent.json entry + authorized_keys line were removed from this machine. */
+ local: boolean
+ /** Whether the phone's Pro entitlement was taken back on the relay backend. */
+ server: DeviceRevokeServerOutcome
+}
+
/** Phone-pairing (nodeterm iOS "scan a QR" flow) bridge. */
export interface PairingApi {
/** Start the one-shot LAN listener; resolves with the QR payload + an SSH-reachable hint. */
@@ -2330,8 +2350,11 @@ export interface PairingApi {
openRemoteLoginSettings(): Promise<void>
/** List paired devices from ~/.nodeterm/agent.json (never includes the token). */
listDevices(): Promise<PairedDevice[]>
- /** Revoke a device: remove its registry entry and delete its authorized_keys line. */
- revokeDevice(id: string): Promise<void>
+ /**
+ * Revoke a device: remove its registry entry, delete its authorized_keys line, and take its Pro
+ * entitlement back on the relay backend. Never rejects for a leg that failed — read the result.
+ */
+ revokeDevice(id: string): Promise<DeviceRevokeResult>
}
/** Team presence (docs/team-presence.md). All of it is transient — nothing here is persisted. */