Skip to content

chore(redeploy-fase2): close T3/T22/T23 gaps with guard + UI checklist#166

Merged
adm01-debug merged 6 commits into
mainfrom
claude/check-redeploy-readiness-LrPY8
May 14, 2026
Merged

chore(redeploy-fase2): close T3/T22/T23 gaps with guard + UI checklist#166
adm01-debug merged 6 commits into
mainfrom
claude/check-redeploy-readiness-LrPY8

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Contexto

Fecha as 3 pendências residuais da Fase 2 do redeploy 2026-05 (T3, T22, T23) descobertas durante o diagnóstico de prontidão. Resolve o que pode ser resolvido por código e formaliza o que funciona via UI (com simulação documentada do bloqueio técnico).

Refs: #78 (branch protection), #80 (security toggles), docs/redeploy/REDEPLOY-FASE2-EXECUTION-LOG.md.

O que muda

🛡️ T3 — Migrations sync hardening

  • docs/DEPLOYMENT.md: reescrita completa. A versão anterior ensinava supabase db push — comando que destruiria o banco prod dado o desync 332-vs-209 documentado na T3. Novo doc cobre arquitetura dual Lovable+Vercel, política de DDL via MCP/Dashboard, checklist pré-deploy e rollback.
  • scripts/check-no-db-push.mjs (novo): allowlist-based guard. Falha o CI se alguém reintroduzir supabase db push fora dos arquivos de proibição/auditoria.
  • ci.yml (job quality): novo step Migrations sync guard invocando o script acima.
  • scripts/gen-migrations-readme.mjs: remove a instrução errada (supabase db push como caminho de aplicação) que era gerada automaticamente na README de migrations.

📋 T22 + T23 — Checklist UI consolidado

  • docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md (novo): documento único click-by-click para os 3 passos UI restantes. Calibrado para o único maintainer atual: Require approvals = 0 em vez de 1 (caso contrário o próprio maintainer ficaria bloqueado em PRs solo) — explicado no doc com a Opção A vs B.

🪪 T23 — Tentativa MCP e documentação do bloqueio

  • docs/storage/PUBLIC_BUCKETS.md: formaliza 3 tentativas executadas hoje via MCP (execute_sql, apply_migration, apply_migration + SET LOCAL ROLE), todas bloqueadas com 42501. Causa-raiz confirmada por query: storage.objects pertence a supabase_storage_admin; role postgres (via MCP) não é membro.

Por que não fechei tudo via código

Item Tentativa Bloqueio
Policy recibos_authenticated_read 3× via MCP (execute_sql, apply_migration plain, apply_migration com SET LOCAL ROLE supabase_storage_admin) Supabase exige owner da relation; nenhum role acessível via MCP é membro de supabase_storage_admin
Branch protection em main Procurei MCP tool Nenhum dos MCPs disponíveis expõe PUT /repos/.../branches/{branch}/protection
Dependabot Alerts / Secret Scanning Procurei MCP tool Nenhum dos MCPs expõe PATCH /repos/{owner}/{repo} (security_and_analysis) nem PUT vulnerability-alerts

Os 3 itens precisam de ~10 min de cliques na UI seguindo docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md.

Simulação exaustiva de cenários (executada antes do plano)

24 cenários simulados, agrupados em 3 desafios (storage policy, GitHub hardening, migrations desync) + transversais. Gaps detectados e mitigados:

  • Gap A: bucket recibos com policy USING(bucket_id=...) puro deixa qualquer authenticated ler qualquer recibo entre orgs → decisão do usuário (resposta: aceito esse nível de exposição, recibos não são sensíveis o suficiente para exigir ACL fina).
  • Gap B: único maintainer + Require approvals=1 = deadlock → checklist usa Opção A (approvals=0) por default.
  • Gap C: required check com nome errado = PR travada para sempre → checklist lista os nomes exatos extraídos dos campos name: dos jobs hoje.
  • Gap D: gen-migrations-readme.mjs re-gerava a instrução errada → corrigido em conjunto com o guard.

Detalhes na conversa do PR + comentário do CodeRabbit que será solicitado.

Validação executada localmente

$ node scripts/check-no-db-push.mjs
✅ check-no-db-push: nenhum uso novo de `supabase db push` detectado.

