openapi: 3.0.3
info:
  title: Tracebud Partner API
  version: 1.0.0
  description: |
    Curated partner-facing subset of the Tracebud Nest API (`/api` global prefix).

    **Auth:** `Authorization: Bearer <token>` where `<token>` is either a Supabase
    user JWT or a tenant API key secret (`tbk_live_…`). API key *management*
    (`/v1/api-keys`) requires a signed-in dashboard user JWT — keys cannot mint
    or revoke other keys.

    **Not in this document:** dashboard Next.js BFF (`app/api/**`), marketing
    leads APIs, PostgREST on product tables, GraphQL, or unauthenticated access.

    The full internal surface remains `docs/openapi/tracebud-v1-draft.yaml`.
  license:
    name: Proprietary
    url: https://tracebud.com/terms
servers:
  - url: https://api.tracebud.com/api # pragma: allowlist secret
    description: Production Nest API (live). Paths below are relative to this base.
  - url: https://sandbox-api.tracebud.com/api # pragma: allowlist secret
    description: |
      Reserved server entry for a future sandbox host. No sandbox environment is available today — do not send partner traffic here.
security:
  - bearerAuth: []
tags:
  - name: API keys
    description: |
      Create, list, and revoke tenant `tbk_live_…` keys. Manager desk roles only; requires a user JWT (not an API key).
  - name: Partner data
    description: |
      Scoped dataset inventory and export jobs (`read:lineage` | `read:compliance` | `read:risk` | `read:shipments`).
  - name: Webhooks
    description: Register webhooks and inspect delivery history.
