mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 01:42:50 +08:00
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
1 parent
d54c4d0dc2
commit
da4f416e32
2 files changed
+76
-44
No files matched your search
@@ -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<void> {
|
||||||
|
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<void> {
|
||||||
|
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()}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
-44
@@ -1,13 +1,14 @@
|
|||||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||||
import { createServer as createSecureServer } from "node:https";
|
import { createServer as createSecureServer } from "node:https";
|
||||||
import { readFileSync } from "node:fs";
|
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 { timingSafeEqual } from "node:crypto";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { WebSocketServer, type WebSocket } from "ws";
|
import { WebSocketServer, type WebSocket } from "ws";
|
||||||
import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js";
|
import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js";
|
||||||
import { handleStore } from "./store.js";
|
import { handleStore } from "./store.js";
|
||||||
|
import { logFeedback, logConnectionEvent } from "./activity-log.js";
|
||||||
|
|
||||||
const SERVER_TYPES = new Set<ServerType>(["teamspeak", "teaspeak", "auto"]);
|
const SERVER_TYPES = new Set<ServerType>(["teamspeak", "teaspeak", "auto"]);
|
||||||
|
|
||||||
@@ -26,12 +27,6 @@ function parsePrivilegeKey(msg: { privilegeKey?: unknown; token?: unknown }): st
|
|||||||
|
|
||||||
const PORT = Number(process.env.PORT ?? 8080);
|
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
|
// 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
|
// 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.
|
// 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.
|
// feedback is still accepted and logged, just never turned into an issue.
|
||||||
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
|
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
|
||||||
const GITHUB_REPO = process.env.GITHUB_REPO ?? "Moepchi/webspeak3";
|
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_CATEGORIES = new Set(["bug", "idea", "report", "other"]);
|
||||||
const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
|
const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
|
||||||
|
|
||||||
@@ -164,19 +150,6 @@ async function handleBroadcast(req: IncomingMessage, res: ServerResponse) {
|
|||||||
res.end(JSON.stringify({ ok: true, sent }));
|
res.end(JSON.stringify({ ok: true, sent }));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function rotateFeedbackLogIfNeeded(): Promise<void> {
|
|
||||||
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
|
// 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
|
// 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
|
// 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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
await logFeedback({ at: new Date().toISOString(), category, message, email });
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
let githubIssueUrl: string | undefined;
|
let githubIssueUrl: string | undefined;
|
||||||
if (publishAsIssue) {
|
if (publishAsIssue) {
|
||||||
@@ -574,14 +541,10 @@ wss.on("connection", (socket: WebSocket) => {
|
|||||||
liveConnections.add(connection);
|
liveConnections.add(connection);
|
||||||
connection.onEvent((event) => {
|
connection.onEvent((event) => {
|
||||||
if (shuttingDown) return;
|
if (shuttingDown) return;
|
||||||
if (LOG_CONNECTIONS) {
|
if (event.type === "connected") {
|
||||||
if (event.type === "connected") {
|
logConnectionEvent({ type: "connected", host: options.host, server: event.serverName });
|
||||||
console.log(
|
} else if (event.type === "disconnected") {
|
||||||
`[connections] connected host=${options.host} server=${event.serverName} at=${new Date().toISOString()}`
|
logConnectionEvent({ type: "disconnected", host: options.host });
|
||||||
);
|
|
||||||
} else if (event.type === "disconnected") {
|
|
||||||
console.log(`[connections] disconnected host=${options.host} at=${new Date().toISOString()}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
socket.send(JSON.stringify(event));
|
socket.send(JSON.stringify(event));
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in new issue
Block a user