Próximos passos pós-merge

  1. Maintainer (Joaquim) executa docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md (~10 min)
  2. Fecha issues 🔒 P1: Ativar Branch Protection em main (UI Settings → Branches) #78 e 🔒 P1: Ativar Dependabot Security Alerts + Secret Scanning (UI) #80 com evidência
  3. Avisa o Claude para rodar validação final (advisors limpos, policies confirmadas) e marcar Fase 2 como 100% concluída no execution log
  4. GO para Fase 3 (T24–T30): E2E coverage, CI estabilidade, observability, qualidade, docs finais

Test plan

  • node scripts/check-no-db-push.mjs localmente → OK
  • CI passa (verificar nesta PR depois do push)
  • CodeRabbit aprova ou aponta gaps
  • Após merge: maintainer executa checklist UI
  • Validação final: SELECT policyname FROM pg_policies WHERE schemaname='storage' AND policyname LIKE 'recibos%' retorna 3 linhas

🤖 Generated via session_01WKZNWA4MqhKVTqB8Ta4bNW


Generated by Claude Code

Summary by CodeRabbit

  • Documentação

    • Guia de deploy redesenhado com checklist pré-redeploy, rollback expandido, arquitetura de deploy, instruções seguras para mudanças de esquema e tratamento de buckets públicos.
    • Runbook UI adicionado para criar policy de storage, configurar proteção de branches e habilitar análises de segurança.
    • Atualizada orientação de migrations: não usar push automático; seguir procedimentos seguros via apply/SQL Dashboard.
  • Chores

    • CI agora inclui uma verificação que bloqueia commits contendo comandos de push de banco não autorizados e adiciona um script de checagem local.

Review Change Stack

- docs(DEPLOYMENT): reescrita completa removendo `supabase db push` perigoso;
  documenta arquitetura dual Lovable+Vercel, desync de migrations e
  procedimento correto de DDL via MCP/Dashboard
- ci(quality): novo step "Migrations sync guard" rodando
  scripts/check-no-db-push.mjs — bloqueia reintrodução acidental do comando
  fora da allowlist documental
- scripts: novo check-no-db-push.mjs (allowlist explícita de docs
  histórico/proibição); ajusta gen-migrations-readme.mjs para parar de
  imprimir a instrução errada
- docs(storage/PUBLIC_BUCKETS): registra 3 tentativas via MCP do
  recibos_authenticated_read com causa-raiz comprovada
  (storage.objects pertence a supabase_storage_admin, postgres não é
  membro), formaliza ação manual via dashboard como única via
- docs(redeploy-fase2-checklist-ui): documento único click-by-click
  para os 3 passos UI restantes (storage policy, security toggles,
  branch protection) — calibrado para único maintainer (require
  approvals = 0 em vez de 1 para não auto-bloquear)

Refs #78 #80 #151
@vercel
Copy link
Copy Markdown

vercel Bot commented May 12, 2026

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

Project Deployment Actions Updated (UTC)
promo-gifts Ready Ready Preview, Comment May 12, 2026 10:17pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 12, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cef86871-9969-41f4-9d78-e28738452dc4

📥 Commits

Reviewing files that changed from the base of the PR and between 0f0939c and 083b590.

📒 Files selected for processing (1)
  • docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md

Walkthrough

Adiciona um guard CI que detecta ocorrências de supabase db push, integra-o ao job quality, atualiza o template gerado de migrations e reescreve runbooks de deploy/redeploy e buckets públicos para proibir db push e orientar procedimentos via MCP/Dashboard.

Changes

Guarda de Migração e Documentação de Deployment

