Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

19.5 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest'
import type { MobileRelayCredentialBundle } from './mobile-relay-credential-bundle'
import type { connectMobileRelayForPairing } from './mobile-relay-physical-client'
import type { MobileRelayPairingJournal } from './mobile-relay-pairing-journal'
import { racePairingCandidates } from './pairing-candidate-race'
import { startPreProfilePairing } from './pre-profile-pairing-coordinator'
import type { ConnectionLogEntry, HostProfile, PairingOffer, RpcResponse } from './types'
import type { connect, RpcClient } from './rpc-client'

vi.mock('react-native', () => ({ Platform: { OS: 'ios' } }))
vi.mock('expo-crypto', () => ({
  getRandomBytes: (length: number) => new Uint8Array(length).fill(length)
}))
vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED' }))

const now = Date.UTC(2026, 6, 13)
const directOffer: PairingOffer = {
  v: 2,
  endpoint: 'ws://192.168.1.10:6768',
  deviceToken: 'device-token',
  publicKeyB64: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='
}
const relayOffer: PairingOffer = {
  ...directOffer,
  relay: {
    v: 1,
    directorUrl: 'https://relay.onorca.dev',
    cellUrl: 'https://relay-c1.onorca.dev',
    assignmentEpoch: 7,
    relayHostId: 'AbCdEf0123_-xyZ9',
    inviteToken: 'abcdefghijklmnopqrstuvwxyzABCDEFGH012345678',
    inviteExpiresAt: now + 300_000,
    e2eeFraming: 2
  }
}

function success(result: unknown): RpcResponse {
  return { id: 'rpc-1', ok: true, result, _meta: { runtimeId: 'runtime-1' } }
}

function failure(code: string): RpcResponse {
  return {
    id: 'rpc-1',
    ok: false,
    error: { code, message: code },
    _meta: { runtimeId: 'runtime-1' }
  }
}

function fakeClient(responses: RpcResponse[]) {
  return {
    sendRequest: vi.fn().mockImplementation(async () => responses.shift()!),
    close: vi.fn()
  } as unknown as RpcClient
}

function relayProvisioningClient(getJournal: () => MobileRelayPairingJournal) {
  return {
    sendRequest: vi.fn(async (method: string) => {
      if (method === 'status.get') {
        return success({ path: 'relay' })
      }
      const installed = {
        v: 1 as const,
        reqId: getJournal().metadata.installReqId,
        authorizationMode: 'relay-basis' as const,
        currentVersion: 1,
        resumeExpiresAt: now + 86_400_000
      }
      if (method === 'pairing.provisionRelay') {
        return success(installed)
      }
      return success({
        v: 1,
        relay: {
          v: 1,
          directorUrl: relayOffer.relay!.directorUrl,
          cellUrl: relayOffer.relay!.cellUrl,
          assignmentEpoch: 7,
          relayHostId: relayOffer.relay!.relayHostId,
          e2eeFraming: 2
        },
        installStatus: {
          v: 1,
          reqId: getJournal().metadata.installReqId,
          state: 'committed',
          result: installed
        }
      })
    }),
    close: vi.fn()
  } as unknown as RpcClient
}

