Files
muSRFlow/preload.js

287 lines
12 KiB
JavaScript

// Copyright (C) 2026 Zaher Salman
// SPDX-License-Identifier: GPL-3.0-or-later
// Preload bridge for the Electron build. The renderer runs with
// contextIsolation:true and nodeIntegration:false, so it has no direct Node
// access. This script (which runs with full Node access because sandbox:false)
// deliberately exposes only the small, curated set of filesystem, path,
// child-process, and environment helpers the muSRFlow renderer needs. All
// values crossing the bridge are plain, serializable objects or callbacks.
const { contextBridge, ipcRenderer } = require("electron");
const fs = require("fs");
const path = require("path");
const childProcess = require("child_process");
const { pathToFileURL } = require("url");
const zlib = require("zlib");
// Plotly ships as a single bundled script under node_modules/plotly.js-dist.
// The renderer (nodeIntegration:false) cannot require it, so the bridge exposes
// a local file:// URL that the shared renderer loads through a <script> tag,
// mirroring how the web build loads Plotly from a CDN URL.
const BUNDLED_PLOTLY_PATH = path.join(
__dirname, "node_modules", "plotly.js-dist", "plotly.js"
);
// IPC channels the renderer may subscribe to or send on. Send to a channel
// that is not in this list is silently dropped; menus and dialogs in the main
// process are the only senders here.
const ALLOWED_RECEIVE_CHANNELS = [
"openFile",
"openPreferences",
"openSharedConfiguration",
"saveSession",
"openSessionHistory",
"saveFile",
"workFolderSelected",
"dataRootSelected",
"startupXmlSelected",
"binFolderSelected",
"parameterPlotData"
];
const ALLOWED_SEND_CHANNELS = [
"selectWorkFolder",
"selectDataRootFolder",
"selectStartupXmlFile",
"selectBinFolder",
"openParameterPlotWindow",
"openQuickStartWindow"
];
const ALLOWED_INVOKE_CHANNELS = [
"selectParameterDataFile",
"selectParameterDataFiles",
"write-clipboard"
];
function toText(value) {
return Buffer.isBuffer(value) ? value.toString() : (value == null ? "" : String(value));
}
// Handles for running child processes, keyed by a caller-supplied job token.
// The renderer keeps the token for the last launched job, so an Abort action
// can target exactly that job without ever exposing PIDs into the page.
const runningJobs = {};
const bridge = {
ipc: {
on: function (channel, listener) {
if (!ALLOWED_RECEIVE_CHANNELS.includes(channel) || typeof listener !== "function") return;
const wrapped = function (event, ...args) { listener(...args); };
ipcRenderer.on(channel, wrapped);
return function () { ipcRenderer.removeListener(channel, wrapped); };
},
send: function (channel, ...args) {
if (ALLOWED_SEND_CHANNELS.includes(channel)) ipcRenderer.send(channel, ...args);
},
invoke: function (channel, ...args) {
if (!ALLOWED_INVOKE_CHANNELS.includes(channel)) {
return Promise.reject(new Error("IPC channel not allowed: " + channel));
}
return ipcRenderer.invoke(channel, ...args);
}
},
fs: {
existsSync: function (p) { return fs.existsSync(p); },
lstatSync: function (p) {
var s = fs.lstatSync(p);
return {
size: s.size,
isFile: function () { return s.isFile(); },
isDirectory: function () { return s.isDirectory(); },
isSymbolicLink: function () { return s.isSymbolicLink(); }
};
},
statSync: function (p) {
var s = fs.statSync(p);
return {
size: s.size,
isFile: function () { return s.isFile(); },
isDirectory: function () { return s.isDirectory(); },
isSymbolicLink: function () { return s.isSymbolicLink(); }
};
},
accessSync: function (p, mode) { return fs.accessSync(p, mode); },
readdirSync: function (p) { return fs.readdirSync(p); },
readFileSync: function (p, encoding) { return fs.readFileSync(p, encoding); },
writeFileSync: function (p, data, options) { return fs.writeFileSync(p, data, options); },
appendFileSync: function (p, data, options) { return fs.appendFileSync(p, data, options); },
copyFileSync: function (src, dest, mode) { return fs.copyFileSync(src, dest, mode); },
linkSync: function (target, pathStr) { return fs.linkSync(target, pathStr); },
renameSync: function (oldPath, newPath) { return fs.renameSync(oldPath, newPath); },
unlinkSync: function (p) { return fs.unlinkSync(p); },
rmSync: function (p, options) { return fs.rmSync(p, options); },
mkdirSync: function (p, options) { return fs.mkdirSync(p, options); },
mkdir: function (p, options, callback) {
fs.mkdir(p, options, function (err) {
if (typeof callback === "function") callback(err ? { message: err.message } : null);
});
},
readFile: function (p, encoding, callback) {
if (typeof callback === "function") {
fs.readFile(p, encoding, function (err, data) {
console.log("[bridge.readFile] " + p
+ (err ? " error: " + err.message : " ok " + (data ? data.length : 0) + " bytes"));
callback(err ? { message: err.message } : null, data);
});
}
},
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
}
},
path: {
join: function (...parts) { return path.join(...parts); },
resolve: function (...parts) { return path.resolve(...parts); },
basename: function (p, ext) { return path.basename(p, ext); },
dirname: function (p) { return path.dirname(p); }
},
// gzip helpers used by shared-configuration links. They cross the bridge as
// plain base64url/text strings so the sanitized renderer never holds a Buffer
// and never needs a zlib/Buffer require.
zlib: {
gzipBase64URL: function (text) {
const zipped = zlib.gzipSync(Buffer.from(String(text), "utf8"));
return zipped.toString("base64")
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
},
gunzipBase64URL: function (payload) {
let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/");
while (base64.length % 4) base64 += "=";
const zipped = Buffer.from(base64, "base64");
return zlib.gunzipSync(zipped).toString("utf8");
}
},
// Clipboard access for the configuration-link share button, routed through
// the main process (the renderer preload has no electron.clipboard module;
// only the main process can touch the system clipboard here).
clipboard: {
writeText: function (text) {
return ipcRenderer.invoke("write-clipboard", String(text == null ? "" : text));
}
},
process: {
cwd: function () { return process.cwd(); },
resourcesPath: process.resourcesPath || "",
plotlyURL: pathToFileURL(BUNDLED_PLOTLY_PATH).href,
env: Object.assign({}, process.env)
},
childProcess: {
execSync: function (command, options) {
try {
const result = childProcess.execSync(command, options || {});
return { ok: true, stdout: toText(result), 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 || String(err)
};
}
},
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 || String(err) };
}
// Normalize the synchronous child-process result into a plain object
// that the renderer shim turns back into the familiar spawnSync shape.
return {
pid: result && typeof result.pid === "number" ? result.pid : null,
status: result && typeof result.status === "number" ? result.status : null,
signal: result ? (result.signal || null) : null,
stdout: result ? toText(result.stdout) : "",
stderr: result ? toText(result.stderr) : "",
error: result && result.error ? (result.error.message || String(result.error)) : null
};
},
spawnCapture: function (command, args, options, onChunk) {
return new Promise(function (resolve) {
let child;
let stdoutText = "";
let stderrText = "";
let settled = false;
const jobKey = options && options.jobToken ? String(options.jobToken) : "";
const unregister = function () {
if (!jobKey) return;
const entry = runningJobs[jobKey];
if (entry) {
if (entry.killTimer) clearTimeout(entry.killTimer);
delete runningJobs[jobKey];
}
};
const emit = function (label, chunk) {
stdoutText += chunk;
if (typeof onChunk === "function") onChunk(label, chunk);
};
try {
child = childProcess.spawn(command, args || [], Object.assign({}, options, {
shell: false,
stdio: ["ignore", "pipe", "pipe"]
}));
} catch (err) {
resolve({ ok: 0, code: 1, signal: null, stdout: "", stderr: "", error: err.message || String(err) });
return;
}
if (jobKey) {
runningJobs[jobKey] = { child: child, done: false, killTimer: null, escalated: false };
}
child.stdout.on("data", function (chunk) { emit("stdout", chunk.toString()); });
child.stderr.on("data", function (chunk) { emit("stderr", chunk.toString()); });
child.on("error", function (err) {
if (settled) return;
settled = true;
unregister();
resolve({ ok: 0, code: 1, signal: null, stdout: stdoutText, stderr: stderrText, error: err.message || String(err) });
});
child.on("close", function (code, signal) {
if (settled) return;
settled = true;
unregister();
resolve({ ok: code === 0 ? 1 : 0, code: code, signal: signal, stdout: stdoutText, stderr: stderrText, error: null });
});
});
},
// Kill the last launched job (SIGTERM, then SIGKILL after a grace
// period). Returns { ok: false } when the token is unknown or already
// finished so the renderer can stop expecting that job to abort.
abortJob: function (token, signal) {
const key = String(token == null ? "" : token);
const entry = runningJobs[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.killTimer = setTimeout(function () {
const live = runningJobs[key];
if (live && !live.done) {
try { live.child.kill("SIGKILL"); } catch (ignore) {}
}
}, 3000);
}
} catch (err) {
return { ok: false, code: err && err.message ? err.message : String(err) };
}
return { ok: true, code: sig };
}
}
};
contextBridge.exposeInMainWorld("electronAPI", bridge);