> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lerian.studio/llms.txt
> Use this file to discover all available pages before exploring further.

# Criar uma assinatura

> Cria uma assinatura de entrega para o tenant autenticado. O tenant é obtido apenas a partir das claims validadas do JWT — um `tenant_id` no corpo é ignorado.

Uma assinatura `webhook` nasce `active` e gera um segredo de assinatura (signing secret) que é retornado exatamente uma vez nesta resposta (veja `signingSecret`). Uma assinatura de fila (`sqs`, `rabbitmq`, `eventbridge`) nasce `pending_verification` e não gera segredo; ela permanece não entregável até que uma credencial de saída seja fornecida e sondada via `PUT /v1/subscriptions/{id}/credential`. Um `sink_config` ou `credential` inline no create é rejeitado — as credenciais de fila chegam apenas no PUT de credencial.



## OpenAPI

````yaml pt/openapi/v3-current/streaming-hub.yaml post /v1/subscriptions
openapi: 3.1.0
info:
  title: Lerian Streaming Hub API
  version: v1.0.0
  contact:
    email: contact@lerian.studio
    name: Lerian Studio
    url: https://lerian.studio
  license:
    name: Lerian Studio General License
  description: >-
    A API do plano de controle do Streaming Hub. O Streaming Hub é a borda
    gerenciada de entrega de eventos da Lerian: ele consome CloudEvents do
    backbone de streaming interno da plataforma e faz o fan-out para os destinos
    externos do próprio tenant — webhooks, Amazon SQS, RabbitMQ, Amazon
    EventBridge ou uma caixa de entrada pull. Esta API permite que um tenant
    navegue pelo catálogo de eventos alimentado por manifesto, crie e gerencie
    assinaturas de entrega, verifique e rotacione suas credenciais, consulte a
    saúde da entrega e puxe (pull) os eventos aos quais tem direito.


    Os erros usam um envelope plano `{"error":"<token>"}` (um token de baixa
    cardinalidade, legível por máquina — nunca problem+json do RFC 9457). As
    operações de mutação exigem um cabeçalho `X-Idempotency` para semântica de
    no-máximo-uma-vez (at-most-once); uma requisição repetida (replay) retorna a
    resposta original byte a byte com `X-Idempotency-Replayed: true`. O catálogo
    e a superfície de eventos por pull têm escopo de tenant através do JWT
    bearer; os endpoints operacionais de sondagem (`/healthz`, `/readyz`,
    `/version`, `/runtime`, `/metrics`) não exigem autenticação. O Streaming Hub
    é closed source sob a Lerian Studio General License.
servers:
  - url: https://streaming-hub.sandbox.lerian.net
security:
  - BearerAuth: []
tags:
  - name: Catalog
    description: >-
      Navegue pelo catálogo de tipos de evento disponíveis para assinatura,
      alimentado por manifesto.
  - name: Subscriptions
    description: >-
      Crie, leia, atualize e exclua assinaturas de entrega e conduza o ciclo de
      vida de verificação do destino (ping, verify, credential, delegated grant,
      rotação de segredo, saúde).
  - name: Event Delivery
    description: >-
      Puxe (pull) os eventos aos quais uma assinatura de sink pull tem direito
      (leitura com cursor-como-confirmação).
  - name: Admin
    description: >-
      Análise forense de operador entre tenants (cross-tenant). Exige um escopo
      de autorização de operador.
  - name: Operational
    description: >-
      Sondagens não autenticadas de liveness, readiness, build, runtime e
      métricas.
