Open History to see the last commit
1import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
2
3export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
4export const MAX_FAVICON_CANDIDATES = 8;
5export const MAX_FAVICON_HTTP_URL_LENGTH = 2_048;
6
7const MAX_FAVICON_CANDIDATE_INPUT_UNITS = 262_144;
8const MIN_FAVICON_CANDIDATE_INPUT_UNITS = 256;
9const MAX_FAVICON_SOURCE_PIXELS = 1_048_576;
10const MAX_FAVICON_INLINE_URL_LENGTH = Math.ceil((MAX_FAVICON_RESPONSE_BYTES * 4) / 3) + 128;
11const FAVICON_CAPTURE_TIMEOUT_MS = 5_000;
12const FAVICON_RASTER_WORLD_ID = 1001;
13const FAVICON_RASTER_TIMEOUT_MS = 1_000;
14const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
15
16interface RasterizationGate {
17 generation: number;
18 launchAllowed?: Promise<void>;
19}
20
21const rasterizationGates = new WeakMap<Electron.WebContents, RasterizationGate>();
22
23async function waitForRasterLaunch(previous: Promise<void>, signal: AbortSignal): Promise<void> {
24 if (signal.aborted) return;
25 await new Promise<void>((resolve) => {
26 const finish = () => {
27 signal.removeEventListener("abort", finish);
28 resolve();
29 };
30 signal.addEventListener("abort", finish, { once: true });
31 void previous.then(finish);
32 });
33}
34
35export type FaviconCaptureResult =
36 | { readonly kind: "captured"; readonly dataUrl: string }
37 | { readonly kind: "none" }
38 | { readonly kind: "timed-out" };
39
40type RasterizationResult =
41 | { readonly kind: "completed"; readonly value: unknown }
42 | { readonly kind: "timed-out" };
43
44export function safeHttpOrigin(url: string): string | null {
45 try {
46 const parsed = new URL(url);
47 return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
48 } catch {
49 return null;
50 }
51}
52
53export function selectFaviconCandidates(candidates: ReadonlyArray<string>): ReadonlyArray<string> {
54 const selected: string[] = [];
55 const seen = new Set<string>();
56 let inputUnits = 0;
57 for (const candidate of candidates) {
58 // Charge a minimum per entry so a large array of tiny malformed values is bounded too.
59 inputUnits += Math.max(MIN_FAVICON_CANDIDATE_INPUT_UNITS, candidate.length);
60 if (inputUnits > MAX_FAVICON_CANDIDATE_INPUT_UNITS) break;
61 if (!isSupportedFaviconUrl(candidate) || seen.has(candidate)) continue;
62 seen.add(candidate);
63 selected.push(candidate);
64 if (selected.length === MAX_FAVICON_CANDIDATES) break;
65 }
66 return selected;
67}
68
69export async function captureFavicon(input: {
70 readonly webContents: Electron.WebContents;
71 readonly pageUrl: string;
72 readonly candidates: ReadonlyArray<string>;
73 readonly signal: AbortSignal;
74}): Promise<FaviconCaptureResult> {
75 const pageOrigin = safeHttpOrigin(input.pageUrl);
76 if (!pageOrigin) return { kind: "none" };
77 const captureTimeout = AbortSignal.timeout(FAVICON_CAPTURE_TIMEOUT_MS);
78 const captureSignal = AbortSignal.any([input.signal, captureTimeout]);
79
80 for (const candidate of selectFaviconCandidates(input.candidates)) {
81 if (captureSignal.aborted) {
82 return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
83 }
84 const captured = await captureCandidate({
85 webContents: input.webContents,
86 pageOrigin,
87 candidate,
88 signal: captureSignal,
89 });
90 if (captureSignal.aborted) {
91 return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
92 }
93 if (captured.kind === "captured" || captured.kind === "timed-out") return captured;
94 }
95
96 return { kind: "none" };
97}
98
99async function captureCandidate(input: {
100 readonly webContents: Electron.WebContents;
101 readonly pageOrigin: string;
102 readonly candidate: string;
103 readonly signal: AbortSignal;
104}): Promise<FaviconCaptureResult> {
105 try {
106 const inline = parseInlineFavicon(input.candidate);
107 if (inline) {
108 return await normalizeFaviconBuffer(
109 input.webContents,
110 inline.mime,
111 inline.buffer,
112 input.signal,
113 );
114 }
115
116 const candidateOrigin = safeHttpOrigin(input.candidate);
117 if (!candidateOrigin) return { kind: "none" };
118 const response = await input.webContents.session.fetch(input.candidate, {
119 credentials: candidateOrigin === input.pageOrigin ? "include" : "omit",
120 redirect: "error",
121 signal: input.signal,
122 });
123 if (!response.ok) {
124 await response.body?.cancel();
125 return { kind: "none" };
126 }
127 const buffer = await readFaviconResponse(response, input.signal);
128 if (!buffer || input.signal.aborted) return { kind: "none" };
129 const mime = response.headers.get("content-type")?.split(";", 1)[0] ?? null;
130 return await normalizeFaviconBuffer(input.webContents, mime, buffer, input.signal);
131 } catch {
132 return { kind: "none" };
133 }
134}
135
136async function readFaviconResponse(
137 response: Response,
138 signal: AbortSignal,
139): Promise<Buffer | null> {
140 const contentLength = Number(response.headers.get("content-length"));
141 if (Number.isFinite(contentLength) && contentLength > MAX_FAVICON_RESPONSE_BYTES) {
142 await response.body?.cancel();
143 return null;
144 }
145 if (!response.body) {
146 const buffer = Buffer.from(await response.arrayBuffer());
147 return buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES ? buffer : null;
148 }
149
150 const reader = response.body.getReader();
151 const cancelForAbort = () => {
152 void reader.cancel(signal.reason).catch(() => undefined);
153 };
154 signal.addEventListener("abort", cancelForAbort, { once: true });
155 if (signal.aborted) cancelForAbort();
156 const chunks: Buffer[] = [];
157 let byteLength = 0;
158 try {
159 while (true) {
160 const next = await reader.read();
161 if (next.done) return Buffer.concat(chunks, byteLength);
162 byteLength += next.value.byteLength;
163 if (byteLength > MAX_FAVICON_RESPONSE_BYTES) {
164 await reader.cancel();
165 return null;
166 }
167 chunks.push(Buffer.from(next.value));
168 }
169 } finally {
170 signal.removeEventListener("abort", cancelForAbort);
171 reader.releaseLock();
172 }
173}
174
175function isSupportedFaviconUrl(url: string): boolean {
176 if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return false;
177 if (/^data:/i.test(url)) return /^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(url);
178 try {
179 const protocol = new URL(url).protocol;
180 return (
181 (protocol === "http:" || protocol === "https:") && url.length <= MAX_FAVICON_HTTP_URL_LENGTH
182 );
183 } catch {
184 return false;
185 }
186}
187
188function decodeInlineFaviconPayload(payload: string): Buffer | null {
189 const decoded = Buffer.allocUnsafe(Buffer.byteLength(payload));
190 let inputOffset = 0;
191 let outputOffset = 0;
192 while (inputOffset < payload.length) {
193 const escapeOffset = payload.indexOf("%", inputOffset);
194 const literalEnd = escapeOffset === -1 ? payload.length : escapeOffset;
195 outputOffset += decoded.write(payload.slice(inputOffset, literalEnd), outputOffset, "utf8");
196 if (escapeOffset === -1) break;
197 const hex = payload.slice(escapeOffset + 1, escapeOffset + 3);
198 if (!/^[0-9a-f]{2}$/i.test(hex)) return null;
199 decoded[outputOffset] = Number.parseInt(hex, 16);
200 outputOffset += 1;
201 inputOffset = escapeOffset + 3;
202 }
203 return decoded.subarray(0, outputOffset);
204}
205
206function parseInlineFavicon(
207 url: string,
208): { readonly buffer: Buffer; readonly mime: string } | null {
209 if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return null;
210 const match = /^data:(image\/[a-z0-9.+-]+)((?:;[^,]*)?),(.*)$/is.exec(url);
211 if (!match) return null;
212 const mime = match[1]?.toLowerCase();
213 const parameters = match[2]
214 ?.split(";")
215 .filter(Boolean)
216 .map((parameter) => parameter.toLowerCase());
217 const payload = match[3];
218 if (!mime || !parameters || !payload) return null;
219 const base64 = parameters.at(-1) === "base64";
220 if (parameters.includes("base64") && !base64) return null;
221
222 let buffer: Buffer;
223 try {
224 if (base64) {
225 if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null;
226 buffer = Buffer.from(payload, "base64");
227 if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) {
228 return null;
229 }
230 } else {
231 const decoded = decodeInlineFaviconPayload(payload);
232 if (!decoded) return null;
233 buffer = decoded;
234 }
235 } catch {
236 return null;
237 }
238
239 return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
240 ? { buffer, mime }
241 : null;
242}
243
244interface ImageDimensions {
245 readonly width: number;
246 readonly height: number;
247}
248
249function safeDimensions(dimensions: ImageDimensions | null): dimensions is ImageDimensions {
250 return (
251 dimensions !== null &&
252 Number.isSafeInteger(dimensions.width) &&
253 Number.isSafeInteger(dimensions.height) &&
254 dimensions.width > 0 &&
255 dimensions.height > 0 &&
256 dimensions.width * dimensions.height <= MAX_FAVICON_SOURCE_PIXELS
257 );
258}
259
260function pngDimensions(buffer: Buffer): ImageDimensions | null {
261 if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
262 return null;
263 }
264 return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
265}
266
267function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
268 let offset = startOffset;
269 while (offset < buffer.byteLength) {
270 const blockLength = buffer[offset]!;
271 offset += 1;
272 if (blockLength === 0) return offset;
273 if (offset + blockLength > buffer.byteLength) return null;
274 offset += blockLength;
275 }
276 return null;
277}
278
279function gifDimensions(buffer: Buffer): ImageDimensions | null {
280 if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
281 return null;
282 }
283 const logicalWidth = buffer.readUInt16LE(6);
284 const logicalHeight = buffer.readUInt16LE(8);
285 if (!safeDimensions({ width: logicalWidth, height: logicalHeight })) return null;
286 const packed = buffer[10]!;
287 let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
288 if (offset > buffer.byteLength) return null;
289 let width = logicalWidth;
290 let height = logicalHeight;
291 let frameCount = 0;
292 let framePixels = 0;
293 while (offset < buffer.byteLength) {
294 const marker = buffer[offset];
295 if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
296 if (marker === 0x2c) {
297 if (offset + 10 > buffer.byteLength) return null;
298 const left = buffer.readUInt16LE(offset + 1);
299 const top = buffer.readUInt16LE(offset + 3);
300 const frameWidth = buffer.readUInt16LE(offset + 5);
301 const frameHeight = buffer.readUInt16LE(offset + 7);
302 if (frameWidth === 0 || frameHeight === 0) return null;
303 framePixels += frameWidth * frameHeight;
304 if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
305 width = Math.max(width, left + frameWidth);
306 height = Math.max(height, top + frameHeight);
307 if (!safeDimensions({ width, height })) return null;
308 const framePacked = buffer[offset + 9]!;
309 offset += 10;
310 if ((framePacked & 0x80) !== 0) {
311 offset += 3 * 2 ** ((framePacked & 0x07) + 1);
312 }
313 if (offset >= buffer.byteLength) return null;
314 const minimumCodeSize = buffer[offset]!;
315 if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
316 offset += 1;
317 const nextOffset = skipGifSubBlocks(buffer, offset);
318 if (nextOffset === null) return null;
319 offset = nextOffset;
320 frameCount += 1;
321 continue;
322 }
323 if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
324 const nextOffset = skipGifSubBlocks(buffer, offset + 2);
325 if (nextOffset === null) return null;
326 offset = nextOffset;
327 }
328 return null;
329}
330
331interface JpegExifMetadata {
332 readonly complete: boolean;
333 readonly orientation: number | null;
334}
335
336function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
337 if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
338 return null;
339 }
340 const metadataWithoutOrientation = (): JpegExifMetadata => ({
341 complete: true,
342 orientation: null,
343 });
344 if (segment.byteLength < 14) return metadataWithoutOrientation();
345 const tiffOffset = 6;
346 const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
347 const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
348 if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
349 const readUInt16 = (offset: number): number | null => {
350 if (offset < 0 || offset + 2 > segment.byteLength) return null;
351 return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
352 };
353 const readUInt32 = (offset: number): number | null => {
354 if (offset < 0 || offset + 4 > segment.byteLength) return null;
355 return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
356 };
357 const relativeIfdOffset = readUInt32(tiffOffset + 4);
358 if (relativeIfdOffset === null) return metadataWithoutOrientation();
359 // Keep untrusted metadata parsing linear even when IFD pointers overlap.
360 let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
361 const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
362 type IfdOrientation = number | null | typeof budgetExhausted;
363 const subIfdOrientationByOffset = new Map<number, number | null>();
364 const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
365 if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
366 return subIfdOrientationByOffset.get(ifdOffset) ?? null;
367 }
368 const entryCount = readUInt16(ifdOffset);
369 if (entryCount === null) return null;
370 let result: IfdOrientation = null;
371 for (let index = 0; index < entryCount; index += 1) {
372 if (remainingIfdEntryVisits === 0) return budgetExhausted;
373 remainingIfdEntryVisits -= 1;
374 const entryOffset = ifdOffset + 2 + index * 12;
375 if (entryOffset + 12 > segment.byteLength) break;
376 const tag = readUInt16(entryOffset);
377 const type = readUInt16(entryOffset + 2);
378 const count = readUInt32(entryOffset + 4);
379 if (tag === 0x0112 && type === 3 && count === 1) {
380 const orientation = readUInt16(entryOffset + 8);
381 if (orientation !== null && orientation >= 1 && orientation <= 8) {
382 result = orientation;
383 break;
384 }
385 } else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
386 const relativeSubIfdOffset = readUInt32(entryOffset + 8);
387 if (relativeSubIfdOffset !== null) {
388 const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
389 if (orientation === budgetExhausted) return budgetExhausted;
390 if (orientation !== null) {
391 result = orientation;
392 break;
393 }
394 }
395 }
396 }
397 if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
398 return result;
399 };
400 const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
401 return orientation === budgetExhausted
402 ? { complete: false, orientation: null }
403 : { complete: true, orientation };
404}
405
406function jpegDimensions(buffer: Buffer): ImageDimensions | null {
407 if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
408 const startOfFrameMarkers = new Set([
409 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
410 ]);
411 let offset = 2;
412 let dimensions: ImageDimensions | null = null;
413 let exifMetadata: JpegExifMetadata | null = null;
414 while (offset + 3 < buffer.byteLength) {
415 if (buffer[offset] !== 0xff) {
416 offset += 1;
417 continue;
418 }
419 while (buffer[offset] === 0xff) offset += 1;
420 const marker = buffer[offset];
421 offset += 1;
422 if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
423 if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
424 if (offset + 1 >= buffer.byteLength) return null;
425 const length = buffer.readUInt16BE(offset);
426 if (length < 2 || offset + length > buffer.byteLength) return null;
427 if (marker === 0xe1 && exifMetadata === null) {
428 exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
429 }
430 if (startOfFrameMarkers.has(marker)) {
431 if (length < 7) return null;
432 if (dimensions !== null) return null;
433 dimensions = {
434 height: buffer.readUInt16BE(offset + 3),
435 width: buffer.readUInt16BE(offset + 5),
436 };
437 }
438 offset += length;
439 }
440 if (!dimensions) return null;
441 if (exifMetadata?.complete === false) return null;
442 const orientation = exifMetadata?.orientation;
443 return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
444 ? { width: dimensions.height, height: dimensions.width }
445 : dimensions;
446}
447
448function webpDimensions(buffer: Buffer): ImageDimensions | null {
449 if (
450 buffer.byteLength < 30 ||
451 buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
452 buffer.subarray(8, 12).toString("ascii") !== "WEBP"
453 ) {
454 return null;
455 }
456 const kind = buffer.subarray(12, 16).toString("ascii");
457 if (kind === "VP8X") {
458 return {
459 width: 1 + buffer.readUIntLE(24, 3),
460 height: 1 + buffer.readUIntLE(27, 3),
461 };
462 }
463 if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
464 return {
465 width: buffer.readUInt16LE(26) & 0x3fff,
466 height: buffer.readUInt16LE(28) & 0x3fff,
467 };
468 }
469 if (kind === "VP8L" && buffer[20] === 0x2f) {
470 return {
471 width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
472 height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
473 };
474 }
475 return null;
476}
477
478function dibDimensions(buffer: Buffer): ImageDimensions | null {
479 if (buffer.byteLength < 12) return null;
480 const headerSize = buffer.readUInt32LE(0);
481 if (headerSize === 12) {
482 return {
483 width: buffer.readUInt16LE(4),
484 height: buffer.readUInt16LE(6),
485 };
486 }
487 if (headerSize < 40 || buffer.byteLength < 12) return null;
488 return {
489 width: Math.abs(buffer.readInt32LE(4)),
490 height: Math.abs(buffer.readInt32LE(8)),
491 };
492}
493
494function icoDimensions(buffer: Buffer): ImageDimensions | null {
495 if (
496 buffer.byteLength < 22 ||
497 buffer.readUInt16LE(0) !== 0 ||
498 (buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
499 ) {
500 return null;
501 }
502 const count = buffer.readUInt16LE(4);
503 if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
504 let width = 0;
505 let height = 0;
506 for (let index = 0; index < count; index += 1) {
507 const offset = 6 + index * 16;
508 width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
509 height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
510 if (!safeDimensions({ width, height })) return null;
511 const byteLength = buffer.readUInt32LE(offset + 8);
512 const imageOffset = buffer.readUInt32LE(offset + 12);
513 if (
514 byteLength === 0 ||
515 imageOffset < 6 + count * 16 ||
516 imageOffset > buffer.byteLength ||
517 byteLength > buffer.byteLength - imageOffset
518 )
519 return null;
520 const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
521 const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
522 if (!safeDimensions(embeddedDimensions)) return null;
523 }
524 return { width, height };
525}
526
527function sourceDimensions(buffer: Buffer): ImageDimensions | null {
528 return (
529 pngDimensions(buffer) ??
530 gifDimensions(buffer) ??
531 jpegDimensions(buffer) ??
532 webpDimensions(buffer) ??
533 icoDimensions(buffer)
534 );
535}
536
537async function normalizeFaviconBuffer(
538 webContents: Electron.WebContents,
539 mime: string | null,
540 buffer: Buffer,
541 signal: AbortSignal,
542): Promise<FaviconCaptureResult> {
543 const declaredMime = mime?.trim().toLowerCase() || null;
544 const normalizedMime =
545 declaredMime === "application/x-icon"
546 ? "image/x-icon"
547 : declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
548 ? null
549 : declaredMime;
550 const dimensions = sourceDimensions(buffer);
551 if (
552 (normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
553 normalizedMime === "image/svg+xml" ||
554 buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
555 !safeDimensions(dimensions)
556 ) {
557 return { kind: "none" };
558 }
559
560 const rasterized = await rasterizeFavicon(
561 webContents,
562 normalizedMime,
563 buffer,
564 dimensions,
565 signal,
566 );
567 if (rasterized.kind === "timed-out") return rasterized;
568 return typeof rasterized.value === "string" &&
569 rasterized.value.startsWith("data:image/png;base64,") &&
570 rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
571 ? { kind: "captured", dataUrl: rasterized.value }
572 : { kind: "none" };
573}
574
575async function rasterizeFavicon(
576 webContents: Electron.WebContents,
577 mime: string | null,
578 buffer: Buffer,
579 dimensions: ImageDimensions,
580 signal: AbortSignal,
581): Promise<RasterizationResult> {
582 const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
583 rasterizationGates.set(webContents, gate);
584 const generation = ++gate.generation;
585 const previousLaunchAllowed = gate.launchAllowed;
586 if (previousLaunchAllowed) {
587 await waitForRasterLaunch(previousLaunchAllowed, signal);
588 }
589 if (signal.aborted || generation !== gate.generation) {
590 return { kind: "completed", value: null };
591 }
592
593 const payload = buffer.toString("base64");
594 const blobType = mime ?? "";
595 const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
596 const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
597 const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
598 const drawX = (32 - decodeWidth) / 2;
599 const drawY = (32 - decodeHeight) / 2;
600 const code = `
601 (() => {
602 const rasterize = async () => {
603 try {
604 const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
605 const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
606 resizeWidth: ${decodeWidth},
607 resizeHeight: ${decodeHeight},
608 resizeQuality: "high",
609 });
610 try {
611 if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
612 return null;
613 }
614 const canvas = new OffscreenCanvas(32, 32);
615 const context = canvas.getContext("2d");
616 if (!context) return null;
617 context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
618 const blob = await canvas.convertToBlob({ type: "image/png" });
619 const output = new Uint8Array(await blob.arrayBuffer());
620 let binary = "";
621 for (const byte of output) binary += String.fromCharCode(byte);
622 return "data:image/png;base64," + btoa(binary);
623 } finally {
624 bitmap.close();
625 }
626 } catch {
627 return null;
628 }
629 };
630 return rasterize();
631 })()
632 `;
633
634 const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
635 { code },
636 ]);
637
638 const result = new Promise<RasterizationResult>((resolve, reject) => {
639 // Electron cannot cancel isolated-world execution. This timeout ends only
640 // the logical attempt; renderer work may finish after a newer attempt starts.
641 const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
642 let settled = false;
643 const finish = (complete: () => void) => {
644 if (settled) return;
645 settled = true;
646 timeout.removeEventListener("abort", onTimeout);
647 signal.removeEventListener("abort", onAbort);
648 complete();
649 };
650 const onTimeout = () => {
651 finish(() => resolve({ kind: "timed-out" }));
652 };
653 const onAbort = () => {
654 finish(() => resolve({ kind: "completed", value: null }));
655 };
656 timeout.addEventListener("abort", onTimeout, { once: true });
657 signal.addEventListener("abort", onAbort, { once: true });
658 void execution.then(
659 (value) => {
660 finish(() => resolve({ kind: "completed", value }));
661 },
662 (cause: unknown) => {
663 finish(() => reject(cause));
664 },
665 );
666 if (signal.aborted) onAbort();
667 });
668 // The logical timeout does not cancel Electron's renderer work. Keep the
669 // gate closed until that physical execution actually settles.
670 const launchAllowed = execution.then(
671 () => undefined,
672 () => undefined,
673 );
674 gate.launchAllowed = launchAllowed;
675 void launchAllowed.then(() => {
676 if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
677 });
678 return await result;
679}