Skip to content

Auditoria técnica — correções de alto impacto (Track A: app · Track B: prod DB)#517

Merged
adm01-debug merged 4 commits into
mainfrom
claude/wizardly-mayer-0Wy6A
May 29, 2026
Merged

Auditoria técnica — correções de alto impacto (Track A: app · Track B: prod DB)#517
adm01-debug merged 4 commits into
mainfrom
claude/wizardly-mayer-0Wy6A

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Resumo

Rodada de auditoria técnica com correções cirúrgicas de alto impacto, zero regressão de baseline. Dois tracks:

  • Track A — correções no código do app (re-renders de auth, refresh de sessão, higiene de erro async, docstring).
  • Track B — remediação conservadora no Supabase de produção (doufsxqlfjyuvxuezpln), guiada por advisors, migrations aditivas/idempotentes, já aplicadas e verificadas em prod; aqui sincronizadas ao repo.

Track A — código do app (61bdf43)

1. AuthContext — re-render global em cascata. O objeto value do Provider era recriado a cada render e signIn/signOut não eram memoizados → qualquer mudança de estado de auth (sessão, perfil, roles, timers, toasts) trocava a identidade do contexto e re-renderizava todos os consumidores de useAuth() (guards de rota, layout, dezenas de componentes). Fix: useCallback em signIn/signOut + useMemo no value com deps explícitas.

2. AuthContext — duplo refresh de sessão. O efeito de auto-refresh disparava um refresh imediato (timeToExpiry < 10min) e agendava um setTimeout com delay potencialmente negativo (dispara em ~0ms) → duplo refresh redundante em sessões perto de expirar. Fix: caminho único — refresh uma vez se já dentro do buffer de 5 min, senão agenda um único timer (null quando delay ≤ 0). Watchdog de 12s intacto.

3. useProfileRoles — unhandled rejection. Update de last_login_at em background usava .then() sem .catch → rejeição não tratada se a escrita falhasse (rede/RLS). Fix: .catch silencioso (best-effort, não bloqueia isLoading).

4. DevRoute — docstring. Comentário dizia redirect para /login; o código redireciona para /auth. Alinhado.


Track B — Supabase prod (a646f58)

Migrations conservadoras, aditivas/idempotentes, guiadas por advisors, aplicadas a prod via MCP em 2026-05-29 e espelhadas no repo (para db reset reproduzir prod):

Migration O quê Advisor
perf_drop_duplicate_indexes Remove 5 índices duplicados (byte-idênticos a irmãos retidos; zero impacto de leitura) performance · duplicate_index
perf_add_missing_fk_indexes Adiciona índices de cobertura para 2 FKs sem índice performance · unindexed_foreign_keys
security_revoke_anon_execute_internal_secdef_fns Revoga EXECUTE de anon/PUBLIC em 5 funções SECURITY DEFINER internas sem chamador anônimo security

