A reusable desktop shell: your sidecar, your index, safe APIs, installers for every platform
README.md

mollusc #

A desktop shell you build once and reuse for every web-technology app.

Give it a sidecar (your server), an index.html or a localhost URL, a list of the native APIs the page may call, and it gives you a native window with menus, file-type and URL-scheme registration, windows with and without privileges, a development loop, and one command that produces installers for macOS, Windows and Linux. The apps themselves contain no runtime at all: a config file plus their own code.

The motivation is a shelf of local apps (kavu, meow-meow, madam) that are all "a Node server plus a browser UI" and would each otherwise drag their own copy of Electron or a Rust toolchain along. See DESIGN.md for the recommended path and the trade-offs behind it.

Status: the shell, dev, build (macOS verified; Windows and Linux go through the same electron-builder configuration) and doctor work. Signing and notarisation are wired up but not yet exercised with real credentials. kavu, meow-meow, blastile, akashic, madam, and portent's natural and stan run on it; their mollusc.json files show most of what follows in use.

Install #

git clone https://tangled.org/robin.berjon.com/mollusc
cd mollusc && npm install && npm link    # one Electron, one electron-builder, shared by every app
mollusc doctor

Commands #

mollusc dev ./kavu                 # start the sidecar, open the window, reload on change
mollusc build ./kavu               # installers for this platform, in ./kavu/dist
mollusc build ./kavu --mac --win --linux
mollusc build ./kavu --mac --sign  # signed, and notarised when credentials are set (see below)
mollusc doctor                     # Electron, caches, signing identities, platform tools

--sign signs with the Developer ID identity in the keychain (CSC_NAME picks one), and notarises with whichever credentials electron-builder finds: APPLE_ID, APPLE_APP_SPECIFIC_PASSWORD and APPLE_TEAM_ID; or APPLE_API_KEY (the .p8 file), APPLE_API_KEY_ID and APPLE_API_ISSUER; or APPLE_KEYCHAIN_PROFILE.

Linux and Windows bundles can be made on a Mac; macOS bundles need a Mac. The host platform packs the Electron this install already has; other platforms are fetched once into the shared Electron cache.

The app #

An app is a directory with a mollusc.json. Everything else is the app's own. examples/hello is the smallest one: a Node sidecar and a page served from app://. Run it with mollusc dev examples/hello.

{
  "id": "com.berjon.kavu",
  "name": "kavu",
  "version": "0.1.0",
  "icon": "icons/kavu.png",

  "sidecar": {
    "node": true,
    "args": ["server/main.js"],
    "env": { "KAVU_PORT": "${port}" },
    "ready": "http://127.0.0.1:${port}/api/status"
  },

  "window": {
    "url": "http://127.0.0.1:${port}/",
    "width": 1440, "height": 900, "minWidth": 900, "minHeight": 600,
    "titleBarStyle": "hiddenInset"
  },

  "api": ["fs.read", "fs.write", "dialog.open", "dialog.save", "shell.openExternal", "app.quit"],

  "menu": [
    { "label": "File", "items": [
      { "label": "Open…", "accelerator": "CmdOrCtrl+O", "send": "menu:open" },
      { "label": "Save", "accelerator": "CmdOrCtrl+S", "send": "menu:save" },
      { "role": "close" }
    ] },
    { "role": "editMenu" }, { "role": "viewMenu" }, { "role": "windowMenu" }
  ],

  "fileTypes": [{ "ext": ["svg"], "name": "SVG image", "role": "Editor" }],
  "urlSchemes": ["kavu"],

  "build": {
    "files": ["server/**", "web/**", "package.json"],
    "productName": "Kavu",
    "mac": { "category": "public.app-category.graphics-design" }
  }
}

