{
  "openapi": "3.0.3",
  "info": {
    "title": "NSPT Pilot API — интеграционный контур",
    "version": "1.0.0",
    "description": "Машинный контур NSPT для интеграций с АБС банков и уполномоченным органом. Webhook-outbox NSPT-HOOK-1: дедуп по event_id, HMAC-SHA256 подпись, экспоненциальные ретраи (1 мин × 2ⁿ, потолок 6 ч, dead-letter после 8 попыток). Журналы append-only с хэш-цепями; разрыв цепи виден в stats. ПДн в журналах — AES-256-GCM; в событиях — только маскированные значения. Лимиты: 30 запросов/мин с IP на публичные эндпоинты, тело запроса до 64 КБ."
  },
  "servers": [{ "url": "https://nspt.kz/pilot-api" }],
  "paths": {
    "/v1/health": {
      "get": {
        "summary": "Состояние ядра: журналы, цепи, шифрование ПДн",
        "security": [],
        "responses": {
          "200": { "description": "Ядро живо", "content": { "application/json": { "schema": { "type": "object", "properties": {
            "core": { "type": "string", "example": "up" },
            "chain_verified": { "type": "boolean" },
            "pii_encrypted": { "type": "boolean" },
            "journals": { "type": "object", "additionalProperties": { "type": "integer" } }
          } } } } }
        }
      }
    },
    "/v1/hooks": {
      "post": {
        "summary": "Поставить событие в outbox (NSPT-HOOK-1)",
        "description": "event_id — ключ идемпотентности: повторная постановка с тем же event_id возвращает 200 с dedup:true, дубля в журнале нет.",
        "security": [{ "bearerAuth": [] }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HookEvent" }, "example": {
          "event_id": "evt-550e8400-e29b-41d4-a716-446655440000",
          "kind": "case.status",
          "target_url": "https://abs.bank.kz/nspt/hook",
          "secret_ref": "absbank1",
          "payload": { "case": "А01-0042/2026", "status": "in_procedure" }
        } } } },
        "responses": {
          "201": { "description": "Событие поставлено в очередь", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HookAccepted" } } } },
          "200": { "description": "Дедуп: event_id уже поставлен", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HookDedup" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "422": { "$ref": "#/components/responses/Validation" }
        }
      }
    },
    "/v1/hooks/due": {
      "get": {
        "summary": "События, готовые к доставке (для relay)",
        "description": "Каждое событие содержит body_raw — точные подписанные байты: relay отправляет их без пересериализации. Если для secret_ref задан секрет, прилагается signature = \"sha256=<hmac-hex>\" по body_raw.",
        "security": [{ "bearerAuth": [] }],
        "parameters": [{ "name": "limit", "in": "query", "schema": { "type": "integer", "default": 20, "maximum": 100 } }],
        "responses": {
          "200": { "description": "Список due-событий", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HookDueList" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/v1/hooks/{event_id}/ack": {
      "post": {
        "summary": "Подтверждение исхода доставки",
        "description": "delivered — терминально (повторный ack → dedup без записи). failed — attempts+1 и следующий ретрай по экспоненциальной паузе.",
        "security": [{ "bearerAuth": [] }],
        "parameters": [{ "name": "event_id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "required": ["state"], "properties": {
          "state": { "type": "string", "enum": ["delivered", "failed"] },
          "detail": { "type": "string", "example": "HTTP 200" }
        } } } } },
        "responses": {
          "200": { "description": "Исход зафиксирован", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HookAcked" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/v1/hooks/stats": {
      "get": {
        "summary": "Публичные агрегаты outbox (без ПДн)",
        "security": [],
        "responses": {
          "200": { "description": "Агрегаты очереди", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HookStats" }, "example": {
            "journal": "hook_outbox", "format": "NSPT-HOOK-1", "events": 19, "unique_events": 5,
            "queued": 0, "delivered": 4, "failed_retryable": 1, "dead": 0,
            "chain_head": "3684d90c…", "chain_verified": true, "generated_ms": 1794855146401
          } } } }
        }
      }
    },
    "/v1/assignments/stats": {
      "get": {
        "summary": "Сводка назначений управляющих (регуляторная витрина)",
        "security": [],
        "responses": { "200": { "description": "Агрегаты цепи назначений с chain_verified" } }
      }
    },
    "/v1/sandbox/channel": {
      "post": {
        "summary": "Песочница (NSPT-SAND-1): создать тестовый webhook-канал",
        "description": "Self-serve для ИТ-отдела банка. target_url — только публичный http(s) (SSRF-гард всегда). Канал живёт 7 дней, до 20 запусков. Секрет возвращается один раз.",
        "security": [],
        "requestBody": { "content": { "application/json": { "schema": { "type": "object", "required": ["target_url"], "properties": { "target_url": { "type": "string", "example": "https://webhook.site/…" } } } } } },
        "responses": {
          "201": { "description": "Канал создан; secret показан единственный раз" },
          "400": { "description": "bad_url / ssrf_blocked" },
          "429": { "description": "rate_limited / sandbox_full" }
        }
      }
    },
    "/v1/sandbox/channel/{channel_id}/fire": {
      "post": {
        "summary": "Песочница: отправить тестовое событие sandbox.ping",
        "description": "Событие идёт боевым контуром outbox → relay → подписанный POST (заголовок x-nspt-signature) на endpoint канала. Авторизация — секретом канала в теле.",
        "security": [],
        "parameters": [{ "name": "channel_id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "requestBody": { "content": { "application/json": { "schema": { "type": "object", "required": ["secret"], "properties": { "secret": { "type": "string" } } } } } },
        "responses": {
          "201": { "description": "Событие поставлено в outbox" },
          "401": { "description": "неверный секрет" },
          "404": { "description": "канал не найден" },
          "410": { "description": "канал старше 7 дней" },
          "429": { "description": "лимит запусков исчерпан" }
        }
      }
    },
    "/v1/sandbox/channel/{channel_id}/status": {
      "get": {
        "summary": "Песочница: статус канала и исходы доставки",
        "security": [],
        "parameters": [
          { "name": "channel_id", "in": "path", "required": true, "schema": { "type": "string" } },
          { "name": "secret", "in": "query", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "fires, fires_left, expired, events[] со state/attempts" },
          "401": { "description": "неверный секрет" },
          "404": { "description": "канал не найден" }
        }
      }
    },
    "/v1/payments": {
      "post": {
        "summary": "Операция оплаты (NSPT-PAY-1)",
        "description": "Дедуп по invoice_id; total сверяется с суммой позиций. Состояние processing — пессимистичная блокировка с TTL 10 минут.",
        "security": [{ "bearerAuth": [] }],
        "responses": {
          "201": { "description": "Операция создана" },
          "200": { "description": "Дедуп по invoice_id" },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/v1/sign": {
      "post": {
        "summary": "Регистрация ЭЦП-подписи документа (NSPT-SIGN-1)",
        "description": "Подпись привязана к содержимому через doc_hash (sha256). Та же версия документа тем же подписантом → 409.",
        "security": [{ "bearerAuth": [] }],
        "responses": {
          "201": { "description": "Подпись зарегистрирована" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "409": { "description": "Эта версия уже подписана этим подписантом" }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": { "type": "http", "scheme": "bearer", "description": "Токен команды (POST /v1/team/login) или сервисный токен интеграционного канала" }
    },
    "schemas": {
      "HookEvent": { "type": "object", "required": ["event_id", "kind", "target_url", "payload"], "properties": {
        "event_id": { "type": "string", "minLength": 8, "maxLength": 100, "pattern": "^[a-zA-Z0-9._-]+$", "description": "Ключ идемпотентности" },
        "kind": { "type": "string", "maxLength": 60, "example": "case.status" },
        "target_url": { "type": "string", "maxLength": 300, "pattern": "^https?://" },
        "secret_ref": { "type": "string", "maxLength": 40, "pattern": "^[a-z0-9_]*$", "description": "Ссылка на секрет канала (сам секрет — только в env сервера)" },
        "payload": { "type": "object" }
      } },
      "HookAccepted": { "type": "object", "properties": {
        "event_id": { "type": "string" }, "state": { "type": "string", "example": "queued" },
        "seq": { "type": "integer" }, "proof": { "type": "string", "description": "sha256-запись в хэш-цепи" }, "dedup": { "type": "boolean", "example": false }
      } },
      "HookDedup": { "type": "object", "properties": {
        "event_id": { "type": "string" }, "state": { "type": "string" }, "attempts": { "type": "integer" }, "dedup": { "type": "boolean", "example": true }
      } },
      "HookDueList": { "type": "object", "properties": {
        "total": { "type": "integer" }, "generated_ms": { "type": "integer" },
        "items": { "type": "array", "items": { "type": "object", "properties": {
          "event_id": { "type": "string" }, "kind": { "type": "string" }, "target_url": { "type": "string" },
          "attempts": { "type": "integer" },
          "body": { "type": "object" },
          "body_raw": { "type": "string", "description": "Точные подписанные байты — отправлять без пересериализации" },
          "signature": { "type": "string", "example": "sha256=41e4ecb0…" }
        } } }
      } },
      "HookAcked": { "type": "object", "properties": {
        "event_id": { "type": "string" }, "state": { "type": "string" }, "attempts": { "type": "integer" },
        "next_retry_ms": { "type": "integer" }, "seq": { "type": "integer" }, "proof": { "type": "string" }
      } },
      "HookStats": { "type": "object", "properties": {
        "journal": { "type": "string" }, "format": { "type": "string", "example": "NSPT-HOOK-1" },
        "events": { "type": "integer" }, "unique_events": { "type": "integer" },
        "queued": { "type": "integer" }, "delivered": { "type": "integer" },
        "failed_retryable": { "type": "integer" }, "dead": { "type": "integer" },
        "chain_head": { "type": "string" }, "chain_verified": { "type": "boolean" }, "generated_ms": { "type": "integer" }
      } },
      "Error": { "type": "object", "properties": {
        "error": { "type": "string" }, "message": { "type": "string" }, "request_id": { "type": "string" }
      } }
    },
    "responses": {
      "Unauthorized": { "description": "Требуется Bearer-токен", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "NotFound": { "description": "Не найдено", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Validation": { "description": "Ошибка валидации полей", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
    }
  }
}
