{"version":3,"file":"engine-defaults-Bkjyvk_M.mjs","names":[],"sources":["../src/engine/adapters/reputation-oracle.ts","../src/engine/adapters/clock.ts","../src/engine/adapters/resolution-warmer.ts","../src/engine/adapters/engine-defaults.ts"],"sourcesContent":["/**\n * ReputationOracle adapter — sub-phase B.3.\n *\n * Resolves a per-DID reputation score in `[0.0, 1.0]`. Phase 1 wires\n * an optional HTTP endpoint (Argus). Unavailable / misconfigured /\n * out-of-range responses degrade to a baseline score so infrastructure\n * blips can't silently DOS Adobe-class traffic. The orchestrators hand the\n * engine each agent DID's score; a tenant rule over reputation is Cedar.\n *\n * **Degrade-to-trust** (Phase B § 4.5). Reputation is best-effort;\n * Argus outages do not block traffic. The adapter returns the\n * configured baseline (default 1.0 = \"no signal, treat as trusted\")\n * and logs loudly, so no traffic is rejected just because Argus went down.\n */\n\n// -----------------------------------------------------------------------------\n// Public surface.\n// -----------------------------------------------------------------------------\n\nexport interface ReputationOracleAdapter {\n  /**\n   * Return the agent's reputation in `[0.0, 1.0]`. Higher is better.\n   *\n   * **Does not throw.** Network / parse / range failures degrade to\n   * the baseline + log; the engine should never see a thrown error\n   * from this adapter.\n   */\n  score(agentDid: string): Promise<number>;\n}\n\ninterface CacheEntry {\n  value: number;\n  fetchedAt: number;\n}\n\nexport interface ReputationOracleOpts {\n  /**\n   * Base URL for the reputation service (Argus). When unset, the\n   * adapter returns the baseline without fetching.\n   */\n  argusUrl?: string;\n  /** Fetch budget. Default 1500ms — reputation is best-effort, tighter than DID resolution. */\n  fetchTimeoutMs?: number;\n  /** Cache TTL. Default 10s — reputation churns faster than DIDs. */\n  ttlMs?: number;\n  /** Injectable fetch. Defaults to global `fetch`. */\n  fetch?: typeof fetch;\n  /** Returned when Argus is unset / unreachable / malformed. Default 1.0. */\n  baselineWhenUnreachable?: number;\n  /** Injectable cache for tests. */\n  cache?: Map<string, CacheEntry>;\n  /** Injectable wall-clock. */\n  now?: () => number;\n  /** Hook for diagnostics. Phase 1 keeps log volume manageable by sampling. */\n  logger?: (msg: string) => void;\n}\n\nconst DEFAULT_FETCH_TIMEOUT_MS = 1_500;\nconst DEFAULT_TTL_MS = 10_000;\nconst DEFAULT_BASELINE = 1.0;\n\nexport function makeReputationOracle(opts: ReputationOracleOpts = {}): ReputationOracleAdapter {\n  const argusUrl = opts.argusUrl;\n  const timeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n  const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;\n  const fetchImpl = opts.fetch ?? fetch;\n  const baseline = opts.baselineWhenUnreachable ?? DEFAULT_BASELINE;\n  const cache = opts.cache ?? new Map<string, CacheEntry>();\n  const now = opts.now ?? (() => Date.now());\n  const log = opts.logger ?? (() => {});\n\n  return {\n    async score(agentDid: string): Promise<number> {\n      const cached = cache.get(agentDid);\n      if (cached && now() - cached.fetchedAt < ttlMs) {\n        return cached.value;\n      }\n\n      if (!argusUrl) {\n        // No Argus configured — degrade-to-trust silently (the host\n        // logs the config gap once at startup, not per-request).\n        return baseline;\n      }\n\n      const value = await fetchAndValidate(argusUrl, agentDid, fetchImpl, timeoutMs, baseline, log);\n      cache.set(agentDid, { value, fetchedAt: now() });\n      return value;\n    },\n  };\n}\n\nasync function fetchAndValidate(\n  argusUrl: string,\n  agentDid: string,\n  fetchImpl: typeof fetch,\n  timeoutMs: number,\n  baseline: number,\n  log: (msg: string) => void\n): Promise<number> {\n  const url = `${argusUrl.replace(/\\/$/, '')}/v1/reputation?agent=${encodeURIComponent(agentDid)}`;\n\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n  let response: Response;\n  try {\n    response = await fetchImpl(url, { signal: controller.signal });\n  } catch (cause) {\n    if (cause instanceof Error && cause.name === 'AbortError') {\n      log(\n        `[reputation-oracle] Argus timed out after ${timeoutMs}ms (${agentDid}); using baseline ${baseline}`\n      );\n    } else {\n      log(\n        `[reputation-oracle] Argus fetch failed (${agentDid}): ${String(cause)}; using baseline ${baseline}`\n      );\n    }\n    return baseline;\n  } finally {\n    clearTimeout(timer);\n  }\n\n  if (!response.ok) {\n    log(\n      `[reputation-oracle] Argus HTTP ${response.status} (${agentDid}); using baseline ${baseline}`\n    );\n    return baseline;\n  }\n\n  let body: unknown;\n  try {\n    body = await response.json();\n  } catch (cause) {\n    log(\n      `[reputation-oracle] Argus response not JSON (${agentDid}): ${String(cause)}; using baseline ${baseline}`\n    );\n    return baseline;\n  }\n\n  if (body === null || typeof body !== 'object') {\n    log(\n      `[reputation-oracle] Argus response not an object (${agentDid}); using baseline ${baseline}`\n    );\n    return baseline;\n  }\n  const score = (body as Record<string, unknown>).score;\n  if (typeof score !== 'number' || !Number.isFinite(score)) {\n    log(\n      `[reputation-oracle] Argus score not a finite number (${agentDid}): ${String(score)}; using baseline ${baseline}`\n    );\n    return baseline;\n  }\n  if (score < 0 || score > 1) {\n    log(\n      `[reputation-oracle] Argus score out of range (${agentDid}): ${score}; using baseline ${baseline}`\n    );\n    return baseline;\n  }\n  return score;\n}\n","/**\n * Clock adapter — sub-phase B.5.\n *\n * Provides the Unix-seconds timestamp the engine's `Clock` trait needs\n * for Stage 4 expiration checks. Trivial; the trait shape exists so\n * tests can inject a frozen clock (and so the engine's sync-trait\n * surface is satisfied without a JS callback crossing the WASM\n * boundary — `ContextSpec.nowUnix` carries the value).\n */\n\nexport interface ClockAdapter {\n  nowUnix(): number;\n}\n\nexport function makeSystemClock(): ClockAdapter {\n  return { nowUnix: () => Math.floor(Date.now() / 1000) };\n}\n\nexport function makeFixedClock(unixSeconds: number): ClockAdapter {\n  return { nowUnix: () => unixSeconds };\n}\n","/**\n * The resolution warmer of a persistent host (Express): a cache-only\n * resolution host plus the background work that keeps it filled.\n *\n * The request path never fetches. The orchestrator answers the engine's needs\n * from `warmer.host`: a cached DID document or verified status list,\n * `pending` until the first fetch attempt (which a miss starts right away),\n * or the last attempt's failure. A `pending` DID document gives\n * `kyaos/identity-pending` (503, `Retry-After: 1`), so the client's retry\n * usually finds the document fetched.\n *\n * `prime()` registers the configured roots' DID documents (the engine's\n * `rootNeeds`) and fetches them; `refreshTick()` re-reads the roots and\n * refreshes every entry ahead of its maximum age. The roots come from the\n * per-project policy through `rootsSource`, re-read each tick, so a policy\n * edit takes effect within one interval.\n */\n\nimport type { RootNeedsResult } from '../types';\nimport { makeResolutionHost, type ResolutionEngine, type ResolutionHost } from './resolution-host';\n\n/** How often the background refresh runs. */\nexport const RESOLUTION_REFRESH_INTERVAL_MS = 30_000;\n\n/** The engine calls a warmer makes: the roots' needs, and status-list verification. */\nexport interface ResolutionWarmerEngine extends ResolutionEngine {\n  rootNeeds(contextJson: string): RootNeedsResult | Promise<RootNeedsResult>;\n}\n\nexport interface ResolutionWarmerOptions {\n  /** Reads the current trusted-delegation roots (the per-project policy roots). */\n  rootsSource: () => Promise<readonly string[]>;\n  /** The orchestrator entry's `resolutionEngine`. */\n  engine: ResolutionWarmerEngine;\n  /**\n   * Replaces the default transport (`safeGet`). It must connect only to a\n   * vetted public address, refuse redirects, cap the body and enforce a\n   * deadline.\n   */\n  fetch?: typeof fetch;\n  /** Epoch milliseconds. Defaults to `Date.now`. */\n  now?: () => number;\n  logger?: (msg: string) => void;\n}\n\n/** The persistent-host control surface over the warmer's host. */\nexport interface RunnableResolutionWarmer {\n  /** The cache-only host to pass as `VerifyRequestOpts.resolutionHost`. */\n  readonly host: ResolutionHost;\n  /** True once the first {@link prime} has completed. */\n  readonly primed: boolean;\n  /** Register and fetch the configured roots once, then mark {@link primed}. Never throws. */\n  prime(): Promise<void>;\n  /** Re-read the roots and refresh every entry that is due. Never throws. */\n  refreshTick(): Promise<void>;\n  /** prime(), then refreshTick every `intervalMs`. Returns a stop handle. Idempotent. */\n  start(intervalMs?: number): () => void;\n  /** Clear the refresh timer (if any). */\n  stop(): void;\n}\n\nexport function makeResolutionWarmer(options: ResolutionWarmerOptions): RunnableResolutionWarmer {\n  const log = options.logger ?? (() => {});\n  const host = makeResolutionHost({\n    mode: 'cache-only',\n    fetch: options.fetch,\n    now: options.now,\n    logger: options.logger,\n  });\n  let primed = false;\n  let timer: ReturnType<typeof setInterval> | null = null;\n\n  async function syncRoots(): Promise<void> {\n    let roots: readonly string[];\n    try {\n      roots = await options.rootsSource();\n    } catch (err) {\n      log(`[Checkpoint] warmer rootsSource failed: ${errMsg(err)}`);\n      return;\n    }\n    let result: RootNeedsResult;\n    try {\n      result = await options.engine.rootNeeds(JSON.stringify({ trustedDelegationRoots: roots }));\n    } catch (err) {\n      log(`[Checkpoint] warmer rootNeeds failed: ${errMsg(err)}`);\n      return;\n    }\n    if ('error' in result) {\n      log(`[Checkpoint] warmer rootNeeds refused the roots: ${result.error}`);\n      return;\n    }\n    host.setRoots(result.needs);\n  }\n\n  async function refreshTick(): Promise<void> {\n    await syncRoots();\n    await host.refresh(options.engine);\n  }\n\n  async function prime(): Promise<void> {\n    await refreshTick();\n    primed = true;\n  }\n\n  function start(intervalMs: number = RESOLUTION_REFRESH_INTERVAL_MS): () => void {\n    // Kick the initial prime off-thread (don't block the caller's construction).\n    void prime();\n    if (timer === null) {\n      timer = setInterval(() => void refreshTick(), intervalMs);\n      // Don't keep the Node event loop alive solely for the refresh tick.\n      (timer as { unref?: () => void }).unref?.();\n    }\n    return stop;\n  }\n\n  function stop(): void {\n    if (timer !== null) {\n      clearInterval(timer);\n      timer = null;\n    }\n  }\n\n  return {\n    host,\n    get primed() {\n      return primed;\n    },\n    prime,\n    refreshTick,\n    start,\n    stop,\n  };\n}\n\nfunction errMsg(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n","/**\n * The default `verifyRequest` options a host passes for every request: the\n * engine's I/O adapters plus its fixed settings. Express, Next.js and\n * `detectAgent` build them here, so a change to a default lands everywhere at\n * once. Per-request fields (`trustedDelegationRoots` for one credential,\n * `waitUntil`) are added by the caller on top.\n */\n\nimport type { EngineConfig, EnforcementMode } from '../types';\nimport type { ClockAdapter } from './clock';\nimport type { ReputationOracleAdapter } from './reputation-oracle';\nimport type { ResolutionHost } from './resolution-host';\n\nimport { makeSystemClock } from './clock';\nimport { makeReputationOracle } from './reputation-oracle';\nimport { makeResolutionHost } from './resolution-host';\n\n/** Host-supplied adapters that replace the defaults (advanced use and tests). */\nexport type EngineAdapterOverrides = Partial<{\n  /**\n   * The `fetch` DID documents and status lists are fetched with, instead of\n   * the default `safeGet` transport. It must connect only to a vetted public\n   * address (check every resolved address, including after DNS, and never\n   * re-resolve), refuse redirects, cap the body and enforce a deadline: the\n   * connect-time address check is then the caller's job. `safeGet`,\n   * `makeSafeLookup` and `isBlockedIpAddress` (`./adapters`) are the pieces\n   * the default uses. Edge and Workers runtimes have no connect hook, so there\n   * the platform's egress rules keep a fetch off private addresses.\n   */\n  fetch: typeof fetch;\n  reputationOracle: ReputationOracleAdapter;\n}>;\n\nexport interface EngineDefaultsOptions {\n  /** @deprecated No longer used; will be removed. */\n  tenantHost?: string;\n  /** Defaults to `'enforce'`. */\n  enforcementMode?: EnforcementMode;\n  adapters?: EngineAdapterOverrides;\n  /** Reputation service base URL, for the default reputation oracle and the engine. */\n  argusUrl?: string;\n  resourceOrgDid?: string;\n  trustedDelegationRoots?: string[];\n  /** Defaults to `false`. */\n  legacyEnvelopeFallback?: boolean;\n  engineConfig?: EngineConfig;\n}\n\n/**\n * The options `makeEngineDefaults` sets: the part of `VerifyRequestOpts` that\n * does not change per request. Declared here rather than taken from the\n * orchestrator's types, which import this directory.\n */\nexport interface EngineDefaults {\n  /** An inline resolution host; a persistent host swaps in its warmer's cache-only host. */\n  resolutionHost: ResolutionHost;\n  reputationOracle: ReputationOracleAdapter;\n  clock: ClockAdapter;\n  /** @deprecated No longer used; will be removed. */\n  tenantHost?: string;\n  enforcementMode: EnforcementMode;\n  legacyEnvelopeFallback: boolean;\n  resourceOrgDid?: string;\n  trustedDelegationRoots?: string[];\n  argusUrl?: string;\n  engineConfig?: EngineConfig;\n}\n\nexport function makeEngineDefaults(options: EngineDefaultsOptions): EngineDefaults {\n  const overrides = options.adapters ?? {};\n  return {\n    resolutionHost: makeResolutionHost({ mode: 'inline', fetch: overrides.fetch }),\n    reputationOracle:\n      overrides.reputationOracle ?? makeReputationOracle({ argusUrl: options.argusUrl }),\n    clock: makeSystemClock(),\n    enforcementMode: options.enforcementMode ?? 'enforce',\n    legacyEnvelopeFallback: options.legacyEnvelopeFallback ?? false,\n    // Optional settings are present only when set, so an unset one cannot\n    // shadow the orchestrator's own default.\n    ...(options.tenantHost !== undefined ? { tenantHost: options.tenantHost } : {}),\n    ...(options.resourceOrgDid !== undefined ? { resourceOrgDid: options.resourceOrgDid } : {}),\n    ...(options.trustedDelegationRoots !== undefined\n      ? { trustedDelegationRoots: options.trustedDelegationRoots }\n      : {}),\n    ...(options.argusUrl !== undefined ? { argusUrl: options.argusUrl } : {}),\n    ...(options.engineConfig !== undefined ? { engineConfig: options.engineConfig } : {}),\n  };\n}\n"],"mappings":";;AAyDA,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AAEzB,SAAgB,qBAAqB,OAA6B,CAAC,GAA4B;CAC7F,MAAM,WAAW,KAAK;CACtB,MAAM,YAAY,KAAK,kBAAkB;CACzC,MAAM,QAAQ,KAAK,SAAS;CAC5B,MAAM,YAAY,KAAK,SAAS;CAChC,MAAM,WAAW,KAAK,2BAA2B;CACjD,MAAM,QAAQ,KAAK,yBAAS,IAAI,IAAwB;CACxD,MAAM,MAAM,KAAK,cAAc,KAAK,IAAI;CACxC,MAAM,MAAM,KAAK,iBAAiB,CAAC;CAEnC,OAAO,EACL,MAAM,MAAM,UAAmC;EAC7C,MAAM,SAAS,MAAM,IAAI,QAAQ;EACjC,IAAI,UAAU,IAAI,IAAI,OAAO,YAAY,OACvC,OAAO,OAAO;EAGhB,IAAI,CAAC,UAGH,OAAO;EAGT,MAAM,QAAQ,MAAM,iBAAiB,UAAU,UAAU,WAAW,WAAW,UAAU,GAAG;EAC5F,MAAM,IAAI,UAAU;GAAE;GAAO,WAAW,IAAI;EAAE,CAAC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