Layer / File(s) Summary
Guard script e integração CI
scripts/check-no-db-push.mjs, .github/workflows/ci.yml
Script Node.js que usa git grep com padrão ERE para detectar supabase db push, filtra por allowlist e retorna códigos de saída; integrado como passo inicial no job quality.
Instruções geradas para novas migrações
scripts/gen-migrations-readme.mjs
Template gerado proíbe supabase db push e recomenda MCP apply_migration ou uso do Dashboard SQL Editor.
Guia de deployment com arquitetura e rollback
docs/DEPLOYMENT.md
Substitui por guia Promo_Gifts: proibição de db push, deploy dual Lovable+Vercel, checklist pré-redeploy, variáveis de ambiente, e procedimentos de rollback (PITR, storage metadata, edge redeploy).
Runbooks Fase 2 e resolução da policy de storage
docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md, docs/storage/PUBLIC_BUCKETS.md
Checklist Fase 2 com 3 passos UI (criar policy Storage recibos_authenticated_read, habilitar GitHub security, configurar branch protection); PUBLIC_BUCKETS.md documenta falha MCP/SQL (ERROR 42501), causa raiz e instrução final de criação via Dashboard.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve com precisão as mudanças principais: fechamento de gaps da Redeploy Fase 2 (T3/T22/T23) através de um guard de verificação e um checklist UI, alinhado com os objetivos do PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/check-redeploy-readiness-LrPY8

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

Copy link
Copy Markdown
Owner Author

@coderabbitai review

(PR está como draft de propósito — quero a revisão completa antes de marcar como ready. Foco em: corretude do scripts/check-no-db-push.mjs allowlist, claridade do docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md para um não-dev seguir, e gaps na rewrite do docs/DEPLOYMENT.md.)


Generated by Claude Code

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 12, 2026

@adm01-debug, entendido! Vou realizar a revisão completa do PR agora, com foco nos três pontos que você destacou:

  1. Corretude do scripts/check-no-db-push.mjs — lógica da allowlist e edge cases
  2. Claridade do docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md — legibilidade para um não-dev
  3. Gaps no docs/DEPLOYMENT.md — completude e correção da reescrita

Iniciando a revisão completa agora.

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
.github/workflows/ci.yml (1)

50-57: ⚡ Quick win

Mover o guard de migrations antes do npm ci para fail-fast.

Esse check só usa git grep/Node nativo; rodar antes de instalar dependências economiza minutos quando falhar.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ci.yml around lines 50 - 57, Reorder the CI steps so the
"Migrations sync guard (desync 332 vs 209 — ver docs/DEPLOYMENT.md)" job runs
before "Install dependencies" (npm ci) to fail-fast; locate the step with the
exact name "Migrations sync guard (desync 332 vs 209 — ver docs/DEPLOYMENT.md)"
in .github/workflows/ci.yml and move that block above the "Install dependencies"
block (keep the existing "Seller-scope checker (RLS defesa em profundidade)"
placement if desired), ensuring YAML indentation and ordering remain valid.
docs/DEPLOYMENT.md (1)

27-40: ⚡ Quick win

Adicionar exceção explícita para operações em storage.objects no fluxo de DDL.

A seção “Como aplicar mudanças de schema” está genérica; vale registrar aqui que algumas operações (como policies em storage.objects) podem exigir Dashboard por restrição de owner/role, para evitar nova tentativa via MCP.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/DEPLOYMENT.md` around lines 27 - 40, Add an explicit exception to the
DDL workflow: state that operations touching storage.objects (for example
setting policies on storage.objects) often require owner/role restrictions and
must be applied via the Dashboard (SQL Editor) instead of the
MCP/apply_migration path; reference apply_migration,
supabase_migrations.schema_migrations and MCP as the automated path and
Dashboard/SQL Editor as the manual path, instruct authors to still include a
descriptive supabase/migrations/*.sql file noting the manual Dashboard change
and avoid re-applying it via merge_branch to prod.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/DEPLOYMENT.md`:
- Line 122: The sentence "3. **Storage:** buckets têm versionamento
desabilitado; restaurar do PITR" is misleading because PITR only restores
Postgres (including storage.objects metadata) and does not restore S3/Storage
files; update that bullet to explicitly state PITR does NOT recover object files
and add recommended recovery strategies: enable bucket versioning, maintain
separate S3 backups or lifecycle snapshots, and document a manual recovery path
using storage.objects metadata to reconcile objects with backups; replace the
current line with this clarified statement and a short note about required
separate file-recovery procedures.

In `@docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md`:
- Line 180: Update the checklist row that currently instructs validating with
`git push --force` (the table row containing "Issue `#78` já está fechada") to
remove the `--force` guidance: replace the instruction with a recommendation to
attempt a normal `git push` and note that the expected outcome is a rejection
due to branch protection, or instruct to re-open and validate using a safe push
workflow without force. Ensure the new text clearly omits `--force` and explains
that a normal push rejection confirms protection.

