1
0
Fork 0

feat: oeffentliche App-Icon-Route mit Fallback App-Icon -> Logo -> Buchstabe

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonny 2026-10-28 11:14:49 +01:00
parent 6bc029f22b
commit eb20d421b6
3 changed files with 290 additions and 0 deletions

View File

@ -0,0 +1,67 @@
import { createAdminClient } from "@/lib/supabase/admin";
import { STANDARD_FARBE_PRIMAER } from "@/lib/firma/farben";
import {
iconBuchstabe,
iconQuelle,
parseIconAnfrage,
renderAppIcon,
type IconBranding,
} from "@/lib/pwa/app-icon";
// Bewusst oeffentlich (ohne Session): Browser und Betriebssystem laden die
// Icons bei der Installation ohne Cookies. Es werden nur gerenderte PNGs
// ausgeliefert, nie die Originaldateien. Der Admin-Client umgeht RLS, deshalb
// wird "aktiv" explizit gefiltert. "version" dient nur dem Cache-Busting.
export async function GET(
_req: Request,
{ params }: { params: Promise<{ firma: string; version: string; datei: string }> }
) {
const { firma, datei } = await params;
const anfrage = parseIconAnfrage(firma, datei);
if (!anfrage) return new Response("Not found", { status: 404 });
// Das Standard-Icon braucht keine Datenbank.
const admin = anfrage.firmaId ? createAdminClient() : null;
let branding: IconBranding | null = null;
if (admin && anfrage.firmaId) {
const { data } = await admin
.from("firmen")
.select("id, name, logo_pfad, app_icon_pfad, farbe_primaer")
.eq("id", anfrage.firmaId)
.eq("aktiv", true)
.maybeSingle();
if (!data) return new Response("Not found", { status: 404 });
branding = data as IconBranding;
}
const farbe = branding?.farbe_primaer ?? STANDARD_FARBE_PRIMAER;
const quelle = iconQuelle(branding);
const buchstabe = iconBuchstabe(branding);
let png: Buffer | null = null;
if (admin && quelle.art !== "buchstabe") {
const { data, error } = await admin.storage.from("firmen-logos").download(quelle.pfad);
if (!error && data) {
try {
png = await renderAppIcon({
quelle: Buffer.from(await data.arrayBuffer()),
art: quelle.art,
farbe,
groesse: anfrage.groesse,
});
} catch {
// Unlesbare Quelldatei: wie ein Download-Fehler behandeln.
}
}
}
// Download-/Lesefehler oder kein Bild hinterlegt: Buchstabe auf Firmenfarbe.
png ??= await renderAppIcon({ quelle: null, art: "buchstabe", buchstabe, farbe, groesse: anfrage.groesse });
return new Response(new Uint8Array(png), {
headers: {
"Content-Type": "image/png",
"Cache-Control": "public, max-age=31536000, immutable",
"X-Content-Type-Options": "nosniff",
},
});
}

View File

