openapi: 3.1.0
info:
  title: Chitmark API
  description: |
    Chitmark returns allow, challenge, or deny for costly inbound actions
    (signup, trial, and similar grants). Outcomes such as credit burn,
    conversion, and chargeback are labels for attribution, evaluation, and
    scoring calibration.

    Verbs includes `POST /v1/verify`, `POST /v1/feedback`, and `POST /v1/challenge`.
    Agent Paid Access and Agent Attribution use separate endpoints and scopes.
    Authenticate product endpoints with `Authorization: Bearer <API_KEY>`.

    - Fail to challenge, never to allow. When `degraded` is true, decision is
      always `challenge` (never silent allow on timeout or uncertainty).
    - Persist `eventId` from every verify; feedback cannot create attribution
      and joins only on that existing id (never email/IP).
    - Verify is deterministic and fast (benchmarked at single-digit-ms p50 locally, budget
      10ms p50 / 50ms p95; CI gate 60ms p50 / 120ms p95).
    - PII defaults to hashed (`piiMode: hashed`); raw is opt-in.
    - Outcomes such as `credit_burn`, conversion, and chargeback are labels joined
      for attribution, evaluation, and scoring calibration (weekly review), not a
      payments or billing product. Runs alongside your existing controls.
    - `Idempotency-Key` header and body `idempotencyKey` both dedupe verify
      and feedback retries. If both are sent, `Idempotency-Key` takes
      precedence; SDKs set both to the same value.
    - API keys may be limited to `verify:write`, `feedback:write`, and
      `challenge:write`. A key missing a verb returns `403 insufficient_scope`.
    - Challenge `session` is required for issue and completion: it uniquely
      represents one action attempt.
    - Signed `verdictToken` JWTs (ES256) carry `iss: https://api.chitmark.com`.
      Verify signatures against `GET /.well-known/jwks.json` and enforce `iss`,
      `tid` (tenant), and `sub` (session) before trusting a decision.
  version: 0.1.0
  contact:
    name: Chitmark
    url: https://chitmark.com
  license:
    name: Proprietary

servers:
  - url: https://api.chitmark.com
    description: Production

security:
  - bearerAuth: []

tags:
  - name: verify
    description: Return an action decision (allow / challenge / deny)
  - name: feedback
    description: Report outcome labels joined on eventId
  - name: challenge
    description: Add friction after a challenge or degraded verdict
  - name: ops
    description: Non-product operational surfaces

  - name: attribution
    description: Recognize scoped sessions and resolve authorized principal associations

