Auditoria técnica — correções de alto impacto (Track A: app · Track B: prod DB)#517
Conversation
…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
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
Updates to Preview Branch (claude/wizardly-mayer-0Wy6A) ↗︎
Tasks are run on every commit but only new migration files are pushed.
❌ Branch Error • Fri, 29 May 2026 20:46:35 UTC View logs for this Workflow Run ↗︎. |
…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
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Resumo
Rodada de auditoria técnica com correções cirúrgicas de alto impacto, zero regressão de baseline. Dois tracks:
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 objetovaluedo Provider era recriado a cada render esignIn/signOutnã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 deuseAuth()(guards de rota, layout, dezenas de componentes). Fix:useCallbackemsignIn/signOut+useMemonovaluecom deps explícitas.2.
AuthContext— duplo refresh de sessão. O efeito de auto-refresh disparava um refresh imediato (timeToExpiry < 10min) e agendava umsetTimeoutcom 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 (nullquando delay ≤ 0). Watchdog de 12s intacto.3.
useProfileRoles— unhandled rejection. Update delast_login_atem background usava.then()sem.catch→ rejeição não tratada se a escrita falhasse (rede/RLS). Fix:.catchsilencioso (best-effort, não bloqueiaisLoading).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 resetreproduzir prod):perf_drop_duplicate_indexesduplicate_indexperf_add_missing_fk_indexesunindexed_foreign_keyssecurity_revoke_anon_execute_internal_secdef_fnsEXECUTEde anon/PUBLIC em 5 funçõesSECURITY DEFINERinternas sem chamador anônimoEvidência (verificado em prod, antes → depois)
duplicate_index: 5 → 0 ✅idx_personalization_simulations_product_id,idx_user_allowed_ips_created_by) ✅EXECUTEpara anon; RPCs pré-auth preservados (check_login_rate_limit,enforce_password_reset_rate_limit,get_quote_token_by_value,submit_quote_response) ✅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 doAuthContext) ✅npm run build: limpo (59.6s) ✅Achados de auditoria (fora de escopo desta rodada)
external-db-bridge-keepalive(~15 falhas/h) econnections-auto-test(~4/h) falham comnull value in column "url" … http_request_queuee{"apikey": null}— a chamadapg_netrecebe 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.unused_index(INFO; remover é arriscado, exige análise de uso real), 25auth_rls_initplan+ 7multiple_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_executableremanescentes (4 anon + 16 authenticated), 2public_bucket_allows_listing.STATUS.md).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
signIn/signOutcomuseCallbackevaluecomuseMemo; reduz re-renders deuseAuth().useProfileRoles: adiciona.catchno update delast_login_at(best-effort).DevRoute: docstring corrige redirect para/auth.Migration
anon/PUBLICem 5 funçõesSECURITY DEFINER; RPCs pré-auth preservadas.to_regprocedure, tornando a migration idempotente e segura para reset/preview.Written for commit e83d11c. Summary will update on new commits.