fix(desktop): copy images from HTML previews (#17555)

This commit is contained in:
Bilal Bakr authored and GitHub committed 2026-10-10 17:43:56 -05:00
1 parent 0442f5bfcc
commit c8b89a01d7
6 files changed
+359 -15

No files matched your search

@@ -5,6 +5,7 @@ import {
MAX_FAVICON_RESPONSE_BYTES,
captureFavicon,
selectFaviconCandidates,
sourceDimensions,
} from "./FaviconCapture.ts";
const PNG = "data:image/png;base64,cG5n";
@@ -47,6 +48,26 @@ function sourceGif(
return buffer;
}
it.each([
["logical pixels", sourceGif(2048, 1024), { width: 2048, height: 1024 }],
[
"cumulative frame pixels",
sourceGif(1024, 1024, 1024, 1024, [{ width: 1024, height: 1024 }]),
{ width: 1024, height: 1024 },
],
])("uses the caller's GIF limit for %s while keeping the favicon limit", (_, gif, dimensions) => {
expect(sourceDimensions(gif)).toBeNull();
expect(sourceDimensions(gif, 8_388_608)).toEqual(dimensions);
});
it("rejects GIF frames exceeding the caller's cumulative pixel limit", () => {
const gif = sourceGif(2048, 2048, 2048, 2048, [
{ width: 2048, height: 2048 },
{ width: 2048, height: 2048 },
]);
expect(sourceDimensions(gif, 8_388_608)).toBeNull();
});
function sourceJpeg(
width: number,
height: number,
+18 -12
View File
@@ -246,14 +246,17 @@ interface ImageDimensions {
readonly height: number;
}
function safeDimensions(dimensions: ImageDimensions | null): dimensions is ImageDimensions {
function safeDimensions(
dimensions: ImageDimensions | null,
maxPixels = MAX_FAVICON_SOURCE_PIXELS,
): dimensions is ImageDimensions {
return (
dimensions !== null &&
Number.isSafeInteger(dimensions.width) &&
Number.isSafeInteger(dimensions.height) &&
dimensions.width > 0 &&
dimensions.height > 0 &&
dimensions.width * dimensions.height <= MAX_FAVICON_SOURCE_PIXELS
dimensions.width * dimensions.height <= maxPixels
);
}
@@ -276,13 +279,13 @@ function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
return null;
}
function gifDimensions(buffer: Buffer): ImageDimensions | null {
function gifDimensions(buffer: Buffer, maxPixels: number): ImageDimensions | null {
if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
return null;
}
const logicalWidth = buffer.readUInt16LE(6);
const logicalHeight = buffer.readUInt16LE(8);
if (!safeDimensions({ width: logicalWidth, height: logicalHeight })) return null;
if (!safeDimensions({ width: logicalWidth, height: logicalHeight }, maxPixels)) return null;
const packed = buffer[10]!;
let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
if (offset > buffer.byteLength) return null;
@@ -301,10 +304,10 @@ function gifDimensions(buffer: Buffer): ImageDimensions | null {
const frameHeight = buffer.readUInt16LE(offset + 7);
if (frameWidth === 0 || frameHeight === 0) return null;
framePixels += frameWidth * frameHeight;
if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
if (framePixels > maxPixels) return null;
width = Math.max(width, left + frameWidth);
height = Math.max(height, top + frameHeight);
if (!safeDimensions({ width, height })) return null;
if (!safeDimensions({ width, height }, maxPixels)) return null;
const framePacked = buffer[offset + 9]!;
offset += 10;
if ((framePacked & 0x80) !== 0) {
@@ -491,7 +494,7 @@ function dibDimensions(buffer: Buffer): ImageDimensions | null {
};
}
function icoDimensions(buffer: Buffer): ImageDimensions | null {
function icoDimensions(buffer: Buffer, maxPixels: number): ImageDimensions | null {
if (
buffer.byteLength < 22 ||
buffer.readUInt16LE(0) !== 0 ||
@@ -507,7 +510,7 @@ function icoDimensions(buffer: Buffer): ImageDimensions | null {
const offset = 6 + index * 16;
width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
if (!safeDimensions({ width, height })) return null;
if (!safeDimensions({ width, height }, maxPixels)) return null;
const byteLength = buffer.readUInt32LE(offset + 8);
const imageOffset = buffer.readUInt32LE(offset + 12);
if (
@@ -519,18 +522,21 @@ function icoDimensions(buffer: Buffer): ImageDimensions | null {
return null;
const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
if (!safeDimensions(embeddedDimensions)) return null;
if (!safeDimensions(embeddedDimensions, maxPixels)) return null;
}
return { width, height };
}
function sourceDimensions(buffer: Buffer): ImageDimensions | null {
export function sourceDimensions(
buffer: Buffer,
maxPixels = MAX_FAVICON_SOURCE_PIXELS,
): ImageDimensions | null {
return (
pngDimensions(buffer) ??
gifDimensions(buffer) ??
gifDimensions(buffer, maxPixels) ??
jpegDimensions(buffer) ??
webpDimensions(buffer) ??
icoDimensions(buffer)
icoDimensions(buffer, maxPixels)
);
}
@@ -0,0 +1,204 @@
import { beforeEach, expect, it, vi } from "vite-plus/test";
import type * as Electron from "electron";
import { copyContextMenuImage } from "./ContextMenuImage.ts";
const native = vi.hoisted(() => ({
fetch: vi.fn(),
createFromBuffer: vi.fn(),
write: vi.fn(),
image: { isEmpty: vi.fn(() => false), toPNG: vi.fn(() => Buffer.from("png")) },
}));
vi.mock("electron", () => ({
net: { fetch: native.fetch },
nativeImage: { createFromBuffer: native.createFromBuffer },
clipboard: { write: native.write },
ClipboardItem: class {
readonly blobs: Record<string, Blob>;
constructor(blobs: Record<string, Blob>) {
this.blobs = blobs;
}
},
}));
const mainFrame = { isDestroyed: vi.fn(() => false) };
const frame = { isDestroyed: vi.fn(() => false) };
const contents = {
isDestroyed: vi.fn(() => false),
copyImageAt: vi.fn(),
executeJavaScriptInIsolatedWorld: vi.fn(),
mainFrame,
};
const params = {
x: 12,
y: 34,
srcURL: "https://example.com/image.png",
frame,
};
const sourcePng = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAFklEQVR4nGP4TyFgGDVg1IBRA4aLAQBdePwur/3haQAAAABJRU5ErkJggg==",
"base64",
);
const copyImage = (overrides: Partial<typeof params> = {}) =>
copyContextMenuImage(
contents as unknown as Electron.WebContents,
{ ...params, ...overrides } as unknown as Electron.ContextMenuParams,
);
beforeEach(() => {
vi.clearAllMocks();
contents.isDestroyed.mockReturnValue(false);
frame.isDestroyed.mockReturnValue(false);
native.image.isEmpty.mockReturnValue(false);
native.createFromBuffer.mockReturnValue(native.image);
native.fetch.mockResolvedValue(new Response(Uint8Array.from(sourcePng)));
native.write.mockResolvedValue(undefined);
contents.executeJavaScriptInIsolatedWorld.mockRejectedValue(
new Error("Image could not be decoded"),
);
});
it("preserves the clipboard when the context-menu frame is missing", async () => {
await copyContextMenuImage(
contents as unknown as Electron.WebContents,
{ ...params, frame: null } as unknown as Electron.ContextMenuParams,
);
expect(contents.copyImageAt).not.toHaveBeenCalled();
expect(native.fetch).not.toHaveBeenCalled();
expect(native.write).not.toHaveBeenCalled();
});
it("keeps native image copying for the main frame", async () => {
await copyImage({ frame: mainFrame });
expect(contents.copyImageAt).toHaveBeenCalledWith(12, 34);
expect(native.fetch).not.toHaveBeenCalled();
});
it.each(["https://example.com/image.png", `data:image/png;base64,${sourcePng.toString("base64")}`])(
"copies an iframe image from %s",
async (srcURL) => {
await copyImage({ srcURL });
if (srcURL.startsWith("https:")) {
expect(native.fetch).toHaveBeenCalledWith(srcURL, {
credentials: "omit",
redirect: "error",
signal: expect.any(AbortSignal),
});
} else {
expect(native.fetch).not.toHaveBeenCalled();
}
expect(contents.copyImageAt).not.toHaveBeenCalled();
expect(native.createFromBuffer).toHaveBeenCalledWith(sourcePng);
const blob = native.write.mock.calls[0]?.[0][0].blobs["image/png"] as Blob;
expect(blob.type).toBe("image/png");
expect(Buffer.from(await blob.arrayBuffer())).toEqual(Buffer.from("png"));
},
);
it.each([
["WebP", "UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAUAmJaQAA3AA/vz0AAA="],
["GIF", "R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAkQBADs="],
])("copies %s using Chromium when nativeImage cannot decode it", async (_, base64) => {
native.fetch.mockResolvedValue(new Response(Uint8Array.from(Buffer.from(base64, "base64"))));
native.image.isEmpty.mockReturnValue(true);
contents.executeJavaScriptInIsolatedWorld.mockResolvedValue(Uint8Array.from(sourcePng).buffer);
await copyImage();
const blob = native.write.mock.calls[0]?.[0][0].blobs["image/png"] as Blob;
expect(Buffer.from(await blob.arrayBuffer())).toEqual(sourcePng);
expect(native.image.toPNG).not.toHaveBeenCalled();
});
it("preserves the clipboard if the source frame closes during Chromium decoding", async () => {
native.image.isEmpty.mockReturnValue(true);
contents.executeJavaScriptInIsolatedWorld.mockImplementation(() => {
frame.isDestroyed.mockReturnValue(true);
return Promise.resolve(Uint8Array.from(sourcePng).buffer);
});
await copyImage();
expect(native.write).not.toHaveBeenCalled();
});
it("copies a GIF larger than the favicon pixel limit", async () => {
const gif = Buffer.from("R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAkQBADs=", "base64");
gif.writeUInt16LE(2048, 6);
gif.writeUInt16LE(1024, 8);
native.fetch.mockResolvedValue(new Response(Uint8Array.from(gif)));
native.image.isEmpty.mockReturnValue(true);
contents.executeJavaScriptInIsolatedWorld.mockResolvedValue(Uint8Array.from(sourcePng).buffer);
await copyImage();
const blob = native.write.mock.calls[0]?.[0][0].blobs["image/png"] as Blob;
expect(Buffer.from(await blob.arrayBuffer())).toEqual(sourcePng);
});
it.each([
"file:///private/image.png",
"blob:https://example.com/image",
"https://user:[email protected]/image.png",
])("rejects unsupported or credential-bearing URLs: %s", async (srcURL) => {
await expect(copyImage({ srcURL })).rejects.toThrow("Unsupported image URL");
expect(native.fetch).not.toHaveBeenCalled();
expect(native.write).not.toHaveBeenCalled();
});
it("cancels responses whose declared size exceeds the limit", async () => {
const cancel = vi.fn();
native.fetch.mockResolvedValue(
new Response(new ReadableStream({ cancel }), {
headers: { "content-length": String(32 * 1024 * 1024 + 1) },
}),
);
await expect(copyImage()).rejects.toThrow("size limit");
expect(cancel).toHaveBeenCalled();
expect(native.createFromBuffer).not.toHaveBeenCalled();
});
it("cancels oversized streams without a content-length", async () => {
const cancel = vi.fn();
native.fetch.mockResolvedValue(
new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(32 * 1024 * 1024));
controller.enqueue(new Uint8Array(1));
},
cancel,
}),
),
);
await expect(copyImage()).rejects.toThrow("size limit");
expect(cancel).toHaveBeenCalled();
expect(native.write).not.toHaveBeenCalled();
});
it("preserves the clipboard when the response is not an image", async () => {
native.image.isEmpty.mockReturnValue(true);
await expect(copyImage()).rejects.toThrow("could not be decoded");
expect(native.write).not.toHaveBeenCalled();
});
it("rejects large decoded dimensions before image allocation", async () => {
const oversizedPng = Buffer.from(sourcePng);
oversizedPng.writeUInt32BE(4096, 16);
oversizedPng.writeUInt32BE(4096, 20);
native.fetch.mockResolvedValue(new Response(Uint8Array.from(oversizedPng)));
await expect(copyImage()).rejects.toThrow("size limit");
expect(native.createFromBuffer).not.toHaveBeenCalled();
expect(native.image.toPNG).not.toHaveBeenCalled();
expect(native.write).not.toHaveBeenCalled();
});
it("preserves the clipboard when the encoded PNG exceeds the limit", async () => {
native.image.toPNG.mockReturnValueOnce(Buffer.alloc(32 * 1024 * 1024 + 1));
await expect(copyImage()).rejects.toThrow("size limit");
expect(native.write).not.toHaveBeenCalled();
});
it("does not copy after the source frame closes during the request", async () => {
native.fetch.mockImplementation(() => {
frame.isDestroyed.mockReturnValue(true);
return Promise.resolve(new Response(Uint8Array.from(sourcePng)));
});
await copyImage();
expect(native.write).not.toHaveBeenCalled();
});
+104
View File
@@ -0,0 +1,104 @@
import * as Electron from "electron";
import { sourceDimensions } from "../preview/FaviconCapture.ts";
const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
export async function copyContextMenuImage(
contents: Electron.WebContents,
params: Electron.ContextMenuParams,
): Promise<void> {
const frame = params.frame;
if (contents.isDestroyed() || !frame || frame.isDestroyed()) return;
if (frame === contents.mainFrame) {
contents.copyImageAt(params.x, params.y);
return;
}
const url = new URL(params.srcURL);
if (
!["https:", "http:", "data:"].includes(url.protocol) ||
url.username ||
url.password ||
(url.protocol === "data:" && params.srcURL.length > MAX_IMAGE_BYTES * 3)
) {
throw new Error("Unsupported image URL");
}
const fetchImage = url.protocol === "data:" ? globalThis.fetch : Electron.net.fetch;
const response = await fetchImage(url.href, {
credentials: "omit",
redirect: "error",
signal: AbortSignal.timeout(10_000),
});
if (!response.ok || Number(response.headers.get("content-length")) > MAX_IMAGE_BYTES) {
await response.body?.cancel();
throw new Error("Image request failed or exceeded the size limit");
}
if (!response.body) throw new Error("Image response has no body");
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let byteLength = 0;
try {
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
byteLength += chunk.value.byteLength;
if (byteLength > MAX_IMAGE_BYTES) {
await reader.cancel();
throw new Error("Image exceeded the size limit");
}
chunks.push(chunk.value);
}
} finally {
reader.releaseLock();
}
const bytes = Buffer.concat(chunks, byteLength);
const dimensions = sourceDimensions(bytes, MAX_IMAGE_BYTES / 4);
if (
!dimensions ||
dimensions.width <= 0 ||
dimensions.height <= 0 ||
dimensions.width * dimensions.height > MAX_IMAGE_BYTES / 4
) {
throw new Error("Image dimensions exceed the size limit");
}
if (contents.isDestroyed() || frame.isDestroyed()) return;
const image = Electron.nativeImage.createFromBuffer(bytes);
let png: Buffer;
if (image.isEmpty()) {
const decoded: unknown = await contents.executeJavaScriptInIsolatedWorld(1002, [
{
code: `(async () => {
const source = Uint8Array.from(atob("${bytes.toString("base64")}"), char => char.charCodeAt(0));
const bitmap = await createImageBitmap(new Blob([source]));
try {
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_IMAGE_BYTES / 4}) {
throw new Error("Image dimensions exceed the size limit");
}
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
const context = canvas.getContext("2d");
if (!context) throw new Error("Image could not be decoded");
context.drawImage(bitmap, 0, 0);
const output = await canvas.convertToBlob({ type: "image/png" });
if (output.size > ${MAX_IMAGE_BYTES}) throw new Error("PNG exceeded the size limit");
return await output.arrayBuffer();
} finally {
bitmap.close();
}
})()`,
},
]);
if (!(decoded instanceof ArrayBuffer)) throw new Error("Image could not be decoded");
png = Buffer.from(decoded);
} else {
png = image.toPNG();
}
if (png.byteLength > MAX_IMAGE_BYTES) throw new Error("PNG exceeded the size limit");
if (contents.isDestroyed() || frame.isDestroyed()) return;
await Electron.clipboard.write([
new Electron.ClipboardItem({
"image/png": new Blob([Uint8Array.from(png)], { type: "image/png" }),
}),
]);
}
@@ -468,6 +468,10 @@ describe("DesktopWindow", () => {
let focusedContents: unknown = host.window.webContents;
const makeContents = () => {
const contents = Object.assign(new NodeEvents.EventEmitter(), {
mainFrame: {
routingId: 7,
isDestroyed: vi.fn(() => false),
} as unknown as Electron.WebFrameMain,
isDestroyed: vi.fn(() => false),
focus: vi.fn(() => {
focusedContents = contents;
@@ -546,7 +550,7 @@ describe("DesktopWindow", () => {
{ preventDefault },
{
...params,
frame: null,
frame: contents.mainFrame,
misspelledWord: "",
dictionarySuggestions: [],
mediaType: "image",
@@ -554,7 +558,7 @@ describe("DesktopWindow", () => {
},
);
const imageMenu = (yield* Queue.take(menus)).input;
assert.isUndefined(imageMenu.frame);
assert.strictEqual(imageMenu.frame, contents.mainFrame);
const copyImage = imageMenu.template.find((item) => item.label === "Copy Image");
const copyLink = imageMenu.template.find((item) => item.label === "Copy Link");
assert.isDefined(copyImage?.click);
+6 -1
View File
@@ -33,6 +33,7 @@ import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
import { makeQuitShortcutHandler } from "./QuitHold.ts";
import { copyContextMenuImage } from "./ContextMenuImage.ts";
const TITLEBAR_HEIGHT = 40;
// Matches --workspace-topbar-height in apps/web/src/index.css. Native macOS
@@ -595,7 +596,11 @@ export const make = Effect.gen(function* () {
menuTemplate.push({
label: "Copy Image",
click: () => {
if (!contents.isDestroyed()) contents.copyImageAt(params.x, params.y);
void runPromise(
Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe(
Effect.catch(() => logWindowWarning("failed to copy context-menu image")),
),
);
},
});
menuTemplate.push({ type: "separator" });