paths:
  /health:
    get:
      operationId: health
      tags: [ops]
      summary: Health check
      description: Non-product ops surface for uptime checks.
      security: []
      responses:
        "200":
          description: Service health
          content:
            application/json:
              schema:
                type: object
                required: [ok, service]
                properties:
                  ok:
                    type: boolean
                  service:
                    type: string

  /v1/verify:
    post:
      operationId: verify
      tags: [verify]
      summary: Return an action decision
      description: |
        Deterministic and fast (benchmarked at single-digit-ms p50 locally, budget 10ms p50 /
        50ms p95; CI gate 60ms p50 / 120ms p95). Returns allow | challenge |
        deny with principal resolution, confidence, reasons, verdictToken, and
        eventId (persist on the account row for feedback).
        When degraded is true, decision is always challenge: fail to challenge,
        never to allow.
        Raw subject PII (`email`, `ip`, `formData`) is accepted only for
        tenants with explicit raw-mode opt-in. Default integrations should send
        `emailSha256`, `ipTrunc`, and `formDataHashed`.
        Limits (per tenant unless noted): free plan 10,000 verify events per
        UTC calendar month; verify burst budget per plan; challenge issue 20/min;
        feedback 60/min; key creation 10/hr. Exceeding a verify budget returns
        429 with Retry-After. Store outages return HTTP 200 with a degraded
        challenge Verdict (`degraded: true`), never HTTP 503.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/VerifyRequest"
      responses:
        "200":
          description: |
            Verdict body on HTTP 200. This includes store-outage degraded
            challenges: `degraded: true` with `decision: "challenge"`.
            Verify never returns HTTP 503 (with or without a Verdict body).
            Store uncertainty is expressed inside this 200 Verdict, not as a
            503 Error. Deserialize the body as Verdict; map degraded/challenge
            like any other challenge (partner HTTP 428, then POST /v1/challenge).
            Transport timeouts and unexpected 5xx are client-side failures:
            SDKs synthesize a local degraded challenge Verdict (never allow).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Verdict"
              examples:
                allow:
                  summary: Explicit allow
                  value:
                    decision: allow
                    actorType: agent_principal
                    confidence: 0.91
                    reasons:
                      - Valid Ed25519 Web Bot Auth signature (operator=openai)
                    principal:
                      resolved: true
                      operator: openai
                      onBehalfOf: acmecorp.com
                      identityBasis:
                        - web_bot_auth
                        - email_domain
                    verdictToken: eyJhbGciOi…
                    eventId: evt_2f9c…
                    degraded: false
                    enforcementMode: enforce
                challenge:
                  summary: Scored challenge (degraded false)
                  value:
                    decision: challenge
                    actorType: unknown
                    confidence: 0.81
                    reasons:
                      - High one-minute IP action velocity
                      - Session action velocity is elevated
                    principal:
                      resolved: false
                      identityBasis: []
                    verdictToken: eyJhbGciOi…
                    eventId: evt_8a1b…
                    degraded: false
                    enforcementMode: enforce
                degraded:
                  summary: Store-outage degraded challenge (still HTTP 200)
                  value:
                    decision: challenge
                    actorType: unknown
                    confidence: 0
                    reasons:
                      - "Degraded: decision store unavailable"
                    principal:
                      resolved: false
                      identityBasis:
                        - degraded
                    verdictToken: unsigned.evt_degraded_…
                    eventId: evt_degraded_…
                    degraded: true
                    enforcementMode: enforce
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: |
            `idempotency_conflict`: this Idempotency-Key is already associated
            with a different request payload fingerprint. Do not reuse the key;
            generate a new one for the new request.
            Verify fingerprint = SHA-256 of canonical JSON over
            `{ action, session, surface, subject, context }` (sorted object
            keys, undefined fields omitted; body `idempotencyKey` excluded).
            Key order in JSON does not matter. Also used for
            `idempotency_in_flight` while a duplicate is still reserved.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"

  /v1/feedback:
    post:
      operationId: feedback
      tags: [feedback]
      summary: Report an outcome labeled by eventId
      description: |
        Security invariant: feedback cannot create attribution. It can only
        attach an outcome label to an existing verify eventId for the
        authenticated tenant. Join only on eventId from verify; never invent a
        join from email, IP, or other subject fields. Unknown or cross-tenant
        eventIds return 404 unknown_event_id.
        Append-only observations (not latest-wins): multiple outcomes may
        attach to one eventId. Exact duplicate bodies share one feedbackId.
        Compatible labels coexist. Mutually exclusive pairs quarantine the
        new observation (kept for audit, excluded from effective ledger
        totals) without deleting prior evidence. Example: converted then
        abuse_confirmed leaves converted effective and quarantines
        abuse_confirmed. HTTP 200 `{ok:true}` still acknowledges quarantined
        ingest; do not treat 200 as "sole effective label."
        Labels (credit_burn, conversion, chargeback, multi_account_cluster,
        abuse_confirmed, …) are labeled feedback for attribution, evaluation,
        and scoring calibration; they are not a payments product. Prefer fast
        labels that close the feedback loop quickly. The pilot does not
        automatically retrain a model from these labels on the verify path.
        `Idempotency-Key` (or body `idempotencyKey`) dedupes exact retries.
        Same key + same payload fingerprint → same acknowledgement; same key +
        different fingerprint → `409 idempotency_conflict` (generate a new key
        for the new request). Keys do not create observations: warehouse
        `feedbackId` is tenantId + eventId + outcome + value + unit +
        observedAt. Same eventId + same outcome with different keys and an
        identical body collapse to one feedbackId; a different value,
        observedAt, or source is a second append-only observation.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/FeedbackRequest"
      responses:
        "200":
          description: Acknowledged
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/FeedbackResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          description: |
            `unknown_event_id`: no matching verify event for this tenant.
            Feedback cannot create attribution; fix verify-time persistence.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: |
            `idempotency_conflict`: this Idempotency-Key is already associated
            with a different request payload fingerprint. Do not reuse the key;
            generate a new one for the new request.
            Feedback fingerprint = SHA-256 of canonical JSON over
            `{ eventId, outcome, value, unit, observedAt }` (unit defaults to
            `usd`; observedAt is normalized ISO-8601). Also used for
            `idempotency_in_flight` while a duplicate is still reserved.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          description: Feedback ledger temporarily unavailable
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /v1/challenge:
    post:
      operationId: challenge
      tags: [challenge]
      summary: Issue or complete an asymmetric-cost challenge
      description: |
        Same verb, two modes. Do not conflate them with the verify verdict.

        1. **When friction is warranted:** verify returns `decision: challenge`
           (or degraded). Your app returns HTTP 428; that is not this endpoint.
        2. **Issue** (no `proof`): create friction. Method preference via
           `prefer`, ranked best → worst for anti-abuse economics
           (payment_preauth → proof_of_work → device_attestation →
           web_bot_auth_stepup → email_otp). Never defaults to email_otp.
           Chitmark decides when friction is warranted; you choose the
           least-costly mechanism for the funnel.
        3. **Complete** (`challengeId` + `proof`): prove the issued friction
           was satisfied. Clears only the bound session, once. **Invariant
           (bound-session clear):** never globally clears identity, account,
           IP, or device. **Invariant (complete ≠ authorize):** completion
           changes session state only; it does not authorize the action.
           Re-verify with `context.challengeId` and proceed only on
           non-degraded `allow`. Wrong session, replay, expiry, wrong tenant,
           and invalid proofs fail with the documented error codes below.
           Issuing alone never clears a session.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ChallengeRequest"
      responses:
        "200":
          description: Challenge issued, or completion acknowledged
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/ChallengeResponse"
                  - $ref: "#/components/schemas/ChallengeCompletionResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          description: |
            API key missing challenge:write, or completion session does not
            match the issued boundTo.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "404":
          description: Unknown challengeId for this tenant
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "409":
          description: Challenge was already solved (anti-replay)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "410":
          description: Challenge has expired
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "415":
          $ref: "#/components/responses/UnsupportedMediaType"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          description: Challenge state store unavailable
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /v1/charge:
    post:
      operationId: charge
      tags: [charge]
      summary: Paid access lifecycle
      description: |
        Purchase and manage paid resource access (API calls, datasets,
        compute, specific actions). Seller-authenticated lifecycle requests:
        quote, accept terms, authorize, report usage or completion, inspect
        status, cancellation, and refunds. Each request carries an
        `Idempotency-Key`; the header takes precedence over body
        `idempotencyKey`. Charge is separate from the security verbs (verify,
        feedback, challenge) and is not a verify data-plane operation.
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ChargeRequest"
      responses:
        "200":
          description: Charge lifecycle result
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ChargeResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: |
            `idempotency_conflict`: this Idempotency-Key is already
            associated with a different request payload fingerprint.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "413":
          $ref: "#/components/responses/PayloadTooLarge"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          description: Charge store temporarily unavailable
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /.well-known/jwks.json:
    get:
      operationId: getJwks
      tags: [verify]
      summary: JWKS for verdictToken verification
      security: []
      description: >-
        Public keys (ES256/P-256) that verify verdictToken signatures. Every
        signed JWT requires a `kid` in the header (fingerprint: first 16
        base64url chars of SHA-256 over `x:y`). Token TTL is 5 minutes.

        Rotation contract: publish the new key while the old key remains;
        JWKS overlaps both kids; remove the old key only after every token
        signed under it has expired (keep it at least TTL + JWKS cache skew:
        5 minutes + 60 seconds). A previously issued token remains verifiable
        for its full lifetime when this contract is followed.

        HTTP caching: responses include `Cache-Control: public, max-age=60`
        and a strong `ETag` (SHA-256 of the JWKS body). Clients should respect
        `Cache-Control`, and when `ETag` or `Last-Modified` are present use
        conditional requests (`If-None-Match` / `If-Modified-Since`) instead of
        hard-coding a refresh interval. An unchanged set returns `304`. Still
        refresh immediately on an unknown `kid`. Do not fetch JWKS on every
        verification, and never permanently pin a single signing key.

        Never disable signature verification because JWKS is temporarily
        unavailable: fail closed (`jwks_unavailable` / `unknown_kid`), never
        allow. When no signing key is configured, JWKS is `{ "keys": [] }`
        and verdicts may be `unsigned.<eventId>` (local/CI only). An empty
        JWKS means no verdict token can currently be cryptographically
        verified: consumers must fail closed; never treat an empty key set
        as evidence that a token is valid. Each key is an EC P-256 public
        JWK intended for ES256 (`kty: EC`, `crv: P-256`, `alg: ES256`,
        `use: sig`, plus `kid` / `x` / `y`). Consumers must validate the
        JWT header `alg` is exactly `ES256` before verifying (reject
        `wrong_algorithm`); never select whatever algorithm the token
        requests. Flow: JWT `alg` = ES256 → JWKS key type/curve compatible
        with ES256 → signature verification. After signature verification,
        require `iss === "https://api.chitmark.com"`, match `tid` to the
        expected tenant, and match `sub` to the expected session before
        authorizing.
      responses:
        "200":
          description: JSON Web Key Set (`Cache-Control`, `ETag`)
          headers:
            Cache-Control:
              schema:
                type: string
                example: public, max-age=60
            ETag:
              schema:
                type: string
                description: Strong ETag of the JWKS body; send as If-None-Match
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/JwksResponse"
        "304":
          description: Not modified (If-None-Match matched current ETag)
          headers:
            Cache-Control:
              schema:
                type: string
            ETag:
              schema:
                type: string

  /v1/attributions/resolve:
    post:
      operationId: resolveAttribution
      tags: [attribution]
      description: Requires `attribution:read`. Recognizes enrolled agent keys across recipients with fresh audience-bound proof. Principal disclosure requires a matching current grant. Unknown identity is a successful outcome.
      parameters:
        - name: Idempotency-Key
          in: header
          schema: { type: string, minLength: 1, maxLength: 128 }
          description: A repeated resolve returns its stored observation with principal fields withheld.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AttributionResolveRequest" }
      responses:
        "200":
          description: Successful result
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionResult" }
              examples:
                unknown:
                  value:
                    id: "00000000-0000-4000-8000-000000000001"
                    agent: { detected: false, provider: null, operator_verified: false }
                    identity:
                      { recognized: false, subject_id: null, scope: null, match: none }
                    principal:
                      {
                        status: unknown,
                        email: null,
                        email_verified: null,
                        current_delegation_verified: null,
                        document_verified: null,
                      }
                session:
                  value:
                    id: "00000000-0000-4000-8000-000000000002"
                    agent: { detected: false, provider: null, operator_verified: false }
                    identity:
                      {
                        recognized: true,
                        subject_id: "00000000-0000-4000-8000-000000000011",
                        scope: site,
                        match: existing_session,
                      }
                    principal:
                      {
                        status: unknown,
                        email: null,
                        email_verified: null,
                        current_delegation_verified: null,
                        document_verified: null,
                      }
                principal:
                  value:
                    id: "00000000-0000-4000-8000-000000000003"
                    agent: { detected: true, provider: null, operator_verified: false }
                    identity:
                      {
                        recognized: true,
                        subject_id: "00000000-0000-4000-8000-000000000012",
                        scope: site,
                        match: verified_identity_link,
                      }
                    principal:
                      {
                        status: previously_verified,
                        email: "fixture@example.invalid",
                        email_verified: true,
                        current_delegation_verified: true,
                        document_verified: true,
                      }
                recognized_agent:
                  value:
                    id: "00000000-0000-4000-8000-000000000004"
                    agent: { detected: true, provider: null, operator_verified: false }
                    identity:
                      recognized: true
                      subject_id: sub_a3b04917c8ca03ee545798fc3609ea3825c117a376fc42a39f4337cbb51a5f66
                      scope: site
                      match: verified_agent_account
                    principal:
                      status: withheld
                      email: null
                      email_verified: null
                      current_delegation_verified: null
                      document_verified: null
        "400":
          description: Invalid request
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "401":
          description: Missing or inactive credential
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "403":
          description: Missing scope or forbidden disclosure mode
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "409":
          description: Idempotency conflict
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "429":
          description: Request rate exceeded
          headers:
            Retry-After:
              schema: { type: integer }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "503":
          description: Attribution temporarily unavailable
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
  /v1/attributions/{id}:
    get:
      operationId: getAttribution
      tags: [attribution]
      description: Requires `attribution:read`. Retrieves a stored session observation with principal fields withheld.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: Successful result
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionResult" }
        "401":
          description: Missing or inactive credential
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "403":
          description: Missing scope or forbidden disclosure mode
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "404":
          description: Unknown or inaccessible record
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "429":
          description: Request rate exceeded
          headers:
            Retry-After:
              schema: { type: integer }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "503":
          description: Attribution temporarily unavailable
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
  /v1/identity-links:
    post:
      operationId: createIdentityLink
      tags: [attribution]
      description: Requires `attribution:write`. The examples illustrate the wire shape with placeholder signatures and expiry. Generate fresh signatures for your own configuration.
      parameters:
        - name: Idempotency-Key
          in: header
          schema: { type: string, minLength: 1, maxLength: 128 }
          description: A matching retry returns the existing link. A different body returns a conflict.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/AttributionLinkRequest" }
            examples:
              siteLink:
                summary: Site link
                value:
                  enrollmentId: "00000000-0000-4000-8000-000000000001"
                  site: "https://receiver-b.example"
                  agentKey:
                    {
                      "kty": "OKP",
                      "crv": "Ed25519",
                      "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo",
                    }
                  recipientKeyId: "key_recipientb"
                  emailConsent: false
                  expiresAt: 1800000000
                  principalProof: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
              networkAgent:
                summary: Network agent
                value:
                  kind: "network_agent"
                  enrollmentId: "00000000-0000-4000-8000-000000000001"
                  agentKey:
                    {
                      "kty": "OKP",
                      "crv": "Ed25519",
                      "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo",
                    }
                  expiresAt: 1800000000
                  principalProof: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                  agentProof: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
              networkGrant:
                summary: Network grant
                value:
                  kind: "network_grant"
                  agentId: "00000000-0000-4000-8000-000000000011"
                  site: "https://receiver-b.example"
                  recipientKeyId: "key_recipientb"
                  purpose: "identity_attribution"
                  emailConsent: true
                  expiresAt: 1800000000
                  principalProof: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
      responses:
        "201":
          description: Site link, network binding, or recipient grant created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionLink" }
              examples:
                siteLink:
                  summary: The ID is the site link ID used in agent proofs and revocation.
                  value:
                    { id: "00000000-0000-4000-8000-000000000010", expires_at: 1800000000 }
                networkAgent:
                  summary: The ID is the agent ID used in grants, rotation, and revocation.
                  value:
                    { id: "00000000-0000-4000-8000-000000000011", expires_at: 1800000000 }
                networkGrant:
                  summary: The ID is the disclosure grant ID used in revocation.
                  value:
                    { id: "00000000-0000-4000-8000-000000000012", expires_at: 1800000000 }
        "200":
          description: Matching idempotent retry.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionLink" }
        "400":
          description: Invalid request
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "401":
          description: Missing or inactive credential
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "403":
          description: Missing scope or forbidden disclosure mode
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "404":
          description: Unknown or inaccessible record
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "409":
          description: Idempotency conflict, network binding conflict, or active identity link allowance exhausted.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "429":
          description: Request rate exceeded
          headers:
            Retry-After:
              schema: { type: integer }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "503":
          description: Attribution temporarily unavailable
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
  /v1/identity-links/{id}:
    delete:
      operationId: revokeIdentityLink
      tags: [attribution]
      description: Requires `attribution:write`. Revokes a site link, recipient grant, or owned network agent. Revoking the agent revokes all of its grants.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "204":
          description: Identity link revoked
        "401":
          description: Missing or inactive credential
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "403":
          description: Missing scope or forbidden disclosure mode
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "404":
          description: Unknown or inaccessible record
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "429":
          description: Request rate exceeded
          headers:
            Retry-After:
              schema: { type: integer }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }
        "503":
          description: Attribution temporarily unavailable
          content:
            application/json:
              schema: { $ref: "#/components/schemas/AttributionError" }

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: CHITMARK_API_KEY as Bearer token

  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema:
        type: string
      description: |
        Dedupes verify or feedback retries. If this header and body
        `idempotencyKey` are both sent, this header takes precedence.
        SDKs set both to the same value. `409 idempotency_conflict` means
        this key is already associated with a different payload fingerprint:
        do not reuse it; generate a new key for the new request.

  responses:
    BadRequest:
      description: Invalid request body or missing required field
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    Forbidden:
      description: |
        Forbidden: raw PII without tenant opt-in, or API key missing the
        required verb scope (verify:write, feedback:write, challenge:write).
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    RateLimited:
      description: |
        Rate limited. Response includes `Retry-After` (seconds, clamped 1..60).
        Recommended client policy: honor `Retry-After` when present; otherwise
        exponential backoff with jitter; cap total retries (for example 3);
        resend the same `Idempotency-Key` for the same logical attempt. After
        the retry budget is exhausted on verify, fail closed to challenge,
        never allow.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    PayloadTooLarge:
      description: Request body exceeds 32 KB
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    UnsupportedMediaType:
      description: Content-Type must be application/json
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"

  schemas:
    AttributionResolveRequest:
      type: object
      additionalProperties: false
      description: Maximum request size is 8192 bytes. Use an HTTPS site origin when submitting evidence.
      properties:
        site: { type: string, format: uri, maxLength: 253 }
        session:
          type: string
          pattern: "^[A-Za-z0-9_-]{32,128}$"
          description: Opaque credential selected by the integrating server.
        piiMode:
          type: string
          enum: [hashed, none, raw]
          default: hashed
        purpose:
          type: string
          pattern: "^[a-z][a-z0-9_]{0,63}$"
          default: identity_attribution
          description: Recipient-selected disclosure purpose bound to the network proof and grant.
        agentEnvironment:
          type: string
          enum: [browser, server, other, unknown]
          default: unknown
          description: Caller-declared runtime for aggregate coverage metrics. It carries no identity or disclosure authority.
        agentProof:
          oneOf:
            - $ref: "#/components/schemas/AttributionSiteProof"
            - $ref: "#/components/schemas/AttributionNetworkProof"
    AttributionSiteProof:
      type: object
      required: [linkId, nonce, issuedAt, signature]
      properties:
        linkId: { type: string, format: uuid }
        nonce: { type: string, format: uuid }
        issuedAt: { type: integer, description: Unix seconds }
        signature: { $ref: "#/components/schemas/AttributionSignature" }
      not:
        required: [iss]
    AttributionNetworkProof:
      type: object
      required: [iss, agentKey, nonce, issuedAt, signature]
      properties:
        iss: { const: chitmark-agent-key-v1 }
        agentKey: { $ref: "#/components/schemas/AttributionAgentKey" }
        nonce: { type: string, format: uuid }
        issuedAt: { type: integer, description: Unix seconds }
        signature: { $ref: "#/components/schemas/AttributionSignature" }
    AttributionAgentKey:
      type: object
      required: [kty, crv, x]
      properties:
        kty: { const: OKP }
        crv: { const: Ed25519 }
        x: { type: string, pattern: "^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$" }
      not:
        required: [d]
    AttributionSignature:
      type: string
      pattern: "^[A-Za-z0-9_-]{86}$"
    AttributionResult:
      type: object
      required: [id, agent, identity, principal]
      properties:
        id: { type: string, format: uuid }
        agent:
          type: object
          required: [detected, provider, operator_verified]
          properties:
            detected: { type: boolean }
            provider: { type: [string, "null"] }
            operator_verified: { type: boolean }
        identity:
          type: object
          required: [recognized, subject_id, scope, match]
          properties:
            recognized: { type: boolean }
            subject_id:
              type: [string, "null"]
              description: Opaque site-scoped subject. Network subjects use the sub_ prefix.
            scope: { enum: [site, null] }
            match:
              {
                enum:
                  [
                    none,
                    existing_session,
                    verified_identity_link,
                    verified_agent_account,
                  ],
              }
        principal:
          type: object
          required:
            [
              status,
              email,
              email_verified,
              current_delegation_verified,
              document_verified,
            ]
          properties:
            status: { enum: [unknown, previously_verified, withheld] }
            email: { type: [string, "null"] }
            email_verified: { type: [boolean, "null"] }
            current_delegation_verified: { type: [boolean, "null"] }
            document_verified:
              type: [boolean, "null"]
              description: Optional Stripe document verification status, separate from account authentication and agent delegation.
    AttributionLinkRequest:
      oneOf:
        - $ref: "#/components/schemas/AttributionSiteLinkRequest"
        - $ref: "#/components/schemas/AttributionNetworkAgentRequest"
        - $ref: "#/components/schemas/AttributionNetworkGrantRequest"
    AttributionSiteLinkRequest:
      description: The enrolling workspace submits a signed site link for its authenticated enrollment and active recipient key. Omit kind. Email consent requires a retained verified address and a key with attribution:email.
      type: object
      additionalProperties: false
      required:
        [
          enrollmentId,
          site,
          agentKey,
          recipientKeyId,
          emailConsent,
          expiresAt,
          principalProof,
        ]
      properties:
        enrollmentId: { type: string, format: uuid }
        site:
          type: string
          format: uri
          maxLength: 253
          description: Exact HTTPS origin without a path, query, fragment, or trailing slash.
        agentKey: { $ref: "#/components/schemas/AttributionAgentKey" }
        recipientKeyId: { type: string, pattern: "^key_[a-z0-9]{1,80}$" }
        emailConsent: { type: boolean }
        expiresAt:
          type: integer
          description: Future Unix seconds, at most 30 days ahead and within 90 days of account authentication.
        principalProof: { type: string, pattern: "^[A-Za-z0-9_-]{86}$" }
    AttributionNetworkAgentRequest:
      description: The enrolling workspace binds the agent key. The enrolled principal and new agent sign with distinct keys. Rotation requires the ID and current key of an active binding.
      type: object
      additionalProperties: false
      required: [kind, enrollmentId, agentKey, principalProof, agentProof, expiresAt]
      properties:
        kind: { const: network_agent }
        enrollmentId: { type: string, format: uuid }
        agentKey: { $ref: "#/components/schemas/AttributionAgentKey" }
        principalProof: { $ref: "#/components/schemas/AttributionSignature" }
        agentProof: { $ref: "#/components/schemas/AttributionSignature" }
        expiresAt:
          type: integer
          description: Future Unix seconds within 90 days of account authentication.
        rotation:
          type: object
          additionalProperties: false
          required: [agentId, previousKey]
          properties:
            agentId: { type: string, format: uuid }
            previousKey: { $ref: "#/components/schemas/AttributionAgentKey" }
    AttributionNetworkGrantRequest:
      description: The principal signs and the recipient workspace submits. The recipient key must be active in that workspace and environment with attribution:read. Email consent requires a retained verified email, an eligible recipient plan, and attribution:email on the recipient key.
      type: object
      additionalProperties: false
      required:
        [
          kind,
          agentId,
          site,
          recipientKeyId,
          purpose,
          emailConsent,
          expiresAt,
          principalProof,
        ]
      properties:
        kind: { const: network_grant }
        agentId: { type: string, format: uuid }
        site:
          type: string
          format: uri
          maxLength: 253
          description: Exact HTTPS origin without a path, query, fragment, or trailing slash.
        recipientKeyId: { type: string, pattern: "^key_[a-z0-9]{1,80}$" }
        purpose: { type: string, pattern: "^[a-z][a-z0-9_]{0,63}$" }
        emailConsent: { type: boolean }
        expiresAt:
          type: integer
          description: Future Unix seconds, at most 30 days ahead and no later than the agent binding.
        principalProof: { $ref: "#/components/schemas/AttributionSignature" }
    AttributionLink:
      type: object
      required: [id, expires_at]
      properties:
        id: { type: string, format: uuid }
        expires_at: { type: integer }
    AttributionError:
      type: object
      required: [error]
      properties:
        error: { type: string }
    Decision:
      type: string
      enum: [allow, challenge, deny]

    ActorType:
      type: string
      enum: [human, agent_principal, agent_abusive, unknown]

    EnforcementMode:
      type: string
      enum: [enforce, log_only]
      description: |
        enforce: partner may gate on the verdict (challenge / deny / allow).
        log_only: observation only; the same detector and a usable verdictToken
        are returned, but the token does not authorize the action. Mode is on
        the Verdict body (not a JWT claim today): check enforcementMode before
        treating decision or verdictToken as authorization.

    Action:
      type: string
      enum:
        - signup
        - trial_activation
        - api_key
        - demo_request
        - quote
        - ticket
        - custom
      description: Or any custom action string the customer defines

    Outcome:
      type: string
      description: |
        Downstream business label joined on a stored verify `eventId`.
        Prefer fast labels (`credit_burn`, `multi_account_cluster`,
        `abuse_confirmed`) for the pilot proof window.

        - `credit_burn`: free compute/API credits or infra consumed after the
          action (typically first 24–72h).
        - `multi_account_cluster`: accounts sharing infra/fingerprint linked to
          this event.
        - `abuse_confirmed`: trust/safety (or equivalent) confirmed abuse on
          this event.
        - `converted`: later paid/activated as a real customer. Optional
          `value` is **realized first-year ARR** (annualized contract value)
          at conversion time (`12 × MRR` for monthly, annual contract amount
          for annual), not expected ARR, multi-year TCV, or LTV.
        - `chargeback`: payment dispute attributed to this event. Optional
          `value` is the disputed amount.
        - `churned`: later cancelled / stopped using after conversion-like
          activity.
        - `false_positive`: a previously attributed **abuse signal** on this
          `eventId` was reviewed and determined **not** to represent abuse
          (T&S clear / overturn). Conflicts with abuse-positive labels
          (`abuse_confirmed`, `multi_account_cluster`, `credit_burn`,
          `chargeback`). **Not** "Chitmark challenged or denied a legitimate
          user": that cost trade-off is `context.decisionCosts.falseChallenge`
          / `falseDeny` on verify, not this outcome. **Not** a generic
          "external classifier was wrong" unless the correction is about abuse
          attribution joined on this `eventId`.
      enum:
        - credit_burn
        - multi_account_cluster
        - abuse_confirmed
        - converted
        - chargeback
        - churned
        - false_positive

    FeedbackUnit:
      type: string
      description: |
        Scale for feedback `value`. Not free-form: only these tokens are
        accepted today. Values in different units are not converted and are
        not comparable. Weekly Agent Farming Ledger dollar totals only sum
        `credit_burn` rows where `unit` is `usd`.
      enum:
        - usd
        - credits
        - count
      default: usd

    FeedbackSource:
      type: string
      description: |
        Provenance of the label: why you trusted this outcome for this
        `eventId`. `eventId` + `outcome` say what was learned; `source` says
        where the label came from. Optional today. When set, included in the
        warehouse `feedbackId` digest (two sources with otherwise identical
        bodies are separate observations).
      enum:
        - billing
        - usage_metering
        - trust_queue
        - manual_review
        - customer_system
        - automated_detector

    ChallengeMethod:
      type: string
      description: |
        Friction method. `payment_preauth` validates a payment-provider
        setup result (e.g. SetupIntent succeeded); it does not transfer
        funds or authorize a purchase. Chitmark is not a payments product.
      enum:
        - payment_preauth
        - proof_of_work
        - device_attestation
        - web_bot_auth_stepup
        - email_otp

    Subject:
      type: object
      description: |
        Subject signals. Prefer hashed/tokenized fields (piiMode hashed).
        Raw email/ip are opt-in only.
      properties:
        email:
          type: string
          format: email
        emailSha256:
          type: string
          description: Client-side SHA-256 of lowercased email
        ip:
          type: string
        ipTrunc:
          type: string
          description: Truncated IP (/24 IPv4 or /48 IPv6)
        userAgent:
          type: string
        headers:
          type: object
          additionalProperties:
            oneOf:
              - type: string
              - type: array
                items:
                  type: string
          description: Includes Web Bot Auth headers when present
        formData:
          type: object
          additionalProperties: true
        formDataHashed:
          type: object
          additionalProperties: true

    Principal:
      type: object
      required: [resolved, identityBasis]
      description: |
        Attribution hints for who is acting and on whose behalf. Not an
        authorization credential: never treat principal.resolved as "this is
        a human", and never unlock an action from principal alone. Gate on
        decision (plus degraded / enforcementMode).
      properties:
        resolved:
          type: boolean
          description: |
            True when Chitmark has a usable principal signal for this
            request: today, a verified Web Bot Auth operator signature
            and/or enrichment marking a known-good principal. False means
            sparse/unresolved (typical for farms and unsigned traffic).
            Resolved is not cryptographic proof of an end-user human, not
            an IdP login, and not equivalent to actorType "human".
        operator:
          type: string
          description: |
            Bot maker / agent operator when known from Web Bot Auth
            Signature-Agent (e.g. "openai"). Authenticates the operator
            channel when WBA verifies; does not by itself prove onBehalfOf.
        onBehalfOf:
          type: string
          description: |
            The principal the agent is acting for when known: may be an
            organization identifier (e.g. "acmecorp.com") or an end-user
            identifier, depending on what the signing/context path
            supplies. Often absent at the wedge. Presence is not proof the
            named party authorized this action; do not use as sole authz.
        identityBasis:
          type: array
          items:
            type: string
          description: |
            Which signals contributed to principal attribution (e.g.
            web_bot_auth, email_domain, enrichment). Mixed cryptographic
            and inferred sources: inspect the list; do not assume every
            basis is equally strong.
    VerifyRequest:
      type: object
      required: [action, subject]
      properties:
        idempotencyKey:
          type: string
          description: |
            Body form of the verify idempotency key. If the `Idempotency-Key`
            header is also sent, the header takes precedence. Not included in
            the payload fingerprint. Conflict when this key is already tied to
            a different fingerprint of action/session/surface/subject/context.
        action:
          oneOf:
            - $ref: "#/components/schemas/Action"
            - type: string
        session:
          type: string
          description: |
            Binding id you supply for this action attempt. Binds challenge
            and `verdictToken` (`sub`). Prefer high-entropy, unpredictable,
            server-generated ids (e.g. UUID v4). If client-generated,
            treat as attacker-influenced: guessable values weaken challenge
            anti-replay and token binding. Reuse across verify → challenge →
            re-verify for the same attempt only.
        surface:
          type: string
          description: e.g. app.acme.com/signup
        subject:
          $ref: "#/components/schemas/Subject"
        context:
          type: object
          description: |
            Optional per-request policy flags.
            `logOnly` (true): observation-only `log_only` verdict, accepted only
            when the API key has the `log_only` capability (or the tenant is in
            log-only mode). This is an integration-side control: set it in your
            server code (or via env/key policy). Never derive it from
            client-provided request data (for example `req.body.logOnly`).
            The verdict response reports the effective mode as
            `enforcementMode: "log_only" | "enforce"`.
            `challengeId`: reference a challenge this partner completed for
            `session`; the next verify for that session honors it once. A
            successful clear short-circuits scoring to `decision: allow`
            with `challengeCleared: true` (never challenge/deny with that
            flag). Under `log_only` the allow is still observation-only.
            `challengePolicy`: "default" (challenge the gray zone) or
            "confirmed_tail_only" (enforce mode only: challenge only the
            confirmed farm tail, allow the gray zone).
            `decisionCosts`: {falseAllow, falseChallenge, falseDeny}:
            relative, dimensionless weights for three error classes (not
            dollars and not score thresholds; only ratios matter). Verify is
            a three-way decision (allow ← challenge → deny), not a single
            risk cutoff; these weights move both boundaries.
            falseAllow = cost of allowing abusive traffic;
            falseChallenge = cost of challenging legitimate traffic
            (friction when allow would have been fine; a challenge can still
            be appropriate for legitimate users);
            falseDeny = cost of denying legitimate traffic.
            Higher falseAllow challenges earlier (abuse-averse); higher
            falseChallenge lets more of the gray zone through; higher
            falseDeny reserves deny for confirmed abuse. Defaults 1/1/3
            preserve fail-to-challenge semantics. A field that is missing,
            not a number, or non-positive falls back to its default.
          additionalProperties: true

    Verdict:
      description: |
        Verify verdict. Constraint: when `degraded` is true, `decision` is
        always `challenge` (fail to challenge, never to allow).
      allOf:
        - type: object
          required:
            - decision
            - actorType
            - confidence
            - reasons
            - principal
            - verdictToken
            - eventId
            - degraded
            - enforcementMode
          properties:
            decision:
              $ref: "#/components/schemas/Decision"
            actorType:
              $ref: "#/components/schemas/ActorType"
            confidence:
              type: number
              minimum: 0
              maximum: 1
              description: |
                Model confidence for the returned decision (0..1). Not a
                calibrated probability of abuse, and not the threshold that
                decisionCosts moves. Gate on decision (plus degraded /
                enforcementMode); use confidence for ops triage and
                dashboards, not as a substitute allow/deny cutoff.
            reasons:
              type: array
              items:
                type: string
              description: |
                Human-readable signal strings for ops (always populated).
                Wire format today is string[]. Treat the text as display
                copy, not a stable machine API: do not scrape or regex
                reason strings for analytics. A future additive revision
                may expose structured entries such as
                {code, message, category} (keeping a human-readable
                message) so dashboards can answer "why are challenges
                increasing?" without parsing free text.
            principal:
              $ref: "#/components/schemas/Principal"
            verdictToken:
              type: string
              description: |
                ES256 JWT decision receipt. Claims are documented under
                VerdictTokenClaims. Always validate signature (JWKS), then
                `iss` (`https://api.chitmark.com`), `tid` (tenant), and `sub`
                (session) before trusting the decision. Authenticity is not
                authorization: still require non-degraded `decision: allow`.
                Under log_only the token remains a valid signed observation
                receipt but does not authorize the action; check
                enforcementMode on the Verdict body before gating.
            eventId:
              type: string
              description: "Store on account row: feedback join key"
            degraded:
              type: boolean
              description: If true, decision is always challenge
            enforcementMode:
              $ref: "#/components/schemas/EnforcementMode"
            challengeCleared:
              type: boolean
              description: |
                true when this verify honored `context.challengeId` for the
                request session. Guaranteed only with `decision: allow` and
                `degraded: false`: a successful clear short-circuits scoring
                and never returns challenge/deny with this flag set. Under
                `log_only`, still an observation receipt (does not authorize).
        - if:
            required: [degraded]
            properties:
              degraded:
                const: true
          then:
            properties:
              decision:
                const: challenge

    FeedbackRequest:
      type: object
      required: [eventId, outcome]
      properties:
        eventId:
          type: string
          description: |
            Join key from a prior verify for this tenant. Required. Feedback
            cannot create attribution: unknown or cross-tenant ids return 404
            unknown_event_id. Never invent a join from email, IP, or other
            subject fields.
        outcome:
          $ref: "#/components/schemas/Outcome"
        value:
          type: number
          minimum: 0
          maximum: 1000000
          description: |
            Measured economic magnitude associated with this outcome, expressed
            in `unit`. Optional for most outcomes. Non-negative and finite;
            capped at 1_000_000. Not a currency field by itself: the same
            number means different things under `usd` vs `credits` vs `count`,
            and those magnitudes are not automatically comparable or converted
            (e.g. credit_burn 12.4 usd vs converted 4800 usd first-year ARR vs
            chargeback 73.2 usd are different economic quantities that share a
            unit token only when you chose usd). For `converted`, when `value`
            is set it means realized first-year ARR at conversion, not
            expected ARR, multi-year TCV, or LTV. Omit when the label has no
            measured magnitude (common for `abuse_confirmed`, `false_positive`,
            `multi_account_cluster`, `churned`).
        unit:
          $ref: "#/components/schemas/FeedbackUnit"
          description: |
            Scale for `value`. Allowed today: `usd`, `credits`, `count`
            (default `usd` when `value` is set and `unit` is omitted). Requires
            `value`. Rejected if sent alone. Not an open currency or unit
            string: unknown tokens return `400 invalid_value`.
        source:
          $ref: "#/components/schemas/FeedbackSource"
          description: |
            Provenance of the label (billing, usage_metering, trust_queue,
            manual_review, customer_system, automated_detector). Optional.
            Included in warehouse identity when set: same outcome from two
            sources is two observations. Unknown tokens return `400
            invalid_source`.
        observedAt:
          type: string
          format: date-time
          description: |
            When the outcome was observed. Included in the warehouse feedback
            identity digest with eventId, outcome, value, unit, and source.
            Different timestamps are separate observations. If omitted, the API
            uses server receipt time (so retries a moment later are not body
            duplicates unless you also send Idempotency-Key).
        idempotencyKey:
          type: string
          description: |
            Body form of the feedback idempotency key. If the `Idempotency-Key`
            header is also sent, the header takes precedence.
            `409 idempotency_conflict`: key already associated with a different
            fingerprint of eventId/outcome/value/unit/source/observedAt; create
            a new key.
            Without a key, exact duplicate bodies still share one warehouse
            feedbackId: equality is tenantId + eventId + outcome + value +
            unit (default usd) + source (or null) + normalized observedAt.

    FeedbackResponse:
      type: object
      required: [ok, eventId]
      properties:
        ok:
          type: boolean
        eventId:
          type: string

    ChallengeRequest:
      type: object
      description: |
        Issue mode (no `proof`) or completion mode (`challengeId` + `proof`).
      required: [eventId, session]
      properties:
        eventId:
          type: string
          description: eventId from the verify verdict that routed to challenge
        session:
          type: string
          minLength: 1
          maxLength: 128
          description: |
            Binding id you supply that uniquely represents one action attempt.
            Required for issue and completion. Prefer high-entropy,
            unpredictable, server-generated values (e.g. UUID v4 / CSPRNG).
            Completion and the follow-up verify that consumes the solved
            challenge must present the same session. Client-generated or
            guessable sessions are attacker-influenced and weaken binding.
        prefer:
          type: array
          description: |
            Ordered hints, not guarantees. Chitmark walks the list and
            selects the first issuable method for this request (currently
            `payment_preauth`, `proof_of_work`). Skips unsupported or
            not-yet-available entries; never errors solely because a
            preferred method is unavailable. Omitted or empty list, or no
            issuable entry → `proof_of_work`. Never `email_otp` as an
            implicit default. If `payment_preauth` is selected but the
            payment processor cannot create, falls back to `proof_of_work`.
            Always branch on the returned `method`.
          items:
            $ref: "#/components/schemas/ChallengeMethod"
        context:
          type: object
          description: |
            Issue-mode context. `riskTier` scales the issued proof-of-work
            difficulty so the challenge's economic tax rises with risk.
            Monotonicity: riskTier ↑ ⇒ challenge cost never ↓
            (`default` → D, `elevated` → ≥ D, `severe` → ≥ elevated).
            Issued difficulty is immutable: completion validates the sealed
            value; a later tier change cannot retroactively alter required
            proof.
          properties:
            riskTier:
              type: string
              enum: [default, elevated, severe]
              description: |
                PoW difficulty tier. Absent or unknown → `default`
                (baseline D). Higher tiers never issue weaker puzzles than
                lower ones. Sealed at issue; not re-read on complete.
          additionalProperties: false
        challengeId:
          type: string
          description: "Completion mode: the challenge being solved"
        proof:
          $ref: "#/components/schemas/ChallengeProof"

    ChallengeProof:
      type: object
      description: |
        Server-verified completion proof, bound to challengeId + session.
        For `stripe_setup_intent`, Chitmark validates the payment-provider
        result only; it does not transfer funds or authorize a purchase.
      oneOf:
        - type: object
          required: [type, nonce]
          properties:
            type:
              const: proof_of_work
            nonce:
              type: string
              minLength: 1
              maxLength: 128
              description: |
                First nonce where sha256(`${challengeId}:${seed}:${nonce}`) in
                hex starts with `difficulty` zero nibbles.
        - type: object
          required: [type, setupIntentId]
          properties:
            type:
              const: stripe_setup_intent
            setupIntentId:
              type: string
              description: |
                SetupIntent id from the issued instructions after the
                payment provider reports status `succeeded` (test-mode);
                stub mode accepts the issued `seti_stub_<challengeId>`.
                Validates provider result only: no fund transfer, no
                purchase authorization.

    ChallengeResponse:
      type: object
      required: [challengeId, method, instructions, boundTo, expiresAt]
      properties:
        challengeId:
          type: string
        method:
          $ref: "#/components/schemas/ChallengeMethod"
        instructions:
          oneOf:
            - $ref: "#/components/schemas/PowInstructions"
            - $ref: "#/components/schemas/StripeSetupIntentInstructions"
        boundTo:
          type: string
          description: |
            Session the solve clears (anti-replay). Completing never globally
            clears an identity, account, IP, or device: only this session.
        expiresAt:
          type: string
          format: date-time

    PowInstructions:
      type: object
      description: |
        Normalized proof-of-work parameters returned at issue. Clients must
        solve against these fields exactly: `difficulty` is sealed here and
        is what completion validates (do not invent or re-derive from
        `riskTier`). Puzzle: hex SHA-256 of `${challengeId}:${seed}:${nonce}`
        must start with `difficulty` zero nibbles (`algorithm` is always
        `sha256-prefix`; bounds 1–12).
      required: [type, difficulty, seed, algorithm]
      properties:
        type:
          const: pow
        difficulty:
          type: integer
          minimum: 1
          maximum: 12
          description: |
            Leading zero nibbles required. Sealed at issue from `riskTier`
            (monotonic: higher tier ⇒ difficulty never lower). Completion
            validates this value only; tier is not re-applied. Always present
            on PoW issue responses.
          example: 4
        seed:
          type: string
          description: Per-challenge seed; combine as `${challengeId}:${seed}:${nonce}`
        algorithm:
          const: sha256-prefix
          description: Only supported PoW algorithm today

    StripeSetupIntentInstructions:
      type: object
      description: |
        Client instructions for `payment_preauth`. Confirms instrument
        binding with the payment provider; Chitmark does not transfer funds
        or authorize a purchase.
      required: [type, mode, clientSecret]
      properties:
        type:
          const: stripe_setup_intent
        mode:
          type: string
          enum: [test, stub]
          description: |
            `test`: real Stripe test-mode SetupIntent (Stripe secret wired).
            `stub`: deterministic `seti_stub_<challengeId>` for testing
            without Stripe credentials.
        clientSecret:
          type: string
        publishableKey:
          type: string
          description: Present when mode is test (pk_test_...)

    ChallengeCompletionResponse:
      type: object
      description: |
        Completion acknowledged. Changes session state only: does not
        authorize the action. Re-verify with `context.challengeId` and
        proceed only on non-degraded `allow`.
      required: [ok, challengeId, boundTo, clearedAt]
      properties:
        ok:
          const: true
          description: |
            Friction was satisfied for `boundTo`. Not permission to continue
            the original action without a follow-up verify.
        challengeId:
          type: string
        boundTo:
          type: string
          description: |
            Session that was cleared (single use, anti-replay). Not an
            identity, account, IP, or device clear.
        clearedAt:
          type: string
          format: date-time

    JwksResponse:
      type: object
      required: [keys]
      description: |
        JSON Web Key Set for verdictToken verification. Empty until signing
        keys are configured. Each key is an EC P-256 public JWK for ES256.
      properties:
        keys:
          type: array
          items:
            $ref: "#/components/schemas/VerdictTokenPublicJwk"
          description: |
            Public keys only (never `d`). Empty array means verification is
            impossible: fail closed.

    VerdictTokenPublicJwk:
      type: object
      required: [kty, crv, x, y, kid, alg, use]
      description: |
        EC P-256 public key for ES256 verdictToken verification. Consumers
        must require JWT header `alg === "ES256"` before verifying
        (`wrong_algorithm` otherwise); never trust the token-requested alg.
      properties:
        kty:
          const: EC
        crv:
          const: P-256
        x:
          type: string
          description: Base64url-encoded X coordinate
        y:
          type: string
          description: Base64url-encoded Y coordinate
        kid:
          type: string
          description: Key fingerprint (JWT header kid)
        alg:
          const: ES256
        use:
          const: sig

    VerdictTokenClaims:
      type: object
      description: |
        Decoded payload of a signed `verdictToken` (ES256 JWT, `typ: JWT`).
        Three distinct bindings: `iss` (who issued), `tid` (which tenant),
        `sub` (which session). Signature verification proves authenticity and
        integrity; it does not make the JWT single-use. `jti` is a correlation
        id: track accepted values only where one-time presentation is required.
        `enforcementMode` is on the Verdict body, not in these claims.
      required:
        - iss
        - eventId
        - decision
        - actorType
        - confidence
        - aud
        - sub
        - tid
        - jti
        - iat
        - exp
        - degraded
      properties:
        iss:
          type: string
          const: https://api.chitmark.com
          description: Issuer. Always https://api.chitmark.com; reject any other value.
        eventId:
          type: string
          description: Verify event the decision belongs to
        decision:
          $ref: "#/components/schemas/Decision"
        actorType:
          $ref: "#/components/schemas/ActorType"
        confidence:
          type: number
          minimum: 0
          maximum: 1
          description: |
            Model confidence for the returned decision (0..1). Not a
            calibrated probability of abuse. Same meaning as Verdict.confidence.
        aud:
          type: string
          description: |
            Origin hint from request headers (advisory). Attacker influenced:
            it may represent information derived from an untrusted request.
            Never use aud as the sole authorization binding. Enforce session
            (sub) and tenantId (tid), never aud alone.
        sub:
          type: string
          description: Session the token is bound to (enforce against expected session)
        tid:
          type: string
          description: |
            Issuing tenant, server-derived from the API key (enforce against
            expected tenant)
        jti:
          type: string
          description: |
            Unique token identifier for correlation. Not single-use unless the
            consumer tracks and invalidates accepted values.
        iat:
          type: integer
          description: Issued-at (unix seconds)
        exp:
          type: integer
          description: |
            Expiry (unix seconds). TTL is 5 minutes by design: tokens are
            short-lived receipts. Verify at consumption time; do not persist
            the JWT as a long-lived authorization credential. Use eventId and
            your own account state for durable records.
        degraded:
          type: boolean
          description: When true, decision is always challenge

    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
        message:
          type: string
        code:
          type: string
