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

+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),