Skip to content

fix(webhook-inbound): refactor híbrido v1/v2 + idempotência + migrations seguras#460

Merged
adm01-debug merged 1 commit into
mainfrom
fix/webhook-inbound-hybrid-and-safe-migrations-20260526
May 26, 2026
Merged

fix(webhook-inbound): refactor híbrido v1/v2 + idempotência + migrations seguras#460
adm01-debug merged 1 commit into
mainfrom
fix/webhook-inbound-hybrid-and-safe-migrations-20260526

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 26, 2026

Resumo

Restaura funcionalidades críticas removidas pelo Lovable em 26/05 enquanto preserva os ganhos legítimos do refactor (idempotência, structured logging, retry).

Contexto

Em 26/05/2026 entre 14:09 e 14:41 UTC, o Lovable produziu 28 commits no projeto rotulados como "Fast Visual Edit" / "Centralizou stepper" / "Unificou ícones do header". Auditoria desses commits identificou:

  1. Bug base64 (vercel.json + BUG_REPORT) → corrigido no PR fix(infra): decodifica vercel.json + BUG_REPORT base64 — desbloqueia deploys Vercel #459 (já mergeado ✅)
  2. Refactor mascarado do webhook-inbound → este PR
  3. 3 migrations problemáticas não aplicadas → este PR

Mudanças

📁 supabase/functions/webhook-inbound/index.ts

Preserva (regressão do Lovable):

  • Lógica de versionamento de contrato v1/v2 (readRequestedVersion, parseAllowlist)
  • Headers Deprecation / Sunset / Warning para v1 deprecada
  • Response 426 Upgrade Required para v1 não-allowlisted
  • Variáveis WEBHOOK_INBOUND_V1_COMPAT_ENABLED e WEBHOOK_INBOUND_V1_ALLOWLIST
  • Métrica estruturada webhook_inbound_contract_version_adoption (observabilidade)

Incorpora (ganhos do refactor):

  • Idempotência via x-idempotency-key header, payload.idempotency_key (v2) ou hash da assinatura HMAC (fallback). Validação 8-256 chars
  • Tratamento de 23505 (unique_violation) como duplicate=true para resolver race conditions
  • Structured logger + request-id propagado em todos os logs
  • retrySupabaseCall envolvendo queries críticas
  • RPC increment_webhook_stats atômica (substitui UPDATE direto com race)

Corrige bugs presentes em AMBAS as versões anteriores:

  • INSERT agora usa colunas reais: ip_address (não source_ip), error_message (não error). A versão pré-Lovable inseria em colunas inexistentes — provavelmente com payload silenciosamente truncado.

📁 Migrations

Arquivo Antes (Lovable) Agora
20260526141234_31aaa458 DROP/CREATE em massa nas policies de user_roles, order_items, admin_audit_log com can_view_all_sales(auth.uid()) quando função tem 0 args NO-OP com comentário explicativo. Falharia em CREATE POLICY; modelo assumido (organization_members) diverge do guarded atual
20260526141615_52d285ed ADD idempotency_key + ADD contract_version (esta já existe NOT NULL) Reescrito: só adiciona idempotency_key nullable + índice único parcial. contract_version não tocado
20260526141659_5cd6e346 Função increment_webhook_stats sem ACL Mantido com ACL explícito: REVOKE ALL FROM PUBLIC, anon, authenticated; GRANT EXECUTE TO service_role, postgres

Status do banco

As migrations seguras (141615 e 141659) já foram aplicadas no banco doufsxqlfjyuvxuezpln via MCP. Validação:

check_name                                | ok
------------------------------------------|----
idempotency_key                           | t
idx_webhook_idempotency                   | t
increment_webhook_stats                   | t
increment_webhook_stats_acl_service_role  | t

A migration RLS (141234) NÃO foi aplicada e está como NO-OP. Se o rewrite for desejado, abrir PR humano dedicado conforme nota no arquivo.

Validação

  • npm run build — 1m49s, sem erros
  • ✅ Banco validado com 4/4 checks passando
  • ⚠️ npm run lint reporta regressões TS pré-existentes do PR Claude/frontend supabase bugs spsu e #457 (baseline desatualizado), não causadas por este PR

Deploy da edge function

Este PR atualiza o código da função. O Supabase auto-deploya edge functions a partir do push no main se o GitHub integration estiver configurado; caso contrário, rodar manualmente:

supabase functions deploy webhook-inbound --project-ref doufsxqlfjyuvxuezpln

Próximos passos sugeridos (fora do escopo deste PR)

  1. CI workflow que falha em commit com linha >200 chars puramente alfanumérica (preveniria bug base64 — ocorreu 3x)
  2. Branch protection na main exigindo check Vercel verde
  3. Regra .coderabbit.yaml flagando commits "visual" que tocam supabase/functions/ ou supabase/migrations/

🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com


Summary by cubic

Restores inbound webhook v1/v2 behavior (allowlist, deprecation/sunset headers, 426 for blocked v1) and adds idempotency with race-safe inserts and structured logging. Also fixes wrong column writes and replaces risky migrations with safe ones.

  • New Features

    • Idempotency via x-idempotency-key, payload idempotency_key, or HMAC signature fallback; 23505 treated as duplicate using a partial unique index.
    • Structured logs with request-id and retry around critical DB calls.
    • Atomic increment_webhook_stats RPC for endpoint stats.
  • Migration

    • 20260526141234: RLS rewrite changed to NO-OP with guidance; not applied.
    • 20260526141615: add nullable idempotency_key and partial unique index; do not touch existing contract_version.
    • 20260526141659: create increment_webhook_stats with strict ACL (service_role, postgres).

Written for commit c9d8afa. Summary will update on new commits. Review in cubic

…ons seguras

Contexto:
- Lovable em 26/05 (commits 14:09-14:41 UTC) reescreveu webhook-inbound
  com mensagem "Fast Visual Edit" mas removeu funcionalidades críticas
  (versionamento de contrato v1/v2, allowlist legada, headers de sunset,
  resposta 426 para v1 bloqueada, métrica de adoção de contrato).
- Trouxe também 3 migrations problemáticas que não foram aplicadas.

Webhook-inbound — versão híbrida:
✅ Preserva:
  - Lógica v1/v2 com readRequestedVersion() e parseAllowlist()
  - Headers Deprecation/Sunset/Warning para v1 deprecada
  - Response 426 para v1 não-allowlisted
  - WEBHOOK_INBOUND_V1_COMPAT_ENABLED e WEBHOOK_INBOUND_V1_ALLOWLIST
  - Métrica estruturada webhook_inbound_contract_version_adoption

✅ Incorpora do refactor:
  - Idempotency via x-idempotency-key, payload.idempotency_key ou hash da
    assinatura HMAC (fallback). Validação 8-256 chars.
  - Tratamento 23505 (unique_violation) como duplicate em race condition
  - Structured logger + request-id propagado
  - retrySupabaseCall em todas as queries críticas
  - RPC increment_webhook_stats (atômico, sem race)

✅ Corrige bugs presentes em AMBAS as versões anteriores:
  - INSERT usa colunas reais: ip_address (não source_ip), error_message
    (não error). A versão antiga inseria em colunas inexistentes —
    silenciosamente, com payload truncado.

Migrations:
- 20260526141234 (RLS user_roles/order_items/admin_audit_log): convertido
  para NO-OP com comentário explicando por quê (DROP POLICY em massa sem
  revisão; chama can_view_all_sales(auth.uid()) mas função tem 0 args;
  modelo organization_members diverge do guarded atual).
- 20260526141615 (idempotency_key + contract_version): reescrito.
  contract_version já existe NOT NULL — não tocar. idempotency_key
  adicionado nullable com índice único parcial.
- 20260526141659 (increment_webhook_stats): mantido com ACL explícito
  (service_role + postgres only).

Migrations seguras (141615 e 141659) JÁ APLICADAS no banco
doufsxqlfjyuvxuezpln. RLS rewrite (141234) deixado para PR humano dedicado.

Build local: ✅ npm run build 1m49s
Banco validado: ✅ idempotency_key existe, idx_webhook_idempotency criado,
                  increment_webhook_stats função criada com ACL correta

Co-authored-by: Claude <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings May 26, 2026 15:57
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@vercel
Copy link
Copy Markdown

vercel Bot commented May 26, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 26, 2026 3:57pm

@supabase
Copy link
Copy Markdown

supabase Bot commented May 26, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln due to reaching the limit of concurrent preview branches.
Go to Project Integrations Settings ↗︎ if you wish to update this limit.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 26, 2026

Warning

Review limit reached

@adm01-debug, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 48 minutes. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ff587a4e-e7df-43f9-89e3-c395abc9dadd

📥 Commits

Reviewing files that changed from the base of the PR and between 77ba5c5 and c9d8afa.

📒 Files selected for processing (4)
  • supabase/functions/webhook-inbound/index.ts
  • supabase/migrations/20260526141234_31aaa458-1bc1-476f-bca6-8152907d7a99.sql
  • supabase/migrations/20260526141615_52d285ed-e141-4437-9a13-0fec9285c93c.sql
  • supabase/migrations/20260526141659_5cd6e346-f106-4e21-b2b7-171d86b581b6.sql
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/webhook-inbound-hybrid-and-safe-migrations-20260526

Comment @coderabbitai help to get the list of available commands and usage tips.