function dependencies(client: RpcClient, events: string[]) {
  const unavailableRelay = fakeClient([])
  ;(unavailableRelay.sendRequest as ReturnType<typeof vi.fn>).mockRejectedValue(
    new Error('relay unavailable')
  )
  return {
    connectDirect: vi.fn(
      (..._args: Parameters<typeof connect>) => (events.push('connect'), client)
    ),
    connectRelay: vi.fn(
      (..._args: Parameters<typeof connectMobileRelayForPairing>) => unavailableRelay
    ),
    resolveInviteDirector: vi.fn(async () => {
      throw new Error('director unavailable')
    }),
    resolveHostIdentity: vi.fn(async (_publicKeyB64: string, hostId: string) => ({
      id: hostId,
      name: 'Blue Whale'
    })),
    savePairedHost: vi.fn(async (_host: HostProfile) => {
      events.push('save-host')
    }),
    saveJournal: vi.fn(async (_journal: MobileRelayPairingJournal) => {
      events.push('save-journal')
    }),
    updateJournal: vi.fn(async () => {
      events.push('update-journal')
    }),
    clearJournal: vi.fn(async () => {
      events.push('clear-journal')
    }),
    releaseJournal: vi.fn(),
    recoverPendingJournal: vi.fn(async () => {}),
    writeCredentialBundle: vi.fn(async (_bundle: MobileRelayCredentialBundle) => {
      events.push('write-credential')
    }),
    recordDescriptorFromStatus: vi.fn(() => {
      events.push('record-descriptor')
    }),
    now: () => now,
    platform: 'ios'
  }
}

