TypeScript
fix(desktop): ask once per site before a preview page reads the clipboard (#26173)
Julius Marminge3ae672f82e17
diff --git a/apps/desktop/src/preview/BrowserSession.test.ts b/apps/desktop/src/preview/BrowserSession.test.tsindex d9b797dd045..22af4a829e0 100644--- a/apps/desktop/src/preview/BrowserSession.test.ts+++ b/apps/desktop/src/preview/BrowserSession.test.ts@@ -168,12 +168,7 @@ describe("BrowserSession", () => {return granted;};- for (const permission of [- "clipboard-read",- "clipboard-sanitized-write",- "geolocation",- "fullscreen",- ]) {+ for (const permission of ["clipboard-sanitized-write", "geolocation", "fullscreen"]) {assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);assert.isTrue(checkHandler(null, permission) as boolean,@@ -226,6 +221,55 @@ describe("BrowserSession", () => {}).pipe(Effect.provide(layer)),);+ it.effect("asks once per origin before a page reads the clipboard", () =>+ Effect.gen(function* () {+ const browserSessions = yield* BrowserSession.BrowserSession;+ const partition = yield* browserSessions.getPartition("scope-a");+ yield* browserSessions.getSession("scope-a");+ const browserSession = sessions.get(partition);+ assert.isDefined(browserSession);+ const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];+ const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];+ assert.isFunction(requestHandler);+ assert.isFunction(checkHandler);++ const readClipboard = (requestingUrl: string) =>+ Effect.callback<boolean>((resume) => {+ requestHandler(+ null,+ "clipboard-read",+ (granted: boolean) => resume(Effect.succeed(granted)),+ { requestingUrl, isMainFrame: true },+ );+ });+ const checkClipboard = (origin: string): boolean =>+ checkHandler(null, "clipboard-read", origin, {}) as boolean;++ showMessageBox.mockReset();+ showMessageBox.mockReturnValueOnce(0).mockReturnValueOnce(1);++ assert.isFalse(checkClipboard("https://allowed.test"));+ assert.isTrue(yield* readClipboard("https://allowed.test/page"));+ assert.strictEqual(showMessageBox.mock.calls.length, 1);+ assert.strictEqual(+ showMessageBox.mock.calls[0]?.[0].message,+ "https://allowed.test wants to see text and images copied to the clipboard",+ );+ assert.deepStrictEqual(showMessageBox.mock.calls[0]?.[0].buttons, ["Allow", "Block"]);+ // Enter must not accept a prompt the page raised while the user was typing.+ assert.strictEqual(showMessageBox.mock.calls[0]?.[0].defaultId, 1);++ assert.isTrue(yield* readClipboard("https://allowed.test/other"));+ assert.isTrue(checkClipboard("https://allowed.test"));++ assert.isFalse(yield* readClipboard("https://blocked.test/"));+ assert.isFalse(yield* readClipboard("https://blocked.test/again"));+ assert.isFalse(checkClipboard("https://blocked.test"));+ assert.isTrue(checkClipboard("https://allowed.test"));+ assert.strictEqual(showMessageBox.mock.calls.length, 2);+ }).pipe(Effect.provide(layer)),+ );+it.effect("clears a partition whose session has not been opened yet", () =>Effect.gen(function* () {const browserSessions = yield* BrowserSession.BrowserSession;diff --git a/apps/desktop/src/preview/BrowserSession.ts b/apps/desktop/src/preview/BrowserSession.tsindex 0f900d521b7..2ea7efdb88e 100644--- a/apps/desktop/src/preview/BrowserSession.ts+++ b/apps/desktop/src/preview/BrowserSession.ts@@ -20,7 +20,6 @@ export type BrowserSessionPartitionNamespace = "profile";// Electron's clipboard API uses clipboard-sanitized-write and checks both permission handlers.const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([- "clipboard-read","clipboard-sanitized-write","geolocation",// DesktopWindow confines HTML fullscreen to the guest's webview.@@ -55,6 +54,19 @@ const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null =>const MAX_PROMPT_URL_LENGTH = 300;+const truncateForPrompt = (text: string): string =>+ text.length > MAX_PROMPT_URL_LENGTH ? `${text.slice(0, MAX_PROMPT_URL_LENGTH)}…` : text;++const permissionOrigin = (rawUrl: string | undefined): string | null => {+ if (!rawUrl) return null;+ try {+ const { origin } = new URL(rawUrl);+ return origin === "null" ? null : origin;+ } catch {+ return null;+ }+};+export class BrowserSessionPartitionDerivationError extends Schema.TaggedError<BrowserSessionPartitionDerivationError>()("BrowserSessionPartitionDerivationError",{@@ -175,47 +187,70 @@ export const make = Effect.gen(function* BrowserSessionMake() {const electronDialog = yield* ElectronDialog.ElectronDialog;const runFork = Effect.runForkWith(yield* Effect.context<never>());// One prompt at a time, so a page cannot stack dialogs by looping a deep link.- let externalPromptOpen = false;- /** Electron launches external protocols after granting openExternal; untrusted pages require confirmation. */- const confirmOpenExternal = (+ let permissionPromptOpen = false;+ /** Settles with `undefined` when the user gave no answer: another prompt was open or the dialog failed. */+ const promptPermission = (requester: WebContents | null,- rawUrl: string | undefined,- callback: (granted: boolean) => void,+ prompt: {+ readonly buttons: readonly [allow: string, deny: string];+ readonly message: string;+ readonly detail?: string;+ },+ callback: (answer: boolean | undefined) => void,): void => {- const url = externalProtocolPromptUrl(rawUrl);- if (url === null || externalPromptOpen) {- callback(false);+ if (permissionPromptOpen) {+ callback(undefined);return;}- externalPromptOpen = true;- const settle = (granted: boolean) =>+ permissionPromptOpen = true;+ const settle = (answer: boolean | undefined) =>Effect.sync(() => {- externalPromptOpen = false;- callback(granted);+ permissionPromptOpen = false;+ callback(answer);});- const shownUrl =- url.length > MAX_PROMPT_URL_LENGTH ? `${url.slice(0, MAX_PROMPT_URL_LENGTH)}…` : url;runFork(electronDialog.showMessageBox({type: "question",- buttons: ["Open", "Cancel"],- defaultId: 0,+ buttons: [...prompt.buttons],+ // Default to deny so an Enter typed into the page cannot accept a prompt it raised.+ defaultId: 1,cancelId: 1,- message: `Open this ${new URL(url).protocol.slice(0, -1)} link?`,- detail: `A page in the browser wants to open another application:\n\n${shownUrl}`,+ message: prompt.message,+ ...(prompt.detail === undefined ? {} : { detail: prompt.detail }),},previewHostWindow(requester),).pipe(- Effect.map(({ response }) => response === 0),- Effect.orElseSucceed(() => false),+ Effect.map(({ response }): boolean | undefined => response === 0),+ Effect.orElseSucceed(() => undefined),Effect.flatMap(settle),- Effect.onInterrupt(() => settle(false)),+ Effect.onInterrupt(() => settle(undefined)),),);};+ /** Electron launches external protocols after granting openExternal; untrusted pages require confirmation. */+ const confirmOpenExternal = (+ requester: WebContents | null,+ rawUrl: string | undefined,+ callback: (granted: boolean) => void,+ ): void => {+ const url = externalProtocolPromptUrl(rawUrl);+ if (url === null) {+ callback(false);+ return;+ }+ promptPermission(+ requester,+ {+ buttons: ["Open", "Cancel"],+ message: `Open this ${new URL(url).protocol.slice(0, -1)} link?`,+ detail: `A page in the browser wants to open another application:\n\n${truncateForPrompt(url)}`,+ },+ (answer) => callback(answer === true),+ );+ };const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());const getPartition = Effect.fn("BrowserSession.getPartition")(function* (@@ -248,6 +283,35 @@ export const make = Effect.gen(function* BrowserSessionMake() {return Effect.try({try: () => {const browserSession = session.fromPartition(partition);+ // Like Chrome, clipboard reads ask once per origin; both answers last for the session.+ const clipboardReadDecisions = new Map<string, boolean>();+ const confirmClipboardRead = (+ requester: WebContents,+ rawUrl: string | undefined,+ callback: (granted: boolean) => void,+ ): void => {+ const origin = permissionOrigin(rawUrl);+ if (origin === null) {+ callback(false);+ return;+ }+ const remembered = clipboardReadDecisions.get(origin);+ if (remembered !== undefined) {+ callback(remembered);+ return;+ }+ promptPermission(+ requester,+ {+ buttons: ["Allow", "Block"],+ message: `${truncateForPrompt(origin)} wants to see text and images copied to the clipboard`,+ },+ (answer) => {+ if (answer !== undefined) clipboardReadDecisions.set(origin, answer);+ callback(answer === true);+ },+ );+ };// Rewriting Electron's native User-Agent makes Turnstile fail integrity checks with error 600010.browserSession.setPermissionRequestHandler((webContents, permission, callback, details) => {@@ -259,11 +323,21 @@ export const make = Effect.gen(function* BrowserSessionMake() {);return;}+ if (permission === "clipboard-read") {+ confirmClipboardRead(+ webContents,+ "requestingUrl" in details ? details.requestingUrl : undefined,+ callback,+ );+ return;+ }callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));},);- browserSession.setPermissionCheckHandler((_webContents, permission) =>- ALLOWED_PREVIEW_PERMISSIONS.has(permission),+ browserSession.setPermissionCheckHandler((_webContents, permission, requestingOrigin) =>+ permission === "clipboard-read"+ ? clipboardReadDecisions.get(permissionOrigin(requestingOrigin) ?? "") === true+ : ALLOWED_PREVIEW_PERMISSIONS.has(permission),);const next = new Map(sessions);next.set(partition, browserSession);