Multiplayer agent harness for work.
Fix desktop sign-in, connection handoff, and window navigation (#1581)
Regan Bell73fde1749006
diff --git a/desktop/README.md b/desktop/README.mdindex c8d1c4384..b97c4c968 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -23,6 +23,27 @@ When sign-in is needed, the app opens `/auth/desktop` in your default browser. SThe 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.+On macOS, the window controls sit inside the sidebar header. With a single session open, drag its title bar to move the window; tab dragging remains available in multi-pane layouts. Hold Command to reveal shortcuts for the first nine sessions in expanded sidebar groups, then press 1–9 to switch. Windows and Linux use Control. Collapsed groups and a hidden sidebar are excluded.++Remote content is sandboxed with no Node.js access. An isolated desktop preload adds window styling and session shortcuts with one sender-validated operation for opening a same-instance setup page in the browser. 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).++## Connection setup and previews++Slack installation and personal app authorization start in your browser before QM creates the connection attempt. Finish setup there, then return to the desktop app; it refreshes connection status on focus. Settings contains both personal Slack linking and the app picker. This keeps provider callbacks, installation POSTs, cookies, and tab-local authorization state in one browser.++Same-instance links opened in a new tab use a separate sandboxed window sharing the instance session. External links open in the browser. View → Back and Forward navigate the focused window. Closing the main window closes its previews.++## Mac release++`npm run package` builds the unsigned local app. For a signed and notarized build, install a Developer ID Application certificate in the Mac keychain and store notarization credentials using Apple's `notarytool`. Then run:++```sh+QM_MAC_SIGN_IDENTITY="Developer ID Application: Your Organization (TEAMID)" \+QM_MAC_NOTARY_PROFILE="qm-notary" npm run package:release+```++The release command requires both values and fails if signing or notarization fails. Neither credentials nor certificates belong in this repository. Builds target the current machine's architecture. Automatic updates are not implemented.++`npm run test:electron` exercises actual Electron preview windows, POST popups, session sharing, sandboxing, and browser handoff against a temporary local server.diff --git a/desktop/assets/qm.icns b/desktop/assets/qm.icnsnew file mode 100644index 000000000..5714383a3Binary files /dev/null and b/desktop/assets/qm.icns differdiff --git a/desktop/assets/qm.png b/desktop/assets/qm.pngnew file mode 100644index 000000000..f05ad7cf6Binary files /dev/null and b/desktop/assets/qm.png differdiff --git a/desktop/login.mjs b/desktop/login.mjsindex 5bb6c541a..10aee2f48 100644--- a/desktop/login.mjs+++ b/desktop/login.mjs@@ -1,12 +1,25 @@import { createHash, randomBytes } from "node:crypto";-export function createLogin(instance, now = Date.now()) {+export function createLogin(instance, now = Date.now(), loginUrl) {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 };+ let destination = url;+ if (loginUrl) {+ const login = new URL(loginUrl);+ if (+ login.origin === url.origin &&+ (login.pathname === "/auth/trusted/login" ||+ (login.pathname === "/auth/login" && login.searchParams.get("provider") === "primary"))+ ) {+ destination = new URL(login.pathname, url);+ if (login.pathname === "/auth/login") destination.searchParams.set("provider", "primary");+ destination.searchParams.set("returnTo", url.pathname + url.search);+ }+ }+ return { verifier, state, url: destination.href, instance, expiresAt: now + 10 * 60_000 };}export function loginCallback(value, pending, now = Date.now()) {diff --git a/desktop/main.mjs b/desktop/main.mjsindex c69c781ef..87fcda2d7 100644--- a/desktop/main.mjs+++ b/desktop/main.mjs@@ -3,11 +3,12 @@ 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";+import { instanceUrl, externalUrl, browserLoginUrl, loginDestination, internalUrl } from "./url.mjs";const directory = path.dirname(fileURLToPath(import.meta.url));const setupUrl = pathToFileURL(path.join(directory, "setup.html")).href;let mainWindow;+const workspaceWindows = new Set();let setupWindow;let target;let pendingLogin;@@ -63,7 +64,9 @@ function showSetup() {setupWindow.webContents.setWindowOpenHandler(() => ({ action: "deny" }));setupWindow.on("closed", () => {setupWindow = undefined;- if (pendingLogin) mainWindow?.destroy();+ pendingLogin?.controller.abort();+ pendingLogin = undefined;+ loginStatus = "";});setupWindow.loadURL(setupUrl);}@@ -72,13 +75,14 @@ function instanceSession(url) {return electronSession.fromPartition(`persist:qm-${new URL(url).origin}`);}-async function beginBrowserSignIn(url) {+async function beginBrowserSignIn(url, loginUrl) {+ if (pendingLogin?.instance === url) return;pendingLogin?.controller.abort();- const attempt = { ...createLogin(url), controller: new AbortController() };+ const attempt = { ...createLogin(url, Date.now(), loginUrl), 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();+ mainWindow?.destroy();setupWindow.webContents.send("qm:login-status", loginStatus);try {await shell.openExternal(attempt.url);@@ -128,7 +132,7 @@ async function finishBrowserSignIn(url) {async function showInstance(url) {pendingLogin?.controller.abort();pendingLogin = undefined;- if (browserLoginUrl(url, new URL(url).origin)) url = new URL("/", url).href;+ if (browserLoginUrl(url, new URL(url).origin)) url = loginDestination(url, url);if (mainWindow) mainWindow.destroy();const window = new BrowserWindow({title: "QM",@@ -137,8 +141,10 @@ async function showInstance(url) {minWidth: 800,minHeight: 600,backgroundColor: "#f5f4f0",+ ...(process.platform === "darwin" ? { titleBarStyle: "hiddenInset", trafficLightPosition: { x: 20, y: 20 } } : {}),webPreferences: {session: instanceSession(url),+ preload: path.join(directory, "workspace-preload.cjs"),nodeIntegration: false,contextIsolation: true,sandbox: true,@@ -150,34 +156,65 @@ async function showInstance(url) {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();+ const children = new Set();+ const configureNavigation = (page) => {+ workspaceWindows.add(page);+ page.on("closed", () => workspaceWindows.delete(page));+ const active = () => !page.isDestroyed() && !window.isDestroyed() && mainWindow === window;+ const signIn = (destination) => {handedOff = true;- openExternal(destination);- }+ void beginBrowserSignIn(loginDestination(destination, url, page.webContents.getURL()), destination);+ };+ const navigate = (event, destination) => {+ if (!active()) return event.preventDefault();+ if (event.isMainFrame === false) return;+ if (browserLoginUrl(destination, origin)) {+ event.preventDefault();+ signIn(destination);+ } else if (!internalUrl(destination, origin)) {+ event.preventDefault();+ handedOff = true;+ openExternal(destination);+ }+ };+ page.webContents.on("will-navigate", navigate);+ page.webContents.on("will-redirect", navigate);+ page.webContents.on("will-attach-webview", (event) => event.preventDefault());+ page.webContents.setWindowOpenHandler(({ url: destination }) => {+ if (!active()) return { action: "deny" };+ if (browserLoginUrl(destination, origin)) signIn(destination);+ else if (internalUrl(destination, origin)) {+ return {+ action: "allow",+ overrideBrowserWindowOptions: {+ width: 1100,+ height: 800,+ minWidth: 600,+ minHeight: 400,+ ...(process.platform === "darwin"+ ? { titleBarStyle: "hiddenInset", trafficLightPosition: { x: 20, y: 20 } }+ : {}),+ webPreferences: {+ session,+ preload: path.join(directory, "workspace-preload.cjs"),+ nodeIntegration: false,+ contextIsolation: true,+ sandbox: true,+ },+ },+ };+ } else openExternal(destination);+ return { action: "deny" };+ });+ page.webContents.on("did-create-window", (child) => {+ children.add(child);+ child.on("closed", () => children.delete(child));+ configureNavigation(child);+ });};- 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" };- });+ configureNavigation(window);window.on("closed", () => {+ for (const child of children) if (!child.isDestroyed()) child.destroy();if (mainWindow === window) mainWindow = undefined;});try {@@ -208,6 +245,27 @@ async function start() {throw new Error("Untrusted settings request");}};+ ipcMain.handle("qm:open-browser", async (event, value) => {+ if (+ !mainWindow ||+ mainWindow.isDestroyed() ||+ ![...workspaceWindows].some((page) => !page.isDestroyed() && page.webContents === event.sender) ||+ event.senderFrame !== event.sender.mainFrame ||+ !target ||+ new URL(event.senderFrame.url).origin !== new URL(target).origin ||+ typeof value !== "string"+ ) {+ throw new Error("Untrusted browser request");+ }+ const destination = new URL(value, target);+ if (+ destination.origin !== new URL(target).origin ||+ !externalUrl(destination.href) ||+ !["http:", "https:"].includes(destination.protocol)+ )+ throw new Error("Untrusted browser destination");+ await shell.openExternal(destination.href);+ });ipcMain.handle("qm:current-instance", (event) => {assertSetup(event);return { url: target ?? "", status: loginStatus };@@ -250,6 +308,22 @@ async function start() {{label: "View",submenu: [+ {+ label: "Back",+ accelerator: "Alt+Left",+ click: () => {+ const contents = BrowserWindow.getFocusedWindow()?.webContents;+ if (contents?.navigationHistory.canGoBack()) contents.navigationHistory.goBack();+ },+ },+ {+ label: "Forward",+ accelerator: "Alt+Right",+ click: () => {+ const contents = BrowserWindow.getFocusedWindow()?.webContents;+ if (contents?.navigationHistory.canGoForward()) contents.navigationHistory.goForward();+ },+ },{ role: "reload" },{ role: "forceReload" },{ role: "toggleDevTools" },diff --git a/desktop/package-lock.json b/desktop/package-lock.jsonindex 282a5a214..805f3eed9 100644--- a/desktop/package-lock.json+++ b/desktop/package-lock.json@@ -9,7 +9,212 @@"version": "0.1.0","devDependencies": {"@electron/packager": "20.3.0",- "electron": "44.4.3"+ "electron": "44.4.3",+ "jsdom": "^29.1.1"+ }+ },+ "node_modules/@asamuzakjp/css-color": {+ "version": "5.1.11",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@csstools/css-calc": "^3.2.0",+ "@csstools/css-color-parser": "^4.1.0",+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/dom-selector": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@asamuzakjp/nwsapi": "^2.3.9",+ "bidi-js": "^1.0.3",+ "css-tree": "^3.2.1",+ "is-potential-custom-element-name": "^1.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/generational-cache": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/nwsapi": {+ "version": "2.3.9",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },+ "node_modules/@csstools/color-helpers": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.1.tgz",+ "integrity": "sha512-gLNsunvwf3mCi5u5o46/Z/JcJMnhbHSaZ69rkgPzNM3J4s8hWwpPUQB6/tt0EDFyCiWzxANlx+2LJwpYj4zS1w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.0.tgz",+ "integrity": "sha512-XQKj5B7QiZcHiegCOCAzcAOJdhGgWOHbbu62h5e5mkHnn8lWcfiJhllkqWmxu5zWR9jucPHuo1iTB56P033hcg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.3.tgz",+ "integrity": "sha512-y4LpL+lmpuyKDiEFq2PnZUVFdAjsoB/qQJod79yLNokXyW7jewi+/WJ69EfItj8A2unWtxXnGjw6LYXgXu5ZjA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.1.1",+ "@csstools/css-calc": "^3.4.0"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.14",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.14.tgz",+ "integrity": "sha512-HpbVXyrofRXpHpgkNIjU/3EWR4WJvOkO3emNK/L6X/mTJU7bGUI3AkkpoTNXznQLp0KRjLHELTGeKI5dIkI9JQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.1.tgz",+ "integrity": "sha512-bPlN9S9O1A0euCpEWE4qnvB5YDuyYVsUTrxSgmAM1Is0j4tICHoVyOVAXfWMP/kS9ZrjvyIXWV2PmomiAXXqOw==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"}},"node_modules/@electron-internal/extract-zip": {@@ -162,6 +367,24 @@"node": ">=22.12.0"}},+ "node_modules/@exodus/bytes": {+ "version": "1.16.0",+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",+ "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ },+ "peerDependencies": {+ "@noble/hashes": "^1.8.0 || ^2.0.0"+ },+ "peerDependenciesMeta": {+ "@noble/hashes": {+ "optional": true+ }+ }+ },"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",@@ -236,6 +459,16 @@],"license": "MIT"},+ "node_modules/bidi-js": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",+ "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "require-from-string": "^2.0.2"+ }+ },"node_modules/brace-expansion": {"version": "5.0.12","resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",@@ -274,6 +507,34 @@"node": ">= 8"}},+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },+ "node_modules/data-urls": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -292,6 +553,13 @@}}},+ "node_modules/decimal.js": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/electron": {"version": "44.4.3","resolved": "https://registry.npmjs.org/electron/-/electron-44.4.3.tgz",@@ -311,6 +579,19 @@"node": ">= 22.12.0"}},+ "node_modules/entities": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",+ "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20.19.0"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/env-paths": {"version": "3.0.0","resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",@@ -412,6 +693,26 @@"dev": true,"license": "ISC"},+ "node_modules/html-encoding-sniffer": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.6.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/is-potential-custom-element-name": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/isbinaryfile": {"version": "4.0.10","resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",@@ -432,6 +733,47 @@"dev": true,"license": "ISC"},+ "node_modules/jsdom": {+ "version": "29.1.1",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^5.1.11",+ "@asamuzakjp/dom-selector": "^7.1.1",+ "@bramus/specificity": "^2.4.2",+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",+ "@exodus/bytes": "^1.15.0",+ "css-tree": "^3.2.1",+ "data-urls": "^7.0.0",+ "decimal.js": "^10.6.0",+ "html-encoding-sniffer": "^6.0.0",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.3.5",+ "parse5": "^8.0.1",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^6.0.1",+ "undici": "^7.25.0",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^8.0.1",+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.1",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },"node_modules/junk": {"version": "4.0.1","resolved": "https://registry.npmjs.org/junk/-/junk-4.0.1.tgz",@@ -455,6 +797,13 @@"node": "20 || >=22"}},+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },"node_modules/minimatch": {"version": "10.2.6","resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",@@ -488,6 +837,19 @@"dev": true,"license": "MIT"},+ "node_modules/parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^8.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },"node_modules/path-key": {"version": "3.1.1","resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",@@ -585,6 +947,26 @@"node": ">=10"}},+ "node_modules/punycode": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/resedit": {"version": "2.0.3","resolved": "https://registry.npmjs.org/resedit/-/resedit-2.0.3.tgz",@@ -613,6 +995,19 @@"node": ">= 4"}},+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },"node_modules/semver": {"version": "7.8.5","resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",@@ -649,6 +1044,16 @@"node": ">=8"}},+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/sumchecker": {"version": "3.0.1","resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",@@ -662,13 +1067,65 @@"node": ">= 8.0"}},+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tldts": {+ "version": "7.4.14",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.14.tgz",+ "integrity": "sha512-EahQoi+Q5oqmG3yxRHx+bwn36OaLbtw6jnTFcGjc8fcmktzTgk45xRnzAx8Ch87PFEiqRhoc3FWBmY+LBrvEGQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^7.4.14"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "7.4.14",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.14.tgz",+ "integrity": "sha512-KYkjfJHnIC5t+Gy7hPrMHgJmWc/N9FfmS+fggRPSlpFckidpB9HD6OzPsSTkfDH+MpZgcu2tJPGgLfHl979N1Q==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tough-cookie": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^7.0.5"+ },+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },"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"}@@ -680,6 +1137,54 @@"dev": true,"license": "MIT"},+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/webidl-conversions": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-mimetype": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/which": {"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",@@ -696,6 +1201,16 @@"node": ">= 8"}},+ "node_modules/xml-name-validator": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/xmlbuilder": {"version": "15.1.1","resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",@@ -706,6 +1221,13 @@"node": ">=8.0"}},+ "node_modules/xmlchars": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/yargs-parser": {"version": "22.0.0","resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",diff --git a/desktop/package.json b/desktop/package.jsonindex 4c8fc604a..11d599a4b 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -8,10 +8,13 @@"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)'"+ "package": "node package.mjs",+ "package:release": "node package.mjs --release",+ "test:electron": "electron test/navigation.electron.mjs"},"devDependencies": {+ "@electron/packager": "20.3.0","electron": "44.4.3",- "@electron/packager": "20.3.0"+ "jsdom": "^29.1.1"}}diff --git a/desktop/package.mjs b/desktop/package.mjsnew file mode 100644index 000000000..2e62735fd--- /dev/null+++ b/desktop/package.mjs@@ -0,0 +1,24 @@+import { packager } from "@electron/packager";+import path from "node:path";+import { fileURLToPath } from "node:url";++const directory = path.dirname(fileURLToPath(import.meta.url));+const release = process.argv.includes("--release");+const identity = process.env.QM_MAC_SIGN_IDENTITY;+const keychainProfile = process.env.QM_MAC_NOTARY_PROFILE;+if (release && (process.platform !== "darwin" || !identity || !keychainProfile)) {+ throw new Error("Mac releases require macOS, QM_MAC_SIGN_IDENTITY and QM_MAC_NOTARY_PROFILE.");+}+const apps = await packager({+ dir: directory,+ name: "QM",+ appBundleId: "com.qm.desktop",+ protocols: [{ name: "QM", schemes: ["qm-desktop"] }],+ icon: path.join(directory, "assets/qm"),+ out: path.join(directory, "dist"),+ overwrite: true,+ asar: true,+ ignore: /^\/(dist|test|README\.md|package\.mjs)/,+ ...(release ? { osxSign: { identity }, osxNotarize: { keychainProfile } } : {}),+});+for (const app of apps) console.log(app);diff --git a/desktop/test/login.test.mjs b/desktop/test/login.test.mjsindex 7ae025b58..09e9944c6 100644--- a/desktop/test/login.test.mjs+++ b/desktop/test/login.test.mjs@@ -31,3 +31,20 @@ test("only a callback for the current unexpired attempt is accepted", () => {])assert.equal(loginCallback(invalid, pending, 2000), null);});++test("explicit provider choice wraps the proof request without leaking the destination", () => {+ for (const route of ["/auth/trusted/login", "/auth/login?provider=primary"]) {+ const attempt = createLogin("https://qm.example.com/drop/test?t=private", 1000, `https://qm.example.com${route}`);+ const url = new URL(attempt.url);+ const request = new URL(url.searchParams.get("returnTo"), url);+ assert.equal(url.pathname, route.split("?")[0]);+ assert.equal(request.pathname, "/auth/desktop");+ assert.equal(request.searchParams.get("state"), attempt.state);+ assert.equal(attempt.url.includes("private"), false);+ assert.equal(attempt.url.includes(attempt.verifier), false);+ }+ assert.equal(+ new URL(createLogin("https://qm.example.com", 1000, "https://evil.example/auth/trusted/login").url).pathname,+ "/auth/desktop",+ );+});diff --git a/desktop/test/main.test.mjs b/desktop/test/main.test.mjsindex 6974e9303..38200c5e9 100644--- a/desktop/test/main.test.mjs+++ b/desktop/test/main.test.mjs@@ -44,6 +44,7 @@ test(this.options = options;this.webContents = Object.assign(new EventEmitter(), {session,+ getURL: () => this.url,send() {},setWindowOpenHandler: (handler) => {this.popup = handler;@@ -93,6 +94,24 @@ test(await import("../main.mjs");await initialLoad.promise;assert.equal(windows[0].url, "https://old.example/");+ for (const destination of ["about:blank", "https://old.example/file.pdf", "blob:https://old.example/id"]) {+ const popup = windows[0].popup({ url: destination });+ assert.equal(popup.action, "allow");+ assert.equal(popup.overrideBrowserWindowOptions.webPreferences.sandbox, true);+ assert.equal(popup.overrideBrowserWindowOptions.webPreferences.nodeIntegration, false);+ assert.equal(popup.overrideBrowserWindowOptions.webPreferences.preload.endsWith("workspace-preload.cjs"), true);+ }+ assert.equal(windows[0].url, "https://old.example/");+ assert.deepEqual(windows[0].popup({ url: "file:///tmp/private" }), { action: "deny" });+ assert.equal(opened.length, 0);+ const frame = { url: "https://old.example/" };+ windows[0].webContents.mainFrame = frame;+ const browserEvent = { sender: windows[0].webContents, senderFrame: frame };+ await assert.rejects(handlers.get("qm:open-browser")(browserEvent, "https://evil.example/"));+ await assert.rejects(+ handlers.get("qm:open-browser")({ ...browserEvent, senderFrame: { url: frame.url } }, "/settings"),+ );+ await assert.rejects(handlers.get("qm:open-browser")(browserEvent, "https://user:[email protected]/"));let prevented = false;windows[0].webContents.emit("will-redirect",@@ -105,8 +124,16 @@ test();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")}`;+ assert.equal(windows[0].isDestroyed(), true);+ windows[0].webContents.emit("will-redirect", { preventDefault() {} }, "https://old.example/auth/login");+ assert.equal(opened.length, 1);+ const callback = (index) => {+ const browser = new URL(opened[index]);+ const request = browser.searchParams.has("returnTo")+ ? new URL(browser.searchParams.get("returnTo"), browser)+ : browser;+ return `qm-desktop://auth/callback?code=test-code&state=${request.searchParams.get("state")}`;+ };const event = { preventDefault() {} };app.emit("open-url", event, callback(0));app.emit("open-url", event, callback(0));@@ -127,7 +154,12 @@ test(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.deepEqual(+ windows[2].popup({+ url: "https://new.example/auth/trusted/login?returnTo=%2Fdrop%2Ftest%2Fform%3Ft%3Dtest-token",+ }),+ { action: "deny" },+ );assert.equal(opened.length, 2);app.emit("open-url", event, callback(1));assert.equal(requests.length, 2);@@ -135,8 +167,33 @@ test(requests[1].resolve({ ok: true });await tick();assert.equal(flushes, 1);- assert.equal(windows.at(-1).url, "https://new.example/");+ assert.equal(windows.at(-1).url, "https://new.example/drop/test/form?t=test-token");+ assert.equal(new URL(opened[1]).pathname, "/auth/trusted/login");+ assert.equal(opened[1].includes("test-token"), false);assert.equal(windows[3].isDestroyed(), true);+ const active = windows.at(-1);+ const child = new BrowserWindow({});+ child.url = "https://new.example/file.pdf";+ active.webContents.emit("did-create-window", child);+ let blockedChild = false;+ child.webContents.emit(+ "will-navigate",+ {+ preventDefault() {+ blockedChild = true;+ },+ },+ "file:///tmp/private",+ );+ assert.equal(blockedChild, true);+ assert.equal(active.isDestroyed(), false);+ active.webContents.emit("will-redirect", { preventDefault() {} }, "https://new.example/auth/login");+ assert.equal(child.isDestroyed(), true);+ const cancelled = windows.at(-1);+ cancelled.close();+ app.emit("open-url", event, callback(2));+ await tick();+ assert.equal(requests.length, 2);assert.deepEqual(errors, []);} finally {if (original === undefined) delete process.env.QM_DESKTOP_URL;diff --git a/desktop/test/navigation.electron.mjs b/desktop/test/navigation.electron.mjsnew file mode 100644index 000000000..6c4f3cd47--- /dev/null+++ b/desktop/test/navigation.electron.mjs@@ -0,0 +1,88 @@+import assert from "node:assert/strict";+import { mkdtemp, rm } from "node:fs/promises";+import { createServer } from "node:http";+import { tmpdir } from "node:os";+import path from "node:path";+import { app, BrowserWindow, shell } from "electron";+const tick = () => new Promise((resolve) => setTimeout(resolve, 25));+async function waitFor(read) {+ for (let i = 0; i < 200; i++) {+ const result = await read();+ if (result) return result;+ await tick();+ }+ throw new Error("Timed out waiting for desktop navigation");+}+(async () => {+ const directory = await mkdtemp(path.join(tmpdir(), "qm-navigation-"));+ app.setPath("userData", directory);+ app.setPath("sessionData", directory);+ const opened = [];+ shell.openExternal = async (url) => {+ opened.push(url);+ };+ const server = createServer((req, res) => {+ res.setHeader("content-type", "text/html");+ if (req.url === "/") res.setHeader("set-cookie", "qm_navigation_test=yes; Path=/; HttpOnly");+ res.end(+ `<title>Navigation fixture</title><main>${req.method}:${req.headers.cookie?.includes("qm_navigation_test=yes") ? "session" : "initial"}</main>`,+ );+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ const origin = `http://127.0.0.1:${server.address().port}`;+ process.env.QM_DESKTOP_URL = origin;+ try {+ await import("../main.mjs");+ const main = await waitFor(() =>+ BrowserWindow.getAllWindows().find((w) => w.webContents.getURL() === origin + "/"),+ );+ await waitFor(() => main.webContents.executeJavaScript("!!window.qmDesktop"));+ await main.webContents.executeJavaScript('window.open("/preview", "_blank"); void 0');+ const preview = await waitFor(() =>+ BrowserWindow.getAllWindows().find((w) => w !== main && w.webContents.getURL() === origin + "/preview"),+ );+ assert.equal(+ await preview.webContents.executeJavaScript('document.querySelector("main").textContent'),+ "GET:session",+ );+ assert.equal(main.webContents.getURL(), origin + "/");+ assert.equal(await preview.webContents.executeJavaScript("typeof require"), "undefined");+ assert.equal(preview.webContents.getLastWebPreferences().sandbox, true);+ await main.webContents.executeJavaScript(+ 'window.open(URL.createObjectURL(new Blob(["<title>Blob preview</title>"], {type:"text/html"})), "_blank"); void 0',+ );+ await waitFor(() => BrowserWindow.getAllWindows().find((w) => w.webContents.getURL().startsWith("blob:")));+ await main.webContents.executeJavaScript(+ 'const p=window.open("", "_blank"); const form=p.document.createElement("form"); form.method="POST"; form.action="' ++ origin ++ '/posted"; p.document.body.append(form); form.submit(); void 0',+ );+ const posted = await waitFor(() =>+ BrowserWindow.getAllWindows().find((w) => w.webContents.getURL() === origin + "/posted"),+ );+ assert.equal(+ await posted.webContents.executeJavaScript('document.querySelector("main").textContent'),+ "POST:session",+ );+ await main.webContents.executeJavaScript('window.qmDesktop.openBrowser("/settings")');+ assert.deepEqual(opened, [origin + "/settings"]);+ const refused = await main.webContents.executeJavaScript(+ 'window.qmDesktop.openBrowser("https://evil.example/").then(()=>false,()=>true)',+ );+ assert.equal(refused, true);+ assert.equal(opened.length, 1);+ main.destroy();+ assert.equal(BrowserWindow.getAllWindows().length, 0);+ console.log(+ "PASS: separate previews, cookie isolation, blob URLs, blank POST popups, sandbox, browser bridge and child cleanup",+ );+ } finally {+ for (const window of BrowserWindow.getAllWindows()) window.destroy();+ await new Promise((resolve) => server.close(resolve));+ await rm(directory, { recursive: true, force: true });+ app.quit();+ }+})().catch((error) => {+ console.error(error);+ app.exit(1);+});diff --git a/desktop/test/screenshots/admin.png b/desktop/test/screenshots/admin.pngnew file mode 100644index 000000000..08543fed9Binary files /dev/null and b/desktop/test/screenshots/admin.png differdiff --git a/desktop/test/screenshots/settings.png b/desktop/test/screenshots/settings.pngnew file mode 100644index 000000000..bdecd26dcBinary files /dev/null and b/desktop/test/screenshots/settings.png differdiff --git a/desktop/test/url.test.mjs b/desktop/test/url.test.mjsindex 3f1b99d62..e4736d048 100644--- a/desktop/test/url.test.mjs+++ b/desktop/test/url.test.mjs@@ -1,6 +1,6 @@import assert from "node:assert/strict";import { test } from "node:test";-import { instanceUrl, externalUrl, browserLoginUrl } from "../url.mjs";+import { instanceUrl, externalUrl, browserLoginUrl, loginDestination, internalUrl } from "../url.mjs";test("accepts secure deployments and explicit loopback development URLs", () => {for (const url of [@@ -52,3 +52,74 @@ test("browser sign-in only intercepts exact same-origin auth route families", ()])assert.equal(browserLoginUrl(value, origin), false);});++test("desktop login preserves same-origin return destinations", () => {+ const instance = "https://qm.example.com/s/current";+ const drop = "/drop/example/form?t=test-token&other=value";+ const login = `https://qm.example.com/auth/login?returnTo=${encodeURIComponent(drop)}`;+ assert.equal(loginDestination(login, instance), `https://qm.example.com${drop}`);+ assert.equal(+ loginDestination(login.replace("/auth/login", "/auth/trusted/login"), instance),+ `https://qm.example.com${drop}`,+ );+ assert.equal(loginDestination("https://qm.example.com/auth/login", instance), instance);+ assert.equal(+ loginDestination("https://qm.example.com/auth/login", "https://qm.example.com/auth/login"),+ "https://qm.example.com/",+ );+});++test("desktop login never resumes off-origin, credential-bearing or auth destinations", () => {+ const instance = "https://qm.example.com/s/current";+ for (const target of [+ "https://evil.example/drop",+ "//evil.example/drop",+ "https://user:[email protected]/drop",+ "javascript:alert(1)",+ "file:///tmp/key",+ "blob:https://qm.example.com/id",+ "/auth/login",+ "/auth/desktop/redeem",+ ]) {+ assert.equal(+ loginDestination(`https://qm.example.com/auth/login?returnTo=${encodeURIComponent(target)}`, instance),+ instance,+ );+ }+ assert.equal(loginDestination("https://evil.example/auth/login?returnTo=/drop/example", instance), instance);+});++test("initial blank or failed pages cannot change the trusted instance origin", () => {+ const instance = "https://qm.example.com/";+ const login = "https://qm.example.com/auth/login?returnTo=%2Fdrop%2Ftest%2Fform";+ for (const current of [+ "",+ "about:blank",+ "chrome-error://chromewebdata/",+ "https://other.example/page",+ "blob:https://qm.example.com/id",+ ]) {+ assert.equal(loginDestination(login, instance, current), "https://qm.example.com/drop/test/form");+ assert.equal(loginDestination("https://qm.example.com/auth/login", instance, current), instance);+ }+ assert.equal(+ loginDestination("https://qm.example.com/auth/login", instance, "https://qm.example.com/s/current"),+ "https://qm.example.com/s/current",+ );+});++test("auxiliary pages allow only blank or the trusted instance including its blobs", () => {+ const origin = "https://qm.example.com";+ for (const url of ["about:blank", `${origin}/file.pdf`, `blob:${origin}/file`])+ assert.equal(internalUrl(url, origin), true);+ for (const url of [+ "file:///tmp/private",+ "data:text/html,hi",+ "https://other.example/",+ "blob:https://other.example/file",+ "https://user:[email protected]/",+ "invalid",+ ])+ assert.equal(internalUrl(url, origin), false);+ assert.equal(externalUrl("tel:+15551234567"), true);+});diff --git a/desktop/test/workspace.test.mjs b/desktop/test/workspace.test.mjsnew file mode 100644index 000000000..f45f4a25d--- /dev/null+++ b/desktop/test/workspace.test.mjs@@ -0,0 +1,147 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import { test } from "node:test";+import { JSDOM } from "jsdom";++const preload = await readFile(new URL("../workspace-preload.cjs", import.meta.url), "utf8");++async function workspace(platform = "darwin") {+ const dom = new JSDOM('<div id="sidebar-body"></div><textarea></textarea>', { runScripts: "outside-only" });+ const { window } = dom;+ window.process = { platform };+ window.require = () => ({ contextBridge: { exposeInMainWorld() {} }, ipcRenderer: { invoke() {} } });+ window.HTMLElement.prototype.checkVisibility = function () {+ return !this.closest("[hidden], .collapsed, .sidebar-closed");+ };+ await new Promise((resolve) => window.addEventListener("DOMContentLoaded", resolve));+ window.eval(preload);+ window.dispatchEvent(new window.Event("DOMContentLoaded"));+ const list = window.document.querySelector("#sidebar-body");+ const opened = [];+ const add = (id, hidden = false) => {+ const row = window.document.createElement("div");+ row.className = "session-row";+ row.dataset.sessionId = id;+ row.hidden = hidden;+ row.innerHTML = `<a class="session" href="/s/${id}">Session ${id}</a>`;+ row.firstChild.addEventListener("click", (event) => {+ event.preventDefault();+ opened.push(id);+ });+ list.append(row);+ return row;+ };+ const key = (key, options = {}, type = "keydown") => {+ const event = new window.KeyboardEvent(type, { key, bubbles: true, cancelable: true, ...options });+ window.document.querySelector("textarea").dispatchEvent(event);+ return event;+ };+ return {+ window,+ list,+ opened,+ add,+ key,+ close: () => {+ window.dispatchEvent(new window.Event("blur"));+ window.close();+ },+ };+}++test("Command shortcuts match expanded sidebar order, exclude hidden and duplicate sessions, and stop at nine", async () => {+ const app = await workspace();+ try {+ app.add("hidden", true);+ app.add("first");+ app.add("first");+ for (let i = 2; i <= 11; i++) app.add(String(i));+ app.key("Meta", { metaKey: true });+ const hints = [...app.list.querySelectorAll("[data-qm-shortcut]")];+ assert.equal(hints.length, 9);+ assert.equal(hints[0].textContent, "Session first");+ assert.equal(hints[8].dataset.qmShortcut, "⌘9");+ assert.equal(app.key("2", { metaKey: true }).defaultPrevented, true);+ assert.deepEqual(app.opened, ["2"]);+ app.key("2", { metaKey: true, repeat: true });+ assert.deepEqual(app.opened, ["2"]);+ assert.equal(app.key("0", { metaKey: true }).defaultPrevented, false);+ app.key("Meta", {}, "keyup");+ assert.equal(app.window.document.documentElement.hasAttribute("data-qm-shortcuts"), false);+ } finally {+ app.close();+ }+});++test("hints follow reordered and removed rows while Command is held and clear on blur", async () => {+ const app = await workspace();+ try {+ const first = app.add("first");+ const second = app.add("second");+ app.key("Meta", { metaKey: true });+ app.list.prepend(second);+ await Promise.resolve();+ assert.equal(second.firstChild.dataset.qmShortcut, "⌘1");+ first.remove();+ await Promise.resolve();+ assert.equal(first.firstChild.hasAttribute("data-qm-shortcut"), false);+ app.key("1", { metaKey: true });+ assert.deepEqual(app.opened, ["second"]);+ app.window.dispatchEvent(new app.window.Event("blur"));+ assert.equal(app.window.document.documentElement.hasAttribute("data-qm-shortcuts"), false);+ } finally {+ app.close();+ }+});++test("modal dialogs, hidden sidebar, composition and extra modifiers do not switch sessions", async () => {+ const app = await workspace();+ try {+ app.add("first");+ for (const options of [{ shiftKey: true }, { altKey: true }, { ctrlKey: true }, { isComposing: true }]) {+ assert.equal(app.key("1", { metaKey: true, ...options }).defaultPrevented, false);+ }+ app.list.classList.add("sidebar-closed");+ app.key("1", { metaKey: true });+ app.list.classList.remove("sidebar-closed");+ const dialog = app.window.document.createElement("dialog");+ dialog.open = true;+ app.window.document.body.append(dialog);+ app.key("1", { metaKey: true });+ assert.deepEqual(app.opened, []);+ } finally {+ app.close();+ }+});++test("non-Mac desktop uses Control without intercepting bare number keys", async () => {+ const app = await workspace("linux");+ try {+ const first = app.add("first");+ app.key("1");+ app.key("1", { metaKey: true });+ assert.deepEqual(app.opened, []);+ app.key("1", { ctrlKey: true });+ assert.deepEqual(app.opened, ["first"]);+ assert.equal(first.firstChild.dataset.qmShortcut, "Ctrl 1");+ } finally {+ app.close();+ }+});++test("the compact sidebar remains a shortcut target when it is an accessible modal drawer", async () => {+ const app = await workspace();+ try {+ const sidebar = app.window.document.createElement("aside");+ sidebar.className = "sidebar";+ sidebar.setAttribute("role", "dialog");+ sidebar.setAttribute("aria-modal", "true");+ app.list.replaceWith(sidebar);+ sidebar.append(app.list);+ app.add("first");+ app.key("1", { metaKey: true });+ assert.deepEqual(app.opened, ["first"]);+ } finally {+ app.close();+ }+});diff --git a/desktop/url.mjs b/desktop/url.mjsindex 622264630..d5663e08a 100644--- a/desktop/url.mjs+++ b/desktop/url.mjs@@ -11,7 +11,7 @@ export function instanceUrl(value) {export function externalUrl(value) {try {const url = new URL(value);- return ["https:", "http:", "mailto:"].includes(url.protocol) && !url.username && !url.password;+ return ["https:", "http:", "mailto:", "tel:"].includes(url.protocol) && !url.username && !url.password;} catch {return false;}@@ -21,3 +21,46 @@ export function browserLoginUrl(value, origin) {const url = new URL(value);return url.origin === origin && /^\/auth\/(login|trusted\/login)(?:\/|$)/.test(url.pathname);}++export function loginDestination(value, instance, current = instance) {+ const base = new URL(instance);+ const page = new URL(current || instance);+ const safePage =+ ["https:", "http:"].includes(page.protocol) &&+ page.origin === base.origin &&+ !page.username &&+ !page.password &&+ !page.pathname.startsWith("/auth/");+ let fallback = base.pathname.startsWith("/auth/") ? new URL("/", base).href : base.href;+ if (safePage) fallback = page.href;+ try {+ const login = new URL(value);+ if (!browserLoginUrl(login.href, base.origin)) return fallback;+ const returnTo = login.searchParams.get("returnTo");+ if (!returnTo) return fallback;+ const destination = new URL(returnTo, base.origin);+ if (+ !["https:", "http:"].includes(destination.protocol) ||+ destination.origin !== base.origin ||+ destination.username ||+ destination.password ||+ destination.pathname.startsWith("/auth/")+ )+ return fallback;+ return destination.href;+ } catch {+ return fallback;+ }+}++export function internalUrl(value, origin) {+ if (value === "about:blank") return true;+ try {+ const url = new URL(value);+ return (+ url.origin === origin && !url.username && !url.password && ["https:", "http:", "blob:"].includes(url.protocol)+ );+ } catch {+ return false;+ }+}diff --git a/desktop/workspace-preload.cjs b/desktop/workspace-preload.cjsnew file mode 100644index 000000000..695f6a774--- /dev/null+++ b/desktop/workspace-preload.cjs@@ -0,0 +1,150 @@+const { contextBridge, ipcRenderer } = require("electron");++contextBridge.exposeInMainWorld("qmDesktop", {+ openBrowser: (url) => ipcRenderer.invoke("qm:open-browser", url),+});++window.addEventListener("DOMContentLoaded", () => {+ const root = document.documentElement;+ const mac = process.platform === "darwin";+ root.dataset.qmDesktop = process.platform;+ const style = document.createElement("style");+ style.textContent = `+ html[data-qm-desktop="darwin"] body { padding-top: 48px; }+ html[data-qm-desktop="darwin"] body::before {+ content: ""; position: fixed; inset: 0 0 auto; height: 48px;+ background: var(--background, #f5f4f0); z-index: 100;+ -webkit-app-region: drag;+ }+ html[data-qm-desktop="darwin"] .layout { height: calc(100dvh - 48px); }+ html[data-qm-desktop="darwin"] .layout.bannered {+ height: calc(100dvh - 86px - env(safe-area-inset-top));+ }+ html[data-qm-desktop="darwin"] .top-banner { top: 48px; }+ html[data-qm-desktop="darwin"] header.top { top: 48px; }+ html[data-qm-desktop="darwin"] #app-view #main .admin-inner { margin-inline: 0; }+ @media (min-width: 901px) {+ html[data-qm-desktop="darwin"]:has(.admin-app:not(.hidden)) body { padding-top: 0; }+ html[data-qm-desktop="darwin"]:has(.admin-app:not(.hidden)) body::before { display: none; }+ html[data-qm-desktop="darwin"]:has(.admin-app:not(.hidden)) header.top {+ top: 0; -webkit-app-region: drag;+ }+ html[data-qm-desktop="darwin"] .admin-sidebar { top: 0; height: 100dvh; }+ html[data-qm-desktop="darwin"] .admin-sidebar .brand {+ min-height: 56px; padding-left: 92px; -webkit-app-region: drag; user-select: none;+ }+ html[data-qm-desktop="darwin"] header.top :is(a, button, input, select) {+ -webkit-app-region: no-drag;+ }+ }+ @media (max-width: 900px) {+ html[data-qm-desktop="darwin"] .admin-sidebar { top: calc(48px + var(--header-total-h)); }+ }+ @media (max-width: 860px) {+ html[data-qm-desktop="darwin"] .layout { top: 48px; }+ }+ @media (min-width: 861px) {+ html[data-qm-desktop="darwin"]:has(.layout:not(.bannered)) body { padding-top: 0; }+ html[data-qm-desktop="darwin"]:has(.layout:not(.bannered)) body::before { display: none; }+ html[data-qm-desktop="darwin"] .layout:not(.bannered) { height: 100dvh; --rail-w: 100px; }+ html[data-qm-desktop="darwin"] .layout:not(.bannered) .sidebar { padding-top: 0; }+ html[data-qm-desktop="darwin"] .layout:not(.bannered) .brand {+ height: 56px; min-height: 56px; box-sizing: border-box; padding: 0 8px 0 92px;+ justify-content: flex-end; -webkit-app-region: drag; user-select: none;+ }+ html[data-qm-desktop="darwin"] .layout:not(.bannered) .brand-lockup { display: none; }+ html[data-qm-desktop="darwin"] .layout:not(.bannered).sidebar-closed .brand {+ height: 96px; min-height: 96px; padding: 48px 0 8px; justify-content: center;+ }+ html[data-qm-desktop="darwin"] .brand button { -webkit-app-region: no-drag; }+ html[data-qm-desktop="darwin"] .dv-tabs-and-actions-container,+ html[data-qm-desktop="darwin"] .chat-topbar { -webkit-app-region: drag; }+ html[data-qm-desktop="darwin"] .dv-tabs-and-actions-container :is(button, a, input, [role="tab"], .dv-tab),+ html[data-qm-desktop="darwin"] .chat-topbar :is(button, a, input, [role="tab"]) {+ -webkit-app-region: no-drag;+ }+ }+ html[data-qm-desktop="darwin"] .single-pane .dv-tabs-and-actions-container .dv-tab {+ -webkit-app-region: drag; user-select: none;+ }+ html[data-qm-desktop="darwin"] .single-pane .dv-tab :is(button, a, input) {+ -webkit-app-region: no-drag;+ }+ [data-qm-shortcut] { position: relative; }+ html[data-qm-shortcuts] [data-qm-shortcut] { padding-right: 48px !important; }+ [data-qm-shortcut]::after {+ content: attr(data-qm-shortcut); display: none; position: absolute; right: 7px;+ top: 50%; transform: translateY(-50%); min-width: 28px; height: 20px;+ align-items: center; justify-content: center; box-sizing: border-box;+ padding: 0 4px; border: 1px solid var(--border, #ddd); border-radius: 5px;+ background: var(--background, #f5f4f0); color: var(--muted-foreground, #777);+ font: 11px ui-sans-serif, system-ui, sans-serif; font-variant-numeric: tabular-nums;+ pointer-events: none;+ }+ html[data-qm-shortcuts] [data-qm-shortcut]::after { display: flex; }+ html[data-qm-shortcuts] .session-row:has([data-qm-shortcut]) .session-menu { visibility: hidden; }+ `;+ document.head.append(style);+ let links = [];+ let held = false;+ const clear = () => {+ held = false;+ delete root.dataset.qmShortcuts;+ };+ const refresh = () => {+ for (const link of links) delete link.dataset.qmShortcut;+ const seen = new Set();+ links = [...document.querySelectorAll("#sidebar-body .session-row[data-session-id] > a.session[href]")]+ .filter((link) => {+ const id = link.parentElement.dataset.sessionId;+ if (seen.has(id) || !link.checkVisibility({ checkVisibilityCSS: true })) return false;+ seen.add(id);+ return true;+ })+ .slice(0, 9);+ links.forEach((link, index) => {+ link.dataset.qmShortcut = `${mac ? "⌘" : "Ctrl "}${index + 1}`;+ });+ };+ window.addEventListener(+ "keydown",+ (event) => {+ const modifier = mac ? event.metaKey : event.ctrlKey;+ if (!modifier || event.altKey || event.shiftKey || (mac && event.ctrlKey) || (!mac && event.metaKey)) {+ clear();+ return;+ }+ if (event.isComposing || document.querySelector('dialog[open], [aria-modal="true"]:not(.sidebar)')) {+ clear();+ return;+ }+ refresh();+ held = true;+ root.dataset.qmShortcuts = "";+ const index = /^[1-9]$/.test(event.key) ? Number(event.key) - 1 : -1;+ const link = links[index];+ if (!link) return;+ event.preventDefault();+ event.stopImmediatePropagation();+ if (!event.repeat) link.click();+ },+ true,+ );+ window.addEventListener(+ "keyup",+ (event) => {+ if (!(mac ? event.metaKey : event.ctrlKey)) clear();+ },+ true,+ );+ window.addEventListener("blur", clear);+ document.addEventListener("visibilitychange", clear);+ new MutationObserver(() => {+ if (held) refresh();+ }).observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ["class", "style", "hidden"],+ });+});diff --git a/eslint.config.mjs b/eslint.config.mjsindex 1fffaec40..bf6901fbf 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -20,11 +20,11 @@ export default tseslint.config(js.configs.recommended,tseslint.configs.recommended,{- files: ["desktop/preload.cjs"],+ files: ["desktop/preload.cjs", "desktop/workspace-preload.cjs"],rules: { "@typescript-eslint/no-require-imports": "off" },},{- files: ["desktop/setup.js"],+ files: ["desktop/setup.js", "desktop/workspace-preload.cjs"],languageOptions: { globals: globals.browser },},{diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex a99ace36d..c838bc4fa 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -7924,6 +7924,10 @@const FOCUS_REFRESH_EXEMPT = new Set(["governance", "connectors", "slack-settings", "user"]);window.addEventListener("focus", () => {if ($("app-view").classList.contains("hidden")) return;+ if (view === "slack-settings") {+ void loadSlackInstallation();+ return;+ }if (isGovLike(view) || FOCUS_REFRESH_EXEMPT.has(view)) return;if (Date.now() - (viewLoadedAt[view] || 0) < FOCUS_STALE_MS) return;if (view === "memory" && !(orgWideView() && urlToState().mem !== "edit")) return;diff --git a/plugins/admin/ui/integrations-state.ts b/plugins/admin/ui/integrations-state.tsindex 271d2d163..f18ab6184 100644--- a/plugins/admin/ui/integrations-state.ts+++ b/plugins/admin/ui/integrations-state.ts@@ -1,3 +1,4 @@+import { openDesktopBrowser } from "../../chassis/src/desktop-browser.ts";import { SettingState, settingRegistry } from "./setting-state.ts";export type Api = (method: string,@@ -240,6 +241,9 @@ export class SlackInstallationState {this.busy = "start";this.render();try {+ const browser = new URL(location.href);+ browser.searchParams.set("slack", step);+ if (await openDesktopBrowser(browser.href)) return;const result = await context.api("POST", "/api/slack-installation/start", { step });if (result.ok && result.data.url) {const form = document.createElement("form");@@ -248,6 +252,8 @@ export class SlackInstallationState {document.body.appendChild(form);form.submit();} else this.setStatus("Could not start Slack installation. Please try again.", "err");+ } catch {+ this.setStatus("Could not start Slack installation. Please try again.", "err");} finally {this.busy = "";this.render();diff --git a/plugins/chassis/src/desktop-browser.ts b/plugins/chassis/src/desktop-browser.tsnew file mode 100644index 000000000..4c7832cae--- /dev/null+++ b/plugins/chassis/src/desktop-browser.ts@@ -0,0 +1,7 @@+export async function openDesktopBrowser(url: string): Promise<boolean> {+ const bridge = (globalThis as { window?: { qmDesktop?: { openBrowser: (url: string) => Promise<void> } } }).window+ ?.qmDesktop;+ if (!bridge) return false;+ await bridge.openBrowser(url);+ return true;+}diff --git a/plugins/portal/src/desktop-login.ts b/plugins/portal/src/desktop-login.tsindex 2de1d55b0..5baf7aea1 100644--- a/plugins/portal/src/desktop-login.ts+++ b/plugins/portal/src/desktop-login.ts@@ -1,6 +1,9 @@import { createHash } from "node:crypto";import { deriveKey, open, randomToken, safeEqual, seal, type SessionClaims } from "./session.ts";+export const DESKTOP_LAUNCH_SCRIPT = `window.location.href = document.getElementById("desktop-launch").href;`;+export const DESKTOP_LAUNCH_SCRIPT_HASH = `sha256-${createHash("sha256").update(DESKTOP_LAUNCH_SCRIPT).digest("base64")}`;+export function desktopChallenge(value: string): boolean {return /^[A-Za-z0-9_-]{43}$/.test(value);}diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 1ecc3baf2..25a92f974 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -1,4 +1,10 @@-import { desktopChallenge, mintDesktopLogin, openDesktopLogin } from "./desktop-login.ts";+import {+ DESKTOP_LAUNCH_SCRIPT,+ DESKTOP_LAUNCH_SCRIPT_HASH,+ 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";@@ -1419,12 +1425,13 @@ async function desktopLogin(req: IncomingMessage, res: ServerResponse, url: URL)200,cardPage({title: "Ready to open QM",- heading: "Your desktop sign-in is ready",+ heading: "Opening QM Desktop…",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>`,+ msg: "If QM doesn’t open automatically, use the button below.",+ actions: `<a id="desktop-launch" class="btn primary" href="${escapeHtml(callback.href)}">Open QM Desktop</a><script>${DESKTOP_LAUNCH_SCRIPT}</script>`,help: "This link expires in two minutes and works only for the app that requested it.",}),+ `${PAGE_CSP}; script-src '${DESKTOP_LAUNCH_SCRIPT_HASH}'`,);}diff --git a/plugins/portal/test/desktop-login.test.ts b/plugins/portal/test/desktop-login.test.tsindex 3b19c6a5f..2abd1bd6f 100644--- a/plugins/portal/test/desktop-login.test.ts+++ b/plugins/portal/test/desktop-login.test.ts@@ -3,6 +3,7 @@ import assert from "node:assert/strict";import { createHash, randomBytes } from "node:crypto";import { createServer } from "node:http";import type { AddressInfo } from "node:net";+import { runInNewContext } from "node:vm";import { mintDesktopLogin, openDesktopLogin } from "../src/desktop-login.ts";import { deriveKey, openSession, seal, type SessionClaims } from "../src/session.ts";@@ -101,6 +102,29 @@ test("GET requires explicit confirmation and cannot mint a code", async () => {assert.equal(response.headers.get("cache-control"), "no-store");});+test("confirmed sign-in launches the app with a CSP-authorized script and retains the fallback link", async () => {+ const response = await fetch(`${base}${requestPath}`, { method: "POST", headers: { origin, cookie } });+ const html = await response.text();+ const callback = html.match(/id="desktop-launch"[^>]+href="([^"]+)"/)?.[1]?.replaceAll("&", "&");+ const script = html.match(/<script>([\s\S]*?)<\/script>/i)?.[1];+ assert.ok(callback?.startsWith("qm-desktop://auth/callback?"));+ assert.ok(script);+ const hash = createHash("sha256").update(script).digest("base64");+ assert.ok(response.headers.get("content-security-policy")?.includes(`script-src 'sha256-${hash}'`));+ const location = { href: "" };+ runInNewContext(script, {+ window: { location },+ document: {+ getElementById: (id: string) => {+ assert.equal(id, "desktop-launch");+ return { href: callback };+ },+ },+ });+ assert.equal(location.href, callback);+ 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",diff --git a/plugins/web-ui/src/onboarding-slack.ts b/plugins/web-ui/src/onboarding-slack.tsindex 64c72836d..1350a7619 100644--- a/plugins/web-ui/src/onboarding-slack.ts+++ b/plugins/web-ui/src/onboarding-slack.ts@@ -1,3 +1,4 @@+import { openDesktopBrowser } from "../../chassis/src/desktop-browser";import "./slack-account.css";import { LitElement, html, nothing } from "lit";import { ArrowUpRight, Check } from "lucide";@@ -79,6 +80,16 @@ export class OnboardingSlack extends LitElement {private async install(): Promise<void> {if (this.busy || this.installAvailable === undefined) return;+ try {+ if (await openDesktopBrowser(`${this.adminBase}/slack-settings?slack=install`)) {+ this.pollUntil = Date.now() + 10 * 60_000;+ void this.refresh();+ return;+ }+ } catch {+ this.error = "Could not open your browser. Please try again.";+ return;+ }const popup = window.open("", "_blank");if (!popup) {this.error = "Allow a new tab to install QM, then try again.";diff --git a/plugins/web-ui/src/onboarding-welcome.ts b/plugins/web-ui/src/onboarding-welcome.tsindex 439eb5fd6..18d862793 100644--- a/plugins/web-ui/src/onboarding-welcome.ts+++ b/plugins/web-ui/src/onboarding-welcome.ts@@ -1,3 +1,4 @@+import { openDesktopBrowser } from "../../chassis/src/desktop-browser";import {isConnectionReturn,takeConnectionReturn,@@ -317,6 +318,7 @@ export class OnboardingWelcome extends LitElement {this.authorizing = service.name;this.authorizationError = "";try {+ if (await openDesktopBrowser(`${this.base}settings`)) return;const state = crypto.randomUUID();const attempt: ConnectionAttempt = {state,diff --git a/plugins/web-ui/src/settings.ts b/plugins/web-ui/src/settings.tsindex 7e6e69324..af80b1fd8 100644--- a/plugins/web-ui/src/settings.ts+++ b/plugins/web-ui/src/settings.ts@@ -1,6 +1,7 @@+import "./onboarding-welcome";import "./slack-account";import { openModelConnectManager, type StatusResponse } from "./model-connect";-import { api } from "./core-bridge";+import { api, withBase } from "./core-bridge";import { html, nothing, render, type TemplateResult } from "lit";import { BookOpen, ExternalLink, LogOut, Monitor, Moon, ShieldUser, Sun, type IconNode } from "lucide";import { icon } from "./ui";@@ -431,6 +432,15 @@ function settingsPane(): TemplateResult {<div class="settings-row settings-slack-account"><qm-slack-account .user=${`${appState.me?.org}:${appState.me?.user}`}></qm-slack-account></div>+ <div class="settings-row">+ <qm-onboarding-welcome+ .me=${appState.me}+ .setupOnly=${true}+ .widget=${"apps"}+ .returnKey=${"settings"}+ .base=${withBase("")}+ ></qm-onboarding-welcome>+ </div></div>`;}diff --git a/plugins/web-ui/src/slack-account.ts b/plugins/web-ui/src/slack-account.tsindex 8f137b964..f39fb3e90 100644--- a/plugins/web-ui/src/slack-account.ts+++ b/plugins/web-ui/src/slack-account.ts@@ -1,3 +1,4 @@+import { openDesktopBrowser } from "../../chassis/src/desktop-browser";import { LitElement, html, nothing } from "lit";import { ArrowUpRight, Check, Link2, UserRound } from "lucide";import { icon, slackMark } from "./ui";@@ -37,6 +38,22 @@ export class SlackAccount extends LitElement {return this;}+ connectedCallback(): void {+ super.connectedCallback();+ window.addEventListener("focus", this.refreshStatus);+ document.addEventListener("visibilitychange", this.refreshStatus);+ }++ disconnectedCallback(): void {+ super.disconnectedCallback();+ window.removeEventListener("focus", this.refreshStatus);+ document.removeEventListener("visibilitychange", this.refreshStatus);+ }++ private refreshStatus = (): void => {+ if (!document.hidden) void this.status();+ };+protected firstUpdated(): void {const url = returnUrl ?? new URL(location.href);returnUrl = null;@@ -90,6 +107,7 @@ export class SlackAccount extends LitElement {this.busy = true;this.error = "";try {+ if (await openDesktopBrowser(withBase("/settings"))) return;const state = crypto.randomUUID();const response = await fetch(withBase("/api/composio/slack/authorize"), {method: "POST",diff --git a/plugins/web-ui/test/desktop-connections.test.ts b/plugins/web-ui/test/desktop-connections.test.tsnew file mode 100644index 000000000..6a2364981--- /dev/null+++ b/plugins/web-ui/test/desktop-connections.test.ts@@ -0,0 +1,43 @@+import assert from "node:assert/strict";+import test from "node:test";+import { harness } from "./deep-link-boot-fixture.ts";++test("desktop connection buttons hand off before creating authorization state", async () => {+ const h = await harness({ path: "/settings", welcome: true });+ const fetchBefore = globalThis.fetch;+ const browserUrls: string[] = [];+ const authorized: string[] = [];+ globalThis.fetch = async (input, init) => {+ if (String(input).includes("/authorize")) authorized.push(String(input));+ return fetchBefore(input, init);+ };+ try {+ Object.assign(window, {+ qmDesktop: {+ openBrowser: async (url: string) => {+ browserUrls.push(url);+ },+ },+ });+ h.releaseSessions();+ await h.boot();+ const slack = document.querySelector("qm-slack-account")!;+ assert.ok(slack);+ (slack as unknown as { connect(): Promise<void> }).connect();+ const apps = document.querySelector("qm-onboarding-welcome")!;+ assert.ok(apps);+ await (apps as unknown as { authorize(service: { id: string; name: string }): Promise<void> }).authorize({+ id: "gmail",+ name: "Gmail",+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.deepEqual(browserUrls, ["/settings", "/settings"]);+ assert.deepEqual(authorized, []);+ assert.equal(sessionStorage.getItem("qm-slack-account"), null);+ assert.equal(sessionStorage.getItem("qm-connection-return:test:tester"), null);+ } finally {+ Reflect.deleteProperty(window, "qmDesktop");+ globalThis.fetch = fetchBefore;+ await h.close();+ }+});diff --git a/plugins/web-ui/test/onboarding-slack.test.ts b/plugins/web-ui/test/onboarding-slack.test.tsindex b32cd3885..32da3e20e 100644--- a/plugins/web-ui/test/onboarding-slack.test.ts+++ b/plugins/web-ui/test/onboarding-slack.test.ts@@ -38,6 +38,19 @@ test("Slack onboarding launches directly and verifies connection on return", asyawait settle();assert.match(element.textContent ?? "", /Add to Slack/);assert.doesNotMatch(element.textContent ?? "", /QM added to Slack/);+ const browserUrls: string[] = [];+ Object.assign(window, {+ qmDesktop: {+ openBrowser: async (url: string) => {+ browserUrls.push(url);+ },+ },+ });+ element.querySelector<HTMLButtonElement>("button")!.click();+ await settle();+ assert.deepEqual(browserUrls, ["/admin/slack-settings?slack=install"]);+ assert.equal(launches.length, 0);+ Reflect.deleteProperty(window, "qmDesktop");let submitted: HTMLFormElement | undefined;const popupDocument = document.implementation.createHTMLDocument();const createElement = popupDocument.createElement.bind(popupDocument);diff --git a/test/qm-brand.test.ts b/test/qm-brand.test.tsindex 7242e684e..a8345c2cc 100644--- a/test/qm-brand.test.ts+++ b/test/qm-brand.test.ts@@ -123,6 +123,7 @@ function isCompressedMedia(content: Buffer): boolean {content.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff])) ||content.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) ||content.subarray(0, 4).toString("ascii") === "GIF8" ||+ content.subarray(0, 4).toString("ascii") === "icns" ||(content.subarray(0, 4).toString("ascii") === "RIFF" && content.subarray(8, 12).toString("ascii") === "WEBP"));}