From 26c654fcfcbedcf81caafb941cff41bfc6a84efd Mon Sep 17 00:00:00 2001 From: salman Date: Tue, 8 Sep 2026 13:46:34 +0200 Subject: [PATCH] Fix share-link copy through a main-process clipboard bridge The hardened renderer has no require() and no electron.clipboard module in the preload, and window.prompt() throws in Electron, so the configuration share button silently failed. Route clipboard writes through ipcRenderer invoke to a main-process handler, and guard the prompt fallback so an unsupported prompt() cannot reject the copy flow. --- main.js | 10 ++- muSRFitelec.js | 17 +++- muSRFitlib.js | 9 +- preload.js | 12 ++- tests/electron-bridge.test.js | 48 +++++++++++ tests/shared-configuration.test.js | 128 ++++++++++++++++++++--------- 6 files changed, 177 insertions(+), 47 deletions(-) diff --git a/main.js b/main.js index bd26582..65853d5 100644 --- a/main.js +++ b/main.js @@ -1,7 +1,7 @@ // Copyright (C) 2026 Zaher Salman // SPDX-License-Identifier: GPL-3.0-or-later -const { app, BrowserWindow, Menu, dialog, ipcMain, screen, shell } = require('electron'); +const { app, BrowserWindow, Menu, dialog, ipcMain, screen, shell, clipboard } = require('electron'); const path = require('path'); const fs = require('fs'); const childProcess = require('child_process'); @@ -410,3 +410,11 @@ ipcMain.handle("selectParameterDataFile", async (event, currentPath) => { }); return result.canceled || !result.filePaths.length ? "" : result.filePaths[0]; }); + +// The configuration-link share button writes to the system clipboard. The +// renderer cannot (no require, no clipboard module in the preload), so the +// main process performs the write on its behalf. +ipcMain.handle("write-clipboard", async (event, text) => { + clipboard.writeText(String(text == null ? "" : text)); + return true; +}); diff --git a/muSRFitelec.js b/muSRFitelec.js index ba17f3d..13846b1 100644 --- a/muSRFitelec.js +++ b/muSRFitelec.js @@ -327,11 +327,22 @@ function electronShareBaseURL() { } function electronWriteClipboard(url) { - let clipboard = require("electron").clipboard; - if (!clipboard || typeof clipboard.writeText !== "function") { + let write = window.electronAPI && window.electronAPI.clipboard + && typeof window.electronAPI.clipboard.writeText === "function" + ? window.electronAPI.clipboard.writeText.bind(window.electronAPI.clipboard) + : null; + if (!write && typeof require === "function") { + // Test-sandbox fallback. The hardened renderer has no global require, so + // this branch is only reachable in the vm sandbox where require exists. + let electron = require("electron"); + if (electron && electron.clipboard && typeof electron.clipboard.writeText === "function") { + write = electron.clipboard.writeText.bind(electron.clipboard); + } + } + if (typeof write !== "function") { throw new Error("Electron clipboard is unavailable"); } - clipboard.writeText(url); + write(url); return true; } diff --git a/muSRFitlib.js b/muSRFitlib.js index 3c63c17..41c71d5 100644 --- a/muSRFitlib.js +++ b/muSRFitlib.js @@ -242,8 +242,13 @@ async function shareConfigurationLink(platform) { // Browser clipboard access can be blocked by policy. A prompt still gives // the user the exact link without storing it anywhere in the application. if (typeof window !== "undefined" && typeof window.prompt === "function") { - window.prompt("Copy configuration link:", url); - return true; + try { + window.prompt("Copy configuration link:", url); + return true; + } catch (promptError) { + // Electron defines prompt() but throws "prompt() is not supported."; + // fall through to the transient warning and status error path. + } } if (typeof showTransientWarning === "function") { showTransientWarning( diff --git a/preload.js b/preload.js index edd00b4..002a176 100644 --- a/preload.js +++ b/preload.js @@ -46,7 +46,8 @@ const ALLOWED_SEND_CHANNELS = [ ]; const ALLOWED_INVOKE_CHANNELS = [ - "selectParameterDataFile" + "selectParameterDataFile", + "write-clipboard" ]; function toText(value) { @@ -162,6 +163,15 @@ readFile: function (p, encoding, callback) { } }, + // 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 || "", diff --git a/tests/electron-bridge.test.js b/tests/electron-bridge.test.js index 7387b03..04a4296 100644 --- a/tests/electron-bridge.test.js +++ b/tests/electron-bridge.test.js @@ -121,6 +121,11 @@ function makeBridge() { X_OK: fs.constants.X_OK }; + bridge.clipboard = { + writeText: function (text) { bridge.__clipboardText = String(text); return true; }, + readText: function () { return bridge.__clipboardText || ""; } + }; + return bridge; } @@ -342,6 +347,42 @@ 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=/); + }); +} + +// 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 @@ -353,6 +394,8 @@ function testMainProcessDialogRouting() { 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\)\)/); } testBridgeDrivesPortableNaming(); @@ -365,7 +408,12 @@ testPreloadReadFileForwardsData(); testRunLocalProcessOverBridge(); testHardeningContract(); testPreloadExposesBridgeObject(); +testElectronShareCopyUsesBridgeClipboard().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 diff --git a/tests/shared-configuration.test.js b/tests/shared-configuration.test.js index 168daa3..09ece07 100644 --- a/tests/shared-configuration.test.js +++ b/tests/shared-configuration.test.js @@ -7,10 +7,10 @@ const path = require("path"); const vm = require("vm"); const repoRoot = path.resolve(__dirname, ".."); +const commonCode = fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"); +const electronCode = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8"); function loadSharedConfigurationHelpers() { - const commonCode = fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"); - const electronCode = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8"); const ipcListeners = {}; let clipboardText = ""; const electron = { @@ -323,42 +323,10 @@ async function testUserCanCancelOverwritingEditorOwnership() { assert.strictEqual(lib.getMSRDocumentState("current").dirty, true); } -async function testElectronBridgeDecodeHardenedRenderer() { - // In the hardened Electron renderer (contextIsolation:true, sandbox:false), - // require('zlib') and require('buffer') are not available. This test loads - // muSRFitelec.js in a sandbox where require throws for Node builtins and only - // window.electronAPI.zlib is available, confirming the bridge-based path works. - const realZlib = require("zlib"); - const realBuffer = require("buffer"); - - function gzipBase64URL(text) { - const zipped = realZlib.gzipSync(realBuffer.Buffer.from(text, "utf8")); - return zipped.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); - } - function gunzipBase64URL(payload) { - let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/"); - while (base64.length % 4) base64 += "="; - const zipped = realBuffer.Buffer.from(base64, "base64"); - return realZlib.gunzipSync(zipped).toString("utf8"); - } - const bridgeZlib = { gzipBase64URL: gzipBase64URL, gunzipBase64URL: gunzipBase64URL }; - - // First encode in a normal environment to get a valid #c= payload. - const normalEnv = loadSharedConfigurationHelpers(); - const config = { - v: 1, - controls: { instrName: "LEM", runNumbers: "514-516" }, - components: ["ExponentialCos"], - parameters: { valFrq_514: "1.2" }, - functionMaps: { 1: { target: "Phi", parameters: ["RelPh_L", "RelPh_R"] } } - }; - const encoded = await normalEnv.sandbox.encodeElectronSharedConfiguration(config); - const url = "http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload; - - // Create a sandbox that simulates the hardened renderer: require throws for - // Node builtins, only window.electronAPI is available. - const commonCode = fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"); - const electronCode = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8"); +// A sandbox that simulates the hardened Electron renderer: require throws for +// Node builtins, only window.electronAPI is available. extraAPI merges into +// window.electronAPI so each test can expose the bridge surface it targets. +function buildHardenedSandbox(bridgeZlib, extraAPI) { const hardenedElements = {}; const hardenedSandbox = { URL: URL, @@ -368,7 +336,7 @@ async function testElectronBridgeDecodeHardenedRenderer() { setTimeout: function(callback) { callback(); }, window: { MSREditor: {}, - electronAPI: { + electronAPI: Object.assign({ zlib: bridgeZlib, ipc: { on: function() {}, send: function() {}, invoke: function() { return Promise.resolve(null); } }, fs: { @@ -401,7 +369,7 @@ async function testElectronBridgeDecodeHardenedRenderer() { spawnSync: function() { return { pid: null, status: 0, signal: null, stdout: "", stderr: "", error: null }; }, spawnCapture: function() { return Promise.resolve({ ok: 1, code: 0, signal: null, stdout: "", stderr: "", error: null }); } } - } + }, extraAPI || {}) }, document: { getElementById: function(id) { return hardenedElements[id] || null; }, @@ -418,6 +386,44 @@ async function testElectronBridgeDecodeHardenedRenderer() { vm.runInNewContext(commonCode, hardenedSandbox, { filename: "muSRFitlib.js" }); vm.runInNewContext(electronCode, hardenedSandbox, { filename: "muSRFitelec.js" }); + return { sandbox: hardenedSandbox, elements: hardenedElements }; +} + +async function testElectronBridgeDecodeHardenedRenderer() { + // In the hardened Electron renderer (contextIsolation:true, sandbox:false), + // require('zlib') and require('buffer') are not available. This test loads + // muSRFitelec.js in a sandbox where require throws for Node builtins and only + // window.electronAPI.zlib is available, confirming the bridge-based path works. + const realZlib = require("zlib"); + const realBuffer = require("buffer"); + + function gzipBase64URL(text) { + const zipped = realZlib.gzipSync(realBuffer.Buffer.from(text, "utf8")); + return zipped.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + } + function gunzipBase64URL(payload) { + let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/"); + while (base64.length % 4) base64 += "="; + const zipped = realBuffer.Buffer.from(base64, "base64"); + return realZlib.gunzipSync(zipped).toString("utf8"); + } + const bridgeZlib = { gzipBase64URL: gzipBase64URL, gunzipBase64URL: gunzipBase64URL }; + + // First encode in a normal environment to get a valid #c= payload. + const normalEnv = loadSharedConfigurationHelpers(); + const config = { + v: 1, + controls: { instrName: "LEM", runNumbers: "514-516" }, + components: ["ExponentialCos"], + parameters: { valFrq_514: "1.2" }, + functionMaps: { 1: { target: "Phi", parameters: ["RelPh_L", "RelPh_R"] } } + }; + const encoded = await normalEnv.sandbox.encodeElectronSharedConfiguration(config); + const url = "http://musruser.psi.ch/muSRFlow/" + encoded.prefix + encoded.payload; + + // Only window.electronAPI.zlib is available (no clipboard, no require). + const hardened = buildHardenedSandbox(bridgeZlib); + const hardenedSandbox = hardened.sandbox; // Decode must succeed using only the bridge, without require('zlib'). const decoded = await hardenedSandbox.decodeElectronSharedConfiguration(url); @@ -434,6 +440,47 @@ async function testElectronBridgeDecodeHardenedRenderer() { assert.strictEqual(JSON.stringify(reDecoded.config), JSON.stringify(config)); } +async function testElectronBridgeCopyUsesBridgeClipboard() { + // Regression for "share link not working" in the packaged app: the hardened + // renderer has no require() and window.prompt() throws, so the working path + // must be bridge clipboard (window.electronAPI.clipboard.writeText). Prove + // copyWebConfigurationLink() completes and reaches the clipboard without + // ever touching require or prompt. + const realZlib = require("zlib"); + const realBuffer = require("buffer"); + function gzipBase64URL(text) { + const zipped = realZlib.gzipSync(realBuffer.Buffer.from(text, "utf8")); + return zipped.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + } + function gunzipBase64URL(payload) { + let base64 = String(payload).replace(/-/g, "+").replace(/_/g, "/"); + while (base64.length % 4) base64 += "="; + const zipped = realBuffer.Buffer.from(base64, "base64"); + return realZlib.gunzipSync(zipped).toString("utf8"); + } + let bridgeClipboardText = ""; + const hardened = buildHardenedSandbox( + { gzipBase64URL: gzipBase64URL, gunzipBase64URL: gunzipBase64URL }, + { + clipboard: { + writeText: function(value) { bridgeClipboardText = value; return true; } + } + } + ); + const lib = hardened.sandbox; + hardened.elements.Runs = { querySelectorAll: function() { return []; } }; + hardened.elements.Params = { querySelectorAll: function() { return []; } }; + lib.prepCFG = function() {}; + lib.getFitComponentValues = function() { return ["Exponential"]; }; + lib.showTransientWarning = function() {}; + lib.setFitStatus = function() {}; + + const copied = await lib.copyWebConfigurationLink(); + + assert.strictEqual(copied, true); + assert.match(bridgeClipboardText, /^http:\/\/musruser\.psi\.ch\/muSRFlow\/#c=/); +} + async function main() { await testElectronCodecReadsWebCompatibleLinks(); testSharedConfigurationIncludesDetectorMaps(); @@ -444,6 +491,7 @@ async function main() { await testElectronDialogRestoresStateAndMarksEditorStale(); await testUserCanCancelOverwritingEditorOwnership(); await testElectronBridgeDecodeHardenedRenderer(); + await testElectronBridgeCopyUsesBridgeClipboard(); console.log("shared configuration tests passed"); }