From 7dcbcaae78b935ad9f9b34e990f4c6138d3187ba Mon Sep 17 00:00:00 2001 From: illusia <64828020+EchoSixHIYA@users.noreply.github.com> Date: Tue, 1 Sep 2026 13:09:51 +0800 Subject: [PATCH] M001: replace bootstrap setup with forced password rotation --- README.md | 42 +++--- src/admin/admin-router.ts | 75 ++++------ src/admin/admin-service.ts | 73 +++++----- src/config.ts | 6 +- src/index.ts | 15 +- src/persistence/database.ts | 15 +- src/security/admin-password.ts | 14 +- src/security/bootstrap.ts | 54 -------- test/admin-api.test.ts | 98 ++++++------- test/admin-service.test.ts | 28 ++-- test/config.test.ts | 2 +- test/security.test.ts | 18 +-- web/src/views/AdminView.vue | 246 +++++++++++++++++++++++++-------- web/src/views/WebClient.vue | 12 +- 14 files changed, 369 insertions(+), 329 deletions(-) delete mode 100644 src/security/bootstrap.ts diff --git a/README.md b/README.md index 0fa8ab2..7bda23e 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ WebSpeak 是一个自托管的 TeamSpeak 浏览器客户端与访客接入网关 - PCM/Opus 语音桥接、自由麦、按键说话、麦克风选择与音量控制。 - 发言成员头像显示绿色动态边框。 - 中英文访客页面和中英文管理控制台。 -- Web 管理闭环:首次配置、单管理员登录、概览、服务器设置和真实连接测试。 +- Web 管理闭环:默认账号首次登录强制改密、单管理员登录、概览、服务器设置和真实连接测试。 - `fixed` 与 `open` 两种访问模式。 - TeamSpeak 密码使用安装级主密钥加密保存,不向管理 API 返回明文。 - 旧 `config.json` 一次性导入,导入后不再作为实时配置源。 @@ -46,32 +46,22 @@ npm run build node dist/index.js ``` -WebSpeak 内部端口固定为 `3040`。首次启动会输出一次初始化提示: +WebSpeak 内部端口固定为 `3040`。首次启动会自动创建默认管理员账号: ```text -WebSpeak is not initialized. -Open /admin/setup and enter bootstrap code: XXXX-XXXX-... +账号:admin +密码:admin ``` -然后打开: - -```text -http://127.0.0.1:3040/admin/setup -``` - -三步完成配置: - -1. 输入启动日志中的一次性初始化代码,创建至少 12 字符的管理员密码。 -2. 输入 `host[:port]` 形式的 TeamSpeak 地址和可选密码,执行真实短连接测试。 -3. 选择访问模式,并设置站点名称和欢迎文本。 - -配置完成后初始化代码立即失效并从数据目录删除。后续管理入口为: +然后打开管理入口: ```text http://127.0.0.1:3040/admin ``` -管理员只有密码,没有用户名、用户列表或角色系统。 +首次登录后必须设置一个至少 12 个字符的新密码。改密完成后,在“服务器设置”中填写 TeamSpeak 目标并执行连接测试,再保存访问模式和站点信息。 + +后续管理入口仍为 `/admin`。管理员账号名固定为 `admin`,当前版本不提供用户列表或角色系统。 ### 访问模式 @@ -89,11 +79,11 @@ http://127.0.0.1:3040/admin data/ webspeak.db SQLite 配置、管理员凭据和有限审计事件 master.key 32 字节安装级主密钥 - bootstrap 仅在首次初始化完成前存在 logs/ 本地日志 ``` - 管理员密码使用 Node.js `crypto.scrypt`、随机 salt 和 constant-time compare。 +- 新部署首次使用 `admin/admin` 登录后必须立即修改密码;修改完成后默认密码失效。 - TeamSpeak 服务器密码使用 AES-256-GCM 加密。 - 管理 Session 是随机服务端 Session;Cookie 为 `HttpOnly`、`SameSite=Strict`,直接 HTTPS 下同时启用 `Secure`。 - 管理 mutation 检查同源请求、JSON Content-Type、服务端 Session 与 CSRF token。 @@ -182,14 +172,14 @@ npm audit src/ admin/ 管理服务、API、Session 与登录限速 persistence/database.ts SQLite schema、repository 和迁移边界 - security/ 主密钥、秘密加密、scrypt、Bootstrap 与网络策略 + security/ 主密钥、秘密加密、scrypt 与网络策略 domain/teamspeak-target.ts host[:port] 规范化解析 server/teamspeak-adapter.ts TeamSpeak 协议边界与 endpoint 协议缓存 server/teamspeak-probe.ts 可清理的短连接测试 server/join-ticket.ts 一次性访客连接票据 server/voice-bridge.ts 每用户语音 WebSocket 桥接 web/src/views/ - AdminView.vue 双语 Setup/Login/Overview/Server UI + AdminView.vue 双语 Login/Password change/Overview/Server UI WebClient.vue 双语访客与语音工作台 ``` @@ -204,7 +194,7 @@ WebSpeak is a self-hosted TeamSpeak web client and guest gateway. Every browser - Channel/member directory, channel switching, channel text chat, and live member movement. - PCM/Opus voice bridge, VOX, push-to-talk, microphone selection, and volume controls. - Bilingual guest UI and bilingual admin console. -- Browser-based first setup, single-admin login, Overview, server settings, and a real short-lived connection test. +- Browser-based admin login, mandatory first-login password change, Overview, server settings, and a real short-lived connection test. - Fixed and open guest access modes. - Encrypted TeamSpeak server password and one-time legacy config import. - No ServerQuery, WebQuery, admin token, or maintenance bot. @@ -224,17 +214,17 @@ npm run build node dist/index.js ``` -WebSpeak always listens on internal port `3040`. On first boot, read the one-time bootstrap code from startup output and open: +WebSpeak always listens on internal port `3040`. On first boot it creates the default administrator `admin` with password `admin`. Open the admin console: ```text -http://127.0.0.1:3040/admin/setup +http://127.0.0.1:3040/admin ``` -Create the admin password, test the TeamSpeak target, choose the access mode, and finish setup. Future administration is performed at `/admin`; no JSON editing or restart is needed for normal setting changes. +The first login is forced to a password-change screen. Set a password of at least 12 characters, then configure and test the TeamSpeak target from Server settings. Future administration is performed at `/admin`; no JSON editing or restart is needed for normal setting changes. ### Security and persistence -Local state is stored under `data/` in SQLite plus a 32-byte `master.key`. Admin passwords use `crypto.scrypt`. TeamSpeak secrets use AES-256-GCM. Admin sessions are server-side with HttpOnly/SameSite Strict cookies, same-origin and CSRF checks, and fixed login throttling. +Local state is stored under `data/` in SQLite plus a 32-byte `master.key`. Admin passwords use `crypto.scrypt`. A new instance starts with `admin/admin` and marks that credential for mandatory rotation on first login. TeamSpeak secrets use AES-256-GCM. Admin sessions are server-side with HttpOnly/SameSite Strict cookies, same-origin and CSRF checks, and fixed login throttling. In fixed mode, guests cannot override the configured target. In open mode, arbitrary public targets are validated after DNS resolution; private, loopback, link-local, multicast, broadcast, and reserved addresses are rejected. Session passwords travel through an opaque one-time Join Ticket and are never placed in share or WebSocket URLs. diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts index 1b77078..ebe0406 100644 --- a/src/admin/admin-router.ts +++ b/src/admin/admin-router.ts @@ -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(); }; } diff --git a/src/admin/admin-service.ts b/src/admin/admin-service.ts index 304f644..6071a8c 100644 --- a/src/admin/admin-service.ts +++ b/src/admin/admin-service.ts @@ -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 { 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 { - 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 { + async verifyPassword(username: string, password: string): Promise { 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 { + 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 { @@ -90,18 +80,6 @@ export class AdminService { }; } - getSetupDefaults(): Record { - 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 { const settings = this.database.getSettings(); return { @@ -223,6 +201,17 @@ export class AdminService { }; } + private toSettingsUpdate(settings: ReturnType): 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)) { diff --git a/src/config.ts b/src/config.ts index 08a34c8..6e64d93 100644 --- a/src/config.ts +++ b/src/config.ts @@ -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 }); diff --git a/src/index.ts b/src/index.ts index 01addd8..3b582f6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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); diff --git a/src/persistence/database.ts b/src/persistence/database.ts index 4df8860..88bb549 100644 --- a/src/persistence/database.ts +++ b/src/persistence/database.ts @@ -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; + 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 { diff --git a/src/security/admin-password.ts b/src/security/admin-password.ts index e4b053d..85f78c6 100644 --- a/src/security/admin-password.ts +++ b/src/security/admin-password.ts @@ -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 { - const validationError = validateAdminPassword(password); +export async function hashAdminPassword(password: string, options: AdminPasswordOptions = {}): Promise { + 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: { diff --git a/src/security/bootstrap.ts b/src/security/bootstrap.ts deleted file mode 100644 index 5649b3b..0000000 --- a/src/security/bootstrap.ts +++ /dev/null @@ -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(); -} diff --git a/test/admin-api.test.ts b/test/admin-api.test.ts index 2ff0861..f81257d 100644 --- a/test/admin-api.test.ts +++ b/test/admin-api.test.ts @@ -9,24 +9,20 @@ import { createAdminRouter } from "../src/admin/admin-router.js"; import { AdminService } from "../src/admin/admin-service.js"; import { AdminSessionStore } from "../src/admin/admin-session.js"; import { WebSpeakDatabase } from "../src/persistence/database.js"; -import { BootstrapManager } from "../src/security/bootstrap.js"; import { loadOrCreateMasterSecret } from "../src/security/master-secret.js"; import { silentLogger } from "./helpers/logger.js"; -test("admin API completes bootstrap, authentication, test, save, CSRF, and logout", async (context) => { +test("admin API requires the default password to be changed before administration", async (context) => { const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-api-")); const database = new WebSpeakDatabase(path.join(directory, "webspeak.db")); - const bootstrap = new BootstrapManager(path.join(directory, "bootstrap")); const service = new AdminService( database, loadOrCreateMasterSecret(path.join(directory, "master.key")), - bootstrap, silentLogger, path.join(directory, "missing-config.json"), async (_target, password) => ({ ok: true, protocol: "ts6", latencyMs: 7, serverName: "Mock Server", requiresPassword: Boolean(password) }), ); - service.initialize(); - const bootstrapCode = bootstrap.ensure(); + await service.initialize(); const app = express(); app.use(express.json()); @@ -51,53 +47,49 @@ test("admin API completes bootstrap, authentication, test, save, CSRF, and logou const status = await request(origin, "/api/admin/status"); assert.equal(status.response.status, 200); assert.equal(status.response.headers.get("cache-control"), "no-store"); - assert.equal(status.body.initialized, false); + assert.equal(status.body.initialized, true); assert.equal("setupDefaults" in status.body, false); - const rejectedDefaults = await request(origin, "/api/admin/setup/defaults", { + const login = await request(origin, "/api/admin/login", { method: "POST", - body: { bootstrapCode: "not-the-bootstrap-code" }, + body: { username: "admin", password: "admin" }, }); - assert.equal(rejectedDefaults.response.status, 403); - assert.equal(rejectedDefaults.body.code, "INVALID_BOOTSTRAP"); - - const defaults = await request(origin, "/api/admin/setup/defaults", { - method: "POST", - body: { bootstrapCode }, - }); - assert.equal(defaults.body.target, "127.0.0.1:9987"); - - const tested = await request(origin, "/api/admin/setup/test", { - method: "POST", - body: { bootstrapCode, target: "voice.example.com:9987", serverPassword: "server-secret", passwordAction: "replace" }, - }); - assert.equal(tested.body.ok, true); - assert.equal(tested.body.protocol, "ts6"); - - const setup = await request(origin, "/api/admin/setup", { - method: "POST", - body: { - bootstrapCode, - adminPassword: "integration-admin-password", - target: "voice.example.com:9987", - serverPassword: "server-secret", - passwordAction: "replace", - accessMode: "fixed", - siteName: "Integration WebSpeak", - welcomeText: "Welcome", - }, - }); - assert.equal(setup.response.status, 201); - assert.equal(setup.body.ok, true); - assert.equal(typeof setup.body.csrfToken, "string"); - const cookie = setup.response.headers.get("set-cookie")?.split(";", 1)[0]; + assert.equal(login.response.status, 200); + assert.equal(login.body.mustChangePassword, true); + assert.equal(typeof login.body.csrfToken, "string"); + const cookie = login.response.headers.get("set-cookie")?.split(";", 1)[0]; assert.ok(cookie?.startsWith("webspeak_admin=")); - assert.match(setup.response.headers.get("set-cookie") ?? "", /HttpOnly/i); - assert.match(setup.response.headers.get("set-cookie") ?? "", /SameSite=Strict/i); + assert.match(login.response.headers.get("set-cookie") ?? "", /HttpOnly/i); + assert.match(login.response.headers.get("set-cookie") ?? "", /SameSite=Strict/i); const session = await request(origin, "/api/admin/session", { cookie }); assert.equal(session.body.authenticated, true); + assert.equal(session.body.mustChangePassword, true); + const blockedOverview = await request(origin, "/api/admin/overview", { cookie }); + assert.equal(blockedOverview.response.status, 403); + assert.equal(blockedOverview.body.code, "PASSWORD_CHANGE_REQUIRED"); + + const shortPassword = await request(origin, "/api/admin/change-password", { + method: "POST", + cookie, + csrf: login.body.csrfToken, + body: { newPassword: "too-short" }, + }); + assert.equal(shortPassword.response.status, 400); + assert.equal(shortPassword.body.code, "INVALID_ADMIN_PASSWORD"); + + const changed = await request(origin, "/api/admin/change-password", { + method: "POST", + cookie, + csrf: login.body.csrfToken, + body: { newPassword: "integration-admin-password" }, + }); + assert.equal(changed.response.status, 200); + assert.equal(changed.body.mustChangePassword, false); + + const updatedSession = await request(origin, "/api/admin/session", { cookie }); + assert.equal(updatedSession.body.mustChangePassword, false); const overview = await request(origin, "/api/admin/overview", { cookie }); assert.deepEqual(overview.body.sessions, { active: 2, peak: 4, limit: 100 }); @@ -112,7 +104,7 @@ test("admin API completes bootstrap, authentication, test, save, CSRF, and logou const saved = await request(origin, "/api/admin/server", { method: "PUT", cookie, - csrf: setup.body.csrfToken, + csrf: login.body.csrfToken, body: { target: "voice.example.com:9988", passwordAction: "remove", @@ -129,7 +121,7 @@ test("admin API completes bootstrap, authentication, test, save, CSRF, and logou const probe = await request(origin, "/api/admin/server/test", { method: "POST", cookie, - csrf: setup.body.csrfToken, + csrf: login.body.csrfToken, body: { target: "voice.example.com:9988", passwordAction: "remove" }, }); assert.equal(probe.body.protocol, "ts6"); @@ -137,10 +129,22 @@ test("admin API completes bootstrap, authentication, test, save, CSRF, and logou assert.equal(settings.body.detectedProtocol, "ts6"); assert.equal(settings.body.lastTestLatencyMs, 7); - const logout = await request(origin, "/api/admin/logout", { method: "POST", cookie, csrf: setup.body.csrfToken, body: {} }); + const logout = await request(origin, "/api/admin/logout", { method: "POST", cookie, csrf: login.body.csrfToken, body: {} }); assert.equal(logout.body.ok, true); const denied = await request(origin, "/api/admin/overview", { cookie }); assert.equal(denied.response.status, 401); + + const oldPassword = await request(origin, "/api/admin/login", { + method: "POST", + body: { username: "admin", password: "admin" }, + }); + assert.equal(oldPassword.response.status, 401); + const newPassword = await request(origin, "/api/admin/login", { + method: "POST", + body: { username: "admin", password: "integration-admin-password" }, + }); + assert.equal(newPassword.response.status, 200); + assert.equal(newPassword.body.mustChangePassword, false); }); async function request( diff --git a/test/admin-service.test.ts b/test/admin-service.test.ts index e03e85b..e1f7fbc 100644 --- a/test/admin-service.test.ts +++ b/test/admin-service.test.ts @@ -5,11 +5,10 @@ import path from "node:path"; import test from "node:test"; import { AdminService } from "../src/admin/admin-service.js"; import { WebSpeakDatabase } from "../src/persistence/database.js"; -import { BootstrapManager } from "../src/security/bootstrap.js"; import { loadOrCreateMasterSecret } from "../src/security/master-secret.js"; import { silentLogger } from "./helpers/logger.js"; -test("legacy config imports once, remains untouched, and setup consumes bootstrap", async () => { +test("legacy config imports once, seeds the default admin, and allows password rotation", async () => { const directory = mkdtempSync(path.join(tmpdir(), "webspeak-admin-service-")); const legacyPath = path.join(directory, "config.json"); const legacyText = JSON.stringify({ @@ -23,37 +22,28 @@ test("legacy config imports once, remains untouched, and setup consumes bootstra }, null, 2); writeFileSync(legacyPath, legacyText); const database = new WebSpeakDatabase(path.join(directory, "webspeak.db")); - const bootstrap = new BootstrapManager(path.join(directory, "bootstrap")); const service = new AdminService( database, loadOrCreateMasterSecret(path.join(directory, "master.key")), - bootstrap, silentLogger, legacyPath, async () => ({ ok: true, protocol: "ts6", latencyMs: 4, serverName: "Mock TS", requiresPassword: true }), ); - service.initialize(); + await service.initialize(); assert.equal(readFileSync(legacyPath, "utf8"), legacyText); assert.equal(database.getSettings().tsHost, "legacy.example.com"); assert.equal(database.getSettings().tsPort, 9988); assert.equal(service.getConnectionPolicy().serverPassword, "legacy-secret-value"); assert.equal(readFileSync(path.join(directory, "webspeak.db")).includes(Buffer.from("legacy-secret-value")), false); - assert.equal(service.getSetupDefaults().legacyConfigImported, true); - - const code = bootstrap.ensure(); - await service.setup({ - bootstrapCode: code, - adminPassword: "a-secure-admin-password", - target: "[2001:db8::10]:9989", - passwordAction: "keep", - accessMode: "fixed", - siteName: "My WebSpeak", - welcomeText: "Hello everyone", - }); assert.equal(service.isInitialized(), true); - assert.equal(await service.verifyPassword("a-secure-admin-password"), true); - assert.equal(await service.verifyPassword("not-the-password"), false); + assert.equal(await service.verifyPassword("admin", "admin"), true); + assert.equal(await service.verifyPassword("wrong-user", "admin"), false); + assert.equal(service.isPasswordChangeRequired(), true); + await service.changePassword("a-secure-admin-password"); + assert.equal(await service.verifyPassword("admin", "a-secure-admin-password"), true); + assert.equal(await service.verifyPassword("admin", "admin"), false); + assert.equal(service.isPasswordChangeRequired(), false); assert.equal(service.getPublicConfig().accessMode, "fixed"); assert.equal("target" in service.getPublicConfig(), false); diff --git a/test/config.test.ts b/test/config.test.ts index 285f5b8..6e4c78a 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { describe, it } from "node:test"; import { migrateConfig, saveConfig } from "../src/config.js"; -describe("bootstrap config migration", () => { +describe("legacy config migration", () => { it("drops deprecated runtime controls while preserving the TeamSpeak target", () => { assert.deepEqual(migrateConfig({ port: 3999, diff --git a/test/security.test.ts b/test/security.test.ts index de83430..1d8816e 100644 --- a/test/security.test.ts +++ b/test/security.test.ts @@ -1,12 +1,11 @@ import assert from "node:assert/strict"; -import { mkdtempSync, readFileSync } from "node:fs"; +import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { loadOrCreateMasterSecret } from "../src/security/master-secret.js"; import { decryptSecret, encryptSecret } from "../src/security/secret-crypto.js"; import { hashAdminPassword, verifyAdminPassword } from "../src/security/admin-password.js"; -import { BootstrapManager } from "../src/security/bootstrap.js"; test("master secret is stable and protects authenticated ciphertext", () => { const directory = mkdtempSync(path.join(tmpdir(), "webspeak-secret-")); @@ -32,17 +31,8 @@ test("admin password uses a salted scrypt credential", async () => { assert.equal(await verifyAdminPassword("a-long-admin-password", first), true); assert.equal(await verifyAdminPassword("wrong-password-value", first), false); assert.equal(JSON.stringify(first).includes("a-long-admin-password"), false); -}); -test("bootstrap code persists until it is consumed", () => { - const directory = mkdtempSync(path.join(tmpdir(), "webspeak-bootstrap-")); - const bootstrapPath = path.join(directory, "bootstrap"); - const firstManager = new BootstrapManager(bootstrapPath); - const code = firstManager.ensure(); - assert.match(code, /^(?:[A-F0-9]{4}-){7}[A-F0-9]{4}$/); - assert.equal(new BootstrapManager(bootstrapPath).ensure(), code); - assert.equal(firstManager.verify(code.toLocaleLowerCase()), true); - assert.equal(firstManager.verify("0000-0000"), false); - firstManager.consume(); - assert.throws(() => readFileSync(bootstrapPath)); + const pending = await hashAdminPassword("admin", { username: "admin", mustChangePassword: true, allowWeakPassword: true }); + assert.equal(pending.username, "admin"); + assert.equal(pending.mustChangePassword, true); }); diff --git a/web/src/views/AdminView.vue b/web/src/views/AdminView.vue index 8608876..5816423 100644 --- a/web/src/views/AdminView.vue +++ b/web/src/views/AdminView.vue @@ -2,43 +2,12 @@

