openapi: 3.1.0
info:
  title: Shadow Identity API
  version: "1"
  description: |
    Exposure intelligence, delivered as an API: boolean search across breach records,
    infostealer logs and drop-site dumps.

    ## Authentication

    Every request to `/search` and `/records/*` is made on behalf of a **team**.
    Send `X-API-Key: sk_si_…` (or a browser session cookie); an unauthenticated caller gets
    `401 authentication_required` before anything is metered. A caller whose account is not
    attached to a team gets `403 team_required`; a suspended team gets `403 team_suspended`;
    when the team's configuration cannot be read the answer is `503 team_unavailable` — retry.
    A key belongs to the member who created it and works only while they remain on the team
    it was created for; once they leave that team, the key is refused like a revoked one.
    Teams are invite-only — ask your team admin for an invite, or request access at
    https://shadowidentity.com/request-access.

    ## Queries

    A search is anchored on identifier terms: `email`, `phone`, `address`, `ssn`,
    `password`, `username`, `fbid`, `linkedin`, `domain`, `name` or `full_name`, or an untyped
    email address, phone number or word. A username that is an email address is indexed as
    that address, so a `username` term whose value is one is read as that `email` term:
    `username:d.whitfield@example.com` searches, excludes and is reported in
    `stats.suppressed_terms` exactly as `email:d.whitfield@example.com`. A phone number is
    searched in both forms a source can have stored it in: a US or Canadian number bare and
    after `+1`, any other country's number with and without its `+` (`+447911123456`,
    `447911123456`). So `phone:"(212) 555-0143"`, `phone:1-212-555-0143` and
    `phone:"+1 212 555 0143"` each find the number written any of those ways, show each
    record once and are charged as one `scalar` lookup. A number with ten digits after its `+`
    (`phone:"+46 8 123 4567"`) is searched after its `+` alone: its ten digits written bare
    are a US or Canadian number's, so a source that wrote it without its `+` is found by a
    search for that US or Canadian number instead. A number written after a dialing prefix
    or a trunk zero (`0044…`, `07911…`) is stored under that writing alone. `first_name`,
    `middle_name`, `last_name`, `suffix`, `city`, `state`, `zip`, `country`, `gender`, `dob`,
    `birth_year`, `birth_month`, `birth_day` and `dataset` only narrow the records an
    identifier finds, and every one of them outside a `NOT` applies wherever it sits in the
    query — an `OR` of them never widens a match. A group in parentheses with no identifier
    term outside a `NOT` — two or more narrowing terms and `NOT`s — finds no records of its
    own, so as one side of an `AND` it empties the match:
    `email:d.whitfield@example.com (city:Leeds NOT state:MA)` is searched, billed and returns
    nothing, where `email:d.whitfield@example.com city:Leeds NOT state:MA` narrows that
    address's records. Parentheses around a single term change nothing. A query with no
    identifier term outside a `NOT` is refused with `400 query_needs_identifier` and is not
    billed. On `GET`, URL-encode `q` — an unencoded `+` arrives as a space, so
    `phone:+441134960000` is sent as `phone%3A%2B441134960000`.

    ## Suppressed values

    Search withholds some values, and every answered search names each
    identifier term it withheld in `stats.suppressed_terms`, with the reason. A value found in
    more than 1,000,000 records (the most common passwords, the largest mail domains) is dropped
    from the index once it crosses that cutoff (`too_common`); a value Shadow Identity has
    excluded from search is `excluded`. Some values are never indexed (`not_indexed`), each
    read as its field normalizes it. In any term: a number shorter than 5 digits, a
    placeholder word such as null, unknown or not provided, a fragment of JSON markup, a value
    with no letter A–Z or digit 0–9, and a value shorter than 5 characters — except a domain,
    which is held to a registrable domain instead: `domain:x.ai` is searched. In an email
    term, typed or untyped: a placeholder or shared-mailbox address (`noreply@…`,
    `postmaster@…`, `test@example.com`, …). In a phone term, typed or untyped: a placeholder
    phone number (`5555555555`, `+15555555555`, …). A value on one field's list is looked up
    under any other field: `password:5555555555` is searched. A username that is an email
    address is that address's email term (see **Queries**), so `username:noreply@example.com`
    is never indexed. A value its field cannot hold is never indexed either, since no record
    stores one for that field: one the field does not accept as a value at all
    (`ssn:123-45-678`, `email:bobby`), named by another part when its text falls under one
    (`ssn:1234` is a number shorter than 5 digits, `password:unknown` a placeholder word).
    `stats.suppressed_terms` lists blacklisted and never-indexed values only: the index can
    lack another value — a group compaction drops without recording it, for one — and a term on
    one of those comes back empty without being listed, so an empty result is not by itself
    proof of no exposure. A search that runs is billed whatever it could not answer. A query
    whose every identifier term outside a `NOT` is never indexed could only come back empty:
    it is refused with `400 query_not_indexed` and is not billed.

    ## Billing

    Your team buys **credits** in advance, in packs, on [Team → Billing](/team/billing)
    through a hosted checkout; the packs and their prices are listed there. Each `/search`
    request — every page, GET or POST — is charged the credits its lookup kind costs at your
    team's rate card: `scalar`, a query naming one value — one term, a quoted phrase, one
    email address or one phone number, typed or untyped — or `boolean`, any query combining
    two or more terms, with `AND`, `OR` or `NOT` or just by writing them side by side
    (adjacent terms are an `AND`: `john smith` is a `boolean` lookup, `"john smith"` a
    `scalar` one). The rate card is your team's `credit_cost_scalar` and
    `credit_cost_boolean` on `GET /team`, also shown on Team → Billing. A search that costs
    more credits than your team's balance is refused with `402 insufficient_credits` and
    nothing is charged. A
    refused request (`4xx`) is not billed: one refused before it runs is never charged, and
    one refused once it has started (`400 query_too_broad`) is refunded. A search that fails
    on our side is refunded. The exception: when the billing store cannot confirm whether the
    charge or its refund landed (a DynamoDB fault or a deadline cut-off), the search's credits
    can stay spent; such an event is logged (`search_charge_outcome_unknown` /
    `search_refund_failed` with `refund_outcome`) and alarmed, and an operator does not
    reverse it blindly. `/records/*` are not billed. Your team's daily cap (if one is set)
    answers `429 quota_exceeded`. `503 search_busy` (too many of your team's searches at
    once) and `503 search_timeout` carry `cta: retry`.

    A team admin can keep a card on file — the card of the team's latest checkout or card
    setup — and turn on **auto-reload**: the pack the team chose is charged to the card on
    file automatically, with no one asked to confirm it, when a search leaves the balance at
    or below the team's threshold, and when a search is refused because it costs more than
    the balance. The threshold must be below the chosen pack's credits, so one reload always
    lifts the balance above it, and over time the card is charged one pack for each pack's
    worth of credits used. Auto-reload is off — and charges nothing — while it is turned off,
    while there is no card on file, and while it is set to a pack the price list no longer
    sells (a team admin chooses a pack again). Turning it off, or changing or removing the
    card, stops a reload in flight from being sent again — except a send already claimed
    when the change lands, which may still go out; a charge of it that does go through
    still adds its credits — and no new reload starts until that one is settled, its charge
    is refused, or an hour has passed since it was last sent. A reload whose answer did not arrive is otherwise
    sent again at most once for each minute that lapses in its first hour, at most once
    more after that, and never 12 hours after it began.

    A search that sets off a reload answers only once the reload step ends — normally within
    a second or two. A charge is given at most ten seconds, and what follows one that does
    not go through (recording it, the notice email) can add to that; the search's own
    25-second time limit is the bound, so set your client's timeout with that room. A search
    refused for credits (`402 insufficient_credits`) answers `cta: retry` when it can be
    sent again in a moment, and `cta: billing` when auto-reload cannot add credits now and
    they must be bought on Team → Billing; the 402 below lists the outcomes behind each. A
    reload that does not complete pauses auto-reload until a team admin puts a new card on
    file or buys credits at checkout — or, for an `unconfirmed` or `uncredited` reload, until
    that charge's credits arrive after all; saving the settings never resumes it.
    The team's admins who sign in with an email address, and its billing email
    (`billing_email`) when one is set, are emailed once each time the balance runs out —
    when a search is refused for credits and no auto-reload restores the balance — and
    whenever auto-reload is paused. Each purchase links to its receipt, and each closed UTC
    month from the team's first activity — a search, a purchase or an adjustment — gets a
    statement. Team admins see the balance, usage, purchases, receipts and statements under
    [Team → Billing](/team/billing) (`GET /team/billing`).

    ## Redaction

    `socialSecurityNumber` is masked (`***`) for every team by default;
    revealing it is a team-level masking policy that Shadow Identity sets. While your team
    masks SSN, a raw row that carries one, or has ambiguous placement on a dataset that may hold SSNs, answers `403 raw_ssn_record_restricted`. Passwords
    and password hashes are returned as stored, with a server-side `passwordClass` saying which
    one a value is.

    ## Meta envelope

    Every JSON body on the search, record, stats, access-request and account
    routes, errors included, carries `meta.response_ms` beside the route's own fields (a `204`
    has no body). `/search` adds `meta.quota` with `{limit, used, remaining, resets_at}` on
    success and on `429` (`limit` and `remaining` are `null` when the team has no daily cap),
    and `meta.credits` with `{kind, charged, balance}` on success: the search's lookup kind,
    the credits it was charged and your team's balance after the charge.
    An error body is `{error, message?, cta?, meta}`: `error` is a stable code, except that a
    field-validation failure carries its human-readable sentence in `error` itself; `cta` is
    the suggested next step (`login`, `contact`, `billing` or `retry`). The dataset catalog
    (`/datasets*`) carries no `meta`, and neither do two answers any route can give: a request
    rejected before the route runs — `{error: "FST_…", message}`, e.g.
    `400 FST_ERR_CTP_INVALID_JSON_BODY`, `413 FST_ERR_CTP_BODY_TOO_LARGE` (a body over 1 MiB),
    `415 FST_ERR_CTP_INVALID_MEDIA_TYPE` — and a URL no route matches
    (`404 {message, error: "Not Found", statusCode: 404}`).

    ## Links

    Every search result carries `links` to its record, its original row and its
    dataset; a `GET /search` page carries `page.next_url` for the next page.

    ## Account routes are session-only

    `/user*`, `/team*` and `/api-keys*` answer an API-key
    caller `401 session_required` — a key searches; it never manages the account.
    Create and manage keys under [API keys](/api-keys).

