feat(sentry): comprehensive data scrubbing, settings UI, and privacy policy

Before-send scrubbing in instrument.ts covers:
- Matrix user IDs (@user:server → @[USER_ID])
- Room IDs (!room:server → ![ROOM_ID])
- Event IDs ($event → $[EVENT_ID])
- Percent-encoded sigils (%40, %21, %24, %23)
- Hybrid-encoded forms (decoded sigil + %3A colon)
- Tokens, credentials, and query params (access_token, next_batch, etc.)
- All span data string values (not just http.url)
- Profile URLs, key backup paths, media paths in span data
- preview_url query params and exception values
- 'none' sentinel for unset room tags

Privacy policy added to docs/PRIVACY.md (linked from General settings).
DiagnosticsAndPrivacy component added to General settings with error
reporting and session replay toggles.
TS2367 redundant phase guard removed from useCallSignaling.ts.
This commit is contained in:
Evie Gauthier committed 2026-03-15 23:40:58 -04:00
1 parent 36c4e0591b
commit 4e539b91ca
21 files changed
+896 -399

No files matched your search

@@ -0,0 +1,5 @@
---
default: patch
---
Fix duplicate unread badges on the /direct/ icon for DM rooms already shown as individual sidebar avatars
@@ -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.
@@ -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
+116
View File
@@ -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: **[email protected]**
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 **[email protected]** 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 **[email protected]**.
+82 -12
View File
@@ -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://[email protected]/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://[email protected]/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
+88 -88
View File
@@ -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
+6 -2
View File
@@ -75,7 +75,9 @@ export function ErrorPage({ error, eventId }: ErrorPageProps) {
</Button>
<Button
variant="Secondary"
onClick={() => window.open(createIssueUrl(error), '_blank', 'noopener noreferrer')}
onClick={() =>
window.open(createIssueUrl(error), '_blank', 'noopener noreferrer')
}
fill="None"
title="Opens a pre-filled GitHub issue as an alternative reporting method."
>
@@ -87,7 +89,9 @@ export function ErrorPage({ error, eventId }: ErrorPageProps) {
) : (
<Button
variant="Secondary"
onClick={() => window.open(createIssueUrl(error), '_blank', 'noopener noreferrer')}
onClick={() =>
window.open(createIssueUrl(error), '_blank', 'noopener noreferrer')
}
fill="Solid"
title="Clicking this button will open a new issue on our GitHub repository with the error details pre-filled. Please review the information before submitting."
>
+47 -8
View File
@@ -14,6 +14,7 @@ import { isKeyHotkey } from 'is-hotkey';
import {
EventType,
IContent,
MatrixEvent,
MsgType,
RelationType,
Room,
@@ -114,6 +115,7 @@ import { settingsAtom } from '$state/settings';
import {
getMemberDisplayName,
getMentionContent,
reactionOrEditEvent,
trimReplyFromBody,
trimReplyFromFormattedBody,
} from '$utils/room';
@@ -131,6 +133,7 @@ import { createLogger } from '$utils/debug';
import { createDebugLogger } from '$utils/debugLogger';
import FocusTrap from 'focus-trap-react';
import { useQueryClient } from '@tanstack/react-query';
import * as Sentry from '@sentry/react';
import {
delayedEventsSupportedAtom,
roomIdToScheduledTimeAtomFamily,
@@ -151,7 +154,6 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions';
import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice';
import { SchedulePickerDialog } from './schedule-send';
import * as css from './schedule-send/SchedulePickerDialog.css';
import * as Sentry from '@sentry/react';
import {
getAudioMsgContent,
getFileMsgContent,
@@ -161,7 +163,33 @@ import {
import { CommandAutocomplete } from './CommandAutocomplete';
import { AudioMessageRecorder } from './AudioMessageRecorder';
const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => {
// Returns the event ID of the most recent non-reaction/non-edit event in a thread,
// falling back to the thread root if no replies exist yet.
const getLatestThreadEventId = (room: Room, threadRootId: string): string => {
const thread = room.getThread(threadRootId);
const threadEvents: MatrixEvent[] = thread?.events ?? [];
const filtered = threadEvents.filter(
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
if (filtered.length > 0) {
return filtered[filtered.length - 1].getId() ?? threadRootId;
}
// Fall back to the live timeline if the Thread object hasn't been registered yet
const liveEvents = room
.getUnfilteredTimelineSet()
.getLiveTimeline()
.getEvents()
.filter(
(ev) =>
ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
if (liveEvents.length > 0) {
return liveEvents[liveEvents.length - 1].getId() ?? threadRootId;
}
return threadRootId;
};
const getReplyContent = (replyDraft: IReplyDraft | undefined, room?: Room): IEventRelation => {
if (!replyDraft) return {};
const relatesTo: IEventRelation = {};
@@ -174,13 +202,19 @@ const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation =>
// Check if this is a reply to a specific message in the thread
// (replyDraft.body being empty means it's just a seeded thread draft)
if (replyDraft.body && replyDraft.eventId !== replyDraft.relation.event_id) {
// This is a reply to a message within the thread
// Explicit reply to a specific message — per spec, is_falling_back must be false
relatesTo['m.in_reply_to'] = {
event_id: replyDraft.eventId,
};
relatesTo.is_falling_back = false;
} else {
// This is just a regular thread message
// Regular thread message — per spec, include fallback m.in_reply_to pointing to the
// most recent thread message so unthreaded clients can display it as a reply chain
const threadRootId = replyDraft.relation.event_id ?? replyDraft.eventId;
const latestEventId = room ? getLatestThreadEventId(room, threadRootId) : threadRootId;
relatesTo['m.in_reply_to'] = {
event_id: latestEventId,
};
relatesTo.is_falling_back = true;
}
} else {
@@ -462,7 +496,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises));
if (contents.length > 0) {
const replyContent = plainText?.length === 0 ? getReplyContent(replyDraft) : undefined;
const replyContent =
plainText?.length === 0 ? getReplyContent(replyDraft, room) : undefined;
if (replyContent) contents[0]['m.relates_to'] = replyContent;
if (threadRootId) {
setReplyDraft({
@@ -606,7 +641,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
content.formatted_body = formattedBody;
}
if (replyDraft) {
content['m.relates_to'] = getReplyContent(replyDraft);
content['m.relates_to'] = getReplyContent(replyDraft, room);
}
const invalidate = () =>
queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] });
@@ -670,7 +705,11 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
resetInput();
debugLog.info('message', 'Sending message', { roomId, msgtype: (content as any).msgtype });
Sentry.startSpan(
{ name: 'message.send', op: 'matrix.message', attributes: { encrypted: String(isEncrypted) } },
{
name: 'message.send',
op: 'matrix.message',
attributes: { encrypted: String(isEncrypted) },
},
() => mx.sendMessage(roomId, threadRootId ?? null, content as any)
)
.then((res) => {
@@ -805,7 +844,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
info,
};
if (replyDraft) {
content['m.relates_to'] = getReplyContent(replyDraft);
content['m.relates_to'] = getReplyContent(replyDraft, room);
if (threadRootId) {
setReplyDraft({
userId: mx.getUserId() ?? '',
+96 -37
View File
@@ -481,6 +481,12 @@ const useTimelinePagination = (
};
const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) => {
// Stable ref so the effect dep array only contains `room`. The listener is
// registered once per room mount; onArrive can change freely without causing
// listener churn during rapid re-renders (e.g. sync error/retry cycles).
const onArriveRef = useRef(onArrive);
onArriveRef.current = onArrive;
useEffect(() => {
// Capture the live timeline and registration time. Events appended to the
// live timeline AFTER this point can be genuinely new even when
@@ -507,14 +513,14 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void)
data.timeline === liveTimeline &&
mEvent.getTs() >= registeredAt - 60_000);
if (!isLive) return;
onArrive(mEvent);
onArriveRef.current(mEvent);
};
const handleRedaction: RoomEventHandlerMap[RoomEvent.Redaction] = (
mEvent: MatrixEvent,
eventRoom: Room | undefined
) => {
if (eventRoom?.roomId !== room.roomId) return;
onArrive(mEvent);
onArriveRef.current(mEvent);
};
room.on(RoomEvent.Timeline, handleTimelineEvent);
@@ -523,10 +529,13 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void)
room.removeListener(RoomEvent.Timeline, handleTimelineEvent);
room.removeListener(RoomEvent.Redaction, handleRedaction);
};
}, [room, onArrive]);
}, [room]); // stable: re-register only when room changes, not on callback identity changes
};
const useRelationUpdate = (room: Room, onRelation: () => void) => {
const onRelationRef = useRef(onRelation);
onRelationRef.current = onRelation;
useEffect(() => {
const handleTimelineEvent: EventTimelineSetHandlerMap[RoomEvent.Timeline] = (
mEvent: MatrixEvent,
@@ -540,42 +549,61 @@ const useRelationUpdate = (room: Room, onRelation: () => void) => {
// also need to trigger a re-render so makeReplaced state is reflected.
if (eventRoom?.roomId !== room.roomId || data.liveEvent) return;
if (mEvent.getRelation()?.rel_type === RelationType.Replace) {
onRelation();
onRelationRef.current();
}
};
room.on(RoomEvent.Timeline, handleTimelineEvent);
return () => {
room.removeListener(RoomEvent.Timeline, handleTimelineEvent);
};
}, [room, onRelation]);
}, [room]);
};
const useLiveTimelineRefresh = (room: Room, onRefresh: () => void) => {
const onRefreshRef = useRef(onRefresh);
onRefreshRef.current = onRefresh;
useEffect(() => {
const handleTimelineRefresh: RoomEventHandlerMap[RoomEvent.TimelineRefresh] = (r: Room) => {
if (r.roomId !== room.roomId) return;
onRefresh();
onRefreshRef.current();
};
// The SDK fires RoomEvent.TimelineReset on the EventTimelineSet (not the Room)
// when a limited sliding-sync response replaces the live EventTimeline with a
// fresh one. Without this handler, the stored linkedTimelines reference the old
// detached chain and back-pagination silently no-ops, freezing the room.
const handleTimelineReset: EventTimelineSetHandlerMap[RoomEvent.TimelineReset] = () => {
onRefreshRef.current();
};
const unfilteredTimelineSet = room.getUnfilteredTimelineSet();
room.on(RoomEvent.TimelineRefresh, handleTimelineRefresh);
unfilteredTimelineSet.on(RoomEvent.TimelineReset, handleTimelineReset);
return () => {
room.removeListener(RoomEvent.TimelineRefresh, handleTimelineRefresh);
unfilteredTimelineSet.removeListener(RoomEvent.TimelineReset, handleTimelineReset);
};
}, [room, onRefresh]);
}, [room]);
};
// Trigger re-render when thread reply counts change so the thread chip updates.
const useThreadUpdate = (room: Room, onUpdate: () => void) => {
const onUpdateRef = useRef(onUpdate);
onUpdateRef.current = onUpdate;
useEffect(() => {
room.on(ThreadEvent.New, onUpdate);
room.on(ThreadEvent.Update, onUpdate);
room.on(ThreadEvent.NewReply, onUpdate);
// Stable wrapper: the same function identity is kept for the lifetime of
// the room so add/removeListener calls always match.
const handler = () => onUpdateRef.current();
room.on(ThreadEvent.New, handler);
room.on(ThreadEvent.Update, handler);
room.on(ThreadEvent.NewReply, handler);
return () => {
room.removeListener(ThreadEvent.New, onUpdate);
room.removeListener(ThreadEvent.Update, onUpdate);
room.removeListener(ThreadEvent.NewReply, onUpdate);
room.removeListener(ThreadEvent.New, handler);
room.removeListener(ThreadEvent.Update, handler);
room.removeListener(ThreadEvent.NewReply, handler);
};
}, [room, onUpdate]);
}, [room]);
};
// Returns the number of replies in a thread, counting actual reply events
@@ -786,6 +814,10 @@ export function RoomTimeline({
const imagePackRooms: Room[] = useImagePackRooms(room.roomId, roomToParents);
const [unreadInfo, setUnreadInfo] = useState(() => getRoomUnreadInfo(room, true));
// Stable ref so listeners that only need to *read* unreadInfo don't force
// effect re-registration (and listener churn) every time a new message arrives.
const unreadInfoRef = useRef(unreadInfo);
unreadInfoRef.current = unreadInfo;
const readUptoEventIdRef = useRef<string>();
if (unreadInfo) {
readUptoEventIdRef.current = unreadInfo.readUptoEventId;
@@ -800,6 +832,12 @@ export function RoomTimeline({
atBottomRef.current = val;
}, []);
// Set to true by the useLiveTimelineRefresh callback when the timeline is
// re-initialised (TimelineRefresh or TimelineReset). Allows the range self-heal
// effect below to run even when atBottom=false, so the virtual paginator window
// is restored to the live end without forcing a viewport scroll.
const timelineJustResetRef = useRef(false);
const scrollRef = useRef<HTMLDivElement>(null);
const scrollToBottomRef = useRef({
count: 0,
@@ -986,14 +1024,17 @@ export function RoomTimeline({
// otherwise we update timeline without paginating
// so timeline can be updated with evt like: edits, reactions etc
if (atBottomRef.current && atLiveEndRef.current) {
if (document.hasFocus() && (!unreadInfo || mEvt.getSender() === mx.getUserId())) {
if (
document.hasFocus() &&
(!unreadInfoRef.current || mEvt.getSender() === mx.getUserId())
) {
// Check if the document is in focus (user is actively viewing the app),
// and either there are no unread messages or the latest message is from the current user.
// If either condition is met, trigger the markAsRead function to send a read receipt.
requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideReads));
}
if (!document.hasFocus() && !unreadInfo) {
if (!document.hasFocus() && !unreadInfoRef.current) {
setUnreadInfo(getRoomUnreadInfo(room));
}
@@ -1012,11 +1053,11 @@ export function RoomTimeline({
return;
}
setTimeline((ct) => ({ ...ct }));
if (!unreadInfo) {
if (!unreadInfoRef.current) {
setUnreadInfo(getRoomUnreadInfo(room));
}
},
[mx, room, unreadInfo, hideReads]
[mx, room, hideReads]
)
);
@@ -1030,7 +1071,7 @@ export function RoomTimeline({
Sentry.metrics.count('sable.message.send_failed', 1);
}
setTimeline((ct) => ({ ...ct }));
if (!unreadInfo) {
if (!unreadInfoRef.current) {
setUnreadInfo(getRoomUnreadInfo(room));
}
};
@@ -1039,7 +1080,7 @@ export function RoomTimeline({
return () => {
room.removeListener(RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated);
};
}, [room, unreadInfo, setTimeline, setUnreadInfo]);
}, [room, setTimeline, setUnreadInfo]);
const handleOpenEvent = useCallback(
async (
@@ -1090,18 +1131,20 @@ export function RoomTimeline({
useLiveTimelineRefresh(
room,
useCallback(() => {
// Always reinitialize on TimelineRefresh. With sliding sync, a limited
// response replaces the room's live EventTimeline with a brand-new object,
// firing TimelineRefresh. At that moment liveTimelineLinked is stale-false
// (the stored linkedTimelines still reference the old detached object),
// so the previous guard `if (liveTimelineLinked || ...)` would silently
// skip reinit. Back-pagination then calls paginateEventTimeline against
// the dead old timeline, which no-ops, and the IntersectionObserver never
// re-fires because intersection state didn't change — causing a permanent
// hang at the top of the timeline with no spinner and no history loaded.
// Unconditionally reinitializing is correct: TimelineRefresh signals that
// the SDK has replaced the timeline chain, so any stored range/indices
// against the old chain are invalid anyway.
// Always reinitialize on TimelineRefresh/TimelineReset. With sliding sync,
// a limited response replaces the room's live EventTimeline with a brand-new
// object. At that moment liveTimelineLinked is stale-false (stored
// linkedTimelines reference the old detached chain), so any guard on that
// flag would skip reinit, causing back-pagination to no-op silently and the
// room to appear frozen. Unconditional reinit is correct: both events signal
// that stored range/indices against the old chain are invalid.
//
// Only force the viewport to the bottom if the user was already there.
// When the user has scrolled up to read history and a sync gap fires, we
// must still reinit (the old timeline is gone), but scrolling them back to
// the bottom is jarring. Instead we set timelineJustResetRef=true so the
// self-heal effect below can advance the range as events arrive on the fresh
// timeline, without atBottom=true being required.
//
// Also force atBottom=true and queue a scroll-to-bottom. The SDK fires
// TimelineRefresh before adding new events to the fresh live timeline, so
@@ -1113,11 +1156,19 @@ export function RoomTimeline({
// correct: TimelineRefresh always reinits to the live end, so the user
// should be repositioned to the bottom regardless.
Sentry.metrics.count('sable.timeline.reinit', 1);
// When the user WAS at the bottom we still call setAtBottom(true) so a
// transient isIntersecting=false from the IntersectionObserver during the
// DOM transition cannot stick the "Jump to Latest" button on-screen.
debugLog.info('timeline', 'Live timeline refresh triggered', { roomId: room.roomId });
const wasAtBottom = atBottomRef.current;
timelineJustResetRef.current = true;
setTimeline(getInitialTimeline(room));
setAtBottom(true);
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = false;
if (wasAtBottom) {
setAtBottom(true);
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = false;
}
}, [room, setAtBottom])
);
@@ -1144,9 +1195,17 @@ export function RoomTimeline({
// position we want to display. Without this, loading more history makes it look
// like we've scrolled up because the range (0, 10) is now showing the old events
// instead of the latest ones.
//
// Also runs after a timeline reset (timelineJustResetRef=true) even when
// atBottom=false. After TimelineReset the SDK fires the event before populating
// the fresh timeline, so getInitialTimeline sees range.end=0. When events
// arrive eventsLength grows and we need to heal the range back to the live end
// regardless of the user's scroll position.
useEffect(() => {
if (atBottom && liveTimelineLinked && eventsLength > timeline.range.end) {
// More events exist than our current range shows. Adjust to stay at bottom.
const resetPending = timelineJustResetRef.current;
if ((atBottom || resetPending) && liveTimelineLinked && eventsLength > timeline.range.end) {
if (resetPending) timelineJustResetRef.current = false;
// More events exist than our current range shows. Adjust to the live end.
setTimeline((ct) => ({
...ct,
range: {
@@ -18,13 +18,6 @@ const ALL_CATEGORIES: LogCategory[] = [
];
export function SentrySettings() {
const [sentryEnabled, setSentryEnabled] = useState(
localStorage.getItem('sable_sentry_enabled') !== 'false'
);
const [sessionReplayEnabled, setSessionReplayEnabled] = useState(
localStorage.getItem('sable_sentry_replay_enabled') === 'true'
);
const [needsRefresh, setNeedsRefresh] = useState(false);
const [categoryEnabled, setCategoryEnabled] = useState<Record<LogCategory, boolean>>(() => {
const logger = getDebugLogger();
return Object.fromEntries(
@@ -40,26 +33,6 @@ export function SentrySettings() {
return () => clearInterval(interval);
}, []);
const handleSentryToggle = (enabled: boolean) => {
setSentryEnabled(enabled);
if (enabled) {
localStorage.removeItem('sable_sentry_enabled');
} else {
localStorage.setItem('sable_sentry_enabled', 'false');
}
setNeedsRefresh(true);
};
const handleReplayToggle = (enabled: boolean) => {
setSessionReplayEnabled(enabled);
if (enabled) {
localStorage.setItem('sable_sentry_replay_enabled', 'true');
} else {
localStorage.removeItem('sable_sentry_replay_enabled');
}
setNeedsRefresh(true);
};
const handleCategoryToggle = (category: LogCategory, enabled: boolean) => {
getDebugLogger().setBreadcrumbCategoryEnabled(category, enabled);
setCategoryEnabled((prev) => ({ ...prev, [category]: enabled }));
@@ -77,6 +50,7 @@ export function SentrySettings() {
};
const isSentryConfigured = Boolean(import.meta.env.VITE_SENTRY_DSN);
const sentryEnabled = localStorage.getItem('sable_sentry_enabled') !== 'false';
const environment = import.meta.env.VITE_SENTRY_ENVIRONMENT || import.meta.env.MODE;
const isProd = environment === 'production';
const traceSampleRate = isProd ? '10%' : '100%';
@@ -85,19 +59,9 @@ export function SentrySettings() {
return (
<Box direction="Column" gap="100">
<Text size="L400">Error Tracking (Sentry)</Text>
{needsRefresh && (
<Box
style={{
padding: '12px',
backgroundColor: 'rgba(33, 150, 243, 0.1)',
borderRadius: '8px',
}}
>
<Text size="T300" style={{ color: 'rgb(33, 150, 243)' }}>
Please refresh the page for Sentry settings to take effect.
</Text>
</Box>
)}
<Text size="T200" style={{ opacity: 0.7 }}>
Error reporting toggles are in <strong>Settings → General → Diagnostics & Privacy</strong>.
</Text>
{!isSentryConfigured && (
<Box
style={{
@@ -111,57 +75,6 @@ export function SentrySettings() {
</Text>
</Box>
)}
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Enable Sentry Error Tracking"
description={
isSentryConfigured
? 'Send anonymous error reports to help improve Sable. No personal data is sent.'
: 'Error tracking is not configured for this instance.'
}
after={
<Switch
variant="Primary"
value={sentryEnabled}
onChange={handleSentryToggle}
disabled={!isSentryConfigured}
/>
}
/>
{sentryEnabled && isSentryConfigured && (
<>
<SettingTile
title="Enable Session Replay"
description={`Record sessions for debugging errors. All text, media, and inputs are FULLY MASKED for privacy. ${environment === 'development' || environment === 'preview' ? 'Records 100% of sessions in dev/preview.' : 'Records 10% of sessions in production, 100% on errors.'}`}
after={
<Switch
variant="Primary"
value={sessionReplayEnabled}
onChange={handleReplayToggle}
/>
}
/>
</>
)}
</SequenceCard>
{isSentryConfigured && (
<Box direction="Column" gap="100">
<Text size="T200" style={{ opacity: 0.7 }}>
All data sent to Sentry is filtered for sensitive information like passwords and access
tokens. You can opt out at any time.
</Text>
<Text size="T200" style={{ opacity: 0.7 }}>
<strong>Session Replay Privacy:</strong> When enabled, all text content, media
(images/video/audio), and form inputs are completely masked or blocked. Only UI
structure and interactions are recorded.
</Text>
</Box>
)}
{isSentryConfigured && sentryEnabled && (
<>
@@ -182,7 +95,7 @@ export function SentrySettings() {
/>
<SettingTile
title="Session Error Budget"
description={`At most 50 error events are forwarded to Sentry per page load to prevent quota exhaustion.`}
description="At most 50 error events are forwarded to Sentry per page load to prevent quota exhaustion."
/>
</SequenceCard>
@@ -1053,6 +1053,109 @@ export function Sync() {
type GeneralProps = {
requestClose: () => void;
};
function DiagnosticsAndPrivacy() {
const [sentryEnabled, setSentryEnabled] = useState(
localStorage.getItem('sable_sentry_enabled') !== 'false'
);
const [sessionReplayEnabled, setSessionReplayEnabled] = useState(
localStorage.getItem('sable_sentry_replay_enabled') === 'true'
);
const [needsRefresh, setNeedsRefresh] = useState(false);
const isSentryConfigured = Boolean(import.meta.env.VITE_SENTRY_DSN);
const handleSentryToggle = (enabled: boolean) => {
setSentryEnabled(enabled);
if (enabled) {
localStorage.removeItem('sable_sentry_enabled');
} else {
localStorage.setItem('sable_sentry_enabled', 'false');
}
setNeedsRefresh(true);
};
const handleReplayToggle = (enabled: boolean) => {
setSessionReplayEnabled(enabled);
if (enabled) {
localStorage.setItem('sable_sentry_replay_enabled', 'true');
} else {
localStorage.removeItem('sable_sentry_replay_enabled');
}
setNeedsRefresh(true);
};
return (
<Box direction="Column" gap="100">
<Text size="L400">Diagnostics & Privacy</Text>
{needsRefresh && (
<Box
style={{
padding: '12px',
backgroundColor: 'rgba(33, 150, 243, 0.1)',
borderRadius: '8px',
}}
>
<Text size="T300" style={{ color: 'rgb(33, 150, 243)' }}>
Please refresh the page for these settings to take effect.
</Text>
</Box>
)}
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Error Reporting"
description={
isSentryConfigured
? 'Send anonymous crash reports to help improve Sable. No messages, room names, or personal data are included.'
: 'Error reporting is not configured for this build.'
}
after={
<Switch
variant="Primary"
value={sentryEnabled}
onChange={handleSentryToggle}
disabled={!isSentryConfigured}
/>
}
/>
{sentryEnabled && isSentryConfigured && (
<SettingTile
title="Session Replay"
description="Allow recording of UI interactions to help debug errors. All text, media, and inputs are fully masked before sending."
after={
<Switch
variant="Primary"
value={sessionReplayEnabled}
onChange={handleReplayToggle}
/>
}
/>
)}
</SequenceCard>
<Box gap="200" wrap="Wrap" style={{ paddingTop: '4px' }}>
<Button
as="a"
href="https://github.com/SableClient/Sable/blob/dev/docs/PRIVACY_POLICY.md"
rel="noreferrer noopener"
target="_blank"
variant="Secondary"
fill="Soft"
size="300"
radii="300"
before={<Icon src={Icons.Shield} size="100" filled />}
>
<Text size="B300">Privacy Policy</Text>
</Button>
</Box>
</Box>
);
}
export function General({ requestClose }: GeneralProps) {
return (
<Page>
@@ -1078,6 +1181,7 @@ export function General({ requestClose }: GeneralProps) {
<Gestures isMobile={mobileOrTablet()} />
<Editor isMobile={mobileOrTablet()} />
<Messages />
<DiagnosticsAndPrivacy />
</Box>
</PageContent>
</Scroll>
+24 -7
View File
@@ -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<SignalState>(
(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;
}
+51 -51
View File
@@ -164,59 +164,59 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
beforeCapture={(scope) => scope.setTag('section', 'client')}
>
<AuthRouteThemeManager>
{/* 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. */}
<HandleNotificationClick />
<ClientRoot>
<ClientInitStorageAtom>
<ClientRoomsNotificationPreferences>
<ClientBindAtoms>
<ClientNonUIFeatures>
<NotificationJumper />
<CallEmbedProvider>
<ClientLayout
nav={
<MobileFriendlyClientNav>
<SidebarNav />
</MobileFriendlyClientNav>
}
>
<Outlet />
</ClientLayout>
<CallStatusRenderer />
</CallEmbedProvider>
<SearchModalRenderer />
<UserRoomProfileRenderer />
<CreateRoomModalRenderer />
<CreateSpaceModalRenderer />
<BugReportModalRenderer />
<RoomSettingsRenderer />
<SpaceSettingsRenderer />
<GlobalKeyboardShortcuts />
{/* Screen reader live region — populated by announce() in utils/announce.ts */}
<div
id="sable-announcements"
role="status"
aria-live="polite"
aria-atomic="true"
style={{
position: 'absolute',
width: '1px',
height: '1px',
overflow: 'hidden',
clip: 'rect(0,0,0,0)',
whiteSpace: 'nowrap',
}}
/>
<ReceiveSelfDeviceVerification />
<AutoRestoreBackupOnVerification />
</ClientNonUIFeatures>
</ClientBindAtoms>
</ClientRoomsNotificationPreferences>
</ClientInitStorageAtom>
</ClientRoot>
</AuthRouteThemeManager>
<HandleNotificationClick />
<ClientRoot>
<ClientInitStorageAtom>
<ClientRoomsNotificationPreferences>
<ClientBindAtoms>
<ClientNonUIFeatures>
<NotificationJumper />
<CallEmbedProvider>
<ClientLayout
nav={
<MobileFriendlyClientNav>
<SidebarNav />
</MobileFriendlyClientNav>
}
>
<Outlet />
</ClientLayout>
<CallStatusRenderer />
</CallEmbedProvider>
<SearchModalRenderer />
<UserRoomProfileRenderer />
<CreateRoomModalRenderer />
<CreateSpaceModalRenderer />
<BugReportModalRenderer />
<RoomSettingsRenderer />
<SpaceSettingsRenderer />
<GlobalKeyboardShortcuts />
{/* Screen reader live region — populated by announce() in utils/announce.ts */}
<div
id="sable-announcements"
role="status"
aria-live="polite"
aria-atomic="true"
style={{
position: 'absolute',
width: '1px',
height: '1px',
overflow: 'hidden',
clip: 'rect(0,0,0,0)',
whiteSpace: 'nowrap',
}}
/>
<ReceiveSelfDeviceVerification />
<AutoRestoreBackupOnVerification />
</ClientNonUIFeatures>
</ClientBindAtoms>
</ClientRoomsNotificationPreferences>
</ClientInitStorageAtom>
</ClientRoot>
</AuthRouteThemeManager>
</Sentry.ErrorBoundary>
}
>
+8 -7
View File
@@ -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',
+12 -50
View File
@@ -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;
+10 -2
View File
@@ -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<RectCords>();
const directSelected = useDirectSelected();
@@ -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]);
};
+19 -10
View File
@@ -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<MatrixEvent>();
+10 -9
View File
@@ -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<string, string | number | boolean> = {};
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);
+8 -4
View File
@@ -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 },
});
+141 -20
View File
@@ -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<string, unknown> | 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<string, unknown> | 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<string, string>;
if (headers.Authorization) {