Files
raucao b057e3edca Add custom site links with icon discovery and upload
Users can add any website as a dashboard quick link from Settings → Site
Links. The link is stored in the integrations namespace as a `custom`
type so it flows through the existing sites/integrations/settings
pipeline, and appears in a new "Links" group.

Its icon is discovered with the existing favicon pipeline; an uploaded
icon overrides it and stays pinned until the user chooses "Use site's
icon" again. resolveIcons and refreshIcon skip pinned sites (and
re-check the live list before writing back) so an in-flight discovery
can never clobber a freshly uploaded icon.

URLs are normalized to http(s) only, with embedded credentials stripped,
so a value can never reach an anchor's href as javascript:/data:.
Uploads are validated, size-capped and downscaled to 192px (SVGs kept
as-is), and only ever rendered through an <img>.

Adds app/utils/site-url.js and app/utils/image-file.js, a custom-link
form, a `custom` registry entry/group and adapter, and tests.
2026-11-13 15:57:57 +04:00

462 lines
13 KiB
JavaScript

import Service, { service } from '@ember/service';
import { readIconFile } from '../utils/image-file';
// Icons rarely change, so a week-old record is good enough until we lazily
// revalidate it in the background.
export const SITE_ICON_TTL = 7 * 24 * 60 * 60 * 1000;
// The dashboard tiles render around 56px, so aim for something crisp on
// higher-density displays without pulling down 1024px art.
export const SITE_ICON_TARGET_SIZE = 192;
export function normalizeOrigin(value) {
if (!value) {
return null;
}
try {
return new URL(value).origin;
} catch {
return null;
}
}
function resolveUrl(href, base) {
try {
return new URL(href, base).href;
} catch {
return null;
}
}
function parseWidth(sizes) {
const match = /(\d+)x(\d+)/.exec(sizes ?? '');
// "any" (usually SVG) has no intrinsic size.
if (!match) {
return 0;
}
return Number(match[1]);
}
function relTokens(link) {
return (link.getAttribute('rel') ?? '').toLowerCase().split(/\s+/);
}
function candidateScore(candidate, target) {
let score = 0;
// A maskable icon is authored for a safe area, which is exactly what our
// rounded-square tile needs, so it outranks everything else.
if (candidate.maskable) {
score += 1000;
}
if (candidate.type === 'image/svg+xml') {
score += 400;
}
if (candidate.rel === 'apple-touch-icon') {
score += 200;
} else if (candidate.rel === 'icon') {
score += 50;
}
const width = candidate.width ?? 0;
if (width === 0) {
score += candidate.type === 'image/svg+xml' ? 100 : 0;
} else if (width >= target) {
score += 200 - Math.min(width - target, 300) / 5;
} else {
score += width / 4;
}
return score;
}
function isImageMime(type) {
return typeof type === 'string' && type.toLowerCase().startsWith('image/');
}
// A server answering 200 with an error/challenge page (or a CDN response with no
// content type) must not be mistaken for an icon: an `<img>` pointed at a
// non-image data URL fails silently, with no console error or network request.
function imageMime(...types) {
for (const type of types) {
if (isImageMime(type)) {
return type;
}
}
return null;
}
// Determine the MIME type to store for a fetched icon. A declared image type
// wins; a missing or generic binary content type falls back to what the
// candidate declared, but an explicit non-image type (e.g. `text/html`) is
// rejected so an error or challenge page is never mistaken for an icon.
function resolveIconMime(responseType, candidateType) {
if (isImageMime(responseType)) {
return responseType;
}
if (!responseType || responseType === 'application/octet-stream') {
return imageMime(candidateType);
}
return null;
}
function dataUrlMime(dataUrl) {
const match = /^data:([^;,]+)/i.exec(dataUrl ?? '');
return match ? match[1].toLowerCase() : null;
}
// An empty response body (a 204 from `/favicon.ico`, say) can still be stamped
// with the candidate's declared type, yielding `data:image/x-icon;base64,`:
// an image MIME with no bytes behind it.
function dataUrlHasContent(dataUrl) {
const comma = typeof dataUrl === 'string' ? dataUrl.indexOf(',') : -1;
return comma >= 0 && comma < dataUrl.length - 1;
}
function startsWithBytes(bytes, signature, offset = 0) {
return signature.every((byte, i) => bytes[offset + i] === byte);
}
function headerText(bytes) {
return new TextDecoder()
.decode(bytes.subarray(0, 256))
.trimStart()
.toLowerCase();
}
// Identify an image from its leading bytes. Used when the response carries no
// usable content type (a CDN may serve `application/octet-stream`), so a real
// icon isn't discarded just because its MIME is generic.
function detectImageMime(bytes) {
if (
startsWithBytes(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
) {
return 'image/png';
}
if (startsWithBytes(bytes, [0xff, 0xd8, 0xff])) {
return 'image/jpeg';
}
if (startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38])) {
return 'image/gif';
}
if (
startsWithBytes(bytes, [0x52, 0x49, 0x46, 0x46]) &&
startsWithBytes(bytes, [0x57, 0x45, 0x42, 0x50], 8)
) {
return 'image/webp';
}
if (
startsWithBytes(bytes, [0x00, 0x00, 0x01, 0x00]) ||
startsWithBytes(bytes, [0x00, 0x00, 0x02, 0x00])
) {
return 'image/x-icon';
}
if (startsWithBytes(bytes, [0x42, 0x4d])) {
return 'image/bmp';
}
if (
startsWithBytes(bytes, [0x49, 0x49, 0x2a, 0x00]) ||
startsWithBytes(bytes, [0x4d, 0x4d, 0x00, 0x2a])
) {
return 'image/tiff';
}
if (startsWithBytes(bytes, [0x66, 0x74, 0x79, 0x70], 4)) {
const brand = new TextDecoder().decode(bytes.subarray(8, 12));
if (brand === 'avif' || brand === 'avis') {
return 'image/avif';
}
if (brand.startsWith('hei') || brand.startsWith('mif')) {
return 'image/heic';
}
}
const head = headerText(bytes);
if (
head.startsWith('<svg') ||
(head.startsWith('<?xml') && head.includes('<svg'))
) {
return 'image/svg+xml';
}
return null;
}
// Markup (an HTML login/challenge page, an XML error document) is a definitive
// non-image: it must be rejected even when a candidate declared an image type.
function looksLikeMarkup(bytes) {
const head = headerText(bytes);
return (
head.startsWith('<!doctype') ||
head.startsWith('<html') ||
head.startsWith('<?xml')
);
}
async function sniffImageMime(blob) {
const bytes = new Uint8Array(await blob.slice(0, 512).arrayBuffer());
return { mime: detectImageMime(bytes), markup: looksLikeMarkup(bytes) };
}
// True when a cached record holds decodable image bytes. The browser keys off
// the data URL's MIME, not `record.mime` (which can disagree: a response with no
// Content-Type yields `data:application/octet-stream;…` while the candidate's
// declared type was stamped on `mime`). Records whose rendered data URL isn't an
// image, or that carry no bytes at all, are treated as if they were never
// cached.
function isUsableIcon(record) {
return (
isImageMime(dataUrlMime(record?.dataUrl)) &&
dataUrlHasContent(record?.dataUrl)
);
}
function toDataUrl(blob, mime) {
// FileReader derives the data URL's MIME from the blob, so stamp the resolved
// type on a copy when the response arrived without a usable content type.
const source =
mime && mime !== blob.type ? new Blob([blob], { type: mime }) : blob;
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () =>
reject(reader.error ?? new Error('Unable to read icon'));
reader.readAsDataURL(source);
});
}
function fallbackCandidates(origin) {
return [
{
url: `${origin}/apple-touch-icon.png`,
rel: 'fallback',
type: 'image/png',
width: 0,
// Apple touch icons are authored for iOS's rounded-square mask, so the
// well-known path is treated the same as a declared one.
maskable: true,
},
{
url: `${origin}/favicon.ico`,
rel: 'fallback',
type: 'image/x-icon',
width: 0,
maskable: false,
},
];
}
export default class SiteIconsService extends Service {
@service storage;
@service http;
inFlight = new Map();
// Resolves a site's best icon, caching the bytes in IndexedDB. Returns
// `undefined` when nothing usable could be discovered. Always resolves;
// callers can render a fallback and should never need to catch.
async iconFor(urlOrOrigin, { refresh = false } = {}) {
const origin = normalizeOrigin(urlOrOrigin);
if (!origin) {
return undefined;
}
const cached = refresh ? null : await this.storage.get('icons', origin);
if (cached && !this.isStale(cached)) {
return cached;
}
// A record whose bytes aren't an image (e.g. an HTML error page that got
// cached) is treated as absent so it never renders as a broken tile.
const usableCached = cached && isUsableIcon(cached) ? cached : null;
if (this.inFlight.has(origin)) {
return usableCached ?? this.inFlight.get(origin);
}
const work = this.resolve(origin, cached);
this.inFlight.set(origin, work);
// Serve a stale-but-usable icon immediately while the refresh runs.
return usableCached ?? work;
}
async refresh(urlOrOrigin) {
return this.iconFor(urlOrOrigin, { refresh: true });
}
// Turns a user-uploaded image file into an icon record for storage. Kept on
// this service so the form has a single icon seam (and tests can stub it).
async iconFromFile(file, options) {
return readIconFile(file, options);
}
async resolve(origin, cached) {
try {
const { candidates, themeColor } = await this.discover(origin);
const usableCached = cached && isUsableIcon(cached) ? cached : undefined;
for (const candidate of candidates) {
try {
const blob = await this.http.requestBlob(candidate.url);
// A 204/empty response (some servers answer `/favicon.ico` this way)
// carries no icon. Without this guard the candidate's declared type
// would turn the empty body into `data:image/x-icon;base64,`, which
// looks like an image and gets cached and rendered as a blank tile.
if (blob.size === 0) {
continue;
}
// Trust the actual bytes first: a CDN serving `application/octet-stream`
// (or no content type) may still hand back a perfectly good icon, while
// an HTML/XML error page must always be rejected.
const sniffed = await sniffImageMime(blob);
const mime =
sniffed.mime ??
(sniffed.markup
? null
: resolveIconMime(blob.type, candidate.type));
if (!mime) {
continue;
}
const dataUrl = await toDataUrl(blob, mime);
const record = {
origin,
href: candidate.url,
dataUrl,
mime,
maskable: candidate.maskable,
width: candidate.width || null,
themeColor,
updatedAt: Date.now(),
};
await this.storage.set('icons', origin, record);
return record;
} catch {
// Try the next candidate.
}
}
return usableCached;
} catch {
return cached && isUsableIcon(cached) ? cached : undefined;
} finally {
this.inFlight.delete(origin);
}
}
async discover(origin) {
let html;
try {
html = await this.http.requestText(`${origin}/`);
} catch {
return { candidates: fallbackCandidates(origin), themeColor: null };
}
const doc = new DOMParser().parseFromString(html, 'text/html');
let themeColor =
doc
.querySelector('meta[name="theme-color"]')
?.getAttribute('content')
?.trim() || null;
const candidates = [];
for (const link of doc.querySelectorAll('link[rel]')) {
const rels = relTokens(link);
const isApple = rels.includes('apple-touch-icon');
const isIcon = rels.includes('icon');
if (!isApple && !isIcon) {
continue;
}
const href = link.getAttribute('href');
const url = href && resolveUrl(href, `${origin}/`);
if (!url) {
continue;
}
candidates.push({
url,
rel: isApple ? 'apple-touch-icon' : 'icon',
type: link.getAttribute('type') || null,
width: parseWidth(link.getAttribute('sizes')),
// iOS renders touch icons inside a rounded-square mask, so they're
// already shaped for our tile and can safely render full-bleed.
maskable: isApple,
});
}
const manifestHref = doc
.querySelector('link[rel="manifest"]')
?.getAttribute('href');
const manifestUrl = manifestHref && resolveUrl(manifestHref, `${origin}/`);
if (manifestUrl) {
try {
const manifest = await this.http.requestJson(manifestUrl);
if (!themeColor && manifest?.theme_color) {
themeColor = String(manifest.theme_color);
}
for (const icon of manifest?.icons ?? []) {
const url = icon?.src && resolveUrl(icon.src, manifestUrl);
if (!url) {
continue;
}
const purpose = String(icon.purpose ?? 'any').toLowerCase();
candidates.push({
url,
rel: 'manifest',
type: icon.type || null,
width: parseWidth(icon.sizes),
maskable: purpose.split(/\s+/).includes('maskable'),
});
}
} catch {
// A broken manifest shouldn't stop us from using link tags.
}
}
candidates.push(...fallbackCandidates(origin));
const seen = new Set();
const unique = candidates.filter((candidate) => {
if (seen.has(candidate.url)) {
return false;
}
seen.add(candidate.url);
return true;
});
unique.sort(
(a, b) =>
candidateScore(b, SITE_ICON_TARGET_SIZE) -
candidateScore(a, SITE_ICON_TARGET_SIZE)
);
return { candidates: unique, themeColor };
}
isStale(record) {
if (!record?.updatedAt || Date.now() - record.updatedAt > SITE_ICON_TTL) {
return true;
}
// Records cached before the content-type check (or poisoned by an HTML
// response) are re-resolved so they heal without user intervention.
return !isUsableIcon(record);
}
}