diff --git a/packages/react-native/src/private/webapis/structuredClone/__tests__/structuredClone-itest.js b/packages/react-native/src/private/webapis/structuredClone/__tests__/structuredClone-itest.js index 03ff093daffb..cfcd464c43db 100644 --- a/packages/react-native/src/private/webapis/structuredClone/__tests__/structuredClone-itest.js +++ b/packages/react-native/src/private/webapis/structuredClone/__tests__/structuredClone-itest.js @@ -117,6 +117,16 @@ describe('structuredClone', () => { expectDataCloneError(() => structuredClone(Promise.resolve(4))); }); + it('does not write to WeakMap, WeakSet, or Promise prototypes', () => { + Object.freeze(WeakMap.prototype); + Object.freeze(WeakSet.prototype); + Object.freeze(Promise.prototype); + + expectDataCloneError(() => structuredClone(new WeakMap())); + expectDataCloneError(() => structuredClone(new WeakSet())); + expectDataCloneError(() => structuredClone(new Promise(() => {}))); + }); + it('clones simple objects', () => { const value = {foo: 'bar'}; const clone = structuredClone(value); diff --git a/packages/react-native/src/private/webapis/structuredClone/structuredClone.js b/packages/react-native/src/private/webapis/structuredClone/structuredClone.js index 820534ef2a57..ef64df93f736 100644 --- a/packages/react-native/src/private/webapis/structuredClone/structuredClone.js +++ b/packages/react-native/src/private/webapis/structuredClone/structuredClone.js @@ -295,8 +295,6 @@ export default function structuredClone(value: T): T { } } -const NON_SERIALIZABLE_OBJECT_KEY = Symbol('nonSerializableObject'); - function cloneArrayBuffer(value: ArrayBuffer): ArrayBuffer { const existingClone = memory.get(value); if (existingClone instanceof ArrayBuffer) { @@ -392,16 +390,11 @@ function createErrorClone(value: Error): Error { } function isNonSerializableObject(obj: T): boolean { - // $FlowExpectedError[invalid-in-lhs] - return NON_SERIALIZABLE_OBJECT_KEY in obj; -} - -function markClassAsNonSerializable(cls: Class): void { - // $FlowExpectedError[incompatible-use] - cls.prototype[NON_SERIALIZABLE_OBJECT_KEY] = true; + // Built-in prototypes must not be written to because Hardened JS + // environments (SES) freeze them, so the non-serializable + // built-ins are detected with `instanceof` instead of marking the + // prototypes with e.g. Symbol('nonSerializableObject'). + return ( + obj instanceof WeakMap || obj instanceof WeakSet || obj instanceof Promise + ); } - -// Non-serializable built-ins. -markClassAsNonSerializable(WeakMap); -markClassAsNonSerializable(WeakSet); -markClassAsNonSerializable(Promise);