paths:
  /v1/api-keys:
    get:
      tags:
        - API keys
      operationId: listApiKeys
      summary: List the tenant’s API keys (prefix only, never the secret)
      description: |
        Returns key metadata for the caller’s tenant. Secrets are never listed. Forbidden when the principal is itself an API key.
      security:
        - bearerAuth: []
      responses:
        '200':
          description: Key list
          content:
            application/json:
              schema:
                type: object
                required:
                  - items
                properties:
                  items:
                    type: array
                    items:
                      $ref: '#/components/schemas/ApiKeyRecord'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim, wrong role, or API-key principal
    post:
      tags:
        - API keys
      operationId: createApiKey
      summary: Create an API key (secret returned once)
      description: |
        Creates a `tbk_live_…` secret. The full secret appears only in this response. Store it immediately; later list calls return `keyPrefix` only.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateApiKeyRequest'
      responses:
        '201':
          description: Key created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiKeyCreatedResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim, wrong role, or API-key principal
  /v1/api-keys/{id}:
    delete:
      tags:
        - API keys
      operationId: revokeApiKey
      summary: Revoke an API key (idempotent)
      security:
        - bearerAuth: []
      parameters:
        - $ref: '#/components/parameters/IdPath'
      responses:
        '200':
          description: Key revoked
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiKeyRecord'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim, wrong role, or API-key principal
        '404':
          $ref: '#/components/responses/BadRequest'
  /v1/partner-data/datasets:
    get:
      tags:
        - Integrations
      operationId: listPartnerDatasets
      summary: List external partner datasets
      description: Returns tenant-scoped dataset inventory for external reporting and analytics partners by explicit scope.
      parameters:
        - name: scope
          in: query
          required: true
          schema:
            type: string
            enum:
              - read:lineage
              - read:compliance
              - read:risk
              - read:shipments
      responses:
        '200':
          description: Dataset list by requested scope
          content:
            application/json:
              schema:
                type: object
                required:
                  - tenantId
                  - scope
                  - datasets
                  - state
                properties:
                  tenantId:
                    type: string
                  scope:
                    type: string
                    enum:
                      - read:lineage
                      - read:compliance
                      - read:risk
                      - read:shipments
                  datasets:
                    type: array
                    items:
                      type: string
                  state:
                    type: string
                    enum:
                      - partner_connection_active
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim or role policy violation
  /v1/partner-data/exports:
    post:
      tags:
        - Integrations
      operationId: startPartnerDatasetExport
      summary: Start partner dataset export
      description: Queues a tenant-safe export job for external analytics/reporting systems with explicit idempotency key and immutable audit evidence.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - scope
                - dataset
                - format
                - idempotencyKey
              properties:
                scope:
                  type: string
                  enum:
                    - read:lineage
                    - read:compliance
                    - read:risk
                    - read:shipments
                dataset:
                  type: string
                format:
                  type: string
                  enum:
                    - csv
                    - parquet
                idempotencyKey:
                  type: string
                cursor:
                  type: string
      responses:
        '200':
          description: Export queued successfully
          content:
            application/json:
              schema:
                type: object
                required:
                  - exportId
                  - status
                  - state
                  - dataset
                  - format
                  - idempotencyKey
                  - replayed
                  - attemptCount
                  - errorCode
                  - nextRetryAt
                  - retryExhaustedAt
                  - createdAt
                  - updatedAt
                properties:
                  exportId:
                    type: string
                  status:
                    type: string
                    enum:
                      - queued
                  state:
                    type: string
                    enum:
                      - partner_sync_pending
                  dataset:
                    type: string
                  format:
                    type: string
                    enum:
                      - csv
                      - parquet
                  idempotencyKey:
                    type: string
                  cursor:
                    type: string
                    nullable: true
                  replayed:
                    type: boolean
                  attemptCount:
                    type: integer
                  errorCode:
                    type: string
                    nullable: true
                  nextRetryAt:
                    type: string
                    format: date-time
                    nullable: true
                  retryExhaustedAt:
                    type: string
                    format: date-time
                    nullable: true
                  createdAt:
                    type: string
                    format: date-time
                  updatedAt:
                    type: string
                    format: date-time
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim or role policy violation
  /v1/partner-data/exports/{id}:
    get:
      tags:
        - Integrations
      operationId: getPartnerDatasetExportStatus
      summary: Get partner dataset export status
      parameters:
        - $ref: '#/components/parameters/IdPath'
      responses:
        '200':
          description: Export status payload
          content:
            application/json:
              schema:
                type: object
                required:
                  - exportId
                  - status
                  - state
                  - dataset
                  - format
                  - idempotencyKey
                  - replayed
                  - attemptCount
                  - errorCode
                  - nextRetryAt
                  - retryExhaustedAt
                  - createdAt
                  - updatedAt
                properties:
                  exportId:
                    type: string
                  status:
                    type: string
                    enum:
                      - queued
                      - completed
                      - failed
                  state:
                    type: string
                    enum:
                      - partner_sync_pending
                      - partner_sync_succeeded
                      - partner_sync_terminal_failed
                  dataset:
                    type: string
                  format:
                    type: string
                    enum:
                      - csv
                      - parquet
                  idempotencyKey:
                    type: string
                  cursor:
                    type: string
                    nullable: true
                  replayed:
                    type: boolean
                  attemptCount:
                    type: integer
                  errorCode:
                    type: string
                    nullable: true
                  nextRetryAt:
                    type: string
                    format: date-time
                    nullable: true
                  retryExhaustedAt:
                    type: string
                    format: date-time
                    nullable: true
                  createdAt:
                    type: string
                    format: date-time
                  updatedAt:
                    type: string
                    format: date-time
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim or role policy violation
  /v1/webhooks:
    get:
      tags:
        - Webhooks
      operationId: listWebhooks
      summary: List webhooks
      parameters:
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 200
        - name: offset
          in: query
          required: false
          schema:
            type: integer
            minimum: 0
      responses:
        '200':
          description: Webhook registrations list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PaginatedListResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
    post:
      tags:
        - Webhooks
      operationId: registerWebhook
      summary: Register webhook
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateWebhookRequest'
      responses:
        '201':
          description: Webhook registered
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GenericEntityResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim or role policy violation
  /v1/webhooks/{id}/deliveries:
    get:
      tags:
        - Webhooks
      operationId: listWebhookDeliveries
      summary: List webhook deliveries
      parameters:
        - $ref: '#/components/parameters/IdPath'
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 200
        - name: offset
          in: query
          required: false
          schema:
            type: integer
            minimum: 0
      responses:
        '200':
          description: Deliveries list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PaginatedListResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Missing tenant claim or role policy violation
        '404':
          $ref: '#/components/responses/BadRequest'
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT or tbk_live_ API key
      description: |
        Pass a Supabase user JWT or a tenant API key secret (`tbk_live_…`). Do not use dashboard cookie sessions as partner auth.
  schemas:
    ApiKeyScope:
      type: string
      enum:
        - read
        - write
    CreateApiKeyRequest:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 80
          example: Partner analytics read
        role:
          type: string
          description: Desk role the key acts as (admin may choose another allowed role).
        scopes:
          type: array
          items:
            $ref: '#/components/schemas/ApiKeyScope'
          default:
            - read
        expiresAt:
          type: string
          format: date-time
          nullable: true
    ApiKeyRecord:
      type: object
      required:
        - id
        - name
        - keyPrefix
        - role
        - scopes
        - createdAt
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        keyPrefix:
          type: string
          description: Public prefix only (for example `tbk_live_abcd`).
          example: tbk_live_abcd
        role:
          type: string
        scopes:
          type: array
          items:
            $ref: '#/components/schemas/ApiKeyScope'
        createdAt:
          type: string
          format: date-time
        expiresAt:
          type: string
          format: date-time
          nullable: true
        lastUsedAt:
          type: string
          format: date-time
          nullable: true
        revokedAt:
          type: string
          format: date-time
          nullable: true
    ApiKeyCreatedResponse:
      allOf:
        - $ref: '#/components/schemas/ApiKeyRecord'
        - type: object
          required:
            - secret
          properties:
            secret:
              type: string
              description: Full `tbk_live_…` secret. Shown once at creation.
              example: tbk_live_example_not_a_real_secret
    ErrorResponse:
      type: object
      properties:
        error_code:
          type: string
        message:
          type: string
        field_errors:
          type: array
          items:
            type: object
        request_id:
          type: string
      required:
        - error_code
        - message
        - request_id
    PaginatedListResponse:
      type: object
      properties:
        items:
          type: array
          items:
            type: object
            additionalProperties: true
        page_info:
          type: object
          additionalProperties: true
    CreateWebhookRequest:
      type: object
      properties:
        endpoint_url:
          type: string
          format: uri
        event_types:
          type: array
          items:
            type: string
        secret_rotation_policy:
          type: string
      required:
        - endpoint_url
        - event_types
        - secret_rotation_policy
    GenericEntityResponse:
      type: object
      additionalProperties: true
      properties:
        id:
          type: string
          format: uuid
  responses:
    Unauthorized:
      description: Unauthorized
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    BadRequest:
      description: Validation error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  parameters:
    IdPath:
      name: id
      in: path
      required: true
      schema:
        type: string
        format: uuid
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      schema:
        type: string
