Skip to content

feat(widget): wire sentry into the error-reporting seam - #123

Merged
Ardnived merged 6 commits into
mainfrom
feat/sentry-reporting
Aug 8, 2026
Merged

Ardnived merged 6 commits into
mainfrom
feat/sentry-reporting

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • The widget can now tell us when it breaks on somebody else's page. reportInternalError was designed as the single seam a real error reporter would wire into, and had none. Sentry now hangs off that one function — @sentry/browser is imported from exactly one place in the repo.
  • And it reports the failures people actually see. The seam had five callers, but every one was a failure the code had already caught and worked around by hand; not one was an ordinary boundary trip. ResetErrorBoundary now reports, which covers all six boundaries at once and means a boundary added later can't forget.
  • Zero cost when it's off. No VITE_SENTRY_DSN → exactly today's console-only behaviour and nothing fetched. Hosts can decline it per-embed with error-reporting="false".

Review record — both passes DID run

An earlier revision of this description said neither review completed. That was wrong: both subagents finished late, after the run had moved on. Both have now been triaged and their findings fixed. Correcting the record because the earlier version told a reviewer not to expect one.

They found three things I'd got wrong, two of them security-relevant. All are fixed in 1e82ff1, a04a405 and c05998e.

Security review — two real leaks

1. The host's full URL could escape inside an exception message. claimFragment reported the raw DOMException from a refused replaceState, and engines build that message out of the URL they refused — query string and fragment included. That walks straight past hostPageUrl(), whose entire job is to strip exactly those before anything leaves the page. Classified unknown, so it was reported. Now claimFragment reports a sentence we built, keeping only the exception's name (SecurityError is the diagnostic half and carries no URL), and maxValueLength caps every value at the same 500 chars the human report uses.

2. A host page can share our Sentry global scope. getCombinedScopeData always merges getGlobalScope(), and the global carrier is keyed by SDK version string — so a site running this same @sentry/browser version shares it with us. Their setTag/setExtra/setContext would ride out on our events, and ours on theirs. Same family as the cross-tracker contamination #95 found with Fathom, one layer down. beforeSend is now an allowlist that rebuilds the event from what we know we put on it, rather than a blocklist trimming what we happened to think of. It also clears hint.attachments, which are appended after the hook so nothing else can remove them. Dropping extra closes a third hole on its own: a thrown plain object is serialized into it wholesale.

Also from the security pass: pass our own fetch to makeFetchTransport, because the default implementation injects a hidden iframe into the host's <head> when anything has wrapped window.fetch (every consent and analytics script does), and re-does it per failed send.

Code review — the CSP story was false in code and docs

3. A blocked ingest origin retried forever. My comment claimed the dynamic import fails under a strict CSP. It doesn't — the chunk comes from our origin under script-src, which the host already allows, because they loaded the widget. What CSP blocks is the transport POST, and Sentry's transport never learns from that: it records a network_error outcome and rethrows, and its only back-off comes from a rate-limit header on a response that a blocked request never gets. So a host who declined the origin got one blocked request and one browser CSP-violation error per reported failure, for the life of the page — the exact noise this seam exists to avoid, and the opposite of what README.md promised them.

Fixed behaviourally rather than by weakening the prose: the transport latches off after the first refusal, which makes the README's promise true and the memoization comment accurate. Covered by a test.

4. *.ingest.sentry.io in the README would have blocked everything for most orgs. A CSP host wildcard matches a suffix, and any Sentry org created since 2024 gets a regional ingest host (o123.ingest.us.sentry.io) that does not end in .ingest.sentry.io. The line came from my test fixture, which uses the legacy non-regional form — and since the DSN isn't committed, nothing in this repo could catch it against reality. Widened to https://*.sentry.io.

5. No dedupe, with a caller reporting from a render body. Link.tsx reports a refused href during render, so one malformed webPath in a search-results list is one event per row per render pass. Free when this was console-only. Added dedupeIntegration() (pure event processor, touches nothing on the host page) plus a hard MAX_EVENTS_PER_PAGE ceiling — different jobs: dedupe is about accuracy, the cap is the absolute bound. Also added linkedErrorsIntegration(), without which error.cause chains were silently dropped.

