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.

5.5 KB
Raw Blame
import {
  createWsOutboundBackpressureQueue,
  type WsOutboundBackpressureQueue
} from '../../../src/shared/ws-outbound-backpressure-queue'
import {
  classifyPairedE2EEV2AuthReply,
  pairedE2EEV2TokenAuth
} from '../../../src/shared/paired-e2ee-client-handshake'
import type { MobileE2EEV2ClientSession } from './mobile-e2ee-v2-client-session'
import { WsInboundMessageQueue } from '../../../src/shared/ws-inbound-message-queue'

type ChannelState = 'awaiting-ready' | 'awaiting-authenticated' | 'ready'
type OutboundItem = { kind: 'text'; plaintext: string } | { kind: 'binary'; plaintext: Uint8Array }

export class MobileE2EEAuthenticationError extends Error {
  constructor() {
    super('E2EE device authentication rejected')
  }
}

export type MobileE2EEV2Socket = {
  readonly OPEN: number
  readonly readyState: number
  readonly bufferedAmount: number
  send: (frame: string | Uint8Array) => void
}

export class MobileE2EEV2PhysicalChannel {
  private state: ChannelState = 'awaiting-ready'
  private generation = 0
  private readonly inbound: WsInboundMessageQueue
  private readonly outboundQueue: WsOutboundBackpressureQueue<OutboundItem>

  constructor(
    private readonly args: {
      session: MobileE2EEV2ClientSession
      socket: MobileE2EEV2Socket
      deviceToken: string
      decodeBinary: (raw: unknown) => Promise<Uint8Array | null>
      onReadyAccepted?: () => void
      onAuthenticated: () => void
      onText: (plaintext: string) => void
      onBinary: (plaintext: Uint8Array) => void
      onError: (error: Error) => void
    }
  ) {
    this.inbound = new WsInboundMessageQueue(
      (raw) => this.processMessage(raw, this.generation),
      (error) => args.onError(error instanceof Error ? error : new Error(String(error)))
    )
    this.outboundQueue = createWsOutboundBackpressureQueue<OutboundItem>({
      // Why: encryption happens only when an admitted item reaches the wire,
      // so a bounded-queue rejection cannot burn an ordered v2 counter.
      send: (item) => {
        args.socket.send(
          item.kind === 'text'
            ? args.session.sealText(item.plaintext)
            : args.session.sealBinary(item.plaintext)
        )
      },
      byteLengthOf: (item) =>
        (item.kind === 'text'
          ? new TextEncoder().encode(item.plaintext).length
          : item.plaintext.length) + 82,
      getBufferedAmount: () => args.socket.bufferedAmount,
      isWritable: () => args.socket.readyState === args.socket.OPEN,
      onOverflow: () => args.onError(new Error('E2EE v2 outbound buffer overflow'))
    })
  }

  start(): void {
    this.args.socket.send(JSON.stringify(this.args.session.hello))
  }

  handleMessage(raw: unknown): Promise<void> {
    return this.inbound.enqueue(raw)
  }

  sendText(plaintext: string): boolean {
    return this.enqueueReady({ kind: 'text', plaintext })
  }

  sendBinary(plaintext: Uint8Array): boolean {
    return this.enqueueReady({ kind: 'binary', plaintext })
  }

  dispose(): void {
    this.generation++
    this.inbound.dispose()
    this.outboundQueue.dispose()
  }

  private async processMessage(raw: unknown, generation: number): Promise<void> {
    if (generation !== this.generation) {
      return
    }
    if (this.state === 'awaiting-ready') {
      this.acceptReady(raw)
      return
    }

    const plaintext =
      typeof raw === 'string'
        ? this.args.session.openText(raw)
        : await this.openBinary(raw, generation)
    if (generation !== this.generation || plaintext === null) {
      return
    }
    if (this.state === 'awaiting-authenticated') {
      if (typeof plaintext === 'string' && isAuthenticationRejection(plaintext)) {
        throw new MobileE2EEAuthenticationError()
      }
      if (typeof plaintext !== 'string' || !this.isAuthenticated(plaintext)) {
        throw new Error('Invalid E2EE v2 authenticated response')
      }
      this.state = 'ready'
      this.args.onAuthenticated()
    } else if (typeof plaintext === 'string') {
      this.args.onText(plaintext)
    } else {
      this.args.onBinary(plaintext)
    }
  }

  private acceptReady(raw: unknown): void {
    if (typeof raw !== 'string') {
      throw new Error('Expected plaintext E2EE v2 ready')
    }
    let ready: unknown
    try {
      ready = JSON.parse(raw)
    } catch {
      throw new Error('Invalid E2EE v2 ready JSON')
    }
    if (!this.args.session.acceptReady(ready)) {
      throw new Error('Invalid E2EE v2 ready')
    }
    this.state = 'awaiting-authenticated'
    this.args.onReadyAccepted?.()
    this.outboundQueue.enqueue({
      kind: 'text',
      plaintext: JSON.stringify(
        pairedE2EEV2TokenAuth(this.args.session.transcriptHashB64, this.args.deviceToken)
      )
    })
  }

  private async openBinary(raw: unknown, generation: number): Promise<Uint8Array | null> {
    const bytes = await this.args.decodeBinary(raw)
    if (!bytes || generation !== this.generation) {
      return null
    }
    return this.args.session.openBinary(bytes)
  }

  private isAuthenticated(plaintext: string): boolean {
    try {
      return (
        classifyPairedE2EEV2AuthReply(JSON.parse(plaintext), this.args.session.transcriptHashB64)
          .kind === 'authenticated'
      )
    } catch {
      return false
    }
  }

  private enqueueReady(item: OutboundItem): boolean {
    if (this.state !== 'ready') {
      return false
    }
    this.outboundQueue.enqueue(item)
    return true
  }
}

function isAuthenticationRejection(plaintext: string): boolean {
  try {
    const message = JSON.parse(plaintext) as Record<string, unknown>
    return message.type === 'e2ee_error'
  } catch {
    return false
  }
}