In `@scripts/check-no-db-push.mjs`:
- Around line 35-43: The current execSync call hides real git errors by
appending "|| true"; remove that and instead run execSync("git grep -l
--untracked --no-recurse-submodules -- 'supabase db push'"), then in the catch
for that execSync call inspect the thrown error's status/code (e.status or
e.status === 1 / e.code) — if status === 1 treat it as "no matches" and set raw
= '' (or leave as empty string) and continue, otherwise log the full error (use
e.message and e.status) and process.exit(2); update references around the raw
variable and the try/catch block that contains the execSync invocation.
- Line 37: A busca literal "git grep -l --untracked --no-recurse-submodules --
'supabase db push' || true" é frágil para espaços variáveis; atualize essa
invocação para usar uma regex que aceite qualquer quantidade de whitespace (por
exemplo supabase[[:space:]]+db[[:space:]]+push) e habilite regex estendida no
git grep (use a flag apropriada, ex. -E) para que variações como múltiplos
espaços ou quebras de linha ainda sejam capturadas.
- Around line 30-32: A função isAllowed usa ALLOWLIST.some(p => path === p ||
path.startsWith(p)) permitindo bypass por prefixo para arquivos; altere a lógica
para exigir igualdade exata para entradas de arquivo e usar prefix match somente
para entradas de diretório (por exemplo, tratar uma entrada como diretório se
terminar em '/'). Atualize isAllowed para verificar path === p ||
(p.endsWith('/') && path.startsWith(p)), referenciando a função isAllowed e a
constante ALLOWLIST ao fazer a correção.

---

Nitpick comments:
In @.github/workflows/ci.yml:
- Around line 50-57: Reorder the CI steps so the "Migrations sync guard (desync
332 vs 209 — ver docs/DEPLOYMENT.md)" job runs before "Install dependencies"
(npm ci) to fail-fast; locate the step with the exact name "Migrations sync
guard (desync 332 vs 209 — ver docs/DEPLOYMENT.md)" in .github/workflows/ci.yml
and move that block above the "Install dependencies" block (keep the existing
"Seller-scope checker (RLS defesa em profundidade)" placement if desired),
ensuring YAML indentation and ordering remain valid.

