Skip to content
Open
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
4 changes: 4 additions & 0 deletions build.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
44 changes: 44 additions & 0 deletions proxy.js
Original file line number Diff line number Diff line change
@@ -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;
};
}
89 changes: 89 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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"]);
});
});
41 changes: 41 additions & 0 deletions ubo.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down