Add client-only Design Store MVP

Opt-in gateway endpoints (STORE_ENABLED=1, off by default like every other
optional feature here) to browse and publish community themes, reusing the
existing {name, baseTheme, css} export/import shape so no new packaging
format is needed. CSS is sanitized against @import and remote url() before
being accepted, since it's rendered on other users' pages. Client side adds
a "Store" button to the design picker with a browse/install and a publish
view built on the same DesignPanel patterns as import/export.

No website-side store yet - deliberately client-only for the MVP.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Sonnet 5 committed 2026-09-17 21:22:57 +00:00
1 parent 7b52c0baa4
commit bd33b962fe
6 files changed
+483 -2

No files matched your search

+222 -2
View File
@@ -1,8 +1,8 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { createServer as createSecureServer } from "node:https";
import { readFileSync } from "node:fs";
import { readFile, appendFile, rename, stat } from "node:fs/promises";
import { timingSafeEqual } from "node:crypto";
import { readFile, writeFile, appendFile, rename, stat } from "node:fs/promises";
import { timingSafeEqual, randomUUID } from "node:crypto";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { WebSocketServer, type WebSocket } from "ws";
@@ -320,6 +320,222 @@ async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
res.end(JSON.stringify({ ok: true, githubIssueUrl }));
}
// --- Design Store endpoint -------------------------------------------------
//
// Opt-in only, same convention as LOG_CONNECTIONS/FEEDBACK_ENABLED/BROADCAST_TOKEN
// above: public CSS uploads need moderation attention a plain self-hosted
// instance shouldn't inherit just because the code exists. Set STORE_ENABLED=1
// to turn it on.
const STORE_ENABLED = process.env.STORE_ENABLED === "1";
const STORE_ALLOWED_ORIGIN = process.env.STORE_ALLOWED_ORIGIN ?? "*";
// Plain JSON file (whole-array read-modify-write, not JSON-lines like
// feedback.log above): the store needs to list and look up by id, and the
// expected volume (community theme submissions) is small enough that
// rewriting the whole file each time is simpler than a real DB - see the
// "never add SQLite to the public gateway" note in mem:reference_webspeak3_private_sqlite_persistence.
const STORE_DATA_FILE = process.env.STORE_DATA_FILE ?? path.resolve(process.cwd(), "store-themes.json");
const STORE_NAME_MAX_LENGTH = 60;
const STORE_AUTHOR_MAX_LENGTH = 40;
const STORE_CSS_MAX_LENGTH = 50_000;
// Hard cap so the flat file can't grow unbounded from spam that slips past
// rate limiting (a fresh IP per submission, say).
const STORE_MAX_THEMES = 2000;
const STORE_BASE_THEMES = new Set(["standard", "nova", "greenteaspeak", "pulse"]);
interface StoreTheme {
id: string;
name: string;
baseTheme: string;
css: string;
author: string;
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";
}
// 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;
function sanitizeThemeCss(css: string): string | null {
return CSS_IMPORT_RE.test(css) || CSS_REMOTE_URL_RE.test(css) ? null : css;
}
let storeCache: StoreTheme[] | null = null;
async function loadStoreThemes(): Promise<StoreTheme[]> {
if (storeCache) return storeCache;
try {
storeCache = JSON.parse(await readFile(STORE_DATA_FILE, "utf-8")) as StoreTheme[];
} catch {
storeCache = [];
}
return storeCache;
}
async function saveStoreThemes(themes: StoreTheme[]): Promise<void> {
storeCache = themes;
await writeFile(STORE_DATA_FILE, JSON.stringify(themes), "utf-8");
}
// Same in-memory-per-IP approach as FEEDBACK_RATE_LIMIT above; kept as a
// separate map since the two endpoints are independent.
const STORE_RATE_LIMIT = 5;
const STORE_RATE_WINDOW_MS = 60 * 60 * 1000;
const storeSubmissionTimes = new Map<string, number[]>();
function isStoreRateLimited(ip: string): boolean {
const now = Date.now();
const recent = (storeSubmissionTimes.get(ip) ?? []).filter((t) => now - t < STORE_RATE_WINDOW_MS);
recent.push(now);
storeSubmissionTimes.set(ip, recent);
return recent.length > STORE_RATE_LIMIT;
}
function setStoreCors(res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", STORE_ALLOWED_ORIGIN);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
}
async function handleStoreList(res: ServerResponse) {
const themes = await loadStoreThemes();
const listing = themes
.filter((t) => t.status === "approved")
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
.map(({ id, name, baseTheme, author, createdAt }) => ({ id, name, baseTheme, author, createdAt }));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(listing));
}
async function handleStoreDownload(res: ServerResponse, id: string) {
const themes = await loadStoreThemes();
const theme = themes.find((t) => t.id === id && t.status === "approved");
if (!theme) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
// Same shape as the client's own .webspeak3theme.json export/import, so the
// browsed result feeds straight into the existing import validator.
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ name: theme.name, baseTheme: theme.baseTheme, css: theme.css }));
}
async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
const ip = (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
if (isStoreRateLimited(ip)) {
res.writeHead(429, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "rate_limited" }));
return;
}
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > STORE_CSS_MAX_LENGTH + 5_000) {
res.writeHead(413, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "payload_too_large" }));
return;
}
}
let body: { name?: unknown; baseTheme?: unknown; css?: unknown; author?: unknown; website?: unknown };
try {
body = JSON.parse(raw || "{}");
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_json" }));
return;
}
// Honeypot, same as /api/feedback above.
if (typeof body.website === "string" && body.website.trim() !== "") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
return;
}
const name = typeof body.name === "string" ? body.name.trim().slice(0, STORE_NAME_MAX_LENGTH) : "";
const baseTheme = typeof body.baseTheme === "string" && STORE_BASE_THEMES.has(body.baseTheme) ? body.baseTheme : "";
const rawCss = typeof body.css === "string" ? body.css.slice(0, STORE_CSS_MAX_LENGTH) : "";
const author =
typeof body.author === "string" ? body.author.trim().slice(0, STORE_AUTHOR_MAX_LENGTH) || "Anonymous" : "Anonymous";
if (!name || !baseTheme || !rawCss) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_theme" }));
return;
}
const css = sanitizeThemeCss(rawCss);
if (css === null) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "css_rejected" }));
return;
}
const themes = await loadStoreThemes();
if (themes.length >= STORE_MAX_THEMES) {
res.writeHead(507, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "store_full" }));
return;
}
const theme: StoreTheme = {
id: randomUUID(),
name,
baseTheme,
css,
author,
createdAt: new Date().toISOString(),
status: "approved",
};
themes.push(theme);
try {
await saveStoreThemes(themes);
} catch (err) {
console.error("[store] Failed to save theme:", 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, id: theme.id }));
}
async function handleStore(req: IncomingMessage, res: ServerResponse, pathname: string) {
setStoreCors(res);
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
if (!STORE_ENABLED) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
if (pathname === "/api/store/themes") {
if (req.method === "GET") return handleStoreList(res);
if (req.method === "POST") return handleStoreSubmit(req, res);
} else {
const id = pathname.slice("/api/store/themes/".length);
if (req.method === "GET" && id) return handleStoreDownload(res, id);
}
res.writeHead(405, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "method_not_allowed" }));
}
const DEV_HINT = `<!doctype html><html><body style="font:14px system-ui;padding:2rem;max-width:40rem">
<h1>WebSpeak3 gateway</h1>
<p>WebSocket: <code>/ws</code></p>
@@ -360,6 +576,10 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
await handleBroadcast(req, res);
return;
}
if (requestUrl.pathname === "/api/store/themes" || requestUrl.pathname.startsWith("/api/store/themes/")) {
await handleStore(req, res, requestUrl.pathname);
return;
}
// Container healthcheck target (see Dockerfile). Deliberately its own
// route rather than "/": with WEB_STATIC=0 every browser-facing path
+193
View File
@@ -97,6 +97,17 @@ const FEEDBACK_URL = import.meta.env.DEV
? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "").replace(/^ws(s?):\/\//, "http$1://")}/api/feedback`
: `${window.location.protocol}//${window.location.host}/api/feedback`;
// Same derivation again, for the design store (see gateway/src/index.ts's
// /api/store/themes handler). Unlike FEEDBACK_URL/IS_OWN_HOSTED_INSTANCE this
// isn't limited to the maintainer's own instance - any self-hosted gateway
// can turn STORE_ENABLED on, so the button always shows and the store panel
// itself reports "unavailable" if the gateway 404s.
const STORE_URL = import.meta.env.DEV
? "http://localhost:8080/api/store/themes"
: import.meta.env.VITE_GATEWAY_URL
? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "").replace(/^ws(s?):\/\//, "http$1://")}/api/store/themes`
: `${window.location.protocol}//${window.location.host}/api/store/themes`;
// Ko-fi page of the project (.github/FUNDING.yml). Unlike the feedback button
// below this is not limited to the maintainer's own instance: it ships in
// every build, the Docker image included. Self-hosters who would rather not
@@ -291,6 +302,18 @@ type CustomTheme = {
css: string;
};
/** Metadata for one theme listed by GET /api/store/themes - deliberately
* without `css`, so browsing the store doesn't pull every submission's full
* stylesheet up front. The full package (matching CustomTheme's export
* shape) is fetched separately per-id on install, see STORE_URL above. */
type StoreThemeSummary = {
id: string;
name: string;
baseTheme: DesignTheme;
author: string;
createdAt: string;
};
function isDesignTheme(value: string): value is DesignTheme {
return value === "standard" || value === "nova" || value === "greenteaspeak" || value === "pulse";
}
@@ -5193,6 +5216,7 @@ function DesignPanel({
}) {
const t = useT();
const [editing, setEditing] = useState<CustomThemeDraft | null>(null);
const [storeOpen, setStoreOpen] = useState(false);
const importInputRef = useRef<HTMLInputElement | null>(null);
const builtins: { id: DesignTheme; name: string; desc: string }[] = [
@@ -5250,6 +5274,20 @@ function DesignPanel({
}
};
if (storeOpen) {
return (
<DesignStorePanel
customThemes={customThemes}
onInstall={(theme) => {
const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
onSaveCustomTheme({ id, name: theme.name, baseTheme: theme.baseTheme, css: theme.css });
onSelectionChange(`custom:${id}`);
}}
onClose={() => setStoreOpen(false)}
/>
);
}
if (editing) {
return (
<>
@@ -5363,6 +5401,161 @@ function DesignPanel({
style={{ display: "none" }}
onChange={handleImportSelected}
/>
<button onClick={() => setStoreOpen(true)}>{t("design.store.open")}</button>
</div>
</>
);
}
/** Browse community-submitted designs (GET STORE_URL) and publish one of the
* viewer's own custom themes (POST STORE_URL) - see gateway/src/index.ts's
* /api/store/themes handler. Reports "unavailable" rather than erroring when
* the gateway has STORE_ENABLED off (the default), same as a 404. */
function DesignStorePanel({
customThemes,
onInstall,
onClose,
}: {
customThemes: CustomTheme[];
onInstall: (theme: { name: string; baseTheme: DesignTheme; css: string }) => void;
onClose: () => void;
}) {
const t = useT();
const [themes, setThemes] = useState<StoreThemeSummary[] | null>(null);
const [unavailable, setUnavailable] = useState(false);
const [installedIds, setInstalledIds] = useState<Set<string>>(new Set());
const [publishTarget, setPublishTarget] = useState("");
const [publishAuthor, setPublishAuthor] = useState("");
const [publishing, setPublishing] = useState(false);
const [publishResult, setPublishResult] = useState<"ok" | "error" | null>(null);
const refreshThemes = () =>
fetch(STORE_URL)
.then((res) => {
if (!res.ok) throw new Error(String(res.status));
return res.json() as Promise<StoreThemeSummary[]>;
})
.then(setThemes)
.catch(() => setUnavailable(true));
useEffect(() => {
refreshThemes();
// Only ever needs to run once per panel open - refreshThemes is re-created
// each render but doesn't depend on any prop/state that would need it here.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleInstall = async (id: string) => {
try {
const res = await fetch(`${STORE_URL}/${id}`);
if (!res.ok) throw new Error(String(res.status));
const parsed = await res.json();
if (
!parsed ||
typeof parsed.name !== "string" ||
!isDesignTheme(parsed.baseTheme) ||
typeof parsed.css !== "string"
) {
throw new Error("invalid");
}
onInstall({ name: parsed.name, baseTheme: parsed.baseTheme, css: parsed.css });
setInstalledIds((prev) => new Set(prev).add(id));
} catch {
window.alert(t("design.custom.importError"));
}
};
const handlePublish = async () => {
const theme = customThemes.find((c) => c.id === publishTarget);
if (!theme) return;
setPublishing(true);
setPublishResult(null);
try {
const res = await fetch(STORE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: theme.name,
baseTheme: theme.baseTheme,
css: theme.css,
author: publishAuthor.trim() || undefined,
}),
});
if (!res.ok) throw new Error(String(res.status));
setPublishResult("ok");
setPublishAuthor("");
await refreshThemes();
} catch {
setPublishResult("error");
} finally {
setPublishing(false);
}
};
return (
<>
<h3>{t("design.store.title")}</h3>
{unavailable ? (
<p className="ts-options-subtitle">{t("design.store.unavailable")}</p>
) : themes === null ? (
<p className="ts-options-subtitle">{t("design.store.loading")}</p>
) : (
<>
<div className="ts-design-theme-grid">
{themes.length === 0 && <p className="ts-options-subtitle">{t("design.store.empty")}</p>}
{themes.map((theme) => (
<div key={theme.id} className="ts-design-theme-card ts-design-theme-card-custom">
<div className="ts-design-theme-card-select">
<span className="ts-design-theme-swatch ts-design-theme-swatch-custom" />
<span className="ts-design-theme-card-name">{theme.name}</span>
<span className="ts-design-theme-card-desc">{t("design.store.by", { author: theme.author })}</span>
</div>
<div className="ts-design-theme-card-actions">
<button onClick={() => handleInstall(theme.id)} disabled={installedIds.has(theme.id)}>
{installedIds.has(theme.id) ? t("design.store.installed") : t("design.store.install")}
</button>
</div>
</div>
))}
</div>
<h3>{t("design.store.publishTitle")}</h3>
{customThemes.length === 0 ? (
<p className="ts-options-subtitle">{t("design.store.publish.none")}</p>
) : (
<>
<label className="ts-options-field">
{t("design.store.publish.select")}
<select value={publishTarget} onChange={(e) => setPublishTarget(e.target.value)}>
<option value="" />
{customThemes.map((theme) => (
<option key={theme.id} value={theme.id}>
{theme.name}
</option>
))}
</select>
</label>
<label className="ts-options-field">
{t("design.store.publish.author")}
<input
value={publishAuthor}
onChange={(e) => setPublishAuthor(e.target.value)}
placeholder={t("design.store.publish.authorPlaceholder")}
/>
</label>
<div className="ts-dialog-buttons-right">
<button onClick={handlePublish} disabled={!publishTarget || publishing}>
{t("design.store.publish.submit")}
</button>
</div>
{publishResult === "ok" && <p className="ts-options-subtitle">{t("design.store.publish.success")}</p>}
{publishResult === "error" && <p className="ts-options-subtitle">{t("design.store.publish.error")}</p>}
</>
)}
</>
)}
<div className="ts-dialog-buttons-right">
<button onClick={onClose}>{t("design.store.back")}</button>
</div>
</>
);
+17
View File
@@ -289,6 +289,23 @@
"design.custom.save": "Speichern",
"design.custom.copyOf": "Kopie von {name}",
"design.custom.importError": "Diese Datei konnte nicht als WebSpeak3-Design gelesen werden.",
"design.store.open": "Store",
"design.store.title": "Design-Store",
"design.store.back": "Zurück",
"design.store.loading": "Lädt…",
"design.store.unavailable": "Der Design-Store ist auf diesem Server nicht verfügbar.",
"design.store.empty": "Noch keine Designs im Store.",
"design.store.install": "Installieren",
"design.store.installed": "Installiert",
"design.store.by": "von {author}",
"design.store.publishTitle": "Ein Design veröffentlichen",
"design.store.publish.select": "Eigenes Design auswählen",
"design.store.publish.none": "Du hast noch kein eigenes Design zum Veröffentlichen.",
"design.store.publish.author": "Dein Name (optional)",
"design.store.publish.authorPlaceholder": "Anonym",
"design.store.publish.submit": "Im Store veröffentlichen",
"design.store.publish.success": "Design wurde veröffentlicht!",
"design.store.publish.error": "Veröffentlichen fehlgeschlagen.",
"options.section.erweiterungen": "Erweiterungen",
"options.section.hotkeys": "Hotkeys",
"options.section.whispern": "Whispern",
+17
View File
@@ -289,6 +289,23 @@
"design.custom.save": "Save",
"design.custom.copyOf": "Copy of {name}",
"design.custom.importError": "This file couldn't be read as a WebSpeak3 design.",
"design.store.open": "Store",
"design.store.title": "Design store",
"design.store.back": "Back",
"design.store.loading": "Loading…",
"design.store.unavailable": "The design store isn't available on this server.",
"design.store.empty": "No designs in the store yet.",
"design.store.install": "Install",
"design.store.installed": "Installed",
"design.store.by": "by {author}",
"design.store.publishTitle": "Publish a design",
"design.store.publish.select": "Choose one of your own designs",
"design.store.publish.none": "You don't have a custom design to publish yet.",
"design.store.publish.author": "Your name (optional)",
"design.store.publish.authorPlaceholder": "Anonymous",
"design.store.publish.submit": "Publish to the store",
"design.store.publish.success": "Design published!",
"design.store.publish.error": "Publishing failed.",
"options.section.erweiterungen": "Addons",
"options.section.hotkeys": "Hotkeys",
"options.section.whispern": "Whisper",
+17
View File
@@ -289,6 +289,23 @@
"design.custom.save": "ذخیره",
"design.custom.copyOf": "کپی از {name}",
"design.custom.importError": "این فایل به‌عنوان طراحی WebSpeak3 خوانده نشد.",
"design.store.open": "فروشگاه",
"design.store.title": "فروشگاه طراحی‌ها",
"design.store.back": "بازگشت",
"design.store.loading": "در حال بارگذاری…",
"design.store.unavailable": "فروشگاه طراحی روی این سرور در دسترس نیست.",
"design.store.empty": "هنوز طراحی در فروشگاه نیست.",
"design.store.install": "نصب",
"design.store.installed": "نصب شد",
"design.store.by": "از {author}",
"design.store.publishTitle": "انتشار یک طراحی",
"design.store.publish.select": "یکی از طراحی‌های خودت را انتخاب کن",
"design.store.publish.none": "هنوز طراحی سفارشی برای انتشار نداری.",
"design.store.publish.author": "نام تو (اختیاری)",
"design.store.publish.authorPlaceholder": "ناشناس",
"design.store.publish.submit": "انتشار در فروشگاه",
"design.store.publish.success": "طراحی منتشر شد!",
"design.store.publish.error": "انتشار ناموفق بود.",
"options.section.erweiterungen": "افزونه‌ها",
"options.section.hotkeys": "کلیدهای میانبر",
"options.section.whispern": "نجوا",
+17
View File
@@ -571,6 +571,23 @@
"design.custom.save": "保存",
"design.custom.copyOf": "{name} 的副本",
"design.custom.importError": "该文件无法作为 WebSpeak3 设计读取。",
"design.store.open": "商店",
"design.store.title": "设计商店",
"design.store.back": "返回",
"design.store.loading": "加载中…",
"design.store.unavailable": "此服务器未启用设计商店。",
"design.store.empty": "商店里还没有设计。",
"design.store.install": "安装",
"design.store.installed": "已安装",
"design.store.by": "作者:{author}",
"design.store.publishTitle": "发布设计",
"design.store.publish.select": "选择你自己的设计",
"design.store.publish.none": "你还没有可发布的自定义设计。",
"design.store.publish.author": "你的名字(可选)",
"design.store.publish.authorPlaceholder": "匿名",
"design.store.publish.submit": "发布到商店",
"design.store.publish.success": "设计已发布!",
"design.store.publish.error": "发布失败。",
"recording.autoGainControl": "自动增益控制",
"tree.streaming": "正在直播",
"publish.alpha": "内测",