diff --git a/README.md b/README.md index 6f4e12f..358c715 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,7 @@ All optional; add them under `environment:` in your compose override next to `PO | `STORE_ENABLED` | off | Set to `1` to turn this gateway's own `/api/store/themes` endpoint on. Only needed if you want to run your own Design Store instead of using the maintainer's shared one (see `STORE_URL` build arg above) — the endpoint 404s while unset. | | `STORE_DATA_FILE` | `store-themes.json` in the container's working dir | Where submitted themes (including screenshots) are stored. Mount a volume over this path if they should survive a container recreate. | | `STORE_ALLOWED_ORIGIN` | `*` | CORS origin allowed to call the store endpoint, if you want to restrict it to your own frontend's origin. | -| `STORE_ADMIN_TOKEN` | unset | Bearer token that lets its holder publish under the reserved author name(s) and moderate (delete) any theme. Without it, nobody can. | +| `STORE_ADMIN_TOKEN` | unset | Bearer token for moderation. New submissions wait as "pending" until approved on the review page at `/api/store/admin` (enter the token there); the token holder's own submissions and the reserved author name(s) skip the queue. Without it, nothing ever gets published. Submitted CSS is also checked server-side: no `@import`/`@font-face`, no external `url()` — only inline `data:` images. | | `ALLOWED_SERVERS` | unset (any server) | Comma-separated list of server addresses this gateway is allowed to connect to (e.g. `ts.example.com,*.example.net`). A port is matched separately from the host, so listing `ts.example.com` allows any port on it. An entry starting with `*.` matches any subdomain (`*.example.com` allows `ts.example.com`, not `example.com` itself - list that separately too if it should also be reachable). Locks a self-hosted instance down to specific server(s) instead of acting as a general "connect anywhere" client; a rejected `connect` gets an error back before any connector process is even spawned. | | `ALLOW_PRIVATE_TARGETS` | off | By default the gateway refuses to connect to private/internal addresses (loopback, `10.x`, `192.168.x`, CGNAT, link-local, …), no matter how they were reached (IP, DNS, SRV, TSDNS, nickname, file-transfer redirect), so it can't be abused to probe the network it runs in. **If your TeamSpeak server is on the same LAN as the gateway, set this to `1`.** | | `ALLOWED_ORIGINS` | unset (any origin) | Comma-separated list of web origins allowed to open `/ws` (e.g. `https://client.example.com`). Stops other websites from silently using your gateway as their relay. | diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 20fb415..ef12f8e 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -426,7 +426,11 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => { await handleBroadcast(req, res); return; } - if (requestUrl.pathname === "/api/store/themes" || requestUrl.pathname.startsWith("/api/store/themes/")) { + if ( + requestUrl.pathname === "/api/store/admin" || + requestUrl.pathname === "/api/store/themes" || + requestUrl.pathname.startsWith("/api/store/themes/") + ) { await handleStore(req, res, requestUrl.pathname); return; } diff --git a/gateway/src/store.ts b/gateway/src/store.ts index 89d4ccb..3eed178 100644 --- a/gateway/src/store.ts +++ b/gateway/src/store.ts @@ -11,7 +11,7 @@ // touched. It has zero private modifications, so the overlay just copies it // verbatim; only index.ts's small SQLite-persistence sections need patching. import type { IncomingMessage, ServerResponse } from "node:http"; -import { readFile, writeFile } from "node:fs/promises"; +import { readFile, rename, writeFile } from "node:fs/promises"; import { timingSafeEqual, randomUUID } from "node:crypto"; import path from "node:path"; import { clientIp, createRateLimiter } from "./net.js"; @@ -68,22 +68,47 @@ interface StoreTheme { ratingSum: number; ratingCount: number; createdAt: string; - // ponytail: no moderation queue/admin UI yet - everything publishes as - // "approved" immediately. The field exists so a bad submission can be - // hidden by hand-editing STORE_DATA_FILE (status: "rejected") without a - // schema change, once there's an actual admin surface to do that from. - status: "approved" | "rejected"; + // New submissions start "pending" and only become public once someone + // holding STORE_ADMIN_TOKEN approves them (GET /api/store/admin); rejected + // ones are deleted outright. "rejected" only survives in old data files. + status: "approved" | "pending" | "rejected"; } -// Rendered CSS reaches other users' browsers, so block the two ways a -// stylesheet can reach outside itself. Everything else (colors, selectors, -// animations, pseudo-elements) is harmless - it only ever applies inside the -// app's own theme wrapper class. -const CSS_IMPORT_RE = /@import/i; -const CSS_REMOTE_URL_RE = /url\s*\(\s*["']?\s*(?:https?:)?\/\//i; +// Undo what a plain pattern check would miss: comments splitting a keyword +// (u/**/rl), CSS escapes (\75 rl( is url(), and case. +function normalizeCss(css: string): string { + return css + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/\\([0-9a-f]{1,6})\s?/gi, (_, hex: string) => { + const cp = parseInt(hex, 16); + return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "\ufffd"; + }) + .replace(/\\(.)/gs, "$1") + .toLowerCase(); +} -function sanitizeThemeCss(css: string): string | null { - return CSS_IMPORT_RE.test(css) || CSS_REMOTE_URL_RE.test(css) ? null : css; +// Theme CSS runs in every installer's browser, so it may style the app but +// never load anything: no imports/fonts, no functions that fetch a resource, +// and url() only for inline data: images. Everything else (colors, +// selectors, animations) can at worst look bad - which moderation catches. +const FORBIDDEN_CSS = [ + /@import/, + /@font-face/, + /@namespace/, + /(?:^|[^a-z-])(?:image-set|image|cross-fade|element|src|expression)\s*\(/, + /-moz-binding/, + /behavior\s*:/, + /javascript:/, + /<\/?style/, +]; + +export function isSafeThemeCss(css: string): boolean { + const normalized = normalizeCss(css); + if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false; + for (const match of normalized.matchAll(/url\s*\(\s*(["']?)\s*([^"')\s]*)/g)) { + if (!/^data:image\/(?:png|jpeg|gif|webp|svg\+xml)[;,]/.test(match[2])) return false; + } + return true; } let storeCache: StoreTheme[] | null = null; @@ -100,7 +125,22 @@ async function loadStoreThemes(): Promise { async function saveStoreThemes(themes: StoreTheme[]): Promise { storeCache = themes; - await writeFile(STORE_DATA_FILE, JSON.stringify(themes), "utf-8"); + // Write-then-rename: a crash mid-write must not leave a truncated file, + // which loadStoreThemes() would read as "no themes" and then overwrite. + const tmp = `${STORE_DATA_FILE}.tmp`; + await writeFile(tmp, JSON.stringify(themes), "utf-8"); + await rename(tmp, STORE_DATA_FILE); +} + +function isAdminRequest(req: IncomingMessage): boolean { + const authHeader = req.headers.authorization ?? ""; + return authHeader.startsWith("Bearer ") && isValidStoreAdminToken(authHeader.slice("Bearer ".length)); +} + +// Approved, and still passing today's CSS check - themes published before +// that check got stricter are hidden instead of served. +function isPublic(theme: StoreTheme): boolean { + return theme.status === "approved" && isSafeThemeCss(theme.css); } // Same in-memory-per-IP approach as FEEDBACK_RATE_LIMIT in index.ts; kept as a @@ -130,7 +170,7 @@ function storeRating(theme: StoreTheme): { average: number; count: number } { async function handleStoreList(res: ServerResponse) { const themes = await loadStoreThemes(); const listing = themes - .filter((t) => t.status === "approved") + .filter(isPublic) .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) .map((t) => ({ id: t.id, @@ -146,9 +186,9 @@ async function handleStoreList(res: ServerResponse) { res.end(JSON.stringify(listing)); } -async function handleStoreDownload(res: ServerResponse, id: string) { +async function handleStoreDownload(req: IncomingMessage, res: ServerResponse, id: string) { const themes = await loadStoreThemes(); - const theme = themes.find((t) => t.id === id && t.status === "approved"); + const theme = themes.find((t) => t.id === id && (isPublic(t) || isAdminRequest(req))); if (!theme) { res.writeHead(404, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "not_found" })); @@ -160,9 +200,9 @@ async function handleStoreDownload(res: ServerResponse, id: string) { res.end(JSON.stringify({ name: theme.name, baseTheme: theme.baseTheme, css: theme.css })); } -async function handleStoreScreenshot(res: ServerResponse, id: string) { +async function handleStoreScreenshot(req: IncomingMessage, res: ServerResponse, id: string) { const themes = await loadStoreThemes(); - const theme = themes.find((t) => t.id === id && t.status === "approved"); + const theme = themes.find((t) => t.id === id && (isPublic(t) || isAdminRequest(req))); if (!theme?.screenshot) { res.writeHead(404, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "not_found" })); @@ -214,7 +254,7 @@ async function handleStoreRate(req: IncomingMessage, res: ServerResponse, id: st } const themes = await loadStoreThemes(); - const theme = themes.find((t) => t.id === id && t.status === "approved"); + const theme = themes.find((t) => t.id === id && isPublic(t)); if (!theme) { res.writeHead(404, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "not_found" })); @@ -296,18 +336,17 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) { return; } + const isAdmin = isAdminRequest(req); if (STORE_RESERVED_AUTHORS.has(author.toLowerCase())) { - const authHeader = req.headers.authorization ?? ""; - const token = authHeader.startsWith("Bearer ") ? authHeader.slice("Bearer ".length) : ""; - if (!isValidStoreAdminToken(token)) { + if (!isAdmin) { res.writeHead(403, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "author_reserved" })); return; } } - const css = sanitizeThemeCss(rawCss); - if (css === null) { + const css = rawCss; + if (!isSafeThemeCss(css)) { res.writeHead(400, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "css_rejected" })); return; @@ -341,7 +380,8 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) { ratingSum: 0, ratingCount: 0, createdAt: new Date().toISOString(), - status: "approved", + // The admin's own submissions skip the queue - they'd approve them anyway. + status: isAdmin ? "approved" : "pending", }; themes.push(theme); try { @@ -354,9 +394,95 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) { } res.writeHead(200, { "Content-Type": "application/json" }); - res.end(JSON.stringify({ ok: true, id: theme.id })); + res.end(JSON.stringify({ ok: true, id: theme.id, status: theme.status })); + if (theme.status === "pending") console.log(`[store] New theme awaiting review: "${theme.name}" (${theme.id})`); } +async function handleStorePending(req: IncomingMessage, res: ServerResponse) { + if (!isAdminRequest(req)) { + res.writeHead(401, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "unauthorized" })); + return; + } + const themes = await loadStoreThemes(); + const pending = themes + .filter((t) => t.status === "pending") + .map(({ screenshot, ratingSum: _s, ratingCount: _c, ...t }) => ({ ...t, hasScreenshot: Boolean(screenshot) })); + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(pending)); +} + +async function handleStoreModerate(req: IncomingMessage, res: ServerResponse, id: string, action: string) { + if (!isAdminRequest(req)) { + res.writeHead(401, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "unauthorized" })); + return; + } + const themes = await loadStoreThemes(); + const index = themes.findIndex((t) => t.id === id); + if (index === -1) { + res.writeHead(404, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "not_found" })); + return; + } + // Reject and delete are the same thing: drop it, freeing its slot. + if (action === "approve") themes[index].status = "approved"; + else themes.splice(index, 1); + try { + await saveStoreThemes(themes); + } catch (err) { + console.error("[store] Failed to save moderation result:", err); + res.writeHead(500, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "save_failed" })); + return; + } + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ ok: true })); +} + +// Minimal moderation page. The theme CSS is shown as text only (textContent), +// never applied, so reviewing a hostile submission is harmless. +const ADMIN_PAGE = ` +Store moderation

