import { DetectionDetail, DetectionDetail as DetectionDetail$1, IpRoutingType, McpIPayload, McpIPayload as McpIPayload$1, ProxyAssertion, ProxyCollectionState, TraceStep } from "@kya-os/checkpoint-shared"; //#region src/engine/adapters/status-list-cache.d.ts /** * The engine's status-list verifier, as a resolution host calls it: the host * fetches a credential's signed status list (and its issuer's DID document) * and hands both to `verifyStatusList`, which checks the signature against * the issuer's `assertionMethod` key, the URL, purpose, validity and the * signed `encodedList`. Nothing is decoded or trusted on the host side; a * list the engine rejects fails closed. */ /** The engine's `verifyStatusList` result. */ type StatusListVerification = { ok: true; envelope: 'StatusList2021' | 'BitstringStatusList'; /** The bare list URL: the `ContextSpec.revoked` key. */ url: string; issuer: string; issuedAt: number; /** Unix seconds; the list must not be used at or after this instant. */ expiresAt: number; setIndices: number[]; } | { ok: false; code: string; message: string; }; /** * The engine's `verifyStatusList` export: sync on the node and bundler * builds, async on the edge build (its wasm loads lazily). */ type StatusListVerifier = (requestJson: string) => StatusListVerification | Promise; //#endregion //#region src/engine/types.d.ts /** * What the edge engine can be instantiated from. On Cloudflare Workers this * must be the `WebAssembly.Module` wrangler hands over for a static import of * `@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-web/kya_os_engine_bg.wasm`. */ type EngineWasmSource = WebAssembly.Module | URL | string | Request | BufferSource; interface McpIRequest { raw: number[]; payload: McpIPayload; } /** * The A2A JSON-RPC payload rides over the same HTTP transport an RFC 9421 or * JWT-bearer signature covers, so the shape mirrors {@link HttpSignedRequest} * rather than carrying only `raw` bytes — see * `docs/architecture/a2a-verification.md`. */ interface A2ARequest { raw: number[]; method: string; path: string; headers: Array<[string, string]>; body?: number[] | null; remoteIp?: string | null; } interface A2PRequest { raw: number[]; } interface HttpSignedRequest { raw: number[]; method: string; path: string; headers: Array<[string, string]>; /** * The request body exactly as the client sent it. The KYA HTTP Binding * (`kya=`, `tag="kya-http/2"`) recomputes the RFC 9530 `Content-Digest` * over these bytes, so a body-carrying signed request that omits them is * refused as `kyaos/invalid-signature`. The vendor `sig1` path never reads * it. Mirrors the Rust `HttpSignedRequest::body`. */ body?: number[] | null; /** * Client IP resolved by the host's own trust policy (#4794), mirroring * {@link PlainHttpRequest.remoteIp}. The engine never derives an address * from `headers`, so without this it has none. */ remoteIp?: string | null; /** * Mirrors {@link PlainHttpRequest.signals}. A verified signature never * reads them; a signature that fails or is skipped falls through to * classification with them, exactly as the same request unsigned. */ signals?: SignalsEnvelope | null; /** Mirrors {@link PlainHttpRequest.sessionVelocity}, read on the same * fall-through as `signals`. */ sessionVelocity?: SessionVelocitySignal | null; } /** * Reserved ahead of the full signal-versioning registry — a tier * cannot be backfilled onto historical records once collected without * one. Nothing assigns this yet. */ type StabilityTier = 'high' | 'medium' | 'low'; /** One client-collected attribute: a value digest plus its (currently unassigned) stability tier. */ interface ClientSignalAttribute { value: string; stabilityTier?: StabilityTier | null; } /** * Transport-layer fingerprint from the terminating proxy. `tlsJa4` * sorts extensions before hashing (unlike a raw extensions digest), * so it survives Chrome's TLS-extension-order shuffling. * * `cfBotScore`/`cfVerifiedBot`/`asn`/`asOrganization` (roadmap item 2, * spoofed-browser-api-bots PROMPT.md) are Cloudflare bot-management/ASN * fields resolved via `resolveBotSignals` (`@kya-os/checkpoint-shared`) — * never read off `request.cf` directly, and never forwarded as a header * between two different request objects (the exact class of bug PR #4269 * shipped and #4282 reverted same-day). `cfBotScore` is pre-normalized: * Cloudflare's `0` ("Bot Management did not run") is absent here, never a * real score, only 1-99 are real values. These four fields are Noisy-OR * combiner inputs (shadow confidence, persisted evidence). They move the * live verdict under `NoisyOrShadowMode`'s `'live'` mode, the default: * omit `noisyOrCalibration` to inherit the engine's embedded curve, or * pass `null` to fail closed to the static table instead. * * `tlsCiphersSha1`/`tlsExtensionsSha1` (SW-P20) are Cloudflare's raw TLS * client cipher-suite / extension-list hashes, present on every zone * regardless of Bot Management, unlike `tlsJa4`, which requires it. * `tlsExtensionsSha1` is order-dependent (Chrome has shuffled TLS extension * order since early 2023) and is therefore NOT a stable per-client identity * key for browser traffic; both are safe as static non-browser-tool * deny-list keys in the engine, the same rationale `tlsJa4`'s own deny * table already relies on. */ interface TransportSignals { tlsJa4?: string | null; /** Akamai HTTP/2 fingerprint from the terminating proxy. */ http2Fingerprint?: string | null; httpProtocol?: string; tlsVersion?: string | null; cfBotScore?: number | null; cfVerifiedBot?: boolean | null; asn?: number | null; asOrganization?: string | null; tlsCiphersSha1?: string | null; tlsExtensionsSha1?: string | null; } /** * Client-collected entropy, per attribute rather than one blob — a * single opaque hash cannot be weighted or debugged when it moves. */ interface ClientSignals { attributes: Record; } /** Interaction dynamics collected client-side. */ interface BehaviouralSignals { mouseMovements?: number | null; clickCount?: number | null; /** Percentage, 0-100. */ scrollDepthPercent?: number | null; timeOnPageMs?: number | null; /** Count of key presses observed on the page. */ keyEvents?: number | null; /** Count of touch events observed on the page. */ touchEvents?: number | null; } /** * Host-verified client-integrity facts for a browser request (the pixel and * beacon ingest): the host's own beacon nonce check, and the session verdict * of the host's interaction-integrity scorer or its latch. Deliberately NOT a * field of {@link SignalsEnvelope}, which carries what the client reported: * these are the host's findings about that client. A failed nonce classifies * the request as a bot; an `agent-driven` verdict keeps it from being called * human. `verdict` is a string so a newer scorer vocabulary never fails * verification: a value the engine doesn't know counts as absent. */ interface ClientIntegrityInput { nonceFailed?: boolean | null; verdict?: 'agent-driven' | 'human' | 'insufficient' | (string & Record) | null; scorerVersion?: number | null; } /** Coarse network-path classification for a request's `trueIp`. */ type RoutingType = 'residential' | 'mobile' | 'datacenter' | 'hosting' | 'unknown'; /** Coarse proxy/anonymization category, when {@link ProxyInfo.isProxy} is true. */ type ProxyType = 'vpn' | 'tor' | 'datacenter' | 'residential_proxy' | 'unknown'; /** Host-supplied proxy/anonymization verdict for a request's `trueIp`. */ interface ProxyInfo { isProxy: boolean; proxyIp?: string | null; proxyType: ProxyType; lastDetected?: number | null; /** Provider confidence in the proxy verdict, `0..=100`. */ confidence: number; } interface IpReputation { attackSource?: boolean; spamSource?: boolean; lists: readonly string[]; asOf: number; } /** * Host-supplied network / IP-intelligence context for a request's `trueIp`. * Absent-safe like the other {@link SignalsEnvelope} families: a request with * no network context is the normal case, not an error. Echoed verbatim on * {@link VerifyResult.network} and exposed to Cedar as `context.ip_routing_type` * / `context.is_proxy` only when supplied. */ interface NetworkContext { trueIp?: string | null; asn?: number | null; isp?: string | null; routingType: RoutingType; proxy?: ProxyInfo | null; /** * TypeScript-host evidence, retained in detection rows and extended API read-back. * Older Rust readers do not echo these additive fields. */ proxyAssertions?: readonly ProxyAssertion[]; proxyCollectionState?: ProxyCollectionState; ipRoutingType?: IpRoutingType; ipReputation?: IpReputation; } /** * Optional entropy signals accompanying a {@link PlainHttpRequest}. * Absent-safe at every level — a request with no signals is the * normal case at the gateway, not an error. */ interface SignalsEnvelope { transport?: TransportSignals | null; client?: ClientSignals | null; behavioural?: BehaviouralSignals | null; network?: NetworkContext | null; } /** * Edge-computed request-velocity heuristic for the current client within * a rolling window (gateway-session-velocity). **Deliberately NOT a * field of {@link SignalsEnvelope}** — unlike that envelope, this input * also drives the (default-off) dormant-escalation reclassification in * `api.rs`. SW-P40: confidence/weight now scale with * `requestCountInWindow` (a documented first-pass linear ramp up to a * fixed ceiling) * instead of the flat `UNCALIBRATED_CONFIDENCE`/`UNCALIBRATED_WEIGHT` * (0) the envelope's three producers still use: bestbrian's #4897 * review found the gateway counted every proxied sub-resource (now * fixed), which is what made a real confidence safe to stamp. Mirrors * the Rust `kya_os_engine::types::SessionVelocitySignal`. */ interface SessionVelocitySignal { /** Requests observed from this client within `windowSeconds`. */ requestCountInWindow: number; windowSeconds: number; /** `requestCountInWindow` normalized to a per-minute rate, when cheap * to compute. Omit if not computed. **If supplied, it MUST equal * `requestCountInWindow * 60 / windowSeconds`** (the engine's own * `session_velocity_rate` derives that same value and rejects the WHOLE * signal — not just this field — when a supplied rate disagrees by more * than 0.01; rust/crates/kya-os-engine/src/api.rs). In particular, do NOT * compute this from actual elapsed wall-clock time while reporting a * fixed `windowSeconds` — the two will disagree for almost every real * request (SW-P42 fixed exactly this bug in the gateway producer). When * in doubt, omit it and let the engine derive the rate itself. */ requestsPerMinute?: number | null; } interface PlainHttpRequest { raw: number[]; method: string; path: string; headers: Array<[string, string]>; userAgent?: string | null; remoteIp?: string | null; signals?: SignalsEnvelope | null; /** See {@link SessionVelocitySignal}. Additive; omit when the host * hasn't wired an edge tracker. */ sessionVelocity?: SessionVelocitySignal | null; /** See {@link ClientIntegrityInput}. Additive; omit when the host runs no * client-integrity checks. */ clientIntegrity?: ClientIntegrityInput | null; } type AgentRequest = { protocol: 'McpI'; request: McpIRequest; } | { protocol: 'A2A'; request: A2ARequest; } | { protocol: 'A2P'; request: A2PRequest; } | { protocol: 'HttpSigned'; request: HttpSignedRequest; } | { protocol: 'PlainHttp'; request: PlainHttpRequest; }; type BlockReason = { kind: 'Revoked'; } | { kind: 'InvalidSignature'; } | { kind: 'Unauthenticated'; } | { kind: 'Expired'; } | { kind: 'OutOfScope'; requested: string; granted: string[]; } | { kind: 'LowReputation'; score: number; threshold: number; } | /** * `policyId` (#3272 PR2): the determining policy's authored Cedar `@id` * annotation — the stable join key into the `policies` index. Optional + * additive; absent on pre-PR2 engines, deny-by-default, and `@id`-less * policies. */ { kind: 'PolicyDenied'; detail: string; policyId?: string; } | { kind: 'ParseError'; detail: string; } | /** * Tier-2 IP+UA cross-match against the vendor SSOT (AIVF-1 Path B * / agent-shield#2639). Emitted by `TieredPolicy` when the request * carries both a vendor-published IP and a matching UA pattern. * `tier` is the tier ordinal (`2` for IP+UA cross-match today; * reserved for future Tier-1 cryptographic attribution). * `confidence` is f32 in `[0.0, 1.0]`. */ { kind: 'AgentAttribution'; vendor: string; tier: number; confidence: number; } | /** * Tier-3 UA-only pattern match short-circuit (Engine-Tier3- * Ruleset-Wiring-1 / agent-shield#2641). Emitted at Stage 1b when * `EngineConfig.tier3_action == Block` and the request classifies * as KnownAiAgent / AiCrawler / HeadlessBrowser. **Field names are * snake_case on the wire** (no `rename_all` on the Rust enum) — * they mirror the Rust struct field names verbatim. */ { kind: 'Tier3UAMatch'; pattern_id: string; pattern_kind: string; confidence: number; }; interface ChallengeParams { nonce: string; audience: string; expiresAt: number; algorithmsAccepted: string[]; /** Minimum assurance tier demanded by the determining policy. */ minAssurance?: 'anonymous' | 'attested-bearer' | 'key-bound' | 'registered' | 'delegated'; /** Determining policy's authored Cedar `@id` (#3272 PR2). Optional + additive. */ policyId?: string; /** * Which handshake this challenge demands, set by a Cedar * `@challenge_type(...)` annotation. Known values today: `'delegation'` * (the pre-existing MCP-I Level 2+ handshake) | `'browser_integrity'` | * `'human_step_up'`. Kept a loose `string` (like the shared * `ChallengeParamsSchema.challengeType`, not a literal union) so a FUTURE * engine-added kind this host doesn't know yet stays additive rather than * a type mismatch. Absent means `'delegation'`. **Every renderer MUST * treat an absent or unrecognized value as `'delegation'`** — fail closed * to the handshake it already understands, never throw or silently drop * the challenge. See `normalizeChallengeType` in `@kya-os/checkpoint-shared`. */ challengeType?: string; } interface RedirectTarget { url: string; reason: string; state?: string | null; /** Determining policy's authored Cedar `@id` (#3272 PR2). Optional + additive. */ policyId?: string; } type SuggestedAction = { kind: 'UseDifferentScope'; scope: string; } | { kind: 'UpdateRequestField'; field: string; acceptedValues: string[]; } | { kind: 'UpgradeProtocolVersion'; version: string; } | { kind: 'Other'; code: string; detail: string; }; interface InstructPayload { problem: string; title: string; suggestedActions: SuggestedAction[]; /** Determining policy's authored Cedar `@id` (#3272 PR2). Optional + additive. */ policyId?: string; } type Decision = /** * `policyId` (#3272 PR2): the authored Cedar `@id` of the determining * permit policy — "which rule admitted this". Absent on pre-PR2 engines * and non-policy-determined permits. */ { kind: 'Permit'; policyId?: string; } | { kind: 'Block'; reason: BlockReason; } | { kind: 'Challenge'; params: ChallengeParams; } | { kind: 'Redirect'; target: RedirectTarget; } | { kind: 'Instruct'; payload: InstructPayload; }; type EnforcementMode = 'enforce' | 'observe'; interface EngineInfo { name: string; version: string; rulesetHash: string; rulesetVersion: string; buildSha?: string; extras?: Record; } /** * The standalone bearer delegation (`Authorization: Bearer `) an * orchestrator observed on the request, independent of what the engine's own * `detectionDetail.metadata` chose to stamp (KYA-1099 W1). TS-host-composed, * like `composedBlobHash` above — never produced by the Rust ABI itself. * * Kept separate from the engine-metadata-derived identity the reporter * already builds (`buildReportedIdentity` in `reporter/index.ts`, sourced * from `metadata.agent_did` / `metadata.kya_session_id`) rather than folded * into it here: that mechanism is sid-gated (kya-http/2 registered * sessions) and doesn't carry a delegation `jti`. This field is the carrier * for the case that mechanism misses — a plain bearer delegation with no * `sid` claim — and the reporter merges the two (see `buildReportedIdentity` * doc comment) rather than one replacing the other. */ interface BearerDelegationIdentity { /** The delegation credential's `sub` claim, when present. */ agentDid?: string; /** * The delegation credential's handle: `vc.id`, else its `jti` claim. The * reported wire field keeps the name `jti`. */ jti?: string; /** The delegation credential's `iss` claim, when present. */ iss?: string; /** Whether `verifyDelegation` (or the request's overall decision, after any fail-closed demotion) resolved to `Permit`. */ verified: boolean; } interface VerifyResult { decision: Decision; detectionDetail: DetectionDetail; enforcementMode: EnforcementMode; engineInfo: EngineInfo; /** Per-stage trace from the engine (Layer 1 / #3164). Optional — absent on WASM builds predating this field. */ trace?: TraceStep[]; /** * Revision pin for the composed bundle that produced `decision` (#3246 * PR5): the SSOT-served sha256, set by the middleware when the composed * path ACTED (see checkpoint-express composed-policy apply). The reporter * copies it into `enforcement.composedBlobHash`; joins * `policy_revisions (project_id, policy_id, composed_blob_hash)`. */ composedBlobHash?: string; /** * Set by `verifyRequestEdge` (KYA-1099 W1) when the request carried a * standalone bearer delegation. Absent otherwise — every existing caller * that never sees a bearer delegation is unaffected. See * {@link BearerDelegationIdentity}. */ bearerDelegationIdentity?: BearerDelegationIdentity; /** * Echo of the host-supplied {@link NetworkContext}, when the request * carried one (`PlainHttpRequest.signals.network`). Absent on every * other protocol and on any `PlainHttp` request that supplied none. */ network?: NetworkContext | null; /** * The vendor-key miss this verify raised, already recorded in the * engine's own feed state. A host that runs its vendor-key feed on another * engine instance passes it unchanged to that instance's `feedNoteMiss`; * this package runs one instance and needs nothing. Absent when the verify * raised none. */ vendorKeyMiss?: VendorKeyMiss; } type KeyType = 'Ed25519'; interface VerificationMethod { id: string; keyType: KeyType; publicKeyBytes: number[]; } interface DidDocument { id: string; verificationMethods: VerificationMethod[]; } /** * The verifiable subset of an A2A Agent Card's `securitySchemes`, already * selected and resolved by the host — see * `docs/architecture/a2a-verification.md`. Mirrors the Rust * `AgentCardSecurityScheme` enum's internally-tagged wire format. */ type AgentCardSecurityScheme = { kind: 'httpMessageSignatures'; keyid: string; } | { kind: 'jwtBearer'; keys: VerificationMethod[]; } | { kind: 'unverifiable'; }; /** A resolved A2A Agent Card. Mirrors the Rust `AgentCard` struct. */ interface AgentCard { name: string; providerOrganization?: string; securityScheme: AgentCardSecurityScheme; } interface ContextSpec { didDocs?: Record; /** * Agent Cards the host already resolved (fetched + reduced), keyed by * origin (`https://scheme-and-authority`, no path) — `AgentRequest.A2A` * only. An origin absent from this map fails closed identically to * omitting the field entirely; see `docs/architecture/a2a-verification.md`. * * bestbrian, PR #4987 review 2 P3: keys MUST be the canonical origin the * Rust engine's `canonical_a2a_origin` produces (lowercased, `https://`, * no trailing `/`, no default `:443` port, no userinfo) — the same form * `agent-card-resolver.ts`'s `normalizeOrigin` already keys its own * cache on. A resolver (in any language) that populates this map with * the raw, un-normalized origin fails every A2A lookup silently, * indistinguishable from a genuinely unreachable card. The engine also * caps every card's `name`/`providerOrganization` at 128 chars on its * own deserialization boundary, on top of (never instead of) * `reduceCard`'s cap here. */ agentCards?: Record; revoked?: Record; reputation?: Record; tenantDecision: Decision; nowUnix: number; enforcementMode: EnforcementMode; /** * Engine-default behaviour knobs. Omit, or pass `{}`, to take the * customer-onboarding-safe defaults (Tier-3 in Monitor mode — * tenant policy is the arbiter). See [`EngineConfig`]. */ config?: EngineConfig; /** * Allow-list of trusted Layer-2 delegation root DIDs, forwarded to the * engine's `trusted_delegation_roots`. Empty/omitted ⇒ the engine rejects every * presented delegation (fail closed). The host * resolves this (see `resolveTrustedDelegationRoots` in * `@kya-os/checkpoint-shared`); the runtime never derives it. camelCase * matches the Rust `#[serde(rename_all = "camelCase")]` wire key. */ trustedDelegationRoots?: string[]; /** * This resource server's own org DID — the audience a * DelegationCredential must name on the standalone bearer path * (`engineVerifyDelegation`, `draft-kya-http-02` §4.3(2)). Optional; * absent ⇒ the bearer path fails closed (`kyaos/audience-mismatch`). * Unused by `engineVerify`. */ resourceOrgDid?: string; /** Resource-owned HTTP agent-lane requirements, never copied from request headers. */ httpDelegation?: { resourceDid: string; requiredScopes: string[]; /** Trusted configured HTTPS authority (including non-default port), required for native propagation. */ resourceAuthority?: string; }; /** * `'engine-directed'`: the engine names every DID document and status list * the request needs and reads them only from `resources`; `didDocs` and * `revoked` are ignored. Absent, the host supplies them up front. */ resolution?: ResolutionMode; /** The host's answer to each need, keyed by the need's `key` (engine-directed only). */ resources?: Record; } type ResolutionMode = 'engine-directed'; type NeedKind = 'did-document' | 'status-list'; /** * Where a need came from: a configured trusted root's DID document, a status * list named after the trust gates passed, or any other DID the request named. */ type NeedRole = 'root' | 'issuer' | 'presenter'; /** One resource the engine needs before it decides. */ interface Need { /** `":"`; answers, caches and in-flight fetches are keyed by it. */ key: string; kind: NeedKind; /** The HTTPS URL to fetch, built by the engine. */ url: string; role: NeedRole; /** Largest response body to accept, in bytes. */ maxBytes: number; /** Age, in seconds, up to which an answer is fresh. */ maxAgeSeconds: number; /** Age up to which a DID document is still accepted while its refresh is failing; 0 for status lists. */ maxStaleSeconds: number; /** The DID whose document this is (`did-document` only). */ did?: string; /** The DID that must have signed the list (`status-list` only). */ issuer?: string; /** The list's expected `statusPurpose` (`status-list` only). */ purpose?: string; } /** A verified status list: what `verifyStatusList` returned with `ok: true`. */ interface StatusListRecord { url: string; issuer: string; issuedAt: number; expiresAt: number; setIndices: number[]; } /** Why a host could not answer a need. */ type ResourceFailureDetail = 'timeout' | 'http-status' | 'too-large' | 'unsafe-address' | 'network' | 'rejected'; /** The host's answer to one need. */ type ResourceOutcome = { ok: true; body: string; fetchedAtUnix: number; lastRefreshFailed: boolean; } | { ok: true; record: StatusListRecord; fetchedAtUnix: number; } | { ok: false; reason: 'pending'; } | { ok: false; reason: 'failed'; detail: ResourceFailureDetail; }; /** An engine-directed verify: the decision, or the needs to answer first. */ type DirectedVerifyResult = VerifyResult | { needs: Need[]; }; /** The engine's `rootNeeds` answer: the trusted roots' DID-document needs. */ type RootNeedsResult = { needs: Need[]; } | { error: string; }; /** * Input to the standalone Layer-2-only delegation-verify entry * (`engineVerifyDelegation`, `draft-kya-http-02` §4.1/§4.3). Header-agnostic: * the host extracts the VC-JWT from wherever it arrived (`Authorization: * Bearer`, the `KYA-Delegation:` fallback, the optional `KYA-OS-*` headers, or * an MCP param) and passes it in. Mirrors the Rust `DelegationVerifyInput`. */ interface DelegationVerifyInput { /** The DelegationCredential as a JWS-compact VC-JWT (§4.2 claims profile). */ credential: string; /** * The scopes this action requires — the WHOLE set (§4.3(3) is granted ⊇ * required). The credential's granted scopes MUST include every entry, else * `kyaos/scope-insufficient`. Empty set asserts nothing (passes). */ requiredScopes: string[]; /** * Opt-in `@min_assurance(...)` floor (draft-kya-http-02 §1/§8). When set, a * verified credential whose achieved assurance tier is BELOW this floor is * denied (`kyaos/assurance-insufficient`) — a bearer credential * (`attested-bearer`, no proof-of-possession) cannot satisfy a `key-bound`+ * floor (trust-gap G3). Absent = no floor = permit-any-verified (legacy). * Mirrors the Rust `required_min_assurance` (wire: `requiredMinAssurance`). */ requiredMinAssurance?: string; } /** * Engine-default behaviour knobs the host can opt into. Mirrors the * Rust `kya_os_engine::EngineConfig` shape; deserialised by the WASM * glue with `#[serde(default)]` so an absent / empty `config` resolves * to the safe defaults. */ interface EngineConfig { /** * Tier-3 (UA-only pattern match) engine-default action. Defaults to * `'monitor'` — Stage 1 classification flows through to the tenant * policy evaluator, but the engine does NOT short-circuit with its * own `Block { Tier3UAMatch }`. Set to `'block'` when the host * wants the engine to emit an engine-default block for known-agent * UAs before the tenant policy seam (e.g., the bench harness or * customers who've reviewed their traffic and want the calibrated * block without writing a tenant-policy rule). */ tier3Action?: Tier3Action; /** * O2: how the Tier 1 verified-vendor arm treats the tenant policy seam. * Defaults to `'enforcePolicy'` — a cryptographically verified vendor * still obeys the tenant's resolved decision. Set to `'bypassPolicy'` * to restore the pre-O2 immediate-permit shortcut. On WASM hosts this * knob has no per-vendor effect — `WasmConstantPolicy` echoes a * pre-resolved `tenantDecision` and ignores `PolicyEvaluationInput` * entirely, so `'enforcePolicy'` here only gates the engine's own * short-circuit, not per-vendor Cedar rules (that needs a WASM policy * seam — see `docs/architecture/D-design-ratification.md` § O2). */ tier1PolicyMode?: Tier1PolicyMode; /** * Governs Stage 1's Noisy-OR probability combiner and (since P18) * whether its score drives the live verdict. An earlier draft of the * P18 cutover deleted the static first-match-wins confidence table * this combiner replaced; that was reversed before merge. `'off'` IS * byte-identical to the pre-P16 engine: `'off'` and `'shadow'` both * use the static table for `detectionDetail.confidence`, never the * combiner's score. Only `'live'` reads the combiner, and only once a * `noisyOrCalibration` curve is configured (with no curve it fails * closed to the same static table). `'shadow'` * additionally attaches `shadow_noisy_or_confidence` / * `shadow_scoring_algorithm` (and, with a curve configured, a * `shadow_calibrated_confidence` / `shadow_calibration_method` PREVIEW * of what `'live'` would produce, without applying it) to * `detectionDetail.metadata` under those verbatim (not camelCased) * keys, see `crate::stages::scoring` on the Rust side. Defaults to * `'live'` (the engine's own `EngineConfig::default()`): omit * `noisyOrCalibration` to inherit the engine's embedded curve and move * the verdict, or pass `null` to keep the static table. Never * consulted on the Tier 1 cryptographic-verification * path — a verified signature is dispositive and short-circuits before * Stage 1 (and this flag) is ever reached. */ noisyOrShadow?: NoisyOrShadowMode; /** * A fitted Noisy-OR calibration curve, produced offline by * `apps/web/lib/services/detections/calibration` and supplied here. * Drives the live verdict only when `noisyOrShadow` is `'live'`; under * `'off'` / `'shadow'` a curve here has zero effect on * `detectionDetail.confidence` (curve-or-not, both always use the * static confidence table, never the combiner) — `'shadow'` still logs * what the curve WOULD produce as a preview. Omit it to inherit the * engine's embedded production-fitted curve * (`EMBEDDED_NOISY_OR_CALIBRATION` in `context.rs`), which is how every * runtime gets calibrated `'live'` scoring with nothing plumbed. Supply * a curve to override it. Send an explicit `null` to opt out: `'live'` * then fails closed to the static table (the same `confidence` as * `'off'` / `'shadow'`, never the combiner's raw score) and stamps * `shadow_calibration_curve_missing: true` so that degradation isn't * silent. See `crate::stages::calibration` on the * Rust side. */ noisyOrCalibration?: CalibrationCurve | null; /** * Session velocity classification for high-volume anonymous traffic * (gateway-session-velocity). **Defaults to `true`** (since SW-P42; was * `false`). When `true`, a valid signal meeting the engine's count and * normalized-rate floors produces a provisional `bot` detail with * confidence `80` before the tenant policy seam runs. It never emits an * engine-default block, and known agent attribution remains unchanged. * See the Rust `EngineConfig.session_velocity_escalation` / * `SessionVelocityEscalation` doc comments for the full contract. */ sessionVelocityEscalation?: boolean; /** * Roadmap item 2 (spoofed-browser-api-bots PROMPT.md): the narrow Option * A fix for the zero-evidence branch's Detection-Scanner-Misclassification * gap — a browser UA with strongly contradicting resolved bot-management * evidence (a real Cloudflare bot-management score at or below a low * threshold) classifies `'incomplete_data'` instead of `'human'`. * **Defaults to `'on'`** (since SW-P42; was `'off'`), same rationale as * `sessionVelocityEscalation`: evidence the engine already resolves * should not sit silently discarded by default. Even `'on'`, this only * ever produces `'incomplete_data'` — never a `bot`/`ai_agent` * classification and never an engine-default block on its own; tenant * policy still owns what, if anything, happens with the result. No SDK * caller has a way to request `'off'` through this package today (added * for type completeness — see the Rust `EngineConfig. * scanner_misclassification_hint` / `ScannerMisclassificationHint` doc * comments for the full contract and the explicit rollback path). */ scannerMisclassificationHint?: 'on' | 'off'; /** * Client-Headless-Engine-Consumption-1 (PR #5072): whether beacon- * collected automation evidence (`checkpoint-beacon`'s * `client.webdriver` / `client.headless` attributes on * {@link ClientSignals.attributes}) escalates the Stage-1 classification * bucket. **Defaults to `'on'`**, same as `sessionVelocityEscalation` * since SW-P42: a beacon-collected automation disclosure left dormant * behind an opt-in flag defeats the point of collecting it. Two tiers: * `client.webdriver === 'true'` (direct disclosure) escalates to * `headlessBrowser` at confidence 80; * `client.headless === 'true'` alone (corroborating evidence only, no * direct disclosure) escalates only to `unknown` at confidence 40 — * weak evidence alone never asserts a confident Bot verdict. Neither * tier overrides an already self-identified class or double-counts an * existing UA-based `headlessBrowser` match. Set to `'off'` to restore * pre-PR-#5072 behaviour: the raw attributes still transport and * persist either way, only the classification escalation stops. See * the Rust `EngineConfig.client_headless_escalation` / * `ClientHeadlessEscalation` doc comments for the full contract. */ clientHeadlessEscalation?: 'on' | 'off'; /** * Whether an unsigned browser request with client-reported interaction * and nothing pointing the other way classifies as `human` (confidence 85, * `detectionDetail.metadata.detection_basis` `client_interaction`). * Interaction is the engine's own reading of the behavioural counts: more * than 5 mouse moves, any click, key press or touch, or a scroll depth over * 10% of the page. **Defaults to `'on'`.** `'off'` is "human only when * proven": such requests stay `incomplete_data`. See the Rust * `EngineConfig.client_interaction_human` doc comment for the full rule. */ clientInteractionHuman?: 'on' | 'off'; /** * Whether an automation tool's default viewport (`screen.viewport` * 800x600) with reported behaviour and no interaction classifies an * unsigned browser request as a bot at confidence 70. A request without * behaviour data is never a tell. **Defaults to `'on'`.** */ clientViewportTell?: 'on' | 'off'; } /** * Tier-3 default action — `'monitor'` (default) lets tenant policy * decide; `'block'` opts into the engine-default short-circuit. */ type Tier3Action = 'monitor' | 'block'; /** * Noisy-OR scoring mode. `'off'` and `'shadow'` both drive * `detectionDetail.confidence` with the static first-match-wins * confidence table, byte-identical to the pre-P16 engine — `'shadow'` * additionally logs the combiner's score (and a calibration preview) to * metadata, without applying either to the live verdict. `'live'` (P18) * is the default and the only mode that reads the combiner for the live * verdict: it applies a configured `noisyOrCalibration` curve, and with no * curve it fails closed to the same static table. See * `EngineConfig.noisyOrShadow`'s doc comment for the full P18 history. */ type NoisyOrShadowMode = 'off' | 'shadow' | 'live'; /** * A fitted Noisy-OR calibration mapping (P17). Mirrors the Rust * `kya_os_engine::CalibrationCurve` wire shape field-for-field (internally * tagged on `method`) — which itself mirrors TS `CalibrationCurve` from * `apps/web/lib/services/detections/calibration/types.ts`. This is the * SAME shape `fitCalibration()`'s `FitCalibrationReport.curve` produces, * so a fitted curve can be passed here without translation. */ type CalibrationCurve = PlattCurve | IsotonicCurve; /** Sigmoid: `P(automated | score) = 1 / (1 + exp(a * score + b))`. */ interface PlattCurve { method: 'platt'; params: { a: number; b: number; }; } /** * Non-decreasing step function over the raw score, ordered by `minScore` * ascending. `maxScore` is informational — the engine selects by * `minScore` alone (flat, right-continuous extrapolation), matching TS * `predictIsotonic`. */ interface IsotonicCurve { method: 'isotonic'; blocks: ReadonlyArray<{ minScore: number; maxScore: number; probability: number; }>; } /** * O2 default-action knob — `'enforcePolicy'` (default) routes a Tier 1 * verified vendor through the tenant policy seam; `'bypassPolicy'` restores * the pre-O2 immediate-permit shortcut. */ type Tier1PolicyMode = 'enforcePolicy' | 'bypassPolicy'; /** Why the engine refused a bundle. Compiled-in data stays in effect. */ type RuleBundleRejectionCode = 'too-large' | 'invalid-clock' | 'malformed-envelope' | 'unsupported-envelope' | 'unknown-key' | 'key-not-valid' | 'bad-signature' | 'malformed-payload' | 'unsupported-schema' | 'expired' | 'not-yet-valid' | 'invalid-window' | 'invalid-key-set' | 'invalid-delegation' | 'invalid-version' | 'rollback' | 'invalid-ranges' | 'too-many-entries'; interface KeySetOutcome { kind: 'added' | 'extended' | 'shortened' | 'unchanged' | 'retired'; keyid: string; previousExp?: number; newExp?: number; } interface ReinstateExtendedOutcome { kind: 'extended'; keyid: string; previousExp: number; newExp: number; } interface ReinstateUnchangedOutcome { kind: 'unchanged'; keyid: string; } type ReinstateRefusalReason = 'unknown_keyid' | 'key_material_changed' | 'validity_window_changed' | 'expiry_regression' | 'malformed'; interface ReinstateRefusedOutcome { kind: 'refused'; keyid: string; reason: ReinstateRefusalReason; } type ReinstateOutcome = ReinstateExtendedOutcome | ReinstateUnchangedOutcome | ReinstateRefusedOutcome; type FeedDemandReason = 'cold-start' | 'unknown-key' | 'expired-key' | 'feed-aging'; type FeedAttemptOutcome = 'applied' | 'current' | 'failed'; type VendorKeyMissReason = 'unknown-key' | 'expired-key'; /** A vendor-key miss, in the shape `feedNoteMiss` takes. */ interface VendorKeyMiss { keyid: string; reason: VendorKeyMissReason; } interface AdoptedVendorKey { keyid: string; x: string; notBefore: number; expiresAt: number; } interface AdoptedVendorKeys { feedVersion: number | null; keys: AdoptedVendorKey[]; } interface VendorKeyFeedKeyStatus { keyid: string; notBefore: number; expiresAt: number; expired: boolean; } interface VendorKeyFeedStatus { keySource: 'feed' | 'embedded'; feedVersion?: number; issuedAt?: number; expiresAt?: number; refreshDueAt?: number; stale: boolean; pendingDemand?: FeedDemandReason; inFlight: boolean; failureStreak: number; keys: VendorKeyFeedKeyStatus[]; } /** The bundle verified and was applied (or was already in effect). */ interface RuleBundleApplied { ok: true; version: number; /** True when this exact version was already in effect and nothing changed. */ unchanged: boolean; /** Unix seconds after which the publisher considers this bundle stale. */ expiresAt: number; /** Vendors whose CIDR sets were replaced. */ ipVendorsUpdated: string[]; /** Vendors named in the bundle that this engine build does not know. */ vendorsIgnored: string[]; keyOutcomes: KeySetOutcome[]; } /** The bundle was refused; nothing was applied. */ interface RuleBundleRejected { ok: false; code: RuleBundleRejectionCode; message: string; } type RuleBundleReport = RuleBundleApplied | RuleBundleRejected; //#endregion export { RuleBundleRejectionCode as $, IsotonicCurve as A, ProxyInfo as B, EngineInfo as C, HttpSignedRequest as D, FeedDemandReason as E, Need as F, ReinstateRefusalReason as G, RedirectTarget as H, NetworkContext as I, ResourceOutcome as J, ReinstateRefusedOutcome as K, NoisyOrShadowMode as L, KeyType as M, McpIPayload$1 as N, InstructPayload as O, McpIRequest as P, RuleBundleRejected as Q, PlainHttpRequest as R, EngineConfig as S, FeedAttemptOutcome as T, ReinstateExtendedOutcome as U, ProxyType as V, ReinstateOutcome as W, RoutingType as X, RootNeedsResult as Y, RuleBundleApplied as Z, DelegationVerifyInput as _, AgentCard as a, Tier1PolicyMode as at, DirectedVerifyResult as b, BehaviouralSignals as c, VendorKeyFeedKeyStatus as ct, ChallengeParams as d, VendorKeyMissReason as dt, RuleBundleReport as et, ClientIntegrityInput as f, VerificationMethod as ft, Decision as g, ContextSpec as h, StatusListVerifier as ht, AdoptedVendorKeys as i, SuggestedAction as it, KeySetOutcome as j, IpReputation as k, BlockReason as l, VendorKeyFeedStatus as lt, ClientSignals as m, StatusListVerification as mt, A2PRequest as n, SignalsEnvelope as nt, AgentCardSecurityScheme as o, Tier3Action as ot, ClientSignalAttribute as p, VerifyResult as pt, ReinstateUnchangedOutcome as q, AdoptedVendorKey as r, StabilityTier as rt, AgentRequest as s, TransportSignals as st, A2ARequest as t, SessionVelocitySignal as tt, CalibrationCurve as u, VendorKeyMiss as ut, DetectionDetail$1 as v, EngineWasmSource as w, EnforcementMode as x, DidDocument as y, PlattCurve as z }; //# sourceMappingURL=types-BZXvyqcb.d.mts.map