feat(desktop): add favicons to the Browser panel (#5644)
This commit is contained in:
1 parent
e15f655ba4
commit
710fd0eeb3
28 files changed
+4189
-71
No files matched your search
@@ -0,0 +1,999 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MAX_FAVICON_CANDIDATES,
|
||||
MAX_FAVICON_RESPONSE_BYTES,
|
||||
captureFavicon,
|
||||
selectFaviconCandidates,
|
||||
} from "./FaviconCapture.ts";
|
||||
|
||||
const PNG = "data:image/png;base64,cG5n";
|
||||
const SOURCE_PNG = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(SOURCE_PNG);
|
||||
SOURCE_PNG.writeUInt32BE(1, 16);
|
||||
SOURCE_PNG.writeUInt32BE(1, 20);
|
||||
const SOURCE_PNG_URL = `data:image/png;base64,${SOURCE_PNG.toString("base64")}`;
|
||||
|
||||
function sourceGif(
|
||||
width: number,
|
||||
height: number,
|
||||
frameWidth = width,
|
||||
frameHeight = height,
|
||||
additionalFrames: ReadonlyArray<{
|
||||
readonly left?: number;
|
||||
readonly top?: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}> = [],
|
||||
): Buffer {
|
||||
const frames = [{ width: frameWidth, height: frameHeight }, ...additionalFrames];
|
||||
const buffer = Buffer.alloc(13 + frames.length * 12 + 1);
|
||||
buffer.write("GIF89a", 0, "ascii");
|
||||
buffer.writeUInt16LE(width, 6);
|
||||
buffer.writeUInt16LE(height, 8);
|
||||
let offset = 13;
|
||||
for (const frame of frames) {
|
||||
buffer[offset] = 0x2c;
|
||||
buffer.writeUInt16LE(frame.left ?? 0, offset + 1);
|
||||
buffer.writeUInt16LE(frame.top ?? 0, offset + 3);
|
||||
buffer.writeUInt16LE(frame.width, offset + 5);
|
||||
buffer.writeUInt16LE(frame.height, offset + 7);
|
||||
offset += 10;
|
||||
buffer[offset] = 2;
|
||||
buffer[offset + 1] = 0;
|
||||
offset += 2;
|
||||
}
|
||||
buffer[offset] = 0x3b;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceJpeg(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: number | ReadonlyArray<number> = [],
|
||||
): Buffer {
|
||||
const frame = Buffer.from([
|
||||
0xff,
|
||||
0xd8,
|
||||
0xff,
|
||||
0xc0,
|
||||
0x00,
|
||||
0x07,
|
||||
0x08,
|
||||
height >>> 8,
|
||||
height & 0xff,
|
||||
width >>> 8,
|
||||
width & 0xff,
|
||||
]);
|
||||
const app1Segments = (typeof orientations === "number" ? [orientations] : orientations).map(
|
||||
(orientation) => sourceJpegExifSegment([orientation]),
|
||||
);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...app1Segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegApp1Segment(payload: Buffer): Buffer {
|
||||
const app1 = Buffer.alloc(4 + payload.byteLength);
|
||||
app1[0] = 0xff;
|
||||
app1[1] = 0xe1;
|
||||
app1.writeUInt16BE(payload.byteLength + 2, 2);
|
||||
payload.copy(app1, 4);
|
||||
return app1;
|
||||
}
|
||||
|
||||
function sourceJpegExifSegment(
|
||||
orientations: ReadonlyArray<number>,
|
||||
options?: {
|
||||
readonly byteOrder?: "II" | "MM";
|
||||
readonly magic?: number;
|
||||
readonly padding?: number;
|
||||
},
|
||||
): Buffer {
|
||||
const exif = Buffer.alloc(20 + orientations.length * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif[5] = options?.padding ?? 0;
|
||||
const littleEndian = options?.byteOrder !== "MM";
|
||||
exif.write(littleEndian ? "II" : "MM", 6, "ascii");
|
||||
const writeUInt16 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt16LE(value, offset) : exif.writeUInt16BE(value, offset);
|
||||
const writeUInt32 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt32LE(value, offset) : exif.writeUInt32BE(value, offset);
|
||||
writeUInt16(options?.magic ?? 42, 8);
|
||||
writeUInt32(8, 10);
|
||||
writeUInt16(orientations.length, 14);
|
||||
orientations.forEach((orientation, index) => {
|
||||
const entryOffset = 16 + index * 12;
|
||||
writeUInt16(0x0112, entryOffset);
|
||||
writeUInt16(3, entryOffset + 2);
|
||||
writeUInt32(1, entryOffset + 4);
|
||||
writeUInt16(orientation, entryOffset + 8);
|
||||
});
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegWithApp1Segments(
|
||||
width: number,
|
||||
height: number,
|
||||
segments: ReadonlyArray<Buffer>,
|
||||
): Buffer {
|
||||
const frame = sourceJpeg(width, height);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithOrientationEntries(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: ReadonlyArray<number>,
|
||||
): Buffer {
|
||||
return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer {
|
||||
const exif = sourceJpegExifSegment([6], { byteOrder });
|
||||
exif[10] = alias;
|
||||
exif[11] = alias;
|
||||
return sourceJpegWithApp1Segments(64, 32, [exif]);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfd(options: {
|
||||
readonly rootOrientation?: number;
|
||||
readonly subIfdFirst?: boolean;
|
||||
readonly subIfdOrientation: number;
|
||||
}): Buffer {
|
||||
const rootEntries = options.rootOrientation === undefined ? 1 : 2;
|
||||
const rootIfdOffset = 14;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
|
||||
const writeOrientation = (offset: number, orientation: number) => {
|
||||
exif.writeUInt16LE(0x0112, offset);
|
||||
exif.writeUInt16LE(3, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt16LE(orientation, offset + 8);
|
||||
};
|
||||
const writeSubIfdPointer = (offset: number) => {
|
||||
exif.writeUInt16LE(0x8769, offset);
|
||||
exif.writeUInt16LE(4, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, offset + 8);
|
||||
};
|
||||
|
||||
const firstRootEntryOffset = rootIfdOffset + 2;
|
||||
if (options.rootOrientation === undefined) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
} else if (options.subIfdFirst) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
writeOrientation(firstRootEntryOffset + 12, options.rootOrientation);
|
||||
} else {
|
||||
writeOrientation(firstRootEntryOffset, options.rootOrientation);
|
||||
writeSubIfdPointer(firstRootEntryOffset + 12);
|
||||
}
|
||||
|
||||
exif.writeUInt16LE(1, subIfdOffset);
|
||||
writeOrientation(subIfdOffset + 2, options.subIfdOrientation);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfdPointers(options: {
|
||||
readonly pointerCount: number;
|
||||
readonly subIfdEntries: number;
|
||||
}): Buffer {
|
||||
const { pointerCount, subIfdEntries } = options;
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset);
|
||||
for (let index = 0; index < subIfdEntries; index += 1) {
|
||||
const entryOffset = subIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(1, entryOffset);
|
||||
exif.writeUInt16LE(3, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
}
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer {
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + pointerCount * 2 + 2 + subIfdEntries * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset + index * 2 - 6, entryOffset + 8);
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset + index * 2);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceWebp(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.alloc(30);
|
||||
buffer.write("RIFF", 0, "ascii");
|
||||
buffer.write("WEBP", 8, "ascii");
|
||||
buffer.write("VP8X", 12, "ascii");
|
||||
buffer.writeUIntLE(width - 1, 24, 3);
|
||||
buffer.writeUIntLE(height - 1, 27, 3);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceIco(embedded: Buffer): Buffer {
|
||||
const buffer = Buffer.alloc(22 + embedded.byteLength);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(embedded.byteLength, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
embedded.copy(buffer, 22);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafePng(): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(4096, 16);
|
||||
buffer.writeUInt32BE(4096, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourcePng(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafeDib(): Buffer {
|
||||
const buffer = Buffer.alloc(40);
|
||||
buffer.writeUInt32LE(40, 0);
|
||||
buffer.writeInt32LE(4096, 4);
|
||||
buffer.writeInt32LE(4096, 8);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeWebContents(options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
}) {
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : PNG,
|
||||
);
|
||||
return {
|
||||
webContents: {
|
||||
session: { fetch },
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
} as never,
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
};
|
||||
}
|
||||
|
||||
const JPEG_LANDSCAPE_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
resizeHeight: 16,
|
||||
resizeWidth: 32,
|
||||
} as const;
|
||||
const JPEG_PORTRAIT_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
resizeHeight: 32,
|
||||
resizeWidth: 16,
|
||||
} as const;
|
||||
|
||||
async function expectJpegLayout(
|
||||
source: Buffer,
|
||||
layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT,
|
||||
): Promise<void> {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`);
|
||||
expect(code).toContain(layout.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
describe("selectFaviconCandidates", () => {
|
||||
it("filters and deduplicates before applying the candidate cap", () => {
|
||||
const valid = Array.from(
|
||||
{ length: MAX_FAVICON_CANDIDATES + 2 },
|
||||
(_, index) => `https://example.com/favicon-${index}.png`,
|
||||
);
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 64 }, () => "javascript:alert(1)"),
|
||||
valid[0]!,
|
||||
valid[0]!,
|
||||
...valid.slice(1),
|
||||
]),
|
||||
).toEqual(valid.slice(0, MAX_FAVICON_CANDIDATES));
|
||||
});
|
||||
|
||||
it("bounds raw candidate scanning independently of the usable-candidate cap", () => {
|
||||
const oversizedInvalid = `javascript:${"x".repeat(2_048)}`;
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 128 }, () => oversizedInvalid),
|
||||
"https://example.com/too-late.png",
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("captureFavicon", () => {
|
||||
it.each([
|
||||
{
|
||||
label: "same-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://example.com/favicon.png",
|
||||
credentials: "include",
|
||||
},
|
||||
{
|
||||
label: "cross-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://cdn.example.net/favicon.png",
|
||||
credentials: "omit",
|
||||
},
|
||||
])("uses the explicit credential policy for $label requests", async (testCase) => {
|
||||
const { webContents, fetch } = makeWebContents();
|
||||
const result = await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: testCase.pageUrl,
|
||||
candidates: [testCase.faviconUrl],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
testCase.faviconUrl,
|
||||
expect.objectContaining({ credentials: testCase.credentials, redirect: "error" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("decodes base64 and percent-encoded inline images without fetching", async () => {
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const percentEncodedPng = [...SOURCE_PNG]
|
||||
.map((byte) => `%${byte.toString(16).padStart(2, "0")}`)
|
||||
.join("");
|
||||
|
||||
for (const candidate of [SOURCE_PNG_URL, `data:image/png,${percentEncodedPng}`]) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("tries the next candidate after an ordinary rejection", async () => {
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(null, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("cancels a rejected response body before trying the next candidate", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(body, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("stops a pending fetch when its capture is aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: (_url, init) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
expect(await capture).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("ends candidate fallback when the overall capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: (url, init) => {
|
||||
if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 }));
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [
|
||||
"https://example.com/first.png",
|
||||
"https://example.com/second.png",
|
||||
"https://example.com/third.png",
|
||||
],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(timeout).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not publish a rasterization that completes after the capture deadline", async () => {
|
||||
const captureTimeoutController = new AbortController();
|
||||
const rasterTimeoutController = new AbortController();
|
||||
const timeout = vi
|
||||
.spyOn(AbortSignal, "timeout")
|
||||
.mockImplementation((milliseconds) =>
|
||||
milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal,
|
||||
);
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce());
|
||||
captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a stalled response body when the capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const cancel = vi.fn();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
cancel,
|
||||
}),
|
||||
{ headers: { "content-type": "image/png" } },
|
||||
),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects and cancels an oversized streamed response", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(MAX_FAVICON_RESPONSE_BYTES));
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () => new Response(body, { headers: { "content-type": "image/png" } }),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains bounded compatibility with common favicon formats", async () => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
for (const [mime, buffer] of [
|
||||
["image/gif", sourceGif(32, 32)],
|
||||
["image/jpeg", sourceJpeg(32, 32)],
|
||||
["image/webp", sourceWebp(32, 32)],
|
||||
["image/x-icon", sourceIco(SOURCE_PNG)],
|
||||
] as const) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:${mime};base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "landscape",
|
||||
source: sourcePng(64, 32),
|
||||
resizeWidth: 32,
|
||||
resizeHeight: 16,
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
},
|
||||
{
|
||||
label: "portrait",
|
||||
source: sourcePng(32, 64),
|
||||
resizeWidth: 16,
|
||||
resizeHeight: 32,
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
},
|
||||
])("preserves $label aspect ratio within the 32x32 output", async (testCase) => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`);
|
||||
expect(code).toContain('resizeQuality: "high"');
|
||||
expect(code).toContain(testCase.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
});
|
||||
|
||||
it.each([
|
||||
...[1, 2, 3, 4].map((orientation) => ({
|
||||
label: `keeps stored dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
...[5, 6, 7, 8].map((orientation) => ({
|
||||
label: `uses display dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is transposed",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [6, 1]),
|
||||
},
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is untransposed",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [1, 6]),
|
||||
},
|
||||
{
|
||||
label: "does not consult a later EXIF segment after an invalid orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "uses a later valid orientation in the same IFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithOrientationEntries(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "skips a non-EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("not-exif")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "skips an empty EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "stops after a malformed qualifying EXIF APP1 segment",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "ignores the EXIF padding byte",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]),
|
||||
},
|
||||
{
|
||||
label: "reads big-endian EXIF",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]),
|
||||
},
|
||||
{
|
||||
label: "matches Chromium for a nonstandard TIFF magic field",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit little-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xc9, "II"),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit big-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xcd, "MM"),
|
||||
},
|
||||
{
|
||||
label: "reads an orientation from a SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a SubIFD orientation before a later root orientation",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({
|
||||
rootOrientation: 1,
|
||||
subIfdFirst: true,
|
||||
subIfdOrientation: 6,
|
||||
}),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a root orientation before a later SubIFD orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "memoizes repeated aliases to the same SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }),
|
||||
]),
|
||||
},
|
||||
])("matches Chromium JPEG layout: $label", async ({ source, layout }) => {
|
||||
await expectJpegLayout(source, layout);
|
||||
});
|
||||
|
||||
it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => {
|
||||
const source = sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithOverlappingSubIfds(32, 32),
|
||||
]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects JPEGs with multiple frame headers before rasterization", async () => {
|
||||
const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unsafe PNG size before rasterization", async () => {
|
||||
const buffer = makeUnsafePng();
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(new Uint8Array(buffer), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["GIF", "image/gif", sourceGif(4096, 4096)],
|
||||
["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)],
|
||||
["GIF later frame", "image/gif", sourceGif(1, 1, 1, 1, [{ width: 4096, height: 4096 }])],
|
||||
[
|
||||
"GIF cumulative frames",
|
||||
"image/gif",
|
||||
sourceGif(
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
Array.from({ length: 256 }, () => ({ width: 64, height: 64 })),
|
||||
),
|
||||
],
|
||||
["JPEG", "image/jpeg", sourceJpeg(4096, 4096)],
|
||||
["WebP", "image/webp", sourceWebp(4096, 4096)],
|
||||
["ICO with PNG", "image/x-icon", sourceIco(makeUnsafePng())],
|
||||
["ICO with DIB", "image/x-icon", sourceIco(makeUnsafeDib())],
|
||||
["SVG", "image/svg+xml", Buffer.from('<svg width="1" height="1"/>')],
|
||||
[
|
||||
"SVG with embedded bitmap",
|
||||
"image/svg+xml",
|
||||
Buffer.from(
|
||||
`<svg width="1" height="1"><image href="data:image/png;base64,${makeUnsafePng().toString("base64")}"/></svg>`,
|
||||
),
|
||||
],
|
||||
[
|
||||
"ICO invalid payload span",
|
||||
"image/x-icon",
|
||||
(() => {
|
||||
const buffer = Buffer.alloc(22);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(100, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
return buffer;
|
||||
})(),
|
||||
],
|
||||
])("rejects unsafe or unsupported %s before rasterization", async (_label, mime, buffer) => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const candidate = `data:${mime};base64,${buffer.toString("base64")}`;
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores output that is not a bounded PNG data URL", async () => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async () => "data:image/svg+xml;base64,c3Zn",
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("waits for physical rasterization settlement after a logical timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveOld!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveOld = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const timedOut = captureFavicon(input);
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
expect(await timedOut).toEqual({ kind: "timed-out" });
|
||||
|
||||
const newer = captureFavicon(input);
|
||||
await Promise.resolve();
|
||||
expect(executions).toBe(1);
|
||||
resolveOld(PNG);
|
||||
expect(await newer).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("ends candidate fallback after a rasterization timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce();
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("coalesces queued rasterizations so only the latest pending capture launches", async () => {
|
||||
let resolveFirst!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const first = captureFavicon(input);
|
||||
const superseded = captureFavicon(input);
|
||||
const newest = captureFavicon(input);
|
||||
|
||||
expect(executions).toBe(1);
|
||||
resolveFirst(PNG);
|
||||
expect(await first).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(await superseded).toEqual({ kind: "none" });
|
||||
expect(await newest).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,679 @@
|
||||
import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
|
||||
export const MAX_FAVICON_CANDIDATES = 8;
|
||||
export const MAX_FAVICON_HTTP_URL_LENGTH = 2_048;
|
||||
|
||||
const MAX_FAVICON_CANDIDATE_INPUT_UNITS = 262_144;
|
||||
const MIN_FAVICON_CANDIDATE_INPUT_UNITS = 256;
|
||||
const MAX_FAVICON_SOURCE_PIXELS = 1_048_576;
|
||||
const MAX_FAVICON_INLINE_URL_LENGTH = Math.ceil((MAX_FAVICON_RESPONSE_BYTES * 4) / 3) + 128;
|
||||
const FAVICON_CAPTURE_TIMEOUT_MS = 5_000;
|
||||
const FAVICON_RASTER_WORLD_ID = 1001;
|
||||
const FAVICON_RASTER_TIMEOUT_MS = 1_000;
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
|
||||
interface RasterizationGate {
|
||||
generation: number;
|
||||
launchAllowed?: Promise<void>;
|
||||
}
|
||||
|
||||
const rasterizationGates = new WeakMap<Electron.WebContents, RasterizationGate>();
|
||||
|
||||
async function waitForRasterLaunch(previous: Promise<void>, signal: AbortSignal): Promise<void> {
|
||||
if (signal.aborted) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const finish = () => {
|
||||
signal.removeEventListener("abort", finish);
|
||||
resolve();
|
||||
};
|
||||
signal.addEventListener("abort", finish, { once: true });
|
||||
void previous.then(finish);
|
||||
});
|
||||
}
|
||||
|
||||
export type FaviconCaptureResult =
|
||||
| { readonly kind: "captured"; readonly dataUrl: string }
|
||||
| { readonly kind: "none" }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
type RasterizationResult =
|
||||
| { readonly kind: "completed"; readonly value: unknown }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
export function safeHttpOrigin(url: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function selectFaviconCandidates(candidates: ReadonlyArray<string>): ReadonlyArray<string> {
|
||||
const selected: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
let inputUnits = 0;
|
||||
for (const candidate of candidates) {
|
||||
// Charge a minimum per entry so a large array of tiny malformed values is bounded too.
|
||||
inputUnits += Math.max(MIN_FAVICON_CANDIDATE_INPUT_UNITS, candidate.length);
|
||||
if (inputUnits > MAX_FAVICON_CANDIDATE_INPUT_UNITS) break;
|
||||
if (!isSupportedFaviconUrl(candidate) || seen.has(candidate)) continue;
|
||||
seen.add(candidate);
|
||||
selected.push(candidate);
|
||||
if (selected.length === MAX_FAVICON_CANDIDATES) break;
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
export async function captureFavicon(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageUrl: string;
|
||||
readonly candidates: ReadonlyArray<string>;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
if (!pageOrigin) return { kind: "none" };
|
||||
const captureTimeout = AbortSignal.timeout(FAVICON_CAPTURE_TIMEOUT_MS);
|
||||
const captureSignal = AbortSignal.any([input.signal, captureTimeout]);
|
||||
|
||||
for (const candidate of selectFaviconCandidates(input.candidates)) {
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
const captured = await captureCandidate({
|
||||
webContents: input.webContents,
|
||||
pageOrigin,
|
||||
candidate,
|
||||
signal: captureSignal,
|
||||
});
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
if (captured.kind === "captured" || captured.kind === "timed-out") return captured;
|
||||
}
|
||||
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
async function captureCandidate(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageOrigin: string;
|
||||
readonly candidate: string;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
try {
|
||||
const inline = parseInlineFavicon(input.candidate);
|
||||
if (inline) {
|
||||
return await normalizeFaviconBuffer(
|
||||
input.webContents,
|
||||
inline.mime,
|
||||
inline.buffer,
|
||||
input.signal,
|
||||
);
|
||||
}
|
||||
|
||||
const candidateOrigin = safeHttpOrigin(input.candidate);
|
||||
if (!candidateOrigin) return { kind: "none" };
|
||||
const response = await input.webContents.session.fetch(input.candidate, {
|
||||
credentials: candidateOrigin === input.pageOrigin ? "include" : "omit",
|
||||
redirect: "error",
|
||||
signal: input.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
return { kind: "none" };
|
||||
}
|
||||
const buffer = await readFaviconResponse(response, input.signal);
|
||||
if (!buffer || input.signal.aborted) return { kind: "none" };
|
||||
const mime = response.headers.get("content-type")?.split(";", 1)[0] ?? null;
|
||||
return await normalizeFaviconBuffer(input.webContents, mime, buffer, input.signal);
|
||||
} catch {
|
||||
return { kind: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
async function readFaviconResponse(
|
||||
response: Response,
|
||||
signal: AbortSignal,
|
||||
): Promise<Buffer | null> {
|
||||
const contentLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await response.body?.cancel();
|
||||
return null;
|
||||
}
|
||||
if (!response.body) {
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
return buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES ? buffer : null;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const cancelForAbort = () => {
|
||||
void reader.cancel(signal.reason).catch(() => undefined);
|
||||
};
|
||||
signal.addEventListener("abort", cancelForAbort, { once: true });
|
||||
if (signal.aborted) cancelForAbort();
|
||||
const chunks: Buffer[] = [];
|
||||
let byteLength = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const next = await reader.read();
|
||||
if (next.done) return Buffer.concat(chunks, byteLength);
|
||||
byteLength += next.value.byteLength;
|
||||
if (byteLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await reader.cancel();
|
||||
return null;
|
||||
}
|
||||
chunks.push(Buffer.from(next.value));
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener("abort", cancelForAbort);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function isSupportedFaviconUrl(url: string): boolean {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return false;
|
||||
if (/^data:/i.test(url)) return /^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(url);
|
||||
try {
|
||||
const protocol = new URL(url).protocol;
|
||||
return (
|
||||
(protocol === "http:" || protocol === "https:") && url.length <= MAX_FAVICON_HTTP_URL_LENGTH
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeInlineFaviconPayload(payload: string): Buffer | null {
|
||||
const decoded = Buffer.allocUnsafe(Buffer.byteLength(payload));
|
||||
let inputOffset = 0;
|
||||
let outputOffset = 0;
|
||||
while (inputOffset < payload.length) {
|
||||
const escapeOffset = payload.indexOf("%", inputOffset);
|
||||
const literalEnd = escapeOffset === -1 ? payload.length : escapeOffset;
|
||||
outputOffset += decoded.write(payload.slice(inputOffset, literalEnd), outputOffset, "utf8");
|
||||
if (escapeOffset === -1) break;
|
||||
const hex = payload.slice(escapeOffset + 1, escapeOffset + 3);
|
||||
if (!/^[0-9a-f]{2}$/i.test(hex)) return null;
|
||||
decoded[outputOffset] = Number.parseInt(hex, 16);
|
||||
outputOffset += 1;
|
||||
inputOffset = escapeOffset + 3;
|
||||
}
|
||||
return decoded.subarray(0, outputOffset);
|
||||
}
|
||||
|
||||
function parseInlineFavicon(
|
||||
url: string,
|
||||
): { readonly buffer: Buffer; readonly mime: string } | null {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return null;
|
||||
const match = /^data:(image\/[a-z0-9.+-]+)((?:;[^,]*)?),(.*)$/is.exec(url);
|
||||
if (!match) return null;
|
||||
const mime = match[1]?.toLowerCase();
|
||||
const parameters = match[2]
|
||||
?.split(";")
|
||||
.filter(Boolean)
|
||||
.map((parameter) => parameter.toLowerCase());
|
||||
const payload = match[3];
|
||||
if (!mime || !parameters || !payload) return null;
|
||||
const base64 = parameters.at(-1) === "base64";
|
||||
if (parameters.includes("base64") && !base64) return null;
|
||||
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
if (base64) {
|
||||
if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null;
|
||||
buffer = Buffer.from(payload, "base64");
|
||||
if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const decoded = decodeInlineFaviconPayload(payload);
|
||||
if (!decoded) return null;
|
||||
buffer = decoded;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
|
||||
? { buffer, mime }
|
||||
: null;
|
||||
}
|
||||
|
||||
interface ImageDimensions {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
function safeDimensions(dimensions: ImageDimensions | null): 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
|
||||
);
|
||||
}
|
||||
|
||||
function pngDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
|
||||
return null;
|
||||
}
|
||||
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
|
||||
}
|
||||
|
||||
function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
|
||||
let offset = startOffset;
|
||||
while (offset < buffer.byteLength) {
|
||||
const blockLength = buffer[offset]!;
|
||||
offset += 1;
|
||||
if (blockLength === 0) return offset;
|
||||
if (offset + blockLength > buffer.byteLength) return null;
|
||||
offset += blockLength;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function gifDimensions(buffer: Buffer): 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;
|
||||
const packed = buffer[10]!;
|
||||
let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
|
||||
if (offset > buffer.byteLength) return null;
|
||||
let width = logicalWidth;
|
||||
let height = logicalHeight;
|
||||
let frameCount = 0;
|
||||
let framePixels = 0;
|
||||
while (offset < buffer.byteLength) {
|
||||
const marker = buffer[offset];
|
||||
if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
|
||||
if (marker === 0x2c) {
|
||||
if (offset + 10 > buffer.byteLength) return null;
|
||||
const left = buffer.readUInt16LE(offset + 1);
|
||||
const top = buffer.readUInt16LE(offset + 3);
|
||||
const frameWidth = buffer.readUInt16LE(offset + 5);
|
||||
const frameHeight = buffer.readUInt16LE(offset + 7);
|
||||
if (frameWidth === 0 || frameHeight === 0) return null;
|
||||
framePixels += frameWidth * frameHeight;
|
||||
if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
|
||||
width = Math.max(width, left + frameWidth);
|
||||
height = Math.max(height, top + frameHeight);
|
||||
if (!safeDimensions({ width, height })) return null;
|
||||
const framePacked = buffer[offset + 9]!;
|
||||
offset += 10;
|
||||
if ((framePacked & 0x80) !== 0) {
|
||||
offset += 3 * 2 ** ((framePacked & 0x07) + 1);
|
||||
}
|
||||
if (offset >= buffer.byteLength) return null;
|
||||
const minimumCodeSize = buffer[offset]!;
|
||||
if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
|
||||
offset += 1;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
frameCount += 1;
|
||||
continue;
|
||||
}
|
||||
if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset + 2);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface JpegExifMetadata {
|
||||
readonly complete: boolean;
|
||||
readonly orientation: number | null;
|
||||
}
|
||||
|
||||
function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
|
||||
if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
|
||||
return null;
|
||||
}
|
||||
const metadataWithoutOrientation = (): JpegExifMetadata => ({
|
||||
complete: true,
|
||||
orientation: null,
|
||||
});
|
||||
if (segment.byteLength < 14) return metadataWithoutOrientation();
|
||||
const tiffOffset = 6;
|
||||
const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
|
||||
const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
|
||||
if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
|
||||
const readUInt16 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 2 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
|
||||
};
|
||||
const readUInt32 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 4 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
|
||||
};
|
||||
const relativeIfdOffset = readUInt32(tiffOffset + 4);
|
||||
if (relativeIfdOffset === null) return metadataWithoutOrientation();
|
||||
// Keep untrusted metadata parsing linear even when IFD pointers overlap.
|
||||
let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
|
||||
const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
|
||||
type IfdOrientation = number | null | typeof budgetExhausted;
|
||||
const subIfdOrientationByOffset = new Map<number, number | null>();
|
||||
const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
|
||||
if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
|
||||
return subIfdOrientationByOffset.get(ifdOffset) ?? null;
|
||||
}
|
||||
const entryCount = readUInt16(ifdOffset);
|
||||
if (entryCount === null) return null;
|
||||
let result: IfdOrientation = null;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (remainingIfdEntryVisits === 0) return budgetExhausted;
|
||||
remainingIfdEntryVisits -= 1;
|
||||
const entryOffset = ifdOffset + 2 + index * 12;
|
||||
if (entryOffset + 12 > segment.byteLength) break;
|
||||
const tag = readUInt16(entryOffset);
|
||||
const type = readUInt16(entryOffset + 2);
|
||||
const count = readUInt32(entryOffset + 4);
|
||||
if (tag === 0x0112 && type === 3 && count === 1) {
|
||||
const orientation = readUInt16(entryOffset + 8);
|
||||
if (orientation !== null && orientation >= 1 && orientation <= 8) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
} else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
|
||||
const relativeSubIfdOffset = readUInt32(entryOffset + 8);
|
||||
if (relativeSubIfdOffset !== null) {
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
|
||||
if (orientation === budgetExhausted) return budgetExhausted;
|
||||
if (orientation !== null) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
|
||||
return result;
|
||||
};
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
|
||||
return orientation === budgetExhausted
|
||||
? { complete: false, orientation: null }
|
||||
: { complete: true, orientation };
|
||||
}
|
||||
|
||||
function jpegDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
|
||||
const startOfFrameMarkers = new Set([
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
|
||||
]);
|
||||
let offset = 2;
|
||||
let dimensions: ImageDimensions | null = null;
|
||||
let exifMetadata: JpegExifMetadata | null = null;
|
||||
while (offset + 3 < buffer.byteLength) {
|
||||
if (buffer[offset] !== 0xff) {
|
||||
offset += 1;
|
||||
continue;
|
||||
}
|
||||
while (buffer[offset] === 0xff) offset += 1;
|
||||
const marker = buffer[offset];
|
||||
offset += 1;
|
||||
if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
|
||||
if (offset + 1 >= buffer.byteLength) return null;
|
||||
const length = buffer.readUInt16BE(offset);
|
||||
if (length < 2 || offset + length > buffer.byteLength) return null;
|
||||
if (marker === 0xe1 && exifMetadata === null) {
|
||||
exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
|
||||
}
|
||||
if (startOfFrameMarkers.has(marker)) {
|
||||
if (length < 7) return null;
|
||||
if (dimensions !== null) return null;
|
||||
dimensions = {
|
||||
height: buffer.readUInt16BE(offset + 3),
|
||||
width: buffer.readUInt16BE(offset + 5),
|
||||
};
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
if (!dimensions) return null;
|
||||
if (exifMetadata?.complete === false) return null;
|
||||
const orientation = exifMetadata?.orientation;
|
||||
return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
|
||||
? { width: dimensions.height, height: dimensions.width }
|
||||
: dimensions;
|
||||
}
|
||||
|
||||
function webpDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 30 ||
|
||||
buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
|
||||
buffer.subarray(8, 12).toString("ascii") !== "WEBP"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const kind = buffer.subarray(12, 16).toString("ascii");
|
||||
if (kind === "VP8X") {
|
||||
return {
|
||||
width: 1 + buffer.readUIntLE(24, 3),
|
||||
height: 1 + buffer.readUIntLE(27, 3),
|
||||
};
|
||||
}
|
||||
if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(26) & 0x3fff,
|
||||
height: buffer.readUInt16LE(28) & 0x3fff,
|
||||
};
|
||||
}
|
||||
if (kind === "VP8L" && buffer[20] === 0x2f) {
|
||||
return {
|
||||
width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
|
||||
height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function dibDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 12) return null;
|
||||
const headerSize = buffer.readUInt32LE(0);
|
||||
if (headerSize === 12) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(4),
|
||||
height: buffer.readUInt16LE(6),
|
||||
};
|
||||
}
|
||||
if (headerSize < 40 || buffer.byteLength < 12) return null;
|
||||
return {
|
||||
width: Math.abs(buffer.readInt32LE(4)),
|
||||
height: Math.abs(buffer.readInt32LE(8)),
|
||||
};
|
||||
}
|
||||
|
||||
function icoDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 22 ||
|
||||
buffer.readUInt16LE(0) !== 0 ||
|
||||
(buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const count = buffer.readUInt16LE(4);
|
||||
if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
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;
|
||||
const byteLength = buffer.readUInt32LE(offset + 8);
|
||||
const imageOffset = buffer.readUInt32LE(offset + 12);
|
||||
if (
|
||||
byteLength === 0 ||
|
||||
imageOffset < 6 + count * 16 ||
|
||||
imageOffset > buffer.byteLength ||
|
||||
byteLength > buffer.byteLength - imageOffset
|
||||
)
|
||||
return null;
|
||||
const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
|
||||
const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
|
||||
if (!safeDimensions(embeddedDimensions)) return null;
|
||||
}
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function sourceDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
return (
|
||||
pngDimensions(buffer) ??
|
||||
gifDimensions(buffer) ??
|
||||
jpegDimensions(buffer) ??
|
||||
webpDimensions(buffer) ??
|
||||
icoDimensions(buffer)
|
||||
);
|
||||
}
|
||||
|
||||
async function normalizeFaviconBuffer(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
signal: AbortSignal,
|
||||
): Promise<FaviconCaptureResult> {
|
||||
const declaredMime = mime?.trim().toLowerCase() || null;
|
||||
const normalizedMime =
|
||||
declaredMime === "application/x-icon"
|
||||
? "image/x-icon"
|
||||
: declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
|
||||
? null
|
||||
: declaredMime;
|
||||
const dimensions = sourceDimensions(buffer);
|
||||
if (
|
||||
(normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
|
||||
normalizedMime === "image/svg+xml" ||
|
||||
buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
|
||||
!safeDimensions(dimensions)
|
||||
) {
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
const rasterized = await rasterizeFavicon(
|
||||
webContents,
|
||||
normalizedMime,
|
||||
buffer,
|
||||
dimensions,
|
||||
signal,
|
||||
);
|
||||
if (rasterized.kind === "timed-out") return rasterized;
|
||||
return typeof rasterized.value === "string" &&
|
||||
rasterized.value.startsWith("data:image/png;base64,") &&
|
||||
rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
|
||||
? { kind: "captured", dataUrl: rasterized.value }
|
||||
: { kind: "none" };
|
||||
}
|
||||
|
||||
async function rasterizeFavicon(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
dimensions: ImageDimensions,
|
||||
signal: AbortSignal,
|
||||
): Promise<RasterizationResult> {
|
||||
const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
|
||||
rasterizationGates.set(webContents, gate);
|
||||
const generation = ++gate.generation;
|
||||
const previousLaunchAllowed = gate.launchAllowed;
|
||||
if (previousLaunchAllowed) {
|
||||
await waitForRasterLaunch(previousLaunchAllowed, signal);
|
||||
}
|
||||
if (signal.aborted || generation !== gate.generation) {
|
||||
return { kind: "completed", value: null };
|
||||
}
|
||||
|
||||
const payload = buffer.toString("base64");
|
||||
const blobType = mime ?? "";
|
||||
const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
|
||||
const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
|
||||
const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
|
||||
const drawX = (32 - decodeWidth) / 2;
|
||||
const drawY = (32 - decodeHeight) / 2;
|
||||
const code = `
|
||||
(() => {
|
||||
const rasterize = async () => {
|
||||
try {
|
||||
const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
|
||||
const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
|
||||
resizeWidth: ${decodeWidth},
|
||||
resizeHeight: ${decodeHeight},
|
||||
resizeQuality: "high",
|
||||
});
|
||||
try {
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
|
||||
return null;
|
||||
}
|
||||
const canvas = new OffscreenCanvas(32, 32);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return null;
|
||||
context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
|
||||
const blob = await canvas.convertToBlob({ type: "image/png" });
|
||||
const output = new Uint8Array(await blob.arrayBuffer());
|
||||
let binary = "";
|
||||
for (const byte of output) binary += String.fromCharCode(byte);
|
||||
return "data:image/png;base64," + btoa(binary);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return rasterize();
|
||||
})()
|
||||
`;
|
||||
|
||||
const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
|
||||
{ code },
|
||||
]);
|
||||
|
||||
const result = new Promise<RasterizationResult>((resolve, reject) => {
|
||||
// Electron cannot cancel isolated-world execution. This timeout ends only
|
||||
// the logical attempt; renderer work may finish after a newer attempt starts.
|
||||
const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
|
||||
let settled = false;
|
||||
const finish = (complete: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
timeout.removeEventListener("abort", onTimeout);
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
complete();
|
||||
};
|
||||
const onTimeout = () => {
|
||||
finish(() => resolve({ kind: "timed-out" }));
|
||||
};
|
||||
const onAbort = () => {
|
||||
finish(() => resolve({ kind: "completed", value: null }));
|
||||
};
|
||||
timeout.addEventListener("abort", onTimeout, { once: true });
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
void execution.then(
|
||||
(value) => {
|
||||
finish(() => resolve({ kind: "completed", value }));
|
||||
},
|
||||
(cause: unknown) => {
|
||||
finish(() => reject(cause));
|
||||
},
|
||||
);
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
// The logical timeout does not cancel Electron's renderer work. Keep the
|
||||
// gate closed until that physical execution actually settles.
|
||||
const launchAllowed = execution.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
gate.launchAllowed = launchAllowed;
|
||||
void launchAllowed.then(() => {
|
||||
if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
|
||||
});
|
||||
return await result;
|
||||
}
|
||||
@@ -186,6 +186,102 @@ const makeTestPreviewWebContents = (
|
||||
capturePage,
|
||||
}) as never;
|
||||
|
||||
const TEST_FAVICON = "data:image/png;base64,cG5n";
|
||||
|
||||
const makeSourcePng = (width = 1, height = 1): Buffer => {
|
||||
const buffer = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(buffer);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
};
|
||||
|
||||
const makeFaviconWebContents = (options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly id?: number;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
readonly url?: string;
|
||||
}) => {
|
||||
const sourcePng = makeSourcePng();
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
let currentUrl = options?.url ?? "http://localhost:3200/";
|
||||
let destroyed = false;
|
||||
let loading = false;
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(sourcePng), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON,
|
||||
);
|
||||
const reload = vi.fn();
|
||||
const loadURL = vi.fn(async (url: string) => {
|
||||
currentUrl = url;
|
||||
});
|
||||
const off = vi.fn();
|
||||
const debuggerOff = vi.fn();
|
||||
const webContents = {
|
||||
id: options?.id ?? 42,
|
||||
isDestroyed: () => destroyed,
|
||||
getType: () => "webview",
|
||||
getURL: () => currentUrl,
|
||||
getTitle: () => "Preview",
|
||||
isLoading: () => loading,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
reload,
|
||||
reloadIgnoringCache: vi.fn(),
|
||||
loadURL,
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off,
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
session: { fetch },
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: debuggerOff,
|
||||
},
|
||||
};
|
||||
return {
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
debuggerOff,
|
||||
listeners,
|
||||
loadURL,
|
||||
off,
|
||||
reload,
|
||||
setDestroyed: (value: boolean) => {
|
||||
destroyed = value;
|
||||
},
|
||||
setLoading: (value: boolean) => {
|
||||
loading = value;
|
||||
},
|
||||
setUrl: (url: string) => {
|
||||
currentUrl = url;
|
||||
},
|
||||
webContents: webContents as never,
|
||||
};
|
||||
};
|
||||
|
||||
const settle = function* (until: () => boolean) {
|
||||
for (let attempt = 0; attempt < 30 && !until(); attempt++) {
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
};
|
||||
|
||||
const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
|
||||
const listeners = new Map<string, () => void>();
|
||||
const send = vi.fn();
|
||||
@@ -257,6 +353,32 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("rejects a destroyed webview during registration", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const getType = vi.fn(() => "webview" as const);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => true,
|
||||
getType,
|
||||
} as never);
|
||||
yield* manager.createTab("tab_destroyed_registration");
|
||||
|
||||
const exit = yield* Effect.exit(manager.registerWebview("tab_destroyed_registration", 42));
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
|
||||
_tag: "PreviewWebContentsNotFoundError",
|
||||
tabId: "tab_destroyed_registration",
|
||||
webContentsId: 42,
|
||||
});
|
||||
}
|
||||
expect(getType).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
@@ -375,6 +497,488 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("detaches a destroyed webview instead of navigating it", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_destroyed_navigation");
|
||||
yield* manager.registerWebview("tab_destroyed_navigation", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_navigation", "dark");
|
||||
preview.setDestroyed(true);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_navigation", "https://example.com/");
|
||||
|
||||
expect(preview.loadURL).not.toHaveBeenCalled();
|
||||
expect(preview.reload).not.toHaveBeenCalled();
|
||||
expect(preview.off).toHaveBeenCalled();
|
||||
expect(preview.debuggerOff).toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: null,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const previous = makeFaviconWebContents();
|
||||
const replacement = makeFaviconWebContents({ url: "https://example.com/" });
|
||||
let current = previous.webContents;
|
||||
let startReplacementRegistration: () => void = () => void 0;
|
||||
const replacementReady = new Promise<void>((resolve) => {
|
||||
startReplacementRegistration = resolve;
|
||||
});
|
||||
fromId.mockImplementation(() => current);
|
||||
yield* manager.createTab("tab_destroyed_replacement_race");
|
||||
yield* manager.registerWebview("tab_destroyed_replacement_race", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_replacement_race", "dark");
|
||||
const replacementRegistration = yield* Effect.promise(() => replacementReady).pipe(
|
||||
Effect.flatMap(() => manager.registerWebview("tab_destroyed_replacement_race", 42)),
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
previous.setDestroyed(true);
|
||||
previous.debuggerOff.mockImplementationOnce(() => {
|
||||
current = replacement.webContents;
|
||||
startReplacementRegistration();
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_replacement_race", "https://example.com/");
|
||||
const registrationExit = yield* Fiber.await(replacementRegistration);
|
||||
|
||||
expect(Exit.isSuccess(registrationExit)).toBe(true);
|
||||
expect(previous.off).toHaveBeenCalled();
|
||||
expect(replacement.off).not.toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: 42,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("publishes a canonical favicon origin while the page is loading", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents({
|
||||
url: `http://localhost:3200/${"x".repeat(3_000)}`,
|
||||
});
|
||||
preview.setLoading(true);
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_loading");
|
||||
yield* manager.registerWebview("tab_favicon_loading", 42);
|
||||
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(states.at(-1)?.favicon).toMatchObject({
|
||||
dataUrl: TEST_FAVICON,
|
||||
pageUrl: "http://localhost:3200",
|
||||
});
|
||||
expect(states.at(-1)?.favicon?.capturedAt).toEqual(expect.any(Number));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("shares an identical in-flight event and lets a changed event win", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFirst!: (response: Response) => void;
|
||||
const firstResponse = new Promise<Response>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
});
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: (url) =>
|
||||
url.endsWith("first.png")
|
||||
? firstResponse
|
||||
: Promise.resolve(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_latest");
|
||||
yield* manager.registerWebview("tab_favicon_latest", 42);
|
||||
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
resolveFirst(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(preview.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("allows an identical retry after an undecodable capture", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let rasterizations = 0;
|
||||
const preview = makeFaviconWebContents({
|
||||
rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_retry");
|
||||
yield* manager.registerWebview("tab_favicon_retry", 42);
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => rasterizations === 1);
|
||||
yield* settle(() => false);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(rasterizations).toBe(2);
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not publish a capture invalidated by navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_navigation");
|
||||
yield* manager.registerWebview("tab_favicon_navigation", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
preview.listeners.get("did-start-navigation")?.({
|
||||
isMainFrame: true,
|
||||
isSameDocument: false,
|
||||
} as never);
|
||||
preview.setUrl("https://example.com/");
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.some((state) => state.favicon !== undefined)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("retains a favicon when reloading the current URL without a new event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reload");
|
||||
yield* manager.registerWebview("tab_favicon_reload", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.navigate("tab_favicon_reload", "http://localhost:3200/");
|
||||
|
||||
expect(preview.reload).toHaveBeenCalledOnce();
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon after a confirmed cross-origin navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_origin");
|
||||
yield* manager.registerWebview("tab_favicon_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("https://example.com/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect(
|
||||
"retains the previous document icon across a failed cross-origin navigation",
|
||||
() =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_failed_origin");
|
||||
yield* manager.registerWebview("tab_favicon_failed_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.listeners.get("did-fail-load")?.(
|
||||
{} as never,
|
||||
-105 as never,
|
||||
"Name not resolved" as never,
|
||||
"https://unreachable.example/" as never,
|
||||
true as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "LoadFailed");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not resurrect an icon after a confirmed about:blank document", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_blank");
|
||||
yield* manager.registerWebview("tab_favicon_blank", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("about:blank");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Idle");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
|
||||
preview.setUrl("http://localhost:3200/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon when a replacement webview attaches", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) => {
|
||||
if (id === 42) return initial.webContents;
|
||||
if (id === 43) return replacement.webContents;
|
||||
return null;
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_replace");
|
||||
yield* manager.registerWebview("tab_favicon_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_replace", 43);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("ignores an old capture that completes after webview replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const initial = makeFaviconWebContents({
|
||||
id: 42,
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) =>
|
||||
id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null,
|
||||
);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_late_replace");
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => initial.fetch.mock.calls.length === 1);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 43);
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(
|
||||
states.some((state) => state.webContentsId === 43 && state.favicon !== undefined),
|
||||
).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("treats a reused WebContents id as a new attachment", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 42 });
|
||||
let active = initial.webContents;
|
||||
fromId.mockImplementation(() => active);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reused_id");
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
active = replacement.webContents;
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
expect(initial.off).toHaveBeenCalled();
|
||||
expect(replacement.listeners.has("page-favicon-updated")).toBe(true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("preserves a favicon when the active attachment registers again", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reregister");
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewFavicon,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -85,6 +87,7 @@ export interface PreviewTabState {
|
||||
pictureInPicture: boolean;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
favicon?: DesktopPreviewFavicon;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -346,7 +349,10 @@ type PreviewInputSignal =
|
||||
| { readonly kind: "key"; readonly key: string; readonly code: string };
|
||||
|
||||
interface ManagedListeners {
|
||||
readonly attachmentId: symbol;
|
||||
readonly cancelFaviconCapture: () => void;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly webContents: Electron.WebContents;
|
||||
}
|
||||
|
||||
type FrameCaptureConsumer = "picture-in-picture" | "recording";
|
||||
@@ -613,6 +619,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const emitIfCurrent = Effect.fn("PreviewManager.emitIfCurrent")(function* (
|
||||
tabId: string,
|
||||
state: PreviewTabState,
|
||||
) {
|
||||
if ((yield* SynchronizedRef.get(tabsRef)).get(tabId) === state) {
|
||||
yield* emit(tabId, state);
|
||||
}
|
||||
});
|
||||
|
||||
const update = Effect.fn("PreviewManager.update")(function* (
|
||||
tabId: string,
|
||||
patch: Partial<PreviewTabState>,
|
||||
@@ -1204,7 +1219,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
copy.delete(webContentsId);
|
||||
}),
|
||||
]);
|
||||
if (managed) yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
if (managed) {
|
||||
managed.cancelFaviconCapture();
|
||||
yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const isAppShortcut = (input: Electron.Input): boolean =>
|
||||
@@ -1268,8 +1286,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const attachmentId = Symbol();
|
||||
let documentId = 0;
|
||||
let nextRequestId = 0;
|
||||
let activeCapture: {
|
||||
readonly controller: AbortController;
|
||||
readonly documentId: number;
|
||||
readonly eventKey: string;
|
||||
readonly requestId: number;
|
||||
} | null = null;
|
||||
const cancelFaviconCapture = () => {
|
||||
documentId += 1;
|
||||
activeCapture?.controller.abort();
|
||||
activeCapture = null;
|
||||
};
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
confirmedNavigation = false,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
const zoomFactor = yield* attempt(
|
||||
@@ -1282,7 +1315,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
if (!current || current.webContentsId !== wc.id || webContents.fromId(wc.id) !== wc) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
@@ -1292,8 +1327,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const clearFavicon =
|
||||
confirmedNavigation &&
|
||||
current.favicon !== undefined &&
|
||||
safeHttpOrigin(current.favicon.pageUrl) !==
|
||||
safeHttpOrigin(navStatus.kind === "Idle" ? wc.getURL() : navStatus.url);
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
...(clearFavicon ? currentWithoutFavicon : current),
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
@@ -1307,10 +1348,109 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const syncNavigation = () => runFork(syncState(false, true));
|
||||
const syncInPageNavigation = () => runFork(syncState(false));
|
||||
const navigationStarted = (
|
||||
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
|
||||
) => {
|
||||
if (event.isMainFrame && !event.isSameDocument) cancelFaviconCapture();
|
||||
};
|
||||
const publishFavicon = Effect.fn("PreviewManager.publishFavicon")(function* (input: {
|
||||
readonly captureDocumentId: number;
|
||||
readonly dataUrl: string;
|
||||
readonly pageUrl: string;
|
||||
readonly requestId: number;
|
||||
}) {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
const managed = (yield* Ref.get(attachedRef)).get(wc.id);
|
||||
if (
|
||||
!pageOrigin ||
|
||||
wc.isDestroyed() ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
managed?.attachmentId !== attachmentId ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId ||
|
||||
safeHttpOrigin(wc.getURL()) !== pageOrigin
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const capturedAt = yield* currentMillis;
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (
|
||||
!current ||
|
||||
current.webContentsId !== wc.id ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId
|
||||
) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
favicon: { dataUrl: input.dataUrl, pageUrl: pageOrigin, capturedAt },
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
});
|
||||
const faviconUpdated = (_event: Event, rawCandidates: ReadonlyArray<string>): void => {
|
||||
const pageUrl = wc.getURL();
|
||||
if (!safeHttpOrigin(pageUrl)) return;
|
||||
const candidates = selectFaviconCandidates(rawCandidates);
|
||||
if (candidates.length === 0) return;
|
||||
const eventKey = JSON.stringify([pageUrl, ...candidates]);
|
||||
if (activeCapture?.eventKey === eventKey) return;
|
||||
activeCapture?.controller.abort();
|
||||
const captureDocumentId = documentId;
|
||||
const requestId = ++nextRequestId;
|
||||
const controller = new AbortController();
|
||||
activeCapture = { controller, documentId: captureDocumentId, eventKey, requestId };
|
||||
runFork(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
captureFavicon({ webContents: wc, pageUrl, candidates, signal: controller.signal }),
|
||||
catch: (cause) =>
|
||||
new PreviewOperationError({
|
||||
operation: "captureFavicon",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.kind === "captured"
|
||||
? publishFavicon({
|
||||
captureDocumentId,
|
||||
dataUrl: result.dataUrl,
|
||||
pageUrl,
|
||||
requestId,
|
||||
})
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
controller.signal.aborted
|
||||
? Effect.void
|
||||
: Effect.logDebug("Favicon capture failed.", { error, tabId, webContentsId: wc.id }),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (activeCapture?.requestId === requestId) activeCapture = null;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
@@ -1387,9 +1527,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
cancelFaviconCapture();
|
||||
wc.off("did-start-navigation", navigationStarted);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("page-favicon-updated", faviconUpdated as never);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
wc.off("did-fail-load", failed as never);
|
||||
@@ -1399,9 +1542,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-start-navigation", navigationStarted);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("page-favicon-updated", faviconUpdated as never);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
wc.on("did-fail-load", failed as never);
|
||||
@@ -1418,7 +1563,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* Ref.update(attachedRef, (attached) =>
|
||||
replaceMap(attached, (copy) => {
|
||||
copy.set(wc.id, { scope });
|
||||
copy.set(wc.id, { attachmentId, cancelFaviconCapture, scope, webContents: wc });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1561,6 +1706,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const mainWindow = yield* Ref.get(mainWindowRef);
|
||||
if (
|
||||
!wc ||
|
||||
wc.isDestroyed() ||
|
||||
wc.getType() !== "webview" ||
|
||||
(Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents)
|
||||
) {
|
||||
@@ -1568,7 +1714,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const currentAttachment = attached.get(webContentsId);
|
||||
if (tab.webContentsId === webContentsId && currentAttachment?.webContents === wc) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
@@ -1580,7 +1727,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return;
|
||||
}
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
tab.webContentsId != null &&
|
||||
(tab.webContentsId !== webContentsId || currentAttachment?.webContents !== wc)
|
||||
? tab.webContentsId
|
||||
: null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
@@ -1627,8 +1777,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
] as const;
|
||||
}
|
||||
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = {
|
||||
...current,
|
||||
...currentWithoutFavicon,
|
||||
webContentsId,
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
@@ -1707,6 +1858,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
pictureInPicture: current?.pictureInPicture ?? false,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
...(current?.favicon ? { favicon: current.favicon } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
@@ -1718,17 +1870,48 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* emit(tabId, pending);
|
||||
if (pending.webContentsId == null) return;
|
||||
const wc = webContents.fromId(pending.webContentsId);
|
||||
if (!wc) {
|
||||
const detached = { ...pending, webContentsId: null };
|
||||
yield* SynchronizedRef.update(tabsRef, (tabs) =>
|
||||
tabs.get(tabId)?.webContentsId !== pending.webContentsId
|
||||
? tabs
|
||||
: replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, detached);
|
||||
}),
|
||||
const webContentsId = pending.webContentsId;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) {
|
||||
const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
yield* withTabLifecycleLock(
|
||||
tabId,
|
||||
Effect.gen(function* () {
|
||||
const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
const currentWebContents = webContents.fromId(webContentsId);
|
||||
if (
|
||||
currentTab?.webContentsId !== webContentsId ||
|
||||
currentAttachment !== expectedAttachment ||
|
||||
(currentWebContents && !currentWebContents.isDestroyed())
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(webContentsId),
|
||||
detachListeners(webContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (current?.webContentsId !== webContentsId) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null };
|
||||
return [
|
||||
Option.some(next),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value);
|
||||
}),
|
||||
);
|
||||
yield* emit(tabId, detached);
|
||||
return;
|
||||
}
|
||||
if (wc.getURL() === url) {
|
||||
|
||||
@@ -180,4 +180,135 @@ describe("browser target resolver", () => {
|
||||
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
|
||||
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), " ")).toBe(" ");
|
||||
});
|
||||
|
||||
it("classifies exact private IPv4 and IPv6 boundaries", async () => {
|
||||
const { isPrivateNetworkHost } = await import("./browserTargetResolver");
|
||||
const privateHosts = [
|
||||
"0.0.0.0",
|
||||
"10.0.0.0",
|
||||
"10.255.255.255",
|
||||
"100.64.0.0",
|
||||
"100.127.255.255",
|
||||
"127.0.0.0",
|
||||
"127.255.255.255",
|
||||
"169.254.0.0",
|
||||
"169.254.255.255",
|
||||
"172.16.0.0",
|
||||
"172.31.255.255",
|
||||
"192.168.0.0",
|
||||
"192.168.255.255",
|
||||
"198.18.0.0",
|
||||
"198.19.255.255",
|
||||
"fc00::",
|
||||
"fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
"fe80::",
|
||||
"febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
"::ffff:192.168.1.1",
|
||||
"localhost.",
|
||||
"localhost..",
|
||||
"devbox.",
|
||||
"devbox..",
|
||||
"printer.local.",
|
||||
"printer.local..",
|
||||
"printer.home.arpa.",
|
||||
"printer.home.arpa..",
|
||||
"devbox.example.ts.net.",
|
||||
"devbox.example.ts.net..",
|
||||
];
|
||||
const publicHosts = [
|
||||
"1.0.0.0",
|
||||
"100.63.255.255",
|
||||
"100.128.0.0",
|
||||
"169.253.255.255",
|
||||
"169.255.0.0",
|
||||
"172.15.255.255",
|
||||
"172.32.0.0",
|
||||
"192.167.255.255",
|
||||
"192.169.0.0",
|
||||
"198.17.255.255",
|
||||
"198.20.0.0",
|
||||
"fbff:ffff::",
|
||||
"fec0::",
|
||||
"2001:4860:4860::8888",
|
||||
"::ffff:8.8.8.8",
|
||||
"example.com.",
|
||||
];
|
||||
expect(privateHosts.filter((host) => !isPrivateNetworkHost(host))).toEqual([]);
|
||||
expect(publicHosts.filter(isPrivateNetworkHost)).toEqual([]);
|
||||
});
|
||||
|
||||
it("allows only globally routable hosts to reach a public favicon provider", async () => {
|
||||
const { isPublicFaviconHost } = await import("./browserTargetResolver");
|
||||
const nonPublic = [
|
||||
"192.0.0.0",
|
||||
"192.0.0.255",
|
||||
"192.0.2.0",
|
||||
"192.0.2.255",
|
||||
"192.88.99.0",
|
||||
"192.88.99.255",
|
||||
"198.51.100.0",
|
||||
"198.51.100.255",
|
||||
"203.0.113.0",
|
||||
"203.0.113.255",
|
||||
"224.0.0.0",
|
||||
"255.255.255.255",
|
||||
"::2",
|
||||
"100::",
|
||||
"100::ffff:ffff:ffff:ffff",
|
||||
"100:0:0:1::",
|
||||
"100:0:0:1:ffff:ffff:ffff:ffff",
|
||||
"64:ff9b:1::1",
|
||||
"64:ff9b::a00:1",
|
||||
"64:ff9b::7f00:1",
|
||||
"64:ff9b::c0a8:101",
|
||||
"64:ff9b::c000:201",
|
||||
"2001:5::1",
|
||||
"2001:2::",
|
||||
"2001:2:0:ffff:ffff:ffff:ffff:ffff",
|
||||
"2001:db8::",
|
||||
"2001:db8:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
"3fff::",
|
||||
"3fff:fff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
"5f00::1",
|
||||
"fec0::",
|
||||
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||
"::ffff:192.0.2.1",
|
||||
"app.test",
|
||||
"app.test..",
|
||||
"printer.local..",
|
||||
"printer.home.arpa..",
|
||||
"devbox.example.ts.net..",
|
||||
"127.0.0.1..",
|
||||
"127.1..",
|
||||
"10.1..",
|
||||
"172.16.1..",
|
||||
"192.168.1..",
|
||||
"service.internal",
|
||||
"hidden.onion",
|
||||
];
|
||||
const publicHosts = [
|
||||
"191.255.255.255",
|
||||
"192.0.1.255",
|
||||
"192.0.3.0",
|
||||
"198.51.99.255",
|
||||
"198.51.101.0",
|
||||
"203.0.112.255",
|
||||
"203.0.114.0",
|
||||
"223.255.255.255",
|
||||
"1.1.1.1",
|
||||
"2001:4860:4860::8888",
|
||||
"2606:4700:4700::1111",
|
||||
"64:ff9b::808:808",
|
||||
"2001:1::1",
|
||||
"2001:3::1",
|
||||
"2001:4:112::1",
|
||||
"2001:20::1",
|
||||
"2001:30::1",
|
||||
"::ffff:8.8.8.8",
|
||||
"example.com",
|
||||
"example.com.",
|
||||
];
|
||||
expect(nonPublic.filter(isPublicFaviconHost)).toEqual([]);
|
||||
expect(publicHosts.filter((host) => !isPublicFaviconHost(host))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,10 @@ import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import { readPreparedConnection } from "~/state/session";
|
||||
|
||||
export const normalizeHostname = (host: string): string =>
|
||||
host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
host
|
||||
.toLowerCase()
|
||||
.replace(/^\[|\]$/g, "")
|
||||
.replace(/\.+$/u, "");
|
||||
|
||||
const parseIpv4Address = (host: string): readonly number[] | null => {
|
||||
const parts = normalizeHostname(host).split(".").map(Number);
|
||||
@@ -18,28 +21,91 @@ const parseIpv4Address = (host: string): readonly number[] | null => {
|
||||
: null;
|
||||
};
|
||||
|
||||
const parseIpv4MappedIpv6Address = (host: string): readonly number[] | null => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (!normalized.startsWith("::ffff:")) return null;
|
||||
const suffix = normalized.slice("::ffff:".length);
|
||||
const dotted = parseIpv4Address(suffix);
|
||||
if (dotted) return dotted;
|
||||
const hextets = suffix.split(":");
|
||||
if (hextets.length !== 2 || hextets.some((part) => !/^[\da-f]{1,4}$/u.test(part))) return null;
|
||||
const high = Number.parseInt(hextets[0]!, 16);
|
||||
const low = Number.parseInt(hextets[1]!, 16);
|
||||
return [high >>> 8, high & 0xff, low >>> 8, low & 0xff];
|
||||
};
|
||||
|
||||
const parseIpv6Address = (host: string): readonly number[] | null => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (!normalized.includes(":")) return null;
|
||||
const halves = normalized.split("::");
|
||||
if (halves.length > 2) return null;
|
||||
const head = halves[0] ? halves[0].split(":") : [];
|
||||
const tail = halves[1] ? halves[1].split(":") : [];
|
||||
if ([...head, ...tail].some((part) => !/^[\da-f]{1,4}$/u.test(part))) return null;
|
||||
const missing = 8 - head.length - tail.length;
|
||||
if ((halves.length === 1 && missing !== 0) || (halves.length === 2 && missing < 1)) return null;
|
||||
return [...head, ...Array.from({ length: missing }, () => "0"), ...tail].map((part) =>
|
||||
Number.parseInt(part, 16),
|
||||
);
|
||||
};
|
||||
|
||||
const ipv6PrefixMatches = (
|
||||
address: readonly number[],
|
||||
prefix: readonly number[],
|
||||
prefixLength: number,
|
||||
): boolean => {
|
||||
const fullHextets = Math.floor(prefixLength / 16);
|
||||
if (address.slice(0, fullHextets).some((part, index) => part !== prefix[index])) return false;
|
||||
const remainingBits = prefixLength % 16;
|
||||
if (remainingBits === 0) return true;
|
||||
const mask = (0xffff << (16 - remainingBits)) & 0xffff;
|
||||
return (address[fullHextets]! & mask) === (prefix[fullHextets]! & mask);
|
||||
};
|
||||
|
||||
const isPrivateIpv4Address = (parts: readonly number[]): boolean =>
|
||||
parts[0] === 0 ||
|
||||
parts[0] === 10 ||
|
||||
parts[0] === 127 ||
|
||||
(parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
|
||||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
|
||||
(parts[0] === 192 && parts[1] === 168) ||
|
||||
(parts[0] === 169 && parts[1] === 254) ||
|
||||
(parts[0] === 198 && parts[1]! >= 18 && parts[1]! <= 19);
|
||||
|
||||
const isSpecialPurposeIpv4Address = (parts: readonly number[]): boolean =>
|
||||
isPrivateIpv4Address(parts) ||
|
||||
parts[0]! >= 224 ||
|
||||
// Deliberately suppress the whole protocol-assignment block. IANA marks
|
||||
// .9 and .10 globally reachable, but privacy-safe false negatives are
|
||||
// preferable to disclosing another special-purpose address by mistake.
|
||||
(parts[0] === 192 && parts[1] === 0 && parts[2] === 0) ||
|
||||
(parts[0] === 192 && parts[1] === 0 && parts[2] === 2) ||
|
||||
(parts[0] === 192 && parts[1] === 88 && parts[2] === 99) ||
|
||||
(parts[0] === 198 && parts[1] === 51 && parts[2] === 100) ||
|
||||
(parts[0] === 203 && parts[1] === 0 && parts[2] === 113);
|
||||
|
||||
export const isLocalLoopbackHost = (host: string): boolean => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (normalized === "localhost" || normalized === "::1") return true;
|
||||
return parseIpv4Address(normalized)?.[0] === 127;
|
||||
};
|
||||
|
||||
const isPrivateNetworkHost = (host: string): boolean => {
|
||||
export const isPrivateNetworkHost = (host: string): boolean => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (isLocalLoopbackHost(normalized) || normalized.endsWith(".local")) {
|
||||
if (
|
||||
normalized === "::" ||
|
||||
isLocalLoopbackHost(normalized) ||
|
||||
normalized.endsWith(".localhost") ||
|
||||
normalized.endsWith(".local") ||
|
||||
normalized === "home.arpa" ||
|
||||
normalized.endsWith(".home.arpa") ||
|
||||
(!normalized.includes(".") && !normalized.includes(":"))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (normalized.endsWith(".ts.net")) return true;
|
||||
const parts = parseIpv4Address(normalized);
|
||||
if (parts) {
|
||||
return (
|
||||
parts[0] === 10 ||
|
||||
(parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
|
||||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
|
||||
(parts[0] === 192 && parts[1] === 168) ||
|
||||
(parts[0] === 169 && parts[1] === 254)
|
||||
);
|
||||
}
|
||||
const parts = parseIpv4Address(normalized) ?? parseIpv4MappedIpv6Address(normalized);
|
||||
if (parts) return isPrivateIpv4Address(parts);
|
||||
const firstIpv6Token = normalized.split(":", 1)[0] ?? "";
|
||||
if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false;
|
||||
const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16);
|
||||
@@ -49,6 +115,48 @@ const isPrivateNetworkHost = (host: string): boolean => {
|
||||
);
|
||||
};
|
||||
|
||||
/** Whether a hostname is eligible to be disclosed to a public favicon provider. */
|
||||
export const isPublicFaviconHost = (host: string): boolean => {
|
||||
// A single trailing dot is a valid absolute DNS name. Repeated trailing
|
||||
// dots are malformed and can conceal legacy numeric forms such as 127.1.
|
||||
if (host.endsWith("..")) return false;
|
||||
const normalized = normalizeHostname(host);
|
||||
if (isPrivateNetworkHost(normalized)) return false;
|
||||
if (
|
||||
[".alt", ".example", ".internal", ".invalid", ".onion", ".test"].some(
|
||||
(suffix) => normalized === suffix.slice(1) || normalized.endsWith(suffix),
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const ipv4 = parseIpv4Address(normalized) ?? parseIpv4MappedIpv6Address(normalized);
|
||||
if (ipv4) return !isSpecialPurposeIpv4Address(ipv4);
|
||||
if (!normalized.includes(":")) return true;
|
||||
const ipv6 = parseIpv6Address(normalized);
|
||||
if (!ipv6) return false;
|
||||
if (ipv6PrefixMatches(ipv6, [0x0064, 0xff9b, 0, 0, 0, 0, 0, 0], 96)) {
|
||||
const embeddedIpv4 = [ipv6[6]! >>> 8, ipv6[6]! & 0xff, ipv6[7]! >>> 8, ipv6[7]! & 0xff];
|
||||
return !isSpecialPurposeIpv4Address(embeddedIpv4);
|
||||
}
|
||||
const first = ipv6[0]!;
|
||||
if ((first & 0xe000) !== 0x2000) return false;
|
||||
if (ipv6PrefixMatches(ipv6, [0x2001, 0, 0, 0, 0, 0, 0, 0], 23)) {
|
||||
const publicProtocolAssignment =
|
||||
(ipv6[1] === 1 &&
|
||||
ipv6.slice(2, 7).every((part) => part === 0) &&
|
||||
[1, 2, 3].includes(ipv6[7]!)) ||
|
||||
ipv6PrefixMatches(ipv6, [0x2001, 3, 0, 0, 0, 0, 0, 0], 32) ||
|
||||
ipv6PrefixMatches(ipv6, [0x2001, 4, 0x0112, 0, 0, 0, 0, 0], 48) ||
|
||||
ipv6PrefixMatches(ipv6, [0x2001, 0x20, 0, 0, 0, 0, 0, 0], 28) ||
|
||||
ipv6PrefixMatches(ipv6, [0x2001, 0x30, 0, 0, 0, 0, 0, 0], 28);
|
||||
return publicProtocolAssignment;
|
||||
}
|
||||
if (ipv6PrefixMatches(ipv6, [0x2001, 0x0db8, 0, 0, 0, 0, 0, 0], 32)) return false;
|
||||
if (ipv6PrefixMatches(ipv6, [0x2002, 0, 0, 0, 0, 0, 0, 0], 16)) return false;
|
||||
if (first === 0x3fff && (ipv6[1]! & 0xf000) === 0) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
const readEnvironmentUrl = (environmentId: EnvironmentId): URL => {
|
||||
const connection = readPreparedConnection(environmentId);
|
||||
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
BROWSER_FAVICON_MAX_ENTRIES,
|
||||
type BrowserFaviconEntry,
|
||||
evictExcessFavicons,
|
||||
faviconKey,
|
||||
faviconStorageLocation,
|
||||
isStorableFaviconDataUrl,
|
||||
migratePersistedBrowserFaviconState,
|
||||
} from "./browserFaviconLogic";
|
||||
|
||||
const PNG = "data:image/png;base64,AAAA";
|
||||
|
||||
function entry(capturedAt = 0): BrowserFaviconEntry {
|
||||
return { dataUrl: PNG, capturedAt };
|
||||
}
|
||||
|
||||
describe("browser favicon logic", () => {
|
||||
it("keys valid origins canonically while keeping distinct scopes separate", () => {
|
||||
expect(faviconKey("env:project", "http://myapp.test:3000/admin?x=1", null)).toBe(
|
||||
"env:project http://myapp.test:3000",
|
||||
);
|
||||
expect(faviconKey("env:project", "http://192.168.64.2:3000/", "192.168.64.2")).toBe(
|
||||
faviconKey("env:project", "http://localhost:3000/", "192.168.64.2"),
|
||||
);
|
||||
expect(faviconKey("env:project", "http://127.0.0.1:3000/", null)).toBe(
|
||||
faviconKey("env:project", "http://0.0.0.0:3000/", null),
|
||||
);
|
||||
const keys = [
|
||||
faviconKey("env:a", "http://localhost:3000/", null),
|
||||
faviconKey("env:b", "http://localhost:3000/", null),
|
||||
faviconKey("env:a", "http://localhost:5173/", null),
|
||||
faviconKey("env:a", "https://localhost:3000/", null),
|
||||
faviconKey("env:a", "http://192.168.1.50:3000/", "192.168.64.2"),
|
||||
];
|
||||
expect(new Set(keys).size).toBe(keys.length);
|
||||
expect(faviconKey("env:a", "not a url", null)).toBeNull();
|
||||
expect(faviconKey("env:a", "ftp://example.com/", null)).toBeNull();
|
||||
expect(faviconKey("", "http://localhost/", null)).toBeNull();
|
||||
expect(faviconKey("env:a", "http://local:3000/", null)).not.toBe(
|
||||
faviconKey("env:a", "http://localhost:3000/", null),
|
||||
);
|
||||
});
|
||||
|
||||
it("retains an exact environment-host alias for offline lookup", () => {
|
||||
const expected = {
|
||||
aliases: ["192.168.64.2"],
|
||||
key: "env:project http://localhost:3000",
|
||||
};
|
||||
expect(
|
||||
faviconStorageLocation("env:project", "http://localhost:3000/app", "192.168.64.2"),
|
||||
).toEqual(expected);
|
||||
expect(
|
||||
faviconStorageLocation("env:project", "http://192.168.64.2:3000/app", "192.168.64.2"),
|
||||
).toEqual(expected);
|
||||
expect(
|
||||
faviconStorageLocation("env:project", "https://example.com/app", "192.168.64.2"),
|
||||
).toEqual({ aliases: [], key: "env:project https://example.com:443" });
|
||||
expect(faviconStorageLocation("env:project", "http://localhost:3000/app", "fd00::1")).toEqual({
|
||||
aliases: ["fd00::1"],
|
||||
key: "env:project http://localhost:3000",
|
||||
});
|
||||
expect(faviconKey("env:project", "http://[2001:4860:4860::8888]/", null)).toBe(
|
||||
"env:project http://[2001:4860:4860::8888]:80",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts only bounded base64 PNG data", () => {
|
||||
expect(isStorableFaviconDataUrl(PNG)).toBe(true);
|
||||
expect(isStorableFaviconDataUrl("data:image/svg+xml;base64,AAAA")).toBe(false);
|
||||
expect(isStorableFaviconDataUrl("data:image/png;base64,")).toBe(false);
|
||||
expect(isStorableFaviconDataUrl("data:image/png;base64,%%%%")).toBe(false);
|
||||
expect(isStorableFaviconDataUrl(`data:image/png;base64,${"A".repeat(8192)}`)).toBe(false);
|
||||
});
|
||||
|
||||
it("evicts old entries and sanitizes hydrated state", () => {
|
||||
const byKey = Object.fromEntries(
|
||||
Array.from({ length: BROWSER_FAVICON_MAX_ENTRIES + 2 }, (_, index) => [
|
||||
`key-${index}`,
|
||||
entry(index),
|
||||
]),
|
||||
);
|
||||
const result = evictExcessFavicons(byKey);
|
||||
expect(Object.keys(result)).toHaveLength(BROWSER_FAVICON_MAX_ENTRIES);
|
||||
expect(result["key-0"]).toBeUndefined();
|
||||
expect(result["key-1"]).toBeUndefined();
|
||||
expect(
|
||||
migratePersistedBrowserFaviconState({
|
||||
byKey: {
|
||||
"env:project http://local:3000": entry(4),
|
||||
"env:project http://localhost:3000": entry(5),
|
||||
"env:project http://localhost:3003": {
|
||||
...entry(6),
|
||||
aliases: [
|
||||
"192.168.64.2",
|
||||
"192.168.64.2",
|
||||
"192.168.64.3",
|
||||
"192.168.64.4",
|
||||
"192.168.64.5",
|
||||
"192.168.64.6",
|
||||
"Not Normalized",
|
||||
"not a host/",
|
||||
"x".repeat(5_000),
|
||||
],
|
||||
},
|
||||
"env:project http://localhost:3001": {
|
||||
dataUrl: "https://example.com/icon.png",
|
||||
capturedAt: 6,
|
||||
},
|
||||
"env:project http://localhost:3002": { dataUrl: PNG, capturedAt: Number.NaN },
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
byKey: {
|
||||
"env:project http://localhost:3000": entry(5),
|
||||
"env:project http://localhost:3003": {
|
||||
...entry(6),
|
||||
aliases: ["192.168.64.2", "192.168.64.3", "192.168.64.4", "192.168.64.5"],
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { FAVICON_CAPTURED_AT_MAX, FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
|
||||
|
||||
import { isLocalLoopbackHost, normalizeHostname } from "./browser/browserTargetResolver";
|
||||
|
||||
export type BrowserFaviconEntry = {
|
||||
dataUrl: string;
|
||||
capturedAt: number;
|
||||
aliases?: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
export const BROWSER_FAVICON_MAX_ENTRIES = 40;
|
||||
export const BROWSER_FAVICON_MAX_KEY_LENGTH = 4_096;
|
||||
const BROWSER_FAVICON_MAX_FUTURE_SKEW_MS = 5 * 60 * 1_000;
|
||||
export const BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY = 4;
|
||||
const BROWSER_FAVICON_MAX_ALIAS_LENGTH = 255;
|
||||
|
||||
function formatFaviconHost(host: string): string {
|
||||
return host.includes(":") ? `[${host}]` : host;
|
||||
}
|
||||
|
||||
export function canCanonicalizeFaviconWithoutEnvironment(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const host = normalizeHostname(parsed.hostname);
|
||||
return (
|
||||
(parsed.protocol === "http:" || parsed.protocol === "https:") &&
|
||||
(isLocalLoopbackHost(host) || host === "0.0.0.0")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isValidFaviconCapturedAt(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === "number" &&
|
||||
Number.isFinite(value) &&
|
||||
value >= 0 &&
|
||||
value <= FAVICON_CAPTURED_AT_MAX &&
|
||||
value <= Date.now() + BROWSER_FAVICON_MAX_FUTURE_SKEW_MS
|
||||
);
|
||||
}
|
||||
|
||||
function migratePersistedFaviconKey(key: string): string | null {
|
||||
if (key.length === 0 || key.length > BROWSER_FAVICON_MAX_KEY_LENGTH) return null;
|
||||
const separator = key.indexOf(" ");
|
||||
if (separator <= 0) return null;
|
||||
const scope = key.slice(0, separator);
|
||||
const origin = key.slice(separator + 1);
|
||||
try {
|
||||
const parsed = new URL(origin);
|
||||
if (
|
||||
(parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
|
||||
parsed.pathname !== "/" ||
|
||||
parsed.search !== "" ||
|
||||
parsed.hash !== "" ||
|
||||
parsed.username !== "" ||
|
||||
parsed.password !== ""
|
||||
)
|
||||
return null;
|
||||
if (normalizeHostname(parsed.hostname) !== "local") return key;
|
||||
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
|
||||
return `${scope} ${parsed.protocol}//localhost:${port}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistedFaviconAlias(value: unknown): string | null {
|
||||
if (typeof value !== "string" || value.length > BROWSER_FAVICON_MAX_ALIAS_LENGTH) return null;
|
||||
const normalized = normalizeHostname(value);
|
||||
if (!normalized || normalized !== value) return null;
|
||||
try {
|
||||
const parsed = new URL(`http://${formatFaviconHost(normalized)}`);
|
||||
return normalizeHostname(parsed.hostname) === normalized ? normalized : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function faviconKey(
|
||||
projectRefKey: string,
|
||||
url: string,
|
||||
environmentHostname: string | null,
|
||||
): string | null {
|
||||
if (projectRefKey.length === 0) return null;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
||||
const host = normalizeHostname(parsed.hostname);
|
||||
const canonicalHost =
|
||||
isLocalLoopbackHost(host) ||
|
||||
host === "0.0.0.0" ||
|
||||
(environmentHostname !== null && host === normalizeHostname(environmentHostname))
|
||||
? "localhost"
|
||||
: host;
|
||||
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
|
||||
return `${projectRefKey} ${parsed.protocol}//${formatFaviconHost(canonicalHost)}:${port}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function faviconStorageLocation(
|
||||
projectRefKey: string,
|
||||
url: string,
|
||||
environmentHostname: string | null,
|
||||
): { readonly aliases: ReadonlyArray<string>; readonly key: string } | null {
|
||||
const canonicalKey = faviconKey(projectRefKey, url, environmentHostname);
|
||||
if (!canonicalKey) return null;
|
||||
if (environmentHostname === null) return { aliases: [], key: canonicalKey };
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const host = normalizeHostname(parsed.hostname);
|
||||
const normalizedEnvironmentHostname = normalizeHostname(environmentHostname);
|
||||
if (
|
||||
normalizedEnvironmentHostname.length === 0 ||
|
||||
(!isLocalLoopbackHost(host) && host !== "0.0.0.0" && host !== normalizedEnvironmentHostname)
|
||||
) {
|
||||
return { aliases: [], key: canonicalKey };
|
||||
}
|
||||
return {
|
||||
aliases:
|
||||
isLocalLoopbackHost(normalizedEnvironmentHostname) ||
|
||||
normalizedEnvironmentHostname === "0.0.0.0"
|
||||
? []
|
||||
: [normalizedEnvironmentHostname],
|
||||
key: canonicalKey,
|
||||
};
|
||||
} catch {
|
||||
return { aliases: [], key: canonicalKey };
|
||||
}
|
||||
}
|
||||
|
||||
export function isStorableFaviconDataUrl(value: unknown): value is string {
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
!value.startsWith("data:image/png;base64,") ||
|
||||
value.length > FAVICON_DATA_URL_MAX_LENGTH
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const payload = value.slice("data:image/png;base64,".length);
|
||||
return (
|
||||
payload.length > 0 &&
|
||||
payload.length % 4 !== 1 &&
|
||||
!/[^a-z0-9+/=]/i.test(payload) &&
|
||||
/^[a-z0-9+/]*={0,2}$/i.test(payload)
|
||||
);
|
||||
}
|
||||
|
||||
export function evictExcessFavicons(
|
||||
byKey: Record<string, BrowserFaviconEntry>,
|
||||
): Record<string, BrowserFaviconEntry> {
|
||||
const keys = Object.keys(byKey);
|
||||
if (keys.length <= BROWSER_FAVICON_MAX_ENTRIES) return byKey;
|
||||
return Object.fromEntries(
|
||||
keys
|
||||
.toSorted((left, right) => (byKey[right]?.capturedAt ?? 0) - (byKey[left]?.capturedAt ?? 0))
|
||||
.slice(0, BROWSER_FAVICON_MAX_ENTRIES)
|
||||
.map((key) => [key, byKey[key] as BrowserFaviconEntry]),
|
||||
);
|
||||
}
|
||||
|
||||
export function migratePersistedBrowserFaviconState(persistedState: unknown): {
|
||||
byKey: Record<string, BrowserFaviconEntry>;
|
||||
} {
|
||||
if (!persistedState || typeof persistedState !== "object") return { byKey: {} };
|
||||
const raw = "byKey" in persistedState ? (persistedState as { byKey?: unknown }).byKey : null;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { byKey: {} };
|
||||
const byKey: Record<string, BrowserFaviconEntry> = {};
|
||||
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||
const migratedKey = migratePersistedFaviconKey(key);
|
||||
if (!migratedKey) continue;
|
||||
if (!value || typeof value !== "object") continue;
|
||||
const { dataUrl, capturedAt } = value as Record<string, unknown>;
|
||||
if (!isStorableFaviconDataUrl(dataUrl)) continue;
|
||||
if (!isValidFaviconCapturedAt(capturedAt)) continue;
|
||||
const rawAliases = (value as Record<string, unknown>).aliases;
|
||||
const aliases = Array.isArray(rawAliases)
|
||||
? [...new Set(rawAliases.map(persistedFaviconAlias).filter((alias) => alias !== null))].slice(
|
||||
0,
|
||||
BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
|
||||
)
|
||||
: [];
|
||||
const existing = byKey[migratedKey];
|
||||
const newest = !existing || capturedAt > existing.capturedAt;
|
||||
const mergedAliases = [
|
||||
...new Set([
|
||||
...(newest ? aliases : (existing?.aliases ?? [])),
|
||||
...(newest ? (existing?.aliases ?? []) : aliases),
|
||||
]),
|
||||
].slice(0, BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY);
|
||||
byKey[migratedKey] = {
|
||||
dataUrl: newest ? dataUrl : existing.dataUrl,
|
||||
capturedAt: newest ? capturedAt : existing.capturedAt,
|
||||
...(mergedAliases.length > 0 ? { aliases: mergedAliases } : {}),
|
||||
};
|
||||
}
|
||||
return { byKey: evictExcessFavicons(byKey) };
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
vi.mock("~/state/entities", () => ({ useThreadShell: () => null }));
|
||||
vi.mock("~/state/session", () => ({ usePreparedConnection: () => ({ _tag: "None" }) }));
|
||||
|
||||
import {
|
||||
flushPendingFaviconsForThread,
|
||||
lookupFavicon,
|
||||
mergeBrowserFaviconState,
|
||||
recordFaviconForProject,
|
||||
recordFaviconForThread,
|
||||
registerFaviconProjectForThread,
|
||||
resetBrowserFaviconsForTests,
|
||||
resolveBrowserFaviconStorage,
|
||||
useBrowserFaviconStore,
|
||||
} from "./browserFaviconStore";
|
||||
import {
|
||||
BROWSER_FAVICON_MAX_ENTRIES,
|
||||
migratePersistedBrowserFaviconState,
|
||||
} from "./browserFaviconLogic";
|
||||
|
||||
const environmentId = EnvironmentId.make("env-1");
|
||||
const projectRef = scopeProjectRef(environmentId, ProjectId.make("project-1"));
|
||||
const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
|
||||
const PNG = "data:image/png;base64,AAAA";
|
||||
const favicon = (pageUrl: string, capturedAt: number, dataUrl = PNG) => ({
|
||||
pageUrl,
|
||||
capturedAt,
|
||||
dataUrl,
|
||||
});
|
||||
|
||||
describe("browser favicon store", () => {
|
||||
beforeEach(resetBrowserFaviconsForTests);
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("keeps the newest capture for an origin and permits an identical later revisit", () => {
|
||||
const recordFavicon = vi.spyOn(useBrowserFaviconStore.getState(), "recordFavicon");
|
||||
recordFaviconForProject(projectRef, favicon("http://localhost:3000/", 20), null);
|
||||
recordFaviconForProject(
|
||||
projectRef,
|
||||
favicon("http://localhost:3000/old", 10, "data:image/png;base64,QkJCQg=="),
|
||||
null,
|
||||
);
|
||||
recordFaviconForProject(projectRef, favicon("http://localhost:3000/new", 30), null);
|
||||
recordFaviconForProject(projectRef, favicon("http://localhost:3000/new", 30), null);
|
||||
expect(Object.values(useBrowserFaviconStore.getState().byKey)).toEqual([
|
||||
{ dataUrl: PNG, capturedAt: 30 },
|
||||
]);
|
||||
expect(recordFavicon).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not share localhost icons across environments or physical projects", () => {
|
||||
const otherEnvironment = scopeProjectRef(
|
||||
EnvironmentId.make("env-2"),
|
||||
ProjectId.make("project-1"),
|
||||
);
|
||||
const otherProject = scopeProjectRef(environmentId, ProjectId.make("project-2"));
|
||||
recordFaviconForProject(projectRef, favicon("http://localhost:3000/", 1), null);
|
||||
recordFaviconForProject(otherEnvironment, favicon("http://localhost:3000/", 2), null);
|
||||
recordFaviconForProject(otherProject, favicon("http://localhost:3000/", 3), null);
|
||||
expect(Object.keys(useBrowserFaviconStore.getState().byKey)).toEqual([
|
||||
"env-1:project-1 http://localhost:3000",
|
||||
"env-2:project-1 http://localhost:3000",
|
||||
"env-1:project-2 http://localhost:3000",
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds a persisted environment icon after shell hydration without a live connection", () => {
|
||||
recordFaviconForProject(projectRef, favicon("http://192.168.64.2:3000/app", 5), "192.168.64.2");
|
||||
const byKey = useBrowserFaviconStore.getState().byKey;
|
||||
expect(lookupFavicon(byKey, null, "http://localhost:3000/app", null)).toBeNull();
|
||||
expect(lookupFavicon(byKey, projectRef, "http://localhost:3000/app", null)).toBe(PNG);
|
||||
expect(lookupFavicon(byKey, projectRef, "http://192.168.64.2:3000/app", null)).toBe(PNG);
|
||||
expect(lookupFavicon(byKey, projectRef, "http://192.168.64.3:3000/app", null)).toBeNull();
|
||||
expect(lookupFavicon(byKey, projectRef, "https://192.168.64.2:3000/app", null)).toBeNull();
|
||||
expect(lookupFavicon(byKey, projectRef, "http://192.168.64.2:3001/app", null)).toBeNull();
|
||||
expect(
|
||||
lookupFavicon(
|
||||
byKey,
|
||||
scopeProjectRef(environmentId, ProjectId.make("project-2")),
|
||||
"http://192.168.64.2:3000/app",
|
||||
null,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("finds a persisted IPv6 environment icon without a live connection", () => {
|
||||
recordFaviconForProject(projectRef, favicon("http://[fd00::1]:3000/app", 5), "fd00::1");
|
||||
const migrated = migratePersistedBrowserFaviconState({
|
||||
byKey: useBrowserFaviconStore.getState().byKey,
|
||||
}).byKey;
|
||||
expect(lookupFavicon(migrated, projectRef, "http://[fd00::1]:3000/app", null)).toBe(PNG);
|
||||
});
|
||||
|
||||
it("keeps exact host aliases attached to the newest canonical icon", () => {
|
||||
const olderPng = "data:image/png;base64,QkJCQg==";
|
||||
const newerPng = "data:image/png;base64,Q0NDQw==";
|
||||
recordFaviconForProject(
|
||||
projectRef,
|
||||
favicon("http://192.168.64.2:3000/", 10, olderPng),
|
||||
"192.168.64.2",
|
||||
);
|
||||
recordFaviconForProject(
|
||||
projectRef,
|
||||
favicon("http://192.168.64.3:3000/", 20, newerPng),
|
||||
"192.168.64.3",
|
||||
);
|
||||
recordFaviconForProject(
|
||||
projectRef,
|
||||
favicon("http://192.168.64.4:3000/", 15, olderPng),
|
||||
"192.168.64.4",
|
||||
);
|
||||
const byKey = useBrowserFaviconStore.getState().byKey;
|
||||
for (const host of ["192.168.64.2", "192.168.64.3", "192.168.64.4"]) {
|
||||
expect(lookupFavicon(byKey, projectRef, `http://${host}:3000/`, null)).toBe(newerPng);
|
||||
}
|
||||
expect(byKey["env-1:project-1 http://localhost:3000"]?.capturedAt).toBe(20);
|
||||
});
|
||||
|
||||
it("evicts an icon and its exact host aliases atomically", () => {
|
||||
recordFaviconForProject(projectRef, favicon("http://192.168.64.2:3000/", 100), "192.168.64.2");
|
||||
for (let index = 1; index < BROWSER_FAVICON_MAX_ENTRIES; index += 1) {
|
||||
recordFaviconForProject(
|
||||
projectRef,
|
||||
favicon(`https://example-${index}.com/`, 100 + index),
|
||||
null,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
lookupFavicon(
|
||||
useBrowserFaviconStore.getState().byKey,
|
||||
projectRef,
|
||||
"http://192.168.64.2:3000/",
|
||||
null,
|
||||
),
|
||||
).toBe(PNG);
|
||||
|
||||
recordFaviconForProject(projectRef, favicon("https://evicts-oldest.example/", 1_000), null);
|
||||
expect(
|
||||
lookupFavicon(
|
||||
useBrowserFaviconStore.getState().byKey,
|
||||
projectRef,
|
||||
"http://192.168.64.2:3000/",
|
||||
null,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("retains multiple origins until project and connection metadata hydrate", () => {
|
||||
expect(
|
||||
recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 1), null, undefined),
|
||||
).toBe(false);
|
||||
expect(
|
||||
recordFaviconForThread(threadRef, favicon("http://localhost:5173/", 2), null, undefined),
|
||||
).toBe(false);
|
||||
expect(
|
||||
Object.keys(Object.values(useBrowserFaviconStore.getState().pendingByThreadKey)[0] ?? {}),
|
||||
).toHaveLength(2);
|
||||
|
||||
expect(flushPendingFaviconsForThread(threadRef, projectRef, "192.168.64.2")).toBe(true);
|
||||
expect(Object.keys(useBrowserFaviconStore.getState().byKey).toSorted()).toEqual([
|
||||
"env-1:project-1 http://localhost:3000",
|
||||
"env-1:project-1 http://localhost:5173",
|
||||
]);
|
||||
expect(useBrowserFaviconStore.getState().pendingByThreadKey).toEqual({});
|
||||
});
|
||||
|
||||
it("persists unambiguous loopback captures while the environment is offline", () => {
|
||||
expect(
|
||||
recordFaviconForThread(
|
||||
threadRef,
|
||||
favicon("http://localhost:3000/", 1),
|
||||
projectRef,
|
||||
undefined,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(useBrowserFaviconStore.getState().byKey).toEqual({
|
||||
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 1 },
|
||||
});
|
||||
|
||||
recordFaviconForThread(
|
||||
threadRef,
|
||||
favicon("http://192.168.64.2:5173/", 2),
|
||||
projectRef,
|
||||
undefined,
|
||||
);
|
||||
expect(flushPendingFaviconsForThread(threadRef, projectRef, undefined)).toBe(false);
|
||||
expect(Object.values(useBrowserFaviconStore.getState().pendingByThreadKey)[0]).toBeDefined();
|
||||
});
|
||||
|
||||
it("keeps pending captures in store-owned state independent of bridge lifetime", () => {
|
||||
recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 10), null, undefined);
|
||||
const pendingAfterUnmount = useBrowserFaviconStore.getState().pendingByThreadKey;
|
||||
useBrowserFaviconStore.setState({ pendingByThreadKey: pendingAfterUnmount });
|
||||
flushPendingFaviconsForThread(threadRef, projectRef, "localhost");
|
||||
expect(useBrowserFaviconStore.getState().byKey).toEqual({
|
||||
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 10 },
|
||||
});
|
||||
});
|
||||
|
||||
it("flushes and resolves a pending draft-thread favicon after physical project registration", () => {
|
||||
recordFaviconForThread(threadRef, favicon("http://localhost:8025/", 10), null, undefined);
|
||||
registerFaviconProjectForThread(threadRef, projectRef);
|
||||
const registered = useBrowserFaviconStore.getState().projectRefByThreadKey["env-1:thread-1"];
|
||||
expect(registered).toEqual(projectRef);
|
||||
expect(flushPendingFaviconsForThread(threadRef, registered!, undefined)).toBe(true);
|
||||
expect(
|
||||
lookupFavicon(
|
||||
useBrowserFaviconStore.getState().byKey,
|
||||
registered!,
|
||||
"http://localhost:8025/",
|
||||
null,
|
||||
),
|
||||
).toBe(PNG);
|
||||
});
|
||||
|
||||
it("bounds pending memory by origin and thread", () => {
|
||||
for (let thread = 0; thread < 22; thread += 1) {
|
||||
for (let port = 3000; port < 3012; port += 1) {
|
||||
recordFaviconForThread(
|
||||
{ environmentId, threadId: ThreadId.make(`thread-${thread}`) },
|
||||
favicon(`http://localhost:${port}/`, port),
|
||||
null,
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
}
|
||||
const pending = useBrowserFaviconStore.getState().pendingByThreadKey;
|
||||
expect(Object.keys(pending)).toHaveLength(20);
|
||||
expect(Object.values(pending).every((byOrigin) => Object.keys(byOrigin).length === 10)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("sanitizes hydrated state while preserving actions and transient pending data", () => {
|
||||
recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 1), null, undefined);
|
||||
const current = useBrowserFaviconStore.getState();
|
||||
const merged = mergeBrowserFaviconState(
|
||||
{
|
||||
byKey: {
|
||||
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 2 },
|
||||
"env-1:project-1 http://localhost:3001": { dataUrl: "bad", capturedAt: 3 },
|
||||
"env-1:project-1 http://localhost:3002": { dataUrl: PNG, capturedAt: 1e308 },
|
||||
["x".repeat(5_000)]: { dataUrl: PNG, capturedAt: 4 },
|
||||
},
|
||||
},
|
||||
current,
|
||||
);
|
||||
expect(merged.byKey).toEqual({
|
||||
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 2 },
|
||||
});
|
||||
expect(merged.pendingByThreadKey).toEqual(current.pendingByThreadKey);
|
||||
expect(typeof merged.recordFavicon).toBe("function");
|
||||
});
|
||||
|
||||
it("falls back to memory when localStorage access throws", () => {
|
||||
vi.stubGlobal(
|
||||
"window",
|
||||
Object.defineProperty({}, "localStorage", {
|
||||
get: () => {
|
||||
throw new Error("storage blocked");
|
||||
},
|
||||
}),
|
||||
);
|
||||
const storage = resolveBrowserFaviconStorage();
|
||||
storage.setItem("key", "value");
|
||||
expect(storage.getItem("key")).toBe("value");
|
||||
});
|
||||
|
||||
it("falls back to memory when localStorage operations throw", () => {
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: {
|
||||
getItem: vi.fn(() => {
|
||||
throw new Error("read blocked");
|
||||
}),
|
||||
setItem: vi.fn(() => {
|
||||
throw new Error("quota exceeded");
|
||||
}),
|
||||
removeItem: vi.fn(() => {
|
||||
throw new Error("remove blocked");
|
||||
}),
|
||||
},
|
||||
});
|
||||
const storage = resolveBrowserFaviconStorage();
|
||||
|
||||
storage.setItem("key", "value");
|
||||
expect(storage.getItem("key")).toBe("value");
|
||||
storage.removeItem("key");
|
||||
expect(storage.getItem("key")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the memory shadow authoritative after an asymmetric primary write failure", () => {
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: {
|
||||
getItem: vi.fn(() => "stale"),
|
||||
setItem: vi.fn(() => {
|
||||
throw new Error("quota exceeded");
|
||||
}),
|
||||
removeItem: vi.fn(() => {
|
||||
throw new Error("remove blocked");
|
||||
}),
|
||||
},
|
||||
});
|
||||
const storage = resolveBrowserFaviconStorage();
|
||||
|
||||
storage.setItem("key", "fresh");
|
||||
expect(storage.getItem("key")).toBe("fresh");
|
||||
storage.removeItem("key");
|
||||
expect(storage.getItem("key")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
import {
|
||||
scopedProjectKey,
|
||||
scopedThreadKey,
|
||||
scopeProjectRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import type { DesktopPreviewFavicon, ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { useMemo } from "react";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
import { normalizeHostname } from "~/browser/browserTargetResolver";
|
||||
import { useThreadShell } from "~/state/entities";
|
||||
import { usePreparedConnection } from "~/state/session";
|
||||
|
||||
import {
|
||||
BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
|
||||
type BrowserFaviconEntry,
|
||||
canCanonicalizeFaviconWithoutEnvironment,
|
||||
evictExcessFavicons,
|
||||
faviconKey,
|
||||
faviconStorageLocation,
|
||||
isStorableFaviconDataUrl,
|
||||
isValidFaviconCapturedAt,
|
||||
migratePersistedBrowserFaviconState,
|
||||
} from "./browserFaviconLogic";
|
||||
import { createMemoryStorage, type StateStorage } from "./lib/storage";
|
||||
|
||||
const BROWSER_FAVICON_STORAGE_KEY = "t3code:browser-favicons:v1";
|
||||
const MAX_PENDING_ORIGINS_PER_THREAD = 10;
|
||||
const MAX_PENDING_THREADS = 20;
|
||||
const MAX_REGISTERED_THREADS = 100;
|
||||
|
||||
type PendingFavicon = DesktopPreviewFavicon;
|
||||
type PendingFaviconsByOrigin = Record<string, PendingFavicon>;
|
||||
|
||||
export interface BrowserFaviconStoreState {
|
||||
byKey: Record<string, BrowserFaviconEntry>;
|
||||
/** Capture buffering only. */
|
||||
pendingByThreadKey: Record<string, PendingFaviconsByOrigin>;
|
||||
/** Non-persisted fallback for draft/background threads without a hydrated shell. */
|
||||
projectRefByThreadKey: Record<string, ScopedProjectRef>;
|
||||
recordFavicon: (
|
||||
key: string,
|
||||
dataUrl: string,
|
||||
capturedAt: number,
|
||||
aliases?: ReadonlyArray<string>,
|
||||
) => void;
|
||||
}
|
||||
|
||||
function pendingOriginKey(pageUrl: string): string | null {
|
||||
return faviconKey("pending", pageUrl, null)?.slice("pending ".length) ?? null;
|
||||
}
|
||||
|
||||
function addPendingFavicon(
|
||||
pendingByThreadKey: Record<string, PendingFaviconsByOrigin>,
|
||||
threadKey: string,
|
||||
favicon: PendingFavicon,
|
||||
): Record<string, PendingFaviconsByOrigin> {
|
||||
const originKey = pendingOriginKey(favicon.pageUrl);
|
||||
if (!originKey) return pendingByThreadKey;
|
||||
const current = pendingByThreadKey[threadKey] ?? {};
|
||||
const existing = current[originKey];
|
||||
if (existing && existing.capturedAt >= favicon.capturedAt) return pendingByThreadKey;
|
||||
const nextForThread = {
|
||||
...current,
|
||||
[originKey]: favicon,
|
||||
};
|
||||
const boundedForThread = Object.fromEntries(
|
||||
Object.entries(nextForThread)
|
||||
.toSorted(([, left], [, right]) => right.capturedAt - left.capturedAt)
|
||||
.slice(0, MAX_PENDING_ORIGINS_PER_THREAD),
|
||||
);
|
||||
|
||||
const withoutThread = { ...pendingByThreadKey };
|
||||
delete withoutThread[threadKey];
|
||||
return Object.fromEntries(
|
||||
[...Object.entries(withoutThread), [threadKey, boundedForThread]].slice(-MAX_PENDING_THREADS),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveBrowserFaviconStorage(): StateStorage {
|
||||
const fallback = createMemoryStorage();
|
||||
const shadowedNames = new Set<string>();
|
||||
let primary: Storage;
|
||||
try {
|
||||
if (typeof window === "undefined") return fallback;
|
||||
primary = window.localStorage;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
return {
|
||||
getItem: (name) => {
|
||||
if (shadowedNames.has(name)) return fallback.getItem(name);
|
||||
try {
|
||||
return primary.getItem(name);
|
||||
} catch {
|
||||
return fallback.getItem(name);
|
||||
}
|
||||
},
|
||||
setItem: (name, value) => {
|
||||
fallback.setItem(name, value);
|
||||
try {
|
||||
primary.setItem(name, value);
|
||||
shadowedNames.delete(name);
|
||||
} catch {
|
||||
shadowedNames.add(name);
|
||||
}
|
||||
},
|
||||
removeItem: (name) => {
|
||||
fallback.removeItem(name);
|
||||
try {
|
||||
primary.removeItem(name);
|
||||
shadowedNames.delete(name);
|
||||
} catch {
|
||||
shadowedNames.add(name);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const useBrowserFaviconStore = create<BrowserFaviconStoreState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
byKey: {},
|
||||
pendingByThreadKey: {},
|
||||
projectRefByThreadKey: {},
|
||||
recordFavicon: (key, dataUrl, capturedAt, aliases = []) =>
|
||||
set((state) => {
|
||||
if (!isStorableFaviconDataUrl(dataUrl)) return state;
|
||||
if (!isValidFaviconCapturedAt(capturedAt)) return state;
|
||||
const existing = state.byKey[key];
|
||||
const aliasCandidates =
|
||||
capturedAt > (existing?.capturedAt ?? -1)
|
||||
? [...aliases, ...(existing?.aliases ?? [])]
|
||||
: [...(existing?.aliases ?? []), ...aliases];
|
||||
const nextAliases = [...new Set(aliasCandidates)].slice(
|
||||
0,
|
||||
BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
|
||||
);
|
||||
const aliasesUnchanged =
|
||||
nextAliases.length === (existing?.aliases?.length ?? 0) &&
|
||||
nextAliases.every((alias, index) => alias === existing?.aliases?.[index]);
|
||||
if (existing && capturedAt <= existing.capturedAt && aliasesUnchanged) return state;
|
||||
return {
|
||||
byKey: evictExcessFavicons({
|
||||
...state.byKey,
|
||||
[key]: {
|
||||
dataUrl: capturedAt > (existing?.capturedAt ?? -1) ? dataUrl : existing!.dataUrl,
|
||||
capturedAt: Math.max(capturedAt, existing?.capturedAt ?? -1),
|
||||
...(nextAliases.length > 0 ? { aliases: nextAliases } : {}),
|
||||
},
|
||||
}),
|
||||
};
|
||||
}),
|
||||
}),
|
||||
{
|
||||
name: BROWSER_FAVICON_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(resolveBrowserFaviconStorage),
|
||||
partialize: (state) => ({ byKey: state.byKey }),
|
||||
migrate: migratePersistedBrowserFaviconState,
|
||||
merge: mergeBrowserFaviconState,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export function mergeBrowserFaviconState(
|
||||
persistedState: unknown,
|
||||
currentState: BrowserFaviconStoreState,
|
||||
): BrowserFaviconStoreState {
|
||||
return {
|
||||
...currentState,
|
||||
...migratePersistedBrowserFaviconState(persistedState),
|
||||
};
|
||||
}
|
||||
|
||||
export function registerFaviconProjectForThread(
|
||||
threadRef: ScopedThreadRef,
|
||||
projectRef: ScopedProjectRef,
|
||||
): void {
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const state = useBrowserFaviconStore.getState();
|
||||
const current = state.projectRefByThreadKey[threadKey];
|
||||
if (
|
||||
current?.environmentId === projectRef.environmentId &&
|
||||
current.projectId === projectRef.projectId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
useBrowserFaviconStore.setState({
|
||||
projectRefByThreadKey: Object.fromEntries(
|
||||
[
|
||||
...Object.entries(state.projectRefByThreadKey).filter(([key]) => key !== threadKey),
|
||||
[threadKey, projectRef],
|
||||
].slice(-MAX_REGISTERED_THREADS),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
|
||||
const shell = useThreadShell(threadRef);
|
||||
const shellProjectId = shell?.projectId ?? null;
|
||||
const shellProjectRef = useMemo(
|
||||
() => (shellProjectId ? scopeProjectRef(threadRef.environmentId, shellProjectId) : null),
|
||||
[shellProjectId, threadRef.environmentId],
|
||||
);
|
||||
const registered = useBrowserFaviconStore(
|
||||
(state) => state.projectRefByThreadKey[scopedThreadKey(threadRef)] ?? null,
|
||||
);
|
||||
return shellProjectRef ?? registered;
|
||||
}
|
||||
|
||||
export function recordFaviconForProject(
|
||||
projectRef: ScopedProjectRef,
|
||||
favicon: DesktopPreviewFavicon,
|
||||
environmentHostname: string | null,
|
||||
): boolean {
|
||||
if (!isStorableFaviconDataUrl(favicon.dataUrl) || !isValidFaviconCapturedAt(favicon.capturedAt)) {
|
||||
return false;
|
||||
}
|
||||
const location = faviconStorageLocation(
|
||||
scopedProjectKey(projectRef),
|
||||
favicon.pageUrl,
|
||||
environmentHostname,
|
||||
);
|
||||
if (!location) return false;
|
||||
const state = useBrowserFaviconStore.getState();
|
||||
const existing = state.byKey[location.key];
|
||||
if (
|
||||
existing &&
|
||||
existing.capturedAt >= favicon.capturedAt &&
|
||||
location.aliases.every((alias) => existing.aliases?.includes(alias))
|
||||
)
|
||||
return true;
|
||||
state.recordFavicon(location.key, favicon.dataUrl, favicon.capturedAt, location.aliases);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function recordFaviconForThread(
|
||||
threadRef: ScopedThreadRef,
|
||||
favicon: DesktopPreviewFavicon,
|
||||
projectRef: ScopedProjectRef | null,
|
||||
environmentHostname: string | undefined,
|
||||
): boolean {
|
||||
if (
|
||||
!isStorableFaviconDataUrl(favicon.dataUrl) ||
|
||||
!isValidFaviconCapturedAt(favicon.capturedAt) ||
|
||||
!pendingOriginKey(favicon.pageUrl)
|
||||
)
|
||||
return false;
|
||||
const hostname =
|
||||
environmentHostname !== undefined
|
||||
? environmentHostname
|
||||
: canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
|
||||
? null
|
||||
: undefined;
|
||||
if (
|
||||
projectRef &&
|
||||
hostname !== undefined &&
|
||||
recordFaviconForProject(projectRef, favicon, hostname)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const state = useBrowserFaviconStore.getState();
|
||||
const pendingByThreadKey = addPendingFavicon(state.pendingByThreadKey, threadKey, favicon);
|
||||
if (pendingByThreadKey !== state.pendingByThreadKey) {
|
||||
useBrowserFaviconStore.setState({ pendingByThreadKey });
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function flushPendingFaviconsForThread(
|
||||
threadRef: ScopedThreadRef,
|
||||
projectRef: ScopedProjectRef,
|
||||
environmentHostname: string | undefined,
|
||||
): boolean {
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const pending = useBrowserFaviconStore.getState().pendingByThreadKey[threadKey];
|
||||
if (!pending) return true;
|
||||
const remaining = Object.fromEntries(
|
||||
Object.entries(pending).filter(([, favicon]) => {
|
||||
const hostname =
|
||||
environmentHostname !== undefined
|
||||
? environmentHostname
|
||||
: canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
|
||||
? null
|
||||
: undefined;
|
||||
return hostname === undefined || !recordFaviconForProject(projectRef, favicon, hostname);
|
||||
}),
|
||||
);
|
||||
useBrowserFaviconStore.setState((state) => {
|
||||
const pendingByThreadKey = { ...state.pendingByThreadKey };
|
||||
if (Object.keys(remaining).length === 0) delete pendingByThreadKey[threadKey];
|
||||
else pendingByThreadKey[threadKey] = remaining;
|
||||
return { pendingByThreadKey };
|
||||
});
|
||||
return Object.keys(remaining).length === 0;
|
||||
}
|
||||
|
||||
export function useFaviconForThreadUrl(threadRef: ScopedThreadRef, url: string): string | null {
|
||||
const projectRef = useFaviconProjectRefForThread(threadRef);
|
||||
const preparedConnection = usePreparedConnection(threadRef.environmentId);
|
||||
const environmentHostname = Option.isSome(preparedConnection)
|
||||
? new URL(preparedConnection.value.httpBaseUrl).hostname
|
||||
: null;
|
||||
return useBrowserFaviconStore((state) =>
|
||||
lookupFavicon(state.byKey, projectRef, url, environmentHostname),
|
||||
);
|
||||
}
|
||||
|
||||
export function lookupFavicon(
|
||||
byKey: Record<string, BrowserFaviconEntry>,
|
||||
projectRef: ScopedProjectRef | null,
|
||||
url: string,
|
||||
environmentHostname: string | null,
|
||||
): string | null {
|
||||
const key = projectRef
|
||||
? faviconKey(scopedProjectKey(projectRef), url, environmentHostname)
|
||||
: null;
|
||||
if (!key) return null;
|
||||
const direct = byKey[key];
|
||||
if (direct) return direct.dataUrl;
|
||||
try {
|
||||
const requestedHost = normalizeHostname(new URL(url).hostname);
|
||||
const localKey = faviconKey(scopedProjectKey(projectRef!), url, requestedHost);
|
||||
const localEntry = localKey ? byKey[localKey] : null;
|
||||
return localEntry?.aliases?.includes(requestedHost) ? localEntry.dataUrl : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function resetBrowserFaviconsForTests(): void {
|
||||
useBrowserFaviconStore.setState({
|
||||
byKey: {},
|
||||
pendingByThreadKey: {},
|
||||
projectRefByThreadKey: {},
|
||||
});
|
||||
useBrowserFaviconStore.persist.clearStorage();
|
||||
}
|
||||
@@ -179,6 +179,7 @@ import {
|
||||
} from "~/projectScripts";
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { useBrowserHistoryStore } from "~/browserHistoryStore";
|
||||
import { registerFaviconProjectForThread } from "~/browserFaviconStore";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
|
||||
import {
|
||||
@@ -1704,9 +1705,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]);
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const activeProjectRef = activeThread
|
||||
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
|
||||
: null;
|
||||
const activeProjectRef = useMemo(
|
||||
() =>
|
||||
activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null,
|
||||
[activeThread?.environmentId, activeThread?.projectId],
|
||||
);
|
||||
const activeProject = useProject(activeProjectRef);
|
||||
const handleNewThreadInActiveProject = useCallback(() => {
|
||||
startNewThreadForProject(activeProjectRef, handleNewThread);
|
||||
@@ -1758,6 +1761,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
// drive the environment picker in BranchToolbar.
|
||||
const allProjects = useProjects();
|
||||
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
|
||||
useEffect(() => {
|
||||
if (!activeThreadRef || !activeProjectRef) return;
|
||||
registerFaviconProjectForThread(activeThreadRef, activeProjectRef);
|
||||
}, [activeProjectRef, activeThreadRef]);
|
||||
useEffect(() => {
|
||||
if (!clientSettingsHydrated || !activeThreadRef || !activeProject) return;
|
||||
// Reuse the sidebar's grouping so history follows the project rows the user
|
||||
@@ -6546,6 +6553,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
activeSurfaceId={activeRightPanelSurface?.id ?? null}
|
||||
pendingSurfaceIds={pendingFileSurfaceIds}
|
||||
previewSessions={activePreviewState.sessions}
|
||||
desktopByTabId={activePreviewState.desktopByTabId}
|
||||
terminalLabelsById={activeTerminalLabelsById}
|
||||
onActivate={activateRightPanelSurface}
|
||||
onCloseSurface={closeRightPanelSurface}
|
||||
@@ -6580,6 +6588,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
activeSurfaceId={activeRightPanelSurface?.id ?? null}
|
||||
pendingSurfaceIds={pendingFileSurfaceIds}
|
||||
previewSessions={activePreviewState.sessions}
|
||||
desktopByTabId={activePreviewState.desktopByTabId}
|
||||
terminalLabelsById={activeTerminalLabelsById}
|
||||
onActivate={activateRightPanelSurface}
|
||||
onCloseSurface={closeRightPanelSurface}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { DesktopPreviewFavicon, PreviewSessionSnapshot } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { RightPanelTabs } from "./RightPanelTabs";
|
||||
|
||||
const previewSurface = {
|
||||
id: "browser:tab-1" as const,
|
||||
kind: "preview" as const,
|
||||
resourceId: "tab-1",
|
||||
};
|
||||
const secondSurface = {
|
||||
id: "browser:tab-2" as const,
|
||||
kind: "preview" as const,
|
||||
resourceId: "tab-2",
|
||||
};
|
||||
const sessions: Readonly<Record<string, PreviewSessionSnapshot>> = {
|
||||
"tab-1": {
|
||||
threadId: "thread-1",
|
||||
tabId: "tab-1",
|
||||
navStatus: { _tag: "Success", url: "http://24x.xf.local/", title: "Local site" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
updatedAt: "2026-08-09T00:00:00.000Z",
|
||||
},
|
||||
"tab-2": {
|
||||
threadId: "thread-1",
|
||||
tabId: "tab-2",
|
||||
navStatus: { _tag: "Success", url: "http://24x.xf.local/admin", title: "Admin" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
updatedAt: "2026-08-09T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
const favicon = (dataUrl: string, pageUrl: string): DesktopPreviewFavicon => ({
|
||||
dataUrl,
|
||||
pageUrl,
|
||||
capturedAt: 1,
|
||||
});
|
||||
|
||||
function overlay(icon: DesktopPreviewFavicon | null) {
|
||||
return {
|
||||
hasWebContents: true,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
loading: false,
|
||||
zoomFactor: 1,
|
||||
pictureInPicture: false,
|
||||
colorScheme: "system" as const,
|
||||
controller: "none" as const,
|
||||
favicon: icon,
|
||||
};
|
||||
}
|
||||
|
||||
function renderTabs(first: DesktopPreviewFavicon | null, second?: DesktopPreviewFavicon) {
|
||||
return renderToStaticMarkup(
|
||||
<RightPanelTabs
|
||||
mode="inline"
|
||||
surfaces={second ? [previewSurface, secondSurface] : [previewSurface]}
|
||||
activeSurfaceId={previewSurface.id}
|
||||
pendingSurfaceIds={new Set()}
|
||||
previewSessions={sessions}
|
||||
desktopByTabId={{
|
||||
"tab-1": overlay(first),
|
||||
...(second ? { "tab-2": overlay(second) } : {}),
|
||||
}}
|
||||
terminalLabelsById={new Map()}
|
||||
onActivate={() => undefined}
|
||||
onCloseSurface={() => undefined}
|
||||
onCloseOtherSurfaces={() => undefined}
|
||||
onCloseSurfacesToRight={() => undefined}
|
||||
onCloseAllSurfaces={() => undefined}
|
||||
onCopyFilePath={() => undefined}
|
||||
onAddBrowser={() => undefined}
|
||||
onAddTerminal={() => undefined}
|
||||
onAddPullRequest={() => undefined}
|
||||
onAddDiff={() => undefined}
|
||||
onAddFiles={() => undefined}
|
||||
onAddAgents={() => undefined}
|
||||
liveAgentCount={0}
|
||||
browserAvailable
|
||||
terminalAvailable={false}
|
||||
diffAvailable={false}
|
||||
filesAvailable={false}
|
||||
pullRequestAvailable={false}
|
||||
agentsAvailable={false}
|
||||
>
|
||||
<div>content</div>
|
||||
</RightPanelTabs>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("RightPanelTabs preview favicon", () => {
|
||||
it("prefers a live capture and never asks Google about a private hostname", () => {
|
||||
const captured = renderTabs(favicon("data:image/png;base64,AAAA", "http://24x.xf.local/"));
|
||||
expect(captured).toContain("data:image/png;base64,AAAA");
|
||||
expect(captured).not.toContain("s2/favicons");
|
||||
expect(renderTabs(null)).not.toContain("s2/favicons");
|
||||
});
|
||||
|
||||
it("keeps route-specific captures isolated between live tabs on one origin", () => {
|
||||
const html = renderTabs(
|
||||
favicon("data:image/png;base64,AAAA", "http://24x.xf.local/"),
|
||||
favicon("data:image/png;base64,BBBB", "http://24x.xf.local/admin"),
|
||||
);
|
||||
expect(html).toContain("data:image/png;base64,AAAA");
|
||||
expect(html).toContain("data:image/png;base64,BBBB");
|
||||
});
|
||||
|
||||
it("hides a capture while the server session still describes another origin", () => {
|
||||
const html = renderTabs(favicon("data:image/png;base64,AAAA", "https://example.com/"));
|
||||
expect(html).not.toContain("data:image/png;base64,AAAA");
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from "react";
|
||||
|
||||
import { isElectron } from "~/env";
|
||||
import type { DesktopPreviewOverlay } from "~/previewStateStore";
|
||||
import type { RightPanelSurface } from "~/rightPanelStore";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
@@ -34,6 +35,7 @@ import { useTheme } from "~/hooks/useTheme";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
|
||||
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
|
||||
import { FaviconImage } from "./preview/PreviewFaviconIcon";
|
||||
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
|
||||
|
||||
interface RightPanelTabsProps {
|
||||
@@ -48,6 +50,7 @@ interface RightPanelTabsProps {
|
||||
activeSurfaceId: string | null;
|
||||
pendingSurfaceIds: ReadonlySet<string>;
|
||||
previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
|
||||
desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
|
||||
terminalLabelsById: ReadonlyMap<string, string>;
|
||||
onActivate: (surface: RightPanelSurface) => void;
|
||||
onCloseSurface: (surface: RightPanelSurface) => void;
|
||||
@@ -435,30 +438,35 @@ function surfaceTitle(
|
||||
}
|
||||
}
|
||||
|
||||
function PreviewFavicon({ url }: { url: string | null }) {
|
||||
const faviconUrl = faviconUrlForOrigin(url, 32);
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
if (!faviconUrl || failedUrl === faviconUrl) return <Globe2 className="size-3 shrink-0" />;
|
||||
function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) {
|
||||
const publicProviderUrl = faviconUrlForOrigin(url, 32);
|
||||
return (
|
||||
<img
|
||||
src={faviconUrl}
|
||||
alt=""
|
||||
aria-hidden
|
||||
draggable={false}
|
||||
className="size-3 shrink-0 rounded-sm"
|
||||
onError={() => setFailedUrl(faviconUrl)}
|
||||
<FaviconImage
|
||||
sources={[capturedUrl, publicProviderUrl]}
|
||||
fallback={<Globe2 className="size-3 shrink-0" />}
|
||||
className="size-3 shrink-0 rounded-sm object-contain"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function sameOrigin(left: string, right: string): boolean {
|
||||
try {
|
||||
return new URL(left).origin === new URL(right).origin;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function SurfaceIcon({
|
||||
surface,
|
||||
sessions,
|
||||
desktopByTabId,
|
||||
theme,
|
||||
pullRequestStatuses,
|
||||
}: {
|
||||
surface: RightPanelSurface;
|
||||
sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
|
||||
desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
|
||||
theme: "light" | "dark";
|
||||
pullRequestStatuses: Readonly<Record<string, PullRequestTabStatus>> | undefined;
|
||||
}) {
|
||||
@@ -466,7 +474,10 @@ function SurfaceIcon({
|
||||
case "preview": {
|
||||
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
|
||||
const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
|
||||
return <PreviewFavicon url={url} />;
|
||||
const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null;
|
||||
const capturedUrl =
|
||||
favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null;
|
||||
return <PreviewFavicon capturedUrl={capturedUrl} url={url} />;
|
||||
}
|
||||
case "diff":
|
||||
return <FileDiff className="size-3 shrink-0" />;
|
||||
@@ -636,6 +647,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
|
||||
<SurfaceIcon
|
||||
surface={surface}
|
||||
sessions={props.previewSessions}
|
||||
desktopByTabId={props.desktopByTabId}
|
||||
theme={resolvedTheme}
|
||||
pullRequestStatuses={props.pullRequestStatuses}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
@@ -19,10 +19,14 @@ const mocks = vi.hoisted(() => ({
|
||||
vi.mock("./useDiscoveredLocalServers", () => ({
|
||||
useDiscoveredLocalServers: () => mocks.servers,
|
||||
}));
|
||||
vi.mock("./PreviewFaviconIcon", () => ({
|
||||
PreviewFaviconIcon: () => <span data-favicon-icon />,
|
||||
}));
|
||||
|
||||
import { PreviewEmptyState } from "./PreviewEmptyState";
|
||||
|
||||
const environmentId = EnvironmentId.make("env-1");
|
||||
const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
|
||||
|
||||
function server(port: number) {
|
||||
return {
|
||||
@@ -41,6 +45,7 @@ function server(port: number) {
|
||||
function render(recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>) {
|
||||
return renderToStaticMarkup(
|
||||
<PreviewEmptyState
|
||||
threadRef={threadRef}
|
||||
environmentId={environmentId}
|
||||
recentEntries={recentEntries}
|
||||
onRemoveRecent={() => undefined}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { Globe, History, RadioTower } from "lucide-react";
|
||||
|
||||
import type { BrowserHistoryEntry } from "~/browserHistoryStore";
|
||||
@@ -9,6 +9,7 @@ import { PreviewRecentUrlCard } from "./PreviewRecentUrlCard";
|
||||
import { useDiscoveredLocalServers } from "./useDiscoveredLocalServers";
|
||||
|
||||
interface Props {
|
||||
threadRef: ScopedThreadRef;
|
||||
environmentId: EnvironmentId;
|
||||
configuredUrls?: ReadonlyArray<string> | undefined;
|
||||
recentlySeenUrls?: ReadonlyArray<string> | undefined;
|
||||
@@ -18,6 +19,7 @@ interface Props {
|
||||
}
|
||||
|
||||
export function PreviewEmptyState({
|
||||
threadRef,
|
||||
environmentId,
|
||||
configuredUrls,
|
||||
recentlySeenUrls,
|
||||
@@ -60,6 +62,7 @@ export function PreviewEmptyState({
|
||||
{recents.map((entry) => (
|
||||
<PreviewRecentUrlCard
|
||||
key={entry.url}
|
||||
threadRef={threadRef}
|
||||
entry={entry}
|
||||
onOpen={() => onOpenUrl(entry.url)}
|
||||
onRemove={() => onRemoveRecent(entry.url)}
|
||||
@@ -78,6 +81,7 @@ export function PreviewEmptyState({
|
||||
{servers.map((server) => (
|
||||
<PreviewLocalServerCard
|
||||
key={`${server.host}:${server.port}`}
|
||||
threadRef={threadRef}
|
||||
server={server}
|
||||
onOpen={() => onOpenUrl(server.requestedUrl)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ favicon: null as string | null }));
|
||||
|
||||
vi.mock("~/browserFaviconStore", () => ({
|
||||
useFaviconForThreadUrl: () => mocks.favicon,
|
||||
}));
|
||||
|
||||
import { FaviconImage, PreviewFaviconIcon, selectFaviconSource } from "./PreviewFaviconIcon";
|
||||
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
|
||||
describe("preview favicon image", () => {
|
||||
it("renders a captured source before later fallback sources", () => {
|
||||
expect(
|
||||
renderToStaticMarkup(
|
||||
<FaviconImage
|
||||
sources={["data:image/png;base64,AAAA", "https://public.example/icon"]}
|
||||
fallback={<span>fallback</span>}
|
||||
/>,
|
||||
),
|
||||
).toContain('src="data:image/png;base64,AAAA"');
|
||||
const captured = "data:image/png;base64,AAAA";
|
||||
const google = "https://public.example/icon";
|
||||
expect(selectFaviconSource([captured, google], new Set())).toBe(captured);
|
||||
expect(selectFaviconSource([captured, google], new Set([captured]))).toBe(google);
|
||||
expect(selectFaviconSource([captured, google], new Set([captured, google]))).toBeNull();
|
||||
expect(selectFaviconSource(["data:image/png;base64,BBBB", google], new Set([captured]))).toBe(
|
||||
"data:image/png;base64,BBBB",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses a stored project icon or falls back to the browser mockup", () => {
|
||||
mocks.favicon = null;
|
||||
const html = renderToStaticMarkup(
|
||||
<PreviewFaviconIcon threadRef={threadRef} url="http://localhost:3000/" />,
|
||||
);
|
||||
expect(html).not.toContain("<img");
|
||||
expect(html).toContain("rounded-[5px]");
|
||||
mocks.favicon = "data:image/png;base64,AAAA";
|
||||
const faviconHtml = renderToStaticMarkup(
|
||||
<PreviewFaviconIcon threadRef={threadRef} url="http://localhost:3000/" />,
|
||||
);
|
||||
expect(faviconHtml).toContain('src="data:image/png;base64,AAAA"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { type ReactNode, useState } from "react";
|
||||
|
||||
import { useFaviconForThreadUrl } from "~/browserFaviconStore";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { BrowserMockup } from "./BrowserMockup";
|
||||
|
||||
export function selectFaviconSource(
|
||||
sources: ReadonlyArray<string>,
|
||||
failed: ReadonlySet<string>,
|
||||
): string | null {
|
||||
return sources.find((candidate) => !failed.has(candidate)) ?? null;
|
||||
}
|
||||
|
||||
export function FaviconImage(props: {
|
||||
sources: ReadonlyArray<string | null | undefined>;
|
||||
fallback: ReactNode;
|
||||
className?: string | undefined;
|
||||
}) {
|
||||
const sources = props.sources.filter((source): source is string => Boolean(source));
|
||||
return (
|
||||
<FaviconImageAttempt
|
||||
key={sources.join("\0")}
|
||||
sources={sources}
|
||||
fallback={props.fallback}
|
||||
className={props.className}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FaviconImageAttempt(props: {
|
||||
sources: ReadonlyArray<string>;
|
||||
fallback: ReactNode;
|
||||
className?: string | undefined;
|
||||
}) {
|
||||
const [failed, setFailed] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const source = selectFaviconSource(props.sources, failed);
|
||||
if (!source) return props.fallback;
|
||||
return (
|
||||
<img
|
||||
src={source}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
draggable={false}
|
||||
className={props.className}
|
||||
onError={() => setFailed((current) => new Set(current).add(source))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function PreviewFaviconIcon(props: {
|
||||
threadRef: ScopedThreadRef;
|
||||
url: string;
|
||||
className?: string | undefined;
|
||||
}) {
|
||||
const source = useFaviconForThreadUrl(props.threadRef, props.url);
|
||||
const fallback = <BrowserMockup className={cn("size-7 shrink-0", props.className)} />;
|
||||
return (
|
||||
<FaviconImage
|
||||
sources={[source]}
|
||||
fallback={fallback}
|
||||
className={cn("size-7 shrink-0 rounded object-contain", props.className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { BrowserMockup } from "./BrowserMockup";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
|
||||
import { PreviewFaviconIcon } from "./PreviewFaviconIcon";
|
||||
import type { PreviewableServer } from "./useDiscoveredLocalServers";
|
||||
|
||||
interface Props {
|
||||
threadRef: ScopedThreadRef;
|
||||
server: PreviewableServer;
|
||||
onOpen: () => void;
|
||||
}
|
||||
|
||||
export function PreviewLocalServerCard({ server, onOpen }: Props) {
|
||||
export function PreviewLocalServerCard({ threadRef, server, onOpen }: Props) {
|
||||
const subtitle = describeServer(server);
|
||||
return (
|
||||
<button
|
||||
@@ -14,7 +17,7 @@ export function PreviewLocalServerCard({ server, onOpen }: Props) {
|
||||
onClick={onOpen}
|
||||
className="group flex w-full items-center gap-3 px-3 py-3 text-left hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
|
||||
>
|
||||
<BrowserMockup className="size-7 shrink-0" />
|
||||
<PreviewFaviconIcon threadRef={threadRef} url={server.requestedUrl} />
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm font-medium text-foreground">{subtitle}</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
import { isValidHistoryTimestamp, type BrowserHistoryEntry } from "~/browserHistoryStore";
|
||||
import { useNowMinute } from "~/hooks/useNowMinute";
|
||||
import { formatRelativeTimeLabel } from "~/timestampFormat";
|
||||
|
||||
import { BrowserMockup } from "./BrowserMockup";
|
||||
import { PreviewFaviconIcon } from "./PreviewFaviconIcon";
|
||||
|
||||
interface Props {
|
||||
threadRef: ScopedThreadRef;
|
||||
entry: BrowserHistoryEntry;
|
||||
onOpen: () => void;
|
||||
onRemove: () => void;
|
||||
}
|
||||
|
||||
export function PreviewRecentUrlCard({ entry, onOpen, onRemove }: Props) {
|
||||
export function PreviewRecentUrlCard({ threadRef, entry, onOpen, onRemove }: Props) {
|
||||
const parsed = new URL(entry.url);
|
||||
const path = parsed.pathname === "/" ? "" : parsed.pathname;
|
||||
const label = `${parsed.host}${path}${parsed.search}${parsed.hash}`;
|
||||
@@ -27,7 +29,7 @@ export function PreviewRecentUrlCard({ entry, onOpen, onRemove }: Props) {
|
||||
onClick={onOpen}
|
||||
className="flex w-full items-center gap-3 px-3 py-3 pr-10 text-left hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
|
||||
>
|
||||
<BrowserMockup className="size-7 shrink-0" />
|
||||
<PreviewFaviconIcon threadRef={threadRef} url={entry.url} />
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm font-medium text-foreground">
|
||||
{entry.title ?? label}
|
||||
|
||||
@@ -710,6 +710,7 @@ export function PreviewView({
|
||||
) : null}
|
||||
{showEmptyState ? (
|
||||
<PreviewEmptyState
|
||||
threadRef={threadRef}
|
||||
environmentId={threadRef.environmentId}
|
||||
configuredUrls={configuredUrls}
|
||||
recentlySeenUrls={previewState.recentlySeenUrls}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { DesktopPreviewTabState } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { projectDesktopState } from "./usePreviewBridge";
|
||||
|
||||
const favicon = {
|
||||
dataUrl: "data:image/png;base64,AAAA",
|
||||
pageUrl: "http://localhost:3000/app",
|
||||
capturedAt: 1,
|
||||
};
|
||||
|
||||
function state(navStatus: DesktopPreviewTabState["navStatus"]): DesktopPreviewTabState {
|
||||
return {
|
||||
tabId: "tab-1",
|
||||
webContentsId: 1,
|
||||
navStatus,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: 1,
|
||||
pictureInPicture: false,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
favicon,
|
||||
updatedAt: "2026-08-09T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("projectDesktopState", () => {
|
||||
it("shows a retained icon only while the current document has the captured origin", () => {
|
||||
expect(
|
||||
projectDesktopState(
|
||||
state({ kind: "Loading", url: "http://localhost:3000/reload", title: "" }),
|
||||
).favicon,
|
||||
).toEqual(favicon);
|
||||
expect(
|
||||
projectDesktopState(
|
||||
state({
|
||||
kind: "LoadFailed",
|
||||
url: "https://example.com/",
|
||||
title: "",
|
||||
code: -105,
|
||||
description: "failed",
|
||||
}),
|
||||
).favicon,
|
||||
).toBeNull();
|
||||
expect(projectDesktopState(state({ kind: "Idle" })).favicon).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -6,15 +6,31 @@ import type {
|
||||
ScopedThreadRef,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import * as Option from "effect/Option";
|
||||
import { useEffect, useEffectEvent, useMemo, useRef } from "react";
|
||||
|
||||
import {
|
||||
flushPendingFaviconsForThread,
|
||||
recordFaviconForThread,
|
||||
useFaviconProjectRefForThread,
|
||||
} from "~/browserFaviconStore";
|
||||
import { useBrowserPointerStore } from "~/browser/browserPointerStore";
|
||||
import { applyPreviewDesktopState, type DesktopPreviewOverlay } from "~/previewStateStore";
|
||||
import { previewEnvironment } from "~/state/preview";
|
||||
import { usePreparedConnection } from "~/state/session";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
|
||||
function originOf(url: string): string | null {
|
||||
try {
|
||||
return new URL(url).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors low-latency desktop state into the store and reflects navigation
|
||||
* events back to the server. Webview lifetime is owned by ElectronBrowserHost.
|
||||
@@ -28,26 +44,36 @@ export function usePreviewBridge(input: {
|
||||
const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
|
||||
const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
|
||||
const bridge = previewBridge;
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const stableThreadRef = useMemo(() => {
|
||||
const parsed = parseScopedThreadKey(threadKey);
|
||||
if (!parsed) throw new Error(`Invalid scoped thread key: ${threadKey}`);
|
||||
return parsed;
|
||||
}, [threadKey]);
|
||||
const projectRef = useFaviconProjectRefForThread(stableThreadRef);
|
||||
const preparedConnection = usePreparedConnection(stableThreadRef.environmentId);
|
||||
const environmentHostname = Option.isSome(preparedConnection)
|
||||
? new URL(preparedConnection.value.httpBaseUrl).hostname
|
||||
: undefined;
|
||||
|
||||
// One bridge subscription does both jobs (mirror state + forward to
|
||||
// server) so the desktop bridge keeps a single listener entry per tab.
|
||||
const lastReportedUrl = useRef<string | null>(null);
|
||||
const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
|
||||
const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
|
||||
useEffect(() => {
|
||||
if (!bridge || typeof window === "undefined") return;
|
||||
lastReportedUrl.current = null;
|
||||
lastReportedKind.current = null;
|
||||
lastDesktopNavStatus.current = null;
|
||||
const unsubscribe = bridge.onStateChange((changedTabId, state) => {
|
||||
const handleStateChange = useEffectEvent(
|
||||
(changedTabId: string, state: DesktopPreviewTabState): void => {
|
||||
if (changedTabId !== runtimeTabId) return;
|
||||
if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
|
||||
clearBrowserPointer(runtimeTabId);
|
||||
}
|
||||
lastDesktopNavStatus.current = state.navStatus;
|
||||
applyPreviewDesktopState(threadRef, tabId, projectDesktopState(state));
|
||||
applyPreviewDesktopState(stableThreadRef, tabId, projectDesktopState(state));
|
||||
if (state.favicon) {
|
||||
recordFaviconForThread(stableThreadRef, state.favicon, projectRef, environmentHostname);
|
||||
}
|
||||
const reported = buildReportInput({
|
||||
threadId: threadRef.threadId,
|
||||
threadId: stableThreadRef.threadId,
|
||||
tabId,
|
||||
state,
|
||||
lastReportedUrl: lastReportedUrl.current,
|
||||
@@ -57,12 +83,22 @@ export function usePreviewBridge(input: {
|
||||
lastReportedUrl.current = reported.lastReportedUrl;
|
||||
lastReportedKind.current = reported.lastReportedKind;
|
||||
void reportStatus({
|
||||
environmentId: threadRef.environmentId,
|
||||
environmentId: stableThreadRef.environmentId,
|
||||
input: reported.input,
|
||||
});
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [bridge, clearBrowserPointer, reportStatus, runtimeTabId, tabId, threadRef]);
|
||||
},
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!bridge || typeof window === "undefined") return;
|
||||
lastReportedUrl.current = null;
|
||||
lastReportedKind.current = null;
|
||||
lastDesktopNavStatus.current = null;
|
||||
return bridge.onStateChange(handleStateChange);
|
||||
}, [bridge, runtimeTabId, stableThreadRef, tabId]);
|
||||
useEffect(() => {
|
||||
if (!projectRef) return;
|
||||
flushPendingFaviconsForThread(stableThreadRef, projectRef, environmentHostname);
|
||||
}, [environmentHostname, projectRef, stableThreadRef]);
|
||||
}
|
||||
|
||||
function shouldClearBrowserPointer(
|
||||
@@ -75,7 +111,8 @@ function shouldClearBrowserPointer(
|
||||
return current.url !== previous.url;
|
||||
}
|
||||
|
||||
function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
|
||||
export function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
|
||||
const navOrigin = state.navStatus.kind === "Idle" ? null : originOf(state.navStatus.url);
|
||||
return {
|
||||
hasWebContents: state.webContentsId !== null,
|
||||
canGoBack: state.canGoBack,
|
||||
@@ -85,6 +122,7 @@ function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverl
|
||||
pictureInPicture: state.pictureInPicture,
|
||||
colorScheme: state.colorScheme,
|
||||
controller: state.controller,
|
||||
favicon: state.favicon && originOf(state.favicon.pageUrl) === navOrigin ? state.favicon : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { faviconUrlForOrigin } from "./favicon";
|
||||
|
||||
describe("faviconUrlForOrigin", () => {
|
||||
it("never sends private origin hostnames to the public provider", () => {
|
||||
for (const url of [
|
||||
"http://localhost:3000/",
|
||||
"http://127.0.0.1:3000/",
|
||||
"http://0.0.0.0:3000/",
|
||||
"http://devbox:3000/",
|
||||
"https://24x.xf.local/",
|
||||
"http://printer.home.arpa/",
|
||||
"http://192.168.1.20:3000/",
|
||||
"http://[::]/",
|
||||
"http://[::ffff:192.168.1.20]/",
|
||||
"http://100.65.180.100:3000/",
|
||||
"https://devbox.example.ts.net/",
|
||||
"http://192.0.2.1/",
|
||||
"http://198.51.100.1/",
|
||||
"http://203.0.113.1/",
|
||||
"http://224.0.0.1/",
|
||||
"http://240.0.0.1/",
|
||||
"http://[2001:db8::1]/",
|
||||
"http://[ff02::1]/",
|
||||
"http://app.test../",
|
||||
"https://24x.xf.local../",
|
||||
"http://printer.home.arpa../",
|
||||
"https://devbox.example.ts.net../",
|
||||
"http://127.0.0.1../",
|
||||
"http://127.1../",
|
||||
"http://10.1../",
|
||||
"http://172.16.1../",
|
||||
"http://192.168.1../",
|
||||
]) {
|
||||
expect(faviconUrlForOrigin(url)).toBeNull();
|
||||
}
|
||||
expect(faviconUrlForOrigin("https://example.com/path", 32)).toBe(
|
||||
"https://www.google.com/s2/favicons?domain=example.com&sz=32",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isPublicFaviconHost } from "~/browser/browserTargetResolver";
|
||||
|
||||
/**
|
||||
* Favicon helpers for the preview tab strip.
|
||||
*
|
||||
@@ -13,6 +15,7 @@ export function faviconUrlForOrigin(rawUrl: string | null | undefined, size = 32
|
||||
const url = new URL(rawUrl);
|
||||
if (!url.host) return null;
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
||||
if (!isPublicFaviconHost(url.hostname)) return null;
|
||||
return `${FAVICON_PROVIDER}?domain=${encodeURIComponent(url.host)}&sz=${size}`;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -322,6 +322,7 @@ describe("previewStateStore (single-tab)", () => {
|
||||
pictureInPicture: false,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
favicon: null,
|
||||
});
|
||||
const state = readThreadPreviewState(ref);
|
||||
expect(state.desktopOverlay?.canGoBack).toBe(true);
|
||||
@@ -342,6 +343,7 @@ describe("previewStateStore (single-tab)", () => {
|
||||
pictureInPicture: false,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
favicon: null,
|
||||
});
|
||||
setActivePreviewTab(ref, first.tabId);
|
||||
|
||||
@@ -390,6 +392,7 @@ describe("previewStateStore (single-tab)", () => {
|
||||
pictureInPicture: false,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
favicon: null,
|
||||
});
|
||||
|
||||
reconcilePreviewServerSessions(ref, { sessions: [active], serverEpoch, revision: 1 });
|
||||
@@ -504,6 +507,7 @@ describe("previewStateStore (single-tab)", () => {
|
||||
pictureInPicture: false,
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
favicon: null,
|
||||
});
|
||||
const restarted = makeSnapshot({
|
||||
navStatus: { _tag: "Success", url: "https://new.example", title: "New" },
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
type DesktopPreviewColorScheme,
|
||||
type DesktopPreviewFavicon,
|
||||
type PreviewEvent,
|
||||
type PreviewListResult,
|
||||
type PreviewSessionSnapshot,
|
||||
@@ -28,6 +29,7 @@ export interface DesktopPreviewOverlay {
|
||||
pictureInPicture: boolean;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
favicon: DesktopPreviewFavicon | null;
|
||||
}
|
||||
|
||||
export interface ThreadPreviewState {
|
||||
|
||||
@@ -175,6 +175,7 @@ const PULL_REQUESTS_PANEL_ENVIRONMENT_ID = "pull-requests-panel" as EnvironmentI
|
||||
/** Stable so a read that is not wanted right now does not re-key on every render. */
|
||||
const NO_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> = [];
|
||||
const EMPTY_PREVIEW_SESSIONS = {};
|
||||
const EMPTY_PREVIEW_DESKTOP_STATE = {};
|
||||
const EMPTY_TERMINAL_LABELS = new Map<string, string>();
|
||||
const EMPTY_PENDING_SURFACES = new Set<string>();
|
||||
|
||||
@@ -1540,6 +1541,7 @@ function PullRequestsRouteView() {
|
||||
activeSurfaceId={activePullRequestSurface.id}
|
||||
pendingSurfaceIds={EMPTY_PENDING_SURFACES}
|
||||
previewSessions={EMPTY_PREVIEW_SESSIONS}
|
||||
desktopByTabId={EMPTY_PREVIEW_DESKTOP_STATE}
|
||||
terminalLabelsById={EMPTY_TERMINAL_LABELS}
|
||||
onActivate={(surface) => {
|
||||
if (surface.kind === "pull-request") activateSurface(surface);
|
||||
|
||||
@@ -524,6 +524,28 @@ export type DesktopPreviewColorScheme = "system" | "light" | "dark";
|
||||
export const DesktopPreviewColorSchemeSchema: Schema.Codec<DesktopPreviewColorScheme> =
|
||||
Schema.Literals(["system", "light", "dark"]);
|
||||
|
||||
export const FAVICON_DATA_URL_MAX_LENGTH = 8192;
|
||||
export const FAVICON_CAPTURED_AT_MAX = 8_640_000_000_000_000;
|
||||
|
||||
export interface DesktopPreviewFavicon {
|
||||
dataUrl: string;
|
||||
pageUrl: string;
|
||||
capturedAt: number;
|
||||
}
|
||||
|
||||
export const DesktopPreviewFaviconSchema: Schema.Codec<DesktopPreviewFavicon> = Schema.Struct({
|
||||
dataUrl: Schema.String.check(
|
||||
Schema.isMaxLength(FAVICON_DATA_URL_MAX_LENGTH),
|
||||
Schema.isPattern(/^data:image\/png;base64,[a-z0-9+/]+={0,2}$/i),
|
||||
),
|
||||
pageUrl: Schema.String.check(Schema.isMaxLength(2_048)),
|
||||
capturedAt: Schema.Number.check(
|
||||
Schema.isFinite(),
|
||||
Schema.isGreaterThanOrEqualTo(0),
|
||||
Schema.isLessThanOrEqualTo(FAVICON_CAPTURED_AT_MAX),
|
||||
),
|
||||
});
|
||||
|
||||
export interface DesktopPreviewTabState {
|
||||
tabId: string;
|
||||
webContentsId: number | null;
|
||||
@@ -536,6 +558,7 @@ export interface DesktopPreviewTabState {
|
||||
pictureInPicture: boolean;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
favicon?: DesktopPreviewFavicon;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -574,6 +597,7 @@ export const DesktopPreviewTabStateSchema: Schema.Codec<DesktopPreviewTabState>
|
||||
pictureInPicture: Schema.Boolean,
|
||||
colorScheme: DesktopPreviewColorSchemeSchema,
|
||||
controller: Schema.Literals(["human", "agent", "none"]),
|
||||
favicon: Schema.optionalKey(DesktopPreviewFaviconSchema),
|
||||
updatedAt: Schema.String,
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user