6. The console line fired at error level for kinds I'd deliberately decided aren't news. Now that every boundary reports, a dead link was putting a red [sahaj-atlas] error into a stranger's console for something the codebase already calls not-a-malfunction. The log level now follows the same REPORTED_KINDS table that decides what's worth an event.

7. integrations: []'s stated reason was wrong — I kept the option and rewrote the claim. Worth recording so nobody re-derives it: a bare new BrowserClient(...) installs no default integrations at all; getDefaultIntegrations runs only inside Sentry.init. The option is load-bearing for a completely different reason — Client.init does this._options.integrations.some(...), which throws on undefined, inside a fallback where a throw blanks the widget.

8. Two comments asserted things that weren't true. Fallbacks.tsx said the seam's only prior caller was the fallback-of-the-fallback (there were five), and report.ts still opened by describing itself as recording a failure "while rendering an error state". Both corrected.

9. Two load-bearing behaviours had no test. ResetErrorBoundary's composed onError — the one place that makes all six sites report — now has jsdom coverage for both halves (the surface name reaches the seam; a caller's own onError still runs). reportIntegrationWarning staying console-only was a 20-line documented decision with zero assertions; one line pins it. Plus report.test.ts now stubs VITE_SENTRY_DSN empty, or those specs would reach the real unmocked SDK if one were ever set in the environment.

Where I disagreed

Nothing substantive. The reviewers independently confirmed the memoization can't leak a rejection, the child-scope tag isolation is real in @sentry/[email protected], the gate ordering means the opt-out can't be outrun, and REPORTED_KINDS as a total Record is the right shape. I left ResetErrorBoundaryProps out of the barrel (not consumed outside the module, per DESIGN_SYSTEM.md) and left the prod-<hash> chunk name alone (rolldown-derived, cosmetic).

/simplify was not run — it was being held for the reviews and the session ran out of budget before it came back around. Not a gap I'd block on, but stating it.

Error kinds: reported vs dropped

Kind Sent? Why
server ✅ SahajCloud is down, or a CORS/CSP block reported as one
config ✅ A customer's API key is wrong/expired — their embed is dead on arrival
unknown ✅ Ours: render crash, schema drift, refused link
offline ❌ The POST needs the network that just failed. ERROR_POLICY already withholds the report CTA here for the same reason
not-found ❌ A dead link is not a malfunction — stale bookmarks and CMS unpublishes. The codebase already says so by rendering the neutral register, not the danger one

REPORTED_KINDS is a Record<ErrorKind, boolean>, so adding a kind forces a decision. The not-found counter-argument is real — a 404 spike caused by our routing would be invisible — so it's one line to flip and says so. The same table now also picks the console level.

Bundle cost — measured both ways

pnpm build && pnpm size, gzip at zlib default, budget BUDGET_KIB = 395 (not raised).

Build standalone embed
main @ e9909e5 (no Sentry) 380.5 KiB 382.1 KiB
This branch, no DSN 381.1 KiB 382.7 KiB
This branch, with a DSN 381.1 KiB 382.7 KiB

Eager cost: +0.6 KiB on both graphs — the seam code itself. Identical with and without a DSN (the DSN is a string literal, not a graph change). Headroom left: 13.9 / 12.3 KiB. Measured against the old base before the rebase too: +0.6 / +0.7 — same answer.

The SDK is a separate 19.0 KiB gz chunk, reached only by await import() inside captureError (up from 18.3 with the two integrations added). @sentry/replay, @sentry/feedback and @sentry/replay-canvas are transitive deps but tree-shake out entirely. Verified in dist/: the eager chunks contain only the dynamic-import expression and the DSN literal.

One honest caveat: the chunk is emitted even on a DSN-less build (Vite only string-replaces import.meta.env.VITE_X for keys that exist, so the guard stays a runtime lookup). It is never fetched.

Verification

  • Lint ✓ · Types ✓ · Tests ✓ 832 passing / 76 files · Build ✓ · Size ✓ both graphs · Ladle ✓ · Audit ✓ 0 new high/critical
  • CI green — all five checks.

