Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@
> make sure you follow our [migration guide](https://docs.sentry.io/platforms/react-native/migration/) first.
<!-- prettier-ignore-end -->

## Unreleased

### Features

- Session Replay network details now capture `fetch` (Blob/ArrayBuffer) response bodies ([#6473](https://github.com/getsentry/sentry-react-native/pull/6473))

React Native's `fetch` is built on XMLHttpRequest with `responseType: 'blob'`, so fetch response bodies previously always showed `[UNPARSEABLE_BODY_TYPE]` in the Replay network tab. Text-like binary payloads (JSON, XML, `text/*`, form data) are now read asynchronously and inlined like text bodies — still only for URLs matching `networkDetailAllowUrls` with `networkCaptureBodies` enabled, with the same size cap. Genuinely binary payloads (images, media) remain marked as unparseable.

## 8.19.0

### Features
Expand Down
53 changes: 49 additions & 4 deletions packages/core/src/js/replay/mobilereplay.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import type { Client, DynamicSamplingContext, ErrorEvent, Event, EventHint, Integration, Metric } from '@sentry/core';

import { debug } from '@sentry/core';
import type {
Breadcrumb,
BreadcrumbHint,
Client,
DynamicSamplingContext,
ErrorEvent,
Event,
EventHint,
Integration,
Metric,
} from '@sentry/core';

import { addBreadcrumb, debug } from '@sentry/core';

import type { ResolvedNetworkOptions } from './networkUtils';

Expand All @@ -9,7 +19,12 @@ import { hasHooks } from '../utils/clientutils';
import { isExpoGo, notMobileOs } from '../utils/environment';
import { registerFeatureMarker } from '../utils/featureMarkers';
import { NATIVE } from '../wrapper';
import { makeEnrichXhrBreadcrumbsForMobileReplay } from './xhrUtils';
import {
makeEnrichXhrBreadcrumbsForMobileReplay,
REPLAY_RESOLVED_RESPONSE_BODY_HINT_KEY,
resolveXhrResponseBody,
shouldCaptureResponseBodyAsync,
} from './xhrUtils';

const MOBILE_REPLAY_NETWORK_DETAILS_INTEGRATION_NAME = 'MobileReplayNetworkDetails';
const MOBILE_REPLAY_NETWORK_BODIES_INTEGRATION_NAME = 'MobileReplayNetworkBodies';
Expand Down Expand Up @@ -433,6 +448,36 @@ export const mobileReplayIntegration = (initOptions: MobileReplayOptions = defau

// Wrap beforeSend to run processEvent after user's beforeSend
const clientOptions = client.getOptions();

// Binary (Blob/ArrayBuffer) response bodies — which is every `fetch`
// response, since RN's fetch polyfill uses XHR with responseType 'blob' —
// can only be read asynchronously, but the breadcrumb is forwarded to the
// native SDKs synchronously. Hold such breadcrumbs here (return null),
// read the body, then re-add the same breadcrumb (timestamp is already
// set, so it keeps its original time) with the resolved body and a
// metadata snapshot on the hint — the xhr itself may be reused by then.
if (networkOptions.captureBodies && networkOptions.allowUrls.length > 0) {
const originalBeforeBreadcrumb = clientOptions.beforeBreadcrumb;
clientOptions.beforeBreadcrumb = (breadcrumb: Breadcrumb, hint?: BreadcrumbHint): Breadcrumb | null => {
if (hint && REPLAY_RESOLVED_RESPONSE_BODY_HINT_KEY in hint) {
// second pass with the resolved body — the user's beforeBreadcrumb already ran
return breadcrumb;
}
const result = originalBeforeBreadcrumb ? originalBeforeBreadcrumb(breadcrumb, hint) : breadcrumb;
if (result === null || !shouldCaptureResponseBodyAsync(result, hint, networkOptions)) {
return result;
}
const xhr = hint.xhr;
resolveXhrResponseBody(xhr)
.then(resolved => {
addBreadcrumb(result, { ...hint, [REPLAY_RESOLVED_RESPONSE_BODY_HINT_KEY]: resolved });
})
.then(undefined, (error: unknown) => {
debug.error(`[Sentry] ${MOBILE_REPLAY_INTEGRATION_NAME} Failed to re-add network breadcrumb`, error);
});
return null;
Comment thread
cursor[bot] marked this conversation as resolved.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Held fetch breadcrumbs miss error events

High Severity

Returning null from beforeBreadcrumb while awaiting FileReader drops allow-listed fetch xhr breadcrumbs from the scope until the read finishes. RN fetch always uses responseType: 'blob', and FileReader completion runs after promise microtasks, so errors thrown in fetch response handlers (and hard crashes in that window) no longer include that network breadcrumb — a regression versus the previous synchronous UNPARSEABLE_BODY_TYPE path. Flagged under the PR review correctness guidance for instrumentation that must not lose telemetry on common error paths.

Additional Locations (2)
Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit e479547. Configure here.

};
}
const originalBeforeSend = clientOptions.beforeSend;
clientOptions.beforeSend = async (event: ErrorEvent, hint: EventHint): Promise<ErrorEvent | null> => {
let result: ErrorEvent | null = event;
Expand Down
133 changes: 133 additions & 0 deletions packages/core/src/js/replay/networkUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ function _serializeFormData(formData: FormData): string {

export const NETWORK_BODY_MAX_SIZE = 150_000;

/** How long to wait for an async body read (FileReader) before giving up. */
export const NETWORK_BODY_READ_TIMEOUT_MS = 500;

export const DEFAULT_NETWORK_HEADERS = ['content-type', 'content-length', 'accept'];

const DENY_HEADERS = new Set([
Expand Down Expand Up @@ -174,6 +177,136 @@ export function getBodyString(body: unknown): NetworkBody | undefined {
}
}

/**
* Whether a Content-Type describes a payload that is safe to decode into text
* (JSON, XML, form data, `text/*`). Genuinely binary payloads (images, media,
* octet-stream) are excluded so they stay marked as unparseable.
*/
export function isTextLikeContentType(contentType: string | null | undefined): boolean {
if (!contentType) {
return false;
}
const normalized = contentType.toLowerCase();
return (
normalized.startsWith('text/') ||
normalized.includes('json') ||
normalized.includes('xml') ||
normalized.includes('x-www-form-urlencoded')
);
}

/**
* Read a Blob as UTF-8 text via FileReader (React Native's Blob has no `text()`).
* Rejects on read error, abort or after `timeoutMs`.
*/
export function readBlobAsText(blob: Blob, timeoutMs: number): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
const timeout = setTimeout(() => {
// reject first — abort() may fire onabort synchronously
reject(new Error(`Timed out reading response body after ${timeoutMs}ms`));
try {
reader.abort();
} catch {
// ignore — already rejected
}
}, timeoutMs);
reader.onload = () => {
clearTimeout(timeout);
const result = reader.result;
if (typeof result === 'string') {
resolve(result);
} else {
reject(new Error('FileReader did not produce a string result'));
}
};
reader.onerror = () => {
clearTimeout(timeout);
reject(reader.error ?? new Error('FileReader failed'));
};
reader.onabort = () => {
clearTimeout(timeout);
reject(new Error('FileReader aborted'));
};
reader.readAsText(blob);
});
}

type TextDecoderLike = { decode(input: Uint8Array): string };

/* oxlint-disable eslint(no-bitwise) -- decoding UTF-8 is inherently bit manipulation */
/**
* Decode UTF-8 bytes into a string. Uses the global TextDecoder when the JS
* engine provides one and falls back to a manual decoder otherwise (Hermes
* has no TextDecoder). Invalid sequences decode to U+FFFD.
*/
export function decodeUtf8(bytes: Uint8Array): string {
const TextDecoderConstructor = (globalThis as { TextDecoder?: new () => TextDecoderLike }).TextDecoder;
if (TextDecoderConstructor) {
try {
return new TextDecoderConstructor().decode(bytes);
} catch {
// fall through to the manual decoder
}
}

let out = '';
let i = 0;
while (i < bytes.length) {
const byte = bytes[i] ?? 0;
let codePoint: number;
let extraBytes: number;
if (byte < 0x80) {
codePoint = byte;
extraBytes = 0;
} else if ((byte & 0xe0) === 0xc0) {
codePoint = byte & 0x1f;
extraBytes = 1;
} else if ((byte & 0xf0) === 0xe0) {
codePoint = byte & 0x0f;
extraBytes = 2;
} else if ((byte & 0xf8) === 0xf0) {
codePoint = byte & 0x07;
extraBytes = 3;
} else {
out += '�';
i += 1;
continue;
}

let consumed = 0;
while (consumed < extraBytes && i + 1 + consumed < bytes.length) {
const continuation = bytes[i + 1 + consumed] ?? 0;
if ((continuation & 0xc0) !== 0x80) {
break;
}
codePoint = (codePoint << 6) | (continuation & 0x3f);
consumed += 1;
}

if (consumed < extraBytes) {
// truncated or interrupted sequence: the consumed prefix decodes to one
// U+FFFD and decoding resumes at the offending byte (maximal subpart)
out += '�';
i += consumed + 1;
continue;
}

if (codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) {
// structurally complete sequence encoding an invalid code point
// (surrogate or beyond U+10FFFF): the whole sequence is one U+FFFD
out += '�';
i += extraBytes + 1;
continue;
Comment thread
cursor[bot] marked this conversation as resolved.
}

out += String.fromCodePoint(codePoint);
i += extraBytes + 1;
}
return out;
}
/* oxlint-enable eslint(no-bitwise) */

/**
* Filter a headers map down to the set explicitly captured (defaults + user-supplied)
* and strip authorization-like headers. Header name comparison is case-insensitive;
Expand Down
Loading
Loading