diff --git a/src/main/runtime/delegated-mobile-device.integration.test.ts b/src/main/runtime/delegated-mobile-device.integration.test.ts index b4bfa2f679b..f8f258c40b7 100644 --- a/src/main/runtime/delegated-mobile-device.integration.test.ts +++ b/src/main/runtime/delegated-mobile-device.integration.test.ts @@ -326,26 +326,43 @@ describe('pairing.delegatedMobileDevice.sync', () => { expect(registry.listDelegatedMobileDevices(desktop.pairedDeviceId!)).toHaveLength(1) }) - it('keeps the parent when a child cleanup cannot be saved', async () => { - const { server, registry } = await startServer() - const desktop = pairDesktop(server) - const [child] = await sync(desktop, [{ phoneKey: 'p', name: 'p' }]) - expect( - server.setMobileRelayBinding(child!.deviceId, { - relayHostId: 'host', - relayDeviceId: child!.deviceId, - ownerIdentityKey: 'owner' + it.each(['bearer', 'fork'] as const)( + 'keeps the ancestors when a %s child cleanup cannot be saved', + async (kind) => { + const { server, registry } = await startServer() + const desktop = pairDesktop(server) + const parent = + kind === 'fork' + ? registry.forkDeviceKey( + desktop.pairedDeviceId!, + Buffer.alloc(32, 7).toString('base64'), + 'Fork' + ) + : registry.getDevice(desktop.pairedDeviceId!)! + const [child] = registry.upsertDelegatedMobileDevices(parent, [{ phoneKey: 'p', name: 'p' }]) + expect( + server.setMobileRelayBinding(child!.deviceId, { + relayHostId: 'host', + relayDeviceId: child!.deviceId, + ownerIdentityKey: 'owner' + }) + ).toBe(true) + const enqueue = vi.spyOn(server.getRelayRevokeOutbox(), 'enqueue').mockImplementation(() => { + throw new Error('disk full') }) - ).toBe(true) - const enqueue = vi.spyOn(server.getRelayRevokeOutbox(), 'enqueue').mockImplementation(() => { - throw new Error('disk full') - }) - cleanups.push(() => enqueue.mockRestore()) + cleanups.push(() => enqueue.mockRestore()) - expect(server.revokeRuntimeAccess(desktop.pairedDeviceId!)).toBe(false) - expect(registry.getDevice(desktop.pairedDeviceId!)).not.toBeNull() - expect(registry.getDevice(child!.deviceId)).not.toBeNull() - }) + expect(server.revokeRuntimeAccess(desktop.pairedDeviceId!)).toBe(false) + expect(registry.getDevice(desktop.pairedDeviceId!)).not.toBeNull() + expect(registry.getDevice(parent.deviceId)).not.toBeNull() + expect(registry.getDevice(child!.deviceId)).not.toBeNull() + + enqueue.mockRestore() + expect(server.revokeRuntimeAccess(desktop.pairedDeviceId!)).toBe(true) + expect(registry.getDevice(parent.deviceId)).toBeNull() + expect(registry.getDevice(child!.deviceId)).toBeNull() + } + ) it('fails a sync whose dropped child cannot be revoked, keeping that child', async () => { const { server, registry } = await startServer() diff --git a/src/main/runtime/device-entry.ts b/src/main/runtime/device-entry.ts index 502aa813d91..8847e43c67e 100644 --- a/src/main/runtime/device-entry.ts +++ b/src/main/runtime/device-entry.ts @@ -44,6 +44,7 @@ export type DeviceKeyLookup = | { kind: 'unknown' } // An unusable key is not revocation evidence. | { kind: 'not-keyed' } + | { kind: 'refused' } | { kind: 'unavailable' } // Only unscanned token rows are rotatable pairing offers; keyed rows never are. @@ -59,13 +60,19 @@ export function sameGrants(entry: DeviceEntry, grants: readonly RuntimeDeviceGra } // Clients erase keys on unknown; reserve that verdict for readable absence. -export function lookupDeviceKeyRow(device: DeviceEntry | null): DeviceKeyLookup { +export function lookupDeviceKeyRow( + device: DeviceEntry | null, + devices: readonly DeviceEntry[] +): DeviceKeyLookup { if (!device) { return { kind: 'unknown' } } - return device.credentialKind === 'device-key' && device.devicePublicKeyB64 + if (device.credentialKind !== 'device-key' || !device.devicePublicKeyB64) { + return { kind: 'not-keyed' } + } + return withPairedParent(device, devices) ? { kind: 'found', device: { ...device, devicePublicKeyB64: device.devicePublicKeyB64 } } - : { kind: 'not-keyed' } + : { kind: 'refused' } } export type AuthenticatedPrincipalBinding = { @@ -86,15 +93,25 @@ export function isStillAuthenticated( ) } -/** A delegated child authenticates only while its parent desktop is still paired. */ +// Forks and delegated phones lose authority with any ancestor pairing. function withPairedParent( device: DeviceEntry, - devices: readonly DeviceEntry[] + devices: readonly DeviceEntry[], + ancestors = new Set() ): DeviceEntry | null { - const { parentDeviceId } = device - return parentDeviceId === undefined || devices.some((d) => d.deviceId === parentDeviceId) - ? device - : null + if (ancestors.has(device.deviceId)) { + return null + } + ancestors.add(device.deviceId) + const paired = [device.parentDeviceId, device.forkedFrom].every((parentId) => { + if (parentId === undefined) { + return true + } + const parent = devices.find((candidate) => candidate.deviceId === parentId) + return parent !== undefined && withPairedParent(parent, devices, ancestors) !== null + }) + ancestors.delete(device.deviceId) + return paired ? device : null } export function findTokenDevice( diff --git a/src/main/runtime/device-registry-delegated-parent.test.ts b/src/main/runtime/device-registry-delegated-parent.test.ts index 687460cda2f..b7b04bfa62d 100644 --- a/src/main/runtime/device-registry-delegated-parent.test.ts +++ b/src/main/runtime/device-registry-delegated-parent.test.ts @@ -75,4 +75,44 @@ describe('delegated phone auth follows its parent desktop', () => { expect(registry.validateToken(phone.token)?.deviceId).toBe(phone.deviceId) }) + + it.each(['mobile', 'runtime'] as const)( + 'refuses a %s fork and its delegated phones after the bearer parent disappears on disk', + (scope) => { + const registry = new DeviceRegistry(dir) + const parent = registry.addDevice('Parent', scope) + registry.updateLastSeen(parent.deviceId) + const fork = registry.forkDeviceKey( + parent.deviceId, + Buffer.alloc(32, 1).toString('base64'), + 'Migrated installation' + ) + const children = + scope === 'runtime' + ? registry.upsertDelegatedMobileDevices(fork, [{ phoneKey: 'phone', name: 'Pixel' }]) + : [] + const principal = { deviceId: fork.deviceId, credentialRevision: 0 } + expect(registry.lookupDeviceKey(fork.deviceId)).toMatchObject({ kind: 'found' }) + expect(registry.resolveAuthenticatedPrincipal(principal)?.deviceId).toBe(fork.deviceId) + for (const child of children) { + expect(registry.validateToken(child.token)?.deviceId).toBe(child.deviceId) + } + + removeOnDisk(parent.deviceId) + + expect(registry.lookupDeviceKey(fork.deviceId)).toEqual({ kind: 'refused' }) + expect(registry.resolveAuthenticatedPrincipal(principal)).toBeNull() + for (const child of children) { + expect(registry.validateToken(child.token)).toBeNull() + expect( + registry.resolveAuthenticatedPrincipal({ + deviceId: child.deviceId, + credentialRevision: 0, + deviceToken: child.token + }) + ).toBeNull() + } + expect(registry.getDevice(fork.deviceId)).not.toBeNull() + } + ) }) diff --git a/src/main/runtime/device-registry.ts b/src/main/runtime/device-registry.ts index 4de5e93e72c..747189ee814 100644 --- a/src/main/runtime/device-registry.ts +++ b/src/main/runtime/device-registry.ts @@ -209,7 +209,7 @@ export class DeviceRegistry { // Clients erase keys on unknown; reserve that verdict for readable absence. lookupDeviceKey(deviceId: string): DeviceKeyLookup { this.adoptExternalEdits() - const lookup = lookupDeviceKeyRow(this.getDevice(deviceId)) + const lookup = lookupDeviceKeyRow(this.getDevice(deviceId), this.devices) return lookup.kind === 'unknown' && (this.registryUnreadable || this.registryDoubtful) ? { kind: 'unavailable' } : lookup diff --git a/src/main/runtime/rpc/device-key-auth.test.ts b/src/main/runtime/rpc/device-key-auth.test.ts index fa6c980a824..7c78ce20fcf 100644 --- a/src/main/runtime/rpc/device-key-auth.test.ts +++ b/src/main/runtime/rpc/device-key-auth.test.ts @@ -138,6 +138,15 @@ describe('device-key authentication (host)', () => { deviceProofB64: sign(otherKey, 'register', other.transcriptHashB64) }) expect(otherFork.deviceId).not.toBe(forked.deviceId) + + registry.rotatePendingDevice('New QR', 'mobile') + expect( + connect((keyedHash) => ({ + deviceId: forked.deviceId, + deviceProofB64: sign(key, 'auth', keyedHash) + })).reply + ).toMatchObject({ type: 'e2ee_authenticated' }) + expect(registry.validateToken(legacy.token)?.deviceId).toBe(legacy.deviceId) }) it('refuses a keyed row presented with a token, a replayed proof and a wrong-purpose proof', () => { @@ -204,6 +213,14 @@ describe('device-key authentication (host)', () => { type: 'e2ee_error', error: { code: 'unauthorized' } }) + + registry.removeDevice(legacy.deviceId) + for (const metadata of [undefined, relay(legacy.deviceId)]) { + expect(harness(registry, metadata).connect(keyAuth).reply).toEqual({ + type: 'e2ee_error', + error: { code: 'unauthorized' } + }) + } }) it('answers registry_unavailable, never device_revoked, after loading a corrupt registry', () => { diff --git a/src/main/runtime/rpc/mobile-socket-wiring.test.ts b/src/main/runtime/rpc/mobile-socket-wiring.test.ts index d2bc83953d3..2706ff7d9ad 100644 --- a/src/main/runtime/rpc/mobile-socket-wiring.test.ts +++ b/src/main/runtime/rpc/mobile-socket-wiring.test.ts @@ -54,6 +54,7 @@ function registryFor( token: string, scope: 'mobile' | 'runtime' = 'mobile' ): DeviceRegistry { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: transport tests use only credential lookups and last-seen writes. return { validateToken: (candidate: string) => candidate === token @@ -66,6 +67,10 @@ function registryFor( lastSeenAt: 0 } : null, + resolveAuthenticatedPrincipal: (principal: { deviceId: string; deviceToken?: string }) => + principal.deviceId === deviceId && principal.deviceToken === token + ? { deviceId, token, name: 'Phone', scope, pairedAt: 1, lastSeenAt: 0 } + : null, updateLastSeen: vi.fn(), updateLastSeenDeferred: vi.fn() } as unknown as DeviceRegistry diff --git a/src/main/runtime/rpc/mobile-socket-wiring.ts b/src/main/runtime/rpc/mobile-socket-wiring.ts index a043814dcbe..6a7005cd9f8 100644 --- a/src/main/runtime/rpc/mobile-socket-wiring.ts +++ b/src/main/runtime/rpc/mobile-socket-wiring.ts @@ -175,6 +175,12 @@ export class MobileSocketWiring { message: MobileSocketPayload, metadata: MobileSocketTransportMetadata ): void { + const socket = this.authenticatedSockets.get(ws) + if (socket && !this.deviceRegistry.resolveAuthenticatedPrincipal(socket.device)) { + ws.close(4001, 'Unauthorized') + this.handleClose(ws) + return + } let channel = this.channels.get(ws) if (!channel) { const connectionId = randomBytes(8).toString('hex') diff --git a/src/main/runtime/runtime-rpc-device-revocation.test.ts b/src/main/runtime/runtime-rpc-device-revocation.test.ts index 8ba0cabbf13..ecfe0eb2637 100644 --- a/src/main/runtime/runtime-rpc-device-revocation.test.ts +++ b/src/main/runtime/runtime-rpc-device-revocation.test.ts @@ -1,12 +1,24 @@ import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../git/worktrees/catalog/worktree-listing' -import { mkdtempSync } from 'node:fs' +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' +import nacl from 'tweetnacl' +import { encodeDeviceProofMessage } from '../../shared/device-key-proof' +import { SimulatedMobileE2EEV2Peer } from './mobile-cloud-relay/simulated-mobile-e2ee-v2-peer' import { OrcaRuntimeService } from './orca-runtime' +import { DeviceRegistry } from './device-registry' +import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files' +import { makeStore } from './runtime-rpc-worktree-store-fixtures' +import { partialRuntimeStore } from './runtime-store-partial-fixture' +import { + TerminalStreamOpcode, + encodeTerminalStreamFrame, + encodeTerminalStreamText +} from '../../shared/terminal-stream-protocol' import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { parsePairingCode } from '../../shared/pairing' +import { encodePairingOffer, parsePairingCode, type PairingOffer } from '../../shared/pairing' import { generateKeyPair } from '../../shared/e2ee-crypto' import { waitFor } from './runtime-rpc-test-harness' import { @@ -52,6 +64,37 @@ const { getWorktreeListingMocks } = vi.hoisted(() => { return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } }) +async function authenticateKeyedWs(offer: PairingOffer, deviceId: string, key: nacl.SignKeyPair) { + const ws = await connectWs(offer.endpoint) + const peer = new SimulatedMobileE2EEV2Peer( + nacl.box.keyPair(), + Uint8Array.from(Buffer.from(offer.publicKeyB64, 'base64')), + null + ) + ws.send(JSON.stringify(peer.hello)) + expect(peer.acceptReady(JSON.parse(await nextWsMessage(ws)))).toBe(true) + const transcriptHashB64 = peer.transcriptHashB64 + const proof = nacl.sign.detached( + encodeDeviceProofMessage('auth', Buffer.from(transcriptHashB64, 'base64')), + key.secretKey + ) + ws.send( + peer.sealText( + JSON.stringify({ + type: 'e2ee_auth', + v: 2, + transcriptHashB64, + deviceId, + deviceProofB64: Buffer.from(proof).toString('base64') + }) + ) + ) + expect(JSON.parse(peer.openText(await nextWsMessage(ws))!)).toMatchObject({ + type: 'e2ee_authenticated' + }) + return { ws, peer } +} + describe('OrcaRuntimeRpcServer', () => { it('cleans up pre-auth E2EE WebSocket state when the socket closes', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) @@ -209,4 +252,249 @@ describe('OrcaRuntimeRpcServer', () => { await server.stop() } }, 15_000) + + it.each([ + ['mobile', false], + ['runtime', false], + ['mobile', true] + ] as const)( + 'revoking a %s bearer, removed on disk %s, removes descendants and closes their sockets', + async (scope, removedOnDisk) => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-revoke-')) + const server = new OrcaRuntimeRpcServer({ + runtime: new OrcaRuntimeService(), + userDataPath, + enableWebSocket: true, + wsPort: 0 + }) + await server.start() + try { + const offer = server.createPairingOffer({ address: '127.0.0.1', name: 'Parent', scope }) + if (!offer.available) { + throw new Error('WebSocket pairing unavailable') + } + const parsed = parsePairingCode(offer.pairingUrl)! + const parentSocket = await authenticateMobileWs(offer.pairingUrl) + const registry = server.getDeviceRegistry()! + const key = nacl.sign.keyPair() + const fork = registry.forkDeviceKey( + offer.deviceId, + Buffer.from(key.publicKey).toString('base64'), + 'Fork' + ) + const idleFork = registry.forkDeviceKey( + offer.deviceId, + Buffer.alloc(32, 9).toString('base64'), + 'Offline fork' + ) + const { ws: forkSocket } = await authenticateKeyedWs(parsed, fork.deviceId, key) + const children = + scope === 'runtime' + ? registry.upsertDelegatedMobileDevices(fork, [{ phoneKey: 'p', name: 'Pixel' }]) + : [] + const sockets = [parentSocket, forkSocket] + for (const child of children) { + sockets.push( + await authenticateMobileWs( + encodePairingOffer({ + ...parsed, + deviceToken: child.token, + pairedDeviceId: child.deviceId, + scope: 'mobile' + }) + ) + ) + } + const unrelated = registry.addDevice('Unrelated', scope) + const unrelatedSocket = await authenticateMobileWs( + encodePairingOffer({ + ...parsed, + deviceToken: unrelated.token, + pairedDeviceId: unrelated.deviceId + }) + ) + const closed = sockets.map(waitForWsClose) + if (removedOnDisk) { + const path = join(userDataPath, DEVICE_REGISTRY_FILENAME) + const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8')) + writeFileSync(path, JSON.stringify(rows.filter((row) => row.deviceId !== offer.deviceId))) + } + + const revoked = + scope === 'mobile' + ? await server.revokeMobileDevice(offer.deviceId) + : server.revokeRuntimeAccess(offer.deviceId) + + expect(revoked).toBe(true) + for (const device of [fork, idleFork, ...children]) { + expect(registry.getDevice(device.deviceId)).toBeNull() + expect(new DeviceRegistry(userDataPath).getDevice(device.deviceId)).toBeNull() + } + await Promise.all(closed) + expect(registry.validateToken(unrelated.token)?.deviceId).toBe(unrelated.deviceId) + expect(unrelatedSocket.readyState).toBe(unrelatedSocket.OPEN) + unrelatedSocket.close() + } finally { + await server.stop() + } + }, + 15_000 + ) + + it.each(['binary', 'text', 'sibling-cascade'] as const)( + 'retires an established keyed terminal subscription through %s revocation', + async (kind) => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-stream-revoke-')) + const runtime = new OrcaRuntimeService(partialRuntimeStore(makeStore())) + const write = vi.fn(() => true) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: 'fork-stream-pty' }), + write, + kill: () => true, + getForegroundProcess: async () => null + }) + const cleanup = vi.spyOn(runtime, 'cleanupSubscriptionsForConnection') + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + enableWebSocket: true, + wsPort: 0 + }) + await server.start() + try { + const terminal = await runtime.createTerminal('id:repo-1::/tmp/worktree-a') + const offer = server.createPairingOffer({ + address: '127.0.0.1', + name: 'Parent', + scope: kind === 'sibling-cascade' ? 'mobile' : 'runtime' + }) + if (!offer.available) { + throw new Error('WebSocket pairing unavailable') + } + const registry = server.getDeviceRegistry()! + const key = nacl.sign.keyPair() + const earlier = + kind === 'sibling-cascade' + ? registry.forkDeviceKey( + offer.deviceId, + Buffer.alloc(32, 7).toString('base64'), + 'Earlier' + ) + : null + const fork = registry.forkDeviceKey( + offer.deviceId, + Buffer.from(key.publicKey).toString('base64'), + 'Fork' + ) + const later = + kind === 'sibling-cascade' + ? registry.forkDeviceKey( + offer.deviceId, + Buffer.alloc(32, 8).toString('base64'), + 'Later' + ) + : null + if (kind === 'sibling-cascade') { + server.setMobileRelayBinding(fork.deviceId, { + relayHostId: 'host', + relayDeviceId: fork.deviceId, + ownerIdentityKey: 'owner' + }) + registry.setPushRegistration(fork.deviceId, { + registrationId: 'fork-push', + filter: {}, + expiresAt: 4_000_000_000_000 + }) + } + const { ws, peer } = await authenticateKeyedWs( + parsePairingCode(offer.pairingUrl)!, + fork.deviceId, + key + ) + const responses: { result?: { type?: string; streamId?: number } }[] = [] + ws.on('message', (data, isBinary) => { + if (isBinary && Buffer.isBuffer(data)) { + peer.openBinary(data) + } else if (!isBinary) { + responses.push(JSON.parse(peer.openText(data.toString())!)) + } + }) + ws.send( + peer.sealText( + JSON.stringify({ + id: 'subscribe', + method: 'terminal.subscribe', + params: { terminal: terminal.handle, capabilities: { terminalBinaryStream: 1 } } + }) + ) + ) + await waitFor(() => responses.some((response) => response.result?.type === 'subscribed')) + const streamId = responses.find((response) => response.result?.type === 'subscribed') + ?.result?.streamId + if (streamId === undefined) { + throw new Error('Expected binary terminal subscription') + } + const sendInput = (text: string) => + ws.send( + peer.sealBinary( + encodeTerminalStreamFrame({ + opcode: TerminalStreamOpcode.Input, + streamId, + seq: 1, + payload: encodeTerminalStreamText(text) + }) + ) + ) + sendInput('before') + await waitFor(() => write.mock.calls.length === 1) + const path = join(userDataPath, DEVICE_REGISTRY_FILENAME) + const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8')) + writeFileSync( + path, + JSON.stringify( + rows.filter( + (row) => + row.deviceId !== (kind === 'sibling-cascade' ? fork.deviceId : offer.deviceId) + ) + ) + ) + const closed = waitForWsClose(ws) + + if (kind === 'sibling-cascade') { + expect(await server.revokeMobileDevice(offer.deviceId)).toBe(true) + for (const device of [earlier, fork, later]) { + if (device) { + expect(registry.getDevice(device.deviceId)).toBeNull() + } + } + expect(registry.getDevice(offer.deviceId)).toBeNull() + expect(server.getRelayRevokeOutbox().pendingFor('owner', 'host')).toMatchObject([ + { relayDeviceId: fork.deviceId } + ]) + expect(server.getPushUnregisterOutbox().pending()).toMatchObject([ + { deviceId: fork.deviceId, registrationId: 'fork-push' } + ]) + } else if (kind === 'binary') { + sendInput('after') + } else { + ws.send(peer.sealText(JSON.stringify({ id: 'denied', method: 'status.get' }))) + } + + await waitFor( + () => + cleanup.mock.calls.length > 0 || + write.mock.calls.length > 1 || + responses.some((response) => 'error' in response) + ) + expect(write).toHaveBeenCalledTimes(1) + expect(cleanup).toHaveBeenCalledOnce() + await closed + expect(server['mobileSocketWiring']?.channelCount).toBe(0) + expect(server['mobileSocketWiring']?.connectionCount).toBe(0) + } finally { + cleanup.mockRestore() + await server.stop() + } + } + ) }) diff --git a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-devices.ts b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-devices.ts index 6ccac9a49cb..3a0c4795b9d 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-devices.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-devices.ts @@ -6,6 +6,7 @@ import type { DelegatedPhone, DelegatedMobileDeviceSyncResult } from '../../../shared/delegated-mobile-device-contract' +import type { DeviceEntry } from '../device-registry' import { RuntimeRpcRequestAdmission } from './runtime-rpc-request-admission' // Why: below dispatch so a caller-bound RPC context can revoke and mint mobile devices. @@ -13,50 +14,57 @@ export class RuntimeRpcMobileDevices extends RuntimeRpcRequestAdmission { private onPushUnregisterQueued?: () => void async revokeMobileDevice(deviceId: string): Promise { - const revoked = this.revokeMobileDeviceNow(deviceId) + const device = this.deviceRegistry?.getDevice(deviceId) + const revoked = device?.scope === 'mobile' && this.revokeDevicesNow([device]) if (revoked) { this.mobileDesktopRelay?.phonesChanged() } return revoked } - private revokeMobileDeviceNow(deviceId: string): boolean { - const device = this.deviceRegistry?.getDevice(deviceId) - if (device?.scope !== 'mobile') { - return false - } - if (device.relayBinding) { - if (!this.queueRelayDeviceRevoke(device.relayBinding)) { - return false - } - } - // Capture gateway registration before deleting its device row so unpair also revokes push. - this.queuePushUnregister(deviceId, device.pushRegistration?.registrationId) - if (!this.deviceRegistry?.removeDevice(deviceId)) { - return false - } - this.mobileRelayPairingProvider?.onDemandStateChanged?.() - this.runtime.forgetClientNavigationState(deviceId) - this.mobileSocketWiring?.terminateDeviceConnections(deviceId) - return true - } - revokeRuntimeAccess(deviceId: string): boolean { const device = this.deviceRegistry?.getDevice(deviceId) - if (device?.scope !== 'runtime') { + return device?.scope === 'runtime' && this.revokeDevicesNow([device]) + } + + private revokeDevicesNow(roots: readonly DeviceEntry[]): boolean { + const registry = this.deviceRegistry + if (!registry) { return false } - for (const child of this.deviceRegistry?.listDelegatedMobileDevices(deviceId) ?? []) { - // Keep parent until child cleanup is durable so retry can rediscover them. - if (!this.revokeMobileDeviceNow(child.deviceId)) { - return false + // Saves adopt disk deletions, so capture every descendant's cleanup facts before the first write. + const paired = registry.listDevices() + const plan: DeviceEntry[] = [] + const visited = new Set() + const visit = (device: DeviceEntry): void => { + if (visited.has(device.deviceId)) { + return } + visited.add(device.deviceId) + for (const child of paired) { + if (child.parentDeviceId === device.deviceId || child.forkedFrom === device.deviceId) { + visit(child) + } + } + plan.push(device) } - if (!this.deviceRegistry?.removeDevice(deviceId)) { - return false + roots.forEach(visit) + for (const device of plan) { + const { deviceId } = device + // Keep ancestors until child cleanup is durable so retry can rediscover them. + if (device.scope === 'mobile') { + if (device.relayBinding && !this.queueRelayDeviceRevoke(device.relayBinding)) { + return false + } + this.queuePushUnregister(deviceId, device.pushRegistration?.registrationId) + } + registry.removeDevice(deviceId) + if (device.scope === 'mobile') { + this.mobileRelayPairingProvider?.onDemandStateChanged?.() + } + this.runtime.forgetClientNavigationState(deviceId) + this.mobileSocketWiring?.terminateDeviceConnections(deviceId) } - this.runtime.forgetClientNavigationState(deviceId) - this.mobileSocketWiring?.terminateDeviceConnections(deviceId) return true } @@ -71,14 +79,13 @@ export class RuntimeRpcMobileDevices extends RuntimeRpcRequestAdmission { throw new Error('delegated_device_parent_unavailable') } const wanted = new Set(phones.map((phone) => phone.phoneKey)) - for (const child of registry.listDelegatedMobileDevices(parentDeviceId)) { - if ( - (!child.phoneKey || !wanted.has(child.phoneKey)) && - !this.revokeMobileDeviceNow(child.deviceId) - ) { - throw new Error('delegated_device_revoke_failed') - } + const dropped = registry + .listDelegatedMobileDevices(parentDeviceId) + .filter((child) => !child.phoneKey || !wanted.has(child.phoneKey)) + if (!this.revokeDevicesNow(dropped)) { + throw new Error('delegated_device_revoke_failed') } + let devices = registry.upsertDelegatedMobileDevices(parent, phones) // A child removed on disk meanwhile is dropped by the save; one rerun mints it fresh. if (devices.length < phones.length) {