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
69 changes: 68 additions & 1 deletion 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 @@ -82,6 +82,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: a click asks for
// clipboard-sanitized-write, and a write without one asks for the read/write
// pair the application never needs. Both paths are checked, so a policy that
// grants the read/write name to satisfy a scripted write cannot pass either.
await waitFor(() => window.webContents.executeJavaScript('document.hasFocus()'), 'Renderer did not take document focus before the clipboard check');
await assertClipboardDenied(window);
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");
Expand Down Expand Up @@ -248,13 +256,72 @@ 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');
return result;
}

// A write without user activation asks Chromium for the read/write clipboard
// pair, the name that also opens `navigator.clipboard.readText`. Every copy in
// the shared UI starts from a click, so the shell denies this path, and the
// denial is part of the contract: it must neither reach the system clipboard nor
// stay pending.
async function assertClipboardDenied(window) {
const before = await clipboard.readText();
const outcome = await window.webContents.executeJavaScript(
`navigator.clipboard.writeText('opendirector-smoke-denied').then(() => 'granted', error => error.name)`, false);
if (outcome !== 'NotAllowedError') throw new Error(`A clipboard write without user activation was not denied: ${outcome}`);
const after = await clipboard.readText();
if (after !== before) throw new Error(`A denied clipboard write changed the system clipboard: ${JSON.stringify(before)} became ${JSON.stringify(after)}`);
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: ${read}`);
}

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);
// The renderer promise settles before the system clipboard holds the value:
// 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)}`);
} finally {
// Give back the text this run found so a developer smoke does not replace the
// clipboard of the session that launched it. Non-text formats are not kept.
clipboard.writeText(previous);
}
}

// A denial here is invisible to the renderer: `requestFullscreen`'s promise stays
// pending, so the player's button looks dead instead of reporting a refusal.
// Assert the entry, the exit, and that a refusal surfaces at all.
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');
}

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 @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
36 changes: 36 additions & 0 deletions apps/desktop/src/permissions.mjs
Original file line number Diff line number Diff line change
@@ -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 belongs to a call the renderer makes; a permission without a caller is
* a capability, not a fix. 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` from a click: Chromium asks for
// clipboard-sanitized-write only when the write is sanitized and a click is
// the activation, and for the read/write pair otherwise. The renderer copies
// from click handlers only, so the read/write name stays denied: it also
// grants `navigator.clipboard.readText`, and this application never reads the
// system clipboard. Granting it would be a policy change for a future
// activation-free copy, not a repair for a broken copy button.
'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;
}
}
43 changes: 43 additions & 0 deletions apps/desktop/tests/permissions.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
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);
// The check handler answers a serialized origin, which carries no path.
assert.equal(permissionGranted(permission, 'opendirector://app'), true, permission);
}
});

test('A clipboard write without user activation stays denied', () => {
// Chromium reports the read/write clipboard permission as clipboard-read, so
// granting it to satisfy a scripted write would also grant
// `navigator.clipboard.readText`. Every copy in the shared UI starts from a
// click and asks for clipboard-sanitized-write instead, so the shell keeps this
// name denied and the installed smoke asserts the denial.
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 click-activated `navigator.clipboard.writeText` 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. The installed smoke test asserts that a click-activated copy reaches the system clipboard, that a write without user activation is refused and leaves the clipboard untouched, and 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 会一直挂起,播放器的全屏按钮会静默失效。已安装包的冒烟检查会断言点击激活的复制确实写入系统剪贴板、无用户激活的写入被拒绝且不改变剪贴板内容,并断言全屏能够进入也能够退出。新增任何渲染进程权限都属于策略变更,不是界面细节。

## 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,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, asserts that a click-activated renderer copy reaches the system clipboard and that a write without user activation is refused, enters and exits fullscreen, 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 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 measure each activation path: in Electron 45 a scripted clipboard write asks for `clipboard-read`, the read/write name that also opens `navigator.clipboard.readText`, while the same write from a click asks for `clipboard-sanitized-write`; the shell grants only the click-activated name, and the smoke asserts that the scripted path is refused with `NotAllowedError` and leaves the clipboard unchanged. 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; the packaged run on each platform establishes that its system clipboard and window server behave.

## Terminal command

Expand Down
Loading
Loading