@adm01-debug adm01-debug merged commit 2445032 into main May 26, 2026
29 of 35 checks passed
adm01-debug added a commit that referenced this pull request May 26, 2026
Implementa as 4 melhorias sugeridas no PR #460 para prevenir
recorrência dos 3 padrões problemáticos identificados em 26/05.

1. .github/workflows/detect-base64-content.yml (NOVO)
   CI check que detecta arquivos texto acidentalmente commitados
   em base64 (linha >=200 chars com alfabeto [A-Za-z0-9+/=]).
   Roda em pull_request + push para main. Falha o check se achar.
   Self-tested: 0 false positives no repo atual, true positive em
   payload sintético, true negative em prosa longa.
   Cobre regressão dos PRs #319, #457, #459.

2. .coderabbit.yaml (UPDATE)
   Adiciona 3 alertas:
   - ALERTA DE DRIFT em supabase/functions/**/*.ts: flag PRs com
     título/commit "Fast Visual Edit"/"visual"/"stepper" tocando
     edge functions — caso PR #460.
   - ALERTA DE DRIFT em supabase/migrations/**/*.sql: idem para
     migrations, com checks específicos (DROP POLICY massa, ADD
     COLUMN no-op, SECURITY DEFINER sem REVOKE).
   - Detecção base64 em arquivos texto como reforço do workflow.

3. .github/workflows/required-checks-guard.yml (UPDATE)
   Estende verificação existente para também checar que algum
   check do Vercel/deploy está como required em main. Tolerante:
   emite warning ao invés de fail enquanto config é ajustada.
   Background: 26/05/2026 — 20 deploys ERROR não impediram 19
   commits entrarem em main.

4. docs/RLS_REWRITE_PLAN.md (NOVO) + nota na migration 141234
   Documento técnico explicando por que o RLS rewrite (migration
   141234) foi convertido em NO-OP, com snapshot completo das
   policies atuais e checklist do que deve ser feito se alguém
   decidir retomar o rewrite no futuro. Substitui criar issue.

Validações:
✅ yamllint nos 3 arquivos YAML
✅ Detector base64: 0 FP em supabase/functions/webhook-inbound,
   vercel.json, .coderabbit.yaml e ele mesmo
✅ Detector base64: TP em payload sintético >200 chars
✅ Detector base64: TN em prosa em PT-BR com acentos/espaços

Co-authored-by: Claude <noreply@anthropic.com>
adm01-debug added a commit that referenced this pull request May 26, 2026
Implementa as 4 melhorias sugeridas no PR #460 para prevenir
recorrência dos 3 padrões problemáticos identificados em 26/05.

1. .github/workflows/detect-base64-content.yml (NOVO)
   CI check que detecta arquivos texto acidentalmente commitados
   em base64 (linha >=200 chars com alfabeto [A-Za-z0-9+/=]).
   Roda em pull_request + push para main. Falha o check se achar.
   Self-tested: 0 false positives no repo atual, true positive em
   payload sintético, true negative em prosa longa.
   Cobre regressão dos PRs #319, #457, #459.

2. .coderabbit.yaml (UPDATE)
   Adiciona 3 alertas:
   - ALERTA DE DRIFT em supabase/functions/**/*.ts: flag PRs com
     título/commit "Fast Visual Edit"/"visual"/"stepper" tocando
     edge functions — caso PR #460.
   - ALERTA DE DRIFT em supabase/migrations/**/*.sql: idem para
     migrations, com checks específicos (DROP POLICY massa, ADD
     COLUMN no-op, SECURITY DEFINER sem REVOKE).
   - Detecção base64 em arquivos texto como reforço do workflow.

3. .github/workflows/required-checks-guard.yml (UPDATE)
   Estende verificação existente para também checar que algum
   check do Vercel/deploy está como required em main. Tolerante:
   emite warning ao invés de fail enquanto config é ajustada.
   Background: 26/05/2026 — 20 deploys ERROR não impediram 19
   commits entrarem em main.

4. docs/RLS_REWRITE_PLAN.md (NOVO) + nota na migration 141234
   Documento técnico explicando por que o RLS rewrite (migration
   141234) foi convertido em NO-OP, com snapshot completo das
   policies atuais e checklist do que deve ser feito se alguém
   decidir retomar o rewrite no futuro. Substitui criar issue.

Validações:
✅ yamllint nos 3 arquivos YAML
✅ Detector base64: 0 FP em supabase/functions/webhook-inbound,
   vercel.json, .coderabbit.yaml e ele mesmo
✅ Detector base64: TP em payload sintético >200 chars
✅ Detector base64: TN em prosa em PT-BR com acentos/espaços

Co-authored-by: Claude <noreply@anthropic.com>
@adm01-debug adm01-debug review requested due to automatic review settings May 26, 2026 16:21
@adm01-debug adm01-debug deleted the fix/webhook-inbound-hybrid-and-safe-migrations-20260526 branch May 29, 2026 13:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant