openapi: 3.1.0
info:
  title: Banky API
  version: "1.0.0"
  summary: API de Open Finance para Chile (solo lectura).
  description: |
    Conecta cuentas bancarias chilenas de empresas y personas, y lee sus saldos y movimientos.
    Solo lectura: la API nunca mueve dinero.

    - Autenticación: `Authorization: Bearer <llave>`. Las llaves secret (`banky_sk_live_…`, `banky_sk_test_…`)
      acceden a toda la API; las publishable (`banky_pk_live_…`, `banky_pk_test_…`) solo a
      `POST /v1/link_tokens` y `GET /v1/institutions`.
    - Live y test son mundos separados: el modo lo decide la llave.
    - Montos en pesos chilenos enteros: positivo es abono, negativo es cargo.
    - Paginación por cursor con `limit` y `starting_after`.

    Documentación: https://banky.cl/docs
  contact:
    name: Banky
    email: hola@banky.cl
    url: https://banky.cl/docs
servers:
  - url: https://api.banky.cl
    description: Producción (live y test, según la llave)
security:
  - llave: []
tags:
  - name: API
    description: Información de la API.
  - name: Link tokens
    description: Tokens de un solo uso para abrir el widget de conexión.
  - name: Links
    description: Conexiones autorizadas por un titular sobre un banco.
  - name: Cuentas
    description: Cuentas bancarias de cada conexión, con su saldo.
  - name: Movimientos
    description: Abonos y cargos de una cuenta.
  - name: Instituciones
    description: Bancos soportados y su estado.
externalDocs:
  description: Documentación de Banky
  url: https://banky.cl/docs