{{ tr('loading') }}

-
-
-
WebSpeak{{ tr('adminConsole') }}
-
{{ tr('firstSetup') }}

{{ tr('setupTitle') }}

{{ tr('setupLead') }}

-
- -
-
- -
-
-
-
{{ tr('stepCounter', { current: setupStep, total: 3 }) }}

{{ setupSteps[setupStep - 1]?.title }}

{{ setupSteps[setupStep - 1]?.lead }}

-
{{ errorMessage }}
- -
- - - -
-
- -
- - - -
{{ testResult.ok ? tr('connectionReady') : tr('connectionFailed') }}{{ testResultText }}
-
- -
-
{{ tr('accessMode') }}
- - -
- -
-
+
+
@@ -46,7 +15,7 @@
@@ -88,7 +57,7 @@ import { RouterLink, useRoute, useRouter } from "vue-router"; import Icon from "../components/Icon.vue"; type Language = "zh" | "en"; -type Screen = "setup" | "login" | "admin"; +type Screen = "login" | "change-password" | "admin"; type AccessMode = "fixed" | "open"; interface ProbeState { ok: boolean; protocol?: string | null; latencyMs?: number; serverName?: string | null; code?: string } @@ -98,49 +67,203 @@ const language = ref((localStorage.getItem("webspeak:language") as Lan const loading = ref(true); const screen = ref("login"); const csrfToken = ref(""); -const setupStep = ref(1); const submitting = ref(false); const testing = ref(false); const errorMessage = ref(""); +const loginUsername = ref("admin"); const loginPassword = ref(""); +const newPassword = ref(""); +const confirmNewPassword = ref(""); const testResult = ref(null); -const setup = reactive({ bootstrapCode: "", adminPassword: "", confirmPassword: "", target: "127.0.0.1:9987", serverPassword: "", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "" }); const serverForm = reactive({ target: "", serverPassword: "", passwordAction: "keep" as "keep" | "replace" | "remove", hasPassword: false, accessMode: "fixed" as AccessMode, siteName: "WebSpeak", welcomeText: "", detectedProtocol: null as string | null, lastTestAt: null as string | null, lastTestLatencyMs: null as number | null }); const overview = reactive({ gateway: { version: "", uptimeSeconds: 0 }, teamSpeak: { target: "", status: "unknown", protocol: null as string | null, lastTestAt: null as string | null, latencyMs: null as number | null }, sessions: { active: 0, peak: 0, limit: 100 }, recentEvents: [] as Array<{ event: string; createdAt: string }>, legacyConfigImported: false }); const copy = { zh: { - loading: "正在载入管理控制台…", adminConsole: "管理控制台", firstSetup: "首次配置", setupTitle: "几分钟内完成 WebSpeak 配置", setupLead: "建立管理员安全域、连接 TeamSpeak,并决定访客可以连接到哪里。", secureAdmin: "保护管理入口", secureAdminLead: "使用 Bootstrap 代码创建唯一的管理员密码。", connectTeamSpeak: "连接 TeamSpeak", connectTeamSpeakLead: "填写服务器地址并进行真实连接测试。", accessExperience: "访问与站点", accessExperienceLead: "选择访问策略并设置访客看到的内容。", stepCounter: "第 {{current}} / {{total}} 步", bootstrapCode: "Bootstrap 代码", bootstrapPlaceholder: "从启动日志中复制", newPassword: "新管理员密码", passwordPlaceholder: "至少 12 个字符", passwordHint: "无需特定符号组合,建议使用长且唯一的密码。", confirmPassword: "确认管理员密码", serverAddress: "TeamSpeak 服务器地址", serverPlaceholder: "例如 ts.example.com:9987", serverHint: "支持主机名、IPv4 与 [IPv6]:端口;不需要选择 TS3 或 TS6。", serverPassword: "服务器密码", optional: "可选", optionalPassword: "无密码则留空", passwordConfigured: "已配置密码(留空保持不变)", testConnection: "测试连接", testing: "正在测试…", connectionReady: "连接成功", connectionFailed: "连接失败", accessMode: "访客访问模式", fixedMode: "仅限此 TeamSpeak 服务器", fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。", openMode: "允许访客输入其他服务器", openModeLead: "访客可输入公网 TeamSpeak 地址;内网和保留地址会被阻止。", siteName: "站点显示名称", welcomeText: "欢迎文本", back: "返回", continue: "继续", finishSetup: "完成配置", languageSwitch: "English", welcomeAdmin: "欢迎回来", loginLead: "输入管理员密码以管理此 WebSpeak 实例。", adminPassword: "管理员密码", login: "登录", overview: "概览", server: "服务器", openGuest: "打开访客页面", logout: "退出登录", gatewayRunning: "网关运行中", serverSettings: "服务器设置", serverSettingsLead: "管理默认 TeamSpeak 目标、访问策略和访客页面内容。", saving: "正在保存…", saveChanges: "保存更改", teamSpeakTarget: "TeamSpeak 目标", change: "修改", remove: "移除", accessAndIdentity: "访问与站点信息", runtimeFacts: "运行时信息", detectedProtocol: "检测到的协议", lastTest: "最近测试", latency: "延迟", internalPort: "内部端口", unknown: "未知", legacyImported: "已导入旧 config.json。WebSpeak 现在由管理控制台管理,原文件不会再作为实时配置源。", gotIt: "知道了", systemStatus: "系统状态", everythingRunning: "WebSpeak 正常运行", overviewLead: "管理服务可用;TeamSpeak 可达性以最近一次连接测试为准。", running: "运行中", gateway: "网关", activeSessions: "活动会话", peakSessions: "本次启动峰值 {{count}}", targetHealth: "目标状态", targetHealthLead: "最近一次短连接测试的结果。", manage: "管理", status: "状态", recentEvents: "最近事件", recentEventsLead: "仅记录管理和系统事件,不包含聊天内容。", noRecentEvents: "暂无事件", reachable: "可连接", unreachable: "不可连接", notTested: "尚未测试", setupPasswordsMismatch: "两次输入的密码不一致。", setupPasswordShort: "管理员密码至少需要 12 个字符。", connectionTestRequired: "请先成功测试 TeamSpeak 连接。", invalidBootstrap: "Bootstrap 代码无效。", invalidPassword: "管理员密码错误。", rateLimited: "尝试次数过多,请稍后再试。", requestFailed: "请求失败,请检查输入后重试。", saved: "设置已保存", loginEvent: "管理员登录成功", logoutEvent: "管理员退出登录", settingsEvent: "服务器设置已更新", initializedEvent: "管理员初始化完成", importedEvent: "已导入旧配置", testEvent: "连接测试完成", + loading: "正在载入管理控制台…", + adminConsole: "管理控制台", + changePasswordTitle: "首次登录需要修改密码", + changePasswordLead: "默认密码仅用于首次登录。请设置一个至少 12 个字符的新管理员密码。", + savePassword: "保存新密码", + defaultCredentialNotice: "默认账号:admin,默认密码:admin。修改后旧密码将立即失效。", + adminUsername: "管理员账号", + newPassword: "新管理员密码", + passwordPlaceholder: "至少 12 个字符", + passwordHint: "建议使用长且唯一的密码。", + confirmPassword: "确认管理员密码", + languageSwitch: "English", + welcomeAdmin: "欢迎回来", + loginLead: "输入管理员账号和密码以管理此 WebSpeak 实例。", + adminPassword: "管理员密码", + login: "登录", + overview: "概览", + server: "服务器", + openGuest: "打开访客页面", + logout: "退出登录", + gatewayRunning: "网关运行中", + serverSettings: "服务器设置", + serverSettingsLead: "管理默认 TeamSpeak 目标、访问策略和访客页面内容。", + saving: "正在保存…", + saveChanges: "保存更改", + teamSpeakTarget: "TeamSpeak 目标", + serverAddress: "TeamSpeak 服务器地址", + serverPlaceholder: "例如 ts.example.com:9987", + serverHint: "支持主机名、IPv4 与 [IPv6]:端口;不需要选择 TS3 或 TS6。", + serverPassword: "服务器密码", + optional: "可选", + optionalPassword: "无密码则留空", + passwordConfigured: "已配置密码(留空保持不变)", + change: "修改", + remove: "移除", + testConnection: "测试连接", + testing: "正在测试…", + connectionReady: "连接成功", + connectionFailed: "连接失败", + accessAndIdentity: "访问与站点信息", + accessMode: "访客访问模式", + fixedMode: "仅限此 TeamSpeak 服务器", + fixedModeLead: "访客只需填写昵称,目标和密码由 WebSpeak 管理。", + openMode: "允许访客输入其他服务器", + openModeLead: "访客可输入公网 TeamSpeak 地址;内网和保留地址会被阻止。", + siteName: "站点显示名称", + welcomeText: "欢迎文本", + runtimeFacts: "运行时信息", + detectedProtocol: "检测到的协议", + lastTest: "最近测试", + latency: "延迟", + internalPort: "内部端口", + unknown: "未知", + legacyImported: "已导入旧 config.json。WebSpeak 现在由管理控制台管理,原文件不会再作为实时配置源。", + gotIt: "知道了", + systemStatus: "系统状态", + everythingRunning: "WebSpeak 正常运行", + overviewLead: "管理服务可用;TeamSpeak 可达性以最近一次连接测试为准。", + running: "运行中", + gateway: "网关", + activeSessions: "活动会话", + peakSessions: "本次启动峰值 {{count}}", + targetHealth: "目标状态", + targetHealthLead: "最近一次短连接测试的结果。", + manage: "管理", + status: "状态", + recentEvents: "最近事件", + recentEventsLead: "仅记录管理和系统事件,不包含聊天内容。", + noRecentEvents: "暂无事件", + reachable: "可连接", + unreachable: "不可连接", + notTested: "尚未测试", + setupPasswordsMismatch: "两次输入的密码不一致。", + setupPasswordShort: "管理员密码至少需要 12 个字符。", + invalidPassword: "管理员密码错误。", + rateLimited: "尝试次数过多,请稍后再试。", + requestFailed: "请求失败,请检查输入后重试。", + loginEvent: "管理员登录成功", + logoutEvent: "管理员退出登录", + settingsEvent: "服务器设置已更新", + initializedEvent: "默认管理员账号已创建", + importedEvent: "已导入旧配置", + testEvent: "连接测试完成", }, en: { - loading: "Loading the admin console…", adminConsole: "Admin Console", firstSetup: "FIRST SETUP", setupTitle: "Configure WebSpeak in a few minutes", setupLead: "Secure the admin area, connect TeamSpeak, and decide where guests may connect.", secureAdmin: "Secure admin access", secureAdminLead: "Use the bootstrap code to create the single administrator password.", connectTeamSpeak: "Connect TeamSpeak", connectTeamSpeakLead: "Enter the server address and run a real connection test.", accessExperience: "Access and site", accessExperienceLead: "Choose the access policy and guest-facing content.", stepCounter: "Step {{current}} of {{total}}", bootstrapCode: "Bootstrap code", bootstrapPlaceholder: "Copy it from the startup log", newPassword: "New admin password", passwordPlaceholder: "At least 12 characters", passwordHint: "No symbol template is required; use a long, unique password.", confirmPassword: "Confirm admin password", serverAddress: "TeamSpeak server address", serverPlaceholder: "e.g. ts.example.com:9987", serverHint: "Hostnames, IPv4 and [IPv6]:port are supported. TS3/TS6 is detected automatically.", serverPassword: "Server password", optional: "Optional", optionalPassword: "Leave blank when unused", passwordConfigured: "Password configured (leave blank to keep it)", testConnection: "Test connection", testing: "Testing…", connectionReady: "Connection ready", connectionFailed: "Connection failed", accessMode: "Guest access mode", fixedMode: "Only this TeamSpeak server", fixedModeLead: "Guests enter only a nickname; WebSpeak manages the target and password.", openMode: "Allow other TeamSpeak servers", openModeLead: "Guests may enter public TeamSpeak addresses; private and reserved networks are blocked.", siteName: "Site display name", welcomeText: "Welcome text", back: "Back", continue: "Continue", finishSetup: "Finish setup", languageSwitch: "中文", welcomeAdmin: "Welcome back", loginLead: "Enter the admin password to manage this WebSpeak instance.", adminPassword: "Admin password", login: "Sign in", overview: "Overview", server: "Server", openGuest: "Open guest page", logout: "Log out", gatewayRunning: "Gateway running", serverSettings: "Server settings", serverSettingsLead: "Manage the default TeamSpeak target, access policy, and guest-facing content.", saving: "Saving…", saveChanges: "Save changes", teamSpeakTarget: "TeamSpeak target", change: "Change", remove: "Remove", accessAndIdentity: "Access and site identity", runtimeFacts: "Runtime facts", detectedProtocol: "Detected protocol", lastTest: "Last test", latency: "Latency", internalPort: "Internal port", unknown: "Unknown", legacyImported: "Legacy config.json was imported. WebSpeak is now managed here and the old file is no longer a live configuration source.", gotIt: "Got it", systemStatus: "SYSTEM STATUS", everythingRunning: "WebSpeak is running", overviewLead: "The management service is available. TeamSpeak reachability reflects the latest connection test.", running: "Running", gateway: "Gateway", activeSessions: "Active sessions", peakSessions: "Peak this run: {{count}}", targetHealth: "Target health", targetHealthLead: "Result of the latest short-lived connection test.", manage: "Manage", status: "Status", recentEvents: "Recent events", recentEventsLead: "Only system and admin events are recorded; chat content is excluded.", noRecentEvents: "No recent events", reachable: "Reachable", unreachable: "Unreachable", notTested: "Not tested", setupPasswordsMismatch: "The two passwords do not match.", setupPasswordShort: "The admin password must be at least 12 characters.", connectionTestRequired: "Run a successful TeamSpeak connection test first.", invalidBootstrap: "The bootstrap code is invalid.", invalidPassword: "The admin password is incorrect.", rateLimited: "Too many attempts. Try again later.", requestFailed: "The request failed. Check the fields and try again.", saved: "Settings saved", loginEvent: "Administrator signed in", logoutEvent: "Administrator signed out", settingsEvent: "Server settings changed", initializedEvent: "Administrator setup completed", importedEvent: "Legacy configuration imported", testEvent: "Connection test completed", + loading: "Loading the admin console…", + adminConsole: "Admin Console", + changePasswordTitle: "Change the default password", + changePasswordLead: "The default password is for first sign-in only. Set a new admin password with at least 12 characters.", + savePassword: "Save new password", + defaultCredentialNotice: "Default account: admin. Default password: admin. The old password expires immediately after you save.", + adminUsername: "Admin username", + newPassword: "New admin password", + passwordPlaceholder: "At least 12 characters", + passwordHint: "Use a long, unique password.", + confirmPassword: "Confirm admin password", + languageSwitch: "中文", + welcomeAdmin: "Welcome back", + loginLead: "Enter the admin account and password to manage this WebSpeak instance.", + adminPassword: "Admin password", + login: "Sign in", + overview: "Overview", + server: "Server", + openGuest: "Open guest page", + logout: "Log out", + gatewayRunning: "Gateway running", + serverSettings: "Server settings", + serverSettingsLead: "Manage the default TeamSpeak target, access policy, and guest-facing content.", + saving: "Saving…", + saveChanges: "Save changes", + teamSpeakTarget: "TeamSpeak target", + serverAddress: "TeamSpeak server address", + serverPlaceholder: "e.g. ts.example.com:9987", + serverHint: "Hostnames, IPv4 and [IPv6]:port are supported. TS3/TS6 is detected automatically.", + serverPassword: "Server password", + optional: "Optional", + optionalPassword: "Leave blank when unused", + passwordConfigured: "Password configured (leave blank to keep it)", + change: "Change", + remove: "Remove", + testConnection: "Test connection", + testing: "Testing…", + connectionReady: "Connection ready", + connectionFailed: "Connection failed", + accessAndIdentity: "Access and site identity", + accessMode: "Guest access mode", + fixedMode: "Only this TeamSpeak server", + fixedModeLead: "Guests enter only a nickname; WebSpeak manages the target and password.", + openMode: "Allow other TeamSpeak servers", + openModeLead: "Guests may enter public TeamSpeak addresses; private and reserved networks are blocked.", + siteName: "Site display name", + welcomeText: "Welcome text", + runtimeFacts: "Runtime facts", + detectedProtocol: "Detected protocol", + lastTest: "Last test", + latency: "Latency", + internalPort: "Internal port", + unknown: "Unknown", + legacyImported: "Legacy config.json was imported. WebSpeak is now managed here and the old file is no longer a live configuration source.", + gotIt: "Got it", + systemStatus: "SYSTEM STATUS", + everythingRunning: "WebSpeak is running", + overviewLead: "The management service is available. TeamSpeak reachability reflects the latest connection test.", + running: "Running", + gateway: "Gateway", + activeSessions: "Active sessions", + peakSessions: "Peak this run: {{count}}", + targetHealth: "Target health", + targetHealthLead: "Result of the latest short-lived connection test.", + manage: "Manage", + status: "Status", + recentEvents: "Recent events", + recentEventsLead: "Only system and admin events are recorded; chat content is excluded.", + noRecentEvents: "No recent events", + reachable: "Reachable", + unreachable: "Unreachable", + notTested: "Not tested", + setupPasswordsMismatch: "The two passwords do not match.", + setupPasswordShort: "The admin password must be at least 12 characters.", + invalidPassword: "The admin password is incorrect.", + rateLimited: "Too many attempts. Try again later.", + requestFailed: "The request failed. Check the fields and try again.", + loginEvent: "Administrator signed in", + logoutEvent: "Administrator signed out", + settingsEvent: "Server settings changed", + initializedEvent: "Default administrator account created", + importedEvent: "Legacy configuration imported", + testEvent: "Connection test completed", }, } as const; -const zhCopyOverrides: Partial> = { - secureAdminLead: "使用初始化代码创建唯一的管理员密码。", - bootstrapCode: "初始化代码", - invalidBootstrap: "初始化代码无效。", -}; -function tr(key: keyof typeof copy.zh, vars: Record = {}): string { let value: string = language.value === "zh" ? zhCopyOverrides[key] ?? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; } -const setupSteps = computed(() => [{ index: 1, title: tr('secureAdmin'), lead: tr('secureAdminLead') }, { index: 2, title: tr('connectTeamSpeak'), lead: tr('connectTeamSpeakLead') }, { index: 3, title: tr('accessExperience'), lead: tr('accessExperienceLead') }]); -const passwordStrength = computed(() => Math.min(100, Math.max(8, setup.adminPassword.length * 5 + (/[\s\W]/.test(setup.adminPassword) ? 15 : 0)))); +function tr(key: keyof typeof copy.zh, vars: Record = {}): string { let value: string = language.value === "zh" ? copy.zh[key] : copy.en[key] ?? copy.zh[key]; for (const [name, replacement] of Object.entries(vars)) value = value.replaceAll(`{{${name}}}`, String(replacement)); return value; } +const passwordStrength = computed(() => Math.min(100, Math.max(8, newPassword.value.length * 5 + (/[\s\W]/.test(newPassword.value) ? 15 : 0)))); const currentPageTitle = computed(() => route.path === "/admin/server" ? tr('server') : tr('overview')); const testResultText = computed(() => { if (!testResult.value) return ""; if (!testResult.value.ok) return errorText(testResult.value.code); return [testResult.value.protocol?.toUpperCase(), testResult.value.serverName, testResult.value.latencyMs == null ? null : `${testResult.value.latencyMs} ms`].filter(Boolean).join(" · "); }); const targetStatusText = computed(() => overview.teamSpeak.status === "reachable" ? tr('reachable') : overview.teamSpeak.status === "unreachable" ? tr('unreachable') : tr('notTested')); -onMounted(bootstrapView); -watch(() => [setup.target, setup.serverPassword], () => { if (!testing.value) testResult.value = null; }); +onMounted(loadAdminView); watch(() => [serverForm.target, serverForm.serverPassword, serverForm.passwordAction], () => { if (!testing.value && screen.value === "admin") testResult.value = null; }); -async function bootstrapView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.initialized) { screen.value = "setup"; if (route.path !== "/admin/setup") await router.replace("/admin/setup"); } else if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/setup") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } } -function applySetupDefaults(value: Record) { if (typeof value.target === "string") setup.target = value.target; if (value.accessMode === "open") setup.accessMode = "open"; if (typeof value.siteName === "string") setup.siteName = value.siteName; if (typeof value.welcomeText === "string") setup.welcomeText = value.welcomeText; setup.hasPassword = Boolean(value.hasPassword); } -function goToSetupStep(step: number) { if (step < setupStep.value) setupStep.value = step; } -async function nextSetupStep() { errorMessage.value = ""; if (setupStep.value === 1) { if (setup.adminPassword.length < 12) return void (errorMessage.value = tr('setupPasswordShort')); if (setup.adminPassword !== setup.confirmPassword) return void (errorMessage.value = tr('setupPasswordsMismatch')); submitting.value = true; try { applySetupDefaults(await sendJson("/api/admin/setup/defaults", "POST", { bootstrapCode: setup.bootstrapCode }, false)); setupStep.value = 2; } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } return; } if (setupStep.value === 2) { if (!testResult.value?.ok) return void (errorMessage.value = tr('connectionTestRequired')); setupStep.value = 3; return; } await finishSetup(); } -async function testSetupConnection() { await runTest("/api/admin/setup/test", { bootstrapCode: setup.bootstrapCode, target: setup.target, serverPassword: setup.serverPassword, passwordAction: setup.serverPassword ? "replace" : "keep" }); } -async function finishSetup() { submitting.value = true; try { const result = await sendJson("/api/admin/setup", "POST", { bootstrapCode: setup.bootstrapCode, adminPassword: setup.adminPassword, target: setup.target, serverPassword: setup.serverPassword, passwordAction: setup.serverPassword ? "replace" : "keep", accessMode: setup.accessMode, siteName: setup.siteName, welcomeText: setup.welcomeText }, false); csrfToken.value = String(result.csrfToken || ""); screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } -async function login() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/login", "POST", { password: loginPassword.value }, false); csrfToken.value = String(result.csrfToken || ""); loginPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } +async function loadAdminView() { loading.value = true; try { const session = await getJson("/api/admin/session"); if (!session.authenticated) { screen.value = "login"; if (route.path !== "/admin/login") await router.replace("/admin/login"); } else if (session.mustChangePassword) { csrfToken.value = String(session.csrfToken || ""); screen.value = "change-password"; if (route.path !== "/admin/change-password") await router.replace("/admin/change-password"); } else { csrfToken.value = String(session.csrfToken || ""); screen.value = "admin"; if (route.path === "/admin/login" || route.path === "/admin/change-password") await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } } catch { errorMessage.value = tr('requestFailed'); } finally { loading.value = false; } } +async function login() { submitting.value = true; errorMessage.value = ""; try { const result = await sendJson("/api/admin/login", "POST", { username: loginUsername.value, password: loginPassword.value }, false); csrfToken.value = String(result.csrfToken || ""); loginPassword.value = ""; if (result.mustChangePassword) { screen.value = "change-password"; await router.replace("/admin/change-password"); } else { screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } +async function changePassword() { errorMessage.value = ""; if (newPassword.value.length < 12) { errorMessage.value = tr('setupPasswordShort'); return; } if (newPassword.value !== confirmNewPassword.value) { errorMessage.value = tr('setupPasswordsMismatch'); return; } submitting.value = true; try { await sendJson("/api/admin/change-password", "POST", { newPassword: newPassword.value }); newPassword.value = ""; confirmNewPassword.value = ""; screen.value = "admin"; await router.replace("/admin"); await Promise.all([loadOverview(), loadServerSettings()]); } catch (error) { errorMessage.value = errorText((error as ApiError).code); } finally { submitting.value = false; } } async function logout() { try { await sendJson("/api/admin/logout", "POST", {}); } finally { csrfToken.value = ""; screen.value = "login"; await router.replace("/admin/login"); } } async function loadOverview() { Object.assign(overview, await getJson("/api/admin/overview")); } async function loadServerSettings() { const value = await getJson("/api/admin/server"); Object.assign(serverForm, value, { serverPassword: "", passwordAction: "keep" }); } @@ -153,7 +276,7 @@ function toggleLanguage() { language.value = language.value === "zh" ? "en" : "z function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat(language.value === "zh" ? "zh-CN" : "en-US", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)) : "—"; } function formatUptime(seconds: number) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); return language.value === "zh" ? `已运行 ${hours} 小时 ${minutes} 分钟` : `Up ${hours}h ${minutes}m`; } function eventName(event: string) { if (event === "ADMIN_LOGIN_FAILED") return language.value === "zh" ? "管理员登录失败" : "Administrator login failed"; if (event === "CONNECTION_TEST_SUCCEEDED") return language.value === "zh" ? "连接测试成功" : "Connection test succeeded"; if (event === "CONNECTION_TEST_FAILED") return language.value === "zh" ? "连接测试失败" : "Connection test failed"; const names: Record = { ADMIN_LOGIN_SUCCEEDED: "loginEvent", ADMIN_LOGOUT: "logoutEvent", SETTINGS_CHANGED: "settingsEvent", ADMIN_INITIALIZED: "initializedEvent", LEGACY_CONFIG_IMPORTED: "importedEvent", CONNECTION_TEST: "testEvent" }; return names[event] ? tr(names[event]) : language.value === "zh" ? "系统事件" : event.replaceAll("_", " "); } -function errorText(code?: string) { if (code === "INVALID_BOOTSTRAP") return tr('invalidBootstrap'); if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "RATE_LIMITED") return tr('rateLimited'); const probe: Record = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); } +function errorText(code?: string) { if (code === "INVALID_PASSWORD") return tr('invalidPassword'); if (code === "INVALID_ADMIN_PASSWORD") return tr('setupPasswordShort'); if (code === "PASSWORD_CHANGE_REQUIRED") return tr('changePasswordLead'); if (code === "RATE_LIMITED") return tr('rateLimited'); const probe: Record = { INVALID_TARGET: { zh: "TeamSpeak 服务器地址格式无效。", en: "The TeamSpeak server address is invalid." }, HOST_NOT_FOUND: { zh: "找不到服务器主机名。", en: "The server hostname could not be resolved." }, UNREACHABLE: { zh: "无法连接 TeamSpeak 服务器。", en: "The TeamSpeak server is unreachable." }, TIMEOUT: { zh: "连接 TeamSpeak 超时。", en: "The TeamSpeak connection timed out." }, PROTOCOL_NEGOTIATION_FAILED: { zh: "无法识别 TeamSpeak 协议。", en: "TeamSpeak protocol negotiation failed." }, SERVER_REJECTED: { zh: "TeamSpeak 服务器拒绝了连接。", en: "The TeamSpeak server rejected the connection." }, TARGET_NOT_ALLOWED: { zh: "此地址不允许在开放模式中使用。", en: "This target is not allowed in open mode." } }; return probe[code || ""]?.[language.value] ?? tr('requestFailed'); } interface ApiError extends Error { code?: string } async function getJson(url: string): Promise { const response = await fetch(url, { headers: { accept: "application/json" } }); return parseResponse(response); } @@ -166,4 +289,5 @@ async function parseResponse(response: Response) { const value = await response. :global(*){box-sizing:border-box}:global(body){margin:0;font-family:Inter,"Segoe UI","PingFang SC",sans-serif;color:#20302c;background:#f4f8f6}.admin-root{min-height:100dvh}.auth-layout{display:grid;min-height:100dvh;grid-template-columns:minmax(360px,.82fr) minmax(520px,1.18fr)}.auth-intro{display:flex;flex-direction:column;padding:48px clamp(38px,6vw,92px);color:#e8fffa;background:radial-gradient(circle at 20% 0,rgba(90,211,191,.28),transparent 32rem),#063f3b}.admin-brand{display:flex;align-items:center;gap:12px}.admin-brand>span{display:grid;place-items:center;width:42px;height:42px;color:#fff;background:#07877d;border-radius:12px;box-shadow:0 8px 22px rgba(0,0,0,.15)}.admin-brand strong,.admin-brand small{display:block}.admin-brand strong{font-size:20px;letter-spacing:-.04em}.admin-brand small{margin-top:3px;color:#9bc9c2;font-size:11px}.intro-copy{margin:auto 0 48px}.intro-copy i{color:#75e3d2;font-size:12px;font-style:normal;font-weight:800;letter-spacing:.12em}.intro-copy h1{max-width:540px;margin:16px 0;font-size:clamp(40px,5vw,66px);line-height:1.03;letter-spacing:-.065em}.intro-copy p{max-width:530px;color:#a9d0ca;font-size:16px;line-height:1.75}.step-list{display:grid;gap:10px}.step-list button{display:flex;align-items:center;gap:13px;width:100%;padding:13px;color:#89bbb4;text-align:left;background:transparent;border:1px solid transparent;border-radius:12px}.step-list button.active{color:#fff;background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.1)}.step-list button.done{color:#8ee4d7}.step-list button>span{display:grid;place-items:center;width:28px;height:28px;flex:none;border:1px solid currentColor;border-radius:50%;font-size:12px;font-weight:800}.step-list strong,.step-list small{display:block}.step-list strong{font-size:13px}.step-list small{margin-top:3px;font-size:10px;opacity:.75}.auth-panel{position:relative;display:grid;place-items:center;padding:80px 40px;background:radial-gradient(circle at 80% 10%,rgba(99,205,188,.15),transparent 25rem),#f5f9f7}.panel-tools{position:absolute;top:28px;right:34px}.panel-tools button,.language-link,.admin-topbar button{color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;padding:8px 12px;font-size:11px;font-weight:700;cursor:pointer}.setup-card,.login-card{width:min(560px,100%);padding:36px;background:#fff;border:1px solid #dfeae6;border-radius:20px;box-shadow:0 20px 55px rgba(27,69,61,.09)}.setup-card header small{color:#07877d;font-size:11px;font-weight:800;letter-spacing:.08em}.setup-card header h2,.login-card h1{margin:10px 0 7px;font-size:29px;letter-spacing:-.045em}.setup-card header p,.login-card header p{margin:0;color:#71817c;font-size:13px;line-height:1.6}.form-stack,.login-card form{display:grid;gap:17px;margin-top:27px}label>span,fieldset legend{display:block;margin-bottom:7px;color:#40514c;font-size:12px;font-weight:700}label em{color:#91a09c;font-size:10px;font-style:normal;font-weight:500}label small{display:block;margin-top:6px;color:#899792;font-size:10px;line-height:1.5}input,textarea{width:100%;padding:11px 12px;color:#22332f;background:#fbfdfc;border:1px solid #dbe7e3;border-radius:9px;font:inherit;font-size:13px;outline:none}input{height:43px}input:focus,textarea:focus{border-color:#54bdb2;box-shadow:0 0 0 3px rgba(84,189,178,.13)}textarea{resize:vertical}.strength{height:4px;overflow:hidden;background:#e7eeeb;border-radius:4px}.strength i{display:block;height:100%;background:linear-gradient(90deg,#e7a452,#50c5a2);transition:.2s}fieldset{display:grid;gap:9px;margin:0;padding:0;border:0}.choice{display:flex;align-items:flex-start;gap:10px;padding:13px;border:1px solid #dfe9e6;border-radius:10px;cursor:pointer}.choice:has(input:checked){border-color:#62bfb5;background:#eff8f6}.choice input{width:16px;height:16px;flex:none;margin:2px 0}.choice strong,.choice small{display:block}.choice strong{font-size:12px}.choice small{margin-top:4px;color:#7b8985;font-size:10px;line-height:1.45}.setup-card footer{display:flex;align-items:center;justify-content:space-between;margin-top:28px;padding-top:20px;border-top:1px solid #edf1ef}.primary-button,.secondary-button,.text-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:42px;padding:0 18px;border:0;border-radius:9px;font-size:12px;font-weight:800;cursor:pointer}.primary-button{color:#fff;background:#087d74}.primary-button:hover{background:#056b63}.primary-button:disabled,.secondary-button:disabled{opacity:.55;cursor:not-allowed}.secondary-button{color:#08776e;background:#eaf6f3;border:1px solid #cfe9e3}.text-button{color:#687a74;background:transparent}.wide{width:100%}.spinner{display:inline-block;width:22px;height:22px;border:2px solid #cde6df;border-top-color:#087d74;border-radius:50%;animation:spin .7s linear infinite}.spinner.small{width:15px;height:15px;border-color:rgba(255,255,255,.35);border-top-color:currentColor}@keyframes spin{to{transform:rotate(360deg)}}.alert{padding:12px 14px;border-radius:9px;font-size:12px;line-height:1.5}.alert.error{color:#a3423d;background:#fff0ef;border:1px solid #f4cbc8}.alert.info{color:#23665f;background:#eaf7f3;border:1px solid #cde9e2}.test-result{display:flex;gap:10px;padding:12px;border-radius:9px}.test-result.success{color:#246c52;background:#eaf8f0}.test-result.error{color:#a3423d;background:#fff0ef}.test-result strong,.test-result small{display:block}.test-result strong{font-size:12px}.test-result small{margin-top:3px;font-size:10px}.login-page{display:grid;min-height:100dvh;place-items:center;padding:25px;background:radial-gradient(circle at 50% 10%,rgba(95,211,191,.2),transparent 30rem),#f4f8f6}.login-card{max-width:430px;text-align:center}.admin-brand.centered{justify-content:center}.login-card header{margin:30px 0 24px}.login-card label{text-align:left}.language-link{margin-top:20px}.center-card{position:absolute;inset:0;display:grid;place-content:center;justify-items:center;color:#60746e}.admin-shell{display:grid;min-height:100dvh;grid-template-columns:236px minmax(0,1fr)}.admin-sidebar{position:sticky;top:0;display:flex;height:100dvh;flex-direction:column;padding:26px 18px;background:#073f3b;color:#eafffb}.admin-sidebar .admin-brand{padding:0 8px 28px}.admin-sidebar nav{display:grid;gap:6px}.admin-sidebar nav a,.sidebar-bottom a,.sidebar-bottom button{display:flex;align-items:center;gap:10px;padding:11px 12px;color:#9fc8c2;text-decoration:none;background:transparent;border:0;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer}.admin-sidebar nav a.active{color:#fff;background:#0b5b54}.sidebar-bottom{display:grid;gap:4px;margin-top:auto;padding-top:20px;border-top:1px solid rgba(255,255,255,.1)}.admin-main{min-width:0}.admin-topbar{display:flex;align-items:center;justify-content:space-between;min-height:82px;padding:0 clamp(24px,4vw,58px);background:#fff;border-bottom:1px solid #e4ebe8}.admin-topbar small,.admin-topbar h1{display:block;margin:0}.admin-topbar small{color:#8b9995;font-size:10px;text-transform:uppercase}.admin-topbar h1{margin-top:4px;font-size:21px}.admin-topbar>div:last-child{display:flex;align-items:center;gap:8px;color:#66807a;font-size:11px}.running-dot{width:7px;height:7px;background:#55d17a;border-radius:50%;box-shadow:0 0 0 4px #e5f8ea}.page-content{width:min(1180px,calc(100% - 48px));margin:0 auto;padding:40px 0 70px}.page-alert{margin:20px 24px 0}.page-heading{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px}.page-heading h2{margin:0;font-size:25px}.page-heading p{margin:7px 0 0;color:#75857f;font-size:12px}.settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px}.settings-card,.readonly-card,.overview-card{padding:24px;background:#fff;border:1px solid #dfe8e5;border-radius:14px}.settings-card{display:grid;align-content:start;gap:18px}.settings-card h3,.readonly-card h3,.overview-card h3{margin:0;font-size:15px}.password-row{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:9px}.password-actions{display:flex;gap:5px;padding-bottom:1px}.password-actions button{height:42px;padding:0 10px;color:#55706a;background:#eef4f2;border:0;border-radius:8px;font-size:10px;font-weight:700;cursor:pointer}.password-actions button.active{color:#fff;background:#16877d}.password-actions button.danger{color:#a24640;background:#fff0ef}.readonly-card{margin-top:20px}.readonly-card dl,.overview-card dl{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin:18px 0 0}.readonly-card dl div,.overview-card dl div{padding:13px;background:#f6f9f8;border-radius:9px}.readonly-card dt,.overview-card dt{color:#85948f;font-size:10px}.readonly-card dd,.overview-card dd{margin:5px 0 0;font-size:12px;font-weight:700}.import-notice{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}.import-notice button{color:#08776e;background:transparent;border:0;font-weight:800;cursor:pointer}.hero-status{display:flex;align-items:center;justify-content:space-between;padding:30px;color:#eafffa;background:linear-gradient(135deg,#07524c,#087d74);border-radius:16px}.hero-status small{color:#80d8cc;font-size:10px;font-weight:800;letter-spacing:.1em}.hero-status h2{margin:9px 0 5px;font-size:27px}.hero-status p{margin:0;color:#a8d8d1;font-size:12px}.status-badge{display:flex;align-items:center;gap:7px;padding:8px 12px;background:rgba(255,255,255,.12);border-radius:99px;font-size:11px;font-weight:700}.status-badge i{width:7px;height:7px;background:#69e78b;border-radius:50%}.metric-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin:18px 0}.metric-grid article{position:relative;padding:21px;background:#fff;border:1px solid #dfe8e5;border-radius:13px}.metric-grid article>span{position:absolute;top:17px;right:17px;display:grid;place-items:center;width:35px;height:35px;color:#087d74;background:#e9f5f2;border-radius:9px}.metric-grid small,.metric-grid strong,.metric-grid em{display:block}.metric-grid small{color:#82908c;font-size:10px}.metric-grid strong{max-width:80%;margin-top:13px;overflow:hidden;font-size:20px;text-overflow:ellipsis;white-space:nowrap}.metric-grid em{margin-top:7px;color:#71817c;font-size:10px;font-style:normal}.overview-columns{display:grid;grid-template-columns:1.05fr .95fr;gap:18px}.overview-card header{display:flex;justify-content:space-between}.overview-card header p{margin:5px 0 0;color:#7e8c88;font-size:10px}.overview-card header a{color:#087d74;font-size:11px;font-weight:700;text-decoration:none}.overview-card dl{grid-template-columns:1fr 1fr}.overview-card dd{display:flex;align-items:center;gap:7px}.overview-card dd i{width:7px;height:7px;background:#aab5b2;border-radius:50%}.overview-card dd i.reachable{background:#55cb76}.overview-card dd i.unreachable{background:#d85f57}.event-list{display:grid;gap:10px;margin:18px 0 0;padding:0;list-style:none}.event-list li{display:flex;align-items:center;gap:10px;padding:10px;background:#f6f9f8;border-radius:9px}.event-list li>span{display:grid;place-items:center;width:27px;height:27px;color:#087d74;background:#dff1ed;border-radius:8px}.event-list strong,.event-list small{display:block}.event-list strong{font-size:11px}.event-list small{margin-top:3px;color:#879590;font-size:9px}.event-list .empty-event{display:block;color:#82908c;text-align:center} @media(max-width:850px){.auth-layout{display:block}.auth-intro{min-height:auto;padding:28px 24px}.intro-copy{margin:55px 0 35px}.step-list{display:none}.auth-panel{padding:35px 18px 60px}.panel-tools{top:18px;right:18px}.admin-shell{display:block}.admin-sidebar{position:static;width:100%;height:auto;flex-direction:row;align-items:center;padding:12px 16px}.admin-sidebar .admin-brand{padding:0}.admin-sidebar .admin-brand small{display:none}.admin-sidebar nav{display:flex;margin-left:auto}.admin-sidebar nav a{font-size:0}.admin-sidebar nav a .ui-icon{width:20px;height:20px}.sidebar-bottom{display:flex;margin:0 0 0 8px;padding:0;border:0}.sidebar-bottom a{display:none}.sidebar-bottom button{font-size:0}.settings-grid,.overview-columns{grid-template-columns:1fr}.readonly-card dl{grid-template-columns:1fr 1fr}.admin-topbar{padding:0 18px}.page-content{width:min(100% - 28px,700px);padding-top:24px}.metric-grid{grid-template-columns:1fr}.hero-status{align-items:flex-start;gap:20px}.hero-status p{max-width:75%}} @media(max-width:520px){.setup-card,.login-card{padding:25px 20px;border-radius:15px}.setup-card header h2{font-size:24px}.admin-topbar>div:last-child{font-size:0}.page-heading{gap:15px}.page-heading .primary-button{padding-inline:12px}.settings-card,.readonly-card,.overview-card{padding:18px}.readonly-card dl,.overview-card dl{grid-template-columns:1fr}.password-row{grid-template-columns:1fr}.password-actions{padding:0}.hero-status{padding:23px}.status-badge{display:none}} +.security-note{margin:18px 0 0;color:#879590;font-size:11px;line-height:1.5} diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 1c20288..30ff569 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -32,7 +32,7 @@
!{{ localizedMessage(voiceState.error) }}
i{{ localizedMessage(browserError) }}
-
i{{ t('notConfigured') }} {{ t('configureNow') }}
+
i{{ t('notConfigured') }} {{ t('configureNow') }}
@@ -245,8 +245,8 @@ const translations: Record> = { browserWorkspace: "浏览器语音工作台", secureGateway: "安全语音网关", adminConsole: "管理控制台", - notConfigured: "WebSpeak 尚未完成首次配置。", - configureNow: "立即配置", + notConfigured: "WebSpeak 尚未配置 TeamSpeak 目标。", + configureNow: "打开管理控制台", privateAudio: "私密社区语音", joinLine1: "连接服务器,", joinLine2: "马上开始交流。", @@ -381,8 +381,8 @@ const translations: Record> = { browserWorkspace: "Browser voice workspace", secureGateway: "Secure voice gateway", adminConsole: "Admin console", - notConfigured: "WebSpeak setup has not been completed.", - configureNow: "Configure now", + notConfigured: "The WebSpeak TeamSpeak target has not been configured.", + configureNow: "Open admin console", privateAudio: "Private community audio", joinLine1: "Connect to your server,", joinLine2: "start the conversation.", @@ -552,7 +552,7 @@ function localizedMessage(message: string) { "TeamSpeak 服务器地址无效": "The TeamSpeak server address is invalid", "TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server", "服务器当前已满,请稍后重试": "The server is full. Try again shortly", - "WebSpeak 尚未完成首次配置": "WebSpeak setup has not been completed", + "WebSpeak 尚未配置 TeamSpeak 目标。": "The WebSpeak TeamSpeak target has not been configured", "此 TeamSpeak 服务器地址不允许连接": "This TeamSpeak server address is not allowed", "请输入有效的昵称": "Enter a valid nickname", };