Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/desktop-installers.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ jobs:
codesign --force --deep --sign - "$app"
codesign --verify --deep --strict "$app"
- name: Build and smoke-test DMG
env:
OPENDIRECTOR_DESKTOP_SMOKE_CLIPBOARD: '1'
run: |
mount="$RUNNER_TEMP/desktop-mount"
installer="$PWD/apps/desktop/installer/macos"
Expand Down Expand Up @@ -137,6 +139,8 @@ jobs:
npm run pack:windows --prefix apps/desktop
if ($LASTEXITCODE -ne 0) { throw 'Windows packaging failed' }
- name: Smoke-test installed application
env:
OPENDIRECTOR_DESKTOP_SMOKE_CLIPBOARD: '1'
run: |
$name = "OpenDirector-v$env:DESKTOP_VERSION-win-x64-unsigned.exe"
$installer = Get-Item "apps/desktop/build/$name"
Expand Down
60 changes: 58 additions & 2 deletions apps/desktop/scripts/smoke-window.mjs
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -94,6 +94,11 @@ export async function smokeWindow({ window, host, getLocale }) {
window.focus();
window.webContents.focus();
await waitFor(() => window.isFocused(), 'Desktop window could not take focus before search');
if (process.env.OPENDIRECTOR_DESKTOP_SMOKE_CLIPBOARD === '1') {
await waitFor(() => window.webContents.executeJavaScript('document.hasFocus()'), 'Renderer did not take document focus before the clipboard check');
await assertClipboardReadDenied(window);
await assertClipboardWrite(window, 'opendirector-smoke-click', true);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion:这里实际覆盖的是「点击写入成功、读取被拒」,没有断言所有无激活写入被拒。开发文档也明确说这不是当前保证。建议把 PR 摘要改成与这里一致;如果「只允许真实用户手势写入」是产品要求,就单独明确这个边界,再为它补安装包回归。

}
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");
Expand Down Expand Up @@ -266,13 +271,64 @@ export async function smokeWindow({ window, host, getLocale }) {
await window.webContents.executeJavaScript("document.querySelector('.od-caption-actions button').click()");
}
await waitFor(() => window.webContents.executeJavaScript(`localStorage.getItem('opendirector.desktop.sidebar.v1') === '${result.sidebarFinallyOpen ? 'open' : 'closed'}'`), 'Sidebar preference was not saved');
await assertFullscreen(window);
await window.webContents.executeJavaScript('window.opendirectorDesktop.setExporting(true)');
await delay(50);
window.close();
if (window.isVisible() || !(await host.inspect())) throw new Error('Closing a window stopped the Host');
await assertWindowClosedAndHostRunning(window, host);
return result;
}

async function assertWindowClosedAndHostRunning(window, host) {
const visible = () => !window.isDestroyed() && window.isVisible();
const deadline = performance.now() + 15_000;
while (performance.now() < deadline) {
if (!visible() && (await host.inspect())) return;
await delay(100);
}
throw new Error(`Closing a window stopped the Host (window visible: ${visible()})`);
}

async function assertClipboardReadDenied(window) {
const read = await window.webContents.executeJavaScript(
`navigator.clipboard.readText().then(() => 'granted', error => error.name)`, false);
if (read !== 'NotAllowedError') throw new Error('A clipboard read was not denied');
}

async function assertClipboardWrite(window, text, userGesture) {
const previous = await clipboard.readText();
try {
await window.webContents.executeJavaScript(
`navigator.clipboard.writeText(${JSON.stringify(text)}).then(() => true, error => { throw new Error('Clipboard write was rejected: ' + error.name); })`, userGesture);
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');
} finally {
await clipboard.writeText(previous);
}
}

async function assertFullscreen(window) {
const state = await window.webContents.executeJavaScript(`(async () => {
const element = document.querySelector('.cw-workspace') ?? document.body;
const outcome = await Promise.race([
element.requestFullscreen().then(() => 'entered', error => error.name),
new Promise(resolve => setTimeout(() => resolve('pending'), 10000)),
]);
if (outcome !== 'entered') return { outcome };
const entered = document.fullscreenElement === element;
document.exitFullscreen().catch(() => {});
return { outcome, entered };
})()`, true);
if (state.outcome !== 'entered') throw new Error(`Fullscreen request did not enter fullscreen: ${state.outcome}`);
if (!state.entered) throw new Error('Fullscreen request did not make the element fullscreen');
await waitFor(() => window.webContents.executeJavaScript('!document.fullscreenElement'), 'Fullscreen did not exit');
await waitFor(() => !window.isFullScreen(), 'Fullscreen did not exit the window');
}

async function smokeLargeVideo(window, host, projectId, fixture, firstLaunch) {
const { webContents } = window;
const name = 'large-video.mp4';
Expand Down
6 changes: 5 additions & 1 deletion apps/desktop/src/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Host, ownedURL, proxyRequest } from './host.mjs';
import { resolveHostEnv } from './environment.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);
Expand Down Expand Up @@ -134,7 +135,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)));
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;
Expand Down
12 changes: 12 additions & 0 deletions apps/desktop/src/permissions.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ownedURL } from './host.mjs';

const granted = new Set(['clipboard-sanitized-write', 'fullscreen', 'automatic-fullscreen']);

export function permissionGranted(permission, requestingUrl) {
if (!granted.has(permission)) return false;
try {
return ownedURL(requestingUrl);
} catch {
return false;
}
}
37 changes: 37 additions & 0 deletions apps/desktop/tests/permissions.test.mjs
Original file line number Diff line number Diff line change
@@ -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-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);
assert.equal(permissionGranted(permission, 'opendirector://app'), true, permission);
}
});

