syncova-links/server/icons.js
jf 27924e55e9
All checks were successful
Docker-Image veröffentlichen / publish (push) Successful in 1m44s
Initial import with Gitea Docker publishing
2026-11-16 15:14:43 +01:00

148 lines
6.3 KiB
JavaScript

import { lookup } from 'node:dns/promises'
import { request as http } from 'node:http'
import { request as https } from 'node:https'
import { isIP } from 'node:net'
import { loadBuffer } from 'cheerio'
import { decodeIco } from 'icojs'
import ipaddr from 'ipaddr.js'
import sharp from 'sharp'
import { httpUrl } from './model.js'
export const iconLimit = 512 * 1024
const imageOptions = { limitInputPixels: 4096 * 4096, failOn: 'warning' }
const globalIPv6 = ipaddr.parseCIDR('2000::/3')
const specialIPv6 = [ipaddr.parseCIDR('2001::/23'), ipaddr.parseCIDR('2002::/16')]
export async function normalizeIcon(buffer) {
const ico = buffer.length >= 22 && buffer.readUInt32LE(0) === 0x00010000
let image
if (ico) {
// Decode only the selected frame. Each ICO entry encodes dimensions in one byte.
const count = buffer.readUInt16LE(4)
if (!count || count > 64 || 6 + count * 16 > buffer.length) throw new Error('Ungültiges ICO.')
let entry = 6
for (let offset = 22; offset < 6 + count * 16; offset += 16) {
if ((buffer[offset] || 256) > (buffer[entry] || 256)) entry = offset
}
const size = buffer.readUInt32LE(entry + 8)
const offset = buffer.readUInt32LE(entry + 12)
if (size < 8 || offset < 6 + count * 16 || offset + size > buffer.length) throw new Error('Ungültiges ICO.')
const frame = buffer.subarray(offset, offset + size)
if (frame.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
image = sharp(frame, imageOptions)
} else {
if (frame.length < 40 || frame.readUInt32LE(0) !== 40 ||
frame.readInt32LE(4) !== (buffer[entry] || 256) ||
Math.abs(frame.readInt32LE(8)) !== 2 * (buffer[entry + 1] || 256)) {
throw new Error('Ungültiges ICO.')
}
const header = Buffer.from(buffer.subarray(0, 22))
header.writeUInt16LE(1, 4)
buffer.copy(header, 6, entry, entry + 16)
header.writeUInt32LE(22, 18)
const [decoded] = await decodeIco(Buffer.concat([header, frame]), 'image/png')
image = sharp(Buffer.from(decoded.buffer), imageOptions)
}
} else {
const png = buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
const jpeg = buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255
const gif = ['GIF87a', 'GIF89a'].includes(buffer.toString('ascii', 0, 6))
const webp = buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP'
if (!png && !jpeg && !gif && !webp) throw new Error('Unzulässiges Bildformat.')
image = sharp(buffer, imageOptions)
}
return image.resize(128, 128, { fit: 'inside', withoutEnlargement: true }).png().toBuffer()
}
function publicAddress(address) {
const ip = ipaddr.process(address)
if (ip.range() !== 'unicast') return false
return ip.kind() === 'ipv4' ||
(ip.match(globalIPv6) && !specialIPv6.some((subnet) => ip.match(subnet)))
}
async function resolvePublic(hostname, signal) {
const host = hostname.replace(/^\[|\]$/g, '')
if (isIP(host)) {
if (!publicAddress(host)) throw new Error('Interne Adresse.')
return { address: host, family: isIP(host) }
}
const { promise, resolve } = Promise.withResolvers()
const onAbort = () => resolve([])
signal.addEventListener('abort', onAbort, { once: true })
try {
const addresses = await Promise.race([lookup(host, { all: true }), promise])
signal.throwIfAborted()
if (!addresses.length || addresses.some(({ address }) => !publicAddress(address))) {
throw new Error('Interne oder ungültige Adresse.')
}
return addresses.find(({ family }) => family === 4) ?? addresses[0]
} finally {
signal.removeEventListener('abort', onAbort)
}
}
async function download(url, signal, redirects = 0) {
signal.throwIfAborted()
if (redirects > 4) throw new Error('Zu viele Weiterleitungen.')
const pinned = await resolvePublic(url.hostname, signal)
const response = await new Promise((resolve, reject) => {
const request = url.protocol === 'https:' ? https : http
const req = request(url, {
agent: false,
signal,
lookup: (_host, options, callback) => options.all
? callback(null, [pinned])
: callback(null, pinned.address, pinned.family),
headers: { 'User-Agent': 'syncova-links/1.0', Accept: 'text/html,image/*;q=0.9,*/*;q=0.1' },
}, resolve)
req.on('error', reject)
req.end()
})
if ([301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.location) {
response.destroy()
return download(httpUrl(new URL(response.headers.location, url).href), signal, redirects + 1)
}
if (response.statusCode !== 200 || Number(response.headers['content-length']) > iconLimit) {
response.destroy()
throw new Error('Antwort fehlgeschlagen oder zu groß.')
}
const chunks = []
let bytes = 0
for await (const chunk of response) {
bytes += chunk.length
if (bytes > iconLimit) throw new Error('Antwort zu groß.')
chunks.push(chunk)
}
return { url, body: Buffer.concat(chunks) }
}
export async function fetchFavicon(value) {
const url = httpUrl(value)
const total = AbortSignal.timeout(10_000)
const get = (target) => download(target, AbortSignal.any([total, AbortSignal.timeout(3_500)]))
let page
try { page = await get(url) } catch { /* Try the conventional path. */ }
const finalUrl = page?.url ?? url
const candidates = new Set([new URL('/favicon.ico', finalUrl).href])
if (page) {
try { return await normalizeIcon(page.body) } catch { /* The page may contain icon links. */ }
const html = loadBuffer(page.body)
const base = html('base[href]').first().attr('href')
let baseUrl = finalUrl
try { if (base) baseUrl = new URL(base, finalUrl) } catch { /* Use the page URL. */ }
for (const element of html('link[rel][href]').toArray()) {
const rel = html(element).attr('rel').toLowerCase().split(/\s+/)
if (!rel.some((part) => ['icon', 'apple-touch-icon'].includes(part))) continue
try { candidates.add(httpUrl(new URL(html(element).attr('href'), baseUrl).href).href) } catch { /* Invalid link. */ }
if (candidates.size >= 5) break
}
}
const [fallback, ...declared] = candidates
for (const href of [...declared, fallback]) {
if (total.aborted) break
try { return await normalizeIcon((await get(new URL(href))).body) } catch { /* Try another icon. */ }
}
throw new Error('Kein verwendbares Favicon gefunden.')
}