Design Store – pending themes

+

+
`; + export async function handleStore(req: IncomingMessage, res: ServerResponse, pathname: string) { setStoreCors(res); if (req.method === "OPTIONS") { @@ -370,13 +496,22 @@ export async function handleStore(req: IncomingMessage, res: ServerResponse, pat return; } + if (pathname === "/api/store/admin") { + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); + res.end(ADMIN_PAGE); + return; + } if (pathname === "/api/store/themes") { if (req.method === "GET") return handleStoreList(res); if (req.method === "POST") return handleStoreSubmit(req, res); } else { const [id, sub] = pathname.slice("/api/store/themes/".length).split("/"); - if (id && !sub && req.method === "GET") return handleStoreDownload(res, id); - if (id && sub === "screenshot" && req.method === "GET") return handleStoreScreenshot(res, id); + if (id === "pending" && !sub && req.method === "GET") return handleStorePending(req, res); + if (id && !sub && req.method === "GET") return handleStoreDownload(req, res, id); + if (id && sub === "screenshot" && req.method === "GET") return handleStoreScreenshot(req, res, id); + if (id && (sub === "approve" || sub === "reject") && req.method === "POST") { + return handleStoreModerate(req, res, id, sub); + } if (id && sub === "rate" && req.method === "POST") return handleStoreRate(req, res, id); } diff --git a/web/src/App.tsx b/web/src/App.tsx index 3dcea61..f1aa97f 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -5487,7 +5487,7 @@ function DesignStorePanel({ () => localStorage.getItem(STORE_ADMIN_TOKEN_KEY) ?? "" ); const [publishing, setPublishing] = useState(false); - const [publishResult, setPublishResult] = useState<"ok" | "error" | null>(null); + const [publishResult, setPublishResult] = useState<"ok" | "pending" | "error" | null>(null); const [ratedIds, setRatedIds] = useState>(new Set()); const refreshThemes = () => @@ -5567,7 +5567,8 @@ function DesignStorePanel({ }), }); if (!res.ok) throw new Error(String(res.status)); - setPublishResult("ok"); + const body = (await res.json().catch(() => ({}))) as { status?: string }; + setPublishResult(body.status === "pending" ? "pending" : "ok"); setPublishAuthor(""); setPublishDescription(""); setPublishScreenshot(null); @@ -5715,6 +5716,7 @@ function DesignStorePanel({ {t("design.store.publish.submit")} {publishResult === "ok" &&

{t("design.store.publish.success")}

} + {publishResult === "pending" &&

{t("design.store.publish.pending")}

} {publishResult === "error" &&

{t("design.store.publish.error")}

} )} diff --git a/web/src/locales/de.json b/web/src/locales/de.json index 4862deb..46814b1 100644 --- a/web/src/locales/de.json +++ b/web/src/locales/de.json @@ -315,6 +315,7 @@ "design.store.publish.adminTokenPlaceholder": "Leer lassen, außer du weißt, was das ist", "design.store.publish.submit": "Im Store veröffentlichen", "design.store.publish.success": "Design wurde veröffentlicht!", + "design.store.publish.pending": "Danke! Dein Design wurde eingereicht und erscheint im Store, sobald es geprüft wurde.", "design.store.publish.error": "Veröffentlichen fehlgeschlagen.", "options.section.erweiterungen": "Erweiterungen", "options.section.hotkeys": "Hotkeys", diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 2700e6b..0a774d6 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -315,6 +315,7 @@ "design.store.publish.adminTokenPlaceholder": "Leave empty unless you know what this is", "design.store.publish.submit": "Publish to the store", "design.store.publish.success": "Design published!", + "design.store.publish.pending": "Thanks! Your design was submitted and will appear in the store once it has been reviewed.", "design.store.publish.error": "Publishing failed.", "options.section.erweiterungen": "Addons", "options.section.hotkeys": "Hotkeys", diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json index b974f85..d64f0f5 100644 --- a/web/src/locales/fa.json +++ b/web/src/locales/fa.json @@ -315,6 +315,7 @@ "design.store.publish.adminTokenPlaceholder": "اگر نمی‌دانی این چیست، خالی بگذار", "design.store.publish.submit": "انتشار در فروشگاه", "design.store.publish.success": "طراحی منتشر شد!", + "design.store.publish.pending": "ممنون! طراحی تو ارسال شد و پس از بررسی در فروشگاه نمایش داده می‌شود.", "design.store.publish.error": "انتشار ناموفق بود.", "options.section.erweiterungen": "افزونه‌ها", "options.section.hotkeys": "کلیدهای میانبر", diff --git a/web/src/locales/zh-CN.json b/web/src/locales/zh-CN.json index 7164fd8..a86c0d2 100644 --- a/web/src/locales/zh-CN.json +++ b/web/src/locales/zh-CN.json @@ -598,6 +598,7 @@ "design.store.publish.adminTokenPlaceholder": "不确定的话请留空", "design.store.publish.submit": "发布到商店", "design.store.publish.success": "设计已发布!", + "design.store.publish.pending": "谢谢!你的设计已提交,审核通过后将显示在商店中。", "design.store.publish.error": "发布失败。", "recording.autoGainControl": "自动增益控制", "tree.streaming": "正在直播",