Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .changeset/web-cross-realm-plain-objects.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@e2e-dev/web": patch
---

`browser.evaluate` now returns a plain object made in a same-origin iframe, such as `iframe.contentWindow.eval('({ a: 1 })')`, instead of failing with `evaluate result must be JSON-safe`.
2 changes: 2 additions & 0 deletions docs/reference/web.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,8 @@ const title = await browser.evaluate<string>('document.title');
evaluates to a function, that function is called with `arg`. Else its
value is the result.
- A promise, from either, is awaited.
- A plain object made in a same-origin iframe, such as one that
`iframe.contentWindow.eval(...)` returns, is returned too.

| Throws | When |
| --- | --- |
Expand Down
31 changes: 27 additions & 4 deletions packages/web/src/evaluation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,36 @@ interface InvalidPageValue {
* Called before the caller's code runs, it takes the intrinsics it needs from
* literals, so code that deletes or replaces `Array`, `Object`, or `JSON`
* cannot reach it. Only JSON passes: `null`, booleans, finite numbers,
* strings, arrays, and plain objects. Anything else throws `{ invalid }` with
* strings, arrays, and plain objects, including those made in another
* same-origin frame. Anything else throws `{ invalid }` with
* the reason `validateJsonValue` gives. Embedded into the page as source, so
* it captures nothing from this module.
*/
export function pageValueEncoder(): (root: unknown) => string | undefined {
const { getPrototypeOf, keys } = ({}).constructor as ObjectConstructor;
const { getOwnPropertyDescriptor, getPrototypeOf, hasOwn, keys } = ({}).constructor as ObjectConstructor;
const objectPrototype: unknown = getPrototypeOf({});
/** An own data property's value, or undefined for an accessor; never runs a getter the page defined. */
const own = (target: object, key: string): unknown => {
const descriptor = getOwnPropertyDescriptor(target, key);
return descriptor !== undefined && hasOwn(descriptor, 'value') ? descriptor.value : undefined;
};
/**
* This realm's Object.prototype, or another same-origin frame's: a prototype with a null
* prototype whose own `constructor` is a function named `Object` that points back to it.
* A Proxy trap that throws during the check means the prototype is not one.
*/
const isObjectPrototype = (prototype: object): boolean => {
if (prototype === objectPrototype) return true;
try {
if (getPrototypeOf(prototype) !== null) return false;
const constructor = own(prototype, 'constructor');
return typeof constructor === 'function'
&& own(constructor, 'name') === 'Object'
&& own(constructor, 'prototype') === prototype;
Comment on lines +75 to +79

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

P2 · Fix before merge · An instance of class Object extends null passes as a plain object

Trigger. browser.evaluate returns an instance of a class named Object that extends null. Example, evaluated in a same-origin iframe:

const C = class Object extends null {
  constructor() { return globalThis.Object.setPrototypeOf({ a: 1 }, new.target.prototype); }
  get total() { return 10; }
};
new C();

The prototype of the instance has a null prototype. Its own constructor is a function, the own name of that function is 'Object', and its own prototype points back. So isObjectPrototype returns true. The check does not use the realm, so an instance made in the evaluating frame passes the same way.

Impact. The class instance is encoded as JSON of its own data, and its prototype members are dropped without an error. The merge base rejected this value. The reference says that a class instance is not a JsonValue and gives INVALID_ARGUMENT (docs/reference/web.mdx:671). The PR description also says that a class instance, "a class named Object included", still fails. The only test of that claim is new (class Object {})() in tests/unit/evaluation.test.ts. That class does not extend null, so the check rejects it at the null-prototype test and the test does not reach the case above.

Evidence. I ran the example above through browser.evaluate in Chromium and WebKit:

merge base 970b74ed4 this head b8d45c006
Chromium INVALID_ARGUMENT: evaluate result must be JSON-safe {"a":1}
WebKit INVALID_ARGUMENT: evaluate result must be JSON-safe {"a":1}

} catch {
return false;
}
};
const { isArray } = ([] as unknown[]).constructor as ArrayConstructor;
const charCodeAt = ''.charCodeAt;
const hex = '0123456789abcdef';
Expand Down Expand Up @@ -88,8 +111,8 @@ export function pageValueEncoder(): (root: unknown) => string | undefined {
throw invalid(`must be JSON-safe, found ${typeof value}`);
}
const array = isArray(value);
const prototype: unknown = getPrototypeOf(value);
if (!array && prototype !== objectPrototype && prototype !== null) throw invalid('must be JSON-safe');
const prototype: object | null = getPrototypeOf(value);
if (!array && prototype !== null && !isObjectPrototype(prototype)) throw invalid('must be JSON-safe');
for (let i = 0; i < ancestors.length; i++) {
if (ancestors[i] === value) throw invalid('contains a cycle');
}
Expand Down
23 changes: 23 additions & 0 deletions packages/web/tests/integration/evaluate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,27 @@ describe('browser.evaluate error boundaries', () => {
await expect(browser.evaluate((n: number) => ({ items: [n, 'two'] }), 1)).resolves.toEqual({ items: [1, 'two'] });
await expect(browser.evaluate('() => [1, 2]')).resolves.toEqual([1, 2]);
});

it('returns a plain object on a page that renamed Object', async () => {
await page.setContent('<script>Object.defineProperty(Object, "name", { value: "Renamed" });</script>');
await expect(browser.evaluate('() => ({ a: 1 })')).resolves.toEqual({ a: 1 });
});

it('returns a plain object made in a same-origin iframe, and still rejects its other objects', async () => {
await page.setContent('<iframe id="f" srcdoc="<p>frame</p>"></iframe>');
await page.frameLocator('#f').locator('p').waitFor();
const inFrame = (expression: string) => `() => document.getElementById("f").contentWindow.eval(${JSON.stringify(expression)})`;
await expect(browser.evaluate(inFrame('({ a: 1, nested: { b: [2] } })'))).resolves.toEqual({ a: 1, nested: { b: [2] } });
await expect(browser.evaluate(inFrame('[1, 2]'))).resolves.toEqual([1, 2]);
for (const expression of [
'new Date(0)',
'new Map()',
'document.body',
'new (class Cart {})()',
'Object.create(Object.create(null))',
'Object.create(new Proxy({}, { getPrototypeOf() { throw new Error("trap"); } }))',
]) {
await expect(browser.evaluate(inFrame(expression))).rejects.toMatchObject({ code: 'INVALID_ARGUMENT', message: 'evaluate result must be JSON-safe' });
}
});
});
47 changes: 47 additions & 0 deletions packages/web/tests/unit/evaluation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* references a module-scoped `__name` helper.
*/

