Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

fix icon resolution and link handling

Tw93612cc0d1871a
diff --git a/bin/options/icon.ts b/bin/options/icon.ts
index eb7da50e..19b3264d 100644
--- a/bin/options/icon.ts
+++ b/bin/options/icon.ts
@@ -9,7 +9,13 @@ import sharp from 'sharp';
import logger from './logger';
import { getSpinner } from '@/utils/info';
import { npmDirectory } from '@/utils/dir';
-import { IS_LINUX, IS_WIN, IS_MAC } from '@/utils/platform';
+import { IS_LINUX, IS_WIN } from '@/utils/platform';
+import {
+ generateDashboardIconSlugs,
+ getIconSourcePriority,
+ type IconSource,
+} from '@/utils/icon-source';
+import { generateLinuxPackageName, generateSafeFilename } from '@/utils/name';
import { PakeAppOptions } from '@/types';
import { writeIcoWithPreferredSize } from '@/utils/ico';
@@ -20,8 +26,15 @@ type PlatformIconConfig = {
};
const ICON_CONFIG = {
minFileSize: 100,
- supportedFormats: ['png', 'ico', 'jpeg', 'jpg', 'webp', 'icns'] as const,
- whiteBackground: { r: 255, g: 255, b: 255 },
+ supportedFormats: [
+ 'png',
+ 'ico',
+ 'jpeg',
+ 'jpg',
+ 'webp',
+ 'icns',
+ 'svg',
+ ] as const,
transparentBackground: { r: 255, g: 255, b: 255, alpha: 0 },
downloadTimeout: {
ci: 5000,
@@ -40,11 +53,11 @@ const API_KEYS = {
brandfetch: ['1idqvJC0CeFSeyp3Yf7', '1idej-yhU_ThggIHFyG'],
};
+type SupportedIconFormat = (typeof ICON_CONFIG.supportedFormats)[number];
+
/**
* Generates platform-specific icon paths and handles copying for Windows
*/
-import { generateLinuxPackageName, generateSafeFilename } from '@/utils/name';
-
function generateIconPath(appName: string, isDefault = false): string {
const safeName = isDefault ? 'icon' : getIconBaseName(appName);
const baseName = safeName;
@@ -95,32 +108,27 @@ async function copyWindowsIconIfNeeded(
}
/**
- * Adds white background to transparent icons only
+ * Normalizes icon inputs to PNG while preserving alpha.
*/
async function preprocessIcon(inputPath: string): Promise<string> {
try {
- const metadata = await sharp(inputPath).metadata();
- if (metadata.channels !== 4) return inputPath; // No transparency
+ const extension = path.extname(inputPath).toLowerCase();
+ const shouldNormalize = ['.png', '.jpeg', '.jpg', '.webp', '.svg'].includes(
+ extension,
+ );
+ if (!shouldNormalize) {
+ return inputPath;
+ }
const { path: tempDir } = await dir();
- const outputPath = path.join(tempDir, 'icon-with-background.png');
-
- await sharp({
- create: {
- width: metadata.width || 512,
- height: metadata.height || 512,
- channels: 4,
- background: { ...ICON_CONFIG.whiteBackground, alpha: 1 },
- },
- })
- .composite([{ input: inputPath }])
- .png()
- .toFile(outputPath);
+ const outputPath = path.join(tempDir, 'icon-normalized.png');
+
+ await sharp(inputPath).ensureAlpha().png().toFile(outputPath);
return outputPath;
} catch (error) {
if (error instanceof Error) {
- logger.warn(`Failed to add background to icon: ${error.message}`);
+ logger.warn(`Failed to normalize icon: ${error.message}`);
}
return inputPath;
}
@@ -405,17 +413,113 @@ function generateIconServiceUrls(domain: string): string[] {
*/
function generateDashboardIconUrls(appName: string): string[] {
const baseUrl = 'https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png';
- const name = appName.toLowerCase().trim();
- const slugs = new Set<string>();
+ return generateDashboardIconSlugs(appName).map(
+ (slug) => `${baseUrl}/${slug}.png`,
+ );
+}
+
+function isSupportedIconFormat(
+ extension: string,
+): extension is SupportedIconFormat {
+ return ICON_CONFIG.supportedFormats.includes(
+ extension as SupportedIconFormat,
+ );
+}
+
+function looksLikeSvg(arrayBuffer: ArrayBuffer): boolean {
+ const sample = Buffer.from(arrayBuffer)
+ .toString('utf-8', 0, Math.min(arrayBuffer.byteLength, 512))
+ .trimStart()
+ .toLowerCase();
+
+ return (
+ sample.startsWith('<svg') ||
+ (sample.startsWith('<?xml') && sample.includes('<svg'))
+ );
+}
+
+function getUrlExtension(iconUrl: string): string {
+ try {
+ return path.extname(new URL(iconUrl).pathname).slice(1).toLowerCase();
+ } catch {
+ return path.extname(iconUrl).slice(1).toLowerCase();
+ }
+}
- // Exact name
- slugs.add(name);
- // Replace spaces with hyphens
- slugs.add(name.replace(/\s+/g, '-'));
+async function detectDownloadedIconExtension(
+ response: Response,
+ arrayBuffer: ArrayBuffer,
+ iconUrl: string,
+): Promise<SupportedIconFormat | null> {
+ const fileDetails = await fileTypeFromBuffer(arrayBuffer);
+ if (fileDetails && isSupportedIconFormat(fileDetails.ext)) {
+ return fileDetails.ext;
+ }
- return [...slugs]
- .filter((s) => s.length > 0)
- .map((slug) => `${baseUrl}/${slug}.png`);
+ const contentType = response.headers
+ .get('content-type')
+ ?.split(';')[0]
+ .trim();
+ if (contentType === 'image/svg+xml' && looksLikeSvg(arrayBuffer)) {
+ return 'svg';
+ }
+
+ if (getUrlExtension(iconUrl) === 'svg' && looksLikeSvg(arrayBuffer)) {
+ return 'svg';
+ }
+
+ return null;
+}
+
+async function resolveIconFromUrl(
+ iconUrl: string,
+ appName: string,
+ downloadTimeout: number,
+): Promise<string | null> {
+ const iconPath = await downloadIcon(iconUrl, false, downloadTimeout);
+ if (!iconPath) {
+ return null;
+ }
+
+ const convertedPath = await convertIconFormat(iconPath, appName);
+ if (!convertedPath) {
+ return null;
+ }
+
+ return await copyWindowsIconIfNeeded(convertedPath, appName);
+}
+
+async function tryResolveIconSource(
+ source: IconSource,
+ domain: string,
+ appName: string,
+ downloadTimeout: number,
+): Promise<string | null> {
+ const iconUrls =
+ source === 'dashboard'
+ ? generateDashboardIconUrls(appName)
+ : generateIconServiceUrls(domain);
+
+ for (const iconUrl of iconUrls) {
+ try {
+ const resolvedPath = await resolveIconFromUrl(
+ iconUrl,
+ appName,
+ downloadTimeout,
+ );
+ if (resolvedPath) {
+ return resolvedPath;
+ }
+ } catch (error: unknown) {
+ if (error instanceof Error) {
+ const label =
+ source === 'dashboard' ? 'Dashboard icon' : 'Icon service';
+ logger.debug(`${label} ${iconUrl} failed: ${error.message}`);
+ }
+ }
+ }
+
+ return null;
}
/**
@@ -435,65 +539,26 @@ async function tryGetFavicon(
? ICON_CONFIG.downloadTimeout.ci
: ICON_CONFIG.downloadTimeout.default;
- const serviceUrls = generateIconServiceUrls(domain);
-
- for (const serviceUrl of serviceUrls) {
- try {
- const faviconPath = await downloadIcon(
- serviceUrl,
- false,
- downloadTimeout,
- );
- if (!faviconPath) continue;
-
- const convertedPath = await convertIconFormat(faviconPath, appName);
- if (convertedPath) {
- const finalPath = await copyWindowsIconIfNeeded(
- convertedPath,
- appName,
- );
- spinner.succeed(
- chalk.green('Icon fetched and converted successfully!'),
- );
- return finalPath;
- }
- } catch (error: unknown) {
- if (error instanceof Error) {
- logger.debug(`Icon service ${serviceUrl} failed: ${error.message}`);
- }
+ const sourcePriority = getIconSourcePriority(url, appName);
+ for (const source of sourcePriority) {
+ const resolvedIconPath = await tryResolveIconSource(
+ source,
+ domain,
+ appName,
+ downloadTimeout,
+ );
+ if (!resolvedIconPath) {
continue;
}
- }
- // Final fallback for selfhosted apps behind auth where domain-based
- // services cannot access the site favicon.
- if (appName) {
- const dashboardIconUrls = generateDashboardIconUrls(appName);
- for (const iconUrl of dashboardIconUrls) {
- try {
- const iconPath = await downloadIcon(iconUrl, false, downloadTimeout);
- if (!iconPath) continue;
-
- const convertedPath = await convertIconFormat(iconPath, appName);
- if (convertedPath) {
- const finalPath = await copyWindowsIconIfNeeded(
- convertedPath,
- appName,
- );
- spinner.succeed(
- chalk.green(
- `Icon found via dashboard-icons fallback for "${appName}"!`,
- ),
- );
- return finalPath;
- }
- } catch (error: unknown) {
- if (error instanceof Error) {
- logger.debug(`Dashboard icon ${iconUrl} failed: ${error.message}`);
- }
- continue;
- }
- }
+ spinner.succeed(
+ chalk.green(
+ source === 'dashboard'
+ ? `Icon found via dashboard-icons for "${appName}"!`
+ : 'Icon fetched and converted successfully!',
+ ),
+ );
+ return resolvedIconPath;
}
spinner.warn(`No favicon found for ${domain}. Using default.`);
@@ -538,15 +603,16 @@ export async function downloadIcon(
if (!arrayBuffer || arrayBuffer.byteLength < ICON_CONFIG.minFileSize)
return null;
- const fileDetails = await fileTypeFromBuffer(arrayBuffer);
- if (
- !fileDetails ||
- !ICON_CONFIG.supportedFormats.includes(fileDetails.ext as any)
- ) {
+ const extension = await detectDownloadedIconExtension(
+ response,
+ arrayBuffer,
+ iconUrl,
+ );
+ if (!extension) {
return null;
}
- return await saveIconFile(arrayBuffer, fileDetails.ext);
+ return await saveIconFile(arrayBuffer, extension);
} catch (error: unknown) {
clearTimeout(timeoutId);
if (showSpinner) {
diff --git a/bin/utils/icon-source.ts b/bin/utils/icon-source.ts
new file mode 100644
index 00000000..64cd1876
--- /dev/null
+++ b/bin/utils/icon-source.ts
@@ -0,0 +1,109 @@
+import * as psl from 'psl';
+
+export type IconSource = 'dashboard' | 'domain';
+
+const LOCAL_HOST_SUFFIXES = [
+ '.local',
+ '.lan',
+ '.internal',
+ '.home',
+ '.localdomain',
+] as const;
+
+const IPV4_ADDRESS_PATTERN = /^(\d{1,3}\.){3}\d{1,3}$/;
+
+function normalize(value: string): string {
+ return value.trim().toLowerCase();
+}
+
+function simplify(value: string): string {
+ return normalize(value).replace(/[\s._-]+/g, '');
+}
+
+export function generateDashboardIconSlugs(appName: string): string[] {
+ const normalizedName = normalize(appName);
+ if (!normalizedName) {
+ return [];
+ }
+
+ const slugs = new Set<string>([
+ normalizedName,
+ normalizedName.replace(/\s+/g, '-'),
+ ]);
+
+ return [...slugs].filter(Boolean);
+}
+
+export function isLikelyLocalHostname(hostname: string): boolean {
+ const normalizedHostname = normalize(hostname);
+ if (!normalizedHostname) {
+ return false;
+ }
+
+ return (
+ normalizedHostname === 'localhost' ||
+ IPV4_ADDRESS_PATTERN.test(normalizedHostname) ||
+ normalizedHostname.includes(':') ||
+ !normalizedHostname.includes('.') ||
+ LOCAL_HOST_SUFFIXES.some((suffix) => normalizedHostname.endsWith(suffix))
+ );
+}
+
+export function shouldPreferDashboardIcons(
+ url: string,
+ appName: string,
+): boolean {
+ if (!appName) {
+ return false;
+ }
+
+ try {
+ const hostname = new URL(url).hostname.toLowerCase();
+ if (!hostname) {
+ return false;
+ }
+
+ if (isLikelyLocalHostname(hostname)) {
+ return true;
+ }
+
+ const parsed = psl.parse(hostname);
+ if (!('domain' in parsed) || !parsed.domain) {
+ return true;
+ }
+
+ const registrableDomain = parsed.domain.toLowerCase();
+ if (hostname === registrableDomain) {
+ return false;
+ }
+
+ const subdomain =
+ 'subdomain' in parsed && typeof parsed.subdomain === 'string'
+ ? parsed.subdomain
+ : '';
+ if (!subdomain) {
+ return false;
+ }
+
+ const productLabel = subdomain.split('.').pop() || '';
+ const rootLabel = registrableDomain.split('.')[0] || '';
+ const normalizedAppName = simplify(appName);
+
+ return (
+ normalizedAppName.length > 0 &&
+ simplify(productLabel) === normalizedAppName &&
+ simplify(rootLabel) !== normalizedAppName
+ );
+ } catch {
+ return false;
+ }
+}
+
+export function getIconSourcePriority(
+ url: string,
+ appName: string,
+): IconSource[] {
+ return shouldPreferDashboardIcons(url, appName)
+ ? ['dashboard', 'domain']
+ : ['domain', 'dashboard'];
+}
diff --git a/dist/cli.js b/dist/cli.js
index 1a8ce3c4..3469c7f3 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -1470,6 +1470,85 @@ class BuilderProvider {
}
}
+const LOCAL_HOST_SUFFIXES = [
+ '.local',
+ '.lan',
+ '.internal',
+ '.home',
+ '.localdomain',
+];
+const IPV4_ADDRESS_PATTERN = /^(\d{1,3}\.){3}\d{1,3}$/;
+function normalize(value) {
+ return value.trim().toLowerCase();
+}
+function simplify(value) {
+ return normalize(value).replace(/[\s._-]+/g, '');
+}
+function generateDashboardIconSlugs(appName) {
+ const normalizedName = normalize(appName);
+ if (!normalizedName) {
+ return [];
+ }
+ const slugs = new Set([
+ normalizedName,
+ normalizedName.replace(/\s+/g, '-'),
+ ]);
+ return [...slugs].filter(Boolean);
+}
+function isLikelyLocalHostname(hostname) {
+ const normalizedHostname = normalize(hostname);
+ if (!normalizedHostname) {
+ return false;
+ }
+ return (normalizedHostname === 'localhost' ||
+ IPV4_ADDRESS_PATTERN.test(normalizedHostname) ||
+ normalizedHostname.includes(':') ||
+ !normalizedHostname.includes('.') ||
+ LOCAL_HOST_SUFFIXES.some((suffix) => normalizedHostname.endsWith(suffix)));
+}
+function shouldPreferDashboardIcons(url, appName) {
+ if (!appName) {
+ return false;
+ }
+ try {
+ const hostname = new URL(url).hostname.toLowerCase();
+ if (!hostname) {
+ return false;
+ }
+ if (isLikelyLocalHostname(hostname)) {
+ return true;
+ }
+ const parsed = psl.parse(hostname);
+ if (!('domain' in parsed) || !parsed.domain) {
+ return true;
+ }
+ const registrableDomain = parsed.domain.toLowerCase();
+ if (hostname === registrableDomain) {
+ return false;
+ }
+ const subdomain = 'subdomain' in parsed && typeof parsed.subdomain === 'string'
+ ? parsed.subdomain
+ : '';
+ if (!subdomain) {
+ return false;
+ }
+ const productLabel = subdomain.split('.').pop() || '';
+ const rootLabel = registrableDomain.split('.')[0] || '';
+ const normalizedAppName = simplify(appName);
+ return (normalizedAppName.length > 0 &&
+ simplify(productLabel) === normalizedAppName &&
+ simplify(rootLabel) !== normalizedAppName);
+ }
+ catch {
+ return false;
+ }
+}
+function getIconSourcePriority(url, appName) {
+ return shouldPreferDashboardIcons(url, appName)
+ ? ['dashboard', 'domain']
+ : ['domain', 'dashboard'];
+}
+
const ICO_HEADER_SIZE = 6;
const ICO_DIR_ENTRY_SIZE = 16;
const ICO_TYPE_ICON = 1;
@@ -1574,8 +1653,7 @@ async function writeIcoWithPreferredSize(sourcePath, outputPath, preferredSize)
const ICON_CONFIG = {
minFileSize: 100,
- supportedFormats: ['png', 'ico', 'jpeg', 'jpg', 'webp', 'icns'],
- whiteBackground: { r: 255, g: 255, b: 255 },
+ supportedFormats: ['png', 'ico', 'jpeg', 'jpg', 'webp', 'icns', 'svg'],
transparentBackground: { r: 255, g: 255, b: 255, alpha: 0 },
downloadTimeout: {
ci: 5000,
@@ -1591,6 +1669,9 @@ const API_KEYS = {
logoDev: ['pk_JLLMUKGZRpaG5YclhXaTkg', 'pk_Ph745P8mQSeYFfW2Wk039A'],
brandfetch: ['1idqvJC0CeFSeyp3Yf7', '1idej-yhU_ThggIHFyG'],
};
+/**
+ * Generates platform-specific icon paths and handles copying for Windows
+ */
function generateIconPath(appName, isDefault = false) {
const safeName = isDefault ? 'icon' : getIconBaseName(appName);
const baseName = safeName;
@@ -1628,31 +1709,23 @@ async function copyWindowsIconIfNeeded(convertedPath, appName) {
}
}
/**
- * Adds white background to transparent icons only
+ * Normalizes icon inputs to PNG while preserving alpha.
*/
async function preprocessIcon(inputPath) {
try {
- const metadata = await sharp(inputPath).metadata();
- if (metadata.channels !== 4)
- return inputPath; // No transparency
+ const extension = path.extname(inputPath).toLowerCase();
+ const shouldNormalize = ['.png', '.jpeg', '.jpg', '.webp', '.svg'].includes(extension);
+ if (!shouldNormalize) {
+ return inputPath;
+ }
const { path: tempDir } = await dir();
- const outputPath = path.join(tempDir, 'icon-with-background.png');
- await sharp({
- create: {
- width: metadata.width || 512,
- height: metadata.height || 512,
- channels: 4,
- background: { ...ICON_CONFIG.whiteBackground, alpha: 1 },
- },
- })
- .composite([{ input: inputPath }])
- .png()
- .toFile(outputPath);
+ const outputPath = path.join(tempDir, 'icon-normalized.png');
+ await sharp(inputPath).ensureAlpha().png().toFile(outputPath);
return outputPath;
}
catch (error) {
if (error instanceof Error) {
- logger.warn(`Failed to add background to icon: ${error.message}`);
+ logger.warn(`Failed to normalize icon: ${error.message}`);
}
return inputPath;
}
@@ -1882,15 +1955,71 @@ function generateIconServiceUrls(domain) {
*/
function generateDashboardIconUrls(appName) {
const baseUrl = 'https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png';
- const name = appName.toLowerCase().trim();
- const slugs = new Set();
- // Exact name
- slugs.add(name);
- // Replace spaces with hyphens
- slugs.add(name.replace(/\s+/g, '-'));
- return [...slugs]
- .filter((s) => s.length > 0)
- .map((slug) => `${baseUrl}/${slug}.png`);
+ return generateDashboardIconSlugs(appName).map((slug) => `${baseUrl}/${slug}.png`);
+}
+function isSupportedIconFormat(extension) {
+ return ICON_CONFIG.supportedFormats.includes(extension);
+}
+function looksLikeSvg(arrayBuffer) {
+ const sample = Buffer.from(arrayBuffer)
+ .toString('utf-8', 0, Math.min(arrayBuffer.byteLength, 512))
+ .trimStart()
+ .toLowerCase();
+ return (sample.startsWith('<svg') ||
+ (sample.startsWith('<?xml') && sample.includes('<svg')));
+}
+function getUrlExtension(iconUrl) {
+ try {
+ return path.extname(new URL(iconUrl).pathname).slice(1).toLowerCase();
+ }
+ catch {
+ return path.extname(iconUrl).slice(1).toLowerCase();
+ }
+}
+async function detectDownloadedIconExtension(response, arrayBuffer, iconUrl) {
+ const fileDetails = await fileTypeFromBuffer(arrayBuffer);
+ if (fileDetails && isSupportedIconFormat(fileDetails.ext)) {
+ return fileDetails.ext;
+ }
+ const contentType = response.headers.get('content-type')?.split(';')[0].trim();
+ if (contentType === 'image/svg+xml' && looksLikeSvg(arrayBuffer)) {
+ return 'svg';
+ }
+ if (getUrlExtension(iconUrl) === 'svg' && looksLikeSvg(arrayBuffer)) {
+ return 'svg';
+ }
+ return null;
+}
+async function resolveIconFromUrl(iconUrl, appName, downloadTimeout) {
+ const iconPath = await downloadIcon(iconUrl, false, downloadTimeout);
+ if (!iconPath) {
+ return null;
+ }
+ const convertedPath = await convertIconFormat(iconPath, appName);
+ if (!convertedPath) {
+ return null;
+ }
+ return await copyWindowsIconIfNeeded(convertedPath, appName);
+}
+async function tryResolveIconSource(source, domain, appName, downloadTimeout) {
+ const iconUrls = source === 'dashboard'
+ ? generateDashboardIconUrls(appName)
+ : generateIconServiceUrls(domain);
+ for (const iconUrl of iconUrls) {
+ try {
+ const resolvedPath = await resolveIconFromUrl(iconUrl, appName, downloadTimeout);
+ if (resolvedPath) {
+ return resolvedPath;
+ }
+ }
+ catch (error) {
+ if (error instanceof Error) {
+ const label = source === 'dashboard' ? 'Dashboard icon' : 'Icon service';
+ logger.debug(`${label} ${iconUrl} failed: ${error.message}`);
+ }
+ }
+ }
+ return null;
}
/**
* Attempts to fetch favicon from website
@@ -1903,49 +2032,16 @@ async function tryGetFavicon(url, appName) {
const downloadTimeout = isCI
? ICON_CONFIG.downloadTimeout.ci
: ICON_CONFIG.downloadTimeout.default;
- const serviceUrls = generateIconServiceUrls(domain);
- for (const serviceUrl of serviceUrls) {
- try {
- const faviconPath = await downloadIcon(serviceUrl, false, downloadTimeout);
- if (!faviconPath)
- continue;
- const convertedPath = await convertIconFormat(faviconPath, appName);
- if (convertedPath) {
- const finalPath = await copyWindowsIconIfNeeded(convertedPath, appName);
- spinner.succeed(chalk.green('Icon fetched and converted successfully!'));
- return finalPath;
- }
- }
- catch (error) {
- if (error instanceof Error) {
- logger.debug(`Icon service ${serviceUrl} failed: ${error.message}`);
- }
+ const sourcePriority = getIconSourcePriority(url, appName);
+ for (const source of sourcePriority) {
+ const resolvedIconPath = await tryResolveIconSource(source, domain, appName, downloadTimeout);
+ if (!resolvedIconPath) {
continue;
}
- }
- // Final fallback for selfhosted apps behind auth where domain-based
- // services cannot access the site favicon.
- if (appName) {
- const dashboardIconUrls = generateDashboardIconUrls(appName);
- for (const iconUrl of dashboardIconUrls) {
- try {
- const iconPath = await downloadIcon(iconUrl, false, downloadTimeout);
- if (!iconPath)
- continue;
- const convertedPath = await convertIconFormat(iconPath, appName);
- if (convertedPath) {
- const finalPath = await copyWindowsIconIfNeeded(convertedPath, appName);
- spinner.succeed(chalk.green(`Icon found via dashboard-icons fallback for "${appName}"!`));
- return finalPath;
- }
- }
- catch (error) {
- if (error instanceof Error) {
- logger.debug(`Dashboard icon ${iconUrl} failed: ${error.message}`);
- }
- continue;
- }
- }
+ spinner.succeed(chalk.green(source === 'dashboard'
+ ? `Icon found via dashboard-icons for "${appName}"!`
+ : 'Icon fetched and converted successfully!'));
+ return resolvedIconPath;
}
spinner.warn(`No favicon found for ${domain}. Using default.`);
return null;
@@ -1979,12 +2075,11 @@ async function downloadIcon(iconUrl, showSpinner = true, customTimeout) {
const arrayBuffer = await response.arrayBuffer();
if (!arrayBuffer || arrayBuffer.byteLength < ICON_CONFIG.minFileSize)
return null;
- const fileDetails = await fileTypeFromBuffer(arrayBuffer);
- if (!fileDetails ||
- !ICON_CONFIG.supportedFormats.includes(fileDetails.ext)) {
+ const extension = await detectDownloadedIconExtension(response, arrayBuffer, iconUrl);
+ if (!extension) {
return null;
}
- return await saveIconFile(arrayBuffer, fileDetails.ext);
+ return await saveIconFile(arrayBuffer, extension);
}
catch (error) {
clearTimeout(timeoutId);
diff --git a/src-tauri/src/inject/event.js b/src-tauri/src/inject/event.js
index 0f57103f..3472ab1d 100644
--- a/src-tauri/src/inject/event.js
+++ b/src-tauri/src/inject/event.js
@@ -257,6 +257,21 @@ function isDownloadableFile(url) {
}
}
+function normalizeAnchorHref(rawHref) {
+ return typeof rawHref === "string" ? rawHref.trim() : "";
+}
+
+function shouldBypassPakeLinkHandling(rawHref) {
+ const normalizedHref = normalizeAnchorHref(rawHref).toLowerCase();
+ if (!normalizedHref) {
+ return false;
+ }
+
+ return (
+ normalizedHref.startsWith("javascript:") || normalizedHref.startsWith("#")
+ );
+}
+
document.addEventListener("DOMContentLoaded", () => {
const tauri = window.__TAURI__;
const appWindow = tauri.window.getCurrentWindow();
@@ -506,6 +521,11 @@ document.addEventListener("DOMContentLoaded", () => {
const anchorElement = e.target.closest("a");
if (anchorElement && anchorElement.href) {
+ const rawHref = anchorElement.getAttribute("href") || "";
+ if (shouldBypassPakeLinkHandling(rawHref)) {
+ return;
+ }
+
const target = anchorElement.target;
const hrefUrl = new URL(anchorElement.href);
const absoluteUrl = hrefUrl.href;
@@ -611,6 +631,16 @@ document.addEventListener("DOMContentLoaded", () => {
// Rewrite the window.open function.
const originalWindowOpen = window.open;
window.open = function (url, name, specs) {
+ const normalizedUrl = normalizeAnchorHref(url);
+ if (normalizedUrl.startsWith("#")) {
+ window.location.href = new URL(normalizedUrl, window.location.href).href;
+ return window;
+ }
+
+ if (shouldBypassPakeLinkHandling(url)) {
+ return originalWindowOpen.call(window, url, name, specs);
+ }
+
// Allow authentication popups to open normally
if (window.isAuthPopup(url, name)) {
return originalWindowOpen.call(window, url, name, specs);
diff --git a/tests/unit/event-link-guard.test.js b/tests/unit/event-link-guard.test.js
new file mode 100644
index 00000000..ff0fc31e
--- /dev/null
+++ b/tests/unit/event-link-guard.test.js
@@ -0,0 +1,74 @@
+import fs from "fs";
+import path from "path";
+import { runInNewContext } from "node:vm";
+import { describe, expect, it } from "vitest";
+
+function loadEventHelpers() {
+ const source = fs.readFileSync(
+ path.join(process.cwd(), "src-tauri/src/inject/event.js"),
+ "utf-8",
+ );
+
+ const context = {
+ console,
+ URL,
+ Event: class {},
+ Notification: function Notification() {},
+ setTimeout,
+ clearTimeout,
+ scrollTo: () => {},
+ navigator: {
+ userAgent: "Mozilla/5.0",
+ language: "en-US",
+ },
+ window: {
+ history: {
+ back: () => {},
+ forward: () => {},
+ },
+ location: {
+ href: "https://example.com/app",
+ reload: () => {},
+ },
+ localStorage: {
+ getItem: () => null,
+ setItem: () => {},
+ },
+ dispatchEvent: () => {},
+ },
+ document: {
+ addEventListener: () => {},
+ getElementsByTagName: () => [{ style: {} }],
+ body: {
+ style: {},
+ scrollHeight: 0,
+ },
+ execCommand: () => {},
+ },
+ };
+
+ runInNewContext(source, context);
+ return context;
+}
+
+describe("event link guard", () => {
+ it("bypasses javascript pseudo-links", () => {
+ const { shouldBypassPakeLinkHandling } = loadEventHelpers();
+
+ expect(shouldBypassPakeLinkHandling("javascript:void(0)")).toBe(true);
+ });
+
+ it("bypasses hash-only anchors", () => {
+ const { shouldBypassPakeLinkHandling } = loadEventHelpers();
+
+ expect(shouldBypassPakeLinkHandling("#captcha-confirm")).toBe(true);
+ });
+
+ it("keeps normal navigations under Pake handling", () => {
+ const { shouldBypassPakeLinkHandling } = loadEventHelpers();
+
+ expect(shouldBypassPakeLinkHandling("https://example.com/account")).toBe(
+ false,
+ );
+ });
+});
diff --git a/tests/unit/icon.test.ts b/tests/unit/icon.test.ts
new file mode 100644
index 00000000..3ee9df4f
--- /dev/null
+++ b/tests/unit/icon.test.ts
@@ -0,0 +1,119 @@
+import fs from 'fs';
+import path from 'path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { downloadIcon } from '@/options/icon';
+import { getIconSourcePriority } from '@/utils/icon-source';
+
+const downloadedIconPaths: string[] = [];
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+
+ while (downloadedIconPaths.length > 0) {
+ const iconPath = downloadedIconPaths.pop();
+ if (!iconPath) {
+ continue;
+ }
+
+ const tempDir = path.dirname(iconPath);
+ if (fs.existsSync(tempDir)) {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ }
+ }
+});
+
+describe('icon source priority', () => {
+ it('prefers dashboard-icons for matching public subdomain products', () => {
+ expect(
+ getIconSourcePriority('https://notebooklm.google.com/', 'NotebookLM'),
+ ).toEqual(['dashboard', 'domain']);
+ });
+
+ it('prefers dashboard-icons for local or self-hosted hosts', () => {
+ expect(
+ getIconSourcePriority('https://grafana.mylab.local/', 'Grafana'),
+ ).toEqual(['dashboard', 'domain']);
+ });
+
+ it('keeps domain-first lookup for public root domains', () => {
+ expect(getIconSourcePriority('https://github.com/', 'GitHub')).toEqual([
+ 'domain',
+ 'dashboard',
+ ]);
+ });
+});
+
+describe('downloadIcon', () => {
+ it('accepts svg icons when the response advertises image/svg+xml', async () => {
+ const svg = `
+ <svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
+ <rect width="128" height="128" rx="24" fill="#0f172a" />
+ <circle cx="64" cy="64" r="36" fill="#38bdf8" />
+ </svg>
+ `;
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ headers: {
+ get: (name: string) =>
+ name === 'content-type' ? 'image/svg+xml; charset=utf-8' : null,
+ },
+ arrayBuffer: async () => new TextEncoder().encode(svg).buffer,
+ }),
+ );
+
+ const iconPath = await downloadIcon(
+ 'https://cdn.example.com/icons/notebooklm.svg',
+ false,
+ 1000,
+ );
+
+ expect(iconPath).toBeTruthy();
+ expect(iconPath?.endsWith('.svg')).toBe(true);
+
+ if (iconPath) {
+ downloadedIconPaths.push(iconPath);
+ expect(fs.existsSync(iconPath)).toBe(true);
+ expect(fs.readFileSync(iconPath, 'utf-8')).toContain('<svg');
+ }
+ });
+
+ it('rejects html responses that only contain inline svg markup', async () => {
+ const html = `
+ <!doctype html>
+ <html>
+ <body>
+ <svg viewBox="0 0 16 16"></svg>
+ </body>
+ </html>
+ `;
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ headers: {
+ get: (name: string) =>
+ name === 'content-type' ? 'text/html; charset=utf-8' : null,
+ },
+ arrayBuffer: async () => new TextEncoder().encode(html).buffer,
+ }),
+ );
+
+ await expect(
+ downloadIcon(
+ 'https://cdn.example.com/icons/not-an-icon.svg',
+ false,
+ 1000,
+ ),
+ ).resolves.toBeNull();
+ });
+});