describe('pre-profile pairing coordinator', () => {
  it('chooses direct when both post-E2EE status successes settle in the same turn', async () => {
    let resolveDirect!: (response: RpcResponse) => void
    let resolveRelay!: (response: RpcResponse) => void
    const direct = fakeClient([])
    const relay = fakeClient([])
    ;(direct.sendRequest as ReturnType<typeof vi.fn>).mockReturnValue(
      new Promise<RpcResponse>((resolve) => {
        resolveDirect = resolve
      })
    )
    ;(relay.sendRequest as ReturnType<typeof vi.fn>).mockReturnValue(
      new Promise<RpcResponse>((resolve) => {
        resolveRelay = resolve
      })
    )
    const racing = racePairingCandidates([
      { path: 'direct', client: direct },
      { path: 'relay', client: relay }
    ])
    resolveRelay(success({ path: 'relay' }))
    resolveDirect(success({ path: 'direct' }))

    await expect(racing).resolves.toMatchObject({ path: 'direct' })
    expect(relay.close).toHaveBeenCalledOnce()
    expect(direct.close).not.toHaveBeenCalled()
  })

  it('keeps a legacy offer direct-only through the shared path', async () => {
    const events: string[] = []
    const client = fakeClient([success({ version: '1.0.0' })])
    const deps = dependencies(client, events)

    const attempt = startPreProfilePairing({
      offer: directOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })

    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })
    expect(deps.savePairedHost).toHaveBeenCalledWith({
      id: `host-${now}`,
      name: 'Blue Whale',
      endpoint: directOffer.endpoint,
      deviceToken: directOffer.deviceToken,
      publicKeyB64: directOffer.publicKeyB64,
      lastConnected: now
    })
    expect(events).toEqual(['connect', 'save-host', 'record-descriptor'])
  })

  it('reuses the existing host id and name when re-pairing the same desktop key (no duplicate)', async () => {
    // Re-pair by preserved identity so a different id cannot create a duplicate host card (STA-1840).
    const events: string[] = []
    const client = fakeClient([success({ version: '1.0.0' })])
    const deps = dependencies(client, events)
    deps.resolveHostIdentity = vi.fn(async (publicKeyB64: string, newHostId: string) => {
      expect(publicKeyB64).toBe(directOffer.publicKeyB64)
      expect(newHostId).toBe(`host-${now}`)
      return { id: 'host-existing', name: 'Studio Mac' }
    })

    const attempt = startPreProfilePairing({
      offer: directOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })

    await expect(attempt.result).resolves.toEqual({ hostId: 'host-existing' })
    expect(deps.savePairedHost).toHaveBeenCalledWith({
      id: 'host-existing',
      name: 'Studio Mac',
      endpoint: directOffer.endpoint,
      deviceToken: directOffer.deviceToken,
      publicKeyB64: directOffer.publicKeyB64,
      lastConnected: now
    })
  })

  it('hands the winning status to the descriptor recorder only after the host is saved', async () => {
    const events: string[] = []
    const client = fakeClient([success({ machineName: 'm4airs-Air', hostPlatform: 'darwin' })])
    const deps = dependencies(client, events)
    const attempt = startPreProfilePairing({
      offer: directOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })

    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })
    expect(events).toEqual(['connect', 'save-host', 'record-descriptor'])
    expect(deps.recordDescriptorFromStatus).toHaveBeenCalledWith(
      `host-${now}`,
      expect.objectContaining({ machineName: 'm4airs-Air', hostPlatform: 'darwin' })
    )
  })

  it('pairs a desktop whose status reply is unreadable, recording no descriptor', async () => {
    const deps = dependencies(fakeClient([success(null)]), [])
    const attempt = startPreProfilePairing({
      offer: directOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })

    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })
    expect(deps.savePairedHost).toHaveBeenCalledOnce()
    expect(deps.recordDescriptorFromStatus).not.toHaveBeenCalled()
  })

  it('still resolves a saved pairing when descriptor recording throws', async () => {
    const events: string[] = []
    const client = fakeClient([success({ machineName: 'm4airs-Air', hostPlatform: 'darwin' })])
    const deps = dependencies(client, events)
    deps.recordDescriptorFromStatus.mockImplementation(() => {
      throw new Error('storage unavailable')
    })
    const attempt = startPreProfilePairing({
      offer: directOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })

    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })
    expect(deps.savePairedHost).toHaveBeenCalledOnce()
  })

  it('journals before connecting and publishes only after authoritative direct install', async () => {
    const events: string[] = []
    let journal: MobileRelayPairingJournal | null = null
    const client = {
      sendRequest: vi.fn(async (method: string) => {
        if (method === 'status.get') {
          return success({ version: '1.0.0' })
        }
        if (!journal) {
          throw new Error('journal was not saved before RPC')
        }
        const installed = {
          v: 1 as const,
          reqId: journal.metadata.installReqId,
          authorizationMode: 'authenticated-direct' as const,
          currentVersion: 1,
          resumeExpiresAt: now + 86_400_000
        }
        if (method === 'pairing.provisionRelay') {
          return success(installed)
        }
        return success({
          v: 1,
          relay: {
            v: 1,
            directorUrl: relayOffer.relay!.directorUrl,
            cellUrl: relayOffer.relay!.cellUrl,
            assignmentEpoch: 7,
            relayHostId: relayOffer.relay!.relayHostId,
            e2eeFraming: 2
          },
          installStatus: {
            v: 1,
            reqId: journal.metadata.installReqId,
            state: 'committed',
            result: installed
          }
        })
      }),
      close: vi.fn()
    } as unknown as RpcClient
    const deps = dependencies(client, events)
    deps.saveJournal.mockImplementation(async (value) => {
      journal = value
      events.push('save-journal')
    })

    const attempt = startPreProfilePairing({
      offer: relayOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })
    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })

    expect(journal).not.toBeNull()
    expect(events).toEqual([
      'save-journal',
      'connect',
      'update-journal',
      'write-credential',
      'save-host',
      'clear-journal',
      'record-descriptor'
    ])
    expect(client.sendRequest).toHaveBeenNthCalledWith(2, 'pairing.provisionRelay', {
      reqId: journal!.metadata.installReqId,
      newResumeTokenHash: journal!.metadata.pendingResumeTokenHash
    })
    expect(deps.savePairedHost).toHaveBeenCalledWith(
      expect.objectContaining({
        id: `host-${now}`,
        endpoint: directOffer.endpoint,
        relay: expect.objectContaining({ relayHostId: relayOffer.relay!.relayHostId })
      })
    )
  })

  it('tolerates an old desktop method_not_found and commits a direct-only host', async () => {
    const events: string[] = []
    const client = fakeClient([success({ version: '1.0.0' }), failure('method_not_found')])
    const deps = dependencies(client, events)

    const attempt = startPreProfilePairing({
      offer: relayOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })
    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })

    expect(deps.savePairedHost).toHaveBeenCalledWith(
      expect.not.objectContaining({ relay: expect.anything() })
    )
    expect(events).toEqual([
      'save-journal',
      'connect',
      'update-journal',
      'save-host',
      'clear-journal',
      'record-descriptor'
    ])
  })

  // Even a relay-advertising host may omit probe allowlisting; forbidden must still allow LAN-only pairing.
  it('tolerates an old desktop scope refusal and commits a direct-only host', async () => {
    const events: string[] = []
    const entries: ConnectionLogEntry[] = []
    const client = fakeClient([success({ version: '1.0.0' }), failure('forbidden')])
    const deps = dependencies(client, events)

    const attempt = startPreProfilePairing({
      offer: relayOffer,
      timeoutMs: 5_000,
      connectOptions: { onLog: (entry) => entries.push(entry) },
      dependencies: deps
    })
    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })

    expect(deps.savePairedHost).toHaveBeenCalledWith(
      expect.not.objectContaining({ relay: expect.anything() })
    )
    expect(events).toEqual([
      'save-journal',
      'connect',
      'update-journal',
      'save-host',
      'clear-journal',
      'record-descriptor'
    ])
    expect(entries).toContainEqual(
      expect.objectContaining({
        message: 'Relay: desktop will not serve relay pairing',
        detail: 'forbidden'
      })
    )
  })

  it('uses relay-basis provisioning when only the relay reaches post-E2EE status', async () => {
    const direct = fakeClient([])
    ;(direct.sendRequest as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('LAN down'))
    let journal: MobileRelayPairingJournal | null = null
    const relay = relayProvisioningClient(() => journal!)
    const deps = dependencies(direct, [])
    deps.connectRelay.mockReturnValue(relay)
    deps.saveJournal.mockImplementation(async (value) => {
      journal = value
    })

    const attempt = startPreProfilePairing({
      offer: relayOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })
    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })

    expect(direct.close).toHaveBeenCalled()
    expect(relay.sendRequest).toHaveBeenNthCalledWith(2, 'pairing.provisionRelay', {
      reqId: journal!.metadata.installReqId,
      newResumeTokenHash: journal!.metadata.pendingResumeTokenHash
    })
    expect(deps.writeCredentialBundle).toHaveBeenCalledWith(
      expect.objectContaining({ current: expect.objectContaining({ version: 1 }) })
    )
  })

  it('streams the relay path and the winning path into the pairing log', async () => {
    const entries: ConnectionLogEntry[] = []
    const direct = fakeClient([])
    ;(direct.sendRequest as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('LAN down'))
    let journal: MobileRelayPairingJournal | null = null
    const relay = relayProvisioningClient(() => journal!)
    const deps = dependencies(direct, [])
    deps.saveJournal.mockImplementation(async (value) => {
      journal = value
    })
    // Emit through the physical connection sink to prove log attribution reaches beyond the candidate.
    deps.connectRelay.mockImplementation((connectArgs) => {
      connectArgs.onLog?.({
        id: 'relay-dial',
        ts: now,
        level: 'info',
        message: 'Relay: dialing cell',
        detail: 'relay-c1.onorca.dev'
      })
      return relay
    })

    const attempt = startPreProfilePairing({
      offer: relayOffer,
      timeoutMs: 5_000,
      connectOptions: { onLog: (entry) => entries.push(entry) },
      dependencies: deps
    })
    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })

    expect(entries.map((entry) => entry.message)).toEqual([
      'Relay: pairing candidate started',
      'Relay: dialing cell',
      'Pairing path selected'
    ])
    expect(entries[0]!.detail).toBe('relay-c1.onorca.dev')
    expect(entries[2]).toMatchObject({ level: 'success', detail: 'winner: relay' })
  })

  it('attributes each racing candidate so direct retries cannot read as relay', async () => {
    const entries: ConnectionLogEntry[] = []
    const direct = fakeClient([])
    ;(direct.sendRequest as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('LAN down'))
    let journal: MobileRelayPairingJournal | null = null
    const relay = relayProvisioningClient(() => journal!)
    const deps = dependencies(direct, [])
    deps.saveJournal.mockImplementation(async (value) => {
      journal = value
    })
    // Model unlabeled direct reconnect logs whose LAN addresses were mistaken for relay retries.
    deps.connectDirect.mockImplementation((...args) => {
      const options = args[3]
      if (options && typeof options !== 'function') {
        options.onLog?.({
          id: 'direct-reconnect',
          ts: now,
          level: 'warn',
          message: 'Reconnecting (attempt 2)',
          detail: '10.5.0.2:6768'
        })
      }
      return direct
    })
    deps.connectRelay.mockImplementation((connectArgs) => {
      connectArgs.onLog?.({
        id: 'relay-dial',
        ts: now,
        level: 'info',
        message: 'Relay: dialing cell',
        detail: 'relay-c1.onorca.dev'
      })
      connectArgs.onLog?.({ id: 'relay-open', ts: now, level: 'info', message: 'Cell socket open' })
      return relay
    })

    const attempt = startPreProfilePairing({
      offer: relayOffer,
      timeoutMs: 5_000,
      connectOptions: { onLog: (entry) => entries.push(entry) },
      dependencies: deps
    })
    await expect(attempt.result).resolves.toEqual({ hostId: `host-${now}` })

    expect(entries.map((entry) => entry.message)).toEqual([
      'Direct: Reconnecting (attempt 2)',
      'Relay: pairing candidate started',
      // Already self-labelled: attribution must not stutter into 'Relay: Relay:'.
      'Relay: dialing cell',
      'Relay: Cell socket open',
      'Pairing path selected'
    ])
    expect(entries[0]).toMatchObject({ level: 'warn', detail: '10.5.0.2:6768' })
  })

  it('lets a stale journal recover before the new scan journals, and releases it on failure', async () => {
    const events: string[] = []
    const client = fakeClient([])
    vi.mocked(client.sendRequest).mockRejectedValue(new Error('offline'))
    const deps = dependencies(client, events)
    let finishRecovery!: () => void
    deps.recoverPendingJournal.mockImplementation(
      () => new Promise<void>((resolve) => (finishRecovery = resolve))
    )
    const attempt = startPreProfilePairing({
      offer: relayOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })
    const settled = attempt.result.catch(() => null)
    await vi.waitFor(() => expect(deps.recoverPendingJournal).toHaveBeenCalled())
    expect(events).toEqual([])
    finishRecovery()
    await settled
    expect(events[0]).toBe('save-journal')
    const journalId = deps.saveJournal.mock.calls[0]?.[0].metadata.journalId
    expect(journalId).toEqual(expect.any(String))
    expect(deps.releaseJournal).toHaveBeenCalledWith(journalId)
  })

  it('cancels the disposable physical client without publishing a host', async () => {
    let resolveStatus!: (response: RpcResponse) => void
    const status = new Promise<RpcResponse>((resolve) => {
      resolveStatus = resolve
    })
    const client = fakeClient([])
    ;(client.sendRequest as ReturnType<typeof vi.fn>).mockReturnValue(status)
    const deps = dependencies(client, [])
    const attempt = startPreProfilePairing({
      offer: directOffer,
      timeoutMs: 5_000,
      dependencies: deps
    })
    await vi.waitFor(() => expect(client.sendRequest).toHaveBeenCalledWith('status.get'))
    attempt.dispose()
    resolveStatus(success({ version: '1.0.0' }))

    await expect(attempt.result).rejects.toThrow(/cancelled/)
    expect(client.close).toHaveBeenCalledOnce()
    expect(deps.savePairedHost).not.toHaveBeenCalled()
  })
})