Simulate configured and standard tool locations through the bridge filesystem mock. Verify directory precedence and PATH fallback without relying on /usr/local/bin/musrfit, which caused the first PSI runner validation to fail.
831 lines
36 KiB
JavaScript
831 lines
36 KiB
JavaScript
// Copyright (C) 2026 Zaher Salman
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// Electron preload bridge: muSRFitelec.js must run with nodeIntegration:false
|
|
// and contextIsolation:true, consuming only the curated window.electronAPI
|
|
// surface exposed by preload.js. These tests drive the renderer shim against a
|
|
// bridge mock with the same normalized shape, confirming fs/path/child-process
|
|
// and runLocalProcess behave correctly through the hardened path, and that
|
|
// index.html gates electron scripts on window.electronAPI.
|
|
|
|
const assert = require("assert");
|
|
const fs = require("fs");
|
|
const os = require("os");
|
|
const path = require("path");
|
|
const vm = require("vm");
|
|
const childProcess = require("child_process");
|
|
|
|
const repoRoot = path.resolve(__dirname, "..");
|
|
const testRoot = fs.mkdtempSync(path.join(os.tmpdir(), "musrflow-bridge-"));
|
|
const workDir = path.join(testRoot, "work");
|
|
fs.mkdirSync(workDir, { recursive: true });
|
|
|
|
// A bridge mock that mirrors the normalized electronAPI shape produced by
|
|
// preload.js (plain serializable results; buffered spawnCapture).
|
|
function toText(value) {
|
|
return Buffer.isBuffer(value) ? value.toString() : (value == null ? "" : String(value));
|
|
}
|
|
|
|
function makeBridge() {
|
|
const spawnJobs = {};
|
|
const bridge = {
|
|
ipc: {
|
|
on: function (channel, listener) {
|
|
if (!bridge.ipc.listeners) bridge.ipc.listeners = {};
|
|
(bridge.ipc.listeners[channel] = bridge.ipc.listeners[channel] || []).push(listener);
|
|
return function () {};
|
|
},
|
|
send: function (channel) {},
|
|
invoke: function () { return Promise.resolve(""); }
|
|
},
|
|
path: {
|
|
join: function (...p) { return path.join(...p); },
|
|
resolve: function (...p) { return path.resolve(...p); },
|
|
basename: function (p, e) { return path.basename(p, e); },
|
|
dirname: function (p) { return path.dirname(p); }
|
|
},
|
|
process: {
|
|
cwd: function () { return workDir; },
|
|
resourcesPath: "",
|
|
plotlyURL: "file:///bundled/plotly.js",
|
|
env: { HOME: os.homedir(), PATH: process.env.PATH || "" }
|
|
},
|
|
childProcess: {
|
|
execSync: function (command, options) {
|
|
try {
|
|
return { ok: true, stdout: toText(childProcess.execSync(command, options || {})), error: null };
|
|
} catch (err) {
|
|
return { ok: false, stdout: toText(err.stdout), stderr: toText(err.stderr),
|
|
status: typeof err.status === "number" ? err.status : 1, error: err.message };
|
|
}
|
|
},
|
|
spawnSync: function (command, args, options) {
|
|
let result;
|
|
try { result = childProcess.spawnSync(command, args || [], options || {}); }
|
|
catch (err) { return { pid: null, status: null, signal: null, stdout: "", stderr: "", error: err.message }; }
|
|
return { pid: result.pid, status: result.status, signal: result.signal,
|
|
stdout: toText(result.stdout), stderr: toText(result.stderr),
|
|
error: result.error ? result.error.message : null };
|
|
},
|
|
spawnCapture: function (command, args, options, onChunk) {
|
|
return new Promise(function (resolve) {
|
|
const child = childProcess.spawn(command, args || [], Object.assign({}, options, {
|
|
shell: false, stdio: ["ignore", "pipe", "pipe"]
|
|
}));
|
|
const jobKey = options && options.jobToken ? String(options.jobToken) : "";
|
|
const unregister = function () {
|
|
if (!jobKey) return;
|
|
const entry = spawnJobs[jobKey];
|
|
if (entry) {
|
|
if (entry.timer) clearTimeout(entry.timer);
|
|
delete spawnJobs[jobKey];
|
|
}
|
|
};
|
|
if (jobKey) {
|
|
spawnJobs[jobKey] = { child: child, done: false, timer: null, escalated: false };
|
|
}
|
|
let stdoutText = "";
|
|
let stderrText = "";
|
|
child.stdout.on("data", function (chunk) {
|
|
const text = chunk.toString();
|
|
stdoutText += text;
|
|
if (typeof onChunk === "function") onChunk("stdout", text);
|
|
});
|
|
child.stderr.on("data", function (chunk) {
|
|
const text = chunk.toString();
|
|
stderrText += text;
|
|
if (typeof onChunk === "function") onChunk("stderr", text);
|
|
});
|
|
child.on("error", function (err) {
|
|
unregister();
|
|
resolve({ ok: 0, code: 1, signal: null, stdout: stdoutText, stderr: stderrText,
|
|
error: err.message });
|
|
});
|
|
child.on("close", function (code, signal) {
|
|
unregister();
|
|
resolve({ ok: code === 0 ? 1 : 0, code: code, signal: signal,
|
|
stdout: stdoutText, stderr: stderrText, error: null });
|
|
});
|
|
});
|
|
},
|
|
// Mirrors the preload bridge: kill the child identified by the job
|
|
// token (SIGTERM, then SIGKILL after a grace period).
|
|
abortJob: function (token, signal) {
|
|
const key = String(token == null ? "" : token);
|
|
const entry = spawnJobs[key];
|
|
if (!entry || entry.done) return { ok: false, code: "no-such-job" };
|
|
const sig = signal || "SIGTERM";
|
|
try {
|
|
if (!entry.escalated) {
|
|
entry.escalated = true;
|
|
entry.child.kill(sig);
|
|
entry.timer = setTimeout(function () {
|
|
const live = spawnJobs[key];
|
|
if (live && !live.done) {
|
|
try { live.child.kill("SIGKILL"); } catch (ignore) {}
|
|
}
|
|
}, 3000);
|
|
}
|
|
} catch (err) {
|
|
return { ok: false, code: err.message };
|
|
}
|
|
return { ok: true, code: sig };
|
|
}
|
|
}
|
|
};
|
|
|
|
// Sync fs wrappers matching preload.js.
|
|
const fsWrappers = [
|
|
"existsSync", "lstatSync", "statSync", "readdirSync", "readFileSync", "writeFileSync",
|
|
"appendFileSync", "copyFileSync", "linkSync", "renameSync", "unlinkSync",
|
|
"rmSync", "mkdirSync", "accessSync"
|
|
];
|
|
bridge.fs = {};
|
|
fsWrappers.forEach(function (name) {
|
|
bridge.fs[name] = function (...args) { return fs[name](...args); };
|
|
});
|
|
bridge.fs.mkdir = function (p, options, callback) {
|
|
fs.mkdir(p, options, function (err) {
|
|
if (typeof callback === "function") callback(err ? { message: err.message } : null);
|
|
});
|
|
};
|
|
bridge.fs.readFile = function (p, encoding, callback) {
|
|
fs.readFile(p, encoding, function (err, data) { if (typeof callback === "function") callback(err, data); });
|
|
};
|
|
bridge.fs.constants = {
|
|
O_WRONLY: fs.constants.O_WRONLY,
|
|
COPYFILE_EXCL: fs.constants.COPYFILE_EXCL,
|
|
W_OK: fs.constants.W_OK,
|
|
X_OK: fs.constants.X_OK
|
|
};
|
|
|
|
bridge.clipboard = {
|
|
writeText: function (text) { bridge.__clipboardText = String(text); return true; },
|
|
readText: function () { return bridge.__clipboardText || ""; }
|
|
};
|
|
|
|
return bridge;
|
|
}
|
|
|
|
function localStoreFactory() {
|
|
const store = {};
|
|
return {
|
|
getItem: function (key) { return Object.prototype.hasOwnProperty.call(store, key) ? store[key] : null; },
|
|
setItem: function (key, value) { store[key] = String(value); },
|
|
removeItem: function (key) { delete store[key]; }
|
|
};
|
|
}
|
|
|
|
// Load the shared lib + electron shim with ONLY the bridge exposed (no
|
|
// nodeIntegration fallbacks), as in the hardened BrowserWindow.
|
|
function load(bridge, documentElements = {}) {
|
|
const localStorage = localStoreFactory();
|
|
const sandbox = {
|
|
console: { log: function () {}, error: console.error, warn: console.warn },
|
|
process: { env: {}, cwd: function () { return workDir; } },
|
|
require: require,
|
|
window: { MSREditor: {}, localStorage: localStorage, electronAPI: bridge || makeBridge() },
|
|
document: {
|
|
getElementById: function (id) {
|
|
return Object.prototype.hasOwnProperty.call(documentElements, id)
|
|
? documentElements[id] : null;
|
|
}
|
|
}
|
|
};
|
|
sandbox.global = sandbox;
|
|
vm.runInNewContext(
|
|
fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"),
|
|
sandbox, { filename: "muSRFitlib.js" });
|
|
vm.runInNewContext(
|
|
fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8"),
|
|
sandbox, { filename: "muSRFitelec.js" });
|
|
return { lib: sandbox, localStorage: localStorage };
|
|
}
|
|
|
|
// The shim must pick up fs/path/child-process from the bridge and keep the
|
|
// portable-naming pipeline working (nodePath.join, nodeFs.existsSync).
|
|
function testBridgeDrivesPortableNaming() {
|
|
const bridge = makeBridge();
|
|
const { lib, localStorage } = load(bridge);
|
|
const portableFile = path.join(workDir, "d2026", "tdc", "lem26_his_0007.root");
|
|
fs.mkdirSync(path.dirname(portableFile), { recursive: true });
|
|
fs.writeFileSync(portableFile, "x\n");
|
|
const startupXmlPath = path.join(workDir, "musrfit_startup.xml");
|
|
fs.writeFileSync(startupXmlPath,
|
|
`<musrfit><data_path>${workDir}</data_path>` +
|
|
`<run_name_template inst="lem">d%yyyy%/tdc/lem%yy%_his_%rrrr%.root</run_name_template></musrfit>`);
|
|
localStorage.setItem("musrflow.startupXml", startupXmlPath);
|
|
assert.strictEqual(lib.loadLocalPortableRunNaming(), startupXmlPath);
|
|
assert.strictEqual(
|
|
lib.runFileNameAuto(7, "2026", "LEM", "/psi.ch/data/"),
|
|
"RUN d2026/tdc/lem26_his_0007 MUE4 PSI MUSR-ROOT"
|
|
);
|
|
}
|
|
|
|
// execSync/spawnSync surface through the bridge behaves like the Node API.
|
|
function testBridgeChildProcessSurface() {
|
|
const { lib } = load(makeBridge());
|
|
const cp = lib.nodeChildProcess;
|
|
assert.strictEqual(cp.execSync("printf 'hello'"), "hello");
|
|
|
|
const syncRes = cp.spawnSync("printf", ["world"], { encoding: "utf8" });
|
|
assert.strictEqual(syncRes.stdout, "world");
|
|
assert.strictEqual(syncRes.status, 0);
|
|
}
|
|
|
|
// The preload readFile wrapper must forward the content and not just the error.
|
|
// The renderer's Open MSR handler consumes (err, data); dropping data made the
|
|
// File > Open MSR menu appear to do nothing while an uncaught data.toString()
|
|
// TypeError fired on the renderer side.
|
|
function testPreloadReadFileForwardsData() {
|
|
const preloadContents = fs.readFileSync(path.join(repoRoot, "preload.js"), "utf8");
|
|
assert.match(preloadContents, /callback\(err \? \{ message: err\.message \} : null, data\)/);
|
|
const renderer = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8");
|
|
assert.match(renderer, /readFile\(filePath, "utf8", function read\(err, data\)/);
|
|
assert.match(renderer, /loadMSRIntoEditor\(data\.toString\(\), filePath/);
|
|
}
|
|
|
|
// Run file-menu payloads crossing the bridge contract with the real preload
|
|
// readFile semantics: success forwards content to the renderer callback. The
|
|
// read is asynchronous, so this test settles on the renderer's load callback.
|
|
function testFileMenuOpenForwardsContentThroughBridge() {
|
|
return new Promise(function(resolve, reject) {
|
|
const bridge = makeBridge();
|
|
bridge.fs.readFile = function (p, encoding, callback) {
|
|
fs.readFile(p, encoding, function (err, data) {
|
|
if (typeof callback === "function") callback(err ? { message: err.message } : null, data);
|
|
});
|
|
};
|
|
const { lib } = load(bridge);
|
|
let loaded = false;
|
|
lib.loadMSRIntoEditor = function (contents, filePath) {
|
|
try {
|
|
assert.strictEqual(contents, "TITLE Content forwarded\n");
|
|
loaded = true;
|
|
resolve();
|
|
} catch (error) {
|
|
reject(error);
|
|
}
|
|
};
|
|
lib.openTab = function () {
|
|
};
|
|
lib.firstLoad();
|
|
|
|
const sourcePath = path.join(testRoot, "bridge-open-content.msr");
|
|
fs.writeFileSync(sourcePath, "TITLE Content forwarded\n", "utf8");
|
|
bridge.ipc.listeners.openFile[0]([sourcePath]);
|
|
setTimeout(function() {
|
|
if (!loaded) {
|
|
reject(new Error("MSR open did not reach loadMSRIntoEditor"));
|
|
}
|
|
}, 200);
|
|
});
|
|
}
|
|
|
|
// A new working directory must exist before checkDir returns. Existing files
|
|
// must be rejected immediately rather than failing later during MSR generation.
|
|
function testSynchronousWorkDirectoryPreparation() {
|
|
const bridge = makeBridge();
|
|
bridge.fs.mkdir = function() {
|
|
throw new Error("asynchronous mkdir must not be used");
|
|
};
|
|
const { lib } = load(bridge);
|
|
const newDirectory = path.join(testRoot, "new-work", "nested");
|
|
const created = lib.checkDir(newDirectory);
|
|
assert.strictEqual(created.ok, 1);
|
|
assert.strictEqual(fs.statSync(newDirectory).isDirectory(), true);
|
|
|
|
const filePath = path.join(testRoot, "not-a-directory");
|
|
fs.writeFileSync(filePath, "file\n", "utf8");
|
|
const rejected = lib.checkDir(filePath);
|
|
assert.strictEqual(rejected.ok, 0);
|
|
assert.match(rejected.message, /not a directory/);
|
|
}
|
|
|
|
// The preload wrapper deliberately strips the Electron event object. Renderer
|
|
// listeners must therefore consume the selected path as their first argument.
|
|
function testPreferenceBrowsePayloadsUseBridgeContract() {
|
|
const bridge = makeBridge();
|
|
const fields = {
|
|
workPath: { value: "." },
|
|
dataRoot: { value: "/old/data" },
|
|
startupXml: { value: "" },
|
|
binDir: { value: "" }
|
|
};
|
|
const { lib } = load(bridge, fields);
|
|
lib.firstLoad();
|
|
|
|
bridge.ipc.listeners.workFolderSelected[0](["/selected/work"]);
|
|
bridge.ipc.listeners.dataRootSelected[0](["/selected/data"]);
|
|
bridge.ipc.listeners.startupXmlSelected[0]("/selected/musrfit_startup.xml");
|
|
bridge.ipc.listeners.binFolderSelected[0](["/opt/musrfit-tools/bin"]);
|
|
|
|
assert.strictEqual(fields.workPath.value, "/selected/work");
|
|
assert.strictEqual(fields.dataRoot.value, "/selected/data");
|
|
assert.strictEqual(fields.startupXml.value, "/selected/musrfit_startup.xml");
|
|
assert.strictEqual(fields.binDir.value, "/opt/musrfit-tools/bin");
|
|
}
|
|
|
|
// The musrfit binaries preference is null-tolerant exactly like the data-root
|
|
// browse reply: a string and an empty result both leave the field unchanged.
|
|
function testBinFolderBrowsePayloadTolerance() {
|
|
const bridge = makeBridge();
|
|
const fields = { binDir: { value: "" } };
|
|
const { lib } = load(bridge, fields);
|
|
lib.firstLoad();
|
|
|
|
bridge.ipc.listeners.binFolderSelected[0]("");
|
|
assert.strictEqual(fields.binDir.value, "");
|
|
bridge.ipc.listeners.binFolderSelected[0]([]);
|
|
assert.strictEqual(fields.binDir.value, "");
|
|
bridge.ipc.listeners.binFolderSelected[0]("/only/bin");
|
|
assert.strictEqual(fields.binDir.value, "/only/bin");
|
|
}
|
|
|
|
// resolveLocalCommand must prefer the configured musrfit-tools directory over
|
|
// every built-in location, and localCommandPathBias must place it ahead of the
|
|
// PSI/local dirs so tools musrfit launches itself also follow the preference.
|
|
function testConfiguredBinDirDrivesCommandResolution() {
|
|
const bridge = makeBridge();
|
|
const tools = path.join(workDir, "musrfit-tools");
|
|
// Define every visible tool explicitly. Auto-detection must not depend on
|
|
// musrfit or a separate runtime being installed on the developer/CI host.
|
|
const availableFiles = new Set([
|
|
path.join(tools, "musrfit"),
|
|
path.join(tools, "msr2data"),
|
|
path.join(tools, "dump_header"),
|
|
"/usr/local/bin/musrfit",
|
|
"/usr/bin/musrfit",
|
|
"/usr/bin/musrview"
|
|
]);
|
|
bridge.fs.existsSync = function(filename) {
|
|
return availableFiles.has(filename);
|
|
};
|
|
const { lib, localStorage } = load(bridge);
|
|
localStorage.setItem("musrflow.binDir", tools);
|
|
|
|
assert.strictEqual(
|
|
lib.resolveLocalCommand("musrfit"),
|
|
path.join(tools, "musrfit"));
|
|
assert.strictEqual(
|
|
lib.resolveLocalCommand("msr2data"),
|
|
path.join(tools, "msr2data"));
|
|
assert.strictEqual(
|
|
lib.resolveLocalCommand("dump_header"),
|
|
path.join(tools, "dump_header"));
|
|
// A tool absent from the configured folder still uses host auto-detection.
|
|
assert.strictEqual(lib.resolveLocalCommand("musrview"), "/usr/bin/musrview");
|
|
assert.strictEqual(
|
|
lib.localCommandPathBias().indexOf(tools + ":/usr/local/bin") === 0, true);
|
|
|
|
// Clearing the preference restores the ordered host search, followed by
|
|
// a bare command for PATH lookup when no candidate file is found.
|
|
localStorage.removeItem("musrflow.binDir");
|
|
assert.strictEqual(lib.resolveLocalCommand("musrfit"), "/usr/local/bin/musrfit");
|
|
availableFiles.delete("/usr/local/bin/musrfit");
|
|
assert.strictEqual(lib.resolveLocalCommand("musrfit"), "/usr/bin/musrfit");
|
|
availableFiles.delete("/usr/bin/musrfit");
|
|
assert.strictEqual(lib.resolveLocalCommand("musrfit"), "musrfit");
|
|
|
|
localStorage.setItem("musrflow.binDir", tools);
|
|
assert.strictEqual(lib.resolveLocalCommand("musrfit"), path.join(tools, "musrfit"));
|
|
}
|
|
|
|
// The binDir preference round-trips through set/get/initialize and the
|
|
// preferences save path, mirroring how workPath and startupXml behave.
|
|
function testBinDirPreferencePersistence() {
|
|
const bridge = makeBridge();
|
|
const fields = {
|
|
binDir: { value: "" },
|
|
workPath: { value: "." },
|
|
dataRoot: { value: "/old/data" },
|
|
startupXml: { value: "" },
|
|
asymmetrySuffix: { value: "_asy" },
|
|
singleHistSuffix: { value: "_singleHist" },
|
|
guessInitialParameters: { checked: true }
|
|
};
|
|
const { lib, localStorage } = load(bridge, fields);
|
|
lib.updateStartupNamingSourceIndicator = function() {};
|
|
lib.reloadLocalPortableRunNaming = function() {};
|
|
lib.setConfiguredInitialParameterGuess = function() {};
|
|
lib.closeElectronPreferences = function() {};
|
|
|
|
// Simulate the user entering a tools directory and saving.
|
|
fields.binDir.value = "/custom/tools";
|
|
lib.saveElectronPreferences();
|
|
assert.strictEqual(localStorage.getItem("musrflow.binDir"), "/custom/tools");
|
|
assert.strictEqual(lib.getConfiguredBinDir(), "/custom/tools");
|
|
|
|
// A cleared field removes the stored preference.
|
|
fields.binDir.value = "";
|
|
lib.saveElectronPreferences();
|
|
assert.strictEqual(localStorage.getItem("musrflow.binDir"), null);
|
|
assert.strictEqual(lib.getConfiguredBinDir(), "");
|
|
|
|
// initializeBinDir restores the saved value into the field.
|
|
localStorage.setItem("musrflow.binDir", "/restored/tools");
|
|
lib.initializeBinDir();
|
|
assert.strictEqual(fields.binDir.value, "/restored/tools");
|
|
}
|
|
|
|
function testBinDirPreferenceCancelRestoresOriginal() {
|
|
const bridge = makeBridge();
|
|
const dialog = {
|
|
dataset: {},
|
|
addEventListener: function() {},
|
|
showModal: function() {},
|
|
close: function() {}
|
|
};
|
|
const fields = {
|
|
preferencesDialog: dialog,
|
|
binDir: { value: "/stored/tools" },
|
|
workPath: { value: "." },
|
|
dataRoot: { value: "/old/data" },
|
|
startupXml: { value: "" },
|
|
asymmetrySuffix: { value: "_asy" },
|
|
singleHistSuffix: { value: "_singleHist" },
|
|
guessInitialParameters: { checked: true }
|
|
};
|
|
const { lib } = load(bridge, fields);
|
|
lib.openElectronPreferences();
|
|
fields.binDir.value = "/edited/elsewhere";
|
|
lib.cancelElectronPreferences();
|
|
assert.strictEqual(fields.binDir.value, "/stored/tools");
|
|
}
|
|
|
|
// File-menu payloads cross the same event-stripping bridge as Preferences.
|
|
// Exercise both directions so Open and Save cannot silently regress to the old
|
|
// ipcRenderer callback signature.
|
|
function testFileMenuPayloadsUseBridgeContract() {
|
|
const bridge = makeBridge();
|
|
bridge.fs.readFile = function (filePath, encoding, callback) {
|
|
callback(null, fs.readFileSync(filePath, encoding));
|
|
};
|
|
const { lib } = load(bridge);
|
|
let openedPath = "";
|
|
lib.loadMSRIntoEditor = function (contents, filePath) {
|
|
assert.match(contents, /TITLE Bridge open/);
|
|
openedPath = filePath;
|
|
};
|
|
lib.openTab = function () {
|
|
};
|
|
lib.getCurrentEditorText = function () {
|
|
return "TITLE Bridge save\n";
|
|
};
|
|
lib.firstLoad();
|
|
|
|
const sourcePath = path.join(testRoot, "bridge-open.msr");
|
|
const targetPath = path.join(testRoot, "bridge-save.msr");
|
|
fs.writeFileSync(sourcePath, "TITLE Bridge open\n", "utf8");
|
|
bridge.ipc.listeners.openFile[0]([sourcePath]);
|
|
bridge.ipc.listeners.saveFile[0](targetPath);
|
|
|
|
assert.strictEqual(openedPath, sourcePath);
|
|
assert.strictEqual(fs.readFileSync(targetPath, "utf8"), "TITLE Bridge save\n");
|
|
}
|
|
|
|
// runLocalProcess drives a real external command through spawnCapture and
|
|
// resolves the same result shape callers expect.
|
|
async function testRunLocalProcessOverBridge() {
|
|
const { lib } = load(makeBridge());
|
|
const logFile = path.join(workDir, "run.out");
|
|
const result = await lib.runLocalProcess(
|
|
"echo test", "printf", ["from-bridge\n"], workDir, logFile, { reportStatus: false });
|
|
assert.strictEqual(result.ok, 1);
|
|
assert.strictEqual(result.code, 0);
|
|
assert.strictEqual(result.stdout, "from-bridge\n");
|
|
assert.match(fs.readFileSync(logFile, "utf8"), /from-bridge\n/);
|
|
}
|
|
|
|
// The hardened build must not fall back to require() when the bridge present,
|
|
// and index.html must gate the electron script load on window.electronAPI.
|
|
function testHardeningContract() {
|
|
const elec = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8");
|
|
assert.match(elec, /window\.electronAPI/);
|
|
const index = fs.readFileSync(path.join(repoRoot, "index.html"), "utf8");
|
|
const main = fs.readFileSync(path.join(repoRoot, "main.js"), "utf8");
|
|
assert.match(index, /window\.electronAPI/);
|
|
assert.doesNotMatch(index, /typeof module !== "undefined" && module\.exports/);
|
|
assert.match(main, /forwardedX11[\s\S]*delete childEnvironment\.DBUS_SESSION_BUS_ADDRESS/);
|
|
assert.match(main, /MUSRFLOW_FORWARDED_X11/);
|
|
}
|
|
|
|
// preload.js must expose exactly the bridge object the shim consumes.
|
|
function testPreloadExposesBridgeObject() {
|
|
const preload = fs.readFileSync(path.join(repoRoot, "preload.js"), "utf8");
|
|
assert.match(preload, /exposeInMainWorld\("electronAPI"/);
|
|
assert.match(preload, /contextBridge\.exposeInMainWorld/);
|
|
assert.match(preload, /clipboard:\s*\{\s*writeText/);
|
|
assert.match(preload, /ipcRenderer\.invoke\("write-clipboard"/);
|
|
}
|
|
|
|
// The share button must copy through window.electronAPI.clipboard.writeText (the
|
|
// bridge), not require('electron').clipboard which does not exist in the
|
|
// hardened renderer.
|
|
function testElectronShareCopyUsesBridgeClipboard() {
|
|
const bridge = makeBridge();
|
|
const { lib } = load(bridge);
|
|
lib.prepCFG = function() {};
|
|
lib.getFitComponentValues = function() { return ["Exponential"]; };
|
|
lib.showTransientWarning = function() {};
|
|
lib.setFitStatus = function() {};
|
|
const elements = {
|
|
Runs: { querySelectorAll: function() { return []; } },
|
|
Params: { querySelectorAll: function() { return []; } }
|
|
};
|
|
lib.document.getElementById = function(id) { return elements[id] || null; };
|
|
|
|
return lib.copyWebConfigurationLink().then(function(copied) {
|
|
assert.strictEqual(copied, true);
|
|
assert.match(bridge.clipboard.readText(), /^http:\/\/musruser\.psi\.ch\/muSRFlow\/#c=/);
|
|
});
|
|
}
|
|
|
|
// Abort must kill a running child process (SIGTERM), and the bridge entry must
|
|
// be gone afterwards so a second abort reports no such job.
|
|
function testPreloadAbortJobKillsProcess() {
|
|
return new Promise(function(resolve, reject) {
|
|
const bridge = makeBridge();
|
|
const started = Date.now();
|
|
const run = bridge.childProcess.spawnCapture("sleep", ["60"], { jobToken: "aborttest" }, function() {});
|
|
let settled = false;
|
|
function settle(fn) {
|
|
if (settled) return;
|
|
settled = true;
|
|
fn();
|
|
}
|
|
setTimeout(function() {
|
|
settle(function() {
|
|
try {
|
|
const first = bridge.childProcess.abortJob("aborttest", "SIGTERM");
|
|
assert.strictEqual(first.ok, true);
|
|
assert.strictEqual(first.code, "SIGTERM");
|
|
} catch (err) {
|
|
reject(err);
|
|
}
|
|
});
|
|
}, 150);
|
|
run.then(function(result) {
|
|
settle(function() {
|
|
try {
|
|
assert.strictEqual(result.signal, "SIGTERM");
|
|
assert.ok(Date.now() - started < 5000, "aborted child should exit before sleep 60 ends");
|
|
const late = bridge.childProcess.abortJob("aborttest", "SIGTERM");
|
|
assert.strictEqual(late.ok, false);
|
|
assert.strictEqual(late.code, "no-such-job");
|
|
} catch (err) {
|
|
return reject(err);
|
|
}
|
|
resolve();
|
|
});
|
|
}).catch(reject);
|
|
});
|
|
}
|
|
|
|
// The renderer-level Abort path: window.triggerMusrfitAbort() ends the last
|
|
// launched runLocalProcess job through the bridge and reports an "aborted"
|
|
// outcome instead of a failed fit.
|
|
function testElectronAbortEndsRunningJob() {
|
|
return new Promise(function(resolve, reject) {
|
|
const bridge = makeBridge();
|
|
const { lib } = load(bridge);
|
|
lib.updateJobStatus = function() {};
|
|
lib.appendJobLog = function() {};
|
|
const logFile = path.join(testRoot, "abort-run.out");
|
|
fs.writeFileSync(logFile, "");
|
|
let captured = null;
|
|
lib.finishJobStatus = function(ok, code, message, outcome) {
|
|
captured = { ok: ok, code: code, message: message, outcome: outcome };
|
|
};
|
|
|
|
assert.strictEqual(lib.window.MusrfitAction.abortSupported, true);
|
|
assert.strictEqual(typeof lib.window.triggerMusrfitAbort, "function");
|
|
|
|
const run = lib.runLocalProcess("sleep probe", "sleep", ["60"], testRoot, logFile);
|
|
let settled = false;
|
|
function settle(fn) {
|
|
if (settled) return;
|
|
settled = true;
|
|
fn();
|
|
}
|
|
setTimeout(function() {
|
|
settle(function() {
|
|
try {
|
|
assert.strictEqual(lib.window.triggerMusrfitAbort("fit"), true);
|
|
} catch (err) {
|
|
reject(err);
|
|
}
|
|
});
|
|
}, 150);
|
|
run.then(function(result) {
|
|
settle(function() {
|
|
try {
|
|
assert.strictEqual(result.outcome, "aborted");
|
|
assert.strictEqual(result.signal, "SIGTERM");
|
|
assert.strictEqual(captured.outcome, "aborted");
|
|
assert.match(String(captured.message), /aborted/);
|
|
} catch (err) {
|
|
return reject(err);
|
|
}
|
|
resolve();
|
|
});
|
|
}).catch(reject);
|
|
});
|
|
}
|
|
|
|
// The main process must start the MSR dialogs in the last used folder and
|
|
// persist that folder after a successful open or save.
|
|
function testMainRemembersMSRDialogDirectory() {
|
|
const main = fs.readFileSync(path.join(repoRoot, "main.js"), "utf8");
|
|
assert.match(main, /fs\.mkdirSync\(app\.getPath\("userData"\), \{ recursive: true \}\)/);
|
|
assert.match(main, /fs\.writeFileSync\(lastMSRDirectoryFile\(\), JSON\.stringify\(\{ directory: directory \}\)/);
|
|
assert.match(main, /fs\.statSync\(directory\)\.isDirectory\(\)/);
|
|
assert.match(main, /defaultPath: msrDialogDirectory\(\)/);
|
|
assert.match(main, /rememberMSRDirectory\(path\.dirname\(result\.filePaths\[0\]\)\)/);
|
|
assert.match(main, /rememberMSRDirectory\(path\.dirname\(result\.filePath\)\)/);
|
|
}
|
|
|
|
// Native selectors must remain attached to the requesting BrowserWindow. File
|
|
// menu results return to the known main window rather than transient focus,
|
|
// which can be null after a Linux portal dialog closes.
|
|
function testMainProcessDialogRouting() {
|
|
const main = fs.readFileSync(path.join(repoRoot, "main.js"), "utf8");
|
|
assert.match(main, /BrowserWindow\.fromWebContents\(event\.sender\)/);
|
|
assert.match(main, /dialog\.showOpenDialog\(owner,/);
|
|
assert.match(main, /win\.webContents\.send\('openFile'/);
|
|
assert.match(main, /win\.webContents\.send\('saveFile'/);
|
|
assert.match(main, /ipcMain\.handle\("write-clipboard"/);
|
|
assert.match(main, /clipboard\.writeText\(String\(text == null \? "" : text\)\)/);
|
|
assert.match(main, /ipcMain\.on\("selectBinFolder"/);
|
|
assert.match(main, /event\.reply\("binFolderSelected", result\.filePaths\)/);
|
|
}
|
|
|
|
testBridgeDrivesPortableNaming();
|
|
testBridgeChildProcessSurface();
|
|
testSynchronousWorkDirectoryPreparation();
|
|
testPreferenceBrowsePayloadsUseBridgeContract();
|
|
testBinFolderBrowsePayloadTolerance();
|
|
testConfiguredBinDirDrivesCommandResolution();
|
|
testBinDirPreferencePersistence();
|
|
testBinDirPreferenceCancelRestoresOriginal();
|
|
testFileMenuPayloadsUseBridgeContract();
|
|
const openForwards = testFileMenuOpenForwardsContentThroughBridge();
|
|
testPreloadReadFileForwardsData();
|
|
testRunLocalProcessOverBridge();
|
|
testHardeningContract();
|
|
testPreloadExposesBridgeObject();
|
|
testElectronShareCopyUsesBridgeClipboard().catch(function(error) {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|
|
testPreloadAbortJobKillsProcess().catch(function(error) {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|
|
testElectronAbortEndsRunningJob().catch(function(error) {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|
|
testMainProcessDialogRouting();
|
|
testMainRemembersMSRDialogDirectory();
|
|
|
|
// The auxiliary parameter-plot window must consume the same bridge. Load both
|
|
// auxiliary shims in a fresh sandbox exposing only window.electronAPI (the
|
|
// hardened shape); loadPlotly/readDataSource/chooseDataSource and the
|
|
// parameterPlotData listener must work without any require() path.
|
|
function loadAuxiliarySandbox(bridge, extra = {}) {
|
|
const sandbox = {
|
|
console: console,
|
|
process: { env: {} },
|
|
require: require,
|
|
window: Object.assign({
|
|
electronAPI: bridge || makeBridge(),
|
|
addEventListener: function () {},
|
|
MusrfitParameterPlotPlatform: {}
|
|
}, extra.window || {}),
|
|
document: Object.assign({
|
|
body: { appendChild: function () {}, textContent: "" },
|
|
createElement: function (tag) {
|
|
const el = {
|
|
addEventListener: function () {},
|
|
setAttribute: function () {},
|
|
appendChild: function () {},
|
|
textContent: ""
|
|
};
|
|
// Simulate loading a local <script src> by assigning window.Plotly
|
|
// and firing its onload, mirroring what the renderer does when the
|
|
// bundled Plotly file finishes loading.
|
|
if (tag === "script") {
|
|
el.async = true;
|
|
el._onAppend = function () {
|
|
sandbox.window.Plotly = { __bridgePlotly: true, Icons: {} };
|
|
if (typeof el.onload === "function") el.onload();
|
|
};
|
|
}
|
|
return el;
|
|
},
|
|
head: { appendChild: function () {} }
|
|
}, extra.document || {})
|
|
};
|
|
|
|
// head.appendChild drives the <script> load simulation above.
|
|
sandbox.document.head.appendChild = function (element) {
|
|
if (element && typeof element._onAppend === "function") element._onAppend();
|
|
};
|
|
|
|
sandbox.global = sandbox;
|
|
// The window script calls showMusrfitParameterPlotWindow as a bare global
|
|
// (defined by the shared renderer in production). Hoist a stub onto the vm
|
|
// global so the IPC handler can run; tests override it to capture the call.
|
|
sandbox.showMusrfitParameterPlotWindow =
|
|
(extra.window && extra.window.showMusrfitParameterPlotWindow) || function () {};
|
|
const windowCode = fs.readFileSync(
|
|
path.join(repoRoot, "parameter-plot-window.js"), "utf8");
|
|
vm.runInNewContext(windowCode, sandbox, { filename: "parameter-plot-window.js" });
|
|
const elecCode = fs.readFileSync(
|
|
path.join(repoRoot, "muSRFitParameterPlotElec.js"), "utf8");
|
|
vm.runInNewContext(elecCode, sandbox, { filename: "muSRFitParameterPlotElec.js" });
|
|
return sandbox;
|
|
}
|
|
|
|
// The parameter-plot window must subscribe through the bridge and normalize the
|
|
// IPC payload (no event wrapper) before forwarding to the shared renderer.
|
|
function testParameterPlotWindowUsesBridge() {
|
|
const bridge = makeBridge();
|
|
let shown = null;
|
|
const sandbox = loadAuxiliarySandbox(bridge, {
|
|
window: {
|
|
showMusrfitParameterPlotWindow: function (...args) { shown = args; }
|
|
}
|
|
});
|
|
const handlers = bridge.ipc.listeners && bridge.ipc.listeners.parameterPlotData;
|
|
assert.ok(Array.isArray(handlers) && handlers.length === 1,
|
|
"parameter-plot-window must subscribe through the bridge");
|
|
handlers[0]({ parameterPath: "a_par.dat", jobName: "J", preferredParameters: ["Asy"], preferredXColumn: "dataT" });
|
|
assert.ok(shown, "payload must reach the shared renderer");
|
|
assert.strictEqual(shown[0], "a_par.dat");
|
|
assert.strictEqual(shown[1], "J");
|
|
assert.deepStrictEqual(Array.from(shown[2]), ["Asy"]);
|
|
assert.strictEqual(shown[3], "dataT");
|
|
handlers[0]({});
|
|
assert.strictEqual(shown[0], "");
|
|
}
|
|
|
|
// The electron plot adapter must read files and choose data through the bridge,
|
|
// and load Plotly from the local plotlyURL exposed by preload.
|
|
function testParameterPlotElecAdapterUsesBridge() {
|
|
const dataFile = path.join(workDir, "params.dat");
|
|
fs.writeFileSync(dataFile, "RUN Asy\n514 0.2\n", "utf8");
|
|
const bridge = makeBridge();
|
|
bridge.ipc.invoke = function (channel, currentPath) {
|
|
return Promise.resolve(channel === "selectParameterDataFile" ? "/picked/params.dat" : "");
|
|
};
|
|
const sandbox = loadAuxiliarySandbox(bridge);
|
|
const platform = sandbox.window.MusrfitParameterPlotPlatform;
|
|
|
|
assert.strictEqual(typeof platform.readDataSource, "function");
|
|
assert.strictEqual(typeof platform.chooseDataSource, "function");
|
|
assert.strictEqual(typeof platform.loadPlotly, "function");
|
|
|
|
return platform.loadPlotly().then(function (plotly) {
|
|
assert.ok(plotly && plotly.__bridgePlotly);
|
|
return platform.readDataSource({ kind: "path", path: dataFile });
|
|
}).then(function (contents) {
|
|
assert.match(contents, /RUN Asy/);
|
|
return platform.chooseDataSource({ kind: "path", path: "" });
|
|
}).then(function (source) {
|
|
assert.ok(source, "chooseDataSource must resolve a source");
|
|
assert.strictEqual(source.kind, "path");
|
|
assert.strictEqual(source.path, "/picked/params.dat");
|
|
});
|
|
}
|
|
|
|
// loadPlotly in the hardened build must prefer the bridge plotlyURL script
|
|
// loader and only require() plotly as a last resort.
|
|
function testParameterPlotElecLoadsLocalPlotly() {
|
|
const code = fs.readFileSync(
|
|
path.join(repoRoot, "muSRFitParameterPlotElec.js"), "utf8");
|
|
assert.match(code, /plotlyURL/);
|
|
assert.doesNotMatch(code, /^[ \t]*const \{ ipcRenderer \} = require\("electron"\)/);
|
|
assert.doesNotMatch(code, /require\("plotly\.js-dist"\)[^(]/);
|
|
|
|
// Bridge path with no window.Plotly pre-set must still expose the URL it
|
|
// will load, and must not throw during module evaluation.
|
|
const bridge = makeBridge();
|
|
const sandbox = loadAuxiliarySandbox(bridge);
|
|
const platform = sandbox.window.MusrfitParameterPlotPlatform;
|
|
const p = platform.loadPlotly();
|
|
assert.ok(p && typeof p.then === "function");
|
|
}
|
|
|
|
testParameterPlotWindowUsesBridge();
|
|
testParameterPlotElecAdapterUsesBridge();
|
|
testParameterPlotElecLoadsLocalPlotly();
|
|
|
|
openForwards.then(function() {
|
|
console.log("Electron preload-bridge tests passed");
|
|
}).catch(function(error) {
|
|
console.error(error);
|
|
process.exitCode = 1;
|
|
});
|