From da4f416e3225dce9a5cfc4566eb81f25844b2e13 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Fri, 18 Sep 2026 11:09:37 +0000 Subject: [PATCH] Extract feedback/connection logging into a swappable module Same pattern as the recent store.ts extraction: feedback-log writes and connection-event logging move from inline file/console I/O in index.ts into activity-log.ts, called via logFeedback()/logConnectionEvent(). The public default behavior is unchanged (JSON-lines file with rotation, console logging gated by LOG_CONNECTIONS). This is the piece of the private SQLite overlay's persistence swap that's a clean drop-in replacement - the private VPS gateway now imports the same two function names from its own activity-log.ts (SQLite-backed) instead of patching these call sites into a forked index.ts. Note: the private overlay's live host-ban enforcement (blocked_hosts table, heartbeat-driven disconnect) is NOT extracted here - it has no public equivalent and touches the WS connection/heartbeat control flow directly, not just a persistence call. Left as-is for now. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- gateway/src/activity-log.ts | 69 +++++++++++++++++++++++++++++++++++++ gateway/src/index.ts | 51 ++++----------------------- 2 files changed, 76 insertions(+), 44 deletions(-) create mode 100644 gateway/src/activity-log.ts diff --git a/gateway/src/activity-log.ts b/gateway/src/activity-log.ts new file mode 100644 index 0000000..e75d092 --- /dev/null +++ b/gateway/src/activity-log.ts @@ -0,0 +1,69 @@ +// --- Activity logging (feedback + connection events) ----------------------- +// +// Narrow interface so the private VPS overlay can swap in SQLite persistence +// (see mem:reference_webspeak3_private_sqlite_persistence) without forking +// index.ts - only this module differs between public and private; index.ts's +// two call sites just call logFeedback/logConnectionEvent unconditionally. +// This file itself has zero private modifications, same as store.ts. +import { appendFile, rename, stat } from "node:fs/promises"; +import path from "node:path"; + +// Plain JSON-lines file. 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"); +// Simple size-based rotation: once the log crosses this size, the current +// file is moved to feedback.log.1 (overwriting any previous one) and a +// fresh file is started. Keeps disk usage bounded on a plain JSON-lines +// file with no other retention policy. +const FEEDBACK_LOG_MAX_BYTES = 5 * 1024 * 1024; + +async function rotateFeedbackLogIfNeeded(): Promise { + try { + const { size } = await stat(FEEDBACK_LOG_FILE); + if (size < FEEDBACK_LOG_MAX_BYTES) return; + await rename(FEEDBACK_LOG_FILE, `${FEEDBACK_LOG_FILE}.1`); + } catch (err) { + // ENOENT just means there's no log yet - nothing to rotate. + if ((err as NodeJS.ErrnoException).code !== "ENOENT") { + console.error("[feedback] Failed to rotate feedback log:", err); + } + } +} + +export interface FeedbackEntry { + at: string; + category: string; + message: string; + email?: string; +} + +export async function logFeedback(entry: FeedbackEntry): Promise { + try { + await rotateFeedbackLogIfNeeded(); + await appendFile(FEEDBACK_LOG_FILE, JSON.stringify(entry) + "\n", "utf-8"); + } catch (err) { + console.error("[feedback] Failed to write feedback log:", err); + } +} + +// Opt-in only, off by default: this is an open-source, self-hostable image, +// and other instances shouldn't get connection logging just because it's in +// the codebase. Set LOG_CONNECTIONS=1 in the .env of the instance you want it +// on. Logs only host/server-name/timestamp — no nickname, no IP. +export const LOG_CONNECTIONS = process.env.LOG_CONNECTIONS === "1"; + +export interface ConnectionEvent { + type: "connected" | "disconnected"; + host: string; + server?: string; +} + +export function logConnectionEvent(event: ConnectionEvent): void { + if (!LOG_CONNECTIONS) return; + if (event.type === "connected") { + console.log(`[connections] connected host=${event.host} server=${event.server} at=${new Date().toISOString()}`); + } else { + console.log(`[connections] disconnected host=${event.host} at=${new Date().toISOString()}`); + } +} diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 086fd25..248c823 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -1,13 +1,14 @@ 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 { readFile } from "node:fs/promises"; import { timingSafeEqual } from "node:crypto"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { WebSocketServer, type WebSocket } from "ws"; import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js"; import { handleStore } from "./store.js"; +import { logFeedback, logConnectionEvent } from "./activity-log.js"; const SERVER_TYPES = new Set(["teamspeak", "teaspeak", "auto"]); @@ -26,12 +27,6 @@ function parsePrivilegeKey(msg: { privilegeKey?: unknown; token?: unknown }): st const PORT = Number(process.env.PORT ?? 8080); -// Opt-in only, off by default: this is an open-source, self-hostable image, -// and other instances shouldn't get connection logging just because it's in -// the codebase. Set LOG_CONNECTIONS=1 in the .env of the instance you want it -// on. Logs only host/server-name/timestamp — no nickname, no IP. -const LOG_CONNECTIONS = process.env.LOG_CONNECTIONS === "1"; - // In production (Docker), the built web app lives alongside the gateway and // is served from the same port as the WebSocket endpoint, so a single // reverse-proxied origin (e.g. a Zoraxy subdomain) is enough for everything. @@ -74,15 +69,6 @@ const FEEDBACK_ALLOWED_ORIGIN = process.env.FEEDBACK_ALLOWED_ORIGIN ?? "*"; // 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. 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"); -// Simple size-based rotation: once the log crosses this size, the current -// file is moved to feedback.log.1 (overwriting any previous one) and a -// fresh file is started. Keeps disk usage bounded on a plain JSON-lines -// file with no other retention policy. -const FEEDBACK_LOG_MAX_BYTES = 5 * 1024 * 1024; const FEEDBACK_CATEGORIES = new Set(["bug", "idea", "report", "other"]); const FEEDBACK_MESSAGE_MAX_LENGTH = 4000; @@ -164,19 +150,6 @@ async function handleBroadcast(req: IncomingMessage, res: ServerResponse) { res.end(JSON.stringify({ ok: true, sent })); } -async function rotateFeedbackLogIfNeeded(): Promise { - try { - const { size } = await stat(FEEDBACK_LOG_FILE); - if (size < FEEDBACK_LOG_MAX_BYTES) return; - await rename(FEEDBACK_LOG_FILE, `${FEEDBACK_LOG_FILE}.1`); - } catch (err) { - // ENOENT just means there's no log yet - nothing to rotate. - if ((err as NodeJS.ErrnoException).code !== "ENOENT") { - console.error("[feedback] Failed to rotate feedback log:", err); - } - } -} - // 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 @@ -300,13 +273,7 @@ async function handleFeedback(req: IncomingMessage, res: ServerResponse) { return; } - try { - await rotateFeedbackLogIfNeeded(); - 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); - } + await logFeedback({ at: new Date().toISOString(), category, message, email }); let githubIssueUrl: string | undefined; if (publishAsIssue) { @@ -574,14 +541,10 @@ wss.on("connection", (socket: WebSocket) => { liveConnections.add(connection); connection.onEvent((event) => { if (shuttingDown) return; - if (LOG_CONNECTIONS) { - if (event.type === "connected") { - console.log( - `[connections] connected host=${options.host} server=${event.serverName} at=${new Date().toISOString()}` - ); - } else if (event.type === "disconnected") { - console.log(`[connections] disconnected host=${options.host} at=${new Date().toISOString()}`); - } + if (event.type === "connected") { + logConnectionEvent({ type: "connected", host: options.host, server: event.serverName }); + } else if (event.type === "disconnected") { + logConnectionEvent({ type: "disconnected", host: options.host }); } socket.send(JSON.stringify(event)); });