// The mollusc shell: one generic Electron main process driven by an app's // mollusc.json. It finds the app, starts its sidecar, opens its window, builds // its menu and tray, and hands it the files and URLs the OS asks it to open. import { randomBytes } from 'node:crypto'; import { existsSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { Menu, Tray, app, dialog, nativeImage, powerMonitor, screen, session } from 'electron'; import { installBridge } from './bridge.js'; import { appHost, forDev, loadConfig, substitute, usesVariable, windowTarget } from './config.js'; import { compile } from './glob.js'; import { createLogger } from './log.js'; import { applicationTemplate, translate } from './menu.js'; import { expandHome } from './paths.js'; import { registerScheme, serveApp } from './protocol.js'; import { choosePort, loginPath } from './launch.js'; import { startSidecar } from './sidecar.js'; import { createWindowManager } from './windows.js'; import { fitBounds, windowState } from './bounds.js'; const here = dirname(fileURLToPath(import.meta.url)); const dev = !app.isPackaged; const smoke = !!process.env.MOLLUSC_SMOKE; // Started at login, say: no window until asked for one. const startHidden = process.argv.includes('--hidden'); // In a built app the app directory ships unpacked next to the shell's asar; // in dev the CLI passes it. function findAppDir () { if (app.isPackaged) return join(process.resourcesPath, 'mollusc-app'); const i = process.argv.indexOf('--app'); const dir = i !== -1 ? process.argv[i + 1] : process.env.MOLLUSC_APP; return dir ? resolve(dir) : null; } // Nothing sensible can happen after this; tell the user how we can and stop. function fatal (message) { if (dev) { console.error(`mollusc: ${message}`); app.exit(1); } else app.whenReady().then(() => { dialog.showErrorBox('This app could not start', message); app.exit(1); }); return new Promise(() => {}); } const appDir = findAppDir(); if (!appDir) await fatal('No app given: run `mollusc dev `, or pass --app .'); let loaded; try { loaded = await loadConfig(appDir); } catch (err) { await fatal(err.message); } const { warnings } = loaded; const config = dev ? forDev(loaded.config) : loaded.config; app.setName(config.name); // The same user data directory in dev and once built, and one per app even // though every dev run goes through the same shell. Set before the single // instance lock, which is keyed by it. app.setPath('userData', smoke ? join(tmpdir(), `${config.name}-smoke`) : join(app.getPath('appData'), config.name)); registerScheme(); const state = { windows: null, bridge: null, main: null, mainLoaded: false, sidecar: null, attached: false, serves: [], tray: null, log: null, cfg: null, target: null, vars: null, hiddenAt: 0, }; const pending = []; // [kind, target] the OS asked us to open before the window could take them app.on('open-file', (e, file) => { e.preventDefault(); takeOpen('open-file', file); }); app.on('open-url', (e, url) => { e.preventDefault(); takeOpen('open-url', url); }); // network: "loopback": the renderers reach only loopback. No name but // localhost, *.localhost and 127.0.0.1 resolves; what still has an address // goes to a proxy that is not there (set once the session exists, below); // and WebRTC may not use UDP except through that proxy, so there is no ICE // either. The sidecar does the app's networking. For apps that render // untrusted content: this is what Delta Chat does for webxdc. Switches have // to be set before the app is ready. if (config.network === 'loopback') { app.commandLine.appendSwitch('host-resolver-rules', 'MAP * ~NOTFOUND, EXCLUDE localhost, EXCLUDE *.localhost, EXCLUDE 127.0.0.1'); app.commandLine.appendSwitch('force-webrtc-ip-handling-policy', 'disable_non_proxied_udp'); } if (!app.requestSingleInstanceLock()) { app.quit(); } else { app.on('second-instance', (e, argv) => { // ` --quit` asks the running one to stop. if (argv.includes('--quit')) { app.quit(); return; } for (const [kind, target] of openables(argv)) takeOpen(kind, target); if (!argv.includes('--hidden')) showMain(); }); app.whenReady().then(ready).catch((err) => { state.log?.error(err.stack || err.message); fatal(err.message); }); } async function ready () { const userData = app.getPath('userData'); const log = state.log = createLogger({ dir: join(userData, 'logs'), name: 'mollusc', toConsole: dev }); for (const w of warnings) log.warn(w); log.info(`${config.name} ${config.version} from ${appDir}${dev ? ' (dev)' : ''}`); // Started from the Finder or at login, the environment has a bare PATH. if (app.isPackaged) { const path = await loginPath(); if (path) process.env.PATH = path; } const saved = readState(userData); const token = randomBytes(24).toString('base64url'); const base = { token, appDir, userData, home: homedir() }; let port = null; if (config.sidecar || usesVariable(config, 'port')) { const readyUrl = (p) => (config.sidecar?.ready ? substitute(config.sidecar.ready, { ...base, port: p }) : null); try { const chosen = await choosePort({ sidecar: config.sidecar, remembered: saved.port, readyUrl }); port = chosen.port; state.attached = chosen.attach; } catch (err) { return failStart(err, null); } if (!config.sidecar?.port) writeState(userData, { ...saved, port }); } const vars = state.vars = { ...base, port }; const cfg = state.cfg = substitute(config, vars); const host = appHost(cfg); const target = state.target = cfg.window ? windowTarget(cfg) : null; const sidecarOrigin = port ? `http://127.0.0.1:${port}` : null; const allowedOrigins = new Set([`app://${host}`, sidecarOrigin, port && `http://localhost:${port}`, target?.origin].filter(Boolean)); const env = { name: cfg.name, version: cfg.version, platform: process.platform, port, token, sidecarOrigin, appOrigin: `app://${host}` }; serveApp({ root: appDir, host, log }); setPermissions(cfg.permissions); if (cfg.network === 'loopback') await lockToLoopback(); const windows = state.windows = createWindowManager({ preload: cfg.api.length ? join(here, 'preload.cjs') : null, api: cfg.api, env, allowedOrigins, log, network: cfg.network, }); state.bridge = installBridge({ api: cfg.api, roots: roots(cfg, vars), windows, log, info: () => ({ ...env, appDir, userData }) }); if (dev) { for (const s of cfg.dev.serve) { try { state.serves.push(await startProcess(s, 'serve')); } catch (err) { return failStart(err, s.command); } } } if (cfg.sidecar && !state.attached) { await runSidecar(); if (!state.sidecar) return; } if (state.attached) log.info(`attached to the sidecar already on port ${port}`); if (cfg.menu) Menu.setApplicationMenu(Menu.buildFromTemplate(applicationTemplate(cfg.menu, { send: windows.send, actions: menuActions }))); if (cfg.tray) state.tray = createTray(cfg.tray); if (cfg.tray && (!cfg.window || cfg.window.popover)) app.dock?.hide(); if (dev && cfg.icon && existsSync(resolve(appDir, cfg.icon)) && !cfg.window?.popover) app.dock?.setIcon(resolve(appDir, cfg.icon)); if (cfg.window) { openMain(); if (cfg.window.popover) watchPopover(); } // Built apps are registered by their installer; in dev, point the OS at this // shell with this app so `scheme://` links reach us too. for (const scheme of cfg.urlSchemes) { if (app.isPackaged) app.setAsDefaultProtocolClient(scheme); else if (!smoke) app.setAsDefaultProtocolClient(scheme, process.execPath, [here, '--app', appDir]); } // Windows and Linux pass the file or URL we were launched with on the command line. for (const [kind, t] of openables(process.argv)) takeOpen(kind, t); if (dev && !smoke) watchForChanges(); if (smoke) runSmoke(); app.on('activate', () => showMain()); app.on('window-all-closed', () => { // The sidecar follows the windows unless keepAlive says otherwise; a tray // app lives in the menu bar and stays. if (cfg.tray || smoke) return; if (cfg.sidecar?.keepAlive && process.platform === 'darwin') return; app.quit(); }); app.on('will-quit', () => { state.sidecar?.kill(); for (const s of state.serves) s.kill(); log.close(); }); } // ── state kept between launches ────────────────────────────────────────────── function readState (userData) { try { return JSON.parse(readFileSync(join(userData, 'mollusc-state.json'), 'utf8')); } catch { return {}; } } function writeState (userData, data) { try { writeFileSync(join(userData, 'mollusc-state.json'), `${JSON.stringify(data)}\n`); } catch (err) { state.log?.warn(`could not save state: ${err.message}`); } } // ── sidecar and dev processes ──────────────────────────────────────────────── function processEnv (extra) { const { vars } = state; const env = { ...process.env, ...extra, MOLLUSC_APP: vars.appDir, MOLLUSC_USER_DATA: vars.userData, MOLLUSC_TOKEN: vars.token, // How to start this app again, as argv (a login item, say): the bundle's // binary once built, this shell on this app in dev. MOLLUSC_LAUNCH: JSON.stringify(app.isPackaged ? [process.execPath] : [process.execPath, here, '--app', vars.appDir]), }; if (vars.port) env.MOLLUSC_PORT = String(vars.port); // Set, this makes any Electron the sidecar starts a plain Node. delete env.ELECTRON_RUN_AS_NODE; return env; } async function startProcess (spec, name) { const { vars } = state; const log = createLogger({ dir: join(vars.userData, 'logs'), name, toConsole: dev }); return startSidecar({ sidecar: spec, appDir: vars.appDir, env: processEnv(spec.env), log, name }); } async function runSidecar () { const { cfg, vars, log } = state; try { const sidecar = state.sidecar = await startProcess(cfg.sidecar, 'sidecar'); log.info(`sidecar ready on port ${vars.port}`); sidecar.exited.then((r) => { if (state.sidecar !== sidecar) return; // replaced on purpose state.sidecar = null; state.windows.broadcast('sidecar-exit', { code: r.code, signal: r.signal }); }); } catch (err) { failStart(err, 'sidecar'); } } function failStart (err, logName) { const { log, cfg } = state; log.error(err.message); const detail = logName ? `${err.message}\n\nSee ${join(app.getPath('userData'), 'logs', `${logName === 'sidecar' ? 'sidecar' : 'serve'}.log`)}` : err.message; if (dev) console.error(`mollusc: ${detail}`); else dialog.showErrorBox(`${(cfg || config).name} could not start`, detail); for (const s of state.serves) s.kill(); app.exit(1); } async function restartSidecar () { const old = state.sidecar; state.sidecar = null; if (old) await old.kill(); await runSidecar(); } // ── windows, menu, tray ────────────────────────────────────────────────────── function openMain () { const { cfg, target, windows } = state; const popover = !!cfg.window.popover; // Where it was last time, when that place is still on a screen; a popover // is placed under its tray icon instead. const remembered = cfg.window.remember !== false && !popover ? rememberedWindow() : null; const win = state.main = windows.open(target.url, { ...cfg.window, ...remembered, privileged: true, hideOnClose: popover, show: popover || startHidden ? false : cfg.window.show, }); if (remembered) rememberWindow(win); state.mainLoaded = false; win.webContents.once('did-finish-load', () => { state.mainLoaded = true; while (pending.length) windows.send(...pending.shift()); if (popover && !startHidden && !smoke) showMain(); }); win.on('closed', () => { if (state.main === win) { state.main = null; state.mainLoaded = false; } }); return win; } // The main window's last size, position and state, as options for a new one. function rememberedWindow () { const saved = readState(app.getPath('userData')).window; if (!saved) return {}; const bounds = fitBounds(saved.bounds, screen.getAllDisplays()); return { ...(bounds ?? {}), maximized: !!saved.maximized, fullScreen: !!saved.fullScreen }; } // Keep the main window's bounds and state as they change, and once more when it closes. function rememberWindow (win) { const userData = app.getPath('userData'); let timer = null; const save = () => { timer = null; if (win.isDestroyed()) return; writeState(userData, { ...readState(userData), window: windowState(win, screen) }); }; const later = () => { clearTimeout(timer); timer = setTimeout(save, 500); }; for (const ev of ['resize', 'move', 'maximize', 'unmaximize', 'enter-full-screen', 'leave-full-screen']) win.on(ev, later); win.on('close', () => { clearTimeout(timer); save(); }); } function showMain () { if (!state.cfg?.window) return; if (!state.main) { openMain(); return; } if (state.cfg.window.popover) placeUnderTray(state.main); if (state.main.isMinimized()) state.main.restore(); state.main.show(); state.main.focus(); } const menuActions = { showWindow: () => showMain() }; function toggleMain () { if (state.main?.isVisible()) state.main.hide(); // Clicking the tray icon while a popover is open blurs (and so hides) it // before the click arrives; don't pop it straight back up. else if (Date.now() - state.hiddenAt > 300) showMain(); } // A popover sits under the tray icon, centred on it and kept on screen. function placeUnderTray (win) { let tb = state.tray?.getBounds(); if (!tb?.width || !tb?.height) { // No usable tray bounds (menu bar hidden?): top right of the main display. const { workArea } = screen.getPrimaryDisplay(); tb = { x: workArea.x + workArea.width - 24, y: workArea.y - 24, width: 24, height: 24 }; } const { workArea } = screen.getDisplayNearestPoint({ x: tb.x, y: tb.y }); const [width] = win.getSize(); let x = Math.round(tb.x + tb.width / 2 - width / 2); x = Math.max(workArea.x + 8, Math.min(x, workArea.x + workArea.width - width - 8)); const y = process.platform === 'darwin' || tb.y < workArea.y + workArea.height / 2 ? Math.round(tb.y + tb.height + 4) : Math.round(tb.y - win.getSize()[1] - 4); win.setPosition(x, y, false); } // A popover goes away when it loses focus (unless one of its own dialogs took // it), and when sleep, a locked screen or a display change would leave it // floating somewhere odd. function watchPopover () { const hide = () => { if (state.main?.isVisible()) state.main.hide(); }; state.main.setVisibleOnAllWorkspaces?.(true, { visibleOnFullScreen: true }); state.main.on('blur', () => { if (!state.bridge.inDialog()) hide(); }); state.main.on('hide', () => { state.hiddenAt = Date.now(); }); for (const ev of ['suspend', 'resume', 'lock-screen']) powerMonitor.on(ev, hide); for (const ev of ['display-added', 'display-removed', 'display-metrics-changed']) screen.on(ev, hide); } function createTray (tray) { const { windows, log } = state; const file = resolve(appDir, tray.icon); const icon = nativeImage.createFromPath(file); if (icon.isEmpty()) log.warn(`tray icon not found or not an image: ${file}`); // A `…Template.png` is a monochrome icon macOS tints for the menu bar. if (/Template(@\dx)?\.png$/i.test(tray.icon)) icon.setTemplateImage(true); const t = new Tray(icon); if (tray.tooltip) t.setToolTip(tray.tooltip); const menu = tray.menu ? Menu.buildFromTemplate(translate(tray.menu, windows.send, menuActions)) : null; const click = tray.click ?? (menu && !state.cfg.window ? 'menu' : 'window'); t.on('click', () => { if (click === 'menu') { if (menu) t.popUpContextMenu(menu); } else if (click === 'window') toggleMain(); else windows.send(click); }); t.on('right-click', () => { if (menu) t.popUpContextMenu(menu); }); return t; } function setPermissions (extra) { const allowed = new Set(['fullscreen', 'clipboard-sanitized-write', 'clipboard-read', ...extra]); session.defaultSession.setPermissionRequestHandler((wc, permission, cb) => cb(allowed.has(permission))); session.defaultSession.setPermissionCheckHandler((wc, permission) => allowed.has(permission)); } // The rest of network: "loopback" (the switches are set at the top): IP // literals and anything else that skipped the resolver go to a proxy with // nobody listening. Loopback bypasses it. async function lockToLoopback () { await session.defaultSession.setProxy({ proxyRules: 'http=127.0.0.1:1;https=127.0.0.1:1;ftp=127.0.0.1:1;socks=127.0.0.1:1', proxyBypassRules: ';localhost;*.localhost;127.0.0.1;[::1]', }); } // Where the bridge's fs calls may go: the configured roots (the home directory // by default), plus the app's own user data and the temp directory. function roots (cfg, vars) { return [...(cfg.roots ?? ['~']).map((r) => expandHome(r)), vars.userData, tmpdir()]; } // ── files and URLs from the OS ─────────────────────────────────────────────── function openables (argv) { const out = []; for (const arg of argv.slice(1)) { if (arg.startsWith('-')) continue; if (config.urlSchemes.some((s) => arg.toLowerCase().startsWith(`${s.toLowerCase()}:`))) out.push(['open-url', arg]); else if (existsSync(arg) && statSync(arg).isFile()) out.push(['open-file', resolve(arg)]); } return out; } function takeOpen (kind, target) { // The page may read what the OS handed it, wherever it is. if (kind === 'open-file') state.bridge?.grants.add(target); if (state.mainLoaded) { state.windows.send(kind, target); showMain(); } else pending.push([kind, target]); } // ── dev ────────────────────────────────────────────────────────────────────── // Changes to the sidecar's files restart it; changes to the page's files // reload the windows. `dev.restart` and `dev.reload` override the guesses. function watchForChanges () { const { cfg, target, log, windows } = state; const dirOf = (p) => { const d = dirname(p.replace(/\\/g, '/')); return d === '.' ? '**' : `${d}/**`; }; const restart = compile(cfg.dev.restart ?? (cfg.sidecar?.node && !state.attached ? [dirOf(cfg.sidecar.args[0])] : [])); const reload = compile(cfg.dev.reload ?? (target?.kind === 'app' ? [dirOf(target.path)] : [])); const changed = new Set(); let timer = null; let busy = false; const apply = async () => { if (busy) { timer = setTimeout(apply, 250); return; } const files = [...changed]; changed.clear(); busy = true; try { if (cfg.sidecar && !state.attached && files.some(restart)) { log.info(`restarting the sidecar (${files.find(restart)} changed)`); await restartSidecar(); windows.reload(); } else if (files.some(reload)) { log.info(`reloading (${files.find(reload)} changed)`); windows.reload(); } } finally { busy = false; } }; try { watch(appDir, { recursive: true }, (ev, file) => { if (!file || /(^|[\\/])(node_modules|\.git|dist)([\\/]|$)/.test(file)) return; changed.add(file.replace(/\\/g, '/')); clearTimeout(timer); timer = setTimeout(apply, 250); }); } catch (err) { log.warn(`not watching for changes: ${err.message}`); } } // MOLLUSC_SMOKE=1: load the window, report its title, exit. Exit code 1 when // the page put "error" in its title, so a page can fail the run. // MOLLUSC_SMOKE_WAIT sets how long the page gets after loading (ms), and // MOLLUSC_SMOKE_SCRIPT names a module whose default export is then called with // { win, app, Menu, tray, env } to drive the app (menus, keys, the tray); what // it returns is reported, and a throw fails the run. function runSmoke () { const finish = (msg, code) => { state.sidecar?.kill(); for (const s of state.serves) s.kill(); // stdout is a pipe here, and pipe writes are asynchronous on macOS. process.stdout.write(`smoke: ${msg}\n`, () => app.exit(code)); }; const wait = Number(process.env.MOLLUSC_SMOKE_WAIT || 1500); const timer = setTimeout(() => finish('timed out waiting for the window', 1), 20000 + wait); const win = state.main; if (!win) { clearTimeout(timer); finish('no window to show', 0); return; } win.webContents.once('did-finish-load', async () => { // Give the page a moment to talk to the sidecar through the bridge. await new Promise((res) => setTimeout(res, wait)); let report = ''; if (process.env.MOLLUSC_SMOKE_SCRIPT) { try { const script = await import(pathToFileURL(resolve(process.env.MOLLUSC_SMOKE_SCRIPT)).href); const out = await script.default({ win, app, Menu, tray: state.tray, env: state.vars }); report = out === undefined ? '' : `, script: ${typeof out === 'string' ? out : JSON.stringify(out)}`; } catch (err) { clearTimeout(timer); finish(`script failed: ${err.stack || err.message}`, 1); return; } } const title = win.isDestroyed() ? '(window closed)' : await win.webContents.executeJavaScript('document.title').catch((err) => `error: ${err.message}`); clearTimeout(timer); finish(`title "${title}"${report}`, /error/i.test(title) ? 1 : 0); }); }