feat(observability): GlitchTip init com captureConsole + replay on-error (Onda 5)#194
Conversation
…on-error (Onda 5)
Fechamento do ciclo da Onda 4. O console.error/warn que agora sobrevive
no bundle de prod (Onda 4) é capturado e enviado pro GlitchTip self-hosted.
Mudanças em src/lib/sentry.ts:
+ captureConsoleIntegration({ levels: ['error'] })
+ maskAllInputs: true (LGPD)
+ replaysOnErrorSampleRate: 1.0 em prod (era 0.1)
+ release: VITE_VERCEL_GIT_COMMIT_SHA (associar erro ao deploy)
+ environment: VITE_SENTRY_ENVIRONMENT || MODE
+ ignoreErrors: ResizeObserver/network/extensions noise
Novo arquivo:
+ .env.example documentando as 7 vars VITE_* do projeto
GlitchTip aceita SDK Sentry sem modificação. DSN do projeto
"PromoGifts Frontend" (id=4) em erros.atomicabr.com.br.
Validação:
- captureConsoleIntegration confirmada em @sentry/core (v8.55.2)
- Sintaxe TS validada via esbuild standalone
- tsc completo roda no CI
Pré-requisito pós-merge: adicionar VITE_SENTRY_DSN no Vercel
(detalhes em docs/hardening/ONDA-5-GLITCHTIP-INIT.md).
Risco: baixo. 1 arquivo modificado (sentry.ts), 2 docs novos.
Bloqueador: B-1.2 da auditoria de 10/mai.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
WalkthroughImplementação de observabilidade de erros com GlitchTip (Sentry-compatível) em produção: documentação arquitetural da decisão, template ChangesGlitchTip Error Observability
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/hardening/ONDA-5-GLITCHTIP-INIT.md`:
- Around line 97-100: The runbook contains a real Sentry DSN under the
VITE_SENTRY_DSN entry which must be removed; replace the hardcoded DSN value in
the table (the `VITE_SENTRY_DSN` row) with a placeholder like
`<SENTRY_DSN_PLACEHOLDER>` or `REDACTED` and add a note to source the real DSN
only from environment in Vercel/GlitchTip, ensuring the repository no longer
contains the actual DSN.
In `@src/lib/sentry.ts`:
- Around line 59-61: The global console.error capture via
mod.captureConsoleIntegration({ levels: ['error'] }) can leak sensitive data;
update the Sentry beforeSend handler to defensively sanitize event.message, each
event.exception.values[].value, and event.extra by redacting patterns for
emails, CPF/CNPJ, tokens (bearer/hex), and common password keys before sending;
locate the beforeSend function in this file and add a sanitizer utility (used
from within beforeSend) that walks the event payload and replaces matches for
email regex, CPF/CNPJ regex, token formats, and keys like
password/passphrase/secret with a stable redaction string, then keep the
existing header cleanup for authorization/cookie and run a short rollout.
🪄 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: 6a8a9c2d-3116-4a8a-95d5-d56d2d6087aa
📒 Files selected for processing (3)
.env.exampledocs/hardening/ONDA-5-GLITCHTIP-INIT.mdsrc/lib/sentry.ts
| | Variável | Valor | | ||
| |---|---| | ||
| | `VITE_SENTRY_DSN` | `https://66323199858e42958e4dfcde3cd77b7e@erros.atomicabr.com.br/4` | | ||
|
|
There was a problem hiding this comment.
Evite DSN real no runbook versionado.
Mesmo sendo público por design, deixar o DSN real no repositório facilita abuso de ingestão (spam/ruído) e poluição de observabilidade. Troque por placeholder e mantenha o valor real só no Vercel/GlitchTip.
Patch sugerido
| Variável | Valor |
|---|---|
-| `VITE_SENTRY_DSN` | `https://66323199858e42958e4dfcde3cd77b7e@erros.atomicabr.com.br/4` |
+| `VITE_SENTRY_DSN` | `https://<public-key>@erros.atomicabr.com.br/<project-id>` |📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| | Variável | Valor | | |
| |---|---| | |
| | `VITE_SENTRY_DSN` | `https://66323199858e42958e4dfcde3cd77b7e@erros.atomicabr.com.br/4` | | |
| | Variável | Valor | | |
| |---|---| | |
| | `VITE_SENTRY_DSN` | `https://<public-key>@erros.atomicabr.com.br/<project-id>` | |
🤖 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/hardening/ONDA-5-GLITCHTIP-INIT.md` around lines 97 - 100, The runbook
contains a real Sentry DSN under the VITE_SENTRY_DSN entry which must be
removed; replace the hardcoded DSN value in the table (the `VITE_SENTRY_DSN`
row) with a placeholder like `<SENTRY_DSN_PLACEHOLDER>` or `REDACTED` and add a
note to source the real DSN only from environment in Vercel/GlitchTip, ensuring
the repository no longer contains the actual DSN.
| // Onda 5: captura console.error automaticamente | ||
| // (logger.error → console.error → GlitchTip) | ||
| mod.captureConsoleIntegration({ levels: ['error'] }), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verificação read-only: mapear logs potencialmente sensíveis que podem cair em console.error/logger.error
# Esperado: lista de ocorrências para auditoria de LGPD antes de habilitar captura global.
rg -n -C2 --type=ts --type=tsx --type=js --type=jsx \
'\b(console\.error|logger\.error)\s*\('
echo "---- possíveis termos sensíveis próximos de logs ----"
rg -n -C2 --type=ts --type=tsx --type=js --type=jsx \
'(token|authorization|bearer|cookie|senha|password|cpf|cnpj|email|phone|telefone|session|jwt)'Repository: adm01-debug/Promo_Gifts
Length of output: 195
🏁 Script executed:
cd src/lib && wc -l sentry.ts && cat -n sentry.tsRepository: adm01-debug/Promo_Gifts
Length of output: 6390
🏁 Script executed:
#!/bin/bash
# Busca por console.error/logger.error sem type=tsx (que causou erro)
rg -n -C2 'console\.(error|log|warn)|logger\.(error|log|warn)' --glob='*.ts' --glob='*.js' --glob='*.jsx'Repository: adm01-debug/Promo_Gifts
Length of output: 50380
🏁 Script executed:
#!/bin/bash
# Busca por termos sensíveis sem type=tsx
rg -in -C2 '(token|authorization|bearer|cookie|senha|password|cpf|cnpj|email|phone|session|jwt|api_key)' --glob='*.ts' --glob='*.js' --glob='*.jsx'Repository: adm01-debug/Promo_Gifts
Length of output: 50380
Captura global de console.error vaza dados sensíveis para GlitchTip.
Com captureConsoleIntegration({ levels: ['error'] }) habilitado, qualquer console.error contendo token, e-mail, CNPJ, senha ou payload de API se torna evento no Sentry/GlitchTip. O beforeSend atual limpa apenas headers (authorization, cookie), deixando event.message, event.exception.values[].value e event.extra sem sanitização. Aplicação registra dados sensíveis em múltiplos console.error (sellers, APIs, etc.).
Adicionar sanitização defensiva no beforeSend para limpar padrões de dados sensíveis (email, CPF/CNPJ, tokens, senhas) em event.message, event.exception.values[*].value e event.extra antes do rollout completo. Auditar pontos de log de erro na aplicação que podem expor dados de negócio.
🤖 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 `@src/lib/sentry.ts` around lines 59 - 61, The global console.error capture via
mod.captureConsoleIntegration({ levels: ['error'] }) can leak sensitive data;
update the Sentry beforeSend handler to defensively sanitize event.message, each
event.exception.values[].value, and event.extra by redacting patterns for
emails, CPF/CNPJ, tokens (bearer/hex), and common password keys before sending;
locate the beforeSend function in this file and add a sanitizer utility (used
from within beforeSend) that walks the event payload and replaces matches for
email regex, CPF/CNPJ regex, token formats, and keys like
password/passphrase/secret with a stable redaction string, then keep the
existing header cleanup for authorization/cookie and run a short rollout.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: afa78fcb53
ℹ️ 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".
| replaysSessionSampleRate: 0, | ||
| replaysOnErrorSampleRate: import.meta.env.PROD ? 0.1 : 0, | ||
| // Onda 5: aprovado por Joaquim — replay 100% quando dá erro | ||
| replaysOnErrorSampleRate: import.meta.env.PROD ? 1.0 : 0, |
There was a problem hiding this comment.
Disable Replay sampling for GlitchTip
Because this PR documents and configures a GlitchTip DSN, replaysOnErrorSampleRate: 1.0 adds work that the target backend cannot use: GlitchTip's own JavaScript setup disables session tracking because sessions are unsupported, and the GlitchTip project notes Replay is a Sentry-only feature. In production, every captured error will now start Replay buffering/upload behavior without producing the promised replay in GlitchTip, adding client CPU/bandwidth and storage attempts for no debugging benefit. Gate Replay on a Sentry backend or remove the Replay integration/options for GlitchTip.
Useful? React with 👍 / 👎.
| 'ResizeObserver loop completed with undelivered notifications', | ||
| 'Non-Error promise rejection captured', | ||
| // Network noise (oscilação de conexão dos vendedores) | ||
| 'Failed to fetch', |
There was a problem hiding this comment.
Don't suppress all fetch failures
This blanket ignoreErrors string will drop any event whose message partially contains Failed to fetch; Sentry's JavaScript option treats string entries as partial-match filters. In the existing global error path (installGlobalErrorHandlers → reportError → captureException), real backend/CORS outages surface in browsers as TypeError: Failed to fetch, so those production incidents will now be hidden from GlitchTip instead of just reducing offline noise. Filter network noise with context such as navigator.onLine, request URL, or known extension frames rather than the generic browser error text.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
1 issue found across 3 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/lib/sentry.ts">
<violation number="1" location="src/lib/sentry.ts:61">
P2: `captureConsoleIntegration` on `error` duplicates events already forwarded by `createClientLogger.error()`, which can inflate issue volume and alert/quota noise.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.
| }), | ||
| // Onda 5: captura console.error automaticamente | ||
| // (logger.error → console.error → GlitchTip) | ||
| mod.captureConsoleIntegration({ levels: ['error'] }), |
There was a problem hiding this comment.
P2: captureConsoleIntegration on error duplicates events already forwarded by createClientLogger.error(), which can inflate issue volume and alert/quota noise.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/lib/sentry.ts, line 61:
<comment>`captureConsoleIntegration` on `error` duplicates events already forwarded by `createClientLogger.error()`, which can inflate issue volume and alert/quota noise.</comment>
<file context>
@@ -41,13 +41,38 @@ async function loadSentry(): Promise<SentryModule | null> {
+ }),
+ // Onda 5: captura console.error automaticamente
+ // (logger.error → console.error → GlitchTip)
+ mod.captureConsoleIntegration({ levels: ['error'] }),
+ ],
+ // Onda 5: ignorar ruído conhecido (não-bug nosso)
</file context>
There was a problem hiding this comment.
Pull request overview
This PR hardens frontend observability by extending the lazy-loaded Sentry SDK initialization for GlitchTip, adding replay/privacy configuration, and documenting required frontend environment variables and deployment steps.
Changes:
- Adds GlitchTip/Sentry release, environment, replay, console capture, and ignore-error configuration.
- Introduces
.env.examplefor frontendVITE_*variables. - Adds an Onda 5 hardening runbook for GlitchTip setup and rollback.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 7 comments.
| File | Description |
|---|---|
src/lib/sentry.ts |
Updates Sentry initialization with GlitchTip-oriented observability settings. |
.env.example |
Documents frontend environment variables for Supabase, Sentry/GlitchTip, Vercel, and flags. |
docs/hardening/ONDA-5-GLITCHTIP-INIT.md |
Adds operational runbook and rationale for the Onda 5 observability changes. |
Comments suppressed due to low confidence (1)
src/lib/sentry.ts:61
- This console capture will duplicate events for code paths using
createClientLogger:structuredLoggeralready callscaptureExceptionforerrorlogs and also writes toconsole.error, so after this integration loads the same failure is sent once bycaptureExceptionand once by the console wrapper. That will inflate GlitchTip issue counts and can double-trigger alerts unless one of the two forwarding paths is removed or deduplicated.
mod.captureConsoleIntegration({ levels: ['error'] }),
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // Release tag = commit SHA do Vercel — permite associar erro ao deploy | ||
| release: (import.meta.env.VITE_VERCEL_GIT_COMMIT_SHA as string | undefined) || undefined, |
| // Network noise (oscilação de conexão dos vendedores) | ||
| 'Failed to fetch', | ||
| 'NetworkError when attempting to fetch resource', | ||
| 'Load failed', |
| /extension:\/\//, | ||
| /moz-extension:\/\//, |
| # ---------------------------------------------------------------------------- | ||
| # FEATURE FLAGS (opcionais) | ||
| # ---------------------------------------------------------------------------- | ||
|
|
| # VERCEL (injetadas automaticamente pelo Vercel — não preencher manualmente) | ||
| # ---------------------------------------------------------------------------- | ||
| # Documentação: https://vercel.com/docs/projects/environment-variables/system-environment-variables | ||
|
|
||
| # SHA do commit do deploy — usado como release tag no GlitchTip | ||
| # Vercel injeta automaticamente. Em dev local, fica vazio. |
| # Valores: 'true' | 'false' (default: 'false') | ||
| # VITE_SHOW_DEV_INFRA_MESSAGES=false |
| `logger.error()` já chama `console.error()` internamente (logger.ts:70). Com a Onda 4 mantendo `console.error` no bundle prod + `captureConsoleIntegration({ levels: ['error'] })` da Onda 5, a captura é **automática e transparente**. Não há ganho em adicionar `Sentry.captureException()` explícito no logger. | ||
|
|
…I e testes - Resolve conflitos em baselines (ESLint 853, TSC 1262) e test files - Corrige non-null assertion em sentry.ts (lint-staged pre-commit) - Mantém: SidebarNavGroup tests fixed, CI workflow fixes, baseline melhorado https://claude.ai/code/session_01MuNDxFSRRaJLsvkBdyQ2dK
Onda 5 do hardening pré-prod. Fechamento do ciclo da Onda 4.
A Onda 4 (PR #191) preservou console.error/warn no bundle de prod.
Esta Onda os envia pro GlitchTip self-hosted (erros.atomicabr.com.br).
Mudanças em src/lib/sentry.ts (+25/-3 linhas):
→ logger.error → console.error → GlitchTip automaticamente
Novos arquivos:
GlitchTip aceita SDK Sentry sem modificação. Projeto
"PromoGifts Frontend" (id=4) em erros.atomicabr.com.br já criado.
Pré-requisito pós-merge: adicionar VITE_SENTRY_DSN no Vercel.
Instruções detalhadas em docs/hardening/ONDA-5-GLITCHTIP-INIT.md.
Risco: baixo. 1 arquivo lógico modificado, 2 docs novos.
Bloqueador: B-1.2 da auditoria de 10/mai.
Summary by cubic
Initialize GlitchTip (Sentry-compatible) to capture
console.errorfrom production and send errors to our self-hosted endpoint. Enables 100% on-error replays with safe masking, release tagging, and noisy-error filtering; adds.env.exampleand a rollout runbook.New Features
captureConsoleIntegration({ levels: ['error'] })in@sentry/react.1.0in prod withmaskAllText,maskAllInputs, andblockAllMedia.VITE_VERCEL_GIT_COMMIT_SHA; setenvironmentfromVITE_SENTRY_ENVIRONMENTorMODE..env.exampleanddocs/hardening/ONDA-5-GLITCHTIP-INIT.md.Migration
VITE_SENTRY_DSNin Vercel.VITE_SENTRY_ENVIRONMENT=production.Written for commit afa78fc. Summary will update on new commits.
Summary by CodeRabbit
Release Notes
New Features
Chores