Any string may use ${port} (the sidecar's port), ${token} (a secret made fresh at each launch, shared by the sidecar and the page), ${appDir}, ${userData} and ${home}.

  • sidecar (optional). With node: true, args[0] is a script run on Electron's own Node, so nothing extra ships; otherwise command is spawned with args (a command with a slash in it, like bin/server, is a path in the app). env is added to the environment, along with MOLLUSC_PORT, MOLLUSC_TOKEN, MOLLUSC_APP and MOLLUSC_USER_DATA; a built app also gets the PATH of the user's login shell, since the Finder gives it a bare one. The shell waits for ready to answer (readyTimeout, default 30 s) before opening a window. The sidecar is killed when the last window closes unless keepAlive is true (macOS only; elsewhere the app quits). Its stdout and stderr go to <userData>/logs/sidecar.log and, in dev, to the terminal. The sidecar trusts the certificates the machine trusts (NODE_USE_SYSTEM_CA=1 is set for it; an env of its own may override), so a box on the LAN behind a locally issued certificate the keychain knows is reachable from it.

    • The port is the one used last time when it is free, so the page keeps its origin, and with it localStorage, from one launch to the next. port fixes it instead (an error if something else holds it); with attach, a server of the app's own already answering ready on that port is used rather than starting another (for apps a CLI or an extension also talks to).
    • A sidecar that does anything a web page should not be able to ask for should require the token: anything in the user's browser can reach 127.0.0.1.
  • window (optional). url is a localhost URL, or a path relative to the app directory, served from app://<id>/ so that fetch, modules and CORS behave as on the web. The other keys are the usual BrowserWindow ones (width, height, minWidth, titleBarStyle, frame, show, …, and maximized to open maximised). The window comes back where it was: its last size, position, screen and state are kept in the app's user data and restored at the next launch when that screen is still there (width and height are for the first launch); "remember": false turns that off; backgroundColor may be { "light": "#fff", "dark": "#000" }. No window plus a tray makes a menu bar app, hidden from the Dock; popover: true with a tray makes the window a popover under the tray icon, toggled by it and hidden when it loses focus.

  • api is the allowlist for the bridge (below). An empty list means a window with no bridge at all.

  • menu is Electron's menu template; items is accepted for submenu, send names an event the page receives, with the item's data in the payload ({ label, checked, data }), and "action": "showWindow" brings the window up (for a tray menu, when the page is hidden). Roles cover the platform menus; on macOS the app menu is added first if missing.

  • fileTypes ({ ext, name, description, role, rank, mimeType, icon }; "rank": "Alternate" opens a type without claiming to be its default app) and urlSchemes are written into the installers. What the OS opens arrives as open-file and open-url events, including what the app was launched with.

  • tray: { "icon": "icons/trayTemplate.png", "tooltip": "…", "menu": [...], "click": "menu" | "window" | "<event name>" }.

  • roots: directories the bridge's fs calls may touch, ["~"] by default; the app's user data and the temp directory are always allowed, as is anything the user picked in a dialog.

  • permissions: web permissions to grant beyond fullscreen and the clipboard ("media", "notifications", …). Everything else is denied.

  • network: "loopback" confines every window to loopback. No name but localhost, *.localhost and 127.0.0.1 resolves; anything that still has an address goes to a proxy that is not there; and WebRTC may not send UDP except through that proxy, so there is no ICE either (Chromium's disable_non_proxied_udp policy, by switch and per window). The sidecar does the app's networking. For apps that render untrusted content, web tiles say; it is what Delta Chat does for webxdc. Default "any".

  • build: before, commands run in the app directory first ("npx vite build", or ["deno", "compile", …]); output, where installers go (dist by default; out when a bundler builds the page into dist); files globs to ship (default: everything but node_modules, dist and test; with a node sidecar, its production dependencies are added from npm ls unless node_modules is listed or modules is false); productName; and mac, win, linux, dmg, nsis objects passed to electron-builder.

  • dev applies when running from source. sidecar and window are laid over the top-level ones (deno run main.ts in dev, a compiled binary once built; a Vite server in dev, dist/index.html once built). serve lists processes to run alongside, like a bundler in watch mode or a dev server ({ "command", "args", "env", "ready" }, waited for when ready is set); before lists commands run to completion first, like a first build of the bundle those watchers then keep up to date. restart and reload are globs for the dev loop; by default a change under the sidecar script's directory restarts it, and a change under the page's directory reloads the windows.

    On macOS, mollusc dev does not run the stock Electron binary. macOS names an app in the menu bar, the Dock and the app switcher after the bundle its executable lives in, and nothing a running process does changes that, so every app in dev would be "Electron" with Electron's icon. Dev runs a copy of Electron.app that carries the app's own build.productName (or name), the bundle identifier <id>.dev, and its icon when that is a PNG. The copy is a copy-on-write clone, so it is made in a moment and takes no disk of its own on APFS, though tools that add up file sizes count it in full. It is kept in ~/Library/Caches/mollusc/dev/<id>/, one per app, signed ad hoc, and remade when the Electron version, the name or the icon changes; deleting that directory is always safe. MOLLUSC_STOCK_ELECTRON=1 runs the stock binary instead, and so does any failure to make the copy. Other platforms take the name from app.setName and are unchanged.

The bridge #

Pages in privileged windows get window.mollusc:

  • the api entries, grouped by namespace: mollusc.fs.read(path, { encoding }), fs.write(path, data), fs.list(dir), fs.stat(path), fs.mkdir(dir), fs.trash(path); dialog.open(options), dialog.save(options), dialog.message(options); shell.openExternal(url), shell.showInFolder(path); window.close(), window.hide(); notification.show({ id, title, body, subtitle, silent, actions: [{ id, title }] }), whose buttons and clicks come back as notification-action { id, action } and notification-click { id } (a click also brings the window forward); app.info(), app.setBadge(text), app.quit(). All return promises and are validated in the main process: paths are resolved and checked against roots, dialogs belong to the window that asked.
  • mollusc.on(name, fn) for menu events, open-file, open-url, sidecar-exit, window-show, window-hide, window-focus, window-blur, notification-action, notification-click, and close-requested; returns an unsubscribe function. Listening for close-requested makes the shell ask before the window closes (or the app quits): the page checks for unsaved work and calls mollusc.window.close() to go ahead.
  • mollusc.pathForFile(file) (with any fs api): the path of a File the user dropped or picked, which the fs calls may then reach.
  • mollusc.openWindow(url, { privileged: false, width, height, … }). An unprivileged window has no preload at all and may show anything. privileged: true is only honoured for the app's own origins.
  • mollusc.env: name, version, platform, port, token, sidecarOrigin, appOrigin.

Menu items with an accelerator and a send event pair well with the page's own keyboard handling: on macOS a page that handles the key and calls preventDefault() keeps it, and the menu item only fires when clicked or when the page lets the key through.

<app> --hidden starts without showing the window (for login items); <app> --quit stops the running instance; in dev, mollusc dev <app> --hidden passes them on. The sidecar's MOLLUSC_LAUNCH is how to start the app again, as a JSON argv (the built binary, or Electron on the shell and the app in dev), for an app that registers itself as a login item.

Every window is sandboxed and context-isolated with no Node integration. Navigation away from the app's origins is blocked and goes to the system browser instead. Anything the shell does not offer belongs in the sidecar.

What a build contains #

build stages <app>/dist/.mollusc/stage: the shell and a generated package.json go into the asar; the app's files and production node_modules ship unpacked as Resources/mollusc-app, which is what the sidecar runs. Output lands in <app>/dist (or build.output). Installers are around 110 MB (zip and dmg on macOS).

Development #

npm test            # unit tests: config, globs, menus, paths, ports, builder
npm run smoke       # opens examples/hello, checks the bridge round trip, exits

MOLLUSC_SMOKE=1 makes any app load its window, print the page title, and exit; a title containing "error" fails the run. MOLLUSC_SMOKE_WAIT (ms) gives the page longer, and MOLLUSC_SMOKE_SCRIPT=drive.mjs runs a module whose default export gets { win, app, Menu, tray, env } to drive the app. Logs live under the app's user data directory (~/Library/Application Support/<name>/logs on macOS).