Prevent broken logo from crashing site (#2619)

* Prevent broken logo from crashing site

* Cache icons in memory to make site less vulnerable to DOS attacks

* Swap try and if blocks for apple touch icon
This commit is contained in:
SleeplessOne1917 2024-07-21 18:56:57 +00:00 committed by GitHub
parent ab51245ca5
commit 01c095d269
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 58 additions and 49 deletions

View file

@ -33,6 +33,7 @@ export async function createSsrHtml(
);
if (!appleTouchIcon) {
try {
appleTouchIcon = site?.site_view.site.icon
? `data:image/png;base64,${await sharp(
await fetchIconPng(site.site_view.site.icon),
@ -49,6 +50,12 @@ export async function createSsrHtml(
.toBuffer()
.then(buf => buf.toString("base64"))}`
: favIconPngUrl;
} catch (e) {
console.log(
"Could not fetch site logo for apple touch icon. Using default icon.",
);
appleTouchIcon = favIconPngUrl;
}
}
const erudaStr =

View file

@ -1,20 +1,44 @@
import { readFile } from "fs/promises";
import { Site } from "lemmy-js-client";
import path from "path";
import { fetchIconPng } from "./fetch-icon-png";
import { getStaticDir } from "@utils/env";
type Icon = { sizes: string; src: string; type: string; purpose: string };
const iconSizes = [72, 96, 128, 144, 152, 192, 384, 512];
const defaultLogoPathDirectory = path.join(
process.cwd(),
"dist",
"assets",
"icons",
);
let icons: Icon[] | null = null;
export default async function (site: Site) {
if (!icons) {
try {
const icon = site.icon ? await fetchIconPng(site.icon) : null;
icons = await Promise.all(
iconSizes.map(async size => {
let src = `${getStaticDir()}/assets/icons/icon-${size}x${size}.png`;
if (icon) {
const sharp = (await import("sharp")).default;
src = `data:image/png:base64,${await sharp(icon)
.resize(size, size)
.png()
.toBuffer()
.then(buf => buf.toString("base64"))}`;
}
return {
sizes: `${size}x${size}`,
type: "image/png",
src,
purpose: "any maskable",
};
}),
);
} catch (e) {
console.log(
`Failed to fetch site logo for manifest icon. Using default icon`,
);
}
}
return {
name: site.name,
description: site.description ?? "A link aggregator for the fediverse",
@ -24,29 +48,7 @@ export default async function (site: Site) {
id: "/",
background_color: "#222222",
theme_color: "#222222",
icons: await Promise.all(
iconSizes.map(async size => {
let src = await readFile(
path.join(defaultLogoPathDirectory, `icon-${size}x${size}.png`),
).then(buf => buf.toString("base64"));
if (icon) {
const sharp = (await import("sharp")).default;
src = await sharp(icon)
.resize(size, size)
.png()
.toBuffer()
.then(buf => buf.toString("base64"));
}
return {
sizes: `${size}x${size}`,
type: "image/png",
src: `data:image/png;base64,${src}`,
purpose: "any maskable",
};
}),
),
icons,
shortcuts: [
{
name: "Search",