Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions mobile/src/tasks/mobile-agent-launch-architecture.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { openTestAgentSessionRecordStore } from '../../../src/main/runtime/agent
import { OrcaRuntimeRpcServer } from '../../../src/main/runtime/runtime-rpc'
import { DeviceRegistry } from '../../../src/main/runtime/device-registry'
import type { AuthenticatedMobileSocket } from '../../../src/main/runtime/rpc/mobile-socket-wiring'
import { devicePrincipalOf } from '../../../src/main/runtime/device-principal'
import { RpcDispatcher } from '../../../src/main/runtime/rpc/dispatcher'
import { AgentLaunchFields } from '../../../src/shared/rpc-contract/agent-launch-params'
import {
Expand Down Expand Up @@ -172,6 +173,7 @@ describe('mobile launch retry authority', () => {
const replies: RpcResponse[] = []
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: with no pairing provider or physical socket, this admission path reads only clientCapabilities.
const authenticatedSocket = {
device: { ...devicePrincipalOf(mobile), deviceToken: mobile.token },
clientCapabilities: [AGENT_LAUNCH_RUNTIME_CAPABILITY]
} as unknown as AuthenticatedMobileSocket
await server['handleWebSocketMessage'](
Expand Down
152 changes: 152 additions & 0 deletions src/main/runtime/device-principal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { createHash } from 'node:crypto'
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 { devicePrincipalOf } from './device-principal'
import { DeviceRegistry, type DeviceEntry } from './device-registry'
import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files'
import type { OrcaRuntimeService } from './orca-runtime'
import { OrcaRuntimeRpcServer } from './runtime-rpc'
import type { AuthenticatedMobileSocket } from './rpc/mobile-socket-wiring'

function legacyRow(overrides: Partial<DeviceEntry> = {}): DeviceEntry {
return {
deviceId: 'device-1',
name: 'Phone',
token: 'legacy-token',
scope: 'mobile',
pairedAt: 1,
lastSeenAt: 2,
...overrides
}
}

function registryWith(rows: unknown[]): { registry: DeviceRegistry; path: string } {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-device-principal-'))
const path = join(userDataPath, DEVICE_REGISTRY_FILENAME)
writeFileSync(path, JSON.stringify(rows))
return { registry: new DeviceRegistry(userDataPath), path }
}

function socketFor(device: DeviceEntry): AuthenticatedMobileSocket {
return {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch only uses ws as a map key for abort registration.
ws: {} as AuthenticatedMobileSocket['ws'],
connectionId: 'connection-1',
device: { ...devicePrincipalOf(device), deviceToken: device.token },
clientCapabilities: [],
transport: { transport: 'direct' }
}
}

describe('device principal', () => {
it('keeps the legacy token as client id and sha256(token) as caller fingerprint', () => {
expect(devicePrincipalOf(legacyRow())).toEqual({
deviceId: 'device-1',
scope: 'mobile',
clientId: 'legacy-token',
callerFingerprint: createHash('sha256').update('legacy-token').digest('hex'),
credentialRevision: 0
})
expect(
devicePrincipalOf(legacyRow({ callerFingerprint: 'carried', credentialRevision: 3 }))
).toMatchObject({ callerFingerprint: 'carried', credentialRevision: 3 })
})

it('round-trips the optional principal fields and drops malformed values on load', () => {
const { registry, path } = registryWith([
legacyRow(),
legacyRow({
deviceId: 'device-2',
token: 't2',
credentialRevision: 2,
callerFingerprint: 'f'
}),
{
...legacyRow({ deviceId: 'device-3', token: 't3' }),
credentialRevision: -1,
callerFingerprint: 7
}
])
expect(registry.getDevice('device-1')).not.toHaveProperty(
'credentialRevision',
expect.anything()
)
expect(registry.getDevice('device-2')).toMatchObject({
credentialRevision: 2,
callerFingerprint: 'f'
})
expect(registry.getDevice('device-3')?.credentialRevision).toBeUndefined()
expect(registry.getDevice('device-3')?.callerFingerprint).toBeUndefined()

registry.updateLastSeen('device-2')
const saved: unknown = JSON.parse(readFileSync(path, 'utf-8'))
expect(saved).toContainEqual(expect.objectContaining({ deviceId: 'device-2' }))
expect(Array.isArray(saved) ? saved[1] : null).toMatchObject({
token: 't2',
credentialRevision: 2,
callerFingerprint: 'f'
})
})

it('binds an authenticated socket to its device id, revision and token', () => {
const { registry } = registryWith([legacyRow({ credentialRevision: 1 })])
const bound = { deviceId: 'device-1', credentialRevision: 1, deviceToken: 'legacy-token' }
expect(registry.resolveAuthenticatedPrincipal(bound)?.deviceId).toBe('device-1')
expect(registry.resolveAuthenticatedPrincipal({ ...bound, credentialRevision: 0 })).toBeNull()
expect(registry.resolveAuthenticatedPrincipal({ ...bound, deviceToken: 'other' })).toBeNull()
registry.removeDevice('device-1')
expect(registry.resolveAuthenticatedPrincipal(bound)).toBeNull()
})

it('dispatches an old phone with its token as client id and refuses it once re-credentialed', async () => {
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-device-principal-rpc-'))
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: status.get only reads these three members.
const runtime = {
configureNotificationDismissalStore: () => {},
getRuntimeId: () => 'test-runtime',
getStatus: vi.fn().mockResolvedValue({ graphStatus: 'ok' })
} as unknown as OrcaRuntimeService
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false })
const registry = new DeviceRegistry(userDataPath)
server['deviceRegistry'] = registry
const phone = registry.addDevice('phone', 'mobile')
const socket = socketFor(phone)
const dispatch = vi.spyOn(server['dispatcher'], 'dispatchStreaming')

const replies: string[] = []
await server['handleWebSocketMessage'](
JSON.stringify({ id: 'r1', method: 'status.get' }),
(response) => replies.push(response),
() => {},
undefined,
undefined,
phone.token,
socket
)
expect(dispatch.mock.calls[0]?.[2]).toMatchObject({
clientId: phone.token,
pairedDeviceId: phone.deviceId,
authenticatedCallerFingerprint: createHash('sha256').update(phone.token).digest('hex')
})

// A credential change bumps the revision; the open socket's next request is refused.
registry['devices'] = registry['devices'].map((row) => ({ ...row, credentialRevision: 1 }))
await server['handleWebSocketMessage'](
JSON.stringify({ id: 'r2', method: 'status.get' }),
(response) => replies.push(response),
() => {},
undefined,
undefined,
phone.token,
socket
)
expect(dispatch).toHaveBeenCalledOnce()
expect(JSON.parse(replies.at(-1)!)).toMatchObject({
id: 'r2',
ok: false,
error: { code: 'unauthorized' }
})
})
})
38 changes: 38 additions & 0 deletions src/main/runtime/device-principal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { DeviceEntry } from './device-registry'
import type { RpcCallerScope } from './rpc/rpc-caller-scope'
import { createHash } from 'node:crypto'

/**
* Who an authenticated paired socket is. Socket bookkeeping (close, revoke) keys on `deviceId`;
* per-client runtime state (terminal drivers, dictation, file grants) keys on `clientId`.
*/
export type DevicePrincipal = {
deviceId: string
scope: DeviceEntry['scope']
// Why: token rows keep their token here because shipped phones stamp it into terminal
// `client.id` params; a row without a token is keyed by its id.
clientId: string
callerFingerprint: string
credentialRevision: number
}

export function devicePrincipalOf(device: DeviceEntry): DevicePrincipal {
return {
deviceId: device.deviceId,
scope: device.scope,
clientId: device.token,
callerFingerprint:
device.callerFingerprint ?? fingerprintAuthenticatedPairingCredential(device.token),
credentialRevision: device.credentialRevision ?? 0
}
}

export function callerScopeOf(device: DeviceEntry): RpcCallerScope {
return device.scope === 'mobile'
? { kind: 'mobile', delegated: device.parentDeviceId !== undefined }
: { kind: 'runtime-paired', grants: device.grants ?? [] }
}

export function fingerprintAuthenticatedPairingCredential(token: string): string {
return createHash('sha256').update(token).digest('hex')
}
33 changes: 33 additions & 0 deletions src/main/runtime/device-registry-row-validation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { DeviceScope } from '../../shared/runtime-types'
import type { RelayDeviceBinding } from './relay/relay-revoke-outbox'
import type { DeviceEntry } from './device-registry'
import { parseMobilePushRegistration } from '../../shared/mobile-push-contract'
import { RUNTIME_DEVICE_GRANTS, type RuntimeDeviceGrant } from './rpc/rpc-method-permission'

const GRANTABLE: ReadonlySet<string> = new Set(RUNTIME_DEVICE_GRANTS)
Expand Down Expand Up @@ -37,3 +39,34 @@ export function validRelayBinding(
}
: undefined
}

export function normalizeLoadedDeviceRow(device: DeviceEntry): DeviceEntry {
return {
...device,
// Why: older registries only existed for phone pairing. Treat missing
// scope as mobile so legacy device tokens do not gain new CLI powers.
scope: device.scope === 'runtime' ? 'runtime' : 'mobile',
grants: validGrants(device.grants, device.scope === 'runtime' ? 'runtime' : 'mobile'),
relayBinding: validRelayBinding(device.relayBinding, device.deviceId),
mobilePairingConnectionMode:
device.mobilePairingConnectionMode === 'local-only' ? 'local-only' : 'automatic',
// Why: registries written before this field existed only ever held network-reach grants (phones and
// LAN links), so a missing value must keep binding every interface on reconnect.
pairingReach: device.pairingReach === 'this-computer' ? 'this-computer' : 'network',
// Why: a malformed row must degrade to "no background push", never fail the load
// and strand every paired device.
pushRegistration: parseMobilePushRegistration(device.pushRegistration),
parentDeviceId: typeof device.parentDeviceId === 'string' ? device.parentDeviceId : undefined,
phoneKey: typeof device.phoneKey === 'string' ? device.phoneKey : undefined,
credentialRevision:
typeof device.credentialRevision === 'number' &&
Number.isSafeInteger(device.credentialRevision) &&
device.credentialRevision > 0
? device.credentialRevision
: undefined,
callerFingerprint:
typeof device.callerFingerprint === 'string' && device.callerFingerprint.length > 0
? device.callerFingerprint
: undefined
}
}
48 changes: 24 additions & 24 deletions src/main/runtime/device-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,8 @@ import {
type DelegatedMobileDeviceEntry
} from './delegated-mobile-devices'
import type { RuntimeDeviceGrant } from './rpc/rpc-method-permission'
import { validGrants, validRelayBinding } from './device-registry-row-validation'
import {
parseMobilePushRegistration,
type MobilePushRegistration
} from '../../shared/mobile-push-contract'
import { normalizeLoadedDeviceRow, validGrants } from './device-registry-row-validation'
import type { MobilePushRegistration } from '../../shared/mobile-push-contract'

export type { DeviceScope }

Expand All @@ -50,6 +47,10 @@ export type DeviceEntry = {
phoneKey?: string
// Why: administrative permissions are granted only when pairing; absent on older rows means none.
grants?: RuntimeDeviceGrant[]
// Why: authenticated sockets are bound to this; a credential change bumps it. Absent = 0.
credentialRevision?: number
// Why: orchestration ownership survives a credential change. Absent = sha256(token).
callerFingerprint?: string
}

function sameGrants(entry: DeviceEntry, grants: readonly RuntimeDeviceGrant[]): boolean {
Expand Down Expand Up @@ -270,6 +271,23 @@ export class DeviceRegistry {
return this.devices.find((d) => d.token === token) ?? null
}

/** The row an authenticated socket is still entitled to, or null once revoked or re-credentialed. */
resolveAuthenticatedPrincipal(principal: {
deviceId: string
credentialRevision: number
deviceToken?: string
}): DeviceEntry | null {
const device = this.getDevice(principal.deviceId)
if (
!device ||
(device.credentialRevision ?? 0) !== principal.credentialRevision ||
(principal.deviceToken !== undefined && device.token !== principal.deviceToken)
) {
return null
}
return device
}

updateLastSeen(deviceId: string): void {
const index = this.devices.findIndex((d) => d.deviceId === deviceId)
if (index === -1) {
Expand Down Expand Up @@ -345,25 +363,7 @@ export class DeviceRegistry {
try {
hardenExistingSecureFile(this.registryPath)
const parsed = JSON.parse(readFileSync(this.registryPath, 'utf-8')) as DeviceEntry[]
this.devices = parsed.map((device) => ({
...device,
// Why: older registries only existed for phone pairing. Treat missing
// scope as mobile so legacy device tokens do not gain new CLI powers.
scope: device.scope === 'runtime' ? 'runtime' : 'mobile',
grants: validGrants(device.grants, device.scope === 'runtime' ? 'runtime' : 'mobile'),
relayBinding: validRelayBinding(device.relayBinding, device.deviceId),
mobilePairingConnectionMode:
device.mobilePairingConnectionMode === 'local-only' ? 'local-only' : 'automatic',
// Why: registries written before this field existed only ever held network-reach grants (phones and
// LAN links), so a missing value must keep binding every interface on reconnect.
pairingReach: device.pairingReach === 'this-computer' ? 'this-computer' : 'network',
// Why: a malformed row must degrade to "no background push", never fail the load
// and strand every paired device.
pushRegistration: parseMobilePushRegistration(device.pushRegistration),
parentDeviceId:
typeof device.parentDeviceId === 'string' ? device.parentDeviceId : undefined,
phoneKey: typeof device.phoneKey === 'string' ? device.phoneKey : undefined
}))
this.devices = parsed.map(normalizeLoadedDeviceRow)
this.registryUnreadable = false
} catch (error) {
// "Cannot read" is not "is empty". Saving an empty list over a registry we were merely
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function connectLegacyChannel() {
serverSecretKey: serverKeys.secretKey,
resolveAuthenticatedDevice: (token) =>
token === 'valid-token'
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile' }
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile', clientId: token, callerFingerprint: 'test-fingerprint', credentialRevision: 0 }
: null,
onReady: vi.fn(),
onError
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function createRuntimeBinarySender() {
serverSecretKey: serverKeys.secretKey,
resolveAuthenticatedDevice: (token) =>
token === 'valid-token'
? { deviceId: 'device-1', deviceToken: token, scope: 'runtime' }
? { deviceId: 'device-1', deviceToken: token, scope: 'runtime', clientId: token, callerFingerprint: 'test-fingerprint', credentialRevision: 0 }
: null,
onReady: vi.fn(),
onError: onTransportError
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function setup(overrides?: Partial<E2EEChannelOptions>) {
serverSecretKey: serverKeys.secretKey,
resolveAuthenticatedDevice: (token) =>
token === 'valid-token'
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile' }
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile', clientId: token, callerFingerprint: 'test-fingerprint', credentialRevision: 0 }
: null,
onReady: vi.fn(),
onError,
Expand Down
7 changes: 5 additions & 2 deletions src/main/runtime/rpc/e2ee-channel-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function setup() {
const onError = vi.fn()
const resolveAuthenticatedDevice = vi.fn((token: string) =>
token === 'valid-token'
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile' as const }
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile' as const, clientId: token, callerFingerprint: 'test-fingerprint', credentialRevision: 0 }
: null
)
const channel = new E2EEChannel(ws as unknown as WebSocket, {
Expand Down Expand Up @@ -147,7 +147,10 @@ describe('E2EEChannel v2', () => {
expect(ctx.onReady).toHaveBeenCalledWith(ctx.channel, {
deviceId: 'device-1',
deviceToken: 'valid-token',
scope: 'mobile'
scope: 'mobile',
clientId: 'valid-token',
callerFingerprint: 'test-fingerprint',
credentialRevision: 0
})
const authenticated = openServerFrame(ctx.ws.sent[1]!.data, 'text', schedule, 0n)
expect(JSON.parse(new TextDecoder().decode(authenticated!))).toEqual({
Expand Down
Loading
Loading