mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 20:12:52 +08:00
M001: replace bootstrap setup with forced password rotation
This commit is contained in:
1 parent
34ef16b737
commit
7dcbcaae78
14 files changed
+369
-329
No files matched your search
+26
-49
@@ -33,49 +33,11 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
response.json({
|
||||
initialized: options.service.isInitialized(),
|
||||
authenticated: Boolean(session),
|
||||
mustChangePassword: Boolean(session) && options.service.isPasswordChangeRequired(),
|
||||
...(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" });
|
||||
@@ -89,8 +51,9 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
return;
|
||||
}
|
||||
const body = asRecord(request.body);
|
||||
const username = readString(body, "username", 64).trim();
|
||||
const password = readOptionalString(body, "password", 1024);
|
||||
if (!await options.service.verifyPassword(password)) {
|
||||
if (!await options.service.verifyPassword(username, password)) {
|
||||
const delayMs = limiter.recordFailure(peer);
|
||||
await waitFor(delayMs);
|
||||
options.service.database.addAudit("ADMIN_LOGIN_FAILED");
|
||||
@@ -101,10 +64,26 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
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 });
|
||||
response.json({ ok: true, csrfToken: session.csrfToken, expiresAt: session.expiresAt, mustChangePassword: options.service.isPasswordChangeRequired() });
|
||||
});
|
||||
|
||||
router.use(requireAdmin(options.sessions));
|
||||
router.post("/change-password", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
|
||||
try {
|
||||
const body = asRecord(request.body);
|
||||
await options.service.changePassword(readString(body, "newPassword", 1024));
|
||||
response.json({ ok: true, mustChangePassword: false });
|
||||
} catch (error: unknown) {
|
||||
sendAdminError(response, error);
|
||||
}
|
||||
});
|
||||
|
||||
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(requireAdmin(options.sessions, options.service));
|
||||
|
||||
router.get("/overview", (_request, response) => {
|
||||
response.json(options.service.getOverview(
|
||||
@@ -143,12 +122,6 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
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);
|
||||
});
|
||||
@@ -156,12 +129,16 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
return router;
|
||||
}
|
||||
|
||||
function requireAdmin(sessions: AdminSessionStore) {
|
||||
function requireAdmin(sessions: AdminSessionStore, service: AdminService) {
|
||||
return (request: Request, response: Response, next: NextFunction): void => {
|
||||
if (!sessions.get(request)) {
|
||||
response.status(401).json({ ok: false, code: "AUTH_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
if (service.isPasswordChangeRequired()) {
|
||||
response.status(403).json({ ok: false, code: "PASSWORD_CHANGE_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
+31
-42
@@ -4,7 +4,6 @@ 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";
|
||||
|
||||
@@ -17,11 +16,6 @@ export interface AdminSettingsInput {
|
||||
welcomeText: string;
|
||||
}
|
||||
|
||||
export interface SetupInput extends AdminSettingsInput {
|
||||
bootstrapCode: string;
|
||||
adminPassword: string;
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
defaultTarget: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
@@ -34,17 +28,17 @@ 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 {
|
||||
async initialize(): Promise<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}`);
|
||||
const credential = await hashAdminPassword("admin", { username: "admin", mustChangePassword: true, allowWeakPassword: true });
|
||||
this.database.initializeAdmin(credential, this.toSettingsUpdate(this.database.getSettings()));
|
||||
this.logger.warn("Default admin account created. Change the password on first login.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,27 +46,23 @@ export class AdminService {
|
||||
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> {
|
||||
async verifyPassword(username: string, password: string): Promise<boolean> {
|
||||
const credential = this.database.getAdminCredential();
|
||||
return credential ? verifyAdminPassword(password, credential) : false;
|
||||
return credential?.username === username && await verifyAdminPassword(password, credential);
|
||||
}
|
||||
|
||||
isPasswordChangeRequired(): boolean {
|
||||
return this.database.getAdminCredential()?.mustChangePassword === true;
|
||||
}
|
||||
|
||||
async changePassword(password: string): Promise<void> {
|
||||
const credential = this.database.getAdminCredential();
|
||||
if (!credential) throw new AdminInputError("NOT_INITIALIZED", "The administrator account is not initialized");
|
||||
const passwordError = validateAdminPassword(password);
|
||||
if (passwordError) throw new AdminInputError("INVALID_ADMIN_PASSWORD", passwordError);
|
||||
const replacement = await hashAdminPassword(password, { username: credential.username, mustChangePassword: false });
|
||||
this.database.updateAdminCredential(replacement);
|
||||
this.database.addAudit("ADMIN_PASSWORD_CHANGED");
|
||||
}
|
||||
|
||||
getPublicConfig(): Record<string, unknown> {
|
||||
@@ -90,18 +80,6 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -223,6 +201,17 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
private toSettingsUpdate(settings: ReturnType<WebSpeakDatabase["getSettings"]>): SettingsUpdate {
|
||||
return {
|
||||
siteName: settings.siteName,
|
||||
welcomeText: settings.welcomeText,
|
||||
accessMode: settings.accessMode,
|
||||
tsHost: settings.tsHost,
|
||||
tsPort: settings.tsPort,
|
||||
tsPasswordEncrypted: settings.tsPasswordEncrypted,
|
||||
};
|
||||
}
|
||||
|
||||
private importLegacyConfigOnce(): void {
|
||||
if (this.database.getMeta("legacy_config_checked") === "1") return;
|
||||
if (existsSync(this.legacyConfigPath)) {
|
||||
|
||||
+3
-3
@@ -5,7 +5,7 @@ import {
|
||||
parseTeamSpeakTargetParts,
|
||||
} from "./domain/teamspeak-target.js";
|
||||
|
||||
/** The only TeamSpeak state still read from the legacy bootstrap file. */
|
||||
/** The only TeamSpeak state still read from the legacy JSON config. */
|
||||
export interface AppConfig {
|
||||
tsHost: string;
|
||||
tsPort: number;
|
||||
@@ -22,7 +22,7 @@ export function getDefaultConfig(): AppConfig {
|
||||
|
||||
/**
|
||||
* Convert both the old JSON shape and the M000 shape into the normalized
|
||||
* bootstrap model. Deprecated fields are intentionally ignored and disappear
|
||||
* normalized legacy model. Deprecated fields are intentionally ignored and disappear
|
||||
* when the migrated model is written back.
|
||||
*/
|
||||
export function migrateConfig(input: unknown): AppConfig {
|
||||
@@ -55,7 +55,7 @@ export function loadConfig(path: string): AppConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/** Write only the normalized M000 shape; this is the one-time legacy cleanup. */
|
||||
/** Write only the normalized legacy shape; this is the one-time legacy cleanup. */
|
||||
export function saveConfig(path: string, config: AppConfig): void {
|
||||
try {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
|
||||
+11
-4
@@ -1,12 +1,11 @@
|
||||
import path from "node:path";
|
||||
import { existsSync } from "node:fs";
|
||||
import { existsSync, unlinkSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { createWebServer } from "./server/server.js";
|
||||
import { APP_PORT } from "./constants.js";
|
||||
import { WebSpeakDatabase } from "./persistence/database.js";
|
||||
import { loadOrCreateMasterSecret } from "./security/master-secret.js";
|
||||
import { BootstrapManager } from "./security/bootstrap.js";
|
||||
import { AdminService } from "./admin/admin-service.js";
|
||||
import { JoinTicketStore } from "./server/join-ticket.js";
|
||||
|
||||
@@ -25,11 +24,11 @@ async function main() {
|
||||
const adminService = new AdminService(
|
||||
database,
|
||||
masterSecret,
|
||||
new BootstrapManager(path.join(DATA_DIR, "bootstrap")),
|
||||
logger,
|
||||
CONFIG_PATH,
|
||||
);
|
||||
adminService.initialize();
|
||||
await adminService.initialize();
|
||||
removeObsoleteBootstrapFile();
|
||||
const joinTickets = new JoinTicketStore();
|
||||
|
||||
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
|
||||
@@ -60,6 +59,14 @@ async function main() {
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
}
|
||||
|
||||
function removeObsoleteBootstrapFile(): void {
|
||||
try {
|
||||
unlinkSync(path.join(DATA_DIR, "bootstrap"));
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Fatal error:", err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -70,7 +70,13 @@ export class WebSpeakDatabase {
|
||||
getAdminCredential(): AdminCredential | null {
|
||||
const row = this.database.prepare("SELECT credential_json FROM admin_credentials WHERE id = 1").get() as { credential_json?: string } | undefined;
|
||||
if (!row?.credential_json) return null;
|
||||
return JSON.parse(row.credential_json) as AdminCredential;
|
||||
const credential = JSON.parse(row.credential_json) as Partial<AdminCredential>;
|
||||
return {
|
||||
...credential,
|
||||
version: 1,
|
||||
username: typeof credential.username === "string" && credential.username ? credential.username : "admin",
|
||||
mustChangePassword: credential.mustChangePassword === true,
|
||||
} as AdminCredential;
|
||||
}
|
||||
|
||||
initializeAdmin(credential: AdminCredential, settings: SettingsUpdate): void {
|
||||
@@ -85,6 +91,13 @@ export class WebSpeakDatabase {
|
||||
});
|
||||
}
|
||||
|
||||
updateAdminCredential(credential: AdminCredential): void {
|
||||
const now = new Date().toISOString();
|
||||
this.database.prepare(
|
||||
"UPDATE admin_credentials SET credential_json = ?, updated_at = ? WHERE id = 1",
|
||||
).run(JSON.stringify(credential), now);
|
||||
}
|
||||
|
||||
getSettings(): PersistedSettings {
|
||||
const row = this.database.prepare("SELECT * FROM settings WHERE id = 1").get() as SettingsRow;
|
||||
return {
|
||||
|
||||
@@ -5,6 +5,8 @@ const SCRYPT_PARAMETERS = Object.freeze({ N: 32768, r: 8, p: 1, maxmem: 64 * 102
|
||||
|
||||
export interface AdminCredential {
|
||||
version: 1;
|
||||
username: string;
|
||||
mustChangePassword: boolean;
|
||||
salt: string;
|
||||
hash: string;
|
||||
parameters: {
|
||||
@@ -14,19 +16,27 @@ export interface AdminCredential {
|
||||
};
|
||||
}
|
||||
|
||||
export interface AdminPasswordOptions {
|
||||
username?: string;
|
||||
mustChangePassword?: boolean;
|
||||
allowWeakPassword?: boolean;
|
||||
}
|
||||
|
||||
export function validateAdminPassword(password: string): string | null {
|
||||
if (password.length < 12) return "Admin password must contain at least 12 characters";
|
||||
if (password.length > 1024) return "Admin password is too long";
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function hashAdminPassword(password: string): Promise<AdminCredential> {
|
||||
const validationError = validateAdminPassword(password);
|
||||
export async function hashAdminPassword(password: string, options: AdminPasswordOptions = {}): Promise<AdminCredential> {
|
||||
const validationError = options.allowWeakPassword ? null : validateAdminPassword(password);
|
||||
if (validationError) throw new Error(validationError);
|
||||
const salt = randomBytes(16);
|
||||
const hash = await derive(password, salt, SCRYPT_PARAMETERS);
|
||||
return {
|
||||
version: 1,
|
||||
username: options.username ?? "admin",
|
||||
mustChangePassword: options.mustChangePassword ?? false,
|
||||
salt: salt.toString("base64url"),
|
||||
hash: hash.toString("base64url"),
|
||||
parameters: {
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { chmodSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export class BootstrapManager {
|
||||
private code: string | null = null;
|
||||
|
||||
constructor(private readonly path: string) {}
|
||||
|
||||
ensure(): string {
|
||||
if (this.code) return this.code;
|
||||
try {
|
||||
const stored = readFileSync(this.path, "utf8").trim();
|
||||
if (normalize(stored).length >= 20) {
|
||||
this.code = stored;
|
||||
return stored;
|
||||
}
|
||||
} catch {
|
||||
// A missing or invalid bootstrap file is replaced below.
|
||||
}
|
||||
|
||||
const raw = randomBytes(16).toString("hex").toUpperCase();
|
||||
this.code = raw.match(/.{1,4}/g)!.join("-");
|
||||
mkdirSync(dirname(this.path), { recursive: true });
|
||||
writeFileSync(this.path, `${this.code}\n`, { encoding: "utf8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(this.path, 0o600);
|
||||
} catch {
|
||||
// POSIX permissions are best-effort on non-POSIX filesystems.
|
||||
}
|
||||
return this.code;
|
||||
}
|
||||
|
||||
verify(candidate: string): boolean {
|
||||
const expected = normalize(this.ensure());
|
||||
const actual = normalize(candidate);
|
||||
const expectedBytes = Buffer.from(expected, "utf8");
|
||||
const actualBytes = Buffer.from(actual, "utf8");
|
||||
return expectedBytes.length === actualBytes.length && timingSafeEqual(expectedBytes, actualBytes);
|
||||
}
|
||||
|
||||
consume(): void {
|
||||
this.code = null;
|
||||
try {
|
||||
unlinkSync(this.path);
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalize(value: string): string {
|
||||
return value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
|
||||
}
|
||||
Reference in new issue
Block a user