Add Orca Relay desktop and mobile transport (#8536)
* feat(mobile): define relay protocol groundwork Co-authored-by: Orca <help@stably.ai> * feat(mobile): implement replay-safe E2EE v2 sessions Co-authored-by: Orca <help@stably.ai> * test(auth): lock cloud refresh single-flight Co-authored-by: Orca <help@stably.ai> * test(mobile): complete E2EE v2 adversarial coverage Co-authored-by: Orca <help@stably.ai> * refactor(runtime): unify mobile socket wiring Co-authored-by: Orca <help@stably.ai> * feat(runtime): add relay control and data clients Co-authored-by: Orca <help@stably.ai> * feat(runtime): coordinate desktop relay sessions Co-authored-by: Orca <help@stably.ai> * fix(auth): fence stale cloud session mutations Co-authored-by: Orca <help@stably.ai> * feat(runtime): add relay pairing and durable revoke Co-authored-by: Orca <help@stably.ai> * feat(runtime): add relay credential pairing RPCs Co-authored-by: Orca <help@stably.ai> * feat(settings): show Orca Relay sign-in status Co-authored-by: Orca <help@stably.ai> * test(relay): prove desktop lifecycle and E2EE splice Co-authored-by: Orca <help@stably.ai> * feat(mobile): persist relay pairing state Co-authored-by: Orca <help@stably.ai> * feat(mobile): race direct and relay pairing Co-authored-by: Orca <help@stably.ai> * feat(mobile): recover pairing through relay director Co-authored-by: Orca <help@stably.ai> * fix(relay): preserve origin controls during drain Co-authored-by: Orca <help@stably.ai> * feat(mobile): recover interrupted relay pairing Co-authored-by: Orca <help@stably.ai> * feat(mobile): add stable relay RPC sessions Co-authored-by: Orca <help@stably.ai> * feat(mobile): supervise direct and relay endpoints Co-authored-by: Orca <help@stably.ai> * Cover mobile relay director fallback matrix Co-authored-by: Orca <help@stably.ai> * Fix relay settings component test isolation Co-authored-by: Orca <help@stably.ai> * Remove unrelated merge formatting drift Co-authored-by: Orca <help@stably.ai> * Update runtime connection count integration assertion Co-authored-by: Orca <help@stably.ai> * Run mobile typecheck through pnpm Co-authored-by: Orca <help@stably.ai> * feat(relay): gate desktop controls on mobile demand Co-authored-by: Orca <help@stably.ai> * test(mobile): cover served relay recovery Co-authored-by: Orca <help@stably.ai> * feat(mobile): upgrade direct pairings to relay Co-authored-by: Orca <help@stably.ai> * fix(relay): harden mobile reconnect and teardown Co-authored-by: Orca <help@stably.ai> * fix(auth): clarify account sign-in state Co-authored-by: Orca <help@stably.ai> * fix(auth): polish sign-in completion flow Co-authored-by: Orca <help@stably.ai> * fix(auth): clarify sign-out confirmation Co-authored-by: Orca <help@stably.ai> * fix(auth): simplify sign-in completion page Co-authored-by: Orca <help@stably.ai> * feat(mobile): add per-device pairing connection mode Co-authored-by: Orca <help@stably.ai> * fix(mobile): stabilize pairing option layout Co-authored-by: Orca <help@stably.ai> * fix(mobile): give pairing choices stable space Co-authored-by: Orca <help@stably.ai> * fix(mobile): stabilize pairing QR regeneration Co-authored-by: Orca <help@stably.ai> * Animate mobile pairing flow height Co-authored-by: Orca <help@stably.ai> * Configure auth in packaged builds Co-authored-by: Orca <help@stably.ai> * Make Orca Relay pairing an opt-in beta Co-authored-by: Orca <help@stably.ai> * Show Relay beta details on hover Co-authored-by: Orca <help@stably.ai> * Refine mobile relay pairing choice Co-authored-by: Orca <help@stably.ai> * Polish Orca Relay pairing controls Co-authored-by: Orca <help@stably.ai> * Keep mobile contract fallback test additive Co-authored-by: Orca <help@stably.ai> --------- Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -8,6 +8,8 @@ import { join } from 'node:path'
|
||||
import { hardenExistingSecureFile, writeSecureJsonFile } from '../../shared/secure-file'
|
||||
import type { DeviceScope } from '../../shared/runtime-types'
|
||||
import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files'
|
||||
import type { RelayDeviceBinding } from './relay/relay-revoke-outbox'
|
||||
import type { MobilePairingConnectionMode } from '../../shared/mobile-pairing-connection-mode'
|
||||
|
||||
export type { DeviceScope }
|
||||
|
||||
@@ -18,6 +20,27 @@ export type DeviceEntry = {
|
||||
scope: DeviceScope
|
||||
pairedAt: number
|
||||
lastSeenAt: number
|
||||
relayBinding?: RelayDeviceBinding
|
||||
mobilePairingConnectionMode?: MobilePairingConnectionMode
|
||||
}
|
||||
|
||||
function validRelayBinding(value: unknown, deviceId: string): RelayDeviceBinding | undefined {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return undefined
|
||||
}
|
||||
const binding = value as Partial<RelayDeviceBinding>
|
||||
return binding.relayDeviceId === deviceId &&
|
||||
typeof binding.relayHostId === 'string' &&
|
||||
typeof binding.ownerIdentityKey === 'string'
|
||||
? {
|
||||
relayHostId: binding.relayHostId,
|
||||
relayDeviceId: binding.relayDeviceId,
|
||||
ownerIdentityKey: binding.ownerIdentityKey,
|
||||
...(typeof binding.inviteExpiresAt === 'number' && Number.isFinite(binding.inviteExpiresAt)
|
||||
? { inviteExpiresAt: binding.inviteExpiresAt }
|
||||
: {})
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
export class DeviceRegistry {
|
||||
@@ -82,6 +105,40 @@ export class DeviceRegistry {
|
||||
return this.devices.find((d) => d.deviceId === deviceId) ?? null
|
||||
}
|
||||
|
||||
getPendingDevice(scope: DeviceScope = 'mobile'): DeviceEntry | null {
|
||||
return this.devices.find((device) => device.lastSeenAt === 0 && device.scope === scope) ?? null
|
||||
}
|
||||
|
||||
setRelayBinding(deviceId: string, binding: RelayDeviceBinding): boolean {
|
||||
const device = this.devices.find((candidate) => candidate.deviceId === deviceId)
|
||||
if (!device || binding.relayDeviceId !== deviceId) {
|
||||
return false
|
||||
}
|
||||
device.relayBinding = binding
|
||||
this.save()
|
||||
return true
|
||||
}
|
||||
|
||||
setMobilePairingConnectionMode(deviceId: string, mode: MobilePairingConnectionMode): boolean {
|
||||
const device = this.devices.find((candidate) => candidate.deviceId === deviceId)
|
||||
if (!device || device.scope !== 'mobile') {
|
||||
return false
|
||||
}
|
||||
device.mobilePairingConnectionMode = mode
|
||||
this.save()
|
||||
return true
|
||||
}
|
||||
|
||||
getMobilePairingConnectionMode(deviceId: string): MobilePairingConnectionMode | null {
|
||||
const device = this.devices.find((candidate) => candidate.deviceId === deviceId)
|
||||
if (!device || device.scope !== 'mobile') {
|
||||
return null
|
||||
}
|
||||
// Why: pairings created before this preference existed used automatic
|
||||
// direct-first Relay fallback, so missing state must preserve that behavior.
|
||||
return device.mobilePairingConnectionMode === 'local-only' ? 'local-only' : 'automatic'
|
||||
}
|
||||
|
||||
listDevices(): readonly DeviceEntry[] {
|
||||
return this.devices
|
||||
}
|
||||
@@ -110,7 +167,10 @@ export class DeviceRegistry {
|
||||
...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'
|
||||
scope: device.scope === 'runtime' ? 'runtime' : 'mobile',
|
||||
relayBinding: validRelayBinding(device.relayBinding, device.deviceId),
|
||||
mobilePairingConnectionMode:
|
||||
device.mobilePairingConnectionMode === 'local-only' ? 'local-only' : 'automatic'
|
||||
}))
|
||||
} catch {
|
||||
this.devices = []
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { MobilePairingConnectionContext } from '../runtime-rpc'
|
||||
import { DesktopRelayService, pairingAuthorizationForContext } from './desktop-relay-service'
|
||||
|
||||
const relayHostId = 'AbCdEf0123_-xyZ9'
|
||||
|
||||
function context(
|
||||
transport: MobilePairingConnectionContext['transport']
|
||||
): MobilePairingConnectionContext {
|
||||
return { deviceId: 'device-1', connectionId: 'e2ee-connection-1', transport }
|
||||
}
|
||||
|
||||
describe('pairingAuthorizationForContext', () => {
|
||||
it('derives direct authorization only from the authenticated connection', () => {
|
||||
expect(pairingAuthorizationForContext(context({ transport: 'direct' }), relayHostId)).toEqual({
|
||||
mode: 'authenticated-direct',
|
||||
directAuthId: 'e2ee-connection-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('derives invite authorization only from immutable relay metadata', () => {
|
||||
expect(
|
||||
pairingAuthorizationForContext(
|
||||
context({
|
||||
transport: 'relay',
|
||||
relayHostId,
|
||||
relayDeviceId: 'device-1',
|
||||
basisConnId: 'relay-basis-1',
|
||||
credentialKind: 'invite'
|
||||
}),
|
||||
relayHostId
|
||||
)
|
||||
).toEqual({ mode: 'relay-basis', basisConnId: 'relay-basis-1' })
|
||||
})
|
||||
|
||||
it('reserves resume metadata for confirmation and rejects stale hosts', () => {
|
||||
expect(
|
||||
pairingAuthorizationForContext(
|
||||
context({
|
||||
transport: 'relay',
|
||||
relayHostId,
|
||||
relayDeviceId: 'device-1',
|
||||
basisConnId: 'resume-basis-1',
|
||||
credentialKind: 'resume'
|
||||
}),
|
||||
relayHostId
|
||||
)
|
||||
).toBeNull()
|
||||
expect(() =>
|
||||
pairingAuthorizationForContext(
|
||||
context({
|
||||
transport: 'relay',
|
||||
relayHostId: 'stale-host-id-1',
|
||||
relayDeviceId: 'device-1',
|
||||
basisConnId: 'relay-basis-1',
|
||||
credentialKind: 'invite'
|
||||
}),
|
||||
relayHostId
|
||||
)
|
||||
).toThrow('stale_relay_connection')
|
||||
})
|
||||
})
|
||||
|
||||
describe('local-only mobile pairing', () => {
|
||||
it('refuses endpoint discovery and provisioning without opening Relay demand', async () => {
|
||||
const registry = {
|
||||
getDevice: () => ({ deviceId: 'device-1', scope: 'mobile' }),
|
||||
getMobilePairingConnectionMode: () => 'local-only'
|
||||
}
|
||||
const service = Object.create(DesktopRelayService.prototype) as DesktopRelayService
|
||||
Object.defineProperty(service, 'runtimeRpc', {
|
||||
value: { getDeviceRegistry: () => registry }
|
||||
})
|
||||
|
||||
await expect(service.getEndpoints(context({ transport: 'direct' }), {})).resolves.toEqual({
|
||||
v: 1,
|
||||
relay: null
|
||||
})
|
||||
await expect(
|
||||
service.provisionRelay(context({ transport: 'direct' }), {
|
||||
reqId: 'install-1',
|
||||
newResumeTokenHash: 'A'.repeat(43)
|
||||
})
|
||||
).rejects.toThrow('relay_disabled_for_device')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,305 @@
|
||||
import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config'
|
||||
import type { MobilePairingConnectionContext, OrcaRuntimeRpcServer } from '../runtime-rpc'
|
||||
import type {
|
||||
DeviceCredentialInstalled,
|
||||
PairingGetEndpointsParams,
|
||||
PairingGetEndpointsResult,
|
||||
PairingProvisionRelayParams
|
||||
} from '../../../shared/mobile-relay-credential-contract'
|
||||
import { readRelayAuthContext } from './relay-auth-context'
|
||||
import { RelayAuthCoordinator } from './relay-auth-coordinator'
|
||||
import { RelaySessionBroker, type RelayBrokerStatus } from './relay-session-broker'
|
||||
import type { PairingRelay } from '../../../shared/mobile-relay-pairing-offer'
|
||||
import type {
|
||||
RelayRevokeOutbox,
|
||||
RelayDeviceBinding,
|
||||
RelayRevokeOutboxItem
|
||||
} from './relay-revoke-outbox'
|
||||
import type { DeviceCredentialInstallAuthorization } from './relay-control-requests'
|
||||
import { deriveRelayHostId } from './relay-http-client'
|
||||
import { RelayDemandLedger } from './relay-demand-ledger'
|
||||
|
||||
type DesktopRelayServiceOptions = {
|
||||
authConfig: OrcaCloudAuthConfig
|
||||
userDataPath: string
|
||||
appVersion: string
|
||||
runtimeRpc: OrcaRuntimeRpcServer
|
||||
onStatus: (status: RelayBrokerStatus) => void
|
||||
}
|
||||
|
||||
export function pairingAuthorizationForContext(
|
||||
context: MobilePairingConnectionContext,
|
||||
relayHostId: string
|
||||
): DeviceCredentialInstallAuthorization | null {
|
||||
if (context.transport.transport === 'direct') {
|
||||
return { mode: 'authenticated-direct', directAuthId: context.connectionId }
|
||||
}
|
||||
if (context.transport.relayHostId !== relayHostId) {
|
||||
throw new Error('stale_relay_connection')
|
||||
}
|
||||
return context.transport.credentialKind === 'invite'
|
||||
? { mode: 'relay-basis', basisConnId: context.transport.basisConnId }
|
||||
: null
|
||||
}
|
||||
|
||||
export class DesktopRelayService {
|
||||
private readonly coordinator: RelayAuthCoordinator
|
||||
private readonly revokeOutbox: RelayRevokeOutbox
|
||||
private readonly runtimeRpc: OrcaRuntimeRpcServer
|
||||
private readonly demandLedger: RelayDemandLedger
|
||||
private demandExpiryTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private stopped = false
|
||||
|
||||
constructor(options: DesktopRelayServiceOptions) {
|
||||
const keypair = options.runtimeRpc.getE2EEKeypair()
|
||||
const mobileSocketWiring = options.runtimeRpc.getMobileSocketWiring()
|
||||
if (!keypair || !mobileSocketWiring) {
|
||||
throw new Error('mobile_runtime_not_ready')
|
||||
}
|
||||
this.runtimeRpc = options.runtimeRpc
|
||||
this.revokeOutbox = options.runtimeRpc.getRelayRevokeOutbox()
|
||||
this.demandLedger = new RelayDemandLedger({
|
||||
deviceRegistry: options.runtimeRpc.getDeviceRegistry()!,
|
||||
revokeOutbox: this.revokeOutbox,
|
||||
relayHostId: deriveRelayHostId(keypair.publicKey)
|
||||
})
|
||||
this.coordinator = new RelayAuthCoordinator({
|
||||
readContext: () => readRelayAuthContext(options.authConfig, options.userDataPath),
|
||||
hasDemand: ({ identity }) =>
|
||||
this.demandLedger.hasDemand(
|
||||
`${identity.userId}\0${identity.profileId}\0${identity.organizationId}`
|
||||
),
|
||||
openBroker: async ({ context, isCurrent, refreshAccessToken }) => {
|
||||
const broker = await RelaySessionBroker.connect({
|
||||
authConfig: options.authConfig,
|
||||
accessToken: context.accessToken,
|
||||
identity: context.identity,
|
||||
keypair,
|
||||
appVersion: options.appVersion,
|
||||
mobileSocketWiring,
|
||||
isCurrent,
|
||||
refreshAccessToken,
|
||||
onStatus: options.onStatus
|
||||
})
|
||||
void this.flushRevokeOutbox(broker)
|
||||
return broker
|
||||
},
|
||||
onStatus: options.onStatus
|
||||
})
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.refreshDemand()
|
||||
}
|
||||
|
||||
authMutated(): void {
|
||||
this.refreshDemand()
|
||||
}
|
||||
|
||||
fenceAndCloseNow(): void {
|
||||
this.coordinator.fenceAndCloseNow()
|
||||
}
|
||||
|
||||
async createPairingRelay(
|
||||
relayDeviceId: string
|
||||
): Promise<{ relay: PairingRelay; binding: RelayDeviceBinding }> {
|
||||
return await this.withTransientDemand(`pairing:${relayDeviceId}`, async () => {
|
||||
const broker = await this.requireActiveBroker()
|
||||
const relay = await broker.createPairingRelay(relayDeviceId)
|
||||
return {
|
||||
relay,
|
||||
binding: {
|
||||
relayHostId: broker.hostId,
|
||||
relayDeviceId,
|
||||
ownerIdentityKey: broker.ownerIdentityKey,
|
||||
inviteExpiresAt: relay.inviteExpiresAt
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onDeviceRevokeQueued(item: RelayRevokeOutboxItem): void {
|
||||
this.refreshDemand()
|
||||
const broker = this.coordinator.getActiveBroker()
|
||||
if (
|
||||
broker instanceof RelaySessionBroker &&
|
||||
broker.hostId === item.relayHostId &&
|
||||
broker.ownerIdentityKey === item.ownerIdentityKey
|
||||
) {
|
||||
void this.flushRevoke(broker, item)
|
||||
}
|
||||
}
|
||||
|
||||
async getEndpoints(
|
||||
context: MobilePairingConnectionContext,
|
||||
params: PairingGetEndpointsParams
|
||||
): Promise<PairingGetEndpointsResult> {
|
||||
this.requireMobileDevice(context.deviceId)
|
||||
if (
|
||||
this.runtimeRpc.getDeviceRegistry()?.getMobilePairingConnectionMode(context.deviceId) ===
|
||||
'local-only'
|
||||
) {
|
||||
return { v: 1, relay: null }
|
||||
}
|
||||
return await this.withTransientDemand(`endpoints:${context.deviceId}`, async () => {
|
||||
const broker = await this.activeBrokerForDemand()
|
||||
if (!broker?.endpoint) {
|
||||
return { v: 1, relay: null }
|
||||
}
|
||||
this.assertRelayHost(context, broker)
|
||||
const result: PairingGetEndpointsResult = { v: 1, relay: broker.endpoint }
|
||||
if (params.installReqId) {
|
||||
result.installStatus = await broker.credentialInstallStatus(
|
||||
context.deviceId,
|
||||
params.installReqId
|
||||
)
|
||||
}
|
||||
if (params.resumeConfirmReqId) {
|
||||
if (
|
||||
context.transport.transport !== 'relay' ||
|
||||
context.transport.credentialKind !== 'resume'
|
||||
) {
|
||||
throw new Error('resume_confirmation_unavailable')
|
||||
}
|
||||
result.resumeConfirmation = await broker.confirmResume(
|
||||
context.transport.basisConnId,
|
||||
params.resumeConfirmReqId
|
||||
)
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
async provisionRelay(
|
||||
context: MobilePairingConnectionContext,
|
||||
params: PairingProvisionRelayParams
|
||||
): Promise<DeviceCredentialInstalled> {
|
||||
this.requireMobileDevice(context.deviceId)
|
||||
if (
|
||||
this.runtimeRpc.getDeviceRegistry()?.getMobilePairingConnectionMode(context.deviceId) ===
|
||||
'local-only'
|
||||
) {
|
||||
throw new Error('relay_disabled_for_device')
|
||||
}
|
||||
return await this.withTransientDemand(`provision:${context.deviceId}`, async () => {
|
||||
const broker = await this.requireActiveBroker()
|
||||
if (!broker.endpoint) {
|
||||
throw new Error('relay_control_not_active')
|
||||
}
|
||||
this.assertRelayHost(context, broker)
|
||||
const authorization = pairingAuthorizationForContext(context, broker.hostId)
|
||||
if (!authorization) {
|
||||
// Why: a resume splice proves renewal through confirmation; it cannot be
|
||||
// repurposed as either of the two initial-install authorization modes.
|
||||
throw new Error('relay_provision_authorization_unavailable')
|
||||
}
|
||||
if (
|
||||
!this.runtimeRpc.setMobileRelayBinding(context.deviceId, {
|
||||
relayHostId: broker.hostId,
|
||||
relayDeviceId: context.deviceId,
|
||||
ownerIdentityKey: broker.ownerIdentityKey
|
||||
})
|
||||
) {
|
||||
throw new Error('mobile_device_not_found')
|
||||
}
|
||||
this.refreshDemand()
|
||||
return await broker.installCredential(context.deviceId, params, authorization)
|
||||
})
|
||||
}
|
||||
|
||||
demandStateChanged(): void {
|
||||
this.refreshDemand()
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true
|
||||
if (this.demandExpiryTimer) {
|
||||
clearTimeout(this.demandExpiryTimer)
|
||||
this.demandExpiryTimer = null
|
||||
}
|
||||
this.coordinator.stop()
|
||||
}
|
||||
|
||||
private async flushRevokeOutbox(broker: RelaySessionBroker): Promise<void> {
|
||||
for (const item of this.revokeOutbox.pendingFor(broker.ownerIdentityKey, broker.hostId)) {
|
||||
await this.flushRevoke(broker, item)
|
||||
}
|
||||
}
|
||||
|
||||
private requireMobileDevice(deviceId: string): void {
|
||||
if (this.runtimeRpc.getDeviceRegistry()?.getDevice(deviceId)?.scope !== 'mobile') {
|
||||
throw new Error('mobile_device_not_found')
|
||||
}
|
||||
}
|
||||
|
||||
private assertRelayHost(
|
||||
context: MobilePairingConnectionContext,
|
||||
broker: RelaySessionBroker
|
||||
): void {
|
||||
if (
|
||||
context.transport.transport === 'relay' &&
|
||||
context.transport.relayHostId !== broker.hostId
|
||||
) {
|
||||
throw new Error('stale_relay_connection')
|
||||
}
|
||||
}
|
||||
|
||||
private async flushRevoke(
|
||||
broker: RelaySessionBroker,
|
||||
item: RelayRevokeOutboxItem
|
||||
): Promise<void> {
|
||||
try {
|
||||
await broker.revokeDevice(item.relayDeviceId, item.reqId)
|
||||
this.revokeOutbox.remove(item.reqId)
|
||||
this.refreshDemand()
|
||||
} catch {
|
||||
// Why: the durable item is the source of truth; reconnecting the same
|
||||
// account/control retries this stable reqId without delaying local revoke.
|
||||
}
|
||||
}
|
||||
|
||||
private async withTransientDemand<T>(key: string, operation: () => Promise<T>): Promise<T> {
|
||||
const release = this.demandLedger.acquireTransient(key)
|
||||
this.refreshDemand()
|
||||
try {
|
||||
return await operation()
|
||||
} finally {
|
||||
release()
|
||||
this.refreshDemand()
|
||||
}
|
||||
}
|
||||
|
||||
private async activeBrokerForDemand(): Promise<RelaySessionBroker | null> {
|
||||
const broker =
|
||||
this.coordinator.getActiveBroker() ?? (await this.coordinator.waitForActiveBroker())
|
||||
return broker instanceof RelaySessionBroker ? broker : null
|
||||
}
|
||||
|
||||
private async requireActiveBroker(): Promise<RelaySessionBroker> {
|
||||
const broker = await this.activeBrokerForDemand()
|
||||
if (!broker) {
|
||||
throw new Error('relay_control_not_active')
|
||||
}
|
||||
return broker
|
||||
}
|
||||
|
||||
private refreshDemand(): void {
|
||||
if (this.stopped) {
|
||||
return
|
||||
}
|
||||
if (this.demandExpiryTimer) {
|
||||
clearTimeout(this.demandExpiryTimer)
|
||||
this.demandExpiryTimer = null
|
||||
}
|
||||
this.coordinator.reconcile()
|
||||
const expiresAt = this.demandLedger.nextPendingExpiry()
|
||||
if (expiresAt !== null) {
|
||||
// Why: an unscanned QR must stop holding a standing control when its
|
||||
// server invite expires, even if no renderer survives to report closure.
|
||||
this.demandExpiryTimer = setTimeout(
|
||||
() => this.refreshDemand(),
|
||||
Math.max(1, expiresAt - Date.now() + 1)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import WebSocketClient, { WebSocketServer, type RawData, type WebSocket } from 'ws'
|
||||
import { DeviceRegistry } from '../device-registry'
|
||||
import { MobileSocketWiring } from '../rpc/mobile-socket-wiring'
|
||||
import { CloudRelayTransport } from '../rpc/relay-transport'
|
||||
import { deriveRelayHostId } from './relay-http-client'
|
||||
import { SimulatedMobileE2EEV2Peer } from './simulated-mobile-e2ee-v2-peer'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((resolvePromise) => {
|
||||
resolve = resolvePromise
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
function waitForOpen(socket: WebSocketClient): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once('open', resolve)
|
||||
socket.once('error', reject)
|
||||
})
|
||||
}
|
||||
|
||||
function nextText(socket: WebSocketClient): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
socket.once('message', (raw) => resolve(raw.toString()))
|
||||
})
|
||||
}
|
||||
|
||||
function forward(socket: WebSocket, raw: RawData, isBinary: boolean): void {
|
||||
if (socket.readyState === socket.OPEN) {
|
||||
socket.send(raw, { binary: isBinary })
|
||||
}
|
||||
}
|
||||
|
||||
describe('desktop relay E2EE integration', () => {
|
||||
const servers: WebSocketServer[] = []
|
||||
const transports: CloudRelayTransport[] = []
|
||||
const userDataPaths: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(transports.splice(0).map((transport) => transport.stop()))
|
||||
await Promise.all(
|
||||
servers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
for (const client of server.clients) {
|
||||
client.terminate()
|
||||
}
|
||||
server.close(() => resolve())
|
||||
})
|
||||
)
|
||||
)
|
||||
for (const path of userDataPaths.splice(0)) {
|
||||
rmSync(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('splices a simulated phone through CloudRelayTransport with real NaCl E2EE v2', async () => {
|
||||
const relay = new WebSocketServer({ port: 0, perMessageDeflate: false })
|
||||
servers.push(relay)
|
||||
await new Promise<void>((resolve) => relay.once('listening', resolve))
|
||||
const address = relay.address()
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('expected local relay TCP address')
|
||||
}
|
||||
let hostSocket: WebSocket | null = null
|
||||
let phoneSocket: WebSocket | null = null
|
||||
let phoneAuthorized = false
|
||||
const maybeSplice = (): void => {
|
||||
if (!hostSocket || !phoneSocket || !phoneAuthorized) {
|
||||
return
|
||||
}
|
||||
const host = hostSocket
|
||||
const phone = phoneSocket
|
||||
host.on('message', (raw, isBinary) => forward(phone, raw, isBinary))
|
||||
phone.on('message', (raw, isBinary) => forward(host, raw, isBinary))
|
||||
phone.send(
|
||||
JSON.stringify({
|
||||
type: 'relay-hello',
|
||||
ok: true,
|
||||
credentialKind: 'invite',
|
||||
leaseExpiresAt: Date.now() + 60_000
|
||||
})
|
||||
)
|
||||
}
|
||||
relay.on('connection', (socket, request) => {
|
||||
expect(request.url).not.toContain('?')
|
||||
if (request.url === '/v1/host/data/connection-1') {
|
||||
socket.once('message', (raw) => {
|
||||
expect(JSON.parse(raw.toString())).toEqual({
|
||||
type: 'host-data-auth',
|
||||
v: 1,
|
||||
connTicket: 'A'.repeat(43),
|
||||
generation: 1
|
||||
})
|
||||
hostSocket = socket
|
||||
maybeSplice()
|
||||
})
|
||||
return
|
||||
}
|
||||
if (request.url?.startsWith('/v1/connect/')) {
|
||||
socket.once('message', (raw) => {
|
||||
expect(JSON.parse(raw.toString())).toEqual({
|
||||
type: 'relay-auth',
|
||||
v: 1,
|
||||
mode: 'connect',
|
||||
credential: 'B'.repeat(43)
|
||||
})
|
||||
phoneSocket = socket
|
||||
phoneAuthorized = true
|
||||
maybeSplice()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-relay-e2ee-'))
|
||||
userDataPaths.push(userDataPath)
|
||||
const registry = new DeviceRegistry(userDataPath)
|
||||
const device = registry.addDevice('Phone', 'mobile')
|
||||
const desktopKeys = nacl.box.keyPair()
|
||||
const relayHostId = deriveRelayHostId(desktopKeys.publicKey)
|
||||
const receivedText = deferred<string>()
|
||||
const receivedBinary = deferred<Uint8Array>()
|
||||
const phoneBinary = deferred<Uint8Array>()
|
||||
const wiring = new MobileSocketWiring({
|
||||
deviceRegistry: registry,
|
||||
e2eeKeypair: {
|
||||
publicKey: desktopKeys.publicKey,
|
||||
secretKey: desktopKeys.secretKey,
|
||||
publicKeyB64: Buffer.from(desktopKeys.publicKey).toString('base64')
|
||||
},
|
||||
onText: (socket, plaintext, reply, sendBinary) => {
|
||||
expect(socket.transport).toEqual({
|
||||
transport: 'relay',
|
||||
relayHostId,
|
||||
relayDeviceId: device.deviceId,
|
||||
basisConnId: 'connection-1',
|
||||
credentialKind: 'invite'
|
||||
})
|
||||
receivedText.resolve(plaintext)
|
||||
reply(JSON.stringify({ id: 'rpc-1', ok: true, result: { path: 'relay' } }))
|
||||
sendBinary(new Uint8Array([4, 5, 6]))
|
||||
},
|
||||
onBinary: (_socket, bytes) => receivedBinary.resolve(new Uint8Array(bytes)),
|
||||
onClose: vi.fn()
|
||||
})
|
||||
const transport = new CloudRelayTransport({
|
||||
cellUrl: `http://127.0.0.1:${address.port}`,
|
||||
relayHostId,
|
||||
generation: 1
|
||||
})
|
||||
transports.push(transport)
|
||||
wiring.attachTransport(transport, (socket) => transport.metadataFor(socket))
|
||||
await transport.start()
|
||||
await transport.openConnection({
|
||||
connId: 'connection-1',
|
||||
connTicket: 'A'.repeat(43),
|
||||
kind: 'invite',
|
||||
relayDeviceId: device.deviceId,
|
||||
attachDeadlineMs: 5_000
|
||||
})
|
||||
|
||||
const phone = new WebSocketClient(`ws://127.0.0.1:${address.port}/v1/connect/${relayHostId}`, {
|
||||
perMessageDeflate: false
|
||||
})
|
||||
await waitForOpen(phone)
|
||||
const relayHello = nextText(phone)
|
||||
phone.send(
|
||||
JSON.stringify({
|
||||
type: 'relay-auth',
|
||||
v: 1,
|
||||
mode: 'connect',
|
||||
credential: 'B'.repeat(43)
|
||||
})
|
||||
)
|
||||
await expect(relayHello).resolves.toMatch('"ok":true')
|
||||
|
||||
const authenticated = deferred<void>()
|
||||
const phoneText = deferred<string>()
|
||||
const phoneSession = new SimulatedMobileE2EEV2Peer(
|
||||
nacl.box.keyPair(),
|
||||
desktopKeys.publicKey,
|
||||
relayHostId
|
||||
)
|
||||
let phoneState: 'awaiting-ready' | 'awaiting-authenticated' | 'ready' = 'awaiting-ready'
|
||||
phone.on('message', (raw, isBinary) => {
|
||||
if (phoneState === 'awaiting-ready') {
|
||||
expect(isBinary).toBe(false)
|
||||
expect(phoneSession.acceptReady(JSON.parse(raw.toString()))).toBe(true)
|
||||
phoneState = 'awaiting-authenticated'
|
||||
phone.send(
|
||||
phoneSession.sealText(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_auth',
|
||||
v: 2,
|
||||
transcriptHashB64: phoneSession.transcriptHashB64,
|
||||
deviceToken: device.token
|
||||
})
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
const plaintext = isBinary
|
||||
? phoneSession.openBinary(new Uint8Array(raw as Buffer))
|
||||
: phoneSession.openText(raw.toString())
|
||||
expect(plaintext).not.toBeNull()
|
||||
if (phoneState === 'awaiting-authenticated') {
|
||||
expect(JSON.parse(plaintext as string)).toEqual({
|
||||
type: 'e2ee_authenticated',
|
||||
v: 2,
|
||||
transcriptHashB64: phoneSession.transcriptHashB64
|
||||
})
|
||||
phoneState = 'ready'
|
||||
authenticated.resolve()
|
||||
} else if (typeof plaintext === 'string') {
|
||||
phoneText.resolve(plaintext)
|
||||
} else {
|
||||
phoneBinary.resolve(plaintext!)
|
||||
}
|
||||
})
|
||||
phone.send(JSON.stringify(phoneSession.hello))
|
||||
await authenticated.promise
|
||||
phone.send(phoneSession.sealText(JSON.stringify({ id: 'rpc-1', method: 'status.get' })))
|
||||
phone.send(phoneSession.sealBinary(new Uint8Array([1, 2, 3])))
|
||||
|
||||
await expect(receivedText.promise).resolves.toBe(
|
||||
JSON.stringify({ id: 'rpc-1', method: 'status.get' })
|
||||
)
|
||||
await expect(receivedBinary.promise).resolves.toEqual(new Uint8Array([1, 2, 3]))
|
||||
await expect(phoneText.promise).resolves.toBe(
|
||||
JSON.stringify({ id: 'rpc-1', ok: true, result: { path: 'relay' } })
|
||||
)
|
||||
await expect(phoneBinary.promise).resolves.toEqual(new Uint8Array([4, 5, 6]))
|
||||
|
||||
phone.terminate()
|
||||
}, 15_000)
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config'
|
||||
import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store'
|
||||
import { readFreshOrcaCloudSession } from '../../orca-profiles/profile-cloud-session-refresh'
|
||||
import type { RelayAuthContext } from './relay-auth-coordinator'
|
||||
|
||||
export async function readRelayAuthContext(
|
||||
authConfig: OrcaCloudAuthConfig,
|
||||
userDataPath: string
|
||||
): Promise<RelayAuthContext | null> {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
if (!active.profile.cloud) {
|
||||
return null
|
||||
}
|
||||
const session = await readFreshOrcaCloudSession(authConfig, active, userDataPath)
|
||||
if (session.status !== 'found') {
|
||||
return null
|
||||
}
|
||||
// Why: refresh and org-selection can rewrite cloud linkage while the request
|
||||
// is in flight; identity must come from the post-refresh profile state.
|
||||
const refreshed = ensureActiveOrcaProfile(userDataPath)
|
||||
const cloud = refreshed.profile.cloud
|
||||
if (!cloud || refreshed.profile.id !== active.profile.id) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
identity: {
|
||||
userId: cloud.userId,
|
||||
profileId: cloud.cloudProfileId,
|
||||
organizationId: cloud.activeOrgId ?? ''
|
||||
},
|
||||
accessToken: session.session.accessToken,
|
||||
relayEntitled: session.session.capabilities.flags['relay.use'] === true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { RelayAuthCoordinator, type RelayAuthContext } from './relay-auth-coordinator'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((resolvePromise) => {
|
||||
resolve = resolvePromise
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
const context: RelayAuthContext = {
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
accessToken: 'access-1',
|
||||
relayEntitled: true
|
||||
}
|
||||
|
||||
describe('RelayAuthCoordinator', () => {
|
||||
it('stays signed-in but does not open a broker without relay demand', async () => {
|
||||
const openBroker = vi.fn()
|
||||
const statuses: string[] = []
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
hasDemand: () => false,
|
||||
openBroker,
|
||||
onStatus: (status) => statuses.push(status)
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await coordinator.waitForActiveBroker()
|
||||
expect(openBroker).not.toHaveBeenCalled()
|
||||
expect(statuses.at(-1)).toBe('standby')
|
||||
})
|
||||
|
||||
it('opens on demand and lingers before closing the last control', async () => {
|
||||
let demanded = false
|
||||
const broker = { closeNow: vi.fn() }
|
||||
const statuses: string[] = []
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
hasDemand: () => demanded,
|
||||
openBroker: async () => broker,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
lingerMs: 250
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await coordinator.waitForActiveBroker()
|
||||
demanded = true
|
||||
coordinator.reconcile()
|
||||
await expect(coordinator.waitForActiveBroker()).resolves.toBe(broker)
|
||||
demanded = false
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(statuses.at(-1)).toBe('standby'))
|
||||
expect(broker.closeNow).not.toHaveBeenCalled()
|
||||
await vi.waitFor(() => expect(broker.closeNow).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('cancels linger when demand returns', async () => {
|
||||
let demanded = true
|
||||
const broker = { closeNow: vi.fn() }
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
hasDemand: () => demanded,
|
||||
openBroker: async () => broker,
|
||||
onStatus: vi.fn(),
|
||||
lingerMs: 20
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await expect(coordinator.waitForActiveBroker()).resolves.toBe(broker)
|
||||
demanded = false
|
||||
coordinator.reconcile()
|
||||
demanded = true
|
||||
coordinator.reconcile()
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
expect(broker.closeNow).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not carry old-profile demand through an identity switch', async () => {
|
||||
let current = context
|
||||
const broker = { closeNow: vi.fn() }
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => current,
|
||||
hasDemand: ({ identity }) => identity.profileId === 'profile-1',
|
||||
openBroker: async () => broker,
|
||||
onStatus: vi.fn(),
|
||||
lingerMs: 10_000
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await expect(coordinator.waitForActiveBroker()).resolves.toBe(broker)
|
||||
current = { ...context, identity: { ...context.identity, profileId: 'profile-2' } }
|
||||
coordinator.reconcile()
|
||||
await coordinator.waitForActiveBroker()
|
||||
expect(broker.closeNow).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('fences a session read that finishes after sign-out', async () => {
|
||||
const read = deferred<RelayAuthContext | null>()
|
||||
const openBroker = vi.fn()
|
||||
const statuses: string[] = []
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: () => read.promise,
|
||||
openBroker,
|
||||
onStatus: (status) => statuses.push(status)
|
||||
})
|
||||
coordinator.reconcile()
|
||||
coordinator.fenceAndCloseNow()
|
||||
read.resolve(context)
|
||||
await vi.waitFor(() => expect(openBroker).not.toHaveBeenCalled())
|
||||
expect(statuses.at(-1)).toBe('offline')
|
||||
})
|
||||
|
||||
it('closes a broker whose open finishes after an identity mutation', async () => {
|
||||
const opened = deferred<{ closeNow(): void }>()
|
||||
const staleClose = vi.fn()
|
||||
const readContext = vi
|
||||
.fn<() => Promise<RelayAuthContext | null>>()
|
||||
.mockResolvedValueOnce(context)
|
||||
.mockResolvedValueOnce({
|
||||
...context,
|
||||
identity: { ...context.identity, organizationId: 'org-2' }
|
||||
})
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => opened.promise)
|
||||
.mockResolvedValueOnce({ closeNow: vi.fn() })
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext,
|
||||
openBroker,
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(openBroker).toHaveBeenCalledOnce())
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(openBroker).toHaveBeenCalledTimes(2))
|
||||
opened.resolve({ closeNow: staleClose })
|
||||
await vi.waitFor(() => expect(staleClose).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('keeps one broker for duplicate events with unchanged identity', async () => {
|
||||
const broker = { closeNow: vi.fn() }
|
||||
const openBroker = vi.fn(async () => broker)
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(openBroker).toHaveBeenCalledOnce())
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(openBroker).toHaveBeenCalledOnce())
|
||||
expect(broker.closeNow).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a refresh result after capability removal', async () => {
|
||||
let current: RelayAuthContext | null = context
|
||||
let refreshAccessToken: (() => Promise<string | null>) | null = null
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => current,
|
||||
openBroker: async (input) => {
|
||||
refreshAccessToken = input.refreshAccessToken
|
||||
return { closeNow: vi.fn() }
|
||||
},
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(refreshAccessToken).not.toBeNull())
|
||||
current = { ...context, relayEntitled: false }
|
||||
coordinator.reconcile()
|
||||
await expect(refreshAccessToken!()).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('invalidates pending ownership immediately while broker opening is paused', async () => {
|
||||
const firstOpen = deferred<{ closeNow(): void }>()
|
||||
const firstClose = vi.fn()
|
||||
let firstIsCurrent: (() => boolean) | null = null
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockImplementationOnce((input) => {
|
||||
firstIsCurrent = input.isCurrent
|
||||
return firstOpen.promise
|
||||
})
|
||||
.mockResolvedValueOnce({ closeNow: vi.fn() })
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker,
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(firstIsCurrent).not.toBeNull())
|
||||
coordinator.reconcile()
|
||||
expect(firstIsCurrent!()).toBe(false)
|
||||
await vi.waitFor(() => expect(openBroker).toHaveBeenCalledTimes(2))
|
||||
firstOpen.resolve({ closeNow: firstClose })
|
||||
await vi.waitFor(() => expect(firstClose).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('rejects a token refresh whose session read crosses an auth mutation', async () => {
|
||||
const refreshRead = deferred<RelayAuthContext | null>()
|
||||
let readCount = 0
|
||||
let current = context
|
||||
let refreshAccessToken: (() => Promise<string | null>) | null = null
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: () => {
|
||||
readCount += 1
|
||||
return readCount === 2 ? refreshRead.promise : Promise.resolve(current)
|
||||
},
|
||||
openBroker: async (input) => {
|
||||
refreshAccessToken = input.refreshAccessToken
|
||||
return { closeNow: vi.fn() }
|
||||
},
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(refreshAccessToken).not.toBeNull())
|
||||
const refreshing = refreshAccessToken!()
|
||||
current = { ...context, identity: { ...context.identity, organizationId: 'org-2' } }
|
||||
coordinator.reconcile()
|
||||
refreshRead.resolve(context)
|
||||
|
||||
await expect(refreshing).resolves.toBeNull()
|
||||
await vi.waitFor(() => expect(readCount).toBeGreaterThanOrEqual(3))
|
||||
})
|
||||
|
||||
it('reconnects automatically after a signed-in process restart or relaunch fence', async () => {
|
||||
const firstBroker = { closeNow: vi.fn() }
|
||||
const firstCoordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => context,
|
||||
openBroker: async () => firstBroker,
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
firstCoordinator.reconcile()
|
||||
await vi.waitFor(() => expect(firstCoordinator.getActiveBroker()).toBe(firstBroker))
|
||||
firstCoordinator.fenceAndCloseNow()
|
||||
expect(firstBroker.closeNow).toHaveBeenCalledOnce()
|
||||
|
||||
const reopenedBroker = { closeNow: vi.fn() }
|
||||
const reopenedCoordinator = new RelayAuthCoordinator({
|
||||
// Why: normal quit/relaunch preserves the session store, so a fresh
|
||||
// process reads the same entitled identity and opens without new login.
|
||||
readContext: async () => context,
|
||||
openBroker: async () => reopenedBroker,
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
reopenedCoordinator.reconcile()
|
||||
await vi.waitFor(() => expect(reopenedCoordinator.getActiveBroker()).toBe(reopenedBroker))
|
||||
})
|
||||
|
||||
it('closes and reopens for valid profile and organization identity switches', async () => {
|
||||
let current = context
|
||||
const brokers = Array.from({ length: 3 }, () => ({ closeNow: vi.fn() }))
|
||||
const openBroker = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(brokers[0])
|
||||
.mockResolvedValueOnce(brokers[1])
|
||||
.mockResolvedValueOnce(brokers[2])
|
||||
const coordinator = new RelayAuthCoordinator({
|
||||
readContext: async () => current,
|
||||
openBroker,
|
||||
onStatus: vi.fn()
|
||||
})
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(coordinator.getActiveBroker()).toBe(brokers[0]))
|
||||
|
||||
current = { ...context, identity: { ...context.identity, profileId: 'profile-2' } }
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(coordinator.getActiveBroker()).toBe(brokers[1]))
|
||||
expect(brokers[0]!.closeNow).toHaveBeenCalledOnce()
|
||||
|
||||
current = {
|
||||
...context,
|
||||
identity: { ...context.identity, profileId: 'profile-2', organizationId: 'org-2' }
|
||||
}
|
||||
coordinator.reconcile()
|
||||
await vi.waitFor(() => expect(coordinator.getActiveBroker()).toBe(brokers[2]))
|
||||
expect(brokers[1]!.closeNow).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,225 @@
|
||||
import type { RelayBrokerStatus } from './relay-session-broker'
|
||||
|
||||
export type RelayAuthIdentity = {
|
||||
userId: string
|
||||
profileId: string
|
||||
organizationId: string
|
||||
}
|
||||
|
||||
export type RelayAuthContext = {
|
||||
identity: RelayAuthIdentity
|
||||
accessToken: string
|
||||
relayEntitled: boolean
|
||||
}
|
||||
|
||||
export type CoordinatedRelayBroker = {
|
||||
closeNow(): void
|
||||
}
|
||||
|
||||
type RelayAuthCoordinatorOptions = {
|
||||
readContext: () => Promise<RelayAuthContext | null>
|
||||
hasDemand?: (context: RelayAuthContext) => boolean
|
||||
openBroker: (input: {
|
||||
context: RelayAuthContext
|
||||
isCurrent: () => boolean
|
||||
refreshAccessToken: () => Promise<string | null>
|
||||
}) => Promise<CoordinatedRelayBroker>
|
||||
onStatus: (status: RelayBrokerStatus) => void
|
||||
lingerMs?: number
|
||||
}
|
||||
|
||||
type BrokerOwnership = {
|
||||
identityKey: string
|
||||
broker: CoordinatedRelayBroker | null
|
||||
valid: boolean
|
||||
}
|
||||
|
||||
function identityKey(identity: RelayAuthIdentity): string {
|
||||
return `${identity.userId}\0${identity.profileId}\0${identity.organizationId}`
|
||||
}
|
||||
|
||||
export class RelayAuthCoordinator {
|
||||
private readonly options: RelayAuthCoordinatorOptions
|
||||
private authEpoch = 0
|
||||
private ownership: BrokerOwnership | null = null
|
||||
private readonly pendingOwnerships = new Set<BrokerOwnership>()
|
||||
private latestReconcile: Promise<void> = Promise.resolve()
|
||||
private lingerTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private stopped = false
|
||||
|
||||
constructor(options: RelayAuthCoordinatorOptions) {
|
||||
this.options = options
|
||||
}
|
||||
|
||||
reconcile(): void {
|
||||
if (this.stopped) {
|
||||
return
|
||||
}
|
||||
const epoch = ++this.authEpoch
|
||||
this.invalidatePendingOwnerships()
|
||||
const reconcile = this.reconcileEpoch(epoch)
|
||||
this.latestReconcile = reconcile
|
||||
void reconcile
|
||||
}
|
||||
|
||||
fenceAndCloseNow(): void {
|
||||
++this.authEpoch
|
||||
this.cancelLinger()
|
||||
this.invalidatePendingOwnerships()
|
||||
this.invalidateOwnership()
|
||||
this.options.onStatus('offline')
|
||||
}
|
||||
|
||||
getActiveBroker(): CoordinatedRelayBroker | null {
|
||||
return this.ownership?.valid ? this.ownership.broker : null
|
||||
}
|
||||
|
||||
async waitForActiveBroker(): Promise<CoordinatedRelayBroker | null> {
|
||||
while (!this.stopped) {
|
||||
const broker = this.getActiveBroker()
|
||||
if (broker) {
|
||||
return broker
|
||||
}
|
||||
const pending = this.latestReconcile
|
||||
await pending
|
||||
if (pending === this.latestReconcile) {
|
||||
return this.getActiveBroker()
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true
|
||||
this.fenceAndCloseNow()
|
||||
}
|
||||
|
||||
private async reconcileEpoch(epoch: number): Promise<void> {
|
||||
try {
|
||||
const context = await this.options.readContext()
|
||||
if (!this.isEpochCurrent(epoch)) {
|
||||
return
|
||||
}
|
||||
if (!context || !context.relayEntitled) {
|
||||
this.cancelLinger()
|
||||
this.invalidateOwnership()
|
||||
this.options.onStatus('offline')
|
||||
return
|
||||
}
|
||||
const nextIdentityKey = identityKey(context.identity)
|
||||
if (!(this.options.hasDemand?.(context) ?? true)) {
|
||||
if (this.ownership?.valid && this.ownership.identityKey !== nextIdentityKey) {
|
||||
this.cancelLinger()
|
||||
this.invalidateOwnership()
|
||||
} else if (this.ownership?.valid) {
|
||||
this.scheduleLinger(context, this.ownership)
|
||||
}
|
||||
this.options.onStatus('standby')
|
||||
return
|
||||
}
|
||||
this.cancelLinger()
|
||||
if (this.ownership?.valid && this.ownership.identityKey === nextIdentityKey) {
|
||||
this.options.onStatus('registered')
|
||||
return
|
||||
}
|
||||
this.invalidateOwnership()
|
||||
this.options.onStatus('connecting')
|
||||
const ownership: BrokerOwnership = {
|
||||
identityKey: nextIdentityKey,
|
||||
broker: null,
|
||||
valid: true
|
||||
}
|
||||
this.pendingOwnerships.add(ownership)
|
||||
const isCurrent = (): boolean =>
|
||||
ownership.valid &&
|
||||
!this.stopped &&
|
||||
(ownership.broker ? this.ownership === ownership : this.isEpochCurrent(epoch))
|
||||
let broker: CoordinatedRelayBroker
|
||||
try {
|
||||
broker = await this.options.openBroker({
|
||||
context,
|
||||
isCurrent,
|
||||
refreshAccessToken: () => this.refreshAccessToken(ownership, nextIdentityKey)
|
||||
})
|
||||
} finally {
|
||||
this.pendingOwnerships.delete(ownership)
|
||||
}
|
||||
ownership.broker = broker
|
||||
if (!this.isEpochCurrent(epoch) || !ownership.valid) {
|
||||
broker.closeNow()
|
||||
return
|
||||
}
|
||||
this.ownership = ownership
|
||||
this.options.onStatus('registered')
|
||||
} catch {
|
||||
if (this.isEpochCurrent(epoch)) {
|
||||
this.options.onStatus('offline')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshAccessToken(
|
||||
ownership: { valid: boolean },
|
||||
expectedIdentityKey: string
|
||||
): Promise<string | null> {
|
||||
if (!ownership.valid || this.stopped) {
|
||||
return null
|
||||
}
|
||||
const epoch = this.authEpoch
|
||||
const context = await this.options.readContext()
|
||||
if (
|
||||
!ownership.valid ||
|
||||
!this.isEpochCurrent(epoch) ||
|
||||
!context?.relayEntitled ||
|
||||
identityKey(context.identity) !== expectedIdentityKey
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return context.accessToken
|
||||
}
|
||||
|
||||
private invalidateOwnership(): void {
|
||||
const ownership = this.ownership
|
||||
this.ownership = null
|
||||
if (ownership) {
|
||||
ownership.valid = false
|
||||
ownership.broker?.closeNow()
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleLinger(context: RelayAuthContext, ownership: BrokerOwnership): void {
|
||||
if (this.lingerTimer) {
|
||||
return
|
||||
}
|
||||
const lingerMs = this.options.lingerMs ?? 10 * 60_000
|
||||
this.lingerTimer = setTimeout(() => {
|
||||
this.lingerTimer = null
|
||||
if (
|
||||
this.ownership === ownership &&
|
||||
ownership.valid &&
|
||||
!(this.options.hasDemand?.(context) ?? true)
|
||||
) {
|
||||
this.invalidateOwnership()
|
||||
this.options.onStatus('standby')
|
||||
}
|
||||
}, lingerMs)
|
||||
}
|
||||
|
||||
private cancelLinger(): void {
|
||||
if (this.lingerTimer) {
|
||||
clearTimeout(this.lingerTimer)
|
||||
this.lingerTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
private invalidatePendingOwnerships(): void {
|
||||
for (const ownership of this.pendingOwnerships) {
|
||||
ownership.valid = false
|
||||
}
|
||||
this.pendingOwnerships.clear()
|
||||
}
|
||||
|
||||
private isEpochCurrent(epoch: number): boolean {
|
||||
return !this.stopped && this.authEpoch === epoch
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
import { createHash, createHmac, randomBytes } from 'node:crypto'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import { WebSocketServer, type WebSocket } from 'ws'
|
||||
import type { E2EEKeypair } from '../e2ee-keypair'
|
||||
import { RelayControlClient } from './relay-control-client'
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const HOST_PROOF_DOMAIN = 'orca-relay-host-proof/v1'
|
||||
const CHALLENGE_DOMAIN = 'orca-relay-host-challenge/v1'
|
||||
|
||||
function concat(parts: readonly Uint8Array[]): Uint8Array {
|
||||
const output = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0))
|
||||
let offset = 0
|
||||
for (const part of parts) {
|
||||
output.set(part, offset)
|
||||
offset += part.byteLength
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
function uint32(value: number): Uint8Array {
|
||||
const bytes = new Uint8Array(4)
|
||||
new DataView(bytes.buffer).setUint32(0, value, false)
|
||||
return bytes
|
||||
}
|
||||
|
||||
function uint64(value: number): Uint8Array {
|
||||
const bytes = new Uint8Array(8)
|
||||
new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false)
|
||||
return bytes
|
||||
}
|
||||
|
||||
function field(name: string, value: Uint8Array): Uint8Array {
|
||||
const encodedName = encoder.encode(name)
|
||||
return concat([uint32(encodedName.byteLength), encodedName, uint32(value.byteLength), value])
|
||||
}
|
||||
|
||||
function text(value: string): Uint8Array {
|
||||
return encoder.encode(value)
|
||||
}
|
||||
|
||||
function buildTranscript(input: {
|
||||
origin: string
|
||||
relayKey: Uint8Array
|
||||
nonce: Uint8Array
|
||||
challengeId: string
|
||||
issuedAt: number
|
||||
expiresAt: number
|
||||
relayHostId: string
|
||||
hostKey: Uint8Array
|
||||
}): Uint8Array {
|
||||
return concat([
|
||||
field('protocol', text(HOST_PROOF_DOMAIN)),
|
||||
field('version', new Uint8Array([1])),
|
||||
field('relayOrigin', text(input.origin)),
|
||||
field('relayEphemeralPublicKey', input.relayKey),
|
||||
field('challengeNonce', input.nonce),
|
||||
field('challengeId', text(input.challengeId)),
|
||||
field('issuedAt', uint64(input.issuedAt)),
|
||||
field('expiresAt', uint64(input.expiresAt)),
|
||||
field('userId', text('user-1')),
|
||||
field('profileId', text('profile-1')),
|
||||
field('organizationId', text('org-1')),
|
||||
field('relayHostId', text(input.relayHostId)),
|
||||
field('hostPublicKey', input.hostKey),
|
||||
field('assignmentEpoch', uint64(3)),
|
||||
field('previousGeneration', new Uint8Array()),
|
||||
field('resumeRequested', new Uint8Array([0]))
|
||||
])
|
||||
}
|
||||
|
||||
function nextJson(ws: WebSocket): Promise<Record<string, unknown>> {
|
||||
return new Promise((resolve) => {
|
||||
ws.once('message', (raw) => resolve(JSON.parse(raw.toString()) as Record<string, unknown>))
|
||||
})
|
||||
}
|
||||
|
||||
describe('RelayControlClient', () => {
|
||||
const servers: WebSocketServer[] = []
|
||||
const clients: RelayControlClient[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const client of clients.splice(0)) {
|
||||
client.closeNow()
|
||||
}
|
||||
await Promise.all(
|
||||
servers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
for (const socket of server.clients) {
|
||||
socket.terminate()
|
||||
}
|
||||
server.close(() => resolve())
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('proves the host key and drives control/data commands without URL credentials', async () => {
|
||||
const server = new WebSocketServer({ port: 0, perMessageDeflate: false })
|
||||
servers.push(server)
|
||||
await new Promise<void>((resolve) => server.once('listening', resolve))
|
||||
const address = server.address()
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('expected TCP relay test server')
|
||||
}
|
||||
const origin = `http://127.0.0.1:${address.port}`
|
||||
const hostKeys = nacl.box.keyPair()
|
||||
const keypair: E2EEKeypair = {
|
||||
publicKey: hostKeys.publicKey,
|
||||
secretKey: hostKeys.secretKey,
|
||||
publicKeyB64: Buffer.from(hostKeys.publicKey).toString('base64')
|
||||
}
|
||||
const relayHostId = createHash('sha256')
|
||||
.update(hostKeys.publicKey)
|
||||
.digest('base64url')
|
||||
.slice(0, 16)
|
||||
const accepted = new Promise<{ socket: WebSocket; authorization: string; path: string }>(
|
||||
(resolve) => {
|
||||
server.once('connection', (socket, request) =>
|
||||
resolve({
|
||||
socket,
|
||||
authorization: String(request.headers.authorization),
|
||||
path: request.url ?? ''
|
||||
})
|
||||
)
|
||||
}
|
||||
)
|
||||
const onConnectionOpen = vi.fn()
|
||||
const onDrain = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const client = new RelayControlClient({
|
||||
cellUrl: origin,
|
||||
relayJwt: 'scoped-token',
|
||||
relayHostId,
|
||||
assignmentEpoch: 3,
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
keypair,
|
||||
appVersion: '1.2.3',
|
||||
onConnectionOpen,
|
||||
onDrain,
|
||||
onClose
|
||||
})
|
||||
clients.push(client)
|
||||
const connecting = client.connect()
|
||||
const { socket, authorization, path } = await accepted
|
||||
expect(authorization).toBe('Bearer scoped-token')
|
||||
expect(path).toBe('/v1/host/control')
|
||||
const hello = await nextJson(socket)
|
||||
expect(hello).toMatchObject({
|
||||
type: 'host-hello',
|
||||
relayHostId,
|
||||
assignmentEpoch: 3,
|
||||
hostPublicKeyB64: keypair.publicKeyB64
|
||||
})
|
||||
|
||||
const relayKeys = nacl.box.keyPair()
|
||||
const nonce = randomBytes(24)
|
||||
const secret = randomBytes(32)
|
||||
const issuedAt = Date.now()
|
||||
const expiresAt = issuedAt + 10_000
|
||||
const transcript = buildTranscript({
|
||||
origin,
|
||||
relayKey: relayKeys.publicKey,
|
||||
nonce,
|
||||
challengeId: 'challenge-1',
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
relayHostId,
|
||||
hostKey: hostKeys.publicKey
|
||||
})
|
||||
const plaintext = concat([
|
||||
text(`${CHALLENGE_DOMAIN}\0`),
|
||||
uint32(transcript.byteLength),
|
||||
transcript,
|
||||
secret
|
||||
])
|
||||
const proofMessage = nextJson(socket)
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'host-challenge',
|
||||
challengeId: 'challenge-1',
|
||||
relayEphemeralPublicKeyB64: Buffer.from(relayKeys.publicKey).toString('base64'),
|
||||
nonceB64: nonce.toString('base64'),
|
||||
ciphertextB64: Buffer.from(
|
||||
nacl.box(plaintext, nonce, hostKeys.publicKey, relayKeys.secretKey)
|
||||
).toString('base64'),
|
||||
expiresAt
|
||||
})
|
||||
)
|
||||
const proof = await proofMessage
|
||||
expect(proof).toMatchObject({ type: 'host-challenge-ack', challengeId: 'challenge-1' })
|
||||
const expectedProof = createHmac('sha256', secret)
|
||||
.update(text(`${HOST_PROOF_DOMAIN}\0ack\0`))
|
||||
.update(transcript)
|
||||
.digest('base64')
|
||||
expect(proof.proofB64).toBe(expectedProof)
|
||||
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'host-hello-ack',
|
||||
v: 1,
|
||||
generation: 4,
|
||||
controlResumeSecret: randomBytes(32).toString('base64url'),
|
||||
leaseExpiresAt: Date.now() + 60_000,
|
||||
activeConnIds: [],
|
||||
pendingConns: []
|
||||
})
|
||||
)
|
||||
await expect(connecting).resolves.toMatchObject({ generation: 4 })
|
||||
|
||||
socket.send(JSON.stringify({ type: 'ping', t: Date.now() }))
|
||||
await expect(nextJson(socket)).resolves.toMatchObject({ type: 'pong' })
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'conn-open',
|
||||
connId: 'conn-1',
|
||||
connTicket: randomBytes(32).toString('base64url'),
|
||||
kind: 'invite',
|
||||
relayDeviceId: 'device-1',
|
||||
attachDeadlineMs: 10_000
|
||||
})
|
||||
)
|
||||
await vi.waitFor(() => expect(onConnectionOpen).toHaveBeenCalledOnce())
|
||||
|
||||
const inviteRequest = nextJson(socket)
|
||||
const invitePromise = client.createInvite('device-1', 'invite-req')
|
||||
await expect(inviteRequest).resolves.toEqual({
|
||||
type: 'invite-create',
|
||||
reqId: 'invite-req',
|
||||
relayDeviceId: 'device-1'
|
||||
})
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'invite-created',
|
||||
reqId: 'invite-req',
|
||||
inviteToken: randomBytes(32).toString('base64url'),
|
||||
expiresAt: Date.now() + 60_000,
|
||||
maxAttempts: 3
|
||||
})
|
||||
)
|
||||
await expect(invitePromise).resolves.toMatchObject({ reqId: 'invite-req' })
|
||||
|
||||
const installRequest = nextJson(socket)
|
||||
const installPromise = client.installCredential({
|
||||
reqId: 'install-req',
|
||||
relayDeviceId: 'device-1',
|
||||
newResumeTokenHash: 'A'.repeat(43),
|
||||
authorization: { mode: 'relay-basis', basisConnId: 'conn-1' }
|
||||
})
|
||||
await expect(installRequest).resolves.toEqual({
|
||||
type: 'device-credential-install',
|
||||
v: 1,
|
||||
reqId: 'install-req',
|
||||
relayDeviceId: 'device-1',
|
||||
newResumeTokenHash: 'A'.repeat(43),
|
||||
authorization: { mode: 'relay-basis', basisConnId: 'conn-1' }
|
||||
})
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'device-credential-installed',
|
||||
v: 1,
|
||||
reqId: 'install-req',
|
||||
authorizationMode: 'relay-basis',
|
||||
currentVersion: 1,
|
||||
resumeExpiresAt: Date.now() + 60_000
|
||||
})
|
||||
)
|
||||
await expect(installPromise).resolves.toMatchObject({ currentVersion: 1 })
|
||||
|
||||
const statusRequest = nextJson(socket)
|
||||
const statusPromise = client.credentialInstallStatus('device-1', 'install-req')
|
||||
await expect(statusRequest).resolves.toEqual({
|
||||
type: 'device-credential-install-status',
|
||||
v: 1,
|
||||
reqId: 'install-req',
|
||||
relayDeviceId: 'device-1'
|
||||
})
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'device-credential-install-status-result',
|
||||
v: 1,
|
||||
reqId: 'install-req',
|
||||
state: 'not-found'
|
||||
})
|
||||
)
|
||||
await expect(statusPromise).resolves.toMatchObject({ state: 'not-found' })
|
||||
|
||||
const confirmationRequest = nextJson(socket)
|
||||
const confirmationPromise = client.confirmResume('conn-2', 'confirm-req')
|
||||
await expect(confirmationRequest).resolves.toEqual({
|
||||
type: 'device-resume-confirm',
|
||||
v: 1,
|
||||
reqId: 'confirm-req',
|
||||
basisConnId: 'conn-2'
|
||||
})
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'device-resume-confirmed',
|
||||
v: 1,
|
||||
reqId: 'confirm-req',
|
||||
currentVersion: 1,
|
||||
acceptedAs: 'current',
|
||||
renewed: true,
|
||||
resumeExpiresAt: Date.now() + 60_000
|
||||
})
|
||||
)
|
||||
await expect(confirmationPromise).resolves.toMatchObject({ renewed: true })
|
||||
|
||||
socket.send(JSON.stringify({ type: 'drain', graceMs: 5_000, recovery: 'resolve-director' }))
|
||||
await vi.waitFor(() => expect(onDrain).toHaveBeenCalledOnce())
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,284 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import WebSocket, { type RawData } from 'ws'
|
||||
import { MOBILE_RELAY_CLOSE_CODE } from '../../../shared/mobile-relay-close-codes'
|
||||
import type { E2EEKeypair } from '../e2ee-keypair'
|
||||
import {
|
||||
RelayConnectionOpenMessageSchema,
|
||||
RelayDrainMessageSchema,
|
||||
RelayHostChallengeMessageSchema,
|
||||
RelayHostHelloAckMessageSchema,
|
||||
RelayPingMessageSchema,
|
||||
parseRelayControlMessage,
|
||||
type RelayConnectionOpenMessage,
|
||||
type RelayDrainMessage,
|
||||
type RelayHostHelloAckMessage,
|
||||
type RelayInviteCreatedMessage
|
||||
} from './relay-control-protocol'
|
||||
import { RelayControlRequests } from './relay-control-requests'
|
||||
import type { DeviceCredentialInstallAuthorization } from './relay-control-requests'
|
||||
import { answerRelayHostChallenge } from './relay-host-proof'
|
||||
|
||||
type RelayControlState = 'idle' | 'opening' | 'proving' | 'active' | 'draining' | 'closed'
|
||||
|
||||
type RelayControlClientOptions = {
|
||||
cellUrl: string
|
||||
relayJwt: string
|
||||
relayHostId: string
|
||||
assignmentEpoch: number
|
||||
identity: { userId: string; profileId: string; organizationId: string }
|
||||
keypair: E2EEKeypair
|
||||
appVersion: string
|
||||
previousGeneration?: number
|
||||
controlResumeSecret?: string
|
||||
onConnectionOpen: (message: RelayConnectionOpenMessage) => void
|
||||
onDrain: (message: RelayDrainMessage) => void
|
||||
onClose: (code: number) => void
|
||||
createSocket?: (url: string, relayJwt: string) => WebSocket
|
||||
}
|
||||
|
||||
function controlWebSocketUrl(cellUrl: string): { origin: string; url: string } {
|
||||
const parsed = new URL(cellUrl)
|
||||
if (parsed.pathname !== '/' || parsed.search || parsed.hash) {
|
||||
throw new Error('relay_cell_url_must_be_an_origin')
|
||||
}
|
||||
const origin = parsed.origin
|
||||
if (parsed.protocol === 'https:') {
|
||||
parsed.protocol = 'wss:'
|
||||
} else if (parsed.protocol === 'http:') {
|
||||
parsed.protocol = 'ws:'
|
||||
} else {
|
||||
throw new Error('relay_cell_url_must_use_http')
|
||||
}
|
||||
return { origin, url: `${parsed.origin}/v1/host/control` }
|
||||
}
|
||||
|
||||
export class RelayControlClient {
|
||||
private readonly options: RelayControlClientOptions
|
||||
private readonly relayOrigin: string
|
||||
private readonly controlUrl: string
|
||||
private readonly createSocket: NonNullable<RelayControlClientOptions['createSocket']>
|
||||
private readonly requests = new RelayControlRequests()
|
||||
private socket: WebSocket | null = null
|
||||
private state: RelayControlState = 'idle'
|
||||
private connectResolve: ((ack: RelayHostHelloAckMessage) => void) | null = null
|
||||
private connectReject: ((error: Error) => void) | null = null
|
||||
|
||||
constructor(options: RelayControlClientOptions) {
|
||||
this.options = options
|
||||
const endpoint = controlWebSocketUrl(options.cellUrl)
|
||||
this.relayOrigin = endpoint.origin
|
||||
this.controlUrl = endpoint.url
|
||||
this.createSocket =
|
||||
options.createSocket ??
|
||||
((url, token) =>
|
||||
new WebSocket(url, {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
perMessageDeflate: false,
|
||||
maxPayload: 64 * 1024
|
||||
}))
|
||||
}
|
||||
|
||||
connect(): Promise<RelayHostHelloAckMessage> {
|
||||
if (this.state !== 'idle') {
|
||||
return Promise.reject(new Error('relay_control_already_started'))
|
||||
}
|
||||
this.state = 'opening'
|
||||
const socket = this.createSocket(this.controlUrl, this.options.relayJwt)
|
||||
this.socket = socket
|
||||
socket.once('open', () => this.sendHostHello())
|
||||
socket.on('message', (raw, isBinary) => {
|
||||
if (isBinary) {
|
||||
this.failProtocol('binary control message')
|
||||
return
|
||||
}
|
||||
this.handleMessage(raw)
|
||||
})
|
||||
socket.once('error', (error) => {
|
||||
if (this.state === 'opening' || this.state === 'proving') {
|
||||
this.connectReject?.(error)
|
||||
this.clearConnectPromise()
|
||||
}
|
||||
})
|
||||
socket.once('close', (code) => this.handleClose(code))
|
||||
return new Promise((resolve, reject) => {
|
||||
this.connectResolve = resolve
|
||||
this.connectReject = reject
|
||||
})
|
||||
}
|
||||
|
||||
get pendingRequestCount(): number {
|
||||
return this.requests.size
|
||||
}
|
||||
|
||||
refreshAuthorization(relayJwt: string): void {
|
||||
this.sendActive({ type: 'auth-refresh', relayJwt })
|
||||
}
|
||||
|
||||
createInvite(
|
||||
relayDeviceId: string,
|
||||
reqId: string = randomUUID()
|
||||
): Promise<RelayInviteCreatedMessage> {
|
||||
return this.requests.createInvite(reqId, relayDeviceId, (payload) => this.sendActive(payload))
|
||||
}
|
||||
|
||||
revokeDevice(relayDeviceId: string, reqId: string = randomUUID()): Promise<void> {
|
||||
return this.requests.revokeDevice(reqId, relayDeviceId, (payload) => this.sendActive(payload))
|
||||
}
|
||||
|
||||
installCredential(input: {
|
||||
reqId: string
|
||||
relayDeviceId: string
|
||||
newResumeTokenHash: string
|
||||
expectedCurrentHash?: string
|
||||
authorization: DeviceCredentialInstallAuthorization
|
||||
}): ReturnType<RelayControlRequests['installCredential']> {
|
||||
const { reqId, ...request } = input
|
||||
return this.requests.installCredential(reqId, request, (payload) => this.sendActive(payload))
|
||||
}
|
||||
|
||||
credentialInstallStatus(
|
||||
relayDeviceId: string,
|
||||
reqId: string
|
||||
): ReturnType<RelayControlRequests['credentialInstallStatus']> {
|
||||
return this.requests.credentialInstallStatus(reqId, relayDeviceId, (payload) =>
|
||||
this.sendActive(payload)
|
||||
)
|
||||
}
|
||||
|
||||
confirmResume(
|
||||
basisConnId: string,
|
||||
reqId: string
|
||||
): ReturnType<RelayControlRequests['confirmResume']> {
|
||||
return this.requests.confirmResume(reqId, basisConnId, (payload) => this.sendActive(payload))
|
||||
}
|
||||
|
||||
closeNow(): void {
|
||||
this.state = 'closed'
|
||||
this.requests.rejectAll(new Error('relay_control_closed'))
|
||||
this.socket?.terminate()
|
||||
this.socket = null
|
||||
}
|
||||
|
||||
private sendHostHello(): void {
|
||||
if (!this.socket || this.state !== 'opening') {
|
||||
return
|
||||
}
|
||||
this.state = 'proving'
|
||||
this.socket.send(
|
||||
JSON.stringify({
|
||||
type: 'host-hello',
|
||||
v: 1,
|
||||
relayHostId: this.options.relayHostId,
|
||||
assignmentEpoch: this.options.assignmentEpoch,
|
||||
hostPublicKeyB64: this.options.keypair.publicKeyB64,
|
||||
appVersion: this.options.appVersion,
|
||||
...(this.options.previousGeneration === undefined
|
||||
? {}
|
||||
: { previousGeneration: this.options.previousGeneration }),
|
||||
...(this.options.controlResumeSecret
|
||||
? { controlResumeSecret: this.options.controlResumeSecret }
|
||||
: {})
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
private handleMessage(raw: RawData): void {
|
||||
const message = parseRelayControlMessage(raw)
|
||||
if (!message) {
|
||||
this.failProtocol('invalid control JSON')
|
||||
return
|
||||
}
|
||||
if (this.state === 'proving') {
|
||||
this.handleProofMessage(message)
|
||||
return
|
||||
}
|
||||
if (this.state !== 'active' && this.state !== 'draining') {
|
||||
this.failProtocol('control message before activation')
|
||||
return
|
||||
}
|
||||
if (RelayPingMessageSchema.safeParse(message).success) {
|
||||
this.socket?.send(JSON.stringify({ type: 'pong', t: message.t }))
|
||||
return
|
||||
}
|
||||
const connection = RelayConnectionOpenMessageSchema.safeParse(message)
|
||||
if (connection.success && this.state === 'active') {
|
||||
this.options.onConnectionOpen(connection.data)
|
||||
return
|
||||
}
|
||||
const drain = RelayDrainMessageSchema.safeParse(message)
|
||||
if (drain.success) {
|
||||
this.state = 'draining'
|
||||
this.options.onDrain(drain.data)
|
||||
return
|
||||
}
|
||||
if (this.requests.resolveMessage(message)) {
|
||||
return
|
||||
}
|
||||
this.failProtocol('unknown control message')
|
||||
}
|
||||
|
||||
private handleProofMessage(message: Record<string, unknown>): void {
|
||||
const challenge = RelayHostChallengeMessageSchema.safeParse(message)
|
||||
if (challenge.success) {
|
||||
const proofB64 = answerRelayHostChallenge(challenge.data, {
|
||||
relayOrigin: this.relayOrigin,
|
||||
...this.options.identity,
|
||||
relayHostId: this.options.relayHostId,
|
||||
hostPublicKey: this.options.keypair.publicKey,
|
||||
hostSecretKey: this.options.keypair.secretKey,
|
||||
assignmentEpoch: this.options.assignmentEpoch,
|
||||
previousGeneration: this.options.previousGeneration,
|
||||
resumeRequested: Boolean(this.options.controlResumeSecret)
|
||||
})
|
||||
if (!proofB64) {
|
||||
this.failProtocol('invalid host challenge')
|
||||
return
|
||||
}
|
||||
this.socket?.send(
|
||||
JSON.stringify({
|
||||
type: 'host-challenge-ack',
|
||||
challengeId: challenge.data.challengeId,
|
||||
proofB64
|
||||
})
|
||||
)
|
||||
return
|
||||
}
|
||||
const ack = RelayHostHelloAckMessageSchema.safeParse(message)
|
||||
if (!ack.success) {
|
||||
this.failProtocol('invalid host proof message')
|
||||
return
|
||||
}
|
||||
this.state = 'active'
|
||||
this.connectResolve?.(ack.data)
|
||||
this.clearConnectPromise()
|
||||
}
|
||||
|
||||
private sendActive(payload: object): void {
|
||||
if (!this.socket || (this.state !== 'active' && this.state !== 'draining')) {
|
||||
throw new Error('relay_control_not_active')
|
||||
}
|
||||
this.socket.send(JSON.stringify(payload))
|
||||
}
|
||||
|
||||
private failProtocol(reason: string): void {
|
||||
this.connectReject?.(new Error(reason))
|
||||
this.clearConnectPromise()
|
||||
this.socket?.close(MOBILE_RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, reason)
|
||||
}
|
||||
|
||||
private handleClose(code: number): void {
|
||||
const wasConnecting = this.state === 'opening' || this.state === 'proving'
|
||||
this.state = 'closed'
|
||||
if (wasConnecting) {
|
||||
this.connectReject?.(new Error(`relay_control_closed_${code}`))
|
||||
this.clearConnectPromise()
|
||||
}
|
||||
this.requests.rejectAll(new Error(`relay_control_closed_${code}`))
|
||||
this.options.onClose(code)
|
||||
}
|
||||
|
||||
private clearConnectPromise(): void {
|
||||
this.connectResolve = null
|
||||
this.connectReject = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { E2EEKeypair } from '../e2ee-keypair'
|
||||
import { CloudRelayTransport } from '../rpc/relay-transport'
|
||||
import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring'
|
||||
import { RelayControlClient } from './relay-control-client'
|
||||
import type {
|
||||
RelayConnectionOpenMessage,
|
||||
RelayDrainMessage,
|
||||
RelayHostHelloAckMessage
|
||||
} from './relay-control-protocol'
|
||||
import type { RelayIdentity } from './relay-session-broker-contract'
|
||||
import type { RelayAssignment } from './relay-http-client'
|
||||
|
||||
type RelayControlOriginOptions = {
|
||||
assignment: RelayAssignment
|
||||
relayJwt: string
|
||||
relayHostId: string
|
||||
identity: RelayIdentity
|
||||
keypair: E2EEKeypair
|
||||
appVersion: string
|
||||
mobileSocketWiring: MobileSocketWiring
|
||||
createControlSocket?: (url: string, relayJwt: string) => WebSocket
|
||||
createDataSocket?: (url: string) => WebSocket
|
||||
onConnectionOwned: (connectionId: string, origin: RelayControlOrigin) => void
|
||||
onConnectionReleased: (connectionId: string, origin: RelayControlOrigin) => void
|
||||
onDrain: (origin: RelayControlOrigin, message: RelayDrainMessage) => void
|
||||
onClose: (origin: RelayControlOrigin, code: number) => void
|
||||
}
|
||||
|
||||
export class RelayControlOrigin {
|
||||
readonly assignment: RelayAssignment
|
||||
readonly transport: CloudRelayTransport
|
||||
private readonly options: RelayControlOriginOptions
|
||||
private readonly controls = new Set<RelayControlClient>()
|
||||
private readonly retiredControlTimers = new Map<
|
||||
RelayControlClient,
|
||||
ReturnType<typeof setTimeout>
|
||||
>()
|
||||
private activeControl: RelayControlClient | null = null
|
||||
private generation = 0
|
||||
private controlResumeSecret: string | null = null
|
||||
private leaseExpiresAt = 0
|
||||
private acceptingConnections = true
|
||||
private closed = false
|
||||
|
||||
constructor(options: RelayControlOriginOptions) {
|
||||
this.options = options
|
||||
this.assignment = options.assignment
|
||||
this.transport = new CloudRelayTransport({
|
||||
cellUrl: options.assignment.cellUrl,
|
||||
relayHostId: options.relayHostId,
|
||||
generation: 0,
|
||||
createSocket: options.createDataSocket,
|
||||
onConnectionClosed: (connectionId) => options.onConnectionReleased(connectionId, this)
|
||||
})
|
||||
options.mobileSocketWiring.attachTransport(this.transport, (ws) =>
|
||||
this.transport.metadataFor(ws)
|
||||
)
|
||||
}
|
||||
|
||||
get control(): RelayControlClient {
|
||||
if (!this.activeControl) {
|
||||
throw new Error('relay_control_not_active')
|
||||
}
|
||||
return this.activeControl
|
||||
}
|
||||
|
||||
get availableControl(): RelayControlClient | null {
|
||||
return this.activeControl
|
||||
}
|
||||
|
||||
get cellUrl(): string {
|
||||
return this.assignment.cellUrl
|
||||
}
|
||||
|
||||
get assignmentEpoch(): number {
|
||||
return this.assignment.assignmentEpoch
|
||||
}
|
||||
|
||||
get controlLeaseExpiresAt(): number {
|
||||
return this.leaseExpiresAt
|
||||
}
|
||||
|
||||
get pendingRequestCount(): number {
|
||||
let count = 0
|
||||
for (const control of this.controls) {
|
||||
count += control.pendingRequestCount
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
async open(): Promise<void> {
|
||||
await this.transport.start()
|
||||
const { control, ack } = await this.openControl()
|
||||
this.activate(control, ack)
|
||||
}
|
||||
|
||||
async rebind(relayJwt: string, assignment: RelayAssignment): Promise<void> {
|
||||
if (assignment.cellUrl !== this.cellUrl || !this.controlResumeSecret || this.generation <= 0) {
|
||||
throw new Error('relay_control_rebind_origin_mismatch')
|
||||
}
|
||||
const previous = this.activeControl
|
||||
const { control, ack } = await this.openControl({
|
||||
relayJwt,
|
||||
assignmentEpoch: assignment.assignmentEpoch,
|
||||
previousGeneration: this.generation,
|
||||
controlResumeSecret: this.controlResumeSecret
|
||||
})
|
||||
this.activate(control, ack)
|
||||
this.acceptingConnections = true
|
||||
// Why: the resumed control owns the same server generation and splices;
|
||||
// the predecessor remains only long enough for any idempotent reply in flight.
|
||||
if (previous && previous.pendingRequestCount === 0) {
|
||||
this.closeRetiredControl(previous)
|
||||
} else if (previous) {
|
||||
// Why: basis-bound requests keep their original control through its
|
||||
// bounded request deadline; afterward the resumed control is sole owner.
|
||||
this.retiredControlTimers.set(
|
||||
previous,
|
||||
setTimeout(() => this.closeRetiredControl(previous), 10_100)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
markDraining(): void {
|
||||
// The relay changes the control's protocol state when it sends drain. This
|
||||
// marker exists for the broker's ownership policy, not a second wire event.
|
||||
this.acceptingConnections = false
|
||||
}
|
||||
|
||||
refreshAuthorization(relayJwt: string): void {
|
||||
for (const control of this.controls) {
|
||||
try {
|
||||
control.refreshAuthorization(relayJwt)
|
||||
} catch {
|
||||
// A closing drain-only origin cannot block refresh on the active target.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) {
|
||||
return
|
||||
}
|
||||
this.closed = true
|
||||
for (const timer of this.retiredControlTimers.values()) {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
this.retiredControlTimers.clear()
|
||||
for (const control of this.controls) {
|
||||
control.closeNow()
|
||||
}
|
||||
this.controls.clear()
|
||||
this.activeControl = null
|
||||
await this.transport.stop()
|
||||
}
|
||||
|
||||
closeNow(): void {
|
||||
void this.close()
|
||||
}
|
||||
|
||||
private async openControl(overrides?: {
|
||||
relayJwt: string
|
||||
assignmentEpoch: number
|
||||
previousGeneration: number
|
||||
controlResumeSecret: string
|
||||
}): Promise<{ control: RelayControlClient; ack: RelayHostHelloAckMessage }> {
|
||||
let control!: RelayControlClient
|
||||
control = new RelayControlClient({
|
||||
cellUrl: this.cellUrl,
|
||||
relayJwt: overrides?.relayJwt ?? this.options.relayJwt,
|
||||
relayHostId: this.options.relayHostId,
|
||||
assignmentEpoch: overrides?.assignmentEpoch ?? this.assignmentEpoch,
|
||||
identity: this.options.identity,
|
||||
keypair: this.options.keypair,
|
||||
appVersion: this.options.appVersion,
|
||||
...(overrides
|
||||
? {
|
||||
previousGeneration: overrides.previousGeneration,
|
||||
controlResumeSecret: overrides.controlResumeSecret
|
||||
}
|
||||
: {}),
|
||||
onConnectionOpen: (message) => this.openConnection(message),
|
||||
onDrain: (message) => this.options.onDrain(this, message),
|
||||
onClose: (code) => {
|
||||
this.controls.delete(control)
|
||||
const timer = this.retiredControlTimers.get(control)
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
this.retiredControlTimers.delete(control)
|
||||
}
|
||||
if (this.activeControl === control) {
|
||||
this.activeControl = null
|
||||
this.options.onClose(this, code)
|
||||
}
|
||||
},
|
||||
createSocket: this.options.createControlSocket
|
||||
})
|
||||
this.controls.add(control)
|
||||
try {
|
||||
return { control, ack: await control.connect() }
|
||||
} catch (error) {
|
||||
this.controls.delete(control)
|
||||
control.closeNow()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private closeRetiredControl(control: RelayControlClient): void {
|
||||
const timer = this.retiredControlTimers.get(control)
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
this.retiredControlTimers.delete(control)
|
||||
}
|
||||
if (this.activeControl !== control && this.controls.delete(control)) {
|
||||
control.closeNow()
|
||||
}
|
||||
}
|
||||
|
||||
private activate(control: RelayControlClient, ack: RelayHostHelloAckMessage): void {
|
||||
if (ack.generation <= 0) {
|
||||
throw new Error('invalid_relay_generation')
|
||||
}
|
||||
this.transport.setGeneration(ack.generation)
|
||||
this.generation = ack.generation
|
||||
this.controlResumeSecret = ack.controlResumeSecret
|
||||
this.leaseExpiresAt = ack.leaseExpiresAt
|
||||
this.activeControl = control
|
||||
for (const connectionId of ack.activeConnIds) {
|
||||
this.options.onConnectionOwned(connectionId, this)
|
||||
}
|
||||
}
|
||||
|
||||
private openConnection(message: RelayConnectionOpenMessage): void {
|
||||
if (!this.acceptingConnections) {
|
||||
return
|
||||
}
|
||||
this.options.onConnectionOwned(message.connId, this)
|
||||
void this.transport.openConnection(message).catch(() => {
|
||||
this.options.onConnectionReleased(message.connId, this)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { z } from 'zod'
|
||||
import type { RawData } from 'ws'
|
||||
import {
|
||||
DeviceCredentialInstalledSchema,
|
||||
DeviceResumeConfirmedSchema
|
||||
} from '../../../shared/mobile-relay-credential-contract'
|
||||
|
||||
const OpaqueIdSchema = z.string().min(1).max(128)
|
||||
const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/)
|
||||
const Base6432ByteSchema = z.string().regex(/^[A-Za-z0-9+/]{43}=$/)
|
||||
const Base64Raw24ByteSchema = z.string().regex(/^[A-Za-z0-9+/]{32}$/)
|
||||
const EpochMsSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
|
||||
const GenerationSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
|
||||
|
||||
export const RelayHostChallengeMessageSchema = z
|
||||
.object({
|
||||
type: z.literal('host-challenge'),
|
||||
challengeId: OpaqueIdSchema,
|
||||
relayEphemeralPublicKeyB64: Base6432ByteSchema,
|
||||
nonceB64: Base64Raw24ByteSchema,
|
||||
ciphertextB64: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(16 * 1024),
|
||||
expiresAt: EpochMsSchema
|
||||
})
|
||||
.strict()
|
||||
|
||||
const PendingConnectionSchema = z
|
||||
.object({ connId: OpaqueIdSchema, connTicket: Base64Url32ByteSchema })
|
||||
.strict()
|
||||
|
||||
export const RelayHostHelloAckMessageSchema = z
|
||||
.object({
|
||||
type: z.literal('host-hello-ack'),
|
||||
v: z.literal(1),
|
||||
generation: GenerationSchema,
|
||||
controlResumeSecret: Base64Url32ByteSchema,
|
||||
leaseExpiresAt: EpochMsSchema,
|
||||
activeConnIds: z.array(OpaqueIdSchema).max(8),
|
||||
pendingConns: z.array(PendingConnectionSchema).max(8)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const RelayConnectionOpenMessageSchema = z
|
||||
.object({
|
||||
type: z.literal('conn-open'),
|
||||
connId: OpaqueIdSchema,
|
||||
connTicket: Base64Url32ByteSchema,
|
||||
kind: z.enum(['invite', 'resume']),
|
||||
relayDeviceId: OpaqueIdSchema,
|
||||
attachDeadlineMs: z.number().int().positive().max(60_000)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const RelayDrainMessageSchema = z
|
||||
.object({
|
||||
type: z.literal('drain'),
|
||||
graceMs: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.max(60 * 60 * 1000),
|
||||
recovery: z.literal('resolve-director')
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const RelayPingMessageSchema = z
|
||||
.object({ type: z.literal('ping'), t: EpochMsSchema })
|
||||
.strict()
|
||||
|
||||
export const RelayInviteCreatedMessageSchema = z
|
||||
.object({
|
||||
type: z.literal('invite-created'),
|
||||
reqId: OpaqueIdSchema,
|
||||
inviteToken: Base64Url32ByteSchema,
|
||||
expiresAt: EpochMsSchema,
|
||||
maxAttempts: z.number().int().positive().max(16)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const RelayDeviceRevokedMessageSchema = z
|
||||
.object({ type: z.literal('device-revoked'), reqId: OpaqueIdSchema })
|
||||
.strict()
|
||||
|
||||
export const RelayDeviceCredentialInstalledMessageSchema = DeviceCredentialInstalledSchema.extend({
|
||||
type: z.literal('device-credential-installed')
|
||||
}).strict()
|
||||
|
||||
export const RelayDeviceCredentialInstallStatusResultMessageSchema = z.union([
|
||||
z
|
||||
.object({
|
||||
type: z.literal('device-credential-install-status-result'),
|
||||
v: z.literal(1),
|
||||
reqId: OpaqueIdSchema,
|
||||
state: z.literal('not-found')
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal('device-credential-install-status-result'),
|
||||
v: z.literal(1),
|
||||
reqId: OpaqueIdSchema,
|
||||
state: z.literal('committed'),
|
||||
result: DeviceCredentialInstalledSchema
|
||||
})
|
||||
.strict()
|
||||
])
|
||||
|
||||
export const RelayDeviceResumeConfirmedMessageSchema = DeviceResumeConfirmedSchema.extend({
|
||||
type: z.literal('device-resume-confirmed')
|
||||
}).strict()
|
||||
|
||||
export const RelayControlErrorMessageSchema = z
|
||||
.object({
|
||||
type: z.literal('control-error'),
|
||||
reqId: OpaqueIdSchema.optional(),
|
||||
code: z.string().min(1).max(128)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type RelayHostChallengeMessage = z.infer<typeof RelayHostChallengeMessageSchema>
|
||||
export type RelayHostHelloAckMessage = z.infer<typeof RelayHostHelloAckMessageSchema>
|
||||
export type RelayConnectionOpenMessage = z.infer<typeof RelayConnectionOpenMessageSchema>
|
||||
export type RelayDrainMessage = z.infer<typeof RelayDrainMessageSchema>
|
||||
export type RelayInviteCreatedMessage = z.infer<typeof RelayInviteCreatedMessageSchema>
|
||||
export type RelayDeviceCredentialInstalledMessage = z.infer<
|
||||
typeof RelayDeviceCredentialInstalledMessageSchema
|
||||
>
|
||||
export type RelayDeviceCredentialInstallStatusResultMessage = z.infer<
|
||||
typeof RelayDeviceCredentialInstallStatusResultMessageSchema
|
||||
>
|
||||
export type RelayDeviceResumeConfirmedMessage = z.infer<
|
||||
typeof RelayDeviceResumeConfirmedMessageSchema
|
||||
>
|
||||
|
||||
export function parseRelayControlMessage(raw: RawData): Record<string, unknown> | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw.toString()) as unknown
|
||||
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import {
|
||||
RelayControlErrorMessageSchema,
|
||||
RelayDeviceCredentialInstalledMessageSchema,
|
||||
RelayDeviceCredentialInstallStatusResultMessageSchema,
|
||||
RelayDeviceRevokedMessageSchema,
|
||||
RelayDeviceResumeConfirmedMessageSchema,
|
||||
RelayInviteCreatedMessageSchema,
|
||||
type RelayDeviceCredentialInstalledMessage,
|
||||
type RelayDeviceCredentialInstallStatusResultMessage,
|
||||
type RelayDeviceResumeConfirmedMessage,
|
||||
type RelayInviteCreatedMessage
|
||||
} from './relay-control-protocol'
|
||||
|
||||
type PendingRequest = {
|
||||
kind: 'invite' | 'revoke' | 'install' | 'install-status' | 'confirm'
|
||||
resolve: (value: unknown) => void
|
||||
reject: (error: Error) => void
|
||||
timer: ReturnType<typeof setTimeout>
|
||||
}
|
||||
|
||||
export type DeviceCredentialInstallAuthorization =
|
||||
| { mode: 'relay-basis'; basisConnId: string }
|
||||
| { mode: 'authenticated-direct'; directAuthId: string }
|
||||
|
||||
export class RelayControlRequests {
|
||||
private readonly pending = new Map<string, PendingRequest>()
|
||||
|
||||
get size(): number {
|
||||
return this.pending.size
|
||||
}
|
||||
|
||||
createInvite(
|
||||
reqId: string,
|
||||
relayDeviceId: string,
|
||||
send: (payload: object) => void
|
||||
): Promise<RelayInviteCreatedMessage> {
|
||||
return this.request(
|
||||
reqId,
|
||||
'invite',
|
||||
{ type: 'invite-create', reqId, relayDeviceId },
|
||||
send
|
||||
) as Promise<RelayInviteCreatedMessage>
|
||||
}
|
||||
|
||||
revokeDevice(
|
||||
reqId: string,
|
||||
relayDeviceId: string,
|
||||
send: (payload: object) => void
|
||||
): Promise<void> {
|
||||
return this.request(
|
||||
reqId,
|
||||
'revoke',
|
||||
{ type: 'device-revoke', reqId, relayDeviceId },
|
||||
send
|
||||
) as Promise<void>
|
||||
}
|
||||
|
||||
installCredential(
|
||||
reqId: string,
|
||||
input: {
|
||||
relayDeviceId: string
|
||||
newResumeTokenHash: string
|
||||
expectedCurrentHash?: string
|
||||
authorization: DeviceCredentialInstallAuthorization
|
||||
},
|
||||
send: (payload: object) => void
|
||||
): Promise<RelayDeviceCredentialInstalledMessage> {
|
||||
return this.request(
|
||||
reqId,
|
||||
'install',
|
||||
{ type: 'device-credential-install', v: 1, reqId, ...input },
|
||||
send
|
||||
) as Promise<RelayDeviceCredentialInstalledMessage>
|
||||
}
|
||||
|
||||
credentialInstallStatus(
|
||||
reqId: string,
|
||||
relayDeviceId: string,
|
||||
send: (payload: object) => void
|
||||
): Promise<RelayDeviceCredentialInstallStatusResultMessage> {
|
||||
return this.request(
|
||||
reqId,
|
||||
'install-status',
|
||||
{ type: 'device-credential-install-status', v: 1, reqId, relayDeviceId },
|
||||
send
|
||||
) as Promise<RelayDeviceCredentialInstallStatusResultMessage>
|
||||
}
|
||||
|
||||
confirmResume(
|
||||
reqId: string,
|
||||
basisConnId: string,
|
||||
send: (payload: object) => void
|
||||
): Promise<RelayDeviceResumeConfirmedMessage> {
|
||||
return this.request(
|
||||
reqId,
|
||||
'confirm',
|
||||
{ type: 'device-resume-confirm', v: 1, reqId, basisConnId },
|
||||
send
|
||||
) as Promise<RelayDeviceResumeConfirmedMessage>
|
||||
}
|
||||
|
||||
resolveMessage(message: Record<string, unknown>): boolean {
|
||||
const reqId = typeof message.reqId === 'string' ? message.reqId : null
|
||||
const pending = reqId ? this.pending.get(reqId) : null
|
||||
if (!pending || !reqId) {
|
||||
return false
|
||||
}
|
||||
const error = RelayControlErrorMessageSchema.safeParse(message)
|
||||
if (error.success) {
|
||||
this.finish(reqId)
|
||||
pending.reject(new Error(error.data.code))
|
||||
return true
|
||||
}
|
||||
if (pending.kind === 'invite') {
|
||||
const invite = RelayInviteCreatedMessageSchema.safeParse(message)
|
||||
if (!invite.success) {
|
||||
return false
|
||||
}
|
||||
this.finish(reqId)
|
||||
pending.resolve(invite.data)
|
||||
return true
|
||||
}
|
||||
if (pending.kind === 'revoke') {
|
||||
const revoked = RelayDeviceRevokedMessageSchema.safeParse(message)
|
||||
if (!revoked.success) {
|
||||
return false
|
||||
}
|
||||
this.finish(reqId)
|
||||
pending.resolve(undefined)
|
||||
return true
|
||||
}
|
||||
const schema =
|
||||
pending.kind === 'install'
|
||||
? RelayDeviceCredentialInstalledMessageSchema
|
||||
: pending.kind === 'install-status'
|
||||
? RelayDeviceCredentialInstallStatusResultMessageSchema
|
||||
: RelayDeviceResumeConfirmedMessageSchema
|
||||
const result = schema.safeParse(message)
|
||||
if (!result.success) {
|
||||
return false
|
||||
}
|
||||
this.finish(reqId)
|
||||
pending.resolve(result.data)
|
||||
return true
|
||||
}
|
||||
|
||||
rejectAll(error: Error): void {
|
||||
for (const [reqId, pending] of this.pending) {
|
||||
this.finish(reqId)
|
||||
pending.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
private request(
|
||||
reqId: string,
|
||||
kind: PendingRequest['kind'],
|
||||
payload: object,
|
||||
send: (payload: object) => void
|
||||
): Promise<unknown> {
|
||||
if (this.pending.has(reqId)) {
|
||||
return Promise.reject(new Error('duplicate_relay_request_id'))
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(reqId)
|
||||
reject(new Error('relay_control_request_timeout'))
|
||||
}, 10_000)
|
||||
this.pending.set(reqId, { kind, resolve, reject, timer })
|
||||
try {
|
||||
send(payload)
|
||||
} catch (error) {
|
||||
this.finish(reqId)
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private finish(reqId: string): void {
|
||||
const pending = this.pending.get(reqId)
|
||||
if (pending) {
|
||||
clearTimeout(pending.timer)
|
||||
this.pending.delete(reqId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DeviceRegistry } from '../device-registry'
|
||||
import { RelayDemandLedger } from './relay-demand-ledger'
|
||||
import { RelayRevokeOutbox, type RelayDeviceBinding } from './relay-revoke-outbox'
|
||||
|
||||
const ownerIdentityKey = 'user-1\0profile-1\0org-1'
|
||||
const relayHostId = 'relay-host-1'
|
||||
|
||||
function fixture(now: number) {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-relay-demand-'))
|
||||
const deviceRegistry = new DeviceRegistry(userDataPath)
|
||||
const revokeOutbox = new RelayRevokeOutbox(userDataPath)
|
||||
const ledger = new RelayDemandLedger({
|
||||
deviceRegistry,
|
||||
revokeOutbox,
|
||||
relayHostId,
|
||||
now: () => now
|
||||
})
|
||||
return { userDataPath, deviceRegistry, revokeOutbox, ledger }
|
||||
}
|
||||
|
||||
function binding(relayDeviceId: string, inviteExpiresAt?: number): RelayDeviceBinding {
|
||||
return { relayDeviceId, relayHostId, ownerIdentityKey, inviteExpiresAt }
|
||||
}
|
||||
|
||||
describe('RelayDemandLedger', () => {
|
||||
it('reference-counts concurrent main-process work', () => {
|
||||
const { ledger } = fixture(1_000)
|
||||
const releaseFirst = ledger.acquireTransient('pairing:device-1')
|
||||
const releaseSecond = ledger.acquireTransient('pairing:device-1')
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(true)
|
||||
releaseFirst()
|
||||
releaseFirst()
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(true)
|
||||
releaseSecond()
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(false)
|
||||
})
|
||||
|
||||
it('holds pending QR demand only through invite expiry', () => {
|
||||
const { userDataPath, deviceRegistry, ledger } = fixture(1_000)
|
||||
const pending = deviceRegistry.addDevice('Pending phone')
|
||||
deviceRegistry.setRelayBinding(pending.deviceId, binding(pending.deviceId, 2_000))
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(true)
|
||||
expect(ledger.nextPendingExpiry()).toBe(2_000)
|
||||
const restarted = new RelayDemandLedger({
|
||||
deviceRegistry: new DeviceRegistry(userDataPath),
|
||||
revokeOutbox: new RelayRevokeOutbox(userDataPath),
|
||||
relayHostId,
|
||||
now: () => 1_500
|
||||
})
|
||||
expect(restarted.hasDemand(ownerIdentityKey)).toBe(true)
|
||||
|
||||
const expiredFixture = fixture(3_000)
|
||||
const expired = expiredFixture.deviceRegistry.addDevice('Expired phone')
|
||||
expiredFixture.deviceRegistry.setRelayBinding(
|
||||
expired.deviceId,
|
||||
binding(expired.deviceId, 2_000)
|
||||
)
|
||||
expect(expiredFixture.ledger.hasDemand(ownerIdentityKey)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not promote a scanned invite to provisioned demand before install', () => {
|
||||
const { deviceRegistry, ledger } = fixture(3_000)
|
||||
const scanned = deviceRegistry.addDevice('Scanned phone')
|
||||
deviceRegistry.setRelayBinding(scanned.deviceId, binding(scanned.deviceId, 2_000))
|
||||
deviceRegistry.updateLastSeen(scanned.deviceId)
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps provisioned devices and revoke outbox work authoritative', () => {
|
||||
const { deviceRegistry, revokeOutbox, ledger } = fixture(5_000)
|
||||
const paired = deviceRegistry.addDevice('Paired phone')
|
||||
deviceRegistry.setRelayBinding(paired.deviceId, binding(paired.deviceId))
|
||||
deviceRegistry.updateLastSeen(paired.deviceId)
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(true)
|
||||
|
||||
deviceRegistry.removeDevice(paired.deviceId)
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(false)
|
||||
revokeOutbox.enqueue(binding(paired.deviceId))
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not activate another signed-in identity or relay host', () => {
|
||||
const { deviceRegistry, ledger } = fixture(1_000)
|
||||
const pending = deviceRegistry.addDevice('Other phone')
|
||||
deviceRegistry.setRelayBinding(pending.deviceId, {
|
||||
...binding(pending.deviceId, 2_000),
|
||||
ownerIdentityKey: 'other-user\0profile\0org'
|
||||
})
|
||||
expect(ledger.hasDemand(ownerIdentityKey)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { DeviceRegistry } from '../device-registry'
|
||||
import type { RelayRevokeOutbox } from './relay-revoke-outbox'
|
||||
|
||||
type RelayDemandLedgerOptions = {
|
||||
deviceRegistry: DeviceRegistry
|
||||
revokeOutbox: RelayRevokeOutbox
|
||||
relayHostId: string
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export class RelayDemandLedger {
|
||||
private readonly options: RelayDemandLedgerOptions
|
||||
private readonly transientRefs = new Map<string, number>()
|
||||
|
||||
constructor(options: RelayDemandLedgerOptions) {
|
||||
this.options = options
|
||||
}
|
||||
|
||||
acquireTransient(key: string): () => void {
|
||||
this.transientRefs.set(key, (this.transientRefs.get(key) ?? 0) + 1)
|
||||
let released = false
|
||||
return () => {
|
||||
if (released) {
|
||||
return
|
||||
}
|
||||
released = true
|
||||
const count = this.transientRefs.get(key) ?? 0
|
||||
if (count <= 1) {
|
||||
this.transientRefs.delete(key)
|
||||
} else {
|
||||
this.transientRefs.set(key, count - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasDemand(ownerIdentityKey: string): boolean {
|
||||
if (this.transientRefs.size > 0) {
|
||||
return true
|
||||
}
|
||||
if (this.options.revokeOutbox.pendingFor(ownerIdentityKey, this.options.relayHostId).length) {
|
||||
return true
|
||||
}
|
||||
const now = (this.options.now ?? Date.now)()
|
||||
return this.options.deviceRegistry.listDevices().some((device) => {
|
||||
const binding = device.relayBinding
|
||||
if (
|
||||
device.scope !== 'mobile' ||
|
||||
!binding ||
|
||||
binding.ownerIdentityKey !== ownerIdentityKey ||
|
||||
binding.relayHostId !== this.options.relayHostId
|
||||
) {
|
||||
return false
|
||||
}
|
||||
// Why: E2EE authentication marks a scanned DeviceEntry as seen before
|
||||
// relay credential install commits. Only removing the invite expiry at
|
||||
// the durable install boundary promotes it to standing device demand.
|
||||
return binding.inviteExpiresAt === undefined || binding.inviteExpiresAt > now
|
||||
})
|
||||
}
|
||||
|
||||
nextPendingExpiry(): number | null {
|
||||
const now = (this.options.now ?? Date.now)()
|
||||
let next: number | null = null
|
||||
for (const device of this.options.deviceRegistry.listDevices()) {
|
||||
const expiresAt = device.relayBinding?.inviteExpiresAt
|
||||
if (expiresAt && expiresAt > now && (next === null || expiresAt < next)) {
|
||||
next = expiresAt
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto'
|
||||
import nacl from 'tweetnacl'
|
||||
|
||||
const HOST_PROOF_TRANSCRIPT_DOMAIN = 'orca-relay-host-proof/v1'
|
||||
const HOST_CHALLENGE_PLAINTEXT_DOMAIN = 'orca-relay-host-challenge/v1'
|
||||
const textEncoder = new TextEncoder()
|
||||
const textDecoder = new TextDecoder()
|
||||
|
||||
export type RelayHostChallenge = {
|
||||
challengeId: string
|
||||
relayEphemeralPublicKeyB64: string
|
||||
nonceB64: string
|
||||
ciphertextB64: string
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
export type RelayHostProofContext = {
|
||||
relayOrigin: string
|
||||
userId: string
|
||||
profileId: string
|
||||
organizationId: string
|
||||
relayHostId: string
|
||||
hostPublicKey: Uint8Array
|
||||
hostSecretKey: Uint8Array
|
||||
assignmentEpoch: number
|
||||
previousGeneration?: number
|
||||
resumeRequested: boolean
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
function decodeCanonicalBase64(value: string, expectedBytes: number): Uint8Array | null {
|
||||
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
|
||||
return null
|
||||
}
|
||||
const decoded = Buffer.from(value, 'base64')
|
||||
return decoded.byteLength === expectedBytes && decoded.toString('base64') === value
|
||||
? decoded
|
||||
: null
|
||||
}
|
||||
|
||||
function uint64(value: number): Uint8Array {
|
||||
const bytes = new Uint8Array(8)
|
||||
new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false)
|
||||
return bytes
|
||||
}
|
||||
|
||||
function equal(left: Uint8Array | undefined, right: Uint8Array): boolean {
|
||||
return Boolean(left && left.byteLength === right.byteLength && timingSafeEqual(left, right))
|
||||
}
|
||||
|
||||
function parseTranscript(transcript: Uint8Array): Map<string, Uint8Array> | null {
|
||||
const fields = new Map<string, Uint8Array>()
|
||||
const view = new DataView(transcript.buffer, transcript.byteOffset, transcript.byteLength)
|
||||
let offset = 0
|
||||
try {
|
||||
while (offset < transcript.byteLength) {
|
||||
const nameLength = view.getUint32(offset, false)
|
||||
offset += 4
|
||||
const name = textDecoder.decode(transcript.slice(offset, offset + nameLength))
|
||||
offset += nameLength
|
||||
const valueLength = view.getUint32(offset, false)
|
||||
offset += 4
|
||||
if (fields.has(name) || offset + valueLength > transcript.byteLength) {
|
||||
return null
|
||||
}
|
||||
fields.set(name, transcript.slice(offset, offset + valueLength))
|
||||
offset += valueLength
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return offset === transcript.byteLength ? fields : null
|
||||
}
|
||||
|
||||
function readUint64(value: Uint8Array | undefined): number | null {
|
||||
if (!value || value.byteLength !== 8) {
|
||||
return null
|
||||
}
|
||||
const parsed = new DataView(value.buffer, value.byteOffset, value.byteLength).getBigUint64(
|
||||
0,
|
||||
false
|
||||
)
|
||||
return parsed <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(parsed) : null
|
||||
}
|
||||
|
||||
function validateTranscript(
|
||||
transcript: Uint8Array,
|
||||
challenge: RelayHostChallenge,
|
||||
context: RelayHostProofContext,
|
||||
relayKey: Uint8Array,
|
||||
nonce: Uint8Array
|
||||
): boolean {
|
||||
const fields = parseTranscript(transcript)
|
||||
if (!fields || fields.size !== 16) {
|
||||
return false
|
||||
}
|
||||
const now = (context.now ?? Date.now)()
|
||||
const issuedAt = readUint64(fields.get('issuedAt'))
|
||||
const expiresAt = readUint64(fields.get('expiresAt'))
|
||||
const previousGeneration = fields.get('previousGeneration')
|
||||
const expectedPrevious =
|
||||
context.previousGeneration === undefined ? new Uint8Array() : uint64(context.previousGeneration)
|
||||
return (
|
||||
issuedAt !== null &&
|
||||
issuedAt <= now &&
|
||||
now <= challenge.expiresAt &&
|
||||
challenge.expiresAt - issuedAt <= 10_000 &&
|
||||
expiresAt === challenge.expiresAt &&
|
||||
equal(fields.get('protocol'), textEncoder.encode(HOST_PROOF_TRANSCRIPT_DOMAIN)) &&
|
||||
equal(fields.get('version'), new Uint8Array([1])) &&
|
||||
equal(fields.get('relayOrigin'), textEncoder.encode(context.relayOrigin)) &&
|
||||
equal(fields.get('relayEphemeralPublicKey'), relayKey) &&
|
||||
equal(fields.get('challengeNonce'), nonce) &&
|
||||
equal(fields.get('challengeId'), textEncoder.encode(challenge.challengeId)) &&
|
||||
equal(fields.get('userId'), textEncoder.encode(context.userId)) &&
|
||||
equal(fields.get('profileId'), textEncoder.encode(context.profileId)) &&
|
||||
equal(fields.get('organizationId'), textEncoder.encode(context.organizationId)) &&
|
||||
equal(fields.get('relayHostId'), textEncoder.encode(context.relayHostId)) &&
|
||||
equal(fields.get('hostPublicKey'), context.hostPublicKey) &&
|
||||
equal(fields.get('assignmentEpoch'), uint64(context.assignmentEpoch)) &&
|
||||
equal(previousGeneration, expectedPrevious) &&
|
||||
equal(fields.get('resumeRequested'), new Uint8Array([context.resumeRequested ? 1 : 0]))
|
||||
)
|
||||
}
|
||||
|
||||
export function answerRelayHostChallenge(
|
||||
challenge: RelayHostChallenge,
|
||||
context: RelayHostProofContext
|
||||
): string | null {
|
||||
const relayKey = decodeCanonicalBase64(challenge.relayEphemeralPublicKeyB64, 32)
|
||||
const nonce = decodeCanonicalBase64(challenge.nonceB64, 24)
|
||||
const ciphertext = Buffer.from(challenge.ciphertextB64, 'base64')
|
||||
if (!relayKey || !nonce || ciphertext.toString('base64') !== challenge.ciphertextB64) {
|
||||
return null
|
||||
}
|
||||
const plaintext = nacl.box.open(ciphertext, nonce, relayKey, context.hostSecretKey)
|
||||
if (!plaintext) {
|
||||
return null
|
||||
}
|
||||
const domain = textEncoder.encode(`${HOST_CHALLENGE_PLAINTEXT_DOMAIN}\0`)
|
||||
if (
|
||||
!equal(plaintext.slice(0, domain.byteLength), domain) ||
|
||||
plaintext.byteLength < domain.byteLength + 36
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const transcriptLength = new DataView(
|
||||
plaintext.buffer,
|
||||
plaintext.byteOffset + domain.byteLength,
|
||||
4
|
||||
).getUint32(0, false)
|
||||
const transcriptStart = domain.byteLength + 4
|
||||
const secretStart = transcriptStart + transcriptLength
|
||||
if (secretStart + 32 !== plaintext.byteLength) {
|
||||
return null
|
||||
}
|
||||
const transcript = plaintext.slice(transcriptStart, secretStart)
|
||||
if (!validateTranscript(transcript, challenge, context, relayKey, nonce)) {
|
||||
return null
|
||||
}
|
||||
const secret = plaintext.slice(secretStart)
|
||||
return createHmac('sha256', secret)
|
||||
.update(textEncoder.encode(`${HOST_PROOF_TRANSCRIPT_DOMAIN}\0ack\0`))
|
||||
.update(transcript)
|
||||
.digest('base64')
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import { exchangeRelayAuthorization, requestRelayAssignment } from './relay-http-client'
|
||||
|
||||
describe('relay HTTP client', () => {
|
||||
it('exchanges only the ordinary bearer for a host-bound relay token', async () => {
|
||||
const keypair = nacl.box.keyPair()
|
||||
const fetch = vi.fn<typeof globalThis.fetch>(async () =>
|
||||
Response.json({ relayToken: 'scoped-relay-token', expiresAt: Date.now() + 300_000 })
|
||||
)
|
||||
await expect(
|
||||
exchangeRelayAuthorization({
|
||||
endpoint: 'https://auth.example/v1/desktop/auth/relay-token',
|
||||
accessToken: 'ordinary-access-token',
|
||||
keypair: {
|
||||
...keypair,
|
||||
publicKeyB64: Buffer.from(keypair.publicKey).toString('base64')
|
||||
},
|
||||
fetch
|
||||
})
|
||||
).resolves.toMatchObject({ relayToken: 'scoped-relay-token' })
|
||||
const request = fetch.mock.calls[0]!
|
||||
expect(request[0]).toBe('https://auth.example/v1/desktop/auth/relay-token')
|
||||
expect(request[1]?.headers).toEqual({
|
||||
authorization: 'Bearer ordinary-access-token',
|
||||
'content-type': 'application/json'
|
||||
})
|
||||
expect(JSON.parse(String(request[1]?.body))).toEqual({
|
||||
relayHostId: expect.stringMatching(/^[A-Za-z0-9_-]{16}$/),
|
||||
hostPublicKeyB64: Buffer.from(keypair.publicKey).toString('base64')
|
||||
})
|
||||
})
|
||||
|
||||
it('requests assignment without putting credentials in the URL', async () => {
|
||||
const fetch = vi.fn<typeof globalThis.fetch>(async () =>
|
||||
Response.json({
|
||||
v: 1,
|
||||
cellUrl: 'https://relay-c1.example',
|
||||
assignmentEpoch: 4,
|
||||
lease: 'signed-assignment'
|
||||
})
|
||||
)
|
||||
await expect(
|
||||
requestRelayAssignment({
|
||||
directorUrl: 'https://relay.example',
|
||||
relayToken: 'scoped-token',
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
fetch
|
||||
})
|
||||
).resolves.toMatchObject({ assignmentEpoch: 4 })
|
||||
expect(fetch.mock.calls[0]?.[0]).toBe('https://relay.example/v1/assign')
|
||||
expect(fetch.mock.calls[0]?.[1]?.headers).toMatchObject({
|
||||
authorization: 'Bearer scoped-token'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects data-plane supplied non-origin URLs', async () => {
|
||||
const fetch = vi.fn<typeof globalThis.fetch>(async () =>
|
||||
Response.json({
|
||||
v: 1,
|
||||
cellUrl: 'https://relay-c1.example/path?token=bad',
|
||||
assignmentEpoch: 4,
|
||||
lease: 'signed-assignment'
|
||||
})
|
||||
)
|
||||
await expect(
|
||||
requestRelayAssignment({
|
||||
directorUrl: 'https://relay.example',
|
||||
relayToken: 'scoped-token',
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
fetch
|
||||
})
|
||||
).rejects.toThrow('relay_assignment_failed_502')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
import type { E2EEKeypair } from '../e2ee-keypair'
|
||||
|
||||
const RelayTokenResponseSchema = z
|
||||
.object({
|
||||
relayToken: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(8 * 1024),
|
||||
expiresAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
|
||||
})
|
||||
.strict()
|
||||
|
||||
const AssignmentResponseSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
cellUrl: z.string().min(1).max(2048),
|
||||
assignmentEpoch: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
lease: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(8 * 1024)
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type RelayAuthorization = z.infer<typeof RelayTokenResponseSchema>
|
||||
export type RelayAssignment = z.infer<typeof AssignmentResponseSchema>
|
||||
|
||||
export class RelayHttpError extends Error {
|
||||
constructor(
|
||||
readonly operation: 'token-exchange' | 'assignment',
|
||||
readonly statusCode: number
|
||||
) {
|
||||
super(`relay_${operation}_failed_${statusCode}`)
|
||||
}
|
||||
}
|
||||
|
||||
export function deriveRelayHostId(publicKey: Uint8Array): string {
|
||||
return createHash('sha256').update(publicKey).digest('base64url').slice(0, 16)
|
||||
}
|
||||
|
||||
function isAllowedRelayOrigin(value: string): boolean {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
const loopback =
|
||||
url.hostname === '127.0.0.1' || url.hostname === 'localhost' || url.hostname === '[::1]'
|
||||
return (
|
||||
url.origin === value && (url.protocol === 'https:' || (url.protocol === 'http:' && loopback))
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function exchangeRelayAuthorization(input: {
|
||||
endpoint: string
|
||||
accessToken: string
|
||||
keypair: E2EEKeypair
|
||||
fetch?: typeof globalThis.fetch
|
||||
}): Promise<RelayAuthorization> {
|
||||
const relayHostId = deriveRelayHostId(input.keypair.publicKey)
|
||||
const response = await (input.fetch ?? globalThis.fetch)(input.endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${input.accessToken}`,
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ relayHostId, hostPublicKeyB64: input.keypair.publicKeyB64 })
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new RelayHttpError('token-exchange', response.status)
|
||||
}
|
||||
const parsed = RelayTokenResponseSchema.safeParse(await response.json())
|
||||
if (!parsed.success) {
|
||||
throw new RelayHttpError('token-exchange', 502)
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
export async function requestRelayAssignment(input: {
|
||||
directorUrl: string
|
||||
relayToken: string
|
||||
relayHostId: string
|
||||
fetch?: typeof globalThis.fetch
|
||||
}): Promise<RelayAssignment> {
|
||||
if (!isAllowedRelayOrigin(input.directorUrl)) {
|
||||
throw new RelayHttpError('assignment', 400)
|
||||
}
|
||||
const response = await (input.fetch ?? globalThis.fetch)(`${input.directorUrl}/v1/assign`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${input.relayToken}`,
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ v: 1, relayHostId: input.relayHostId })
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new RelayHttpError('assignment', response.status)
|
||||
}
|
||||
const parsed = AssignmentResponseSchema.safeParse(await response.json())
|
||||
if (!parsed.success || !isAllowedRelayOrigin(parsed.data.cellUrl)) {
|
||||
throw new RelayHttpError('assignment', 502)
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { E2EEKeypair } from '../e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring'
|
||||
import { RelayControlOrigin } from './relay-control-origin'
|
||||
import type { RelayControlClient } from './relay-control-client'
|
||||
import type { RelayDrainMessage } from './relay-control-protocol'
|
||||
import { requestRelayAssignment, type RelayAssignment } from './relay-http-client'
|
||||
import type { RelayBrokerStatus, RelayIdentity } from './relay-session-broker-contract'
|
||||
|
||||
type RelayOriginPoolOptions = {
|
||||
directorUrl: string
|
||||
relayHostId: string
|
||||
identity: RelayIdentity
|
||||
keypair: E2EEKeypair
|
||||
appVersion: string
|
||||
mobileSocketWiring: MobileSocketWiring
|
||||
isCurrent: () => boolean
|
||||
onStatus: (status: RelayBrokerStatus) => void
|
||||
fetch?: typeof globalThis.fetch
|
||||
createControlSocket?: (url: string, relayJwt: string) => WebSocket
|
||||
createDataSocket?: (url: string) => WebSocket
|
||||
random?: () => number
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export class RelayOriginPool {
|
||||
private readonly options: RelayOriginPoolOptions
|
||||
private activeOrigin: RelayControlOrigin | null = null
|
||||
private readonly origins = new Set<RelayControlOrigin>()
|
||||
private readonly drainingOrigins = new Set<RelayControlOrigin>()
|
||||
private readonly basisOrigins = new Map<string, RelayControlOrigin>()
|
||||
private readonly drainTimers = new Map<RelayControlOrigin, ReturnType<typeof setTimeout>>()
|
||||
private assignment: RelayAssignment | null = null
|
||||
private relayJwt: string | null = null
|
||||
private rotationTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private rotationPromise: Promise<void> | null = null
|
||||
private closed = false
|
||||
|
||||
constructor(options: RelayOriginPoolOptions) {
|
||||
this.options = options
|
||||
}
|
||||
|
||||
get activeAssignment(): RelayAssignment | null {
|
||||
return this.assignment
|
||||
}
|
||||
|
||||
get activeControl(): RelayControlClient | null {
|
||||
return this.activeOrigin?.availableControl ?? null
|
||||
}
|
||||
|
||||
controlForBasis(basisConnId: string): RelayControlClient | null {
|
||||
return this.basisOrigins.get(basisConnId)?.availableControl ?? null
|
||||
}
|
||||
|
||||
async openInitial(assignment: RelayAssignment, relayJwt: string): Promise<void> {
|
||||
this.assignment = assignment
|
||||
this.relayJwt = relayJwt
|
||||
const origin = this.createOrigin(assignment, relayJwt)
|
||||
this.origins.add(origin)
|
||||
await origin.open()
|
||||
this.assertCurrent()
|
||||
this.activeOrigin = origin
|
||||
this.scheduleControlRotation()
|
||||
}
|
||||
|
||||
refreshAuthorization(relayJwt: string): void {
|
||||
this.relayJwt = relayJwt
|
||||
for (const origin of this.origins) {
|
||||
origin.refreshAuthorization(relayJwt)
|
||||
}
|
||||
}
|
||||
|
||||
closeNow(): void {
|
||||
if (this.closed) {
|
||||
return
|
||||
}
|
||||
this.closed = true
|
||||
if (this.rotationTimer) {
|
||||
clearTimeout(this.rotationTimer)
|
||||
this.rotationTimer = null
|
||||
}
|
||||
for (const timer of this.drainTimers.values()) {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
this.drainTimers.clear()
|
||||
for (const origin of this.origins) {
|
||||
origin.closeNow()
|
||||
}
|
||||
this.origins.clear()
|
||||
this.drainingOrigins.clear()
|
||||
this.basisOrigins.clear()
|
||||
this.activeOrigin = null
|
||||
}
|
||||
|
||||
private createOrigin(assignment: RelayAssignment, relayJwt: string): RelayControlOrigin {
|
||||
return new RelayControlOrigin({
|
||||
assignment,
|
||||
relayJwt,
|
||||
relayHostId: this.options.relayHostId,
|
||||
identity: this.options.identity,
|
||||
keypair: this.options.keypair,
|
||||
appVersion: this.options.appVersion,
|
||||
mobileSocketWiring: this.options.mobileSocketWiring,
|
||||
createControlSocket: this.options.createControlSocket,
|
||||
createDataSocket: this.options.createDataSocket,
|
||||
onConnectionOwned: (connectionId, origin) => {
|
||||
if (this.isCurrent() && this.origins.has(origin)) {
|
||||
this.basisOrigins.set(connectionId, origin)
|
||||
}
|
||||
},
|
||||
onConnectionReleased: (connectionId, origin) => {
|
||||
if (this.basisOrigins.get(connectionId) === origin) {
|
||||
this.basisOrigins.delete(connectionId)
|
||||
}
|
||||
this.maybeCloseDrainedOrigin(origin)
|
||||
},
|
||||
onDrain: (origin, message) => this.handleDrain(origin, message),
|
||||
onClose: (origin) => {
|
||||
if (origin === this.activeOrigin && this.isCurrent()) {
|
||||
this.options.onStatus('offline')
|
||||
this.handleDrain(origin, {
|
||||
type: 'drain',
|
||||
graceMs: 0,
|
||||
recovery: 'resolve-director'
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private handleDrain(origin: RelayControlOrigin, message: RelayDrainMessage): void {
|
||||
if (!this.isCurrent() || origin !== this.activeOrigin) {
|
||||
return
|
||||
}
|
||||
origin.markDraining()
|
||||
this.drainingOrigins.add(origin)
|
||||
this.options.onStatus('draining')
|
||||
if (!this.rotationPromise) {
|
||||
this.rotationPromise = this.resolveDrainTarget(origin, message).finally(() => {
|
||||
this.rotationPromise = null
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveDrainTarget(
|
||||
origin: RelayControlOrigin,
|
||||
message: RelayDrainMessage
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (!this.relayJwt) {
|
||||
throw new Error('relay_authorization_unavailable')
|
||||
}
|
||||
// Why: only the configured director can choose a migration target.
|
||||
const assignment = await requestRelayAssignment({
|
||||
directorUrl: this.options.directorUrl,
|
||||
relayToken: this.relayJwt,
|
||||
relayHostId: this.options.relayHostId,
|
||||
fetch: this.options.fetch
|
||||
})
|
||||
this.assertCurrent()
|
||||
if (assignment.cellUrl === origin.cellUrl) {
|
||||
let rebound = false
|
||||
try {
|
||||
await origin.rebind(this.relayJwt, assignment)
|
||||
rebound = true
|
||||
} catch {
|
||||
// Why: a restarted cell cannot know the prior process's resume secret;
|
||||
// after rebind fails, a fresh generation is the only recoverable path.
|
||||
await this.activateTarget(origin, assignment, this.relayJwt, message.graceMs)
|
||||
}
|
||||
if (rebound) {
|
||||
this.assertCurrent()
|
||||
this.activeOrigin = origin
|
||||
this.assignment = assignment
|
||||
this.drainingOrigins.delete(origin)
|
||||
}
|
||||
} else {
|
||||
await this.activateTarget(origin, assignment, this.relayJwt, message.graceMs)
|
||||
}
|
||||
this.options.onStatus('registered')
|
||||
this.scheduleControlRotation()
|
||||
} catch {
|
||||
if (this.isCurrent()) {
|
||||
const random = this.options.random ?? Math.random
|
||||
setTimeout(() => this.handleDrain(origin, message), 250 + Math.floor(random() * 751))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async activateTarget(
|
||||
origin: RelayControlOrigin,
|
||||
assignment: RelayAssignment,
|
||||
relayJwt: string,
|
||||
graceMs: number
|
||||
): Promise<void> {
|
||||
const target = this.createOrigin(assignment, relayJwt)
|
||||
this.origins.add(target)
|
||||
try {
|
||||
await target.open()
|
||||
this.assertCurrent()
|
||||
} catch (error) {
|
||||
this.origins.delete(target)
|
||||
target.closeNow()
|
||||
throw error
|
||||
}
|
||||
this.activeOrigin = target
|
||||
this.assignment = assignment
|
||||
this.scheduleDrainDeadline(origin, graceMs)
|
||||
this.maybeCloseDrainedOrigin(origin)
|
||||
}
|
||||
|
||||
private scheduleControlRotation(): void {
|
||||
if (this.rotationTimer) {
|
||||
clearTimeout(this.rotationTimer)
|
||||
}
|
||||
const origin = this.activeOrigin
|
||||
if (!origin || this.closed) {
|
||||
this.rotationTimer = null
|
||||
return
|
||||
}
|
||||
const now = (this.options.now ?? Date.now)()
|
||||
const random = this.options.random ?? Math.random
|
||||
const earlyMs = 60_000 + Math.floor(random() * 60_001)
|
||||
const delay = Math.max(0, origin.controlLeaseExpiresAt - earlyMs - now)
|
||||
this.rotationTimer = setTimeout(() => void this.rebindActiveControl(origin), delay)
|
||||
}
|
||||
|
||||
private async rebindActiveControl(origin: RelayControlOrigin): Promise<void> {
|
||||
this.rotationTimer = null
|
||||
if (!this.isCurrent() || origin !== this.activeOrigin || this.rotationPromise) {
|
||||
return
|
||||
}
|
||||
if (!this.relayJwt || !this.assignment) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await origin.rebind(this.relayJwt, this.assignment)
|
||||
this.assertCurrent()
|
||||
this.scheduleControlRotation()
|
||||
} catch {
|
||||
if (this.isCurrent() && origin === this.activeOrigin) {
|
||||
const random = this.options.random ?? Math.random
|
||||
this.rotationTimer = setTimeout(
|
||||
() => void this.rebindActiveControl(origin),
|
||||
5_000 + Math.floor(random() * 10_001)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleDrainDeadline(origin: RelayControlOrigin, graceMs: number): void {
|
||||
const existing = this.drainTimers.get(origin)
|
||||
if (existing) {
|
||||
clearTimeout(existing)
|
||||
}
|
||||
this.drainTimers.set(
|
||||
origin,
|
||||
setTimeout(() => this.closeOrigin(origin), graceMs)
|
||||
)
|
||||
}
|
||||
|
||||
private maybeCloseDrainedOrigin(origin: RelayControlOrigin): void {
|
||||
if (
|
||||
!this.drainingOrigins.has(origin) ||
|
||||
origin.pendingRequestCount > 0 ||
|
||||
[...this.basisOrigins.values()].includes(origin)
|
||||
) {
|
||||
return
|
||||
}
|
||||
this.closeOrigin(origin)
|
||||
}
|
||||
|
||||
private closeOrigin(origin: RelayControlOrigin): void {
|
||||
if (origin === this.activeOrigin) {
|
||||
return
|
||||
}
|
||||
const timer = this.drainTimers.get(origin)
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
this.drainTimers.delete(origin)
|
||||
}
|
||||
for (const [connectionId, owner] of this.basisOrigins) {
|
||||
if (owner === origin) {
|
||||
this.basisOrigins.delete(connectionId)
|
||||
}
|
||||
}
|
||||
this.drainingOrigins.delete(origin)
|
||||
this.origins.delete(origin)
|
||||
origin.closeNow()
|
||||
}
|
||||
|
||||
private assertCurrent(): void {
|
||||
if (!this.isCurrent()) {
|
||||
throw new Error('stale_relay_origin_pool')
|
||||
}
|
||||
}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
return !this.closed && this.options.isCurrent()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { RelayRevokeOutbox } from './relay-revoke-outbox'
|
||||
|
||||
describe('RelayRevokeOutbox', () => {
|
||||
const paths: string[] = []
|
||||
afterEach(() => {
|
||||
for (const path of paths.splice(0)) {
|
||||
rmSync(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('durably retains an idempotent account-scoped revoke after local deletion', () => {
|
||||
const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-'))
|
||||
paths.push(path)
|
||||
const binding = {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: 'device-1',
|
||||
ownerIdentityKey: 'user-1\0profile-1\0org-1'
|
||||
}
|
||||
const first = new RelayRevokeOutbox(path).enqueue(binding)
|
||||
const reloaded = new RelayRevokeOutbox(path)
|
||||
expect(reloaded.enqueue(binding).reqId).toBe(first.reqId)
|
||||
expect(reloaded.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([first])
|
||||
reloaded.remove(first.reqId)
|
||||
expect(
|
||||
new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId)
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { hardenExistingSecureFile, writeSecureJsonFile } from '../../../shared/secure-file'
|
||||
|
||||
export type RelayDeviceBinding = {
|
||||
relayHostId: string
|
||||
relayDeviceId: string
|
||||
ownerIdentityKey: string
|
||||
inviteExpiresAt?: number
|
||||
}
|
||||
|
||||
export type RelayRevokeOutboxItem = RelayDeviceBinding & {
|
||||
reqId: string
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
const OUTBOX_FILENAME = 'mobile-relay-revoke-outbox.json'
|
||||
|
||||
function isItem(value: unknown): value is RelayRevokeOutboxItem {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false
|
||||
}
|
||||
const item = value as Partial<RelayRevokeOutboxItem>
|
||||
return (
|
||||
typeof item.reqId === 'string' &&
|
||||
typeof item.relayHostId === 'string' &&
|
||||
typeof item.relayDeviceId === 'string' &&
|
||||
typeof item.ownerIdentityKey === 'string' &&
|
||||
(item.inviteExpiresAt === undefined ||
|
||||
(typeof item.inviteExpiresAt === 'number' && Number.isFinite(item.inviteExpiresAt))) &&
|
||||
typeof item.createdAt === 'number' &&
|
||||
Number.isFinite(item.createdAt)
|
||||
)
|
||||
}
|
||||
|
||||
export class RelayRevokeOutbox {
|
||||
private readonly path: string
|
||||
private items: RelayRevokeOutboxItem[]
|
||||
|
||||
constructor(userDataPath: string) {
|
||||
this.path = join(userDataPath, OUTBOX_FILENAME)
|
||||
this.items = this.load()
|
||||
}
|
||||
|
||||
enqueue(binding: RelayDeviceBinding): RelayRevokeOutboxItem {
|
||||
const existing = this.items.find(
|
||||
(item) =>
|
||||
item.relayHostId === binding.relayHostId &&
|
||||
item.relayDeviceId === binding.relayDeviceId &&
|
||||
item.ownerIdentityKey === binding.ownerIdentityKey
|
||||
)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const item = { ...binding, reqId: randomUUID(), createdAt: Date.now() }
|
||||
this.items.push(item)
|
||||
this.save()
|
||||
return item
|
||||
}
|
||||
|
||||
pendingFor(ownerIdentityKey: string, relayHostId: string): readonly RelayRevokeOutboxItem[] {
|
||||
return this.items.filter(
|
||||
(item) => item.ownerIdentityKey === ownerIdentityKey && item.relayHostId === relayHostId
|
||||
)
|
||||
}
|
||||
|
||||
remove(reqId: string): void {
|
||||
const next = this.items.filter((item) => item.reqId !== reqId)
|
||||
if (next.length === this.items.length) {
|
||||
return
|
||||
}
|
||||
this.items = next
|
||||
this.save()
|
||||
}
|
||||
|
||||
private load(): RelayRevokeOutboxItem[] {
|
||||
if (!existsSync(this.path)) {
|
||||
return []
|
||||
}
|
||||
try {
|
||||
hardenExistingSecureFile(this.path)
|
||||
const parsed: unknown = JSON.parse(readFileSync(this.path, 'utf-8'))
|
||||
return Array.isArray(parsed) ? parsed.filter(isItem) : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
writeSecureJsonFile(this.path, this.items)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type WebSocket from 'ws'
|
||||
import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config'
|
||||
import type { MobileRelayStatus } from '../../../shared/mobile-relay-status'
|
||||
import type { E2EEKeypair } from '../e2ee-keypair'
|
||||
import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring'
|
||||
|
||||
export type RelayBrokerStatus = MobileRelayStatus
|
||||
|
||||
export type RelayIdentity = {
|
||||
userId: string
|
||||
profileId: string
|
||||
organizationId: string
|
||||
}
|
||||
|
||||
export type RelaySessionBrokerOptions = {
|
||||
authConfig: OrcaCloudAuthConfig
|
||||
accessToken: string
|
||||
identity: RelayIdentity
|
||||
keypair: E2EEKeypair
|
||||
appVersion: string
|
||||
mobileSocketWiring: MobileSocketWiring
|
||||
isCurrent: () => boolean
|
||||
refreshAccessToken: () => Promise<string | null>
|
||||
onStatus: (status: RelayBrokerStatus) => void
|
||||
fetch?: typeof globalThis.fetch
|
||||
createControlSocket?: (url: string, relayJwt: string) => WebSocket
|
||||
createDataSocket?: (url: string) => WebSocket
|
||||
random?: () => number
|
||||
now?: () => number
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config'
|
||||
import type { RelayHostHelloAckMessage } from './relay-control-protocol'
|
||||
import type * as RelayHttpClientModule from './relay-http-client'
|
||||
|
||||
const fakes = vi.hoisted(() => ({
|
||||
controls: [] as {
|
||||
options: {
|
||||
onConnectionOpen(message: {
|
||||
connId: string
|
||||
connTicket: string
|
||||
kind: 'invite' | 'resume'
|
||||
relayDeviceId: string
|
||||
attachDeadlineMs: number
|
||||
}): void
|
||||
onDrain(message: { type: 'drain'; graceMs: number; recovery: 'resolve-director' }): void
|
||||
onClose(code: number): void
|
||||
previousGeneration?: number
|
||||
controlResumeSecret?: string
|
||||
}
|
||||
connect: ReturnType<typeof vi.fn>
|
||||
closeNow: ReturnType<typeof vi.fn>
|
||||
confirmResume: ReturnType<typeof vi.fn>
|
||||
installCredential: ReturnType<typeof vi.fn>
|
||||
pendingRequestCount: number
|
||||
}[],
|
||||
transports: [] as {
|
||||
start: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
setGeneration: ReturnType<typeof vi.fn>
|
||||
metadataFor: ReturnType<typeof vi.fn>
|
||||
openConnection: ReturnType<typeof vi.fn>
|
||||
}[],
|
||||
controlConnect: vi.fn(),
|
||||
exchange: vi.fn(),
|
||||
assign: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./relay-http-client', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof RelayHttpClientModule>()),
|
||||
exchangeRelayAuthorization: fakes.exchange,
|
||||
requestRelayAssignment: fakes.assign
|
||||
}))
|
||||
|
||||
vi.mock('./relay-control-client', () => ({
|
||||
RelayControlClient: class {
|
||||
connect = fakes.controlConnect
|
||||
closeNow = vi.fn()
|
||||
confirmResume = vi.fn().mockResolvedValue({
|
||||
type: 'device-resume-confirmed',
|
||||
v: 1,
|
||||
reqId: 'confirm-1',
|
||||
currentVersion: 1,
|
||||
acceptedAs: 'current',
|
||||
renewed: true,
|
||||
resumeExpiresAt: 100_000
|
||||
})
|
||||
installCredential = vi.fn().mockResolvedValue({
|
||||
type: 'device-credential-installed',
|
||||
v: 1,
|
||||
reqId: 'install-1',
|
||||
authorizationMode: 'relay-basis',
|
||||
currentVersion: 1,
|
||||
resumeExpiresAt: 100_000
|
||||
})
|
||||
pendingRequestCount = 0
|
||||
|
||||
constructor(readonly options: (typeof fakes.controls)[number]['options']) {
|
||||
fakes.controls.push(this)
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('../rpc/relay-transport', () => ({
|
||||
CloudRelayTransport: class {
|
||||
start = vi.fn().mockResolvedValue(undefined)
|
||||
stop = vi.fn().mockResolvedValue(undefined)
|
||||
setGeneration = vi.fn()
|
||||
metadataFor = vi.fn()
|
||||
openConnection = vi.fn().mockResolvedValue(undefined)
|
||||
|
||||
constructor() {
|
||||
fakes.transports.push(this)
|
||||
}
|
||||
}
|
||||
}))
|
||||
|
||||
import { RelaySessionBroker, StaleRelayBrokerError } from './relay-session-broker'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((resolvePromise) => {
|
||||
resolve = resolvePromise
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
describe('RelaySessionBroker lifecycle ownership', () => {
|
||||
beforeEach(() => {
|
||||
fakes.controls.length = 0
|
||||
fakes.transports.length = 0
|
||||
fakes.controlConnect.mockReset()
|
||||
fakes.exchange.mockReset().mockResolvedValue({ relayToken: 'relay-jwt', expiresAt: 1_000_000 })
|
||||
fakes.assign.mockReset().mockResolvedValue({
|
||||
cellUrl: 'https://relay.example.test',
|
||||
assignmentEpoch: 1,
|
||||
leaseExpiresAt: 60_000
|
||||
})
|
||||
})
|
||||
|
||||
it('closes partially opened resources without publishing stale state', async () => {
|
||||
const controlAck = deferred<RelayHostHelloAckMessage>()
|
||||
fakes.controlConnect.mockReturnValue(controlAck.promise)
|
||||
let current = true
|
||||
const statuses: string[] = []
|
||||
const keypair = nacl.box.keyPair()
|
||||
const connecting = RelaySessionBroker.connect({
|
||||
authConfig: {
|
||||
relayTokenEndpoint: 'https://auth.example.test/v1/relay-token',
|
||||
relayDirectorUrl: 'https://relay.example.test'
|
||||
} as OrcaCloudAuthConfig,
|
||||
accessToken: 'access-token',
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
keypair: {
|
||||
...keypair,
|
||||
publicKeyB64: Buffer.from(keypair.publicKey).toString('base64')
|
||||
},
|
||||
appVersion: '1.0.0',
|
||||
mobileSocketWiring: { attachTransport: vi.fn() } as never,
|
||||
isCurrent: () => current,
|
||||
refreshAccessToken: async () => null,
|
||||
onStatus: (status) => statuses.push(status)
|
||||
})
|
||||
await vi.waitFor(() => expect(fakes.controls).toHaveLength(1))
|
||||
current = false
|
||||
controlAck.resolve({
|
||||
type: 'host-hello-ack',
|
||||
v: 1,
|
||||
generation: 1,
|
||||
controlResumeSecret: 'A'.repeat(43),
|
||||
leaseExpiresAt: 1_000_000,
|
||||
activeConnIds: [],
|
||||
pendingConns: []
|
||||
})
|
||||
|
||||
await expect(connecting).rejects.toBeInstanceOf(StaleRelayBrokerError)
|
||||
expect(fakes.controls[0]!.closeNow).toHaveBeenCalledOnce()
|
||||
expect(fakes.transports[0]!.stop).toHaveBeenCalledOnce()
|
||||
expect(statuses).toEqual(['connecting'])
|
||||
})
|
||||
|
||||
it('activates a new origin while keeping basis-bound work on the drained origin', async () => {
|
||||
const firstAck: RelayHostHelloAckMessage = {
|
||||
type: 'host-hello-ack',
|
||||
v: 1,
|
||||
generation: 1,
|
||||
controlResumeSecret: 'A'.repeat(43),
|
||||
leaseExpiresAt: 1_000_000,
|
||||
activeConnIds: [],
|
||||
pendingConns: []
|
||||
}
|
||||
fakes.controlConnect.mockResolvedValueOnce(firstAck).mockResolvedValueOnce({
|
||||
...firstAck,
|
||||
generation: 2,
|
||||
controlResumeSecret: 'B'.repeat(43)
|
||||
})
|
||||
fakes.assign
|
||||
.mockResolvedValueOnce({
|
||||
cellUrl: 'https://relay-c1.example.test',
|
||||
assignmentEpoch: 1,
|
||||
leaseExpiresAt: 1_000_000
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
cellUrl: 'https://relay-c2.example.test',
|
||||
assignmentEpoch: 2,
|
||||
leaseExpiresAt: 2_000_000
|
||||
})
|
||||
const broker = await RelaySessionBroker.connect(brokerOptions({ onStatus: vi.fn() }))
|
||||
fakes.controls[0]!.options.onConnectionOpen({
|
||||
connId: 'old-basis',
|
||||
connTicket: 'T'.repeat(43),
|
||||
kind: 'resume',
|
||||
relayDeviceId: 'device-1',
|
||||
attachDeadlineMs: 1_000
|
||||
})
|
||||
expect(brokerBasisIds(broker)).toEqual(['old-basis'])
|
||||
fakes.controls[0]!.options.onDrain({
|
||||
type: 'drain',
|
||||
graceMs: 30_000,
|
||||
recovery: 'resolve-director'
|
||||
})
|
||||
await vi.waitFor(() => expect(fakes.controls).toHaveLength(2))
|
||||
|
||||
expect(broker.endpoint?.cellUrl).toBe('https://relay-c2.example.test')
|
||||
expect(fakes.transports[0]!.openConnection).toHaveBeenCalledOnce()
|
||||
expect(brokerBasisIds(broker)).toEqual(['old-basis'])
|
||||
expect(fakes.controls[0]!.closeNow).not.toHaveBeenCalled()
|
||||
expect(fakes.transports[0]!.stop).not.toHaveBeenCalled()
|
||||
await broker.confirmResume('old-basis', 'confirm-1')
|
||||
expect(fakes.controls[0]!.confirmResume).toHaveBeenCalledWith('old-basis', 'confirm-1')
|
||||
await broker.installCredential(
|
||||
'device-1',
|
||||
{ reqId: 'install-1', newResumeTokenHash: 'H'.repeat(43) },
|
||||
{ mode: 'relay-basis', basisConnId: 'old-basis' }
|
||||
)
|
||||
expect(fakes.controls[0]!.installCredential).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('rebinds the same process generation with its control resume secret', async () => {
|
||||
const ack: RelayHostHelloAckMessage = {
|
||||
type: 'host-hello-ack',
|
||||
v: 1,
|
||||
generation: 7,
|
||||
controlResumeSecret: 'R'.repeat(43),
|
||||
leaseExpiresAt: 1_000_000,
|
||||
activeConnIds: ['existing-basis'],
|
||||
pendingConns: []
|
||||
}
|
||||
fakes.controlConnect.mockResolvedValueOnce(ack).mockResolvedValueOnce({
|
||||
...ack,
|
||||
leaseExpiresAt: 2_000_000
|
||||
})
|
||||
fakes.assign
|
||||
.mockResolvedValueOnce({
|
||||
cellUrl: 'https://relay.example.test',
|
||||
assignmentEpoch: 1,
|
||||
leaseExpiresAt: 1_000_000
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
cellUrl: 'https://relay.example.test',
|
||||
assignmentEpoch: 1,
|
||||
leaseExpiresAt: 2_000_000
|
||||
})
|
||||
const broker = await RelaySessionBroker.connect(brokerOptions())
|
||||
expect(brokerBasisIds(broker)).toEqual(['existing-basis'])
|
||||
fakes.controls[0]!.options.onDrain({
|
||||
type: 'drain',
|
||||
graceMs: 5_000,
|
||||
recovery: 'resolve-director'
|
||||
})
|
||||
await vi.waitFor(() => expect(fakes.controls).toHaveLength(2))
|
||||
|
||||
expect(fakes.transports).toHaveLength(1)
|
||||
expect(fakes.controls[1]!.options.previousGeneration).toBe(7)
|
||||
expect(fakes.controls[1]!.options.controlResumeSecret).toBe('R'.repeat(43))
|
||||
await vi.waitFor(() => expect(brokerBasisIds(broker)).toEqual(['existing-basis']))
|
||||
await broker.confirmResume('existing-basis', 'confirm-1')
|
||||
expect(fakes.controls[1]!.confirmResume).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('opens a fresh same-cell generation when process-local rebind state is lost', async () => {
|
||||
const ack: RelayHostHelloAckMessage = {
|
||||
type: 'host-hello-ack',
|
||||
v: 1,
|
||||
generation: 7,
|
||||
controlResumeSecret: 'R'.repeat(43),
|
||||
leaseExpiresAt: 1_000_000,
|
||||
activeConnIds: [],
|
||||
pendingConns: []
|
||||
}
|
||||
fakes.controlConnect
|
||||
.mockResolvedValueOnce(ack)
|
||||
.mockRejectedValueOnce(new Error('relay_control_closed_4401'))
|
||||
.mockResolvedValueOnce({
|
||||
...ack,
|
||||
generation: 1,
|
||||
controlResumeSecret: 'N'.repeat(43),
|
||||
leaseExpiresAt: 2_000_000
|
||||
})
|
||||
fakes.assign
|
||||
.mockResolvedValueOnce({
|
||||
cellUrl: 'https://relay.example.test',
|
||||
assignmentEpoch: 1,
|
||||
leaseExpiresAt: 1_000_000
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
cellUrl: 'https://relay.example.test',
|
||||
assignmentEpoch: 1,
|
||||
leaseExpiresAt: 2_000_000
|
||||
})
|
||||
const onStatus = vi.fn()
|
||||
const broker = await RelaySessionBroker.connect(brokerOptions({ onStatus }))
|
||||
|
||||
fakes.controls[0]!.options.onClose(1006)
|
||||
await vi.waitFor(() => expect(fakes.controls).toHaveLength(3))
|
||||
|
||||
expect(fakes.controls[1]!.options.previousGeneration).toBe(7)
|
||||
expect(fakes.controls[1]!.options.controlResumeSecret).toBe('R'.repeat(43))
|
||||
expect(fakes.controls[2]!.options.previousGeneration).toBeUndefined()
|
||||
expect(fakes.controls[2]!.options.controlResumeSecret).toBeUndefined()
|
||||
expect(fakes.transports).toHaveLength(2)
|
||||
await vi.waitFor(() => expect(onStatus).toHaveBeenLastCalledWith('registered'))
|
||||
expect(broker.endpoint?.cellUrl).toBe('https://relay.example.test')
|
||||
})
|
||||
})
|
||||
|
||||
function brokerBasisIds(broker: RelaySessionBroker): string[] {
|
||||
const pool = (broker as unknown as { originPool: unknown }).originPool
|
||||
return [...(pool as { basisOrigins: Map<string, unknown> }).basisOrigins.keys()]
|
||||
}
|
||||
|
||||
function brokerOptions(
|
||||
overrides: Partial<Parameters<typeof RelaySessionBroker.connect>[0]> = {}
|
||||
): Parameters<typeof RelaySessionBroker.connect>[0] {
|
||||
const keypair = nacl.box.keyPair()
|
||||
return {
|
||||
authConfig: {
|
||||
relayTokenEndpoint: 'https://auth.example.test/v1/relay-token',
|
||||
relayDirectorUrl: 'https://relay.example.test'
|
||||
} as OrcaCloudAuthConfig,
|
||||
accessToken: 'access-token',
|
||||
identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
|
||||
keypair: {
|
||||
...keypair,
|
||||
publicKeyB64: Buffer.from(keypair.publicKey).toString('base64')
|
||||
},
|
||||
appVersion: '1.0.0',
|
||||
mobileSocketWiring: { attachTransport: vi.fn() } as never,
|
||||
isCurrent: () => true,
|
||||
refreshAccessToken: async () => null,
|
||||
onStatus: vi.fn(),
|
||||
now: () => 0,
|
||||
random: () => 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import type { PairingRelay } from '../../../shared/mobile-relay-pairing-offer'
|
||||
import type {
|
||||
DeviceCredentialInstalled,
|
||||
DeviceCredentialInstallStatusResult,
|
||||
DeviceResumeConfirmed,
|
||||
MobileRelayEndpoint,
|
||||
PairingProvisionRelayParams
|
||||
} from '../../../shared/mobile-relay-credential-contract'
|
||||
import type { DeviceCredentialInstallAuthorization } from './relay-control-requests'
|
||||
import {
|
||||
deriveRelayHostId,
|
||||
exchangeRelayAuthorization,
|
||||
requestRelayAssignment,
|
||||
type RelayAuthorization,
|
||||
type RelayAssignment
|
||||
} from './relay-http-client'
|
||||
import { RelayOriginPool } from './relay-origin-pool'
|
||||
import type { RelayBrokerStatus, RelaySessionBrokerOptions } from './relay-session-broker-contract'
|
||||
|
||||
export type { RelayBrokerStatus } from './relay-session-broker-contract'
|
||||
|
||||
export class StaleRelayBrokerError extends Error {
|
||||
constructor() {
|
||||
super('stale_relay_broker')
|
||||
}
|
||||
}
|
||||
|
||||
export class RelaySessionBroker {
|
||||
private readonly options: RelaySessionBrokerOptions
|
||||
private readonly relayHostId: string
|
||||
private readonly originPool: RelayOriginPool
|
||||
private authorization: RelayAuthorization | null = null
|
||||
private refreshTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private closed = false
|
||||
|
||||
private constructor(options: RelaySessionBrokerOptions) {
|
||||
this.options = options
|
||||
this.relayHostId = deriveRelayHostId(options.keypair.publicKey)
|
||||
this.originPool = new RelayOriginPool({
|
||||
directorUrl: options.authConfig.relayDirectorUrl,
|
||||
relayHostId: this.relayHostId,
|
||||
identity: options.identity,
|
||||
keypair: options.keypair,
|
||||
appVersion: options.appVersion,
|
||||
mobileSocketWiring: options.mobileSocketWiring,
|
||||
isCurrent: () => this.isCurrent(),
|
||||
onStatus: (status) => this.publishStatus(status),
|
||||
fetch: options.fetch,
|
||||
createControlSocket: options.createControlSocket,
|
||||
createDataSocket: options.createDataSocket,
|
||||
random: options.random,
|
||||
now: options.now
|
||||
})
|
||||
}
|
||||
|
||||
static async connect(options: RelaySessionBrokerOptions): Promise<RelaySessionBroker> {
|
||||
const broker = new RelaySessionBroker(options)
|
||||
try {
|
||||
await broker.open(options.accessToken)
|
||||
return broker
|
||||
} catch (error) {
|
||||
broker.closeNow()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
get hostId(): string {
|
||||
return this.relayHostId
|
||||
}
|
||||
|
||||
get currentAssignment(): RelayAssignment | null {
|
||||
return this.originPool.activeAssignment
|
||||
}
|
||||
|
||||
get ownerIdentityKey(): string {
|
||||
const identity = this.options.identity
|
||||
return `${identity.userId}\0${identity.profileId}\0${identity.organizationId}`
|
||||
}
|
||||
|
||||
get endpoint(): MobileRelayEndpoint | null {
|
||||
const assignment = this.originPool.activeAssignment
|
||||
if (!assignment) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
v: 1,
|
||||
directorUrl: this.options.authConfig.relayDirectorUrl,
|
||||
cellUrl: assignment.cellUrl,
|
||||
assignmentEpoch: assignment.assignmentEpoch,
|
||||
relayHostId: this.relayHostId,
|
||||
e2eeFraming: 2
|
||||
}
|
||||
}
|
||||
|
||||
createInvite(relayDeviceId: string) {
|
||||
const control = this.originPool.activeControl
|
||||
if (!control) {
|
||||
return Promise.reject(new Error('relay_control_not_active'))
|
||||
}
|
||||
return control.createInvite(relayDeviceId)
|
||||
}
|
||||
|
||||
async createPairingRelay(relayDeviceId: string): Promise<PairingRelay> {
|
||||
const assignment = this.originPool.activeAssignment
|
||||
const control = this.originPool.activeControl
|
||||
if (!assignment || !control) {
|
||||
throw new Error('relay_control_not_active')
|
||||
}
|
||||
const invite = await control.createInvite(relayDeviceId)
|
||||
this.assertCurrent()
|
||||
return {
|
||||
v: 1,
|
||||
directorUrl: this.options.authConfig.relayDirectorUrl,
|
||||
cellUrl: assignment.cellUrl,
|
||||
assignmentEpoch: assignment.assignmentEpoch,
|
||||
relayHostId: this.relayHostId,
|
||||
inviteToken: invite.inviteToken,
|
||||
inviteExpiresAt: invite.expiresAt,
|
||||
e2eeFraming: 2
|
||||
}
|
||||
}
|
||||
|
||||
revokeDevice(relayDeviceId: string, reqId?: string): Promise<void> {
|
||||
const control = this.originPool.activeControl
|
||||
if (!control) {
|
||||
return Promise.reject(new Error('relay_control_not_active'))
|
||||
}
|
||||
return control.revokeDevice(relayDeviceId, reqId)
|
||||
}
|
||||
|
||||
async installCredential(
|
||||
relayDeviceId: string,
|
||||
params: PairingProvisionRelayParams,
|
||||
authorization: DeviceCredentialInstallAuthorization
|
||||
): Promise<DeviceCredentialInstalled> {
|
||||
const control =
|
||||
authorization.mode === 'relay-basis'
|
||||
? this.originPool.controlForBasis(authorization.basisConnId)
|
||||
: this.originPool.activeControl
|
||||
if (!control) {
|
||||
throw new Error('relay_control_not_active')
|
||||
}
|
||||
const message = await control.installCredential({
|
||||
relayDeviceId,
|
||||
authorization,
|
||||
...params
|
||||
})
|
||||
this.assertCurrent()
|
||||
const { type: _type, ...result } = message
|
||||
return result
|
||||
}
|
||||
|
||||
async credentialInstallStatus(
|
||||
relayDeviceId: string,
|
||||
reqId: string
|
||||
): Promise<DeviceCredentialInstallStatusResult> {
|
||||
const control = this.originPool.activeControl
|
||||
if (!control) {
|
||||
throw new Error('relay_control_not_active')
|
||||
}
|
||||
const message = await control.credentialInstallStatus(relayDeviceId, reqId)
|
||||
this.assertCurrent()
|
||||
const { type: _type, ...result } = message
|
||||
return result
|
||||
}
|
||||
|
||||
async confirmResume(basisConnId: string, reqId: string): Promise<DeviceResumeConfirmed> {
|
||||
const control = this.originPool.controlForBasis(basisConnId)
|
||||
if (!control) {
|
||||
throw new Error('relay_basis_origin_not_found')
|
||||
}
|
||||
const message = await control.confirmResume(basisConnId, reqId)
|
||||
this.assertCurrent()
|
||||
const { type: _type, ...result } = message
|
||||
return result
|
||||
}
|
||||
|
||||
closeNow(): void {
|
||||
if (this.closed) {
|
||||
return
|
||||
}
|
||||
const publishOffline = this.options.isCurrent()
|
||||
this.closed = true
|
||||
if (this.refreshTimer) {
|
||||
clearTimeout(this.refreshTimer)
|
||||
this.refreshTimer = null
|
||||
}
|
||||
this.originPool.closeNow()
|
||||
if (publishOffline) {
|
||||
this.options.onStatus('offline')
|
||||
}
|
||||
}
|
||||
|
||||
private async open(accessToken: string): Promise<void> {
|
||||
this.publishStatus('connecting')
|
||||
const authorization = await exchangeRelayAuthorization({
|
||||
endpoint: this.options.authConfig.relayTokenEndpoint,
|
||||
accessToken,
|
||||
keypair: this.options.keypair,
|
||||
fetch: this.options.fetch
|
||||
})
|
||||
this.assertCurrent()
|
||||
const assignment = await requestRelayAssignment({
|
||||
directorUrl: this.options.authConfig.relayDirectorUrl,
|
||||
relayToken: authorization.relayToken,
|
||||
relayHostId: this.relayHostId,
|
||||
fetch: this.options.fetch
|
||||
})
|
||||
this.assertCurrent()
|
||||
try {
|
||||
await this.originPool.openInitial(assignment, authorization.relayToken)
|
||||
} catch (error) {
|
||||
if (!this.isCurrent()) {
|
||||
throw new StaleRelayBrokerError()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
this.assertCurrent()
|
||||
this.authorization = authorization
|
||||
this.publishStatus('registered')
|
||||
this.scheduleRefresh()
|
||||
}
|
||||
|
||||
private scheduleRefresh(): void {
|
||||
const authorization = this.authorization
|
||||
if (!authorization || this.closed) {
|
||||
return
|
||||
}
|
||||
const now = (this.options.now ?? Date.now)()
|
||||
const random = this.options.random ?? Math.random
|
||||
const earlyMs = 60_000 + Math.floor(random() * 60_001)
|
||||
const delay = Math.max(0, authorization.expiresAt - earlyMs - now)
|
||||
this.refreshTimer = setTimeout(() => void this.refreshAuthorization(), delay)
|
||||
}
|
||||
|
||||
private async refreshAuthorization(): Promise<void> {
|
||||
this.refreshTimer = null
|
||||
try {
|
||||
const accessToken = await this.options.refreshAccessToken()
|
||||
this.assertCurrent()
|
||||
if (!accessToken) {
|
||||
this.closeNow()
|
||||
return
|
||||
}
|
||||
const authorization = await exchangeRelayAuthorization({
|
||||
endpoint: this.options.authConfig.relayTokenEndpoint,
|
||||
accessToken,
|
||||
keypair: this.options.keypair,
|
||||
fetch: this.options.fetch
|
||||
})
|
||||
this.assertCurrent()
|
||||
this.originPool.refreshAuthorization(authorization.relayToken)
|
||||
this.authorization = authorization
|
||||
this.scheduleRefresh()
|
||||
} catch {
|
||||
const expiry = this.authorization?.expiresAt ?? 0
|
||||
const now = (this.options.now ?? Date.now)()
|
||||
if (!this.closed && this.options.isCurrent() && now <= expiry + 60_000) {
|
||||
const random = this.options.random ?? Math.random
|
||||
this.refreshTimer = setTimeout(
|
||||
() => void this.refreshAuthorization(),
|
||||
5_000 + Math.floor(random() * 10_001)
|
||||
)
|
||||
return
|
||||
}
|
||||
this.closeNow()
|
||||
}
|
||||
}
|
||||
|
||||
private assertCurrent(): void {
|
||||
if (!this.isCurrent()) {
|
||||
throw new StaleRelayBrokerError()
|
||||
}
|
||||
}
|
||||
|
||||
private isCurrent(): boolean {
|
||||
return !this.closed && this.options.isCurrent()
|
||||
}
|
||||
|
||||
private publishStatus(status: RelayBrokerStatus): void {
|
||||
if (this.isCurrent()) {
|
||||
this.options.onStatus(status)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import nacl from 'tweetnacl'
|
||||
import {
|
||||
encodeMobileE2EEV2Transcript,
|
||||
validateMobileE2EEV2Handshake,
|
||||
type MobileE2EEPayloadKind,
|
||||
type MobileE2EEV2Hello
|
||||
} from '../../../shared/mobile-e2ee-v2-contract'
|
||||
import {
|
||||
openMobileE2EEV2Frame,
|
||||
sealMobileE2EEV2Frame
|
||||
} from '../../../shared/mobile-e2ee-v2-framing'
|
||||
import { deriveSharedKey } from '../rpc/e2ee-crypto'
|
||||
import { deriveMobileE2EEV2KeySchedule } from '../rpc/mobile-e2ee-v2-key-schedule'
|
||||
|
||||
// Why: the relay integration test needs an independent mobile-side wire peer
|
||||
// without importing Expo modules into the desktop Node TypeScript project.
|
||||
export class SimulatedMobileE2EEV2Peer {
|
||||
readonly hello: MobileE2EEV2Hello
|
||||
private inboundCounter = 0n
|
||||
private outboundCounter = 0n
|
||||
private schedule: ReturnType<typeof deriveMobileE2EEV2KeySchedule> | null = null
|
||||
|
||||
constructor(
|
||||
private readonly clientKeys: nacl.BoxKeyPair,
|
||||
private readonly desktopPublicKey: Uint8Array,
|
||||
relayHostId: string,
|
||||
clientNonce = nacl.randomBytes(32)
|
||||
) {
|
||||
this.hello = {
|
||||
type: 'e2ee_hello',
|
||||
v: 2,
|
||||
clientPublicKeyB64: Buffer.from(clientKeys.publicKey).toString('base64'),
|
||||
clientNonceB64: Buffer.from(clientNonce).toString('base64'),
|
||||
capabilities: { framing: [2], payloadKinds: ['text', 'binary'] },
|
||||
context: {
|
||||
protocol: 'orca-mobile-e2ee',
|
||||
initiator: 'mobile',
|
||||
responder: 'desktop',
|
||||
transport: 'relay',
|
||||
relayHostId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
acceptReady(value: unknown): boolean {
|
||||
const handshake = validateMobileE2EEV2Handshake(this.hello, value)
|
||||
if (!handshake || !nacl.verify(handshake.desktopPublicKey, this.desktopPublicKey)) {
|
||||
return false
|
||||
}
|
||||
this.schedule = deriveMobileE2EEV2KeySchedule({
|
||||
sharedSecret: deriveSharedKey(this.clientKeys.secretKey, this.desktopPublicKey),
|
||||
transcript: encodeMobileE2EEV2Transcript(handshake),
|
||||
clientNonce: handshake.clientNonce,
|
||||
desktopNonce: handshake.desktopNonce
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
get transcriptHashB64(): string {
|
||||
return Buffer.from(this.requireSchedule().transcriptHash).toString('base64')
|
||||
}
|
||||
|
||||
sealText(plaintext: string): string {
|
||||
return Buffer.from(this.seal(new TextEncoder().encode(plaintext), 'text')).toString('base64')
|
||||
}
|
||||
|
||||
sealBinary(plaintext: Uint8Array): Uint8Array {
|
||||
return this.seal(plaintext, 'binary')
|
||||
}
|
||||
|
||||
openText(frameB64: string): string | null {
|
||||
const plaintext = this.open(Buffer.from(frameB64, 'base64'), 'text')
|
||||
return plaintext ? new TextDecoder().decode(plaintext) : null
|
||||
}
|
||||
|
||||
openBinary(frame: Uint8Array): Uint8Array | null {
|
||||
return this.open(frame, 'binary')
|
||||
}
|
||||
|
||||
private seal(payload: Uint8Array, payloadKind: MobileE2EEPayloadKind): Uint8Array {
|
||||
const schedule = this.requireSchedule()
|
||||
const frame = sealMobileE2EEV2Frame({
|
||||
payload,
|
||||
key: schedule.mobileToDesktopKey,
|
||||
sessionId: schedule.sessionId,
|
||||
direction: 'mobile-to-desktop',
|
||||
payloadKind,
|
||||
counter: this.outboundCounter
|
||||
})
|
||||
this.outboundCounter++
|
||||
return frame
|
||||
}
|
||||
|
||||
private open(frame: Uint8Array, payloadKind: MobileE2EEPayloadKind): Uint8Array | null {
|
||||
const schedule = this.requireSchedule()
|
||||
const plaintext = openMobileE2EEV2Frame({
|
||||
frame,
|
||||
key: schedule.desktopToMobileKey,
|
||||
sessionId: schedule.sessionId,
|
||||
direction: 'desktop-to-mobile',
|
||||
payloadKind,
|
||||
expectedCounter: this.inboundCounter
|
||||
})
|
||||
if (plaintext) {
|
||||
this.inboundCounter++
|
||||
}
|
||||
return plaintext
|
||||
}
|
||||
|
||||
private requireSchedule(): ReturnType<typeof deriveMobileE2EEV2KeySchedule> {
|
||||
if (!this.schedule) {
|
||||
throw new Error('Simulated mobile peer has not accepted E2EE ready')
|
||||
}
|
||||
return this.schedule
|
||||
}
|
||||
}
|
||||
@@ -478,9 +478,7 @@ describe('remote runtime request connection integration', () => {
|
||||
REMOTE_RUNTIME_REQUEST_TIMEOUT_MS,
|
||||
() => `cleanup count ${subscriptionCleanups.size}, event count ${mixedEvents.length}`
|
||||
)
|
||||
expect(
|
||||
(server as unknown as { wsConnectionIds: Map<unknown, unknown> }).wsConnectionIds.size
|
||||
).toBe(1)
|
||||
expect(server.getMobileSocketWiring()?.connectionCount).toBe(1)
|
||||
for (const mixed of mixedSubscriptions) {
|
||||
mixed.close()
|
||||
}
|
||||
@@ -500,9 +498,7 @@ describe('remote runtime request connection integration', () => {
|
||||
)
|
||||
)
|
||||
)
|
||||
expect(
|
||||
(server as unknown as { wsConnectionIds: Map<unknown, unknown> }).wsConnectionIds.size
|
||||
).toBe(1)
|
||||
expect(server.getMobileSocketWiring()?.connectionCount).toBe(1)
|
||||
for (const extra of extraSubscriptions) {
|
||||
extra.close()
|
||||
}
|
||||
|
||||
@@ -5,6 +5,17 @@
|
||||
import { ZodError, type ZodType } from 'zod'
|
||||
import type { TerminalStreamFrame } from '../../../shared/terminal-stream-protocol'
|
||||
import type { OrcaRuntimeService } from '../orca-runtime'
|
||||
import type {
|
||||
DeviceCredentialInstalled,
|
||||
PairingGetEndpointsParams,
|
||||
PairingGetEndpointsResult,
|
||||
PairingProvisionRelayParams
|
||||
} from '../../../shared/mobile-relay-credential-contract'
|
||||
|
||||
export type PairingRpcContext = {
|
||||
getEndpoints(params: PairingGetEndpointsParams): Promise<PairingGetEndpointsResult>
|
||||
provisionRelay(params: PairingProvisionRelayParams): Promise<DeviceCredentialInstalled>
|
||||
}
|
||||
|
||||
export type RpcEnvelopeMeta = {
|
||||
runtimeId: string
|
||||
@@ -64,6 +75,7 @@ export type RpcContext = {
|
||||
// clients. Carries the paired device's scope so handlers can gate the diet to
|
||||
// phones only. Undefined for in-process callers → treat as full-class (no clip).
|
||||
clientKind?: 'mobile' | 'runtime'
|
||||
pairing?: PairingRpcContext
|
||||
// Why: mobile terminal traffic is byte-oriented and bypasses JSON streaming
|
||||
// responses after the binary terminal cutover. Undefined on Unix/socket
|
||||
// transports and non-E2EE WebSocket paths.
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
isStreamingMethod,
|
||||
type RpcAnyMethod,
|
||||
type RpcEnvelopeMeta,
|
||||
type PairingRpcContext,
|
||||
type RpcRegistry,
|
||||
type RpcRequest,
|
||||
type RpcResponse
|
||||
@@ -102,6 +103,7 @@ export class RpcDispatcher {
|
||||
signal?: AbortSignal
|
||||
clientId?: string
|
||||
clientKind?: 'mobile' | 'runtime'
|
||||
pairing?: PairingRpcContext
|
||||
sendBinary?: (bytes: Uint8Array<ArrayBufferLike>) => boolean | void
|
||||
registerBinaryStreamHandler?: (
|
||||
streamId: number,
|
||||
@@ -135,6 +137,7 @@ export class RpcDispatcher {
|
||||
connectionId: options?.connectionId,
|
||||
clientId: options?.clientId,
|
||||
clientKind: options?.clientKind,
|
||||
pairing: options?.pairing,
|
||||
sendBinary: options?.sendBinary,
|
||||
registerBinaryStreamHandler: options?.registerBinaryStreamHandler
|
||||
})
|
||||
|
||||
@@ -34,7 +34,10 @@ function setup(overrides?: Partial<E2EEChannelOptions>) {
|
||||
const onError = vi.fn()
|
||||
const channel = new E2EEChannel(ws as unknown as WebSocket, {
|
||||
serverSecretKey: serverKeys.secretKey,
|
||||
validateToken: (token) => token === 'valid-token',
|
||||
resolveAuthenticatedDevice: (token) =>
|
||||
token === 'valid-token'
|
||||
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile' }
|
||||
: null,
|
||||
onReady: vi.fn(),
|
||||
onError,
|
||||
...overrides
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import type { WebSocket } from 'ws'
|
||||
import {
|
||||
encodeMobileE2EEV2Transcript,
|
||||
validateMobileE2EEV2Handshake,
|
||||
type MobileE2EEV2Hello,
|
||||
type MobileE2EEV2Ready
|
||||
} from '../../../shared/mobile-e2ee-v2-contract'
|
||||
import {
|
||||
openMobileE2EEV2Frame,
|
||||
sealMobileE2EEV2Frame
|
||||
} from '../../../shared/mobile-e2ee-v2-framing'
|
||||
import { deriveSharedKey } from './e2ee-crypto'
|
||||
import { E2EEChannel } from './e2ee-channel'
|
||||
import { deriveMobileE2EEV2KeySchedule } from './mobile-e2ee-v2-key-schedule'
|
||||
|
||||
const server = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1))
|
||||
const client = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2))
|
||||
|
||||
function createMockWs() {
|
||||
const sent: { data: string | Buffer; options?: { binary?: boolean } }[] = []
|
||||
return {
|
||||
OPEN: 1 as const,
|
||||
readyState: 1,
|
||||
bufferedAmount: 0,
|
||||
send: vi.fn((data: string | Buffer, options?: { binary?: boolean }) => {
|
||||
sent.push({ data, options })
|
||||
}),
|
||||
sent
|
||||
}
|
||||
}
|
||||
|
||||
function hello(): MobileE2EEV2Hello {
|
||||
return {
|
||||
type: 'e2ee_hello',
|
||||
v: 2,
|
||||
clientPublicKeyB64: Buffer.from(client.publicKey).toString('base64'),
|
||||
clientNonceB64: Buffer.from(new Uint8Array(32).fill(3)).toString('base64'),
|
||||
capabilities: { framing: [2], payloadKinds: ['text', 'binary'] },
|
||||
context: {
|
||||
protocol: 'orca-mobile-e2ee',
|
||||
initiator: 'mobile',
|
||||
responder: 'desktop',
|
||||
transport: 'relay',
|
||||
relayHostId: 'AbCdEf0123_-xyZ9'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setup() {
|
||||
const ws = createMockWs()
|
||||
const onReady = vi.fn()
|
||||
const onError = vi.fn()
|
||||
const resolveAuthenticatedDevice = vi.fn((token: string) =>
|
||||
token === 'valid-token'
|
||||
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile' as const }
|
||||
: null
|
||||
)
|
||||
const channel = new E2EEChannel(ws as unknown as WebSocket, {
|
||||
serverSecretKey: server.secretKey,
|
||||
resolveAuthenticatedDevice,
|
||||
onReady,
|
||||
onError,
|
||||
transportContext: { transport: 'relay', relayHostId: 'AbCdEf0123_-xyZ9' },
|
||||
requireV2: true
|
||||
})
|
||||
return { ws, channel, onReady, onError, resolveAuthenticatedDevice }
|
||||
}
|
||||
|
||||
function startV2(ctx: ReturnType<typeof setup>) {
|
||||
const clientHello = hello()
|
||||
ctx.channel.handleRawMessage(JSON.stringify(clientHello))
|
||||
const ready = JSON.parse(ctx.ws.sent[0]!.data.toString()) as MobileE2EEV2Ready
|
||||
const handshake = validateMobileE2EEV2Handshake(clientHello, ready)!
|
||||
const schedule = deriveMobileE2EEV2KeySchedule({
|
||||
sharedSecret: deriveSharedKey(client.secretKey, server.publicKey),
|
||||
transcript: encodeMobileE2EEV2Transcript(handshake),
|
||||
clientNonce: handshake.clientNonce,
|
||||
desktopNonce: handshake.desktopNonce
|
||||
})
|
||||
return { ready, schedule }
|
||||
}
|
||||
|
||||
function clientText(
|
||||
plaintext: string,
|
||||
schedule: ReturnType<typeof startV2>['schedule'],
|
||||
counter: bigint
|
||||
): string {
|
||||
const frame = sealMobileE2EEV2Frame({
|
||||
payload: new TextEncoder().encode(plaintext),
|
||||
key: schedule.mobileToDesktopKey,
|
||||
sessionId: schedule.sessionId,
|
||||
direction: 'mobile-to-desktop',
|
||||
payloadKind: 'text',
|
||||
counter
|
||||
})
|
||||
return Buffer.from(frame).toString('base64')
|
||||
}
|
||||
|
||||
function openServerFrame(
|
||||
frame: string | Buffer,
|
||||
kind: 'text' | 'binary',
|
||||
schedule: ReturnType<typeof startV2>['schedule'],
|
||||
counter: bigint
|
||||
): Uint8Array | null {
|
||||
return openMobileE2EEV2Frame({
|
||||
frame: typeof frame === 'string' ? Buffer.from(frame, 'base64') : frame,
|
||||
key: schedule.desktopToMobileKey,
|
||||
sessionId: schedule.sessionId,
|
||||
direction: 'desktop-to-mobile',
|
||||
payloadKind: kind,
|
||||
expectedCounter: counter
|
||||
})
|
||||
}
|
||||
|
||||
function authenticate(
|
||||
ctx: ReturnType<typeof setup>,
|
||||
schedule: ReturnType<typeof startV2>['schedule']
|
||||
) {
|
||||
const transcriptHashB64 = Buffer.from(schedule.transcriptHash).toString('base64')
|
||||
ctx.channel.handleRawMessage(
|
||||
clientText(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_auth',
|
||||
v: 2,
|
||||
transcriptHashB64,
|
||||
deviceToken: 'valid-token'
|
||||
}),
|
||||
schedule,
|
||||
0n
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
describe('E2EEChannel v2', () => {
|
||||
beforeEach(() => vi.useFakeTimers())
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('confirms the transcript before evaluating DeviceRegistry auth', () => {
|
||||
const ctx = setup()
|
||||
const { schedule } = startV2(ctx)
|
||||
authenticate(ctx, schedule)
|
||||
|
||||
expect(ctx.resolveAuthenticatedDevice).toHaveBeenCalledOnce()
|
||||
expect(ctx.onReady).toHaveBeenCalledWith(ctx.channel, {
|
||||
deviceId: 'device-1',
|
||||
deviceToken: 'valid-token',
|
||||
scope: 'mobile'
|
||||
})
|
||||
const authenticated = openServerFrame(ctx.ws.sent[1]!.data, 'text', schedule, 0n)
|
||||
expect(JSON.parse(new TextDecoder().decode(authenticated!))).toEqual({
|
||||
type: 'e2ee_authenticated',
|
||||
v: 2,
|
||||
transcriptHashB64: Buffer.from(schedule.transcriptHash).toString('base64')
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects legacy downgrade and injected auth metadata when v2 is required', () => {
|
||||
const legacy = setup()
|
||||
legacy.channel.handleRawMessage(
|
||||
JSON.stringify({ type: 'e2ee_hello', publicKeyB64: 'legacy-key' })
|
||||
)
|
||||
expect(legacy.onError).toHaveBeenCalledWith(4001, 'E2EE v2 required')
|
||||
|
||||
const ctx = setup()
|
||||
const { schedule } = startV2(ctx)
|
||||
const transcriptHashB64 = Buffer.from(schedule.transcriptHash).toString('base64')
|
||||
ctx.channel.handleRawMessage(
|
||||
clientText(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_auth',
|
||||
v: 2,
|
||||
transcriptHashB64,
|
||||
deviceToken: 'valid-token',
|
||||
relayDeviceId: 'injected'
|
||||
}),
|
||||
schedule,
|
||||
0n
|
||||
)
|
||||
)
|
||||
expect(ctx.resolveAuthenticatedDevice).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a captured auth frame replayed onto a fresh desktop nonce', () => {
|
||||
const first = setup()
|
||||
const firstHandshake = startV2(first)
|
||||
const capturedAuth = clientText(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_auth',
|
||||
v: 2,
|
||||
transcriptHashB64: Buffer.from(firstHandshake.schedule.transcriptHash).toString('base64'),
|
||||
deviceToken: 'valid-token'
|
||||
}),
|
||||
firstHandshake.schedule,
|
||||
0n
|
||||
)
|
||||
|
||||
const second = setup()
|
||||
const secondHandshake = startV2(second)
|
||||
expect(secondHandshake.ready.desktopNonceB64).not.toBe(firstHandshake.ready.desktopNonceB64)
|
||||
second.channel.handleRawMessage(capturedAuth)
|
||||
expect(second.resolveAuthenticatedDevice).not.toHaveBeenCalled()
|
||||
expect(second.onReady).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a captured authenticated mutating trace on a fresh socket', () => {
|
||||
const first = setup()
|
||||
const firstHandshake = startV2(first)
|
||||
const transcriptHashB64 = Buffer.from(firstHandshake.schedule.transcriptHash).toString('base64')
|
||||
const capturedAuth = clientText(
|
||||
JSON.stringify({ type: 'e2ee_auth', v: 2, transcriptHashB64, deviceToken: 'valid-token' }),
|
||||
firstHandshake.schedule,
|
||||
0n
|
||||
)
|
||||
const capturedMutation = clientText(
|
||||
JSON.stringify({ method: 'device.remove', params: { deviceId: 'device-1' } }),
|
||||
firstHandshake.schedule,
|
||||
1n
|
||||
)
|
||||
const firstMutation = vi.fn()
|
||||
first.channel.onMessage(firstMutation)
|
||||
first.channel.handleRawMessage(capturedAuth)
|
||||
first.channel.handleRawMessage(capturedMutation)
|
||||
expect(firstMutation).toHaveBeenCalledOnce()
|
||||
|
||||
const second = setup()
|
||||
startV2(second)
|
||||
const replayedMutation = vi.fn()
|
||||
second.channel.onMessage(replayedMutation)
|
||||
second.channel.handleRawMessage(capturedAuth)
|
||||
second.channel.handleRawMessage(capturedMutation)
|
||||
expect(second.resolveAuthenticatedDevice).not.toHaveBeenCalled()
|
||||
expect(replayedMutation).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('preserves one queued counter order across text and binary replies', () => {
|
||||
const ctx = setup()
|
||||
const { schedule } = startV2(ctx)
|
||||
authenticate(ctx, schedule)
|
||||
ctx.ws.bufferedAmount = 9 * 1024 * 1024
|
||||
ctx.channel.onMessage((_request, textReply, binaryReply) => {
|
||||
textReply('one')
|
||||
binaryReply(new Uint8Array([2]))
|
||||
})
|
||||
ctx.channel.handleRawMessage(clientText('{"method":"status.get"}', schedule, 1n))
|
||||
expect(ctx.ws.sent).toHaveLength(2)
|
||||
|
||||
ctx.ws.bufferedAmount = 0
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(
|
||||
new TextDecoder().decode(openServerFrame(ctx.ws.sent[2]!.data, 'text', schedule, 1n)!)
|
||||
).toBe('one')
|
||||
expect(openServerFrame(ctx.ws.sent[3]!.data, 'binary', schedule, 2n)).toEqual(
|
||||
new Uint8Array([2])
|
||||
)
|
||||
expect(ctx.ws.sent[3]!.options).toEqual({ binary: true })
|
||||
})
|
||||
})
|
||||
@@ -27,7 +27,10 @@ function setup(overrides?: Partial<E2EEChannelOptions>) {
|
||||
|
||||
const channel = new E2EEChannel(ws as unknown as WebSocket, {
|
||||
serverSecretKey: serverKeys.secretKey,
|
||||
validateToken: (token) => token === 'valid-token',
|
||||
resolveAuthenticatedDevice: (token) =>
|
||||
token === 'valid-token'
|
||||
? { deviceId: 'device-1', deviceToken: token, scope: 'mobile' }
|
||||
: null,
|
||||
onReady,
|
||||
onError,
|
||||
...overrides
|
||||
@@ -63,7 +66,11 @@ describe('E2EEChannel', () => {
|
||||
const ctx = setup()
|
||||
doHandshake(ctx)
|
||||
|
||||
expect(ctx.onReady).toHaveBeenCalledWith(ctx.channel)
|
||||
expect(ctx.onReady).toHaveBeenCalledWith(ctx.channel, {
|
||||
deviceId: 'device-1',
|
||||
deviceToken: 'valid-token',
|
||||
scope: 'mobile'
|
||||
})
|
||||
expect(ctx.onError).not.toHaveBeenCalled()
|
||||
expect(ctx.channel.deviceToken).toBe('valid-token')
|
||||
|
||||
|
||||
@@ -7,6 +7,16 @@ import {
|
||||
createWsOutboundBackpressureQueue,
|
||||
type WsOutboundBackpressureQueue
|
||||
} from '../../../shared/ws-outbound-backpressure-queue'
|
||||
import {
|
||||
DesktopMobileE2EEV2Session,
|
||||
type DesktopMobileE2EEV2Context
|
||||
} from './mobile-e2ee-v2-desktop-session'
|
||||
import {
|
||||
createDesktopMobileE2EEV2OutboundQueue,
|
||||
type DesktopMobileE2EEV2OutboundItem as V2OutboundItem
|
||||
} from './mobile-e2ee-v2-desktop-outbound'
|
||||
import { handleDesktopMobileE2EEV2Inbound } from './mobile-e2ee-v2-desktop-inbound'
|
||||
import { isValidMobileE2EEAuthVersion, type MobileE2EEAuth } from './mobile-e2ee-auth-validation'
|
||||
|
||||
type ChannelState = 'awaiting_hello' | 'awaiting_auth' | 'ready'
|
||||
|
||||
@@ -14,21 +24,19 @@ const HANDSHAKE_TIMEOUT_MS = 10_000
|
||||
const MAX_CONSECUTIVE_DECRYPT_FAILURES = 5
|
||||
const MAX_BINARY_BUFFERED_AMOUNT = 8 * 1024 * 1024
|
||||
|
||||
type E2EEHello = {
|
||||
type: 'e2ee_hello'
|
||||
publicKeyB64: string
|
||||
}
|
||||
|
||||
type E2EEAuth = {
|
||||
type: 'e2ee_auth'
|
||||
deviceToken: string
|
||||
}
|
||||
|
||||
export type E2EEChannelOptions = {
|
||||
serverSecretKey: Uint8Array
|
||||
validateToken: (token: string) => boolean
|
||||
onReady: (channel: E2EEChannel) => void
|
||||
resolveAuthenticatedDevice: (token: string) => E2EEAuthenticatedDevice | null
|
||||
onReady: (channel: E2EEChannel, device: E2EEAuthenticatedDevice) => void
|
||||
onError: (code: number, reason: string) => void
|
||||
transportContext?: DesktopMobileE2EEV2Context
|
||||
requireV2?: boolean
|
||||
}
|
||||
|
||||
export type E2EEAuthenticatedDevice = {
|
||||
deviceId: string
|
||||
deviceToken: string
|
||||
scope: 'mobile' | 'runtime'
|
||||
}
|
||||
|
||||
export class E2EEChannel {
|
||||
@@ -38,9 +46,13 @@ export class E2EEChannel {
|
||||
private handshakeTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readonly ws: WebSocket
|
||||
private readonly serverSecretKey: Uint8Array
|
||||
private readonly validateToken: (token: string) => boolean
|
||||
private readonly onReady: (channel: E2EEChannel) => void
|
||||
private readonly resolveAuthenticatedDevice: (token: string) => E2EEAuthenticatedDevice | null
|
||||
private readonly onReady: (channel: E2EEChannel, device: E2EEAuthenticatedDevice) => void
|
||||
private readonly onError: (code: number, reason: string) => void
|
||||
private readonly transportContext: DesktopMobileE2EEV2Context
|
||||
private readonly requireV2: boolean
|
||||
private v2Session: DesktopMobileE2EEV2Session | null = null
|
||||
private v2OutboundQueue: WsOutboundBackpressureQueue<V2OutboundItem> | null = null
|
||||
// Why: the RPC handler is set after the channel is ready, so the channel
|
||||
// can forward decrypted messages. Kept as a callback rather than constructor
|
||||
// param because the handler needs the encrypt function for replies.
|
||||
@@ -59,13 +71,16 @@ export class E2EEChannel {
|
||||
private textReplyQueue: WsOutboundBackpressureQueue<string> | null = null
|
||||
|
||||
deviceToken: string | null = null
|
||||
authenticatedDevice: E2EEAuthenticatedDevice | null = null
|
||||
|
||||
constructor(ws: WebSocket, options: E2EEChannelOptions) {
|
||||
this.ws = ws
|
||||
this.serverSecretKey = options.serverSecretKey
|
||||
this.validateToken = options.validateToken
|
||||
this.resolveAuthenticatedDevice = options.resolveAuthenticatedDevice
|
||||
this.onReady = options.onReady
|
||||
this.onError = options.onError
|
||||
this.transportContext = options.transportContext ?? { transport: 'direct' }
|
||||
this.requireV2 = options.requireV2 ?? false
|
||||
|
||||
this.handshakeTimer = setTimeout(() => {
|
||||
this.onError(4002, 'E2EE handshake timeout')
|
||||
@@ -96,12 +111,17 @@ export class E2EEChannel {
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.sharedKey) {
|
||||
if (this.v2Session) {
|
||||
this.handleV2RawMessage(raw)
|
||||
return
|
||||
}
|
||||
const sharedKey = this.sharedKey
|
||||
if (!sharedKey) {
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof raw !== 'string') {
|
||||
const plaintextBytes = decryptBytes(raw, this.sharedKey)
|
||||
const plaintextBytes = decryptBytes(raw, sharedKey)
|
||||
if (plaintextBytes === null) {
|
||||
this.trackDecryptFailure()
|
||||
return
|
||||
@@ -115,7 +135,7 @@ export class E2EEChannel {
|
||||
return
|
||||
}
|
||||
|
||||
const plaintext = decrypt(raw, this.sharedKey)
|
||||
const plaintext = decrypt(raw, sharedKey)
|
||||
if (plaintext === null) {
|
||||
this.trackDecryptFailure()
|
||||
return
|
||||
@@ -160,15 +180,37 @@ export class E2EEChannel {
|
||||
}
|
||||
|
||||
private handleHello(raw: string): void {
|
||||
let hello: E2EEHello
|
||||
let hello: Record<string, unknown>
|
||||
try {
|
||||
hello = JSON.parse(raw) as E2EEHello
|
||||
hello = JSON.parse(raw) as Record<string, unknown>
|
||||
} catch {
|
||||
this.onError(4001, 'Invalid handshake message')
|
||||
return
|
||||
}
|
||||
|
||||
if (hello.type !== 'e2ee_hello' || !hello.publicKeyB64) {
|
||||
if (hello.type === 'e2ee_hello' && hello.v === 2) {
|
||||
const session = DesktopMobileE2EEV2Session.create({
|
||||
hello,
|
||||
serverSecretKey: this.serverSecretKey,
|
||||
expectedContext: this.transportContext
|
||||
})
|
||||
if (!session) {
|
||||
this.onError(4001, 'Invalid e2ee_hello v2')
|
||||
return
|
||||
}
|
||||
this.v2Session = session
|
||||
this.state = 'awaiting_auth'
|
||||
if (this.ws.readyState === this.ws.OPEN) {
|
||||
this.ws.send(JSON.stringify(session.ready))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (this.requireV2) {
|
||||
this.onError(4001, 'E2EE v2 required')
|
||||
return
|
||||
}
|
||||
if (hello.type !== 'e2ee_hello' || typeof hello.publicKeyB64 !== 'string') {
|
||||
this.onError(4001, 'Invalid e2ee_hello')
|
||||
return
|
||||
}
|
||||
@@ -192,27 +234,33 @@ export class E2EEChannel {
|
||||
}
|
||||
|
||||
private handleAuth(plaintext: string): void {
|
||||
let auth: E2EEAuth
|
||||
let auth: MobileE2EEAuth
|
||||
try {
|
||||
auth = JSON.parse(plaintext) as E2EEAuth
|
||||
auth = JSON.parse(plaintext) as MobileE2EEAuth
|
||||
} catch {
|
||||
this.sendEncryptedControl({ type: 'e2ee_error', error: { code: 'bad_auth' } })
|
||||
this.onError(4001, 'Invalid e2ee_auth')
|
||||
return
|
||||
}
|
||||
|
||||
if (auth.type !== 'e2ee_auth' || !auth.deviceToken) {
|
||||
if (
|
||||
auth.type !== 'e2ee_auth' ||
|
||||
!auth.deviceToken ||
|
||||
!isValidMobileE2EEAuthVersion(auth, this.v2Session)
|
||||
) {
|
||||
this.sendEncryptedControl({ type: 'e2ee_error', error: { code: 'bad_auth' } })
|
||||
this.onError(4001, 'Invalid e2ee_auth')
|
||||
return
|
||||
}
|
||||
if (!this.validateToken(auth.deviceToken)) {
|
||||
const authenticatedDevice = this.resolveAuthenticatedDevice(auth.deviceToken)
|
||||
if (!authenticatedDevice || authenticatedDevice.deviceToken !== auth.deviceToken) {
|
||||
this.sendEncryptedControl({ type: 'e2ee_error', error: { code: 'unauthorized' } })
|
||||
this.onError(4001, 'Unauthorized')
|
||||
return
|
||||
}
|
||||
|
||||
this.deviceToken = auth.deviceToken
|
||||
this.authenticatedDevice = authenticatedDevice
|
||||
this.state = 'ready'
|
||||
|
||||
if (this.handshakeTimer) {
|
||||
@@ -220,8 +268,52 @@ export class E2EEChannel {
|
||||
this.handshakeTimer = null
|
||||
}
|
||||
|
||||
this.sendEncryptedControl({ type: 'e2ee_authenticated' })
|
||||
this.onReady(this)
|
||||
// Why: transport-bound identity checks must complete before the peer sees
|
||||
// authentication success; relay sockets additionally bind this context to
|
||||
// their immutable relayDeviceId in the resolver.
|
||||
this.onReady(this, authenticatedDevice)
|
||||
this.sendEncryptedControl(
|
||||
this.v2Session
|
||||
? {
|
||||
type: 'e2ee_authenticated',
|
||||
v: 2,
|
||||
transcriptHashB64: this.v2Session.transcriptHashB64
|
||||
}
|
||||
: { type: 'e2ee_authenticated' }
|
||||
)
|
||||
}
|
||||
|
||||
private handleV2RawMessage(raw: string | Uint8Array<ArrayBufferLike>): void {
|
||||
handleDesktopMobileE2EEV2Inbound({
|
||||
session: this.v2Session!,
|
||||
raw,
|
||||
awaitingAuth: this.state === 'awaiting_auth',
|
||||
onDecryptFailure: () => this.trackDecryptFailure(),
|
||||
onDecryptSuccess: () => (this.consecutiveFailures = 0),
|
||||
onAuth: (plaintext) => this.handleAuth(plaintext),
|
||||
onBinary: (plaintext) => this.binaryMessageHandler?.(plaintext),
|
||||
onText: (plaintext) =>
|
||||
this.messageHandler?.(
|
||||
plaintext,
|
||||
(response) => this.enqueueV2({ kind: 'text', plaintext: response }),
|
||||
(response) => (this.enqueueV2({ kind: 'binary', plaintext: response }), true)
|
||||
),
|
||||
onProtocolError: () => this.onError(4001, 'Invalid binary message before authentication')
|
||||
})
|
||||
}
|
||||
|
||||
private enqueueV2(item: V2OutboundItem): void {
|
||||
if (!this.v2Session || this.ws.readyState !== this.ws.OPEN) {
|
||||
return
|
||||
}
|
||||
if (!this.v2OutboundQueue) {
|
||||
this.v2OutboundQueue = createDesktopMobileE2EEV2OutboundQueue({
|
||||
ws: this.ws,
|
||||
session: this.v2Session,
|
||||
onOverflow: () => this.onError(1013, 'Outbound reply buffer overflow')
|
||||
})
|
||||
}
|
||||
this.v2OutboundQueue.enqueue(item)
|
||||
}
|
||||
|
||||
private ensureTextReplyQueue(): WsOutboundBackpressureQueue<string> {
|
||||
@@ -241,7 +333,9 @@ export class E2EEChannel {
|
||||
}
|
||||
|
||||
private sendEncryptedControl(message: unknown): void {
|
||||
if (this.ws.readyState === this.ws.OPEN && this.sharedKey) {
|
||||
if (this.v2Session) {
|
||||
this.enqueueV2({ kind: 'text', plaintext: JSON.stringify(message) })
|
||||
} else if (this.ws.readyState === this.ws.OPEN && this.sharedKey) {
|
||||
this.ws.send(encrypt(JSON.stringify(message), this.sharedKey))
|
||||
}
|
||||
}
|
||||
@@ -252,9 +346,13 @@ export class E2EEChannel {
|
||||
this.handshakeTimer = null
|
||||
}
|
||||
this.sharedKey = null
|
||||
this.authenticatedDevice = null
|
||||
this.v2Session = null
|
||||
this.messageHandler = null
|
||||
this.binaryMessageHandler = null
|
||||
this.textReplyQueue?.dispose()
|
||||
this.textReplyQueue = null
|
||||
this.v2OutboundQueue?.dispose()
|
||||
this.v2OutboundQueue = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import {
|
||||
generateKeyPair,
|
||||
deriveSharedKey,
|
||||
@@ -7,8 +8,24 @@ import {
|
||||
encryptBytes,
|
||||
decryptBytes
|
||||
} from './e2ee-crypto'
|
||||
import { MOBILE_E2EE_LEGACY_FIXTURE } from '../../../shared/mobile-e2ee-legacy-fixtures'
|
||||
|
||||
describe('e2ee-crypto', () => {
|
||||
it('preserves the captured legacy key and text/binary frame bytes', () => {
|
||||
const fixture = MOBILE_E2EE_LEGACY_FIXTURE
|
||||
const server = nacl.box.keyPair.fromSecretKey(fixture.serverSecretKey)
|
||||
const client = nacl.box.keyPair.fromSecretKey(fixture.clientSecretKey)
|
||||
const shared = deriveSharedKey(client.secretKey, server.publicKey)
|
||||
|
||||
expect(Buffer.from(server.publicKey).toString('base64')).toBe(fixture.serverPublicKeyB64)
|
||||
expect(Buffer.from(client.publicKey).toString('base64')).toBe(fixture.clientPublicKeyB64)
|
||||
expect(Buffer.from(shared).toString('hex')).toBe(fixture.sharedKeyHex)
|
||||
expect(decrypt(fixture.authFrameB64, shared)).toBe(fixture.authPlaintext)
|
||||
expect(decryptBytes(Buffer.from(fixture.binaryFrameHex, 'hex'), shared)).toEqual(
|
||||
fixture.binaryPlaintext
|
||||
)
|
||||
})
|
||||
|
||||
it('encrypt/decrypt round-trips with shared key', () => {
|
||||
const server = generateKeyPair()
|
||||
const client = generateKeyPair()
|
||||
|
||||
@@ -44,7 +44,10 @@ describe('E2EE integration (simulated mobile ↔ desktop)', () => {
|
||||
|
||||
channel = new E2EEChannel(mockWs as unknown as WebSocket, {
|
||||
serverSecretKey: serverKeys.secretKey,
|
||||
validateToken: (token) => token === 'device-abc',
|
||||
resolveAuthenticatedDevice: (token) =>
|
||||
token === 'device-abc'
|
||||
? { deviceId: 'device-abc', deviceToken: token, scope: 'mobile' }
|
||||
: null,
|
||||
onReady,
|
||||
onError
|
||||
})
|
||||
@@ -118,7 +121,10 @@ describe('E2EE integration (simulated mobile ↔ desktop)', () => {
|
||||
const newMobileKeys = generateKeyPair()
|
||||
const newChannel = new E2EEChannel(mockWs as unknown as WebSocket, {
|
||||
serverSecretKey: serverKeys.secretKey,
|
||||
validateToken: (token) => token === 'device-abc',
|
||||
resolveAuthenticatedDevice: (token) =>
|
||||
token === 'device-abc'
|
||||
? { deviceId: 'device-abc', deviceToken: token, scope: 'mobile' }
|
||||
: null,
|
||||
onReady,
|
||||
onError
|
||||
})
|
||||
|
||||
@@ -34,6 +34,7 @@ import { SKILL_METHODS } from './skills'
|
||||
import { CLIPBOARD_METHODS } from './clipboard'
|
||||
import { HOST_CAPABILITY_METHODS } from './host-capabilities'
|
||||
import { EMULATOR_METHODS } from './emulator'
|
||||
import { PAIRING_METHODS } from './pairing'
|
||||
|
||||
// Why: a flat manifest keeps registration order explicit and provides one
|
||||
// grep-point for "what methods does the RPC server expose?" — useful when
|
||||
@@ -73,5 +74,6 @@ export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [
|
||||
...HOST_CAPABILITY_METHODS,
|
||||
...CLIENT_EVENT_METHODS,
|
||||
...CLIENT_UI_METHODS,
|
||||
...EMULATOR_METHODS
|
||||
...EMULATOR_METHODS,
|
||||
...PAIRING_METHODS
|
||||
]
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import { PAIRING_METHODS } from './pairing'
|
||||
|
||||
function dispatchPairing(
|
||||
method: string,
|
||||
params: unknown,
|
||||
pairing: NonNullable<Parameters<RpcDispatcher['dispatchStreaming']>[2]>['pairing']
|
||||
): Promise<Record<string, unknown>> {
|
||||
return new Promise((resolve) => {
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
methods: PAIRING_METHODS
|
||||
})
|
||||
void dispatcher.dispatchStreaming(
|
||||
{ id: 'request-1', authToken: '', method, params },
|
||||
(response) => resolve(JSON.parse(response) as Record<string, unknown>),
|
||||
{ pairing }
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
describe('pairing RPC methods', () => {
|
||||
it('passes only phone-owned credential material to the server-bound provider', async () => {
|
||||
const provisionRelay = vi.fn().mockResolvedValue({
|
||||
v: 1,
|
||||
reqId: 'install-1',
|
||||
authorizationMode: 'authenticated-direct',
|
||||
currentVersion: 1,
|
||||
resumeExpiresAt: Date.now() + 60_000
|
||||
})
|
||||
const pairing = { getEndpoints: vi.fn(), provisionRelay }
|
||||
|
||||
await expect(
|
||||
dispatchPairing(
|
||||
'pairing.provisionRelay',
|
||||
{ reqId: 'install-1', newResumeTokenHash: 'A'.repeat(43) },
|
||||
pairing
|
||||
)
|
||||
).resolves.toMatchObject({ ok: true })
|
||||
expect(provisionRelay).toHaveBeenCalledWith({
|
||||
reqId: 'install-1',
|
||||
newResumeTokenHash: 'A'.repeat(43)
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects caller-selected identity and authorization metadata', async () => {
|
||||
const pairing = { getEndpoints: vi.fn(), provisionRelay: vi.fn() }
|
||||
|
||||
for (const injected of [
|
||||
{ relayDeviceId: 'attacker-device' },
|
||||
{ authorization: { mode: 'relay-basis', basisConnId: 'attacker-basis' } },
|
||||
{ directAuthId: 'attacker-direct' },
|
||||
{ acceptedCredentialVersion: 99 }
|
||||
]) {
|
||||
await expect(
|
||||
dispatchPairing(
|
||||
'pairing.provisionRelay',
|
||||
{ reqId: 'install-1', newResumeTokenHash: 'A'.repeat(43), ...injected },
|
||||
pairing
|
||||
)
|
||||
).resolves.toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
}
|
||||
await expect(
|
||||
dispatchPairing(
|
||||
'pairing.getEndpoints',
|
||||
{ installReqId: 'status-1', basisConnId: 'injected' },
|
||||
pairing
|
||||
)
|
||||
).resolves.toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
expect(pairing.provisionRelay).not.toHaveBeenCalled()
|
||||
expect(pairing.getEndpoints).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import { defineMethod, type RpcAnyMethod } from '../core'
|
||||
import {
|
||||
PairingGetEndpointsParamsSchema,
|
||||
PairingProvisionRelayParamsSchema
|
||||
} from '../../../../shared/mobile-relay-credential-contract'
|
||||
|
||||
export const PAIRING_METHODS: readonly RpcAnyMethod[] = [
|
||||
defineMethod({
|
||||
name: 'pairing.getEndpoints',
|
||||
params: PairingGetEndpointsParamsSchema,
|
||||
handler: async (params, ctx) => {
|
||||
if (!ctx.pairing) {
|
||||
throw new Error('pairing_context_unavailable')
|
||||
}
|
||||
return await ctx.pairing.getEndpoints(params)
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'pairing.provisionRelay',
|
||||
params: PairingProvisionRelayParamsSchema,
|
||||
handler: async (params, ctx) => {
|
||||
if (!ctx.pairing) {
|
||||
throw new Error('pairing_context_unavailable')
|
||||
}
|
||||
return await ctx.pairing.provisionRelay(params)
|
||||
}
|
||||
})
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { DesktopMobileE2EEV2Session } from './mobile-e2ee-v2-desktop-session'
|
||||
|
||||
export type MobileE2EEAuth = {
|
||||
type: 'e2ee_auth'
|
||||
deviceToken: string
|
||||
v?: 2
|
||||
transcriptHashB64?: string
|
||||
}
|
||||
|
||||
export function isValidMobileE2EEAuthVersion(
|
||||
auth: MobileE2EEAuth,
|
||||
v2Session: DesktopMobileE2EEV2Session | null
|
||||
): boolean {
|
||||
if (!v2Session) {
|
||||
return auth.v === undefined && auth.transcriptHashB64 === undefined
|
||||
}
|
||||
return (
|
||||
Object.keys(auth).sort().join(',') === 'deviceToken,transcriptHashB64,type,v' &&
|
||||
auth.v === 2 &&
|
||||
auth.transcriptHashB64 === v2Session.transcriptHashB64
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { DesktopMobileE2EEV2Session } from './mobile-e2ee-v2-desktop-session'
|
||||
|
||||
export function handleDesktopMobileE2EEV2Inbound(args: {
|
||||
session: DesktopMobileE2EEV2Session
|
||||
raw: string | Uint8Array<ArrayBufferLike>
|
||||
awaitingAuth: boolean
|
||||
onDecryptFailure: () => void
|
||||
onDecryptSuccess: () => void
|
||||
onAuth: (plaintext: string) => void
|
||||
onBinary: (plaintext: Uint8Array<ArrayBufferLike>) => void
|
||||
onText: (plaintext: string) => void
|
||||
onProtocolError: () => void
|
||||
}): void {
|
||||
const plaintext =
|
||||
typeof args.raw === 'string'
|
||||
? args.session.openText(args.raw)
|
||||
: args.session.openBinary(args.raw)
|
||||
if (plaintext === null) {
|
||||
args.onDecryptFailure()
|
||||
return
|
||||
}
|
||||
args.onDecryptSuccess()
|
||||
if (args.awaitingAuth) {
|
||||
if (typeof plaintext !== 'string') {
|
||||
args.onProtocolError()
|
||||
return
|
||||
}
|
||||
args.onAuth(plaintext)
|
||||
} else if (typeof plaintext === 'string') {
|
||||
args.onText(plaintext)
|
||||
} else {
|
||||
args.onBinary(plaintext)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { WebSocket } from 'ws'
|
||||
import {
|
||||
createWsOutboundBackpressureQueue,
|
||||
type WsOutboundBackpressureQueue
|
||||
} from '../../../shared/ws-outbound-backpressure-queue'
|
||||
import type { DesktopMobileE2EEV2Session } from './mobile-e2ee-v2-desktop-session'
|
||||
|
||||
export type DesktopMobileE2EEV2OutboundItem =
|
||||
| { kind: 'text'; plaintext: string }
|
||||
| { kind: 'binary'; plaintext: Uint8Array<ArrayBufferLike> }
|
||||
|
||||
export function createDesktopMobileE2EEV2OutboundQueue(args: {
|
||||
ws: WebSocket
|
||||
session: DesktopMobileE2EEV2Session
|
||||
onOverflow: () => void
|
||||
}): WsOutboundBackpressureQueue<DesktopMobileE2EEV2OutboundItem> {
|
||||
return createWsOutboundBackpressureQueue<DesktopMobileE2EEV2OutboundItem>({
|
||||
// Why: sealing happens only after queue admission, so counters cannot be
|
||||
// consumed by an item rejected at the bounded queue boundary.
|
||||
send: (item) => {
|
||||
if (item.kind === 'text') {
|
||||
args.ws.send(args.session.sealText(item.plaintext))
|
||||
} else {
|
||||
args.ws.send(Buffer.from(args.session.sealBinary(item.plaintext)), { binary: true })
|
||||
}
|
||||
},
|
||||
byteLengthOf: (item) =>
|
||||
(item.kind === 'text'
|
||||
? new TextEncoder().encode(item.plaintext).length
|
||||
: item.plaintext.length) + 82,
|
||||
getBufferedAmount: () => args.ws.bufferedAmount,
|
||||
isWritable: () => args.ws.readyState === args.ws.OPEN,
|
||||
onOverflow: args.onOverflow
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import { deriveSharedKey } from './e2ee-crypto'
|
||||
import { deriveMobileE2EEV2KeySchedule } from './mobile-e2ee-v2-key-schedule'
|
||||
import {
|
||||
encodeMobileE2EEV2Transcript,
|
||||
validateMobileE2EEV2Handshake,
|
||||
type MobileE2EEV2Hello
|
||||
} from '../../../shared/mobile-e2ee-v2-contract'
|
||||
import { sealMobileE2EEV2Frame } from '../../../shared/mobile-e2ee-v2-framing'
|
||||
import { DesktopMobileE2EEV2Session } from './mobile-e2ee-v2-desktop-session'
|
||||
|
||||
const server = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1))
|
||||
const client = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2))
|
||||
|
||||
function hello(): MobileE2EEV2Hello {
|
||||
return {
|
||||
type: 'e2ee_hello',
|
||||
v: 2,
|
||||
clientPublicKeyB64: Buffer.from(client.publicKey).toString('base64'),
|
||||
clientNonceB64: Buffer.from(new Uint8Array(32).fill(3)).toString('base64'),
|
||||
capabilities: { framing: [2], payloadKinds: ['text', 'binary'] },
|
||||
context: {
|
||||
protocol: 'orca-mobile-e2ee',
|
||||
initiator: 'mobile',
|
||||
responder: 'desktop',
|
||||
transport: 'relay',
|
||||
relayHostId: 'AbCdEf0123_-xyZ9'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('desktop mobile E2EE v2 session', () => {
|
||||
it('creates a fresh ready message and opens exact-next auth counter zero', () => {
|
||||
const clientHello = hello()
|
||||
const session = DesktopMobileE2EEV2Session.create({
|
||||
hello: clientHello,
|
||||
serverSecretKey: server.secretKey,
|
||||
expectedContext: { transport: 'relay', relayHostId: 'AbCdEf0123_-xyZ9' },
|
||||
randomBytes: () => new Uint8Array(32).fill(4)
|
||||
})!
|
||||
const handshake = validateMobileE2EEV2Handshake(clientHello, session.ready)!
|
||||
const schedule = deriveMobileE2EEV2KeySchedule({
|
||||
sharedSecret: deriveSharedKey(client.secretKey, server.publicKey),
|
||||
transcript: encodeMobileE2EEV2Transcript(handshake),
|
||||
clientNonce: handshake.clientNonce,
|
||||
desktopNonce: handshake.desktopNonce
|
||||
})
|
||||
const auth = JSON.stringify({
|
||||
type: 'e2ee_auth',
|
||||
v: 2,
|
||||
transcriptHashB64: session.transcriptHashB64,
|
||||
deviceToken: 'token'
|
||||
})
|
||||
const frame = sealMobileE2EEV2Frame({
|
||||
payload: new TextEncoder().encode(auth),
|
||||
key: schedule.mobileToDesktopKey,
|
||||
sessionId: schedule.sessionId,
|
||||
direction: 'mobile-to-desktop',
|
||||
payloadKind: 'text',
|
||||
counter: 0n
|
||||
})
|
||||
|
||||
expect(session.openText(Buffer.from(frame).toString('base64'))).toBe(auth)
|
||||
expect(session.openText(Buffer.from(frame).toString('base64'))).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a transport or relayHostId mismatch before deriving keys', () => {
|
||||
expect(
|
||||
DesktopMobileE2EEV2Session.create({
|
||||
hello: hello(),
|
||||
serverSecretKey: server.secretKey,
|
||||
expectedContext: { transport: 'direct' }
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('shares one outbound counter across text and binary', () => {
|
||||
const session = DesktopMobileE2EEV2Session.create({
|
||||
hello: hello(),
|
||||
serverSecretKey: server.secretKey,
|
||||
expectedContext: { transport: 'relay', relayHostId: 'AbCdEf0123_-xyZ9' },
|
||||
randomBytes: () => new Uint8Array(32).fill(4)
|
||||
})!
|
||||
|
||||
const text = Buffer.from(session.sealText('one'), 'base64')
|
||||
const binary = session.sealBinary(new Uint8Array([2]))
|
||||
expect(text.subarray(16, 24)).toEqual(Buffer.alloc(8, 0))
|
||||
expect(binary.subarray(16, 24)).toEqual(Uint8Array.from(Buffer.from('0000000000000001', 'hex')))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
import nacl from 'tweetnacl'
|
||||
import {
|
||||
encodeMobileE2EEV2Transcript,
|
||||
validateMobileE2EEV2Handshake,
|
||||
type MobileE2EETransport,
|
||||
type MobileE2EEV2Hello,
|
||||
type MobileE2EEV2Ready
|
||||
} from '../../../shared/mobile-e2ee-v2-contract'
|
||||
import {
|
||||
openMobileE2EEV2Frame,
|
||||
sealMobileE2EEV2Frame
|
||||
} from '../../../shared/mobile-e2ee-v2-framing'
|
||||
import { deriveSharedKey } from './e2ee-crypto'
|
||||
import { deriveMobileE2EEV2KeySchedule } from './mobile-e2ee-v2-key-schedule'
|
||||
|
||||
export type DesktopMobileE2EEV2Context = {
|
||||
transport: MobileE2EETransport
|
||||
relayHostId?: string
|
||||
}
|
||||
|
||||
export class DesktopMobileE2EEV2Session {
|
||||
private inboundCounter = 0n
|
||||
private outboundCounter = 0n
|
||||
|
||||
private constructor(
|
||||
readonly ready: MobileE2EEV2Ready,
|
||||
readonly transcriptHashB64: string,
|
||||
private readonly mobileToDesktopKey: Uint8Array,
|
||||
private readonly desktopToMobileKey: Uint8Array,
|
||||
private readonly sessionId: Uint8Array
|
||||
) {}
|
||||
|
||||
static create(args: {
|
||||
hello: unknown
|
||||
serverSecretKey: Uint8Array
|
||||
expectedContext: DesktopMobileE2EEV2Context
|
||||
randomBytes?: (length: number) => Uint8Array
|
||||
}): DesktopMobileE2EEV2Session | null {
|
||||
if (!hasExpectedContext(args.hello, args.expectedContext)) {
|
||||
return null
|
||||
}
|
||||
const hello = args.hello as MobileE2EEV2Hello
|
||||
const serverKeys = nacl.box.keyPair.fromSecretKey(args.serverSecretKey)
|
||||
const randomBytes = args.randomBytes ?? ((length: number) => nacl.randomBytes(length))
|
||||
const ready: MobileE2EEV2Ready = {
|
||||
type: 'e2ee_ready',
|
||||
v: 2,
|
||||
desktopPublicKeyB64: Buffer.from(serverKeys.publicKey).toString('base64'),
|
||||
clientNonceB64: hello.clientNonceB64,
|
||||
desktopNonceB64: Buffer.from(randomBytes(32)).toString('base64'),
|
||||
selection: { framing: 2, payloadKinds: ['text', 'binary'] },
|
||||
context: hello.context
|
||||
}
|
||||
const handshake = validateMobileE2EEV2Handshake(hello, ready)
|
||||
if (!handshake) {
|
||||
return null
|
||||
}
|
||||
const sharedSecret = deriveSharedKey(args.serverSecretKey, handshake.clientPublicKey)
|
||||
const schedule = deriveMobileE2EEV2KeySchedule({
|
||||
sharedSecret,
|
||||
transcript: encodeMobileE2EEV2Transcript(handshake),
|
||||
clientNonce: handshake.clientNonce,
|
||||
desktopNonce: handshake.desktopNonce
|
||||
})
|
||||
return new DesktopMobileE2EEV2Session(
|
||||
ready,
|
||||
Buffer.from(schedule.transcriptHash).toString('base64'),
|
||||
schedule.mobileToDesktopKey,
|
||||
schedule.desktopToMobileKey,
|
||||
schedule.sessionId
|
||||
)
|
||||
}
|
||||
|
||||
openText(frameB64: string): string | null {
|
||||
const frame = decodeCanonicalBase64(frameB64)
|
||||
if (!frame) {
|
||||
return null
|
||||
}
|
||||
const plaintext = this.open(frame, 'text')
|
||||
return plaintext ? new TextDecoder().decode(plaintext) : null
|
||||
}
|
||||
|
||||
openBinary(frame: Uint8Array): Uint8Array | null {
|
||||
return this.open(frame, 'binary')
|
||||
}
|
||||
|
||||
sealText(plaintext: string): string {
|
||||
return Buffer.from(this.seal(new TextEncoder().encode(plaintext), 'text')).toString('base64')
|
||||
}
|
||||
|
||||
sealBinary(plaintext: Uint8Array): Uint8Array {
|
||||
return this.seal(plaintext, 'binary')
|
||||
}
|
||||
|
||||
private open(frame: Uint8Array, payloadKind: 'text' | 'binary'): Uint8Array | null {
|
||||
const plaintext = openMobileE2EEV2Frame({
|
||||
frame,
|
||||
key: this.mobileToDesktopKey,
|
||||
sessionId: this.sessionId,
|
||||
direction: 'mobile-to-desktop',
|
||||
payloadKind,
|
||||
expectedCounter: this.inboundCounter
|
||||
})
|
||||
if (plaintext) {
|
||||
this.inboundCounter++
|
||||
}
|
||||
return plaintext
|
||||
}
|
||||
|
||||
private seal(plaintext: Uint8Array, payloadKind: 'text' | 'binary'): Uint8Array {
|
||||
const frame = sealMobileE2EEV2Frame({
|
||||
payload: plaintext,
|
||||
key: this.desktopToMobileKey,
|
||||
sessionId: this.sessionId,
|
||||
direction: 'desktop-to-mobile',
|
||||
payloadKind,
|
||||
counter: this.outboundCounter
|
||||
})
|
||||
this.outboundCounter++
|
||||
return frame
|
||||
}
|
||||
}
|
||||
|
||||
function hasExpectedContext(
|
||||
hello: unknown,
|
||||
expected: DesktopMobileE2EEV2Context
|
||||
): hello is MobileE2EEV2Hello {
|
||||
if (typeof hello !== 'object' || hello === null || !('context' in hello)) {
|
||||
return false
|
||||
}
|
||||
const context = (hello as { context?: unknown }).context
|
||||
if (typeof context !== 'object' || context === null) {
|
||||
return false
|
||||
}
|
||||
const candidate = context as { transport?: unknown; relayHostId?: unknown }
|
||||
return (
|
||||
candidate.transport === expected.transport && candidate.relayHostId === expected.relayHostId
|
||||
)
|
||||
}
|
||||
|
||||
function decodeCanonicalBase64(value: string): Uint8Array | null {
|
||||
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
|
||||
return null
|
||||
}
|
||||
const bytes = Buffer.from(value, 'base64')
|
||||
return bytes.toString('base64') === value ? bytes : null
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
encodeMobileE2EEV2Transcript,
|
||||
validateMobileE2EEV2Handshake
|
||||
} from '../../../shared/mobile-e2ee-v2-contract'
|
||||
import {
|
||||
createMobileE2EEV2Fixture,
|
||||
MOBILE_E2EE_V2_VECTOR
|
||||
} from '../../../shared/mobile-e2ee-v2-fixtures'
|
||||
import { deriveMobileE2EEV2KeySchedule } from './mobile-e2ee-v2-key-schedule'
|
||||
|
||||
describe('desktop mobile E2EE v2 key schedule', () => {
|
||||
it('derives the normative 96-byte HKDF vector', () => {
|
||||
const { hello, ready, sharedSecret } = createMobileE2EEV2Fixture()
|
||||
const handshake = validateMobileE2EEV2Handshake(hello, ready)!
|
||||
const schedule = deriveMobileE2EEV2KeySchedule({
|
||||
sharedSecret,
|
||||
transcript: encodeMobileE2EEV2Transcript(handshake),
|
||||
clientNonce: handshake.clientNonce,
|
||||
desktopNonce: handshake.desktopNonce
|
||||
})
|
||||
|
||||
expect(Buffer.from(schedule.mobileToDesktopKey).toString('hex')).toBe(
|
||||
MOBILE_E2EE_V2_VECTOR.mobileToDesktopKeyHex
|
||||
)
|
||||
expect(Buffer.from(schedule.desktopToMobileKey).toString('hex')).toBe(
|
||||
MOBILE_E2EE_V2_VECTOR.desktopToMobileKeyHex
|
||||
)
|
||||
expect(Buffer.from(schedule.sessionId).toString('hex')).toBe(MOBILE_E2EE_V2_VECTOR.sessionIdHex)
|
||||
expect(Buffer.from(schedule.transcriptHash).toString('hex')).toBe(
|
||||
MOBILE_E2EE_V2_VECTOR.transcriptHashHex
|
||||
)
|
||||
})
|
||||
|
||||
it('derives unique direction keys and session IDs across fresh desktop nonces', () => {
|
||||
const { hello, ready, sharedSecret } = createMobileE2EEV2Fixture()
|
||||
const fingerprints = new Set<string>()
|
||||
for (let index = 0; index < 128; index++) {
|
||||
const nonce = Buffer.alloc(32)
|
||||
nonce.writeUInt32BE(index, 28)
|
||||
const handshake = validateMobileE2EEV2Handshake(hello, {
|
||||
...ready,
|
||||
desktopNonceB64: nonce.toString('base64')
|
||||
})!
|
||||
const schedule = deriveMobileE2EEV2KeySchedule({
|
||||
sharedSecret,
|
||||
transcript: encodeMobileE2EEV2Transcript(handshake),
|
||||
clientNonce: handshake.clientNonce,
|
||||
desktopNonce: handshake.desktopNonce
|
||||
})
|
||||
fingerprints.add(
|
||||
[schedule.mobileToDesktopKey, schedule.desktopToMobileKey, schedule.sessionId]
|
||||
.map((bytes) => Buffer.from(bytes).toString('hex'))
|
||||
.join(':')
|
||||
)
|
||||
}
|
||||
expect(fingerprints.size).toBe(128)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createHash, hkdfSync } from 'node:crypto'
|
||||
|
||||
const SALT_LABEL = new TextEncoder().encode('orca-mobile-e2ee/v2/salt\0')
|
||||
const INFO_LABEL = new TextEncoder().encode('orca-mobile-e2ee/v2/session\0')
|
||||
|
||||
export type MobileE2EEV2KeySchedule = {
|
||||
mobileToDesktopKey: Uint8Array
|
||||
desktopToMobileKey: Uint8Array
|
||||
sessionId: Uint8Array
|
||||
transcriptHash: Uint8Array
|
||||
}
|
||||
|
||||
export function deriveMobileE2EEV2KeySchedule(args: {
|
||||
sharedSecret: Uint8Array
|
||||
transcript: Uint8Array
|
||||
clientNonce: Uint8Array
|
||||
desktopNonce: Uint8Array
|
||||
}): MobileE2EEV2KeySchedule {
|
||||
requireLength(args.sharedSecret, 32, 'shared secret')
|
||||
requireLength(args.clientNonce, 32, 'client nonce')
|
||||
requireLength(args.desktopNonce, 32, 'desktop nonce')
|
||||
|
||||
const transcriptHash = sha256(args.transcript)
|
||||
const salt = sha256(concatBytes([SALT_LABEL, args.clientNonce, args.desktopNonce]))
|
||||
const info = concatBytes([INFO_LABEL, transcriptHash])
|
||||
const expanded = new Uint8Array(hkdfSync('sha256', args.sharedSecret, salt, info, 96))
|
||||
return {
|
||||
mobileToDesktopKey: expanded.slice(0, 32),
|
||||
desktopToMobileKey: expanded.slice(32, 64),
|
||||
sessionId: expanded.slice(64, 96),
|
||||
transcriptHash
|
||||
}
|
||||
}
|
||||
|
||||
function sha256(bytes: Uint8Array): Uint8Array {
|
||||
return new Uint8Array(createHash('sha256').update(bytes).digest())
|
||||
}
|
||||
|
||||
function concatBytes(parts: readonly Uint8Array[]): Uint8Array {
|
||||
const result = new Uint8Array(parts.reduce((total, part) => total + part.length, 0))
|
||||
let offset = 0
|
||||
for (const part of parts) {
|
||||
result.set(part, offset)
|
||||
offset += part.length
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function requireLength(bytes: Uint8Array, expected: number, label: string): void {
|
||||
if (bytes.length !== expected) {
|
||||
throw new Error(`Invalid ${label}: expected ${expected} bytes, got ${bytes.length}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import nacl from 'tweetnacl'
|
||||
import type { WebSocket } from 'ws'
|
||||
import {
|
||||
encodeMobileE2EEV2Transcript,
|
||||
validateMobileE2EEV2Handshake,
|
||||
type MobileE2EEV2Hello,
|
||||
type MobileE2EEV2Ready
|
||||
} from '../../../shared/mobile-e2ee-v2-contract'
|
||||
import { sealMobileE2EEV2Frame } from '../../../shared/mobile-e2ee-v2-framing'
|
||||
import type { DeviceRegistry } from '../device-registry'
|
||||
import { deriveSharedKey, encrypt, generateKeyPair } from './e2ee-crypto'
|
||||
import { deriveMobileE2EEV2KeySchedule } from './mobile-e2ee-v2-key-schedule'
|
||||
import {
|
||||
MobileSocketWiring,
|
||||
type MobileSocketTransport,
|
||||
type MobileSocketTransportMetadata
|
||||
} from './mobile-socket-wiring'
|
||||
|
||||
class FakeSocket {
|
||||
readonly OPEN = 1
|
||||
readyState = this.OPEN
|
||||
bufferedAmount = 0
|
||||
readonly sent: (string | Buffer)[] = []
|
||||
readonly send = vi.fn((data: string | Buffer) => this.sent.push(data))
|
||||
readonly close = vi.fn()
|
||||
}
|
||||
|
||||
class FakeTransport implements MobileSocketTransport {
|
||||
private messageHandler: Parameters<MobileSocketTransport['onMessage']>[0] | null = null
|
||||
private closeHandler: Parameters<MobileSocketTransport['onConnectionClose']>[0] | null = null
|
||||
readonly setClientId = vi.fn()
|
||||
readonly terminateClientConnections = vi.fn(() => 0)
|
||||
|
||||
onMessage(handler: Parameters<MobileSocketTransport['onMessage']>[0]): void {
|
||||
this.messageHandler = handler
|
||||
}
|
||||
|
||||
onConnectionClose(handler: Parameters<MobileSocketTransport['onConnectionClose']>[0]): void {
|
||||
this.closeHandler = handler
|
||||
}
|
||||
|
||||
receive(ws: FakeSocket, message: string): void {
|
||||
this.messageHandler?.(message, vi.fn(), ws as unknown as WebSocket)
|
||||
}
|
||||
|
||||
disconnect(ws: FakeSocket): void {
|
||||
this.closeHandler?.(null, ws as unknown as WebSocket, false)
|
||||
}
|
||||
}
|
||||
|
||||
function registryFor(deviceId: string, token: string): DeviceRegistry {
|
||||
return {
|
||||
validateToken: (candidate: string) =>
|
||||
candidate === token
|
||||
? {
|
||||
deviceId,
|
||||
token,
|
||||
name: 'Phone',
|
||||
scope: 'mobile' as const,
|
||||
pairedAt: 1,
|
||||
lastSeenAt: 0
|
||||
}
|
||||
: null,
|
||||
updateLastSeen: vi.fn()
|
||||
} as unknown as DeviceRegistry
|
||||
}
|
||||
|
||||
describe('MobileSocketWiring', () => {
|
||||
it('terminates a revoked device across every attached transport', () => {
|
||||
const direct = new FakeTransport()
|
||||
const relay = new FakeTransport()
|
||||
direct.terminateClientConnections.mockReturnValue(1)
|
||||
relay.terminateClientConnections.mockReturnValue(2)
|
||||
const desktop = generateKeyPair()
|
||||
const wiring = new MobileSocketWiring({
|
||||
deviceRegistry: registryFor('device-1', 'valid-token'),
|
||||
e2eeKeypair: {
|
||||
publicKey: desktop.publicKey,
|
||||
secretKey: desktop.secretKey,
|
||||
publicKeyB64: Buffer.from(desktop.publicKey).toString('base64')
|
||||
},
|
||||
onText: vi.fn(),
|
||||
onBinary: vi.fn(),
|
||||
onClose: vi.fn()
|
||||
})
|
||||
wiring.attachTransport(direct)
|
||||
wiring.attachTransport(relay)
|
||||
|
||||
expect(wiring.terminateDeviceConnections('valid-token')).toBe(3)
|
||||
expect(direct.terminateClientConnections).toHaveBeenCalledWith('valid-token')
|
||||
expect(relay.terminateClientConnections).toHaveBeenCalledWith('valid-token')
|
||||
})
|
||||
|
||||
it('preserves the legacy direct handshake, identity, and close cleanup', () => {
|
||||
const desktop = generateKeyPair()
|
||||
const phone = generateKeyPair()
|
||||
const ws = new FakeSocket()
|
||||
const transport = new FakeTransport()
|
||||
const onText = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const wiring = new MobileSocketWiring({
|
||||
deviceRegistry: registryFor('device-1', 'valid-token'),
|
||||
e2eeKeypair: {
|
||||
publicKey: desktop.publicKey,
|
||||
secretKey: desktop.secretKey,
|
||||
publicKeyB64: Buffer.from(desktop.publicKey).toString('base64')
|
||||
},
|
||||
onText,
|
||||
onBinary: vi.fn(),
|
||||
onClose
|
||||
})
|
||||
wiring.attachTransport(transport)
|
||||
|
||||
transport.receive(
|
||||
ws,
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: Buffer.from(phone.publicKey).toString('base64')
|
||||
})
|
||||
)
|
||||
const sharedKey = deriveSharedKey(phone.secretKey, desktop.publicKey)
|
||||
transport.receive(
|
||||
ws,
|
||||
encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), sharedKey)
|
||||
)
|
||||
transport.receive(ws, encrypt('{"id":"rpc-1","method":"status.get"}', sharedKey))
|
||||
|
||||
expect(transport.setClientId).toHaveBeenCalledWith(ws, 'valid-token')
|
||||
expect(onText).toHaveBeenCalledOnce()
|
||||
expect(onText.mock.calls[0]?.[0]).toMatchObject({
|
||||
device: { deviceId: 'device-1', deviceToken: 'valid-token', scope: 'mobile' },
|
||||
transport: { transport: 'direct' }
|
||||
})
|
||||
|
||||
transport.disconnect(ws)
|
||||
expect(onClose).toHaveBeenCalledWith(expect.objectContaining({ ws }), false)
|
||||
expect(wiring.channelCount).toBe(0)
|
||||
expect(wiring.connectionCount).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a relay socket whose immutable relayDeviceId differs from E2EE identity', () => {
|
||||
const desktop = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1))
|
||||
const phone = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2))
|
||||
const ws = new FakeSocket()
|
||||
const transport = new FakeTransport()
|
||||
const metadata: MobileSocketTransportMetadata = {
|
||||
transport: 'relay',
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: 'outer-device',
|
||||
basisConnId: 'connection-1',
|
||||
credentialKind: 'invite'
|
||||
}
|
||||
const wiring = new MobileSocketWiring({
|
||||
deviceRegistry: registryFor('e2ee-device', 'valid-token'),
|
||||
e2eeKeypair: {
|
||||
publicKey: desktop.publicKey,
|
||||
secretKey: desktop.secretKey,
|
||||
publicKeyB64: Buffer.from(desktop.publicKey).toString('base64')
|
||||
},
|
||||
onText: vi.fn(),
|
||||
onBinary: vi.fn(),
|
||||
onClose: vi.fn()
|
||||
})
|
||||
wiring.attachTransport(transport, () => metadata)
|
||||
const hello: MobileE2EEV2Hello = {
|
||||
type: 'e2ee_hello',
|
||||
v: 2,
|
||||
clientPublicKeyB64: Buffer.from(phone.publicKey).toString('base64'),
|
||||
clientNonceB64: Buffer.from(new Uint8Array(32).fill(3)).toString('base64'),
|
||||
capabilities: { framing: [2], payloadKinds: ['text', 'binary'] },
|
||||
context: {
|
||||
protocol: 'orca-mobile-e2ee',
|
||||
initiator: 'mobile',
|
||||
responder: 'desktop',
|
||||
transport: 'relay',
|
||||
relayHostId: metadata.relayHostId
|
||||
}
|
||||
}
|
||||
transport.receive(ws, JSON.stringify(hello))
|
||||
const ready = JSON.parse(ws.sent[0]!.toString()) as MobileE2EEV2Ready
|
||||
const handshake = validateMobileE2EEV2Handshake(hello, ready)!
|
||||
const schedule = deriveMobileE2EEV2KeySchedule({
|
||||
sharedSecret: deriveSharedKey(phone.secretKey, desktop.publicKey),
|
||||
transcript: encodeMobileE2EEV2Transcript(handshake),
|
||||
clientNonce: handshake.clientNonce,
|
||||
desktopNonce: handshake.desktopNonce
|
||||
})
|
||||
const auth = sealMobileE2EEV2Frame({
|
||||
payload: new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_auth',
|
||||
v: 2,
|
||||
transcriptHashB64: Buffer.from(schedule.transcriptHash).toString('base64'),
|
||||
deviceToken: 'valid-token'
|
||||
})
|
||||
),
|
||||
key: schedule.mobileToDesktopKey,
|
||||
sessionId: schedule.sessionId,
|
||||
direction: 'mobile-to-desktop',
|
||||
payloadKind: 'text',
|
||||
counter: 0n
|
||||
})
|
||||
transport.receive(ws, Buffer.from(auth).toString('base64'))
|
||||
|
||||
expect(transport.setClientId).not.toHaveBeenCalled()
|
||||
expect(ws.close).toHaveBeenCalledWith(4001, 'Unauthorized')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import type { WebSocket } from 'ws'
|
||||
import type { DeviceEntry, DeviceRegistry } from '../device-registry'
|
||||
import type { E2EEKeypair } from '../e2ee-keypair'
|
||||
import { E2EEChannel, type E2EEAuthenticatedDevice } from './e2ee-channel'
|
||||
|
||||
type MobileSocketPayload = string | Uint8Array<ArrayBufferLike>
|
||||
|
||||
export type MobileSocketTransportMetadata =
|
||||
| { transport: 'direct' }
|
||||
| {
|
||||
transport: 'relay'
|
||||
relayHostId: string
|
||||
relayDeviceId: string
|
||||
basisConnId: string
|
||||
credentialKind: 'invite' | 'resume'
|
||||
}
|
||||
|
||||
export type MobileSocketTransport = {
|
||||
onMessage(
|
||||
handler: (
|
||||
message: MobileSocketPayload,
|
||||
reply: (response: string) => void,
|
||||
ws: WebSocket
|
||||
) => void
|
||||
): void
|
||||
onConnectionClose(
|
||||
handler: (clientId: string | null, ws: WebSocket, hasOtherConnections: boolean) => void
|
||||
): void
|
||||
setClientId(ws: WebSocket, clientId: string): void
|
||||
terminateClientConnections(clientId: string): number
|
||||
}
|
||||
|
||||
export type AuthenticatedMobileSocket = {
|
||||
ws: WebSocket
|
||||
connectionId: string
|
||||
device: E2EEAuthenticatedDevice
|
||||
transport: MobileSocketTransportMetadata
|
||||
}
|
||||
|
||||
type MobileSocketWiringOptions = {
|
||||
deviceRegistry: DeviceRegistry
|
||||
e2eeKeypair: E2EEKeypair
|
||||
onText: (
|
||||
socket: AuthenticatedMobileSocket,
|
||||
plaintext: string,
|
||||
reply: (response: string) => void,
|
||||
sendBinary: (response: Uint8Array<ArrayBufferLike>) => boolean | void
|
||||
) => void
|
||||
onBinary: (socket: AuthenticatedMobileSocket, bytes: Uint8Array<ArrayBufferLike>) => void
|
||||
onClose: (socket: AuthenticatedMobileSocket | null, hasOtherConnections: boolean) => void
|
||||
onReady?: (socket: AuthenticatedMobileSocket) => void
|
||||
}
|
||||
|
||||
function toAuthenticatedDevice(device: DeviceEntry): E2EEAuthenticatedDevice {
|
||||
return {
|
||||
deviceId: device.deviceId,
|
||||
deviceToken: device.token,
|
||||
scope: device.scope
|
||||
}
|
||||
}
|
||||
|
||||
export class MobileSocketWiring {
|
||||
private readonly deviceRegistry: DeviceRegistry
|
||||
private readonly e2eeKeypair: E2EEKeypair
|
||||
private readonly onText: MobileSocketWiringOptions['onText']
|
||||
private readonly onBinary: MobileSocketWiringOptions['onBinary']
|
||||
private readonly onClose: MobileSocketWiringOptions['onClose']
|
||||
private readonly onReady: MobileSocketWiringOptions['onReady']
|
||||
private readonly channels = new Map<WebSocket, E2EEChannel>()
|
||||
private readonly connectionIds = new Map<WebSocket, string>()
|
||||
private readonly authenticatedSockets = new Map<WebSocket, AuthenticatedMobileSocket>()
|
||||
private readonly transports = new Set<MobileSocketTransport>()
|
||||
|
||||
constructor(options: MobileSocketWiringOptions) {
|
||||
this.deviceRegistry = options.deviceRegistry
|
||||
this.e2eeKeypair = options.e2eeKeypair
|
||||
this.onText = options.onText
|
||||
this.onBinary = options.onBinary
|
||||
this.onClose = options.onClose
|
||||
this.onReady = options.onReady
|
||||
}
|
||||
|
||||
attachTransport(
|
||||
transport: MobileSocketTransport,
|
||||
getMetadata: (ws: WebSocket) => MobileSocketTransportMetadata = () => ({
|
||||
transport: 'direct'
|
||||
})
|
||||
): void {
|
||||
this.transports.add(transport)
|
||||
transport.onMessage((message, _reply, ws) => {
|
||||
this.handleRawMessage(transport, ws, message, getMetadata(ws))
|
||||
})
|
||||
transport.onConnectionClose((_clientId, ws) => this.handleClose(ws))
|
||||
}
|
||||
|
||||
getConnectionId(ws: WebSocket): string | undefined {
|
||||
return this.connectionIds.get(ws)
|
||||
}
|
||||
|
||||
get channelCount(): number {
|
||||
return this.channels.size
|
||||
}
|
||||
|
||||
get connectionCount(): number {
|
||||
return this.connectionIds.size
|
||||
}
|
||||
|
||||
terminateDeviceConnections(deviceToken: string): number {
|
||||
let terminated = 0
|
||||
for (const transport of this.transports) {
|
||||
terminated += transport.terminateClientConnections(deviceToken)
|
||||
}
|
||||
return terminated
|
||||
}
|
||||
|
||||
private handleRawMessage(
|
||||
transport: MobileSocketTransport,
|
||||
ws: WebSocket,
|
||||
message: MobileSocketPayload,
|
||||
metadata: MobileSocketTransportMetadata
|
||||
): void {
|
||||
let channel = this.channels.get(ws)
|
||||
if (!channel) {
|
||||
const connectionId = randomBytes(8).toString('hex')
|
||||
this.connectionIds.set(ws, connectionId)
|
||||
channel = new E2EEChannel(ws, {
|
||||
serverSecretKey: this.e2eeKeypair.secretKey,
|
||||
transportContext:
|
||||
metadata.transport === 'relay'
|
||||
? { transport: 'relay', relayHostId: metadata.relayHostId }
|
||||
: { transport: 'direct' },
|
||||
requireV2: metadata.transport === 'relay',
|
||||
resolveAuthenticatedDevice: (token) => {
|
||||
const device = this.deviceRegistry.validateToken(token)
|
||||
if (!device) {
|
||||
return null
|
||||
}
|
||||
// Why: outer relay authorization cannot choose the local Orca
|
||||
// identity; E2EE must resolve the same device before readiness.
|
||||
if (metadata.transport === 'relay' && metadata.relayDeviceId !== device.deviceId) {
|
||||
return null
|
||||
}
|
||||
return toAuthenticatedDevice(device)
|
||||
},
|
||||
onReady: (_channel, device) => {
|
||||
const socket = { ws, connectionId, device, transport: metadata }
|
||||
this.authenticatedSockets.set(ws, socket)
|
||||
transport.setClientId(ws, device.deviceToken)
|
||||
this.deviceRegistry.updateLastSeen(device.deviceId)
|
||||
this.onReady?.(socket)
|
||||
},
|
||||
onError: (code, reason) => {
|
||||
this.channels.get(ws)?.destroy()
|
||||
this.channels.delete(ws)
|
||||
ws.close(code, reason)
|
||||
}
|
||||
})
|
||||
channel.onMessage((plaintext, reply, sendBinary) => {
|
||||
const socket = this.authenticatedSockets.get(ws)
|
||||
if (socket) {
|
||||
this.onText(socket, plaintext, reply, sendBinary)
|
||||
}
|
||||
})
|
||||
channel.onBinaryMessage((bytes) => {
|
||||
const socket = this.authenticatedSockets.get(ws)
|
||||
if (socket) {
|
||||
this.onBinary(socket, bytes)
|
||||
}
|
||||
})
|
||||
this.channels.set(ws, channel)
|
||||
}
|
||||
channel.handleRawMessage(message)
|
||||
}
|
||||
|
||||
private handleClose(ws: WebSocket): void {
|
||||
const socket = this.authenticatedSockets.get(ws) ?? null
|
||||
this.authenticatedSockets.delete(ws)
|
||||
this.channels.get(ws)?.destroy()
|
||||
this.channels.delete(ws)
|
||||
this.connectionIds.delete(ws)
|
||||
const hasOtherConnections =
|
||||
socket !== null &&
|
||||
Array.from(this.authenticatedSockets.values()).some(
|
||||
(candidate) => candidate.device.deviceToken === socket.device.deviceToken
|
||||
)
|
||||
this.onClose(socket, hasOtherConnections)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import WebSocketClient, { WebSocketServer, type WebSocket } from 'ws'
|
||||
import { CloudRelayTransport } from './relay-transport'
|
||||
|
||||
function nextMessage(ws: WebSocket): Promise<{ data: Buffer; isBinary: boolean }> {
|
||||
return new Promise((resolve) => {
|
||||
ws.once('message', (data, isBinary) => resolve({ data: Buffer.from(data as Buffer), isBinary }))
|
||||
})
|
||||
}
|
||||
|
||||
describe('CloudRelayTransport', () => {
|
||||
const servers: WebSocketServer[] = []
|
||||
const transports: CloudRelayTransport[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(transports.splice(0).map((transport) => transport.stop()))
|
||||
await Promise.all(
|
||||
servers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
for (const client of server.clients) {
|
||||
client.terminate()
|
||||
}
|
||||
server.close(() => resolve())
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('authenticates one query-free host-data socket and forwards messages verbatim', async () => {
|
||||
const server = new WebSocketServer({ port: 0, perMessageDeflate: false })
|
||||
servers.push(server)
|
||||
await new Promise<void>((resolve) => server.once('listening', resolve))
|
||||
const address = server.address()
|
||||
if (typeof address === 'string' || address === null) {
|
||||
throw new Error('expected TCP relay test server')
|
||||
}
|
||||
const accepted = new Promise<{ socket: WebSocket; path: string }>((resolve) => {
|
||||
server.once('connection', (socket, request) => resolve({ socket, path: request.url ?? '' }))
|
||||
})
|
||||
let clientSocket: WebSocketClient | null = null
|
||||
const onConnectionClosed = vi.fn()
|
||||
const transport = new CloudRelayTransport({
|
||||
cellUrl: `http://127.0.0.1:${address.port}`,
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
generation: 7,
|
||||
createSocket: (url) => {
|
||||
clientSocket = new WebSocketClient(url, { perMessageDeflate: false })
|
||||
return clientSocket
|
||||
},
|
||||
onConnectionClosed
|
||||
})
|
||||
transports.push(transport)
|
||||
const received: (string | Uint8Array<ArrayBufferLike>)[] = []
|
||||
transport.onMessage((message) => received.push(message))
|
||||
transport.onConnectionClose(vi.fn())
|
||||
await transport.start()
|
||||
const opening = transport.openConnection({
|
||||
connId: 'conn/with spaces',
|
||||
connTicket: 'ticket-1',
|
||||
kind: 'resume',
|
||||
relayDeviceId: 'device-1',
|
||||
attachDeadlineMs: 1_000
|
||||
})
|
||||
const { socket, path } = await accepted
|
||||
const auth = await nextMessage(socket)
|
||||
await opening
|
||||
|
||||
expect(path).toBe('/v1/host/data/conn%2Fwith%20spaces')
|
||||
expect(auth.isBinary).toBe(false)
|
||||
expect(JSON.parse(auth.data.toString())).toEqual({
|
||||
type: 'host-data-auth',
|
||||
v: 1,
|
||||
connTicket: 'ticket-1',
|
||||
generation: 7
|
||||
})
|
||||
socket.send('e2ee-hello')
|
||||
socket.send(Buffer.from([1, 2, 3]), { binary: true })
|
||||
await vi.waitFor(() => expect(received).toHaveLength(2))
|
||||
expect(received[0]).toBe('e2ee-hello')
|
||||
expect(received[1]).toEqual(new Uint8Array([1, 2, 3]))
|
||||
|
||||
expect(clientSocket).not.toBeNull()
|
||||
const metadata = transport.metadataFor(clientSocket!)
|
||||
expect(metadata).toEqual({
|
||||
transport: 'relay',
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: 'device-1',
|
||||
basisConnId: 'conn/with spaces',
|
||||
credentialKind: 'resume'
|
||||
})
|
||||
socket.close()
|
||||
await vi.waitFor(() => expect(onConnectionClosed).toHaveBeenCalledWith('conn/with spaces'))
|
||||
})
|
||||
|
||||
it('rejects non-origin cell URLs before opening a socket', () => {
|
||||
expect(
|
||||
() =>
|
||||
new CloudRelayTransport({
|
||||
cellUrl: 'https://relay.example/path?credential=forbidden',
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
generation: 1
|
||||
})
|
||||
).toThrow('relay_cell_url_must_be_an_origin')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,217 @@
|
||||
import WebSocket from 'ws'
|
||||
import type { RpcTransport } from './transport'
|
||||
import type { MobileSocketTransport, MobileSocketTransportMetadata } from './mobile-socket-wiring'
|
||||
|
||||
const MAX_RELAY_MESSAGE_BYTES = 1024 * 1024
|
||||
|
||||
type RelayMessagePayload = string | Uint8Array<ArrayBufferLike>
|
||||
|
||||
export type RelayConnectionOpen = {
|
||||
connId: string
|
||||
connTicket: string
|
||||
kind: 'invite' | 'resume'
|
||||
relayDeviceId: string
|
||||
attachDeadlineMs: number
|
||||
}
|
||||
|
||||
type CloudRelayTransportOptions = {
|
||||
cellUrl: string
|
||||
relayHostId: string
|
||||
generation: number
|
||||
createSocket?: (url: string) => WebSocket
|
||||
onConnectionClosed?: (connectionId: string) => void
|
||||
}
|
||||
|
||||
function relayWebSocketOrigin(cellUrl: string): string {
|
||||
const url = new URL(cellUrl)
|
||||
if (url.pathname !== '/' || url.search || url.hash) {
|
||||
throw new Error('relay_cell_url_must_be_an_origin')
|
||||
}
|
||||
if (url.protocol === 'https:') {
|
||||
url.protocol = 'wss:'
|
||||
} else if (url.protocol === 'http:') {
|
||||
url.protocol = 'ws:'
|
||||
} else {
|
||||
throw new Error('relay_cell_url_must_use_http')
|
||||
}
|
||||
return url.origin
|
||||
}
|
||||
|
||||
export class CloudRelayTransport implements RpcTransport, MobileSocketTransport {
|
||||
private readonly cellWebSocketOrigin: string
|
||||
private readonly relayHostId: string
|
||||
private generation: number
|
||||
private readonly createSocket: (url: string) => WebSocket
|
||||
private readonly onConnectionClosed: ((connectionId: string) => void) | undefined
|
||||
private readonly socketsByConnectionId = new Map<string, WebSocket>()
|
||||
private readonly metadataBySocket = new Map<WebSocket, MobileSocketTransportMetadata>()
|
||||
private readonly clientIds = new Map<WebSocket, string>()
|
||||
private messageHandler: Parameters<MobileSocketTransport['onMessage']>[0] | null = null
|
||||
private closeHandler: Parameters<MobileSocketTransport['onConnectionClose']>[0] | null = null
|
||||
private stopped = false
|
||||
|
||||
constructor(options: CloudRelayTransportOptions) {
|
||||
this.cellWebSocketOrigin = relayWebSocketOrigin(options.cellUrl)
|
||||
this.relayHostId = options.relayHostId
|
||||
this.generation = options.generation
|
||||
this.onConnectionClosed = options.onConnectionClosed
|
||||
this.createSocket =
|
||||
options.createSocket ??
|
||||
((url) =>
|
||||
new WebSocket(url, { perMessageDeflate: false, maxPayload: MAX_RELAY_MESSAGE_BYTES }))
|
||||
}
|
||||
|
||||
onMessage(handler: Parameters<MobileSocketTransport['onMessage']>[0]): void {
|
||||
this.messageHandler = handler
|
||||
}
|
||||
|
||||
onConnectionClose(handler: Parameters<MobileSocketTransport['onConnectionClose']>[0]): void {
|
||||
this.closeHandler = handler
|
||||
}
|
||||
|
||||
metadataFor(ws: WebSocket): MobileSocketTransportMetadata {
|
||||
const metadata = this.metadataBySocket.get(ws)
|
||||
if (!metadata) {
|
||||
throw new Error('unknown_relay_socket')
|
||||
}
|
||||
return metadata
|
||||
}
|
||||
|
||||
setClientId(ws: WebSocket, clientId: string): void {
|
||||
if (this.metadataBySocket.has(ws)) {
|
||||
this.clientIds.set(ws, clientId)
|
||||
}
|
||||
}
|
||||
|
||||
setGeneration(generation: number): void {
|
||||
if (generation === this.generation) {
|
||||
return
|
||||
}
|
||||
if (
|
||||
this.socketsByConnectionId.size > 0 ||
|
||||
!Number.isSafeInteger(generation) ||
|
||||
generation <= 0
|
||||
) {
|
||||
throw new Error('invalid_relay_generation_transition')
|
||||
}
|
||||
this.generation = generation
|
||||
}
|
||||
|
||||
terminateClientConnections(clientId: string): number {
|
||||
const sockets = Array.from(this.clientIds.entries())
|
||||
.filter(([, candidate]) => candidate === clientId)
|
||||
.map(([socket]) => socket)
|
||||
for (const socket of sockets) {
|
||||
socket.terminate()
|
||||
}
|
||||
return sockets.length
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.stopped = false
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stopped = true
|
||||
const sockets = [...this.metadataBySocket.keys()]
|
||||
for (const socket of sockets) {
|
||||
socket.terminate()
|
||||
}
|
||||
await Promise.all(sockets.map((socket) => this.waitForClose(socket)))
|
||||
}
|
||||
|
||||
async openConnection(connection: RelayConnectionOpen): Promise<void> {
|
||||
if (this.stopped) {
|
||||
throw new Error('relay_transport_stopped')
|
||||
}
|
||||
if (this.socketsByConnectionId.has(connection.connId)) {
|
||||
return
|
||||
}
|
||||
const url = `${this.cellWebSocketOrigin}/v1/host/data/${encodeURIComponent(connection.connId)}`
|
||||
const socket = this.createSocket(url)
|
||||
const metadata: MobileSocketTransportMetadata = {
|
||||
transport: 'relay',
|
||||
relayHostId: this.relayHostId,
|
||||
relayDeviceId: connection.relayDeviceId,
|
||||
basisConnId: connection.connId,
|
||||
credentialKind: connection.kind
|
||||
}
|
||||
this.socketsByConnectionId.set(connection.connId, socket)
|
||||
this.metadataBySocket.set(socket, metadata)
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let opened = false
|
||||
let attached = false
|
||||
let finalized = false
|
||||
const deadline = setTimeout(() => {
|
||||
socket.terminate()
|
||||
if (!opened) {
|
||||
reject(new Error('relay_host_data_attach_timeout'))
|
||||
}
|
||||
}, connection.attachDeadlineMs)
|
||||
const finalize = (): void => {
|
||||
if (finalized) {
|
||||
return
|
||||
}
|
||||
finalized = true
|
||||
clearTimeout(deadline)
|
||||
this.socketsByConnectionId.delete(connection.connId)
|
||||
this.metadataBySocket.delete(socket)
|
||||
const clientId = this.clientIds.get(socket) ?? null
|
||||
this.clientIds.delete(socket)
|
||||
this.onConnectionClosed?.(connection.connId)
|
||||
const hasOtherConnections =
|
||||
clientId !== null && [...this.clientIds.values()].includes(clientId)
|
||||
this.closeHandler?.(clientId, socket, hasOtherConnections)
|
||||
}
|
||||
socket.on('message', (raw, isBinary) => {
|
||||
if (!attached) {
|
||||
attached = true
|
||||
clearTimeout(deadline)
|
||||
}
|
||||
const message: RelayMessagePayload = isBinary
|
||||
? new Uint8Array(raw as Buffer)
|
||||
: raw.toString()
|
||||
this.messageHandler?.(
|
||||
message,
|
||||
(response) => {
|
||||
if (socket.readyState === socket.OPEN) {
|
||||
socket.send(response)
|
||||
}
|
||||
},
|
||||
socket
|
||||
)
|
||||
})
|
||||
socket.once('open', () => {
|
||||
opened = true
|
||||
const networkSocket = (
|
||||
socket as unknown as { _socket?: { setNoDelay(value: boolean): void } }
|
||||
)._socket
|
||||
networkSocket?.setNoDelay(true)
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'host-data-auth',
|
||||
v: 1,
|
||||
connTicket: connection.connTicket,
|
||||
generation: this.generation
|
||||
})
|
||||
)
|
||||
resolve()
|
||||
})
|
||||
socket.once('error', (error) => {
|
||||
if (!opened) {
|
||||
finalize()
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
socket.once('close', finalize)
|
||||
})
|
||||
}
|
||||
|
||||
private waitForClose(socket: WebSocket): Promise<void> {
|
||||
if (socket.readyState === socket.CLOSED) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
return new Promise((resolve) => socket.once('close', resolve))
|
||||
}
|
||||
}
|
||||
@@ -501,6 +501,348 @@ describe('OrcaRuntimeRpcServer', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('adds only the exact optional relay object to GUI mobile pairing offers', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
const relay = {
|
||||
v: 1 as const,
|
||||
directorUrl: 'https://relay.example.com',
|
||||
cellUrl: 'https://cell.example.com',
|
||||
assignmentEpoch: 7,
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
inviteToken: 'A'.repeat(43),
|
||||
inviteExpiresAt: Date.now() + 60_000,
|
||||
e2eeFraming: 2 as const
|
||||
}
|
||||
server.setMobileRelayPairingProvider({
|
||||
createPairingRelay: async (relayDeviceId) => ({
|
||||
relay,
|
||||
binding: {
|
||||
relayHostId: relay.relayHostId,
|
||||
relayDeviceId,
|
||||
ownerIdentityKey: 'user\0profile\0org'
|
||||
}
|
||||
}),
|
||||
onDeviceRevokeQueued: vi.fn(),
|
||||
getEndpoints: vi.fn(),
|
||||
provisionRelay: vi.fn()
|
||||
})
|
||||
|
||||
await server.start()
|
||||
try {
|
||||
const offer = await server.createMobilePairingOffer({
|
||||
address: '100.64.1.20',
|
||||
name: 'Mobile test'
|
||||
})
|
||||
expect(offer.available).toBe(true)
|
||||
if (!offer.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
const parsed = parsePairingCode(offer.pairingUrl)
|
||||
expect(parsed).toEqual(
|
||||
expect.objectContaining({ endpoint: offer.endpoint, scope: 'mobile', relay })
|
||||
)
|
||||
expect(parsed).not.toHaveProperty('endpoints')
|
||||
expect(server.getDeviceRegistry()?.getDevice(offer.deviceId)?.relayBinding).toEqual({
|
||||
relayHostId: relay.relayHostId,
|
||||
relayDeviceId: offer.deviceId,
|
||||
ownerIdentityKey: 'user\0profile\0org'
|
||||
})
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('falls back to a valid direct-only GUI offer when relay invite minting fails', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
server.setMobileRelayPairingProvider({
|
||||
createPairingRelay: vi.fn().mockRejectedValue(new Error('relay offline')),
|
||||
onDeviceRevokeQueued: vi.fn(),
|
||||
getEndpoints: vi.fn(),
|
||||
provisionRelay: vi.fn()
|
||||
})
|
||||
|
||||
await server.start()
|
||||
try {
|
||||
const offer = await server.createMobilePairingOffer({ address: '100.64.1.20' })
|
||||
expect(offer.available).toBe(true)
|
||||
if (!offer.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
expect(parsePairingCode(offer.pairingUrl)).toMatchObject({
|
||||
endpoint: offer.endpoint,
|
||||
scope: 'mobile'
|
||||
})
|
||||
expect(parsePairingCode(offer.pairingUrl)).not.toHaveProperty('relay')
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('persists local-only pairing and never mints or later binds Relay', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
const createPairingRelay = vi.fn()
|
||||
server.setMobileRelayPairingProvider({
|
||||
createPairingRelay,
|
||||
onDeviceRevokeQueued: vi.fn(),
|
||||
getEndpoints: vi.fn(),
|
||||
provisionRelay: vi.fn()
|
||||
})
|
||||
|
||||
await server.start()
|
||||
try {
|
||||
const offer = await server.createMobilePairingOffer({
|
||||
address: '100.64.1.20',
|
||||
connectionMode: 'local-only'
|
||||
})
|
||||
expect(offer.available).toBe(true)
|
||||
if (!offer.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
expect(parsePairingCode(offer.pairingUrl)).not.toHaveProperty('relay')
|
||||
expect(createPairingRelay).not.toHaveBeenCalled()
|
||||
expect(server.getDeviceRegistry()?.getMobilePairingConnectionMode(offer.deviceId)).toBe(
|
||||
'local-only'
|
||||
)
|
||||
expect(
|
||||
server.setMobileRelayBinding(offer.deviceId, {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId: offer.deviceId,
|
||||
ownerIdentityKey: 'user\0profile\0org'
|
||||
})
|
||||
).toBe(false)
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('normalizes untrusted pairing modes to automatic at the runtime boundary', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
|
||||
await server.start()
|
||||
try {
|
||||
const offer = await server.createMobilePairingOffer({
|
||||
connectionMode: 'renderer-controlled-value' as never
|
||||
})
|
||||
expect(offer.available).toBe(true)
|
||||
if (!offer.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
expect(server.getDeviceRegistry()?.getMobilePairingConnectionMode(offer.deviceId)).toBe(
|
||||
'automatic'
|
||||
)
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('revokes and rotates a pending Relay code when switching it to local-only', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
const onDeviceRevokeQueued = vi.fn()
|
||||
server.setMobileRelayPairingProvider({
|
||||
createPairingRelay: async (relayDeviceId) => ({
|
||||
relay: {
|
||||
v: 1,
|
||||
directorUrl: 'https://relay.example.com',
|
||||
cellUrl: 'https://cell.example.com',
|
||||
assignmentEpoch: 7,
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
inviteToken: 'A'.repeat(43),
|
||||
inviteExpiresAt: Date.now() + 60_000,
|
||||
e2eeFraming: 2
|
||||
},
|
||||
binding: {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId,
|
||||
ownerIdentityKey: 'user\0profile\0org'
|
||||
}
|
||||
}),
|
||||
onDeviceRevokeQueued,
|
||||
getEndpoints: vi.fn(),
|
||||
provisionRelay: vi.fn()
|
||||
})
|
||||
|
||||
await server.start()
|
||||
try {
|
||||
const anywhere = await server.createMobilePairingOffer({ address: '100.64.1.20' })
|
||||
expect(anywhere.available).toBe(true)
|
||||
if (!anywhere.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
const local = await server.createMobilePairingOffer({
|
||||
address: '100.64.1.20',
|
||||
connectionMode: 'local-only'
|
||||
})
|
||||
expect(local.available).toBe(true)
|
||||
if (!local.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
expect(local.deviceId).not.toBe(anywhere.deviceId)
|
||||
expect(server.getDeviceRegistry()?.getDevice(anywhere.deviceId)).toBeNull()
|
||||
expect(onDeviceRevokeQueued).toHaveBeenCalledOnce()
|
||||
expect(parsePairingCode(local.pairingUrl)).not.toHaveProperty('relay')
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('records cloud cleanup before rotating or deleting the local mobile credential', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
const registryPresence: boolean[] = []
|
||||
server.setMobileRelayPairingProvider({
|
||||
createPairingRelay: async (relayDeviceId) => ({
|
||||
relay: {
|
||||
v: 1,
|
||||
directorUrl: 'https://relay.example.com',
|
||||
cellUrl: 'https://cell.example.com',
|
||||
assignmentEpoch: 7,
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
inviteToken: 'A'.repeat(43),
|
||||
inviteExpiresAt: Date.now() + 60_000,
|
||||
e2eeFraming: 2
|
||||
},
|
||||
binding: {
|
||||
relayHostId: 'AbCdEf0123_-xyZ9',
|
||||
relayDeviceId,
|
||||
ownerIdentityKey: 'user\0profile\0org'
|
||||
}
|
||||
}),
|
||||
onDeviceRevokeQueued: (item) => {
|
||||
registryPresence.push(server.getDeviceRegistry()?.getDevice(item.relayDeviceId) !== null)
|
||||
},
|
||||
getEndpoints: vi.fn(),
|
||||
provisionRelay: vi.fn()
|
||||
})
|
||||
|
||||
await server.start()
|
||||
try {
|
||||
const first = await server.createMobilePairingOffer({ address: '100.64.1.20' })
|
||||
expect(first.available).toBe(true)
|
||||
if (!first.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
const second = await server.createMobilePairingOffer({
|
||||
address: '100.64.1.20',
|
||||
rotate: true
|
||||
})
|
||||
expect(second.available).toBe(true)
|
||||
if (!second.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
expect(server.getDeviceRegistry()?.getDevice(first.deviceId)).toBeNull()
|
||||
await expect(server.revokeMobileDevice(second.deviceId)).resolves.toBe(true)
|
||||
expect(server.getDeviceRegistry()?.getDevice(second.deviceId)).toBeNull()
|
||||
expect(registryPresence).toEqual([true, true])
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('binds pairing RPC providers to the immutable authenticated socket context', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime: new OrcaRuntimeService(),
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
const getEndpoints = vi.fn().mockResolvedValue({ v: 1, relay: null })
|
||||
const provisionRelay = vi.fn().mockResolvedValue({
|
||||
v: 1,
|
||||
reqId: 'install-1',
|
||||
authorizationMode: 'authenticated-direct',
|
||||
currentVersion: 1,
|
||||
resumeExpiresAt: Date.now() + 60_000
|
||||
})
|
||||
server.setMobileRelayPairingProvider({
|
||||
createPairingRelay: vi.fn(),
|
||||
onDeviceRevokeQueued: vi.fn(),
|
||||
getEndpoints,
|
||||
provisionRelay
|
||||
})
|
||||
|
||||
await server.start()
|
||||
try {
|
||||
const offer = server.createPairingOffer({
|
||||
address: '127.0.0.1',
|
||||
scope: 'mobile'
|
||||
})
|
||||
expect(offer.available).toBe(true)
|
||||
if (!offer.available) {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
const session = await authenticateMobileWsSession(offer.pairingUrl)
|
||||
const responses = createEncryptedWsResponseReader(session)
|
||||
sendEncryptedWsRequest(session, {
|
||||
id: 'endpoints-1',
|
||||
method: 'pairing.getEndpoints',
|
||||
params: { installReqId: 'status-1' }
|
||||
})
|
||||
await expect(responses.next('endpoints-1')).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { v: 1, relay: null }
|
||||
})
|
||||
sendEncryptedWsRequest(session, {
|
||||
id: 'provision-1',
|
||||
method: 'pairing.provisionRelay',
|
||||
params: { reqId: 'install-1', newResumeTokenHash: 'A'.repeat(43) }
|
||||
})
|
||||
await expect(responses.next('provision-1')).resolves.toMatchObject({ ok: true })
|
||||
|
||||
const [endpointContext, endpointParams] = getEndpoints.mock.calls[0]!
|
||||
expect(endpointContext).toEqual({
|
||||
deviceId: offer.deviceId,
|
||||
connectionId: expect.any(String),
|
||||
transport: { transport: 'direct' }
|
||||
})
|
||||
expect(endpointParams).toEqual({ installReqId: 'status-1' })
|
||||
expect(provisionRelay).toHaveBeenCalledWith(endpointContext, {
|
||||
reqId: 'install-1',
|
||||
newResumeTokenHash: 'A'.repeat(43)
|
||||
})
|
||||
responses.dispose()
|
||||
session.ws.close()
|
||||
await waitForWsClose(session.ws)
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('cleans up pre-auth E2EE WebSocket state when the socket closes', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-'))
|
||||
const runtime = new OrcaRuntimeService()
|
||||
@@ -533,12 +875,16 @@ describe('OrcaRuntimeRpcServer', () => {
|
||||
})
|
||||
)
|
||||
expect(JSON.parse(await nextWsMessage(ws))).toEqual({ type: 'e2ee_ready' })
|
||||
expect(server['e2eeChannels'].size).toBe(1)
|
||||
expect(server['wsConnectionIds'].size).toBe(1)
|
||||
expect(server['mobileSocketWiring']?.channelCount).toBe(1)
|
||||
expect(server['mobileSocketWiring']?.connectionCount).toBe(1)
|
||||
|
||||
ws.close()
|
||||
await waitForWsClose(ws)
|
||||
await waitFor(() => server['e2eeChannels'].size === 0 && server['wsConnectionIds'].size === 0)
|
||||
await waitFor(
|
||||
() =>
|
||||
server['mobileSocketWiring']?.channelCount === 0 &&
|
||||
server['mobileSocketWiring']?.connectionCount === 0
|
||||
)
|
||||
} finally {
|
||||
await server.stop()
|
||||
}
|
||||
@@ -570,9 +916,13 @@ describe('OrcaRuntimeRpcServer', () => {
|
||||
const first = await authenticateMobileWs(offer.pairingUrl)
|
||||
const second = await authenticateMobileWs(offer.pairingUrl)
|
||||
|
||||
expect(server.revokeMobileDevice(offer.deviceId)).toBe(true)
|
||||
await expect(server.revokeMobileDevice(offer.deviceId)).resolves.toBe(true)
|
||||
await Promise.all([waitForWsClose(first), waitForWsClose(second)])
|
||||
await waitFor(() => server['e2eeChannels'].size === 0 && server['wsConnectionIds'].size === 0)
|
||||
await waitFor(
|
||||
() =>
|
||||
server['mobileSocketWiring']?.channelCount === 0 &&
|
||||
server['mobileSocketWiring']?.connectionCount === 0
|
||||
)
|
||||
|
||||
expect(disconnectSpy).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
@@ -604,7 +954,7 @@ describe('OrcaRuntimeRpcServer', () => {
|
||||
throw new Error('WebSocket pairing unavailable')
|
||||
}
|
||||
|
||||
expect(server.revokeMobileDevice(offer.deviceId)).toBe(false)
|
||||
await expect(server.revokeMobileDevice(offer.deviceId)).resolves.toBe(false)
|
||||
expect(server.getDeviceRegistry()?.getDevice(offer.deviceId)?.scope).toBe('runtime')
|
||||
} finally {
|
||||
await server.stop()
|
||||
@@ -638,7 +988,11 @@ describe('OrcaRuntimeRpcServer', () => {
|
||||
|
||||
expect(server.revokeRuntimeAccess(offer.deviceId)).toBe(true)
|
||||
await Promise.all([waitForWsClose(first), waitForWsClose(second)])
|
||||
await waitFor(() => server['e2eeChannels'].size === 0 && server['wsConnectionIds'].size === 0)
|
||||
await waitFor(
|
||||
() =>
|
||||
server['mobileSocketWiring']?.channelCount === 0 &&
|
||||
server['mobileSocketWiring']?.connectionCount === 0
|
||||
)
|
||||
|
||||
expect(server.getDeviceRegistry()?.getDevice(offer.deviceId)).toBeNull()
|
||||
} finally {
|
||||
@@ -718,7 +1072,9 @@ describe('OrcaRuntimeRpcServer', () => {
|
||||
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
||||
const entry = server['deviceRegistry']!.addDevice('runtime-test', 'runtime')
|
||||
const ws = new FakeWebSocket()
|
||||
server['wsConnectionIds'].set(ws as unknown as WebSocket, 'conn-test')
|
||||
server['mobileSocketWiring'] = {
|
||||
getConnectionId: () => 'conn-test'
|
||||
} as unknown as NonNullable<(typeof server)['mobileSocketWiring']>
|
||||
const replies: Record<string, unknown>[] = []
|
||||
|
||||
try {
|
||||
@@ -778,7 +1134,9 @@ describe('OrcaRuntimeRpcServer', () => {
|
||||
server['deviceRegistry'] = new DeviceRegistry(userDataPath)
|
||||
const entry = server['deviceRegistry']!.addDevice('runtime-test', 'runtime')
|
||||
const ws = new FakeWebSocket()
|
||||
server['wsConnectionIds'].set(ws as unknown as WebSocket, 'conn-test')
|
||||
server['mobileSocketWiring'] = {
|
||||
getConnectionId: () => 'conn-test'
|
||||
} as unknown as NonNullable<(typeof server)['mobileSocketWiring']>
|
||||
let activeDispatches = 0
|
||||
;(
|
||||
server as unknown as {
|
||||
|
||||
+221
-96
@@ -20,7 +20,24 @@ import { readWsFallbackPort, writeWsFallbackPort } from './rpc/ws-fallback-port-
|
||||
import type { WebSocket } from 'ws'
|
||||
import { DeviceRegistry, type DeviceScope } from './device-registry'
|
||||
import { loadOrCreateE2EEKeypair, type E2EEKeypair } from './e2ee-keypair'
|
||||
import { E2EEChannel } from './rpc/e2ee-channel'
|
||||
import {
|
||||
MobileSocketWiring,
|
||||
type AuthenticatedMobileSocket,
|
||||
type MobileSocketTransportMetadata
|
||||
} from './rpc/mobile-socket-wiring'
|
||||
import type { PairingRelay } from '../../shared/mobile-relay-pairing-offer'
|
||||
import type { MobilePairingConnectionMode } from '../../shared/mobile-pairing-connection-mode'
|
||||
import {
|
||||
RelayRevokeOutbox,
|
||||
type RelayDeviceBinding,
|
||||
type RelayRevokeOutboxItem
|
||||
} from './relay/relay-revoke-outbox'
|
||||
import type {
|
||||
DeviceCredentialInstalled,
|
||||
PairingGetEndpointsParams,
|
||||
PairingGetEndpointsResult,
|
||||
PairingProvisionRelayParams
|
||||
} from '../../shared/mobile-relay-credential-contract'
|
||||
import { encodePairingOffer, PAIRING_OFFER_VERSION } from '../../shared/pairing'
|
||||
import {
|
||||
decodeTerminalStreamFrame,
|
||||
@@ -45,6 +62,28 @@ type OrcaRuntimeRpcServerOptions = {
|
||||
longPollCap?: number
|
||||
}
|
||||
|
||||
type MobileRelayPairingProvider = {
|
||||
createPairingRelay(
|
||||
relayDeviceId: string
|
||||
): Promise<{ relay: PairingRelay; binding: RelayDeviceBinding }>
|
||||
onDeviceRevokeQueued(item: RelayRevokeOutboxItem): void
|
||||
onDemandStateChanged?(): void
|
||||
getEndpoints(
|
||||
context: MobilePairingConnectionContext,
|
||||
params: PairingGetEndpointsParams
|
||||
): Promise<PairingGetEndpointsResult>
|
||||
provisionRelay(
|
||||
context: MobilePairingConnectionContext,
|
||||
params: PairingProvisionRelayParams
|
||||
): Promise<DeviceCredentialInstalled>
|
||||
}
|
||||
|
||||
export type MobilePairingConnectionContext = Readonly<{
|
||||
deviceId: string
|
||||
connectionId: string
|
||||
transport: MobileSocketTransportMetadata
|
||||
}>
|
||||
|
||||
// Why: after 10 s of a pending dispatch we emit a tiny `{"_keepalive":true}`
|
||||
// frame every 10 s until the handler resolves. Each write resets both the
|
||||
// server's own socket idle timer (30 s) and — once §3.1 ships on the client —
|
||||
@@ -288,6 +327,8 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([
|
||||
'notifications.getMissedSince',
|
||||
'notifications.subscribe',
|
||||
'notifications.unsubscribe',
|
||||
'pairing.getEndpoints',
|
||||
'pairing.provisionRelay',
|
||||
'preflight.check',
|
||||
'preflight.detectAgents',
|
||||
'preflight.detectRemoteAgents',
|
||||
@@ -411,19 +452,14 @@ export class OrcaRuntimeRpcServer {
|
||||
private readonly authToken = randomBytes(24).toString('hex')
|
||||
private readonly keepaliveIntervalMs: number
|
||||
private readonly longPollCap: number
|
||||
private readonly relayRevokeOutbox: RelayRevokeOutbox
|
||||
private deviceRegistry: DeviceRegistry | null = null
|
||||
private e2eeKeypair: E2EEKeypair | null = null
|
||||
private tlsFingerprint: string | null = null
|
||||
private wsTransport: WebSocketTransport | null = null
|
||||
private activeTransports: RpcTransport[] = []
|
||||
private transports: RuntimeTransportMetadata[] = []
|
||||
// Why: each WebSocket connection has its own E2EE channel that manages the
|
||||
// handshake and encrypt/decrypt lifecycle. Keyed by WebSocket instance.
|
||||
private e2eeChannels = new Map<WebSocket, E2EEChannel>()
|
||||
// Why: stable per-WebSocket id used as the cleanup key for streaming
|
||||
// subscriptions, so the server can reap a closing socket's subscriptions
|
||||
// without affecting other live sockets that share the same deviceToken.
|
||||
private wsConnectionIds = new Map<WebSocket, string>()
|
||||
private mobileSocketWiring: MobileSocketWiring | null = null
|
||||
private mobileRelayPairingProvider: MobileRelayPairingProvider | null = null
|
||||
private readonly binaryStreamHandlers = new Map<
|
||||
string,
|
||||
Map<number, (frame: TerminalStreamFrame) => void>
|
||||
@@ -458,6 +494,7 @@ export class OrcaRuntimeRpcServer {
|
||||
this.webClientRoot = webClientRoot
|
||||
this.keepaliveIntervalMs = keepaliveIntervalMs
|
||||
this.longPollCap = longPollCap
|
||||
this.relayRevokeOutbox = new RelayRevokeOutbox(userDataPath)
|
||||
}
|
||||
|
||||
getDeviceRegistry(): DeviceRegistry | null {
|
||||
@@ -476,12 +513,55 @@ export class OrcaRuntimeRpcServer {
|
||||
return this.e2eeKeypair
|
||||
}
|
||||
|
||||
revokeMobileDevice(deviceId: string): boolean {
|
||||
const device = this.deviceRegistry?.getDevice(deviceId)
|
||||
if (device?.scope !== 'mobile' || !this.deviceRegistry?.removeDevice(deviceId)) {
|
||||
getMobileSocketWiring(): MobileSocketWiring | null {
|
||||
return this.mobileSocketWiring
|
||||
}
|
||||
|
||||
getRelayRevokeOutbox(): RelayRevokeOutbox {
|
||||
return this.relayRevokeOutbox
|
||||
}
|
||||
|
||||
setMobileRelayBinding(deviceId: string, binding: RelayDeviceBinding): boolean {
|
||||
const current = this.deviceRegistry?.getDevice(deviceId)
|
||||
if (
|
||||
current?.scope !== 'mobile' ||
|
||||
this.deviceRegistry?.getMobilePairingConnectionMode(deviceId) === 'local-only'
|
||||
) {
|
||||
return false
|
||||
}
|
||||
this.wsTransport?.terminateClientConnections(device.token)
|
||||
if (
|
||||
current.relayBinding &&
|
||||
(current.relayBinding.relayHostId !== binding.relayHostId ||
|
||||
current.relayBinding.ownerIdentityKey !== binding.ownerIdentityKey)
|
||||
) {
|
||||
// Why: switching the account/host that owns this local pairing cannot
|
||||
// strand the old cloud credential family even if that account is offline.
|
||||
this.queueRelayDeviceRevoke(current.relayBinding)
|
||||
}
|
||||
const updated = this.deviceRegistry?.setRelayBinding(deviceId, binding) ?? false
|
||||
if (updated) {
|
||||
this.mobileRelayPairingProvider?.onDemandStateChanged?.()
|
||||
}
|
||||
return updated
|
||||
}
|
||||
|
||||
setMobileRelayPairingProvider(provider: MobileRelayPairingProvider | null): void {
|
||||
this.mobileRelayPairingProvider = provider
|
||||
}
|
||||
|
||||
async revokeMobileDevice(deviceId: string): Promise<boolean> {
|
||||
const device = this.deviceRegistry?.getDevice(deviceId)
|
||||
if (device?.scope !== 'mobile') {
|
||||
return false
|
||||
}
|
||||
if (device.relayBinding) {
|
||||
this.queueRelayDeviceRevoke(device.relayBinding)
|
||||
}
|
||||
if (!this.deviceRegistry?.removeDevice(deviceId)) {
|
||||
return false
|
||||
}
|
||||
this.mobileRelayPairingProvider?.onDemandStateChanged?.()
|
||||
this.mobileSocketWiring?.terminateDeviceConnections(device.token)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -490,7 +570,7 @@ export class OrcaRuntimeRpcServer {
|
||||
if (device?.scope !== 'runtime' || !this.deviceRegistry?.removeDevice(deviceId)) {
|
||||
return false
|
||||
}
|
||||
this.wsTransport?.terminateClientConnections(device.token)
|
||||
this.mobileSocketWiring?.terminateDeviceConnections(device.token)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -542,6 +622,71 @@ export class OrcaRuntimeRpcServer {
|
||||
}
|
||||
}
|
||||
|
||||
async createMobilePairingOffer(args: {
|
||||
address?: string | null
|
||||
connectionMode?: MobilePairingConnectionMode
|
||||
name?: string
|
||||
rotate?: boolean
|
||||
}): Promise<ReturnType<OrcaRuntimeRpcServer['createPairingOffer']>> {
|
||||
// Why: the renderer is outside the trust boundary; only the explicit
|
||||
// local-only value may suppress Relay provisioning.
|
||||
const connectionMode = args.connectionMode === 'local-only' ? 'local-only' : 'automatic'
|
||||
const pending = this.deviceRegistry?.getPendingDevice('mobile')
|
||||
const switchingPendingToLocal =
|
||||
connectionMode === 'local-only' && pending?.relayBinding !== undefined
|
||||
if (args.rotate || switchingPendingToLocal) {
|
||||
if (pending?.relayBinding) {
|
||||
// Why: the durable cloud revoke is recorded before rotating the local
|
||||
// token, so a previously displayed relay invite cannot outlive the QR.
|
||||
this.queueRelayDeviceRevoke(pending.relayBinding)
|
||||
}
|
||||
}
|
||||
const direct = this.createPairingOffer({
|
||||
...args,
|
||||
rotate: args.rotate || switchingPendingToLocal,
|
||||
scope: 'mobile'
|
||||
})
|
||||
if (!direct.available) {
|
||||
return direct
|
||||
}
|
||||
this.deviceRegistry?.setMobilePairingConnectionMode(direct.deviceId, connectionMode)
|
||||
if (connectionMode === 'local-only' || !this.mobileRelayPairingProvider) {
|
||||
return direct
|
||||
}
|
||||
const device = this.deviceRegistry?.getDevice(direct.deviceId)
|
||||
const publicKeyB64 = this.getE2EEPublicKey()
|
||||
if (!device || !publicKeyB64) {
|
||||
return direct
|
||||
}
|
||||
try {
|
||||
const relayPairing = await this.mobileRelayPairingProvider.createPairingRelay(device.deviceId)
|
||||
if (!this.deviceRegistry?.setRelayBinding(device.deviceId, relayPairing.binding)) {
|
||||
return direct
|
||||
}
|
||||
this.mobileRelayPairingProvider.onDemandStateChanged?.()
|
||||
return {
|
||||
...direct,
|
||||
pairingUrl: encodePairingOffer({
|
||||
v: PAIRING_OFFER_VERSION,
|
||||
endpoint: direct.endpoint,
|
||||
deviceToken: device.token,
|
||||
publicKeyB64,
|
||||
scope: 'mobile',
|
||||
relay: relayPairing.relay
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Why: relay is additive. A transient auth/director/control outage must
|
||||
// still yield the valid LAN/Tailscale pairing offer.
|
||||
return direct
|
||||
}
|
||||
}
|
||||
|
||||
private queueRelayDeviceRevoke(binding: RelayDeviceBinding): void {
|
||||
const item = this.relayRevokeOutbox.enqueue(binding)
|
||||
this.mobileRelayPairingProvider?.onDeviceRevokeQueued(item)
|
||||
}
|
||||
|
||||
private registerBinaryStreamHandler(
|
||||
connectionId: string | undefined,
|
||||
streamId: number,
|
||||
@@ -569,7 +714,7 @@ export class OrcaRuntimeRpcServer {
|
||||
}
|
||||
|
||||
private handleWebSocketBinaryMessage(bytes: Uint8Array<ArrayBufferLike>, ws: WebSocket): void {
|
||||
const connectionId = this.wsConnectionIds.get(ws)
|
||||
const connectionId = this.mobileSocketWiring?.getConnectionId(ws)
|
||||
if (!connectionId) {
|
||||
return
|
||||
}
|
||||
@@ -721,85 +866,39 @@ export class OrcaRuntimeRpcServer {
|
||||
// pin it.
|
||||
...(this.wsPort !== 0 ? { fallbackPort: readWsFallbackPort(this.userDataPath) } : {})
|
||||
})
|
||||
this.wsTransport = wsTransport
|
||||
|
||||
// Why: each WebSocket connection gets an E2EE channel that handles the
|
||||
// handshake before any RPC messages are processed. The channel decrypts
|
||||
// inbound messages and encrypts outbound replies transparently.
|
||||
wsTransport.onMessage((msg, _reply, ws) => {
|
||||
let channel = this.e2eeChannels.get(ws)
|
||||
if (!channel) {
|
||||
// Why: stable per-ws id used as the cleanup-index key for
|
||||
// streaming subscriptions, so the server can reap them exactly
|
||||
// when this socket closes (without affecting other live sockets
|
||||
// that share the same deviceToken).
|
||||
this.wsConnectionIds.set(ws, randomBytes(8).toString('hex'))
|
||||
channel = new E2EEChannel(ws, {
|
||||
serverSecretKey: this.e2eeKeypair!.secretKey,
|
||||
validateToken: (token) => this.deviceRegistry?.validateToken(token) != null,
|
||||
onReady: (ch) => {
|
||||
if (ch.deviceToken) {
|
||||
wsTransport.setClientId(ws, ch.deviceToken)
|
||||
// Why: mark the device as actually connected so it appears
|
||||
// in the "Paired Devices" list. Devices that were only
|
||||
// generated as QR codes but never scanned stay hidden.
|
||||
const device = this.deviceRegistry?.validateToken(ch.deviceToken)
|
||||
if (device) {
|
||||
this.deviceRegistry?.updateLastSeen(device.deviceId)
|
||||
}
|
||||
}
|
||||
},
|
||||
onError: (code, reason) => {
|
||||
this.e2eeChannels.get(ws)?.destroy()
|
||||
this.e2eeChannels.delete(ws)
|
||||
ws.close(code, reason)
|
||||
}
|
||||
})
|
||||
channel.onMessage((plaintext, encryptedReply, encryptedBinaryReply) => {
|
||||
const authenticatedDeviceToken = this.e2eeChannels.get(ws)?.deviceToken ?? null
|
||||
void this.handleWebSocketMessage(
|
||||
plaintext,
|
||||
encryptedReply,
|
||||
encryptedBinaryReply,
|
||||
wsTransport,
|
||||
ws,
|
||||
authenticatedDeviceToken
|
||||
)
|
||||
})
|
||||
channel.onBinaryMessage((bytes) => this.handleWebSocketBinaryMessage(bytes, ws))
|
||||
this.e2eeChannels.set(ws, channel)
|
||||
}
|
||||
channel.handleRawMessage(msg)
|
||||
})
|
||||
|
||||
// Why: when a mobile client disconnects, the runtime must clean up
|
||||
// connection-scoped state like mobile-fit overrides and the E2EE
|
||||
// channel to prevent orphaned state. A single paired device can hold
|
||||
// multiple concurrent sockets (host screen + accounts screen, etc.),
|
||||
// so destroy the channel for THIS exact ws and skip the per-client
|
||||
// teardown when other sockets for the same token are still alive.
|
||||
wsTransport.onConnectionClose((clientId, ws, hasOtherConnections) => {
|
||||
this.abortWebSocketDispatches(ws)
|
||||
// Why: sweep streaming subscriptions for THIS ws regardless of
|
||||
// hasOtherConnections, so per-ws listeners (notifications,
|
||||
// accounts, terminal) don't leak across reconnects. This is
|
||||
// independent of the deviceToken-scoped onClientDisconnected.
|
||||
const connectionId = this.wsConnectionIds.get(ws)
|
||||
if (connectionId) {
|
||||
this.runtime.cleanupSubscriptionsForConnection(connectionId)
|
||||
this.runtime.cancelMobileDictationForConnection(connectionId)
|
||||
this.binaryStreamHandlers.delete(connectionId)
|
||||
this.wsConnectionIds.delete(ws)
|
||||
}
|
||||
const channel = this.e2eeChannels.get(ws)
|
||||
if (channel) {
|
||||
channel.destroy()
|
||||
this.e2eeChannels.delete(ws)
|
||||
}
|
||||
if (clientId && !hasOtherConnections) {
|
||||
this.runtime.onClientDisconnected(clientId)
|
||||
const mobileSocketWiring = new MobileSocketWiring({
|
||||
deviceRegistry: this.deviceRegistry,
|
||||
e2eeKeypair: this.e2eeKeypair,
|
||||
onText: (socket, plaintext, reply, sendBinary) => {
|
||||
void this.handleWebSocketMessage(
|
||||
plaintext,
|
||||
reply,
|
||||
sendBinary,
|
||||
undefined,
|
||||
socket.ws,
|
||||
socket.device.deviceToken,
|
||||
socket
|
||||
)
|
||||
},
|
||||
onBinary: (socket, bytes) => this.handleWebSocketBinaryMessage(bytes, socket.ws),
|
||||
onReady: () => this.mobileRelayPairingProvider?.onDemandStateChanged?.(),
|
||||
onClose: (socket, hasOtherConnections) => {
|
||||
if (!socket) {
|
||||
return
|
||||
}
|
||||
this.abortWebSocketDispatches(socket.ws)
|
||||
// Why: subscriptions and binary streams are socket-scoped, while
|
||||
// client disconnect state is device-scoped across both transports.
|
||||
this.runtime.cleanupSubscriptionsForConnection(socket.connectionId)
|
||||
this.runtime.cancelMobileDictationForConnection(socket.connectionId)
|
||||
this.binaryStreamHandlers.delete(socket.connectionId)
|
||||
if (!hasOtherConnections) {
|
||||
this.runtime.onClientDisconnected(socket.device.deviceToken)
|
||||
}
|
||||
}
|
||||
})
|
||||
mobileSocketWiring.attachTransport(wsTransport)
|
||||
this.mobileSocketWiring = mobileSocketWiring
|
||||
|
||||
await wsTransport.start()
|
||||
if (this.wsPort !== 0 && wsTransport.resolvedPort !== this.wsPort) {
|
||||
@@ -815,7 +914,7 @@ export class OrcaRuntimeRpcServer {
|
||||
// function if it fails to start (e.g., port in use). Log and continue
|
||||
// with Unix socket only.
|
||||
console.error('[runtime] Failed to start WebSocket transport:', error)
|
||||
this.wsTransport = null
|
||||
this.mobileSocketWiring = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -842,7 +941,7 @@ export class OrcaRuntimeRpcServer {
|
||||
const transports = this.activeTransports
|
||||
this.activeTransports = []
|
||||
this.transports = []
|
||||
this.wsTransport = null
|
||||
this.mobileSocketWiring = null
|
||||
if (transports.length === 0) {
|
||||
return
|
||||
}
|
||||
@@ -936,7 +1035,8 @@ export class OrcaRuntimeRpcServer {
|
||||
sendBinary: (response: Uint8Array<ArrayBufferLike>) => boolean | void,
|
||||
wsTransport?: WebSocketTransport,
|
||||
ws?: WebSocket,
|
||||
authenticatedDeviceToken?: string | null
|
||||
authenticatedDeviceToken?: string | null,
|
||||
authenticatedSocket?: AuthenticatedMobileSocket
|
||||
): Promise<void> {
|
||||
let request: RpcRequest
|
||||
try {
|
||||
@@ -1020,7 +1120,31 @@ export class OrcaRuntimeRpcServer {
|
||||
? (response: string): void => reply(injectDeviceScope(response, device.scope))
|
||||
: reply
|
||||
|
||||
const connectionId = ws ? this.wsConnectionIds.get(ws) : undefined
|
||||
const connectionId = ws ? this.mobileSocketWiring?.getConnectionId(ws) : undefined
|
||||
const pairingProvider = this.mobileRelayPairingProvider
|
||||
const pairingContext =
|
||||
pairingProvider && authenticatedSocket
|
||||
? {
|
||||
getEndpoints: (params: PairingGetEndpointsParams) =>
|
||||
pairingProvider.getEndpoints(
|
||||
{
|
||||
deviceId: authenticatedSocket.device.deviceId,
|
||||
connectionId: authenticatedSocket.connectionId,
|
||||
transport: authenticatedSocket.transport
|
||||
},
|
||||
params
|
||||
),
|
||||
provisionRelay: (params: PairingProvisionRelayParams) =>
|
||||
pairingProvider.provisionRelay(
|
||||
{
|
||||
deviceId: authenticatedSocket.device.deviceId,
|
||||
connectionId: authenticatedSocket.connectionId,
|
||||
transport: authenticatedSocket.transport
|
||||
},
|
||||
params
|
||||
)
|
||||
}
|
||||
: undefined
|
||||
try {
|
||||
await this.dispatcher.dispatchStreaming(request, replyForRequest, {
|
||||
connectionId,
|
||||
@@ -1028,6 +1152,7 @@ export class OrcaRuntimeRpcServer {
|
||||
// Why: gates the mobile-only payload diet (native-chat char clipping) so
|
||||
// full-screen web/desktop runtime clients aren't truncated.
|
||||
clientKind: device.scope,
|
||||
pairing: pairingContext,
|
||||
signal: abortRegistration?.signal,
|
||||
sendBinary,
|
||||
registerBinaryStreamHandler: (streamId, handler) =>
|
||||
|
||||
Reference in New Issue
Block a user