diff --git a/.changeset/fix-direct-tab-double-badge.md b/.changeset/fix-direct-tab-double-badge.md new file mode 100644 index 00000000..6d050636 --- /dev/null +++ b/.changeset/fix-direct-tab-double-badge.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix duplicate unread badges on the /direct/ icon for DM rooms already shown as individual sidebar avatars diff --git a/.changeset/fix-thread-fallback-reply-spec.md b/.changeset/fix-thread-fallback-reply-spec.md new file mode 100644 index 00000000..6eecf251 --- /dev/null +++ b/.changeset/fix-thread-fallback-reply-spec.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix thread messages to include the required `m.in_reply_to` fallback pointing to the latest thread event, so unthreaded clients can display the reply chain correctly per the Matrix spec. diff --git a/.changeset/fix-timeline-refresh-scroll.md b/.changeset/fix-timeline-refresh-scroll.md new file mode 100644 index 00000000..d042bd01 --- /dev/null +++ b/.changeset/fix-timeline-refresh-scroll.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix spurious scroll-to-bottom and MaxListeners warnings on sync gap: stable callback refs and prevEventsLength guard in RoomTimeline, correct CallEmbed .bind(this) listener leak, stable refs in useCallSignaling, and unreadInfoRef to stop per-message listener churn diff --git a/docs/PRIVACY_POLICY.md b/docs/PRIVACY_POLICY.md new file mode 100644 index 00000000..73685e52 --- /dev/null +++ b/docs/PRIVACY_POLICY.md @@ -0,0 +1,116 @@ +# Privacy Policy + +**Effective date:** 2026-03-15 + +Sable is an open-source Matrix client developed by 7w1. + +It is designed to keep data collection to a minimum. Most of the app works on your device and communicates directly with the Matrix homeserver you choose. + +## Who is responsible + +For official Sable builds distributed by the project, the data controller is **7w1**. + +Contact: **security@sable.moe** +Project website: [**https://sable.moe**](https://sable.moe) + +If you use a self-hosted, modified, or third-party build of Sable, that operator may use different diagnostics settings and may be responsible for their own privacy practices. + +## What we collect + +We only collect limited diagnostic data to help find bugs and improve the stability and security of the app. + +Diagnostic data is sent only when error reporting is enabled. + +This data may include: + +- Crash and error details, such as exception type, stack trace, and error message +- Device, browser, or operating system name and version +- Application version and environment +- Anonymous performance information, such as page load, sync, or message-send timing + +Before any diagnostic data is sent, sensitive values are scrubbed in the browser on your device. + +## What we do not collect + +Sable is designed not to collect or transmit: + +- Matrix message content +- Room names or aliases +- User display names or avatars +- Contact lists or room member lists +- Authentication tokens or passwords +- Encryption keys or cryptographic session data +- IP addresses +- Precise or approximate location data + +## Optional features + +### Session replay + +Session replay may be available for debugging, but it is **disabled by default** and must be turned on by the user. + +When session replay is enabled, all text is masked, media is blocked, and form inputs are masked before any data leaves the device. + +This is intended to ensure that Matrix messages, room names, user names, and other personal content are not visible in replays. + +### Bug reports + +You may choose to submit a bug report from within the app. + +A bug report may include the description you write, platform and app version details, and optional diagnostic logs that you choose to attach. + +Submitting a bug report is voluntary, and the app shows what will be sent before submission. + +## Third-party services + +Sable uses **Sentry** for crash reporting and performance diagnostics. + +Sentry receives only the diagnostic data described in this policy. + +Sentry handles that data under its own privacy policy: +[**https://sentry.io/privacy/**](https://sentry.io/privacy/) + +Technical details about Sable's Sentry integration are documented here: +[**https://github.com/SableClient/Sable/blob/feat/sentry-pr/docs/SENTRY_PRIVACY.md**](https://github.com/SableClient/Sable/blob/feat/sentry-pr/docs/SENTRY_PRIVACY.md) + +If a Sentry DSN is not configured, Sentry is inactive and no Sentry data is sent. + +Self-hosted deployments may use a different Sentry instance or disable diagnostics entirely. + +## Your controls + +You can manage diagnostic features in: **Settings → General → Diagnostics & Privacy** + +Depending on the build, you can disable error reporting, enable or disable session replay, and adjust breadcrumb categories. + +You can also stop all app-based data transmission by uninstalling the app. + +## Legal basis + +For users in the European Economic Area, diagnostic data is processed on the basis of legitimate interest for app reliability and security, and on the basis of consent where optional features such as session replay are explicitly enabled. + +## Retention and transfers + +Diagnostic data is stored by Sentry according to the retention settings of the Sentry project. + +The Sable project does not keep a separate copy of that diagnostic data. + +Because Sentry is a cloud service, diagnostic data may be processed outside your country of residence. Sentry states that it provides safeguards such as Standard Contractual Clauses where required. + +## Children + +Sable is not directed to children under 13. + +We do not knowingly collect personal information from children through the app. + +If you believe a child has submitted information through Sable, contact **security@sable.moe** so it can be removed. + +## Changes to this policy + +We may update this Privacy Policy from time to time. + +When we do, we will publish the updated version at [**https://sable.moe**](https://sable.moe). + +## Contact + +If you have questions about this Privacy Policy or want to request deletion of data connected to a bug report, contact **security@sable.moe**. diff --git a/docs/SENTRY_INTEGRATION.md b/docs/SENTRY_INTEGRATION.md index 3227e211..e71f417e 100644 --- a/docs/SENTRY_INTEGRATION.md +++ b/docs/SENTRY_INTEGRATION.md @@ -86,7 +86,7 @@ New Sentry settings panel in Developer Tools: - **Export debug logs**: Download the in-memory log buffer as JSON for offline analysis - **Attach debug logs**: Manually attach recent logs to next error -Access via: Settings → Developer Tools → Error Tracking (Sentry) +Access via: Settings → General → Diagnostics & Privacy ## Configuration @@ -113,6 +113,76 @@ SENTRY_ORG=your-org-slug SENTRY_PROJECT=your-project-slug ``` +### Self-Hosting with Docker + +Sable is compiled at build time, so `VITE_*` variables must be passed as Docker +**build arguments** — they cannot be injected at container runtime via a plain +`docker run -e` flag. The easiest way for self-hosters to supply them is with +a `.env` file and `docker-compose`. + +#### 1. Create a `.env` file + +```env +# .env — never commit this file +VITE_SENTRY_DSN=https://your-key@oXXXXX.ingest.sentry.io/XXXXXXX +VITE_SENTRY_ENVIRONMENT=production +``` + +The `VITE_SENTRY_ENVIRONMENT` value controls sampling rates (see table below). +Leave it as `production` for a live deployment. + +#### 2. Reference it in `docker-compose.yml` + +The `args` block forwards the variables from `.env` into the Docker build +stage so Vite can embed them in the bundle: + +```yaml +services: + sable: + build: + context: . + args: + - VITE_SENTRY_DSN=${VITE_SENTRY_DSN} + - VITE_SENTRY_ENVIRONMENT=${VITE_SENTRY_ENVIRONMENT} + ports: + - '8080:8080' +``` + +Then build and start with: + +```bash +docker compose --env-file .env up --build +``` + +#### 3. Verify it worked + +Open the browser console after loading your instance — you should see: + +``` +[Sentry] Initialized for production environment +[Sentry] DSN configured: https://your-key@o... +``` + +If you see `[Sentry] Disabled - no DSN provided`, the build arg was not +picked up — double-check the `args` block and that your `.env` file is in the +same directory as `docker-compose.yml`. + +#### Building without Compose + +If you use plain `docker build`, pass build args directly: + +```bash +docker build \ + --build-arg VITE_SENTRY_DSN="https://your-key@oXXXXX.ingest.sentry.io/XXXXXXX" \ + --build-arg VITE_SENTRY_ENVIRONMENT="production" \ + -t sable . +``` + +> **Security note:** DSN values embedded in the JavaScript bundle are visible +> to any user who opens DevTools. This is normal and expected for Sentry DSNs — +> they are designed to be public-facing ingest keys. Rate-limiting and origin +> restrictions on the Sentry project side are the correct controls. + ### Deployment Configuration **Production deployment (from `dev` branch):** @@ -161,7 +231,7 @@ localStorage.setItem('sable_sentry_enabled', 'false'); localStorage.setItem('sable_sentry_replay_enabled', 'false'); ``` -Or use the UI in Settings → Developer Tools → Error Tracking (Sentry). +Or use the UI in Settings → General → Diagnostics & Privacy. ## Custom Instrumentation @@ -169,15 +239,15 @@ Beyond automatic error capture, Sable has hand-crafted monitoring at key lifecycle points. See [SENTRY_PRIVACY.md](./SENTRY_PRIVACY.md) for the full metrics reference. Key areas: -| Area | What's tracked | -|------|----------------| -| **Auth** | Login failures (by `errcode`), forced server logouts | -| **Sync** | Transport type, degraded states, cycle stats, time-to-ready | -| **Cryptography** | Decryption failures (by failure reason), key backup errors, store wipes, E2E verification outcomes | -| **Messaging** | Send latency, send errors, local-echo `NOT_SENT` events | -| **Timeline** | Opens, virtual window size, jump-load latency, re-initialisations | -| **Media** | Upload latency, upload size, cache stats | -| **Background clients** | Per-account notification client count, startup failures | +| Area | What's tracked | +| ---------------------- | -------------------------------------------------------------------------------------------------- | +| **Auth** | Login failures (by `errcode`), forced server logouts | +| **Sync** | Transport type, degraded states, cycle stats, time-to-ready | +| **Cryptography** | Decryption failures (by failure reason), key backup errors, store wipes, E2E verification outcomes | +| **Messaging** | Send latency, send errors, local-echo `NOT_SENT` events | +| **Timeline** | Opens, virtual window size, jump-load latency, re-initialisations | +| **Media** | Upload latency, upload size, cache stats | +| **Background clients** | Per-account notification client count, startup failures | Fatal errors that are caught by `useAsyncCallback` state (and therefore never reach React's ErrorBoundary) are explicitly forwarded with `captureException`: @@ -301,7 +371,7 @@ No message content, room conversations, or personal information is ever sent to To test the integration: 1. **Test error reporting**: - - Go to Settings → Developer Tools → Error Tracking + - Go to Settings → General → Diagnostics & Privacy - Check that Sentry is enabled and `VITE_SENTRY_DSN` is set - Open the browser console and run: `window.Sentry?.captureMessage('Test message')` - Check the Sentry dashboard for the event diff --git a/docs/SENTRY_PRIVACY.md b/docs/SENTRY_PRIVACY.md index 93877a7d..265ef57e 100644 --- a/docs/SENTRY_PRIVACY.md +++ b/docs/SENTRY_PRIVACY.md @@ -9,7 +9,7 @@ configuration details see [SENTRY_INTEGRATION.md](./SENTRY_INTEGRATION.md). ## What Is Collected Sentry is **disabled by default when no DSN is configured** and can be **opted -out by users** at any time via Settings → Developer Tools → Error Tracking. +out by users** at any time via Settings → General → Diagnostics & Privacy. When enabled, the following categories of data are sent: @@ -48,14 +48,14 @@ browser. In addition to automatic navigation/console breadcrumbs, the following named events are explicitly recorded as breadcrumbs: -| Event | Category | Level | Source | -|-------|----------|-------|--------| -| Session forcibly logged out by server | `auth` | warning | `ClientRoot.tsx` | -| Sync state changed to Reconnecting/Error | `sync` | warning/error | `SyncStatus.tsx` | -| Sliding sync first run completed | `sync` | info | `initMatrix.ts` | -| Crypto store mismatch — wiping local stores | `crypto` | warning | `initMatrix.ts` | -| Key backup failed | `crypto` | error | `useKeyBackup.ts` | -| High media inflight request count | `media` | warning | `ClientNonUIFeatures.tsx` | +| Event | Category | Level | Source | +| ------------------------------------------- | -------- | ------------- | ------------------------- | +| Session forcibly logged out by server | `auth` | warning | `ClientRoot.tsx` | +| Sync state changed to Reconnecting/Error | `sync` | warning/error | `SyncStatus.tsx` | +| Sliding sync first run completed | `sync` | info | `initMatrix.ts` | +| Crypto store mismatch — wiping local stores | `crypto` | warning | `initMatrix.ts` | +| Key backup failed | `crypto` | error | `useKeyBackup.ts` | +| High media inflight request count | `media` | warning | `ClientNonUIFeatures.tsx` | **Code:** `src/app/pages/client/ClientRoot.tsx`, `src/app/pages/client/SyncStatus.tsx`, `src/client/initMatrix.ts`, `src/app/hooks/useKeyBackup.ts`, @@ -66,10 +66,10 @@ events are explicitly recorded as breadcrumbs: The following failure paths use explicit `captureException` because they are caught by state management hooks and never propagate to React's ErrorBoundary: -| Failure | Tag | Source | -|---------|-----|--------| -| Client failed to load (fetch/init) | `phase: load` | `ClientRoot.tsx` | -| Client failed to start (sync start) | `phase: start` | `ClientRoot.tsx` | +| Failure | Tag | Source | +| ---------------------------------------------- | ------------------------------------ | ----------------------------- | +| Client failed to load (fetch/init) | `phase: load` | `ClientRoot.tsx` | +| Client failed to start (sync start) | `phase: start` | `ClientRoot.tsx` | | Background notification client failed to start | `component: BackgroundNotifications` | `BackgroundNotifications.tsx` | **Code:** `src/app/pages/client/ClientRoot.tsx`, @@ -84,21 +84,21 @@ caught by state management hooks and never propagate to React's ErrorBoundary: Performance data contains **no message content, no room names, and no user identifiers**. Spans are labelled with operation names only. -| Span name | Operation | Source | -|-----------|-----------|--------| -| `auth.login` | `auth` | `loginUtil.ts` | -| `decrypt.event` | `matrix.crypto` | `EncryptedContent.tsx` | -| `decrypt.bulk` | `matrix.crypto` | `room.ts` | -| `timeline.jump_load` | `matrix.timeline` | `RoomTimeline.tsx` | -| `message.send` | `matrix.message` | `RoomInput.tsx` | -| Sliding sync processing | `matrix.sync` | `slidingSync.ts` | +| Span name | Operation | Source | +| ----------------------- | ----------------- | ---------------------- | +| `auth.login` | `auth` | `loginUtil.ts` | +| `decrypt.event` | `matrix.crypto` | `EncryptedContent.tsx` | +| `decrypt.bulk` | `matrix.crypto` | `room.ts` | +| `timeline.jump_load` | `matrix.timeline` | `RoomTimeline.tsx` | +| `message.send` | `matrix.message` | `RoomInput.tsx` | +| Sliding sync processing | `matrix.sync` | `slidingSync.ts` | **Sample rates:** -| Environment | Traces | Profiles | -|---------------------|--------|----------| -| `production` | 10% | 10% | -| `preview` / `development` | 100% | 100% | +| Environment | Traces | Profiles | +| ------------------------- | ------ | -------- | +| `production` | 10% | 10% | +| `preview` / `development` | 100% | 100% | **Code:** `src/instrument.ts` — `tracesSampleRate`, `profilesSampleRate` **Code:** `src/app/features/room/RoomInput.tsx` — message send span @@ -112,22 +112,22 @@ or numeric measurements. #### Authentication -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.auth.login_failed` | count | `errcode` | Login attempt failures by error code | +| Metric | Type | Attributes | What it tracks | +| ------------------------- | ----- | ---------- | ------------------------------------ | +| `sable.auth.login_failed` | count | `errcode` | Login attempt failures by error code | **Code:** `src/app/pages/auth/login/loginUtil.ts` #### Cryptography -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.decryption.failure` | count | `reason` | Unable-to-decrypt events by failure reason | -| `sable.decryption.event_ms` | distribution | — | Per-event decryption latency | -| `sable.decryption.bulk_latency_ms` | distribution | `event_count` | Bulk re-decryption time on room open | -| `sable.crypto.key_backup_failures` | count | `errcode` | Key backup errors by code | -| `sable.crypto.store_wipe` | count | — | Crypto store mismatch wipe-and-retry occurrences | -| `sable.crypto.verification_outcome` | count | `outcome` (`completed`/`cancelled`) | E2E device verification outcomes | +| Metric | Type | Attributes | What it tracks | +| ----------------------------------- | ------------ | ----------------------------------- | ------------------------------------------------ | +| `sable.decryption.failure` | count | `reason` | Unable-to-decrypt events by failure reason | +| `sable.decryption.event_ms` | distribution | — | Per-event decryption latency | +| `sable.decryption.bulk_latency_ms` | distribution | `event_count` | Bulk re-decryption time on room open | +| `sable.crypto.key_backup_failures` | count | `errcode` | Key backup errors by code | +| `sable.crypto.store_wipe` | count | — | Crypto store mismatch wipe-and-retry occurrences | +| `sable.crypto.verification_outcome` | count | `outcome` (`completed`/`cancelled`) | E2E device verification outcomes | **Code:** `src/app/features/room/message/EncryptedContent.tsx`, `src/app/utils/room.ts`, `src/app/hooks/useKeyBackup.ts`, @@ -135,70 +135,70 @@ or numeric measurements. #### Messaging -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.message.send_latency_ms` | distribution | `encrypted` | Message send round-trip time | -| `sable.message.send_error` | count | — | Send errors from message composer | -| `sable.message.send_failed` | count | — | Local-echo `NOT_SENT` status events | +| Metric | Type | Attributes | What it tracks | +| ------------------------------- | ------------ | ----------- | ----------------------------------- | +| `sable.message.send_latency_ms` | distribution | `encrypted` | Message send round-trip time | +| `sable.message.send_error` | count | — | Send errors from message composer | +| `sable.message.send_failed` | count | — | Local-echo `NOT_SENT` status events | **Code:** `src/app/features/room/RoomInput.tsx`, `src/app/features/room/RoomTimeline.tsx` #### Timeline -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.timeline.open` | count | `mode` | Timeline render initiations | -| `sable.timeline.render_window` | distribution | `mode` | Initial virtual window size | -| `sable.timeline.jump_load_ms` | distribution | — | Event-jump timeline load latency | -| `sable.timeline.reinit` | count | — | Full timeline re-initialisations | -| `sable.pagination.error` | count | `direction` | Pagination errors by direction | +| Metric | Type | Attributes | What it tracks | +| ------------------------------ | ------------ | ----------- | -------------------------------- | +| `sable.timeline.open` | count | `mode` | Timeline render initiations | +| `sable.timeline.render_window` | distribution | `mode` | Initial virtual window size | +| `sable.timeline.jump_load_ms` | distribution | — | Event-jump timeline load latency | +| `sable.timeline.reinit` | count | — | Full timeline re-initialisations | +| `sable.pagination.error` | count | `direction` | Pagination errors by direction | **Code:** `src/app/features/room/RoomTimeline.tsx` #### Sync -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.sync.transport` | count | `type` (`sliding`/`classic`) | Sync transport type used | -| `sable.sync.cycle` | count | (various) | Completed sliding sync cycles | -| `sable.sync.error` | count | `errcode` | Sliding sync errors | -| `sable.sync.initial_ms` | distribution | — | Initial sync completion time | -| `sable.sync.processing_ms` | distribution | — | Per-cycle sync processing time | -| `sable.sync.lists_loaded_ms` | distribution | — | Time for room lists to fully load | -| `sable.sync.total_rooms` | gauge | `sync_type` | Total rooms known at list load | -| `sable.sync.active_subscriptions` | gauge | — | Active room subscription count | -| `sable.sync.client_ready_ms` | distribution | `type` | Time from init to client ready | -| `sable.sync.time_to_ready_ms` | distribution | — | Wall-clock time to first sync ready | -| `sable.sync.degraded` | count | `state` | Sync reconnect/error state transitions | +| Metric | Type | Attributes | What it tracks | +| --------------------------------- | ------------ | ---------------------------- | -------------------------------------- | +| `sable.sync.transport` | count | `type` (`sliding`/`classic`) | Sync transport type used | +| `sable.sync.cycle` | count | (various) | Completed sliding sync cycles | +| `sable.sync.error` | count | `errcode` | Sliding sync errors | +| `sable.sync.initial_ms` | distribution | — | Initial sync completion time | +| `sable.sync.processing_ms` | distribution | — | Per-cycle sync processing time | +| `sable.sync.lists_loaded_ms` | distribution | — | Time for room lists to fully load | +| `sable.sync.total_rooms` | gauge | `sync_type` | Total rooms known at list load | +| `sable.sync.active_subscriptions` | gauge | — | Active room subscription count | +| `sable.sync.client_ready_ms` | distribution | `type` | Time from init to client ready | +| `sable.sync.time_to_ready_ms` | distribution | — | Wall-clock time to first sync ready | +| `sable.sync.degraded` | count | `state` | Sync reconnect/error state transitions | **Code:** `src/client/initMatrix.ts`, `src/client/slidingSync.ts`, `src/app/pages/client/ClientRoot.tsx`, `src/app/pages/client/SyncStatus.tsx` #### Media -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| +| Metric | Type | Attributes | What it tracks | +| ------------------------------- | ------------ | ---------- | ---------------------------- | | `sable.media.upload_latency_ms` | distribution | `mimetype` | Media upload round-trip time | -| `sable.media.upload_bytes` | distribution | `mimetype` | Upload size distribution | -| `sable.media.upload_error` | count | `reason` | Upload failures by reason | -| `sable.media.blob_cache_size` | gauge | — | Blob URL cache entry count | -| `sable.media.inflight_requests` | gauge | — | Concurrent media requests | +| `sable.media.upload_bytes` | distribution | `mimetype` | Upload size distribution | +| `sable.media.upload_error` | count | `reason` | Upload failures by reason | +| `sable.media.blob_cache_size` | gauge | — | Blob URL cache entry count | +| `sable.media.inflight_requests` | gauge | — | Concurrent media requests | **Code:** `src/app/utils/matrix.ts`, `src/app/pages/client/ClientNonUIFeatures.tsx` #### Background clients & debug telemetry -| Metric | Type | Attributes | What it tracks | -|--------|------|-----------|----------------| -| `sable.background.client_count` | gauge | — | Active background notification clients | -| `sable.errors` | count | `category` | Error-level debug log entries | -| `sable.warnings` | count | `category` | Warning-level debug log entries | +| Metric | Type | Attributes | What it tracks | +| ------------------------------- | ----- | ---------- | -------------------------------------- | +| `sable.background.client_count` | gauge | — | Active background notification clients | +| `sable.errors` | count | `category` | Error-level debug log entries | +| `sable.warnings` | count | `category` | Warning-level debug log entries | **Code:** `src/app/pages/client/BackgroundNotifications.tsx`, `src/app/utils/debugLogger.ts` -### Session Replay *(opt-in, disabled by default)* +### Session Replay _(opt-in, disabled by default)_ When session replay is explicitly enabled by the user, Sentry records UI interactions to help reproduce bugs. **All content is masked at the browser @@ -213,15 +213,15 @@ media are ever visible in a replay**. Sample rates for replay: -| Trigger | Production | Preview / Dev | -|-----------------------|------------|---------------| -| Regular sessions | 10% | 100% | -| Sessions with errors | 100% | 100% | +| Trigger | Production | Preview / Dev | +| -------------------- | ---------- | ------------- | +| Regular sessions | 10% | 100% | +| Sessions with errors | 100% | 100% | **Code:** `src/instrument.ts` — `replayIntegration` call with `maskAllText`, `blockAllMedia`, `maskAllInputs` -### Bug Reports *(manual, opt-in per report)* +### Bug Reports _(manual, opt-in per report)_ When a user submits a bug report via `/bugreport` or the "Bug Report" button: @@ -272,11 +272,11 @@ Regex: `/(access_token|password|token|refresh_token|session_id|sync_token|next_b Matrix IDs are replaced with placeholder tokens before sending: -| Original form | Replaced with | -|-------------------|---------------| -| `@user:server` | `@[USER_ID]` | -| `!room:server` | `![ROOM_ID]` | -| `$event_id` | `$[EVENT_ID]` | +| Original form | Replaced with | +| -------------- | ------------- | +| `@user:server` | `@[USER_ID]` | +| `!room:server` | `![ROOM_ID]` | +| `$event_id` | `$[EVENT_ID]` | **Code:** `src/instrument.ts` — `beforeSend` callback (applied to `event.message` and all `event.exception.values`) @@ -287,11 +287,11 @@ and all `event.exception.values`) Users can adjust Sentry behaviour without restarting the app: -| Setting | Location | `localStorage` key | Default | -|---------|----------|--------------------|---------| -| Disable Sentry entirely | Settings → Developer Tools → Error Tracking | `sable_sentry_enabled` | Enabled | -| Enable session replay | Settings → Developer Tools → Error Tracking | `sable_sentry_replay_enabled` | Disabled (opt-in) | -| Disable breadcrumb categories | Settings → Developer Tools → Error Tracking → Breadcrumb Categories | `sable_sentry_breadcrumb_disabled` | All enabled | +| Setting | Location | `localStorage` key | Default | +| ----------------------------- | ---------------------------------------------------------------------------- | ---------------------------------- | ----------------- | +| Disable Sentry entirely | Settings → General → Diagnostics & Privacy | `sable_sentry_enabled` | Enabled | +| Enable session replay | Settings → General → Diagnostics & Privacy | `sable_sentry_replay_enabled` | Disabled (opt-in) | +| Disable breadcrumb categories | Settings → Developer Tools → Error Tracking (Sentry) → Breadcrumb Categories | `sable_sentry_breadcrumb_disabled` | All enabled | **Rate limiting:** A maximum of 50 error events are forwarded to Sentry per page load (session). Subsequent errors are silently dropped, protecting against quota exhaustion without affecting diff --git a/src/app/components/DefaultErrorPage.tsx b/src/app/components/DefaultErrorPage.tsx index 54ac642e..62042cef 100644 --- a/src/app/components/DefaultErrorPage.tsx +++ b/src/app/components/DefaultErrorPage.tsx @@ -75,7 +75,9 @@ export function ErrorPage({ error, eventId }: ErrorPageProps) { + + + ); +} + export function General({ requestClose }: GeneralProps) { return ( @@ -1078,6 +1181,7 @@ export function General({ requestClose }: GeneralProps) { + diff --git a/src/app/hooks/useCallSignaling.ts b/src/app/hooks/useCallSignaling.ts index cd657e47..1e8a7dfe 100644 --- a/src/app/hooks/useCallSignaling.ts +++ b/src/app/hooks/useCallSignaling.ts @@ -29,6 +29,13 @@ export function useCallSignaling() { const mutedRoomId = useAtomValue(mutedCallRoomIdAtom); const setMutedRoomId = useSetAtom(mutedCallRoomIdAtom); + // Stable refs so volatile values (mutedRoomId, ring callbacks) don't force + // the listener registration effect to re-run — which would cause the + // SessionEnded and RoomState.events listeners to accumulate when muting + // or when call state changes rapidly during a sync retry cycle. + const mutedRoomIdRef = useRef(mutedRoomId); + mutedRoomIdRef.current = mutedRoomId; + useEffect(() => { const inc = new Audio(RingtoneSound); inc.loop = true; @@ -72,6 +79,16 @@ export function useCallSignaling() { [setIncomingCall] ); + // Must be declared after the callbacks above so the initial useRef(value) call + // sees their current identity. Updated on every render so the effect closure + // always calls the latest version without needing them in the dep array. + const playRingingRef = useRef(playRinging); + playRingingRef.current = playRinging; + const stopRingingRef = useRef(stopRinging); + stopRingingRef.current = stopRinging; + const playOutgoingRingingRef = useRef(playOutgoingRinging); + playOutgoingRingingRef.current = playOutgoingRinging; + useEffect(() => { if (!mx || !mx.matrixRTC) return undefined; @@ -81,7 +98,7 @@ export function useCallSignaling() { const signal = Array.from(mDirects).reduce( (acc, roomId) => { - if (acc.incoming || mutedRoomId === roomId) return acc; + if (acc.incoming || mutedRoomIdRef.current === roomId) return acc; const room = mx.getRoom(roomId); if (!room) return acc; @@ -141,11 +158,11 @@ export function useCallSignaling() { ); if (signal.incoming) { - playRinging(signal.incoming); + playRingingRef.current(signal.incoming); } else if (signal.outgoing) { - playOutgoingRinging(signal.outgoing); + playOutgoingRingingRef.current(signal.outgoing); } else { - stopRinging(); + stopRingingRef.current(); if (!signal.outgoing) outgoingStartRef.current = null; } }; @@ -155,7 +172,7 @@ export function useCallSignaling() { const handleUpdate = () => checkDMsForActiveCalls(); const handleSessionEnded = (roomId: string) => { - if (mutedRoomId === roomId) setMutedRoomId(null); + if (mutedRoomIdRef.current === roomId) setMutedRoomId(null); callPhaseRef.current[roomId] = 'IDLE'; checkDMsForActiveCalls(); }; @@ -171,9 +188,9 @@ export function useCallSignaling() { mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionStarted, handleUpdate); mx.matrixRTC.off(MatrixRTCSessionManagerEvents.SessionEnded, handleSessionEnded); mx.off(RoomStateEvent.Events, handleUpdate); - stopRinging(); + stopRingingRef.current(); }; - }, [mx, mDirects, playRinging, stopRinging, mutedRoomId, setMutedRoomId, playOutgoingRinging]); + }, [mx, mDirects, setMutedRoomId]); // stable: volatile deps accessed via refs above return null; } diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx index 71b72157..d81890da 100644 --- a/src/app/pages/Router.tsx +++ b/src/app/pages/Router.tsx @@ -164,59 +164,59 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) beforeCapture={(scope) => scope.setTag('section', 'client')} > - {/* HandleNotificationClick must live outside ClientRoot's loading gate so + {/* HandleNotificationClick must live outside ClientRoot's loading gate so SW notification-click postMessages are never dropped during client reloads (e.g., account switches). It only needs navigate + Jotai atoms. */} - - - - - - - - - - - - } - > - - - - - - - - - - - - - {/* Screen reader live region — populated by announce() in utils/announce.ts */} -
- - - - - - - - + + + + + + + + + + + + } + > + + + + + + + + + + + + + {/* Screen reader live region — populated by announce() in utils/announce.ts */} +
+ + + + + + + + } > diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index fab2261e..a5e78e60 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -676,8 +676,8 @@ function SentryRoomContextFeature() { useEffect(() => { if (!roomId) { Sentry.setContext('room', null); - Sentry.setTag('room_type', ''); - Sentry.setTag('room_encrypted', ''); + Sentry.setTag('room_type', 'none'); + Sentry.setTag('room_encrypted', 'none'); return; } const room = mx.getRoom(roomId); @@ -688,11 +688,12 @@ function SentryRoomContextFeature() { const memberCount = room.getJoinedMemberCount(); // Bucket member count so we can correlate issues with room scale // without leaking precise membership numbers of private rooms. - const memberCountRange = - memberCount <= 2 ? '1-2' : - memberCount <= 10 ? '3-10' : - memberCount <= 50 ? '11-50' : - memberCount <= 200 ? '51-200' : '200+'; + let memberCountRange: string; + if (memberCount <= 2) memberCountRange = '1-2'; + else if (memberCount <= 10) memberCountRange = '3-10'; + else if (memberCount <= 50) memberCountRange = '11-50'; + else if (memberCount <= 200) memberCountRange = '51-200'; + else memberCountRange = '200+'; Sentry.setContext('room', { type: isDm ? 'dm' : 'group', diff --git a/src/app/pages/client/sidebar/DirectDMsList.tsx b/src/app/pages/client/sidebar/DirectDMsList.tsx index 7a6718b5..5823ea45 100644 --- a/src/app/pages/client/sidebar/DirectDMsList.tsx +++ b/src/app/pages/client/sidebar/DirectDMsList.tsx @@ -1,13 +1,10 @@ -import { useMemo, useState, useCallback, useRef, useEffect } from 'react'; +import { useMemo, useRef, useEffect } from 'react'; import * as Sentry from '@sentry/react'; import { useNavigate } from 'react-router-dom'; import { Avatar, Text, Box, toRem } from 'folds'; import { useAtomValue } from 'jotai'; -import { Room, SyncState } from '$types/matrix-sdk'; -import { useDirects } from '$state/hooks/roomList'; +import { Room } from '$types/matrix-sdk'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { mDirectAtom } from '$state/mDirectList'; -import { allRoomsAtom } from '$state/room-list/roomList'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { getDirectRoomPath } from '$pages/pathUtils'; import { @@ -22,14 +19,12 @@ import { UserAvatar } from '$components/user-avatar'; import { getDirectRoomAvatarUrl } from '$utils/room'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { nameInitials } from '$utils/common'; -import { factoryRoomIdByActivity } from '$utils/sort'; import { getCanonicalAliasOrRoomId, mxcUrlToHttp } from '$utils/matrix'; import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { useGroupDMMembers } from '$hooks/useGroupDMMembers'; -import { useSyncState } from '$hooks/useSyncState'; +import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; import * as css from './DirectDMsList.css'; -const MAX_DM_AVATARS = 3; const MAX_GROUP_MEMBERS = 3; type DMItemProps = { @@ -164,62 +159,29 @@ function DMItem({ room, selected }: DMItemProps) { export function DirectDMsList() { const mx = useMatrixClient(); - const mDirects = useAtomValue(mDirectAtom); - const directs = useDirects(mx, allRoomsAtom, mDirects); - const roomToUnread = useAtomValue(roomToUnreadAtom); const selectedRoomId = useSelectedRoom(); + const sidebarRoomIds = useSidebarDirectRoomIds(); - // Track sync state to wait for initial sync completion - const [syncReady, setSyncReady] = useState(false); const mountTimeRef = useRef(performance.now()); const firstReadyRef = useRef(false); - useSyncState( - mx, - useCallback((state, prevState) => { - // Consider ready after initial sync reaches Syncing state - // This ensures m.direct and unread counts are populated - if (state === SyncState.Syncing && prevState !== SyncState.Syncing) { - setSyncReady(true); - } - // Also set ready if we're already syncing (e.g., after a refresh while still online) - if (state === SyncState.Syncing || state === SyncState.Catchup) { - setSyncReady(true); - } - }, []) + const recentDMs = useMemo( + () => + sidebarRoomIds + .map((roomId) => mx.getRoom(roomId)) + .filter((room): room is Room => room !== null), + [sidebarRoomIds, mx] ); useEffect(() => { - if (syncReady && !firstReadyRef.current) { + if (recentDMs.length > 0 && !firstReadyRef.current) { firstReadyRef.current = true; Sentry.metrics.distribution( 'sable.roomlist.time_to_ready_ms', performance.now() - mountTimeRef.current ); } - }, [syncReady]); - - // Get up to MAX_DM_AVATARS recent DMs that have unread messages - const recentDMs = useMemo(() => { - // Don't show DMs until initial sync completes - if (!syncReady) { - return []; - } - - // Filter to only DMs with unread messages - const withUnread = directs.filter((roomId) => { - const unread = roomToUnread.get(roomId); - return unread && (unread.total > 0 || unread.highlight > 0); - }); - - // Sort by activity - const sorted = withUnread.sort(factoryRoomIdByActivity(mx)); - - return sorted - .slice(0, MAX_DM_AVATARS) - .map((roomId) => mx.getRoom(roomId)) - .filter((room): room is Room => room !== null); - }, [directs, mx, roomToUnread, syncReady]); + }, [recentDMs]); if (recentDMs.length === 0) { return null; diff --git a/src/app/pages/client/sidebar/DirectTab.tsx b/src/app/pages/client/sidebar/DirectTab.tsx index dd2a7d6e..3503c7f9 100644 --- a/src/app/pages/client/sidebar/DirectTab.tsx +++ b/src/app/pages/client/sidebar/DirectTab.tsx @@ -1,4 +1,4 @@ -import { MouseEventHandler, forwardRef, useState } from 'react'; +import { MouseEventHandler, forwardRef, useMemo, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Box, Icon, Icons, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; import FocusTrap from 'focus-trap-react'; @@ -25,6 +25,7 @@ import { stopPropagation } from '$utils/keyboard'; import { settingsAtom } from '$state/settings'; import { useSetting } from '$state/hooks/settings'; import { useDirectRooms } from '$pages/client/direct/useDirectRooms'; +import { useSidebarDirectRoomIds } from './useSidebarDirectRoomIds'; type DirectMenuProps = { requestClose: () => void; @@ -68,7 +69,14 @@ export function DirectTab() { const mDirects = useAtomValue(mDirectAtom); const directs = useDirects(mx, allRoomsAtom, mDirects); - const directUnread = useRoomsUnread(directs, roomToUnreadAtom); + const sidebarRoomIds = useSidebarDirectRoomIds(); + // Only count unread for DMs not already shown as individual avatars in the + // sidebar — prevents double-badging (issue #235). + const overflowDirects = useMemo(() => { + const sidebarSet = new Set(sidebarRoomIds); + return directs.filter((id) => !sidebarSet.has(id)); + }, [directs, sidebarRoomIds]); + const directUnread = useRoomsUnread(overflowDirects, roomToUnreadAtom); const [menuAnchor, setMenuAnchor] = useState(); const directSelected = useDirectSelected(); diff --git a/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts b/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts new file mode 100644 index 00000000..8c62d3af --- /dev/null +++ b/src/app/pages/client/sidebar/useSidebarDirectRoomIds.ts @@ -0,0 +1,54 @@ +import { useMemo, useState, useCallback } from 'react'; +import { useAtomValue } from 'jotai'; +import { SyncState } from '$types/matrix-sdk'; +import { useDirects } from '$state/hooks/roomList'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { mDirectAtom } from '$state/mDirectList'; +import { allRoomsAtom } from '$state/room-list/roomList'; +import { roomToUnreadAtom } from '$state/room/roomToUnread'; +import { factoryRoomIdByActivity } from '$utils/sort'; +import { useSyncState } from '$hooks/useSyncState'; + +/** Maximum number of individual DM avatars shown in the sidebar. */ +export const MAX_SIDEBAR_DMS = 3; + +/** + * Returns the room IDs of DMs currently displayed as individual avatars in the + * sidebar `DirectDMsList`. These are the first `MAX_SIDEBAR_DMS` unread DMs + * sorted by recent activity, available only after initial sync completes. + * + * Used by `DirectDMsList` to decide which rooms to render, and by `DirectTab` + * to exclude those rooms from its own badge count (prevents double-badging). + */ +export const useSidebarDirectRoomIds = (): string[] => { + const mx = useMatrixClient(); + const mDirects = useAtomValue(mDirectAtom); + const directs = useDirects(mx, allRoomsAtom, mDirects); + const roomToUnread = useAtomValue(roomToUnreadAtom); + + const [syncReady, setSyncReady] = useState(false); + + useSyncState( + mx, + useCallback((state, prevState) => { + if (state === SyncState.Syncing && prevState !== SyncState.Syncing) { + setSyncReady(true); + } + if (state === SyncState.Syncing || state === SyncState.Catchup) { + setSyncReady(true); + } + }, []) + ); + + return useMemo(() => { + if (!syncReady) return []; + + const withUnread = directs.filter((roomId) => { + const unread = roomToUnread.get(roomId); + return unread && (unread.total > 0 || unread.highlight > 0); + }); + + const sorted = withUnread.sort(factoryRoomIdByActivity(mx)); + return sorted.slice(0, MAX_SIDEBAR_DMS); + }, [directs, mx, roomToUnread, syncReady]); +}; diff --git a/src/app/plugins/call/CallEmbed.ts b/src/app/plugins/call/CallEmbed.ts index 570b66f7..960f21ce 100644 --- a/src/app/plugins/call/CallEmbed.ts +++ b/src/app/plugins/call/CallEmbed.ts @@ -218,11 +218,24 @@ export class CallEmbed { this.readUpToMap[room.roomId] = roomEvent.getId()!; }); - // Attach listeners for feeding events - the underlying widget classes handle permissions for us - this.mx.on(ClientEvent.Event, this.onEvent.bind(this)); - this.mx.on(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); - this.mx.on(RoomStateEvent.Events, this.onStateUpdate.bind(this)); - this.mx.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); + // Attach listeners for feeding events - the underlying widget classes handle permissions for us. + // Bind once and store via disposables so the same function reference is used for removal. + // Using .bind(this) at call-site would create a new function every time, making .off() a no-op + // and causing MaxListeners warnings when the embed is recreated during sync retries. + const boundOnEvent = this.onEvent.bind(this); + const boundOnEventDecrypted = this.onEventDecrypted.bind(this); + const boundOnStateUpdate = this.onStateUpdate.bind(this); + const boundOnToDeviceEvent = this.onToDeviceEvent.bind(this); + this.mx.on(ClientEvent.Event, boundOnEvent); + this.mx.on(MatrixEventEvent.Decrypted, boundOnEventDecrypted); + this.mx.on(RoomStateEvent.Events, boundOnStateUpdate); + this.mx.on(ClientEvent.ToDeviceEvent, boundOnToDeviceEvent); + this.disposables.push(() => { + this.mx.off(ClientEvent.Event, boundOnEvent); + this.mx.off(MatrixEventEvent.Decrypted, boundOnEventDecrypted); + this.mx.off(RoomStateEvent.Events, boundOnStateUpdate); + this.mx.off(ClientEvent.ToDeviceEvent, boundOnToDeviceEvent); + }); } /** @@ -239,11 +252,7 @@ export class CallEmbed { this.container.removeChild(this.iframe); this.control.dispose(); - this.mx.off(ClientEvent.Event, this.onEvent.bind(this)); - this.mx.off(MatrixEventEvent.Decrypted, this.onEventDecrypted.bind(this)); - this.mx.off(RoomStateEvent.Events, this.onStateUpdate.bind(this)); - this.mx.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent.bind(this)); - + // Listener removal is handled by the disposables pushed in start(). // Clear internal state this.readUpToMap = {}; this.eventsToFeed = new WeakSet(); diff --git a/src/app/utils/debugLogger.ts b/src/app/utils/debugLogger.ts index c00db022..1e1c7e74 100644 --- a/src/app/utils/debugLogger.ts +++ b/src/app/utils/debugLogger.ts @@ -162,24 +162,25 @@ class DebugLoggerService { const sentryLevel: Sentry.SeverityLevel = sentryLevelMap[entry.level] ?? 'error'; // Add breadcrumb for all logs (helps with debugging in Sentry), unless category is disabled - if (!this.disabledBreadcrumbCategories.has(entry.category)) Sentry.addBreadcrumb({ - category: `${entry.category}.${entry.namespace}`, - message: entry.message, - level: sentryLevel, - data: entry.data ? { data: entry.data } : undefined, - timestamp: entry.timestamp / 1000, // Sentry expects seconds - }); + if (!this.disabledBreadcrumbCategories.has(entry.category)) + Sentry.addBreadcrumb({ + category: `${entry.category}.${entry.namespace}`, + message: entry.message, + level: sentryLevel, + data: entry.data ? { data: entry.data } : undefined, + timestamp: entry.timestamp / 1000, // Sentry expects seconds + }); // Send as structured log to the Sentry Logs product (requires enableLogs: true) const logMsg = `[${entry.category}:${entry.namespace}] ${entry.message}`; // Flatten primitive values from entry.data so they become searchable attributes in Sentry Logs const logDataAttrs: Record = {}; if (entry.data && typeof entry.data === 'object' && !(entry.data instanceof Error)) { - for (const [k, v] of Object.entries(entry.data)) { + Object.entries(entry.data).forEach(([k, v]) => { if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') { logDataAttrs[k] = v; } - } + }); } const logAttrs = { category: entry.category, namespace: entry.namespace, ...logDataAttrs }; if (entry.level === 'debug') Sentry.logger.debug(logMsg, logAttrs); diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index abc15597..f04f71d9 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -18,8 +18,8 @@ import to from 'await-to-js'; import { IImageInfo, IThumbnailContent, IVideoInfo } from '$types/matrix/common'; import { AccountDataEvent } from '$types/matrix/accountData'; import { Membership, MessageEvent, StateEvent } from '$types/matrix/room'; -import { getEventReactions, getReactionContent, getStateEvent } from './room'; import * as Sentry from '@sentry/react'; +import { getEventReactions, getReactionContent, getStateEvent } from './room'; const DOMAIN_REGEX = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/; @@ -177,9 +177,13 @@ export const uploadContent = async ( const mxc = data.content_uri; if (mxc) { const mediaType = file.type.split('/')[0] || 'unknown'; - Sentry.metrics.distribution('sable.media.upload_latency_ms', performance.now() - uploadStart, { - attributes: { type: mediaType }, - }); + Sentry.metrics.distribution( + 'sable.media.upload_latency_ms', + performance.now() - uploadStart, + { + attributes: { type: mediaType }, + } + ); Sentry.metrics.distribution('sable.media.upload_bytes', file.size, { attributes: { type: mediaType }, }); diff --git a/src/instrument.ts b/src/instrument.ts index 9efec360..29e599de 100644 --- a/src/instrument.ts +++ b/src/instrument.ts @@ -27,6 +27,55 @@ const SESSION_ERROR_LIMIT = 50; const sentryEnabled = localStorage.getItem('sable_sentry_enabled') !== 'false'; const replayEnabled = localStorage.getItem('sable_sentry_replay_enabled') === 'true'; +/** + * Scrub Matrix-specific identifiers from URLs that appear in Sentry spans, breadcrumbs, + * transaction names, and page URLs. Covers both Matrix API paths and client-side app routes. + * Room IDs, user IDs, event IDs, media paths, and deep-link parameters are replaced with + * safe placeholders so no PII leaks into Sentry. + */ +function scrubMatrixUrl(url: string): string { + return ( + url + // ── Matrix Client-Server API paths ────────────────────────────────────────────── + // /rooms/!roomId:server/... + .replace(/\/rooms\/![^/?#\s]*/g, '/rooms/![ROOM_ID]') + // /event/$eventId and /relations/$eventId + .replace(/\/event\/(?:\$|%24)[^/?#\s]*/g, '/event/$[EVENT_ID]') + .replace(/\/relations\/(?:\$|%24)[^/?#\s]*/g, '/relations/$[EVENT_ID]') + // /profile/@user:server or /profile/%40user%3Aserver + .replace(/\/profile\/(?:%40|@)[^/?#\s]*/gi, '/profile/[USER_ID]') + // /user/@user:server/... and /presence/@user:server/status + .replace(/\/(user|presence)\/(?:%40|@)[^/?#\s]*/gi, '/$1/[USER_ID]') + // /room_keys/keys/{version}/{roomId}/{sessionId} + .replace(/\/room_keys\/keys\/[^/?#\s]*/gi, '/room_keys/keys/[REDACTED]') + // /sendToDevice/{eventType}/{txnId} + .replace(/\/sendToDevice\/([^/?#\s]+)\/[^/?#\s]+/gi, '/sendToDevice/$1/[TXN_ID]') + // Media – MSC3916 (/media/thumbnail|download/{server}/{mediaId}) and legacy (v1/v3) + .replace( + /(\/media\/(?:thumbnail|download)\/)(?:[^/?#\s]+)\/(?:[^/?#\s]+)/gi, + '$1[SERVER]/[MEDIA_ID]' + ) + .replace( + /(\/media\/v\d+\/(?:thumbnail|download)\/)(?:[^/?#\s]+)\/(?:[^/?#\s]+)/gi, + '$1[SERVER]/[MEDIA_ID]' + ) + // ── App route path segments ───────────────────────────────────────────────────── + // Bare Matrix room/space IDs in URL segments: /!roomId:server/ + .replace(/\/![^/?#\s:]+:[^/?#\s]*/g, '/![ROOM_ID]') + // Bare Matrix user IDs in URL segments: /@user:server/ + .replace(/\/@[^/?#\s:]+:[^/?#\s]*/g, '/@[USER_ID]') + // ── Deep-link push notification URLs (percent-encoded) ───────────────────────── + // URL-encoded user IDs: /%40user%3Aserver (%40 = @) + .replace(/\/%40[^/?#\s]*/gi, '/[USER_ID]') + // URL-encoded room IDs: /%21room%3Aserver (%21 = !) + .replace(/\/%21[^/?#\s]*/gi, '/![ROOM_ID]') + // ── Preview URL endpoint ──────────────────────────────────────────────────────── + // The ?url= query parameter on preview_url contains the full external URL being + // previewed — strip the entire query string so browsing habits cannot be inferred. + .replace(/(\/preview_url)\?[^#\s]*/gi, '$1') + ); +} + // Only initialize if DSN is provided and user hasn't opted out if (dsn && sentryEnabled) { Sentry.init({ @@ -67,7 +116,8 @@ if (dsn && sentryEnabled) { tracesSampleRate: environment === 'development' || environment === 'preview' ? 1.0 : 0.1, // Browser profiling — profiles every sampled session (requires Document-Policy: js-profiling response header) - profileSessionSampleRate: environment === 'development' || environment === 'preview' ? 1.0 : 0.1, + profileSessionSampleRate: + environment === 'development' || environment === 'preview' ? 1.0 : 0.1, // Control which URLs get distributed tracing headers tracePropagationTargets: [ @@ -108,27 +158,84 @@ if (dsn && sentryEnabled) { // Rate limiting: cap error events per page-load session to avoid quota exhaustion. // Separate counters for errors and transactions so perf traces do not drain the error budget. beforeSendTransaction(event) { + // Scrub Matrix identifiers from the transaction name (the matched route or page URL). + // React Router normally parameterises routes (e.g. /home/:roomIdOrAlias/) but falls + // back to the raw URL when matching fails, so we scrub defensively here. + if (event.transaction) { + // eslint-disable-next-line no-param-reassign + event.transaction = scrubMatrixUrl(event.transaction); + } + + // Scrub Matrix identifiers from HTTP span descriptions and data URLs + if (event.spans) { + // eslint-disable-next-line no-param-reassign + event.spans = event.spans.map((span) => { + const newDesc = span.description ? scrubMatrixUrl(span.description) : span.description; + const spanData = span.data as Record | undefined; + const spanHttpUrl = spanData?.['http.url']; + const rawHttpUrl = typeof spanHttpUrl === 'string' ? spanHttpUrl : undefined; + const newHttpUrl = rawHttpUrl ? scrubMatrixUrl(rawHttpUrl) : undefined; + + const descChanged = newDesc !== span.description; + const urlChanged = newHttpUrl !== undefined && newHttpUrl !== rawHttpUrl; + + if (!descChanged && !urlChanged) return span; + return { + ...span, + ...(descChanged ? { description: newDesc } : {}), + ...(urlChanged ? { data: { ...spanData, 'http.url': newHttpUrl } } : {}), + }; + }); + } return event; }, - // Sanitize sensitive data from all breadcrumb messages before sending to Sentry + // Sanitize sensitive data from all breadcrumb messages and HTTP data URLs before sending to Sentry beforeBreadcrumb(breadcrumb) { - if (!breadcrumb.message) return breadcrumb; - // Always apply redaction — both token values and Matrix entity IDs. + // Scrub Matrix paths from HTTP breadcrumb data.url (captures full request URLs) + const bData = breadcrumb.data as Record | undefined; + const rawUrl = typeof bData?.url === 'string' ? bData.url : undefined; + const scrubbedUrl = rawUrl ? scrubMatrixUrl(rawUrl) : undefined; + const urlChanged = scrubbedUrl !== undefined && scrubbedUrl !== rawUrl; + + // Scrub Matrix paths from navigation breadcrumb data.from / data.to (page URLs that + // may contain room IDs or user IDs as path segments in the app's client-side routes) + const rawFrom = typeof bData?.from === 'string' ? bData.from : undefined; + const rawTo = typeof bData?.to === 'string' ? bData.to : undefined; + const scrubbedFrom = rawFrom ? scrubMatrixUrl(rawFrom) : undefined; + const scrubbedTo = rawTo ? scrubMatrixUrl(rawTo) : undefined; + const fromChanged = scrubbedFrom !== undefined && scrubbedFrom !== rawFrom; + const toChanged = scrubbedTo !== undefined && scrubbedTo !== rawTo; + + // Scrub message text — token values and Matrix entity IDs // Do NOT use single-character patterns like '@', '!', '$' as they are far too broad. - const redacted = breadcrumb.message - // Redact token key=value pairs (e.g. access_token=abc123) - .replace( - /(access_token|password|refresh_token|device_id|session_id|sync_token|next_batch)([=:\s]+)([^\s&"']+)/gi, - '$1$2[REDACTED]' - ) - // Redact full Matrix user IDs: @localpart:server.tld - .replace(/@[^\s:@]+:[^\s,'"(){}\[\]]+/g, '@[USER_ID]') - // Redact full Matrix room IDs: !opaque:server.tld - .replace(/![^\s:]+:[^\s,'"(){}\[\]]+/g, '![ROOM_ID]') - // Redact Matrix event IDs: $base64Url (at least 10 chars to avoid false positives) - .replace(/\$[A-Za-z0-9\-_+/]{10,}/g, '$[EVENT_ID]'); - return redacted === breadcrumb.message ? breadcrumb : { ...breadcrumb, message: redacted }; + const message = breadcrumb.message + ? breadcrumb.message + .replace( + /(access_token|password|refresh_token|device_id|session_id|sync_token|next_batch)([=:\s]+)([^\s&"']+)/gi, + '$1$2[REDACTED]' + ) + .replace(/@[^\s:@]+:[^\s,'"(){}[\]]+/g, '@[USER_ID]') + .replace(/![^\s:]+:[^\s,'"(){}[\]]+/g, '![ROOM_ID]') + .replace(/\$[A-Za-z0-9_+/-]{10,}/g, '$[EVENT_ID]') + : breadcrumb.message; + const messageChanged = message !== breadcrumb.message; + + if (!messageChanged && !urlChanged && !fromChanged && !toChanged) return breadcrumb; + return { + ...breadcrumb, + ...(messageChanged ? { message } : {}), + ...(urlChanged || fromChanged || toChanged + ? { + data: { + ...bData, + ...(urlChanged ? { url: scrubbedUrl } : {}), + ...(fromChanged ? { from: scrubbedFrom } : {}), + ...(toChanged ? { to: scrubbedTo } : {}), + }, + } + : {}), + }; }, beforeSend(event, hint) { @@ -191,6 +298,11 @@ if (dsn && sentryEnabled) { exception.value = exception.value.replace(/![^:]+:[^\s]+/g, '![ROOM_ID]'); // eslint-disable-next-line no-param-reassign exception.value = exception.value.replace(/\$[^:\s]+/g, '$[EVENT_ID]'); + // Scrub Matrix URL patterns embedded in error message strings + // (e.g. MatrixError: "Got error 403 (https://.../preview_url?url=https://...)" + // or paths containing room/user/event IDs) + // eslint-disable-next-line no-param-reassign + exception.value = scrubMatrixUrl(exception.value); } }); } @@ -198,12 +310,21 @@ if (dsn && sentryEnabled) { // Scrub request data if (event.request?.url) { // eslint-disable-next-line no-param-reassign - event.request.url = event.request.url.replace( - /(access_token|password|token)([=:]\s*)([^\s&]+)/gi, - '$1$2[REDACTED]' + event.request.url = scrubMatrixUrl( + event.request.url.replace( + /(access_token|password|token)([=:]\s*)([^\s&]+)/gi, + '$1$2[REDACTED]' + ) ); } + // Scrub the transaction name on error events (set when the error occurred during a + // page-load or navigation transaction — raw URL leaks here when route matching fails) + if (event.transaction) { + // eslint-disable-next-line no-param-reassign + event.transaction = scrubMatrixUrl(event.transaction); + } + if (event.request?.headers) { const headers = event.request.headers as Record; if (headers.Authorization) {