// The main-process side of the bridge: one IPC channel per allowed `api` // entry, each validating its arguments before touching anything. Calls are // only honoured from the main frame of a privileged window. import { randomUUID } from 'node:crypto'; import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { BrowserWindow, Notification, app, dialog, ipcMain, shell } from 'electron'; import { allowedPath, expandHome } from './paths.js'; import { pick } from './windows.js'; const OPEN_KEYS = ['title', 'defaultPath', 'buttonLabel', 'filters', 'message']; const OPEN_PROPERTIES = ['openFile', 'openDirectory', 'multiSelections', 'createDirectory', 'showHiddenFiles', 'treatPackageAsDirectory']; const SAVE_KEYS = ['title', 'defaultPath', 'buttonLabel', 'filters', 'message', 'nameFieldLabel', 'showsTagField']; const SAVE_PROPERTIES = ['createDirectory', 'showHiddenFiles', 'showOverwriteConfirmation', 'treatPackageAsDirectory']; const MESSAGE_KEYS = ['type', 'buttons', 'defaultId', 'cancelId', 'title', 'message', 'detail', 'checkboxLabel', 'checkboxChecked', 'noLink']; const OPEN_WINDOW_KEYS = ['width', 'height', 'minWidth', 'minHeight', 'title', 'titleBarStyle', 'backgroundColor', 'resizable', 'frame', 'alwaysOnTop']; const kind = (s) => (s.isDirectory() ? 'dir' : s.isFile() ? 'file' : 'other'); function dialogOptions (opts, keys, properties) { if (!opts || typeof opts !== 'object') throw new TypeError('options must be an object'); const out = pick(opts, keys); if (out.defaultPath != null) out.defaultPath = expandHome(String(out.defaultPath)); if (out.filters != null) { if (!Array.isArray(out.filters) || out.filters.some((f) => !f || typeof f.name !== 'string' || !Array.isArray(f.extensions))) throw new TypeError('filters must be [{ name, extensions }]'); out.filters = out.filters.map((f) => ({ name: f.name, extensions: f.extensions.map(String) })); } if (Array.isArray(opts.properties)) out.properties = opts.properties.filter((p) => properties.includes(p)); return out; } // A notification's options from the page: text, and buttons as { id, title }. function notificationOptions (opts) { if (!opts || typeof opts !== 'object') throw new TypeError('options must be an object'); if (typeof opts.title !== 'string' || !opts.title) throw new TypeError('a title is required'); const actions = opts.actions ?? []; if (!Array.isArray(actions) || actions.length > 5 || actions.some((a) => typeof a?.id !== 'string' || typeof a?.title !== 'string')) { throw new TypeError('actions must be up to five { id, title }'); } const text = (v) => (v == null ? undefined : String(v)); return { id: text(opts.id) ?? randomUUID(), actions, options: { title: opts.title, body: text(opts.body), subtitle: text(opts.subtitle), silent: !!opts.silent, closeButtonText: text(opts.closeButtonText), actions: actions.map((a) => ({ type: 'button', text: a.title })), }, }; } export function installBridge ({ api, roots, windows, info, log }) { // Shown notifications, kept so they are not collected while they can still // be clicked: a collected one stops reporting. const notifications = new Map(); const grants = new Set(); const guard = (p) => allowedPath(p, { roots, grants: [...grants] }); const grant = (paths) => { for (const p of paths) grants.add(p); return paths; }; const windowOf = (event) => BrowserWindow.fromWebContents(event.sender); // A popover hides when it loses focus, which a dialog of its own would make // it do; it asks here whether one is up. let dialogs = 0; const inDialog = async (fn) => { dialogs++; try { return await fn(); } finally { dialogs--; } }; const handlers = { 'fs.read': async (e, p, opts = {}) => { const file = guard(p); return opts?.encoding === 'binary' ? readFile(file) : readFile(file, 'utf8'); }, 'fs.write': async (e, p, data) => { const file = guard(p); if (typeof data !== 'string' && !ArrayBuffer.isView(data) && !(data instanceof ArrayBuffer)) throw new TypeError('data must be a string or bytes'); await writeFile(file, data instanceof ArrayBuffer ? Buffer.from(data) : data); }, 'fs.list': async (e, p) => { const dir = guard(p); const entries = await readdir(dir, { withFileTypes: true }); return Promise.all(entries.map(async (d) => { const s = await stat(join(dir, d.name)).catch(() => null); return { name: d.name, type: s ? kind(s) : 'other', size: s?.size ?? 0, mtime: s?.mtimeMs ?? 0 }; })); }, 'fs.stat': async (e, p) => { const s = await stat(guard(p)).catch(() => null); return s && { type: kind(s), size: s.size, mtime: s.mtimeMs }; }, 'fs.mkdir': async (e, p) => { await mkdir(guard(p), { recursive: true }); }, 'fs.trash': (e, p) => shell.trashItem(guard(p)), 'dialog.open': async (e, opts = {}) => { const res = await inDialog(() => dialog.showOpenDialog(windowOf(e), dialogOptions(opts, OPEN_KEYS, OPEN_PROPERTIES))); return res.canceled ? null : grant(res.filePaths); }, 'dialog.save': async (e, opts = {}) => { const res = await inDialog(() => dialog.showSaveDialog(windowOf(e), dialogOptions(opts, SAVE_KEYS, SAVE_PROPERTIES))); return res.canceled || !res.filePath ? null : grant([res.filePath])[0]; }, 'dialog.message': async (e, opts = {}) => { const res = await inDialog(() => dialog.showMessageBox(windowOf(e), dialogOptions(opts, MESSAGE_KEYS, []))); return { response: res.response, checkboxChecked: res.checkboxChecked }; }, 'shell.openExternal': async (e, url) => { if (typeof url !== 'string' || !/^(https?|mailto):/i.test(url)) throw new Error('Only http, https and mailto links can be opened'); await shell.openExternal(url); }, 'shell.showInFolder': (e, p) => shell.showItemInFolder(guard(p)), // A system notification; its buttons and a click on it come back to the // page as notification-action { id, action } and notification-click { id }. 'notification.show': (e, opts) => { if (!Notification.isSupported()) return null; const { id, actions, options } = notificationOptions(opts); const sender = e.sender; const tell = (name, payload) => { if (!sender.isDestroyed()) sender.send('mollusc:event', name, payload); }; const n = new Notification(options); n.on('action', (ev, index) => tell('notification-action', { id, action: actions[index]?.id ?? null })); n.on('click', () => { const win = BrowserWindow.fromWebContents(sender); if (win) { win.show(); win.focus(); } tell('notification-click', { id }); }); n.on('close', () => notifications.delete(id)); notifications.get(id)?.close(); notifications.set(id, n); n.show(); return id; }, 'window.close': (e) => windows.close(e.sender), 'window.hide': (e) => windowOf(e)?.hide(), 'app.info': () => info(), // A short text on the Dock icon (macOS) or a count on the launcher (Linux); '' clears it. 'app.setBadge': (e, text) => { const value = text == null ? '' : String(text).slice(0, 16); if (app.dock) app.dock.setBadge(value); else if (/^\d*$/.test(value)) app.setBadgeCount(Number(value || 0)); }, 'app.quit': () => app.quit(), }; function assertPrivileged (event) { if (!windows.isPrivileged(event.sender) || event.senderFrame?.parent) throw new Error('Not allowed from this window'); } for (const name of api) { ipcMain.handle(`mollusc:${name}`, async (event, ...args) => { assertPrivileged(event); try { return await handlers[name](event, ...args); } catch (err) { log.warn(`${name}: ${err.message}`); throw err; } }); } ipcMain.handle('mollusc:openWindow', (event, url, opts) => { assertPrivileged(event); if (typeof url !== 'string') throw new TypeError('url must be a string'); const options = opts && typeof opts === 'object' ? pick(opts, OPEN_WINDOW_KEYS) : {}; return windows.open(url, { ...options, privileged: !!opts?.privileged }).id; }); // From the preload, not the page: a listener for close-requested, and the // path of a file the user dropped (the preload works it out from the File // itself, so a page cannot name one it was not given). ipcMain.handle('mollusc:guardClose', (event, on) => { assertPrivileged(event); windows.guard(event.sender, !!on); }); ipcMain.handle('mollusc:grantDropped', (event, p) => { assertPrivileged(event); if (typeof p !== 'string' || !p) throw new TypeError('A path is required'); grant([p]); }); return { grants, inDialog: () => dialogs > 0 }; }