@ -0,0 +1,117 @@
import { describe, expect, it } from "vitest";
import sharp from "sharp";
import {
appIconPfad,
validateAppIcon,
iconQuelle,
iconVersion,
iconUrl,
parseIconAnfrage,
renderAppIcon,
type IconBranding,
} from "./app-icon";
const basis: IconBranding = {
id: "00000000-0000-0000-0000-00000000f001",
name: "Widmann",
logo_pfad: null,
app_icon_pfad: null,
farbe_primaer: "#0071ed",
};
describe("appIconPfad", () => {
it("baut den Storage-Pfad", () => {
expect(appIconPfad("f", "png", 5)).toBe("f/app-icon-5.png");
});
});
describe("validateAppIcon", () => {
it("lehnt unbekannte Typen und zu grosse Dateien ab", () => {
expect(validateAppIcon({ type: "image/gif", size: 10 }).valid).toBe(false);
expect(validateAppIcon({ type: "image/png", size: 1024 * 1024 + 1 }).valid).toBe(false);
});
it("akzeptiert SVG", () => {
expect(validateAppIcon({ type: "image/svg+xml", size: 10 })).toEqual({ valid: true, endung: "svg" });
});
it("nennt App-Icon in der Fehlermeldung", () => {
const r = validateAppIcon({ type: "image/png", size: 1024 * 1024 + 1 });
expect(!r.valid && r.error).toContain("App-Icon");
});
});
describe("iconQuelle", () => {
it("Fallback-Kette", () => {
expect(iconQuelle({ ...basis, app_icon_pfad: "a.png", logo_pfad: "l.png" })).toEqual({ art: "app-icon", pfad: "a.png" });
expect(iconQuelle({ ...basis, logo_pfad: "l.png" })).toEqual({ art: "logo", pfad: "l.png" });
expect(iconQuelle({ ...basis, name: " widmann" })).toEqual({ art: "buchstabe", buchstabe: "W" });
expect(iconQuelle(null)).toEqual({ art: "buchstabe", buchstabe: "A" });
});
});
describe("iconVersion / iconUrl", () => {
it("null ist standard", () => {
expect(iconVersion(null)).toBe("standard");
});
it("aendert sich mit den Feldern, bleibt sonst gleich", () => {
const v = iconVersion(basis);
expect(iconVersion({ ...basis })).toBe(v);
expect(iconVersion({ ...basis, app_icon_pfad: "x" })).not.toBe(v);
expect(iconVersion({ ...basis, logo_pfad: "x" })).not.toBe(v);
expect(iconVersion({ ...basis, farbe_primaer: "#000000" })).not.toBe(v);
expect(iconVersion({ ...basis, name: "Andere" })).not.toBe(v);
});
it("URL unterscheidet Firmen mit gleichen Daten", () => {
const b = { ...basis, id: "00000000-0000-0000-0000-00000000f002" };
expect(iconUrl(basis, "192")).not.toBe(iconUrl(b, "192"));
expect(iconUrl(null, "512-maskable")).toBe("/app-icon/standard/standard/512-maskable.png");
expect(iconUrl(basis, "192")).toBe(`/app-icon/${basis.id}/${iconVersion(basis)}/192.png`);
});
});
describe("parseIconAnfrage", () => {
it("parst gueltige Anfragen", () => {
expect(parseIconAnfrage("standard", "192.png")).toEqual({ firmaId: null, groesse: "192" });
expect(parseIconAnfrage(basis.id, "512-maskable.png")).toEqual({ firmaId: basis.id, groesse: "512-maskable" });
});
it("lehnt Ungueltiges ab", () => {
expect(parseIconAnfrage("keine-uuid", "192.png")).toBeNull();
expect(parseIconAnfrage("standard", "999.png")).toBeNull();
expect(parseIconAnfrage("standard", "192.svg")).toBeNull();
expect(parseIconAnfrage("../x", "192.png")).toBeNull();
});
});
describe("renderAppIcon", () => {
const png = () =>
sharp({ create: { width: 40, height: 20, channels: 4, background: "#ff0000" } }).png().toBuffer();
const svg = Buffer.from(
'<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><script>alert(1)</script><rect width="40" height="40" fill="#00ff00"/></svg>'
);
async function pruefe(buf: Buffer, n: number) {
expect([...buf.subarray(0, 4)]).toEqual([0x89, 0x50, 0x4e, 0x47]);
const m = await sharp(buf).metadata();
expect(m.width).toBe(n);
expect(m.height).toBe(n);
}
it.each([
["192", 192],
["180", 180],
["512", 512],
["512-maskable", 512],
] as const)("rendert alle Arten in Groesse %s", async (groesse, n) => {
const farbe = "#0071ed";
await pruefe(await renderAppIcon({ quelle: await png(), art: "app-icon", farbe, groesse }), n);
await pruefe(await renderAppIcon({ quelle: await png(), art: "logo", farbe, groesse }), n);
await pruefe(await renderAppIcon({ quelle: svg, art: "app-icon", farbe, groesse }), n);
await pruefe(await renderAppIcon({ quelle: svg, art: "logo", farbe, groesse }), n);
await pruefe(await renderAppIcon({ quelle: null, art: "buchstabe", buchstabe: "W", farbe, groesse }), n);
});
it("maskable: Rand hat Hintergrundfarbe", async () => {
const buf = await renderAppIcon({ quelle: await png(), art: "logo", farbe: "#0071ed", groesse: "512-maskable" });
const data = await sharp(buf).raw().toBuffer();
expect([data[0], data[1], data[2]]).toEqual([0x00, 0x71, 0xed]);
});
});

106
web/lib/pwa/app-icon.ts Normal file
View File

