Multiplayer agent harness for work.
Allow operator-supplied SVG favicons for portal, web-ui and auth (#1538)
Joshua France330f26925ad6
diff --git a/plugins/auth/src/config.ts b/plugins/auth/src/config.tsindex 40626696b..c16837716 100644--- a/plugins/auth/src/config.ts+++ b/plugins/auth/src/config.ts@@ -22,6 +22,7 @@ export interface AuthConfig {allowedEmailDomain: string | undefined;emailFrom: string;brandName: string;+ faviconSvg: string | undefined;transport: EmailTransportKind;resendApiKey: string;smtp: SmtpSettings;@@ -98,6 +99,7 @@ export function readConfig(env: NodeJS.ProcessEnv): AuthConfig {allowedEmailDomain: env.AUTH_ALLOWED_EMAIL_DOMAIN?.trim().toLowerCase() || undefined,emailFrom: env.AUTH_EMAIL_FROM?.trim() ?? "",brandName: env.AUTH_BRAND_NAME?.trim() || "qm",+ faviconSvg: env.AUTH_FAVICON_SVG?.trim() || undefined,transport,resendApiKey: env.RESEND_API_KEY ?? "",smtp: {diff --git a/plugins/auth/src/server.ts b/plugins/auth/src/server.tsindex 72e49b0c0..9e574f3fa 100644--- a/plugins/auth/src/server.ts+++ b/plugins/auth/src/server.ts@@ -2,7 +2,7 @@ import { reportBackendError } from "../../chassis/src/error-reporting.ts";import { createHmac } from "node:crypto";import { coreRememberedSessions, type RememberedSessions, type RememberedSession } from "./sessions.ts";import type { IncomingMessage, ServerResponse } from "node:http";-import { readBody, PayloadTooLargeError, sendBuffered, serveEmojiFavicon } from "../../chassis/src/http.ts";+import { readBody, PayloadTooLargeError, sendBuffered, serveFavicon } from "../../chassis/src/http.ts";import { errMessage } from "../../chassis/src/errors.ts";import type { AuthConfig } from "./config.ts";import { validEmail } from "./config.ts";@@ -543,7 +543,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S}}if (method === "GET" && (path === "/favicon.ico" || path === "/favicon.svg")) {- return serveEmojiFavicon(res, "✉️", "max-age=86400");+ return serveFavicon(res, { svg: cfg.faviconSvg, emoji: "✉️" }, "max-age=86400");}if (method === "GET" && path === "/.well-known/jwks.json") {res.writeHead(200, { "content-type": "application/json", "cache-control": "public, max-age=300" });diff --git a/plugins/auth/test/flow.test.ts b/plugins/auth/test/flow.test.tsindex 0e02ce1c9..67121f925 100644--- a/plugins/auth/test/flow.test.ts+++ b/plugins/auth/test/flow.test.ts@@ -787,3 +787,15 @@ test("trusted sign-in remains available when email is unavailable", async () =>await h.close();}});++test("AUTH_FAVICON_SVG replaces the envelope favicon", async (t) => {+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><rect width="8" height="8"/></svg>';+ const h = await startHarness({ env: { AUTH_FAVICON_SVG: svg } });+ t.after(() => h.close());+ const r = await fetch(`${h.base}/favicon.svg`);+ assert.equal(r.headers.get("content-type"), "image/svg+xml; charset=utf-8");+ assert.equal(await r.text(), svg);+ const plain = await startHarness();+ t.after(() => plain.close());+ assert.match(await (await fetch(`${plain.base}/favicon.ico`)).text(), /✉️/);+});diff --git a/plugins/chassis/src/http.ts b/plugins/chassis/src/http.tsindex a2045b996..c5059d3ba 100644--- a/plugins/chassis/src/http.ts+++ b/plugins/chassis/src/http.ts@@ -78,9 +78,20 @@ export function escapeHtml(s: string): string {);}-export function serveEmojiFavicon(res: ServerResponse, emoji: string, cacheControl: string): void {- res.writeHead(200, { "content-type": "image/svg+xml; charset=utf-8", "cache-control": cacheControl });- res.end(- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90" text-anchor="middle" x="50">${emoji}</text></svg>`,- );+const SVG_DOCUMENT = /^<svg[\s>][\s\S]*<\/svg>$/i;++function faviconSvg(icon: { svg?: string; emoji: string }): string {+ const custom = icon.svg?.trim() ?? "";+ if (SVG_DOCUMENT.test(custom)) return custom;+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90" text-anchor="middle" x="50">${icon.emoji}</text></svg>`;+}++export function serveFavicon(res: ServerResponse, icon: { svg?: string; emoji: string }, cacheControl: string): void {+ res.writeHead(200, {+ "content-type": "image/svg+xml; charset=utf-8",+ "cache-control": cacheControl,+ "x-content-type-options": "nosniff",+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'",+ });+ res.end(faviconSvg(icon));}diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 0e4ff6f16..c8e7efd15 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -56,7 +56,7 @@ import {json,escapeHtml,sendBuffered,- serveEmojiFavicon,+ serveFavicon,readBody,PayloadTooLargeError,} from "../../chassis/src/http.ts";@@ -984,7 +984,14 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>if (method === "GET" && pathname === "/healthz") return json(res, 200, { ok: true });if (method === "GET" && (pathname === "/favicon.ico" || pathname === "/favicon.svg")) {- return serveEmojiFavicon(res, process.env.PORTAL_FAVICON_EMOJI ?? "\u{1F3F4}\u{200D}\u2620\uFE0F", "max-age=86400");+ return serveFavicon(+ res,+ {+ svg: process.env.PORTAL_FAVICON_SVG,+ emoji: process.env.PORTAL_FAVICON_EMOJI ?? "\u{1F3F4}\u{200D}\u2620\uFE0F",+ },+ "max-age=86400",+ );}if (pathname === "/auth/login" && method === "GET") return authLogin(req, res, url);diff --git a/plugins/portal/test/router.test.ts b/plugins/portal/test/router.test.tsindex fff560f10..546d5356a 100644--- a/plugins/portal/test/router.test.ts+++ b/plugins/portal/test/router.test.ts@@ -145,6 +145,24 @@ test("favicon: served unauthenticated as an SVG of the pirate-flag emoji", async}});+test("favicon: PORTAL_FAVICON_SVG replaces the emoji with operator-supplied markup, anything else falls back", async () => {+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><rect width="8" height="8"/></svg>';+ process.env.PORTAL_FAVICON_SVG = svg;+ try {+ for (const path of ["/favicon.ico", "/favicon.svg"]) {+ const r = await fetch(`${base}${path}`);+ assert.equal(r.status, 200);+ assert.equal(r.headers.get("content-type"), "image/svg+xml; charset=utf-8");+ assert.equal(r.headers.get("x-content-type-options"), "nosniff");+ assert.equal(await r.text(), svg);+ }+ process.env.PORTAL_FAVICON_SVG = "not an svg document";+ assert.match(await (await fetch(`${base}/favicon.svg`)).text(), /\u{1F3F4}\u{200D}☠️/u);+ } finally {+ delete process.env.PORTAL_FAVICON_SVG;+ }+});+test("no session: JSON request is 401, HTML navigation is 302 to login", async () => {const j = await fetch(`${base}/api/sessions`, { redirect: "manual" });assert.equal(j.status, 401);diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex c66d107d6..8d4effafd 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -27,7 +27,7 @@ import {cookie,PayloadTooLargeError,sendBuffered,- serveEmojiFavicon,+ serveFavicon,} from "../../chassis/src/http.ts";import { verifyPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";import { createBrandingCache, injectBranding } from "../../chassis/src/branding.ts";@@ -107,7 +107,14 @@ async function serveWebManifest(res: ServerResponse): Promise<void> {orientation: "any",background_color: "#ffffff",theme_color: "#ffffff",- icons: [{ src: "/brand-mark.svg", sizes: "any", type: "image/svg+xml", purpose: "any maskable" }],+ icons: [+ {+ src: process.env.WEB_UI_FAVICON_SVG ? "/favicon.svg" : "/brand-mark.svg",+ sizes: "any",+ type: "image/svg+xml",+ purpose: "any maskable",+ },+ ],};res.writeHead(200, { "content-type": "application/manifest+json; charset=utf-8", "cache-control": "no-cache" });res.end(JSON.stringify(manifest));@@ -3035,7 +3042,14 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {if (method === "GET" && path === "/healthz") return json(res, 200, { ok: true });if (method === "GET" && path === "/favicon.svg") {- return serveEmojiFavicon(res, process.env.WEB_UI_FAVICON_EMOJI ?? "\u{1F3F4}\u{200D}\u2620\uFE0F", "no-cache");+ return serveFavicon(+ res,+ {+ svg: process.env.WEB_UI_FAVICON_SVG,+ emoji: process.env.WEB_UI_FAVICON_EMOJI ?? "\u{1F3F4}\u{200D}\u2620\uFE0F",+ },+ "no-cache",+ );}if (method === "GET" && path === "/manifest.webmanifest") return serveWebManifest(res);diff --git a/plugins/web-ui/test/favicon.test.ts b/plugins/web-ui/test/favicon.test.tsnew file mode 100644index 000000000..9a434e36e--- /dev/null+++ b/plugins/web-ui/test/favicon.test.ts@@ -0,0 +1,60 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { existsSync, mkdirSync, writeFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { dirname, join } from "node:path";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";++const core = createServer((_req, res) => {+ res.writeHead(200, { "content-type": "application/json" });+ res.end("{}");+});+await new Promise<void>((r) => core.listen(0, r));++process.env.CORE_API_URL = `http://localhost:${(core.address() as AddressInfo).port}`;+process.env.CORE_SIGNING_SECRET = "web-ui-favicon-test";+process.env.WEB_UI_PRINCIPALS = "alice";++const distDir = join(dirname(fileURLToPath(import.meta.url)), "..", "dist-web");+const distIndex = join(distDir, "index.html");+if (!existsSync(distIndex)) {+ mkdirSync(distDir, { recursive: true });+ writeFileSync(+ distIndex,+ '<!doctype html><html><head><meta name="brand-self-label" content="Agent" /></head><body></body></html>',+ );+}++const { handler } = await import("../server/index.ts");+const surface = createServer((req, res) => void handler(req, res));+await new Promise<void>((r) => surface.listen(0, r));+const base = `http://localhost:${(surface.address() as AddressInfo).port}`;+const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><rect width="8" height="8"/></svg>';++test.after(() => {+ surface.close();+ core.close();+});++test("without WEB_UI_FAVICON_SVG the favicon is the emoji and the manifest icon is the stock mark", async () => {+ delete process.env.WEB_UI_FAVICON_SVG;+ const icon = await fetch(`${base}/favicon.svg`);+ assert.equal(icon.headers.get("content-type"), "image/svg+xml; charset=utf-8");+ assert.match(await icon.text(), /\u{1F3F4}\u{200D}☠️/u);+ const manifest = (await (await fetch(`${base}/manifest.webmanifest`)).json()) as { icons: Array<{ src: string }> };+ assert.equal(manifest.icons[0]?.src, "/brand-mark.svg");+});++test("WEB_UI_FAVICON_SVG is served verbatim and becomes the manifest icon", async () => {+ process.env.WEB_UI_FAVICON_SVG = svg;+ try {+ const icon = await fetch(`${base}/favicon.svg`);+ assert.equal(icon.headers.get("x-content-type-options"), "nosniff");+ assert.equal(await icon.text(), svg);+ const manifest = (await (await fetch(`${base}/manifest.webmanifest`)).json()) as { icons: Array<{ src: string }> };+ assert.equal(manifest.icons[0]?.src, "/favicon.svg");+ } finally {+ delete process.env.WEB_UI_FAVICON_SVG;+ }+});