Skip to content
Closed
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
7 changes: 7 additions & 0 deletions apps/desktop/src/host.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
7 changes: 5 additions & 2 deletions apps/desktop/src/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -133,7 +133,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(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;
Expand Down
13 changes: 12 additions & 1 deletion apps/desktop/tests/host.test.mjs
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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;
Expand Down
104 changes: 104 additions & 0 deletions src/canvas/systemClipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
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<Blob> };

/**
* 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") 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<Blob>(
new Error(tNow("errors.files.clipboardRead")),
);
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;
}

/** Browsers only accept PNG as clipboard image data, so other formats are re-encoded. */
export async function pngBlob(blob: Blob): Promise<Blob> {
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<Blob>((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<Clipboard, "write" | "writeText">;
createItem?: (items: Record<string, Promise<Blob>>) => ClipboardItem;
toPng?: (blob: Blob) => Promise<Blob>;
}

/**
* 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<void> {
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"),
);
}
}
34 changes: 30 additions & 4 deletions src/canvas/workspace/useWorkspaceTransfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 = () => {
Expand Down
6 changes: 6 additions & 0 deletions src/i18n/messages/en-US/canvasWorkspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
4 changes: 4 additions & 0 deletions src/i18n/messages/en-US/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
6 changes: 6 additions & 0 deletions src/i18n/messages/zh-CN/canvasWorkspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
4 changes: 4 additions & 0 deletions src/i18n/messages/zh-CN/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": "编辑结果来源",
Expand Down
Loading
Loading