@ -0,0 +1,106 @@
import { createHash } from "node:crypto";
import sharp from "sharp";
import { validateLogo, type LogoEndung } from "@/lib/firma/logo";
export type IconGroesse = "180" | "192" | "512" | "512-maskable";
export type IconBranding = {
id: string;
name: string;
logo_pfad: string | null;
app_icon_pfad: string | null;
farbe_primaer: string | null;
};
const GROESSEN: readonly IconGroesse[] = ["180", "192", "512", "512-maskable"];
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// Zeitstempel im Namen: ein neues App-Icon hat einen neuen Pfad und damit eine neue Version.
export function appIconPfad(firmaId: string, endung: LogoEndung, jetzt: number = Date.now()): string {
return `${firmaId}/app-icon-${jetzt}.${endung}`;
}
export function validateAppIcon(datei: { type: string; size: number }): ReturnType<typeof validateLogo> {
const r = validateLogo(datei);
return r.valid ? r : { valid: false, error: r.error.replace("Das Logo", "Das App-Icon") };
}
export function iconVersion(f: IconBranding | null): string {
if (!f) return "standard";
const roh = [f.name, f.logo_pfad, f.app_icon_pfad, f.farbe_primaer].map((v) => v ?? "").join("|");
return createHash("sha1").update(roh).digest("hex").slice(0, 10);
}
export function iconUrl(f: IconBranding | null, groesse: IconGroesse): string {
return `/app-icon/${f ? f.id : "standard"}/${iconVersion(f)}/${groesse}.png`;
}
export function parseIconAnfrage(
firma: string,
datei: string
): { firmaId: string | null; groesse: IconGroesse } | null {
if (!datei.endsWith(".png")) return null;
const groesse = datei.slice(0, -4) as IconGroesse;
if (!GROESSEN.includes(groesse)) return null;
if (firma === "standard") return { firmaId: null, groesse };
if (!UUID_REGEX.test(firma)) return null;
return { firmaId: firma, groesse };
}
export function iconBuchstabe(f: IconBranding | null): string {
return (f?.name ?? "").trim().charAt(0).toUpperCase() || "A";
}
export function iconQuelle(
f: IconBranding | null
): { art: "app-icon"; pfad: string } | { art: "logo"; pfad: string } | { art: "buchstabe"; buchstabe: string } {
if (f?.app_icon_pfad) return { art: "app-icon", pfad: f.app_icon_pfad };
if (f?.logo_pfad) return { art: "logo", pfad: f.logo_pfad };
return { art: "buchstabe", buchstabe: iconBuchstabe(f) };
}
const WEISS = "#ffffff";
function buchstabeSvg(buchstabe: string, n: number): Buffer {
const zeichen = buchstabe.replace(/[<>&"']/g, "") || "A";
return Buffer.from(
`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${n}">` +
`<text x="50%" y="50%" dy="0.35em" text-anchor="middle" fill="${WEISS}" ` +
`font-family="Inter, Arial, Helvetica, sans-serif" font-weight="700" font-size="${Math.round(n * 0.6)}">${zeichen}</text></svg>`
);
}
export async function renderAppIcon(params: {
quelle: Buffer | null;
art: "app-icon" | "logo" | "buchstabe";
buchstabe?: string;
farbe: string;
groesse: IconGroesse;
}): Promise<Buffer> {
const { quelle, art, farbe, groesse } = params;
const maskable = groesse === "512-maskable";
const kante = groesse === "180" ? 180 : groesse === "192" ? 192 : 512;
// Maskable: Inhalt in der Safe Zone (60 %), der Rest ist Hintergrund.
const innen = maskable ? Math.round(kante * 0.6) : kante;
// sharp/librsvg fuehrt kein Script aus und laedt keine externen Ressourcen.
const eingabe = (b: Buffer) => sharp(b, { limitInputPixels: 4096 * 4096 });
let hintergrund: string = farbe;
let inhalt: Buffer;
if (art === "app-icon" && quelle) {
hintergrund = WEISS;
inhalt = await eingabe(quelle).resize(innen, innen, { fit: "cover" }).flatten({ background: WEISS }).png().toBuffer();
} else if (art === "logo" && quelle) {
const breite = Math.round(innen * 0.7);
inhalt = await eingabe(quelle).resize(breite, breite, { fit: "inside" }).png().toBuffer();
} else {
inhalt = await eingabe(buchstabeSvg(params.buchstabe ?? "A", innen)).resize(innen, innen).png().toBuffer();
}
return sharp({ create: { width: kante, height: kante, channels: 4, background: hintergrund } })
.composite([{ input: inhalt, gravity: "centre" }])
.flatten({ background: hintergrund })
.png()
.toBuffer();
}