Open History to see the last commit
1import { beforeEach, expect, it, vi } from "vite-plus/test";
2import type * as Electron from "electron";
3import { copyContextMenuImage } from "./ContextMenuImage.ts";
4
5const native = vi.hoisted(() => ({
6 fetch: vi.fn(),
7 createFromBuffer: vi.fn(),
8 write: vi.fn(),
9 image: { isEmpty: vi.fn(() => false), toPNG: vi.fn(() => Buffer.from("png")) },
10}));
11
12vi.mock("electron", () => ({
13 net: { fetch: native.fetch },
14 nativeImage: { createFromBuffer: native.createFromBuffer },
15 clipboard: { write: native.write },
16 ClipboardItem: class {
17 readonly blobs: Record<string, Blob>;
18 constructor(blobs: Record<string, Blob>) {
19 this.blobs = blobs;
20 }
21 },
22}));
23
24const mainFrame = { isDestroyed: vi.fn(() => false) };
25const frame = { isDestroyed: vi.fn(() => false) };
26const contents = {
27 isDestroyed: vi.fn(() => false),
28 copyImageAt: vi.fn(),
29 executeJavaScriptInIsolatedWorld: vi.fn(),
30 mainFrame,
31};
32const params = {
33 x: 12,
34 y: 34,
35 srcURL: "https://example.com/image.png",
36 frame,
37};
38const sourcePng = Buffer.from(
39 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAFklEQVR4nGP4TyFgGDVg1IBRA4aLAQBdePwur/3haQAAAABJRU5ErkJggg==",
40 "base64",
41);
42
43const copyImage = (overrides: Partial<typeof params> = {}) =>
44 copyContextMenuImage(
45 contents as unknown as Electron.WebContents,
46 { ...params, ...overrides } as unknown as Electron.ContextMenuParams,
47 );
48
49beforeEach(() => {
50 vi.clearAllMocks();
51 contents.isDestroyed.mockReturnValue(false);
52 frame.isDestroyed.mockReturnValue(false);
53 native.image.isEmpty.mockReturnValue(false);
54 native.createFromBuffer.mockReturnValue(native.image);
55 native.fetch.mockResolvedValue(new Response(Uint8Array.from(sourcePng)));
56 native.write.mockResolvedValue(undefined);
57 contents.executeJavaScriptInIsolatedWorld.mockRejectedValue(
58 new Error("Image could not be decoded"),
59 );
60});
61
62it.each(["https://example.com/image.png", `data:image/png;base64,${sourcePng.toString("base64")}`])(
63 "copies an iframe image from %s",
64 async (srcURL) => {
65 await copyImage({ srcURL });
66 if (srcURL.startsWith("https:")) {
67 expect(native.fetch).toHaveBeenCalledWith(srcURL, {
68 credentials: "omit",
69 redirect: "error",
70 signal: expect.any(AbortSignal),
71 });
72 } else {
73 expect(native.fetch).not.toHaveBeenCalled();
74 }
75 expect(contents.copyImageAt).not.toHaveBeenCalled();
76 expect(native.createFromBuffer).toHaveBeenCalledWith(sourcePng);
77 const blob = native.write.mock.calls[0]?.[0][0].blobs["image/png"] as Blob;
78 expect(blob.type).toBe("image/png");
79 expect(Buffer.from(await blob.arrayBuffer())).toEqual(Buffer.from("png"));
80 },
81);
82
83it.each([
84 ["WebP", "UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAUAmJaQAA3AA/vz0AAA="],
85 ["GIF", "R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAkQBADs="],
86])("copies %s using Chromium when nativeImage cannot decode it", async (_, base64) => {
87 native.fetch.mockResolvedValue(new Response(Uint8Array.from(Buffer.from(base64, "base64"))));
88 native.image.isEmpty.mockReturnValue(true);
89 contents.executeJavaScriptInIsolatedWorld.mockResolvedValue(Uint8Array.from(sourcePng).buffer);
90 await copyImage();
91 const blob = native.write.mock.calls[0]?.[0][0].blobs["image/png"] as Blob;
92 expect(Buffer.from(await blob.arrayBuffer())).toEqual(sourcePng);
93 expect(native.image.toPNG).not.toHaveBeenCalled();
94});
95
96it("preserves the clipboard if the source frame closes during Chromium decoding", async () => {
97 native.image.isEmpty.mockReturnValue(true);
98 contents.executeJavaScriptInIsolatedWorld.mockImplementation(() => {
99 frame.isDestroyed.mockReturnValue(true);
100 return Promise.resolve(Uint8Array.from(sourcePng).buffer);
101 });
102 await copyImage();
103 expect(native.write).not.toHaveBeenCalled();
104});
105
106it("copies a GIF larger than the favicon pixel limit", async () => {
107 const gif = Buffer.from("R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAkQBADs=", "base64");
108 gif.writeUInt16LE(2048, 6);
109 gif.writeUInt16LE(1024, 8);
110 native.fetch.mockResolvedValue(new Response(Uint8Array.from(gif)));
111 native.image.isEmpty.mockReturnValue(true);
112 contents.executeJavaScriptInIsolatedWorld.mockResolvedValue(Uint8Array.from(sourcePng).buffer);
113 await copyImage();
114 const blob = native.write.mock.calls[0]?.[0][0].blobs["image/png"] as Blob;
115 expect(Buffer.from(await blob.arrayBuffer())).toEqual(sourcePng);
116});
117
118it.each([
119 "file:///private/image.png",
120 "blob:https://example.com/image",
121 "https://user:pass@example.com/image.png",
122])("rejects unsupported or credential-bearing URLs: %s", async (srcURL) => {
123 await expect(copyImage({ srcURL })).rejects.toThrow("Unsupported image URL");
124 expect(native.fetch).not.toHaveBeenCalled();
125 expect(native.write).not.toHaveBeenCalled();
126});
127
128it("cancels responses whose declared size exceeds the limit", async () => {
129 const cancel = vi.fn();
130 native.fetch.mockResolvedValue(
131 new Response(new ReadableStream({ cancel }), {
132 headers: { "content-length": String(32 * 1024 * 1024 + 1) },
133 }),
134 );
135 await expect(copyImage()).rejects.toThrow("size limit");
136 expect(cancel).toHaveBeenCalled();
137 expect(native.createFromBuffer).not.toHaveBeenCalled();
138});
139
140it("cancels oversized streams without a content-length", async () => {
141 const cancel = vi.fn();
142 native.fetch.mockResolvedValue(
143 new Response(
144 new ReadableStream({
145 start(controller) {
146 controller.enqueue(new Uint8Array(32 * 1024 * 1024));
147 controller.enqueue(new Uint8Array(1));
148 },
149 cancel,
150 }),
151 ),
152 );
153 await expect(copyImage()).rejects.toThrow("size limit");
154 expect(cancel).toHaveBeenCalled();
155 expect(native.write).not.toHaveBeenCalled();
156});
157
158it("preserves the clipboard when the response is not an image", async () => {
159 native.image.isEmpty.mockReturnValue(true);
160 await expect(copyImage()).rejects.toThrow("could not be decoded");
161 expect(native.write).not.toHaveBeenCalled();
162});
163
164it("rejects large decoded dimensions before image allocation", async () => {
165 const oversizedPng = Buffer.from(sourcePng);
166 oversizedPng.writeUInt32BE(4096, 16);
167 oversizedPng.writeUInt32BE(4096, 20);
168 native.fetch.mockResolvedValue(new Response(Uint8Array.from(oversizedPng)));
169 await expect(copyImage()).rejects.toThrow("size limit");
170 expect(native.createFromBuffer).not.toHaveBeenCalled();
171 expect(native.image.toPNG).not.toHaveBeenCalled();
172 expect(native.write).not.toHaveBeenCalled();
173});
174
175it("preserves the clipboard when the encoded PNG exceeds the limit", async () => {
176 native.image.toPNG.mockReturnValueOnce(Buffer.alloc(32 * 1024 * 1024 + 1));
177 await expect(copyImage()).rejects.toThrow("size limit");
178 expect(native.write).not.toHaveBeenCalled();
179});
180
181it("does not copy after the source frame closes during the request", async () => {
182 native.fetch.mockImplementation(() => {
183 frame.isDestroyed.mockReturnValue(true);
184 return Promise.resolve(new Response(Uint8Array.from(sourcePng)));
185 });
186 await copyImage();
187 expect(native.write).not.toHaveBeenCalled();
188});