mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
M001: add secure admin foundation
This commit is contained in:
1 parent
960be106bb
commit
31f320d4c1
32 files changed
+2518
-679
No files matched your search
@@ -0,0 +1,250 @@
|
||||
import { Router, type NextFunction, type Request, type Response } from "express";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { AdminInputError, AdminService, type AdminSettingsInput } from "./admin-service.js";
|
||||
import { AdminSessionStore, isSecureRequest } from "./admin-session.js";
|
||||
import { AdminLoginRateLimiter, waitFor } from "./login-rate-limit.js";
|
||||
import { TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
|
||||
export interface AdminRouterOptions {
|
||||
service: AdminService;
|
||||
sessions: AdminSessionStore;
|
||||
logger: Logger;
|
||||
getActiveSessions(): number;
|
||||
getPeakSessions(): number;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
const router = Router();
|
||||
const limiter = new AdminLoginRateLimiter();
|
||||
const logger = options.logger.child({ component: "admin-api" });
|
||||
|
||||
router.use((_request, response, next) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
next();
|
||||
});
|
||||
|
||||
router.get("/status", (_request, response) => {
|
||||
response.json({ initialized: options.service.isInitialized() });
|
||||
});
|
||||
|
||||
router.get("/session", (request, response) => {
|
||||
const session = options.sessions.get(request);
|
||||
response.json({
|
||||
initialized: options.service.isInitialized(),
|
||||
authenticated: Boolean(session),
|
||||
...(session ? { csrfToken: session.csrfToken, expiresAt: session.expiresAt } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
router.post("/setup/test", requireSameOrigin, async (request, response) => {
|
||||
const body = asRecord(request.body);
|
||||
if (!options.service.verifyBootstrap(readString(body, "bootstrapCode", 128))) {
|
||||
response.status(403).json({ ok: false, code: "INVALID_BOOTSTRAP" });
|
||||
return;
|
||||
}
|
||||
const action = readPasswordAction(body.passwordAction);
|
||||
const password = action === "remove"
|
||||
? ""
|
||||
: action === "replace"
|
||||
? readOptionalString(body, "serverPassword", 512)
|
||||
: options.service.getConnectionPolicy().serverPassword;
|
||||
await runProbe(options.service, response, readString(body, "target", 300), password, false);
|
||||
});
|
||||
|
||||
router.post("/setup/defaults", requireSameOrigin, (request, response) => {
|
||||
const body = asRecord(request.body);
|
||||
if (!options.service.verifyBootstrap(readString(body, "bootstrapCode", 128))) {
|
||||
response.status(403).json({ ok: false, code: "INVALID_BOOTSTRAP" });
|
||||
return;
|
||||
}
|
||||
response.json(options.service.getSetupDefaults());
|
||||
});
|
||||
|
||||
router.post("/setup", requireSameOrigin, async (request, response) => {
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
await options.service.setup({
|
||||
bootstrapCode: readString(body, "bootstrapCode", 128),
|
||||
adminPassword: readString(body, "adminPassword", 1024),
|
||||
...readSettingsInput(body),
|
||||
});
|
||||
const session = options.sessions.create(response, isSecureRequest(request));
|
||||
response.status(201).json({ ok: true, csrfToken: session.csrfToken });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/login", requireSameOrigin, async (request, response) => {
|
||||
if (!options.service.isInitialized()) {
|
||||
response.status(409).json({ ok: false, code: "NOT_INITIALIZED" });
|
||||
return;
|
||||
}
|
||||
const peer = request.socket.remoteAddress ?? "unknown";
|
||||
const retryAfterMs = limiter.retryAfterMs(peer);
|
||||
if (retryAfterMs > 0) {
|
||||
response.setHeader("Retry-After", String(Math.ceil(retryAfterMs / 1000)));
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED", retryAfterMs });
|
||||
return;
|
||||
}
|
||||
const body = asRecord(request.body);
|
||||
const password = readOptionalString(body, "password", 1024);
|
||||
if (!await options.service.verifyPassword(password)) {
|
||||
const delayMs = limiter.recordFailure(peer);
|
||||
await waitFor(delayMs);
|
||||
options.service.database.addAudit("ADMIN_LOGIN_FAILED");
|
||||
logger.warn("Administrator login failed");
|
||||
response.status(401).json({ ok: false, code: "INVALID_PASSWORD" });
|
||||
return;
|
||||
}
|
||||
limiter.recordSuccess(peer);
|
||||
options.service.database.addAudit("ADMIN_LOGIN_SUCCEEDED");
|
||||
const session = options.sessions.create(response, isSecureRequest(request));
|
||||
response.json({ ok: true, csrfToken: session.csrfToken, expiresAt: session.expiresAt });
|
||||
});
|
||||
|
||||
router.use(requireAdmin(options.sessions));
|
||||
|
||||
router.get("/overview", (_request, response) => {
|
||||
response.json(options.service.getOverview(
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
));
|
||||
});
|
||||
|
||||
router.get("/server", (_request, response) => {
|
||||
response.json(options.service.getAdminSettings());
|
||||
});
|
||||
|
||||
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
try {
|
||||
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
|
||||
response.json({ ok: true, settings: options.service.getAdminSettings() });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/server/test", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
const body = asRecord(request.body);
|
||||
const action = readPasswordAction(body.passwordAction);
|
||||
const password = action === "remove"
|
||||
? ""
|
||||
: typeof body.serverPassword === "string"
|
||||
? body.serverPassword.slice(0, 512)
|
||||
: options.service.getConnectionPolicy().serverPassword;
|
||||
await runProbe(options.service, response, readString(body, "target", 300), password, true);
|
||||
});
|
||||
|
||||
router.post("/legacy-import/dismiss", requireSameOrigin, requireCsrf(options.sessions), (_request, response) => {
|
||||
options.service.dismissLegacyImportNotice();
|
||||
response.json({ ok: true });
|
||||
});
|
||||
|
||||
router.post("/logout", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
|
||||
options.sessions.destroy(request, response, isSecureRequest(request));
|
||||
options.service.database.addAudit("ADMIN_LOGOUT");
|
||||
response.json({ ok: true });
|
||||
});
|
||||
|
||||
router.use((error: unknown, _request: Request, response: Response, _next: NextFunction) => {
|
||||
sendAdminError(response, error);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
function requireAdmin(sessions: AdminSessionStore) {
|
||||
return (request: Request, response: Response, next: NextFunction): void => {
|
||||
if (!sessions.get(request)) {
|
||||
response.status(401).json({ ok: false, code: "AUTH_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
function requireCsrf(sessions: AdminSessionStore) {
|
||||
return (request: Request, response: Response, next: NextFunction): void => {
|
||||
const session = sessions.get(request);
|
||||
const csrf = request.header("x-csrf-token");
|
||||
if (!session || !csrf || csrf !== session.csrfToken) {
|
||||
response.status(403).json({ ok: false, code: "CSRF_REJECTED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
function requireSameOrigin(request: Request, response: Response, next: NextFunction): void {
|
||||
if (!request.is("application/json")) {
|
||||
response.status(415).json({ ok: false, code: "JSON_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
const origin = request.header("origin");
|
||||
const host = request.header("host");
|
||||
try {
|
||||
if (!origin || !host || new URL(origin).host !== host) throw new Error("origin mismatch");
|
||||
} catch {
|
||||
response.status(403).json({ ok: false, code: "ORIGIN_REJECTED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
async function runProbe(
|
||||
service: AdminService,
|
||||
response: Response,
|
||||
target: string,
|
||||
password: string,
|
||||
persistResult: boolean,
|
||||
): Promise<void> {
|
||||
try {
|
||||
response.json(await service.testConnection(target, password, persistResult));
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof TeamSpeakProbeError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
return;
|
||||
}
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
}
|
||||
|
||||
function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
return {
|
||||
target: readString(body, "target", 300),
|
||||
serverPassword: typeof body.serverPassword === "string" ? body.serverPassword.slice(0, 512) : undefined,
|
||||
passwordAction: readPasswordAction(body.passwordAction),
|
||||
accessMode: body.accessMode === "open" ? "open" : body.accessMode === "fixed" ? "fixed" : body.accessMode as never,
|
||||
siteName: readString(body, "siteName", 80),
|
||||
welcomeText: readOptionalString(body, "welcomeText", 500),
|
||||
};
|
||||
}
|
||||
|
||||
function readPasswordAction(value: unknown): "keep" | "replace" | "remove" {
|
||||
return value === "replace" || value === "remove" ? value : "keep";
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new AdminInputError("INVALID_REQUEST", "Request body is invalid");
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function readString(body: Record<string, unknown>, key: string, max: number): string {
|
||||
if (typeof body[key] !== "string" || body[key].length > max) throw new AdminInputError("INVALID_REQUEST", `${key} is invalid`);
|
||||
return body[key];
|
||||
}
|
||||
|
||||
function readOptionalString(body: Record<string, unknown>, key: string, max: number): string {
|
||||
return typeof body[key] === "string" ? body[key].slice(0, max) : "";
|
||||
}
|
||||
|
||||
function sendAdminError(response: Response, error: unknown): void {
|
||||
if (error instanceof AdminInputError) {
|
||||
response.status(400).json({ ok: false, code: error.code });
|
||||
return;
|
||||
}
|
||||
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { loadConfig } from "../config.js";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { type AccessMode, type SettingsUpdate, WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from "../security/admin-password.js";
|
||||
import { BootstrapManager } from "../security/bootstrap.js";
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError, type TeamSpeakProbeResult } from "../server/teamspeak-probe.js";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
serverPassword?: string;
|
||||
passwordAction?: "keep" | "replace" | "remove";
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
}
|
||||
|
||||
export interface SetupInput extends AdminSettingsInput {
|
||||
bootstrapCode: string;
|
||||
adminPassword: string;
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
defaultTarget: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
accessMode: AccessMode;
|
||||
}
|
||||
|
||||
type ProbeFunction = typeof probeTeamSpeak;
|
||||
|
||||
export class AdminService {
|
||||
constructor(
|
||||
readonly database: WebSpeakDatabase,
|
||||
private readonly masterSecret: Buffer,
|
||||
private readonly bootstrap: BootstrapManager,
|
||||
private readonly logger: Logger,
|
||||
private readonly legacyConfigPath: string,
|
||||
private readonly probe: ProbeFunction = probeTeamSpeak,
|
||||
) {}
|
||||
|
||||
initialize(): void {
|
||||
this.importLegacyConfigOnce();
|
||||
if (!this.database.hasAdmin()) {
|
||||
const code = this.bootstrap.ensure();
|
||||
this.logger.warn(`WebSpeak is not initialized. Open /admin/setup and enter bootstrap code: ${code}`);
|
||||
}
|
||||
}
|
||||
|
||||
isInitialized(): boolean {
|
||||
return this.database.hasAdmin();
|
||||
}
|
||||
|
||||
verifyBootstrap(code: string): boolean {
|
||||
return !this.isInitialized() && this.bootstrap.verify(code);
|
||||
}
|
||||
|
||||
async setup(input: SetupInput): Promise<void> {
|
||||
if (this.isInitialized()) throw new AdminInputError("ALREADY_INITIALIZED", "WebSpeak is already initialized");
|
||||
if (!this.bootstrap.verify(input.bootstrapCode)) {
|
||||
throw new AdminInputError("INVALID_BOOTSTRAP", "Bootstrap code is invalid");
|
||||
}
|
||||
const passwordError = validateAdminPassword(input.adminPassword);
|
||||
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
|
||||
const credential = await hashAdminPassword(input.adminPassword);
|
||||
const settings = this.normalizeSettings(input, this.database.getSettings());
|
||||
this.database.initializeAdmin(credential, settings);
|
||||
this.bootstrap.consume();
|
||||
this.logger.info("WebSpeak administrator initialized");
|
||||
}
|
||||
|
||||
async verifyPassword(password: string): Promise<boolean> {
|
||||
const credential = this.database.getAdminCredential();
|
||||
return credential ? verifyAdminPassword(password, credential) : false;
|
||||
}
|
||||
|
||||
getPublicConfig(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
initialized: this.isInitialized(),
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
accessMode: settings.accessMode,
|
||||
...(settings.accessMode === "open" ? {
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
getSetupDefaults(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
hasPassword: Boolean(settings.tsPasswordEncrypted),
|
||||
accessMode: settings.accessMode,
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
legacyConfigImported: this.database.getMeta("legacy_config_imported") === "1",
|
||||
};
|
||||
}
|
||||
|
||||
getAdminSettings(): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
hasPassword: Boolean(settings.tsPasswordEncrypted),
|
||||
accessMode: settings.accessMode,
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
detectedProtocol: settings.detectedProtocol,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
internalPort: 3040,
|
||||
updatedAt: settings.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
updateSettings(input: AdminSettingsInput): void {
|
||||
const current = this.database.getSettings();
|
||||
const settings = this.normalizeSettings(input, current);
|
||||
const targetChanged = current.tsHost !== settings.tsHost || current.tsPort !== settings.tsPort;
|
||||
this.database.updateSettings(settings);
|
||||
if (targetChanged) this.database.clearConnectionTest();
|
||||
}
|
||||
|
||||
getConnectionPolicy(): ConnectionPolicy {
|
||||
const settings = this.database.getSettings();
|
||||
let serverPassword = "";
|
||||
try {
|
||||
serverPassword = decryptSecret(settings.tsPasswordEncrypted, this.masterSecret);
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Stored TeamSpeak password could not be decrypted");
|
||||
}
|
||||
return {
|
||||
defaultTarget: { host: settings.tsHost, port: settings.tsPort },
|
||||
serverPassword,
|
||||
accessMode: settings.accessMode,
|
||||
};
|
||||
}
|
||||
|
||||
async testConnection(targetText: string, password: string, persistResult: boolean): Promise<TeamSpeakProbeResult> {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(targetText);
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
try {
|
||||
const result = await this.probe(target, password, this.logger);
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: result.protocol, latencyMs: result.latencyMs, error: null });
|
||||
this.database.addAudit("CONNECTION_TEST_SUCCEEDED", { protocol: result.protocol, latencyMs: result.latencyMs });
|
||||
}
|
||||
return result;
|
||||
} catch (error: unknown) {
|
||||
const probeError = error instanceof TeamSpeakProbeError
|
||||
? error
|
||||
: new TeamSpeakProbeError("INTERNAL_ERROR", "Connection test failed", error);
|
||||
if (persistResult) {
|
||||
this.database.recordConnectionTest({ protocol: null, latencyMs: null, error: probeError.code });
|
||||
this.database.addAudit("CONNECTION_TEST_FAILED", { code: probeError.code });
|
||||
}
|
||||
throw probeError;
|
||||
}
|
||||
}
|
||||
|
||||
getOverview(activeSessions: number, peakSessions: number, startedAt: number): Record<string, unknown> {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
gateway: {
|
||||
status: "running",
|
||||
version: "0.1.0",
|
||||
uptimeSeconds: Math.max(0, Math.floor((Date.now() - startedAt) / 1000)),
|
||||
},
|
||||
teamSpeak: {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
status: settings.lastTestError ? "unreachable" : settings.lastTestAt ? "reachable" : "unknown",
|
||||
protocol: settings.detectedProtocol,
|
||||
lastTestAt: settings.lastTestAt,
|
||||
latencyMs: settings.lastTestLatencyMs,
|
||||
lastError: settings.lastTestError,
|
||||
},
|
||||
sessions: { active: activeSessions, peak: peakSessions, limit: 100 },
|
||||
recentEvents: this.database.recentAudit(),
|
||||
legacyConfigImported: this.database.getMeta("legacy_import_notice_pending") === "1",
|
||||
};
|
||||
}
|
||||
|
||||
dismissLegacyImportNotice(): void {
|
||||
this.database.setMeta("legacy_import_notice_pending", "0");
|
||||
}
|
||||
|
||||
private normalizeSettings(input: AdminSettingsInput, current: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
|
||||
let target: TeamSpeakTarget;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(input.target);
|
||||
} catch {
|
||||
throw new AdminInputError("INVALID_TARGET", "TeamSpeak target is invalid");
|
||||
}
|
||||
const siteName = input.siteName.trim();
|
||||
const welcomeText = input.welcomeText.trim();
|
||||
if (!siteName || siteName.length > 80) throw new AdminInputError("INVALID_SITE_NAME", "Site name must contain 1 to 80 characters");
|
||||
if (welcomeText.length > 500) throw new AdminInputError("INVALID_WELCOME_TEXT", "Welcome text cannot exceed 500 characters");
|
||||
if (input.accessMode !== "fixed" && input.accessMode !== "open") {
|
||||
throw new AdminInputError("INVALID_ACCESS_MODE", "Access mode is invalid");
|
||||
}
|
||||
|
||||
let encryptedPassword = current.tsPasswordEncrypted;
|
||||
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
|
||||
if (action === "remove") encryptedPassword = null;
|
||||
if (action === "replace") encryptedPassword = input.serverPassword ? encryptSecret(input.serverPassword, this.masterSecret) : null;
|
||||
return {
|
||||
siteName,
|
||||
welcomeText,
|
||||
accessMode: input.accessMode,
|
||||
tsHost: target.host,
|
||||
tsPort: target.port,
|
||||
tsPasswordEncrypted: encryptedPassword,
|
||||
};
|
||||
}
|
||||
|
||||
private importLegacyConfigOnce(): void {
|
||||
if (this.database.getMeta("legacy_config_checked") === "1") return;
|
||||
if (existsSync(this.legacyConfigPath)) {
|
||||
const legacy = loadConfig(this.legacyConfigPath);
|
||||
const current = this.database.getSettings();
|
||||
this.database.updateSettings({
|
||||
siteName: current.siteName,
|
||||
welcomeText: current.welcomeText,
|
||||
accessMode: current.accessMode,
|
||||
tsHost: legacy.tsHost,
|
||||
tsPort: legacy.tsPort,
|
||||
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
|
||||
}, "LEGACY_CONFIG_IMPORTED");
|
||||
this.database.setMeta("legacy_config_imported", "1");
|
||||
this.database.setMeta("legacy_import_notice_pending", "1");
|
||||
this.logger.info("Legacy config imported; WebSpeak settings are now managed from /admin");
|
||||
}
|
||||
this.database.setMeta("legacy_config_checked", "1");
|
||||
}
|
||||
}
|
||||
|
||||
export class AdminInputError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "AdminInputError";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import type { Request, Response } from "express";
|
||||
import type { TLSSocket } from "node:tls";
|
||||
|
||||
const COOKIE_NAME = "webspeak_admin";
|
||||
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
|
||||
|
||||
interface AdminSession {
|
||||
csrfToken: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export class AdminSessionStore {
|
||||
private readonly sessions = new Map<string, AdminSession>();
|
||||
|
||||
create(response: Response, secure: boolean, now = Date.now()): { csrfToken: string; expiresAt: number } {
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const csrfToken = randomBytes(24).toString("base64url");
|
||||
const expiresAt = now + SESSION_TTL_MS;
|
||||
this.sessions.set(hashToken(token), { csrfToken, expiresAt });
|
||||
response.cookie(COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure,
|
||||
path: "/",
|
||||
maxAge: SESSION_TTL_MS,
|
||||
});
|
||||
return { csrfToken, expiresAt };
|
||||
}
|
||||
|
||||
get(request: Request, now = Date.now()): AdminSession | null {
|
||||
const token = readCookie(request.headers.cookie, COOKIE_NAME);
|
||||
if (!token) return null;
|
||||
const key = hashToken(token);
|
||||
const session = this.sessions.get(key);
|
||||
if (!session) return null;
|
||||
if (session.expiresAt <= now) {
|
||||
this.sessions.delete(key);
|
||||
return null;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
destroy(request: Request, response: Response, secure: boolean): void {
|
||||
const token = readCookie(request.headers.cookie, COOKIE_NAME);
|
||||
if (token) this.sessions.delete(hashToken(token));
|
||||
response.clearCookie(COOKIE_NAME, { httpOnly: true, sameSite: "strict", secure, path: "/" });
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.sessions.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export function isSecureRequest(request: Request): boolean {
|
||||
return (request.socket as TLSSocket).encrypted === true;
|
||||
}
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("base64url");
|
||||
}
|
||||
|
||||
function readCookie(header: string | undefined, name: string): string | null {
|
||||
if (!header) return null;
|
||||
for (const part of header.split(";")) {
|
||||
const separator = part.indexOf("=");
|
||||
if (separator < 0) continue;
|
||||
if (part.slice(0, separator).trim() === name) {
|
||||
try {
|
||||
return decodeURIComponent(part.slice(separator + 1).trim());
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
const WINDOW_MS = 5 * 60 * 1000;
|
||||
const MAX_FAILURES = 5;
|
||||
|
||||
interface LoginAttempt {
|
||||
failures: number;
|
||||
firstFailureAt: number;
|
||||
}
|
||||
|
||||
export class AdminLoginRateLimiter {
|
||||
private readonly attempts = new Map<string, LoginAttempt>();
|
||||
|
||||
constructor(private readonly maxTrackedPeers = 1024) {}
|
||||
|
||||
retryAfterMs(peer: string, now = Date.now()): number {
|
||||
const attempt = this.attempts.get(peer);
|
||||
if (!attempt) return 0;
|
||||
if (now - attempt.firstFailureAt >= WINDOW_MS) {
|
||||
this.attempts.delete(peer);
|
||||
return 0;
|
||||
}
|
||||
if (attempt.failures < MAX_FAILURES) return 0;
|
||||
return WINDOW_MS - (now - attempt.firstFailureAt);
|
||||
}
|
||||
|
||||
recordFailure(peer: string, now = Date.now()): number {
|
||||
const current = this.attempts.get(peer);
|
||||
if (!current) {
|
||||
this.pruneExpired(now);
|
||||
while (this.attempts.size >= this.maxTrackedPeers) {
|
||||
const oldestPeer = this.attempts.keys().next().value;
|
||||
if (!oldestPeer) break;
|
||||
this.attempts.delete(oldestPeer);
|
||||
}
|
||||
}
|
||||
const attempt = !current || now - current.firstFailureAt >= WINDOW_MS
|
||||
? { failures: 1, firstFailureAt: now }
|
||||
: { ...current, failures: current.failures + 1 };
|
||||
this.attempts.set(peer, attempt);
|
||||
return Math.min(2000, 250 * (2 ** Math.min(3, attempt.failures - 1)));
|
||||
}
|
||||
|
||||
recordSuccess(peer: string): void {
|
||||
this.attempts.delete(peer);
|
||||
}
|
||||
|
||||
private pruneExpired(now: number): void {
|
||||
for (const [peer, attempt] of this.attempts) {
|
||||
if (now - attempt.firstFailureAt >= WINDOW_MS) this.attempts.delete(peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function waitFor(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
Reference in new issue
Block a user