{
  "openapi": "3.1.0",
  "info": {
    "title": "API de webhooks do Sintonia",
    "version": "1.0.0",
    "description": "Contratos dos endpoints implementados. Veja WEBHOOKS.md para criptografia, exemplos, intervalos e configuração. A criação usa 200; revogação usa 200 sem corpo."
  },
  "servers": [
    {
      "url": "https://chat.example.com",
      "description": "Exemplo; substitua pelo backend da sua instalação."
    },
    {
      "url": "http://localhost:8080",
      "description": "Desenvolvimento local."
    }
  ],
  "security": [
    {
      "sessionBearer": []
    }
  ],
  "tags": [
    {
      "name": "Publicação"
    },
    {
      "name": "Administração"
    },
    {
      "name": "Chaves"
    }
  ],
  "paths": {
    "/hooks/{token}": {
      "parameters": [
        {
          "name": "token",
          "in": "path",
          "required": true,
          "schema": {
            "type": "string",
            "maxLength": 128
          },
          "description": "Segredo da URL de entrada."
        }
      ],
      "post": {
        "summary": "Publicar uma mensagem no canal fixado na entrada",
        "operationId": "publishIncomingMessage",
        "tags": [
          "Publicação"
        ],
        "security": [],
        "description": "Até 60 publicações aceitas por janela de 60 segundos por entrada. O servidor processa o texto externo via TLS e cifra antes de persistir. Repetir uma requisição aceita cria outra mensagem.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/IncomingPayload"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Mensagem recebida, cifrada e persistida.",
            "content": {
              "text/plain": {
                "schema": {
                  "type": "string",
                  "enum": [
                    "ok"
                  ]
                },
                "example": "ok"
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/Error"
          },
          "404": {
            "$ref": "#/components/responses/Error"
          },
          "413": {
            "$ref": "#/components/responses/Error"
          },
          "429": {
            "$ref": "#/components/responses/Error"
          }
        }
      }
    },
    "/api/channels/{channel}/integrations": {
      "parameters": [
        {
          "$ref": "#/components/parameters/Channel"
        },
        {
          "$ref": "#/components/parameters/Workspace"
        }
      ],
      "get": {
        "summary": "Listar integrações e até 100 entregas de saída",
        "operationId": "listIntegrations",
        "tags": [
          "Administração"
        ],
        "description": "Exige participação no workspace/canal e função administrador ou proprietário. Entradas e saídas incluem revogadas; entregas ordenadas por next_attempt decrescente. Não retorna segredos nem URLs de destino.",
        "responses": {
          "200": {
            "description": "Sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrationList"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Error"
          },
          "403": {
            "$ref": "#/components/responses/Error"
          },
          "409": {
            "$ref": "#/components/responses/Error"
          }
        }
      }
    },
    "/api/channels/{channel}/integrations/keys": {
      "parameters": [
        {
          "$ref": "#/components/parameters/Channel"
        },
        {
          "$ref": "#/components/parameters/Workspace"
        }
      ],
      "get": {
        "summary": "Consultar pacotes cifrados das entradas do canal",
        "operationId": "getIntegrationKeys",
        "tags": [
          "Chaves"
        ],
        "description": "Exige participação no workspace e canal, sem exigir função administrativa. Inclui entradas revogadas e de outros workspaces que compartilham o canal. Não entrega chaves privadas em claro.",
        "responses": {
          "200": {
            "description": "Sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/IntegrationKey"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Error"
          },
          "403": {
            "$ref": "#/components/responses/Error"
          },
          "409": {
            "$ref": "#/components/responses/Error"
          }
        }
      }
    },
    "/api/channels/{channel}/integrations/incoming": {
      "parameters": [
        {
          "$ref": "#/components/parameters/Channel"
        },
        {
          "$ref": "#/components/parameters/Workspace"
        }
      ],
      "post": {
        "summary": "Criar uma entrada",
        "operationId": "createIncomingIntegration",
        "tags": [
          "Administração"
        ],
        "description": "Exige administrador/proprietário participante. Limite combinado de 100 integrações ativas por workspace. O cliente gera publicKey e keyBox; a chave privada nunca é enviada em claro.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateIncoming"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IncomingCreated"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/Error"
          },
          "401": {
            "$ref": "#/components/responses/Error"
          },
          "403": {
            "$ref": "#/components/responses/Error"
          },
          "409": {
            "$ref": "#/components/responses/Error"
          }
        }
      }
    },
    "/api/channels/{channel}/integrations/outgoing": {
      "parameters": [
        {
          "$ref": "#/components/parameters/Channel"
        },
        {
          "$ref": "#/components/parameters/Workspace"
        }
      ],
      "post": {
        "summary": "Criar uma saída",
        "operationId": "createOutgoingIntegration",
        "tags": [
          "Administração"
        ],
        "description": "Exige administrador/proprietário participante. O destino recebe message.created com envelope cifrado. Criar não testa conectividade. A ausência de chave operacional no SaaS retorna 503.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateOutgoing"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Sucesso.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OutgoingCreated"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/Error"
          },
          "401": {
            "$ref": "#/components/responses/Error"
          },
          "403": {
            "$ref": "#/components/responses/Error"
          },
          "409": {
            "$ref": "#/components/responses/Error"
          },
          "503": {
            "$ref": "#/components/responses/Error"
          }
        }
      }
    },
    "/api/channels/{channel}/integrations/{id}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/Channel"
        },
        {
          "$ref": "#/components/parameters/Workspace"
        },
        {
          "name": "id",
          "in": "path",
          "required": true,
          "schema": {
            "type": "string",
            "format": "uuid"
          }
        }
      ],
      "delete": {
        "summary": "Revogar uma entrada ou saída",
        "operationId": "revokeIntegration",
        "tags": [
          "Administração"
        ],
        "description": "Exige administrador/proprietário participante. Idempotente: identificador sem correspondência no escopo também retorna 200. Preserva o histórico e pacotes cifrados. Não há reativação. Uma entrega em trânsito pode terminar.",
        "responses": {
          "200": {
            "description": "Revogação concluída; sem corpo."
          },
          "401": {
            "$ref": "#/components/responses/Error"
          },
          "403": {
            "$ref": "#/components/responses/Error"
          },
          "409": {
            "$ref": "#/components/responses/Error"
          }
        }
      }
    }
  },
  "webhooks": {
    "message.created": {
      "post": {
        "summary": "Evento enviado pelo Sintonia à URL de saída configurada",
        "operationId": "receiveMessageCreated",
        "security": [],
        "description": "Callback no serviço receptor. Conteúdo cifrado; id estável por destino. Responda 2xx após aceitação durável. Até oito tentativas, sem garantia de ordem ou entrega exatamente uma vez. Não são seguidos redirecionamentos. Valide assinatura, timestamp e deduplique o id antes de processar.",
        "parameters": [
          {
            "name": "X-Sintonia-Event-Id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          },
          {
            "name": "X-Sintonia-Timestamp",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[0-9]+$"
            },
            "description": "Segundos Unix da tentativa."
          },
          {
            "name": "X-Sintonia-Signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^v1=[0-9a-f]{64}$"
            },
            "description": "v1= + HMAC-SHA256 hexadecimal minúsculo de ASCII(timestamp) + ponto + corpo original, usando o segredo Base64 decodificado."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MessageCreated"
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Evento aceito pelo receptor."
          },
          "default": {
            "description": "Evento não confirmado; sujeito a reenvio até esgotar tentativas."
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "sessionBearer": {
        "type": "http",
        "scheme": "bearer",
        "description": "Token opaco da sessão do Sintonia; não é JWT nem o token da entrada."
      }
    },
    "parameters": {
      "Channel": {
        "name": "channel",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string",
          "format": "uuid"
        }
      },
      "Workspace": {
        "name": "X-Workspace-Id",
        "in": "header",
        "required": false,
        "schema": {
          "type": "string",
          "format": "uuid"
        },
        "description": "Informe explicitamente em contas com vários workspaces. Ausência usa uma associação da conta."
      }
    },
    "responses": {
      "Error": {
        "description": "Falha de autorização, validação ou configuração. O formato pode variar em erros de framework.",
        "content": {
          "application/json": {
            "schema": {
              "type": "object",
              "additionalProperties": true,
              "properties": {
                "message": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "schemas": {
      "IntegrationMetadata": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 80,
            "description": "Não pode conter somente espaços."
          },
          "active": {
            "type": "boolean"
          },
          "created_at": {
            "type": "integer",
            "format": "int64",
            "description": "Instante Unix em milissegundos."
          }
        },
        "required": [
          "id",
          "name",
          "active",
          "created_at"
        ]
      },
      "Delivery": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "hook_id": {
            "type": "string",
            "format": "uuid"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "delivered",
              "failed",
              "cancelled"
            ]
          },
          "attempts": {
            "type": "integer",
            "minimum": 0
          },
          "http_status": {
            "type": [
              "integer",
              "null"
            ]
          },
          "next_attempt": {
            "type": "integer",
            "format": "int64",
            "description": "Instante Unix em milissegundos."
          }
        },
        "required": [
          "id",
          "hook_id",
          "status",
          "attempts",
          "http_status",
          "next_attempt"
        ]
      },
      "IntegrationList": {
        "type": "object",
        "properties": {
          "incoming": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/IntegrationMetadata"
            }
          },
          "outgoing": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/IntegrationMetadata"
            }
          },
          "deliveries": {
            "type": "array",
            "maxItems": 100,
            "items": {
              "$ref": "#/components/schemas/Delivery"
            }
          }
        },
        "required": [
          "incoming",
          "outgoing",
          "deliveries"
        ]
      },
      "IncomingPayload": {
        "type": "object",
        "properties": {
          "text": {
            "type": "string",
            "maxLength": 16000,
            "description": "Prioridade sobre blocks quando não vazio. Limite medido em unidades UTF-16."
          },
          "blocks": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "text": {
                  "type": "object",
                  "properties": {
                    "text": {
                      "type": "string"
                    }
                  }
                },
                "elements": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "text": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "anyOf": [
          {
            "required": [
              "text"
            ]
          },
          {
            "required": [
              "blocks"
            ]
          }
        ],
        "description": "Objeto JSON de até 65536 bytes. O texto extraído deve ser não vazio e ter até 16000 unidades UTF-16. Campos extras são ignorados; nome e canal são fixos. Não há idempotência."
      },
      "CreateIncoming": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 80,
            "description": "Não pode conter somente espaços."
          },
          "publicKey": {
            "type": "string",
            "minLength": 44,
            "maxLength": 44,
            "contentEncoding": "base64",
            "description": "Chave pública X25519 de 32 bytes."
          },
          "keyBox": {
            "type": "string",
            "minLength": 1,
            "maxLength": 2000,
            "description": "JSON serializado como string, contendo ciphertext, nonce e mac em Base64. Criado no cliente com a chave do canal; consulte WEBHOOKS.md."
          },
          "keyGeneration": {
            "type": "string",
            "maxLength": 36,
            "description": "Geração atual obtida em /api/channels/{id}/keys. Omitir equivale à geração inicial vazia; após recuperação sem histórico, envie a geração atual."
          }
        },
        "required": [
          "name",
          "publicKey",
          "keyBox"
        ],
        "additionalProperties": false
      },
      "IncomingCreated": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "path": {
            "type": "string",
            "description": "Caminho /hooks/{token}. Token secreto exibido somente na criação."
          }
        },
        "required": [
          "id",
          "path"
        ]
      },
      "IntegrationKey": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "public_key": {
            "type": "string",
            "contentEncoding": "base64"
          },
          "key_box": {
            "type": "string",
            "description": "Pacote cifrado serializado como JSON. Inclui entradas revogadas para leitura do histórico."
          }
        },
        "required": [
          "id",
          "public_key",
          "key_box"
        ]
      },
      "CreateOutgoing": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 80,
            "description": "Não pode conter somente espaços."
          },
          "url": {
            "type": "string",
            "format": "uri",
            "maxLength": 2000,
            "description": "HTTPS sem credenciais ou fragmento. IPs privados/reservados bloqueados na entrega, exceto na configuração selfhost explícita."
          }
        },
        "required": [
          "name",
          "url"
        ],
        "additionalProperties": false
      },
      "OutgoingCreated": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "secret": {
            "type": "string",
            "contentEncoding": "base64",
            "minLength": 44,
            "maxLength": 44,
            "description": "32 bytes em Base64 padrão. Exibido somente na criação."
          }
        },
        "required": [
          "id",
          "secret"
        ]
      },
      "EncryptedMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "channel_id": {
            "type": "string",
            "format": "uuid"
          },
          "user_id": {
            "type": "string",
            "format": "uuid"
          },
          "client_id": {
            "type": "string",
            "format": "uuid"
          },
          "parent_id": {
            "type": [
              "string",
              "null"
            ],
            "format": "uuid"
          },
          "ciphertext": {
            "type": "string",
            "contentEncoding": "base64"
          },
          "nonce": {
            "type": "string",
            "contentEncoding": "base64"
          },
          "mac": {
            "type": "string",
            "contentEncoding": "base64"
          },
          "created_at": {
            "type": "integer",
            "format": "int64",
            "description": "Instante Unix em milissegundos."
          },
          "kind": {
            "type": "string",
            "enum": [
              "message",
              "webhook"
            ]
          },
          "source_id": {
            "type": [
              "string",
              "null"
            ],
            "format": "uuid"
          },
          "ephemeral_key": {
            "type": [
              "string",
              "null"
            ]
          },
          "display_name": {
            "type": [
              "string",
              "null"
            ]
          },
          "author": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "channel_id",
          "user_id",
          "client_id",
          "ciphertext",
          "nonce",
          "mac",
          "created_at",
          "kind",
          "author"
        ]
      },
      "MessageCreated": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "type": {
            "type": "string",
            "enum": [
              "message.created"
            ]
          },
          "workspace_id": {
            "type": "string",
            "format": "uuid"
          },
          "channel_id": {
            "type": "string",
            "format": "uuid"
          },
          "encrypted": {
            "type": "boolean",
            "const": true
          },
          "message": {
            "$ref": "#/components/schemas/EncryptedMessage"
          }
        },
        "required": [
          "id",
          "type",
          "workspace_id",
          "channel_id",
          "encrypted",
          "message"
        ]
      }
    }
  }
}
