Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 MAX_FAVICON_CANDIDATES,
5 MAX_FAVICON_RESPONSE_BYTES,
6 captureFavicon,
7 selectFaviconCandidates,
8} from "./FaviconCapture.ts";
9
10const PNG = "data:image/png;base64,cG5n";
11const SOURCE_PNG = Buffer.alloc(24);
12Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(SOURCE_PNG);
13SOURCE_PNG.writeUInt32BE(1, 16);
14SOURCE_PNG.writeUInt32BE(1, 20);
15const SOURCE_PNG_URL = `data:image/png;base64,${SOURCE_PNG.toString("base64")}`;
16
17function sourceGif(
18 width: number,
19 height: number,
20 frameWidth = width,
21 frameHeight = height,
22 additionalFrames: ReadonlyArray<{
23 readonly left?: number;
24 readonly top?: number;
25 readonly width: number;
26 readonly height: number;
27 }> = [],
28): Buffer {
29 const frames = [{ width: frameWidth, height: frameHeight }, ...additionalFrames];
30 const buffer = Buffer.alloc(13 + frames.length * 12 + 1);
31 buffer.write("GIF89a", 0, "ascii");
32 buffer.writeUInt16LE(width, 6);
33 buffer.writeUInt16LE(height, 8);
34 let offset = 13;
35 for (const frame of frames) {
36 buffer[offset] = 0x2c;
37 buffer.writeUInt16LE(frame.left ?? 0, offset + 1);
38 buffer.writeUInt16LE(frame.top ?? 0, offset + 3);
39 buffer.writeUInt16LE(frame.width, offset + 5);
40 buffer.writeUInt16LE(frame.height, offset + 7);
41 offset += 10;
42 buffer[offset] = 2;
43 buffer[offset + 1] = 0;
44 offset += 2;
45 }
46 buffer[offset] = 0x3b;
47 return buffer;
48}
49
50function sourceJpeg(
51 width: number,
52 height: number,
53 orientations: number | ReadonlyArray<number> = [],
54): Buffer {
55 const frame = Buffer.from([
56 0xff,
57 0xd8,
58 0xff,
59 0xc0,
60 0x00,
61 0x07,
62 0x08,
63 height >>> 8,
64 height & 0xff,
65 width >>> 8,
66 width & 0xff,
67 ]);
68 const app1Segments = (typeof orientations === "number" ? [orientations] : orientations).map(
69 (orientation) => sourceJpegExifSegment([orientation]),
70 );
71 return Buffer.concat([frame.subarray(0, 2), ...app1Segments, frame.subarray(2)]);
72}
73
74function sourceJpegApp1Segment(payload: Buffer): Buffer {
75 const app1 = Buffer.alloc(4 + payload.byteLength);
76 app1[0] = 0xff;
77 app1[1] = 0xe1;
78 app1.writeUInt16BE(payload.byteLength + 2, 2);
79 payload.copy(app1, 4);
80 return app1;
81}
82
83function sourceJpegExifSegment(
84 orientations: ReadonlyArray<number>,
85 options?: {
86 readonly byteOrder?: "II" | "MM";
87 readonly magic?: number;
88 readonly padding?: number;
89 },
90): Buffer {
91 const exif = Buffer.alloc(20 + orientations.length * 12);
92 exif.write("Exif\0\0", 0, "binary");
93 exif[5] = options?.padding ?? 0;
94 const littleEndian = options?.byteOrder !== "MM";
95 exif.write(littleEndian ? "II" : "MM", 6, "ascii");
96 const writeUInt16 = (value: number, offset: number) =>
97 littleEndian ? exif.writeUInt16LE(value, offset) : exif.writeUInt16BE(value, offset);
98 const writeUInt32 = (value: number, offset: number) =>
99 littleEndian ? exif.writeUInt32LE(value, offset) : exif.writeUInt32BE(value, offset);
100 writeUInt16(options?.magic ?? 42, 8);
101 writeUInt32(8, 10);
102 writeUInt16(orientations.length, 14);
103 orientations.forEach((orientation, index) => {
104 const entryOffset = 16 + index * 12;
105 writeUInt16(0x0112, entryOffset);
106 writeUInt16(3, entryOffset + 2);
107 writeUInt32(1, entryOffset + 4);
108 writeUInt16(orientation, entryOffset + 8);
109 });
110 return sourceJpegApp1Segment(exif);
111}
112
113function sourceJpegWithApp1Segments(
114 width: number,
115 height: number,
116 segments: ReadonlyArray<Buffer>,
117): Buffer {
118 const frame = sourceJpeg(width, height);
119 return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]);
120}
121
122function sourceJpegWithOrientationEntries(
123 width: number,
124 height: number,
125 orientations: ReadonlyArray<number>,
126): Buffer {
127 return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]);
128}
129
130function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer {
131 const exif = sourceJpegExifSegment([6], { byteOrder });
132 exif[10] = alias;
133 exif[11] = alias;
134 return sourceJpegWithApp1Segments(64, 32, [exif]);
135}
136
137function sourceJpegExifWithSubIfd(options: {
138 readonly rootOrientation?: number;
139 readonly subIfdFirst?: boolean;
140 readonly subIfdOrientation: number;
141}): Buffer {
142 const rootEntries = options.rootOrientation === undefined ? 1 : 2;
143 const rootIfdOffset = 14;
144 const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
145 const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4);
146 exif.write("Exif\0\0", 0, "binary");
147 exif.write("II", 6, "ascii");
148 exif.writeUInt16LE(42, 8);
149 exif.writeUInt32LE(8, 10);
150 exif.writeUInt16LE(rootEntries, rootIfdOffset);
151
152 const writeOrientation = (offset: number, orientation: number) => {
153 exif.writeUInt16LE(0x0112, offset);
154 exif.writeUInt16LE(3, offset + 2);
155 exif.writeUInt32LE(1, offset + 4);
156 exif.writeUInt16LE(orientation, offset + 8);
157 };
158 const writeSubIfdPointer = (offset: number) => {
159 exif.writeUInt16LE(0x8769, offset);
160 exif.writeUInt16LE(4, offset + 2);
161 exif.writeUInt32LE(1, offset + 4);
162 exif.writeUInt32LE(subIfdOffset - 6, offset + 8);
163 };
164
165 const firstRootEntryOffset = rootIfdOffset + 2;
166 if (options.rootOrientation === undefined) {
167 writeSubIfdPointer(firstRootEntryOffset);
168 } else if (options.subIfdFirst) {
169 writeSubIfdPointer(firstRootEntryOffset);
170 writeOrientation(firstRootEntryOffset + 12, options.rootOrientation);
171 } else {
172 writeOrientation(firstRootEntryOffset, options.rootOrientation);
173 writeSubIfdPointer(firstRootEntryOffset + 12);
174 }
175
176 exif.writeUInt16LE(1, subIfdOffset);
177 writeOrientation(subIfdOffset + 2, options.subIfdOrientation);
178 return sourceJpegApp1Segment(exif);
179}
180
181function sourceJpegExifWithSubIfdPointers(options: {
182 readonly pointerCount: number;
183 readonly subIfdEntries: number;
184}): Buffer {
185 const { pointerCount, subIfdEntries } = options;
186 const rootIfdOffset = 14;
187 const rootEntries = pointerCount + 1;
188 const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
189 const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4);
190 exif.write("Exif\0\0", 0, "binary");
191 exif.write("II", 6, "ascii");
192 exif.writeUInt16LE(42, 8);
193 exif.writeUInt32LE(8, 10);
194 exif.writeUInt16LE(rootEntries, rootIfdOffset);
195 for (let index = 0; index < pointerCount; index += 1) {
196 const entryOffset = rootIfdOffset + 2 + index * 12;
197 exif.writeUInt16LE(0x8769, entryOffset);
198 exif.writeUInt16LE(4, entryOffset + 2);
199 exif.writeUInt32LE(1, entryOffset + 4);
200 exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8);
201 }
202 const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
203 exif.writeUInt16LE(0x0112, orientationOffset);
204 exif.writeUInt16LE(3, orientationOffset + 2);
205 exif.writeUInt32LE(1, orientationOffset + 4);
206 exif.writeUInt16LE(6, orientationOffset + 8);
207
208 exif.writeUInt16LE(subIfdEntries, subIfdOffset);
209 for (let index = 0; index < subIfdEntries; index += 1) {
210 const entryOffset = subIfdOffset + 2 + index * 12;
211 exif.writeUInt16LE(1, entryOffset);
212 exif.writeUInt16LE(3, entryOffset + 2);
213 exif.writeUInt32LE(1, entryOffset + 4);
214 }
215 return sourceJpegApp1Segment(exif);
216}
217
218function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer {
219 const rootIfdOffset = 14;
220 const rootEntries = pointerCount + 1;
221 const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
222 const exif = Buffer.alloc(subIfdOffset + pointerCount * 2 + 2 + subIfdEntries * 12);
223 exif.write("Exif\0\0", 0, "binary");
224 exif.write("II", 6, "ascii");
225 exif.writeUInt32LE(8, 10);
226 exif.writeUInt16LE(rootEntries, rootIfdOffset);
227 for (let index = 0; index < pointerCount; index += 1) {
228 const entryOffset = rootIfdOffset + 2 + index * 12;
229 exif.writeUInt16LE(0x8769, entryOffset);
230 exif.writeUInt16LE(4, entryOffset + 2);
231 exif.writeUInt32LE(1, entryOffset + 4);
232 exif.writeUInt32LE(subIfdOffset + index * 2 - 6, entryOffset + 8);
233 exif.writeUInt16LE(subIfdEntries, subIfdOffset + index * 2);
234 }
235 const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
236 exif.writeUInt16LE(0x0112, orientationOffset);
237 exif.writeUInt16LE(3, orientationOffset + 2);
238 exif.writeUInt32LE(1, orientationOffset + 4);
239 exif.writeUInt16LE(6, orientationOffset + 8);
240 return sourceJpegApp1Segment(exif);
241}
242
243function sourceWebp(width: number, height: number): Buffer {
244 const buffer = Buffer.alloc(30);
245 buffer.write("RIFF", 0, "ascii");
246 buffer.write("WEBP", 8, "ascii");
247 buffer.write("VP8X", 12, "ascii");
248 buffer.writeUIntLE(width - 1, 24, 3);
249 buffer.writeUIntLE(height - 1, 27, 3);
250 return buffer;
251}
252
253function sourceIco(embedded: Buffer): Buffer {
254 const buffer = Buffer.alloc(22 + embedded.byteLength);
255 buffer.writeUInt16LE(1, 2);
256 buffer.writeUInt16LE(1, 4);
257 buffer.writeUInt32LE(embedded.byteLength, 14);
258 buffer.writeUInt32LE(22, 18);
259 embedded.copy(buffer, 22);
260 return buffer;
261}
262
263function makeUnsafePng(): Buffer {
264 const buffer = Buffer.from(SOURCE_PNG);
265 buffer.writeUInt32BE(4096, 16);
266 buffer.writeUInt32BE(4096, 20);
267 return buffer;
268}
269
270function sourcePng(width: number, height: number): Buffer {
271 const buffer = Buffer.from(SOURCE_PNG);
272 buffer.writeUInt32BE(width, 16);
273 buffer.writeUInt32BE(height, 20);
274 return buffer;
275}
276
277function makeUnsafeDib(): Buffer {
278 const buffer = Buffer.alloc(40);
279 buffer.writeUInt32LE(40, 0);
280 buffer.writeInt32LE(4096, 4);
281 buffer.writeInt32LE(4096, 8);
282 return buffer;
283}
284
285function makeWebContents(options?: {
286 readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
287 readonly rasterize?: (code: string) => Promise<unknown>;
288}) {
289 const fetch = vi.fn(
290 options?.fetch ??
291 (async () =>
292 new Response(new Uint8Array(SOURCE_PNG), {
293 headers: { "content-type": "image/png" },
294 })),
295 );
296 const executeJavaScriptInIsolatedWorld = vi.fn(
297 async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
298 options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : PNG,
299 );
300 return {
301 webContents: {
302 session: { fetch },
303 executeJavaScriptInIsolatedWorld,
304 } as never,
305 executeJavaScriptInIsolatedWorld,
306 fetch,
307 };
308}
309
310const JPEG_LANDSCAPE_LAYOUT = {
311 draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
312 resizeHeight: 16,
313 resizeWidth: 32,
314} as const;
315const JPEG_PORTRAIT_LAYOUT = {
316 draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
317 resizeHeight: 32,
318 resizeWidth: 16,
319} as const;
320
321async function expectJpegLayout(
322 source: Buffer,
323 layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT,
324): Promise<void> {
325 const { webContents } = makeWebContents({
326 rasterize: async (code) => {
327 expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`);
328 expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`);
329 expect(code).toContain(layout.draw);
330 return PNG;
331 },
332 });
333
334 expect(
335 await captureFavicon({
336 webContents,
337 pageUrl: "https://example.com/page",
338 candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
339 signal: new AbortController().signal,
340 }),
341 ).toEqual({ kind: "captured", dataUrl: PNG });
342}
343
344describe("selectFaviconCandidates", () => {
345 it("filters and deduplicates before applying the candidate cap", () => {
346 const valid = Array.from(
347 { length: MAX_FAVICON_CANDIDATES + 2 },
348 (_, index) => `https://example.com/favicon-${index}.png`,
349 );
350 expect(
351 selectFaviconCandidates([
352 ...Array.from({ length: 64 }, () => "javascript:alert(1)"),
353 valid[0]!,
354 valid[0]!,
355 ...valid.slice(1),
356 ]),
357 ).toEqual(valid.slice(0, MAX_FAVICON_CANDIDATES));
358 });
359
360 it("bounds raw candidate scanning independently of the usable-candidate cap", () => {
361 const oversizedInvalid = `javascript:${"x".repeat(2_048)}`;
362 expect(
363 selectFaviconCandidates([
364 ...Array.from({ length: 128 }, () => oversizedInvalid),
365 "https://example.com/too-late.png",
366 ]),
367 ).toEqual([]);
368 });
369});
370
371describe("captureFavicon", () => {
372 it.each([
373 {
374 label: "same-origin",
375 pageUrl: "https://example.com/page",
376 faviconUrl: "https://example.com/favicon.png",
377 credentials: "include",
378 },
379 {
380 label: "cross-origin",
381 pageUrl: "https://example.com/page",
382 faviconUrl: "https://cdn.example.net/favicon.png",
383 credentials: "omit",
384 },
385 ])("uses the explicit credential policy for $label requests", async (testCase) => {
386 const { webContents, fetch } = makeWebContents();
387 const result = await captureFavicon({
388 webContents,
389 pageUrl: testCase.pageUrl,
390 candidates: [testCase.faviconUrl],
391 signal: new AbortController().signal,
392 });
393
394 expect(result).toEqual({ kind: "captured", dataUrl: PNG });
395 expect(fetch).toHaveBeenCalledWith(
396 testCase.faviconUrl,
397 expect.objectContaining({ credentials: testCase.credentials, redirect: "error" }),
398 );
399 });
400
401 it("decodes base64 and percent-encoded inline images without fetching", async () => {
402 const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents();
403 const percentEncodedPng = [...SOURCE_PNG]
404 .map((byte) => `%${byte.toString(16).padStart(2, "0")}`)
405 .join("");
406
407 for (const candidate of [SOURCE_PNG_URL, `data:image/png,${percentEncodedPng}`]) {
408 expect(
409 await captureFavicon({
410 webContents,
411 pageUrl: "https://example.com/page",
412 candidates: [candidate],
413 signal: new AbortController().signal,
414 }),
415 ).toEqual({ kind: "captured", dataUrl: PNG });
416 }
417
418 expect(fetch).not.toHaveBeenCalled();
419 expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2);
420 });
421
422 it("tries the next candidate after an ordinary rejection", async () => {
423 const { webContents, fetch } = makeWebContents({
424 fetch: async (url) =>
425 url.endsWith("first.png")
426 ? new Response(null, { status: 404 })
427 : new Response(new Uint8Array(SOURCE_PNG), {
428 headers: { "content-type": "image/png" },
429 }),
430 });
431
432 expect(
433 await captureFavicon({
434 webContents,
435 pageUrl: "https://example.com/page",
436 candidates: ["https://example.com/first.png", "https://example.com/second.png"],
437 signal: new AbortController().signal,
438 }),
439 ).toEqual({ kind: "captured", dataUrl: PNG });
440 expect(fetch).toHaveBeenCalledTimes(2);
441 });
442
443 it("cancels a rejected response body before trying the next candidate", async () => {
444 const cancel = vi.fn();
445 const body = new ReadableStream<Uint8Array>({
446 start(controller) {
447 controller.enqueue(new Uint8Array(1));
448 },
449 cancel,
450 });
451 const { webContents, fetch } = makeWebContents({
452 fetch: async (url) =>
453 url.endsWith("first.png")
454 ? new Response(body, { status: 404 })
455 : new Response(new Uint8Array(SOURCE_PNG), {
456 headers: { "content-type": "image/png" },
457 }),
458 });
459
460 expect(
461 await captureFavicon({
462 webContents,
463 pageUrl: "https://example.com/page",
464 candidates: ["https://example.com/first.png", "https://example.com/second.png"],
465 signal: new AbortController().signal,
466 }),
467 ).toEqual({ kind: "captured", dataUrl: PNG });
468 expect(cancel).toHaveBeenCalledOnce();
469 expect(fetch).toHaveBeenCalledTimes(2);
470 });
471
472 it("stops a pending fetch when its capture is aborted", async () => {
473 const controller = new AbortController();
474 const { webContents } = makeWebContents({
475 fetch: (_url, init) =>
476 new Promise<Response>((_resolve, reject) => {
477 init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
478 once: true,
479 });
480 }),
481 });
482 const capture = captureFavicon({
483 webContents,
484 pageUrl: "https://example.com/page",
485 candidates: ["https://example.com/favicon.png"],
486 signal: controller.signal,
487 });
488 controller.abort();
489 expect(await capture).toEqual({ kind: "none" });
490 });
491
492 it("ends candidate fallback when the overall capture deadline expires", async () => {
493 const timeoutController = new AbortController();
494 const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
495 const { webContents, fetch } = makeWebContents({
496 fetch: (url, init) => {
497 if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 }));
498 return new Promise<Response>((_resolve, reject) => {
499 init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
500 once: true,
501 });
502 });
503 },
504 });
505 try {
506 const capture = captureFavicon({
507 webContents,
508 pageUrl: "https://example.com/page",
509 candidates: [
510 "https://example.com/first.png",
511 "https://example.com/second.png",
512 "https://example.com/third.png",
513 ],
514 signal: new AbortController().signal,
515 });
516 await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
517 timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
518
519 expect(await capture).toEqual({ kind: "timed-out" });
520 expect(fetch).toHaveBeenCalledTimes(2);
521 expect(timeout).toHaveBeenCalledOnce();
522 } finally {
523 timeout.mockRestore();
524 }
525 });
526
527 it("does not publish a rasterization that completes after the capture deadline", async () => {
528 const captureTimeoutController = new AbortController();
529 const rasterTimeoutController = new AbortController();
530 const timeout = vi
531 .spyOn(AbortSignal, "timeout")
532 .mockImplementation((milliseconds) =>
533 milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal,
534 );
535 let resolveRasterization!: (value: unknown) => void;
536 const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
537 rasterize: () =>
538 new Promise((resolve) => {
539 resolveRasterization = resolve;
540 }),
541 });
542 try {
543 const capture = captureFavicon({
544 webContents,
545 pageUrl: "https://example.com/page",
546 candidates: [SOURCE_PNG_URL],
547 signal: new AbortController().signal,
548 });
549 await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce());
550 captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
551
552 expect(await capture).toEqual({ kind: "timed-out" });
553 resolveRasterization(PNG);
554 } finally {
555 timeout.mockRestore();
556 }
557 });
558
559 it("cancels a stalled response body when the capture deadline expires", async () => {
560 const timeoutController = new AbortController();
561 const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
562 const cancel = vi.fn();
563 const { webContents } = makeWebContents({
564 fetch: async () =>
565 new Response(
566 new ReadableStream<Uint8Array>({
567 cancel,
568 }),
569 { headers: { "content-type": "image/png" } },
570 ),
571 });
572 try {
573 const capture = captureFavicon({
574 webContents,
575 pageUrl: "https://example.com/page",
576 candidates: ["https://example.com/favicon.png"],
577 signal: new AbortController().signal,
578 });
579 timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
580
581 expect(await capture).toEqual({ kind: "timed-out" });
582 expect(cancel).toHaveBeenCalledOnce();
583 } finally {
584 timeout.mockRestore();
585 }
586 });
587
588 it("rejects and cancels an oversized streamed response", async () => {
589 const cancel = vi.fn();
590 const body = new ReadableStream<Uint8Array>({
591 start(controller) {
592 controller.enqueue(new Uint8Array(MAX_FAVICON_RESPONSE_BYTES));
593 controller.enqueue(new Uint8Array(1));
594 },
595 cancel,
596 });
597 const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
598 fetch: async () => new Response(body, { headers: { "content-type": "image/png" } }),
599 });
600
601 expect(
602 await captureFavicon({
603 webContents,
604 pageUrl: "https://example.com/page",
605 candidates: ["https://example.com/favicon.png"],
606 signal: new AbortController().signal,
607 }),
608 ).toEqual({ kind: "none" });
609 expect(cancel).toHaveBeenCalledOnce();
610 expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
611 });
612
613 it("retains bounded compatibility with common favicon formats", async () => {
614 const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
615 for (const [mime, buffer] of [
616 ["image/gif", sourceGif(32, 32)],
617 ["image/jpeg", sourceJpeg(32, 32)],
618 ["image/webp", sourceWebp(32, 32)],
619 ["image/x-icon", sourceIco(SOURCE_PNG)],
620 ] as const) {
621 expect(
622 await captureFavicon({
623 webContents,
624 pageUrl: "https://example.com/page",
625 candidates: [`data:${mime};base64,${buffer.toString("base64")}`],
626 signal: new AbortController().signal,
627 }),
628 ).toEqual({ kind: "captured", dataUrl: PNG });
629 }
630 expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4);
631 });
632
633 it.each([
634 {
635 label: "landscape",
636 source: sourcePng(64, 32),
637 resizeWidth: 32,
638 resizeHeight: 16,
639 draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
640 },
641 {
642 label: "portrait",
643 source: sourcePng(32, 64),
644 resizeWidth: 16,
645 resizeHeight: 32,
646 draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
647 },
648 ])("preserves $label aspect ratio within the 32x32 output", async (testCase) => {
649 const { webContents } = makeWebContents({
650 rasterize: async (code) => {
651 expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`);
652 expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`);
653 expect(code).toContain('resizeQuality: "high"');
654 expect(code).toContain(testCase.draw);
655 return PNG;
656 },
657 });
658
659 expect(
660 await captureFavicon({
661 webContents,
662 pageUrl: "https://example.com/page",
663 candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`],
664 signal: new AbortController().signal,
665 }),
666 ).toEqual({ kind: "captured", dataUrl: PNG });
667 });
668
669 it.each([
670 ...[1, 2, 3, 4].map((orientation) => ({
671 label: `keeps stored dimensions for orientation ${orientation}`,
672 layout: JPEG_LANDSCAPE_LAYOUT,
673 source: sourceJpeg(64, 32, orientation),
674 })),
675 ...[5, 6, 7, 8].map((orientation) => ({
676 label: `uses display dimensions for orientation ${orientation}`,
677 layout: JPEG_PORTRAIT_LAYOUT,
678 source: sourceJpeg(64, 32, orientation),
679 })),
680 {
681 label: "uses the first separate EXIF segment when it is transposed",
682 layout: JPEG_PORTRAIT_LAYOUT,
683 source: sourceJpeg(64, 32, [6, 1]),
684 },
685 {
686 label: "uses the first separate EXIF segment when it is untransposed",
687 layout: JPEG_LANDSCAPE_LAYOUT,
688 source: sourceJpeg(64, 32, [1, 6]),
689 },
690 {
691 label: "does not consult a later EXIF segment after an invalid orientation",
692 layout: JPEG_LANDSCAPE_LAYOUT,
693 source: sourceJpeg(64, 32, [9, 6]),
694 },
695 {
696 label: "uses a later valid orientation in the same IFD",
697 layout: JPEG_PORTRAIT_LAYOUT,
698 source: sourceJpegWithOrientationEntries(64, 32, [9, 6]),
699 },
700 {
701 label: "skips a non-EXIF APP1 segment",
702 layout: JPEG_PORTRAIT_LAYOUT,
703 source: sourceJpegWithApp1Segments(64, 32, [
704 sourceJpegApp1Segment(Buffer.from("not-exif")),
705 sourceJpegExifSegment([6]),
706 ]),
707 },
708 {
709 label: "skips an empty EXIF APP1 segment",
710 layout: JPEG_PORTRAIT_LAYOUT,
711 source: sourceJpegWithApp1Segments(64, 32, [
712 sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")),
713 sourceJpegExifSegment([6]),
714 ]),
715 },
716 {
717 label: "stops after a malformed qualifying EXIF APP1 segment",
718 layout: JPEG_LANDSCAPE_LAYOUT,
719 source: sourceJpegWithApp1Segments(64, 32, [
720 sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")),
721 sourceJpegExifSegment([6]),
722 ]),
723 },
724 {
725 label: "ignores the EXIF padding byte",
726 layout: JPEG_PORTRAIT_LAYOUT,
727 source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]),
728 },
729 {
730 label: "reads big-endian EXIF",
731 layout: JPEG_PORTRAIT_LAYOUT,
732 source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]),
733 },
734 {
735 label: "matches Chromium for a nonstandard TIFF magic field",
736 layout: JPEG_PORTRAIT_LAYOUT,
737 source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]),
738 },
739 {
740 label: "rejects a high-bit little-endian alias",
741 layout: JPEG_LANDSCAPE_LAYOUT,
742 source: sourceJpegWithEndianAlias(0xc9, "II"),
743 },
744 {
745 label: "rejects a high-bit big-endian alias",
746 layout: JPEG_LANDSCAPE_LAYOUT,
747 source: sourceJpegWithEndianAlias(0xcd, "MM"),
748 },
749 {
750 label: "reads an orientation from a SubIFD",
751 layout: JPEG_PORTRAIT_LAYOUT,
752 source: sourceJpegWithApp1Segments(64, 32, [
753 sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }),
754 ]),
755 },
756 {
757 label: "uses a SubIFD orientation before a later root orientation",
758 layout: JPEG_PORTRAIT_LAYOUT,
759 source: sourceJpegWithApp1Segments(64, 32, [
760 sourceJpegExifWithSubIfd({
761 rootOrientation: 1,
762 subIfdFirst: true,
763 subIfdOrientation: 6,
764 }),
765 ]),
766 },
767 {
768 label: "uses a root orientation before a later SubIFD orientation",
769 layout: JPEG_LANDSCAPE_LAYOUT,
770 source: sourceJpegWithApp1Segments(64, 32, [
771 sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }),
772 ]),
773 },
774 {
775 label: "memoizes repeated aliases to the same SubIFD",
776 layout: JPEG_PORTRAIT_LAYOUT,
777 source: sourceJpegWithApp1Segments(64, 32, [
778 sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }),
779 ]),
780 },
781 ])("matches Chromium JPEG layout: $label", async ({ source, layout }) => {
782 await expectJpegLayout(source, layout);
783 });
784
785 it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => {
786 const source = sourceJpegWithApp1Segments(64, 32, [
787 sourceJpegExifWithOverlappingSubIfds(32, 32),
788 ]);
789 const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
790
791 expect(
792 await captureFavicon({
793 webContents,
794 pageUrl: "https://example.com/page",
795 candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
796 signal: new AbortController().signal,
797 }),
798 ).toEqual({ kind: "none" });
799 expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
800 });
801
802 it("rejects JPEGs with multiple frame headers before rasterization", async () => {
803 const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]);
804 const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
805
806 expect(
807 await captureFavicon({
808 webContents,
809 pageUrl: "https://example.com/page",
810 candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`],
811 signal: new AbortController().signal,
812 }),
813 ).toEqual({ kind: "none" });
814 expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
815 });
816
817 it("rejects an unsafe PNG size before rasterization", async () => {
818 const buffer = makeUnsafePng();
819 const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
820 fetch: async () =>
821 new Response(new Uint8Array(buffer), {
822 headers: { "content-type": "image/png" },
823 }),
824 });
825
826 expect(
827 await captureFavicon({
828 webContents,
829 pageUrl: "https://example.com/page",
830 candidates: ["https://example.com/favicon.png"],
831 signal: new AbortController().signal,
832 }),
833 ).toEqual({ kind: "none" });
834 expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
835 });
836
837 it.each([
838 ["GIF", "image/gif", sourceGif(4096, 4096)],
839 ["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)],
840 ["GIF later frame", "image/gif", sourceGif(1, 1, 1, 1, [{ width: 4096, height: 4096 }])],
841 [
842 "GIF cumulative frames",
843 "image/gif",
844 sourceGif(
845 64,
846 64,
847 64,
848 64,
849 Array.from({ length: 256 }, () => ({ width: 64, height: 64 })),
850 ),
851 ],
852 ["JPEG", "image/jpeg", sourceJpeg(4096, 4096)],
853 ["WebP", "image/webp", sourceWebp(4096, 4096)],
854 ["ICO with PNG", "image/x-icon", sourceIco(makeUnsafePng())],
855 ["ICO with DIB", "image/x-icon", sourceIco(makeUnsafeDib())],
856 ["SVG", "image/svg+xml", Buffer.from('<svg width="1" height="1"/>')],
857 [
858 "SVG with embedded bitmap",
859 "image/svg+xml",
860 Buffer.from(
861 `<svg width="1" height="1"><image href="data:image/png;base64,${makeUnsafePng().toString("base64")}"/></svg>`,
862 ),
863 ],
864 [
865 "ICO invalid payload span",
866 "image/x-icon",
867 (() => {
868 const buffer = Buffer.alloc(22);
869 buffer.writeUInt16LE(1, 2);
870 buffer.writeUInt16LE(1, 4);
871 buffer.writeUInt32LE(100, 14);
872 buffer.writeUInt32LE(22, 18);
873 return buffer;
874 })(),
875 ],
876 ])("rejects unsafe or unsupported %s before rasterization", async (_label, mime, buffer) => {
877 const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
878 const candidate = `data:${mime};base64,${buffer.toString("base64")}`;
879 expect(
880 await captureFavicon({
881 webContents,
882 pageUrl: "https://example.com/page",
883 candidates: [candidate],
884 signal: new AbortController().signal,
885 }),
886 ).toEqual({ kind: "none" });
887 expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
888 });
889
890 it("ignores output that is not a bounded PNG data URL", async () => {
891 const { webContents } = makeWebContents({
892 rasterize: async () => "data:image/svg+xml;base64,c3Zn",
893 });
894
895 expect(
896 await captureFavicon({
897 webContents,
898 pageUrl: "https://example.com/page",
899 candidates: [SOURCE_PNG_URL],
900 signal: new AbortController().signal,
901 }),
902 ).toEqual({ kind: "none" });
903 });
904
905 it("waits for physical rasterization settlement after a logical timeout", async () => {
906 vi.useFakeTimers();
907 try {
908 let resolveOld!: (value: unknown) => void;
909 let executions = 0;
910 const { webContents } = makeWebContents({
911 rasterize: () => {
912 executions += 1;
913 return executions === 1
914 ? new Promise((resolve) => {
915 resolveOld = resolve;
916 })
917 : Promise.resolve(PNG);
918 },
919 });
920 const input = {
921 webContents,
922 pageUrl: "https://example.com/page",
923 candidates: [SOURCE_PNG_URL],
924 signal: new AbortController().signal,
925 };
926 const timedOut = captureFavicon(input);
927 await vi.advanceTimersByTimeAsync(1_001);
928 expect(await timedOut).toEqual({ kind: "timed-out" });
929
930 const newer = captureFavicon(input);
931 await Promise.resolve();
932 expect(executions).toBe(1);
933 resolveOld(PNG);
934 expect(await newer).toEqual({ kind: "captured", dataUrl: PNG });
935 expect(executions).toBe(2);
936 } finally {
937 vi.useRealTimers();
938 }
939 });
940
941 it("ends candidate fallback after a rasterization timeout", async () => {
942 vi.useFakeTimers();
943 try {
944 let resolveRasterization!: (value: unknown) => void;
945 const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({
946 rasterize: () =>
947 new Promise((resolve) => {
948 resolveRasterization = resolve;
949 }),
950 });
951 const capture = captureFavicon({
952 webContents,
953 pageUrl: "https://example.com/page",
954 candidates: ["https://example.com/first.png", "https://example.com/second.png"],
955 signal: new AbortController().signal,
956 });
957
958 await vi.advanceTimersByTimeAsync(1_001);
959
960 expect(await capture).toEqual({ kind: "timed-out" });
961 expect(fetch).toHaveBeenCalledOnce();
962 expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce();
963 resolveRasterization(PNG);
964 } finally {
965 vi.useRealTimers();
966 }
967 });
968
969 it("coalesces queued rasterizations so only the latest pending capture launches", async () => {
970 let resolveFirst!: (value: unknown) => void;
971 let executions = 0;
972 const { webContents } = makeWebContents({
973 rasterize: () => {
974 executions += 1;
975 return executions === 1
976 ? new Promise((resolve) => {
977 resolveFirst = resolve;
978 })
979 : Promise.resolve(PNG);
980 },
981 });
982 const input = {
983 webContents,
984 pageUrl: "https://example.com/page",
985 candidates: [SOURCE_PNG_URL],
986 signal: new AbortController().signal,
987 };
988 const first = captureFavicon(input);
989 const superseded = captureFavicon(input);
990 const newest = captureFavicon(input);
991
992 expect(executions).toBe(1);
993 resolveFirst(PNG);
994 expect(await first).toEqual({ kind: "captured", dataUrl: PNG });
995 expect(await superseded).toEqual({ kind: "none" });
996 expect(await newest).toEqual({ kind: "captured", dataUrl: PNG });
997 expect(executions).toBe(2);
998 });
999});