/**
 * RelaySpy — the untrusted-relay / attacker vantage. A passthrough that records every ciphertext
 * byte it forwards (exactly what a malicious relay can see). INV2: a known plaintext marker must
 * NEVER appear in `captured`. Mirrors the `relay-e2e/test/integration.test.ts` spy.
 */
import { MAX_FRAME_BYTES } from 'relay-e2e'

export class RelaySpy {
  readonly captured: Uint8Array[] = []

  /** Forward a sealed payload, recording a copy of the ciphertext the relay observes. */
  forward(payload: Uint8Array): Uint8Array {
    if (payload.length > MAX_FRAME_BYTES) {
      throw new Error(`payload exceeds MAX_FRAME_BYTES (${payload.length} > ${MAX_FRAME_BYTES})`)
    }
    this.captured.push(payload.slice())
    return payload
  }

  /** Latin1 concatenation of everything the relay saw — for substring canary scans. */
  snapshot(): string {
    return this.captured.map((b) => Buffer.from(b).toString('latin1')).join(' ')
  }

  /** True if `marker` appears in ANY captured frame (utf8 or latin1) — INV2 tripwire. */
  contains(marker: string): boolean {
    if (this.snapshot().includes(marker)) return true
    return this.captured.some(
      (b) =>
        Buffer.from(b).toString('utf8').includes(marker) ||
        Buffer.from(b).toString('latin1').includes(marker),
    )
  }
}
