Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add QM desktop app with browser sign-in handoff (#1528)

Regan Bellcef8de05c592
diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.yml
index 69db0d181..1d0f2c8f0 100644
--- a/.github/workflows/cicd.yml
+++ b/.github/workflows/cicd.yml
@@ -25,6 +25,10 @@ jobs:
run: |
npm ci
npm run typecheck
+ - name: Desktop sign-in tests
+ run: |
+ npm ci --prefix desktop --ignore-scripts
+ npm test --prefix desktop
core-tests:
name: Core tests (${{ matrix.shard }}/5)
@@ -141,6 +145,7 @@ jobs:
run: |
npm ci
npm ci --prefix plugins/web-ui
+ npm ci --prefix desktop --ignore-scripts
- name: Formatting
run: npm run format:check
- name: Lint whole repo, incl. plugins
diff --git a/desktop/.gitignore b/desktop/.gitignore
new file mode 100644
index 000000000..849ddff3b
--- /dev/null
+++ b/desktop/.gitignore
@@ -0,0 +1 @@
+dist/
diff --git a/desktop/README.md b/desktop/README.md
new file mode 100644
index 000000000..c8d1c4384
--- /dev/null
+++ b/desktop/README.md
@@ -0,0 +1,28 @@
+# QM desktop
+
+An Electron client for an existing QM web deployment. The welcome screen connects to your workspace; the app then runs the same web UI with its own persistent session.
+
+```sh
+cd desktop
+npm ci
+npm start
+```
+
+Enter your QM web URL on first launch. HTTPS is required except for localhost development. Change instances with **QM → Change Instance…** (`Cmd+,` on macOS). You can also set `QM_DESKTOP_URL` when starting the app.
+
+```sh
+QM_DESKTOP_URL=http://localhost:3000 npm start
+npm run package
+```
+
+Packaging writes a native app for the current platform into `desktop/dist/`, registering the `qm-desktop` URL scheme. Use the packaged app for browser sign-in. The macOS build is an unsigned local prototype, with no automatic updates. It connects to a running server; it does not bundle the QM backend or provide offline agent execution.
+
+## Browser sign-in
+
+When sign-in is needed, the app opens `/auth/desktop` in your default browser. Sign in there as usual, confirm your account, and choose **Open QM Desktop**. The browser returns a two-minute, single-use code bound to the app's proof key and random state. The app redeems it over the instance connection and stores the session in its isolated persistent cookie partition. Closing the app or starting another connection cancels unfinished sign-in requests; it does not sign out sessions whose cookie exchange already completed. The portal must include the desktop sign-in routes; older deployments need an update.
+
+The portal preserves the browser session's identity, original authentication time, and expiration. Redemption uses the existing durable core claim store to prevent replay across portal instances and deployments. The desktop proof key exists only for the disposable, in-progress sign-in attempt and is never sent to the browser. Passwords and identity-provider cookies stay in your browser.
+
+Remote content is sandboxed with no Node.js or preload access. Off-origin links open in your browser. Microphone, camera, and notification permissions are disabled in this prototype.
+
+The welcome screen uses _Becalmed off Halfway Rock_ (Fitz Henry Lane, 1860), sourced from [Ève Bouffard’s QM brand board](https://www.evebouffard.com/qm-brand). [National Gallery of Art collection record](https://www.nga.gov/artworks/76213-becalmed-halfway-rock).
diff --git a/desktop/assets/becalmed-off-halfway-rock.webp b/desktop/assets/becalmed-off-halfway-rock.webp
new file mode 100644
index 000000000..ef392c914
Binary files /dev/null and b/desktop/assets/becalmed-off-halfway-rock.webp differ
diff --git a/desktop/login.mjs b/desktop/login.mjs
new file mode 100644
index 000000000..5bb6c541a
--- /dev/null
+++ b/desktop/login.mjs
@@ -0,0 +1,36 @@
+import { createHash, randomBytes } from "node:crypto";
+
+export function createLogin(instance, now = Date.now()) {
+ const verifier = randomBytes(32).toString("base64url");
+ const state = randomBytes(32).toString("base64url");
+ const url = new URL("/auth/desktop", instance);
+ url.searchParams.set("challenge", createHash("sha256").update(verifier).digest("base64url"));
+ url.searchParams.set("state", state);
+ return { verifier, state, url: url.href, instance, expiresAt: now + 10 * 60_000 };
+}
+
+export function loginCallback(value, pending, now = Date.now()) {
+ if (!pending || now >= pending.expiresAt || typeof value !== "string" || value.length > 12288) return null;
+ try {
+ const url = new URL(value);
+ const code = url.searchParams.get("code");
+ if (
+ url.protocol !== "qm-desktop:" ||
+ url.hostname !== "auth" ||
+ url.pathname !== "/callback" ||
+ url.username ||
+ url.password ||
+ url.port ||
+ url.hash ||
+ url.searchParams.getAll("state").length !== 1 ||
+ url.searchParams.getAll("code").length !== 1 ||
+ url.searchParams.get("state") !== pending.state ||
+ !code ||
+ code.length > 8192
+ )
+ return null;
+ return code;
+ } catch {
+ return null;
+ }
+}
diff --git a/desktop/main.mjs b/desktop/main.mjs
new file mode 100644
index 000000000..c69c781ef
--- /dev/null
+++ b/desktop/main.mjs
@@ -0,0 +1,280 @@
+import { app, BrowserWindow, dialog, ipcMain, Menu, shell, session as electronSession } from "electron";
+import { readFile, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { createLogin, loginCallback } from "./login.mjs";
+import { instanceUrl, externalUrl, browserLoginUrl } from "./url.mjs";
+
+const directory = path.dirname(fileURLToPath(import.meta.url));
+const setupUrl = pathToFileURL(path.join(directory, "setup.html")).href;
+let mainWindow;
+let setupWindow;
+let target;
+let pendingLogin;
+let loginStatus = "";
+
+app.setName("QM");
+app.on("open-url", (event, url) => {
+ event.preventDefault();
+ void finishBrowserSignIn(url);
+});
+if (!app.requestSingleInstanceLock()) app.quit();
+else {
+ app.on("second-instance", (_event, argv) => {
+ const callback = argv.find((arg) => arg.startsWith("qm-desktop:"));
+ if (callback) void finishBrowserSignIn(callback);
+ const window = setupWindow ?? mainWindow;
+ if (window?.isMinimized()) window.restore();
+ window?.show();
+ });
+ app
+ .whenReady()
+ .then(start)
+ .catch((error) => {
+ dialog.showErrorBox("QM could not start", error.message);
+ app.quit();
+ });
+}
+
+function openExternal(url) {
+ if (externalUrl(url)) {
+ shell.openExternal(url).catch((error) => dialog.showErrorBox("Could not open link", error.message));
+ }
+}
+
+function showSetup() {
+ if (setupWindow) return setupWindow.show();
+ setupWindow = new BrowserWindow({
+ title: "Welcome to QM",
+ width: 1040,
+ height: 760,
+ minWidth: 700,
+ minHeight: 650,
+ titleBarStyle: "hiddenInset",
+ backgroundColor: "#f7f6f2",
+ webPreferences: {
+ preload: path.join(directory, "preload.cjs"),
+ nodeIntegration: false,
+ contextIsolation: true,
+ sandbox: true,
+ },
+ });
+ setupWindow.webContents.on("will-navigate", (event) => event.preventDefault());
+ setupWindow.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
+ setupWindow.on("closed", () => {
+ setupWindow = undefined;
+ if (pendingLogin) mainWindow?.destroy();
+ });
+ setupWindow.loadURL(setupUrl);
+}
+
+function instanceSession(url) {
+ return electronSession.fromPartition(`persist:qm-${new URL(url).origin}`);
+}
+
+async function beginBrowserSignIn(url) {
+ pendingLogin?.controller.abort();
+ const attempt = { ...createLogin(url), controller: new AbortController() };
+ pendingLogin = attempt;
+ loginStatus = "Finish signing in in your browser. This window will open your workspace when you're done.";
+ mainWindow?.hide();
+ showSetup();
+ setupWindow.webContents.send("qm:login-status", loginStatus);
+ try {
+ await shell.openExternal(attempt.url);
+ } catch {
+ if (pendingLogin !== attempt) return;
+ pendingLogin = undefined;
+ loginStatus = "Could not open your browser. Try connecting again.";
+ setupWindow?.webContents.send("qm:login-status", loginStatus);
+ }
+}
+
+async function finishBrowserSignIn(url) {
+ if (pendingLogin?.redeeming) return;
+ const code = loginCallback(url, pendingLogin);
+ if (!code) return;
+ const attempt = pendingLogin;
+ attempt.redeeming = true;
+ try {
+ const response = await instanceSession(attempt.instance).fetch(
+ new URL("/auth/desktop/redeem", attempt.instance).href,
+ {
+ method: "POST",
+ redirect: "error",
+ credentials: "include",
+ headers: { "content-type": "application/x-www-form-urlencoded", origin: new URL(attempt.instance).origin },
+ body: new URLSearchParams({ code, verifier: attempt.verifier, state: attempt.state }).toString(),
+ signal: AbortSignal.any([attempt.controller.signal, AbortSignal.timeout(15_000)]),
+ },
+ );
+ if (pendingLogin !== attempt) return;
+ if (!response.ok) throw new Error("Sign-in could not be completed. Please connect again to get a fresh link.");
+ await instanceSession(attempt.instance).cookies.flushStore();
+ if (pendingLogin !== attempt) return;
+ pendingLogin = undefined;
+ loginStatus = "";
+ void showInstance(attempt.instance);
+ setupWindow?.close();
+ } catch {
+ if (pendingLogin !== attempt) return;
+ pendingLogin = undefined;
+ loginStatus = "Sign-in could not be completed. Please connect again to get a fresh link.";
+ showSetup();
+ setupWindow.webContents.send("qm:login-status", loginStatus);
+ }
+}
+
+async function showInstance(url) {
+ pendingLogin?.controller.abort();
+ pendingLogin = undefined;
+ if (browserLoginUrl(url, new URL(url).origin)) url = new URL("/", url).href;
+ if (mainWindow) mainWindow.destroy();
+ const window = new BrowserWindow({
+ title: "QM",
+ width: 1440,
+ height: 960,
+ minWidth: 800,
+ minHeight: 600,
+ backgroundColor: "#f5f4f0",
+ webPreferences: {
+ session: instanceSession(url),
+ nodeIntegration: false,
+ contextIsolation: true,
+ sandbox: true,
+ },
+ });
+ mainWindow = window;
+ const origin = new URL(url).origin;
+ const session = window.webContents.session;
+ session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
+ session.setPermissionCheckHandler(() => false);
+ let handedOff = false;
+ const navigate = (event, destination) => {
+ if (event.isMainFrame === false) return;
+ const destinationUrl = new URL(destination);
+ if (browserLoginUrl(destination, origin)) {
+ event.preventDefault();
+ handedOff = true;
+ void beginBrowserSignIn(url);
+ } else if (destinationUrl.origin !== origin) {
+ event.preventDefault();
+ handedOff = true;
+ openExternal(destination);
+ }
+ };
+ window.webContents.on("will-navigate", navigate);
+ window.webContents.on("will-redirect", navigate);
+ window.webContents.on("will-attach-webview", (event) => event.preventDefault());
+ window.webContents.setWindowOpenHandler(({ url: destination }) => {
+ if (browserLoginUrl(destination, origin)) {
+ handedOff = true;
+ void beginBrowserSignIn(url);
+ } else if (new URL(destination).origin === origin) {
+ window.loadURL(destination).catch((error) => {
+ if (error.code !== "ERR_ABORTED") dialog.showErrorBox("Could not open page", error.message);
+ });
+ } else openExternal(destination);
+ return { action: "deny" };
+ });
+ window.on("closed", () => {
+ if (mainWindow === window) mainWindow = undefined;
+ });
+ try {
+ await window.loadURL(url);
+ } catch (error) {
+ if (window.isDestroyed() || handedOff || error.code === "ERR_ABORTED") return;
+ await dialog.showMessageBox(window, {
+ type: "error",
+ message: "Could not connect to QM",
+ detail:
+ "Check that your instance is running and the URL is correct. You can retry with View → Reload or change the URL with QM → Change Instance.",
+ });
+ showSetup();
+ }
+}
+
+async function start() {
+ app.setAsDefaultProtocolClient("qm-desktop");
+ const configPath = path.join(app.getPath("userData"), "instance.json");
+ try {
+ target = instanceUrl(JSON.parse(await readFile(configPath, "utf8")).url);
+ } catch (error) {
+ if (error.code !== "ENOENT") dialog.showErrorBox("QM settings could not be read", error.message);
+ }
+ if (process.env.QM_DESKTOP_URL) target = instanceUrl(process.env.QM_DESKTOP_URL);
+ const assertSetup = (event) => {
+ if (event.sender !== setupWindow?.webContents || event.senderFrame?.url !== setupUrl) {
+ throw new Error("Untrusted settings request");
+ }
+ };
+ ipcMain.handle("qm:current-instance", (event) => {
+ assertSetup(event);
+ return { url: target ?? "", status: loginStatus };
+ });
+ ipcMain.handle("qm:connect", async (event, value) => {
+ assertSetup(event);
+ try {
+ const url = instanceUrl(value);
+ await writeFile(configPath, JSON.stringify({ url }), { mode: 0o600 });
+ target = url;
+ void showInstance(url);
+ setupWindow.close();
+ return { ok: true };
+ } catch (error) {
+ return { error: error.message };
+ }
+ });
+ Menu.setApplicationMenu(
+ Menu.buildFromTemplate([
+ {
+ label: "QM",
+ submenu: [
+ { role: "about" },
+ { label: "Change Instance…", accelerator: "CmdOrCtrl+,", click: showSetup },
+ {
+ label: "Open in Browser",
+ click: () => {
+ if (target) openExternal(target);
+ },
+ },
+ { type: "separator" },
+ { role: "hide" },
+ { role: "hideOthers" },
+ { role: "unhide" },
+ { type: "separator" },
+ { role: "quit" },
+ ],
+ },
+ { role: "editMenu" },
+ {
+ label: "View",
+ submenu: [
+ { role: "reload" },
+ { role: "forceReload" },
+ { role: "toggleDevTools" },
+ { type: "separator" },
+ { role: "resetZoom" },
+ { role: "zoomIn" },
+ { role: "zoomOut" },
+ { type: "separator" },
+ { role: "togglefullscreen" },
+ ],
+ },
+ { role: "windowMenu" },
+ ]),
+ );
+ app.on("activate", () => {
+ if (setupWindow) setupWindow.show();
+ else if (pendingLogin) showSetup();
+ else if (mainWindow) mainWindow.show();
+ else if (target) void showInstance(target);
+ else showSetup();
+ });
+ if (target) await showInstance(target);
+ else showSetup();
+}
+
+app.on("window-all-closed", () => {
+ if (process.platform !== "darwin") app.quit();
+});
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
new file mode 100644
index 000000000..282a5a214
--- /dev/null
+++ b/desktop/package-lock.json
@@ -0,0 +1,720 @@
+{
+ "name": "qm-desktop",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "qm-desktop",
+ "version": "0.1.0",
+ "devDependencies": {
+ "@electron/packager": "20.3.0",
+ "electron": "44.4.3"
+ }
+ },
+ "node_modules/@electron-internal/extract-zip": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",
+ "integrity": "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/@electron/asar": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.3.0.tgz",
+ "integrity": "sha512-k/FFC/NQoTykGBi/Ga4L4KorsAKDdkK0LfNVG90eUG6vPVpJaL3iR9V1ZLbzBAF3QpojK5DcaGOdQOheKZv4JQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "glob": "^13.0.2",
+ "minimatch": "^10.0.1"
+ },
+ "bin": {
+ "asar": "bin/asar.mjs"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/@electron/get": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
+ "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.1.1",
+ "env-paths": "^3.0.0",
+ "graceful-fs": "^4.2.11",
+ "progress": "^2.0.3",
+ "semver": "^7.6.3",
+ "sumchecker": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ },
+ "optionalDependencies": {
+ "undici": "^7.24.4"
+ }
+ },
+ "node_modules/@electron/notarize": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-3.1.1.tgz",
+ "integrity": "sha512-uQQSlOiJnqRkTL1wlEBAxe90nVN/Fc/hEmk0bqpKk8nKjV1if/tXLHKUPePtv9Xsx90PtZU8aidx5lAiOpjkQQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "promise-retry": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 22.12.0"
+ }
+ },
+ "node_modules/@electron/osx-sign": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-2.7.0.tgz",
+ "integrity": "sha512-9DGhNqKMl6ibkhUoXbN7OHX2gZznfY10L3ZwG0u6r667Kfb6kec4JEfFTXftoqzmOfZ+OzwDbr4p/nKBMHnz0g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "debug": "^4.3.4",
+ "isbinaryfile": "^4.0.8",
+ "plist": "^3.0.5",
+ "semver": "^7.7.1"
+ },
+ "bin": {
+ "electron-osx-flat": "bin/electron-osx-flat.mjs",
+ "electron-osx-sign": "bin/electron-osx-sign.mjs"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/@electron/packager": {
+ "version": "20.3.0",
+ "resolved": "https://registry.npmjs.org/@electron/packager/-/packager-20.3.0.tgz",
+ "integrity": "sha512-3MvgJgy6YJ5ti0oGGBKrWKdYwpTaoRrhranMDgHSQ6i5t56yZV9IRDyoXTuqBp97LiKqnZeAMe2wTcF/9+fP5g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@electron-internal/extract-zip": "^1.0.1",
+ "@electron/asar": "^4.0.1",
+ "@electron/get": "^5.0.0",
+ "@electron/notarize": "^3.1.0",
+ "@electron/osx-sign": "^2.2.0",
+ "@electron/universal": "^3.0.1",
+ "@electron/windows-sign": "^2.0.2",
+ "@malept/cross-spawn-promise": "^2.0.0",
+ "debug": "^4.4.1",
+ "filenamify": "^6.0.0",
+ "galactus": "^2.0.2",
+ "graceful-fs": "^4.2.11",
+ "junk": "^4.0.1",
+ "plist": "^3.1.0",
+ "resedit": "^2.0.3",
+ "semver": "^7.7.2",
+ "yargs-parser": "^22.0.0"
+ },
+ "bin": {
+ "electron-packager": "bin/electron-packager.mjs"
+ },
+ "engines": {
+ "node": ">= 22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/electron/packager?sponsor=1"
+ }
+ },
+ "node_modules/@electron/universal": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-3.0.6.tgz",
+ "integrity": "sha512-MonS1kfkZdSEkLZI0pdR/TCx8ecxwRSFm7sORfwIkDI9UaIbHnk4Mgeqq+Ob9qDQRV8LZ9+hHCmimpA9BRcNxw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@electron/asar": "^4.0.0",
+ "debug": "^4.3.1",
+ "plist": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/@electron/windows-sign": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-2.1.0.tgz",
+ "integrity": "sha512-hyRE175pWNxU3R0k7B7Zwm4KpSgK/Ql+7yqUPRfnYc9K06uVPJDLvXH6oXpl/RAKbLu0Y114xuH6BdjDhF/pKA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "debug": "^4.3.4",
+ "graceful-fs": "^4.2.11",
+ "postject": "^1.0.0-alpha.6"
+ },
+ "bin": {
+ "electron-windows-sign": "bin/electron-windows-sign.mjs"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/@malept/cross-spawn-promise": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",
+ "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/malept"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
+ }
+ ],
+ "license": "Apache-2.0",
+ "dependencies": {
+ "cross-spawn": "^7.0.1"
+ },
+ "engines": {
+ "node": ">= 12.13.0"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "24.13.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.6.tgz",
+ "integrity": "sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.18.0"
+ }
+ },
+ "node_modules/@xmldom/xmldom": {
+ "version": "0.9.12",
+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
+ "integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.6"
+ }
+ },
+ "node_modules/balanced-match": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/brace-expansion": {
+ "version": "5.0.12",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
+ "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/commander": {
+ "version": "9.5.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
+ "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || >=14"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/electron": {
+ "version": "44.4.3",
+ "resolved": "https://registry.npmjs.org/electron/-/electron-44.4.3.tgz",
+ "integrity": "sha512-LTpSFTB40qVCXIX5xMo+cgHI/Jjkbjw7VpB26PccEbroqOn72LBukeaDwPVo1fBYzSzs0c9iPuAucFCO7Tw81Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@electron-internal/extract-zip": "^1.0.1",
+ "@electron/get": "^5.0.0",
+ "@types/node": "^24.9.0"
+ },
+ "bin": {
+ "electron": "cli.js",
+ "install-electron": "install.js"
+ },
+ "engines": {
+ "node": ">= 22.12.0"
+ }
+ },
+ "node_modules/env-paths": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
+ "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/err-code": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",
+ "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/filename-reserved-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/filename-reserved-regex/-/filename-reserved-regex-3.0.0.tgz",
+ "integrity": "sha512-hn4cQfU6GOT/7cFHXBqeBg2TbrMBgdD0kcjLhvSQYYwm3s4B6cjvBfb7nBALJLAXqmU5xajSa7X2NnUud/VCdw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/filenamify": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/filenamify/-/filenamify-6.0.0.tgz",
+ "integrity": "sha512-vqIlNogKeyD3yzrm0yhRMQg8hOVwYcYRfjEoODd49iCprMn4HL85gK3HcykQE53EPIpX3HcAbGA5ELQv216dAQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "filename-reserved-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/flora-colossus": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/flora-colossus/-/flora-colossus-3.0.2.tgz",
+ "integrity": "sha512-Jk78K/Tzt6saxQPGChlJw69xuFGpWyTSAS8EdU0h/FyXwD2K46yNOXmo6nRHcZ9ooekyBAzMkwmiGNt7wOC5zg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.1"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/galactus": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/galactus/-/galactus-2.0.2.tgz",
+ "integrity": "sha512-HmKyTFGomdAchz4umx8MwBnrnfFmdpwiTyGA4ZOF7rya2Lmgbc9qate4yweInL+0gUBVImhaz12SBGpW3SY4Yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.1",
+ "flora-colossus": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=22.12.0"
+ }
+ },
+ "node_modules/glob": {
+ "version": "13.0.6",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
+ "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "minimatch": "^10.2.2",
+ "minipass": "^7.1.3",
+ "path-scurry": "^2.0.2"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/graceful-fs": {
+ "version": "4.2.11",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/isbinaryfile": {
+ "version": "4.0.10",
+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",
+ "integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/gjtorikian/"
+ }
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/junk": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/junk/-/junk-4.0.1.tgz",
+ "integrity": "sha512-Qush0uP+G8ZScpGMZvHUiRfI0YBWuB3gVBYlI0v0vvOJt5FLicco+IkP0a50LqTTQhmts/m6tP5SWE+USyIvcQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "11.5.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "10.2.6",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
+ "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "brace-expansion": "^5.0.8"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/minipass": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-scurry": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
+ "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "lru-cache": "^11.0.0",
+ "minipass": "^7.1.2"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/pe-library": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-1.0.1.tgz",
+ "integrity": "sha512-nh39Mo1eGWmZS7y+mK/dQIqg7S1lp38DpRxkyoHf0ZcUs/HDc+yyTjuOtTvSMZHmfSLuSQaX945u05Y2Q6UWZg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14",
+ "npm": ">=7"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/jet2jet"
+ }
+ },
+ "node_modules/plist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",
+ "integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@xmldom/xmldom": "^0.9.10",
+ "base64-js": "^1.5.1",
+ "xmlbuilder": "^15.1.1"
+ },
+ "engines": {
+ "node": ">=10.4.0"
+ }
+ },
+ "node_modules/postject": {
+ "version": "1.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",
+ "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "commander": "^9.4.0"
+ },
+ "bin": {
+ "postject": "dist/cli.js"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/progress": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/promise-retry": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",
+ "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "err-code": "^2.0.2",
+ "retry": "^0.12.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/resedit": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/resedit/-/resedit-2.0.3.tgz",
+ "integrity": "sha512-oTeemxwoMuxxTYxXUwjkrOPfngTQehlv0/HoYFNkB4uzsP1Un1A9nI8JQKGOFkxpqkC7qkMs0lUsGrvUlbLNUA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "pe-library": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=14",
+ "npm": ">=7"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/jet2jet"
+ }
+ },
+ "node_modules/retry": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
+ "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/sumchecker": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
+ "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "debug": "^4.1.0"
+ },
+ "engines": {
+ "node": ">= 8.0"
+ }
+ },
+ "node_modules/undici": {
+ "version": "7.29.1",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz",
+ "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=20.18.1"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.18.2",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/xmlbuilder": {
+ "version": "15.1.1",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
+ "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/yargs-parser": {
+ "version": "22.0.0",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=23"
+ }
+ }
+ }
+}
diff --git a/desktop/package.json b/desktop/package.json
new file mode 100644
index 000000000..4c8fc604a
--- /dev/null
+++ b/desktop/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "qm-desktop",
+ "productName": "QM",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "main": "main.mjs",
+ "scripts": {
+ "start": "electron .",
+ "test": "node --experimental-test-module-mocks --test test/*.test.mjs",
+ "package": "electron-packager . QM --protocol=qm-desktop --protocol-name=QM --app-bundle-id=com.qm.desktop --out=dist --overwrite --ignore='^/(dist|test|README.md)'"
+ },
+ "devDependencies": {
+ "electron": "44.4.3",
+ "@electron/packager": "20.3.0"
+ }
+}
diff --git a/desktop/preload.cjs b/desktop/preload.cjs
new file mode 100644
index 000000000..28a514415
--- /dev/null
+++ b/desktop/preload.cjs
@@ -0,0 +1,7 @@
+const { contextBridge, ipcRenderer } = require("electron");
+
+contextBridge.exposeInMainWorld("qm", {
+ onLoginStatus: (callback) => ipcRenderer.on("qm:login-status", (_event, status) => callback(status)),
+ currentInstance: () => ipcRenderer.invoke("qm:current-instance"),
+ connect: (url) => ipcRenderer.invoke("qm:connect", url),
+});
diff --git a/desktop/setup.css b/desktop/setup.css
new file mode 100644
index 000000000..9d0ef1267
--- /dev/null
+++ b/desktop/setup.css
@@ -0,0 +1,183 @@
+:root {
+ color-scheme: light;
+ --paper: #f7f6f2;
+ --ink: #1b3043;
+ --muted: #6b706f;
+ --brand-font: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif;
+ font-family:
+ ui-sans-serif,
+ system-ui,
+ -apple-system,
+ "Segoe UI",
+ sans-serif;
+ color: var(--ink);
+ background: var(--paper);
+ -webkit-font-smoothing: antialiased;
+}
+* {
+ box-sizing: border-box;
+}
+body {
+ margin: 0;
+}
+main {
+ position: relative;
+ min-height: 100vh;
+ isolation: isolate;
+ padding: 155px 24px 220px;
+}
+.harbour {
+ position: absolute;
+ inset: 0;
+ z-index: -1;
+ margin: 0;
+ overflow: hidden;
+ background: #d8d0bd;
+}
+.harbour > img {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ object-position: center 62%;
+}
+.masthead {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 62px 52px 26px;
+ -webkit-app-region: drag;
+}
+.wordmark {
+ font-family: var(--brand-font);
+ font-size: 40px;
+ letter-spacing: -2px;
+ line-height: 1;
+}
+figcaption {
+ position: absolute;
+ bottom: 19px;
+ right: 28px;
+ display: flex;
+ gap: 12px;
+ font-size: 9px;
+ letter-spacing: 0.035em;
+ color: #fffaf0;
+ text-shadow: 0 1px 5px #211c14;
+}
+figcaption span {
+ opacity: 0.85;
+}
+.connection {
+ width: min(100%, 420px);
+ margin-inline: auto;
+ padding: 28px;
+ border: 1px solid #fffaf080;
+ border-radius: 12px;
+ background: rgb(247 246 242 / 88%);
+ box-shadow: 0 4px 24px rgb(37 38 31 / 5%);
+ backdrop-filter: blur(12px);
+}
+label {
+ display: block;
+ font-size: 13px;
+ font-weight: 550;
+ margin-bottom: 7px;
+}
+.hint {
+ font-size: 11px;
+ line-height: 1.6;
+ color: var(--muted);
+ margin: 0 0 16px;
+}
+input {
+ width: 100%;
+ padding: 13px 14px;
+ border: 1px solid #d6d9d9;
+ border-radius: 7px;
+ background: #fdfdfb;
+ color: var(--ink);
+ font: inherit;
+ font-size: 12px;
+}
+input::placeholder {
+ color: #8a908f;
+}
+input:focus-visible {
+ outline: 2px solid #8394a0;
+ outline-offset: 3px;
+}
+input[aria-invalid="true"] {
+ border-color: #9d3927;
+}
+#error {
+ color: #9d3927;
+ font-size: 11px;
+ line-height: 1.5;
+}
+#error:not(:empty) {
+ margin-top: 9px;
+}
+button {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ width: 100%;
+ margin-top: 12px;
+ border: none;
+ border-radius: 7px;
+ padding: 12px 14px;
+ background: var(--ink);
+ color: #fff;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+}
+button:hover {
+ background: #29445b;
+}
+button:focus-visible {
+ outline: 2px solid #8394a0;
+ outline-offset: 3px;
+}
+button > span:last-child {
+ font-size: 19px;
+ line-height: 16px;
+}
+button:disabled {
+ opacity: 0.65;
+ cursor: wait;
+}
+.settings-hint {
+ color: #78807f;
+ font-size: 10px;
+ margin: 13px 0 0;
+ text-align: center;
+}
+@media (max-width: 600px) {
+ main {
+ padding-top: 130px;
+ }
+ .masthead {
+ padding-inline: 28px;
+ }
+ .connection {
+ padding: 24px;
+ }
+ figcaption {
+ left: 20px;
+ right: auto;
+ font-size: 8px;
+ }
+}
+
+#login-status {
+ color: var(--ink);
+ font-size: 12px;
+ line-height: 1.6;
+ margin: 16px 0 0;
+}
+#login-status:empty {
+ display: none;
+}
diff --git a/desktop/setup.html b/desktop/setup.html
new file mode 100644
index 000000000..2420b7e06
--- /dev/null
+++ b/desktop/setup.html
@@ -0,0 +1,49 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'"
+ />
+ <title>Welcome to QM</title>
+ <link rel="stylesheet" href="setup.css" />
+ </head>
+ <body>
+ <main>
+ <figure class="harbour">
+ <img
+ src="assets/becalmed-off-halfway-rock.webp"
+ alt="Sailing ships resting on still, sunlit water in Becalmed off Halfway Rock by Fitz Henry Lane."
+ />
+ <header class="masthead">
+ <span class="wordmark" aria-label="QM">QM</span>
+ </header>
+ <figcaption>Becalmed off Halfway Rock<span>Fitz Henry Lane, 1860</span></figcaption>
+ </figure>
+ <section class="connection" aria-label="Connect to your workspace">
+ <form>
+ <label for="url">Connect to your workspace</label>
+ <p id="url-help" class="hint">Enter the web address you use to open QM.</p>
+ <input
+ id="url"
+ name="url"
+ type="url"
+ placeholder="https://qm.your-company.com"
+ required
+ autofocus
+ autocomplete="url"
+ spellcheck="false"
+ aria-describedby="url-help error"
+ />
+ <div id="error" role="alert"></div>
+ <button type="submit"><span class="button-label">Open QM</span><span aria-hidden="true">→</span></button>
+ </form>
+ <p class="settings-hint">Your workspace will be remembered on this Mac.</p>
+ <p id="login-status" role="status"></p>
+ </section>
+ </main>
+ <script src="setup.js"></script>
+ </body>
+</html>
diff --git a/desktop/setup.js b/desktop/setup.js
new file mode 100644
index 000000000..7db926315
--- /dev/null
+++ b/desktop/setup.js
@@ -0,0 +1,39 @@
+const form = window.document.querySelector("form");
+const input = window.document.querySelector("input");
+const button = window.document.querySelector("button");
+const buttonLabel = window.document.querySelector(".button-label");
+const status = window.document.querySelector("#login-status");
+window.qm.onLoginStatus((message) => {
+ status.textContent = message;
+});
+const error = window.document.querySelector("#error");
+
+window.qm
+ .currentInstance()
+ .then((result) => {
+ input.value = result.url;
+ status.textContent = result.status;
+ })
+ .catch((reason) => {
+ error.textContent = reason.message;
+ });
+form.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ button.disabled = true;
+ buttonLabel.textContent = "Connecting…";
+ input.removeAttribute("aria-invalid");
+ error.textContent = "";
+ try {
+ const result = await window.qm.connect(input.value.trim());
+ if (result.error) {
+ error.textContent = result.error;
+ input.setAttribute("aria-invalid", "true");
+ input.focus();
+ }
+ } catch (reason) {
+ error.textContent = reason.message;
+ } finally {
+ button.disabled = false;
+ buttonLabel.textContent = "Open QM";
+ }
+});
diff --git a/desktop/test/login.test.mjs b/desktop/test/login.test.mjs
new file mode 100644
index 000000000..7ae025b58
--- /dev/null
+++ b/desktop/test/login.test.mjs
@@ -0,0 +1,33 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { test } from "node:test";
+import { createLogin, loginCallback } from "../login.mjs";
+
+test("browser login carries only the proof challenge, never its secret", () => {
+ const pending = createLogin("https://qm.example.com/s/123", 1000);
+ const url = new URL(pending.url);
+ assert.equal(url.origin, "https://qm.example.com");
+ assert.equal(url.pathname, "/auth/desktop");
+ assert.equal(url.searchParams.get("challenge"), createHash("sha256").update(pending.verifier).digest("base64url"));
+ assert.equal(url.href.includes(pending.verifier), false);
+ assert.notEqual(createLogin(pending.instance).state, pending.state);
+});
+
+test("only a callback for the current unexpired attempt is accepted", () => {
+ const pending = createLogin("https://qm.example.com", 1000);
+ const callback = `qm-desktop://auth/callback?state=${pending.state}&code=signed-code`;
+ assert.equal(loginCallback(callback, pending, 2000), "signed-code");
+ assert.equal(loginCallback(callback, pending, pending.expiresAt), null);
+ assert.equal(loginCallback(callback, undefined, 2000), null);
+ assert.equal(loginCallback(callback, createLogin(pending.instance, 1000), 2000), null);
+ for (const invalid of [
+ callback.replace("qm-desktop:", "https:"),
+ callback.replace("//auth/", "//attacker/"),
+ callback.replace("/callback?", "/elsewhere?"),
+ `${callback}&state=${pending.state}`,
+ `${callback}&code=another`,
+ `${callback}#fragment`,
+ callback.replace("signed-code", ""),
+ ])
+ assert.equal(loginCallback(invalid, pending, 2000), null);
+});
diff --git a/desktop/test/main.test.mjs b/desktop/test/main.test.mjs
new file mode 100644
index 000000000..6974e9303
--- /dev/null
+++ b/desktop/test/main.test.mjs
@@ -0,0 +1,148 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { mock, test } from "node:test";
+
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+
+test(
+ "desktop handoff redeems once, cancels stale completion, and opens the authenticated session",
+ { timeout: 10_000 },
+ async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), "qm-desktop-test-"));
+ await writeFile(path.join(directory, "instance.json"), JSON.stringify({ url: "https://old.example/auth/login" }));
+ const app = Object.assign(new EventEmitter(), {
+ setName() {},
+ requestSingleInstanceLock: () => true,
+ quit() {},
+ whenReady: async () => {},
+ getPath: () => directory,
+ setAsDefaultProtocolClient() {},
+ });
+ const handlers = new Map();
+ const windows = [];
+ const initialLoad = Promise.withResolvers();
+ const opened = [];
+ const requests = [];
+ const errors = [];
+ let flushes = 0;
+ const session = {
+ setPermissionRequestHandler() {},
+ setPermissionCheckHandler() {},
+ cookies: {
+ flushStore: async () => {
+ flushes++;
+ },
+ },
+ fetch: (url, options) => new Promise((resolve) => requests.push({ url, options, resolve })),
+ };
+ class BrowserWindow extends EventEmitter {
+ constructor(options) {
+ super();
+ this.options = options;
+ this.webContents = Object.assign(new EventEmitter(), {
+ session,
+ send() {},
+ setWindowOpenHandler: (handler) => {
+ this.popup = handler;
+ },
+ });
+ windows.push(this);
+ }
+ async loadURL(url) {
+ this.url = url;
+ initialLoad.resolve();
+ }
+ show() {
+ this.visible = true;
+ }
+ hide() {
+ this.visible = false;
+ }
+ isDestroyed() {
+ return !!this.destroyed;
+ }
+ close() {
+ this.destroy();
+ }
+ destroy() {
+ this.destroyed = true;
+ this.emit("closed");
+ }
+ }
+ mock.module("electron", {
+ namedExports: {
+ app,
+ BrowserWindow,
+ ipcMain: { handle: (name, handler) => handlers.set(name, handler) },
+ Menu: { buildFromTemplate: (template) => template, setApplicationMenu() {} },
+ shell: {
+ openExternal: async (url) => {
+ opened.push(url);
+ },
+ },
+ session: { fromPartition: () => session },
+ dialog: { showErrorBox: (...args) => errors.push(args), showMessageBox: async (...args) => errors.push(args) },
+ },
+ });
+ const original = process.env.QM_DESKTOP_URL;
+ delete process.env.QM_DESKTOP_URL;
+ try {
+ await import("../main.mjs");
+ await initialLoad.promise;
+ assert.equal(windows[0].url, "https://old.example/");
+ let prevented = false;
+ windows[0].webContents.emit(
+ "will-redirect",
+ {
+ preventDefault() {
+ prevented = true;
+ },
+ },
+ "https://old.example/auth/login",
+ );
+ assert.equal(prevented, true);
+ assert.equal(opened.length, 1);
+ const callback = (index) =>
+ `qm-desktop://auth/callback?code=test-code&state=${new URL(opened[index]).searchParams.get("state")}`;
+ const event = { preventDefault() {} };
+ app.emit("open-url", event, callback(0));
+ app.emit("open-url", event, callback(0));
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].options.credentials, "include");
+ const setup = windows[1];
+ assert.deepEqual(
+ await handlers.get("qm:connect")(
+ { sender: setup.webContents, senderFrame: { url: setup.url } },
+ "https://new.example/",
+ ),
+ { ok: true },
+ );
+ assert.equal(requests[0].options.signal.aborted, true);
+ requests[0].resolve({ ok: true });
+ await tick();
+ assert.equal(windows.length, 3);
+ assert.equal(windows[2].url, "https://new.example/");
+ assert.equal(windows[2].isDestroyed(), false);
+ assert.equal(flushes, 0);
+ assert.deepEqual(windows[2].popup({ url: "https://new.example/auth/trusted/login" }), { action: "deny" });
+ assert.equal(opened.length, 2);
+ app.emit("open-url", event, callback(1));
+ assert.equal(requests.length, 2);
+ assert.equal(requests[1].url, "https://new.example/auth/desktop/redeem");
+ requests[1].resolve({ ok: true });
+ await tick();
+ assert.equal(flushes, 1);
+ assert.equal(windows.at(-1).url, "https://new.example/");
+ assert.equal(windows[3].isDestroyed(), true);
+ assert.deepEqual(errors, []);
+ } finally {
+ if (original === undefined) delete process.env.QM_DESKTOP_URL;
+ else process.env.QM_DESKTOP_URL = original;
+ mock.restoreAll();
+ await rm(directory, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/desktop/test/url.test.mjs b/desktop/test/url.test.mjs
new file mode 100644
index 000000000..3f1b99d62
--- /dev/null
+++ b/desktop/test/url.test.mjs
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { instanceUrl, externalUrl, browserLoginUrl } from "../url.mjs";
+
+test("accepts secure deployments and explicit loopback development URLs", () => {
+ for (const url of [
+ "https://qm.example.com/chat",
+ "http://localhost:3000/",
+ "http://127.0.0.1:4000/",
+ "http://[::1]:3000/",
+ ]) {
+ assert.equal(instanceUrl(url), url);
+ }
+});
+
+test("rejects insecure remote servers, credentials, and privileged protocols", () => {
+ for (const url of [
+ "http://qm.example.com",
+ "https://user:[email protected]",
+ "file:///etc/passwd",
+ "javascript:alert(1)",
+ "data:text/html,hello",
+ "http://localhost.evil.com",
+ "qm.example.com",
+ ]) {
+ assert.throws(() => instanceUrl(url));
+ }
+});
+
+test("external links cannot launch local files or arbitrary protocol handlers", () => {
+ for (const url of ["https://example.com/path", "http://localhost:3000", "mailto:[email protected]"])
+ assert.equal(externalUrl(url), true);
+ for (const url of [
+ "file:///tmp/script.sh",
+ "javascript:alert(1)",
+ "vscode://file/tmp/foo",
+ "https://user:[email protected]",
+ "invalid",
+ ])
+ assert.equal(externalUrl(url), false);
+});
+
+test("browser sign-in only intercepts exact same-origin auth route families", () => {
+ const origin = "https://qm.example.com";
+ for (const route of ["/auth/login", "/auth/login?returnTo=/", "/auth/trusted/login", "/auth/trusted/login/start"])
+ assert.equal(browserLoginUrl(origin + route, origin), true);
+ for (const value of [
+ "https://other.example/auth/login",
+ origin + "/auth/login-lookalike",
+ origin + "/auth/trusted/login-other",
+ origin + "/chat",
+ ])
+ assert.equal(browserLoginUrl(value, origin), false);
+});
diff --git a/desktop/url.mjs b/desktop/url.mjs
new file mode 100644
index 000000000..622264630
--- /dev/null
+++ b/desktop/url.mjs
@@ -0,0 +1,23 @@
+export function instanceUrl(value) {
+ const url = new URL(value);
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
+ throw new Error("Use an HTTPS URL, or HTTP for a local dev instance.");
+ }
+ if (url.username || url.password) throw new Error("Use a URL without embedded credentials.");
+ return url.href;
+}
+
+export function externalUrl(value) {
+ try {
+ const url = new URL(value);
+ return ["https:", "http:", "mailto:"].includes(url.protocol) && !url.username && !url.password;
+ } catch {
+ return false;
+ }
+}
+
+export function browserLoginUrl(value, origin) {
+ const url = new URL(value);
+ return url.origin === origin && /^\/auth\/(login|trusted\/login)(?:\/|$)/.test(url.pathname);
+}
diff --git a/eslint.config.mjs b/eslint.config.mjs
index d5d80a6aa..1fffaec40 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -19,6 +19,14 @@ export default tseslint.config(
},
js.configs.recommended,
tseslint.configs.recommended,
+ {
+ files: ["desktop/preload.cjs"],
+ rules: { "@typescript-eslint/no-require-imports": "off" },
+ },
+ {
+ files: ["desktop/setup.js"],
+ languageOptions: { globals: globals.browser },
+ },
{
files: ["**/*.js", "**/*.mjs", "**/*.cjs"],
languageOptions: { globals: globals.node },
diff --git a/knip.json b/knip.json
index 19b7c755c..8dc6ba288 100644
--- a/knip.json
+++ b/knip.json
@@ -37,6 +37,9 @@
"docs/qa/resource-search-demo.mjs"
]
},
+ "desktop": {
+ "entry": ["preload.cjs", "setup.js", "test/**/*.test.mjs"]
+ },
"cli": {
"entry": ["bin/qm.ts"]
},
diff --git a/plugins/portal/src/desktop-login.ts b/plugins/portal/src/desktop-login.ts
new file mode 100644
index 000000000..2de1d55b0
--- /dev/null
+++ b/plugins/portal/src/desktop-login.ts
@@ -0,0 +1,89 @@
+import { createHash } from "node:crypto";
+import { deriveKey, open, randomToken, safeEqual, seal, type SessionClaims } from "./session.ts";
+
+export function desktopChallenge(value: string): boolean {
+ return /^[A-Za-z0-9_-]{43}$/.test(value);
+}
+
+export function mintDesktopLogin(
+ session: SessionClaims,
+ secret: string,
+ origin: string,
+ challenge: string,
+ state: string,
+) {
+ const now = Math.floor(Date.now() / 1000);
+ return seal(
+ {
+ k: "desktop-login",
+ aud: origin,
+ sub: session.sub,
+ org: session.org,
+ name: session.name,
+ auth: session.auth ?? session.iat,
+ sessionExp: session.exp,
+ challenge,
+ state,
+ iat: now,
+ exp: Math.min(now + 120, session.exp),
+ jti: randomToken(18),
+ },
+ deriveKey(secret, "portal.desktop-login.v1"),
+ );
+}
+
+export function openDesktopLogin(
+ code: string,
+ verifier: string,
+ state: string,
+ secret: string,
+ origin: string,
+ org: string,
+ maxAge: number,
+ nowMs = Date.now(),
+) {
+ if (code.length > 8192 || !desktopChallenge(verifier) || !desktopChallenge(state)) return null;
+ const p = open(code, deriveKey(secret, "portal.desktop-login.v1"));
+ const now = Math.floor(nowMs / 1000);
+ if (
+ !p ||
+ p.k !== "desktop-login" ||
+ p.aud !== origin ||
+ p.org !== org ||
+ typeof p.sub !== "string" ||
+ !p.sub ||
+ typeof p.auth !== "number" ||
+ !Number.isSafeInteger(p.auth) ||
+ p.auth > now + 5 ||
+ now >= p.auth + maxAge ||
+ typeof p.sessionExp !== "number" ||
+ !Number.isSafeInteger(p.sessionExp) ||
+ p.sessionExp <= now ||
+ typeof p.iat !== "number" ||
+ !Number.isSafeInteger(p.iat) ||
+ p.iat > now + 5 ||
+ typeof p.exp !== "number" ||
+ !Number.isSafeInteger(p.exp) ||
+ p.exp <= now ||
+ p.exp <= p.iat ||
+ p.exp - p.iat > 120 ||
+ typeof p.jti !== "string" ||
+ !/^[a-f0-9]{36}$/.test(p.jti) ||
+ typeof p.challenge !== "string" ||
+ !desktopChallenge(p.challenge) ||
+ typeof p.state !== "string" ||
+ !safeEqual(state, p.state) ||
+ !safeEqual(createHash("sha256").update(verifier).digest("base64url"), p.challenge)
+ )
+ return null;
+ const session: SessionClaims = {
+ k: "session",
+ sub: p.sub,
+ org,
+ auth: p.auth,
+ iat: now,
+ exp: p.sessionExp,
+ ...(typeof p.name === "string" ? { name: p.name } : {}),
+ };
+ return { session, jti: p.jti, expiresAtMs: p.exp * 1000 };
+}
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index 8291825ec..0e4ff6f16 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -1,3 +1,4 @@
+import { desktopChallenge, mintDesktopLogin, openDesktopLogin } from "./desktop-login.ts";
import { INVITE_LOGIN_SCRIPT, INVITE_LOGIN_SCRIPT_HASH } from "./invite-login.ts";
import { reportBackendError } from "../../chassis/src/error-reporting.ts";
import "./instrument.ts";
@@ -928,7 +929,7 @@ async function mintPlaygroundSession(req: IncomingMessage, res: ServerResponse):
return session;
}
-function renewSessionCookie(req: IncomingMessage, res: ServerResponse): void {
+function renewSessionCookie(req: IncomingMessage, res: ServerResponse): SessionClaims | null {
const session = openSession(
readCookie(req.headers.cookie, "portal_session"),
sessionKey,
@@ -936,9 +937,9 @@ function renewSessionCookie(req: IncomingMessage, res: ServerResponse): void {
ORG,
SESSION_MAX_TTL_S,
);
- if (!session) return;
+ if (!session) return null;
const now = Math.floor(Date.now() / 1000);
- if (now - session.iat < SESSION_RENEW_AFTER_S) return;
+ if (now - session.iat < SESSION_RENEW_AFTER_S) return session;
const authenticatedAt = session.auth ?? session.iat;
const renewed: SessionClaims = {
...session,
@@ -947,6 +948,7 @@ function renewSessionCookie(req: IncomingMessage, res: ServerResponse): void {
exp: Math.min(now + SESSION_TTL_S, authenticatedAt + SESSION_MAX_TTL_S),
};
setSession(res, sessionCookieSet(seal(renewed, sessionKey), renewed.sub));
+ return renewed;
}
const server = createServer((req, res) => {
@@ -988,6 +990,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
if (pathname === "/auth/login" && method === "GET") return authLogin(req, res, url);
if (pathname === "/auth/callback" && method === "GET") return authCallback(req, res, url);
if (pathname.startsWith("/auth/trusted/") && method === "GET") return trustedAuth(req, res, url);
+ if (pathname === "/auth/desktop" || pathname === "/auth/desktop/redeem") return desktopLogin(req, res, url);
if (pathname === "/auth/invite") return inviteLogin(req, res);
if (pathname === "/auth/admin-login") return adminLogin(req, res);
if (pathname === "/auth/logout" && method === "POST") {
@@ -1054,8 +1057,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
);
}
- let session = currentSession(req);
- if (session) renewSessionCookie(req, res);
+ let session = renewSessionCookie(req, res) ?? currentSession(req);
const authenticatedPrincipal = session?.sub;
if (session && !session.anon && (!pathname.startsWith("/auth/") || pathname.startsWith("/auth/impersonate"))) {
const canonical = await canonicalPrincipal(session.sub);
@@ -1322,6 +1324,97 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
});
}
+async function desktopLogin(req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
+ res.setHeader("cache-control", "no-store");
+ if (!SESSION_SECRET || SESSION_SECRET.trim().length < 32 || !CORE_SIGNING_SECRET) {
+ return json(res, 503, { error: "not_configured" });
+ }
+ if (url.pathname.endsWith("/redeem")) {
+ if (req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });
+ if ((req.headers.origin !== undefined || req.headers["sec-fetch-site"] !== undefined) && !sameOriginRequest(req))
+ return json(res, 403, { error: "forbidden" });
+ let body: URLSearchParams;
+ try {
+ body = new URLSearchParams(await readBody(req, 12288));
+ } catch (error) {
+ if (error instanceof PayloadTooLargeError) return json(res, 413, { error: "payload_too_large" });
+ throw error;
+ }
+ const claims = openDesktopLogin(
+ body.get("code") ?? "",
+ body.get("verifier") ?? "",
+ body.get("state") ?? "",
+ SESSION_SECRET,
+ ORIGIN,
+ ORG,
+ SESSION_MAX_TTL_S,
+ );
+ if (!claims) return json(res, 400, { error: "invalid_desktop_login" });
+ try {
+ if (
+ !(await claimOnce(
+ coreClaimStore(CORE, CORE_SIGNING_SECRET, "portal"),
+ `desktop-login:${claims.jti}`,
+ claims.expiresAtMs,
+ ))
+ ) {
+ return json(res, 400, { error: "desktop_login_already_used" });
+ }
+ } catch (error) {
+ if (error instanceof ClaimStoreUnavailableError) return json(res, 503, { error: "temporarily_unavailable" });
+ throw error;
+ }
+ setSession(res, [
+ ...sessionCookieSet(seal(claims.session, sessionKey), claims.session.sub),
+ clearCookie("portal_impersonate", "/", SECURE_COOKIES),
+ ]);
+ return json(res, 200, { ok: true });
+ }
+ if (req.method !== "GET" && req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });
+ const challenge = url.searchParams.get("challenge") ?? "";
+ const state = url.searchParams.get("state") ?? "";
+ if (!desktopChallenge(challenge) || !desktopChallenge(state))
+ return json(res, 400, { error: "invalid_desktop_request" });
+ if (req.method === "POST" && !sameOriginRequest(req)) return json(res, 403, { error: "forbidden" });
+ const session = renewSessionCookie(req, res) ?? currentSession(req);
+ if (!session || session.anon) {
+ res.writeHead(303, {
+ location: `/auth/login?returnTo=${encodeURIComponent(`${url.pathname}${url.search}`)}`,
+ "cache-control": "no-store",
+ });
+ return void res.end();
+ }
+ if (req.method === "GET") {
+ return sendHtml(
+ res,
+ 200,
+ cardPage({
+ title: "Open QM Desktop",
+ heading: "Sign in to QM Desktop",
+ icon: LOCK_ICON,
+ msg: `Continue as ${session.sub}.`,
+ actions: `<form method="post" action="${escapeHtml(`${url.pathname}${url.search}`)}"><button class="btn primary" type="submit">Open QM Desktop</button></form>`,
+ help: "Only continue if you just started sign-in in the QM desktop app on this computer.",
+ }),
+ );
+ }
+ const callback = new URL("qm-desktop://auth/callback");
+ callback.searchParams.set("code", mintDesktopLogin(session, SESSION_SECRET, ORIGIN, challenge, state));
+ callback.searchParams.set("state", state);
+ return sendHtml(
+ res,
+ 200,
+ cardPage({
+ title: "Ready to open QM",
+ heading: "Your desktop sign-in is ready",
+ icon: LOCK_ICON,
+ msg: "Return to the app to finish signing in.",
+ actions: `<a class="btn primary" href="${escapeHtml(callback.href)}">Open QM Desktop</a>`,
+ help: "This link expires in two minutes and works only for the app that requested it.",
+ }),
+ );
+}
+
async function inviteLogin(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (!SESSION_SECRET || !CORE_SIGNING_SECRET) return json(res, 503, { error: "not_configured" });
if (req.method === "GET")
diff --git a/plugins/portal/test/desktop-login.test.ts b/plugins/portal/test/desktop-login.test.ts
new file mode 100644
index 000000000..3b19c6a5f
--- /dev/null
+++ b/plugins/portal/test/desktop-login.test.ts
@@ -0,0 +1,180 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createHash, randomBytes } from "node:crypto";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { mintDesktopLogin, openDesktopLogin } from "../src/desktop-login.ts";
+import { deriveKey, openSession, seal, type SessionClaims } from "../src/session.ts";
+
+const secret = "desktop-login-test-session-secret-long-enough";
+const origin = "http://127.0.0.1:19997";
+const verifier = randomBytes(32).toString("base64url");
+const challenge = createHash("sha256").update(verifier).digest("base64url");
+const state = randomBytes(32).toString("base64url");
+const now = Math.floor(Date.now() / 1000);
+const browser: SessionClaims = {
+ k: "session",
+ org: "desktop-test",
+ auth: now - 60,
+ iat: now - 30,
+ exp: now + 3600,
+};
+const cookie = `portal_session=${seal(browser, deriveKey(secret, "portal.session.v1"))}`;
+const claims = new Set<string>();
+let claimsUnavailable = false;
+const core = createServer((req, res) => {
+ void (async () => {
+ if (new URL(req.url!, origin).pathname !== "/v1/auth/broker/claim") return void res.end("{}");
+ if (claimsUnavailable) {
+ res.statusCode = 503;
+ return void res.end("{}");
+ }
+ let raw = "";
+ for await (const chunk of req) raw += chunk;
+ const body = JSON.parse(raw);
+ const key = body.ids[0];
+ const claimed = claims.has(key) ? null : key;
+ claims.add(key);
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify({ claimed }));
+ })().catch(() => {
+ res.statusCode = 500;
+ res.end();
+ });
+});
+await new Promise<void>((resolve) => core.listen(0, "127.0.0.1", resolve));
+const coreUrl = `http://127.0.0.1:${(core.address() as AddressInfo).port}`;
+Object.assign(process.env, {
+ NODE_ENV: "test",
+ PORTAL_PUBLIC_URL: origin,
+ PORTAL_SESSION_SECRET: secret,
+ CORE_SIGNING_SECRET: "desktop-core-secret",
+ CORE_ORG_ID: browser.org,
+ CORE_API_URL: coreUrl,
+ WEB_UI_UPSTREAM: coreUrl,
+ ADMIN_UPSTREAM: coreUrl,
+ PORTAL_LOCAL_AUTH_BYPASS: "0",
+ PORTAL_PLAYGROUND: "0",
+});
+const { server } = await import("../src/index.ts");
+await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+test.after(() => {
+ server.close();
+ core.close();
+});
+const requestPath = `/auth/desktop?challenge=${challenge}&state=${state}`;
+
+async function issue(sessionCookie = cookie) {
+ const response = await fetch(`${base}${requestPath}`, { method: "POST", headers: { origin, cookie: sessionCookie } });
+ assert.equal(response.status, 200);
+ const html = await response.text();
+ const match = html.match(/href="(qm-desktop:[^"]+)"/);
+ assert.ok(match);
+ const callback = new URL(match[1]!.replaceAll("&amp;", "&"));
+ assert.equal(callback.searchParams.get("state"), state);
+ return callback.searchParams.get("code")!;
+}
+function redeem(code: string, proof = verifier, requestOrigin = origin) {
+ return fetch(`${base}/auth/desktop/redeem`, {
+ method: "POST",
+ headers: { origin: requestOrigin },
+ body: new URLSearchParams({ code, verifier: proof, state }),
+ });
+}
+
+test("unauthenticated desktop requests preserve their proof across normal login", async () => {
+ const response = await fetch(`${base}${requestPath}`, { redirect: "manual" });
+ assert.equal(response.status, 303);
+ assert.equal(new URL(response.headers.get("location")!, origin).searchParams.get("returnTo"), requestPath);
+});
+
+test("GET requires explicit confirmation and cannot mint a code", async () => {
+ const response = await fetch(`${base}${requestPath}`, { headers: { cookie } });
+ const html = await response.text();
+ assert.equal(response.status, 200);
+ assert.match(html, /[email protected]/);
+ assert.match(html, /method="post"/);
+ assert.doesNotMatch(html, /qm-desktop:\/\//);
+ assert.equal(response.headers.get("set-cookie"), null);
+ assert.equal(response.headers.get("cache-control"), "no-store");
+});
+
+test("cross-origin authorization and anonymous sessions cannot mint a desktop identity", async () => {
+ const response = await fetch(`${base}${requestPath}`, {
+ method: "POST",
+ headers: { origin: "https://attacker.test", cookie },
+ });
+ assert.equal(response.status, 403);
+ const anonymous = seal({ ...browser, anon: true }, deriveKey(secret, "portal.session.v1"));
+ const anonResponse = await fetch(`${base}${requestPath}`, {
+ redirect: "manual",
+ headers: { cookie: `portal_session=${anonymous}` },
+ });
+ assert.equal(anonResponse.status, 303);
+});
+
+test("wrong proof cannot consume a code and one of concurrent valid redemptions succeeds", async () => {
+ const code = await issue();
+ assert.equal((await redeem(code, randomBytes(32).toString("base64url"))).status, 400);
+ assert.equal((await redeem(code, verifier, "https://attacker.test")).status, 403);
+ const results = await Promise.all([redeem(code), redeem(code)]);
+ assert.deepEqual(results.map((r) => r.status).sort(), [200, 400]);
+ const success = results.find((r) => r.status === 200)!;
+ const sessionCookie = success.headers.getSetCookie().find((c) => c.startsWith("portal_session="))!;
+ const token = sessionCookie.split(";")[0]!.slice("portal_session=".length);
+ const session = openSession(token, deriveKey(secret, "portal.session.v1"), Date.now(), browser.org);
+ assert.equal(session?.sub, browser.sub);
+ assert.equal(session?.auth, browser.auth);
+ assert.equal(session?.exp, browser.exp);
+ assert.match(sessionCookie, /HttpOnly/);
+});
+
+test("claim store outages fail closed without issuing a session", async () => {
+ const code = await issue();
+ claimsUnavailable = true;
+ try {
+ const response = await redeem(code);
+ assert.equal(response.status, 503);
+ assert.equal(response.headers.get("set-cookie"), null);
+ } finally {
+ claimsUnavailable = false;
+ }
+});
+
+test("codes are bounded by signature, audience, organization, state, and browser lifetime", () => {
+ const code = mintDesktopLogin(browser, secret, origin, challenge, state);
+ const verify = (value = code, target = origin, org = browser.org, when = Date.now(), expectedState = state) =>
+ openDesktopLogin(value, verifier, expectedState, secret, target, org, 86400, when);
+ assert.ok(verify());
+ assert.equal(verify(`${code}x`), null);
+ assert.equal(verify(code, "https://other.test"), null);
+ assert.equal(verify(code, origin, "other-org"), null);
+ assert.equal(verify(code, origin, browser.org, Date.now() + 121_000), null);
+ assert.equal(verify(code, origin, browser.org, Date.now(), randomBytes(32).toString("base64url")), null);
+ const old = mintDesktopLogin({ ...browser, auth: now - 86401 }, secret, origin, challenge, state);
+ assert.equal(verify(old), null);
+});
+
+test("desktop handoff renews a browser session near expiry without resetting its original authentication", async () => {
+ const testNow = Math.floor(Date.now() / 1000);
+ const oldBrowser = { ...browser, auth: testNow - 900_000, iat: testNow - 604_770, exp: testNow + 30 };
+ const oldCookie = `portal_session=${seal(oldBrowser, deriveKey(secret, "portal.session.v1"))}`;
+ const page = await fetch(`${base}${requestPath}`, { headers: { cookie: oldCookie } });
+ assert.equal(page.status, 200);
+ assert.ok(page.headers.getSetCookie().some((value) => value.startsWith("portal_session=")));
+ const code = await issue(oldCookie);
+ const effective = openDesktopLogin(
+ code,
+ verifier,
+ state,
+ secret,
+ origin,
+ browser.org,
+ 2_592_000,
+ (testNow + 31) * 1000,
+ );
+ assert.equal(effective?.session.auth, oldBrowser.auth);
+ assert.ok(effective && effective.session.exp >= testNow + 604_800);
+});