servers:
  - url: https://api.shadowidentity.com

tags:
  - name: Search
  - name: Records
  - name: Datasets
  - name: Platform
  - name: Account
  - name: Teams
  - name: API keys
  - name: Access

paths:
  /search:
    get:
      tags: [Search]
      summary: Boolean record search
      description: |
        Search records using boolean operators (`AND` / `OR` / `NOT`, parentheses; adjacent
        terms are an implicit `AND`, and `AND` binds tighter than `OR`) over fields. Quote a
        field's value when it contains spaces: `name:"dana whitfield"`.
        Examples:
          - `email:d.whitfield@example.com`
          - `name:"dana whitfield" AND city:Leeds`
          - `phone:5551234567 OR email:d.whitfield@example.com`
          - `email:d.whitfield@example.com AND NOT state:MA`
          - `email:d.whitfield@example.com AND NOT (city:Boston OR city:Cambridge)`

        `NOT` is a filter, not a set complement: it drops every record its operand matches from
        the whole result, wherever the `NOT` sits, so `email:d.whitfield@example.com OR NOT
        city:Boston` returns that address's records minus the Boston ones. Its operand is a term
        or a group in parentheses, read on each record with an `AND` matching when every operand
        does and an `OR` when any does — unlike outside a `NOT`, an `OR` of narrowing terms under
        it is a true `OR` — and a `NOT` before another `NOT` cancels it. A term matches a record
        whose own fields hold its value, read through the same normalization a search applies:
        `name` / `full_name` is first and last name together, `address` the first line or both lines
        together, an `email` term also matches a username that is that address (so does a `username`
        term for it, which is that `email` term), and `dataset`, `birth_year`, `birth_month` and
        `birth_day` read the record's dataset and date of birth. A record keeps the first value of
        each field; a value its source row held elsewhere — a second column for the field, an
        unlabelled column — is found by a search but not seen by a `NOT`. A search word and a domain
        are taken from every cell of a source row, which a record does not keep, so a `NOT` over
        either (`NOT smith`, `NOT domain:example.com`) is refused with `400 invalid_query` and is
        not billed.

        Identical records are one result, and so is a record a fuller record of its dataset
        contains. On a page, records of one dataset that hold the same value in every field — a
        person repeated across a dataset's daily snapshot files — are returned once; and a record
        whose every value a fuller record of its dataset holds — a file's row with a name and city
        beside its row with a name, city, street and phone — is returned as that fuller record.
        One rule decides both: a record folds under a copy of it, or a record that contains it,
        only where every query term that found it also found that record. A record keeps each
        field's first value, while a search also finds a row by a field's later values and by an
        address in a cell no field keeps, so a record a term found that did not find the other is
        returned as a result of its own, and the value a search was made for stays on a record
        returned. The exception is two values sharing an index key, as values in non-Latin scripts
        can: where a term reaches a row only through such another value, in a cell no field keeps,
        the search cannot tell it from the value searched, and a record that holds the value can
        fold under that row. A query of one term folds on the fields alone. The result's `copies` says how many records it
        stands for, how many source files they came from and how many of them hold fewer fields
        than it; `stats.copies_collapsed` says how many records the page folded, and
        `stats.contained_folded` how many of those held fewer fields. Records of two datasets are
        never folded together, and one value apart — another phone — keeps two records apart. A
        record holding nothing but an email address — a free-text match, or a row of an email-only
        list — is one per line: each line keeps a result of its own, so the text beside the address
        on every line stays reachable through `/records/{id}/raw`. A folded record's file, line and
        raw row are not returned, and its `id` from any page that returned it stays valid. Which
        record stands for a result, and which result counts a record two results both contain,
        depend on the page: they can change as the index changes or with another `limit`. A page
        still reads `limit` matches, and is billed as one search, so records fold only among one
        page's matches: send `limit=1000` to fold a person repeated hundreds of times into one
        result, where the default of 100 shows them once a page.

        Every query needs an identifier term (see **Queries** above): `city:Boston AND NOT state:MA`
        alone is refused with `400 query_needs_identifier`, and `email:noreply@example.com` alone
        with `400 query_not_indexed` (see **Suppressed values**).

        A query is capped at 1024 tokens and 32 levels of parenthesis nesting; past
        either, the route returns `400 invalid_query`. Use `POST /search` for a query too long
        to carry in a URL.

        One search reads at most 2,000,000 records between its identifier values — each value
        counted once, however many terms name it — and at most 128 MB of the index, and its
        `AND` and `OR` groups combine at most 4,000,000 records between them — a group counted
        once, however often and in whatever order or nesting the query repeats it. A query past
        any of these is refused whole with `400 query_too_broad`, never answered from part of
        them, and its charge is refunded (see **Billing** above): search fewer of its values at
        once, or less common ones, or write it with fewer groups.

        Every request is one billable search for your team, charged the credits its lookup kind
        costs (see **Billing** above) once the query validates (a `400` costs nothing:
        `400 query_too_broad`, the one answered after the charge, is refunded). A search that
        costs more credits than your team's balance is refused with `402 insufficient_credits`
        and nothing is charged. A search that fails on our side is refunded. The exception: when
        the billing store cannot confirm whether the charge or its refund landed (a DynamoDB fault
        or a deadline cut-off), the search's credits can stay spent; such an event is
        logged (`search_charge_outcome_unknown` / `search_refund_failed` with `refund_outcome`)
        and alarmed, and an operator does not reverse it blindly. A search that fails after its
        charge answers `500 internal_error`, `500 billing_ledger_corrupt` or `503 search_timeout`;
        `503 team_unavailable`, `503 search_busy`, a `search_timeout` answered before the charge
        (too little time left to start) and a `billing_ledger_corrupt` answered before it are
        never charged.

        There is no `HEAD /search` (`404`): a HEAD would run, and bill, a search whose body is discarded.
      security: [{ apiKey: [] }, { sessionCookie: [] }]
      parameters:
        - { name: q,      in: query, required: true, schema: { type: string }, example: 'email:d.whitfield@example.com', description: "The query, URL-encoded." }
        - { name: limit,  in: query, schema: { type: integer, default: 100, minimum: 1, maximum: 1000 }, description: "Page size. A larger value is clamped to 1000; an unusable one reads as 100." }
        - { name: cursor, in: query, schema: { type: string }, description: Pass page.cursor from a prior response. }
        - { name: fields, in: query, schema: { type: string }, description: "Comma-separated record-key allowlist (repeatable). `datasetId` is always returned." }
      responses:
        "200":
          description: "One page of matching records. `page.next_url` is the GET URL of the next page, `null` on the last."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SearchResponse" }
        "400": { $ref: "#/components/responses/SearchRefused400" }
        "401": { $ref: "#/components/responses/AuthenticationRequired" }
        "402": { $ref: "#/components/responses/InsufficientCredits" }
        "403": { $ref: "#/components/responses/TeamForbidden" }
        "429": { $ref: "#/components/responses/DailyCapReached" }
        "500": { $ref: "#/components/responses/SearchFailed" }
        "503": { $ref: "#/components/responses/SearchUnavailable" }
    post:
      tags: [Search]
      summary: Boolean record search (query in the body)
      description: |
        Identical to `GET /search` — same parameters, same metered charge, same response —
        with the parameters in a JSON body instead of the query string. Use it when the
        query outgrows the URL length the edge will carry, e.g. a footprint narrowed
        with many `NOT` exclusion clauses. The body may be up to 1 MiB.

        `page.next_url` is a GET URL and is `null` here; paginate by sending `page.cursor`
        back in the next request body.
      security: [{ apiKey: [] }, { sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [q]
              properties:
                q:      { type: string, example: 'email:d.whitfield@example.com AND NOT city:Boston' }
                limit:  { type: integer, default: 100, minimum: 1, maximum: 1000, description: "A larger value is clamped to 1000; an unusable one reads as 100." }
                cursor: { type: string, description: Pass page.cursor from a prior response. }
                fields:
                  description: Record-key allowlist — an array, or the same comma-joined string GET takes. `datasetId` is always returned.
                  oneOf:
                    - { type: array, items: { type: string } }
                    - { type: string }
      responses:
        "200":
          description: "One page of matching records. `page.next_url` is always `null`: send `page.cursor` back in the next body."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SearchResponse" }
        "400": { $ref: "#/components/responses/SearchRefused400" }
        "401": { $ref: "#/components/responses/AuthenticationRequired" }
        "402": { $ref: "#/components/responses/InsufficientCredits" }
        "403": { $ref: "#/components/responses/TeamForbidden" }
        "413": { description: "`FST_ERR_CTP_BODY_TOO_LARGE` — the body is over 1 MiB. `{error, message}`, no `meta`. Not billed." }
        "429": { $ref: "#/components/responses/DailyCapReached" }
        "500": { $ref: "#/components/responses/SearchFailed" }
        "503": { $ref: "#/components/responses/SearchUnavailable" }
  /records/{id}:
    get:
      tags: [Records]
      summary: Single record by composite id
      description: Not billed. Requires an active team like `/search`. The record's fields carry the team's SSN masking policy, as on `/search`.
      security: [{ apiKey: [] }, { sessionCookie: [] }]
      parameters:
        - { $ref: "#/components/parameters/RecordId" }
      responses:
        "200":
          description: "The record's fields, with the team's SSN masking policy applied."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RecordResponse" }
        "400": { description: "`invalid_record_id` — not an id `/search` issued, or one issued before a key rotation", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "401": { $ref: "#/components/responses/AuthenticationRequired" }
        "403": { $ref: "#/components/responses/TeamForbidden" }
        "404": { description: "`record_not_found` — the record's bytes are gone", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "413": { description: "`record_too_large` — the record window exceeds the 8 MiB read budget", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /records/{id}/raw:
    get:
      tags: [Records]
      summary: A record's original source row (restricted)
      description: |
        Returns the record's original source: for a structured record, the full original
        row (keyed only by a matching-width header with unique, nonempty labels, else every cell
        in source order as `{columns}`); for a free-text
        match, `{match, context}` — the matched address and its surrounding line, up to 160
        bytes either side. Not billed. Requires an active team. While the caller's team masks
        SSN, a row that carries an SSN value on a dataset whose schema declares an SSN column
        (and any free-text window that carries one) answers `403 raw_ssn_record_restricted`.
        Ambiguous header/row placement is also restricted when the dataset may hold SSNs,
        even when the indexed summary stores no SSN.
      security: [{ apiKey: [] }, { sessionCookie: [] }]
      parameters:
        - { $ref: "#/components/parameters/RecordId" }
      responses:
        "200":
          description: "The complete raw row, keyed by unique matching headers or returned as positional columns."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RawRecordResponse" }
        "400": { description: "`invalid_record_id` — not an id `/search` issued, or one issued before a key rotation", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "401": { $ref: "#/components/responses/AuthenticationRequired" }
        "403": { description: "`team_required`, `team_suspended` (both `cta: contact`), or `raw_ssn_record_restricted` — your team masks SSNs and the row carries one or cannot rule one out because placement is ambiguous", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "404": { description: "`raw_not_available` — the id carries no raw-row pointer; `raw_not_found` — the source is gone, or the id names no match", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "413": { description: "`raw_row_too_large` — the raw row exceeds the 8 MiB read budget", content: { application/json: { schema: { $ref: "#/components/schemas/ErrorBody" } } } }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /stats:
    get:
      tags: [Platform]
      summary: Platform stats
      description: |
        The latest daily snapshot over the public catalog, every dataset whose import completed
        (the population `GET /datasets` lists): how many there are (`breach_count`), the records
        they hold (`record_count`) and their distinct sources (`source_count`; a dataset with no
        source counts toward the other two only), refreshed once a day after 03:00 UTC. Before
        the first snapshot, `date` is `null` and every count is `0`.
      security: []
      responses:
        "200":
          description: The latest snapshot.
          content:
            application/json:
              schema:
                type: object
                properties:
                  stats:
                    type: object
                    properties:
                      date: { type: [string, "null"], format: date }
                      breach_count: { type: integer }
                      record_count: { type: integer }
                      source_count: { type: integer }
                  meta: { $ref: "#/components/schemas/Meta" }
  /datasets:
    get:
      tags: [Datasets]
      summary: The public dataset catalog
      description: Every dataset whose import completed — the target of each search result's `links.dataset` — newest first, up to 5,000.
      security: []
      responses:
        "200":
          description: "`{datasets: [Dataset]}`"
          content:
            application/json:
              schema:
                type: object
                properties:
                  datasets: { type: array, items: { $ref: "#/components/schemas/Dataset" } }
        "500": { description: "`{error: \"Internal server error\"}` — the catalog could not be read" }
  /datasets/search:
    get:
      tags: [Datasets]
      summary: Find datasets by id or source
      description: Case-insensitive substring match on a dataset's id or source (its attribution) across the public catalog, newest first — the order of `GET /datasets`.
      security: []
      parameters:
        - { name: q, in: query, required: true, schema: { type: string, minLength: 3 }, description: "At least 3 characters after trimming." }
        - { name: limit, in: query, schema: { type: integer, default: 20, minimum: 1, maximum: 50 }, description: "A larger value is clamped to 50." }
      responses:
        "200":
          description: The matching datasets.
          content:
            application/json:
              schema:
                type: object
                properties:
                  datasets:
                    type: array
                    items:
                      type: object
                      properties:
                        datasetId: { type: string }
                        source: { type: string, description: "The attribution — an origin domain or a threat actor; absent when the dataset is unattributed, never null or empty." }
                        recordCount: { type: [integer, "null"], description: "The dataset's record total as its last terminal rollup counted it; null until the dataset's first terminal rollup has counted it, never a 0 nobody counted." }
                        category: { type: [string, "null"] }
        "400": { description: "`query_too_short` — `q` is under 3 characters. `{error, message}`" }
        "500": { description: "`{error: \"Internal server error\"}` — the catalog could not be read" }
  /datasets/{id}:
    get:
      tags: [Datasets]
      summary: One dataset, with a page of its source files
      description: |
        The dataset, one page of its source files, and two dataset-wide aggregates: `fields`
        (the record fields its files carry) and `availableIndexTypes` (the indexed terms a
        query scoped to it can use). Page through the files with `cursor`; continuation pages
        return both aggregates as `null`. `files` (repeatable, or comma-joined) looks up those
        files instead, the first 100 distinct keys — a search result's `source.fileKey` is such
        a key — and returns `unresolvedFiles` for the ones that match no file; the aggregates
        then cover the files found only.
      security: []
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: cursor, in: query, schema: { type: string }, description: "`nextCursor` from the previous page, sent once." }
        - { name: limit, in: query, schema: { type: integer, default: 100, minimum: 1, maximum: 500 }, description: "Files per page. A larger value is clamped to 500; an unusable one reads as 100." }
        - { name: files, in: query, schema: { type: string }, description: "File keys to look up. The first 100 distinct keys are resolved; further keys are ignored and are not listed in `unresolvedFiles`, so send a longer list over several requests." }
      responses:
        "200":
          description: The dataset and a page of its files.
          content:
            application/json:
              schema:
                type: object
                properties:
                  dataset: { $ref: "#/components/schemas/Dataset" }
                  files:
                    type: array
                    items:
                      type: object
                      properties:
                        filename: { type: string }
                        recordCount: { type: integer, description: "The records this file's import wrote (the file row's own count)." }
                        schema: { type: [object, "null"], description: "The file's detected structure." }
                        availableIndexTypes: { type: array, items: { type: string } }
                  nextCursor: { type: [string, "null"], description: "`null` on the last page and in a `files` lookup." }
                  fields: { type: [array, "null"], items: { type: string } }
                  availableIndexTypes: { type: [array, "null"], items: { type: string } }
                  unresolvedFiles: { type: array, items: { type: string }, description: "`files` lookups only: the keys looked up that match no file." }
        "400": { description: "`invalid_cursor` — the cursor is not one this dataset issued. `{error, message}`" }
        "404": { description: "No such dataset: `{error: \"Dataset '<id>' not found\"}`" }
        "500": { description: "`{error: \"Internal server error\"}` — the catalog could not be read" }
  /access-requests:
    post:
      tags: [Access]
      summary: Request access (sales form)
      description: |
        Public. Stores the request for the Shadow Identity team and notifies sales; you
        will hear back by email. At most 5 new submissions per source address, and 25 per source
        network (an IPv4 /24 or an IPv6 /48), per UTC day; and at most 500 new requests stored
        per UTC day across every source: past that, every new submission is refused until the
        next UTC midnight. The `website` field is a honeypot and must be omitted or empty.

        Generate `request_id` (a lower-case UUID v4) per submission and send the same value
        when you retry the same values; changed values are a new submission with a new id. A
        repeat with a `request_id` already stored answers `201 {request_id}`, stores nothing
        new and counts against no daily limit — a retry of a stored submission is never refused
        with `429`.

        A stored request is never lost: when the sales email cannot go out (the day's alert
        limit, or a send failure), it waits in the Shadow Identity inbox for review. A send
        whose delivery is unconfirmed is not repeated automatically by a submission retry.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [request_id, company, full_name, work_email, use_case]
              properties:
                request_id: { type: string, format: uuid, pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", description: "Client-generated UUID v4 in canonical lower case — the stored request's id. Re-send it unchanged on a retry of the same values." }
                company:    { type: string, minLength: 1, maxLength: 200 }
                full_name:  { type: string, minLength: 1, maxLength: 200 }
                work_email: { type: string, format: email, maxLength: 254 }
                role:       { type: [string, "null"], maxLength: 120, description: "Blank reads as `null`." }
                use_case:   { type: string, minLength: 20, maxLength: 4000, description: "What you want to look up, and where the results go." }
                expected_monthly_searches:
                  type: [string, "null"]
                  enum: [under_10k, 10k_100k, 100k_1m, over_1m, "", null]
                  description: "`\"\"` reads as `null`."
                message:    { type: [string, "null"], maxLength: 4000, description: "Blank reads as `null`." }
                website:    { type: string, maxLength: 0, description: "Honeypot — leave empty." }
      responses:
        "201":
          description: "`{request_id, meta}` — the submitted `request_id`, whether this call stored the request or an earlier one with the same id did."
          content:
            application/json:
              schema:
                type: object
                properties:
                  request_id: { type: string, format: uuid }
                  meta: { $ref: "#/components/schemas/Meta" }
        "400":
          description: "`invalid_request`, with `fields: {<name>: <sentence>}` naming every invalid field (lengths are measured after trimming)."
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string, const: invalid_request }
                  fields: { type: object, additionalProperties: { type: string } }
                  meta: { $ref: "#/components/schemas/Meta" }
        "429":
          description: "`rate_limited` — the source address's 5 new submissions for the UTC day, or its network's 25 (an IPv4 /24 or an IPv6 /48), are spent; `message` names which. `access_requests_paused` — the day's 500 stored requests, across every source, are reached, and nothing is stored. Either way `resets_at` is the next UTC midnight."
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string, enum: [rate_limited, access_requests_paused] }
                  message: { type: string }
                  resets_at: { type: string, format: date-time }
                  meta: { $ref: "#/components/schemas/Meta" }
  /auth/login:
    post:
      tags: [Account]
      summary: Exchange a Sparkvault JWT for a session cookie
      description: Sets the `si_session` cookie (HttpOnly, 7 days) and places the account on its team.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              properties:
                token: { type: string, description: Sparkvault-issued JWT }
      responses:
        "200":
          description: "Session cookie set; `{user, meta}`."
          content:
            application/json:
              schema:
                type: object
                properties:
                  user: { $ref: "#/components/schemas/PublicUser" }
                  meta: { $ref: "#/components/schemas/Meta" }
        "400": { description: "No `token` string in the body." }
        "401": { description: "`invalid_token` — the token does not verify, or its `sub` is not a usable account id." }
        "403": { description: "`account_deleted` — the account is deleted." }
  /auth/logout:
    post:
      tags: [Account]
      summary: Clear the session cookie
      description: Needs no session; always succeeds.
      security: []
      responses:
        "204": { description: cookie cleared }
  /user:
    get:
      tags: [Account]
      summary: Current user
      security: [{ sessionCookie: [] }]
      responses:
        "200":
          description: "`{user, meta}` — a team that no longer exists reads as no team (`team_id`, `team_role` and `team_name` `null`)."
          content:
            application/json:
              schema:
                type: object
                properties:
                  user: { $ref: "#/components/schemas/PublicUser" }
                  meta: { $ref: "#/components/schemas/Meta" }
        "401": { $ref: "#/components/responses/SessionRequired" }
    patch:
      tags: [Account]
      summary: Set your display name
      description: The email is your verified login identity and cannot be changed here — a body carrying `email` is refused with `400`.
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [full_name]
              properties:
                full_name: { type: [string, "null"], maxLength: 200, description: "Trimmed; `null` or a blank string clears it. A control character other than tab and newline is refused (`400 full_name must not contain control characters other than tab and newline`)." }
      responses:
        "200":
          description: "`{user, meta}` — the updated user."
          content:
            application/json:
              schema:
                type: object
                properties:
                  user: { $ref: "#/components/schemas/PublicUser" }
                  meta: { $ref: "#/components/schemas/Meta" }
        "400": { description: "`full_name` missing, invalid or carrying a control character other than tab and newline, or `email` sent; the sentence is in `error`" }
        "401": { $ref: "#/components/responses/SessionRequired" }
    delete:
      tags: [Account]
      summary: Delete your account and revoke all keys
      description: Deletes the account, revokes every API key and clears the session cookie. A team admin who is the team's last admin, while the team has other members, must make another member an admin first.
      security: [{ sessionCookie: [] }]
      responses:
        "204": { description: deleted }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "409":
          description: "`last_admin` — you are the last admin of a team that has other members; `membership_changed` — your team membership changed while the request ran (reload and retry). Nothing was deleted."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
  /user/quota:
    get:
      tags: [Account]
      summary: Today's team usage, credit balance and rate card + your 14-day history
      security: [{ sessionCookie: [] }]
      responses:
        "200":
          description: "`used` counts the whole team's searches today; `limit`/`remaining` are `null` without a daily cap; `credits_balance` is your team's credit balance and `credit_cost_scalar` / `credit_cost_boolean` its rate card (see **Billing**); `history` is your own 14-day series of charged searches made while signed in (API-key searches are counted per key), every day present; `team_required` is `true` when the account has no team."
          content:
            application/json:
              schema:
                type: object
                properties:
                  quota: { $ref: "#/components/schemas/Quota" }
                  credits_balance: { type: [integer, "null"], minimum: 0, description: "Credits your team can still spend; `null` for an account with no team, and for the operator's own team, which is never billed." }
                  credit_cost_scalar: { type: [integer, "null"], minimum: 0, description: "Credits one `scalar` lookup costs your team; `null` for an account with no team." }
                  credit_cost_boolean: { type: [integer, "null"], minimum: 0, description: "Credits one `boolean` lookup costs your team; `null` for an account with no team." }
                  history:
                    type: array
                    items:
                      type: object
                      properties:
                        date: { type: string, format: date }
                        count: { type: integer }
                  team_required: { type: boolean }
                  meta: { $ref: "#/components/schemas/Meta" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "500":
          description: "`billing_ledger_corrupt` — a row of your team's billing record cannot be read, so today's usage can't be shown until Shadow Identity repairs it. Retrying won't help; contact us. `{error, message, meta}`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /team:
    get:
      tags: [Teams]
      summary: Your team
      description: "Members see the team and its roster; `invites` and `domains` are empty unless you are a team admin. `invited_by` / `added_by` show a current member's user id, or `outside_team` for anyone else (Shadow Identity staff, a former member)."
      security: [{ sessionCookie: [] }]
      responses:
        "200":
          description: "`{team, role, members, invites, domains, meta}`; `{team: null, meta}` when the account has no team or its team has been deleted."
          content:
            application/json:
              schema:
                type: object
                properties:
                  team: { oneOf: [{ $ref: "#/components/schemas/PublicTeam" }, { type: "null" }] }
                  role: { type: string, enum: [admin, member] }
                  members:
                    type: array
                    items:
                      type: object
                      properties:
                        user_id: { type: string }
                        email: { type: string }
                        full_name: { type: [string, "null"] }
                        team_role: { type: string, enum: [admin, member] }
                  invites:
                    type: array
                    items:
                      type: object
                      properties:
                        email: { type: string }
                        team_role: { type: string, enum: [admin, member] }
                        status: { type: string, enum: [pending, accepted] }
                        invited_by: { type: string }
                        created_at: { type: string, format: date-time }
                  domains:
                    type: array
                    items:
                      type: object
                      properties:
                        domain: { type: string }
                        verified_at: { type: string, format: date-time }
                        added_by: { type: string }
                  meta: { $ref: "#/components/schemas/Meta" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
    patch:
      tags: [Teams]
      summary: Rename your team / set its billing contact (team admin)
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string, minLength: 1, maxLength: 100, description: "Trimmed, then 1–100 characters. A control character other than tab and newline is refused with a `400` sentence of its own." }
                billing_email: { type: [string, "null"], format: email, description: "Where billing notices (the balance running out, auto-reload paused) are also sent, beside the team's admins who sign in with an email address. `null` clears it." }
      responses:
        "200":
          description: "`{team, meta}` — the updated team."
          content:
            application/json:
              schema:
                type: object
                properties:
                  team: { $ref: "#/components/schemas/PublicTeam" }
                  meta: { $ref: "#/components/schemas/Meta" }
        "400":
          description: "The route's refusal, its sentence in `error`: `name must be a string 1–100 chars`, `name must not contain control characters other than tab and newline`, `billing_email must be a valid email or null`, or `No fields to update`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminChangeForbidden" }
        "409":
          description: "`super_admin_team_not_billed` — `billing_email` sent for the operator's own team, which is never billed."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /team/billing:
    get:
      tags: [Teams]
      summary: Credits, usage, purchases and statements for your team (team admin)
      security: [{ sessionCookie: [] }]
      parameters:
        - { name: months, in: query, schema: { type: integer, minimum: 1, maximum: 24, default: 12 }, description: "How many months to return: at most this many, from the current month back, never before the month your team was created." }
      responses:
        "200":
          description: Billing report. Usage is counted in credits; every money figure is USD.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TeamBilling" }
        "400":
          description: "`months` is not a whole number from 1 to 24; the sentence is in `error`."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminForbidden" }
        "500": { $ref: "#/components/responses/BillingLedgerCorrupt" }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /team/billing/statements/{period}:
    get:
      tags: [Teams]
      summary: One month's statement (team admin)
      description: "The statement of a closed UTC month with its line items: each day's usage and each credit ledger entry of the month. A month's statement is generated once, from 01:00 UTC on the 1st of the following month, and never changes; `has_statement` on each entry of `GET /team/billing`'s `months` says which months have one."
      security: [{ sessionCookie: [] }]
      parameters:
        - { name: period, in: path, required: true, schema: { type: string, pattern: "^[0-9]{4}-(0[1-9]|1[0-2])$" }, example: "2026-10", description: "The calendar month (UTC), `YYYY-MM`." }
      responses:
        "200":
          description: "The statement. Usage is counted in credits; every money figure is USD."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TeamStatement" }
        "400":
          description: "`invalid_period` — `period` is not a `YYYY-MM` month."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminForbidden" }
        "404":
          description: "`statement_not_found` — your team has no statement for that month: it has not closed and been generated yet, it falls before your team's first search or credit entry, or your team is the operator's own, which is never billed."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "500": { $ref: "#/components/responses/BillingLedgerCorrupt" }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /team/billing/purchases/{entryId}/receipt:
    get:
      tags: [Teams]
      summary: A purchase's receipt (team admin)
      description: "The payment processor's receipt page for a purchase's card charge. The link is valid for a limited time, so none is stored: ask for a fresh one each time it is needed."
      security: [{ sessionCookie: [] }]
      parameters:
        - { name: entryId, in: path, required: true, schema: { type: string, pattern: "^[A-Za-z0-9_-]{1,128}$" }, description: "A purchase's `entry_id`." }
      responses:
        "200":
          description: "`{url, meta}` — the receipt page."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ReceiptAnswer" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminForbidden" }
        "404":
          description: "`purchase_not_found` — no purchase of your team has that id: an id outside the pattern, an unknown id, another team's, or an entry that is not a purchase; `receipt_unavailable` — the payment processor has no receipt for the charge, or answered with a receipt address off its own domain, which is never passed on."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "500": { $ref: "#/components/responses/BillingLedgerCorrupt" }
        "503": { $ref: "#/components/responses/PaymentsUnavailable" }
  /team/billing/checkout:
    post:
      tags: [Teams]
      summary: Buy a pack of credits (team admin)
      description: |
        Opens the payment processor's hosted checkout for one pack of credits; send the browser
        to the `url` answered. The packs and their prices are the ones Team → Billing lists. The
        hosted page returns the browser to `/team/billing?purchase=success` once it is
        completed, or `/team/billing?purchase=canceled` when it is canceled, and expires 60
        minutes after the request that created it. The credits are added only when the payment processor
        confirms the charge, never by the return itself, and the charge's card becomes the
        team's card on file.
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [pack_id]
              properties:
                pack_id: { type: string, enum: [pack_1k, pack_5k, pack_25k, pack_100k, pack_500k, pack_1m, pack_5m], description: "The id of a pack on the price list Team → Billing shows." }
      responses:
        "200":
          description: "`{url, meta}` — the hosted checkout page."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HostedPageAnswer" }
        "400":
          description: "`unknown_pack` — `pack_id` is missing, not a string, or names no pack on the price list."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminChangeForbidden" }
        "409":
          description: "`super_admin_team_not_billed` — the operator's own team, which is never billed, buys no credits."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "500": { $ref: "#/components/responses/BillingLedgerCorrupt" }
        "503": { $ref: "#/components/responses/PaymentsUnavailable" }
  /team/billing/payment-method:
    post:
      tags: [Teams]
      summary: Save a card on file (team admin)
      description: |
        Opens the payment processor's hosted card setup; send the browser to the `url`
        answered. The hosted page returns the browser to `/team/billing?card=saved` once it is
        completed, or `/team/billing?card=canceled` when it is canceled, and expires 60
        minutes after the request that created it. The card becomes the team's card on file when the payment
        processor confirms its setup, never by the return itself; it replaces the card before
        it, and a saved card lifts a paused auto-reload. No body.
      security: [{ sessionCookie: [] }]
      responses:
        "200":
          description: "`{url, meta}` — the hosted card setup page."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/HostedPageAnswer" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminChangeForbidden" }
        "409":
          description: "`super_admin_team_not_billed` — the operator's own team, which is never billed, keeps no card."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "500": { $ref: "#/components/responses/BillingLedgerCorrupt" }
        "503": { $ref: "#/components/responses/PaymentsUnavailable" }
    delete:
      tags: [Teams]
      summary: Remove the card on file (team admin)
      description: "Removes the team's card on file; `auto_reload_state` reads `off` until a card is saved again. With no card on file the account is answered unchanged."
      security: [{ sessionCookie: [] }]
      responses:
        "200":
          description: "`{account, meta}` — the team's credit account as the removal left it."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BillingAccountAnswer" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminChangeForbidden" }
        "409":
          description: "`super_admin_team_not_billed` — the operator's own team, which is never billed, keeps no card."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "500": { $ref: "#/components/responses/BillingLedgerCorrupt" }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /team/billing/auto-reload:
    patch:
      tags: [Teams]
      summary: Set auto-reload (team admin)
      description: |
        Saves the team's auto-reload settings whole: every field is required and saved as sent.
        While `enabled`, the pack `pack_id` names is charged to the card on file automatically,
        with no one asked to confirm it, when a search leaves the balance at or below
        `threshold_credits` and when a search costs more than the balance. `threshold_credits`
        must be below the pack's credits, so one reload always lifts the balance above it.
        Turning auto-reload off stops a reload in flight from being sent again, except a send
        already claimed when the save lands, which may still go out. Saving does not
        lift a paused auto-reload (`auto_reload_state` `failed`): a new card on file
        (`POST /team/billing/payment-method`) or a purchase at checkout does.
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - { $ref: "#/components/schemas/AutoReloadSettings" }
                - type: object
                  properties:
                    pack_id: { type: string, enum: [pack_1k, pack_5k, pack_25k, pack_100k, pack_500k, pack_1m, pack_5m], description: "A pack on the price list Team → Billing shows." }
      responses:
        "200":
          description: "`{account, meta}` — the team's credit account as the save left it."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BillingAccountAnswer" }
        "400":
          description: "The route's refusal, its sentence in `error`: `enabled` is not a boolean; `threshold_credits` is not a whole number of credits from 0 to 4,999,999; or it is not below the chosen pack's credits, which the sentence names. Or `unknown_pack` — `pack_id` is missing, not a string, or names no pack on the price list."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { $ref: "#/components/responses/TeamAdminChangeForbidden" }
        "409":
          description: "`no_payment_method` — `enabled` is `true` and the team has no card on file: save one first (`POST /team/billing/payment-method`, or a checkout); `super_admin_team_not_billed` — the operator's own team, which is never billed, has no auto-reload."
          content:
            application/json:
              schema: { $ref: "#/components/schemas/ErrorBody" }
        "500": { $ref: "#/components/responses/BillingLedgerCorrupt" }
        "503": { $ref: "#/components/responses/TeamUnavailable" }
  /api-keys:
    get:
      tags: [API keys]
      summary: List your API keys
      security: [{ sessionCookie: [] }]
      responses:
        "200":
          description: "`{keys, meta}` — no plaintext."
          content:
            application/json:
              schema:
                type: object
                properties:
                  keys: { type: array, items: { $ref: "#/components/schemas/ApiKey" } }
                  meta: { $ref: "#/components/schemas/Meta" }
        "401": { $ref: "#/components/responses/SessionRequired" }
    post:
      tags: [API keys]
      summary: Create an API key
      description: A key's searches draw on your team's credits at its rate card, so the account must belong to a team. The key is bound to that team and works only while you remain on it.
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [label]
              properties:
                label: { type: string, minLength: 1, maxLength: 100, description: "Trimmed. A control character other than tab and newline is refused (`400 label must not contain control characters other than tab and newline`)." }
      responses:
        "201":
          description: "`{plaintext, key, meta}`. The plaintext is shown exactly once."
          content:
            application/json:
              schema:
                type: object
                properties:
                  plaintext: { type: string, description: "`sk_si_…` — store it now; it is never shown again." }
                  key: { $ref: "#/components/schemas/ApiKey" }
                  meta: { $ref: "#/components/schemas/Meta" }
        "400":
          description: "Invalid label (blank, over 100 characters, or carrying a control character other than tab and newline), or the limit of 100 unrevoked keys is reached — revoke unused keys first (an inactive key counts until it is revoked). The sentence is in `error`."
        "401": { $ref: "#/components/responses/SessionRequired" }
        "403": { description: "`team_required` — the account has no team" }
  /api-keys/{keyHash}:
    delete:
      tags: [API keys]
      summary: Revoke a key
      security: [{ sessionCookie: [] }]
      parameters:
        - { name: keyHash, in: path, required: true, schema: { type: string } }
      responses:
        "204": { description: "revoked (revoking a revoked key succeeds)" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "404": { description: "`key_not_found` — not your key (or it doesn't exist)" }
  /api-keys/{keyHash}/usage:
    get:
      tags: [API keys]
      summary: 90-day daily usage for a key
      security: [{ sessionCookie: [] }]
      parameters:
        - { name: keyHash, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: "`{key, usage: [{date, count}], meta}` — the key's charged searches, one entry per UTC day with any in the last 90 days (refused searches are not counted)."
          content:
            application/json:
              schema:
                type: object
                properties:
                  key: { $ref: "#/components/schemas/ApiKey" }
                  usage:
                    type: array
                    items:
                      type: object
                      properties:
                        date: { type: string, format: date }
                        count: { type: integer }
                  meta: { $ref: "#/components/schemas/Meta" }
        "401": { $ref: "#/components/responses/SessionRequired" }
        "404": { description: "`key_not_found` — not your key (or it doesn't exist)" }

components:
  responses:
    SearchRefused400:
      description: |
        Not billed. `missing_query` — no `q`. `invalid_query` — malformed, over 1024 tokens or
        32 levels of nesting, or a `NOT` over a search word or a domain (the message names each).
        `query_needs_identifier` — no identifier term outside a `NOT`, so the query could never
        match (the message names the identifier and narrowing fields). `query_not_indexed` —
        every identifier term outside a `NOT` has a value that is never indexed (see
        **Suppressed values**), so the query could only come back empty; the message names each
        such value once — normalized, or as typed when its field cannot hold it — with why, and
        says nothing was charged. `query_too_broad` — the query's identifier values are in more
        than 2,000,000 records between them, or would have it read more than 128 MB of the index,
        or its `AND` and `OR` groups would combine more than 4,000,000 records between them (the
        message says which), so no part of it is answered; refused once the search has started,
        so its charge is refunded as **Billing** describes.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    AuthenticationRequired:
      description: "`authentication_required` (`cta: login`) — no session and no valid API key. Not billed."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    SessionRequired:
      description: "`session_required` — no signed-in session (an API key is refused)."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    InsufficientCredits:
      description: |
        `insufficient_credits` — the search costs more credits than your team's balance;
        nothing was charged. `cta: retry` — the search can be sent again in a moment: the
        balance read after the refusal already covers it; an auto-reload settled inside the
        request; an attempt that can still add credits is in flight, or one that was due could
        not be sent in the time the request had; or nothing is in flight and auto-reload can
        run, but this request did not get to add credits (its step failed part-way, or it only
        cleared an earlier attempt away) — a retry runs the step again. `cta: billing` —
        auto-reload cannot add credits now: it is off or paused, or an attempt the team has
        since voided still holds its place; credits must be bought on Team → Billing. Act on
        `cta`, not on `billing.auto_reload`.
        `billing` carries the balance as read right after the refusal — before anything the
        request then did about the shortfall, so a reload it settled is not in it — the
        credits the search needed, its lookup kind, and `auto_reload`. `message` is one fixed
        sentence per outcome, as in the examples.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/InsufficientCreditsRefusal" }
          examples:
            reloaded:
              summary: An auto-reload just added credits — retry
              value:
                error: insufficient_credits
                cta: retry
                message: "Your team's credits do not cover this search. An auto-reload just added credits: retry the search."
                billing: { credits_balance: 2, credits_required: 3, lookup_kind: boolean, auto_reload: armed }
                meta: { response_ms: 1840 }
            reloading:
              summary: An auto-reload is under way — retry in a moment
              value:
                error: insufficient_credits
                cta: retry
                message: "Your team's credits do not cover this search. An auto-reload is under way: retry in a moment."
                billing: { credits_balance: 2, credits_required: 3, lookup_kind: boolean, auto_reload: pending }
                meta: { response_ms: 412 }
            interrupted:
              summary: This request did not get to add credits — a retry runs the auto-reload step again
              value:
                error: insufficient_credits
                cta: retry
                message: "Your team's credits do not cover this search. Its auto-reload could not be run just now: retry in a moment."
                billing: { credits_balance: 2, credits_required: 3, lookup_kind: boolean, auto_reload: armed }
                meta: { response_ms: 61 }
            credits_landed:
              summary: The balance now covers the search — retry
              value:
                error: insufficient_credits
                cta: retry
                message: "Your team's credits did not cover this search when it was sent, but its balance now covers it. Retry the search."
                billing: { credits_balance: 25000, credits_required: 3, lookup_kind: boolean, auto_reload: "off" }
                meta: { response_ms: 52 }
            add_credits:
              summary: Auto-reload is off — buy credits
              value:
                error: insufficient_credits
                cta: billing
                message: "Your team's credits do not cover this search. Auto-reload is off: credits are added only when a team admin buys them. Credits are bought under Team → Billing."
                billing: { credits_balance: 0, credits_required: 1, lookup_kind: scalar, auto_reload: "off" }
                meta: { response_ms: 38 }
            paused:
              summary: Auto-reload is paused — put a new card on file or buy credits
              value:
                error: insufficient_credits
                cta: billing
                message: "Your team's credits do not cover this search. Auto-reload is paused. A team admin can resume it by putting a new card on file or buying credits. Credits are bought under Team → Billing."
                billing: { credits_balance: 1, credits_required: 3, lookup_kind: boolean, auto_reload: failed }
                meta: { response_ms: 44 }
    TeamForbidden:
      description: "`team_required` — the account is not attached to a team; `team_suspended` — the team is suspended. Both `cta: contact`. Not billed."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    DailyCapReached:
      description: "`quota_exceeded` (`reason: daily_cap`, `cta: contact`) — the team's daily cap is reached until midnight UTC; `meta.quota` carries the count. Not billed."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    TeamUnavailable:
      description: "`team_unavailable` — the team's configuration could not be read; retry."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    TeamAdminForbidden:
      description: "`team_required` — the account has no team, or its team has been deleted; `team_admin_required` — the caller is not a team admin."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    TeamAdminChangeForbidden:
      description: "`team_required` — the account has no team, or its team has been deleted; `team_admin_required` — the caller is not a team admin; `team_suspended` (`cta: contact`) — the team is suspended and cannot be changed."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    BillingLedgerCorrupt:
      description: "`billing_ledger_corrupt` — a row of your team's billing record cannot be read, so the request can't be answered until Shadow Identity repairs it. Retrying won't help; contact us. `{error, message, meta}`."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    PaymentsUnavailable:
      description: "Retry. `payments_unavailable` (`cta: retry`) — the payment processor could not be reached. `team_unavailable` — the team's configuration could not be read."
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    SearchFailed:
      description: |
        `internal_error` — the search failed on our side. A search that fails on our side is
        refunded. The exception: when the billing store cannot confirm whether the charge or its
        refund landed (a DynamoDB fault or a deadline cut-off), the search's credits can stay
        spent; such an event is logged (`search_charge_outcome_unknown` /
        `search_refund_failed` with `refund_outcome`) and alarmed, and an operator does not
        reverse it blindly. `billing_ledger_corrupt` (`cta: contact`) — a row of your team's
        billing record cannot be read: a search refused before its charge is not billed, and a
        charged search whose usage count or credit account cannot be read back after its charge
        is refunded. Retrying won't help
        until Shadow Identity repairs the row; contact us. `{error, cta, message, meta}`.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
    SearchUnavailable:
      description: |
        Retry. `team_unavailable` — the team's configuration could not be read; not billed.
        `search_busy` (`cta: retry`, `Retry-After: 1`) — too many of the team's searches were
        updating its balance at once; not billed. `search_timeout` (`cta: retry`) — too little of
        the search's time budget was left to start (not billed), or the search ran past its
        budget, and its charge is refunded as **Billing** describes.
      headers:
        Retry-After:
          description: Seconds to wait before retrying (`search_busy`).
          schema: { type: integer }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/ErrorBody" }
  parameters:
    RecordId:
      name: id
      in: path
      required: true
      description: "The opaque, signed `id` of a `/search` result, sent exactly as issued. Only the server can mint one."
      schema: { type: string }
  schemas:
    Meta:
      type: object
      required: [response_ms]
      properties:
        response_ms: { type: integer }
        quota:
          description: "`/search` only."
          allOf:
            - { $ref: "#/components/schemas/Quota" }
        credits:
          description: "`/search` only, on success."
          allOf:
            - { $ref: "#/components/schemas/CreditsState" }
    CreditsState:
      type: object
      description: "What a metered search cost your team, and the balance it left."
      required: [kind, charged, balance]
      properties:
        kind: { $ref: "#/components/schemas/LookupKind" }
        charged: { type: integer, minimum: 0, description: "Credits charged for the search: its lookup kind's cost on your team's rate card." }
        balance: { type: [integer, "null"], minimum: 0, description: "Your team's credit balance after the charge; `null` for the operator's own team, which is never billed." }
    LookupKind:
      type: string
      enum: [scalar, boolean]
      description: "The kind of lookup a search is metered as. `scalar` — a query naming one value: one term, a quoted phrase, one email address or one phone number, typed or untyped. `boolean` — any query combining two or more terms, with `AND`, `OR` or `NOT` or by writing them side by side (adjacent terms are an `AND`)."
    Quota:
      type: object
      description: "`limit` and `remaining` are `null` when the team has no daily cap."
      properties:
        limit: { type: [integer, "null"] }
        used: { type: integer, description: "The whole team's searches today (UTC)." }
        remaining: { type: [integer, "null"] }
        resets_at: { type: string, format: date-time, description: "The next midnight UTC." }
    ErrorBody:
      type: object
      required: [error, meta]
      properties:
        error: { type: string, description: "Stable code, e.g. `team_required`; a field-validation failure carries its sentence here instead." }
        message: { type: string, description: "A human-readable explanation." }
        cta: { type: string, enum: [login, contact, billing, retry], description: "The suggested next step: `login` — sign in again; `contact` — reach us; `billing` — add credits on Team → Billing; `retry` — send the same request again." }
        reason: { type: string, description: "Qualifies `quota_exceeded`: `daily_cap`." }
        meta: { $ref: "#/components/schemas/Meta" }
    InsufficientCreditsRefusal:
      allOf:
        - { $ref: "#/components/schemas/ErrorBody" }
        - type: object
          required: [cta, message, billing]
          properties:
            billing: { $ref: "#/components/schemas/InsufficientCreditsBilling" }
    InsufficientCreditsBilling:
      type: object
      description: "Your team's balance, what the refused search would have cost, and where your team's auto-reload stands."
      required: [credits_balance, credits_required, lookup_kind, auto_reload]
      properties:
        credits_balance: { type: integer, minimum: 0 }
        credits_required: { type: integer, minimum: 1, description: "Credits the search costs: its lookup kind's cost on your team's rate card." }
        lookup_kind: { $ref: "#/components/schemas/LookupKind" }
        auto_reload:
          $ref: "#/components/schemas/AutoReloadState"
          description: "Where your team's auto-reload stands as this request knows it once it has done what it could: the account's state as read, moved on by what the request itself did — `armed` after a reload it settled, `pending` while one awaits confirmation or is due to be sent again, `failed` after one it recorded as failed. It is not the decision: what to do is the refusal's `cta`."
    RecordLinks:
      type: object
      properties:
        self: { type: string, description: "`GET /records/{id}`" }
        raw: { type: string, description: "`GET /records/{id}/raw`" }
        dataset: { type: string, description: "`GET /datasets/{id}`" }
    PasswordClass:
      type: object
      description: "Server-side classification of the record's `password`, present only when the record carries one."
      properties:
        kind: { type: string, enum: [raw, hashed] }
        hashType: { type: [string, "null"], description: "Best-effort hash family when `kind` is `hashed`, e.g. `md5crypt`, `sha512crypt`; `null` for `raw`." }
    SearchRecord:
      type: object
      required: [id, datasetId, fields, source, copies, links]
      properties:
        id: { type: string, description: "Opaque, signed record id — send it back exactly as issued." }
        datasetId: { type: string }
        fields:
          type: object
          additionalProperties: true
          description: "The record's non-empty fields by record key (`datasetId`, `email`, `firstName`, `phoneNumber`, `socialSecurityNumber`, `password`, …), narrowed by `fields` when sent (`datasetId` always stays). `socialSecurityNumber` is masked under the team's masking policy. A free-text match carries `datasetId` and `email` only."
        source:
          type: object
          description: "Where this occurrence was found."
          properties:
            file: { type: string, description: "Human-readable file label; empty for a free-text match." }
            fileKey: { type: [string, "null"], description: "The key `GET /datasets/{id}?files=` takes; `null` for a free-text match." }
            line: { type: integer, description: "1-based line; for a free-text match, the match's 1-based byte position." }
        copies:
          type: object
          description: "The records on this page this result stands for: its copies and the records it contains, each found by no query term that did not find this result. Two records are copies when they are in the same dataset and every field holds the same value, or none; where each was found — its file and line — is no part of it, except for a record holding nothing but an email address, whose copies are second readings of its own line. A record is contained in another of its dataset that holds every field it holds, with the same value, and a field more. A record folds under a copy, or a record that contains it, only where every query term that found it also found that record, and then under the first such record, in page order, that folds under no other. A record holding nothing but an email address is never contained and contains nothing. The record returned is the first of its copies the same terms found, and its `id` and `source` are that copy's own; a folded record's file, line and raw row are not returned. Counted per page: a copy, or a contained record, on a later page than the record it folds into is returned and counted there."
          required: [count, files, contained]
          properties:
            count: { type: integer, minimum: 1, description: "How many records it stands for, itself included: its copies and the records it contains, so `contained` of them hold fewer fields; 1 when it stands for none." }
            files: { type: integer, minimum: 1, description: "How many distinct source files they were found in; 1 when it stands for none. A file re-imported from its archived copy counts twice." }
            contained: { type: integer, minimum: 0, description: "How many of them hold fewer fields than it, every value they hold its own: from 0 to `count` − 1. `count` − `contained` is the record and its copies." }
        passwordClass: { $ref: "#/components/schemas/PasswordClass" }
        links: { $ref: "#/components/schemas/RecordLinks" }
    Page:
      type: object
      properties:
        limit: { type: integer }
        cursor: { type: [string, "null"], description: "Send back as `cursor` for the next page; `null` on the last." }
        has_more: { type: boolean, description: "Whether index matches remain past this page. A page is read before records are dropped — those the query's narrowing and `NOT` terms rule out, those whose bytes are gone, and those that do not hold the value their term searched — and before each record's copies and the records it contains are folded into it (`copies`), so it can hold fewer records than `limit`, none even, while `has_more` is `true`: send `cursor` back to keep reading." }
        next_url: { type: [string, "null"], description: "The next page as a GET URL. Always `null` on `POST /search`." }
    SuppressedTerm:
      type: object
      description: "An identifier term whose value search withholds — on the blacklist, or never indexed: it contributed no records."
      required: [field, value, reason]
      properties:
        field: { type: [string, "null"], description: "The term's query prefix (`name` for a `full_name:` term; `email` or `phone` for an untyped address or phone number; `email` for a `username:` term whose value is an email address); `null` for an untyped word." }
        value: { type: string, description: "The value as searched, after normalization (e.g. lower-cased); a value its field cannot hold, as it was typed. A phone number withheld in every form it is searched in, for one reason, is listed once, as searched; a form withheld while another is answered is listed itself." }
        reason:
          type: string
          enum: [too_common, excluded, not_indexed]
          description: "`too_common` — the value is in more than 1,000,000 records, so the index does not keep its matches. `excluded` — the value is excluded from search. `not_indexed` — the value is never indexed: a number shorter than 5 digits, a placeholder word such as null, unknown or not provided, a fragment of JSON markup, a value with no letter A–Z or digit 0–9, a value shorter than 5 characters (a domain excepted), or a value its field cannot hold; in an email term, a placeholder or shared-mailbox address; in a phone term, a placeholder phone number."
      example: { field: password, value: "123456", reason: too_common }
    SearchStats:
      type: object
      description: "Execution counters and timings, for diagnostics, and the identifier terms whose values search withholds."
      required: [index_lookups, pointers_evaluated, pointers_after_boolean, records_fetched, records_returned, copies_collapsed, contained_folded, elapsed_ms, lookup_ms, fetch_ms, suppressed_terms]
      properties:
        index_lookups: { type: integer }
        pointers_evaluated: { type: integer }
        pointers_after_boolean: { type: integer }
        records_fetched: { type: integer }
        records_returned: { type: integer }
        copies_collapsed: { type: integer, minimum: 0, description: "How many records this page folded into the records it returns, copies and contained records alike: the sum of each record's `copies.count` − 1. 0 when it folded none." }
        contained_folded: { type: integer, minimum: 0, description: "Of `copies_collapsed`, how many held fewer fields than the record they fold into: the sum of each record's `copies.contained`. 0 when it folded none." }
        elapsed_ms: { type: integer }
        lookup_ms: { type: integer }
        fetch_ms: { type: integer }
        suppressed_terms:
          type: array
          description: "Each identifier term outside a `NOT` whose value search withholds (`too_common`, `excluded`, `not_indexed`), each field and value once, in query order; `[]` when none is. A term whose value the index lacks for another reason is not listed (see **Suppressed values**)."
          items: { $ref: "#/components/schemas/SuppressedTerm" }
    SearchResponse:
      type: object
      properties:
        records: { type: array, items: { $ref: "#/components/schemas/SearchRecord" } }
        page: { $ref: "#/components/schemas/Page" }
        stats: { $ref: "#/components/schemas/SearchStats" }
        meta: { $ref: "#/components/schemas/Meta" }
      example:
        records:
          - id: "ZGF0YXNldC0xMjN8c…"
            datasetId: northwind-crm-2024
            fields:
              datasetId: northwind-crm-2024
              email: d.whitfield@example.com
              firstName: Dana
              city: Leeds
              password: "$1$O3JMY.Tw$AdLnLjQ/5jXF9.MTp3gHv/"
            source: { file: users.csv, fileKey: users.csv, line: 48122 }
            copies: { count: 3, files: 3, contained: 0 }
            passwordClass: { kind: hashed, hashType: md5crypt }
            links:
              self: "/records/ZGF0YXNldC0xMjN8c…"
              raw: "/records/ZGF0YXNldC0xMjN8c…/raw"
              dataset: /datasets/northwind-crm-2024
        page: { limit: 25, cursor: null, has_more: false, next_url: null }
        stats:
          index_lookups: 1
          pointers_evaluated: 3
          pointers_after_boolean: 3
          records_fetched: 3
          records_returned: 1
          copies_collapsed: 2
          contained_folded: 0
          elapsed_ms: 142
          lookup_ms: 48
          fetch_ms: 81
          suppressed_terms: []
        meta:
          quota: { limit: null, used: 1, remaining: null, resets_at: "2026-09-29T00:00:00.000Z" }
          credits: { kind: scalar, charged: 2, balance: 18448 }
          response_ms: 142
    RecordResponse:
      type: object
      properties:
        id: { type: string }
        datasetId: { type: string }
        fields: { type: object, additionalProperties: true }
        links: { $ref: "#/components/schemas/RecordLinks" }
        meta: { $ref: "#/components/schemas/Meta" }
    RawRecordResponse:
      type: object
      properties:
        id: { type: string }
        datasetId: { type: string }
        raw:
          description: "The source row: keyed by header when one is detected, else `{columns: [...]}`; for a free-text match, `{match, context}`."
          type: object
          additionalProperties: true
        links:
          type: object
          properties:
            self: { type: string }
            record: { type: string }
            dataset: { type: string }
        meta: { $ref: "#/components/schemas/Meta" }
    Dataset:
      type: object
      description: "A dataset as `GET /datasets` and `GET /datasets/{id}` send it, the same whatever stage its import has reached: exactly these properties, never the pipeline's own state (its stage and lease, the intake job it came from, its per-status file counts)."
      additionalProperties: false
      properties:
        datasetId: { type: string }
        source: { type: string, description: "The attribution — an origin domain or a threat actor; absent when the dataset is unattributed (a combolist, a paste, an unattributed dump), never null or empty." }
        description: { type: string, description: "What the dataset holds, with every credential-shaped string in it (an access key, an API or bot token, a webhook URL, a private key, a URL's password) replaced by `[redacted]`." }
        category: { type: [string, "null"], enum: [database, stealer-logs, combolist, scraping, paste, chatter, other, null] }
        tags: { type: array, items: { type: string } }
        totalRecords: { type: [integer, "null"], description: "The records the dataset's last terminal rollup counted; null until the dataset's first terminal rollup has counted it, never a 0 nobody counted." }
        fileCount: { type: [integer, "null"], description: "The files the dataset's last terminal rollup counted; null until the dataset's first terminal rollup has counted it, never a 0 nobody counted." }
        incidentDate: { type: [string, "null"] }
        disclosedAt: { type: [string, "null"] }
        createdAt: { type: string, format: date-time }
        importCompletedAt: { type: [string, "null"], format: date-time }
    PublicUser:
      type: object
      properties:
        user_id: { type: string }
        email: { type: string }
        full_name: { type: [string, "null"] }
        team_id: { type: [string, "null"] }
        team_role: { type: [string, "null"], enum: [admin, member, null] }
        team_name: { type: [string, "null"], description: "`null` without a team, or when the team could not be read." }
    PublicTeam:
      type: object
      properties:
        team_id: { type: string }
        name: { type: string }
        status: { type: string, enum: [active, suspended] }
        daily_search_limit: { type: [integer, "null"], description: "`null` when the team has no daily cap." }
        mask_sensitive_pii: { type: boolean, description: "`true` masks `socialSecurityNumber` for the team's members." }
        credit_cost_scalar: { type: integer, minimum: 0, description: "Credits one `scalar` lookup — a search naming one value — costs the team; `0` for the operator's own team." }
        credit_cost_boolean: { type: integer, minimum: 0, description: "Credits one `boolean` lookup — a search combining two or more terms, written side by side or with `AND`, `OR` or `NOT` — costs the team; `0` for the operator's own team." }
        billing_email: { type: [string, "null"], description: "Where billing notices are also sent, beside the team's admins who sign in with an email address." }
        is_super_admin_team: { type: boolean, description: "`true` only for the operator's own team, which is never billed: its credit costs read `0`." }
        created_at: { type: string, format: date-time }
    ApiKey:
      type: object
      properties:
        key_hash: { type: string }
        label: { type: string }
        last_four: { type: string }
        created_at: { type: string, format: date-time }
        last_used_at: { type: [string, "null"], format: date-time }
        revoked_at: { type: [string, "null"], format: date-time }
        active: { type: boolean, description: "`false` for a key created for a team you are no longer on: it authenticates nothing, and you can revoke it." }
    AutoReloadState:
      type: string
      enum: ["off", armed, pending, failed]
      description: "Where a team's auto-reload stands. `off` — it cannot run: turned off, turned on with no card on file to charge, or turned on for a pack the price list no longer sells (a team admin chooses a pack again). `armed` — it can run: a reload is bought when a search leaves the balance at or below the threshold, and when a search costs more than the balance. `pending` — a reload is in flight. `failed` — paused: the last reload did not complete, and nothing is charged again until a team admin puts a new card on file or buys credits at checkout, or — for an `unconfirmed` or `uncredited` reload — that charge's credits arrive after all. Saving the settings never resumes it."
    CardOnFile:
      type: object
      description: "The card the team's latest checkout or card setup saved. The payment processor's ids are never sent."
      required: [brand, last4, exp_month, exp_year]
      properties:
        brand: { type: string, description: "The card network as the payment processor names it, e.g. `visa`." }
        last4: { type: string }
        exp_month: { type: integer, minimum: 1, maximum: 12 }
        exp_year: { type: integer }
    AutoReloadSettings:
      type: object
      description: "Buy the pack `pack_id` names when a search leaves the balance at or below `threshold_credits`, and when a search costs more than the balance."
      required: [enabled, threshold_credits, pack_id]
      properties:
        enabled: { type: boolean }
        threshold_credits: { type: integer, minimum: 0, maximum: 4999999, description: "The balance, in credits, at or below which a reload is bought. It must be below the chosen pack's credits, so one reload always lifts the balance above it; the largest pack is the bound." }
        pack_id: { type: string, description: "The pack to buy. Saved settings can name a pack the price list no longer sells: auto-reload is then off until a team admin chooses a pack again — and then paused instead, if a reload attempt for the old pack was given up meanwhile." }
    BillingAccount:
      type: object
      description: "A team's credit account. `credits_balance` = `lifetime_credits_granted` − `lifetime_credits_used`."
      required: [credits_balance, lifetime_searches, lifetime_credits_used, lifetime_credits_granted, card, auto_reload, auto_reload_state, reload_failure]
      properties:
        credits_balance: { type: integer, minimum: 0, description: "Credits the team can still spend. A search that costs more is refused with `402 insufficient_credits`." }
        lifetime_searches: { type: integer, minimum: 0 }
        lifetime_credits_used: { type: integer, minimum: 0 }
        lifetime_credits_granted: { type: integer, minimum: 0, description: "Every credit ever added: purchases plus adjustments, net of the adjustments that took credits away." }
        card:
          description: "The card on file; `null` when there is none."
          oneOf:
            - { $ref: "#/components/schemas/CardOnFile" }
            - { type: "null" }
        auto_reload:
          description: "The team's auto-reload settings; `null` until it saves some."
          oneOf:
            - { $ref: "#/components/schemas/AutoReloadSettings" }
            - { type: "null" }
        auto_reload_state: { $ref: "#/components/schemas/AutoReloadState" }
        reload_failure:
          description: "Why the last reload did not complete, while `auto_reload_state` is `failed` (paused); `null` otherwise. `unconfirmed` — its outcome is not known: the charge may still settle, and then its credits are added and the pause ends. `uncredited` — the card was charged, and its credits were not on the team's ledger when this was recorded: we add them or refund the charge, and if they arrive automatically after all, the pause ends."
          oneOf:
            - type: object
              required: [code, failed_at]
              properties:
                code:
                  type: string
                  enum: [card_declined, authentication_required, payment_error, unconfirmed, uncredited]
                  description: "`card_declined` — the card was declined. `authentication_required` — the card's issuer wants the cardholder present. `payment_error` — the payment processor refused the charge for another reason. In those three nothing was charged. `unconfirmed` — the charge's outcome could not be confirmed before the attempt was given up: it may have gone through, and if it settles its credits are added. `uncredited` — the card was charged, and its credits were not on the team's ledger when this was recorded: we add them or refund the charge."
                failed_at: { type: string, format: date-time }
            - { type: "null" }
    PurchaseEntry:
      type: object
      description: "A card charge that bought a pack of credits. Its receipt is `GET /team/billing/purchases/{entryId}/receipt`."
      required: [kind, entry_id, at, credits, amount_usd, pack_id, origin, card_brand, card_last4]
      properties:
        kind: { type: string, const: purchase }
        entry_id: { type: string, description: "The entry's id within its team: the charge's id at the payment processor." }
        at: { type: string, format: date-time, description: "When the credits were granted." }
        credits: { type: integer, minimum: 1 }
        amount_usd: { type: number, description: "What the card was charged." }
        pack_id: { type: string }
        origin: { type: string, enum: [checkout, auto_reload], description: "`checkout` — a team admin's purchase; `auto_reload` — an auto-reload charge on the card on file." }
        card_brand: { type: [string, "null"] }
        card_last4: { type: [string, "null"] }
    AdjustmentEntry:
      type: object
      description: "Credits Shadow Identity added (`credits` > 0) or took away (`credits` < 0) by hand, with the reason."
      required: [kind, entry_id, at, credits, note]
      properties:
        kind: { type: string, const: adjustment }
        entry_id: { type: string }
        at: { type: string, format: date-time, description: "When the adjustment was posted." }
        credits: { type: integer, description: "Signed, never 0." }
        note: { type: string }
    CreditEntry:
      description: "One entry of a team's credit ledger, never changed once written."
      oneOf:
        - { $ref: "#/components/schemas/PurchaseEntry" }
        - { $ref: "#/components/schemas/AdjustmentEntry" }
      discriminator:
        propertyName: kind
        mapping:
          purchase: "#/components/schemas/PurchaseEntry"
          adjustment: "#/components/schemas/AdjustmentEntry"
    UsageByKind:
      type: object
      description: "Searches and the credits they cost, per lookup kind."
      required: [scalar, boolean]
      properties:
        scalar: { type: object, required: [searches, credits], properties: { searches: { type: integer }, credits: { type: integer } } }
        boolean: { type: object, required: [searches, credits], properties: { searches: { type: integer }, credits: { type: integer } } }
    UsageDayReport:
      type: object
      required: [date, searches, credits, by_kind]
      properties:
        date: { type: string, format: date, description: "The UTC day." }
        searches: { type: integer }
        credits: { type: integer }
        by_kind: { $ref: "#/components/schemas/UsageByKind" }
    UsageMonthReport:
      type: object
      required: [period, searches, credits, by_kind, has_statement]
      properties:
        period: { type: string, example: "2026-09", description: "Calendar month (UTC)." }
        searches: { type: integer }
        credits: { type: integer }
        by_kind: { $ref: "#/components/schemas/UsageByKind" }
        has_statement: { type: boolean, description: "Whether the month's statement has been generated (`GET /team/billing/statements/{period}`)." }
    StatementSummary:
      type: object
      description: "A closed month's statement: the credits the team started with, bought, was adjusted by and used, and what its card charges came to. `closing_credits` = `opening_credits` + `credits_purchased` + `credits_adjusted` − `credits_used`, and a month's `opening_credits` is the month before's `closing_credits`."
      required: [period, generated_at, opening_credits, credits_purchased, credits_adjusted, credits_used, closing_credits, searches, by_kind, purchases, amount_charged_usd]
      properties:
        period: { type: string, example: "2026-10", description: "Calendar month (UTC)." }
        generated_at: { type: string, format: date-time }
        opening_credits: { type: integer, minimum: 0 }
        credits_purchased: { type: integer, minimum: 0 }
        credits_adjusted: { type: integer, description: "Net of the month's adjustments; negative when they took more than they added." }
        credits_used: { type: integer, minimum: 0 }
        closing_credits: { type: integer, minimum: 0 }
        searches: { type: integer, minimum: 0 }
        by_kind: { $ref: "#/components/schemas/UsageByKind" }
        purchases: { type: integer, minimum: 0, description: "How many card charges the month holds." }
        amount_charged_usd: { type: number, description: "What the month's card charges came to." }
    Statement:
      description: "A statement with its line items: each day's usage and each ledger entry of the month, oldest first."
      allOf:
        - { $ref: "#/components/schemas/StatementSummary" }
        - type: object
          required: [team, days, entries]
          properties:
            team:
              type: object
              required: [team_id, name, billing_email]
              properties:
                team_id: { type: string }
                name: { type: string }
                billing_email: { type: [string, "null"] }
            days: { type: array, items: { $ref: "#/components/schemas/UsageDayReport" } }
            entries: { type: array, items: { $ref: "#/components/schemas/CreditEntry" } }
    TeamStatement:
      allOf:
        - { $ref: "#/components/schemas/Statement" }
        - type: object
          required: [meta]
          properties:
            meta: { $ref: "#/components/schemas/Meta" }
    TeamBilling:
      type: object
      required: [team, account, month, months, recent_entries, statements, meta]
      properties:
        team: { $ref: "#/components/schemas/PublicTeam" }
        account: { $ref: "#/components/schemas/BillingAccount" }
        month:
          type: object
          description: "The current calendar month (UTC), day by day up to today."
          required: [period, searches, credits, by_kind, days]
          properties:
            period: { type: string }
            searches: { type: integer }
            credits: { type: integer }
            by_kind: { $ref: "#/components/schemas/UsageByKind" }
            days: { type: array, description: "Every day of the month up to and including today.", items: { $ref: "#/components/schemas/UsageDayReport" } }
        months:
          type: array
          description: "Newest first from the current month: at most `months` entries, never a month before the team was created. The current month is always present."
          items: { $ref: "#/components/schemas/UsageMonthReport" }
        recent_entries:
          type: array
          description: "The team's latest credit ledger entries, newest first, at most 25. An older entry is on its month's statement once that statement is generated, and on none until then: an entry of the current month, and of the previous month until that month's statement is generated (from 01:00 UTC on the 1st; a failed run is retried)."
          items: { $ref: "#/components/schemas/CreditEntry" }
        statements:
          type: array
          description: "The statements of the months in the window, newest first."
          items: { $ref: "#/components/schemas/StatementSummary" }
        meta: { $ref: "#/components/schemas/Meta" }
    HostedPageAnswer:
      type: object
      required: [url, meta]
      properties:
        url: { type: string, format: uri, description: "The payment processor's hosted page: send the browser to it." }
        meta: { $ref: "#/components/schemas/Meta" }
    BillingAccountAnswer:
      type: object
      required: [account, meta]
      properties:
        account: { $ref: "#/components/schemas/BillingAccount" }
        meta: { $ref: "#/components/schemas/Meta" }
    ReceiptAnswer:
      type: object
      required: [url, meta]
      properties:
        url: { type: string, format: uri, description: "The payment processor's receipt page for the purchase's charge, valid for a limited time." }
        meta: { $ref: "#/components/schemas/Meta" }
  securitySchemes:
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key
    sessionCookie:
      type: apiKey
      in: cookie
      name: si_session
security:
  - apiKey: []