Evidência (verificado em prod, antes → depois)

  • performance advisor duplicate_index: 5 → 0
  • FK indexes: ambos presentes (idx_personalization_simulations_product_id, idx_user_allowed_ips_created_by) ✅
  • security advisors: 0 ERROR (757 WARN, todos de grande superfície / decisão de produto — ver "Achados") ✅
  • Revoke seguro: as 5 funções não têm mais EXECUTE para anon; RPCs pré-auth preservados (check_login_rate_limit, enforce_password_reset_rate_limit, get_quote_token_by_value, submit_quote_response) ✅
  • Smoke tests fn_run_smoke_tests(): 13/14 PASS — a única falha (cron_health_1h) é pré-existente e não relacionada a estas mudanças (ver Achados fix(ci): adicionar gpt-engineer-app[bot] à whitelist do Branch Protection Sentinel #1).

Gates (verificação local, no estado commitado)

  • npm run typecheck (baseline gate): 123/123, sem regressão
  • npm run lint:baseline: sem regressão (89 erros vs baseline 107 — drift positivo de 32, da memoização do AuthContext) ✅
  • npm run build: limpo (59.6s) ✅

Achados de auditoria (fora de escopo desta rodada)

  1. 🔴 Cron falhando em prod (operacional). external-db-bridge-keepalive (~15 falhas/h) e connections-auto-test (~4/h) falham com null value in column "url" … http_request_queue e {"apikey": null} — a chamada pg_net recebe url/apikey NULL (secret/config ausente ou vazio). Precisa do valor real do secret/URL da bridge → decisão do dono; não corrigido às cegas.
  2. Advisors WARN de grande superfície (não-ERROR): 421 unused_index (INFO; remover é arriscado, exige análise de uso real), 25 auth_rls_initplan + 7 multiple_permissive_policies (otimização de RLS em massa), pg_graphql_*_table_exposed (321+414, exposição via GraphQL — decisão de produto), *_security_definer_function_executable remanescentes (4 anon + 16 authenticated), 2 public_bucket_allows_listing.
  3. Dívida técnica baselineada: burndown dos erros TS/ESLint baselineados e reativação dos testes P0/segurança skipados seguem como roadmap multi-semana (já documentado em STATUS.md).
  4. Migration pendente não aplicada: 20260525232003_fix_339_* continua não aplicada a prod (aguarda revisão do dono), conforme guardrail.

https://claude.ai/code/session_01Tz1z1N7dKRztHG4XH9mH3B


Generated by Claude Code


Summary by cubic

Auditoria técnica no app e no Supabase para melhorar performance e segurança. Acaba com re-renders globais de auth e o refresh duplo de sessão; no banco, remove índices duplicados, cobre FKs e deixa REVOKEs seguros para reset/preview.

  • Bug Fixes

    • AuthContext: signIn/signOut com useCallback e value com useMemo; reduz re-renders de useAuth().
    • Auto-refresh de sessão: caminho único com buffer de 5min; agenda 1 timer (ou nenhum) e evita refresh duplo.
    • useProfileRoles: adiciona .catch no update de last_login_at (best-effort).
    • DevRoute: docstring corrige redirect para /auth.
  • Migration

    • Performance: drop de 5 índices duplicados; cria 2 índices para FKs.
    • Segurança: REVOKE EXECUTE de anon/PUBLIC em 5 funções SECURITY DEFINER; RPCs pré-auth preservadas.
    • Robustez: REVOKEs guardados com to_regprocedure, tornando a migration idempotente e segura para reset/preview.

Written for commit e83d11c. Summary will update on new commits.

Review in cubic

claude added 2 commits May 29, 2026 20:21
…rden last_login_at write

- AuthContext: wrap signIn/signOut in useCallback and the context `value` in
  useMemo with explicit deps. The value object was rebuilt on every render,
  changing context identity and re-rendering every useAuth() consumer (route
  guards, layout, dozens of components) on any auth state change (session,
  profile, roles, timers, toasts).
- AuthContext: collapse session auto-refresh to a single path. The old code
  fired an immediate refresh (timeToExpiry < 10min) AND scheduled a setTimeout
  whose delay could be negative (fires at ~0ms) -> redundant double refresh on
  near-expiry sessions. Now: refresh once if already inside the 5min buffer,
  otherwise schedule a single timer (null when delay <= 0). Watchdog untouched.
- useProfileRoles: add .catch to the background last_login_at write so a failed
  update (network/RLS) cannot surface as an unhandled promise rejection.
- DevRoute: align docstring with actual behavior (redirects to /auth, not /login).

https://claude.ai/code/session_01Tz1z1N7dKRztHG4XH9mH3B
Conservative, additive/idempotent migrations applied to prod (project
doufsxqlfjyuvxuezpln) on 2026-05-29 via MCP, now mirrored into repo history so
a fresh `db reset` reproduces prod. All guided by Supabase advisors and
verified before/after: performance advisor duplicate_index count 5 -> 0,
security advisors 0 ERROR, smoke tests 13/14 (the lone failure is a pre-existing
cron/config issue — NULL url/apikey in pg_net keepalive — unrelated to these
changes).

- perf_drop_duplicate_indexes: drop 5 redundant duplicate indexes, each
  byte-identical to a retained sibling (verified via pg_get_indexdef); zero
  read-path impact, less write amplification.
- perf_add_missing_fk_indexes: add covering indexes for 2 unindexed foreign
  keys (personalization_simulations.product_id, user_allowed_ips.created_by).
- security_revoke_anon_execute_internal_secdef_fns: revoke anon/PUBLIC EXECUTE
  on 5 internal SECURITY DEFINER functions that have no anonymous caller;
  authenticated/service_role grants and all pre-auth RPCs left intact.

https://claude.ai/code/session_01Tz1z1N7dKRztHG4XH9mH3B
@vercel
Copy link
Copy Markdown

vercel Bot commented May 29, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Error Error May 29, 2026 8:46pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 29, 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 28 minutes and 23 seconds. 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: 429bc468-7c9f-4f97-a3cf-5515ae0c8093

📥 Commits

Reviewing files that changed from the base of the PR and between 01cf56e and e83d11c.

📒 Files selected for processing (6)
  • src/components/layout/DevRoute.tsx
  • src/contexts/AuthContext.tsx
  • src/hooks/auth/useProfileRoles.ts
  • supabase/migrations/20260529150000_perf_drop_duplicate_indexes.sql
  • supabase/migrations/20260529150100_perf_add_missing_fk_indexes.sql
  • supabase/migrations/20260529150200_security_revoke_anon_execute_internal_secdef_fns.sql
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/wizardly-mayer-0Wy6A

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

@supabase
Copy link
Copy Markdown

supabase Bot commented May 29, 2026

Updates to Preview Branch (claude/wizardly-mayer-0Wy6A) ↗︎

Deployments Status Updated
Database Fri, 29 May 2026 20:46:32 UTC
Services Fri, 29 May 2026 20:46:32 UTC
APIs Fri, 29 May 2026 20:46:32 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Fri, 29 May 2026 20:46:32 UTC
Migrations Fri, 29 May 2026 20:46:34 UTC
Seeding ⏸️ Fri, 29 May 2026 20:46:25 UTC
Edge Functions ⏸️ Fri, 29 May 2026 20:46:25 UTC

❌ Branch Error • Fri, 29 May 2026 20:46:35 UTC

ERROR: cannot change return type of existing function (SQLSTATE 42P13)
At statement: 10
CREATE OR REPLACE FUNCTION public.fn_run_and_persist_smoke_tests()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
  v_ran_at timestamptz := now();
BEGIN
  IF NOT public.is_admin_or_above((SELECT auth.uid())) THEN
    RAISE EXCEPTION 'not authorized';
  END IF;

  INSERT INTO public.smoke_test_runs (
    ran_at,
    test_name,
    test_category,
    result,
    details,
    duration_ms
  )
  SELECT
    v_ran_at,
    test_name,
    test_category,
    result,
    details,
    duration_ms
  FROM public.fn_run_smoke_tests();
END;
$function$

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

…view

The Supabase preview branch and a local `db reset` build the schema from repo
migration history. `send_digest_notification(uuid, uuid[], integer)` exists in
prod but is created out-of-band (no repo migration), so a bare
`REVOKE EXECUTE ON FUNCTION ...` for it would abort the migration with
"function does not exist" on any fresh database.

Wrap all 5 revokes in a single DO block guarded by `to_regprocedure(...)`
(returns NULL instead of raising when the function is absent), preserving the
exact per-function grantees applied to prod. Validated against prod as an
idempotent no-op. No change to prod behavior — only makes the repo file
reproducible on a clean DB.

https://claude.ai/code/session_01Tz1z1N7dKRztHG4XH9mH3B
…-0Wy6A

# Conflicts:
#	src/hooks/auth/useProfileRoles.ts
@adm01-debug adm01-debug marked this pull request as ready for review May 29, 2026 20:58
Copilot AI review requested due to automatic review settings May 29, 2026 20:58
@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.

@adm01-debug adm01-debug merged commit 73c3ffb into main May 29, 2026
42 of 51 checks passed
@adm01-debug adm01-debug deleted the claude/wizardly-mayer-0Wy6A branch May 29, 2026 20:58
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.

2 participants