diff --git a/build.ts b/build.ts index fbb87b7..faad594 100644 --- a/build.ts +++ b/build.ts @@ -1,3 +1,5 @@ +import { createProxy } from './proxy.js'; + const tagName = Deno.args.includes('--tagName') ? Deno.args[Deno.args.findIndex((o) => o === '--tagName') + 1] : false; @@ -52,7 +54,9 @@ fn: '${scriptlet.fn.name}', .join('\n')} // The calls come last, so the class dependencies, which are not hoisted, are declared by then. +// Proxy shadows the global for every scriptlet in run(), see proxy.js. export function run(scriptletGlobals, calls) { +const Proxy = (${createProxy})(globalThis.Proxy); ${[...functions.values()].join('\n')} const table = { ${entries.map((scriptlet) => scriptlet.fn.name).join(', ')} }; for (const [name, ...args] of calls) { diff --git a/proxy.js b/proxy.js new file mode 100644 index 0000000..adcf180 --- /dev/null +++ b/proxy.js @@ -0,0 +1,44 @@ +/** + * Returns a Proxy constructor wrapper that rejects prototype chains reaching + * the proxy or its target before changing the target's prototype. + */ +export function createProxy(NativeProxy) { + const { apply, getPrototypeOf, setPrototypeOf } = Reflect; + const objectCreate = Object.create; + const hasOwnProperty = Object.prototype.hasOwnProperty; + + // Proxies are walked like any other object, so a cycle spanning several scriptlet + // proxies is found. The tortoise ends walks over chains that are already cyclic. + const reaches = (proto, proxy, target) => { + let slow = proto; + let fast = proto; + for (let i = 1; fast !== null; i++) { + if (fast === proxy || fast === target) return true; + fast = getPrototypeOf(fast); + if (i % 2 === 0) { + slow = getPrototypeOf(slow); + if (slow === fast) return false; + } + } + return false; + }; + + return function Proxy(target, handler) { + // Compose with the handler's own setPrototypeOf trap, if any: read it once, as an own + // property only, so page code cannot inject one through Object.prototype. It runs after + // the cycle check below, so it only ever sees non-cyclic prototypes. + const trap = apply(hasOwnProperty, handler, ['setPrototypeOf']) ? handler.setPrototypeOf : undefined; + + // Inherit from the handler rather than copy it, so other traps added to it later still apply. + // A setPrototypeOf trap added to the handler after construction stays shadowed by the composed one. + const proxy = new NativeProxy(target, objectCreate(handler, { + setPrototypeOf: { value(target, proto) { + // Returning false makes Object.setPrototypeOf throw and Reflect.setPrototypeOf + // return false, as both do for a native function. + if (reaches(proto, proxy, target)) return false; + return trap === undefined ? setPrototypeOf(target, proto) : apply(trap, this, [target, proto]); + } }, + })); + return proxy; + }; +} diff --git a/test.js b/test.js index a0be436..52a1360 100644 --- a/test.js +++ b/test.js @@ -2,6 +2,7 @@ import { test, suite } from "node:test"; import assert from "node:assert"; import vm from "node:vm"; import scriptlets, { run } from "./index.js"; +import { createProxy } from "./proxy.js"; const runSource = run.toString(); @@ -84,3 +85,91 @@ suite("run()", () => { assert.strictEqual(keys.length, 0); }); }); + +suite("proxied functions", () => { + // A fresh realm is the page; returns it with the scriptlet applied + function createPage(name, ...args) { + const page = vm.createContext({ EventTarget: class {}, Request: class {} }); + vm.runInContext("self = globalThis; nativeSetTimeout = setTimeout = function setTimeout() {};", page); + vm.runInContext(`(${runSource})(...${JSON.stringify([{}, [[scriptlets[name].fn, ...args]]])});`, page); + return page; + } + + // Akamai Bot Manager's proxy probe + const probe = (fn) => ` + (() => { + const fn = ${fn}; + let error; + try { Object.setPrototypeOf(fn, Object.create(fn)); } catch (e) { error = e; } + return { error: error?.name, reflect: Reflect.setPrototypeOf(fn, Object.create(fn)), call: typeof fn.call }; + })() + `; + const native = vm.runInContext(probe("function native() {}"), vm.createContext({})); + + for (const [name, fn] of [ + ["prevent-setTimeout.js", "Function.prototype.toString"], // proxied by proxyApplyFn() + ["adjust-setTimeout.js", "setTimeout"], // proxied by the scriptlet itself + ]) { + test(`${name}: rejects a cyclic prototype on ${fn} like a native function`, () => { + const page = createPage(name, "x"); + assert(vm.runInContext("setTimeout !== nativeSetTimeout", page), `${name} did not run`); + assert.deepStrictEqual({ ...vm.runInContext(probe(fn), page) }, { ...native }); + }); + } + + test("rejects a cycle spanning two proxied functions like native functions", () => { + const probeBoth = (a, b) => ` + (() => { + const a = ${a}; + const b = ${b}; + Object.setPrototypeOf(a, Object.create(b)); + let error; + try { Object.setPrototypeOf(b, Object.create(a)); } catch (e) { error = e; } + return { error: error?.name, reflect: Reflect.setPrototypeOf(b, Object.create(a)), call: typeof b.call }; + })() + `; + const expected = vm.runInContext(probeBoth("function a() {}", "function b() {}"), vm.createContext({})); + const page = createPage("prevent-setTimeout.js", "x"); + assert.deepStrictEqual({ ...vm.runInContext(probeBoth("setTimeout", "Function.prototype.toString"), page) }, { ...expected }); + }); + + test("still sets a non-cyclic prototype", () => { + const page = createPage("prevent-setTimeout.js", "x"); + const set = "const proto = Object.create(Function.prototype); Object.setPrototypeOf(setTimeout, proto) === setTimeout && Object.getPrototypeOf(setTimeout) === proto"; + assert(vm.runInContext(set, page)); + }); +}); + +suite("createProxy", () => { + test("preserves a handler's own setPrototypeOf trap", () => { + const Proxy = createProxy(globalThis.Proxy); + const target = function fn() {}; + const calls = []; + const proxy = new Proxy(target, { + setPrototypeOf(t, proto) { + calls.push(proto); + return Reflect.setPrototypeOf(t, proto); + }, + }); + + // Non-cyclic: the handler's trap runs and its result is honored. + const proto = Object.create(Function.prototype); + assert.strictEqual(Reflect.setPrototypeOf(proxy, proto), true); + assert.deepStrictEqual(calls, [proto]); + assert.strictEqual(Object.getPrototypeOf(target), proto); + + // A falsish result from the handler's trap is honored, too. + const rejecting = new Proxy(target, { + setPrototypeOf() { + calls.push("reject"); + return false; + }, + }); + assert.strictEqual(Reflect.setPrototypeOf(rejecting, Object.create(Function.prototype)), false); + + // Cyclic: rejected before the handler's trap runs, like a native function. + assert.throws(() => Object.setPrototypeOf(proxy, Object.create(proxy)), TypeError); + assert.strictEqual(Reflect.setPrototypeOf(proxy, Object.create(proxy)), false); + assert.deepStrictEqual(calls, [proto, "reject"]); + }); +}); diff --git a/ubo.js b/ubo.js index fd9ad99..186705a 100644 --- a/ubo.js +++ b/ubo.js @@ -807,7 +807,48 @@ fn: 'trustedOverrideElementMethod', // The calls come last, so the class dependencies, which are not hoisted, are declared by then. +// Proxy shadows the global for every scriptlet in run(), see proxy.js. export function run(scriptletGlobals, calls) { +const Proxy = (function createProxy(NativeProxy) { + const { apply, getPrototypeOf, setPrototypeOf } = Reflect; + const objectCreate = Object.create; + const hasOwnProperty = Object.prototype.hasOwnProperty; + + // Proxies are walked like any other object, so a cycle spanning several scriptlet + // proxies is found. The tortoise ends walks over chains that are already cyclic. + const reaches = (proto, proxy, target) => { + let slow = proto; + let fast = proto; + for (let i = 1; fast !== null; i++) { + if (fast === proxy || fast === target) return true; + fast = getPrototypeOf(fast); + if (i % 2 === 0) { + slow = getPrototypeOf(slow); + if (slow === fast) return false; + } + } + return false; + }; + + return function Proxy(target, handler) { + // Compose with the handler's own setPrototypeOf trap, if any: read it once, as an own + // property only, so page code cannot inject one through Object.prototype. It runs after + // the cycle check below, so it only ever sees non-cyclic prototypes. + const trap = apply(hasOwnProperty, handler, ['setPrototypeOf']) ? handler.setPrototypeOf : undefined; + + // Inherit from the handler rather than copy it, so other traps added to it later still apply. + // A setPrototypeOf trap added to the handler after construction stays shadowed by the composed one. + const proxy = new NativeProxy(target, objectCreate(handler, { + setPrototypeOf: { value(target, proto) { + // Returning false makes Object.setPrototypeOf throw and Reflect.setPrototypeOf + // return false, as both do for a native function. + if (reaches(proto, proxy, target)) return false; + return trap === undefined ? setPrototypeOf(target, proto) : apply(trap, this, [target, proto]); + } }, + })); + return proxy; + }; +})(globalThis.Proxy); function safeSelf() { if ( safeSelf.safe ) { return safeSelf.safe;