test('Clipboard reads stay denied while sanitized writes are granted', () => {
assert.equal(permissionGranted('clipboard-read', app), false);
assert.equal(permissionGranted('clipboard-read', 'opendirector://app/canvas'), false);
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/', 'opendirector://app@evil.com/', 'opendirector://x.app/',
'', undefined, null, 'null', 'not a url']) {
for (const permission of allowed) {
assert.equal(permissionGranted(permission, origin), false, `${permission} on ${String(origin)}`);
}
}
});
2 changes: 2 additions & 0 deletions docs/architecture/desktop.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`: `clipboard-sanitized-write`, the name a `navigator.clipboard.writeText` call carrying user activation requests, and the two fullscreen names `requestFullscreen` uses. The read/write clipboard name stays denied because every copy in the shared UI starts from a click and the renderer never reads the system clipboard, so granting it would hand the page a capability no caller uses. The fullscreen names are granted because a denial leaves the request promise unsettled and the player's button silently does nothing. With `OPENDIRECTOR_DESKTOP_SMOKE_CLIPBOARD=1`, the installed smoke test also asserts that a copy carrying renderer user activation reaches the system clipboard and that the renderer's clipboard read is refused; it always asserts that a fullscreen request enters and exits. 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.
Expand Down
2 changes: 2 additions & 0 deletions docs/architecture/desktop.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ flowchart LR

渲染进程通过 `opendirector://app` 请求应用页面、媒体和 API 资源。主进程转发请求时附带启动凭证,Host 验证凭证后处理请求。渲染进程关闭 Node 集成并开启上下文隔离。预加载脚本提供有限的桌面接口,包括登记编辑会话、同步语言和导出状态。

渲染进程权限默认全部拒绝,只对 `opendirector://app` 开放一份显式清单(见 [`permissions.mjs`](../../apps/desktop/src/permissions.mjs)):带用户激活的 `navigator.clipboard.writeText` 申请的 `clipboard-sanitized-write`,以及 `requestFullscreen` 使用的两种全屏权限。读写剪贴板名称不授予:界面里的复制都由点击发起,渲染进程也从不读取系统剪贴板,授予它等于给页面一项没有调用方的能力。全屏若不授予,申请 Promise 会一直挂起,播放器的全屏按钮会静默失效。设置 `OPENDIRECTOR_DESKTOP_SMOKE_CLIPBOARD=1` 时,已安装包的冒烟检查还会断言带用户激活的复制确实写入系统剪贴板、渲染进程读取剪贴板被拒绝;全屏能够进入也能够退出的断言则始终执行。新增任何渲染进程权限都属于策略变更,不是界面细节。

## Host 管理工程状态

Host 与独立 API 共用工程存储、命令校验和编辑会话规则。桌面壳管理窗口,并通过原生对话框选择文件和保存下载。
Expand Down
4 changes: 3 additions & 1 deletion docs/development/desktop.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ 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 packaged executable with isolated temporary data. It connects the bundled OpenCode, chooses Canvas mode, and imports a WAV through Welcome with a local media model configuration that needs no provider calls. It also drops local MP4, PNG, and WAV files, verifies the saved assets and nodes after reopening, checks authenticated API calls, renderer isolation and both locales, and hides the window while the Host stays running.
The smoke check launches the packaged executable with isolated temporary data. It connects the bundled OpenCode, chooses Canvas mode, and imports a WAV through Welcome with a local media model configuration that needs no provider calls. It also drops local MP4, PNG, and WAV files, verifies the saved assets and nodes after reopening, checks authenticated API calls, renderer isolation and both locales, and hides the window while the Host stays running. With `OPENDIRECTOR_DESKTOP_SMOKE_CLIPBOARD=1` it also asserts that a renderer copy carrying user activation reaches the system clipboard and that the renderer cannot read the clipboard; the flag is off by default so an ordinary run does not replace the clipboard of the machine that launches it. The fullscreen assertion runs in every smoke. It makes no provider calls. It does not establish Agent-assisted creation, export quality, signing, or support on an untested platform.

The live trace fixture supplies the running flag for its own synthetic turn. The trace window reads incremental data from the packaged Host and renders the appended trace record.

Copy actions in the shared UI use `navigator.clipboard.writeText`, and the media player uses `requestFullscreen`; both are renderer permissions. The shell therefore grants the names those calls request 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 check clipboard calls in the state the assertions run: in Electron 45 a scripted clipboard write asked for `clipboard-read`, the read/write name that also opens `navigator.clipboard.readText`, while a write carrying user activation asks for `clipboard-sanitized-write`. The shell grants only the name a user-activation write requests, and the packaged smoke issues the write with Chromium's gesture flag — the activation a click supplies — then checks that it reaches the system clipboard and that `readText` is refused with `NotAllowedError`. The smoke forces window focus before those checks; in the PR #458 packaged run, after earlier page interactions, the granted policy also admitted a write without transient activation, so the smoke does not assert that the activation-free write is refused. That write's requested permission name was not recorded, so the reason is not isolated; a focused probe page still requested `clipboard-read` and had that write refused. 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. The smoke therefore asserts that a fullscreen request settles, enters and exits. 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. The permission name a write requests comes from Chromium's shared permission code and does not vary by platform; only a packaged run on a given platform establishes that its system clipboard and window server behave.

## Terminal command

Use **Manage terminal command** in the application menu to install the launcher in `~/.local/bin`. Add that directory to PATH if needed. The app preserves existing entries. To uninstall or repair an old installation, check the path shown in the app and manually remove the OpenDirector entry. To repair it, run Install again. `opendirector desktop` opens this installation; `opendirector serve` runs the ordinary standalone API. Business CLI commands retain their existing `--url`, project, session and revision rules. Automatic attachment of an external CLI to the private desktop Host is not available.
Expand Down
Loading
Loading