import { createContext, runInContext } from 'node:vm';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { compileEvaluation, decodeEvaluation, pageFunctionSource, pageValueEncoder } from '../../src/evaluation.ts';

Expand Down Expand Up @@ -96,6 +97,52 @@ describe('pageValueEncoder', () => {
expect(() => encodePageValue(cyclic)).toThrow(expect.objectContaining({ invalid: 'contains a cycle' }));
});

it('encodes a plain object made in another realm', () => {
expect(encodePageValue(runInContext('({ a: 1, nested: { b: [2] } })', createContext())))
.toBe('{"a":1,"nested":{"b":[2]}}');
});

it.each([
['a Date', 'new Date(0)'],
['a Map', 'new Map()'],
['a class instance', 'new (class Cart {})()'],
['an instance of a class named Object', 'new (class Object {})()'],
['an object on a null-prototype prototype', 'Object.create(Object.create(null))'],
['an object whose constructor is not a function',
"const p = Object.create(null); p.constructor = { name: 'Object', prototype: p }; Object.create(p)"],
['an object whose constructor is not named Object',
'const p = Object.create(null); p.constructor = function F() {}; p.constructor.prototype = p; Object.create(p)'],
['an object whose constructor does not point back to its prototype',
'const p = Object.create(null); p.constructor = Object; Object.create(p)'],
['an object whose constructor is a getter',
"const p = Object.create(null); const F = function Object() {}; F.prototype = p;"
+ " Object.defineProperty(p, 'constructor', { get: () => F }); Object.create(p)"],
["an object whose constructor's prototype is a getter",
"const p = Object.create(null); const F = { Object: () => {} }.Object;"
+ " Object.defineProperty(F, 'prototype', { get: () => p }); p.constructor = F; Object.create(p)"],
['an object on a Proxy prototype whose getPrototypeOf trap throws',
"Object.create(new Proxy({}, { getPrototypeOf() { throw new Error('trap'); } }))"],
['an object on a Proxy prototype whose getOwnPropertyDescriptor trap throws',
"Object.create(new Proxy(Object.create(null), { getOwnPropertyDescriptor() { throw new Error('trap'); } }))"],
['a plain object of a realm whose Object has a name getter',
"Object.defineProperty(Object, 'name', { get: () => 'Object' }); ({ a: 1 })"],
])('rejects %s from another realm', (_label, source) => {
expect(() => encodePageValue(runInContext(source, createContext())))
.toThrow(expect.objectContaining({ invalid: 'must be JSON-safe' }));
});

it("never runs a value getter the page put on its own Object.prototype", () => {
const page = createContext({ reads: 0 });
runInContext("Object.defineProperty(Object.prototype, 'value', { get() { reads++; } })", page);
const encodeInPage = runInContext(`(${pageValueEncoder.toString()})()`, page) as typeof encodePageValue;
const foreign = runInContext(
"const p = Object.create(null); Object.defineProperty(p, 'constructor', { get: () => Object }); Object.create(p)",
createContext(),
);
expect(() => encodeInPage(foreign)).toThrow(expect.objectContaining({ invalid: 'must be JSON-safe' }));
expect(page.reads).toBe(0);
});

it('encodes a null-prototype object', () => {
expect(encodePageValue(Object.assign(Object.create(null), { sku: 'a' }))).toBe('{"sku":"a"}');
});
Expand Down
Loading