Manual verification (browser not authorized this wave)

  1. Build with a real DSN, load a healthy page → no request to the ingest host, no SDK chunk fetched.
  2. Force a boundary trip → one event tagged atlas.kind/atlas.context, request.url origin + path only (load the host page with ?secret=x#y to prove the trim).
  3. Set error-reporting="false" and repeat → console line, no network request.
  4. Serve a page with a CSP omitting the ingest origin → one blocked request, then none on later errors.

Notes for reviewer

  • No source-map upload. Needs a SENTRY_AUTH_TOKEN in Cloudflare Pages and a build-time plugin — real scope, not asked for. Without it, production stack frames point into minified chunks; the error message plus the two tags carry triage weight until it lands. Highest-value follow-up.
  • The in-widget route is not on the event. Under HashRouter the widget's route is the fragment, which hostPageUrl strips — so unlike the human report, nothing carries it. atlas.context names the boundary, which is the cheap part of what's lost. Carrying the route as its own tag is a follow-up; noted in the code so the comment doesn't overclaim.
  • Two operational steps for whoever provisions the Sentry project: enable "Prevent Storing of IP Addresses" and set a short retention. The ingest request necessarily discloses the visitor's IP, exactly as the README already says of Fathom.
  • CI never exercises the Sentry path — there's no DSN in CI, so the gate proves the off state only. The unit lane covers the on state against a mocked SDK.
  • src/lib/report.ts imports @/config/privacy. Worth a second opinion against the src/lib/ "pure domain helpers" rule; privacy is a plain module singleton with no React, and report.ts already reads window/navigator.
  • App.tsx edits are boundary props only — sibling feat(seo): prevent direct indexing of the standalone build #106 owns the standalone head region.
  • Dev-only: StrictMode double-invokes render, so a developer with a local DSN sees duplicate events. No-op in production; .env ships no DSN.
  • Resolves RELEASE_READINESS.md §9's "zero production error signal" (both compounding facts). Does not resolve report-form delivery (feat(widget): submit issue reports to the SahajCloud endpoint #80) or conversion analytics (feat(widget): track conversion events for registration and sharing #109) — both out of scope.

Full implementation report: .claude/reports/108-sentry-reporting.md.

Rebased onto e9909e5

Five siblings squash-merged while this was open; the overlap was two files. scripts/audit-baseline.json conflicted because #128 had already booked the same four advisories (image-size ×2, nanoid ×2 — newly published that day against main's existing tree, which is why every open PR went red at once). My equivalent commit was dropped in favour of theirs, which is better researched. .claude/rules/i18n-and-state.md auto-merged.

Worth recording: that conflict is why CI looked hung. GitHub queued no pull_request run for two successive pushes while mergeable sat at UNKNOWN and then CONFLICTING — there is no merge commit for the event to run against — while sibling branches built normally throughout, which reads exactly like a per-branch Actions outage. Close/reopen didn't shake it loose; the rebase did, instantly. Check gh pr view --json mergeable before blaming Actions.

Closes #108

🤖 Generated with Claude Code

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Deploying sahajatlas-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: 47771aa
Status: ✅  Deploy successful!
Preview URL: https://bee08d72.sahajatlas-design.pages.dev
Branch Preview URL: https://feat-sentry-reporting.sahajatlas-design.pages.dev

View logs

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: 47771aa
Status: ✅  Deploy successful!
Preview URL: https://18983f12.sahajatlas.pages.dev
Branch Preview URL: https://feat-sentry-reporting.sahajatlas.pages.dev

View logs

Ardnived added a commit that referenced this pull request Aug 7, 2026
From the code + security reviews on #123.

**A host page can share our Sentry global scope.** `getCombinedScopeData`
always merges `getGlobalScope()`, and the carrier is keyed by SDK
version string — so a site running this same @sentry/browser version
shares it with us, and their setTag/setExtra/setContext would ride out on
our events. `beforeSend` is now an allowlist that rebuilds the event from
what we know we put on it, rather than a blocklist trimming what we
happened to think of. It also clears `hint.attachments`, which are
appended AFTER the hook so nothing else can remove them.

**The host's full URL could escape inside an exception message.** A
refused `replaceState` throws a DOMException whose text embeds the URL it
refused, query and fragment included — walking straight past
`hostPageUrl`, which exists to strip exactly that. `claimFragment` now
reports a sentence we built, keeping only the exception's name.
`maxValueLength` additionally caps every value at the same 500 chars the
human report uses.

**A blocked ingest origin retried forever.** The old comment claimed the
import fails under a strict CSP; it doesn't — the chunk comes from our
origin under `script-src`, which the host already allows. What CSP blocks
is the transport POST, and Sentry's transport never learns from that: it
records an outcome and rethrows, and its only back-off comes from a
rate-limit header on a response a blocked request never gets. So a host
who declined the origin got one blocked request AND one CSP-violation
console error per reported failure, for the life of the page — the exact
noise this seam exists to avoid, and the opposite of what the README
promises. The transport now latches off after the first refusal.

Also: pass our own `fetch` to `makeFetchTransport`, since the default
implementation injects a hidden iframe into the host's <head> when
anything has wrapped `window.fetch`; add `dedupeIntegration` (the seam is
now called from render bodies — `Link` reports a refused href per row per
render) and `linkedErrorsIntegration` (`error.cause` chains were
dropped); cap events per page load; and correct the `integrations: []`
rationale, which was wrong — a bare BrowserClient installs no defaults at
all, the option is required because `Client.init` calls `.some()` on it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived added a commit that referenced this pull request Aug 8, 2026
Four high advisories published 2026-08-07 against the existing lockfile (image-size x2, nanoid x2) turned the audit gate red on every open PR, none of which touch either package. Both are verified absent from the shipped bundle by build + grep — payload is types-only so image-size never ships, postcss is build-time, and the one 'nanoid' string in dist/ is zod's .nanoid() validator name. image-size has no published fix; nanoid's is held back by postcss's own pin and arrives free under #101. Baselined against #101 with per-entry reasoning.

Unblocks #123, #125, #126, #127.
@Ardnived Ardnived closed this Aug 8, 2026
@Ardnived Ardnived reopened this Aug 8, 2026
Ardnived and others added 6 commits August 7, 2026 17:26
Until now a widget that broke on a host page told nobody: the seam
`reportInternalError` was designed for a reporter and had none, and only
the fallback-of-the-fallback ever called it — so the failures a viewer
actually sees produced no signal at all.

Sentry now hangs off that one function, and off `ResetErrorBoundary`, so
every boundary in the app reports and a boundary added later cannot
forget to.

- A `BrowserClient` on a private `Scope`, NOT `Sentry.init`: `init`
  installs global error handlers on a page we do not own, which would
  capture the HOST's exceptions into our project and spend their quota.
- Dynamically imported, so the SDK never joins the eager graph. Eager
  payload moves 379.7 -> 380.1 KiB gz standalone, 381.2 -> 381.7 embed,
  identical with and without a DSN; the SDK is an 18.3 KiB gz chunk
  fetched only by a visitor already looking at a broken widget.
- Absent `VITE_SENTRY_DSN` is exactly the old console-only behaviour,
  and nothing is fetched.
- `offline` and `not-found` are deliberately not reported: the first
  needs the network that just failed, the second is somebody's stale
  bookmark rather than a malfunction.
- All default integrations off and a `beforeSend` that rewrites the
  host URL to origin + path, matching the rule `hostPageUrl` already
  enforces for the human report.
- `error-reporting="false"` lets a host decline it, its own flag rather
  than a reading of `analytics` — measuring an audience and learning a
  widget is broken are separate purposes.

`reportIntegrationWarning` stays console-only on purpose: it fires from
the element lifecycle before the privacy attributes have been read, so a
beacon there could outrun an opt-out.

Closes #108

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The CSP row is additive, on the existing `connect-src` line rather than a
second one — a repeated directive name is ignored, which is the trap that
paragraph already warns about.

Says the useful thing for an integrator: the request happens only after
the widget has already broken, blocking it is supported and costs them
nothing, and `error-reporting="false"` is the way to refuse it outright.

`VITE_SENTRY_DSN` is deliberately absent from `.env` — not because a DSN
is secret (it is write-only and ships in the bundle) but because a
committed one would have every fork and preview posting into production.

Closes #108

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two BrowserClient defaults are written for an app that owns its page, and
this one does not:

- `release` defaults to `window.SENTRY_RELEASE?.id` — the HOST's global.
  A site running its own Sentry would have stamped every one of our
  events with their deploy version, so our issues would have claimed to
  come from a release that isn't ours.
- `sendClientReports` defaults to true, posting an outcome summary to the
  ingest endpoint when the page is hidden — a second uninvited request
  from somebody else's page, for SDK bookkeeping we do not read.

Both pinned, and both asserted, since a version bump could reinstate
either one with every gate still green.

Closes #108

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
From the code + security reviews on #123.

**A host page can share our Sentry global scope.** `getCombinedScopeData`
always merges `getGlobalScope()`, and the carrier is keyed by SDK
version string — so a site running this same @sentry/browser version
shares it with us, and their setTag/setExtra/setContext would ride out on
our events. `beforeSend` is now an allowlist that rebuilds the event from
what we know we put on it, rather than a blocklist trimming what we
happened to think of. It also clears `hint.attachments`, which are
appended AFTER the hook so nothing else can remove them.

**The host's full URL could escape inside an exception message.** A
refused `replaceState` throws a DOMException whose text embeds the URL it
refused, query and fragment included — walking straight past
`hostPageUrl`, which exists to strip exactly that. `claimFragment` now
reports a sentence we built, keeping only the exception's name.
`maxValueLength` additionally caps every value at the same 500 chars the
human report uses.

**A blocked ingest origin retried forever.** The old comment claimed the
import fails under a strict CSP; it doesn't — the chunk comes from our
origin under `script-src`, which the host already allows. What CSP blocks
is the transport POST, and Sentry's transport never learns from that: it
records an outcome and rethrows, and its only back-off comes from a
rate-limit header on a response a blocked request never gets. So a host
who declined the origin got one blocked request AND one CSP-violation
console error per reported failure, for the life of the page — the exact
noise this seam exists to avoid, and the opposite of what the README
promises. The transport now latches off after the first refusal.

Also: pass our own `fetch` to `makeFetchTransport`, since the default
implementation injects a hidden iframe into the host's <head> when
anything has wrapped `window.fetch`; add `dedupeIntegration` (the seam is
now called from render bodies — `Link` reports a refused href per row per
render) and `linkedErrorsIntegration` (`error.cause` chains were
dropped); cap events per page load; and correct the `integrations: []`
rationale, which was wrong — a bare BrowserClient installs no defaults at
all, the option is required because `Client.init` calls `.some()` on it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The composed `onError` on `ResetErrorBoundary` is the single place that
makes all six boundaries report, and it had no test — no SSR markup can
show whether a handler fired, so it joins the two existing jsdom specs.
Covers both halves of the contract: the surface name reaches the seam,
and a caller's own `onError` still runs (composed, not overridden).

`reportIntegrationWarning` staying console-only was a 20-line documented
decision with zero assertions; now one line pins it.

Two comments asserted things that were not true:

- `Fallbacks.tsx` said the seam's only prior caller was the
  fallback-of-the-fallback. There were five. The intended point — that
  none of them was an ordinary boundary trip — is the accurate version.
- `report.ts`'s opening line still described the function as recording a
  failure "while rendering an error state", which stopped being what it
  is the moment every boundary started reporting through it.

Also stub `VITE_SENTRY_DSN` empty in `report.test.ts`: with one set in
the environment those specs would reach the real, unmocked SDK.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`https://*.ingest.sentry.io` looked right and would have blocked
everything for most orgs: a CSP host wildcard matches a SUFFIX, and any
Sentry organisation created since 2024 gets a regional ingest host
(`o123.ingest.us.sentry.io`), which does not end in `.ingest.sentry.io`.
An integrator following the README exactly would have got a silently
blocked reporter. Widened to `https://*.sentry.io`, with a note to take
the exact host from the DSN instead of deriving it.

The line came from the test fixture, which uses the legacy
non-regional form — and since the DSN isn't committed, nothing in this
repo could have caught it against reality.

The paragraph's promise — that declining the origin costs nothing — is
now true rather than aspirational, because the transport latches off
after the first refusal. It says what an integrator actually sees: one
blocked request and one CSP-violation entry, not one per error.

Also record in environment.md that the DSN must be the modern
public-key form: the legacy `https://<key>:<secret>@…` spelling would
put a real secret into the public bundle.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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.

feat(widget): wire sentry into the error-reporting seam

1 participant