{"version":3,"file":"reporter.mjs","names":[],"sources":["../src/reporter/index.ts"],"sourcesContent":["import { browserPostureOutcome, verifiedBrowserPosture } from '../browser-posture';\nimport { browserPostureReport } from '@kya-os/checkpoint-shared/browser-posture';\nimport type { EngineInfo, VerifyResult } from '../engine/types';\n\nimport type { ReportedDelegation, ReportedIdentity } from '@kya-os/checkpoint-shared';\nimport type { ClientAddressShadow } from '@kya-os/checkpoint-shared/client-ip';\nimport { RULESET_HASH_REGEX } from '@kya-os/checkpoint-shared/engine-info';\nimport { SID_ATTRIBUTABLE_RESULT } from '@kya-os/checkpoint-shared/kya-http';\nimport { decisionPolicyId } from '@kya-os/checkpoint-shared/policy/enforcement';\nimport {\n  isDidShaped,\n  readKyaErrorCode,\n  readVerifiedAgentDid,\n  readVerifiedDelegationSid,\n} from '../engine/orchestrator/presented-credential';\n\nconst DEFAULT_BASE_URL = 'https://kya.vouched.id';\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst MAX_ATTEMPTS = 3;\nconst REPORT_WARNING_WINDOW_MS = 60_000;\nconst RETRYABLE_STATUSES: ReadonlySet<number> = new Set([429, 502, 503, 504]);\nconst REJECTED_BODY_STATUSES: ReadonlySet<number> = new Set([400, 413, 422]);\nconst GZIP_REFUSED_STATUSES: ReadonlySet<number> = new Set([400, 413, 415, 422, 500]);\nconst RETRY_BASE_DELAY_MS = 500;\nconst RETRY_AFTER_CAP_MS = 5000;\nconst RETRY_AFTER_JITTER_MS = 250;\nconst CLOCK_OFFSET_QUANTUM_MS = 60_000;\n\nexport const DEFAULT_TELEMETRY_BATCH_SIZE = 200;\nexport const MAX_TELEMETRY_BATCH_SIZE = 500;\nexport const DEFAULT_TELEMETRY_FLUSH_INTERVAL_MS = 2000;\nexport const REPORT_QUEUE_CAPACITY = 10_000;\nexport const REPORT_MAX_IN_FLIGHT = 4;\nexport const REPORT_GZIP_MIN_CHARS = 1024;\nexport const REPORT_GZIP_BACKOFF_MS = 10 * 60_000;\nconst KEEPALIVE_MAX_BYTES = 60 * 1024;\nconst REJECTION_BUDGET_SLACK = 4;\n\n/**\n * Request context the middleware extracts from its framework-native\n * request object. Shape matches the `ContextSchema` accepted by\n * `/api/v1/log-detection`.\n */\nexport interface ReporterContext {\n  userAgent?: string;\n  ipAddress?: string;\n  path?: string;\n  url?: string;\n  method?: string;\n  /**\n   * Shadow measurement of the trusted-proxy rule decided on 2026-10-28\n   * (`compareForwardedChainShadow`): agreement and shapes only, never an\n   * address. Removed with that function once the engine resolves the client\n   * address.\n   */\n  clientAddressShadow?: ClientAddressShadow;\n}\n\n/**\n * SDK self-identification — the producing middleware package + its installed\n * version + runtime. The engine WASM reports the SAME `engine.name`\n * (`checkpoint-engine-wasm`) for Express, Next.js-node, AND Next.js-edge, so\n * detections cannot otherwise tell them apart OR know the SDK version. The host\n * wrapper binds this once (from its own `VERSION` constant + entry file), so the\n * dashboard can gate \"composed policy enforces here\" on the actual installed SDK\n * — including showing Next.js-edge as opt-in (it enforces only when the host\n * wires `cedarWasmModule`, which detections can't observe).\n *\n * Carried TOP-LEVEL in the payload (not inside `engine`) so it survives the\n * engine-field drop in {@link sanitizeEngineInfo}.\n */\nexport interface ReporterSdkInfo {\n  /** npm package name, e.g. `@kya-os/checkpoint-express`. */\n  name: string;\n  /** Installed SDK semver, e.g. `1.5.1`. */\n  version: string;\n  /** Host runtime — `'edge'` composed enforcement is opt-in (cedarWasmModule). */\n  runtime: 'node' | 'edge';\n}\n\n/**\n * Configuration for the detection reporter.\n */\nexport interface DetectionReporterConfig {\n  /**\n   * Project API key. Resolved server-side at the ingest endpoint into\n   * the project association used to insert the detection row. Required.\n   */\n  apiKey: string;\n\n  /**\n   * Dashboard base URL. Defaults to `https://kya.vouched.id`. Override\n   * for staging environments or self-hosted dashboards.\n   */\n  baseUrl?: string;\n\n  /**\n   * Per-attempt timeout in milliseconds. Defaults to 5000ms. The POST\n   * is fire-and-forget — a timeout aborts the attempt, which is then\n   * retried like a network error, and never blocks the verdict path.\n   */\n  timeoutMs?: number;\n\n  /**\n   * Log retry attempts, network failures, server errors and dropped engine\n   * fields. Defaults to `false`. Other HTTP failures can still warn.\n   * API key rejections warn once per key and endpoint in each process, even with debug off.\n   */\n  debug?: boolean;\n\n  /**\n   * SDK self-identification — bound once by the host wrapper. Omit for the\n   * legacy/anonymous path (the dashboard then can't version-gate this runtime\n   * and treats it honestly as unknown). See {@link ReporterSdkInfo}.\n   */\n  sdk?: ReporterSdkInfo;\n\n  telemetryBatchSize?: number;\n\n  telemetryFlushIntervalMs?: number;\n}\n\ninterface BatchQueueOptions<T> {\n  batchSize: number;\n  flushIntervalMs: number;\n  capacity: number;\n  maxInFlight: number;\n  send: (batch: T[]) => Promise<void>;\n  onOverflow: (dropped: number) => void;\n  onBusy: () => void;\n  onIdle: () => void;\n}\n\ninterface BatchQueue<T> {\n  add: (item: T) => Promise<void>;\n  flush: () => Promise<void>;\n}\n\ninterface Waiting<T> {\n  item: T;\n  seq: number;\n}\n\ninterface FlightRange {\n  first: number;\n}\n\ninterface FlushWaiter {\n  target: number;\n  release: () => void;\n}\n\nfunction makeBatchQueue<T>(options: BatchQueueOptions<T>): BatchQueue<T> {\n  const waiting: Waiting<T>[] = [];\n  const flights = new Set<FlightRange>();\n  const flushWaiters: FlushWaiter[] = [];\n  let seq = 0;\n  let inFlight = 0;\n  let drainTarget = 0;\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  let ownerRelease: (() => void) | undefined;\n  let lastSendAt = Date.now();\n  let busy = false;\n\n  function disarm() {\n    if (timer === undefined) return;\n    clearTimeout(timer);\n    timer = undefined;\n  }\n\n  function releaseOwner() {\n    const release = ownerRelease;\n    ownerRelease = undefined;\n    release?.();\n  }\n\n  function settleFlushes() {\n    for (const waiter of flushWaiters.splice(0)) {\n      const queued = waiting.length > 0 && waiting[0]!.seq <= waiter.target;\n      const flying = [...flights].some((range) => range.first <= waiter.target);\n      if (queued || flying) flushWaiters.push(waiter);\n      else waiter.release();\n    }\n  }\n\n  function arm() {\n    if (timer !== undefined) return;\n    timer = setTimeout(() => {\n      timer = undefined;\n      drainTarget = seq;\n      const owner = ownerRelease;\n      ownerRelease = undefined;\n      const started = pump(false);\n      void Promise.all(started).finally(() => owner?.());\n    }, options.flushIntervalMs);\n    (timer as { unref?: () => void }).unref?.();\n  }\n\n  function launch(batch: Waiting<T>[]): Promise<void> {\n    inFlight += 1;\n    lastSendAt = Date.now();\n    const range = { first: batch[0]!.seq };\n    flights.add(range);\n    return Promise.resolve()\n      .then(() => options.send(batch.map((entry) => entry.item)))\n      .catch(() => undefined)\n      .then(() => {\n        flights.delete(range);\n        inFlight -= 1;\n        return Promise.all(pump(true)).then(() => undefined);\n      });\n  }\n\n  function pump(releasesOwner: boolean): Promise<void>[] {\n    const started: Promise<void>[] = [];\n    while (\n      waiting.length > 0 &&\n      inFlight < options.maxInFlight &&\n      (waiting.length >= options.batchSize || waiting[0]!.seq <= drainTarget)\n    ) {\n      started.push(launch(waiting.splice(0, options.batchSize)));\n    }\n    if (waiting.length === 0) {\n      disarm();\n      if (releasesOwner) releaseOwner();\n    } else {\n      arm();\n    }\n    settleFlushes();\n    const nowBusy = waiting.length > 0 || inFlight > 0;\n    if (nowBusy !== busy) {\n      busy = nowBusy;\n      if (nowBusy) options.onBusy();\n      else options.onIdle();\n    }\n    return started;\n  }\n\n  return {\n    add(item) {\n      if (waiting.length >= options.capacity) {\n        waiting.shift();\n        options.onOverflow(1);\n      }\n      seq += 1;\n      if (waiting.length === 0 && Date.now() - lastSendAt >= options.flushIntervalMs) {\n        drainTarget = seq;\n      }\n      waiting.push({ item, seq });\n      const timerBefore = timer;\n      const started = pump(true);\n      if (started.length > 0) return Promise.all(started).then(() => undefined);\n      if (timerBefore === undefined && timer !== undefined) {\n        return new Promise<void>((release) => {\n          ownerRelease = release;\n        });\n      }\n      return Promise.resolve();\n    },\n    flush() {\n      drainTarget = seq;\n      const target = seq;\n      const started = pump(true);\n      return new Promise<void>((release) => {\n        flushWaiters.push({ target, release });\n        settleFlushes();\n      }).then(() => Promise.all(started).then(() => undefined));\n    },\n  };\n}\n\nexport interface DetectionReporter {\n  (result: VerifyResult, ctx: ReporterContext): Promise<void>;\n  flush: () => Promise<void>;\n}\n\ninterface PreparedReport {\n  eventId: string;\n  json: string;\n}\n\ninterface DeliveryTarget {\n  endpoint: string;\n  apiKey: string;\n  timeoutMs: number;\n  debug: boolean;\n  notStored: (reasons: string, count: number) => void;\n  authWarningFingerprint?: Promise<string>;\n  gzipOffUntil: number;\n  clockOffsetMinutes: number;\n}\n\nconst busyReporters = new Set<() => Promise<void>>();\nlet exitFlushInstalled = false;\n\nexport function flushDetectionReports(): Promise<void> {\n  return Promise.all([...busyReporters].map((flush) => flush())).then(() => undefined);\n}\n\nfunction flushOnExit(): void {\n  if (exitFlushInstalled) return;\n  const host = (\n    globalThis as { process?: { on?: (event: string, listener: () => void) => unknown } }\n  ).process;\n  if (typeof host?.on !== 'function') return;\n  exitFlushInstalled = true;\n  host.on('beforeExit', () => {\n    void flushDetectionReports();\n  });\n}\n\nfunction resolveBatchSize(requested: number | undefined): number {\n  if (requested === undefined) return DEFAULT_TELEMETRY_BATCH_SIZE;\n  if (!Number.isInteger(requested) || requested < 1) {\n    throw new Error(\n      `makeDetectionReporter: telemetryBatchSize must be an integer >= 1, got ${requested}`\n    );\n  }\n  if (requested > MAX_TELEMETRY_BATCH_SIZE) {\n    console.warn(\n      `[checkpoint-reporter] telemetryBatchSize ${requested} is above the ${MAX_TELEMETRY_BATCH_SIZE} reports the dashboard takes in one batch; using ${MAX_TELEMETRY_BATCH_SIZE}`\n    );\n    return MAX_TELEMETRY_BATCH_SIZE;\n  }\n  return requested;\n}\n\nfunction resolveFlushIntervalMs(requested: number | undefined): number {\n  if (requested === undefined) return DEFAULT_TELEMETRY_FLUSH_INTERVAL_MS;\n  if (!Number.isFinite(requested) || requested <= 0) {\n    throw new Error(\n      `makeDetectionReporter: telemetryFlushIntervalMs must be a positive number, got ${requested}`\n    );\n  }\n  return requested;\n}\n\nexport interface ReportSenderConfig {\n  apiKey: string;\n  baseUrl?: string;\n  timeoutMs?: number;\n  debug?: boolean;\n  telemetryBatchSize?: number;\n  telemetryFlushIntervalMs?: number;\n  runtime?: 'node' | 'edge';\n}\n\nexport interface ReportSender {\n  send: (payload: Record<string, unknown>) => Promise<void>;\n  flush: () => Promise<void>;\n}\n\nexport function makeReportSender(config: ReportSenderConfig): ReportSender {\n  if (!config.apiKey) {\n    throw new Error(\n      'makeDetectionReporter: `apiKey` is required. Without it the dashboard cannot associate detections with your project.'\n    );\n  }\n\n  const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n  const endpoint = `${baseUrl}/api/v1/log-detection`;\n  const batchSize = resolveBatchSize(config.telemetryBatchSize);\n  const flushIntervalMs = resolveFlushIntervalMs(config.telemetryFlushIntervalMs);\n  const target: DeliveryTarget = {\n    endpoint,\n    apiKey: config.apiKey,\n    timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n    debug: config.debug ?? false,\n    notStored: makeNotStoredWarning(endpoint),\n    gzipOffUntil: 0,\n    clockOffsetMinutes: 0,\n  };\n\n  const queue = makeBatchQueue<PreparedReport>({\n    batchSize,\n    flushIntervalMs,\n    capacity: REPORT_QUEUE_CAPACITY,\n    maxInFlight: REPORT_MAX_IN_FLIGHT,\n    send: (batch) => deliverBatch(batch, target),\n    onOverflow: makeOverflowWarning(endpoint),\n    onBusy: () => busyReporters.add(queue.flush),\n    onIdle: () => busyReporters.delete(queue.flush),\n  });\n\n  if (config.runtime !== 'edge') flushOnExit();\n  return {\n    send(payload) {\n      const eventId = crypto.randomUUID();\n      const context = (payload.context ?? {}) as Record<string, unknown>;\n      const json = JSON.stringify({\n        ...payload,\n        context: { ...context, timestamp: new Date().toISOString() },\n        eventId,\n      });\n      return queue.add({ eventId, json });\n    },\n    flush: queue.flush,\n  };\n}\n\nexport function makeDetectionReporter(config: DetectionReporterConfig): DetectionReporter {\n  const sender = makeReportSender({\n    apiKey: config.apiKey,\n    baseUrl: config.baseUrl,\n    timeoutMs: config.timeoutMs,\n    debug: config.debug,\n    telemetryBatchSize: config.telemetryBatchSize,\n    telemetryFlushIntervalMs: config.telemetryFlushIntervalMs,\n    runtime: config.sdk?.runtime,\n  });\n\n  const reportDetection = (result: VerifyResult, ctx: ReporterContext) => {\n    const payload = buildLogDetectionPayload(result, ctx, config.sdk);\n    if (config.debug && !payload.engine && result.engineInfo?.rulesetHash) {\n      console.warn(\n        `[checkpoint-reporter] dropping engine field — rulesetHash \"${result.engineInfo.rulesetHash}\" doesn't match the dashboard's ruleset hash format (RULESET_HASH_REGEX). Detection row will land with NULL engine_* columns.`\n      );\n    }\n    return sender.send(payload);\n  };\n\n  return Object.assign(reportDetection, { flush: sender.flush });\n}\n\nfunction makeWindowedWarning<A>(\n  render: (arg: A, droppedSince: number) => string\n): (arg: A, count: number) => void {\n  let warnedAt: number | undefined;\n  let droppedSince = 0;\n  return (arg, count) => {\n    const now = Date.now();\n    if (warnedAt !== undefined && now - warnedAt < REPORT_WARNING_WINDOW_MS) {\n      droppedSince += count;\n      return;\n    }\n    console.warn(render(arg, droppedSince));\n    warnedAt = now;\n    droppedSince = 0;\n  };\n}\n\n// Share the warning across reporter instances and SDK builds in the same runtime.\nconst API_KEY_WARNING = Symbol.for('kya.reporter.apiKeyWarning');\n\nasync function warnKeyRefusedOnce(target: DeliveryTarget, status: number): Promise<void> {\n  const fingerprint = await (target.authWarningFingerprint ??= fingerprintReportTarget(target));\n  const registry = globalThis as { [API_KEY_WARNING]?: Set<string> };\n  const warned = (registry[API_KEY_WARNING] ??= new Set());\n  if (warned.has(fingerprint)) return;\n  warned.add(fingerprint);\n  console.warn(\n    `[checkpoint-reporter] The dashboard rejected the API key (HTTP ${status}). Detection reports were dropped. Check that CHECKPOINT_API_KEY is an active API key for this project.`\n  );\n}\n\nasync function fingerprintReportTarget(target: DeliveryTarget): Promise<string> {\n  const input = new TextEncoder().encode(JSON.stringify([target.endpoint, target.apiKey]));\n  const digest = await crypto.subtle.digest('SHA-256', input);\n  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nfunction makeOverflowWarning(endpoint: string): (count: number) => void {\n  const warn = makeWindowedWarning<number>((_, droppedSince) => {\n    const earlier = droppedSince > 0 ? `; ${droppedSince} more dropped since the last warning` : '';\n    return `[checkpoint-reporter] ${REPORT_QUEUE_CAPACITY} detection reports are waiting to be sent to ${endpoint}, so the oldest are dropped: the dashboard is not keeping up${earlier}`;\n  });\n  return (count) => warn(0, count);\n}\n\nfunction makeNotStoredWarning(endpoint: string): (reasons: string, count: number) => void {\n  return makeWindowedWarning<string>((reasons, droppedSince) => {\n    const earlier = droppedSince > 0 ? `; ${droppedSince} more since the last warning` : '';\n    return `[checkpoint-reporter] the dashboard at ${endpoint} accepted detection reports without storing them (${reasons}): check that this host's clock is correct${earlier}`;\n  });\n}\n\ninterface Refusal {\n  index?: number;\n  reason?: string;\n}\n\ninterface BatchClock {\n  offsetMinutes: number;\n  corrected: boolean;\n}\n\ntype AttemptOutcome =\n  | { delivered: true; refused: Refusal[]; serverOffsetMinutes: number | undefined }\n  | {\n      delivered: false;\n      retryable: boolean;\n      failure: string;\n      status?: number;\n      retryAfterMs?: number;\n    };\n\ninterface EncodedBody {\n  body: string | Uint8Array<ArrayBuffer>;\n  gzipped: boolean;\n}\n\nasync function gzipText(text: string): Promise<Uint8Array<ArrayBuffer> | null> {\n  try {\n    const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('gzip'));\n    return new Uint8Array(await new Response(stream).arrayBuffer());\n  } catch {\n    return null;\n  }\n}\n\nasync function encodeBatch(records: PreparedReport[], compress: boolean): Promise<EncodedBody> {\n  const only = records.length === 1 ? records[0] : undefined;\n  const json = only ? only.json : `[${records.map((record) => record.json).join(',')}]`;\n  if (only || !compress || json.length < REPORT_GZIP_MIN_CHARS)\n    return { body: json, gzipped: false };\n  const packed = await gzipText(json);\n  return packed ? { body: packed, gzipped: true } : { body: json, gzipped: false };\n}\n\nasync function postWithRetries(\n  target: DeliveryTarget,\n  encoded: EncodedBody,\n  clockOffsetMinutes: number\n): Promise<{ outcome: AttemptOutcome; attempts: number }> {\n  for (let attempt = 1; ; attempt++) {\n    const outcome = await postOnce(target, encoded, clockOffsetMinutes);\n    if (outcome.delivered || !outcome.retryable || attempt >= MAX_ATTEMPTS) {\n      return { outcome, attempts: attempt };\n    }\n    if (target.debug) {\n      console.warn(\n        `[checkpoint-reporter] log-detection failed: ${outcome.failure} at ${target.endpoint}; sending again`\n      );\n    }\n    await new Promise((resolve) =>\n      setTimeout(resolve, retryDelayMs(attempt, outcome.retryAfterMs))\n    );\n  }\n}\n\ninterface RejectionBudget {\n  left: number;\n  dropped: number;\n  failure: string;\n  attempts: number;\n  firstEventId: string | undefined;\n}\n\nfunction dropRecords(\n  budget: RejectionBudget,\n  records: PreparedReport[],\n  failure: string,\n  attempts: number\n) {\n  if (budget.dropped === 0) {\n    budget.failure = failure;\n    budget.attempts = attempts;\n    budget.firstEventId = records[0]?.eventId;\n  }\n  budget.dropped += records.length;\n}\n\nasync function deliverBatch(records: PreparedReport[], target: DeliveryTarget): Promise<void> {\n  const budget: RejectionBudget = {\n    left: records.length + REJECTION_BUDGET_SLACK,\n    dropped: 0,\n    failure: '',\n    attempts: 0,\n    firstEventId: undefined,\n  };\n  await deliverNode(records, target, budget, true, {\n    offsetMinutes: target.clockOffsetMinutes,\n    corrected: false,\n  });\n  if (budget.dropped === 0) return;\n  const what = budget.dropped === 1 ? 'a detection report' : `${budget.dropped} detection reports`;\n  const label = budget.dropped === 1 ? 'eventId' : 'first eventId';\n  const attempts = budget.attempts;\n  console.warn(\n    `[checkpoint-reporter] dropped ${what} after ${attempts} attempt${attempts === 1 ? '' : 's'}: ${budget.failure} (${label} ${budget.firstEventId}, ${target.endpoint})`\n  );\n}\n\nasync function deliverNode(\n  records: PreparedReport[],\n  target: DeliveryTarget,\n  budget: RejectionBudget,\n  compress: boolean,\n  clock: BatchClock\n): Promise<void> {\n  if (budget.left <= 0) {\n    dropRecords(budget, records, 'the dashboard kept rejecting them', 1);\n    return;\n  }\n  budget.left -= 1;\n  const encoded = await encodeBatch(records, compress && Date.now() >= target.gzipOffUntil);\n  let { outcome, attempts } = await postWithRetries(target, encoded, clock.offsetMinutes);\n  let halvesCompress = compress;\n\n  if (\n    !outcome.delivered &&\n    encoded.gzipped &&\n    outcome.status !== undefined &&\n    GZIP_REFUSED_STATUSES.has(outcome.status)\n  ) {\n    budget.left -= 1;\n    const plain = await postWithRetries(\n      target,\n      await encodeBatch(records, false),\n      clock.offsetMinutes\n    );\n    if (plain.outcome.delivered) target.gzipOffUntil = Date.now() + REPORT_GZIP_BACKOFF_MS;\n    else halvesCompress = false;\n    ({ outcome, attempts } = plain);\n  }\n\n  if (outcome.delivered) {\n    await settleRefusals(records, outcome, target, budget, halvesCompress, clock);\n    return;\n  }\n  if (outcome.status === 401 || outcome.status === 403) {\n    await warnKeyRefusedOnce(target, outcome.status);\n    return;\n  }\n  if (\n    records.length > 1 &&\n    outcome.status !== undefined &&\n    REJECTED_BODY_STATUSES.has(outcome.status)\n  ) {\n    const middle = Math.floor(records.length / 2);\n    await deliverNode(records.slice(0, middle), target, budget, halvesCompress, clock);\n    await deliverNode(records.slice(middle), target, budget, halvesCompress, clock);\n    return;\n  }\n  if (!target.debug && (outcome.status === undefined || outcome.status >= 500)) return;\n  dropRecords(budget, records, outcome.failure, attempts);\n}\n\nasync function readRefusals(response: Response): Promise<Refusal[]> {\n  try {\n    const body = (await response.json()) as { refused?: unknown };\n    return Array.isArray(body.refused)\n      ? body.refused.filter(\n          (entry): entry is Refusal => typeof entry === 'object' && entry !== null\n        )\n      : [];\n  } catch {\n    return [];\n  }\n}\n\nfunction noteNotStored(target: DeliveryTarget, refused: Refusal[]): void {\n  if (refused.length === 0) return;\n  const reasons = [...new Set(refused.map((entry) => entry.reason ?? 'unknown'))].join(', ');\n  target.notStored(reasons, refused.length);\n}\n\nasync function settleRefusals(\n  records: PreparedReport[],\n  delivered: Extract<AttemptOutcome, { delivered: true }>,\n  target: DeliveryTarget,\n  budget: RejectionBudget,\n  compress: boolean,\n  clock: BatchClock\n): Promise<void> {\n  const { serverOffsetMinutes } = delivered;\n  const correction =\n    !clock.corrected && serverOffsetMinutes !== clock.offsetMinutes\n      ? serverOffsetMinutes\n      : undefined;\n  const skewed = new Set<number>();\n  const notStored: Refusal[] = [];\n  for (const entry of delivered.refused) {\n    const { index } = entry;\n    if (\n      correction !== undefined &&\n      entry.reason === 'clock_skew' &&\n      typeof index === 'number' &&\n      records[index] !== undefined\n    ) {\n      skewed.add(index);\n    } else {\n      notStored.push(entry);\n    }\n  }\n  noteNotStored(target, notStored);\n  if (correction === undefined || skewed.size === 0) return;\n  await deliverNode(\n    records.filter((_, index) => skewed.has(index)),\n    target,\n    budget,\n    compress,\n    { offsetMinutes: correction, corrected: true }\n  );\n}\n\nfunction learnClockOffset(target: DeliveryTarget, response: Response): number | undefined {\n  const serverNow = Date.parse(response.headers?.get?.('Date') ?? '');\n  if (Number.isNaN(serverNow)) return undefined;\n  const minutes = Math.round((serverNow - Date.now()) / CLOCK_OFFSET_QUANTUM_MS);\n  target.clockOffsetMinutes = minutes;\n  return minutes;\n}\n\nasync function postOnce(\n  target: DeliveryTarget,\n  encoded: EncodedBody,\n  clockOffsetMinutes: number\n): Promise<AttemptOutcome> {\n  const controller = new AbortController();\n  const timeoutId = setTimeout(() => controller.abort(), target.timeoutMs);\n  const size = typeof encoded.body === 'string' ? encoded.body.length : encoded.body.byteLength;\n  let outcome: AttemptOutcome;\n  try {\n    const response = await fetch(target.endpoint, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${target.apiKey}`,\n        ...(clockOffsetMinutes !== 0\n          ? { 'X-Checkpoint-Clock-Offset': String(clockOffsetMinutes) }\n          : {}),\n        ...(encoded.gzipped ? { 'Content-Encoding': 'gzip' } : {}),\n      },\n      body: encoded.body,\n      signal: controller.signal,\n      keepalive: size <= KEEPALIVE_MAX_BYTES,\n    });\n    const serverOffsetMinutes = learnClockOffset(target, response);\n    if (response.ok) {\n      outcome = { delivered: true, refused: await readRefusals(response), serverOffsetMinutes };\n    } else {\n      outcome = {\n        delivered: false,\n        retryable: RETRYABLE_STATUSES.has(response.status),\n        failure: `HTTP ${response.status}`,\n        status: response.status,\n        retryAfterMs: parseRetryAfterMs(response.headers?.get?.('Retry-After')),\n      };\n    }\n  } catch (err) {\n    const failure =\n      err instanceof Error && err.name === 'AbortError'\n        ? `timed out after ${target.timeoutMs}ms`\n        : err instanceof Error\n          ? err.message\n          : String(err);\n    outcome = { delivered: false, retryable: true, failure };\n  } finally {\n    clearTimeout(timeoutId);\n  }\n  return outcome;\n}\n\n/**\n * The wait before retry number `retry` (1-based). A `Retry-After` is honoured\n * up to {@link RETRY_AFTER_CAP_MS}, plus jitter; without one, exponential\n * backoff jittered into the upper half of its step.\n */\nfunction retryDelayMs(retry: number, retryAfterMs: number | undefined): number {\n  if (retryAfterMs !== undefined) {\n    return Math.min(retryAfterMs, RETRY_AFTER_CAP_MS) + Math.random() * RETRY_AFTER_JITTER_MS;\n  }\n  const step = RETRY_BASE_DELAY_MS * 2 ** (retry - 1);\n  return step / 2 + Math.random() * (step / 2);\n}\n\n/** `Retry-After` in milliseconds, from delta-seconds or an HTTP date; undefined when absent or unreadable. */\nfunction parseRetryAfterMs(value: string | null | undefined): number | undefined {\n  const trimmed = value?.trim();\n  if (!trimmed) return undefined;\n  if (/^\\d+$/.test(trimmed)) return Number(trimmed) * 1000;\n  const at = Date.parse(trimmed);\n  return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());\n}\n\n/**\n * Translate the engine's `VerifyResult` into the request body shape\n * accepted by `/api/v1/log-detection`. Exported for tests + for\n * advanced consumers wiring a custom transport.\n */\nexport function buildLogDetectionPayload(\n  result: VerifyResult,\n  ctx: ReporterContext,\n  sdk?: ReporterSdkInfo\n) {\n  const detection = result.detectionDetail;\n  const identity = buildReportedIdentity(result);\n  const posture = verifiedBrowserPosture(result);\n  const postureOutcome = browserPostureOutcome(result);\n  const baseEnforcement = extractEnforcement(result);\n\n  // Widen enforcement with structured fields while keeping legacy narrow\n  // fields for backward compat with older ingest endpoints.\n  const enforcement = {\n    ...baseEnforcement,\n    // Full structured BlockReason alongside the legacy string `reason`.\n    // JSON.stringify drops `undefined`, so non-Block decisions stay lean.\n    ...(result.decision.kind === 'Block' ? { blockReason: result.decision.reason } : {}),\n    // Detection signals from the engine — omit when empty to keep the wire lean.\n    ...(detection.signals?.length ? { signals: detection.signals } : {}),\n    // #3246 PR5: revision pin for the acted composed bundle — same presence\n    // semantics as `policyId` (conditional spread, lean wire).\n    ...(result.composedBlobHash ? { composedBlobHash: result.composedBlobHash } : {}),\n  };\n\n  const detectionClass = stringifyDetectionClass(detection.detectionClass);\n  return {\n    detection: {\n      isAgent: wireIsAgent(detectionClass, detection.isAgent),\n      confidence: detection.confidence,\n      agentName: detection.detectedAgent?.name,\n      agentType: detection.detectedAgent?.type ?? detection.agentType,\n      detectionClass,\n      verificationMethod: detection.verificationMethod,\n      reasons: detection.reasons,\n      shadowMetadata: buildShadowMetadata(detection.metadata),\n      detectionBasis:\n        typeof detection.metadata?.detection_basis === 'string'\n          ? detection.metadata.detection_basis\n          : undefined,\n    },\n    ...(posture ? { browserIntegrity: browserPostureReport(posture) } : {}),\n    ...(postureOutcome ? { postureOutcome } : {}),\n    context: ctx,\n    source: 'middleware' as const,\n    enforcement,\n    engine: sanitizeEngineInfo(result.engineInfo),\n    // TOP-LEVEL (not inside `engine`) so it survives the engine-field drop.\n    // `undefined` is omitted by JSON.stringify → legacy/anonymous path.\n    sdk,\n    // Per-stage trace from the engine (layer 1 / #3164). Omitted when\n    // absent so old SDK payloads are unaffected.\n    ...(result.trace?.length ? { engineSteps: result.trace } : {}),\n    // Reported identity from the engine's verdict (delegation session id +\n    // agent DID). Omitted when absent to keep the wire lean for non-KYA-OS\n    // requests (the overwhelming majority).\n    ...(identity ? { identity } : {}),\n  };\n}\n\nconst SHADOW_METADATA_MAX_KEYS = 32;\nconst SHADOW_METADATA_KEY_MAX_LENGTH = 64;\nconst SHADOW_METADATA_VALUE_MAX_LENGTH = 128;\n\nfunction buildShadowMetadata(\n  metadata: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n  const entries = Object.entries(metadata ?? {})\n    .filter(\n      ([key, value]) =>\n        key.startsWith('shadow_') &&\n        key.length <= SHADOW_METADATA_KEY_MAX_LENGTH &&\n        ((typeof value === 'number' && Number.isFinite(value)) ||\n          typeof value === 'boolean' ||\n          (typeof value === 'string' && value.length <= SHADOW_METADATA_VALUE_MAX_LENGTH))\n    )\n    .slice(0, SHADOW_METADATA_MAX_KEYS);\n  return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n}\n\n/**\n * The dashboard's `EngineInfoSchema` accepts a `rulesetHash` matching\n * `RULESET_HASH_REGEX`, the same definition, from `checkpoint-shared`. A value\n * that does not match would 400 the whole detection, so the engine field is\n * dropped instead; `engine` is optional there, and the row lands with NULL\n * engine_* columns.\n */\nfunction sanitizeEngineInfo(engine: EngineInfo | undefined): EngineInfo | undefined {\n  if (!engine) return undefined;\n  if (!RULESET_HASH_REGEX.test(engine.rulesetHash)) return undefined;\n  return engine;\n}\n\n/**\n * Map the engine's PascalCase `DetectionClass.type` variants to the\n * lowercase wire form the dashboard's `extractDetectionClass()`\n * accepts (see `apps/web/lib/detection/extract-detection-class.ts`).\n *\n * Cursor Bugbot caught this on PR #2843 commit `3ac2df9be`: the\n * previous stringifier emitted `AiAgent` verbatim, which doesn't\n * match the dashboard's string branch (only lowercase values), so\n * detections fell through to `isAgent ? 'bot' : 'human'` and lost\n * the `ai_agent` classification — every ChatGPT/Claude hit landed\n * as `bot` in the database.\n *\n * Explicit table rather than a generic PascalCase→snake_case\n * conversion so a future enum variant added to the engine without\n * a corresponding entry here surfaces as `undefined` (dashboard\n * falls back to `isAgent`-based inference) instead of getting\n * silently mis-routed.\n */\nconst DETECTION_CLASS_WIRE: Record<string, string> = {\n  Human: 'human',\n  AiAgent: 'ai_agent',\n  Automation: 'automation',\n  Bot: 'bot',\n  IncompleteData: 'incomplete_data',\n  Unknown: 'unknown',\n};\n\n/**\n * The `isAgent` the wire carries: what ingest stores for this class\n * (`is_agent = detection_class IN ('ai_agent', 'bot')`, after its\n * `extractDetectionClass()` folds `automation` into `bot` and `unknown` into\n * `incomplete_data`). The engine's own `detectionDetail.isAgent` is true only\n * for a known AI agent, so a bot row (crawler, search bot, headless browser)\n * would otherwise go out as `false` and be corrected at ingest. A class ingest\n * doesn't recognise falls back to the engine's flag, as ingest does.\n * `detectionDetail.isAgent` itself is unchanged.\n */\nfunction wireIsAgent(wireClass: string | undefined, engineIsAgent: boolean): boolean {\n  switch (wireClass) {\n    case 'ai_agent':\n    case 'bot':\n    case 'automation':\n      return true;\n    case 'human':\n    case 'incomplete_data':\n    case 'unknown':\n      return false;\n    default:\n      return engineIsAgent;\n  }\n}\n\nfunction stringifyDetectionClass(detectionClass: unknown): string | undefined {\n  if (!detectionClass) return undefined;\n  if (typeof detectionClass === 'string') {\n    // Already on the wire format? Trust it. Otherwise map from\n    // PascalCase if recognised.\n    return DETECTION_CLASS_WIRE[detectionClass] ?? detectionClass;\n  }\n  if (typeof detectionClass === 'object' && 'type' in detectionClass) {\n    const variant = String((detectionClass as { type: unknown }).type);\n    return DETECTION_CLASS_WIRE[variant];\n  }\n  return undefined;\n}\n\n/**\n * Build the `identity` wire block (`ReportedIdentitySchema` in\n * `@kya-os/checkpoint-shared`) from the engine's verdict. Thin passthrough: every\n * fact here already left the WASM boundary on `detectionDetail.metadata`; this\n * function only decides which of three shapes the ALREADY-DECIDED engine verdict maps\n * to (flow-lab-customer-delegation-timeline plan, D15 / E4 / E5):\n *\n *   1. `metadata.kya_session_id` present AND `decision.kind === 'Permit'` -> the engine\n *      verified a presented delegation. `result: SID_ATTRIBUTABLE_RESULT` ('verified'),\n *      carrying the sid. The engine never stamps a sid on a reject or a demotion, so\n *      this branch alone is what makes \"verified\" trustworthy: the security rule is\n *      never decode the bearer here to get a sid; only the engine's verified output\n *      can supply one. The added `decision.kind === 'Permit'` gate is defense in depth:\n *      the engine only ever pairs a stamped sid with a Permit decision (see\n *      `kya_verified_detail` / `bearer_verified_detail` in `rust/crates/kya-os-engine/src/api.rs`),\n *      so requiring both here guards against a future engine change surfacing a sid\n *      outside that pairing, matching D15's \"the server has to hold the line\"\n *      principle applied client-side too.\n *   2. No sid, but `metadata.kya_error_code` is a registry `kyaos/*` code (via\n *      `readKyaErrorCode`) -> a kya credential was presented and the engine explicitly\n *      rejected it. `result: 'failed'`, no sid (E4).\n *   3. Neither -> nothing kya-shaped was presented, OR the engine demoted the request\n *      (identity-pending / a cold trusted root never resolves to a registry code:\n *      `readKyaErrorCode` already filters `kyaos/identity-pending` out because it is\n *      not a member of `KYA_HTTP_ERROR`). Falls through to branch 4.\n *   4. (KYA-1099 W1) `result.bearerDelegationIdentity` is set — the orchestrator itself\n *      observed a standalone bearer delegation (`verify-request-edge.ts`). This is the\n *      branch that fires for a plain bearer delegation with no `sid` claim (ordinary\n *      Bouncer-issued delegations, not kya-http/2 registered sessions): `result:\n *      'verified' | 'failed'` from the orchestrator's decision, carrying `jti` — the\n *      join key into `delegations.id` that branches 1-3 never carry. Only reached when neither 1 nor 2 already produced a `delegation` (a sid\n *      claim, when present, still wins — the engine-verified sid is the stronger\n *      signal). Omit entirely (branch 5) when nothing was presented at all.\n *\n * `identity.agent.did` rides along whenever the engine attributed a leaf DID\n * (branches 1-3), or, absent that, whenever branch 4's bearer delegation carried one\n * — independent of which delegation branch fired.\n *\n * Returns `undefined` (never `{}`) when there is nothing to report, so callers can\n * `...(identity ? { identity } : {})` and keep the wire lean for every non-KYA-OS\n * request (the overwhelming majority).\n */\nexport function buildReportedIdentity(result: VerifyResult): ReportedIdentity | undefined {\n  const metadata = result.detectionDetail.metadata;\n  const sid = readVerifiedDelegationSid(metadata);\n  const bearer = result.bearerDelegationIdentity;\n\n  let delegation: ReportedDelegation | undefined;\n  if (sid && result.decision.kind === 'Permit') {\n    delegation = { sid, result: SID_ATTRIBUTABLE_RESULT, verifiedBy: 'reporter' };\n  } else if (readKyaErrorCode(metadata)) {\n    delegation = { result: 'failed', verifiedBy: 'reporter' };\n  } else if (bearer) {\n    // `bearerDelegationIdentity`'s `agentDid`/`iss` come straight from the\n    // credential's decoded (not yet cryptographically re-checked here)\n    // `sub`/`iss` claims — unlike `readVerifiedAgentDid`/`readVerifiedDelegationSid`\n    // above (engine-metadata values) — so a malformed claim must not reach the\n    // wire and 400 the whole detection the same way an unguarded value could.\n    // `isDidShaped` is the SAME guard `readVerifiedAgentDid` applies.\n    delegation = {\n      ...(bearer.jti ? { jti: bearer.jti } : {}),\n      ...(bearer.iss && isDidShaped(bearer.iss.trim()) ? { iss: bearer.iss } : {}),\n      result: bearer.verified ? 'verified' : 'failed',\n      verifiedBy: 'reporter',\n    };\n  }\n\n  const agentDid =\n    readVerifiedAgentDid(metadata) ??\n    (bearer?.agentDid && isDidShaped(bearer.agentDid.trim()) ? bearer.agentDid : undefined);\n\n  if (!delegation && !agentDid) return undefined;\n  return {\n    ...(agentDid ? { agent: { did: agentDid } } : {}),\n    ...(delegation ? { delegation } : {}),\n  };\n}\n\n/**\n * Map `Decision` to the dashboard's canonical short-form action +\n * optional reason. Matches the six short forms accepted by\n * `EnforcementActionSchema` in `@kya-os/checkpoint-shared`.\n */\nfunction extractEnforcement(result: VerifyResult): {\n  action: string;\n  reason?: string;\n  policyId?: string;\n} {\n  const decision = result.decision;\n  // #3236: the determining policy's authored @id (PR2 wire) rides along so\n  // the dashboard can join the #3272 policies index. `undefined` is dropped\n  // by JSON.stringify, so pre-attribution payload shapes are unchanged.\n  const policyId = decisionPolicyId(decision);\n  switch (decision.kind) {\n    case 'Permit':\n      return { action: result.enforcementMode === 'observe' ? 'log' : 'allow', policyId };\n    case 'Block':\n      return { action: 'block', reason: decision.reason.kind, policyId };\n    case 'Challenge':\n      return { action: 'challenge', policyId };\n    case 'Redirect':\n      return { action: 'redirect', policyId };\n    case 'Instruct':\n      return { action: 'instruct', policyId };\n  }\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,eAAe;AACrB,MAAM,2BAA2B;AACjC,MAAM,qCAA0C,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;AAAG,CAAC;AAC5E,MAAM,yCAA8C,IAAI,IAAI;CAAC;CAAK;CAAK;AAAG,CAAC;AAC3E,MAAM,wCAA6C,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AACpF,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B;AAEhC,MAAa,+BAA+B;AAC5C,MAAa,2BAA2B;AACxC,MAAa,sCAAsC;AACnD,MAAa,wBAAwB;AACrC,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAa,yBAAyB;AACtC,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAoH/B,SAAS,eAAkB,SAA8C;CACvE,MAAM,UAAwB,CAAC;CAC/B,MAAM,0BAAU,IAAI,IAAiB;CACrC,MAAM,eAA8B,CAAC;CACrC,IAAI,MAAM;CACV,IAAI,WAAW;CACf,IAAI,cAAc;CAClB,IAAI;CACJ,IAAI;CACJ,IAAI,aAAa,KAAK,IAAI;CAC1B,IAAI,OAAO;CAEX,SAAS,SAAS;EAChB,IAAI,UAAU,KAAA,GAAW;EACzB,aAAa,KAAK;EAClB,QAAQ,KAAA;CACV;CAEA,SAAS,eAAe;EACtB,MAAM,UAAU;EAChB,eAAe,KAAA;EACf,UAAU;CACZ;CAEA,SAAS,gBAAgB;EACvB,KAAK,MAAM,UAAU,aAAa,OAAO,CAAC,GAAG;GAC3C,MAAM,SAAS,QAAQ,SAAS,KAAK,QAAQ,EAAE,CAAE,OAAO,OAAO;GAC/D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