Skip to content

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

feat(pairing): remember the phone's relay device id so a removal can name it

enes42952978a917
diff --git a/src/main/pairing-core.test.ts b/src/main/pairing-core.test.ts
index 75345b12f..128635a7e 100644
--- a/src/main/pairing-core.test.ts
+++ b/src/main/pairing-core.test.ts
@@ -285,6 +285,63 @@ describe('device registry helpers', () => {
})
})
+describe('DeviceEntry.relayDeviceId', () => {
+ // The desktop mints its OWN device id (it stamps the authorized_keys comment) and the phone
+ // sends its own — and only the phone's is what the server keys `relay_devices` on. Keeping
+ // just the local one made a paired device unnameable to the server, so a removal could never
+ // say WHICH row to revoke.
+ const entry: DeviceEntry = {
+ id: 'local-uuid',
+ name: 'iPhone',
+ token: 'agent-token',
+ pairedAt: 1,
+ lastSeenAt: 0,
+ relayDeviceId: 'phone-1'
+ }
+
+ it('round-trips through upsertDevice (it is persisted, not derived)', () => {
+ expect(upsertDevice([], entry)[0].relayDeviceId).toBe('phone-1')
+ const replaced = upsertDevice([{ ...entry, relayDeviceId: 'stale' }], entry)
+ expect(replaced).toEqual([entry])
+ })
+
+ it('is exposed to the renderer (an id, not a secret) while the token still is not', () => {
+ const [pub] = toPublicDevices([entry])
+ expect(pub.relayDeviceId).toBe('phone-1')
+ // Whole shape, not a subset: a mapper that spread the record would satisfy the line above
+ // AND leak `token`. Both assertions below fail on `devices.map((d) => ({ ...d }))`.
+ expect(pub).toEqual({
+ id: 'local-uuid',
+ name: 'iPhone',
+ pairedAt: 1,
+ lastSeenAt: 0,
+ relayDeviceId: 'phone-1'
+ })
+ expect(Object.keys(pub).sort()).toEqual([
+ 'id',
+ 'lastSeenAt',
+ 'name',
+ 'pairedAt',
+ 'relayDeviceId'
+ ])
+ expect((pub as Record<string, unknown>).token).toBeUndefined()
+ })
+
+ it('is optional — a device paired before the field existed still maps, with no id and no token', () => {
+ const legacy: DeviceEntry = {
+ id: 'old',
+ name: 'Old Phone',
+ token: 'agent-token',
+ pairedAt: 1,
+ lastSeenAt: 0
+ }
+ expect(readDevices({ devices: [legacy] })).toEqual([legacy])
+ const [pub] = toPublicDevices([legacy])
+ expect(pub.relayDeviceId).toBeUndefined()
+ expect(Object.keys(pub)).not.toContain('token')
+ })
+})
+
describe('pickLanIPv4', () => {
it('picks the first non-internal, non-link-local IPv4', () => {
const picked = pickLanIPv4({
diff --git a/src/main/pairing-core.ts b/src/main/pairing-core.ts
index 18d7e7606..26f5d96f4 100644
--- a/src/main/pairing-core.ts
+++ b/src/main/pairing-core.ts
@@ -135,6 +135,15 @@ export interface DeviceEntry {
token: string
pairedAt: number
lastSeenAt: number
+ /**
+ * The PHONE's own device id, as sent to `/v1/relay/device` — the key `relay_devices` is stored
+ * under. `id` above is ours (it stamps the authorized_keys comment) and means nothing to the
+ * backend, so without this a removal could not tell the server WHICH row to revoke.
+ * Absent for devices paired before this field existed; equal to `id` when the phone sent no id
+ * of its own. Recorded for a LAN-only pairing too — the phone identifies itself either way — so
+ * its presence names a row the server MAY hold, not one it certainly does.
+ */
+ relayDeviceId?: string
}
/** The device shape safe to expose to the renderer (no `token`). */
@@ -169,9 +178,18 @@ export function removeDevice(devices: DeviceEntry[], id: string): DeviceEntry[]
return devices.filter((d) => d.id !== id)
}
-/** Strip the secret `token` from each device before handing the list to the renderer. */
+/**
+ * Strip the secret `token` from each device before handing the list to the renderer. Built field
+ * by field on purpose: spreading the entry would carry the token out with every future field.
+ */
export function toPublicDevices(devices: DeviceEntry[]): PublicDevice[] {
- return devices.map(({ id, name, pairedAt, lastSeenAt }) => ({ id, name, pairedAt, lastSeenAt }))
+ return devices.map(({ id, name, pairedAt, lastSeenAt, relayDeviceId }) => ({
+ id,
+ name,
+ pairedAt,
+ lastSeenAt,
+ relayDeviceId
+ }))
}
/** Minimal shape of `os.networkInterfaces()` we need — kept structural so tests can fake it. */
diff --git a/src/main/pairing-service.test.ts b/src/main/pairing-service.test.ts
index 7700cb4a9..1b1b7856c 100644
--- a/src/main/pairing-service.test.ts
+++ b/src/main/pairing-service.test.ts
@@ -37,9 +37,16 @@ vi.mock('os', async (importOriginal) => {
}
})
+// The relay mint stamps this host's anonymous device id, which is read out of the CorePlatform's
+// userData dir — uninitialized here, and its throw would be swallowed into a silent LAN-only
+// pairing. Pinned to a constant so the mint body is fully assertable.
+vi.mock('../core/device-id', () => ({ getDeviceId: () => 'test-host-device-id' }))
+
import os from 'os'
-import { createPairingService } from './pairing-service'
+import { createPairingService, type PairingRelayDeps } from './pairing-service'
import { rewriteKeyComment, type DeviceEntry } from './pairing-core'
+import { genKeyPair, publicKeyToB64 } from './remote/e2ee'
+import type { Settings } from '../shared/types'
const HOME = os.homedir()
const AGENT_JSON = path.join(HOME, '.nodeterm', 'agent.json')
@@ -298,3 +305,107 @@ describe('pairing POST vs revoke', () => {
}
})
})
+
+describe('pairing remembers the phone’s relay device id', () => {
+ // Two ids are in play and only ONE of them means anything to the relay backend: the desktop
+ // mints a local `deviceId` (it stamps the authorized_keys comment), while `relay_devices` is
+ // keyed on the id the PHONE sends. agent.json used to keep only the local one — the phone's was
+ // computed for the mint and thrown away — so "Remove device" had no way to name the row the
+ // server holds.
+ const hostKeys = genKeyPair()
+ const relayDeps = (): PairingRelayDeps => ({
+ getSettings: () => ({ phoneAccessEnabled: true }) as unknown as Settings,
+ getEntitlement: () => null,
+ loadHostKeyPair: async () => hostKeys,
+ relayEndpoint: 'wss://relay.example/ws',
+ apiBase: 'https://api.example',
+ relayAllowed: () => true
+ })
+
+ const devices = (): DeviceEntry[] => (agentJson().devices as DeviceEntry[] | undefined) ?? []
+ const paired = (id: string): DeviceEntry => {
+ const entry = devices().find((d) => d.id === id)
+ if (!entry) throw new Error(`no agent.json entry for ${id}`)
+ return entry
+ }
+
+ it('persists the id the phone sent, alongside the local one it does not replace', async () => {
+ const service = createPairingService()
+ try {
+ const started = await service.start(() => {})
+ const { token, pairPort } = JSON.parse(started.payload) as { token: string; pairPort: number }
+
+ const respText = await post(pairPort, {
+ token,
+ publicKey: freshEd25519Line(),
+ deviceName: 'New Phone',
+ deviceId: 'phone-abc'
+ })
+
+ const { deviceId } = JSON.parse(respText) as { deviceId: string }
+ expect(paired(deviceId).relayDeviceId).toBe('phone-abc')
+ // The local id still stamps the key line and still identifies the entry — the new field is
+ // an addition, not a rename.
+ expect(deviceId).not.toBe('phone-abc')
+ expect(authKeys()).toContain(`nodeterm-ios-${deviceId}`)
+ } finally {
+ service.stop()
+ }
+ })
+
+ it('falls back to the local id when the phone sent none, so the two coincide', async () => {
+ const service = createPairingService()
+ try {
+ const started = await service.start(() => {})
+ const { token, pairPort } = JSON.parse(started.payload) as { token: string; pairPort: number }
+
+ const respText = await post(pairPort, {
+ token,
+ publicKey: freshEd25519Line(),
+ deviceName: 'Quiet Phone'
+ })
+
+ const { deviceId } = JSON.parse(respText) as { deviceId: string }
+ expect(paired(deviceId).relayDeviceId).toBe(deviceId)
+ } finally {
+ service.stop()
+ }
+ })
+
+ it('sends the SAME id to /v1/relay/device that it records, and sends nothing else new', async () => {
+ // Computing `phoneDeviceId` earlier (so persistDevice can have it) must not change one byte
+ // of the mint body — this pins the whole body, so a reorder that accidentally passed the
+ // LOCAL id, or added a field, fails here rather than in production.
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ json: async () => ({ deviceToken: 'device-token', hostId: 'host-id', exp: 0 })
+ } as unknown as Response)
+ const service = createPairingService(relayDeps())
+ try {
+ const started = await service.start(() => {})
+ const { token, pairPort } = JSON.parse(started.payload) as { token: string; pairPort: number }
+
+ const respText = await post(pairPort, {
+ token,
+ publicKey: freshEd25519Line(),
+ deviceName: 'Relay Phone',
+ deviceId: 'phone-relay-1'
+ })
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe('https://api.example/v1/relay/device')
+ expect(JSON.parse(String(init.body))).toEqual({
+ deviceId: 'phone-relay-1',
+ hostDeviceId: 'test-host-device-id',
+ hostPublicKeyB64: publicKeyToB64(hostKeys.publicKey),
+ label: 'Relay Phone'
+ })
+
+ const { deviceId } = JSON.parse(respText) as { deviceId: string }
+ expect(paired(deviceId).relayDeviceId).toBe('phone-relay-1')
+ } finally {
+ service.stop()
+ }
+ })
+})
diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.ts
index a2fba4617..119582e00 100644
--- a/src/main/pairing-service.ts
+++ b/src/main/pairing-service.ts
@@ -570,6 +570,12 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
const deviceId = randomUUID()
const agentToken = randomBytes(24).toString('base64url')
const name = normalizeDeviceName(body.deviceName)
+ // The phone's OWN id — the key the relay backend stores its device row under, and the
+ // only one it would recognize in a later revoke. Resolved here rather than at the mint
+ // below so the registry entry can carry it; the fallback (phone sent none ⇒ our id) is
+ // unchanged, and the mint still reads this same value.
+ const phoneDeviceId =
+ typeof body.deviceId === 'string' && body.deviceId.trim() ? body.deviceId.trim() : deviceId
// One unit, and queued behind any in-flight revoke: a pairing that interleaves with one
// would either append onto the inode the revoke is about to rename over, or lose its
// agent.json entry to the revoke's stale read.
@@ -580,17 +586,14 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
name,
token: agentToken,
pairedAt: Date.now(),
- lastSeenAt: 0
+ lastSeenAt: 0,
+ relayDeviceId: phoneDeviceId
})
})
// Provision relay access for the phone when enabled + Pro. Any failure ⇒ LAN-only: we
// never fail the pairing over a relay hiccup (the phone still got its SSH key installed).
let relayFields: { relay?: RelayPairingBlock; relayDeviceToken?: string } = {}
if (relayCtx) {
- const phoneDeviceId =
- typeof body.deviceId === 'string' && body.deviceId.trim()
- ? body.deviceId.trim()
- : deviceId
const minted = await mintRelayDevice(relayDeps!.apiBase, {
entitlement: relayCtx.entitlement,
deviceId: phoneDeviceId,
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 5015da94b..206078f57 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2305,6 +2305,12 @@ export interface PairedDevice {
pairedAt: number
/** epoch-ms the host agent last saw this device (0 = never). */
lastSeenAt: number
+ /**
+ * The phone's OWN device id — what the relay backend keys its device row on, as opposed to
+ * `id`, which is ours. Absent for devices paired before this field existed, i.e. "there is no
+ * server row we can name". An id, not a secret, which is why it may cross to the renderer.
+ */
+ relayDeviceId?: string
}
/** Phone-pairing (nodeterm iOS "scan a QR" flow) bridge. */