Expose OpenScript and env to globalThis for reliable secret access

This commit is contained in:
2026-09-08 14:18:32 -07:00
parent b4fd285365
commit a74281c531
2 changed files with 16 additions and 9 deletions

View File

@@ -14,12 +14,19 @@ export const isUserScriptsAvailable = async () => {
export const wrapScriptCode = (code, secrets = {}) => {
const envInjection = `
// [OpenScript Injected Environment]
const OpenScript = Object.freeze({
(function() {
const secretsObj = Object.freeze(${JSON.stringify(secrets)});
const openScriptObj = Object.freeze({
version: "1.0.0",
env: Object.freeze(${JSON.stringify(secrets)})
});
const env = OpenScript.env;
const GM_getValue = (k, def) => (OpenScript.env[k] ?? def);
env: secretsObj
});
globalThis.OpenScript = openScriptObj;
globalThis.env = secretsObj;
globalThis.GM_getValue = (k, def) => (secretsObj[k] ?? def);
})();
var OpenScript = globalThis.OpenScript;
var env = globalThis.env;
var GM_getValue = globalThis.GM_getValue;
`;
return `${envInjection}\n${code}`;
};

View File

@@ -50,10 +50,10 @@ test('wrapScriptCode injects OpenScript.env and GM_getValue polyfill', () => {
const code = 'console.log(env.API_KEY, GM_getValue("API_KEY"));';
const wrapped = wrapScriptCode(code, { API_KEY: 'secret123' });
assert.ok(wrapped.includes('const OpenScript = Object.freeze('));
assert.ok(wrapped.includes('OpenScript'));
assert.ok(wrapped.includes('"API_KEY":"secret123"'));
assert.ok(wrapped.includes('const env = OpenScript.env;'));
assert.ok(wrapped.includes('const GM_getValue ='));
assert.ok(wrapped.includes('globalThis.OpenScript'));
assert.ok(wrapped.includes('GM_getValue'));
assert.ok(wrapped.includes(code));
});