Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

feat: add masked session replay lifecycle (#17194)

Gil Raphaellib2aeb9c6a130
diff --git a/.env.example b/.env.example
index c7860b01dc..dc2eafe767 100644
--- a/.env.example
+++ b/.env.example
@@ -426,8 +426,21 @@ NODE_MAX_OLD_SPACE_SIZE=6144
# RUM_TRACE_PROPAGATION_TARGETS=https://api.example.com
# Privacy defaults: replay, console capture, and full network body capture stay off.
+# Opt in separately with RUM_SESSION_REPLAY_ENABLED=true (requires RUM_ENABLED=true).
+# The client masks all text and input values and stops recording when its session/policy
+# becomes unavailable or the RUM layout unmounts.
+# Authentication, verification, password-reset and OAuth screens are excluded from replay.
+# Replay metadata/DOM URL fields and RUM span URLs lose query strings, fragments and userinfo
+# before export, including in public-token mode. This is not general-purpose DLP:
+# URLs, element attributes and assets may still contain sensitive information;
+# validate with synthetic data before enabling recording for real users.
# Console/network capture may collect sensitive browser logs, prompts, responses, or payloads.
-# RUM_DISABLE_REPLAY=true
+# RUM_SESSION_REPLAY_ENABLED=false
+# Deprecated fallback: RUM_DISABLE_REPLAY=false opts in only when the positive flag is unset.
+# YAML telemetry.rum.enabled / telemetry.rum.sessionReplay.enabled take precedence
+# over environment variables. Explicit false always wins over lower-precedence opt-ins.
+# Proxy mode strips replay records even when /v1/logs remains open for other log sources.
+# Direct public-token ingestion bypasses this server and must enforce its own collector policy.
# RUM_CONSOLE_CAPTURE=false
# RUM_ADVANCED_NETWORK_CAPTURE=false
# RUM_SAMPLE_RATE=1
diff --git a/.gitignore b/.gitignore
index 6c63bf4b27..c56772c2c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -192,6 +192,7 @@ scripts/activity-labels/results/
!e2e/lighthouse/librechat.yaml
/.lighthouse/
/e2e/lighthouse/.test-results/
+/e2e/rum/.test-results/
# Chrome user-data directories a Lighthouse run leaves in the repository root when the browser
# is handed a Windows profile path from WSL: the whole path arrives as one directory name.
/*lighthouse.[0-9]*/
diff --git a/api/server/routes/__tests__/config.rum.spec.js b/api/server/routes/__tests__/config.rum.spec.js
index 3cebde9ae2..20bc8b73ca 100644
--- a/api/server/routes/__tests__/config.rum.spec.js
+++ b/api/server/routes/__tests__/config.rum.spec.js
@@ -66,6 +66,7 @@ afterEach(() => {
delete process.env.RUM_TRACE_PROPAGATION_TARGETS;
delete process.env.RUM_CONSOLE_CAPTURE;
delete process.env.RUM_DISABLE_REPLAY;
+ delete process.env.RUM_SESSION_REPLAY_ENABLED;
delete process.env.RUM_ADVANCED_NETWORK_CAPTURE;
delete process.env.RUM_SAMPLE_RATE;
delete process.env.RUM_ENVIRONMENT;
@@ -73,6 +74,49 @@ afterEach(() => {
});
describe('GET /api/config RUM config', () => {
+ it.each([null, mockUser])('serves separate YAML RUM/replay opt-ins for %p', async (user) => {
+ mockGetAppConfig.mockResolvedValue({
+ ...baseAppConfig,
+ config: {
+ telemetry: {
+ rum: { enabled: true, sessionReplay: { enabled: true } },
+ },
+ },
+ });
+ process.env.RUM_ENABLED = 'false';
+ process.env.RUM_AUTH_MODE = 'proxy';
+ process.env.RUM_PROXY_TARGET_URL = 'http://otel-collector:4318';
+ const response = await request(createApp(user)).get('/api/config');
+ expect(response.body.rum).toMatchObject({
+ enabled: true,
+ sessionReplay: { enabled: true },
+ disableReplay: false,
+ });
+ });
+
+ it('lets YAML disable replay while RUM and client logs stay enabled', async () => {
+ mockGetAppConfig.mockResolvedValue({
+ ...baseAppConfig,
+ config: {
+ telemetry: {
+ rum: { sessionReplay: { enabled: false } },
+ },
+ },
+ });
+ process.env.RUM_ENABLED = 'true';
+ process.env.RUM_SESSION_REPLAY_ENABLED = 'true';
+ process.env.RUM_CLIENT_LOGS = 'true';
+ process.env.RUM_AUTH_MODE = 'proxy';
+ process.env.RUM_PROXY_TARGET_URL = 'http://otel-collector:4318';
+ const response = await request(createApp(mockUser)).get('/api/config');
+ expect(response.body.rum).toMatchObject({
+ enabled: true,
+ sessionReplay: { enabled: false },
+ disableReplay: true,
+ clientLogs: true,
+ });
+ });
+
it('includes public-token RUM config when enabled with valid env', async () => {
mockGetAppConfig.mockResolvedValue(baseAppConfig);
process.env.RUM_ENABLED = 'true';
@@ -96,6 +140,7 @@ describe('GET /api/config RUM config', () => {
tracePropagationTargets: ['https://app.example.com', 'https://api.openai.com'],
consoleCapture: false,
disableReplay: true,
+ sessionReplay: { enabled: false },
advancedNetworkCapture: false,
sampleRate: 0.25,
environment: 'test',
@@ -137,6 +182,7 @@ describe('GET /api/config RUM config', () => {
authMode: 'proxy',
consoleCapture: false,
disableReplay: true,
+ sessionReplay: { enabled: false },
advancedNetworkCapture: false,
clientLogs: false,
});
diff --git a/api/server/routes/__tests__/rum.spec.js b/api/server/routes/__tests__/rum.spec.js
index 318f62e113..eb0274e042 100644
--- a/api/server/routes/__tests__/rum.spec.js
+++ b/api/server/routes/__tests__/rum.spec.js
@@ -6,6 +6,7 @@ const mockIsRumProxyEnabled = jest.fn();
const mockIsRumLogsEndpointEnabled = jest.fn(() => true);
const mockProxyRumRequest = jest.fn((_req, res) => res.status(202).send());
const mockRumProxyLimiter = jest.fn((_req, _res, next) => next());
+const mockGetAppConfig = jest.fn(async () => ({ config: {} }));
const mockLimiterSetup = [];
const mockCreateRumProxyLimiter = jest.fn((options) => {
mockLimiterSetup.push(['createRumProxyLimiter', options]);
@@ -20,7 +21,19 @@ jest.mock('~/server/middleware', () => ({
requireRumProxyAuth: (...args) => mockRequireRumProxyAuth(...args),
}));
+jest.mock('~/server/services/Config/app', () => ({
+ getAppConfig: (...args) => mockGetAppConfig(...args),
+}));
+
jest.mock('@librechat/api', () => ({
+ loadRumConfig: (getAppConfig) => async (req, _res, next) => {
+ try {
+ req.config = await getAppConfig({ baseOnly: true });
+ next();
+ } catch (error) {
+ next(error);
+ }
+ },
getRumProxyBodyLimit: jest.fn(() => '3mb'),
limiterCache: (...args) => mockLimiterCache(...args),
createRumProxyLimiter: (...args) => mockCreateRumProxyLimiter(...args),
@@ -52,6 +65,7 @@ describe('RUM proxy routes', () => {
mockIsRumProxyEnabled.mockReset();
mockProxyRumRequest.mockClear();
mockRumProxyLimiter.mockClear();
+ mockGetAppConfig.mockClear();
mockIsRumLogsEndpointEnabled.mockReset();
mockIsRumLogsEndpointEnabled.mockReturnValue(true);
});
@@ -78,7 +92,7 @@ describe('RUM proxy routes', () => {
delete process.env.RUM_PROXY_AUTHORIZATION;
});
- it('returns 404 before auth and proxying when RUM proxy mode is disabled', async () => {
+ it('returns 404 after auth and limiting when RUM proxy mode is disabled', async () => {
mockIsRumProxyEnabled.mockReturnValue(false);
const response = await request(app)
@@ -88,7 +102,9 @@ describe('RUM proxy routes', () => {
expect(response.status).toBe(404);
expect(response.body).toEqual({ message: 'RUM proxy is not configured' });
- expect(mockRequireRumProxyAuth).not.toHaveBeenCalled();
+ expect(mockRequireRumProxyAuth).toHaveBeenCalledTimes(1);
+ expect(mockRumProxyLimiter).toHaveBeenCalledTimes(1);
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });
expect(mockProxyRumRequest).not.toHaveBeenCalled();
});
@@ -105,6 +121,17 @@ describe('RUM proxy routes', () => {
expect(response.status).toBe(202);
expect(mockRequireRumProxyAuth).toHaveBeenCalledTimes(1);
+ expect(mockGetAppConfig).toHaveBeenCalledTimes(1);
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(mockRequireRumProxyAuth.mock.invocationCallOrder[0]).toBeLessThan(
+ mockRumProxyLimiter.mock.invocationCallOrder[0],
+ );
+ expect(mockRumProxyLimiter.mock.invocationCallOrder[0]).toBeLessThan(
+ mockGetAppConfig.mock.invocationCallOrder[0],
+ );
+ expect(mockGetAppConfig.mock.invocationCallOrder[0]).toBeLessThan(
+ mockProxyRumRequest.mock.invocationCallOrder[0],
+ );
expect(mockProxyRumRequest).toHaveBeenCalledTimes(1);
expect(mockProxyRumRequest).toHaveBeenCalledWith(
expect.any(Object),
@@ -127,6 +154,8 @@ describe('RUM proxy routes', () => {
.send(Buffer.from('payload'));
expect(response.status).toBe(401);
+ expect(mockGetAppConfig).not.toHaveBeenCalled();
+ expect(mockRumProxyLimiter).not.toHaveBeenCalled();
expect(mockProxyRumRequest).not.toHaveBeenCalled();
},
);
@@ -170,6 +199,7 @@ describe('RUM proxy routes', () => {
expect(response.status).toBe(429);
expect(order).toEqual(['auth', 'limit']);
+ expect(mockGetAppConfig).not.toHaveBeenCalled();
expect(mockProxyRumRequest).not.toHaveBeenCalled();
});
@@ -183,6 +213,21 @@ describe('RUM proxy routes', () => {
.send({ resourceLogs: [] });
expect(response.status).toBe(204);
+ expect(mockGetAppConfig).not.toHaveBeenCalled();
expect(mockRumProxyLimiter).not.toHaveBeenCalled();
});
+
+ it.each([
+ ['get', '/api/rum/v1/traces'],
+ ['put', '/api/rum/v1/logs'],
+ ['post', '/api/rum/v1/unknown'],
+ ])('does not load config for unmatched %s %s requests', async (method, path) => {
+ const response = await request(app)[method](path);
+
+ expect(response.status).toBe(404);
+ expect(mockGetAppConfig).not.toHaveBeenCalled();
+ expect(mockRequireRumProxyAuth).not.toHaveBeenCalled();
+ expect(mockRumProxyLimiter).not.toHaveBeenCalled();
+ expect(mockProxyRumRequest).not.toHaveBeenCalled();
+ });
});
diff --git a/api/server/routes/config.js b/api/server/routes/config.js
index 905a735602..678b83f227 100644
--- a/api/server/routes/config.js
+++ b/api/server/routes/config.js
@@ -229,7 +229,6 @@ router.get('/', async function (req, res) {
try {
const preLoginPayload = buildPreLoginPayload();
const publicSharePayload = buildPublicSharePayload();
- const rum = getRumConfig();
if (!req.user) {
const tenantId = getTenantId();
@@ -240,7 +239,7 @@ router.get('/', async function (req, res) {
...preLoginPayload,
socialLogins: baseConfig?.registration?.socialLogins ?? defaultSocialLogins,
turnstile: baseConfig?.turnstileConfig,
- ...(rum ? { rum } : {}),
+ rum: getRumConfig(baseConfig?.config?.telemetry),
};
const interfaceConfig = baseConfig?.interfaceConfig;
@@ -349,7 +348,7 @@ router.get('/', async function (req, res) {
...resolveCodeWorkspaceInheritanceCapability(process.env.CODE_ENVIRONMENT_DECISION_VERSION),
...(codeEnvironmentTransitionVersion != null ? { codeEnvironmentTransitionVersion } : {}),
...(cloudFront ? { cloudFront } : {}),
- ...(rum ? { rum } : {}),
+ rum: getRumConfig(appConfig?.config?.telemetry),
fileUploadSseEnabled: isEnabled(process.env.FILE_UPLOAD_SSE_ENABLED),
endpointsDropParamsMap: endpointsDropParamsMap,
};
diff --git a/api/server/routes/rum.js b/api/server/routes/rum.js
index fd6ed4ca40..7af76bb91f 100644
--- a/api/server/routes/rum.js
+++ b/api/server/routes/rum.js
@@ -7,8 +7,10 @@ const {
requireRumLogsEnabled,
handleJsonParseError,
createRumProxyLimiter,
+ loadRumConfig,
} = require('@librechat/api');
const { requireRumProxyAuth } = require('~/server/middleware');
+const { getAppConfig } = require('~/server/services/Config/app');
const router = express.Router();
const rawOtlpBody = express.raw({
@@ -19,16 +21,19 @@ const rawOtlpBody = express.raw({
const rumProxyLimiter = createRumProxyLimiter({ store: limiterCache('rum_proxy_user_limiter') });
const proxyTelemetry = (req, res) => proxyRumRequest(req, res, process.env.RUM_PROXY_AUTHORIZATION);
const telemetryPipeline = [
- requireRumProxyEnabled,
requireRumProxyAuth,
rumProxyLimiter,
+ loadRumConfig(getAppConfig),
+ requireRumProxyEnabled,
+];
+const proxyPipeline = [
express.json({ limit: getRumProxyBodyLimit() }),
rawOtlpBody,
handleJsonParseError,
proxyTelemetry,
];
-router.post('/v1/traces', ...telemetryPipeline);
-router.post('/v1/logs', requireRumLogsEnabled, ...telemetryPipeline);
+router.post('/v1/traces', ...telemetryPipeline, ...proxyPipeline);
+router.post('/v1/logs', ...telemetryPipeline, requireRumLogsEnabled, ...proxyPipeline);
module.exports = router;
diff --git a/api/server/services/Config/rum.js b/api/server/services/Config/rum.js
index 4d8eca2de9..9b12da8021 100644
--- a/api/server/services/Config/rum.js
+++ b/api/server/services/Config/rum.js
@@ -1,157 +1 @@
-const {
- isEnabled,
- isRumProxyEnabled,
- getRumProxyClientUrl,
- isRumClientLogsEnabled,
-} = require('@librechat/api');
-const { logger } = require('@librechat/data-schemas');
-
-const DEFAULT_RUM_SERVICE_NAME = 'librechat-web';
-
-function parseBooleanEnv(value, defaultValue = false) {
- if (value == null || value === '') {
- return defaultValue;
- }
-
- return isEnabled(value);
-}
-
-function parseNumberEnv(value) {
- if (value == null || value === '') {
- return undefined;
- }
-
- const parsed = Number(value);
- return Number.isFinite(parsed) ? parsed : undefined;
-}
-
-function parseCsvEnv(value) {
- if (!value) {
- return [];
- }
-
- return value
- .split(',')
- .map((item) => item.trim())
- .filter(Boolean);
-}
-
-function parseUrl(value) {
- try {
- return new URL(value);
- } catch {
- return undefined;
- }
-}
-
-function isLocalhost(url) {
- return url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]';
-}
-
-function isSafeRumUrl(url) {
- if (url.username || url.password) {
- return false;
- }
-
- if (url.protocol === 'https:') {
- return true;
- }
-
- return url.protocol === 'http:' && isLocalhost(url);
-}
-
-function isSafeTraceTarget(target) {
- if (target.includes('*')) {
- return false;
- }
-
- const url = parseUrl(target);
- if (!url || url.protocol !== 'https:') {
- return false;
- }
-
- return true;
-}
-
-function getRumConfig() {
- if (!parseBooleanEnv(process.env.RUM_ENABLED)) {
- return undefined;
- }
-
- const provider = process.env.RUM_PROVIDER || 'hyperdx';
- if (provider !== 'hyperdx') {
- logger.warn(`[config] Unsupported RUM provider "${provider}", disabling RUM`);
- return undefined;
- }
-
- const authMode = process.env.RUM_AUTH_MODE || 'publicToken';
- if (authMode !== 'publicToken' && authMode !== 'proxy') {
- logger.warn(`[config] Unsupported RUM auth mode "${authMode}", disabling RUM`);
- return undefined;
- }
-
- let rumUrl;
- if (authMode === 'proxy') {
- rumUrl = getRumProxyClientUrl();
-
- if (!isRumProxyEnabled()) {
- logger.warn('[config] RUM proxy mode requires RUM_PROXY_TARGET_URL, disabling RUM');
- return undefined;
- }
- } else {
- rumUrl = process.env.RUM_URL;
- const parsedUrl = rumUrl ? parseUrl(rumUrl) : undefined;
-
- if (!parsedUrl || !isSafeRumUrl(parsedUrl)) {
- logger.warn('[config] Invalid RUM_URL, disabling RUM');
- return undefined;
- }
-
- if (!process.env.RUM_PUBLIC_TOKEN) {
- logger.warn('[config] RUM publicToken mode requires RUM_PUBLIC_TOKEN, disabling RUM');
- return undefined;
- }
-
- rumUrl = parsedUrl.href.replace(/\/$/, '');
- }
-
- const rawTracePropagationTargets = parseCsvEnv(process.env.RUM_TRACE_PROPAGATION_TARGETS);
- const tracePropagationTargets = rawTracePropagationTargets.filter(isSafeTraceTarget);
- if (rawTracePropagationTargets.length !== tracePropagationTargets.length) {
- logger.info('[config] Ignored unsafe RUM trace propagation targets');
- }
-
- const configuredSampleRate = parseNumberEnv(process.env.RUM_SAMPLE_RATE);
- const sampleRate =
- configuredSampleRate != null && configuredSampleRate >= 0 && configuredSampleRate <= 1
- ? configuredSampleRate
- : undefined;
- const consoleCapture = parseBooleanEnv(process.env.RUM_CONSOLE_CAPTURE);
- const advancedNetworkCapture = parseBooleanEnv(process.env.RUM_ADVANCED_NETWORK_CAPTURE);
-
- if (consoleCapture) {
- logger.warn('[config] RUM console capture is enabled and may collect sensitive browser logs');
- }
-
- if (advancedNetworkCapture) {
- logger.warn('[config] RUM advanced network capture is enabled and may collect payload data');
- }
-
- return {
- provider: 'hyperdx',
- enabled: true,
- url: rumUrl,
- serviceName: process.env.RUM_SERVICE_NAME || DEFAULT_RUM_SERVICE_NAME,
- authMode,
- ...(authMode === 'publicToken' ? { publicToken: process.env.RUM_PUBLIC_TOKEN } : {}),
- ...(tracePropagationTargets.length > 0 ? { tracePropagationTargets } : {}),
- consoleCapture,
- disableReplay: parseBooleanEnv(process.env.RUM_DISABLE_REPLAY, true),
- advancedNetworkCapture,
- ...(sampleRate != null ? { sampleRate } : {}),
- ...(process.env.RUM_ENVIRONMENT ? { environment: process.env.RUM_ENVIRONMENT } : {}),
- clientLogs: isRumClientLogsEnabled(),
- };
-}
-
-module.exports = { getRumConfig };
+module.exports = { getRumConfig: require('@librechat/api').getRumConfig };
diff --git a/client/package.json b/client/package.json
index f4faa06668..5025d5918c 100644
--- a/client/package.json
+++ b/client/package.json
@@ -35,13 +35,17 @@
"@dicebear/collection": "^9.4.3",
"@dicebear/core": "^9.4.3",
"@headlessui/react": "^2.1.2",
- "@hyperdx/browser": "^0.24.0",
+ "@hyperdx/otel-web": "0.18.0",
+ "@hyperdx/otel-web-session-recorder": "2.0.0",
"@librechat/chat": "*",
"@librechat/client": "*",
"@marsidev/react-turnstile": "^1.1.0",
"@mcp-ui/client": "^5.7.0",
"@modelcontextprotocol/ext-apps": "^1.7.4",
"@monaco-editor/react": "^4.7.0",
+ "@opentelemetry/exporter-trace-otlp-http": "0.218.0",
+ "@opentelemetry/resources": "2.7.1",
+ "@opentelemetry/sdk-trace-base": "2.7.1",
"@radix-ui/react-accordion": "^1.2.20",
"@radix-ui/react-alert-dialog": "^1.1.23",
"@radix-ui/react-checkbox": "^1.3.11",
diff --git a/client/src/lib/rum/browser.spec.ts b/client/src/lib/rum/browser.spec.ts
new file mode 100644
index 0000000000..67c153fe4a
--- /dev/null
+++ b/client/src/lib/rum/browser.spec.ts
@@ -0,0 +1,86 @@
+import browser from './browser';
+
+let mockRecording = false;
+const mockRecorderInit = jest.fn<void, unknown[]>(() => {
+ mockRecording = true;
+});
+const mockRecorderDeinit = jest.fn(() => {
+ mockRecording = false;
+});
+const mockRumInit = jest.fn();
+jest.mock('@hyperdx/otel-web', () => ({
+ __esModule: true,
+ default: { _internalInit: (...args: unknown[]) => mockRumInit(...args) },
+}));
+jest.mock('@hyperdx/otel-web-session-recorder', () => ({
+ __esModule: true,
+ default: {
+ get inited() {
+ return mockRecording;
+ },
+ init: (...args: unknown[]) => mockRecorderInit(...args),
+ deinit: () => mockRecorderDeinit(),
+ },
+}));
+
+const config = {
+ apiKey: 'test-key',
+ service: 'browser-test',
+ url: '/api/rum',
+ disableReplay: false,
+ advancedNetworkCapture: false,
+ consoleCapture: false,
+ maskAllInputs: true,
+ maskAllText: true,
+};
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockRecording = false;
+ document.querySelector('base')?.remove();
+ history.replaceState({}, '', '/c/new');
+});
+
+it('installs URL-safe exporters and a pre-queue replay privacy plugin', () => {
+ browser.init(config);
+ expect(mockRumInit).toHaveBeenCalledWith(
+ expect.objectContaining({ exporter: { factory: expect.any(Function) } }),
+ );
+ expect(mockRecorderInit).toHaveBeenCalledWith(
+ expect.objectContaining({
+ maskAllInputs: true,
+ maskTextSelector: '*',
+ recordCanvas: false,
+ plugins: [expect.objectContaining({ eventProcessor: expect.any(Function) })],
+ }),
+ );
+});
+
+it('ends recording observers and restarts with a fresh snapshot rather than retaining auth-page mutations', () => {
+ browser.init(config);
+ browser.stopSessionRecorder();
+ expect(mockRecorderDeinit).toHaveBeenCalledTimes(1);
+ browser.resumeSessionRecorder();
+ expect(mockRecorderInit).toHaveBeenCalledTimes(2);
+ browser.resumeSessionRecorder();
+ expect(mockRecorderInit).toHaveBeenCalledTimes(2);
+});
+
+it('never starts or resumes a recorder on an authentication screen', () => {
+ browser.init(config);
+ browser.stopSessionRecorder();
+ history.replaceState({}, '', '/login/2fa?tempToken=fake-token');
+ browser.resumeSessionRecorder();
+ expect(mockRecorderInit).toHaveBeenCalledTimes(1);
+ browser.init(config);
+ expect(mockRecorderInit).toHaveBeenCalledTimes(1);
+});
+
+it.each(['/librechat/', '/librechat'])('recognizes the root login screen at %s', (pathname) => {
+ const base = document.createElement('base');
+ base.href = '/librechat/';
+ document.head.append(base);
+ history.replaceState({}, '', `${pathname}?tempToken=fake-token`);
+ browser.init(config);
+ expect(mockRecorderInit).not.toHaveBeenCalled();
+});
diff --git a/client/src/lib/rum/browser.ts b/client/src/lib/rum/browser.ts
new file mode 100644
index 0000000000..23de510709
--- /dev/null
+++ b/client/src/lib/rum/browser.ts
@@ -0,0 +1,94 @@
+import Rum from '@hyperdx/otel-web';
+import Recorder from '@hyperdx/otel-web-session-recorder';
+import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
+import type { RumRecorderConfig } from '@hyperdx/otel-web-session-recorder';
+import type { RumActionAttributes } from './diagnostics';
+import { createReplayPrivacyPlugin, isReplayRouteAllowed } from './privacy';
+import { PrivacyTraceExporter } from './exporter';
+
+export type BrowserConfig = {
+ advancedNetworkCapture: boolean;
+ apiKey: string;
+ consoleCapture: boolean;
+ disableReplay: boolean;
+ maskAllInputs: boolean;
+ maskAllText: boolean;
+ service: string;
+ tracePropagationTargets?: string[];
+ url: string;
+};
+
+let advancedNetworkCapture = false;
+let replayConfig: RumRecorderConfig | undefined;
+let replayPathname = () => window.location.pathname;
+
+function startRecorder(): void {
+ if (replayConfig && isReplayRouteAllowed(replayPathname()) && !Recorder.inited) {
+ Recorder.init(replayConfig);
+ }
+}
+
+/** Compose the same SDK components directly so both exporters have pre-serialization privacy hooks. */
+const browser = {
+ init(config: BrowserConfig): void {
+ advancedNetworkCapture = config.advancedNetworkCapture;
+ const network = {
+ ...(config.tracePropagationTargets
+ ? { propagateTraceHeaderCorsUrls: config.tracePropagationTargets }
+ : {}),
+ advancedNetworkCapture: () => advancedNetworkCapture,
+ };
+ Rum._internalInit({
+ allowInsecureUrl: true,
+ apiKey: config.apiKey,
+ applicationName: config.service,
+ url: `${config.url}/v1/traces`,
+ exporter: {
+ factory: ({ url, authHeader }) =>
+ new PrivacyTraceExporter(
+ new OTLPTraceExporter({
+ url,
+ headers: authHeader ? { authorization: authHeader } : {},
+ }),
+ ),
+ },
+ instrumentations: {
+ visibility: true,
+ console: config.consoleCapture,
+ fetch: network,
+ xhr: network,
+ },
+ });
+ const base = new URL(
+ document.querySelector('base')?.getAttribute('href') ?? '/',
+ window.location.origin,
+ ).pathname.replace(/\/$/, '');
+ const getPathname = () => {
+ const pathname = window.location.pathname;
+ if (pathname === base) return '/';
+ return pathname.startsWith(`${base}/`) ? pathname.slice(base.length) : pathname;
+ };
+ replayPathname = getPathname;
+ replayConfig = undefined;
+ if (!config.disableReplay && isReplayRouteAllowed(getPathname())) {
+ replayConfig = {
+ apiKey: config.apiKey,
+ url: `${config.url}/v1/logs`,
+ maskAllInputs: true,
+ maskTextSelector: '*',
+ recordCanvas: false,
+ plugins: [createReplayPrivacyPlugin(getPathname)],
+ };
+ startRecorder();
+ } else {
+ Recorder.deinit();
+ }
+ },
+ stopSessionRecorder: () => Recorder.deinit(),
+ resumeSessionRecorder: startRecorder,
+ getSessionId: () => Rum.getSessionId(),
+ addAction: (name: string, attributes?: RumActionAttributes) => Rum.addAction(name, attributes),
+ setGlobalAttributes: (attributes: Record<string, string>) => Rum.setGlobalAttributes(attributes),
+};
+
+export default browser;
diff --git a/client/src/lib/rum/exporter.spec.ts b/client/src/lib/rum/exporter.spec.ts
new file mode 100644
index 0000000000..ee3267068a
--- /dev/null
+++ b/client/src/lib/rum/exporter.spec.ts
@@ -0,0 +1,44 @@
+import { resourceFromAttributes } from '@opentelemetry/resources';
+import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';
+import { PrivacyTraceExporter } from './exporter';
+
+it('sanitizes the actual span export boundary, including events, resources and links, without changing the source span', () => {
+ const secret = 'fake-login-token-do-not-export';
+ const url = `https://user:${secret}@app.example/login/2fa?tempToken=${secret}#${secret}`;
+ const context = { traceId: 'a'.repeat(32), spanId: 'b'.repeat(16), traceFlags: 1 };
+ const span: ReadableSpan = {
+ name: `GET ${url}`,
+ kind: 0,
+ spanContext: () => context,
+ startTime: [1, 0],
+ endTime: [2, 0],
+ duration: [1, 0],
+ ended: true,
+ status: { code: 2, message: `failed ${url}` },
+ attributes: { 'location.href': url },
+ resource: resourceFromAttributes({ 'service.name': 'librechat-web', 'page.url': url }),
+ instrumentationScope: { name: 'test' },
+ events: [
+ { name: 'exception', time: [2, 0], attributes: { 'exception.stacktrace': `at ${url}` } },
+ ],
+ links: [{ context, attributes: { 'http.url': url } }],
+ droppedAttributesCount: 0,
+ droppedEventsCount: 0,
+ droppedLinksCount: 0,
+ };
+ const exportSpans = jest.fn<
+ ReturnType<SpanExporter['export']>,
+ Parameters<SpanExporter['export']>
+ >();
+ const exporter: SpanExporter = {
+ export: exportSpans,
+ shutdown: jest.fn().mockResolvedValue(undefined),
+ };
+ new PrivacyTraceExporter(exporter).export([span], jest.fn());
+ const safe = exportSpans.mock.calls[0][0][0];
+ expect(JSON.stringify(safe)).not.toContain(secret);
+ expect(safe.spanContext()).toEqual(context);
+ expect(safe.attributes['location.href']).toBe('https://app.example/login/2fa');
+ expect(safe.resource.attributes['service.name']).toBe('librechat-web');
+ expect(span.attributes['location.href']).toBe(url);
+});
diff --git a/client/src/lib/rum/exporter.ts b/client/src/lib/rum/exporter.ts
new file mode 100644
index 0000000000..f33f339e57
--- /dev/null
+++ b/client/src/lib/rum/exporter.ts
@@ -0,0 +1,52 @@
+import { resourceFromAttributes } from '@opentelemetry/resources';
+import type { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';
+import { sanitizeSpanAttributes, sanitizeUrlReferences } from './privacy';
+
+function sanitizeSpan(span: ReadableSpan): ReadableSpan {
+ return {
+ name: sanitizeUrlReferences(span.name),
+ kind: span.kind,
+ spanContext: () => span.spanContext(),
+ parentSpanContext: span.parentSpanContext,
+ startTime: span.startTime,
+ endTime: span.endTime,
+ duration: span.duration,
+ ended: span.ended,
+ status: {
+ ...span.status,
+ ...(span.status.message ? { message: sanitizeUrlReferences(span.status.message) } : {}),
+ },
+ attributes: sanitizeSpanAttributes(span.attributes),
+ resource: resourceFromAttributes(sanitizeSpanAttributes(span.resource.attributes)),
+ instrumentationScope: span.instrumentationScope,
+ events: span.events.map((event) => ({
+ ...event,
+ name: sanitizeUrlReferences(event.name),
+ ...(event.attributes ? { attributes: sanitizeSpanAttributes(event.attributes) } : {}),
+ })),
+ links: span.links.map((link) => ({
+ ...link,
+ ...(link.attributes ? { attributes: sanitizeSpanAttributes(link.attributes) } : {}),
+ })),
+ droppedAttributesCount: span.droppedAttributesCount,
+ droppedEventsCount: span.droppedEventsCount,
+ droppedLinksCount: span.droppedLinksCount,
+ };
+}
+
+/** Redact at the real exporter boundary; the pinned SDK's attribute callback is not wired by its default exporter. */
+export class PrivacyTraceExporter implements SpanExporter {
+ constructor(private readonly exporter: SpanExporter) {}
+
+ export(spans: ReadableSpan[], callback: Parameters<SpanExporter['export']>[1]): void {
+ this.exporter.export(spans.map(sanitizeSpan), callback);
+ }
+
+ shutdown(): Promise<void> {
+ return this.exporter.shutdown();
+ }
+
+ forceFlush(): Promise<void> {
+ return this.exporter.forceFlush?.() ?? Promise.resolve();
+ }
+}
diff --git a/client/src/lib/rum/privacy.spec.ts b/client/src/lib/rum/privacy.spec.ts
new file mode 100644
index 0000000000..9c581ea345
--- /dev/null
+++ b/client/src/lib/rum/privacy.spec.ts
@@ -0,0 +1,206 @@
+import {
+ sanitizeTelemetryUrl,
+ sanitizeSpanAttributes,
+ sanitizeReplayEvent,
+ isReplayRouteAllowed,
+} from './privacy';
+
+const secret = 'synthetic-login-token-do-not-export';
+const url = `https://alice:${secret}@librechat.example/c/new?tempToken=${secret}#${secret}`;
+
+it.each([
+ '/login',
+ '/login/2fa',
+ '/login/2fa/setup',
+ '/register',
+ '/forgot-password',
+ '/reset-password',
+ '/verify',
+ '/oauth/success',
+ '/',
+ '/app/login/2fa',
+ '/LOGIN/2fa',
+ '/%6cogin/2fa',
+])('excludes the authentication route %s', (pathname) => {
+ expect(isReplayRouteAllowed(pathname)).toBe(false);
+});
+
+it('keeps chat and other ordinary application routes recordable', () => {
+ expect(isReplayRouteAllowed('/c/new')).toBe(true);
+ expect(isReplayRouteAllowed('/search')).toBe(true);
+});
+
+it('strips credentials, query strings and fragments without changing useful URL paths', () => {
+ expect(sanitizeTelemetryUrl(url)).toBe('https://librechat.example/c/new');
+ expect(sanitizeTelemetryUrl(`/c/new?tempToken=${secret}#${secret}`)).toBe('/c/new');
+ expect(sanitizeTelemetryUrl(`assets/image.png?token=${secret}`)).toBe('assets/image.png');
+ expect(sanitizeTelemetryUrl(`//cdn.example/image.png?token=${secret}`)).toBe(
+ '//cdn.example/image.png',
+ );
+ expect(sanitizeTelemetryUrl(`javascript:${secret}`)).toBe('[redacted]');
+ expect(sanitizeTelemetryUrl(`data:text/html,${secret}`)).toBe('[redacted]');
+});
+
+it('sanitizes recorder metadata before it can enter the SDK queue', () => {
+ const event = sanitizeReplayEvent(
+ { type: 4, timestamp: 1, data: { href: url, width: 1200, height: 800 } },
+ '/c/new',
+ );
+ expect(event).toMatchObject({ type: 4, data: { href: 'https://librechat.example/c/new' } });
+ expect(JSON.stringify(event)).not.toContain(secret);
+});
+
+it('drops auth-screen metadata and snapshots even during a route/effect race', () => {
+ const authUrl = `https://librechat.example/login/2fa?tempToken=${secret}`;
+ expect(
+ sanitizeReplayEvent(
+ { type: 4, timestamp: 1, data: { href: authUrl, width: 1, height: 1 } },
+ '/c/new',
+ ),
+ ).toEqual({ type: 0, timestamp: 1, data: {} });
+ const event = sanitizeReplayEvent(
+ {
+ type: 2,
+ timestamp: 2,
+ data: {
+ initialOffset: { top: 0, left: 0 },
+ node: { type: 0, id: 1, childNodes: [{ type: 3, id: 2, textContent: secret }] },
+ },
+ },
+ '/login/2fa',
+ );
+ expect(event).toEqual({ type: 0, timestamp: 2, data: {} });
+});
+
+it('sanitizes URL attributes and CSS in the complete DOM snapshot', () => {
+ const event = sanitizeReplayEvent(
+ {
+ type: 2,
+ timestamp: 1,
+ data: {
+ initialOffset: { top: 0, left: 0 },
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'a',
+ attributes: {
+ href: url,
+ 'data-url': `/relative?tempToken=${secret}`,
+ 'data-src': url,
+ srcset: `${url} 1x, /image.png?token=${secret} 2x`,
+ style: `background:url('/image.png?token=${secret}')`,
+ srcdoc: secret,
+ },
+ childNodes: [
+ { type: 3, id: 3, isStyle: true, textContent: `a { background: url('${url}') }` },
+ ],
+ },
+ ],
+ },
+ },
+ },
+ '/c/new',
+ );
+ expect(JSON.stringify(event)).not.toContain(secret);
+ expect(JSON.stringify(event)).toContain('https://librechat.example/c/new');
+});
+
+it('sanitizes newly inserted nodes and attribute mutations', () => {
+ const event = sanitizeReplayEvent(
+ {
+ type: 3,
+ timestamp: 1,
+ data: {
+ source: 0,
+ adds: [
+ {
+ parentId: 1,
+ nextId: null,
+ node: { type: 2, id: 2, tagName: 'img', attributes: { src: url }, childNodes: [] },
+ },
+ ],
+ removes: [],
+ texts: [],
+ attributes: [{ id: 3, attributes: { href: url, src: null } }],
+ },
+ },
+ '/c/new',
+ );
+ expect(JSON.stringify(event)).not.toContain(secret);
+});
+
+it('sanitizes structured style mutations, CSSOM rules and declaration updates', () => {
+ const mutation = sanitizeReplayEvent(
+ {
+ type: 3,
+ timestamp: 1,
+ data: {
+ source: 0,
+ adds: [],
+ removes: [],
+ texts: [{ id: 1, value: null }],
+ attributes: [
+ {
+ id: 2,
+ attributes: {
+ style: {
+ background: `url('${url}')`,
+ 'background-image': [`url('${url}')`, 'important'],
+ color: false,
+ },
+ },
+ },
+ ],
+ },
+ },
+ '/c/new',
+ );
+ const rule = sanitizeReplayEvent(
+ {
+ type: 3,
+ timestamp: 1,
+ data: { source: 8, id: 1, adds: [{ rule: `a { background: url('${url}') }` }] },
+ },
+ '/c/new',
+ );
+ const declaration = sanitizeReplayEvent(
+ {
+ type: 3,
+ timestamp: 1,
+ data: {
+ source: 13,
+ id: 1,
+ index: [0],
+ set: { property: 'background', value: `url('${url}')`, priority: 'important' },
+ },
+ },
+ '/c/new',
+ );
+ expect(JSON.stringify([mutation, rule, declaration])).not.toContain(secret);
+});
+
+it('sanitizes SDK document/referrer/network span attributes and standalone query values', () => {
+ const attributes = sanitizeSpanAttributes({
+ 'location.href': url,
+ 'document.referrer': url,
+ 'http.url': url,
+ 'http.target': `/api/check?token=${secret}`,
+ 'url.query': `token=${secret}`,
+ 'url.fragment': secret,
+ urls: [url],
+ message: `failed resource ${url}`,
+ count: 3,
+ });
+ expect(JSON.stringify(attributes)).not.toContain(secret);
+ expect(attributes).toMatchObject({
+ 'location.href': 'https://librechat.example/c/new',
+ 'http.target': '/api/check',
+ 'url.query': '',
+ 'url.fragment': '',
+ count: 3,
+ });
+});
diff --git a/client/src/lib/rum/privacy.ts b/client/src/lib/rum/privacy.ts
new file mode 100644
index 0000000000..530af034b2
--- /dev/null
+++ b/client/src/lib/rum/privacy.ts
@@ -0,0 +1,169 @@
+import type { RumRecorderConfig } from '@hyperdx/otel-web-session-recorder';
+import type { RumOtelWebExporterOptions } from '@hyperdx/otel-web';
+
+type ReplayPlugin = NonNullable<RumRecorderConfig['plugins']>[number];
+type ReplayEvent = Parameters<NonNullable<ReplayPlugin['eventProcessor']>>[0];
+type SnapshotNode = Extract<ReplayEvent, { type: 2 }>['data']['node'];
+type MutationData = Extract<Extract<ReplayEvent, { type: 3 }>['data'], { source: 0 }>;
+type StyleAttributes = Exclude<
+ MutationData['attributes'][number]['attributes'][string],
+ string | null
+>;
+type SpanAttributes = Parameters<
+ NonNullable<RumOtelWebExporterOptions['onAttributesSerializing']>
+>[0];
+
+const AUTH_ROUTE = /\/(?:login|register|forgot-password|reset-password|verify|oauth)(?:\/|$)/i;
+const URL_ATTRIBUTE =
+ /^(?:data-)?(?:href|src|url|uri|action|formaction|poster|cite|background|data|xlink:href)$/i;
+const URL_SPAN_ATTRIBUTE = /url|uri|href|referr?er|^http\.target$|location/i;
+
+export function isReplayRouteAllowed(pathname: string): boolean {
+ try {
+ return pathname !== '/' && !AUTH_ROUTE.test(decodeURI(pathname));
+ } catch {
+ return false;
+ }
+}
+
+/** Preserve URL origin/path while dropping query strings, fragments and URL credentials. */
+export function sanitizeTelemetryUrl(value: string): string {
+ const trimmed = value.trim();
+ if (/^(?:data|javascript):/i.test(trimmed)) return '[redacted]';
+ try {
+ const url = new URL(value, 'https://librechat.invalid');
+ url.search = '';
+ url.hash = '';
+ url.username = '';
+ url.password = '';
+ if (trimmed.startsWith('//')) return `//${url.host}${url.pathname}`;
+ return /^[a-z][a-z\d+.-]*:/i.test(trimmed) ? url.href : trimmed.split(/[?#]/, 1)[0];
+ } catch {
+ return '[redacted]';
+ }
+}
+
+export function sanitizeUrlReferences(value: string): string {
+ return value
+ .replace(
+ /url\(\s*(['"]?)(.*?)\1\s*\)/gi,
+ (_match, quote: string, url: string) => `url(${quote}${sanitizeTelemetryUrl(url)}${quote})`,
+ )
+ .replace(/https?:\/\/[^\s"'<>)]*/gi, (url) => sanitizeTelemetryUrl(url));
+}
+
+function sanitizeAttributes(
+ attributes: Record<string, string | number | boolean | null | StyleAttributes>,
+): void {
+ for (const [key, value] of Object.entries(attributes)) {
+ if (value != null && typeof value === 'object') {
+ for (const [property, style] of Object.entries(value)) {
+ if (typeof style === 'string') value[property] = sanitizeUrlReferences(style);
+ else if (Array.isArray(style))
+ value[property] = [sanitizeUrlReferences(style[0]), style[1]];
+ }
+ continue;
+ }
+ if (typeof value !== 'string') continue;
+ if (key.toLowerCase() === 'srcdoc') {
+ attributes[key] = '';
+ } else if (URL_ATTRIBUTE.test(key)) {
+ attributes[key] = sanitizeTelemetryUrl(value);
+ } else if (/^(?:data-)?srcset$/i.test(key)) {
+ // Commas in URL values make srcset ambiguous; omit sensitive sets instead of leaking fragments.
+ if (/data:|[?#@]/i.test(value)) {
+ attributes[key] = '[redacted]';
+ continue;
+ }
+ attributes[key] = value
+ .split(',')
+ .map((candidate) => {
+ const [url, ...descriptor] = candidate.trim().split(/\s+/);
+ return [
+ sanitizeTelemetryUrl(url),
+ ...descriptor.filter((entry) => /^\d+(?:\.\d+)?[wx]$/.test(entry)),
+ ].join(' ');
+ })
+ .join(', ');
+ } else {
+ attributes[key] = sanitizeUrlReferences(value);
+ }
+ }
+}
+
+function sanitizeNodes(root: SnapshotNode): void {
+ const pending = [root];
+ while (pending.length) {
+ const node = pending.pop();
+ if (!node) continue;
+ if ('attributes' in node) sanitizeAttributes(node.attributes);
+ if ('childNodes' in node) pending.push(...node.childNodes);
+ if (node.type === 3 && node.isStyle) {
+ node.textContent = sanitizeUrlReferences(node.textContent);
+ }
+ }
+}
+
+/** Runs inside rrweb before its event is serialized, chunked or queued by the recorder. */
+export function sanitizeReplayEvent(event: ReplayEvent, pathname: string): ReplayEvent {
+ if (!isReplayRouteAllowed(pathname)) {
+ return { type: 0, timestamp: event.timestamp, data: {} };
+ }
+ if (event.type === 4) {
+ let allowed = false;
+ try {
+ allowed = isReplayRouteAllowed(
+ new URL(event.data.href, 'https://librechat.invalid').pathname,
+ );
+ } catch {
+ // Malformed metadata is not useful enough to risk forwarding an unparsed URL.
+ }
+ if (!allowed) {
+ return { type: 0, timestamp: event.timestamp, data: {} };
+ }
+ event.data.href = sanitizeTelemetryUrl(event.data.href);
+ } else if (event.type === 2) {
+ sanitizeNodes(event.data.node);
+ } else if (event.type === 3 && event.data.source === 0) {
+ for (const addition of event.data.adds) sanitizeNodes(addition.node);
+ for (const attribute of event.data.attributes) sanitizeAttributes(attribute.attributes);
+ for (const text of event.data.texts) {
+ if (text.value != null) text.value = sanitizeUrlReferences(text.value);
+ }
+ } else if (event.type === 3 && event.data.source === 8) {
+ for (const addition of event.data.adds ?? [])
+ addition.rule = sanitizeUrlReferences(addition.rule);
+ } else if (event.type === 3 && event.data.source === 13 && event.data.set?.value != null) {
+ event.data.set.value = sanitizeUrlReferences(event.data.set.value);
+ }
+ return event;
+}
+
+export function createReplayPrivacyPlugin(getPathname: () => string): ReplayPlugin {
+ return {
+ name: 'librechat-url-privacy',
+ options: undefined,
+ // rrweb's plugin type permits arbitrary extensions, but this plugin only preserves/redacts events.
+ eventProcessor: <TExtend>(event: ReplayEvent) =>
+ sanitizeReplayEvent(event, getPathname()) as ReplayEvent & TExtend,
+ };
+}
+
+/** The SDK calls this hook at export time, including for spans buffered before a route change. */
+export function sanitizeSpanAttributes(attributes: SpanAttributes): SpanAttributes {
+ return Object.fromEntries(
+ Object.entries(attributes).map(([key, value]) => {
+ if (URL_SPAN_ATTRIBUTE.test(key)) {
+ if (/(?:^|\.)query$|(?:^|\.)fragment$/i.test(key)) return [key, ''];
+ if (typeof value === 'string') return [key, sanitizeTelemetryUrl(value)];
+ if (Array.isArray(value)) {
+ return [
+ key,
+ value.map((entry) => (typeof entry === 'string' ? sanitizeTelemetryUrl(entry) : entry)),
+ ];
+ }
+ }
+ return [key, typeof value === 'string' ? sanitizeUrlReferences(value) : value];
+ }),
+ );
+}
diff --git a/client/src/lib/rum/useRum.spec.tsx b/client/src/lib/rum/useRum.spec.tsx
index d05966952a..bb812fe57e 100644
--- a/client/src/lib/rum/useRum.spec.tsx
+++ b/client/src/lib/rum/useRum.spec.tsx
@@ -3,17 +3,21 @@ import useRum from './useRum';
const mockGetSessionId = jest.fn<string | undefined, []>();
const mockInit = jest.fn();
+const mockStopSessionRecorder = jest.fn();
+const mockResumeSessionRecorder = jest.fn();
const mockAddAction = jest.fn();
const mockSetGlobalAttributes = jest.fn();
const mockUseGetStartupConfig = jest.fn();
const mockUseAuthContext = jest.fn();
const mockUseLocation = jest.fn();
-jest.mock('@hyperdx/browser', () => ({
+jest.mock('./browser', () => ({
__esModule: true,
default: {
addAction: (...args: unknown[]) => mockAddAction(...args),
init: (...args: unknown[]) => mockInit(...args),
+ stopSessionRecorder: () => mockStopSessionRecorder(),
+ resumeSessionRecorder: () => mockResumeSessionRecorder(),
getSessionId: () => mockGetSessionId(),
setGlobalAttributes: (...args: unknown[]) => mockSetGlobalAttributes(...args),
},
@@ -92,6 +96,8 @@ describe('useRum', () => {
apiKey: 'public-token',
consoleCapture: false,
disableReplay: true,
+ maskAllInputs: true,
+ maskAllText: true,
service: 'librechat-web',
tracePropagationTargets: ['https://librechat.example.com'],
url: 'https://rum.example.com',
@@ -113,6 +119,7 @@ describe('useRum', () => {
expect.objectContaining({ init: expect.any(Function) }),
expect.any(Function),
);
+ expect(mockResumeSessionRecorder).not.toHaveBeenCalled();
});
it('does not initialize RUM for unsupported auth modes', async () => {
@@ -136,6 +143,179 @@ describe('useRum', () => {
expect(discardEarlyRumQueue).toHaveBeenCalled();
});
+ it('captures masked replays only when opted in and stops recording on unmount', async () => {
+ mockUseGetStartupConfig.mockReturnValue({
+ isFetched: true,
+ data: {
+ rum: {
+ provider: 'hyperdx',
+ enabled: true,
+ url: '/api/rum',
+ serviceName: 'librechat-web',
+ authMode: 'proxy',
+ sessionReplay: { enabled: true },
+ disableReplay: true,
+ },
+ },
+ });
+
+ const { unmount } = renderHook(() => useRum());
+ await waitFor(() => expect(mockResumeSessionRecorder).toHaveBeenCalled());
+ expect(mockInit).toHaveBeenCalledWith(
+ expect.objectContaining({ disableReplay: false, maskAllInputs: true, maskAllText: true }),
+ );
+ unmount();
+ expect(mockStopSessionRecorder).toHaveBeenCalledTimes(1);
+ });
+
+ it('honors an explicit replay-off policy over a legacy replay opt-in', async () => {
+ mockUseGetStartupConfig.mockReturnValue({
+ isFetched: true,
+ data: {
+ rum: {
+ provider: 'hyperdx',
+ enabled: true,
+ url: '/api/rum',
+ serviceName: 'librechat-web',
+ authMode: 'proxy',
+ sessionReplay: { enabled: false },
+ disableReplay: false,
+ },
+ },
+ });
+ renderHook(() => useRum());
+ await waitFor(() => expect(mockInit).toHaveBeenCalled());
+ expect(mockInit).toHaveBeenCalledWith(expect.objectContaining({ disableReplay: true }));
+ expect(mockResumeSessionRecorder).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ '/login',
+ '/login/2fa',
+ '/login/2fa/setup',
+ '/register',
+ '/reset-password',
+ '/verify',
+ '/oauth/success',
+ ])('does not start replay on %s even in public-token mode', async (pathname) => {
+ mockUseAuthContext.mockReturnValue({ token: undefined, user: undefined });
+ mockUseLocation.mockReturnValue({ pathname, search: '?tempToken=fake-login-token' });
+ mockUseGetStartupConfig.mockReturnValue({
+ isFetched: true,
+ data: {
+ rum: {
+ provider: 'hyperdx',
+ enabled: true,
+ url: 'https://collector.example',
+ serviceName: 'librechat-web',
+ authMode: 'publicToken',
+ publicToken: 'public-test-key',
+ sessionReplay: { enabled: true },
+ },
+ },
+ });
+ renderHook(() => useRum());
+ await waitFor(() => expect(mockInit).toHaveBeenCalled());
+ expect(mockInit).toHaveBeenCalledWith(expect.objectContaining({ disableReplay: true }));
+ expect(mockResumeSessionRecorder).not.toHaveBeenCalled();
+ });
+
+ it('stops recording on an auth-route transition even while a session token remains present', async () => {
+ mockUseGetStartupConfig.mockReturnValue({
+ isFetched: true,
+ data: {
+ rum: {
+ provider: 'hyperdx',
+ enabled: true,
+ url: '/api/rum',
+ serviceName: 'librechat-web',
+ authMode: 'proxy',
+ sessionReplay: { enabled: true },
+ },
+ },
+ });
+ const { rerender } = renderHook(() => useRum());
+ await waitFor(() => expect(mockResumeSessionRecorder).toHaveBeenCalledTimes(1));
+ mockUseLocation.mockReturnValue({
+ pathname: '/login/2fa',
+ search: '?tempToken=fake-login-token',
+ });
+ rerender();
+ await waitFor(() => expect(mockInit).toHaveBeenCalledTimes(2));
+ expect(mockStopSessionRecorder).toHaveBeenCalledTimes(1);
+ expect(mockInit).toHaveBeenLastCalledWith(expect.objectContaining({ disableReplay: true }));
+ expect(mockResumeSessionRecorder).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops recording when proxy authentication is lost', async () => {
+ mockUseGetStartupConfig.mockReturnValue({
+ isFetched: true,
+ data: {
+ rum: {
+ provider: 'hyperdx',
+ enabled: true,
+ url: '/api/rum',
+ serviceName: 'librechat-web',
+ authMode: 'proxy',
+ disableReplay: false,
+ },
+ },
+ });
+
+ const { rerender } = renderHook(() => useRum());
+ await waitFor(() => expect(mockResumeSessionRecorder).toHaveBeenCalled());
+ mockUseAuthContext.mockReturnValue({ token: undefined, user: undefined });
+ rerender();
+ expect(mockStopSessionRecorder).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops an active recorder when replay is disabled in startup config', async () => {
+ let rum = {
+ provider: 'hyperdx',
+ enabled: true,
+ url: '/api/rum',
+ serviceName: 'librechat-web',
+ authMode: 'proxy',
+ disableReplay: false,
+ };
+ mockUseGetStartupConfig.mockImplementation(() => ({ isFetched: true, data: { rum } }));
+ const { rerender } = renderHook(() => useRum());
+ await waitFor(() => expect(mockResumeSessionRecorder).toHaveBeenCalledTimes(1));
+
+ rum = { ...rum, disableReplay: true };
+ rerender();
+ await waitFor(() => expect(mockInit).toHaveBeenCalledTimes(2));
+ expect(mockStopSessionRecorder).toHaveBeenCalledTimes(1);
+ expect(mockResumeSessionRecorder).toHaveBeenCalledTimes(1);
+ expect(mockInit).toHaveBeenLastCalledWith(expect.objectContaining({ disableReplay: true }));
+ });
+
+ it('does not re-sample general RUM when replay policy changes', async () => {
+ const random = jest.spyOn(Math, 'random').mockReturnValueOnce(0.1).mockReturnValue(0.9);
+ try {
+ let rum = {
+ provider: 'hyperdx',
+ enabled: true,
+ url: '/api/rum',
+ serviceName: 'librechat-web',
+ authMode: 'proxy',
+ sessionReplay: { enabled: true },
+ sampleRate: 0.5,
+ };
+ mockUseGetStartupConfig.mockImplementation(() => ({ isFetched: true, data: { rum } }));
+ const { rerender } = renderHook(() => useRum());
+ await waitFor(() => expect(mockInit).toHaveBeenCalledTimes(1));
+ rum = { ...rum, sessionReplay: { enabled: false } };
+ rerender();
+ await waitFor(() => expect(mockInit).toHaveBeenCalledTimes(2));
+ expect(random).toHaveBeenCalledTimes(1);
+ expect(mockStopSessionRecorder).toHaveBeenCalledTimes(1);
+ expect(mockInit).toHaveBeenLastCalledWith(expect.objectContaining({ disableReplay: true }));
+ } finally {
+ random.mockRestore();
+ }
+ });
+
it('discards the early RUM queue when sampling excludes the page', async () => {
mockUseGetStartupConfig.mockReturnValue({
isFetched: true,
@@ -262,6 +442,8 @@ describe('useRum', () => {
apiKey: 'librechat-rum-proxy',
consoleCapture: false,
disableReplay: true,
+ maskAllInputs: true,
+ maskAllText: true,
service: 'librechat-web',
tracePropagationTargets: undefined,
url: '/api/rum',
diff --git a/client/src/lib/rum/useRum.ts b/client/src/lib/rum/useRum.ts
index 0482dbf82a..2ec7a75696 100644
--- a/client/src/lib/rum/useRum.ts
+++ b/client/src/lib/rum/useRum.ts
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import type { TRumConfig, TUser } from 'librechat-data-provider';
import type { HyperDXActionClient } from './diagnostics';
+import type { BrowserConfig } from './browser';
import {
discardEarlyRumQueue,
queueSpaRouteChange,
@@ -12,6 +13,7 @@ import {
import { startClientLogs, stopClientLogs } from './logs';
import { useGetStartupConfig } from '~/data-provider';
import { useAuthContext } from '~/hooks/AuthContext';
+import { isReplayRouteAllowed } from './privacy';
import { normalizeRumPath } from './routes';
import { getClientBuildId } from './build';
@@ -21,17 +23,11 @@ let rumProxyToken: string | undefined;
let rumProxyFetchPatched = false;
type HyperDXBrowser = HyperDXActionClient & {
- init: (config: {
- advancedNetworkCapture: boolean;
- apiKey: string;
- consoleCapture: boolean;
- disableReplay: boolean;
- service: string;
- tracePropagationTargets?: string[];
- url: string;
- }) => void;
+ init: (config: BrowserConfig) => void;
setGlobalAttributes: (attributes: Record<string, string>) => void;
getSessionId?: () => string | undefined;
+ stopSessionRecorder: () => void;
+ resumeSessionRecorder: () => void;
};
function shouldInitializeRum(config: TRumConfig | undefined, token: string | undefined): boolean {
@@ -156,7 +152,7 @@ function buildGlobalAttributes(
}
async function loadHyperDX(): Promise<HyperDXBrowser> {
- const module = await import('@hyperdx/browser');
+ const module = await import('./browser');
return module.default;
}
@@ -169,6 +165,9 @@ export default function useRum(): void {
const sampledInRef = useRef<boolean>(true);
const hyperDxRef = useRef<HyperDXBrowser | undefined>(undefined);
const rumConfig = startupConfig?.rum;
+ const replayEnabled =
+ (rumConfig?.sessionReplay?.enabled ?? rumConfig?.disableReplay === false) &&
+ isReplayRouteAllowed(location.pathname);
const shouldBufferRoutes = !startupConfigFetched || !!rumConfig;
const route = useMemo(() => normalizeRumPath(location.pathname), [location.pathname]);
const routeRef = useRef<string>(route);
@@ -182,10 +181,11 @@ export default function useRum(): void {
routeRef.current = route;
}, [route, shouldBufferRoutes]);
- /** Leaving the authenticated layout (e.g. for a share link) ends this session's log export. */
+ /** Leaving the RUM layout (e.g. for a share link) ends this session's recording and log export. */
useEffect(
() => () => {
stopClientLogs();
+ hyperDxRef.current?.stopSessionRecorder();
hyperDxRef.current = undefined;
initializedKeyRef.current = undefined;
},
@@ -197,12 +197,14 @@ export default function useRum(): void {
if (startupConfigFetched) {
discardEarlyRumQueue();
stopClientLogs();
+ hyperDxRef.current?.stopSessionRecorder();
}
return;
}
if (!shouldInitializeRum(rumConfig, token)) {
stopClientLogs();
+ hyperDxRef.current?.stopSessionRecorder();
if (rumConfig?.authMode === 'proxy') {
rumProxyToken = undefined;
hyperDxRef.current = undefined;
@@ -222,23 +224,32 @@ export default function useRum(): void {
}
const identity = config.authMode === 'proxy' ? JSON.stringify([user?.tenantId, user?.id]) : '';
- const initKey = [config.url, config.serviceName, config.authMode, apiKey, identity].join(':');
+ const samplingKey = [config.url, config.serviceName, config.authMode, apiKey, identity].join(
+ ':',
+ );
+ const initKey = [samplingKey, replayEnabled].join(':');
const getSessionId = () => hyperDxRef.current?.getSessionId?.();
if (initializedKeyRef.current === initKey) {
if (hyperDxRef.current) {
restoreRumEmitter(hyperDxRef.current);
+ if (replayEnabled) {
+ hyperDxRef.current.resumeSessionRecorder();
+ }
}
syncClientLogs(config, getSessionId);
return;
}
- if (sampledInitKeyRef.current !== initKey) {
- /* Retire the previous account's queue and correlation before accepting new records. */
- stopClientLogs();
- hyperDxRef.current = undefined;
- initializedKeyRef.current = undefined;
- sampledInitKeyRef.current = initKey;
+ /* Retire the previous recorder and correlation before accepting new records. */
+ stopClientLogs();
+ hyperDxRef.current?.stopSessionRecorder();
+ hyperDxRef.current = undefined;
+ initializedKeyRef.current = undefined;
+
+ // Changing replay policy must not re-roll the general RUM sampling decision.
+ if (sampledInitKeyRef.current !== samplingKey) {
+ sampledInitKeyRef.current = samplingKey;
sampledInRef.current =
typeof config.sampleRate === 'number' ? Math.random() < config.sampleRate : true;
}
@@ -263,7 +274,10 @@ export default function useRum(): void {
advancedNetworkCapture: config.advancedNetworkCapture ?? false,
apiKey,
consoleCapture: config.consoleCapture ?? false,
- disableReplay: config.disableReplay ?? true,
+ disableReplay: !replayEnabled,
+ // Mask chat text and typed values before replay events leave the browser.
+ maskAllInputs: true,
+ maskAllText: true,
service: config.serviceName,
tracePropagationTargets: config.tracePropagationTargets,
url: config.url,
@@ -272,6 +286,9 @@ export default function useRum(): void {
hyperDxRef.current = HyperDX;
initializedKeyRef.current = initKey;
HyperDX.setGlobalAttributes(buildGlobalAttributes(user, config, routeRef.current));
+ if (replayEnabled) {
+ HyperDX.resumeSessionRecorder();
+ }
startRumDiagnostics(HyperDX, () => routeRef.current);
})
.catch(() => undefined);
@@ -279,7 +296,7 @@ export default function useRum(): void {
return () => {
cancelled = true;
};
- }, [rumConfig, startupConfigFetched, token, user]);
+ }, [rumConfig, replayEnabled, startupConfigFetched, token, user]);
useEffect(() => {
hyperDxRef.current?.setGlobalAttributes(
diff --git a/client/src/routes/__tests__/RouteErrorBoundary.spec.tsx b/client/src/routes/__tests__/RouteErrorBoundary.spec.tsx
index 24f3caa1e6..94bec897b8 100644
--- a/client/src/routes/__tests__/RouteErrorBoundary.spec.tsx
+++ b/client/src/routes/__tests__/RouteErrorBoundary.spec.tsx
@@ -30,9 +30,15 @@ jest.mock('~/data-provider', () => ({
jest.mock('~/hooks/AuthContext', () => ({
useAuthContext: () => ({ token: 'session-jwt', user: { id: 'user-1' } }),
}));
-jest.mock('@hyperdx/browser', () => ({
+jest.mock('~/lib/rum/browser', () => ({
__esModule: true,
- default: { init: jest.fn(), addAction: jest.fn(), setGlobalAttributes: jest.fn() },
+ default: {
+ init: jest.fn(),
+ addAction: jest.fn(),
+ setGlobalAttributes: jest.fn(),
+ stopSessionRecorder: jest.fn(),
+ resumeSessionRecorder: jest.fn(),
+ },
}));
type ErrorFactory = () => unknown;
diff --git a/client/vite.config.ts b/client/vite.config.ts
index 76e8a6e3fb..36c8d98174 100644
--- a/client/vite.config.ts
+++ b/client/vite.config.ts
@@ -249,6 +249,11 @@ export default defineConfig(({ command }) => ({
test: /node_modules[\\/](dompurify|uuid|dayjs)[\\/]/,
priority: 1,
},
+ {
+ name: 'utilities',
+ test: /node_modules[\\/]lodash(?:\.[^\\/]+)?[\\/]/,
+ priority: 1,
+ },
{
name(id: string) {
const normalizedId = id.replace(/\\/g, '/');
@@ -257,7 +262,13 @@ export default defineConfig(({ command }) => ({
return 'polyfills';
}
- if (normalizedId.includes('@hyperdx/')) {
+ if (
+ normalizedId.includes('@hyperdx/') ||
+ normalizedId.includes('@opentelemetry/') ||
+ /\/node_modules\/(?:rrweb(?:-snapshot)?|@rrweb\/[^/]+|fflate|protobufjs|long)\//.test(
+ normalizedId,
+ )
+ ) {
return 'rum';
}
diff --git a/e2e/README.md b/e2e/README.md
index 64131b11a3..a5bd1e9d0b 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -2,6 +2,22 @@
The mock e2e profile is the safest default for generated tests. It starts LibreChat with `e2e/config/librechat.e2e.yaml`, injects an in-process fake LLM (via `LIBRECHAT_TEST_RUN_HOOK`), creates an authenticated e2e user, and avoids real provider credentials.
+## RUM privacy export regressions
+
+Run the real HyperDX/OpenTelemetry SDK export checks without a running LibreChat,
+database, collector, or model provider:
+
+```sh
+npx playwright test --config=e2e/playwright.config.rum.ts
+```
+
+The fixture bundles the production RUM adapter, records a synthetic DOM in Chromium,
+and inspects the actual OTLP requests (including gzip/protobuf replay batches). It
+checks proxy and direct-token modes, metadata/DOM URL redaction, and fresh and
+already-recording transitions to a two-factor URL containing a fake login token.
+Playwright traces are disabled so authentication-shaped test data is not retained in
+HAR/trace artifacts.
+
## Automatic title regressions
The standard mock profile disables automatic titles. CI runs the title-enabled cases once on the first memory shard. To run them locally after building the app:
diff --git a/e2e/playwright.config.rum.ts b/e2e/playwright.config.rum.ts
new file mode 100644
index 0000000000..9802e6e8ce
--- /dev/null
+++ b/e2e/playwright.config.rum.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from '@playwright/test';
+
+export default defineConfig({
+ testDir: './rum',
+ outputDir: './rum/.test-results',
+ workers: 1,
+ retries: 0,
+ timeout: 60_000,
+ reporter: 'line',
+ use: { headless: true, trace: 'off' },
+});
diff --git a/e2e/rum/privacy.spec.ts b/e2e/rum/privacy.spec.ts
new file mode 100644
index 0000000000..71eae0d1a6
--- /dev/null
+++ b/e2e/rum/privacy.spec.ts
@@ -0,0 +1,167 @@
+import { build } from 'vite';
+import { resolve } from 'node:path';
+import { gunzipSync } from 'node:zlib';
+import { test, expect } from '@playwright/test';
+import type { Page, Route } from '@playwright/test';
+import type browser from '../../client/src/lib/rum/browser';
+
+declare global {
+ interface Window {
+ RumPrivacyHarness: { default: typeof browser };
+ }
+}
+
+let sdkBundle: string;
+
+test.beforeAll(async () => {
+ const result = await build({
+ configFile: false,
+ logLevel: 'silent',
+ define: { 'process.env.NODE_ENV': JSON.stringify('production') },
+ build: {
+ write: false,
+ minify: false,
+ lib: {
+ entry: resolve(__dirname, '../../client/src/lib/rum/browser.ts'),
+ name: 'RumPrivacyHarness',
+ formats: ['iife'],
+ },
+ rollupOptions: { output: { exports: 'named' } },
+ },
+ });
+ const output = Array.isArray(result) ? result[0] : result;
+ if (!('output' in output)) throw new Error('Expected SDK fixture bundle');
+ const chunk = output.output.find((entry) => entry.type === 'chunk');
+ if (!chunk || chunk.type !== 'chunk') throw new Error('Expected SDK fixture JavaScript');
+ sdkBundle = chunk.code;
+});
+
+async function fixture(page: Page, secret: string) {
+ const traces: Buffer[] = [];
+ const replays: Buffer[] = [];
+ const capture = async (route: Route) => {
+ const request = route.request();
+ const body = request.postDataBuffer();
+ if (body) {
+ const decoded = body[0] === 31 && body[1] === 139 ? gunzipSync(body) : body;
+ (request.url().endsWith('/v1/logs') ? replays : traces).push(decoded);
+ }
+ await route.fulfill({
+ status: 200,
+ body: '{}',
+ headers: {
+ 'access-control-allow-origin': '*',
+ 'access-control-allow-headers': 'authorization, content-type, content-encoding',
+ 'access-control-allow-methods': 'POST, OPTIONS',
+ },
+ });
+ };
+ await page.route('http://collector.test/**', capture);
+ await page.route('http://librechat.test/**', async (route) => {
+ if (new URL(route.request().url()).pathname.startsWith('/api/rum/')) {
+ await capture(route);
+ return;
+ }
+ await route.fulfill({
+ contentType: 'text/html',
+ body: `<!doctype html><html><head><base href="/"></head><body>
+ <textarea aria-label="Prompt"></textarea>
+ <a id="sensitive-link" href="https://alice:${secret}@example.test/resource?token=${secret}#${secret}">Link</a>
+ <a id="relative-link" href="/document?token=${secret}">Relative link</a>
+ </body></html>`,
+ });
+ });
+ return { traces, replays };
+}
+
+for (const mode of ['proxy', 'direct'] as const) {
+ test(`${mode}: actual SDK exports scrub metadata, DOM URLs, mutations and auth transitions`, async ({
+ page,
+ }) => {
+ const secret = `fake-2fa-token-${Date.now()}`;
+ const { traces, replays } = await fixture(page, secret);
+ await page.goto(`http://librechat.test/c/new?tempToken=${secret}#${secret}`);
+ await page.addScriptTag({ content: sdkBundle });
+ await page.evaluate(
+ ({ mode }) =>
+ window.RumPrivacyHarness.default.init({
+ apiKey: 'synthetic-test-key',
+ service: 'rum-privacy-test',
+ url: mode === 'proxy' ? 'http://librechat.test/api/rum' : 'http://collector.test',
+ disableReplay: false,
+ advancedNetworkCapture: false,
+ consoleCapture: false,
+ maskAllInputs: true,
+ maskAllText: true,
+ }),
+ { mode },
+ );
+ await page.getByRole('textbox', { name: 'Prompt' }).fill(secret);
+ await page.evaluate((value) => {
+ document
+ .getElementById('relative-link')
+ ?.setAttribute('href', `/changed?tempToken=${value}#${value}`);
+ window.RumPrivacyHarness.default.addAction('allowed-page-privacy-marker');
+ }, secret);
+ await expect.poll(() => replays.length, { timeout: 20_000 }).toBeGreaterThan(0);
+ await expect
+ .poll(() => traces.some((body) => body.includes('allowed-page-privacy-marker')), {
+ timeout: 20_000,
+ })
+ .toBe(true);
+ expect(replays.some((body) => body.includes('rum.rr-web'))).toBe(true);
+ expect(replays.some((body) => body.includes('http://librechat.test/c/new'))).toBe(true);
+ expect(replays.some((body) => body.includes('https://example.test/resource'))).toBe(true);
+ expect(replays.some((body) => body.includes('/changed'))).toBe(true);
+
+ const batchesBeforeAuth = replays.length;
+ await page.evaluate((value) => {
+ history.pushState({}, '', `/login/2fa?tempToken=${value}#${value}`);
+ document.body.innerHTML =
+ '<main data-testid="auth-screen-must-not-be-recorded">Two-factor authentication</main>';
+ window.RumPrivacyHarness.default.addAction('auth-transition-privacy-marker');
+ }, secret);
+ await expect
+ .poll(() => traces.some((body) => body.includes('auth-transition-privacy-marker')), {
+ timeout: 20_000,
+ })
+ .toBe(true);
+ // Observe the post-navigation replay flush too, not just the earlier allowed-page batch.
+ await expect.poll(() => replays.length, { timeout: 20_000 }).toBeGreaterThan(batchesBeforeAuth);
+ expect(traces.some((body) => body.includes('http://librechat.test/login/2fa'))).toBe(true);
+ for (const body of [...traces, ...replays]) {
+ expect(body.includes(secret)).toBe(false);
+ expect(body.includes('auth-screen-must-not-be-recorded')).toBe(false);
+ }
+ });
+
+ test(`${mode}: a fresh two-factor URL never starts the actual recorder`, async ({ page }) => {
+ const secret = `fake-login-challenge-${Date.now()}`;
+ const { traces, replays } = await fixture(page, secret);
+ await page.goto(`http://librechat.test/login/2fa?tempToken=${secret}`);
+ await page.addScriptTag({ content: sdkBundle });
+ await page.evaluate(
+ ({ mode }) => {
+ window.RumPrivacyHarness.default.init({
+ apiKey: 'synthetic-test-key',
+ service: 'rum-privacy-test',
+ url: mode === 'proxy' ? 'http://librechat.test/api/rum' : 'http://collector.test',
+ disableReplay: false,
+ advancedNetworkCapture: false,
+ consoleCapture: false,
+ maskAllInputs: true,
+ maskAllText: true,
+ });
+ window.RumPrivacyHarness.default.addAction('two-factor-privacy-marker');
+ },
+ { mode },
+ );
+ await expect
+ .poll(() => traces.some((body) => body.includes('two-factor-privacy-marker')), {
+ timeout: 20_000,
+ })
+ .toBe(true);
+ expect(replays).toHaveLength(0);
+ for (const body of traces) expect(body.includes(secret)).toBe(false);
+ });
+}
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 98daf5e775..9ee5c54419 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -7,6 +7,15 @@ version: 1.3.17
# Cache settings: Set to true to enable caching
cache: true
+# Browser telemetry and session recording are independent opt-ins. Collector URL,
+# authentication and service settings remain in .env. YAML flags override .env;
+# omitting them preserves the corresponding environment settings.
+# telemetry:
+# rum:
+# enabled: true
+# sessionReplay:
+# enabled: false # Explicitly opt in to masked DOM/input recordings.
+
# Chat Projects: the ceilings a single project may reach. Every field is optional and
# defaults to the value shown, which is the behavior when the block is absent.
projects:
diff --git a/package-lock.json b/package-lock.json
index 94cdd55455..711e3fda06 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -864,13 +864,17 @@
"@dicebear/collection": "^9.4.3",
"@dicebear/core": "^9.4.3",
"@headlessui/react": "^2.1.2",
- "@hyperdx/browser": "^0.24.0",
+ "@hyperdx/otel-web": "0.18.0",
+ "@hyperdx/otel-web-session-recorder": "2.0.0",
"@librechat/chat": "*",
"@librechat/client": "*",
"@marsidev/react-turnstile": "^1.1.0",
"@mcp-ui/client": "^5.7.0",
"@modelcontextprotocol/ext-apps": "^1.7.4",
"@monaco-editor/react": "^4.7.0",
+ "@opentelemetry/exporter-trace-otlp-http": "0.218.0",
+ "@opentelemetry/resources": "2.7.1",
+ "@opentelemetry/sdk-trace-base": "2.7.1",
"@radix-ui/react-accordion": "^1.2.20",
"@radix-ui/react-alert-dialog": "^1.1.23",
"@radix-ui/react-checkbox": "^1.3.11",
@@ -6955,16 +6959,6 @@
"url": "https://github.com/sponsors/nzakas"
}
},
- "node_modules/@hyperdx/browser": {
- "version": "0.24.0",
- "resolved": "https://registry.npmjs.org/@hyperdx/browser/-/browser-0.24.0.tgz",
- "integrity": "sha512-DTk6Er+RKMe1O9e1uE3ORYl/LLRPlBeVwdUvHOYtqCSJLGcoUbhxyiX6msiTFRbfYu+pohkapxpJ7khYxYYq9g==",
- "license": "Apache-2.0",
- "dependencies": {
- "@hyperdx/otel-web": "0.18.0",
- "@hyperdx/otel-web-session-recorder": "2.0.0"
- }
- },
"node_modules/@hyperdx/instrumentation-exception": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@hyperdx/instrumentation-exception/-/instrumentation-exception-0.3.0.tgz",
@@ -40737,6 +40731,7 @@
"croner": "^10.0.1",
"express-rate-limit": "^8.5.1",
"helmet": "^8.3.0",
+ "protobufjs": "^7.6.5",
"proxy-from-env": "^2.1.0",
"re2js": "^2.8.6"
},
diff --git a/packages/api/package.json b/packages/api/package.json
index 4be37a119c..255589855e 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -177,6 +177,7 @@
"croner": "^10.0.1",
"express-rate-limit": "^8.5.1",
"helmet": "^8.3.0",
+ "protobufjs": "^7.6.5",
"proxy-from-env": "^2.1.0",
"re2js": "^2.8.6"
}
diff --git a/packages/api/src/app/metrics.ts b/packages/api/src/app/metrics.ts
index 5bdb33d3a4..1016bf2bb8 100644
--- a/packages/api/src/app/metrics.ts
+++ b/packages/api/src/app/metrics.ts
@@ -168,6 +168,7 @@ export type GenerationStreamAttachmentOutcome =
export type RumProxyEndpoint = 'traces' | 'logs' | 'unknown';
export type RumProxyResult =
| 'success'
+ | 'replay_disabled'
| 'auth_drop'
| 'auth_error'
| 'bad_request'
diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts
index 7133de3499..7580d1fc16 100644
--- a/packages/api/src/index.ts
+++ b/packages/api/src/index.ts
@@ -135,6 +135,8 @@ export * from './stream';
export { memoryDiagnostics } from './utils/memory';
/* RUM */
export * from './rum/proxy';
+export * from './rum/policy';
+export * from './rum/config';
export * from './rum/limiter';
/* OpenAPI */
export { createOpenApiRouter } from './openapi/router';
diff --git a/packages/api/src/rum/config.ts b/packages/api/src/rum/config.ts
new file mode 100644
index 0000000000..444c4a0953
--- /dev/null
+++ b/packages/api/src/rum/config.ts
@@ -0,0 +1,106 @@
+import { logger } from '@librechat/data-schemas';
+import type { TRumConfig, TTelemetryConfig } from 'librechat-data-provider';
+import { getRumProxyClientUrl, isRumProxyEnabled, isRumClientLogsEnabled } from './proxy';
+import { resolveRumPolicy } from './policy';
+import { isEnabled } from '~/utils';
+
+function parseNumber(value: string | undefined): number | undefined {
+ if (!value?.trim()) return undefined;
+ const parsed = Number(value);
+ return Number.isFinite(parsed) ? parsed : undefined;
+}
+
+function parseUrl(value: string | undefined): URL | undefined {
+ try {
+ return value ? new URL(value) : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function isSafeRumUrl(url: URL): boolean {
+ if (url.username || url.password) return false;
+ return (
+ url.protocol === 'https:' ||
+ (url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
+ );
+}
+
+function isSafeTraceTarget(target: string): boolean {
+ return !target.includes('*') && parseUrl(target)?.protocol === 'https:';
+}
+
+/** Publish only browser-safe settings; collector credentials stay server-side. */
+export function getRumConfig(telemetry?: TTelemetryConfig): TRumConfig | undefined {
+ const env = process.env;
+ const policy = resolveRumPolicy(telemetry, env);
+ if (!policy.enabled) return undefined;
+ if (env.RUM_PROVIDER && env.RUM_PROVIDER !== 'hyperdx') {
+ logger.warn(`[config] Unsupported RUM provider "${env.RUM_PROVIDER}", disabling RUM`);
+ return undefined;
+ }
+ const authMode = env.RUM_AUTH_MODE || 'publicToken';
+ if (authMode !== 'publicToken' && authMode !== 'proxy') {
+ logger.warn(`[config] Unsupported RUM auth mode "${authMode}", disabling RUM`);
+ return undefined;
+ }
+
+ let rumUrl: string;
+ if (authMode === 'proxy') {
+ if (!isRumProxyEnabled(telemetry)) {
+ logger.warn('[config] RUM proxy mode requires RUM_PROXY_TARGET_URL, disabling RUM');
+ return undefined;
+ }
+ rumUrl = getRumProxyClientUrl();
+ } else {
+ const url = parseUrl(env.RUM_URL);
+ if (!url || !isSafeRumUrl(url)) {
+ logger.warn('[config] Invalid RUM_URL, disabling RUM');
+ return undefined;
+ }
+ if (!env.RUM_PUBLIC_TOKEN) {
+ logger.warn('[config] RUM publicToken mode requires RUM_PUBLIC_TOKEN, disabling RUM');
+ return undefined;
+ }
+ rumUrl = url.href.replace(/\/$/, '');
+ }
+
+ const rawTargets = (env.RUM_TRACE_PROPAGATION_TARGETS ?? '')
+ .split(',')
+ .map((target) => target.trim())
+ .filter(Boolean);
+ const tracePropagationTargets = rawTargets.filter(isSafeTraceTarget);
+ if (rawTargets.length !== tracePropagationTargets.length) {
+ logger.info('[config] Ignored unsafe RUM trace propagation targets');
+ }
+ const configuredSampleRate = parseNumber(env.RUM_SAMPLE_RATE);
+ const sampleRate =
+ configuredSampleRate != null && configuredSampleRate >= 0 && configuredSampleRate <= 1
+ ? configuredSampleRate
+ : undefined;
+ const consoleCapture = isEnabled(env.RUM_CONSOLE_CAPTURE);
+ const advancedNetworkCapture = isEnabled(env.RUM_ADVANCED_NETWORK_CAPTURE);
+ if (consoleCapture) {
+ logger.warn('[config] RUM console capture is enabled and may collect sensitive browser logs');
+ }
+ if (advancedNetworkCapture) {
+ logger.warn('[config] RUM advanced network capture is enabled and may collect payload data');
+ }
+
+ return {
+ provider: 'hyperdx',
+ enabled: true,
+ url: rumUrl,
+ serviceName: env.RUM_SERVICE_NAME || 'librechat-web',
+ authMode,
+ ...(authMode === 'publicToken' ? { publicToken: env.RUM_PUBLIC_TOKEN } : {}),
+ ...(tracePropagationTargets.length > 0 ? { tracePropagationTargets } : {}),
+ consoleCapture,
+ sessionReplay: policy.sessionReplay,
+ disableReplay: !policy.sessionReplay.enabled,
+ advancedNetworkCapture,
+ ...(sampleRate != null ? { sampleRate } : {}),
+ ...(env.RUM_ENVIRONMENT ? { environment: env.RUM_ENVIRONMENT } : {}),
+ clientLogs: isRumClientLogsEnabled(telemetry),
+ };
+}
diff --git a/packages/api/src/rum/policy.spec.ts b/packages/api/src/rum/policy.spec.ts
new file mode 100644
index 0000000000..e5077228dc
--- /dev/null
+++ b/packages/api/src/rum/policy.spec.ts
@@ -0,0 +1,105 @@
+import { telemetrySchema } from 'librechat-data-provider';
+import type { RumRequest } from './policy';
+import { resolveRumPolicy, loadRumConfig } from './policy';
+
+describe('RUM replay policy', () => {
+ it('keeps RUM and replay off without configuration', () => {
+ expect(resolveRumPolicy(undefined, {})).toEqual({
+ enabled: false,
+ sessionReplay: { enabled: false },
+ });
+ });
+
+ it.each([
+ [{ RUM_ENABLED: 'true' }, true, false],
+ [{ RUM_ENABLED: 'true', RUM_SESSION_REPLAY_ENABLED: 'true' }, true, true],
+ [{ RUM_ENABLED: 'false', RUM_SESSION_REPLAY_ENABLED: 'true' }, false, false],
+ [{ RUM_ENABLED: 'true', RUM_DISABLE_REPLAY: 'false' }, true, true],
+ [
+ { RUM_ENABLED: 'true', RUM_DISABLE_REPLAY: 'false', RUM_SESSION_REPLAY_ENABLED: 'false' },
+ true,
+ false,
+ ],
+ [
+ { RUM_ENABLED: 'true', RUM_DISABLE_REPLAY: 'true', RUM_SESSION_REPLAY_ENABLED: 'true' },
+ true,
+ true,
+ ],
+ [
+ { RUM_ENABLED: 'true', RUM_DISABLE_REPLAY: 'false', RUM_SESSION_REPLAY_ENABLED: 'invalid' },
+ true,
+ false,
+ ],
+ ])('resolves environment policy %p', (env, enabled, replay) => {
+ expect(resolveRumPolicy(undefined, env)).toEqual({
+ enabled,
+ sessionReplay: { enabled: replay },
+ });
+ });
+
+ it('lets YAML explicitly disable replay despite both environment opt-ins', () => {
+ expect(
+ resolveRumPolicy(
+ { rum: { enabled: true, sessionReplay: { enabled: false } } },
+ {
+ RUM_ENABLED: 'true',
+ RUM_SESSION_REPLAY_ENABLED: 'true',
+ RUM_DISABLE_REPLAY: 'false',
+ },
+ ),
+ ).toEqual({ enabled: true, sessionReplay: { enabled: false } });
+ });
+
+ it('treats a raw empty YAML replay block as off before schema defaults are materialized', () => {
+ expect(
+ resolveRumPolicy(
+ { rum: { sessionReplay: {} } },
+ {
+ RUM_ENABLED: 'true',
+ RUM_SESSION_REPLAY_ENABLED: 'true',
+ },
+ ),
+ ).toEqual({ enabled: true, sessionReplay: { enabled: false } });
+ });
+
+ it('lets YAML enable RUM and replay and keeps the RUM master switch authoritative', () => {
+ const replay = { enabled: true };
+ expect(resolveRumPolicy({ rum: { enabled: true, sessionReplay: replay } }, {})).toEqual({
+ enabled: true,
+ sessionReplay: replay,
+ });
+ expect(
+ resolveRumPolicy(
+ { rum: { enabled: false, sessionReplay: replay } },
+ {
+ RUM_ENABLED: 'true',
+ RUM_SESSION_REPLAY_ENABLED: 'true',
+ },
+ ),
+ ).toEqual({ enabled: false, sessionReplay: { enabled: false } });
+ });
+
+ it('validates YAML flags without injecting defaults over existing environment configuration', () => {
+ expect(telemetrySchema.parse({})).toEqual({});
+ expect(telemetrySchema.parse({ rum: { sessionReplay: {} } })).toEqual({
+ rum: { sessionReplay: { enabled: false } },
+ });
+ expect(telemetrySchema.safeParse({ rum: { sessionReplay: { enabled: 'true' } } }).success).toBe(
+ false,
+ );
+ });
+
+ it('loads only the cached deployment config and fails closed if loading fails', async () => {
+ const getAppConfig = jest.fn().mockResolvedValue({ config: { telemetry: {} } });
+ const middleware = loadRumConfig(getAppConfig);
+ const req = {} as RumRequest;
+ const next = jest.fn();
+ await middleware(req, {} as Parameters<typeof middleware>[1], next);
+ expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(req.config?.config?.telemetry).toEqual({});
+ const error = new Error('configuration unavailable');
+ getAppConfig.mockRejectedValueOnce(error);
+ await middleware(req, {} as Parameters<typeof middleware>[1], next);
+ expect(next).toHaveBeenLastCalledWith(error);
+ });
+});
diff --git a/packages/api/src/rum/policy.ts b/packages/api/src/rum/policy.ts
new file mode 100644
index 0000000000..59dba57b51
--- /dev/null
+++ b/packages/api/src/rum/policy.ts
@@ -0,0 +1,37 @@
+import type { TTelemetryConfig } from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
+import type { Request, RequestHandler } from 'express';
+import { isEnabled } from '~/utils';
+
+export type RumRequest = Request & {
+ config?: { config?: { telemetry?: TTelemetryConfig } };
+};
+
+export function resolveRumPolicy(
+ telemetry: TTelemetryConfig | undefined,
+ env: NodeJS.ProcessEnv,
+): { enabled: boolean; sessionReplay: { enabled: boolean } } {
+ const enabled = telemetry?.rum?.enabled ?? isEnabled(env.RUM_ENABLED);
+ const replayConfig = telemetry?.rum?.sessionReplay;
+ const configuredReplay = replayConfig == null ? undefined : (replayConfig.enabled ?? false);
+ const positiveReplay = env.RUM_SESSION_REPLAY_ENABLED?.trim();
+ const legacyReplay = env.RUM_DISABLE_REPLAY?.trim();
+ const replayEnabled =
+ configuredReplay ??
+ (positiveReplay ? isEnabled(positiveReplay) : !!legacyReplay && !isEnabled(legacyReplay));
+ return { enabled, sessionReplay: { enabled: enabled && replayEnabled } };
+}
+
+/** Deployment policy comes from the cached base config, never a browser payload or user override. */
+export function loadRumConfig(
+ getAppConfig: (options: { baseOnly: true }) => Promise<AppConfig>,
+): RequestHandler {
+ return async (req: RumRequest, _res, next) => {
+ try {
+ req.config = await getAppConfig({ baseOnly: true });
+ next();
+ } catch (error) {
+ next(error);
+ }
+ };
+}
diff --git a/packages/api/src/rum/proxy.spec.ts b/packages/api/src/rum/proxy.spec.ts
index c9bdd2c067..6fcf8612d5 100644
--- a/packages/api/src/rum/proxy.spec.ts
+++ b/packages/api/src/rum/proxy.spec.ts
@@ -255,7 +255,7 @@ describe('RUM proxy configuration', () => {
const res = makeResponse();
await proxyRumRequest(
- { path: '/v1/logs', body: Buffer.from('payload'), headers: PROTOBUF_HEADERS } as never,
+ { path: '/v1/logs', body: Buffer.from([10, 0]), headers: PROTOBUF_HEADERS } as never,
res as never,
);
@@ -391,6 +391,8 @@ describe('RUM proxy upstream HTTP contract', () => {
beforeEach(async () => {
process.env = { ...originalEnv };
+ process.env.RUM_ENABLED = 'true';
+ process.env.RUM_SESSION_REPLAY_ENABLED = 'true';
jest.mocked(recordRumProxyRequest).mockClear();
collector = createServer();
await new Promise<void>((resolve) => collector.listen(0, '127.0.0.1', resolve));
@@ -417,6 +419,85 @@ describe('RUM proxy upstream HTTP contract', () => {
return app;
}
+ it('drops stale replay batches without collector acknowledgement while ordinary logs stay enabled', async () => {
+ process.env.RUM_SESSION_REPLAY_ENABLED = 'false';
+ process.env.RUM_CLIENT_LOGS = 'true';
+ const collectorRequest = jest.fn();
+ collector.on('request', collectorRequest);
+ const response = await request(createProxy())
+ .post('/v1/logs')
+ .send({
+ resourceLogs: [
+ {
+ scopeLogs: [
+ {
+ logRecords: [
+ {
+ attributes: [{ key: 'rr-web.event', value: { intValue: '2' } }],
+ body: { stringValue: 'private-recording' },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ expect(response.status).toBe(204);
+ expect(response.headers[RUM_COLLECTOR_ACK_HEADER]).toBeUndefined();
+ expect(collectorRequest).not.toHaveBeenCalled();
+ expect(recordRumProxyRequest).toHaveBeenCalledWith('logs', 'replay_disabled');
+ });
+
+ it('strips replay records from a mixed batch before contacting the collector', async () => {
+ process.env.RUM_SESSION_REPLAY_ENABLED = 'false';
+ process.env.RUM_CONSOLE_CAPTURE = 'true';
+ let received = '';
+ collector.on('request', (req, res) => {
+ req.on('data', (chunk: Buffer) => {
+ received += chunk.toString();
+ });
+ req.on('end', () => {
+ res.writeHead(202);
+ res.end();
+ });
+ });
+ const response = await request(createProxy())
+ .post('/v1/logs')
+ .send({
+ resourceLogs: [
+ {
+ scopeLogs: [
+ {
+ logRecords: [
+ { body: { stringValue: 'ordinary-error' } },
+ {
+ attributes: [{ key: 'rr-web.event', value: { intValue: '2' } }],
+ body: { stringValue: 'private-recording' },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ expect(response.status).toBe(202);
+ expect(received).toContain('ordinary-error');
+ expect(received).not.toContain('private-recording');
+ expect(response.headers[RUM_COLLECTOR_ACK_HEADER]).toBe('true');
+ });
+
+ it('rejects malformed binary logs while replay is off without contacting the collector', async () => {
+ process.env.RUM_SESSION_REPLAY_ENABLED = 'false';
+ const collectorRequest = jest.fn();
+ collector.on('request', collectorRequest);
+ const response = await request(createProxy())
+ .post('/v1/logs')
+ .set('Content-Type', 'application/x-protobuf')
+ .send(Buffer.from([10, 255]));
+ expect(response.status).toBe(400);
+ expect(collectorRequest).not.toHaveBeenCalled();
+ });
+
it.each(['traces', 'logs'])(
'sends only server credentials and intact %s payloads',
async (signal) => {
diff --git a/packages/api/src/rum/proxy.ts b/packages/api/src/rum/proxy.ts
index 00197e10b9..3d5050d783 100644
--- a/packages/api/src/rum/proxy.ts
+++ b/packages/api/src/rum/proxy.ts
@@ -2,8 +2,12 @@ import { validateHeaderValue } from 'node:http';
import { logger } from '@librechat/data-schemas';
import { RUM_COLLECTOR_ACK_HEADER } from 'librechat-data-provider';
import type { Request, Response, RequestHandler } from 'express';
+import type { TTelemetryConfig } from 'librechat-data-provider';
import type { RumProxyEndpoint, RumProxyResult } from '~/app/metrics';
+import type { RumRequest } from './policy';
import { recordRumProxyRequest } from '~/app/metrics';
+import { resolveRumPolicy } from './policy';
+import { filterReplayLogs } from './replay';
import { isEnabled } from '~/utils';
const DEFAULT_PROXY_PATH = '/api/rum';
@@ -62,9 +66,9 @@ export function getRumProxyTargetBaseUrl(): URL | undefined {
return url;
}
-export function isRumProxyEnabled(): boolean {
+export function isRumProxyEnabled(telemetry?: TTelemetryConfig): boolean {
return (
- isEnabled(process.env.RUM_ENABLED) &&
+ resolveRumPolicy(telemetry, process.env).enabled &&
process.env.RUM_AUTH_MODE === 'proxy' &&
getRumProxyTargetBaseUrl() != null
);
@@ -76,8 +80,8 @@ export function isRumProxyEnabled(): boolean {
* its own; proxy mode only, so the logs reach the collector through session auth and never with
* a browser-held ingestion key.
*/
-export function isRumClientLogsEnabled(): boolean {
- return isRumProxyEnabled() && isEnabled(process.env.RUM_CLIENT_LOGS);
+export function isRumClientLogsEnabled(telemetry?: TTelemetryConfig): boolean {
+ return isRumProxyEnabled(telemetry) && isEnabled(process.env.RUM_CLIENT_LOGS);
}
/**
@@ -85,12 +89,11 @@ export function isRumClientLogsEnabled(): boolean {
* session replay produce browser logs, so with all three off the logs route refuses even tabs
* still holding an older startup config, which makes turning `RUM_CLIENT_LOGS` off authoritative.
*/
-export function isRumLogsEndpointEnabled(): boolean {
- if (!isRumProxyEnabled()) {
+export function isRumLogsEndpointEnabled(telemetry?: TTelemetryConfig): boolean {
+ if (!isRumProxyEnabled(telemetry)) {
return false;
}
- const replaySetting = process.env.RUM_DISABLE_REPLAY?.trim();
- const replayEnabled = !!replaySetting && !isEnabled(replaySetting);
+ const replayEnabled = resolveRumPolicy(telemetry, process.env).sessionReplay.enabled;
return (
isEnabled(process.env.RUM_CLIENT_LOGS) ||
isEnabled(process.env.RUM_CONSOLE_CAPTURE) ||
@@ -99,16 +102,16 @@ export function isRumLogsEndpointEnabled(): boolean {
}
/** HTTP gates stay with the proxy policy rather than the CJS route wiring. */
-export const requireRumProxyEnabled: RequestHandler = (_req, res, next) => {
- if (!isRumProxyEnabled()) {
+export const requireRumProxyEnabled: RequestHandler = (req: RumRequest, res, next) => {
+ if (!isRumProxyEnabled(req.config?.config?.telemetry)) {
res.status(404).json({ message: 'RUM proxy is not configured' });
return;
}
next();
};
-export const requireRumLogsEnabled: RequestHandler = (_req, res, next) => {
- if (!isRumLogsEndpointEnabled()) {
+export const requireRumLogsEnabled: RequestHandler = (req: RumRequest, res, next) => {
+ if (!isRumLogsEndpointEnabled(req.config?.config?.telemetry)) {
res.status(404).json({ message: 'RUM logs are not enabled' });
return;
}
@@ -215,7 +218,7 @@ function getProxyHeaders(
}
export async function proxyRumRequest(
- req: Request,
+ req: RumRequest,
res: Response,
upstreamAuthorization?: string,
): Promise<void> {
@@ -234,13 +237,31 @@ export async function proxyRumRequest(
return;
}
- const body = getRequestBody(req);
+ let body = getRequestBody(req);
if (!body) {
recordRumProxyRequest(endpoint, 'bad_request');
res.status(400).json({ message: 'RUM payload is required' });
return;
}
+ if (
+ endpoint === 'logs' &&
+ !resolveRumPolicy(req.config?.config?.telemetry, process.env).sessionReplay.enabled
+ ) {
+ const filtered = filterReplayLogs(body, getHeader(req, 'content-type') ?? '');
+ if (!filtered.ok) {
+ recordRumProxyRequest(endpoint, 'bad_request');
+ res.status(400).json({ message: 'Invalid RUM logs payload' });
+ return;
+ }
+ if (filtered.body == null) {
+ recordRumProxyRequest(endpoint, 'replay_disabled');
+ res.status(204).end();
+ return;
+ }
+ body = filtered.body;
+ }
+
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), getRumProxyTimeoutMs());
try {
diff --git a/packages/api/src/rum/replay.spec.ts b/packages/api/src/rum/replay.spec.ts
new file mode 100644
index 0000000000..adee05b1cf
--- /dev/null
+++ b/packages/api/src/rum/replay.spec.ts
@@ -0,0 +1,117 @@
+import { parse, Writer } from 'protobufjs';
+import { filterReplayLogs } from './replay';
+
+const requestType = parse(`syntax = "proto3";
+ message AnyValue { string stringValue = 1; }
+ message KeyValue { string key = 1; AnyValue value = 2; }
+ message Scope { string name = 1; }
+ message LogRecord { string severityText = 3; AnyValue body = 5; repeated KeyValue attributes = 6; }
+ message ScopeLogs { Scope scope = 1; repeated LogRecord logRecords = 2; string schemaUrl = 3; }
+ message ResourceLogs { repeated ScopeLogs scopeLogs = 2; string schemaUrl = 3; }
+ message ExportLogsServiceRequest { repeated ResourceLogs resourceLogs = 1; }
+`).root.lookupType('ExportLogsServiceRequest');
+
+const ordinary = {
+ severityText: 'ERROR',
+ body: { stringValue: 'ordinary-client-error' },
+ attributes: [{ key: 'route', value: { stringValue: '/c/new' } }],
+};
+const replay = {
+ body: { stringValue: 'private-replay-snapshot' },
+ attributes: [{ key: 'rr-web.event', value: { stringValue: '2' } }],
+};
+const batch = (records = [ordinary, replay], name = 'browser') => ({
+ resourceLogs: [{ schemaUrl: 'schema', scopeLogs: [{ scope: { name }, logRecords: records }] }],
+});
+
+describe.each(['json', 'protobuf', 'octet-stream'] as const)(
+ 'replay-off %s filtering',
+ (encoding) => {
+ const contentType =
+ encoding === 'json'
+ ? 'application/json'
+ : `application/${encoding === 'protobuf' ? 'x-protobuf' : encoding}`;
+ const encode = (value: ReturnType<typeof batch>) =>
+ encoding === 'json'
+ ? JSON.stringify(value)
+ : Buffer.from(requestType.encode(requestType.create(value)).finish());
+ const decode = (value: Buffer | string) =>
+ encoding === 'json'
+ ? JSON.parse(value.toString())
+ : requestType.toObject(requestType.decode(Buffer.from(value)));
+
+ it('drops replay-only batches without forwarding their content', () => {
+ expect(filterReplayLogs(encode(batch([replay])), contentType)).toEqual({
+ ok: true,
+ body: undefined,
+ });
+ });
+
+ it('preserves ordinary records and envelope metadata in mixed batches', () => {
+ const result = filterReplayLogs(encode(batch()), contentType);
+ expect(result.ok).toBe(true);
+ if (!result.ok || !result.body) throw new Error('Expected ordinary log batch');
+ expect(decode(result.body)).toEqual(batch([ordinary]));
+ expect(result.body.toString()).not.toContain('private-replay-snapshot');
+ });
+
+ it('preserves replay-free payloads byte-for-byte', () => {
+ const body = encode(batch([ordinary]));
+ expect(filterReplayLogs(body, contentType)).toEqual({ ok: true, body });
+ });
+
+ it('drops recorder scopes even when a record has no rr-web attributes', () => {
+ expect(filterReplayLogs(encode(batch([ordinary], 'rum.rr-web')), contentType)).toEqual({
+ ok: true,
+ body: undefined,
+ });
+ });
+
+ it('removes the SDK recorder scope while retaining ordinary scopes', () => {
+ const data = batch([ordinary]);
+ data.resourceLogs[0].scopeLogs.push({
+ scope: { name: 'rum.rr-web' },
+ logRecords: [ordinary],
+ });
+ const result = filterReplayLogs(encode(data), contentType);
+ if (!result.ok || !result.body) throw new Error('Expected ordinary log batch');
+ const decoded = decode(result.body);
+ if (encoding === 'json') {
+ expect(decoded.resourceLogs[0].scopeLogs[0].logRecords).toEqual([ordinary]);
+ expect(decoded.resourceLogs[0].scopeLogs[1].logRecords).toEqual([]);
+ } else {
+ expect(decoded).toEqual(batch([ordinary]));
+ }
+ });
+ },
+);
+
+it.each(['not json', '{"resourceLogs":[{"scope_logs":[]}]}', '{"resource_logs":[]}'])(
+ 'rejects malformed or noncanonical JSON envelopes: %s',
+ (body) => {
+ expect(filterReplayLogs(body, 'application/json')).toEqual({ ok: false });
+ },
+);
+
+it.each([Buffer.from([0]), Buffer.from([10, 255]), Buffer.from([8, 1])])(
+ 'rejects malformed protobuf rather than forwarding opaque logs',
+ (body) => {
+ expect(filterReplayLogs(body, 'application/x-protobuf')).toEqual({ ok: false });
+ },
+);
+
+it('preserves unknown protobuf fields and untouched resources', () => {
+ const original = Buffer.from(requestType.encode(requestType.create(batch([ordinary]))).finish());
+ const extra = Buffer.from(Writer.create().uint32(120).uint32(7).finish());
+ const body = Buffer.concat([original, extra]);
+ expect(filterReplayLogs(body, 'application/x-protobuf')).toEqual({ ok: true, body });
+});
+
+it('preserves unknown protobuf fields when removing a replay from a mixed batch', () => {
+ const original = Buffer.from(requestType.encode(requestType.create(batch())).finish());
+ const extra = Buffer.from(Writer.create().uint32(120).uint32(7).finish());
+ const result = filterReplayLogs(Buffer.concat([original, extra]), 'application/x-protobuf');
+ if (!result.ok || !result.body) throw new Error('Expected ordinary log batch');
+ const expected = Buffer.from(requestType.encode(requestType.create(batch([ordinary]))).finish());
+ expect(result.body).toEqual(Buffer.concat([expected, extra]));
+});
diff --git a/packages/api/src/rum/replay.ts b/packages/api/src/rum/replay.ts
new file mode 100644
index 0000000000..b2c4b28f2a
--- /dev/null
+++ b/packages/api/src/rum/replay.ts
@@ -0,0 +1,162 @@
+import { z } from 'zod';
+import { Reader, Writer } from 'protobufjs/minimal';
+
+const attributeSchema = z.object({ key: z.string() }).passthrough();
+const logsSchema = z
+ .object({
+ resourceLogs: z
+ .array(
+ z
+ .object({
+ resource: z.unknown().optional(),
+ schemaUrl: z.string().optional(),
+ scopeLogs: z
+ .array(
+ z
+ .object({
+ schemaUrl: z.string().optional(),
+ scope: z.object({ name: z.string().optional() }).passthrough().optional(),
+ logRecords: z
+ .array(
+ z
+ .object({
+ attributes: z.array(attributeSchema).optional(),
+ })
+ .passthrough(),
+ )
+ .optional(),
+ })
+ .strict(),
+ )
+ .optional(),
+ })
+ .strict(),
+ )
+ .optional(),
+ })
+ .strict();
+
+const isReplayScope = (name: string | undefined): boolean => name === 'rum.rr-web';
+
+type FilteredMessage = { bytes: Uint8Array; records: number; removed: number };
+
+/** Preserve unknown protobuf fields byte-for-byte; inspect only OTLP's nested log-record fields. */
+function filterMessage(
+ bytes: Uint8Array,
+ field: number,
+ filter: (value: Uint8Array) => FilteredMessage,
+): FilteredMessage {
+ const reader = Reader.create(bytes);
+ const parts: Uint8Array[] = [];
+ let records = 0;
+ let removed = 0;
+ while (reader.pos < reader.len) {
+ const start = reader.pos;
+ const tag = reader.uint32();
+ if (tag >>> 3 === 0) throw new Error('Invalid protobuf field');
+ if (tag >>> 3 === field) {
+ if ((tag & 7) !== 2) throw new Error('Invalid protobuf wire type');
+ const result = filter(reader.bytes());
+ records += result.records;
+ removed += result.removed;
+ if (result.removed === 0) {
+ parts.push(bytes.subarray(start, reader.pos));
+ } else if (result.records > 0) {
+ parts.push(Writer.create().uint32(tag).bytes(result.bytes).finish());
+ }
+ } else {
+ reader.skipType(tag & 7);
+ parts.push(bytes.subarray(start, reader.pos));
+ }
+ }
+ return { bytes: Buffer.concat(parts), records, removed };
+}
+
+function stringField(bytes: Uint8Array, field: number): string | undefined {
+ const reader = Reader.create(bytes);
+ let result: string | undefined;
+ while (reader.pos < reader.len) {
+ const tag = reader.uint32();
+ if (tag >>> 3 === 0) throw new Error('Invalid protobuf field');
+ if (tag >>> 3 === field) {
+ if ((tag & 7) !== 2) throw new Error('Invalid protobuf wire type');
+ result = reader.string();
+ } else {
+ reader.skipType(tag & 7);
+ }
+ }
+ return result;
+}
+
+function filterRecord(bytes: Uint8Array): FilteredMessage {
+ let replay = false;
+ // OTLP LogRecord.attributes = field 6; KeyValue.key = field 1.
+ filterMessage(bytes, 6, (attribute) => {
+ replay ||= stringField(attribute, 1)?.startsWith('rr-web.') ?? false;
+ return { bytes: attribute, records: 1, removed: 0 };
+ });
+ return { bytes, records: replay ? 0 : 1, removed: replay ? 1 : 0 };
+}
+
+function filterScope(bytes: Uint8Array): FilteredMessage {
+ const reader = Reader.create(bytes);
+ let replay = false;
+ while (reader.pos < reader.len) {
+ const tag = reader.uint32();
+ if (tag >>> 3 === 0) throw new Error('Invalid protobuf field');
+ if (tag >>> 3 === 1) {
+ if ((tag & 7) !== 2) throw new Error('Invalid protobuf wire type');
+ const scope = reader.bytes();
+ replay ||= isReplayScope(stringField(scope, 1));
+ } else {
+ reader.skipType(tag & 7);
+ }
+ }
+ // ScopeLogs.logRecords = field 2.
+ return filterMessage(bytes, 2, (record) =>
+ replay ? { bytes: record, records: 0, removed: 1 } : filterRecord(record),
+ );
+}
+
+/** Fail closed on malformed logs. Mixed batches retain ordinary records and their resource metadata. */
+export function filterReplayLogs(
+ body: Buffer | string,
+ contentType: string,
+): { ok: true; body?: Buffer | string } | { ok: false } {
+ try {
+ if (contentType.split(';', 1)[0].trim().toLowerCase() !== 'application/json') {
+ const bytes = typeof body === 'string' ? Buffer.from(body) : body;
+ // ExportLogsServiceRequest.resourceLogs = 1; ResourceLogs.scopeLogs = 2.
+ const result = filterMessage(bytes, 1, (resource) => filterMessage(resource, 2, filterScope));
+ if (result.removed === 0) return { ok: true, body };
+ return {
+ ok: true,
+ body: result.records > 0 ? Buffer.from(result.bytes) : undefined,
+ };
+ }
+
+ const parsed = logsSchema.safeParse(JSON.parse(body.toString()));
+ if (!parsed.success) return { ok: false };
+ let removed = 0;
+ let records = 0;
+ for (const resource of parsed.data.resourceLogs ?? []) {
+ for (const scope of resource.scopeLogs ?? []) {
+ scope.logRecords = scope.logRecords?.filter((record) => {
+ const replay =
+ isReplayScope(scope.scope?.name) ||
+ record.attributes?.some((attribute) => attribute.key.startsWith('rr-web.'));
+ if (replay) {
+ removed++;
+ return false;
+ }
+ records++;
+ return true;
+ });
+ }
+ }
+ if (removed === 0) return { ok: true, body };
+ return { ok: true, body: records > 0 ? JSON.stringify(parsed.data) : undefined };
+ } catch {
+ return { ok: false };
+ }
+}
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index 3340ca6471..dee3a3ed83 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -1,4 +1,5 @@
import type { TEndpointsConfig } from './types';
+
import {
allowedAddressesSchema,
agentsEndpointSchema,
@@ -6,6 +7,7 @@ import {
DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
bedrockModels,
configSchema,
+ telemetrySchema,
chatProjectsConfigSchema,
DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,
codeEnvironmentUserConfigSchema,
@@ -28,6 +30,27 @@ import {
resolveEndpointType,
webSearchSchema,
} from './config';
+
+describe('independent browser replay opt-in', () => {
+ it('preserves absent configuration for existing environment-based RUM deployments', () => {
+ expect(configSchema.parse({ version: '1.3.17' }).telemetry).toBeUndefined();
+ expect(telemetrySchema.parse({ rum: { enabled: true } })).toEqual({ rum: { enabled: true } });
+ });
+
+ it('defaults an explicitly configured replay block to off', () => {
+ expect(telemetrySchema.parse({ rum: { enabled: true, sessionReplay: {} } })).toEqual({
+ rum: { enabled: true, sessionReplay: { enabled: false } },
+ });
+ });
+
+ it.each([
+ { rum: { sessionReplay: { enabled: 'true' } } },
+ { rum: { sessionReplay: { enable: false } } },
+ { rum: { enable: true } },
+ ])('rejects invalid or misspelled policy %p', (telemetry) => {
+ expect(telemetrySchema.safeParse(telemetry).success).toBe(false);
+ });
+});
import { EModelEndpoint, isDocumentSupportedProvider } from './schemas';
import { getEndpointFileConfig, mergeFileConfig } from './file-config';
import { DEFAULT_MCP_APP_CSP_LIMITS } from './mcp/csp';
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index f437e67f28..3d75db9717 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -3221,6 +3221,23 @@ export type TTurnstileConfig = z.infer<typeof turnstileSchema>;
/** Distinguishes collector acceptance from the proxy's silent 204 authentication drop. */
export const RUM_COLLECTOR_ACK_HEADER = 'x-librechat-rum-accepted';
+export const telemetrySchema = z
+ .object({
+ rum: z
+ .object({
+ enabled: z.boolean().optional(),
+ sessionReplay: z
+ .object({ enabled: z.boolean().default(false) })
+ .strict()
+ .optional(),
+ })
+ .strict()
+ .optional(),
+ })
+ .strict();
+
+export type TTelemetryConfig = DeepPartial<z.infer<typeof telemetrySchema>>;
+
export type TRumConfig = {
provider: 'hyperdx';
enabled: boolean;
@@ -3231,6 +3248,8 @@ export type TRumConfig = {
tracePropagationTargets?: string[];
consoleCapture?: boolean;
disableReplay?: boolean;
+ /** Positive replay policy; disableReplay is retained for older browser bundles. */
+ sessionReplay?: { enabled: boolean };
advancedNetworkCapture?: boolean;
sampleRate?: number;
environment?: string;
@@ -4088,6 +4107,7 @@ export type TToolCallPreviewsConfig = z.infer<typeof toolCallPreviewsConfigSchem
export const configSchema = z.object({
version: z.string(),
+ telemetry: telemetrySchema.optional(),
permissions: z
.object({
maxWriteAttempts: permissionWriteAttemptsSchema,