diff --git a/server/src/app.ts b/server/src/app.ts index 7f7db6d..605632c 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -14,6 +14,7 @@ import { fetchPermissions } from "./permissionSchema.js"; import { administrationAllowed, gateAdministration, grantsAdministration } from "./adminGate.js"; import { CookieSessionStore, SessionStore, accountKey, type SessionBackend, type LiveSession } from "./sessions.js"; import { RateLimiter } from "./ratelimit.js"; +import { logoHandler } from "./logo.js"; import { rateLimitKey, resolveClientIp } from "./clientip.js"; import { safeEqual } from "./crypto.js"; import { @@ -78,6 +79,8 @@ const loginFloodLimiter = new RateLimiter(config.loginRateLimit * 20, 15 * 60_00 */ const accountLimiter = new RateLimiter(10, 15 * 60_000); const apiLimiter = new RateLimiter(config.apiRateLimit, 60_000); +/* The branding logo is asked for before sign-in, so it's limited by address. */ +const logoLimiter = new RateLimiter(120, 60_000); /** Per-session budget on the data path. See config.apiRateLimit. */ const apiRateLimited: MiddlewareHandler = async (c, next) => { @@ -557,6 +560,12 @@ export function createApp(basePath = config.basePath): Hono { }), ); + /* The mail server's branding logo (inbuxa-webmail #101); see logo.ts. */ + api.get("/logo", async (c) => { + if (!logoLimiter.check(rateLimitKey(clientIp(c)))) return c.body(null, 429); + return logoHandler(c); + }); + // ---------- Auth ---------- /* * Sign-in through the mail server's page. `start` sends the browser there; diff --git a/server/src/logo.test.ts b/server/src/logo.test.ts new file mode 100644 index 0000000..fb6a94a --- /dev/null +++ b/server/src/logo.test.ts @@ -0,0 +1,102 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { Hono } from "hono"; + +/** + * A stand-in for the mail server's `GET /logo` (branding BT-5, BT-27): it + * answers by the query it was asked, and counts the requests. + */ +const PNG = Buffer.from("89504e470d0a1a0a0000000d49484452", "hex"); +const asked: { url: string; dest: string | undefined }[] = []; +const upstream = createServer((req, res) => { + asked.push({ url: req.url ?? "", dest: req.headers["sec-fetch-dest"] as string | undefined }); + const url = new URL(req.url ?? "/", "http://x"); + const domain = url.searchParams.get("domain") ?? ""; + const dark = url.searchParams.get("theme") === "dark"; + if (domain === "image.example") { + res.writeHead(200, { "content-type": "image/png" }); + res.end(dark ? Buffer.concat([PNG, Buffer.from("dark")]) : PNG); + } else if (domain === "url.example") { + res.writeHead(302, { location: "https://cdn.example/logo.png" }); + res.end(); + } else if (domain === "plain-http.example") { + res.writeHead(302, { location: "http://cdn.example/logo.png" }); + res.end(); + } else if (domain === "html.example") { + res.writeHead(200, { "content-type": "text/html" }); + res.end("x"); + } else { + res.writeHead(404); + res.end(); + } +}); +await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve)); +process.env.MAIL_SERVER_URL = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`; +process.env.APP_SECRET = "test-secret-for-logo"; + +const { logoHandler, cleanDomain, clearLogoCache } = await import("./logo.js"); + +const app = new Hono(); +app.get("/api/logo", logoHandler); +const get = (query: string, dest = "image") => app.request(`/api/logo${query}`, { headers: { "sec-fetch-dest": dest } }); + +test.after(() => upstream.close()); + +test("a logo stored as an image is passed on with the server's protections", async () => { + clearLogoCache(); + const res = await get("?domain=image.example"); + assert.equal(res.status, 200); + assert.equal(res.headers.get("content-type"), "image/png"); + assert.equal(res.headers.get("x-content-type-options"), "nosniff"); + assert.match(res.headers.get("cache-control") ?? "", /max-age=300/); + assert.deepEqual(Buffer.from(await res.arrayBuffer()), PNG); +}); + +// inbuxa-server #410: the dark theme asks for the dark-mode logo +test("theme=dark is passed on, and kept apart from the light answer", async () => { + clearLogoCache(); + const dark = Buffer.from(await (await get("?domain=image.example&theme=dark")).arrayBuffer()); + const light = Buffer.from(await (await get("?domain=image.example")).arrayBuffer()); + assert.ok(dark.toString().endsWith("dark")); + assert.deepEqual(light, PNG); + assert.ok(asked.some((a) => a.url === "/logo?domain=image.example&theme=dark")); +}); + +test("answers are kept, so a page load isn't a request to the server", async () => { + clearLogoCache(); + const before = asked.length; + await get("?domain=image.example"); + await get("?domain=image.example"); + await get("?domain=image.example"); + assert.equal(asked.length - before, 1); +}); + +test("a URL logo goes through the image proxy, and only for an image load", async () => { + clearLogoCache(); + const res = await get("?domain=url.example"); + assert.equal(res.status, 302); + assert.equal(res.headers.get("location"), `/api/image?url=${encodeURIComponent("https://cdn.example/logo.png")}`); + assert.equal(res.headers.get("cache-control"), "no-store"); + // Opened as a page, it sends nobody anywhere + assert.equal((await get("?domain=url.example", "document")).status, 404); + // The server is asked as an image load, and its redirect never followed + assert.ok(asked.filter((a) => a.url.includes("url.example")).every((a) => a.dest === "image")); + assert.ok(!asked.some((a) => a.url.includes("cdn.example"))); +}); + +test("no logo, an http: URL or something that isn't an image is a 404", async () => { + clearLogoCache(); + for (const query of ["", "?domain=none.example", "?domain=plain-http.example", "?domain=html.example"]) { + assert.equal((await get(query)).status, 404, query); + } +}); + +test("only a domain name is passed on", () => { + assert.equal(cleanDomain("Example.ORG."), "example.org"); + assert.equal(cleanDomain("a.example&theme=x"), ""); + assert.equal(cleanDomain("../logo"), ""); + assert.equal(cleanDomain(undefined), ""); + assert.equal(cleanDomain("a".repeat(254)), ""); +}); diff --git a/server/src/logo.ts b/server/src/logo.ts new file mode 100644 index 0000000..7dafc24 --- /dev/null +++ b/server/src/logo.ts @@ -0,0 +1,129 @@ +/** + * ihasmail-inbuxa: the mail server's branding logo, for the sign-in page and the top bar + * (inbuxa-webmail #101). + * + * The server answers `GET /logo` with the logo that applies to a domain: the + * image itself, a redirect to a logo set as an https URL, or 404 when none is + * set (branding BT-5). `?theme=dark` asks for the one set for dark mode, + * falling back to the ordinary one (BT-27, inbuxa-server #410). + * + * The browser doesn't know the mail server's address, so this asks on its + * behalf and hands the answer on, the way the server would have: + * + * - An image is passed on as it is, with the server's own protections: no + * type sniffing, and a sandbox for SVG so a script in one never runs here. + * - A logo set as an https URL becomes a redirect to the image proxy + * (`/api/image`), the way remote images in mail are shown: the page's + * Content-Security-Policy loads images from this origin only, and the proxy + * checks where it may connect. The proxy needs a signed-in reader, so the + * sign-in page shows its built-in logo for a URL logo; a logo stored as an + * image shows everywhere. Like the server, this redirects only an image + * load (`Sec-Fetch-Dest: image`). This module itself fetches no URL a logo + * names. + * - Anything else is a 404, and the page shows its built-in logo. + * + * Answers are kept for five minutes, the time the server lets a browser keep + * one, so every reader's page load doesn't become a request to the server, + * whose anonymous-request limit counts this process as one address. + */ +import type { Context } from "hono"; +import { config } from "./config.js"; +import { upstreamFor } from "./upstream.js"; + +/** How long an answer is kept, here and in the browser. */ +const TTL_MS = 5 * 60_000; +/** The server refuses a logo over 256 KiB (BT-3); a little room for headers. */ +const MAX_BYTES = 300 * 1024; +const MAX_ENTRIES = 256; +const SVG_CSP = "default-src 'none'; style-src 'unsafe-inline'; sandbox"; + +type Answer = + | { kind: "image"; contentType: string; body: Uint8Array } + | { kind: "redirect"; location: string } + | { kind: "none" }; + +const cache = new Map(); + +/** A domain name as a query may carry it: letters, digits, dots and hyphens. */ +export function cleanDomain(value: string | undefined): string { + const domain = (value ?? "").trim().toLowerCase().replace(/\.$/, ""); + return domain.length <= 253 && /^[a-z0-9.-]+$/.test(domain) ? domain : ""; +} + +/** Asks the server; never follows a redirect and never throws. */ +async function ask(base: string, domain: string, dark: boolean): Promise { + const params = new URLSearchParams(); + if (domain) params.set("domain", domain); + if (dark) params.set("theme", "dark"); + const query = params.toString(); + try { + const res = await fetch(`${base}/logo${query ? `?${query}` : ""}`, { + // The server redirects to a URL logo only for an image load + headers: { "sec-fetch-dest": "image", accept: "image/*" }, + redirect: "manual", + signal: AbortSignal.timeout(Math.min(config.upstreamTimeout, 10_000)), + }); + if (res.status >= 300 && res.status < 400) { + const location = res.headers.get("location") ?? ""; + return /^https:\/\/[^\s/?#]/i.test(location) && !/[\s\x00-\x1f]/.test(location) ? { kind: "redirect", location } : { kind: "none" }; + } + const contentType = (res.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase(); + if (res.status !== 200 || !/^image\/(png|jpeg|gif|webp|svg\+xml)$/.test(contentType)) { + await res.body?.cancel(); + return { kind: "none" }; + } + const declared = Number(res.headers.get("content-length") ?? "0"); + if (declared > MAX_BYTES) { + await res.body?.cancel(); + return { kind: "none" }; + } + const body = new Uint8Array(await res.arrayBuffer()); + return body.byteLength > 0 && body.byteLength <= MAX_BYTES ? { kind: "image", contentType, body } : { kind: "none" }; + } catch { + return { kind: "none" }; + } +} + +/** The server's answer for a domain and theme, from the cache when fresh. */ +export async function serverLogo(domain: string, dark: boolean, now = Date.now()): Promise { + const base = domain ? upstreamFor(`logo@${domain}`) : config.stalwartUrl; + const key = `${base}\n${domain}\n${dark ? "dark" : "light"}`; + const hit = cache.get(key); + if (hit && hit.expires > now) return hit.answer; + const answer = await ask(base, domain, dark); + cache.delete(key); + if (cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value!); + cache.set(key, { answer, expires: now + TTL_MS }); + return answer; +} + +/** Forgets every kept answer; for tests. */ +export function clearLogoCache(): void { + cache.clear(); +} + +/** `GET /api/logo?domain=&theme=dark`. */ +export async function logoHandler(c: Context): Promise { + const domain = cleanDomain(c.req.query("domain")); + const dark = c.req.query("theme") === "dark"; + const answer = await serverLogo(domain, dark); + c.header("X-Content-Type-Options", "nosniff"); + if (answer.kind === "image") { + c.header("Content-Type", answer.contentType); + c.header("Cache-Control", `public, max-age=${TTL_MS / 1000}`); + if (answer.contentType === "image/svg+xml") c.header("Content-Security-Policy", SVG_CSP); + return c.body(answer.body as unknown as ArrayBuffer, 200); + } + if (answer.kind === "redirect") { + // Who asks decides the answer, so no shared cache may keep it + c.header("Cache-Control", "no-store"); + c.header("Vary", "Sec-Fetch-Dest"); + if ((c.req.header("sec-fetch-dest") ?? "").toLowerCase() === "image") { + c.header("Location", `${config.basePath}/api/image?url=${encodeURIComponent(answer.location)}`); + return c.body(null, 302); + } + return c.body(null, 404); + } + c.header("Cache-Control", `public, max-age=${TTL_MS / 1000}`); + return c.body(null, 404); +} diff --git a/web/src/lib/__tests__/serverLogo.test.ts b/web/src/lib/__tests__/serverLogo.test.ts new file mode 100644 index 0000000..847f0c7 --- /dev/null +++ b/web/src/lib/__tests__/serverLogo.test.ts @@ -0,0 +1,46 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { domainOf, probeServerLogo, resetServerLogos, serverLogoUrl } from "@/lib/serverLogo"; + +/** An `Image` that loads, or fails, the way the browser would for `/api/logo`. */ +function fakeImage(loads: boolean) { + const sources: string[] = []; + class FakeImage { + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + set src(value: string) { + sources.push(value); + queueMicrotask(() => (loads ? this.onload?.() : this.onerror?.())); + } + } + vi.stubGlobal("Image", FakeImage); + return sources; +} + +describe("the server's logo (#101)", () => { + afterEach(() => { + vi.unstubAllGlobals(); + resetServerLogos(); + }); + + it("asks for the reader's domain, and for the dark-mode logo in the dark theme", () => { + expect(serverLogoUrl("", "light")).toBe("/api/logo"); + expect(serverLogoUrl("example.org", "light")).toBe("/api/logo?domain=example.org"); + expect(serverLogoUrl("example.org", "dark")).toBe("/api/logo?domain=example.org&theme=dark"); + expect(serverLogoUrl("", "dark")).toBe("/api/logo?theme=dark"); + }); + + it("takes the domain from the address", () => { + expect(domainOf("Jane@Example.ORG")).toBe("example.org"); + expect(domainOf("jane")).toBe(""); + expect(domainOf(undefined)).toBe(""); + }); + + it("probes each URL once, as an image", async () => { + const sources = fakeImage(true); + probeServerLogo("/api/logo?theme=dark"); + probeServerLogo("/api/logo?theme=dark"); + probeServerLogo("/api/logo"); + await Promise.resolve(); + expect(sources).toEqual(["/api/logo?theme=dark", "/api/logo"]); + }); +}); diff --git a/web/src/lib/serverLogo.ts b/web/src/lib/serverLogo.ts new file mode 100644 index 0000000..a218b95 --- /dev/null +++ b/web/src/lib/serverLogo.ts @@ -0,0 +1,73 @@ +import { useEffect, useSyncExternalStore } from "react"; +import { withBase } from "@/lib/basePath"; +import { useEffectiveTheme } from "@/store/settings"; +import { useSession } from "@/store/session"; + +/** + * The logo the mail server's administrator set (inbuxa-webmail #101), for the + * sign-in page and the top bar, instead of the built-in one. + * + * `/api/logo` asks the server for the logo that applies to a domain: the + * signed-in reader's own, or the server's default before anybody signs in. + * The dark theme asks for the one set for dark mode, which the server falls + * back from to the ordinary one (inbuxa-server #410). + * + * Probed with an image, not a fetch, the way the server's own pages do it: + * a logo set as a URL arrives as a redirect, and only an image load is + * redirected. Each URL is probed once per page load. + */ +export type ServerLogo = { status: "loading" } | { status: "custom"; url: string } | { status: "default" }; + +const LOADING: ServerLogo = { status: "loading" }; +const probes = new Map(); +const watchers = new Set<() => void>(); + +function subscribe(watch: () => void): () => void { + watchers.add(watch); + return () => void watchers.delete(watch); +} + +/** The `/api/logo` URL for a domain and theme. */ +export function serverLogoUrl(domain: string, theme: "light" | "dark"): string { + const params = new URLSearchParams(); + if (domain) params.set("domain", domain); + if (theme === "dark") params.set("theme", "dark"); + const query = params.toString(); + return withBase(`/api/logo${query ? `?${query}` : ""}`); +} + +/** Starts the probe for a URL; later calls for it do nothing. */ +export function probeServerLogo(url: string): void { + if (probes.has(url)) return; + probes.set(url, LOADING); + const image = new Image(); + const settle = (state: ServerLogo) => { + probes.set(url, state); + for (const watch of watchers) watch(); + }; + image.onload = () => settle({ status: "custom", url }); + image.onerror = () => settle({ status: "default" }); + image.src = url; +} + +/** Forgets every probe; for tests. */ +export function resetServerLogos(): void { + probes.clear(); +} + +/** The domain of an address, or "" for a bare name. */ +export function domainOf(username: string | null | undefined): string { + const at = (username ?? "").lastIndexOf("@"); + return at < 0 ? "" : username!.slice(at + 1).trim().toLowerCase(); +} + +/** The server's logo for the reader in front, in the theme on screen. */ +export function useServerLogo(): ServerLogo { + const theme = useEffectiveTheme(); + const domain = domainOf(useSession((s) => s.session?.username)); + const url = serverLogoUrl(domain, theme); + const read = () => probes.get(url) ?? LOADING; + const logo = useSyncExternalStore(subscribe, read, read); + useEffect(() => probeServerLogo(url), [url]); + return logo; +} diff --git a/web/src/styles/app.css b/web/src/styles/app.css index 9017d4f..d028d5b 100644 --- a/web/src/styles/app.css +++ b/web/src/styles/app.css @@ -1246,6 +1246,8 @@ a.menu-item:hover { color: var(--fg); } .topbar { display: flex; align-items: center; gap: 8px; padding: 0 12px; background: var(--bg); position: relative; z-index: 50; } .topbar .brand { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 1.2em; letter-spacing: -.01em; color: var(--fg); text-decoration: none; padding-right: 8px; min-width: 0; } .topbar .brand img { width: 34px; height: 34px; object-fit: contain; } +/* inbuxa-webmail #101: a logo the server's administrator set keeps its own shape. */ +.topbar .brand img.server-logo { width: auto; max-width: 180px; } .topbar .brand .brand-name { color: #14b8a6; } .topbar .brand .brand-name span { color: var(--fg-muted); font-weight: 500; } /* @@ -2129,6 +2131,7 @@ select optgroup { background-color: var(--bg-elev); color: var(--fg); } .login-card { width: 100%; max-width: 400px; background: var(--bg-elev); border: 1px solid var(--border); border-radius: var(--radius-lg); box-shadow: var(--shadow-2); padding: 32px 28px 24px; animation: rise .25s var(--ease); } .login-card .logo { display: flex; flex-direction: column; align-items: center; gap: 6px; margin-bottom: 20px; } .login-card .logo img { width: 120px; height: auto; } +.login-card .logo img.server-logo { width: auto; max-width: 260px; max-height: 126px; object-fit: contain; } /* The logo is the mark alone, so the name is set here rather than baked in. */ .login-card h1 { margin: 0; font-size: 1.6em; font-weight: 800; letter-spacing: -.02em; color: #14b8a6; } .login-card .sub { color: var(--fg-muted); font-size: .92em; margin: 0; } diff --git a/web/src/views/AppShell.tsx b/web/src/views/AppShell.tsx index 4d82022..b265097 100644 --- a/web/src/views/AppShell.tsx +++ b/web/src/views/AppShell.tsx @@ -3,6 +3,7 @@ import { Link, useLocation } from "wouter"; import { Calendar, Check, ChevronsUpDown, FolderOpen, Globe, HelpCircle, Lock, LogOut, Mail, Menu as MenuIcon, Moon, PanelLeftClose, PanelLeftOpen, PenSquare, Plus, RefreshCw, Settings, ShieldCheck, Sun, Upload, Users, X } from "lucide-react"; import { useSession } from "@/store/session"; import { DEFAULT_APP_NAME, brandImage } from "@/lib/brand"; +import { useServerLogo } from "@/lib/serverLogo"; import { InbuxaWordmark } from "@/ui/InbuxaWordmark"; import { useEffectiveTheme, useSettings } from "@/store/settings"; import { toggleTarget } from "@/lib/palette"; @@ -111,6 +112,7 @@ export function AppShell({ children }: { children: ReactNode }) { window.history.replaceState(null, "", window.location.pathname + (rest ? `?${rest}` : "")); }, []); const appName = useSession((s) => s.session?.ihasmail?.appName) || DEFAULT_APP_NAME; + const serverLogo = useServerLogo(); const acctMenu = useMenu(); const administers = hasAdministration(usePermissions()); const needsOwnDevice = useSession((s) => Boolean(s.session?.ihasmail?.administrationNeedsOwnDevice)); @@ -214,14 +216,25 @@ export function AppShell({ children }: { children: ReactNode }) { )} - + {/* The logo the server's administrator set, else the built-in + one; held in place, unseen, until the server has answered. */} + {serverLogo.status === "custom" ? ( + + ) : ( + + )} {lockedInView && } {/* A product name, not a word: translated it is a different product. Read from the session rather than written here, so a deployment that set APP_NAME is called what it calls itself -- the document - title has taken it from there all along. */} + title has taken it from there all along. The inbuxa wordmark + makes way for a logo of the server's own. */} {appName === DEFAULT_APP_NAME ? ( - + serverLogo.status === "custom" ? null : ) : ( {appName} diff --git a/web/src/views/Login.tsx b/web/src/views/Login.tsx index 6b84dca..8abf4ca 100644 --- a/web/src/views/Login.tsx +++ b/web/src/views/Login.tsx @@ -7,6 +7,7 @@ import { signInTheme } from "@/lib/signInTheme"; import { APP_VERSION } from "@/lib/version"; import { DEFAULT_SOURCE_URL } from "@/lib/source"; import { DEFAULT_APP_NAME, brandImage } from "@/lib/brand"; +import { useServerLogo } from "@/lib/serverLogo"; import { t } from "@/lib/i18n"; import { InbuxaWordmark } from "@/ui/InbuxaWordmark"; @@ -28,6 +29,7 @@ export function LoginPage() { * sign-in form with no name on it would be worse than a wrong one. */ const [appName, setAppName] = useState(DEFAULT_APP_NAME); + const serverLogo = useServerLogo(); /* * How this installation signs people in: on the mail server's own page * ("oauth"), or with the password form. Unknown until the config arrives, @@ -94,7 +96,19 @@ export function LoginPage() {
- + {/* The logo the server's administrator set, else the built-in + one; held in place, unseen, until the server has answered. */} + {serverLogo.status === "custom" ? ( + + ) : ( + + )} {/* A product name, not a word: not translated, and not guessed at from the page it is on. INBUXA's is its wordmark. */}