Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FaviconCapture.ts

685 lines24.1 KB

1import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
2​
3export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
4export const MAX_FAVICON_CANDIDATES = 8;
5const 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>;
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 });
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 }
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;
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" };
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 }
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 }
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 }
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);
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 const encoded = decodeInlineFaviconPayload(payload)?.toString("latin1");
226 if (!encoded || !/^[a-z0-9+/]*={0,2}$/i.test(encoded) || encoded.length % 4 === 1) {
227 return null;
228 }
229 buffer = Buffer.from(encoded, "base64");
230 if (buffer.toString("base64").replace(/=+$/, "") !== encoded.replace(/=+$/, "")) {
231 return null;
232 }
233 } else {
234 const decoded = decodeInlineFaviconPayload(payload);
235 if (!decoded) return null;
236 buffer = decoded;
237 }
238 } catch {
239 return null;
240 }
241​
242 return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
243 ? { buffer, mime }
244 : null;
246​
247interface ImageDimensions {
248 readonly width: number;
249 readonly height: number;
251​
252function safeDimensions(
253 dimensions: ImageDimensions | null,
254 maxPixels = MAX_FAVICON_SOURCE_PIXELS,
255): dimensions is ImageDimensions {
256 return (
257 dimensions !== null &&
258 Number.isSafeInteger(dimensions.width) &&
259 Number.isSafeInteger(dimensions.height) &&
260 dimensions.width > 0 &&
261 dimensions.height > 0 &&
262 dimensions.width * dimensions.height <= maxPixels
263 );
265​
266function pngDimensions(buffer: Buffer): ImageDimensions | null {
267 if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
268 return null;
269 }
270 return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
272​
273function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
274 let offset = startOffset;
275 while (offset < buffer.byteLength) {
276 const blockLength = buffer[offset]!;
277 offset += 1;
278 if (blockLength === 0) return offset;
279 if (offset + blockLength > buffer.byteLength) return null;
280 offset += blockLength;
281 }
282 return null;
284​
285function gifDimensions(buffer: Buffer, maxPixels: number): ImageDimensions | null {
286 if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
287 return null;
288 }
289 const logicalWidth = buffer.readUInt16LE(6);
290 const logicalHeight = buffer.readUInt16LE(8);
291 if (!safeDimensions({ width: logicalWidth, height: logicalHeight }, maxPixels)) return null;
292 const packed = buffer[10]!;
293 let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
294 if (offset > buffer.byteLength) return null;
295 let width = logicalWidth;
296 let height = logicalHeight;
297 let frameCount = 0;
298 let framePixels = 0;
299 while (offset < buffer.byteLength) {
300 const marker = buffer[offset];
301 if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
302 if (marker === 0x2c) {
303 if (offset + 10 > buffer.byteLength) return null;
304 const left = buffer.readUInt16LE(offset + 1);
305 const top = buffer.readUInt16LE(offset + 3);
306 const frameWidth = buffer.readUInt16LE(offset + 5);
307 const frameHeight = buffer.readUInt16LE(offset + 7);
308 if (frameWidth === 0 || frameHeight === 0) return null;
309 framePixels += frameWidth * frameHeight;
310 if (framePixels > maxPixels) return null;
311 width = Math.max(width, left + frameWidth);
312 height = Math.max(height, top + frameHeight);
313 if (!safeDimensions({ width, height }, maxPixels)) return null;
314 const framePacked = buffer[offset + 9]!;
315 offset += 10;
316 if ((framePacked & 0x80) !== 0) {
317 offset += 3 * 2 ** ((framePacked & 0x07) + 1);
318 }
319 if (offset >= buffer.byteLength) return null;
320 const minimumCodeSize = buffer[offset]!;
321 if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
322 offset += 1;
323 const nextOffset = skipGifSubBlocks(buffer, offset);
324 if (nextOffset === null) return null;
325 offset = nextOffset;
326 frameCount += 1;
327 continue;
328 }
329 if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
330 const nextOffset = skipGifSubBlocks(buffer, offset + 2);
331 if (nextOffset === null) return null;
332 offset = nextOffset;
333 }
334 return null;
336​
337interface JpegExifMetadata {
338 readonly complete: boolean;
339 readonly orientation: number | null;
341​
342function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
343 if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
344 return null;
345 }
346 const metadataWithoutOrientation = (): JpegExifMetadata => ({
347 complete: true,
348 orientation: null,
349 });
350 if (segment.byteLength < 14) return metadataWithoutOrientation();
351 const tiffOffset = 6;
352 const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
353 const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
354 if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
355 const readUInt16 = (offset: number): number | null => {
356 if (offset < 0 || offset + 2 > segment.byteLength) return null;
357 return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
358 };
359 const readUInt32 = (offset: number): number | null => {
360 if (offset < 0 || offset + 4 > segment.byteLength) return null;
361 return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
362 };
363 const relativeIfdOffset = readUInt32(tiffOffset + 4);
364 if (relativeIfdOffset === null) return metadataWithoutOrientation();
365 // Keep untrusted metadata parsing linear even when IFD pointers overlap.
366 let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
367 const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
368 type IfdOrientation = number | null | typeof budgetExhausted;
369 const subIfdOrientationByOffset = new Map<number, number | null>();
370 const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
371 if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
372 return subIfdOrientationByOffset.get(ifdOffset) ?? null;
373 }
374 const entryCount = readUInt16(ifdOffset);
375 if (entryCount === null) return null;
376 let result: IfdOrientation = null;
377 for (let index = 0; index < entryCount; index += 1) {
378 if (remainingIfdEntryVisits === 0) return budgetExhausted;
379 remainingIfdEntryVisits -= 1;
380 const entryOffset = ifdOffset + 2 + index * 12;
381 if (entryOffset + 12 > segment.byteLength) break;
382 const tag = readUInt16(entryOffset);
383 const type = readUInt16(entryOffset + 2);
384 const count = readUInt32(entryOffset + 4);
385 if (tag === 0x0112 && type === 3 && count === 1) {
386 const orientation = readUInt16(entryOffset + 8);
387 if (orientation !== null && orientation >= 1 && orientation <= 8) {
388 result = orientation;
389 break;
390 }
391 } else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
392 const relativeSubIfdOffset = readUInt32(entryOffset + 8);
393 if (relativeSubIfdOffset !== null) {
394 const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
395 if (orientation === budgetExhausted) return budgetExhausted;
396 if (orientation !== null) {
397 result = orientation;
398 break;
399 }
400 }
401 }
402 }
403 if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
404 return result;
405 };
406 const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
407 return orientation === budgetExhausted
408 ? { complete: false, orientation: null }
409 : { complete: true, orientation };
411​
412function jpegDimensions(buffer: Buffer): ImageDimensions | null {
413 if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
414 const startOfFrameMarkers = new Set([
415 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
416 ]);
417 let offset = 2;
418 let dimensions: ImageDimensions | null = null;
419 let exifMetadata: JpegExifMetadata | null = null;
420 while (offset + 3 < buffer.byteLength) {
421 if (buffer[offset] !== 0xff) {
422 offset += 1;
423 continue;
424 }
425 while (buffer[offset] === 0xff) offset += 1;
426 const marker = buffer[offset];
427 offset += 1;
428 if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
429 if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
430 if (offset + 1 >= buffer.byteLength) return null;
431 const length = buffer.readUInt16BE(offset);
432 if (length < 2 || offset + length > buffer.byteLength) return null;
433 if (marker === 0xe1 && exifMetadata === null) {
434 exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
435 }
436 if (startOfFrameMarkers.has(marker)) {
437 if (length < 7) return null;
438 if (dimensions !== null) return null;
439 dimensions = {
440 height: buffer.readUInt16BE(offset + 3),
441 width: buffer.readUInt16BE(offset + 5),
442 };
443 }
444 offset += length;
445 }
446 if (!dimensions) return null;
447 if (exifMetadata?.complete === false) return null;
448 const orientation = exifMetadata?.orientation;
449 return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
450 ? { width: dimensions.height, height: dimensions.width }
451 : dimensions;
453​
454function webpDimensions(buffer: Buffer): ImageDimensions | null {
455 if (
456 buffer.byteLength < 30 ||
457 buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
458 buffer.subarray(8, 12).toString("ascii") !== "WEBP"
459 ) {
460 return null;
461 }
462 const kind = buffer.subarray(12, 16).toString("ascii");
463 if (kind === "VP8X") {
464 return {
465 width: 1 + buffer.readUIntLE(24, 3),
466 height: 1 + buffer.readUIntLE(27, 3),
467 };
468 }
469 if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
470 return {
471 width: buffer.readUInt16LE(26) & 0x3fff,
472 height: buffer.readUInt16LE(28) & 0x3fff,
473 };
474 }
475 if (kind === "VP8L" && buffer[20] === 0x2f) {
476 return {
477 width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
478 height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
479 };
480 }
481 return null;
483​
484function dibDimensions(buffer: Buffer): ImageDimensions | null {
485 if (buffer.byteLength < 12) return null;
486 const headerSize = buffer.readUInt32LE(0);
487 if (headerSize === 12) {
488 return {
489 width: buffer.readUInt16LE(4),
490 height: buffer.readUInt16LE(6),
491 };
492 }
493 if (headerSize < 40 || buffer.byteLength < 12) return null;
494 return {
495 width: Math.abs(buffer.readInt32LE(4)),
496 height: Math.abs(buffer.readInt32LE(8)),
497 };
499​
500function icoDimensions(buffer: Buffer, maxPixels: number): ImageDimensions | null {
501 if (
502 buffer.byteLength < 22 ||
503 buffer.readUInt16LE(0) !== 0 ||
504 (buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
505 ) {
506 return null;
507 }
508 const count = buffer.readUInt16LE(4);
509 if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
510 let width = 0;
511 let height = 0;
512 for (let index = 0; index < count; index += 1) {
513 const offset = 6 + index * 16;
514 width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
515 height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
516 if (!safeDimensions({ width, height }, maxPixels)) return null;
517 const byteLength = buffer.readUInt32LE(offset + 8);
518 const imageOffset = buffer.readUInt32LE(offset + 12);
519 if (
520 byteLength === 0 ||
521 imageOffset < 6 + count * 16 ||
522 imageOffset > buffer.byteLength ||
523 byteLength > buffer.byteLength - imageOffset
524 )
525 return null;
526 const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
527 const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
528 if (!safeDimensions(embeddedDimensions, maxPixels)) return null;
529 }
530 return { width, height };
532​
533export function sourceDimensions(
534 buffer: Buffer,
535 maxPixels = MAX_FAVICON_SOURCE_PIXELS,
536): ImageDimensions | null {
537 return (
538 pngDimensions(buffer) ??
539 gifDimensions(buffer, maxPixels) ??
540 jpegDimensions(buffer) ??
541 webpDimensions(buffer) ??
542 icoDimensions(buffer, maxPixels)
543 );
545​
546async function normalizeFaviconBuffer(
547 webContents: Electron.WebContents,
548 mime: string | null,
549 buffer: Buffer,
550 signal: AbortSignal,
551): Promise<FaviconCaptureResult> {
552 const declaredMime = mime?.trim().toLowerCase() || null;
553 const normalizedMime =
554 declaredMime === "application/x-icon"
555 ? "image/x-icon"
556 : declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
557 ? null
558 : declaredMime;
559 const dimensions = sourceDimensions(buffer);
560 if (
561 (normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
562 normalizedMime === "image/svg+xml" ||
563 buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
564 !safeDimensions(dimensions)
565 ) {
566 return { kind: "none" };
567 }
568​
569 const rasterized = await rasterizeFavicon(
570 webContents,
571 normalizedMime,
572 buffer,
573 dimensions,
574 signal,
575 );
576 if (rasterized.kind === "timed-out") return rasterized;
577 return typeof rasterized.value === "string" &&
578 rasterized.value.startsWith("data:image/png;base64,") &&
579 rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
580 ? { kind: "captured", dataUrl: rasterized.value }
581 : { kind: "none" };
583​
584async function rasterizeFavicon(
585 webContents: Electron.WebContents,
586 mime: string | null,
587 buffer: Buffer,
588 dimensions: ImageDimensions,
589 signal: AbortSignal,
590): Promise<RasterizationResult> {
591 const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
592 rasterizationGates.set(webContents, gate);
593 const generation = ++gate.generation;
594 const previousLaunchAllowed = gate.launchAllowed;
595 if (previousLaunchAllowed) {
596 await waitForRasterLaunch(previousLaunchAllowed, signal);
597 }
598 if (signal.aborted || generation !== gate.generation) {
599 return { kind: "completed", value: null };
600 }
601​
602 const payload = buffer.toString("base64");
603 const blobType = mime ?? "";
604 const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
605 const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
606 const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
607 const drawX = (32 - decodeWidth) / 2;
608 const drawY = (32 - decodeHeight) / 2;
609 const code = `
610 (() => {
611 const rasterize = async () => {
612 try {
613 const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
614 const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
615 resizeWidth: ${decodeWidth},
616 resizeHeight: ${decodeHeight},
617 resizeQuality: "high",
618 });
619 try {
620 if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
621 return null;
622 }
623 const canvas = new OffscreenCanvas(32, 32);
624 const context = canvas.getContext("2d");
625 if (!context) return null;
626 context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
627 const blob = await canvas.convertToBlob({ type: "image/png" });
628 const output = new Uint8Array(await blob.arrayBuffer());
629 let binary = "";
630 for (const byte of output) binary += String.fromCharCode(byte);
631 return "data:image/png;base64," + btoa(binary);
632 } finally {
633 bitmap.close();
634 }
635 } catch {
636 return null;
637 }
638 };
639 return rasterize();
640 })()
641 `;
642​
643 const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
644 { code },
645 ]);
646​
647 const result = new Promise<RasterizationResult>((resolve, reject) => {
648 const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
649 let settled = false;
650 const finish = (complete: () => void) => {
651 if (settled) return;
652 settled = true;
653 timeout.removeEventListener("abort", onTimeout);
654 signal.removeEventListener("abort", onAbort);
655 complete();
656 };
657 const onTimeout = () => {
658 finish(() => resolve({ kind: "timed-out" }));
659 };
660 const onAbort = () => {
661 finish(() => resolve({ kind: "completed", value: null }));
662 };
663 timeout.addEventListener("abort", onTimeout, { once: true });
664 signal.addEventListener("abort", onAbort, { once: true });
665 void execution.then(
666 (value) => {
667 finish(() => resolve({ kind: "completed", value }));
668 },
669 (cause: unknown) => {
670 finish(() => reject(cause));
671 },
672 );
673 if (signal.aborted) onAbort();
674 });
675 // Logical timeouts leave renderer work running; keep the gate closed until it settles.
676 const launchAllowed = execution.then(
677 () => undefined,
678 () => undefined,
679 );
680 gate.launchAllowed = launchAllowed;
681 void launchAllowed.then(() => {
682 if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
683 });
684 return await result;