paths:
  /v1/subscriptions:
    post:
      tags:
        - Subscriptions
      summary: Criar uma assinatura
      description: >-
        Cria uma assinatura de entrega para o tenant autenticado. O tenant é
        obtido apenas a partir das claims validadas do JWT — um `tenant_id` no
        corpo é ignorado.


        Uma assinatura `webhook` nasce `active` e gera um segredo de assinatura
        (signing secret) que é retornado exatamente uma vez nesta resposta (veja
        `signingSecret`). Uma assinatura de fila (`sqs`, `rabbitmq`,
        `eventbridge`) nasce `pending_verification` e não gera segredo; ela
        permanece não entregável até que uma credencial de saída seja fornecida
        e sondada via `PUT /v1/subscriptions/{id}/credential`. Um `sink_config`
        ou `credential` inline no create é rejeitado — as credenciais de fila
        chegam apenas no PUT de credencial.
      operationId: createSubscription
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSubscriptionRequest'
      responses:
        '201':
          description: >-
            A assinatura foi criada. O `signingSecret` está presente apenas para
            um sink `webhook` e é exibido exatamente uma vez — salve-o ao
            recebê-lo, pois não pode ser recuperado depois, apenas rotacionado.
          headers:
            X-Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateSubscriptionResponse'
        '400':
          $ref: '#/components/responses/BadRequestOrMissingIdempotency'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '422':
          description: >-
            A requisição é corrigível pelo chamador. `error` é um de
            `validation_error` (`sink_kind` inválido, endpoint / schema /
            event_types inválidos), `inline_sink_config_forbidden` (um
            `sink_config` / `credential` inline foi enviado) ou
            `endpoint_blocked` (o endpoint do webhook resolveu para um endereço
            bloqueado, privado ou de metadados).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '500':
          $ref: '#/components/responses/InternalError'
      security:
        - BearerAuth: []
