From 2f8a08089e49d39e6887e10c239c7f15297141a0 Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 23 Nov 2026 00:48:26 +0800 Subject: [PATCH 1/2] [bugfix] desktop: grant the renderer permissions the shell controls use ## summary - Replace the deny-all renderer permission handler with an explicit allow list limited to `opendirector://app`: the two clipboard names `navigator.clipboard.writeText` can request and the two fullscreen names `requestFullscreen` uses. - Grant by activation path, not by intent: a scripted write asks for `clipboard-read`, while the same write from a click asks for `clipboard-sanitized-write`, so a single name passes a scripted check and still leaves every copy button failing with `NotAllowedError`. - Scope grants by `details.requestingUrl` and the check handler's origin, and treat an empty or opaque origin as a denial instead of letting `new URL` throw. - Cover the shell policy in the installed smoke run: write from the renderer with and without user activation, then compare the system clipboard from the main process, polling because the renderer promise settles before the system clipboard holds the value. ## validation - Measured on Windows with Electron 45.3.3 against the real `opendirector://app` origin: the deny-all handler rejected the write with `NotAllowedError: Write permission denied.`; the allow list accepted both activation paths and the system clipboard held the written text. - `apps/desktop` `node --test tests/*.test.mjs`: 11 passed, 1 skipped (the packaged smoke needs a packaged runtime). - `node --check apps/desktop/scripts/smoke-window.mjs`. - `npm test`: 952 passed. `npm run check:i18n`: 0 problems. Refs: #397 --- apps/desktop/scripts/smoke-window.mjs | 19 ++++++++++++- apps/desktop/src/main.mjs | 6 +++- apps/desktop/src/permissions.mjs | 36 ++++++++++++++++++++++++ apps/desktop/tests/permissions.test.mjs | 37 +++++++++++++++++++++++++ docs/architecture/desktop.md | 2 ++ docs/architecture/desktop.zh-CN.md | 2 ++ docs/development/desktop.md | 4 ++- docs/development/desktop.zh-CN.md | 4 ++- docs/development/lessons.md | 7 +++++ docs/development/validation.md | 1 + 10 files changed, 114 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/src/permissions.mjs create mode 100644 apps/desktop/tests/permissions.test.mjs diff --git a/apps/desktop/scripts/smoke-window.mjs b/apps/desktop/scripts/smoke-window.mjs index 46de96d55..8ed154123 100644 --- a/apps/desktop/scripts/smoke-window.mjs +++ b/apps/desktop/scripts/smoke-window.mjs @@ -1,5 +1,5 @@ import { guardLargeVideoDataUrl, largeVideoState, verifyLargeVideoBytes } from './large-video.mjs'; -import { app, BrowserWindow } from 'electron'; +import { app, BrowserWindow, clipboard } from 'electron'; import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { createHash } from 'node:crypto'; import { join } from 'node:path'; @@ -79,6 +79,14 @@ export async function smokeWindow({ window, host, getLocale }) { window.focus(); window.webContents.focus(); await waitFor(() => window.isFocused(), 'Desktop window could not take focus before search'); + // Chromium asks the embedder for a clipboard permission before an + // asynchronous write, and the name depends on the activation: clipboard-read + // without one, clipboard-sanitized-write when a click triggered the write. + // Both paths are checked so a policy that only covers the scripted one cannot + // pass while every copy button a user presses fails. + await waitFor(() => window.webContents.executeJavaScript('document.hasFocus()'), 'Renderer did not take document focus before the clipboard check'); + await assertClipboardWrite(window, 'opendirector-smoke', false); + await assertClipboardWrite(window, 'opendirector-smoke-click', true); await window.webContents.executeJavaScript("document.querySelector('.od-sidebar-search-toggle').click()"); await waitFor(() => window.webContents.executeJavaScript("document.activeElement === document.querySelector('.od-sidebar-search')"), 'Project search did not take focus'); const firstProject = await window.webContents.executeJavaScript("document.querySelector('.od-project-sidebar nav button span').textContent"); @@ -252,6 +260,15 @@ export async function smokeWindow({ window, host, getLocale }) { return result; } +async function assertClipboardWrite(window, text, userGesture) { + await window.webContents.executeJavaScript( + `navigator.clipboard.writeText(${JSON.stringify(text)}).then(() => true, error => { throw new Error('Clipboard write was rejected: ' + error.name); })`, userGesture); + // The renderer promise settles before the system clipboard holds the value: + // an immediate read still returns the previous contents, which measured + // intermittently for a click-activated write. + await waitFor(async () => (await clipboard.readText()) === text, `Clipboard write did not reach the system clipboard: ${text}`, 20); +} + async function smokeLargeVideo(window, host, projectId, fixture, firstLaunch) { const { webContents } = window; const name = 'large-video.mp4'; diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs index c1ba6060c..ad354e17c 100644 --- a/apps/desktop/src/main.mjs +++ b/apps/desktop/src/main.mjs @@ -7,6 +7,7 @@ import { homedir } from 'node:os'; import { Host, ownedURL, proxyRequest } from './host.mjs'; import { messages, localeFor } from './locale.mjs'; import { registerCommand, commandPath } from './command.mjs'; +import { permissionGranted } from './permissions.mjs'; app.setName('OpenDirector'); const desktopChrome = ['darwin', 'win32'].includes(process.platform); @@ -133,7 +134,10 @@ async function start() { }); await host.ready; const ownedSession = session.fromPartition('persist:opendirector'); - ownedSession.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)); + ownedSession.setPermissionRequestHandler((contents, permission, callback, details) => + callback(permissionGranted(permission, details.requestingUrl ?? contents.getURL()))); + ownedSession.setPermissionCheckHandler((_contents, permission, requestingOrigin) => + permissionGranted(permission, requestingOrigin)); let projectSubscription; ownedSession.protocol.handle('opendirector', request => proxyRequest(request, host, async (url, options) => { const pathname = new URL(url).pathname; diff --git a/apps/desktop/src/permissions.mjs b/apps/desktop/src/permissions.mjs new file mode 100644 index 000000000..3ca08c925 --- /dev/null +++ b/apps/desktop/src/permissions.mjs @@ -0,0 +1,36 @@ +import { ownedURL } from './host.mjs'; + +/** + * Renderer permissions granted by the desktop shell, for its own page only. + * + * Electron grants renderer permissions by default, so denying by default means + * the handler also has to grant the ones the shared UI actually uses. Each name + * below was measured in the installed Electron build, because the same user + * action can ask for different names depending on whether a click activated it. + * Electron can pass an empty or opaque requesting URL, so an untrusted origin + * is a denial rather than a thrown error. + */ +const granted = new Set([ + // `navigator.clipboard.writeText`: Chromium asks for clipboard-read when the + // page writes without user activation and for clipboard-sanitized-write when + // a click is the activation. Granting only clipboard-read leaves the smoke + // write passing while every copy button a user presses fails with + // `NotAllowedError: Write permission denied`. + 'clipboard-read', + 'clipboard-sanitized-write', + // `mediaElement.requestFullscreen`: the check handler answers + // automatic-fullscreen and the request handler answers fullscreen. Denying + // either leaves the fullscreen request promise unsettled, so the player's + // fullscreen button silently does nothing instead of reporting a refusal. + 'fullscreen', + 'automatic-fullscreen', +]); + +export function permissionGranted(permission, requestingUrl) { + if (!granted.has(permission)) return false; + try { + return ownedURL(requestingUrl); + } catch { + return false; + } +} diff --git a/apps/desktop/tests/permissions.test.mjs b/apps/desktop/tests/permissions.test.mjs new file mode 100644 index 000000000..f0a68c2d8 --- /dev/null +++ b/apps/desktop/tests/permissions.test.mjs @@ -0,0 +1,37 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { permissionGranted } from '../src/permissions.mjs'; + +const app = 'opendirector://app/'; +const allowed = ['clipboard-read', 'clipboard-sanitized-write', 'fullscreen', 'automatic-fullscreen']; + +test('The application page receives the permissions its controls use', () => { + for (const permission of allowed) { + assert.equal(permissionGranted(permission, app), true, permission); + assert.equal(permissionGranted(permission, 'opendirector://app/canvas?x=1'), true, permission); + } +}); + +test('A clipboard write needs both names because the activation changes the request', () => { + // Measured in Electron 45: a scripted write asks for clipboard-read, the same + // write from a click asks for clipboard-sanitized-write. Granting one name + // leaves the other path failing with NotAllowedError. + assert.equal(permissionGranted('clipboard-read', app), true); + assert.equal(permissionGranted('clipboard-sanitized-write', app), true); +}); + +test('Other renderer permissions stay denied', () => { + for (const permission of ['media', 'display-capture', 'geolocation', 'notifications', + 'midi', 'pointerLock', 'openExternal', 'fileSystem', 'serial', 'usb', 'unknown', '']) { + assert.equal(permissionGranted(permission, app), false, permission); + } +}); + +test('The granted permissions do not extend to other origins', () => { + for (const origin of ['https://example.com/', 'file:///C:/tmp/a.html', 'opendirector://other/', + 'opendirector://app:8080/', '', undefined, null, 'null', 'not a url']) { + for (const permission of allowed) { + assert.equal(permissionGranted(permission, origin), false, `${permission} on ${String(origin)}`); + } + } +}); diff --git a/docs/architecture/desktop.md b/docs/architecture/desktop.md index 158c81d66..48c068622 100644 --- a/docs/architecture/desktop.md +++ b/docs/architecture/desktop.md @@ -18,6 +18,8 @@ The main process starts the bundled Python runtime and gives the Host a fresh cr The renderer requests application pages, media, and API resources through `opendirector://app`. The main process forwards those requests to the Host with the launch credential. The Host checks the credential before it serves the request. The renderer runs with Node integration off and context isolation on. A preload bridge exposes specific desktop operations, including edit-session registration and language and export status updates. +Renderer permissions are denied by default with an explicit allow list in [`permissions.mjs`](../../apps/desktop/src/permissions.mjs), limited to `opendirector://app`: the two clipboard names `navigator.clipboard.writeText` can request and the two fullscreen names `requestFullscreen` uses. The requested clipboard name depends on the activation, so both are granted; the fullscreen names are granted because a denial leaves the request promise unsettled and the player's button silently does nothing. The installed smoke test writes to the system clipboard from both a scripted and a click-activated renderer call and compares the result in the main process. Granting a new renderer permission is a policy change, not a UI detail. + ## The Host owns project state The Host uses the same project storage, command validation, and edit-session rules as the standalone API. The desktop shell handles window behavior and opens native dialogs for file input and downloads. diff --git a/docs/architecture/desktop.zh-CN.md b/docs/architecture/desktop.zh-CN.md index 8caf00124..b555b9ad9 100644 --- a/docs/architecture/desktop.zh-CN.md +++ b/docs/architecture/desktop.zh-CN.md @@ -18,6 +18,8 @@ flowchart LR 渲染进程通过 `opendirector://app` 请求应用页面、媒体和 API 资源。主进程转发请求时附带启动凭证,Host 验证凭证后处理请求。渲染进程关闭 Node 集成并开启上下文隔离。预加载脚本提供有限的桌面接口,包括登记编辑会话、同步语言和导出状态。 +渲染进程权限默认全部拒绝,只对 `opendirector://app` 开放一份显式清单(见 [`permissions.mjs`](../../apps/desktop/src/permissions.mjs)):`navigator.clipboard.writeText` 可能申请的两种剪贴板权限,以及 `requestFullscreen` 使用的两种全屏权限。剪贴板申请的名称取决于是否有用户激活,因此两种都授予;全屏若不授予,申请 Promise 会一直挂起,播放器的全屏按钮会静默失效。已安装包的冒烟检查会分别用脚本调用和点击激活的渲染进程写入,并在主进程核对系统剪贴板内容。新增任何渲染进程权限都属于策略变更,不是界面细节。 + ## Host 管理工程状态 Host 与独立 API 共用工程存储、命令校验和编辑会话规则。桌面壳管理窗口,并通过原生对话框选择文件和保存下载。 diff --git a/docs/development/desktop.md b/docs/development/desktop.md index 263597304..ca7435a47 100644 --- a/docs/development/desktop.md +++ b/docs/development/desktop.md @@ -18,7 +18,9 @@ node apps/desktop/scripts/smoke.mjs /absolute/path/to/packaged/OpenDirector The runtime preparation builds the Python wheel using the existing build backend, including Web assets, skills and the actual OpenCode executable. It installs the wheel and dependencies into a private standalone Python distribution, validates CLI help and both media binaries, and records the target in `runtime/manifest.json`. It never modifies system Python. Supply media binaries with their redistribution licenses for the target; system package-manager binaries with external shared-library dependencies are not portable. -The smoke check launches the actual packaged executable with isolated temporary data, opens the canvas, drops local MP4, PNG, and WAV files and verifies their assets and nodes persist across launches, checks authenticated health and project queries, verifies renderer isolation and both locales, hides the window without stopping the Host, and reopens the same project after quitting. It makes no provider calls. It does not establish Agent-assisted creation, export quality, signing, or support on an untested platform. +The smoke check launches the actual packaged executable with isolated temporary data, opens the canvas, drops local MP4, PNG, and WAV files and verifies their assets and nodes persist across launches, checks authenticated health and project queries, verifies renderer isolation and both locales, writes to the system clipboard from the renderer with and without user activation, hides the window without stopping the Host, and reopens the same project after quitting. It makes no provider calls. It does not establish Agent-assisted creation, export quality, signing, or support on an untested platform. + +Copy actions in the shared UI use `navigator.clipboard.writeText`, and the media player uses `requestFullscreen`; both are renderer permissions. The shell therefore grants those names to `opendirector://app` and denies every other renderer permission ([`permissions.mjs`](../../apps/desktop/src/permissions.mjs)). Measure the permission names in the shipped Electron build instead of inferring them from Chromium, and measure each activation path: in Electron 45 a scripted clipboard write asks for `clipboard-read`, while the same write from a click asks for `clipboard-sanitized-write`, so an allow list covering only the scripted path passes the smoke write and still breaks every copy button a user presses. Fullscreen follows the same rule from the deny side: denying `automatic-fullscreen` or `fullscreen` leaves the request promise unsettled, so the button does nothing instead of reporting a refusal. A browser page cannot stand in for these checks either, because Chrome grants the write itself, so only the packaged smoke run covers the shell policy. ## Terminal command diff --git a/docs/development/desktop.zh-CN.md b/docs/development/desktop.zh-CN.md index e4efab4ac..315e5c37b 100644 --- a/docs/development/desktop.zh-CN.md +++ b/docs/development/desktop.zh-CN.md @@ -18,7 +18,9 @@ node apps/desktop/scripts/smoke.mjs /absolute/path/to/packaged/OpenDirector 运行时准备复用现有构建后端生成 Python wheel,包含前端、技能和实际 OpenCode 可执行文件;将 wheel 和依赖安装到私有独立 Python,验证 CLI 帮助及两个媒体程序,并将平台写入 `runtime/manifest.json`。不会修改系统 Python。提供对应平台可分发的媒体程序及许可证;依赖包管理器外部动态库的系统二进制不能直接作为便携运行时。 -冒烟检查使用临时数据目录启动实际打包程序,进入画布,拖入本地 MP4、PNG 和 WAV 文件并确认重启后素材和节点仍在,检查鉴权健康接口和工程查询,验证渲染隔离及中英文切换,隐藏窗口并确认 Host 保留,退出后重开同一工程,不调用模型服务。该检查不代表已完成 Agent 辅助创作、导出质量、签名或未测试平台的验收。 +冒烟检查使用临时数据目录启动实际打包程序,进入画布,拖入本地 MP4、PNG 和 WAV 文件并确认重启后素材和节点仍在,检查鉴权健康接口和工程查询,验证渲染隔离及中英文切换,分别以脚本调用和点击激活两种方式由渲染进程写入系统剪贴板并核对内容,隐藏窗口并确认 Host 保留,退出后重开同一工程,不调用模型服务。该检查不代表已完成 Agent 辅助创作、导出质量、签名或未测试平台的验收。 + +界面中的复制操作使用 `navigator.clipboard.writeText`,媒体播放器使用 `requestFullscreen`,两者都受渲染进程权限约束。桌面壳因此只对 `opendirector://app` 授予对应权限,其余渲染进程权限继续默认拒绝(见 [`permissions.mjs`](../../apps/desktop/src/permissions.mjs))。权限名称要在实际 Electron 构建里实测,不能从 Chromium 源码推导,并且要按用户激活方式分别实测:Electron 45 里脚本调用的写入申请 `clipboard-read`,而同一段写入由点击触发时申请 `clipboard-sanitized-write`,只覆盖脚本路径的清单会让冒烟写入通过、却让用户真正点击的每个复制按钮失败。全屏是同一类问题的反面:拒绝 `automatic-fullscreen` 或 `fullscreen` 会让申请 Promise 一直不落地,按钮看起来毫无反应而不是报错。普通浏览器页面同样不能替代这些检查,因为 Chrome 自己会授予写入权限,只有实际安装包的冒烟运行能覆盖桌面壳的权限策略。 ## 终端命令 diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 02d65b52f..527a294a1 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -67,6 +67,13 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Final-window follow-up:** Native PR #193 regressions also broke the guard after the final pre-write check returned and after the final post-write check returned. A check is not an atomic write/cleanup guarantee. Retain the one-time native removal receipt, verify its ACE multiplicities under a fresh guard after a conflict, and report unconfirmed cleanup rather than spending the delta again. At release, distinguish a real oplock-break completion from the host's own cancellation and preserve an existing body error. This contract cannot prevent a principal with independent WRITE_DAC from changing permissions after the guard has been released; do not claim permanent ACL immutability. - **Installation ownership follow-up:** A deterministic PR #193 probe also replayed the pre-install descriptor plus an external identical deny. Retaining both successful installation receipts across the retry let cleanup remove the external rule. ACE counts cannot establish provenance: an equal-count replacement is also possible. If the installation's guard cannot finish successfully after a native acknowledgment, stop initialization and report unconfirmed ownership without retrying or removing that handle's uncertain ACEs. A setter wrapper error with a successfully checked and released guard remains an ordinary rollback case. Cover pre-write retry, both replay shapes, additive writers, partial preparation, setter errors and release failures; distinguish portable control flow from actual Windows scheduling. +## A deny-all renderer permission handler also denies clipboard writes + +- **Trigger:** Adding a renderer permission policy to an Electron shell, or a copy button that fails only in the packaged app. +- **Lesson:** [PR #397](https://github.com/ThinkFlowLab/OpenDirector/pull/397) installed `setPermissionRequestHandler(() => callback(false))`. Electron grants renderer permissions by default and only denies through that handler, so every `navigator.clipboard.writeText` copy in the shared UI rejected with `NotAllowedError: Write permission denied.` in the packaged application while the same page worked in a browser that grants the write itself. +- **Check:** State renderer permissions as an explicit allow list limited to the shell's own origin, and cover each activation path in the installed smoke run: write from the renderer with and without user activation and compare the system clipboard from the main process. Measured Electron 45 on Windows, `navigator.clipboard.writeText` asks for different names per path: a scripted write requests `clipboard-read`, while the same write from a click requests `clipboard-sanitized-write`. An allow list with only `clipboard-read` therefore passed the scripted smoke write while every copy button a user pressed still failed, and `document.execCommand('copy')` also returned false, so a scripted fallback cannot repair a denied write. Measure the requested name for each activation in the shipped build; do not infer it from Chromium source, and do not let a permission-free scripted call stand in for a click. +- **Follow-up:** The permission request handler receives no `securityOrigin` in Electron 45; scope by `details.requestingUrl` (falling back to `contents.getURL()`) and by the check handler's origin, and treat an empty or opaque origin as a denial instead of letting `new URL` throw. A denial the renderer never sees is the harder failure: denying `fullscreen` or `automatic-fullscreen` leaves `requestFullscreen`'s promise unsettled, so the fullscreen button does nothing and no `.catch` runs. `clipboard.readText()` is asynchronous in Electron 45, so a smoke assertion that compares its return value directly always fails; await it, and poll instead of reading once — the renderer promise settles before the system clipboard holds the value, so an immediate read still returns the previous contents (measured intermittently for a click-activated write). + ## A process exit and ownership of its descendants are separate facts - **Trigger:** Adapting browser fixture cleanup or sampled process memory to Windows. diff --git a/docs/development/validation.md b/docs/development/validation.md index 134744d1b..26c309028 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -277,6 +277,7 @@ Replace `all` with comma-separated runtime IDs to select a subset. Bundled reads | 编辑器与时间线 | 结构往返、素材保护、重开续编、真实文件播放及导出 | | UI 与 Agent 接入 | 相同意图的业务结果一致,交错编辑和草稿保留 | | 交互与同步 | 真实拖动、缩放、焦点、锁定、重复事件和断线恢复 | +| 桌面壳与原生能力 | 渲染进程权限清单、安装包冒烟中脚本与点击两种激活下的剪贴板实际写入、全屏请求;浏览器默认授权不能代表桌面壳行为 | | 性能 | 固定素材和手势下比较帧延迟、长任务、内存或 CPU 数据 | | 文档 | 链接、命令与文件路径正确,依赖文件随仓库交付 | From 7c9f562fbd05d72b091f12b8a1c3e29c3e0e034c Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 23 Nov 2026 01:22:49 +0800 Subject: [PATCH 2/2] [bugfix] desktop: report the clipboard value the smoke actually read ## summary - The installed run failed with only "did not reach the system clipboard", which does not distinguish a denied write from a read that arrived before Windows handed the clipboard over. - Poll the read instead of taking one sample, and include the observed value in the failure, so the next packaged failure names the cause. ## verification - Packaged Windows build (win-unpacked, Electron 45.3.3): the scripted and the click-activated write both reach the system clipboard before the smoke moves on. The run then stops at the trace-window step, which reproduces with the previous deny-all handler as well and is unrelated to renderer permissions. --- apps/desktop/scripts/smoke-window.mjs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/desktop/scripts/smoke-window.mjs b/apps/desktop/scripts/smoke-window.mjs index 8ed154123..ac0be529a 100644 --- a/apps/desktop/scripts/smoke-window.mjs +++ b/apps/desktop/scripts/smoke-window.mjs @@ -264,9 +264,14 @@ async function assertClipboardWrite(window, text, userGesture) { await window.webContents.executeJavaScript( `navigator.clipboard.writeText(${JSON.stringify(text)}).then(() => true, error => { throw new Error('Clipboard write was rejected: ' + error.name); })`, userGesture); // The renderer promise settles before the system clipboard holds the value: - // an immediate read still returns the previous contents, which measured - // intermittently for a click-activated write. - await waitFor(async () => (await clipboard.readText()) === text, `Clipboard write did not reach the system clipboard: ${text}`, 20); + // an immediate read still returns the previous contents, measured for the + // scripted write in the packaged application and intermittently for a click. + let actual = await clipboard.readText(); + for (let attempt = 0; attempt < 20 && actual !== text; attempt++) { + await delay(100); + actual = await clipboard.readText(); + } + if (actual !== text) throw new Error(`Clipboard write did not reach the system clipboard: expected ${text}, read ${JSON.stringify(actual)}`); } async function smokeLargeVideo(window, host, projectId, fixture, firstLaunch) {