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(relay): removing a device revokes its relay trust; split pin stores by role

reviewbc90bcea3e94
diff --git a/CLAUDE.md b/CLAUDE.md
index 4e5fad56f..5c1c19b2c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6858,6 +6858,20 @@ to the class, and no bare `.react-flow__viewport` rule carries `will-change`).
inert ("not served"); `host-chat-wiring.test.ts` pins the chain at source level. Served only to an
approved phone; Team-access relay guests never reach them (`relay-host.ts` serves no phone
dialect). Server Edition: N/A (no phone relay; the bridge subscription is inert).
+- **One relay pin store per ROLE, and only the phone store admits anyone** (`main/remote/approved-devices.ts`).
+ `phonePins` (`remote-approved-phones.json`) is what the standing host auto-approves from, silently,
+ with the full phone vocabulary; `guestPins` (Team Access desktops we host) and `joinedHostPins`
+ (hosts we joined) are records that nothing reads to admit. They used to be ONE file, so a host you
+ once joined, or a guest whose seat you revoked, was auto-admitted as a phone. The pre-split
+ `remote-approved-devices.json` is deleted at boot and NOTHING in it is carried over: nothing on
+ this machine can tell its roles apart (the phone's relay box key is never sent at pairing, so
+ agent.json cannot vouch for one), so every phone re-approves by SAS once. **Every revoke goes
+ through `main/remote/peer-revoke.ts`**: unpin from the named role stores, then run every
+ registered host killer (standing host pool incl. pending consent, the interactive `initRemoteHost`
+ session, the Team Access `live` set). A revoke that knows only one host leaves the others serving.
+ Phone "Remove" (`pairing-service.revokeDevice`) revokes ALL phone pins and cuts ALL phone relay
+ sessions, before the SSH key and the device entry go — all-phones because no box key maps to a
+ device; a failure reports `local:false` and keeps the device listed to retry.
- **A Windows desktop pairs relay-only — no SSH key, and do not "fix" that by writing one.** The
phone's direct-SSH path is POSIX sh + tmux end to end (nodeterm-ios `HostCommands`, `TmuxBinary`,
the typed `tmux new-session -A` attach, workspace paths with no `%APPDATA%` candidate). Windows
@@ -6919,7 +6933,7 @@ The invariants, each with its reason:
first-join approval. Unreadable ⇒ hosting stays off with `host-key-unreadable`; only
`team rotate-key` replaces it.
- **`team.json` is not the phone's pin file.** Push's `hasPairedPhone` counts the entries of
- `remote-approved-devices.json`, so a teammate pinned there would read as a paired phone. The same
+ `remote-approved-phones.json`, so a teammate pinned there would read as a paired phone. The same
rule on the joiner: `hosted-join.ts` runs the core relay client with NO pin store, and the
joiner-side pin is the bookmark's `approvedAt` (valid only for the exact host key it was recorded
with).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index acd28ce6d..4b6850bdf 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -443,6 +443,11 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
the relay, so a key that works locks it onto a path that cannot work. CLAUDE.md, "Remote access",
has the details.
+- **Relay pins are per role, and a revoke is one call.** Pin a peer only through its role's store
+ in `src/main/remote/approved-devices.ts` (`phonePins` is the only one anything auto-admits from —
+ never write a desktop peer there), and revoke only through `src/main/remote/peer-revoke.ts`, which
+ unpins AND closes every live session on every host. A new host that serves relay peers must
+ `registerPeerSessionKiller`, or revoking a device leaves its shell open. CLAUDE.md, "Remote access".
- **A relay channel that names a project needs a row in `relay-project-scope.ts`.** A relay guest
bound to one shared project must never reach another, and the jail is keyed on channel class:
anything named `githubIssues:*`, `board-log:*` or `projects.*` is refused on a scoped session
diff --git a/src/core/phone-approval.ts b/src/core/phone-approval.ts
index b291269d2..921d106da 100644
--- a/src/core/phone-approval.ts
+++ b/src/core/phone-approval.ts
@@ -65,6 +65,11 @@ export function createPhoneApprovals(deps: {
return true
},
clear,
+ /** Drop every pending consent whose key satisfies `match` (a revoke: an open SAS dialog for a
+ * revoked key must not be able to re-pin it afterwards). */
+ clearWhere(match: (pub: string) => boolean): void {
+ for (const [id, p] of [...pending]) if (match(p.pub)) clear(id)
+ },
stop(): void {
for (const id of pending.keys()) clear(id)
}
diff --git a/src/core/push-notify.ts b/src/core/push-notify.ts
index fe983c78f..7c27016e6 100644
--- a/src/core/push-notify.ts
+++ b/src/core/push-notify.ts
@@ -148,7 +148,7 @@ function groupByGrantHost<T extends { nodeId: string }>(
*
* The correct exclusion is per DEVICE, and this process cannot express it: a `PushGrant` is keyed by
* the phone's `deviceId` (the grant filename), while the relay-paired registry
- * (`remote-approved-devices.json`, read by `loadApprovedDevices`) stores nothing but base64 NaCl box
+ * (`remote-approved-phones.json`, read by `phonePins.load`) stores nothing but base64 NaCl box
* PUBLIC KEYS — and this service is only told `hasPairedPhone: boolean` in the first place. The two
* identifiers never meet on the desktop: the phone's own deviceId is seen exactly once, transiently,
* during a LAN QR pair (`pairing-service.ts`'s `phoneDeviceId`, spent on the `/v1/relay/device` mint
diff --git a/src/core/relay/approved-devices-core.ts b/src/core/relay/approved-devices-core.ts
index 7715eebe8..e1b8a009e 100644
--- a/src/core/relay/approved-devices-core.ts
+++ b/src/core/relay/approved-devices-core.ts
@@ -7,7 +7,7 @@
// Kept pure (no I/O) so it can be unit-tested; the disk read/write wrapper lives in
// `approved-devices.ts`.
-/** The persisted shape of <userData>/remote-approved-devices.json. */
+/** The persisted shape of every relay pin store (<userData>/remote-approved-{phones,guests,hosts}.json). */
export interface ApprovedDevices {
/** Base64 NaCl box public keys of phones the host has approved at least once. */
pubkeys: string[]
diff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.ts
index 1c90af880..f7a0bd12a 100644
--- a/src/core/relay/relay-host.ts
+++ b/src/core/relay/relay-host.ts
@@ -201,8 +201,15 @@ const live = new Set<RelayHostSession>()
/** Cut every live session with this peer key. The revoker's `onRevoke` (src/main/index.ts). With a
* reason, the peer is told why over the encrypted tunnel first (`deny`); without one it is closed. */
export function killRelayHostsByPeerKey(peerKeyB64: string, reason?: TrustDeniedReason): void {
+ killRelayHostsWhere((key) => key === peerKeyB64, reason)
+}
+
+/** Cut every live session (bridged or still awaiting mutual approval) whose peer key satisfies
+ * `match`. A session whose key is not known yet is never matched. */
+export function killRelayHostsWhere(match: (peerKeyB64: string) => boolean, reason?: TrustDeniedReason): void {
for (const session of [...live]) {
- if (session.peerKeyB64() !== peerKeyB64) continue
+ const key = session.peerKeyB64()
+ if (!key || !match(key)) continue
if (reason) session.deny(reason)
else session.close()
}
diff --git a/src/core/relay/team-store.ts b/src/core/relay/team-store.ts
index 97e0ce825..d9d59e881 100644
--- a/src/core/relay/team-store.ts
+++ b/src/core/relay/team-store.ts
@@ -1,7 +1,7 @@
// The hosted team's membership: which device keys may auto-reconnect, with what role, and which
// projects non-editors may see. Pure transforms + a single-writer store.
//
-// SEPARATE from the phone's remote-approved-devices.json on purpose: push's `hasPairedPhone` counts
+// SEPARATE from the phone's remote-approved-phones.json on purpose: push's `hasPairedPhone` counts
// that file's entries, so a teammate's pin there would read as a paired phone.
//
// Corrupt ⇒ CLOSED: the file is set aside and the store starts with no peers, so nobody
diff --git a/src/main/index.ts b/src/main/index.ts
index 012bdcc1e..d3d357693 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -333,10 +333,9 @@ import {
RELAY_URL
} from './remote/host-service'
import { initStandingHost } from './remote/standing-host'
-import { killRelayHostsByPeerKey } from './remote/relay-host'
import { initRelayHost } from './remote/relay-host-service'
-import { createRevoker } from './remote/revocation'
-import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } from './remote/approved-devices'
+import { PIN_ROLES, phonePins, retireLegacyPinFile } from './remote/approved-devices'
+import { revokeAllPhones, revokePeerKey } from './remote/peer-revoke'
import { publicKeyToB64 } from './remote/e2ee'
import { connectRelayClient, type RelayClientSession } from './remote/relay-client'
import { decodeOffer } from './remote/pairing'
@@ -1703,6 +1702,10 @@ app.whenReady().then(async () => {
relayEndpoint: RELAY_URL,
apiBase: RELAY_API_BASE,
relayAllowed
+ }, {
+ // A phone "Remove" must also revoke its RELAY trust: unpin and cut its live relay sessions.
+ // Which pin is that phone's is unknowable here, so every phone pin goes (peer-revoke.ts).
+ revokePhoneRelayTrust: revokeAllPhones
})
ipcMain.handle(IPC.pairingStart, () =>
pairingService.start((result) => {
@@ -1727,18 +1730,12 @@ app.whenReady().then(async () => {
// Revoking a bridged PEER must CUT THE LIVE SESSION, not just unpin it (revocation.ts): unpinning
// refuses only the NEXT handshake, while the open relay socket keeps full shell access — "the
- // person I just removed is still sitting in my terminal, typing". `killByPeerKey` closes every
- // live session with that key, and each close runs the peer teardown (presence leave →
- // PtyManager.dropClient → sink prune). Host-security control plane, so it stays on raw ipcMain:
- // a remote peer must never be able to revoke anyone.
- const peerRevoker = createRevoker({
- load: loadApprovedDevices,
- save: saveApprovedDevices,
- update: updateApprovedDevices,
- onRevoke: (peerKeyB64) => killRelayHostsByPeerKey(peerKeyB64)
- })
+ // person I just removed is still sitting in my terminal, typing". `revokePeerKey` (peer-revoke.ts)
+ // is the one primitive: it unpins the key from every role store and closes every live session it
+ // holds on every host surface (standing phone host, interactive phone host, Team Access). Host-
+ // security control plane, so it stays on raw ipcMain: a remote peer must never be able to revoke.
ipcMain.handle(IPC.remoteRevokePeer, (_e, peerKeyB64: string) =>
- peerRevoker.revoke(String(peerKeyB64))
+ revokePeerKey(String(peerKeyB64), PIN_ROLES)
)
ipcMain.on(IPC.shellReveal, (_e, p: string) => {
@@ -2217,7 +2214,7 @@ app.whenReady().then(async () => {
// phone silenced every SSH-only phone on this Mac: host mode fans out over the backend's
// `relay_devices` rows, where an SSH-only phone has no row at all. The per-device exclusion that
// would prevent the reverse cost (a phone that is paired AND granted gets two pushes) is not
- // expressible here — a grant is keyed by the phone's deviceId, `loadApprovedDevices` stores only
+ // expressible here — a grant is keyed by the phone's deviceId, `phonePins` stores only
// NaCl box pubkeys, and nothing on this machine maps one to the other. See the long note on
// `resolveSendTarget` in core/push-notify.ts.
const pushGrants = createGrantsAccessor()
@@ -2255,7 +2252,11 @@ app.whenReady().then(async () => {
let pushHasPairedPhone = false
const refreshPushIdentity = async (): Promise<void> => {
try {
- pushHasPairedPhone = (await loadApprovedDevices()).pubkeys.length > 0
+ // A relay-approved phone pin, OR a paired phone that has not re-approved over the relay since
+ // the pin stores were split (approved-devices.ts retires the old mixed file, so every phone
+ // re-prompts SAS once — push must not go silent in the meantime).
+ pushHasPairedPhone =
+ (await phonePins.load()).pubkeys.length > 0 || (await pairingService.listDevices()).length > 0
} catch {
pushHasPairedPhone = false
}
@@ -4263,11 +4264,18 @@ app.whenReady().then(async () => {
ipcMain.on(IPC.agentSeedIdentity, (_e, entries: unknown) => {
seedNodeIdentities(entries)
})
+ // Retire the pre-split mixed pin file BEFORE the standing host can read anything (approved-devices.ts
+ // explains why nothing in it is carried over). The standing host reads only the phone store, so
+ // even a failed retire cannot auto-admit a legacy key — this is for downgrade safety and tidiness.
+ void retireLegacyPinFile().then(
+ (n) => { if (n > 0) console.info(`[relay] retired ${n} legacy pin(s); phones re-approve by SAS once`) },
+ (err) => console.warn('[relay] could not retire the legacy pin file:', (err as Error)?.message)
+ )
initRemoteHost(win, ptyManager, listProjectsOutput, hostBridge)
// NEW interactive relay host (Stage 4): a connecting peer desktop becomes a first-class
// CorePlatform client of this desktop after mutual SAS approval. Runs BESIDE initRemoteHost (the
// phone still uses the legacy flow). Inert until `relay:host:start` — a solo user pays nothing.
- // Revocation reaches its sessions via `killRelayHostsByPeerKey` (peerRevoker, above).
+ // Revocation reaches its sessions via the peer-revoke.ts registry (relay-host.ts registers).
initRelayHost(win, corePlatform, {})
// Standing (phone) relay host: keep a host connection registered so a paired phone can reach
// this Mac from anywhere. Honors settings.phoneAccessEnabled internally.
diff --git a/src/main/pairing-revoke.test.ts b/src/main/pairing-revoke.test.ts
index fd702dea2..201f93f9c 100644
--- a/src/main/pairing-revoke.test.ts
+++ b/src/main/pairing-revoke.test.ts
@@ -265,3 +265,46 @@ describe('createPairingService().revokeDevice', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
})
+
+describe('createPairingService().revokeDevice — relay trust (pinned box key + live sessions)', () => {
+ beforeEach(() => {
+ seed('phone-relay-1')
+ })
+
+ it('revokes the relay trust BEFORE the SSH key and the registry entry are removed', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 204 })))
+ const order: string[] = []
+ const revokePhoneRelayTrust = vi.fn(async () => {
+ // At this instant the device must still be listed and its key still installed.
+ order.push(`relay:${deviceIds().join(',')}:${authKeys().includes('dev-a') ? 'key' : 'nokey'}`)
+ return { persisted: true, killed: true }
+ })
+ const service = createPairingService(relayDeps('TOKEN'), { revokePhoneRelayTrust })
+
+ expect(await service.revokeDevice('dev-a')).toEqual({ local: true, server: 'ok' })
+ expect(revokePhoneRelayTrust).toHaveBeenCalledOnce()
+ expect(order).toEqual(['relay:dev-a:key'])
+ expect(deviceIds()).toEqual([])
+ })
+
+ it('a relay trust revoke that did not stick reports local:false and keeps the device listed to retry', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 204 })))
+ for (const relay of [{ persisted: false, killed: true }, { persisted: true, killed: false }]) {
+ seed('phone-relay-1')
+ const service = createPairingService(relayDeps('TOKEN'), {
+ revokePhoneRelayTrust: async () => relay
+ })
+ const result = await service.revokeDevice('dev-a')
+ expect(result.local).toBe(false)
+ expect(deviceIds()).toEqual(['dev-a'])
+ expect(authKeys()).toContain('dev-a')
+ }
+ })
+
+ it('never touches relay trust for an id that is not in the registry', async () => {
+ const revokePhoneRelayTrust = vi.fn(async () => ({ persisted: true, killed: true }))
+ const service = createPairingService(relayDeps('TOKEN'), { revokePhoneRelayTrust })
+ await service.revokeDevice('never-paired')
+ expect(revokePhoneRelayTrust).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.ts
index f81a2be4f..5e89f1b71 100644
--- a/src/main/pairing-service.ts
+++ b/src/main/pairing-service.ts
@@ -245,7 +245,8 @@ export interface PairingService {
/** All paired devices (token stripped) from ~/.nodeterm/agent.json. */
listDevices(): Promise<PublicDevice[]>
/**
- * Revoke a device: drop its agent.json entry, delete its authorized_keys line, AND take its Pro
+ * Revoke a device: revoke its relay trust (unpin + cut live relay sessions), 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.
@@ -426,6 +427,13 @@ export interface PairingServiceOptions {
defaultRouteAddress?: () => Promise<string | null>
/** Defaults to PAIR_TIMEOUT_MS. */
timeoutMs?: number
+ /**
+ * Revoke the phone's RELAY trust on Remove: unpin its box key from the phone store and close its
+ * live relay sessions (peer-revoke.ts `revokeAllPhones`). Without it a removed phone keeps its
+ * relay shell until the socket drops and is silently re-admitted on reconnect. Absent ⇒ no relay
+ * leg (tests, and any shell without a standing host).
+ */
+ revokePhoneRelayTrust?: () => Promise<{ persisted: boolean; killed: boolean }>
}
export function createPairingService(
@@ -875,7 +883,8 @@ export function createPairingService(
// One unit: agent.json and authorized_keys must not be revoked half-way by an interleaving writer.
//
- // authorized_keys goes FIRST, and the order is load-bearing on partial failure. That file is full
+ // Relay trust goes first (see inside), then authorized_keys, and the order is load-bearing on
+ // partial failure. authorized_keys is full
// shell access; agent.json holds the host-agent bearer token and the device the UI lists. If the
// second step fails, revoking the SSH key first leaves the BIGGER capability already gone and the
// device still listed — visible to its owner, with the Revoke button still there to finish the
@@ -891,6 +900,16 @@ export function createPairingService(
const relayId = entry?.relayDeviceId
const found = !!entry
try {
+ // Relay trust FIRST, for the same reason as the order below: it is shell access (a pinned
+ // box key is auto-admitted by the standing host with the full phone vocabulary), so it goes
+ // before the device leaves the list. If it fails, the device stays listed and the owner can
+ // retry. It runs only for a device we actually know, so a stale id cannot unpin anything.
+ if (found && options.revokePhoneRelayTrust) {
+ const relay = await options.revokePhoneRelayTrust()
+ if (!relay.persisted || !relay.killed) {
+ throw new Error(`relay trust revoke incomplete (persisted=${relay.persisted}, killed=${relay.killed})`)
+ }
+ }
await removeAuthorizedKeysForDevice(id)
await removeAdministratorsKeysForDevice(id)
const obj = await readAgentJson()
diff --git a/src/main/remote/approved-devices.test.ts b/src/main/remote/approved-devices.test.ts
index e1a69f42c..eb941215d 100644
--- a/src/main/remote/approved-devices.test.ts
+++ b/src/main/remote/approved-devices.test.ts
@@ -1,4 +1,5 @@
-// Atomic-write behaviour of <userData>/remote-approved-devices.json.
+// Atomic-write behaviour of the relay pin stores (<userData>/remote-approved-phones.json and its
+// per-role siblings), plus the role split and the retirement of the pre-split mixed file.
//
// Three writers reach `saveApprovedDevices` from the main process with nothing queueing them:
// the standing host's fire-and-forget pin (standing-host.ts, `void loadApprovedDevices().then(...)`),
@@ -15,7 +16,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtempSync, promises as fs, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import path from 'path'
-import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } from './approved-devices'
+import {
+ LEGACY_PIN_FILE,
+ PIN_ROLES,
+ guestPins,
+ joinedHostPins,
+ phonePins,
+ pinFileName,
+ retireLegacyPinFile
+} from './approved-devices'
import { pinDevice, unpinDevice } from './approved-devices-core'
import type { ApprovedDevices } from './approved-devices-core'
@@ -24,12 +33,16 @@ import type { ApprovedDevices } from './approved-devices-core'
let userData = ''
vi.mock('electron', () => ({ app: { getPath: () => userData } }))
+const loadApprovedDevices = (): Promise<ApprovedDevices> => phonePins.load()
+const saveApprovedDevices = (s: ApprovedDevices): Promise<void> => phonePins.save(s)
+const updateApprovedDevices = (u: (s: ApprovedDevices) => ApprovedDevices): Promise<void> => phonePins.update(u)
+
describe('approved-devices atomic write', () => {
let target: string
beforeEach(() => {
userData = mkdtempSync(path.join(tmpdir(), 'nt-approved-'))
- target = path.join(userData, 'remote-approved-devices.json')
+ target = path.join(userData, 'remote-approved-phones.json')
})
afterEach(() => {
@@ -138,3 +151,63 @@ describe('approved-devices atomic write', () => {
expect(await tmpsLeft()).toEqual([])
})
})
+
+describe('pin stores are split by role', () => {
+ beforeEach(() => {
+ userData = mkdtempSync(path.join(tmpdir(), 'nt-approved-'))
+ })
+ afterEach(() => {
+ vi.restoreAllMocks()
+ rmSync(userData, { recursive: true, force: true })
+ })
+
+ it('every role has its own file, and none of them is the legacy mixed file', () => {
+ const names = PIN_ROLES.map(pinFileName)
+ expect(new Set(names).size).toBe(PIN_ROLES.length)
+ expect(names).not.toContain(LEGACY_PIN_FILE)
+ })
+
+ it('a guest or joined-host pin is never visible to the phone store the standing host reads', async () => {
+ await guestPins.update((s) => pinDevice(s, 'team-guest'))
+ await joinedHostPins.update((s) => pinDevice(s, 'joined-host'))
+ expect(await phonePins.load()).toEqual({ pubkeys: [] })
+ expect(await guestPins.load()).toEqual({ pubkeys: ['team-guest'] })
+ expect(await joinedHostPins.load()).toEqual({ pubkeys: ['joined-host'] })
+ })
+})
+
+describe('retireLegacyPinFile (fail-closed migration)', () => {
+ let legacy: string
+ beforeEach(() => {
+ userData = mkdtempSync(path.join(tmpdir(), 'nt-approved-'))
+ legacy = path.join(userData, LEGACY_PIN_FILE)
+ })
+ afterEach(() => {
+ vi.restoreAllMocks()
+ rmSync(userData, { recursive: true, force: true })
+ })
+
+ it('removes the mixed file and carries NONE of its keys into any role store', async () => {
+ // Nothing on disk says which of these was a phone, a joined host or a hosted guest.
+ writeFileSync(legacy, JSON.stringify({ pubkeys: ['maybe-phone', 'joined-host', 'revoked-guest'] }))
+ expect(await retireLegacyPinFile()).toBe(3)
+ await expect(fs.stat(legacy)).rejects.toMatchObject({ code: 'ENOENT' })
+ for (const store of [phonePins, guestPins, joinedHostPins]) {
+ expect(await store.load()).toEqual({ pubkeys: [] })
+ }
+ })
+
+ it('keeps real phones re-approved after the split and is idempotent', async () => {
+ await phonePins.update((s) => pinDevice(s, 'phone-approved-after-split'))
+ writeFileSync(legacy, JSON.stringify({ pubkeys: ['old'] }))
+ await retireLegacyPinFile()
+ expect(await retireLegacyPinFile()).toBe(0)
+ expect(await phonePins.load()).toEqual({ pubkeys: ['phone-approved-after-split'] })
+ })
+
+ it('an unreadable legacy file is still removed (never left for a later reader)', async () => {
+ writeFileSync(legacy, '{broken')
+ expect(await retireLegacyPinFile()).toBe(0)
+ await expect(fs.stat(legacy)).rejects.toMatchObject({ code: 'ENOENT' })
+ })
+})
diff --git a/src/main/remote/approved-devices.ts b/src/main/remote/approved-devices.ts
index c3deb4fba..92d89007f 100644
--- a/src/main/remote/approved-devices.ts
+++ b/src/main/remote/approved-devices.ts
@@ -1,8 +1,25 @@
-// Disk read/write for the standing (phone) host's pinned-device list. The pure pin/lookup logic
-// lives in `approved-devices-core.ts`; this only touches the filesystem.
+// Disk read/write for the relay pin stores. The pure pin/lookup logic lives in
+// `approved-devices-core.ts`; this only touches the filesystem.
//
-// Stored at <userData>/remote-approved-devices.json. The contents are PUBLIC keys (device box
-// public keys the host has approved once), never credentials.
+// ONE STORE PER ROLE, because a pin means something different in each and only one of them grants
+// anything on its own:
+//
+// phone <userData>/remote-approved-phones.json Phones the standing host approved by SAS.
+// READ by standing-host.ts: a key here is
+// AUTO-ADMITTED, silently, with the full phone
+// vocabulary (shell, files, canvas).
+// guest <userData>/remote-approved-guests.json Team Access desktops WE hosted (relay-host.ts).
+// A record only: the desktop relay host never
+// auto-admits from a pin.
+// joinedHost <userData>/remote-approved-hosts.json Desktops WE joined as a guest (relay-client.ts).
+// A record only.
+//
+// They used to be one file, `remote-approved-devices.json`, and that is the bug this split closes:
+// the standing host read every key in it as a paired phone, so a host you once joined, or a guest
+// whose seat you revoked, was silently admitted as a PHONE. `retireLegacyPinFile` removes that file
+// (see there for why nothing in it is carried over).
+//
+// The contents are PUBLIC keys (device box public keys approved once), never credentials.
import { promises as fs } from 'fs'
import path from 'path'
@@ -14,46 +31,105 @@ import {
type ApprovedDevices
} from './approved-devices-core'
-function file(): string {
- return path.join(app.getPath('userData'), 'remote-approved-devices.json')
+export type PinRole = 'phone' | 'guest' | 'joinedHost'
+export const PIN_ROLES: readonly PinRole[] = ['phone', 'guest', 'joinedHost']
+
+const FILE_BY_ROLE: Record<PinRole, string> = {
+ phone: 'remote-approved-phones.json',
+ guest: 'remote-approved-guests.json',
+ joinedHost: 'remote-approved-hosts.json'
}
-/** Load the pinned-device list; returns an empty list when the file is absent; other read/parse failures reject. */
-export async function loadApprovedDevices(): Promise<ApprovedDevices> {
- try {
- return parseApprovedDevices(JSON.parse(await fs.readFile(file(), 'utf-8')))
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
- return emptyApprovedDevices()
+/** The pre-split single store (every role in one file). Only `retireLegacyPinFile` touches it. */
+export const LEGACY_PIN_FILE = 'remote-approved-devices.json'
+
+export function pinFileName(role: PinRole): string {
+ return FILE_BY_ROLE[role]
+}
+
+export interface PinStoreIO {
+ /** Load the pinned-key list; empty when the file is absent; other read/parse failures reject. */
+ load(): Promise<ApprovedDevices>
+ /**
+ * Persist atomically (unique temp + retrying rename, 0600) via `writeFileAtomic`. A failed write
+ * removes its own temp and rethrows, and the OLD file is left byte-for-byte intact —
+ * revocation.ts's `persisted:false` contract depends on both halves.
+ *
+ * No orphan sweep here, unlike the PAT stores or agent.json: these are PUBLIC keys, so a stray
+ * temp is litter rather than a leak.
+ */
+ save(store: ApprovedDevices): Promise<void>
+ /**
+ * Queue the WHOLE read/modify/write, not just the rename: otherwise concurrent approvals lose
+ * pins, and an approval racing a revoke can resurrect the removed key from an obsolete snapshot.
+ * This is an in-process queue, not a cross-process trust-store lock.
+ */
+ update(change: (store: ApprovedDevices) => ApprovedDevices): Promise<void>
+}
+
+function filePath(name: string): string {
+ return path.join(app.getPath('userData'), name)
+}
+
+function createPinStore(role: PinRole): PinStoreIO {
+ const file = (): string => filePath(FILE_BY_ROLE[role])
+ const load = async (): Promise<ApprovedDevices> => {
+ try {
+ return parseApprovedDevices(JSON.parse(await fs.readFile(file(), 'utf-8')))
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
+ return emptyApprovedDevices()
+ }
+ }
+ const save = async (store: ApprovedDevices): Promise<void> => {
+ await writeFileAtomic(file(), JSON.stringify(store), { mode: 0o600 })
+ }
+ let tail: Promise<void> = Promise.resolve()
+ const update = (change: (store: ApprovedDevices) => ApprovedDevices): Promise<void> => {
+ const next = tail.then(async () => {
+ await save(change(await load()))
+ })
+ tail = next.catch(() => {}) // one failed save must not poison later attempts
+ return next
}
+ return { load, save, update }
+}
+
+/** Phones the standing host auto-admits. The ONLY store any code path may auto-approve from. */
+export const phonePins: PinStoreIO = createPinStore('phone')
+/** Team Access desktops this machine hosted. Written on mutual approval; never auto-admits. */
+export const guestPins: PinStoreIO = createPinStore('guest')
+/** Desktops this machine joined as a guest. Written on mutual approval; never auto-admits. */
+export const joinedHostPins: PinStoreIO = createPinStore('joinedHost')
+
+export function pinStore(role: PinRole): PinStoreIO {
+ return role === 'phone' ? phonePins : role === 'guest' ? guestPins : joinedHostPins
}
/**
- * Persist the pinned-device list atomically (unique temp + retrying rename, 0600) via
- * `writeFileAtomic`.
+ * Retire the pre-split `remote-approved-devices.json`. Call once at boot, BEFORE the standing host
+ * starts. Returns how many keys the legacy file held (0 when it was absent), for the log line.
*
- * Production mutations use updateApprovedDevices to serialize read/modify/write. Unique temps
- * still protect atomic publication, including explicit snapshot saves and separate processes.
- * This is an in-process queue, not a cross-process trust-store lock.
+ * NOTHING in it is carried into the phone store, and that is deliberate (fail-closed). The file
+ * mixed three roles with no tag, and nothing on this machine can tell them apart: the phone's relay
+ * box key is never sent at pairing (agent.json records the SSH key and the backend device id, not
+ * the box key), so a legacy key cannot be matched to a paired phone. Carrying the file over as-is
+ * would keep exactly the hole this split closes (a joined host or a revoked guest admitted as a
+ * phone). The cost of dropping it is one SAS comparison per phone, on its next relay connect.
*
- * A failed write removes its own temp and rethrows, and the OLD file is left byte-for-byte
- * intact — revocation.ts's `persisted:false` contract depends on both halves.
- *
- * No orphan sweep here, unlike the PAT stores (src/main/github-control.ts, src/server/github-control.ts)
- * or agent.json (src/main/pairing-service.ts): those orphan temps hold live credentials, but these are
- * PUBLIC keys, so a stray temp is litter rather than a leak.
+ * The file is DELETED rather than left in place so that a downgrade to a pre-split build does not
+ * resurrect the mixed store either. It holds only public keys, so there is nothing to back up.
+ * A read failure other than ENOENT still deletes: an unreadable trust store must not survive to be
+ * read by some later code path, and what it held is being discarded anyway.
*/
-export async function saveApprovedDevices(store: ApprovedDevices): Promise<void> {
- await writeFileAtomic(file(), JSON.stringify(store), { mode: 0o600 })
-}
-
-// Queue the WHOLE read/modify/write, not just rename: otherwise concurrent approvals lose pins,
-// and an approval racing a revoke can resurrect the removed key from an obsolete snapshot.
-let updateTail: Promise<void> = Promise.resolve()
-export function updateApprovedDevices(update: (store: ApprovedDevices) => ApprovedDevices): Promise<void> {
- const next = updateTail.then(async () => {
- await saveApprovedDevices(update(await loadApprovedDevices()))
- })
- updateTail = next.catch(() => {}) // one failed save must not poison later attempts
- return next
+export async function retireLegacyPinFile(): Promise<number> {
+ const legacy = filePath(LEGACY_PIN_FILE)
+ let count = 0
+ try {
+ count = parseApprovedDevices(JSON.parse(await fs.readFile(legacy, 'utf-8'))).pubkeys.length
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return 0
+ }
+ await fs.rm(legacy, { force: true })
+ return count
}
diff --git a/src/main/remote/host-service.presence.test.ts b/src/main/remote/host-service.presence.test.ts
index 37b404a21..16a9014dd 100644
--- a/src/main/remote/host-service.presence.test.ts
+++ b/src/main/remote/host-service.presence.test.ts
@@ -65,7 +65,22 @@ vi.mock('./relay-socket', () => ({
}
}))
+// In-memory pin stores: the revoke primitive (peer-revoke.ts) must not touch the real userData.
+vi.mock('./approved-devices', () => {
+ const mem = () => {
+ let d: { pubkeys: string[] } = { pubkeys: [] }
+ return {
+ load: async () => d,
+ save: async (s: { pubkeys: string[] }) => { d = s },
+ update: async (u: (s: { pubkeys: string[] }) => { pubkeys: string[] }) => { d = u(d) }
+ }
+ }
+ const stores: Record<string, ReturnType<typeof mem>> = { phone: mem(), guest: mem(), joinedHost: mem() }
+ return { PIN_ROLES: ['phone', 'guest', 'joinedHost'], phonePins: stores.phone, pinStore: (r: string) => stores[r] }
+})
+
import { initRemoteHost } from './host-service'
+import { revokeAllPhones, revokePeerKey } from './peer-revoke'
import { IPC } from '../../shared/ipc'
const sentToWin: Array<{ channel: string; args: unknown[] }> = []
@@ -205,3 +220,37 @@ it('a standing phone rejection cannot reject an interactive offer with the same
ipc[IPC.remoteHostReject](null, { id: pendingApprovalId(), pub: 'phone-pub' })
expect(relays[0].closed).toBe(1)
})
+
+describe('interactive host: revocation cuts the session (it is never pinned, so unpinning alone cannot)', () => {
+ it('revoking the phone\'s key closes the approved session and its presence', async () => {
+ makeHost()
+ await start()
+ relays[0].opts.onReady()
+ ipc[IPC.remoteHostApprove](null, { id: pendingApprovalId(), pub: 'phone-pub' })
+ expect(phones()).toBe(1)
+
+ expect(await revokePeerKey('phone-pub', ['phone'])).toEqual({ persisted: true, killed: true })
+ expect(relays[0].closed).toBe(1)
+ expect(phones()).toBe(0)
+ })
+
+ it('a phone "Remove" (revokeAllPhones) also closes a session still awaiting SAS', async () => {
+ makeHost()
+ await start()
+ relays[0].opts.onReady()
+ const id = pendingApprovalId()
+ await revokeAllPhones()
+ expect(relays[0].closed).toBe(1)
+ // The dialog's late Approve is inert: the session is gone.
+ ipc[IPC.remoteHostApprove](null, { id, pub: 'phone-pub' })
+ expect(phones()).toBe(0)
+ })
+
+ it('a different key leaves the session alone', async () => {
+ makeHost()
+ await start()
+ relays[0].opts.onReady()
+ await revokePeerKey('someone-else', ['phone'])
+ expect(relays[0].closed).toBe(0)
+ })
+})
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index d1bef8eb5..5bf5c3c26 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -52,6 +52,7 @@ import { sanitizeClientMutation } from './canvas-sync'
import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'
import { initHostCanvasHub, currentCanvas, subscribeCanvas } from './host-canvas-hub'
import { createPhonePresence, type PhonePresence } from './phone-presence'
+import { registerPeerSessionKiller } from './peer-revoke'
// Default relay endpoint; `NODETERM_RELAY_URL` overrides it (mirrors license.ts's API_BASE /
// CHECKOUT_URL env-override pattern — used both as the dev gate and for local testing).
@@ -1406,6 +1407,13 @@ export function initRemoteHost(
pendingApprovalId = null
}
+ // Revocation (peer-revoke.ts): this session is never pinned, so an unpin alone would never reach
+ // it — a revoke must be able to cut it by the key it authenticated (or is awaiting SAS for).
+ registerPeerSessionKiller('phone', (match) => {
+ const key = session?.peerPublicKeyB64()
+ if (key && match(key)) endSession()
+ })
+
ipcMain.handle(IPC.remoteHostStart, async (): Promise<{ offer: string }> => {
if (!isPremium()) {
throw new Error('Remote access requires nodeterm Pro.')
diff --git a/src/main/remote/peer-revoke.test.ts b/src/main/remote/peer-revoke.test.ts
new file mode 100644
index 000000000..1b1fe0ff3
--- /dev/null
+++ b/src/main/remote/peer-revoke.test.ts
@@ -0,0 +1,110 @@
+// The one revoke primitive: unpin from exactly the named role stores, then run EVERY registered
+// host killer — and report, never swallow, a leg that did not happen.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ApprovedDevices } from './approved-devices-core'
+
+const disks: Record<string, ApprovedDevices> = {}
+const failUpdate = new Set<string>()
+vi.mock('./approved-devices', () => {
+ const mem = (role: string) => ({
+ load: async () => (disks[role] ??= { pubkeys: [] }),
+ save: async (s: ApprovedDevices) => { disks[role] = s },
+ update: async (u: (s: ApprovedDevices) => ApprovedDevices) => {
+ if (failUpdate.has(role)) throw Object.assign(new Error('fixture'), { code: 'EACCES' })
+ disks[role] = u((disks[role] ??= { pubkeys: [] }))
+ }
+ })
+ const stores: Record<string, ReturnType<typeof mem>> = { phone: mem('phone'), guest: mem('guest'), joinedHost: mem('joinedHost') }
+ return { PIN_ROLES: ['phone', 'guest', 'joinedHost'], phonePins: stores.phone, pinStore: (r: string) => stores[r] }
+})
+
+import {
+ killPeerSessions,
+ registerPeerSessionKiller,
+ revokeAllPhones,
+ revokePeerKey
+} from './peer-revoke'
+
+const unregister: Array<() => void> = []
+beforeEach(() => {
+ for (const k of Object.keys(disks)) delete disks[k]
+ failUpdate.clear()
+ while (unregister.length) unregister.pop()!()
+})
+
+/** A fake host holding sessions by key; returns which keys it was told to cut. */
+function fakeHost(surface: 'phone' | 'desktop', keys: string[]) {
+ const live = new Set(keys)
+ const cut: string[] = []
+ unregister.push(
+ registerPeerSessionKiller(surface, (match) => {
+ for (const k of [...live]) if (match(k)) { live.delete(k); cut.push(k) }
+ })
+ )
+ return { live, cut }
+}
+
+describe('revokePeerKey', () => {
+ it('unpins from the named roles only, and cuts that key on EVERY surface', async () => {
+ disks.phone = { pubkeys: ['k', 'other'] }
+ disks.guest = { pubkeys: ['k'] }
+ disks.joinedHost = { pubkeys: ['k'] }
+ const standing = fakeHost('phone', ['k', 'other'])
+ const team = fakeHost('desktop', ['k'])
+
+ expect(await revokePeerKey('k', ['guest'])).toEqual({ persisted: true, killed: true })
+ expect(disks.guest.pubkeys).toEqual([])
+ expect(disks.phone.pubkeys).toEqual(['k', 'other'])
+ expect(disks.joinedHost.pubkeys).toEqual(['k'])
+ expect(standing.cut).toEqual(['k'])
+ expect(team.cut).toEqual(['k'])
+ expect([...standing.live]).toEqual(['other'])
+ })
+
+ it('a failed unpin still cuts the live session and reports persisted:false', async () => {
+ failUpdate.add('phone')
+ disks.guest = { pubkeys: ['k'] }
+ const host = fakeHost('phone', ['k'])
+ expect(await revokePeerKey('k', ['phone', 'guest'])).toEqual({ persisted: false, killed: true })
+ expect(host.cut).toEqual(['k'])
+ expect(disks.guest.pubkeys).toEqual([]) // the other stores are still attempted
+ })
+
+ it('one killer throwing does not spare the sessions the others hold, and reports killed:false', async () => {
+ unregister.push(registerPeerSessionKiller('phone', () => { throw new Error('boom') }))
+ const team = fakeHost('desktop', ['k'])
+ expect(await revokePeerKey('k', ['phone'])).toEqual({ persisted: true, killed: false })
+ expect(team.cut).toEqual(['k'])
+ })
+})
+
+describe('revokeAllPhones (phone "Remove")', () => {
+ it('clears every phone pin and cuts every phone session, leaving desktop peers and stores alone', async () => {
+ disks.phone = { pubkeys: ['p1', 'p2'] }
+ disks.guest = { pubkeys: ['g'] }
+ const standing = fakeHost('phone', ['p1', 'never-pinned'])
+ const team = fakeHost('desktop', ['g'])
+ expect(await revokeAllPhones()).toEqual({ persisted: true, killed: true })
+ expect(disks.phone.pubkeys).toEqual([])
+ expect(disks.guest.pubkeys).toEqual(['g'])
+ expect(standing.cut.sort()).toEqual(['never-pinned', 'p1'])
+ expect(team.cut).toEqual([])
+ })
+
+ it('reports a pin store it could not write', async () => {
+ failUpdate.add('phone')
+ const standing = fakeHost('phone', ['p1'])
+ expect(await revokeAllPhones()).toEqual({ persisted: false, killed: true })
+ expect(standing.cut).toEqual(['p1'])
+ })
+})
+
+describe('killPeerSessions', () => {
+ it('filters by surface', () => {
+ const a = fakeHost('phone', ['x'])
+ const b = fakeHost('desktop', ['x'])
+ killPeerSessions(() => true, ['desktop'])
+ expect(a.cut).toEqual([])
+ expect(b.cut).toEqual(['x'])
+ })
+})
diff --git a/src/main/remote/peer-revoke.ts b/src/main/remote/peer-revoke.ts
new file mode 100644
index 000000000..9408f974f
--- /dev/null
+++ b/src/main/remote/peer-revoke.ts
@@ -0,0 +1,117 @@
+// THE revoke primitive for relay peers: unpin a box public key AND close every live session that
+// key authenticated. Every revoke path goes through `revokePeerKey` — phone "Remove"
+// (pairing-service.ts), the Team Access seat revoke (relay-host-service.ts) and the
+// `remote:revoke-peer` control channel (index.ts) — so none of them can do half of it.
+//
+// Why both halves (revocation.ts states it in full): unpinning refuses only the NEXT handshake; an
+// open relay socket keeps its shell until it drops on its own. And why a REGISTRY of killers: the
+// sessions a key can hold live in three unrelated places — the standing phone host's pool
+// (standing-host.ts), the interactive phone host's single session (host-service.ts
+// `initRemoteHost`) and the desktop relay host's `live` set (relay-host.ts). A revoke that knows
+// only one of them (the old `onRevoke: killRelayHostsByPeerKey`) leaves the other two serving.
+// Each host registers its killer when it is wired; `killPeerSessionsByKey` runs them all.
+import { createRevoker, type RevokeResult } from './revocation'
+import { pinStore, type PinRole } from './approved-devices'
+
+/** Which kind of peer a host serves: the phone vocabulary (standing + interactive phone hosts) or
+ * the desktop Team Access vocabulary (relay-host.ts). */
+export type PeerSurface = 'phone' | 'desktop'
+
+/**
+ * Close every live session this host holds whose peer key satisfies `match` — bridged, approved,
+ * or still awaiting its SAS decision (a pending consent must not outlive the revoke either).
+ */
+export type PeerSessionKiller = (match: (peerKeyB64: string) => boolean) => void
+
+const killers = new Map<PeerSessionKiller, PeerSurface>()
+
+/** Register a host's killer. Returns the unregister function. */
+export function registerPeerSessionKiller(surface: PeerSurface, kill: PeerSessionKiller): () => void {
+ killers.set(kill, surface)
+ return () => {
+ killers.delete(kill)
+ }
+}
+
+/**
+ * Run the registered killers (of the given surfaces). One killer throwing must not spare the
+ * sessions the others hold, so all run first; then the first error is rethrown so the caller
+ * (createRevoker) reports `killed:false` rather than a cut that did not fully happen.
+ */
+export function killPeerSessions(
+ match: (peerKeyB64: string) => boolean,
+ surfaces: readonly PeerSurface[] = ['phone', 'desktop']
+): void {
+ let failure: unknown = null
+ for (const [kill, surface] of [...killers]) {
+ if (!surfaces.includes(surface)) continue
+ try {
+ kill(match)
+ } catch (err) {
+ failure ??= err
+ }
+ }
+ if (failure) throw failure
+}
+
+/** Close every live session, on every surface, authenticated by exactly this key. */
+export function killPeerSessionsByKey(peerKeyB64: string): void {
+ if (!peerKeyB64) return
+ killPeerSessions((k) => k === peerKeyB64)
+}
+
+/**
+ * Unpin `peerKeyB64` from each named role store, then close every live session it holds. The kill
+ * fires even when the unpin failed (a persistence error must never leave a revoked peer connected);
+ * the result reports both legs, per revocation.ts's contract.
+ */
+export function revokePeerKey(peerKeyB64: string, roles: readonly PinRole[]): Promise<RevokeResult> {
+ const stores = roles.map(pinStore)
+ return createRevoker({
+ // Unused: `update` is always provided, and createRevoker prefers it.
+ load: () => Promise.reject(new Error('unused')),
+ save: () => Promise.reject(new Error('unused')),
+ async update(change) {
+ // Every store is attempted; the first failure is rethrown afterwards (persisted:false).
+ let failure: unknown = null
+ for (const store of stores) {
+ try {
+ await store.update(change)
+ } catch (err) {
+ failure ??= err
+ }
+ }
+ if (failure) throw failure
+ },
+ onRevoke: killPeerSessionsByKey
+ }).revoke(peerKeyB64)
+}
+
+/**
+ * What a phone "Remove" does: unpin EVERY phone the standing host has pinned and close EVERY live
+ * phone relay session (standing and interactive hosts, approved or awaiting SAS). Desktop Team
+ * Access sessions are not touched.
+ *
+ * All phones, on purpose: the phone's relay box key is never sent at pairing, so nothing on this
+ * machine maps an agent.json device to the key it presents over the relay — and a phone approved on
+ * the interactive host is never pinned at all. Unpinning or cutting a guess could leave the removed
+ * phone connected; doing all of them costs every OTHER phone a reconnect and one SAS comparison.
+ * Fail-closed wins.
+ */
+export async function revokeAllPhones(): Promise<RevokeResult> {
+ let persisted = true
+ try {
+ await pinStore('phone').update(() => ({ pubkeys: [] }))
+ } catch {
+ // The old file is left intact on a failed write (writeFileAtomic): the pins may survive, so
+ // the caller must keep the device listed and let the owner retry.
+ persisted = false
+ }
+ let killed = true
+ try {
+ killPeerSessions(() => true, ['phone'])
+ } catch {
+ killed = false
+ }
+ return { persisted, killed }
+}
diff --git a/src/main/remote/relay-bookmarks.ts b/src/main/remote/relay-bookmarks.ts
index e69c813d7..97167a1e9 100644
--- a/src/main/remote/relay-bookmarks.ts
+++ b/src/main/remote/relay-bookmarks.ts
@@ -8,7 +8,7 @@
// `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.
+// phone pin store (approved-devices.ts), which counts paired phones.
import { constants as fsConstants, promises as fs } from 'node:fs'
import { dirname } from 'node:path'
import { writeFileAtomic } from '../../core/fs-atomic'
diff --git a/src/main/remote/relay-client.test.ts b/src/main/remote/relay-client.test.ts
index 575805816..50c93342c 100644
--- a/src/main/remote/relay-client.test.ts
+++ b/src/main/remote/relay-client.test.ts
@@ -50,13 +50,33 @@ vi.mock('../main-window', () => ({
// OTHER end's key here.
import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'
let disk: ApprovedDevices = emptyApprovedDevices()
-vi.mock('./approved-devices', () => ({
- updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },
- loadApprovedDevices: async () => disk,
- saveApprovedDevices: async (s: ApprovedDevices) => {
- disk = s
+// Per-role pin stores (approved-devices.ts), in memory. The 'joinedHost' store — the one this module
+// must write — is `disk`; every other role lives in `otherPins`, so a pin landing in the WRONG
+// store is visible to the assertions instead of indistinguishable from the right one.
+const otherPins: Record<string, ApprovedDevices> = {}
+vi.mock('./approved-devices', () => {
+ const mem = (role: string) => {
+ const get = (): ApprovedDevices => (role === 'joinedHost' ? disk : (otherPins[role] ??= { pubkeys: [] }))
+ const set = (s: ApprovedDevices): void => {
+ if (role === 'joinedHost') disk = s
+ else otherPins[role] = s
+ }
+ return {
+ load: async () => get(),
+ save: async (s: ApprovedDevices) => set(s),
+ update: role === 'joinedHost' ? async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get())) : async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get()))
+ }
}
-}))
+ const stores: Record<string, ReturnType<typeof mem>> = { phone: mem('phone'), guest: mem('guest'), joinedHost: mem('joinedHost') }
+ return {
+ PIN_ROLES: ['phone', 'guest', 'joinedHost'],
+ phonePins: stores.phone,
+ guestPins: stores.guest,
+ joinedHostPins: stores.joinedHost,
+ pinStore: (r: string) => stores[r],
+ retireLegacyPinFile: async () => 0
+ }
+})
import { connectRelayHost, type RelayHostSession } from './relay-host'
import { connectRelayClient, type RelayClientSession } from './relay-client'
@@ -177,6 +197,7 @@ beforeEach(() => {
h.sent = []
h.clientIds = [1]
disk = emptyApprovedDevices()
+ for (const k of Object.keys(otherPins)) delete otherPins[k]
gone = []
platform = electronPlatform()
initPlatform(platform)
@@ -214,6 +235,20 @@ describe('relay client — SAS + mutual approval', () => {
expect(p.host.clientId()).not.toBeNull()
})
+ it('each end pins the other in ITS role store — never in the phone store the standing host auto-admits from', async () => {
+ const p = pairHostAndClient()
+ await p.openMutually()
+ const hostKey = p.client.peerKeyB64()
+ // The client (us, joining) pinned the HOST's key as a joined host; the host (the other desktop)
+ // pinned OUR key as a guest. Two distinct keys, each in its own role store.
+ await vi.waitFor(() => expect(disk.pubkeys).toHaveLength(1))
+ await vi.waitFor(() => expect(otherPins.guest?.pubkeys).toEqual([p.host.peerKeyB64()]))
+ expect(disk.pubkeys).not.toContain(p.host.peerKeyB64())
+ expect(disk.pubkeys).toEqual([hostKey])
+ // …and neither role ever reaches the phone store.
+ expect(otherPins.phone?.pubkeys ?? []).toEqual([])
+ })
+
it('ONE side confirming is not enough — the client stays closed', async () => {
const p = pairHostAndClient()
p.client.confirm() // only this human
diff --git a/src/main/remote/relay-client.ts b/src/main/remote/relay-client.ts
index 9de8ff90c..a5fa8f000 100644
--- a/src/main/remote/relay-client.ts
+++ b/src/main/remote/relay-client.ts
@@ -1,14 +1,14 @@
// The desktop relay client: a thin wrapper over the core client (src/core/relay/relay-client.ts),
// which holds the whole mechanism and its SECURITY obligations — read them there before touching
// any call site. The only thing this layer adds is WHERE a mutual approval is pinned: the desktop's
-// approved-devices store, exactly as before the client moved to core (docs/hosted-team-relay.md).
+// joined-hosts pin store — never the phone store the standing host auto-admits from.
import {
connectRelayClient as connectCoreRelayClient,
type RelayClientSession,
type ConnectRelayClientOptions as CoreOptions
} from '../../core/relay/relay-client'
import { recordApproval } from '../../core/relay/mutual-approval-core'
-import { updateApprovedDevices } from './approved-devices'
+import { joinedHostPins } from './approved-devices'
export type { RelayClientSession }
export type ConnectRelayClientOptions = Omit<CoreOptions, 'pins'>
@@ -17,7 +17,7 @@ export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClient
return connectCoreRelayClient({
...opts,
// recordApproval refuses unless BOTH confirmed and pins only the key carried by the state; the
- // serialized updateApprovedDevices queue keeps concurrent approvals and a racing revoke intact.
- pins: { record: (pinned) => updateApprovedDevices((store) => recordApproval(store, pinned)) }
+ // serialized update queue keeps concurrent approvals and a racing revoke intact.
+ pins: { record: (pinned) => joinedHostPins.update((store) => recordApproval(store, pinned)) }
})
}
diff --git a/src/main/remote/relay-host-service.test.ts b/src/main/remote/relay-host-service.test.ts
index f686f00a3..c981e44f1 100644
--- a/src/main/remote/relay-host-service.test.ts
+++ b/src/main/remote/relay-host-service.test.ts
@@ -37,13 +37,33 @@ vi.mock('../main-window', () => ({
import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'
let disk: ApprovedDevices = emptyApprovedDevices()
-vi.mock('./approved-devices', () => ({
- updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },
- loadApprovedDevices: async () => disk,
- saveApprovedDevices: async (s: ApprovedDevices) => {
- disk = s
+// Per-role pin stores (approved-devices.ts), in memory. The 'guest' store — the one this module
+// must write — is `disk`; every other role lives in `otherPins`, so a pin landing in the WRONG
+// store is visible to the assertions instead of indistinguishable from the right one.
+const otherPins: Record<string, ApprovedDevices> = {}
+vi.mock('./approved-devices', () => {
+ const mem = (role: string) => {
+ const get = (): ApprovedDevices => (role === 'guest' ? disk : (otherPins[role] ??= { pubkeys: [] }))
+ const set = (s: ApprovedDevices): void => {
+ if (role === 'guest') disk = s
+ else otherPins[role] = s
+ }
+ return {
+ load: async () => get(),
+ save: async (s: ApprovedDevices) => set(s),
+ update: role === 'guest' ? async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get())) : async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get()))
+ }
}
-}))
+ const stores: Record<string, ReturnType<typeof mem>> = { phone: mem('phone'), guest: mem('guest'), joinedHost: mem('joinedHost') }
+ return {
+ PIN_ROLES: ['phone', 'guest', 'joinedHost'],
+ phonePins: stores.phone,
+ guestPins: stores.guest,
+ joinedHostPins: stores.joinedHost,
+ pinStore: (r: string) => stores[r],
+ retireLegacyPinFile: async () => 0
+ }
+})
// Keep `connectRelayHost` (the reviewed handshake) REAL — the crypto tests below exercise it for
// real — but spy `killRelayHostsByPeerKey` so the revoke test can assert the identity-based cut is
@@ -172,6 +192,7 @@ function wireHost(): {
})
peerSocket = sock
peerGate = createTrustGate({
+ role: 'guest',
peerKeyB64: sock.peerPublicKeyB64()!,
sessionId: 'peer-side',
sas: () => sock.sas(),
@@ -218,6 +239,7 @@ beforeEach(() => {
h.handlers = {}
h.sent = []
disk = emptyApprovedDevices()
+ for (const k of Object.keys(otherPins)) delete otherPins[k]
platform = electronPlatform()
initPlatform(platform)
wirePeerRegistry({
@@ -603,11 +625,18 @@ describe('initRelayHost — Team Access revoke + seat freeing', () => {
// At cap: a fresh invite is refused...
await expect(host.invite()).rejects.toThrow(E_SEATS_FULL)
+ // Both peers were mutually approved at some point: their keys sit in the GUEST store.
+ disk = { pubkeys: ['peer-0', 'peer-1'] }
+ otherPins.phone = { pubkeys: ['a-real-phone'] }
+
h.handlers[IPC.relayHostRevoke]({}, { id: id0 })
// Cut by the revoked peer's identity only.
expect(killRelayHostsByPeerKey).toHaveBeenCalledTimes(1)
expect(killRelayHostsByPeerKey).toHaveBeenCalledWith('peer-0')
+ // …and its pin is gone from the guest store (and only its pin; the phone store is not touched).
+ await vi.waitFor(() => expect(disk.pubkeys).toEqual(['peer-1']))
+ expect(otherPins.phone.pubkeys).toEqual(['a-real-phone'])
// The renderer is told this seat closed.
expect(openedIds(IPC.relayHostClosed).at(-1)).toEqual({ id: id0 })
diff --git a/src/main/remote/relay-host-service.ts b/src/main/remote/relay-host-service.ts
index 71b0144fb..65d8cbd11 100644
--- a/src/main/remote/relay-host-service.ts
+++ b/src/main/remote/relay-host-service.ts
@@ -22,8 +22,9 @@
// cannot serve a peer early even by accident, because it holds none of the machinery that serves.
//
// REVOCATION reaches sessions started here for free: `connectRelayHost` adds every session to its own
-// module-level `live` set, and index.ts's revoker calls `killRelayHostsByPeerKey` (relay-host.ts)
-// against THAT set — independent of the bookkeeping below. `relay:host:revoke` here uses the same cut.
+// module-level `live` set, and relay-host.ts registers a killer over THAT set with the one revoke
+// primitive (peer-revoke.ts) — independent of the bookkeeping below. `relay:host:revoke` here uses
+// the same primitive, and also unpins the guest's key.
import { randomUUID } from 'crypto'
import { ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
@@ -36,6 +37,7 @@ import { loadOrCreatePeerKeyPair } from './peer-identity'
import { isPremium as licenseIsPremium, getStoredEntitlement, licensedSeats as licenseSeats } from '../../core/license'
import { RELAY_URL, relayAllowed as hostRelayAllowed, mintPairingToken } from './host-service'
import { canAcceptSeat } from './seat-cap'
+import { revokePeerKey } from './peer-revoke'
/** Thrown (as an Error message) when a new invite would exceed the licensed seat cap. The renderer
* maps it to "All seats in use — add a seat." Host-side/UX enforcement only (see below). */
@@ -231,16 +233,24 @@ export function initRelayHost(
const entry = msg?.id ? byId.get(msg.id) : undefined
if (!entry) return
// A reserved-but-not-yet-open seat has no live socket to cut (`session` null, or a session with no
- // peer key yet) — freeing the reservation is all that's owed. A live peer is cut by IDENTITY, the
- // same primitive index.ts's 4c revoker uses (killRelayHostsByPeerKey, relay-host.ts): it closes
- // every live session holding that key, the right "remove this device" semantic. Host-side revoke +
- // the seat cap are UX/host enforcement, NOT a server-guaranteed limit (v2 = server-side). On the
- // desktop relay path a pin never auto-admits (isPinned is phone-only), so cutting the socket
- // already forces a fresh SAS+consent re-pair — no separate unpin is needed.
+ // peer key yet) — freeing the reservation is all that's owed. A live peer is cut by IDENTITY:
+ // `killRelayHostsByPeerKey` closes every live session holding that key, synchronously, before any
+ // await. Then the revoke primitive (peer-revoke.ts) unpins the key from the GUEST store and runs
+ // the cut again across every host surface (idempotent). The unpin matters even though a desktop
+ // guest pin never auto-admits: it used to share a file with the phone pins, which the standing
+ // host DID auto-admit from, so a revoked guest stayed a silently-admitted "phone". The stores are
+ // split now (approved-devices.ts), and a revoked seat leaves no pin behind in any of them.
+ // Host-side revoke + the seat cap are UX/host enforcement, NOT a server-guaranteed limit
+ // (v2 = server-side).
const peerKeyB64 = entry.session?.peerKeyB64()
// killRelayHostsByPeerKey → session.close() does NOT fire our `onClose` (that runs only on a wire
// drop, not a local close), so free the seat and notify the renderer here.
- if (peerKeyB64) killRelayHostsByPeerKey(peerKeyB64)
+ if (peerKeyB64) {
+ killRelayHostsByPeerKey(peerKeyB64)
+ void revokePeerKey(peerKeyB64, ['guest']).then((r) => {
+ if (!r.persisted || !r.killed) console.warn('[relay-host] seat revoke incomplete', r)
+ })
+ }
byId.delete(msg.id!)
send(IPC.relayHostClosed, { id: msg.id })
})
diff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.ts
index 799fce835..32104f3ba 100644
--- a/src/main/remote/relay-host.test.ts
+++ b/src/main/remote/relay-host.test.ts
@@ -51,15 +51,36 @@ vi.mock('../main-window', () => ({
// The on-disk pin store, in memory (relay-trust's default load/save path).
import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'
let disk: ApprovedDevices = emptyApprovedDevices()
-vi.mock('./approved-devices', () => ({
- updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },
- loadApprovedDevices: async () => disk,
- saveApprovedDevices: async (s: ApprovedDevices) => {
- disk = s
+// Per-role pin stores (approved-devices.ts), in memory. The 'guest' store — the one this module
+// must write — is `disk`; every other role lives in `otherPins`, so a pin landing in the WRONG
+// store is visible to the assertions instead of indistinguishable from the right one.
+const otherPins: Record<string, ApprovedDevices> = {}
+vi.mock('./approved-devices', () => {
+ const mem = (role: string) => {
+ const get = (): ApprovedDevices => (role === 'guest' ? disk : (otherPins[role] ??= { pubkeys: [] }))
+ const set = (s: ApprovedDevices): void => {
+ if (role === 'guest') disk = s
+ else otherPins[role] = s
+ }
+ return {
+ load: async () => get(),
+ save: async (s: ApprovedDevices) => set(s),
+ update: role === 'guest' ? async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get())) : async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get()))
+ }
}
-}))
+ const stores: Record<string, ReturnType<typeof mem>> = { phone: mem('phone'), guest: mem('guest'), joinedHost: mem('joinedHost') }
+ return {
+ PIN_ROLES: ['phone', 'guest', 'joinedHost'],
+ phonePins: stores.phone,
+ guestPins: stores.guest,
+ joinedHostPins: stores.joinedHost,
+ pinStore: (r: string) => stores[r],
+ retireLegacyPinFile: async () => 0
+ }
+})
import { connectRelayHost, killRelayHostsByPeerKey, type RelayHostSession } from './relay-host'
+import { revokePeerKey } from './peer-revoke'
import { connectRelay, type RelayTransport } from './relay-socket'
import { createTrustGate, type TrustGate } from './relay-trust'
import { genKeyPair, publicKeyToB64 } from './e2ee'
@@ -185,6 +206,7 @@ function openHostAgainstFakeRelay(opts?: {
})
peerGate = createTrustGate({
+ role: 'guest',
peerKeyB64: peerSocket.peerPublicKeyB64()!,
sessionId: 'peer-side',
sas: () => peerSocket.sas(),
@@ -222,6 +244,7 @@ beforeEach(() => {
h.sent = []
h.clientIds = [1] // the main window (a webContents client)
disk = emptyApprovedDevices()
+ for (const k of Object.keys(otherPins)) delete otherPins[k]
flow = []
gone = []
capture = 'CURRENT SCREEN'
@@ -631,4 +654,18 @@ describe('relay host — teardown mirrors src/server/ws.ts', () => {
// A stranger's key cuts nothing.
killRelayHostsByPeerKey('some-other-key')
})
+
+ it('the shared revoke primitive (peer-revoke.ts) reaches Team Access sessions and unpins the guest', async () => {
+ const s = openHostAgainstFakeRelay()
+ await s.openMutually()
+ const id = s.session.clientId()!
+ await vi.waitFor(() => expect(disk.pubkeys).toEqual([s.peerKeyB64])) // pinned as a GUEST
+ expect(otherPins.phone?.pubkeys ?? []).toEqual([]) // never as a phone
+
+ expect(await revokePeerKey(s.peerKeyB64, ['guest'])).toEqual({ persisted: true, killed: true })
+
+ expect(disk.pubkeys).toEqual([])
+ expect(peerRegistry().ids()).not.toContain(id)
+ expect(gone).toEqual([id])
+ })
})
diff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.ts
index f07b69bb6..086720f3a 100644
--- a/src/main/remote/relay-host.ts
+++ b/src/main/remote/relay-host.ts
@@ -27,10 +27,11 @@
// handshake, the trust gate, the tunnel dispatch and every SECURITY obligation above. This file is
// the desktop's side of its seam — the `PeerAttach` that mints a ClientId, registers the peer sink
// and joins presence, the electronPlatform dispatch/cast, and where a mutual approval is pinned
-// (approved-devices). It passes no hooks and no autoApprove, so the desktop takes the unhooked path.
+// (the guest pin store). It passes no hooks and no autoApprove, so the desktop takes the unhooked path.
import {
connectRelayHost as connectCoreRelayHost,
killRelayHostsByPeerKey,
+ killRelayHostsWhere,
type RelayHostSession as CoreRelayHostSession,
type ConnectRelayHostOptions as CoreOptions,
type PeerAttach
@@ -40,10 +41,15 @@ import { recordApproval } from '../../core/relay/mutual-approval-core'
import type { ElectronPlatform } from '../platform-electron'
import { registerPeerSink, unregisterPeerSink } from '../peer-registry'
import { allocateRelayClientId, presenceHub } from '../../core/presence/hub'
-import { updateApprovedDevices } from './approved-devices'
+import { guestPins } from './approved-devices'
+import { registerPeerSessionKiller } from './peer-revoke'
export { killRelayHostsByPeerKey }
+// Every live Team Access session is reachable by the one revoke primitive (peer-revoke.ts). The
+// `live` set is module-level in core, so one registration at import covers every session.
+registerPeerSessionKiller('desktop', (match) => killRelayHostsWhere(match))
+
/** The desktop's view of a hosting session: the core session minus `deny`. Team Access never refuses
* a peer with a reason (a revoke closes it), so the desktop surface stays exactly what it was. */
export type RelayHostSession = Omit<CoreRelayHostSession, 'deny'>
@@ -71,11 +77,12 @@ function desktopAttach(platform: ElectronPlatform): PeerAttach {
}
}
-/** Desktop pins: the phone/desktop approved-devices store, exactly as before the gate moved to core.
- * recordApproval refuses unless BOTH confirmed and pins only the key carried by the state; the
- * serialized updateApprovedDevices queue keeps concurrent approvals and a racing revoke intact. */
+/** Desktop pins: a guest WE hosted goes to the GUEST store — never the phone store, which the
+ * standing host auto-admits from (approved-devices.ts). recordApproval refuses unless BOTH confirmed
+ * and pins only the key carried by the state; the serialized update queue keeps concurrent
+ * approvals and a racing revoke intact. */
function desktopPins(): PinStore {
- return { record: (pinned) => updateApprovedDevices((store) => recordApproval(store, pinned)) }
+ return { record: (pinned) => guestPins.update((store) => recordApproval(store, pinned)) }
}
export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSession {
diff --git a/src/main/remote/relay-trust.test.ts b/src/main/remote/relay-trust.test.ts
index d4c0eebb4..772e3cdd3 100644
--- a/src/main/remote/relay-trust.test.ts
+++ b/src/main/remote/relay-trust.test.ts
@@ -19,17 +19,39 @@ import { TRUST_CONFIRM, createTrustGate, type TrustGate } from './relay-trust'
// ./approved-devices — mocking the module (rather than injecting fakes) means these tests exercise
// the production default path, not a test-only branch.
let disk: ApprovedDevices = emptyApprovedDevices()
-vi.mock('./approved-devices', () => ({
- updateApprovedDevices: async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) },
- loadApprovedDevices: async () => disk,
- saveApprovedDevices: async (s: ApprovedDevices) => {
- disk = s
+// Per-role pin stores (approved-devices.ts), in memory. The 'guest' store — the one this module
+// must write — is `disk`; every other role lives in `otherPins`, so a pin landing in the WRONG
+// store is visible to the assertions instead of indistinguishable from the right one.
+const otherPins: Record<string, ApprovedDevices> = {}
+vi.mock('./approved-devices', () => {
+ const mem = (role: string) => {
+ const get = (): ApprovedDevices => (role === 'guest' ? disk : (otherPins[role] ??= { pubkeys: [] }))
+ const set = (s: ApprovedDevices): void => {
+ if (role === 'guest') disk = s
+ else otherPins[role] = s
+ }
+ return {
+ load: async () => get(),
+ save: async (s: ApprovedDevices) => set(s),
+ update: role === 'guest' ? async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get())) : async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get()))
+ }
}
-}))
-import { loadApprovedDevices } from './approved-devices'
+ const stores: Record<string, ReturnType<typeof mem>> = { phone: mem('phone'), guest: mem('guest'), joinedHost: mem('joinedHost') }
+ return {
+ PIN_ROLES: ['phone', 'guest', 'joinedHost'],
+ phonePins: stores.phone,
+ guestPins: stores.guest,
+ joinedHostPins: stores.joinedHost,
+ pinStore: (r: string) => stores[r],
+ retireLegacyPinFile: async () => 0
+ }
+})
+import { guestPins } from './approved-devices'
+const loadApprovedDevices = (): Promise<ApprovedDevices> => guestPins.load()
beforeEach(() => {
disk = emptyApprovedDevices()
+ for (const k of Object.keys(otherPins)) delete otherPins[k]
})
// A pair of in-process transports wired host<->client, PLUS the relay's own injection ports: the
@@ -128,6 +150,7 @@ function bridgedPair(isolate = false): {
}
const gateFor = (socket: RelaySocket, tag: 'host' | 'peer'): TrustGate =>
createTrustGate({
+ role: 'guest',
peerKeyB64: socket.peerPublicKeyB64()!,
sessionId: `session-${tag}`,
sas: () => socket.sas(),
@@ -260,6 +283,7 @@ describe('obligation (a): only the encrypted tunnel can confirm the peer', () =>
})
hostGate = createTrustGate({
+ role: 'guest',
peerKeyB64: hostSocket.peerPublicKeyB64()!,
sessionId: 'session-host',
sas: () => hostSocket.sas(),
@@ -319,6 +343,7 @@ describe('obligation (b): exactly one MutualApproval per pairing attempt', () =>
const sent: string[] = []
const opened: string[] = []
const gate = createTrustGate({
+ role: 'guest',
peerKeyB64: 'PEER',
sessionId: 's1',
sas: () => '111 222',
@@ -339,6 +364,7 @@ describe('obligation (b): exactly one MutualApproval per pairing attempt', () =>
it('ignores tunnel frames that are not a trust confirm (they stay available to the RPC dispatcher)', () => {
const gate = createTrustGate({
+ role: 'guest',
peerKeyB64: 'PEER',
sessionId: 's1',
sas: () => null,
diff --git a/src/main/remote/relay-trust.ts b/src/main/remote/relay-trust.ts
index d768da9b0..412ccde15 100644
--- a/src/main/remote/relay-trust.ts
+++ b/src/main/remote/relay-trust.ts
@@ -1,7 +1,8 @@
// The desktop trust gate: a thin wrapper over the core gate (src/core/relay/relay-trust.ts), which
// holds the whole mechanism and its SECURITY obligations (a) and (b) — read them there before
// touching any call site. The only thing this layer adds is WHERE a mutual approval is pinned: the
-// desktop's approved-devices store, exactly as before the gate moved to core (docs/hosted-team-relay.md).
+// store for the ROLE the peer plays (approved-devices.ts). Never the phone store — that one is read
+// by the standing host to auto-admit, and a desktop peer must never land in it.
import {
createTrustGate as createCoreTrustGate,
TRUST_CONFIRM,
@@ -13,31 +14,35 @@ import {
type TrustDeniedReason
} from '../../core/relay/relay-trust'
import { recordApproval } from '../../core/relay/mutual-approval-core'
-import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } from './approved-devices'
+import { pinStore } from './approved-devices'
import type { ApprovedDevices } from './approved-devices-core'
export { TRUST_CONFIRM, TRUST_DENIED, deniedFrame, parseDenied, type TrustGate, type TrustDeniedReason }
export interface TrustGateOptions extends Omit<CoreTrustGateOptions, 'pins'> {
+ /** Which desktop store a mutual approval lands in: a guest WE host, or a host WE joined. There is
+ * deliberately no 'phone' here — phones are pinned only by the standing host's SAS approval. */
+ role: 'guest' | 'joinedHost'
load?: () => Promise<ApprovedDevices>
save?: (s: ApprovedDevices) => Promise<void>
}
-/** Desktop trust gate: pins go to the phone/desktop approved-devices store, exactly as before. */
+/** Desktop trust gate: pins go to the role's own store (see `TrustGateOptions.role`). */
export function createTrustGate(opts: TrustGateOptions): TrustGate {
- const { load, save, ...rest } = opts
+ const { load, save, role, ...rest } = opts
+ const store = pinStore(role)
return createCoreTrustGate({
...rest,
pins: {
// recordApproval refuses unless BOTH confirmed, and pins only the key carried by the state.
- // Injected load/save keep their read-then-write path; the default goes through the serialized
- // updateApprovedDevices queue, so concurrent approvals never lose pins and a racing revoke is
+ // Injected load/save keep their read-then-write path; the default goes through the role
+ // store's serialized update queue, so concurrent approvals never lose pins and a racing revoke is
// never undone from a stale snapshot.
async record(pinned) {
if (load || save) {
- await (save ?? saveApprovedDevices)(recordApproval(await (load ?? loadApprovedDevices)(), pinned))
+ await (save ?? store.save)(recordApproval(await (load ?? store.load)(), pinned))
} else {
- await updateApprovedDevices((store) => recordApproval(store, pinned))
+ await store.update((s) => recordApproval(s, pinned))
}
}
}
diff --git a/src/main/remote/standing-host.test.ts b/src/main/remote/standing-host.test.ts
index 910c33f0e..2111a99df 100644
--- a/src/main/remote/standing-host.test.ts
+++ b/src/main/remote/standing-host.test.ts
@@ -40,11 +40,33 @@ vi.mock('./host-canvas-hub', () => ({
let disk: ApprovedDevices = { pubkeys: [] }
const persist = vi.fn(async (update: (s: ApprovedDevices) => ApprovedDevices) => { disk = update(disk) })
vi.mock('./relay-advertise', () => ({ writeRelayAdvertisement: async () => {}, removeRelayAdvertisement: async () => {} }))
-vi.mock('./approved-devices', () => ({
- updateApprovedDevices: (update: (s: ApprovedDevices) => ApprovedDevices) => persist(update),
- loadApprovedDevices: async () => disk,
- saveApprovedDevices: async () => {}
-}))
+// Per-role pin stores (approved-devices.ts), in memory. The 'phone' store — the one this module
+// must write — is `disk`; every other role lives in `otherPins`, so a pin landing in the WRONG
+// store is visible to the assertions instead of indistinguishable from the right one.
+const otherPins: Record<string, ApprovedDevices> = {}
+vi.mock('./approved-devices', () => {
+ const mem = (role: string) => {
+ const get = (): ApprovedDevices => (role === 'phone' ? disk : (otherPins[role] ??= { pubkeys: [] }))
+ const set = (s: ApprovedDevices): void => {
+ if (role === 'phone') disk = s
+ else otherPins[role] = s
+ }
+ return {
+ load: async () => get(),
+ save: async (s: ApprovedDevices) => set(s),
+ update: role === 'phone' ? (u: (s: ApprovedDevices) => ApprovedDevices) => persist(u) : async (u: (s: ApprovedDevices) => ApprovedDevices) => set(u(get()))
+ }
+ }
+ const stores: Record<string, ReturnType<typeof mem>> = { phone: mem('phone'), guest: mem('guest'), joinedHost: mem('joinedHost') }
+ return {
+ PIN_ROLES: ['phone', 'guest', 'joinedHost'],
+ phonePins: stores.phone,
+ guestPins: stores.guest,
+ joinedHostPins: stores.joinedHost,
+ pinStore: (r: string) => stores[r],
+ retireLegacyPinFile: async () => 0
+ }
+})
vi.mock('./e2ee', () => ({ publicKeyToB64: () => 'host-pub' }))
const sessions: Array<{ opts: HostSessionOptions; session: HostSession; closed: number }> = []
@@ -79,6 +101,7 @@ vi.mock('./host-service', () => ({
}))
import { initStandingHost, tokenTtlMs } from './standing-host'
+import { revokeAllPhones, revokePeerKey } from './peer-revoke'
import { IPC } from '../../shared/ipc'
/** Let the async connectOne() chain (token mint, keypair) settle. */
@@ -117,6 +140,7 @@ beforeEach(() => {
errorBoxes.length = 0
persist.mockReset()
disk = { pubkeys: [] }
+ for (const k of Object.keys(otherPins)) delete otherPins[k]
persist.mockImplementation(async (update) => { disk = update(disk) })
keyError = null
for (const key of Object.keys(ipc)) delete ipc[key]
@@ -293,6 +317,72 @@ describe('standing phone approval lifecycle (#819)', () => {
})
})
+describe('standing host: revocation and pin-store roles', () => {
+ const pendingCount = (): number => sentToWin.filter((x) => x.channel === IPC.remoteHostPeerPending).length
+
+ it('a removed phone\'s live session is closed, and its reconnect is NOT auto-approved', async () => {
+ disk = { pubkeys: ['phone-pub'] }
+ const host = makeHost()
+ host.setEnabled(true)
+ await settle()
+ sessions[0].opts.onPeerReady(sessions[0].session)
+ await settle()
+ expect(sessions[0].session.approve).toHaveBeenCalledOnce() // pinned → silent auto-approve
+ expect(phones()).toBe(1)
+
+ // Phone "Remove" (pairing-service → revokeAllPhones): unpin AND cut.
+ expect(await revokeAllPhones()).toEqual({ persisted: true, killed: true })
+ expect(disk.pubkeys).toEqual([])
+ expect(sessions[0].closed).toBe(1)
+ expect(phones()).toBe(0)
+
+ // The same phone reconnects on a fresh listener: it must face the SAS prompt again.
+ const before = pendingCount()
+ await settle()
+ const next = sessions.at(-1)!
+ expect(next).not.toBe(sessions[0])
+ next.opts.onPeerReady(next.session)
+ await settle()
+ expect(next.session.approve).not.toHaveBeenCalled()
+ expect(pendingCount()).toBe(before + 1)
+ host.stop()
+ })
+
+ it('a key pinned as a joined host or a hosted guest is never auto-admitted as a phone', async () => {
+ otherPins.joinedHost = { pubkeys: ['phone-pub'] }
+ otherPins.guest = { pubkeys: ['phone-pub'] }
+ try {
+ const host = makeHost()
+ host.setEnabled(true)
+ await settle()
+ sessions[0].opts.onPeerReady(sessions[0].session)
+ await settle()
+ expect(sessions[0].session.approve).not.toHaveBeenCalled()
+ expect(pendingCount()).toBe(1) // the human is asked, exactly like any unknown phone
+ host.stop()
+ } finally {
+ delete otherPins.joinedHost
+ delete otherPins.guest
+ }
+ })
+
+ it('a revoke drops a pending consent even after its socket closed, so the dialog cannot re-pin it', async () => {
+ const host = makeHost()
+ host.setEnabled(true)
+ await settle()
+ sessions[0].opts.onPeerReady(sessions[0].session)
+ await settle()
+ const msg = { id: pendingApprovalId(), pub: 'phone-pub' }
+ sessions[0].opts.onClose() // #819: consent outlives the socket…
+ await revokePeerKey('phone-pub', ['phone'])
+ // …but not a revoke.
+ expect(await ipc[IPC.remotePhoneApprove]({ sender }, msg)).toEqual({ status: 'stale' })
+ expect(persist).not.toHaveBeenCalledWith(expect.anything(), expect.anything())
+ expect(disk.pubkeys).toEqual([])
+ host.stop()
+ })
+})
+
describe('standing host: a refused token mint backs off', () => {
afterEach(() => {
vi.useRealTimers()
diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.ts
index 9343e8509..4f1d9bc3d 100644
--- a/src/main/remote/standing-host.ts
+++ b/src/main/remote/standing-host.ts
@@ -15,7 +15,8 @@
//
// The heavy lifting (relay wiring, RPC/frame handlers, fs jail, canvas mirror, approval gate) is
// shared with the interactive host via `connectHostSession`. Pin/lookup logic is the pure,
-// unit-tested `approved-devices-core`.
+// unit-tested `approved-devices-core`; the pins live in the PHONE store (`phonePins`) and nowhere
+// else — the desktop relay roles have their own stores, which this module never reads.
import { dialog, ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
@@ -38,7 +39,8 @@ import { currentCanvas, initHostCanvasHub, subscribeCanvas } from './host-canvas
import { hostIdFromPublicKeyB64 } from './relay-id'
import { removeRelayAdvertisement, writeRelayAdvertisement } from './relay-advertise'
import { isPinned, pinDevice } from './approved-devices-core'
-import { loadApprovedDevices, updateApprovedDevices } from './approved-devices'
+import { phonePins } from './approved-devices'
+import { registerPeerSessionKiller } from './peer-revoke'
import { createPhoneApprovals } from '../../core/phone-approval'
// Re-mint the token this long before its expiry (TTL is ~120s). Floored so a bogus/short exp can't
@@ -202,7 +204,7 @@ export function initStandingHost(
// is exactly-once, so a peer never leaves twice (its color is never freed for someone else).
const approvals = createPhoneApprovals({
- persist: (pub) => updateApprovedDevices((store) => pinDevice(store, pub)),
+ persist: (pub) => phonePins.update((store) => pinDevice(store, pub)),
cleared: (id) => send(IPC.remoteHostPeerPendingCleared, { id })
})
@@ -273,7 +275,7 @@ export function initStandingHost(
const pub = s.peerPublicKeyB64()
let store
try {
- store = await loadApprovedDevices()
+ store = await phonePins.load()
} catch {
store = { pubkeys: [] as string[] }
}
@@ -397,6 +399,23 @@ export function initStandingHost(
}
}
+ // Revocation (peer-revoke.ts): cut every pooled session held by a matching key — bridged or still
+ // awaiting SAS — and drop any pending consent for it, including one whose socket already closed
+ // (#819 keeps those alive for the SAS deadline). Otherwise a phone "Remove" would leave the removed
+ // phone in its shell until the socket dropped, or let an open dialog re-pin it afterwards.
+ registerPeerSessionKiller('phone', (match) => {
+ approvals.clearWhere(match)
+ let cut = false
+ for (const p of [...pool]) {
+ const key = p.session.peerPublicKeyB64()
+ if (key && match(key)) {
+ removeFromPool(p)
+ cut = true
+ }
+ }
+ if (cut) ensurePool()
+ })
+
function start(): void {
if (running) return
running = true
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f8dfbdb9d..cd0938e49 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -3754,7 +3754,8 @@ export type DeviceRevokeServerOutcome = 'ok' | 'failed' | 'skipped'
* 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. */
+ /** The phone's relay trust (every phone relay pin + live relay session), its authorized_keys line
+ * and its agent.json entry were all removed from this machine. */
local: boolean
/** Whether the phone's Pro entitlement was taken back on the relay backend. */
server: DeviceRevokeServerOutcome