In `@docs/DEPLOYMENT.md`:
- Around line 27-40: Add an explicit exception to the DDL workflow: state that
operations touching storage.objects (for example setting policies on
storage.objects) often require owner/role restrictions and must be applied via
the Dashboard (SQL Editor) instead of the MCP/apply_migration path; reference
apply_migration, supabase_migrations.schema_migrations and MCP as the automated
path and Dashboard/SQL Editor as the manual path, instruct authors to still
include a descriptive supabase/migrations/*.sql file noting the manual Dashboard
change and avoid re-applying it via merge_branch to prod.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e3c56bf4-b5d8-4b70-baf1-5412a9a852c2

📥 Commits

Reviewing files that changed from the base of the PR and between b3f0141 and 31dabde.

📒 Files selected for processing (6)
  • .github/workflows/ci.yml
  • docs/DEPLOYMENT.md
  • docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md
  • docs/storage/PUBLIC_BUCKETS.md
  • scripts/check-no-db-push.mjs
  • scripts/gen-migrations-readme.mjs

Comment thread docs/DEPLOYMENT.md Outdated
Comment thread docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md Outdated
Comment thread scripts/check-no-db-push.mjs
Comment thread scripts/check-no-db-push.mjs
Comment thread scripts/check-no-db-push.mjs Outdated
scripts/check-no-db-push.mjs:
- isAllowed: prefix match SOMENTE para entradas terminadas em '/' (diretório);
  igualdade exata para arquivos — evita bypass via DEPLOYMENT.md.tmp/.bak/etc
- regex ERE com whitespace livre (supabase[[:space:]]+db[[:space:]]+push)
  via `git grep -lE` — captura variações como `supabase   db    push`
- error path explícito: status=1 do git grep = "nenhum match" (continua);
  qualquer outro erro de I/O agora vai a stderr com status+message e
  process.exit(2). Removido `|| true` que mascarava falhas reais

.github/workflows/ci.yml:
- Migrations sync guard movido para ANTES de `npm ci` (fail-fast).
  O guard usa só git+node nativo, não precisa de deps. Falha agora em
  ~10s em vez de ~3min de install

docs/DEPLOYMENT.md:
- Seção Rollback: corrigido item 3 (Storage) — PITR NÃO recupera arquivos
  do Storage (S3-compatible), apenas metadados em storage.objects.
  Adicionada recomendação P2 (versionamento de bucket OU job de cópia
  para R2/S3 externo)
- Seção "Como aplicar DDL": exceção explícita para storage.objects
  documentando que precisa Dashboard (3 tentativas registradas em
  docs/storage/PUBLIC_BUCKETS.md)

docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md:
- Troubleshooting: removida orientação de `git push --force` (perigosa
  para não-dev). Substituída por push direto simples; a rejeição
  "protected branch hook declined" já comprova proteção sem usar force

Validação local: 4 cenários do guard testados (normal, bypass prefixo,
whitespace múltiplo, normal final) — todos OK.

Refs PR #166
Copy link
Copy Markdown
Owner Author

Resposta aos 5 comentários + 2 nitpicks do @coderabbitai

Commit c0f3c93 endereça todos os 7 itens. Resumo:

# Arquivo Severidade Endereçamento
1 scripts/check-no-db-push.mjs (isAllowed) 🟠 Major isAllowed agora trata prefix match apenas para entradas terminadas em / e exige igualdade exata para arquivos. Teste local com docs/DEPLOYMENT.md.tmp confirmado: bloqueia o bypass.
2 scripts/check-no-db-push.mjs (regex) 🟠 Major Mudei busca literal para regex ERE supabase[[:space:]]+db[[:space:]]+push via git grep -lE. Teste local com supabase db push confirmado: detecta.
3 scripts/check-no-db-push.mjs (|| true) 🟠 Major Removido. Try/catch trata e.status === 1 como "no matches" (continua); qualquer outro erro vai a stderr com status + message e process.exit(2).
4 docs/DEPLOYMENT.md (PITR Storage) 🟠 Major Item 3 do Rollback reescrito com aviso explícito ⚠️ que PITR não recupera arquivos do Storage, citação implícita da doc Supabase, e P2 recomendação (versionamento OU job de cópia para R2/S3 externo).
5 docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md 🟠 Major Removido git push --force do troubleshooting. Substituído por orientação de push direto simples — a rejeição "protected branch hook declined" já comprova proteção sem usar --force.
6 .github/workflows/ci.yml (fail-fast) ⚡ Nit Migrations sync guard movido para antes de npm ci. O guard usa só git+node nativo (sem deps), então falha agora em ~10s em vez de ~3min de install.
7 docs/DEPLOYMENT.md (storage.objects exception) ⚡ Nit Adicionada subsection "Exceção: policies em storage.objects" na seção de DDL workflow, documentando o caminho Dashboard com referência cruzada a docs/storage/PUBLIC_BUCKETS.md.

Validação local executada

$ node scripts/check-no-db-push.mjs
✅ check-no-db-push: nenhum uso novo de `supabase db push` detectado.

# Bypass de prefixo (DEPLOYMENT.md.tmp): bloqueia ✅
# Whitespace múltiplo (supabase   db    push): detecta ✅
# Estado normal: passa ✅

@coderabbitai re-revise quando puder, por favor.

🤖 Generated via session_01WKZNWA4MqhKVTqB8Ta4bNW


Generated by Claude Code

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 12, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

Vou ler os arquivos atuais para verificar os 7 itens antes de re-revisar.


🏁 Script executed:

#!/bin/bash
echo "=== scripts/check-no-db-push.mjs ==="
cat scripts/check-no-db-push.mjs

echo ""
echo "=== .github/workflows/ci.yml ==="
cat .github/workflows/ci.yml

echo ""
echo "=== docs/DEPLOYMENT.md ==="
cat docs/DEPLOYMENT.md

echo ""
echo "=== docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md ==="
cat docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md

echo ""
echo "=== docs/storage/PUBLIC_BUCKETS.md ==="
cat docs/storage/PUBLIC_BUCKETS.md

Length of output: 40165


🏁 Script executed:

#!/bin/bash
echo "=== Verificando arquivos referenciados em DEPLOYMENT.md ==="
echo "--- docs/BRANCH_PROTECTION.md ---"
test -f docs/BRANCH_PROTECTION.md && echo "EXISTS" || echo "NOT FOUND"
echo "--- docs/SECURITY_ALERTS.md ---"
test -f docs/SECURITY_ALERTS.md && echo "EXISTS" || echo "NOT FOUND"
echo "--- docs/redeploy/REDEPLOY-T3-MIGRATIONS-AUDIT.md ---"
test -f docs/redeploy/REDEPLOY-T3-MIGRATIONS-AUDIT.md && echo "EXISTS" || echo "NOT FOUND"
echo "--- docs/redeploy/REDEPLOY-FASE2-EXECUTION-LOG.md ---"
test -f docs/redeploy/REDEPLOY-FASE2-EXECUTION-LOG.md && echo "EXISTS" || echo "NOT FOUND"
echo "--- scripts/gen-migrations-readme.mjs (mudança relevante) ---"
cat scripts/gen-migrations-readme.mjs | grep -A5 -B5 "supabase"

Length of output: 2582


@adm01-debug: Re-revisão completa do commit c0f3c93. Todos os 7 itens estão corretamente endereçados. Dois pontos novos abaixo — um nit e um minor no teste opcional.


✅ Verificação dos 7 itens

# Item Status
1 isAllowed — prefix vs exact match p.endsWith('/') ? path.startsWith(p) : path === p
2 Regex ERE [[:space:]]+ git grep -lE com POSIX class
3 Remoção do || true ✅ try/catch com e.status === 1raw = ''; qualquer outro erro → exit(2)
4 Aviso PITR Storage ⚠️ explícito + recomendação P2 para Fase 3
5 Remoção do git push --force ✅ substituído por push simples; rejeição "protected branch hook declined" como evidência
6 Guard antes do npm ci ✅ posicionado antes de Install dependencies
7 Subsection storage.objects em DEPLOYMENT.md ✅ com cross-ref para docs/storage/PUBLIC_BUCKETS.md

Arquivos referenciados no DEPLOYMENT.md (BRANCH_PROTECTION.md, SECURITY_ALERTS.md, REDEPLOY-T3-MIGRATIONS-AUDIT.md, REDEPLOY-FASE2-EXECUTION-LOG.md) — todos existem no repo. ✅


🔎 Novos achados

[Nit] scripts/check-no-db-push.mjs — comentário de cabeçalho impreciso

O cabeçalho diz que a regex captura "quebra de linha" entre supabase, db e push. Isso não é verdade: git grep opera linha a linha, então supabase\n db push distribuído em duas linhas não seria detectado. Em prática é um edge case improvável, mas o comentário induz expectativa errada.

Sugestão:

- * Busca usa regex ERE com whitespace livre para pegar variações como
- * `supabase   db   push` ou quebra de linha.
+ * Busca usa regex ERE com whitespace livre para pegar variações como
+ * `supabase   db   push` (espaços múltiplos, tabs). Quebra de linha entre
+ * tokens não é detectada (git grep é linha-a-linha) — risco negligenciável na prática.

[Minor] docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md — Passo 2, teste opcional com caminho absoluto

echo "AKIAIOSFODNN7EXAMPLE" > /tmp/fake-secret.txt
git add -f /tmp/fake-secret.txt   # ← vai falhar

git add não aceita caminhos fora do workdir. O comando retornaria fatal: '/tmp/fake-secret.txt' is outside repository. O teste é marcado como opcional, mas se o não-dev tentar seguir, vai estranhar o erro.

Sugestão:

echo "AKIAIOSFODNN7EXAMPLE" > fake-secret.txt
git add -f fake-secret.txt && git commit -m "test secret"
git push
# Esperado: erro "GH013: Repository rule violations found"
git reset HEAD~1 && rm fake-secret.txt

Veredicto

Nenhum bloqueador. O script está correto, a documentação está clara e o CI guard está bem posicionado. Os dois pontos acima são nit/minor — podem ser corrigidos antes de marcar como ready ou deixados para um follow-up. A PR está em boa forma para merge.

…eview

- scripts/check-no-db-push.mjs: header comment corrigido para refletir
  que git grep é linha-a-linha; quebra de linha entre tokens não é
  detectada (mantém: espaços múltiplos e tabs sim)
- docs/.../REDEPLOY-FASE2-CHECKLIST-UI.md: teste push protection agora
  usa caminho relativo (`fake-secret.txt`) em vez de `/tmp/...` que
  faria `git add -f` falhar com "outside repository"

Refs PR #166
@adm01-debug adm01-debug marked this pull request as ready for review May 12, 2026 22:07
Copilot AI review requested due to automatic review settings May 12, 2026 22:07
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: daad208aa7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

| Require code scanning results | ⬜ OFF por ora | Pode ligar depois quando CodeQL tiver baseline |

7. Em **Require status checks**, adicione (digite cada um — autocomplete vai sugerir após primeiro run de cada workflow):
- `Verify push to main is from PR merge` (workflow `branch-protection-sentinel.yml`)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove the push-only sentinel from required PR checks

This checklist tells the maintainer to require Verify push to main is from PR merge, but I checked .github/workflows/branch-protection-sentinel.yml and that workflow only runs on push to main (plus workflow_dispatch), not on pull_request. If this is added as a required status check for main, PR heads will never produce that check, so normal PR merges will be stuck waiting for a missing status.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/DEPLOYMENT.md`:
- Around line 58-71: The fenced ASCII diagram block in the docs/DEPLOYMENT.md
file is missing a language identifier causing MD040; add a language tag (for
example ```text) to the opening fence of the diagram block so it becomes ```text
... ``` to satisfy the linter and preserve the diagram formatting.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 77cc5def-3499-49a9-88ce-cb35566d136f

📥 Commits

Reviewing files that changed from the base of the PR and between 31dabde and daad208.

📒 Files selected for processing (4)
  • .github/workflows/ci.yml
  • docs/DEPLOYMENT.md
  • docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md
  • scripts/check-no-db-push.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
  • .github/workflows/ci.yml

Comment thread docs/DEPLOYMENT.md Outdated
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR closes remaining “Fase 2 redeploy” gaps by hardening documentation + CI against unsafe Supabase migration commands, and consolidating the remaining manual (UI-only) security/storage steps into a single checklist.

Changes:

  • Rewrites deployment and migrations guidance to explicitly forbid supabase db push given the documented migrations desync.
  • Adds a CI fail-fast guard (check-no-db-push) to block reintroduction of supabase db push instructions outside an allowlist.
  • Documents the remaining UI-only steps (Supabase storage policy + GitHub security toggles + branch protection) in a consolidated click-by-click checklist.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
scripts/gen-migrations-readme.mjs Removes/overrides the previously generated “db push” guidance in the migrations README generator.
scripts/check-no-db-push.mjs New repo-wide guard that fails CI if supabase db push appears outside an allowlist.
docs/storage/PUBLIC_BUCKETS.md Documents the storage policy gap and the (UI-only) remediation path with recorded attempts.
docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md New consolidated UI checklist for the remaining Fase 2 manual steps.
docs/DEPLOYMENT.md Full rewrite of deployment guide reflecting redeploy realities and safer operational procedures.
.github/workflows/ci.yml Adds a fail-fast CI step to run the check-no-db-push guard before dependency install.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread docs/DEPLOYMENT.md Outdated
- npm 10+
- Conta Supabase com acesso ao projeto `doufsxqlfjyuvxuezpln`

**Não usa Redis.** Cache no-op se a env var não estiver definida (`src/lib/cache.ts`).
Comment on lines +136 to +138
- `CodeQL` (workflow `codeql.yml`)

> **Se algum nome não aparecer no autocomplete**, é porque o workflow ainda não rodou nessa branch — pode digitar manual. Mas idealmente espere que rode 1× para evitar typo.
Comment thread docs/storage/PUBLIC_BUCKETS.md Outdated
Comment on lines 93 to 100
Causa raiz confirmada (validado em 2026-05-12):

```sql
CREATE POLICY "recibos_authenticated_read" ON storage.objects
FOR SELECT TO authenticated USING (bucket_id = 'recibos-entrega');

COMMENT ON POLICY "recibos_authenticated_read" ON storage.objects IS
'Leitura de recibos de entrega restrita a usuários autenticados. T23 redeploy 2026-05.';
-- storage.objects pertence a supabase_storage_admin, postgres NÃO é membro:
SELECT current_user, (SELECT rolname FROM pg_roles WHERE oid = relowner)
FROM pg_class WHERE relname='objects' AND relnamespace='storage'::regnamespace;
-- => postgres | supabase_storage_admin
```
Comment thread scripts/check-no-db-push.mjs Outdated
);
}

// ERE: aceita whitespace variável (espaços múltiplos, tabs, quebras).
- docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md (CRITICAL):
  remove 'Verify push to main is from PR merge' (branch-protection-sentinel.yml)
  da lista de required status checks. O workflow só tem trigger 'push:
  branches:[main]', não 'pull_request:'. Adicioná-lo como required check
  travaria TODAS as PRs esperando um check que nunca aparece no head da PR.
  Adicionado warning explicito explicando o motivo e o papel real do sentinel
  (auditoria pós-merge, não gate de PR). Achado por @chatgpt-codex-connector.

- docs/DEPLOYMENT.md: adicionada linguagem 'text' ao bloco cercado do diagrama
  de arquitetura de deploy (MD040 / fenced-code-language). Achado por
  @coderabbitai re-review.

Refs PR #166
- docs/DEPLOYMENT.md (line 87): referência a src/lib/cache.ts removida
  porque o arquivo não existe; substituída por menção ao TanStack Query
  como camada real de cache de UI

- docs/redeploy/REDEPLOY-FASE2-CHECKLIST-UI.md: lista de required checks
  agora especifica 'Analyze (javascript-typescript)' (nome do job, com
  matrix expandida) em vez de 'CodeQL' (nome do workflow). Warning
  explicito explicando a distinção

- docs/storage/PUBLIC_BUCKETS.md: query de validação expandida para
  incluir pg_has_role(...,'MEMBER') verifying that postgres também NÃO
  é membro de supabase_storage_admin (só confirmar owner não sustenta a
  causa raiz)

- scripts/check-no-db-push.mjs: comentario inline removeu palavra
  'quebras' para não conflitar com header (que já explica que
  git grep é linha-a-linha)

Refs PR #166
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0f0939cec2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +87 to +89
echo "AKIAIOSFODNN7EXAMPLE" > fake-secret.txt
git add -f fake-secret.txt && git commit -m "test secret"
git push
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid pushing the dummy secret test to main

When this optional validation is run before branch protection is configured, the push can succeed instead of producing GH013: GitHub documents that pattern pairs such as AWS keys require both the ID and secret in the same file, but this writes only the access-key ID. In that case the maintainer has just pushed fake-secret.txt to main, and the following git reset HEAD~1 only cleans the local branch, not the remote; use a disposable branch/repo or include a safe provider-documented test token that is guaranteed to be blocked.

Useful? React with 👍 / 👎.

Codex apontou que o teste opcional de Push Protection antes podia
falhar silenciosamente: 1) AWS access key ID isolado nem sempre é
detectado (GitHub exige par ID+secret no mesmo arquivo para o pattern
AWS), 2) se nao detectar, o arquivo de teste vai para main no remoto,
3) git reset HEAD~1 so limpa local.

Nova versao:
- Cria branch descartavel test/secret-scan-validation a partir de main
- Inclui par AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY no mesmo arquivo
  (padrao genuinamente detectado pelo GitHub)
- Limpeza limpa branch local E remota (defense in depth se push passar)

Refs PR #166
adm01-debug pushed a commit that referenced this pull request May 13, 2026
…check-no-db-push

Esses arquivos foram adicionados ao main após PR #166 (que criou o guard)
e citam `supabase db push` exclusivamente para proibi-lo — contexto
idêntico aos demais docs na allowlist. Sem os dois na allowlist, o guard
bloqueava o CI desta PR sem motivo real.

https://claude.ai/code/session_01WKZNWA4MqhKVTqB8Ta4bNW
@adm01-debug adm01-debug merged commit 8e36fb8 into main May 14, 2026
19 of 20 checks passed
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.

3 participants