From 0035b518d8fbddedca76ab08decf8cca3309f8bb Mon Sep 17 00:00:00 2001 From: Toprak <64380154+Labu1@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:28:39 +0300 Subject: [PATCH 1/2] [feat] canvas: copy a selected image or text node to the system clipboard Ctrl/Cmd+C on the canvas only filled the in-app clipboard, so a copied image node could not be pasted into an email draft, chat composer or slide editor. When exactly one text or image node is copied, also write its plain text or PNG image data to the system clipboard, reusing the bytes the in-app copy already captures. The write starts inside the shortcut's user activation and success is reported only after the platform accepts it; missing media, unsupported browsers and rejected writes show bilingual messages that keep the in-app copy and suggest downloading instead. In-app paste is unchanged. The desktop session denied every permission, which also blocked clipboard writes; it now grants clipboard-sanitized-write only. Fixes #474. --- apps/desktop/src/main.mjs | 5 +- src/canvas/systemClipboard.ts | 102 ++++++++++++++++ src/canvas/workspace/useWorkspaceTransfer.ts | 34 +++++- src/i18n/messages/en-US/canvasWorkspace.ts | 6 + src/i18n/messages/en-US/errors.ts | 4 + src/i18n/messages/zh-CN/canvasWorkspace.ts | 6 + src/i18n/messages/zh-CN/errors.ts | 4 + tests/systemClipboard.test.ts | 118 +++++++++++++++++++ 8 files changed, 274 insertions(+), 5 deletions(-) create mode 100644 src/canvas/systemClipboard.ts create mode 100644 tests/systemClipboard.test.ts diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs index c1ba6060c..3aa554f23 100644 --- a/apps/desktop/src/main.mjs +++ b/apps/desktop/src/main.mjs @@ -133,7 +133,10 @@ async function start() { }); await host.ready; const ownedSession = session.fromPartition('persist:opendirector'); - ownedSession.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)); + // Copying a canvas node to other apps writes the system clipboard; reading + // it and every other permission stay denied. + ownedSession.setPermissionRequestHandler((_contents, permission, callback) => + callback(permission === 'clipboard-sanitized-write')); let projectSubscription; ownedSession.protocol.handle('opendirector', request => proxyRequest(request, host, async (url, options) => { const pathname = new URL(url).pathname; diff --git a/src/canvas/systemClipboard.ts b/src/canvas/systemClipboard.ts new file mode 100644 index 000000000..11a8aed63 --- /dev/null +++ b/src/canvas/systemClipboard.ts @@ -0,0 +1,102 @@ +import { tNow } from "../i18n/messages.ts"; +import type { ClipboardMedia } from "./clipboardMedia.ts"; +import type { CanvasFragment } from "./operations.ts"; + +/** What a canvas copy offers other apps besides the in-app fragment. */ +export type SystemClipboardPayload = + | { kind: "text"; text: string } + | { kind: "image"; blob: Promise }; + +/** + * Only a single text or image node has an unambiguous external form; other + * selections stay in-app so the system clipboard is not filled with a guess. + */ +export function systemClipboardPayload( + fragment: CanvasFragment, + media: ClipboardMedia, +): SystemClipboardPayload | null { + if (fragment.nodes.length !== 1) return null; + const node = fragment.nodes[0]!; + if (node.type === "text") + return node.data.text ? { kind: "text", text: node.data.text } : null; + if (node.type !== "image" || !node.data.src) return null; + if (node.data.assetState === "missing") { + const missing = Promise.reject( + new Error(tNow("errors.files.clipboardRead")), + ); + missing.catch(() => {}); + return { kind: "image", blob: missing }; + } + const blob = media.blobs.get(node.data.src); + return blob ? { kind: "image", blob } : null; +} + +/** Browsers only accept PNG as clipboard image data, so other formats are re-encoded. */ +export async function pngBlob(blob: Blob): Promise { + if (blob.type === "image/png") return blob; + const bitmap = await createImageBitmap(blob); + try { + const canvas = document.createElement("canvas"); + canvas.width = bitmap.width; + canvas.height = bitmap.height; + const context = canvas.getContext("2d"); + if (!context) throw new Error(tNow("errors.files.clipboardRead")); + context.drawImage(bitmap, 0, 0); + return await new Promise((resolve, reject) => + canvas.toBlob( + (png) => + png ? resolve(png) : reject(new Error(tNow("errors.files.clipboardRead"))), + "image/png", + ), + ); + } finally { + bitmap.close(); + } +} + +export interface SystemClipboardDeps { + clipboard?: Pick; + createItem?: (items: Record>) => ClipboardItem; + toPng?: (blob: Blob) => Promise; +} + +/** + * Writes the payload to the system clipboard. The write starts synchronously, + * inside the shortcut's user activation, and resolves only once the platform + * accepted it; failures carry a localized reason. + */ +export async function writeSystemClipboard( + payload: SystemClipboardPayload, + { + clipboard = globalThis.navigator?.clipboard, + createItem = globalThis.ClipboardItem + ? (items) => new ClipboardItem(items) + : undefined, + toPng = pngBlob, + }: SystemClipboardDeps = {}, +): Promise { + if (!clipboard) throw new Error(tNow("errors.files.clipboardUnavailable")); + if (payload.kind === "text") { + try { + await clipboard.writeText(payload.text); + } catch { + throw new Error(tNow("errors.files.clipboardWrite")); + } + return; + } + if (!createItem) throw new Error(tNow("errors.files.clipboardUnavailable")); + let readFailed = false; + const png = payload.blob.then(toPng).catch(() => { + readFailed = true; + throw new Error(tNow("errors.files.clipboardRead")); + }); + try { + await clipboard.write([createItem({ "image/png": png })]); + } catch { + // The write may reject before the image settles; report whichever failed. + await png.catch(() => {}); + throw new Error( + tNow(readFailed ? "errors.files.clipboardRead" : "errors.files.clipboardWrite"), + ); + } +} diff --git a/src/canvas/workspace/useWorkspaceTransfer.ts b/src/canvas/workspace/useWorkspaceTransfer.ts index 52619ada8..76da63608 100644 --- a/src/canvas/workspace/useWorkspaceTransfer.ts +++ b/src/canvas/workspace/useWorkspaceTransfer.ts @@ -38,6 +38,7 @@ import { transferClipboardMedia, type ClipboardMedia, } from "../clipboardMedia.ts"; +import { systemClipboardPayload, writeSystemClipboard } from "../systemClipboard.ts"; import { resourceNodeData } from "../projectAssets"; import { persistCurrentDocument } from "../projectManagement"; import { measureSubjectNodeHeight } from "../subjectLayoutMeasurement.ts"; @@ -459,10 +460,35 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { ); clipboardMedia.current = captureMedia(clipboard.current); pasteCount.current = 0; - notify( - t("canvas.workspace.toast.copied", { - count: clipboard.current.nodes.length, - }), + const payload = systemClipboardPayload( + clipboard.current, + clipboardMedia.current, + ); + if (!payload) { + notify( + t("canvas.workspace.toast.copied", { + count: clipboard.current.nodes.length, + }), + ); + return; + } + // Start the write inside the shortcut's user activation and report success + // only once the platform clipboard accepted it. + writeSystemClipboard(payload).then( + () => + notify( + t( + payload.kind === "image" + ? "canvas.workspace.toast.copiedImage" + : "canvas.workspace.toast.copiedText", + ), + ), + (error: unknown) => + notify( + t("canvas.workspace.toast.copiedInAppOnly", { + error: errorMessage(error), + }), + ), ); }; const cut = () => { diff --git a/src/i18n/messages/en-US/canvasWorkspace.ts b/src/i18n/messages/en-US/canvasWorkspace.ts index 7c2ddf326..b93de4025 100644 --- a/src/i18n/messages/en-US/canvasWorkspace.ts +++ b/src/i18n/messages/en-US/canvasWorkspace.ts @@ -223,6 +223,12 @@ export const canvasWorkspace = { one: "Copied {count} node", other: "Copied {count} nodes", }, + "canvas.workspace.toast.copiedImage": + "Copied the image. Paste it on the canvas or in another app.", + "canvas.workspace.toast.copiedText": + "Copied the text. Paste it on the canvas or in another app.", + "canvas.workspace.toast.copiedInAppOnly": + "Copied for pasting on the canvas only. {error}", "canvas.workspace.toast.selectEditable": "Select an editable node first.", "canvas.workspace.toast.cutLocked": "The node or its members are protected by a locked reference; nothing was cut.", diff --git a/src/i18n/messages/en-US/errors.ts b/src/i18n/messages/en-US/errors.ts index 7c68ae9f2..df498d4f3 100644 --- a/src/i18n/messages/en-US/errors.ts +++ b/src/i18n/messages/en-US/errors.ts @@ -799,6 +799,10 @@ export const errors = { "errors.files.clipboardRead": "Could not read the media.", "errors.files.clipboardExpired": "The copied media has expired. Copy it again.", + "errors.files.clipboardUnavailable": + "This browser cannot write to the system clipboard. Download the asset instead.", + "errors.files.clipboardWrite": + "The system clipboard rejected the copy. Allow clipboard access or download the asset instead.", "errors.media.sharedTable": "The canvas shared-media table is invalid.", "errors.media.sharedMissing": "The canvas references shared media that does not exist.", diff --git a/src/i18n/messages/zh-CN/canvasWorkspace.ts b/src/i18n/messages/zh-CN/canvasWorkspace.ts index 8763288cf..7c7f63bd1 100644 --- a/src/i18n/messages/zh-CN/canvasWorkspace.ts +++ b/src/i18n/messages/zh-CN/canvasWorkspace.ts @@ -216,6 +216,12 @@ export const canvasWorkspace = { one: "已复制 {count} 个节点", other: "已复制 {count} 个节点", }, + "canvas.workspace.toast.copiedImage": + "已复制图片,可粘贴到画布或其他应用。", + "canvas.workspace.toast.copiedText": + "已复制文本,可粘贴到画布或其他应用。", + "canvas.workspace.toast.copiedInAppOnly": + "已复制,仅可粘贴到画布。{error}", "canvas.workspace.toast.selectEditable": "请先选择可编辑的节点。", "canvas.workspace.toast.cutLocked": "节点或其成员受锁定引用保护,未剪切。", "canvas.workspace.toast.cut": { diff --git a/src/i18n/messages/zh-CN/errors.ts b/src/i18n/messages/zh-CN/errors.ts index 652cb0cff..5289ff3e1 100644 --- a/src/i18n/messages/zh-CN/errors.ts +++ b/src/i18n/messages/zh-CN/errors.ts @@ -604,6 +604,10 @@ export const errors = { "errors.files.read": "无法读取 {name}", "errors.files.clipboardRead": "素材读取失败。", "errors.files.clipboardExpired": "复制的素材已失效,请重新复制。", + "errors.files.clipboardUnavailable": + "当前浏览器无法写入系统剪贴板,请改为下载素材。", + "errors.files.clipboardWrite": + "系统剪贴板拒绝了复制,请允许剪贴板访问或改为下载素材。", "errors.media.sharedTable": "画布共享媒体表无效。", "errors.media.sharedMissing": "画布引用了不存在的共享媒体。", "errors.refEvidence.editSource": "编辑结果来源", diff --git a/tests/systemClipboard.test.ts b/tests/systemClipboard.test.ts new file mode 100644 index 000000000..3352192c9 --- /dev/null +++ b/tests/systemClipboard.test.ts @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { captureClipboardMedia } from "../src/canvas/clipboardMedia.ts"; +import { createNode } from "../src/canvas/model.ts"; +import type { CanvasFragment } from "../src/canvas/operations.ts"; +import { + systemClipboardPayload, + writeSystemClipboard, +} from "../src/canvas/systemClipboard.ts"; +import { tNow } from "../src/i18n/messages.ts"; + +const capture = (fragment: CanvasFragment, blob = new Blob(["png"], { type: "image/png" })) => + captureClipboardMedia("project", fragment, { read: async () => blob }); + +test("a single text node offers its text with line breaks and Unicode", async () => { + const text = "第一行\nSecond line"; + const fragment: CanvasFragment = { + nodes: [createNode("text", undefined, { text })], + edges: [], + }; + const payload = systemClipboardPayload(fragment, capture(fragment)); + assert.deepEqual(payload, { kind: "text", text }); + let written = ""; + await writeSystemClipboard(payload!, { + clipboard: { + writeText: async (value: string) => { + written = value; + }, + write: async () => assert.fail("text must use writeText"), + }, + }); + assert.equal(written, text); +}); + +test("a single image node writes PNG clipboard data from the captured bytes", async () => { + const fragment: CanvasFragment = { + nodes: [createNode("image", undefined, { src: "blob:image", mimeType: "image/jpeg" })], + edges: [], + }; + const jpeg = new Blob(["jpg"], { type: "image/jpeg" }); + const png = new Blob(["png"], { type: "image/png" }); + const payload = systemClipboardPayload(fragment, capture(fragment, jpeg)); + assert.equal(payload?.kind, "image"); + const items: Record>[] = []; + await writeSystemClipboard(payload!, { + createItem: (item) => { + items.push(item); + return item as unknown as ClipboardItem; + }, + toPng: async (blob) => { + assert.equal(blob, jpeg); + return png; + }, + clipboard: { + write: async ([item]) => { + await (item as unknown as Record>)["image/png"]; + }, + writeText: async () => assert.fail("images must use write"), + }, + }); + assert.deepEqual(Object.keys(items[0]!), ["image/png"]); + assert.equal(await items[0]!["image/png"], png); +}); + +test("multi-node and non-media selections stay in-app", () => { + const several: CanvasFragment = { + nodes: [createNode("text", undefined, { text: "a" }), createNode("text", undefined, { text: "b" })], + edges: [], + }; + assert.equal(systemClipboardPayload(several, capture(several)), null); + const empty: CanvasFragment = { nodes: [createNode("text", undefined, { text: "" })], edges: [] }; + assert.equal(systemClipboardPayload(empty, capture(empty)), null); +}); + +test("missing media and rejected writes fail with localized reasons", async () => { + const fragment: CanvasFragment = { + nodes: [createNode("image", undefined, { src: "blob:gone", assetState: "missing" })], + edges: [], + }; + const payload = systemClipboardPayload(fragment, capture(fragment)); + const deps = { + createItem: (item: Record>) => item as unknown as ClipboardItem, + toPng: async (blob: Blob) => blob, + }; + await assert.rejects( + writeSystemClipboard(payload!, { + ...deps, + clipboard: { + write: async ([item]) => { + await (item as unknown as Record>)["image/png"]; + }, + writeText: async () => {}, + }, + }), + { message: tNow("errors.files.clipboardRead") }, + ); + await assert.rejects( + writeSystemClipboard( + { kind: "text", text: "hello" }, + { + clipboard: { + write: async () => {}, + writeText: async () => { + throw new DOMException("denied", "NotAllowedError"); + }, + }, + }, + ), + { message: tNow("errors.files.clipboardWrite") }, + ); + await assert.rejects( + writeSystemClipboard( + { kind: "image", blob: Promise.resolve(new Blob()) }, + { ...deps, createItem: undefined, clipboard: { write: async () => {}, writeText: async () => {} } }, + ), + { message: tNow("errors.files.clipboardUnavailable") }, + ); +}); From 2338e585755b064f7ea31bdaecc47f7f6127f6e5 Mon Sep 17 00:00:00 2001 From: Toprak <64380154+Labu1@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:56:07 +0300 Subject: [PATCH 2/2] [feat] canvas: restrict desktop clipboard writes to the app origin Grant clipboard-sanitized-write only to opendirector://app in both the Electron permission request and check handlers, and give missing image nodes without a src the in-app-only copy notice. --- apps/desktop/src/host.mjs | 7 +++++++ apps/desktop/src/main.mjs | 10 +++++----- apps/desktop/tests/host.test.mjs | 13 ++++++++++++- src/canvas/systemClipboard.ts | 4 +++- tests/systemClipboard.test.ts | 20 ++++++++++++++++++++ 5 files changed, 47 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/host.mjs b/apps/desktop/src/host.mjs index 068ffc871..54f2c7ea7 100644 --- a/apps/desktop/src/host.mjs +++ b/apps/desktop/src/host.mjs @@ -100,6 +100,13 @@ export function ownedURL(value) { return url.protocol === 'opendirector:' && url.hostname === 'app' && !url.port && !url.username && !url.password; } +// The app page may write the system clipboard so canvas copies reach other +// apps; reading it, every other permission and every other origin stay denied. +export function grantsPermission(permission, origin) { + if (permission !== 'clipboard-sanitized-write' || typeof origin !== 'string') return false; + try { return ownedURL(origin); } catch { return false; } +} + export async function proxyRequest(request, host, fetcher) { if (!ownedURL(request.url) || !host.url) return new Response(null, { status: 403 }); const incoming = new URL(request.url); diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs index 3aa554f23..ddeae851a 100644 --- a/apps/desktop/src/main.mjs +++ b/apps/desktop/src/main.mjs @@ -4,7 +4,7 @@ import { createWriteStream, mkdirSync, readFileSync, writeFileSync } from 'node: import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { homedir } from 'node:os'; -import { Host, ownedURL, proxyRequest } from './host.mjs'; +import { Host, grantsPermission, ownedURL, proxyRequest } from './host.mjs'; import { messages, localeFor } from './locale.mjs'; import { registerCommand, commandPath } from './command.mjs'; @@ -133,10 +133,10 @@ async function start() { }); await host.ready; const ownedSession = session.fromPartition('persist:opendirector'); - // Copying a canvas node to other apps writes the system clipboard; reading - // it and every other permission stay denied. - ownedSession.setPermissionRequestHandler((_contents, permission, callback) => - callback(permission === 'clipboard-sanitized-write')); + ownedSession.setPermissionRequestHandler((_contents, permission, callback, details) => + callback(grantsPermission(permission, details?.requestingUrl))); + ownedSession.setPermissionCheckHandler((_contents, permission, requestingOrigin) => + grantsPermission(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/tests/host.test.mjs b/apps/desktop/tests/host.test.mjs index 9e9590700..c97136654 100644 --- a/apps/desktop/tests/host.test.mjs +++ b/apps/desktop/tests/host.test.mjs @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { eventSchema, proxyRequest } from '../src/host.mjs'; +import { eventSchema, grantsPermission, proxyRequest } from '../src/host.mjs'; import { messages } from '../src/locale.mjs'; import { registerCommand } from '../src/command.mjs'; import { mkdtemp, readlink, rm, writeFile, readFile } from 'node:fs/promises'; @@ -15,6 +15,17 @@ test('Host readiness rejects foreign origins and malformed control messages', () assert.equal(eventSchema.safeParse({ ...ready, url: 'http://127.0.0.1:23456' }).success, true); }); +test('Only the app page may write the system clipboard', () => { + assert.equal(grantsPermission('clipboard-sanitized-write', 'opendirector://app'), true); + assert.equal(grantsPermission('clipboard-sanitized-write', 'opendirector://app/?traceProject=x'), true); + for (const origin of ['https://evil.test', 'opendirector://other', 'opendirector://u:p@app', 'file:///', '', 'not a url', undefined]) { + assert.equal(grantsPermission('clipboard-sanitized-write', origin), false); + } + for (const permission of ['clipboard-read', 'media', 'notifications', 'geolocation']) { + assert.equal(grantsPermission(permission, 'opendirector://app'), false); + } +}); + test('Proxy authenticates only the owned Host and streams media range responses', async () => { const host = { url: 'http://127.0.0.1:23456', token: 'private-token' }; let calls = 0; diff --git a/src/canvas/systemClipboard.ts b/src/canvas/systemClipboard.ts index 11a8aed63..6d43799a9 100644 --- a/src/canvas/systemClipboard.ts +++ b/src/canvas/systemClipboard.ts @@ -19,7 +19,8 @@ export function systemClipboardPayload( const node = fragment.nodes[0]!; if (node.type === "text") return node.data.text ? { kind: "text", text: node.data.text } : null; - if (node.type !== "image" || !node.data.src) return null; + if (node.type !== "image") return null; + // A missing asset may have no src left; it still gets the in-app-only notice. if (node.data.assetState === "missing") { const missing = Promise.reject( new Error(tNow("errors.files.clipboardRead")), @@ -27,6 +28,7 @@ export function systemClipboardPayload( missing.catch(() => {}); return { kind: "image", blob: missing }; } + if (!node.data.src) return null; const blob = media.blobs.get(node.data.src); return blob ? { kind: "image", blob } : null; } diff --git a/tests/systemClipboard.test.ts b/tests/systemClipboard.test.ts index 3352192c9..70754a732 100644 --- a/tests/systemClipboard.test.ts +++ b/tests/systemClipboard.test.ts @@ -94,6 +94,26 @@ test("missing media and rejected writes fail with localized reasons", async () = }), { message: tNow("errors.files.clipboardRead") }, ); + // A missing asset can lose its src entirely; it must still get the + // in-app-only notice instead of the plain "copied" toast. + const unsourced: CanvasFragment = { + nodes: [createNode("image", undefined, { src: "", assetState: "missing" })], + edges: [], + }; + const unsourcedPayload = systemClipboardPayload(unsourced, capture(unsourced)); + assert.equal(unsourcedPayload?.kind, "image"); + await assert.rejects( + writeSystemClipboard(unsourcedPayload!, { + ...deps, + clipboard: { + write: async ([item]) => { + await (item as unknown as Record>)["image/png"]; + }, + writeText: async () => {}, + }, + }), + { message: tNow("errors.files.clipboardRead") }, + ); await assert.rejects( writeSystemClipboard( { kind: "text", text: "hello" },