diff --git a/packages/maple/docs/divergences.md b/packages/maple/docs/divergences.md index ef44d1b..87d667e 100644 --- a/packages/maple/docs/divergences.md +++ b/packages/maple/docs/divergences.md @@ -52,6 +52,9 @@ one that does; the linked section has the detail. - Set algebra refuses set-like objects other than Sets and Maps, and `Iterator.from` refuses an object with a script `next` ([Built-ins](builtins.md#map-and-set)). - A JSON reviver receives no third `context` argument ([JSON](builtins.md#json)). +- A JSON reviver and replacer read their holder's own data only, so a key a callback deletes + before it is visited reads as `undefined`, where native JavaScript would read the host prototype + ([Security](security.md#how-the-guarantees-hold)). - The legacy `RegExp.$1` statics, the String HTML methods and `Intl` are not available. ## Errors and limits diff --git a/packages/maple/src/builtins/json/json.spec.ts b/packages/maple/src/builtins/json/json.spec.ts index 28fafdd..45f7023 100644 --- a/packages/maple/src/builtins/json/json.spec.ts +++ b/packages/maple/src/builtins/json/json.spec.ts @@ -99,6 +99,40 @@ describe('JSON.parse', () => { ).toBe('LIMIT_EXCEEDED'); }); + it('reads reviver values as own data, never through the host prototype', () => { + const code = ` + const seen = []; + JSON.parse('{"a":0,"hasOwnProperty":0}', function (k, v) { + if (k === 'a') { delete this.hasOwnProperty; } + if (k === 'hasOwnProperty') { seen.push(typeof v); } + return v; + }); + return seen; + `; + + const seen = run(code); + + expect(seen).toEqual(['undefined']); + }); + + it('ignores a reviver write-back to a frozen holder, like the host', () => { + const array = run( + `return JSON.parse('[1,2]', function (k, v) { + if (k === '0') { Object.freeze(this); } + return typeof v === 'number' ? v + 100 : v; + });` + ); + const object = run( + `return JSON.parse('{"a":1}', function (k, v) { + if (k === 'a') { Object.freeze(this); } + return typeof v === 'number' ? v + 100 : v; + });` + ); + + expect(array).toEqual([1, 2]); + expect(object).toEqual({ a: 1 }); + }); + it('refuses to revive text nested deeper than 1000 levels with a catchable RangeError', () => { const deep = '['.repeat(20_000) + ']'.repeat(20_000); @@ -222,6 +256,49 @@ describe('JSON.stringify', () => { ).toBe('TypeError'); }); + it('reads replacer values as own data, never through the host prototype', () => { + const code = ` + const seen = []; + JSON.stringify({ a: 0, hasOwnProperty: 0 }, function (k, v) { + if (k === 'a') { delete this.hasOwnProperty; } + if (k === 'hasOwnProperty') { seen.push(typeof v); } + return v; + }); + return seen; + `; + + const seen = run(code); + + expect(seen).toEqual(['undefined']); + }); + + it('reads array elements as own data, never through the host prototype', () => { + const code = ` + const seen = []; + const text = JSON.stringify([0, 1], function (k, v) { + if (k === '0') { delete this[1]; } + if (k === '1') { seen.push(typeof v); } + return v; + }); + return [text, seen]; + `; + // oxlint-disable-next-line no-extend-native -- stands in for a host page that polluted the prototype + Object.defineProperty(Array.prototype, '1', { + value: 'host', + writable: true, + configurable: true + }); + + let result: unknown; + try { + result = run(code); + } finally { + Reflect.deleteProperty(Array.prototype, '1'); + } + + expect(result).toEqual(['[0,null]', ['undefined']]); + }); + it("writes an array replacer's keys in its order, own properties only", () => { expect(run('return JSON.stringify({ a: 1, b: 2 }, ["b", "a", "b"]);')).toBe('{"b":2,"a":1}'); expect(run('return JSON.stringify({ a: 1 }, ["a", "missing", "toString"]);')).toBe('{"a":1}'); diff --git a/packages/maple/src/builtins/json/statics/parse.ts b/packages/maple/src/builtins/json/statics/parse.ts index 503bad2..700f3da 100644 --- a/packages/maple/src/builtins/json/statics/parse.ts +++ b/packages/maple/src/builtins/json/statics/parse.ts @@ -1,6 +1,6 @@ import { isPlainObject } from '../../../support/is-plain-object.ts'; import { MAX_NESTING } from '../../../support/nesting-limit.ts'; -import { defineOwn } from '../../../support/own-property.ts'; +import { defineOwn, ownDataValue } from '../../../support/own-property.ts'; import { toString } from '../../../values/coercion.ts'; import { type CallContext, @@ -41,25 +41,40 @@ function revive( `A value nested deeper than ${MAX_NESTING} levels cannot be revived` ); } - const value: unknown = Reflect.get(holder, key); + // A reviver callback runs with the holder as `this` and can delete a key that the enclosing walk + // has already queued. Reading own data only keeps a now-missing key from resolving against the + // host prototype and handing the callback a live host reference. + const value: unknown = ownDataValue(holder, key); if (Array.isArray(value)) { for (let index = 0; index < value.length; index++) { - const revived = revive(value, String(index), reviver, context, depth + 1); - if (revived === undefined) { - Reflect.deleteProperty(value, String(index)); - } else { - value[index] = revived; - } + writeBack(value, String(index), revive(value, String(index), reviver, context, depth + 1)); } } else if (isPlainObject(value)) { for (const propertyKey of Object.keys(value)) { - const revived = revive(value, propertyKey, reviver, context, depth + 1); - if (revived === undefined) { - Reflect.deleteProperty(value, propertyKey); - } else { - defineOwn(value, propertyKey, revived); - } + writeBack(value, propertyKey, revive(value, propertyKey, reviver, context, depth + 1)); } } return context.call(holder, reviver, [key, value]); } + +/** + * Writes a revived value back as an own data property, or removes it when the reviver returned + * `undefined`. A callback can freeze its holder mid-walk; like the spec's CreateDataProperty, a + * write that a frozen holder refuses is left as it is rather than thrown to the host. + */ +function writeBack( + holder: Record | Array, + key: string, + revived: unknown +): void { + if (revived === undefined) { + Reflect.deleteProperty(holder, key); + return; + } + Reflect.defineProperty(holder, key, { + value: revived, + writable: true, + enumerable: true, + configurable: true + }); +} diff --git a/packages/maple/src/builtins/json/statics/stringify.ts b/packages/maple/src/builtins/json/statics/stringify.ts index 9f29c76..b616134 100644 --- a/packages/maple/src/builtins/json/statics/stringify.ts +++ b/packages/maple/src/builtins/json/statics/stringify.ts @@ -1,6 +1,6 @@ import { isPlainObject } from '../../../support/is-plain-object.ts'; import { MAX_NESTING } from '../../../support/nesting-limit.ts'; -import { defineOwn } from '../../../support/own-property.ts'; +import { defineOwn, ownDataValue } from '../../../support/own-property.ts'; import { getOwnPropertiesOf } from '../../../values/members.ts'; import { type CallContext, isCallable, NativeFunction } from '../../../values/native.ts'; import { SandboxObject } from '../../../values/sandbox-object.ts'; @@ -150,7 +150,9 @@ function serialize( const parts: Array = []; const length = current.length; for (let index = 0; index < length; index++) { - parts.push(serialize(current, String(index), current[index], inner, serialization) ?? 'null'); + // A replacer can delete an element the walk has not reached; own data only, as below + const element = ownDataValue(current, String(index)); + parts.push(serialize(current, String(index), element, inner, serialization) ?? 'null'); } result = wrap('[', ']', parts, gap, indent, inner); } else { @@ -160,7 +162,9 @@ function serialize( if (isPlainObject(current)) { properties = { has: (propertyKey: string): boolean => Object.hasOwn(current, propertyKey), - get: (propertyKey: string): unknown => current[propertyKey], + // A replacer runs with the holder as `this` between the key snapshot and this read; own + // data only keeps a deleted key from resolving against the host prototype. + get: (propertyKey: string): unknown => ownDataValue(current, propertyKey), keys: (): Array => Object.keys(current) }; } else { diff --git a/packages/maple/src/support/own-property.spec.ts b/packages/maple/src/support/own-property.spec.ts index 92530a5..998ed78 100644 --- a/packages/maple/src/support/own-property.spec.ts +++ b/packages/maple/src/support/own-property.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest'; -import { defineOwn } from './own-property.ts'; +import { defineOwn, ownDataValue } from './own-property.ts'; const DATA_PROPERTY = { enumerable: true, writable: true, configurable: true }; @@ -79,3 +79,65 @@ describe('defineOwn', () => { }); }); }); + +describe('ownDataValue', () => { + it('returns the value of an own data property, enumerable or not', () => { + const target = Object.defineProperty({ a: 1 }, 'hidden', { value: 2 }); + + const values = [ownDataValue(target, 'a'), ownDataValue(target, 'hidden')]; + + expect(values).toEqual([1, 2]); + }); + + it('returns undefined for a missing key and for one the prototype answers', () => { + const target = {}; + + const values = [ownDataValue(target, 'a'), ownDataValue(target, 'hasOwnProperty')]; + + expect(values).toEqual([undefined, undefined]); + }); + + it('returns undefined for an own accessor without calling it', () => { + const get = vi.fn<() => unknown>(() => 1); + const target = Object.defineProperty({}, 'probe', { get }); + + const value = ownDataValue(target, 'probe'); + + expect(value).toBeUndefined(); + expect(get).not.toHaveBeenCalled(); + }); + + it('returns undefined for an own accessor even when the host prototype carries a value', () => { + const get = vi.fn<() => unknown>(() => 'host'); + const target = Object.defineProperty({}, 'probe', { + get, + enumerable: true, + configurable: true + }); + // oxlint-disable-next-line no-extend-native -- stands in for a host page that polluted the prototype + Object.defineProperty(Object.prototype, 'value', { value: 'polluted', configurable: true }); + + let result: unknown; + try { + result = ownDataValue(target, 'probe'); + } finally { + Reflect.deleteProperty(Object.prototype, 'value'); + } + + expect(result).toBeUndefined(); + expect(get).not.toHaveBeenCalled(); + }); + + it('returns undefined for an array hole and for an index past the end', () => { + // oxlint-disable-next-line no-sparse-arrays -- the hole is what is being read + const target = [1, , 3]; + + const values = [ + ownDataValue(target, '0'), + ownDataValue(target, '1'), + ownDataValue(target, '5') + ]; + + expect(values).toEqual([1, undefined, undefined]); + }); +}); diff --git a/packages/maple/src/support/own-property.ts b/packages/maple/src/support/own-property.ts index 98a39cc..1aa099c 100644 --- a/packages/maple/src/support/own-property.ts +++ b/packages/maple/src/support/own-property.ts @@ -15,3 +15,19 @@ export function defineOwn(target: object, key: string, value: unknown): void { configurable: true }); } + +/** + * The target's own data value under `key`, or `undefined` when the key is missing, inherited or an + * accessor. Reading own data keeps a visit from falling through to the host prototype when a key + * is no longer own. + */ +export function ownDataValue(target: object, key: string): unknown { + const descriptor = Object.getOwnPropertyDescriptor(target, key); + // `Object.hasOwn`, not `'value' in descriptor`: the descriptor's own prototype is the host + // `Object.prototype`, so `in` would read a `value` the embedding page added there and misread an + // accessor as data. + if (descriptor === undefined || !Object.hasOwn(descriptor, 'value')) { + return undefined; + } + return descriptor.value; +}