Add in-client feedback form (own-hosted instance only)

- gateway: opt-in POST /api/feedback endpoint (FEEDBACK_ENABLED=1),
  logs submissions to feedback.log and optionally files a GitHub issue
  on Moepchi/webspeak3 when GITHUB_TOKEN is set and the user opts in.
  Rate-limited per IP, CORS-aware for split-hosted deployments.
- web: new "Feedback" menu entry under Extras, gated to
  client.webspeak3.de at runtime (IS_OWN_HOSTED_INSTANCE) so other
  self-hosted/forked deployments and the public demo never see it.
  New FeedbackDialog with category/message/email fields and an
  opt-in "publish as GitHub issue" checkbox. New i18n strings (DE/EN).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
MoepchiandClaude Sonnet 5 committed 2026-09-10 07:29:48 +02:00
1 parent 1d20eb15de
commit e2a09fbb43
4 files changed
+396 -4

No files matched your search

+168 -4
View File
@@ -1,5 +1,5 @@
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { readFile, appendFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { WebSocketServer, type WebSocket } from "ws";
@@ -50,6 +50,165 @@ const MIME_TYPES: Record<string, string> = {
".webmanifest": "application/manifest+json",
};
// --- Feedback endpoint ---------------------------------------------------
//
// Opt-in only, same convention as LOG_CONNECTIONS above: this is an open-
// source, self-hostable image, so other instances don't get a public
// feedback inbox (and potential GitHub-issue creator) just because it's in
// the codebase. Set FEEDBACK_ENABLED=1 on the instance you want it on. The
// web client only shows the "Feedback" menu entry on specific hostnames
// (see IS_OWN_HOSTED_INSTANCE in web/src/App.tsx), but this endpoint
// enforces its own opt-in independently since it's reachable directly over
// HTTP by anyone who finds the gateway's address, not just from that UI.
const FEEDBACK_ENABLED = process.env.FEEDBACK_ENABLED === "1";
// The web app is commonly hosted on a different origin than the gateway
// (see mem:deployment / GATEWAY_URL in web/), so this needs its own CORS
// allowance; default "*" since the endpoint is opt-in, rate-limited, and
// only ever accepts a feedback submission, nothing that reads data back.
const FEEDBACK_ALLOWED_ORIGIN = process.env.FEEDBACK_ALLOWED_ORIGIN ?? "*";
// A token with "Issues: write" access on the target repo. Without it,
// feedback is still accepted and logged, just never turned into an issue.
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_REPO = process.env.GITHUB_REPO ?? "Moepchi/webspeak3";
// Plain JSON-lines file, not a database - this is a low-volume inbox, not
// analytics. Defaults under the container's WORKDIR (/app in the Docker
// image); mount a volume over it if you want submissions to survive a
// container recreate.
const FEEDBACK_LOG_FILE = process.env.FEEDBACK_LOG_FILE ?? path.resolve(process.cwd(), "feedback.log");
const FEEDBACK_CATEGORIES = new Set(["bug", "idea", "other"]);
const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
// Small in-memory rate limit: a handful of submissions per IP per hour is
// far more than any real user needs, and keeps one abusive client from
// spamming the log file or (worse) the GitHub issue tracker. In-memory is
// fine here - it only needs to survive as long as the process does.
const FEEDBACK_RATE_LIMIT = 5;
const FEEDBACK_RATE_WINDOW_MS = 60 * 60 * 1000;
const feedbackSubmissionTimes = new Map<string, number[]>();
function isFeedbackRateLimited(ip: string): boolean {
const now = Date.now();
const recent = (feedbackSubmissionTimes.get(ip) ?? []).filter((t) => now - t < FEEDBACK_RATE_WINDOW_MS);
recent.push(now);
feedbackSubmissionTimes.set(ip, recent);
return recent.length > FEEDBACK_RATE_LIMIT;
}
async function createGithubIssue(payload: {
category: string;
message: string;
email?: string;
}): Promise<string | undefined> {
if (!GITHUB_TOKEN) return undefined;
const title = `[Feedback/${payload.category}] ${payload.message.replace(/\s+/g, " ").trim().slice(0, 72)}`;
const body = [
payload.message,
"",
"---",
`Category: ${payload.category}`,
payload.email ? `Contact: ${payload.email}` : undefined,
"_Submitted via the in-client feedback form._",
]
.filter((line): line is string => Boolean(line))
.join("\n");
const res = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/issues`, {
method: "POST",
headers: {
Authorization: `Bearer ${GITHUB_TOKEN}`,
Accept: "application/vnd.github+json",
"Content-Type": "application/json",
"User-Agent": "webspeak3-gateway",
},
body: JSON.stringify({ title, body, labels: ["feedback"] }),
});
if (!res.ok) {
console.error(`[feedback] GitHub issue creation failed (${res.status}): ${await res.text().catch(() => "")}`);
return undefined;
}
const json = (await res.json()) as { html_url?: string };
return json.html_url;
}
async function handleFeedback(req: IncomingMessage, res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", FEEDBACK_ALLOWED_ORIGIN);
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
if (!FEEDBACK_ENABLED) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not_found" }));
return;
}
if (req.method !== "POST") {
res.writeHead(405, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "method_not_allowed" }));
return;
}
const ip = (req.socket.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
if (isFeedbackRateLimited(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 > 20_000) {
res.writeHead(413, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "payload_too_large" }));
return;
}
}
let body: { category?: unknown; message?: unknown; email?: unknown; publishAsIssue?: unknown };
try {
body = JSON.parse(raw || "{}");
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "invalid_json" }));
return;
}
const category = typeof body.category === "string" && FEEDBACK_CATEGORIES.has(body.category) ? body.category : "other";
const message =
typeof body.message === "string" ? body.message.trim().slice(0, FEEDBACK_MESSAGE_MAX_LENGTH) : "";
const email = typeof body.email === "string" ? body.email.trim().slice(0, 200) || undefined : undefined;
const publishAsIssue = body.publishAsIssue === true;
if (!message) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "message_required" }));
return;
}
try {
const entry = { at: new Date().toISOString(), category, message, email };
await appendFile(FEEDBACK_LOG_FILE, JSON.stringify(entry) + "\n", "utf-8");
} catch (err) {
console.error("[feedback] Failed to write feedback log:", err);
}
let githubIssueUrl: string | undefined;
if (publishAsIssue) {
try {
githubIssueUrl = await createGithubIssue({ category, message, email });
} catch (err) {
console.error("[feedback] Failed to create GitHub issue:", err);
}
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, githubIssueUrl }));
}
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>
@@ -62,13 +221,18 @@ to serve the UI from this port again.</p>
const server = createServer((req, res) => {
void (async () => {
try {
const requestUrl = new URL(req.url ?? "/", "http://localhost");
if (requestUrl.pathname === "/api/feedback") {
await handleFeedback(req, res);
return;
}
if (!SERVE_STATIC) {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(DEV_HINT);
return;
}
const url = new URL(req.url ?? "/", "http://localhost");
let filePath = path.join(WEB_DIST, decodeURIComponent(url.pathname));
let filePath = path.join(WEB_DIST, decodeURIComponent(requestUrl.pathname));
if (!filePath.startsWith(WEB_DIST)) {
res.writeHead(403);
res.end();
+42
View File
@@ -3441,6 +3441,48 @@
opacity: 0.5;
}
.ts-dialog-field textarea {
border: 1px solid var(--border);
border-radius: 2px;
padding: 0.4rem;
font-size: 13px;
font-family: inherit;
resize: vertical;
background: var(--input-bg);
color: var(--input-text);
}
.ts-feedback-dialog {
width: 26rem;
max-width: 90vw;
}
.ts-feedback-intro,
.ts-feedback-hint {
font-size: 12px;
color: var(--text-muted);
margin: 0;
}
.ts-feedback-checkbox-field {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.4rem;
font-size: 12px;
}
.ts-feedback-error {
font-size: 12px;
color: var(--danger, #e0637a);
margin: 0;
}
.ts-feedback-success {
font-size: 13px;
margin: 0.5rem 0;
}
.ts-dialog-grid {
display: grid;
grid-template-columns: 1fr 1fr;
+148
View File
@@ -75,6 +75,27 @@ const GATEWAY_URL = import.meta.env.DEV
? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "")}/ws`
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`;
// Same derivation as GATEWAY_URL above, but for a plain HTTP POST (the
// feedback form) instead of the WebSocket - see gateway/src/index.ts's
// /api/feedback handler.
const FEEDBACK_URL = import.meta.env.DEV
? "http://localhost:8080/api/feedback"
: import.meta.env.VITE_GATEWAY_URL
? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "")}/api/feedback`
: `${window.location.protocol}//${window.location.host}/api/feedback`;
// This file's frontend is deployed as multiple Cloudflare Pages projects
// from the same repo/build (see mem:deployment) - only the maintainer's own
// production instance talks to a gateway they actually operate and read
// feedback from, so the "Feedback" menu entry only appears there. Every
// other deployment (self-hosted forks, and the public demo - which has no
// real gateway at all, see DEMO_MODE) simply never shows it. This is a UI
// nicety, not a security boundary: the gateway's own FEEDBACK_ENABLED
// opt-in (see gateway/src/index.ts) is what actually decides whether
// submissions are accepted at all.
const OWN_HOSTED_HOSTNAMES = new Set(["client.webspeak3.de"]);
const IS_OWN_HOSTED_INSTANCE = !DEMO_MODE && OWN_HOSTED_HOSTNAMES.has(window.location.hostname);
// One-time migration from the pre-rename "ts-web-client:*" localStorage
// namespace so existing users don't lose their favorites/preferences.
(function migrateLegacyStorageKeys() {
@@ -1545,6 +1566,118 @@ function ChannelPasswordDialog({
);
}
type FeedbackCategory = "bug" | "idea" | "other";
function FeedbackDialog({ onClose }: { onClose: () => void }) {
const t = useT();
const backdrop = useBackdropDismiss(onClose);
const [category, setCategory] = useState<FeedbackCategory>("bug");
const [message, setMessage] = useState("");
const [email, setEmail] = useState("");
const [publishAsIssue, setPublishAsIssue] = useState(false);
const [status, setStatus] = useState<"idle" | "sending" | "sent" | "error">("idle");
const [issueUrl, setIssueUrl] = useState<string | undefined>(undefined);
const handleSend = async () => {
const trimmed = message.trim();
if (!trimmed || status === "sending") return;
setStatus("sending");
try {
const res = await fetch(FEEDBACK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
category,
message: trimmed,
email: email.trim() || undefined,
publishAsIssue,
}),
});
if (!res.ok) throw new Error(String(res.status));
const json = (await res.json()) as { ok?: boolean; githubIssueUrl?: string };
setIssueUrl(json.githubIssueUrl);
setStatus("sent");
} catch {
setStatus("error");
}
};
return (
<div className="ts-dialog-backdrop" {...backdrop}>
<div className="ts-dialog ts-feedback-dialog" onClick={(e) => e.stopPropagation()}>
<div className="ts-dialog-titlebar">
<span>{t("feedback.dialog.title")}</span>
<button onClick={onClose} title={t("dialog.close")}>
✕
</button>
</div>
<div className="ts-dialog-body">
{status === "sent" ? (
<p className="ts-feedback-success">
{issueUrl ? (
<>
{t("feedback.dialog.successWithIssue")}{" "}
<a href={issueUrl} target="_blank" rel="noreferrer">
{issueUrl}
</a>
</>
) : (
t("feedback.dialog.success")
)}
</p>
) : (
<>
<p className="ts-feedback-intro">{t("feedback.dialog.intro")}</p>
<label className="ts-dialog-field">
{t("feedback.dialog.category")}
<select value={category} onChange={(e) => setCategory(e.target.value as FeedbackCategory)}>
<option value="bug">{t("feedback.dialog.category.bug")}</option>
<option value="idea">{t("feedback.dialog.category.idea")}</option>
<option value="other">{t("feedback.dialog.category.other")}</option>
</select>
</label>
<label className="ts-dialog-field">
{t("feedback.dialog.message")}
<textarea
autoFocus
rows={5}
value={message}
placeholder={t("feedback.dialog.messagePlaceholder")}
onChange={(e) => setMessage(e.target.value)}
/>
</label>
<label className="ts-dialog-field">
{t("feedback.dialog.email")}
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</label>
<label className="ts-feedback-checkbox-field">
<input
type="checkbox"
checked={publishAsIssue}
onChange={(e) => setPublishAsIssue(e.target.checked)}
/>
{t("feedback.dialog.publishAsIssue")}
</label>
<p className="ts-feedback-hint">{t("feedback.dialog.publishAsIssueHint")}</p>
{status === "error" && <p className="ts-feedback-error">{t("feedback.dialog.error")}</p>}
</>
)}
</div>
<div className="ts-dialog-buttons">
<div className="ts-dialog-buttons-right">
{status !== "sent" && (
<button onClick={() => void handleSend()} disabled={!message.trim() || status === "sending"}>
{status === "sending" ? t("feedback.dialog.sending") : t("feedback.dialog.send")}
</button>
)}
<button onClick={onClose}>{status === "sent" ? t("dialog.close") : t("feedback.dialog.cancel")}</button>
</div>
</div>
</div>
</div>
);
}
function FavoritesDialog({
favorites,
prefillNew,
@@ -5087,6 +5220,7 @@ function AppInner() {
wrongPassword: boolean;
} | null>(null);
const [connectDialogOpen, setConnectDialogOpen] = useState(false);
const [feedbackOpen, setFeedbackOpen] = useState(false);
const [connectDialogExpanded, setConnectDialogExpanded] = useState(false);
const [log, setLog] = useState<LogEntry[]>([]);
const [connected, setConnected] = useState(false);
@@ -8168,6 +8302,18 @@ function AppInner() {
<span className="ts-menu-item-label">{t("menu.extras.options")}</span>
<span className="ts-menu-item-shortcut">Alt+P</span>
</button>
{IS_OWN_HOSTED_INSTANCE && (
<button
className="ts-menu-item"
onClick={() => {
setFeedbackOpen(true);
setExtrasMenuOpen(false);
}}
>
<span className="ts-menu-item-icon">💬</span>
<span className="ts-menu-item-label">{t("menu.extras.feedback")}</span>
</button>
)}
</div>
)}
</div>
@@ -8430,6 +8576,8 @@ function AppInner() {
/>
)}
{feedbackOpen && <FeedbackDialog onClose={() => setFeedbackOpen(false)} />}
{favoritesDialogMode && (
<FavoritesDialog
favorites={favorites}
+38
View File
@@ -45,6 +45,25 @@ const translations: Record<Lang, Record<string, string>> = {
"menu.extras.startMultitrackRecording": "Start Multitrack Recording",
"menu.extras.stopRecording": "Aufnahme beenden",
"menu.extras.options": "Optionen",
"menu.extras.feedback": "Feedback geben",
"feedback.dialog.title": "Feedback",
"feedback.dialog.intro": "Melde einen Fehler oder teile eine Idee zur Weiterentwicklung von WebSpeak3 mit.",
"feedback.dialog.category": "Kategorie",
"feedback.dialog.category.bug": "Fehler",
"feedback.dialog.category.idea": "Idee",
"feedback.dialog.category.other": "Sonstiges",
"feedback.dialog.message": "Nachricht",
"feedback.dialog.messagePlaceholder": "Was ist passiert, oder was schlägst du vor?",
"feedback.dialog.email": "E-Mail (optional, für Rückfragen)",
"feedback.dialog.publishAsIssue": "Als öffentliches GitHub-Issue veröffentlichen",
"feedback.dialog.publishAsIssueHint": "Ohne Haken bleibt dein Feedback privat und geht nur an den Betreiber.",
"feedback.dialog.send": "Senden",
"feedback.dialog.cancel": "Abbrechen",
"feedback.dialog.sending": "Wird gesendet…",
"feedback.dialog.success": "Danke für dein Feedback!",
"feedback.dialog.successWithIssue": "Danke! Issue erstellt:",
"feedback.dialog.error": "Senden fehlgeschlagen. Bitte später erneut versuchen.",
"toolbar.setAway": "Als abwesend markieren",
"toolbar.backOnline": "Wieder online",
@@ -611,6 +630,25 @@ const translations: Record<Lang, Record<string, string>> = {
"menu.extras.startMultitrackRecording": "Start Multitrack Recording",
"menu.extras.stopRecording": "Stop Recording",
"menu.extras.options": "Options",
"menu.extras.feedback": "Send Feedback",
"feedback.dialog.title": "Feedback",
"feedback.dialog.intro": "Report a bug or share an idea to help improve WebSpeak3.",
"feedback.dialog.category": "Category",
"feedback.dialog.category.bug": "Bug",
"feedback.dialog.category.idea": "Idea",
"feedback.dialog.category.other": "Other",
"feedback.dialog.message": "Message",
"feedback.dialog.messagePlaceholder": "What happened, or what are you suggesting?",
"feedback.dialog.email": "Email (optional, for follow-up)",
"feedback.dialog.publishAsIssue": "Publish as a public GitHub issue",
"feedback.dialog.publishAsIssueHint": "Leave unchecked to keep your feedback private, visible only to the maintainer.",
"feedback.dialog.send": "Send",
"feedback.dialog.cancel": "Cancel",
"feedback.dialog.sending": "Sending…",
"feedback.dialog.success": "Thanks for your feedback!",
"feedback.dialog.successWithIssue": "Thanks! Issue created:",
"feedback.dialog.error": "Failed to send. Please try again later.",
"toolbar.setAway": "Set away",
"toolbar.backOnline": "Back online",