components:
  parameters:
    IdempotencyKey:
      name: X-Idempotency
      in: header
      required: true
      description: >-
        A client-chosen unique key that makes this mutation at-most-once. A
        mutation sent without it is rejected before any write with `400
        missing_idempotency_key`. Reusing the same key with an identical request
        replays the original response byte-for-byte (with
        `X-Idempotency-Replayed: true`); reusing it with a different request
        body returns `409 idempotency_conflict`. To re-drive a corrected
        request, mint a new key.
      schema:
        type: string
  schemas:
    CreateSubscriptionRequest:
      type: object
      description: >-
        The create body. It carries no `tenant_id` (the tenant is resolved from
        the JWT). Inline `sink_config` / `credential` fields are rejected with
        `422 inline_sink_config_forbidden` — queue credentials arrive only via
        the credential PUT.
      properties:
        name:
          type: string
          description: >-
            A human label for the subscription. Required and non-blank
            (whitespace-only is rejected).
          examples:
            - orders-webhook
        sink_kind:
          $ref: '#/components/schemas/SinkKind'
        endpoint:
          type: string
          description: >-
            The destination address, interpreted per sink kind. For `webhook`,
            an `https://` URL with no embedded userinfo. For `pull`, omit it —
            the server synthesizes a `pull://<id>` value. For `sqs`, the
            `https://` queue URL. For `rabbitmq`, an `"<exchange>/<routingKey>"`
            string (exchange required, routing key optional). For `eventbridge`,
            the event-bus name / detail-type addressing string. The broker host
            or AWS region for queue kinds lives in the encrypted credential, not
            here.
          examples:
            - https://hooks.example.com/lerian
        event_types:
          type: array
          description: >-
            The event types to deliver. Validated softly against the catalog —
            an unknown type warns but never blocks onboarding.
          items:
            type: string
          examples:
            - - transaction.created
        schema_major:
          type: integer
          description: >-
            Optional schema-major pin. When set, delivery follows the versioned
            topic for that major; when omitted, the subscription follows the
            base topic.
          examples:
            - 1
        plan_tier:
          type: string
          description: The plan tier for the subscription.
          examples:
            - standard
      required:
        - name
        - sink_kind
    CreateSubscriptionResponse:
      type: object
      additionalProperties: false
      description: >-
        The create response. `signingSecret` is present only for a `webhook`
        sink and is shown exactly once; it is stored only as ciphertext and is
        never returned by any read path.
      properties:
        subscription:
          $ref: '#/components/schemas/Subscription'
        signingSecret:
          type: string
          description: >-
            The one-time webhook signing secret (write-only). Minted
            server-side, returned exactly once here, and never retrievable later
            — only rotated. Absent for non-webhook sinks.
          examples:
            - whsec_9f8c2b1e4a7d6055c3e2f10987ab4c21
      required:
        - subscription
    Error:
      type: object
      additionalProperties: false
      description: >-
        The flat error envelope used across the `/v1` and `/admin` surfaces. It
        carries a single low-cardinality, machine-readable token and never leaks
        secret material or internal detail. (A `403` from the authorization
        decision point is the one exception — its body is plain text.)
      properties:
        error:
          type: string
          description: The machine-readable error token.
          examples:
            - not_found
      required:
        - error
    SinkKind:
      type: string
      description: >-
        The delivery destination kind. `webhook` posts signed HTTPS requests;
        `pull` exposes an inbox read over `GET /v1/events`; `sqs`, `rabbitmq`,
        and `eventbridge` fan out to the named queue or bus.
      enum:
        - webhook
        - pull
        - sqs
        - rabbitmq
        - eventbridge
    Subscription:
      type: object
      additionalProperties: false
      description: >-
        The non-secret projection of a subscription. It never carries the
        signing secret or any credential material.
      properties:
        id:
          type: string
          format: uuid
          description: The unique identifier of the subscription (UUIDv7).
          examples:
            - 0192f1a0-0000-7000-8000-00000000c001
        name:
          type: string
          description: The human label supplied at create.
          examples:
            - orders-webhook
        sink_kind:
          $ref: '#/components/schemas/SinkKind'
        endpoint:
          type: string
          description: The destination address (per sink kind).
          examples:
            - https://hooks.example.com/ingest
        event_types:
          type: array
          description: >-
            The event types the subscription delivers. Omitted when none are
            pinned.
          items:
            type: string
          examples:
            - - account.created
              - account.updated
        schema_major:
          type: integer
          description: >-
            The pinned schema major, when set. Omitted when the subscription
            follows the base topic.
          examples:
            - 2
        signature_version:
          type: integer
          description: The webhook signature scheme version.
          examples:
            - 1
        plan_tier:
          type: string
          description: The subscription's plan tier.
          examples:
            - standard
        enabled:
          type: boolean
          description: >-
            The operator on/off flag. Independent of `verification_state`; both
            must hold for delivery.
          examples:
            - true
        verification_state:
          $ref: '#/components/schemas/VerificationState'
        created_at:
          type: string
          format: date-time
          description: Creation timestamp (UTC, RFC 3339).
          examples:
            - '2026-01-15T12:00:00Z'
        updated_at:
          type: string
          format: date-time
          description: Last-update timestamp (UTC, RFC 3339).
          examples:
            - '2026-01-15T12:00:00Z'
      required:
        - id
        - name
        - sink_kind
        - endpoint
        - signature_version
        - plan_tier
        - enabled
        - verification_state
        - created_at
        - updated_at
    VerificationState:
      type: string
      description: >-
        The subscription's position in the destination verification state
        machine. Only an `active` subscription is deliverable. A `webhook` sub
        is born `active`; a queue sub is born `pending_verification` and reaches
        `active` on a successful credential probe. `degraded` and `disabled`
        signal an impaired or auto-disabled destination that a successful
        `verify` returns to `active`.
      enum:
        - pending_verification
        - active
        - degraded
        - disabled
  headers:
    IdempotencyReplayed:
      description: >-
        Presente e definido como `true` quando esta resposta é um replay de uma
        requisição previamente confirmada que carrega a mesma chave
        `X-Idempotency` (o handler não rodou de novo).
      schema:
        type: string
        enum:
          - 'true'
  responses:
    BadRequestOrMissingIdempotency:
      description: >-
        O corpo da requisição está malformado (`bad_request`) ou o cabeçalho
        obrigatório `X-Idempotency` está ausente (`missing_idempotency_key`,
        rejeitado antes de qualquer escrita).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthorized:
      description: >-
        A autenticação falhou, ou não há contexto de tenant confiável. `error` é
        `unauthorized` (corpo uniforme — nenhuma razão é revelada).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Forbidden:
      description: >-
        O ponto de decisão de autorização (authorization decision point) negou a
        requisição. O corpo é texto puro (não o envelope de erro JSON).
      content:
        text/plain:
          schema:
            type: string
    IdempotencyConflict:
      description: >-
        Uma duplicata em andamento (in-flight), ou a mesma chave `X-Idempotency`
        foi reutilizada com um fingerprint de requisição diferente — `error` é
        `idempotency_conflict`.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    InternalError:
      description: >-
        Uma falha de infraestrutura. `error` é `internal_error` (sanitizado; o
        detalhe é logado, nunca retornado).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >-
        Um JWT bearer emitido pelo plugin-auth (lib-auth). A identidade do
        tenant é resolvida a partir das claims validadas do token; a superfície
        `/v1` nunca lê um tenant do corpo, do path ou da query. Chamadores de
        máquina obtêm um token via o fluxo client-credentials do plugin-auth. A
        superfície `/admin` autoriza contra um escopo de operador e não carrega
        contexto de tenant.

````