|
| 1 | +import { createElement, render, Component, Fragment } from 'preact'; |
| 2 | +import { setupRerender } from 'preact/test-utils'; |
| 3 | +import { setupScratch, teardown } from '../_util/helpers'; |
| 4 | +import { expect } from 'vitest'; |
| 5 | + |
| 6 | +/** @jsx createElement */ |
| 7 | +/** @jsxFrag Fragment */ |
| 8 | + |
| 9 | +// Hardened JavaScript environments (SES `lockdown()`, `node |
| 10 | +// --frozen-intrinsics`, LavaMoat) freeze `Object.prototype`, which makes |
| 11 | +// `Object.prototype.constructor` non-writable. Copying a vnode — which carries |
| 12 | +// `constructor: undefined` as its JSON-injection guard — onto a bare `{}` then |
| 13 | +// hits the "override mistake" and throws. See #5109. |
| 14 | +// |
| 15 | +// Making `constructor` non-writable is the narrowest reproduction of that and, |
| 16 | +// unlike freezing, it is reversible so the rest of the suite is unaffected. |
| 17 | +describe('hardened JS (non-writable Object.prototype.constructor)', () => { |
| 18 | + let scratch, rerender, originalDescriptor; |
| 19 | + |
| 20 | + beforeEach(() => { |
| 21 | + scratch = setupScratch(); |
| 22 | + rerender = setupRerender(); |
| 23 | + |
| 24 | + originalDescriptor = Object.getOwnPropertyDescriptor( |
| 25 | + Object.prototype, |
| 26 | + 'constructor' |
| 27 | + ); |
| 28 | + Object.defineProperty(Object.prototype, 'constructor', { |
| 29 | + ...originalDescriptor, |
| 30 | + writable: false |
| 31 | + }); |
| 32 | + }); |
| 33 | + |
| 34 | + afterEach(() => { |
| 35 | + Object.defineProperty(Object.prototype, 'constructor', originalDescriptor); |
| 36 | + teardown(scratch); |
| 37 | + }); |
| 38 | + |
| 39 | + it('should re-render a component when Object.prototype is hardened', () => { |
| 40 | + class Counter extends Component { |
| 41 | + constructor(props) { |
| 42 | + super(props); |
| 43 | + this.state = { count: 0 }; |
| 44 | + } |
| 45 | + |
| 46 | + render() { |
| 47 | + return ( |
| 48 | + <button |
| 49 | + onClick={() => this.setState({ count: this.state.count + 1 })} |
| 50 | + > |
| 51 | + {this.state.count} |
| 52 | + </button> |
| 53 | + ); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + render(<Counter />, scratch); |
| 58 | + expect(scratch.innerHTML).to.equal('<button>0</button>'); |
| 59 | + |
| 60 | + scratch.firstChild.click(); |
| 61 | + rerender(); |
| 62 | + expect(scratch.innerHTML).to.equal('<button>1</button>'); |
| 63 | + }); |
| 64 | + |
| 65 | + it('should render a component returning a Fragment when Object.prototype is hardened', () => { |
| 66 | + // keyless Fragment results get cloned through `cloneNode` |
| 67 | + const App = () => ( |
| 68 | + <> |
| 69 | + <span>a</span> |
| 70 | + <span>b</span> |
| 71 | + </> |
| 72 | + ); |
| 73 | + |
| 74 | + render(<App />, scratch); |
| 75 | + expect(scratch.innerHTML).to.equal('<span>a</span><span>b</span>'); |
| 76 | + }); |
| 77 | +}); |
0 commit comments