paths:
  /v1:
    get:
      tags: [API]
      operationId: obtenerApi
      summary: Información de la API
      description: Nombre, versión y enlace a la documentación. No requiere llave.
      security: []
      responses:
        "200":
          description: Información de la API.
          content:
            application/json:
              schema:
                type: object
                required: [object, name, version, documentation]
                properties:
                  object: { type: string, const: api }
                  name: { type: string, examples: ["Banky API"] }
                  version: { type: string, examples: ["v1"] }
                  documentation: { type: string, format: uri }

  /v1/link_tokens:
    post:
      tags: [Link tokens]
      operationId: crearLinkToken
      summary: Crear un link token
      description: |
        Crea un token de un solo uso que abre el widget de conexión. Vence a los 30 minutos o al crear una conexión.
        Es el único endpoint que acepta llaves publishable y que admite CORS.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [holder_type]
              properties:
                holder_type:
                  $ref: "#/components/schemas/HolderType"
                client_name:
                  type: string
                  maxLength: 80
                  description: Nombre que ve la persona en el widget. Si se omite, se usa el de la organización.
                allow_mcp:
                  type: boolean
                  default: false
                  description: Si la conexión podrá leerse desde el servidor MCP.
                webhook_url:
                  type: string
                  format: uri
                  maxLength: 2048
                  description: |
                    URL HTTPS pública (puerto 443 u 8443, sin usuario ni clave) que recibirá los eventos de esta conexión,
                    firmados con el secreto de webhooks de links de la organización. Solo con llave secret: con una
                    llave publishable responde 403 `secret_key_required`.
            example:
              holder_type: business
              client_name: Contable Austral
              allow_mcp: true
      responses:
        "201":
          description: Link token creado.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/LinkToken"
        "400": { $ref: "#/components/responses/SolicitudInvalida" }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "413": { $ref: "#/components/responses/CuerpoDemasiadoGrande" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

  /v1/links:
    get:
      tags: [Links]
      operationId: listarLinks
      summary: Listar links
      description: Links del modo de la llave, del más reciente al más antiguo. Incluye los revocados.
      parameters:
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/StartingAfter"
      responses:
        "200":
          description: Página de links.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Lista"
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: "#/components/schemas/Link" }
        "400": { $ref: "#/components/responses/SolicitudInvalida" }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "403": { $ref: "#/components/responses/LlaveSecretRequerida" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

  /v1/links/{id}:
    parameters:
      - $ref: "#/components/parameters/LinkId"
    get:
      tags: [Links]
      operationId: obtenerLink
      summary: Obtener un link
      responses:
        "200":
          description: El link.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Link" }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "403": { $ref: "#/components/responses/LlaveSecretRequerida" }
        "404": { $ref: "#/components/responses/NoEncontrado" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }
    delete:
      tags: [Links]
      operationId: eliminarLink
      summary: Eliminar un link
      description: |
        Revoca la conexión: borra sus credenciales y el dispositivo de confianza, la deja en `disconnected` y envía el
        webhook `link.deleted`. Las cuentas y movimientos ya leídos se conservan.
      responses:
        "200":
          description: El link revocado.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Link"
                  - type: object
                    required: [deleted]
                    properties:
                      deleted: { type: boolean, const: true }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "403": { $ref: "#/components/responses/LlaveSecretRequerida" }
        "404": { $ref: "#/components/responses/NoEncontrado" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

  /v1/links/{id}/refresh:
    parameters:
      - $ref: "#/components/parameters/LinkId"
    post:
      tags: [Links]
      operationId: actualizarLink
      summary: Actualizar un link
      description: |
        Pide una sincronización en segundo plano. El resultado llega por los webhooks `link.refreshed` y `movements.new`
        (o `link.credentials_invalid` / `link.action_required`).
      responses:
        "202":
          description: Sincronización solicitada.
          content:
            application/json:
              schema:
                type: object
                required: [id, object, status]
                properties:
                  id: { type: string, pattern: "^link_[0-9a-f]{16}$" }
                  object: { type: string, const: link }
                  status: { type: string, const: syncing }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "403": { $ref: "#/components/responses/LlaveSecretRequerida" }
        "404": { $ref: "#/components/responses/NoEncontrado" }
        "409":
          description: |
            El link no se puede sincronizar: fue revocado (`link_disconnected`) o el banco rechazó la clave o pide una
            acción (`credentials_invalid`, `action_required`). En estos dos últimos casos la persona debe reconectar.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
              example:
                error:
                  type: institution_error
                  code: credentials_invalid
                  message: El banco rechazó el último ingreso. La persona debe volver a conectar su cuenta con el widget.
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

  /v1/accounts:
    get:
      tags: [Cuentas]
      operationId: listarCuentas
      summary: Listar cuentas
      parameters:
        - name: link_id
          in: query
          required: false
          description: Solo las cuentas de este link.
          schema: { type: string, pattern: "^link_[0-9a-f]{16}$" }
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/StartingAfter"
      responses:
        "200":
          description: Página de cuentas.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Lista"
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: "#/components/schemas/Account" }
        "400": { $ref: "#/components/responses/SolicitudInvalida" }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "403": { $ref: "#/components/responses/LlaveSecretRequerida" }
        "404": { $ref: "#/components/responses/NoEncontrado" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

  /v1/accounts/{id}:
    parameters:
      - $ref: "#/components/parameters/AccountId"
    get:
      tags: [Cuentas]
      operationId: obtenerCuenta
      summary: Obtener una cuenta
      responses:
        "200":
          description: La cuenta.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Account" }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "403": { $ref: "#/components/responses/LlaveSecretRequerida" }
        "404": { $ref: "#/components/responses/NoEncontrado" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

  /v1/accounts/{id}/movements:
    parameters:
      - $ref: "#/components/parameters/AccountId"
    get:
      tags: [Movimientos]
      operationId: listarMovimientos
      summary: Listar movimientos
      description: Movimientos de la cuenta por fecha contable, del más nuevo al más antiguo.
      parameters:
        - name: since
          in: query
          required: false
          description: Fecha contable desde (inclusive), AAAA-MM-DD.
          schema: { type: string, format: date }
        - name: until
          in: query
          required: false
          description: Fecha contable hasta (inclusive), AAAA-MM-DD. No puede ser anterior a `since`.
          schema: { type: string, format: date }
        - $ref: "#/components/parameters/Limit"
        - $ref: "#/components/parameters/StartingAfter"
      responses:
        "200":
          description: Página de movimientos.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Lista"
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: "#/components/schemas/Movement" }
        "400": { $ref: "#/components/responses/SolicitudInvalida" }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "403": { $ref: "#/components/responses/LlaveSecretRequerida" }
        "404": { $ref: "#/components/responses/NoEncontrado" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

  /v1/institutions:
    get:
      tags: [Instituciones]
      operationId: listarInstituciones
      summary: Listar instituciones
      description: |
        Todas las instituciones en una sola página, con su estado en el modo de la llave. Acepta llaves secret o
        publishable.
      responses:
        "200":
          description: Lista de instituciones.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/Lista"
                  - type: object
                    properties:
                      data:
                        type: array
                        items: { $ref: "#/components/schemas/Institution" }
        "401": { $ref: "#/components/responses/NoAutenticado" }
        "429": { $ref: "#/components/responses/DemasiadasSolicitudes" }
        "500": { $ref: "#/components/responses/ErrorInterno" }

webhooks:
  evento:
    post:
      summary: Evento de webhook
      description: |
        POST firmado a tus endpoints registrados y a la `webhook_url` del link token. Encabezados:
        `Banky-Signature: t=<unix>,v1=<hex>` (HMAC-SHA256 de `<t>.<cuerpo crudo>` con el secreto `whsec_…` completo) y
        `Banky-Event-Id`. Responde 2xx en menos de 10 segundos; si no, se reintenta hasta 8 veces.
      parameters:
        - name: Banky-Signature
          in: header
          required: true
          schema: { type: string, examples: ["t=1763474532,v1=5f2c8e0a9d1b…"] }
        - name: Banky-Event-Id
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Event" }
      responses:
        "200":
          description: Evento recibido. Cualquier 2xx se considera entregado.

components:
  securitySchemes:
    llave:
      type: http
      scheme: bearer
      description: Llave de API (`banky_sk_live_…`, `banky_sk_test_…`, `banky_pk_live_…` o `banky_pk_test_…`).

  parameters:
    Limit:
      name: limit
      in: query
      required: false
      description: Elementos por página, de 1 a 100.
      schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
    StartingAfter:
      name: starting_after
      in: query
      required: false
      description: Cursor. El `id` del último elemento de la página anterior.
      schema: { type: string }
    LinkId:
      name: id
      in: path
      required: true
      description: Id del link.
      schema: { type: string, pattern: "^link_[0-9a-f]{16}$", examples: ["link_9f2c41ab7e05d318"] }
    AccountId:
      name: id
      in: path
      required: true
      description: Id de la cuenta.
      schema: { type: string, pattern: "^acc_[0-9a-f]{16}$", examples: ["acc_3f9a1c0e5b7d2468"] }

  responses:
    SolicitudInvalida:
      description: Parámetro o cuerpo inválido.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            error: { type: invalid_request_error, code: invalid_limit, message: limit debe ser un entero entre 1 y 100. }
    NoAutenticado:
      description: Falta la llave o no es válida.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            error: { type: authentication_error, code: invalid_api_key, message: La llave de API no es válida o fue revocada. }
    LlaveSecretRequerida:
      description: Se usó una llave publishable en un endpoint que exige una llave secret.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            error:
              type: authentication_error
              code: secret_key_required
              message: Este endpoint requiere una llave secret (sk). Las llaves publishable solo crean link tokens.
    NoEncontrado:
      description: El recurso no existe en la organización o en el modo de la llave.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            error: { type: not_found, code: resource_missing, message: "No existe un link con id «link_0000000000000000»." }
    CuerpoDemasiadoGrande:
      description: El cuerpo supera 32 KB.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    DemasiadasSolicitudes:
      description: Se superó el límite de solicitudes.
      headers:
        Retry-After:
          description: Segundos a esperar antes de reintentar.
          schema: { type: integer }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
          example:
            error: { type: rate_limit_error, code: rate_limited, message: Demasiadas solicitudes. Espera un momento y vuelve a intentarlo. }
    ErrorInterno:
      description: Error inesperado.
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }

  schemas:
    HolderType:
      type: string
      enum: [individual, business]
      description: Tipo de titular.

    Mode:
      type: string
      enum: [live, test]

    Error:
      type: object
      required: [error]
      properties:
        error:
          type: object
          required: [type, code, message]
          properties:
            type:
              type: string
              enum: [invalid_request_error, authentication_error, not_found, rate_limit_error, institution_error, api_error]
            code:
              type: string
              description: Código estable, por ejemplo `invalid_limit`, `resource_missing` o `rate_limited`.
            message:
              type: string
              description: Explicación en español para personas.

    Lista:
      type: object
      required: [object, data, has_more]
      properties:
        object: { type: string, const: list }
        data: { type: array, items: {} }
        has_more: { type: boolean }

    LinkToken:
      type: object
      required: [object, link_token, expires_at, mode]
      properties:
        object: { type: string, const: link_token }
        link_token:
          type: string
          pattern: "^lt_[0-9a-f]{48}$"
        expires_at: { type: string, format: date-time }
        mode: { $ref: "#/components/schemas/Mode" }
      example:
        object: link_token
        link_token: lt_7c1e9a4f2b8d6035e1a7c94b2f0d8e6a1c3b5d7f9e2a4c6b
        expires_at: "2026-11-18T14:31:52.104Z"
        mode: test

    Link:
      type: object
      required:
        [id, object, institution, holder_type, holder_name, holder_id, status, status_message, mode, allow_mcp, last_refreshed_at, next_refresh_at, created_at]
      properties:
        id: { type: string, pattern: "^link_[0-9a-f]{16}$" }
        object: { type: string, const: link }
        institution:
          type: object
          required: [id, name]
          properties:
            id: { type: string, examples: [bci, sandbox] }
            name: { type: string }
        holder_type: { $ref: "#/components/schemas/HolderType" }
        holder_name: { type: [string, "null"], description: Nombre o razón social del titular. }
        holder_id: { type: [string, "null"], description: "RUT del titular sin puntos y con guion (12345678-5)." }
        status:
          type: string
          enum: [active, syncing, credentials_invalid, action_required, error, disconnected]
        status_message: { type: [string, "null"] }
        mode: { $ref: "#/components/schemas/Mode" }
        allow_mcp: { type: boolean }
        last_refreshed_at: { type: [string, "null"], format: date-time }
        next_refresh_at: { type: [string, "null"], format: date-time }
        created_at: { type: string, format: date-time }
      example:
        id: link_9f2c41ab7e05d318
        object: link
        institution: { id: sandbox, name: Banco de Prueba }
        holder_type: business
        holder_name: Panadería La Espiga SpA
        holder_id: 76123874-4
        status: active
        status_message: null
        mode: test
        allow_mcp: true
        last_refreshed_at: "2026-11-18T14:02:11.482Z"
        next_refresh_at: "2026-11-19T14:02:11.482Z"
        created_at: "2026-11-18T14:02:09.917Z"

    Account:
      type: object
      required: [id, object, link_id, number, name, type, currency, balance, refreshed_at]
      properties:
        id: { type: string, pattern: "^acc_[0-9a-f]{16}$" }
        object: { type: string, const: account }
        link_id: { type: string }
        number: { type: string }
        name: { type: string }
        type:
          type: string
          enum: [checking_account, sight_account, savings_account, credit_card, line_of_credit]
        currency: { type: string, examples: [CLP] }
        balance:
          type: object
          required: [available, current]
          properties:
            available: { type: [integer, "null"], description: Saldo disponible en pesos enteros. }
            current: { type: [integer, "null"], description: Saldo contable en pesos enteros. }
        refreshed_at: { type: string, format: date-time }
      example:
        id: acc_3f9a1c0e5b7d2468
        object: account
        link_id: link_9f2c41ab7e05d318
        number: "0012785975"
        name: Cuenta Corriente
        type: checking_account
        currency: CLP
        balance: { available: 26593700, current: 26638700 }
        refreshed_at: "2026-11-18T14:02:11.204Z"

    Movement:
      type: object
      required:
        [id, object, account_id, amount, currency, type, description, bank_description, post_date, transaction_date, counterparty, reference_id]
      properties:
        id: { type: string, pattern: "^mov_[0-9a-f]{16}$" }
        object: { type: string, const: movement }
        account_id: { type: string }
        amount: { type: integer, description: Pesos enteros. Positivo para abonos, negativo para cargos. }
        currency: { type: string, examples: [CLP] }
        type: { type: string, enum: [inflow, outflow] }
        description: { type: string }
        bank_description: { type: [string, "null"], description: Glosa original del banco. }
        post_date: { type: string, format: date, description: Fecha contable. }
        transaction_date: { type: [string, "null"], format: date }
        counterparty:
          type: object
          required: [name, id]
          properties:
            name: { type: [string, "null"] }
            id: { type: [string, "null"], description: RUT sin puntos y con guion. }
        reference_id: { type: [string, "null"], description: Número de operación del banco. }
      example:
        id: mov_e41b9c07a2d85f36
        object: movement
        account_id: acc_3f9a1c0e5b7d2468
        amount: 1315000
        currency: CLP
        type: inflow
        description: Pago de factura de Constructora Valle Central SpA
        bank_description: "TRASPASO DE: CONSTRUCTORA VALLE CENTRAL SPA"
        post_date: "2026-11-18"
        transaction_date: "2026-11-18"
        counterparty: { name: Constructora Valle Central SpA, id: 76287005-3 }
        reference_id: "479249273"

    Institution:
      type: object
      required: [id, object, name, status, holder_types, test_only]
      properties:
        id: { type: string, examples: [bci, sandbox, santander] }
        object: { type: string, const: institution }
        name: { type: string }
        status: { type: string, enum: [available, coming_soon] }
        holder_types:
          type: array
          items: { $ref: "#/components/schemas/HolderType" }
        test_only: { type: boolean }

    Event:
      type: object
      required: [id, object, type, mode, created_at, data]
      properties:
        id: { type: string, pattern: "^evt_[0-9a-f]{24}$" }
        object: { type: string, const: event }
        type:
          type: string
          enum: [link.created, link.refreshed, link.credentials_invalid, link.action_required, movements.new, link.deleted]
        mode: { $ref: "#/components/schemas/Mode" }
        created_at: { type: string, format: date-time }
        data:
          oneOf:
            - title: Evento de link
              type: object
              required: [link]
              properties:
                link: { $ref: "#/components/schemas/Link" }
            - title: Movimientos nuevos
              type: object
              required: [link_id, account_ids, new_movements]
              properties:
                link_id: { type: string }
                account_ids: { type: array, items: { type: string } }
                new_movements: { type: integer, minimum: 1 }
