Skip to content
Merged
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
15 changes: 14 additions & 1 deletion build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,19 @@ for (const scriptlet of scriptlets) {
}
}

// uBO runs all scriptlets of a page in one scope, so they share one safeSelf() cache. Our scriptlets are separate functions, so they share it on globalThis.
// Else each hook captures the earlier hooks as natives, and calls grow as 2^n. The uBO version is in the key, so other versions do not share it.
const safeSelf = index.get('safe-self.fn').fn;
const shareSafeSelf = `try {
const key = Symbol.for('safeSelf.${tagName}');
safeSelf.safe = globalThis[key];
if ( safeSelf.safe === undefined ) {
Object.defineProperty(globalThis, key, { value: safeSelf() });
}
} catch {
}
`;

console.log(`
/*******************************************************************************

Expand Down Expand Up @@ -67,7 +80,7 @@ requiresTrust: ${scriptlet.requiresTrust || false},
func: function (scriptletGlobals = {}, ...args) {
${deps.map((dep) => dep.toString()).join('\n')}
${scriptlet.fn.toString()};
${scriptlet.fn.name}(...args);
${deps.includes(safeSelf) ? shareSafeSelf : ''}${scriptlet.fn.name}(...args);
},
};
`;
Expand Down
53 changes: 53 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { test, suite } from "node:test";
import assert from "node:assert";
import vm from "node:vm";
import scriptlets from "./index.js";

test("default export is an object", () => {
Expand All @@ -26,3 +27,55 @@ suite("uBO", () => {
assert.strictEqual(scriptlets["set-constant.js"], scriptlets["set.js"]);
});
});

suite("safeSelf() cache", () => {
// Each hook clones the argument with safe.JSON_parse(safe.JSON_stringify(obj))
const func = scriptlets["trusted-edit-inbound-object.js"].func;
const HOOKS = 6;
// Same code as the extension makes for each scriptlet; the first argument is scriptletGlobals
const hooks = Array.from({ length: HOOKS }, (_, i) =>
`(${func})(...${JSON.stringify([{}, "JSON.stringify", "0", `[?.hook${i}]+={"edited${i}":true}`])});`
);

// A fresh realm is the page; counters wrap the native JSON methods before the scriptlets run
function createPage() {
const page = vm.createContext({ EventTarget: class {}, Request: class {} });
vm.runInContext(
`
const { parse, stringify } = JSON;
globalThis.calls = { parse: 0, stringify: 0 };
JSON.parse = function (...args) { calls.parse += 1; return parse.apply(JSON, args); };
JSON.stringify = function (...args) { calls.stringify += 1; return stringify.apply(JSON, args); };
`,
page
);
return page;
}

test("is shared in a realm, so stacked hooks stay linear", () => {
const page = createPage();
for (const hook of hooks) {
vm.runInContext(hook, page);
}

const result = vm.runInContext(
"calls.parse = 0; calls.stringify = 0; JSON.stringify({ hook0: true, hook5: true });",
page
);
assert.deepStrictEqual(JSON.parse(result), { hook0: true, hook5: true, edited0: true, edited5: true });
// One call from the page plus one clone per hook, not 2^n
assert.deepStrictEqual({ ...page.calls }, { parse: HOOKS, stringify: HOOKS + 1 });
});

test("is read-only and not enumerable", () => {
const page = createPage();
vm.runInContext(hooks.join("\n"), page);

const keys = vm
.runInContext("Object.getOwnPropertySymbols(globalThis)", page)
.filter((key) => key.description.startsWith("safeSelf."));
assert.strictEqual(keys.length, 1);
const { value, ...flags } = Object.getOwnPropertyDescriptor(page, keys[0]);
assert.deepStrictEqual(flags, { writable: false, enumerable: false, configurable: false });
});
});
Loading
Loading