feat: remember server and channel passwords locally

This commit is contained in:
illusia committed 2026-10-12 11:08:35 +08:00
1 parent 9c8647df50
commit 2f5cdcba90
6 files changed
+289 -43

No files matched your search

+8
View File
@@ -614,3 +614,11 @@
- 根因:服务器在订阅目录时已发送 `channel_flag_password=1`,但 SDK 的 `ChannelInfo` 解析器没有把这个公开标志放进目录快照;普通客户端随后执行独立 `channellist` 查询会收到权限错误,所以 WebSpeak 没有第二条数据来源。
- 修复:SDK 新增可选的 `ChannelInfo.passwordProtected`,从频道列表和频道编辑通知解析 `channel_flag_password`;WebSpeak 锁定新版 SDK。频道密码本身不会读取或传输。
- 验证:真实上海测试连接的 WebSpeak `TSClient` 收到 `msicbot passwordProtected=true`;SDK 全量测试 72 通过、类型检查、lint 和构建通过,改动文件格式检查通过。WebSpeak `npm run verify` 通过(693/693);3040 已重启,健康接口、首页和生产 JS 均返回 HTTP 200。全仓格式检查仍报 53 个未格式化文件。
## 本轮浏览器凭据记忆(2026-10-12)
- 用户要求浏览器记住 TeamSpeak 服务器密码和曾成功进入的加密频道密码,减少重复输入。
- IndexedDB 升至版本 4,新增独立 `credentials` 仓库;记录按规范化服务器目标隔离,频道凭据再按频道 ID 区分。凭据仅保存在当前浏览器,不写入 WebSpeak 服务端;“清除本地数据”会一并删除凭据。
- 连接和频道切换先尝试本地凭据,只有成功连接或成功切入频道后才保存。服务器或频道拒绝旧密码时删除对应记录并显示原密码输入框。切换服务器会清除当前内存密码,避免误带到另一个目标。
- 验证:`npm run verify` 通过(696/696 测试、服务端构建、前端类型检查和 Vite 生产构建);新增浏览器凭据隔离及连接对话框回归测试。3040 健康接口返回 200,线上静态入口引用的 WebClient 生产包返回 200,包内容含服务器与频道凭据实现。
- 安全边界:凭据存于浏览器本地 IndexedDB,未加密;同源脚本可访问它们。
+115 -31
View File
@@ -2,6 +2,14 @@ import { computed, nextTick, watch, type Ref } from "vue";
import type { WebClientChatTab } from "./useWebClientChat.js";
import type { TreeChannel } from "./useWebClientChannels.js";
import { combineTeamSpeakTarget, isValidTeamSpeakPort, suggestedTeamSpeakPort } from "../services/teamspeak-target.js";
import {
loadStoredChannelPassword,
loadStoredServerPassword,
removeStoredChannelPassword,
removeStoredServerPassword,
saveStoredChannelPassword,
saveStoredServerPassword,
} from "../services/local-persistence.js";
interface ChannelPasswordDialogState {
open: boolean;
@@ -21,6 +29,7 @@ interface UseWebClientConnectionOptions {
initialized: Readonly<Ref<boolean>>;
accessMode: Readonly<Ref<string>>;
isConnecting: Readonly<Ref<boolean>>;
isConnected: Readonly<Ref<boolean>>;
errorCode: Readonly<Ref<string>>;
errorMessage: Readonly<Ref<string>>;
channelSwitchedChannelId: Readonly<Ref<string>>;
@@ -53,6 +62,7 @@ export function useWebClientConnection({
initialized,
accessMode,
isConnecting,
isConnected,
errorCode,
errorMessage,
channelSwitchedChannelId,
@@ -90,12 +100,28 @@ export function useWebClientConnection({
serverPort.value = suggestedTeamSpeakPort(previousAddress, address, serverPort.value);
}, { flush: "sync" });
let serverPasswordLookupAttempt = 0;
let resolvingServerPassword = false;
let attemptedServerCredential: { target: string; password: string } | null = null;
let channelSelectionAttempt = 0;
let attemptedChannelCredential: { target: string; channelId: string; password: string } | null = null;
function currentServerTarget(): string {
return combineTeamSpeakTarget(serverHost.value, serverPort.value);
}
watch(() => currentServerTarget(), (target, previousTarget) => {
if (!previousTarget || target === previousTarget) return;
serverPassword.value = "";
resolvingServerPassword = false;
serverPasswordLookupAttempt += 1;
attemptedServerCredential = null;
attemptedChannelCredential = null;
channelSelectionAttempt += 1;
}, { flush: "sync" });
function doConnect(): void {
if (!canJoin.value || isConnecting.value) return;
if (!canJoin.value || isConnecting.value || resolvingServerPassword) return;
beforeConnect?.();
clearError();
nickname.value = nickname.value.trim();
@@ -105,21 +131,41 @@ export function useWebClientConnection({
serverPort.value = serverPort.value.trim();
}
selectedChannelId.value = "";
// Keep the password available for retry even if the target is administrator-managed.
connect(
currentServerTarget(),
channelName.value.trim(),
nickname.value,
serverPassword.value,
rememberIdentity.value ? identityMaterial.value : "",
rememberIdentity.value,
inviteToken.value,
Boolean(accelerationRelayId.value),
accelerationRelayId.value,
);
const target = currentServerTarget();
const attempt = ++serverPasswordLookupAttempt;
resolvingServerPassword = true;
void (async () => {
try {
const savedPassword = serverPassword.value ? "" : await loadStoredServerPassword(target);
if (attempt !== serverPasswordLookupAttempt || target !== currentServerTarget()) return;
// A password entered while IndexedDB was being read takes precedence.
const password = serverPassword.value || savedPassword;
attemptedServerCredential = { target, password };
// Keep the in-memory value available for the existing reconnect flow.
serverPassword.value = password;
connect(
target,
channelName.value.trim(),
nickname.value,
password,
rememberIdentity.value ? identityMaterial.value : "",
rememberIdentity.value,
inviteToken.value,
Boolean(accelerationRelayId.value),
accelerationRelayId.value,
);
} finally {
if (attempt === serverPasswordLookupAttempt) resolvingServerPassword = false;
}
})();
}
function doDisconnect(): void {
serverPasswordLookupAttempt += 1;
resolvingServerPassword = false;
attemptedServerCredential = null;
channelSelectionAttempt += 1;
attemptedChannelCredential = null;
disconnect();
selectedChannelId.value = "";
showToast(t("leftToast"));
@@ -145,17 +191,30 @@ export function useWebClientConnection({
selectedChannelId.value = channel.id;
channelName.value = channel.name;
chatTab.value = "channel";
switchChannel(channel.id);
const target = currentServerTarget();
const attempt = ++channelSelectionAttempt;
attemptedChannelCredential = null;
void loadStoredChannelPassword(target, channel.id).then((password) => {
if (attempt !== channelSelectionAttempt || selectedChannelId.value !== channel.id || target !== currentServerTarget()) return;
attemptedChannelCredential = password ? { target, channelId: channel.id, password } : null;
switchChannel(channel.id, password);
});
}
function submitChannelPassword(): void {
if (!channelPasswordDialog.open || channelPasswordDialog.submitting || !channelPasswordDialog.channelId || !channelPasswordDialog.password) return;
channelPasswordDialog.error = "";
channelPasswordDialog.submitting = true;
switchChannel(channelPasswordDialog.channelId, channelPasswordDialog.password);
const target = currentServerTarget();
const channelId = channelPasswordDialog.channelId;
attemptedChannelCredential = { target, channelId, password: channelPasswordDialog.password };
channelSelectionAttempt += 1;
switchChannel(channelId, channelPasswordDialog.password);
}
function cancelChannelPassword(): void {
channelSelectionAttempt += 1;
attemptedChannelCredential = null;
const ownChannel = channels.value.find((item) => item.members.some((member) => member.id === clientId.value));
if (ownChannel) selectedChannelId.value = ownChannel.id;
channelPasswordDialog.open = false;
@@ -172,36 +231,61 @@ export function useWebClientConnection({
}
watch(errorCode, (code) => {
if (code && code !== "CHANNEL_PASSWORD_REQUIRED" && channelPasswordDialog.open && channelPasswordDialog.submitting) {
channelPasswordDialog.error = errorMessage.value;
if (code === "CHANNEL_PASSWORD_REQUIRED" || code === "INVALID_CHANNEL_PASSWORD") {
const channelId = selectedChannelId.value;
if (!channelId) return;
const target = currentServerTarget();
if (attemptedChannelCredential?.channelId === channelId && attemptedChannelCredential.target === target) {
void removeStoredChannelPassword(target, channelId);
attemptedChannelCredential = null;
}
channelPasswordDialog.open = true;
channelPasswordDialog.channelId = channelId;
channelPasswordDialog.password = "";
channelPasswordDialog.error = t("channelPasswordRetry");
channelPasswordDialog.submitting = false;
clearError();
void nextTick(() => document.getElementById("channel-password-input")?.focus());
return;
}
if (code !== "CHANNEL_PASSWORD_REQUIRED" || !selectedChannelId.value) return;
channelPasswordDialog.open = true;
channelPasswordDialog.channelId = selectedChannelId.value;
channelPasswordDialog.password = "";
channelPasswordDialog.error = t("channelPasswordRetry");
channelPasswordDialog.submitting = false;
clearError();
void nextTick(() => document.getElementById("channel-password-input")?.focus());
if (code && channelPasswordDialog.open && channelPasswordDialog.submitting) {
channelPasswordDialog.error = errorMessage.value;
channelPasswordDialog.submitting = false;
attemptedChannelCredential = null;
clearError();
}
});
watch(errorCode, (code) => {
if (code !== "SERVER_PASSWORD_REQUIRED" && code !== "INVALID_SERVER_PASSWORD") return;
if (attemptedServerCredential) void removeStoredServerPassword(attemptedServerCredential.target);
attemptedServerCredential = null;
serverPassword.value = "";
serverPasswordDialog.open = true;
serverPasswordDialog.password = "";
serverPasswordDialog.errorCode = code;
clearError();
void nextTick(() => document.getElementById("retry-server-password-input")?.focus());
});
watch(isConnected, (connected) => {
if (!connected || !attemptedServerCredential) return;
const credential = attemptedServerCredential;
attemptedServerCredential = null;
if (credential.password) void saveStoredServerPassword(credential.target, credential.password);
});
watch(channelSwitchedChannelId, (channelId) => {
if (!channelPasswordDialog.open || !channelId || channelId !== channelPasswordDialog.channelId) return;
channelPasswordDialog.open = false;
channelPasswordDialog.channelId = "";
channelPasswordDialog.password = "";
channelPasswordDialog.error = "";
channelPasswordDialog.submitting = false;
if (!channelId) return;
const credential = attemptedChannelCredential;
if (credential?.channelId === channelId && credential.target === currentServerTarget()) {
attemptedChannelCredential = null;
void saveStoredChannelPassword(credential.target, channelId, credential.password);
}
if (channelPasswordDialog.open && channelId === channelPasswordDialog.channelId) {
channelPasswordDialog.open = false;
channelPasswordDialog.channelId = "";
channelPasswordDialog.password = "";
channelPasswordDialog.error = "";
channelPasswordDialog.submitting = false;
}
});
return {
+36 -3
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { before, after, beforeEach, test } from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import { getChatHistoryConversationKey, loadLocalPreferences, normalizeChatHistoryServerKey, saveInstalledSkin, saveLocalPreferences } from "./local-persistence.js";
import { getChatHistoryConversationKey, loadLocalPreferences, loadStoredChannelPassword, normalizeBrowserCredentialServerKey, normalizeChatHistoryServerKey, saveInstalledSkin, saveLocalPreferences, saveStoredChannelPassword, saveStoredServerPassword } from "./local-persistence.js";
import type { InstalledSkin } from "./skin-pack.js";
// Control IndexedDB's request and transaction completion separately. These tests
@@ -11,9 +11,9 @@ let opening: any;
let transactions: Transaction[] = [];
class Transaction {
oncomplete?: () => void; onerror?: () => void; onabort?: () => void;
getRequest: any; putRequest: any; written: unknown; aborted = false;
getRequest: any; getKey: unknown; putRequest: any; written: unknown; aborted = false;
objectStore() { return {
get: () => this.getRequest = {},
get: (key: unknown) => { this.getKey = key; return this.getRequest = {}; },
put: (value: unknown) => { this.written = value; return this.putRequest = {}; },
}; }
abort() { this.aborted = true; this.onabort?.(); }
@@ -48,6 +48,39 @@ test("cancelling a skin while IndexedDB opens prevents the delayed write", async
await rejected;
assert.equal(transactions.length, 0);
});
test("browser credentials are normalized and scoped by server plus channel", async () => {
assert.equal(normalizeBrowserCredentialServerKey(" Example.COM:9987 "), "example.com:9987");
const serverWrite = saveStoredServerPassword("Example.COM:9987", "server-secret");
await nextTurn();
const serverTx = transactions[0]!;
const serverRecord = serverTx.written as { id: string; serverKey: string; kind: string; password: string; updatedAt: number };
assert.equal(serverRecord.id, "server:example.com:9987");
assert.equal(serverRecord.serverKey, "example.com:9987");
assert.equal(serverRecord.kind, "server-password");
assert.equal(serverRecord.password, "server-secret");
assert.equal(typeof serverRecord.updatedAt, "number");
serverTx.writtenSuccessfully(); serverTx.commit(); await serverWrite;
const channelWrite = saveStoredChannelPassword("example.com:9987", "42", "channel-secret");
await nextTurn();
const channelTx = transactions[1]!;
const channelRecord = channelTx.written as { id: string; serverKey: string; kind: string; channelId: string; password: string; updatedAt: number };
assert.equal(channelRecord.id, 'channel:["example.com:9987","42"]');
assert.equal(channelRecord.serverKey, "example.com:9987");
assert.equal(channelRecord.kind, "channel-password");
assert.equal(channelRecord.channelId, "42");
assert.equal(channelRecord.password, "channel-secret");
assert.equal(typeof channelRecord.updatedAt, "number");
channelTx.writtenSuccessfully(); channelTx.commit(); await channelWrite;
const channelRead = loadStoredChannelPassword("other.example:9987", "42");
await nextTurn();
const readTx = transactions[2]!;
assert.equal(readTx.getKey, 'channel:["other.example:9987","42"]');
readTx.read({ id: 'channel:["other.example:9987","42"]', serverKey: "other.example:9987", kind: "channel-password", channelId: "42", password: "other-secret" });
readTx.commit();
assert.equal(await channelRead, "other-secret");
});
test("a successful request is not reported as durable until its transaction commits", async () => {
let settled = false;
const pending = saveInstalledSkin(sample).then(() => { settled = true; });
+96 -2
View File
@@ -1,5 +1,5 @@
const DB_NAME = "webspeak-local";
const DB_VERSION = 3;
const DB_VERSION = 4;
const CURRENT_IDENTITY_KEY = "current";
const PREFERENCES_KEY = "singleton";
@@ -46,6 +46,99 @@ export interface RecentServer {
serverIcon?: string;
}
interface BrowserCredentialRecord {
id: string;
serverKey: string;
kind: "server-password" | "channel-password";
channelId?: string;
password: string;
updatedAt: number;
}
export function normalizeBrowserCredentialServerKey(target: string): string {
return target.trim().toLowerCase();
}
function serverCredentialId(serverKey: string): string {
return `server:${serverKey}`;
}
function channelCredentialId(serverKey: string, channelId: string): string {
return `channel:${JSON.stringify([serverKey, channelId])}`;
}
async function loadBrowserCredential(id: string, serverKey: string, kind: BrowserCredentialRecord["kind"], channelId?: string): Promise<string> {
if (!serverKey || (kind === "channel-password" && !channelId)) return "";
try {
const record = await request<BrowserCredentialRecord | null>("credentials", "readonly", (store, resolve, reject) => {
const get = store.get(id);
get.onsuccess = () => resolve((get.result as BrowserCredentialRecord | undefined) ?? null);
get.onerror = () => reject(get.error);
});
if (record?.serverKey !== serverKey || record.kind !== kind || record.channelId !== channelId) return "";
return typeof record.password === "string" ? record.password : "";
} catch {
return "";
}
}
async function saveBrowserCredential(record: BrowserCredentialRecord): Promise<void> {
if (!record.serverKey || !record.password || record.password.length > 512) return;
try {
await request("credentials", "readwrite", (store, resolve, reject) => {
const put = store.put(record);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
} catch {
// Credential persistence is best effort and must never block a connection.
}
}
async function removeBrowserCredential(id: string): Promise<void> {
try {
await request("credentials", "readwrite", (store, resolve, reject) => {
const remove = store.delete(id);
remove.onsuccess = () => resolve(undefined);
remove.onerror = () => reject(remove.error);
});
} catch {
// Credential removal is best effort when browser storage is unavailable.
}
}
export function loadStoredServerPassword(target: string): Promise<string> {
const serverKey = normalizeBrowserCredentialServerKey(target);
return loadBrowserCredential(serverCredentialId(serverKey), serverKey, "server-password");
}
export function saveStoredServerPassword(target: string, password: string): Promise<void> {
const serverKey = normalizeBrowserCredentialServerKey(target);
return saveBrowserCredential({ id: serverCredentialId(serverKey), serverKey, kind: "server-password", password, updatedAt: Date.now() });
}
export function removeStoredServerPassword(target: string): Promise<void> {
const serverKey = normalizeBrowserCredentialServerKey(target);
return removeBrowserCredential(serverCredentialId(serverKey));
}
export function loadStoredChannelPassword(target: string, channelId: string): Promise<string> {
const serverKey = normalizeBrowserCredentialServerKey(target);
return loadBrowserCredential(channelCredentialId(serverKey, channelId), serverKey, "channel-password", channelId);
}
export function saveStoredChannelPassword(target: string, channelId: string, password: string): Promise<void> {
const serverKey = normalizeBrowserCredentialServerKey(target);
if (!channelId) return Promise.resolve();
return saveBrowserCredential({ id: channelCredentialId(serverKey, channelId), serverKey, kind: "channel-password", channelId, password, updatedAt: Date.now() });
}
export function removeStoredChannelPassword(target: string, channelId: string): Promise<void> {
const serverKey = normalizeBrowserCredentialServerKey(target);
if (!channelId) return Promise.resolve();
return removeBrowserCredential(channelCredentialId(serverKey, channelId));
}
export interface LocalPreferences {
schemaVersion: 1;
locale?: "auto" | "zh-CN" | "en";
@@ -84,6 +177,7 @@ function openDatabase(): Promise<IDBDatabase> {
if (!database.objectStoreNames.contains("favorites")) database.createObjectStore("favorites", { keyPath: "id" });
if (!database.objectStoreNames.contains("recent")) database.createObjectStore("recent", { keyPath: "id" });
if (!database.objectStoreNames.contains("skins")) database.createObjectStore("skins", { keyPath: "id" });
if (!database.objectStoreNames.contains("credentials")) database.createObjectStore("credentials", { keyPath: "id" });
if (!database.objectStoreNames.contains("chatHistory")) {
const store = database.createObjectStore("chatHistory", { keyPath: "id" });
store.createIndex("serverKey", "serverKey", { unique: false });
@@ -378,7 +472,7 @@ async function removeRecentServer(id: string): Promise<void> {
export async function clearLocalData(): Promise<void> {
try {
const database = await openDatabase();
await Promise.all(["identities", "preferences", "favorites", "recent", "skins", "chatHistory"].map((storeName) => new Promise<void>((resolve, reject) => {
await Promise.all(["identities", "preferences", "favorites", "recent", "skins", "chatHistory", "credentials"].map((storeName) => new Promise<void>((resolve, reject) => {
const transaction = database.transaction(storeName, "readwrite");
transaction.objectStore(storeName).clear();
transaction.oncomplete = () => resolve();
+4 -3
View File
@@ -1406,9 +1406,10 @@ const {
cancelChannelPassword,
selectChannelById,
} = useWebClientConnection({
initialized,
accessMode,
isConnecting: computed(() => voiceState.connecting),
initialized,
accessMode,
isConnecting: computed(() => voiceState.connecting),
isConnected: computed(() => voiceState.connected),
errorCode: computed(() => voiceState.errorCode),
errorMessage: computed(() => localizedMessage(voiceState.error)),
channelSwitchedChannelId: computed(() => voiceState.channelSwitchedChannelId),
+30 -4
View File
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import { after, before, test } from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { createServer } from "vite";
import { effectScope, nextTick, reactive, ref } from "vue";
@@ -13,21 +14,23 @@ before(async () => {
});
after(async () => { await vite?.close(); });
function mount(t) {
const scope = effectScope(), errors = ref(""), message = ref(""), switched = ref(""), calls = [];
const scope = effectScope(), errors = ref(""), message = ref(""), switched = ref(""), connected = ref(false), calls = [], connectCalls = [];
const dialog = reactive({ open: true, channelId: "2", password: "draft", error: "", submitting: false });
const serverPasswordDialog = reactive({ open: false, password: "", errorCode: "" });
const serverHost = ref("fixture.invalid"), serverPort = ref("9987");
const connection = scope.run(() => useWebClientConnection({
initialized: ref(true), accessMode: ref("fixed"), isConnecting: ref(false), errorCode: errors,
initialized: ref(true), accessMode: ref("fixed"), isConnecting: ref(false), isConnected: connected, errorCode: errors,
errorMessage: message, channelSwitchedChannelId: switched,
nickname: ref("Preview"), channelName: ref("Room"), serverHost, serverPort,
serverPassword: ref(""), rememberIdentity: ref(false), identityMaterial: ref(""), accelerationRelayId: ref(""),
inviteToken: "", selectedChannelId: ref("2"), channels: ref([]), clientId: ref(1),
channelPasswordDialog: dialog, serverPasswordDialog: reactive({ open: false, password: "", errorCode: "" }),
channelPasswordDialog: dialog, serverPasswordDialog,
chatTab: ref("channel"), switchChannel: (...args) => calls.push(args),
connect: (...args) => connectCalls.push(args), disconnect() {}, saveNickname() {}, showToast() {},
clearError: () => { errors.value = ""; message.value = ""; }, t: key => key,
}));
t.after(() => scope.stop());
return { dialog, connection, errors, message, switched, calls, serverHost, serverPort };
return { dialog, serverPasswordDialog, connection, errors, message, switched, calls, connectCalls, connected, serverHost, serverPort };
}
test("pasting a nickname clears the prefilled port and preserves a custom override", t => {
@@ -68,3 +71,26 @@ test("a successful channel switch closes and clears the password dialog", async
await nextTick();
assert.deepEqual({ ...dialog }, { open: false, channelId: "", password: "", error: "", submitting: false });
});
test("a server-password retry proceeds when browser storage is unavailable", async t => {
const { connection, connectCalls, connected, serverPasswordDialog } = mount(t);
serverPasswordDialog.open = true;
serverPasswordDialog.password = "server-secret";
connection.submitServerPassword();
await Promise.resolve();
assert.equal(connectCalls.length, 1);
assert.equal(connectCalls[0][0], "fixture.invalid:9987");
assert.equal(connectCalls[0][3], "server-secret");
connected.value = true;
await nextTick();
// IndexedDB is unavailable in this test runtime, so persistence is a no-op.
});
test("channel selection falls back to the normal switch when no local password exists", async t => {
const { connection, calls } = mount(t);
connection.selectChannel({ id: "42", name: "Locked room", members: [] });
await nextTurn();
assert.equal(calls.length, 1);
assert.equal(calls[0][0], "42");
assert.equal(calls[0][1], "");
});