fix(connection): improve synced password recovery

This commit is contained in:
大熊 authored and GitHub committed 2026-08-13 20:34:54 +08:00
1 parent de72675b67
commit d64908c596
14 files changed
+334 -39

No files matched your search

@@ -12,6 +12,16 @@ function installLocalStorage() {
});
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
function postgresConnection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
return {
id: "pg-1",
@@ -101,7 +111,7 @@ describe("connectionStore save_password opt-out", () => {
it("connect prompts for the password and uses it only for connectDb", async () => {
installApiMocks();
installPasswordPromptMock();
requestPassword.mockResolvedValue("typed-pw");
requestPassword.mockResolvedValue({ password: "typed-pw", rememberPassword: false });
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = postgresConnection({ id: "pg-1", save_password: false, password: "" });
@@ -145,4 +155,174 @@ describe("connectionStore save_password opt-out", () => {
expect(requestPassword).not.toHaveBeenCalled();
});
it("prompts and retries when MySQL rejects a synced connection that sent no password", async () => {
const connectDb = vi.fn().mockRejectedValueOnce(new Error("MySQL connection failed: Access denied for user 'root'@'192.168.100.133' (using password: NO)")).mockResolvedValueOnce("mysql-1");
installApiMocks({ connectDb });
installPasswordPromptMock();
requestPassword.mockResolvedValue({ password: "typed-pw", rememberPassword: true });
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = postgresConnection({
id: "mysql-1",
name: "Synced MySQL",
db_type: "mysql",
port: 3306,
username: "root",
save_password: true,
password: "",
});
store.connections = [connection];
await store.connect(connection);
expect(requestPassword).toHaveBeenCalledWith({ connectionId: "mysql-1", connectionName: "Synced MySQL" });
expect(connectDb).toHaveBeenCalledTimes(2);
expect(connectDb).toHaveBeenNthCalledWith(1, expect.objectContaining({ password: "" }), expect.any(Number));
expect(connectDb).toHaveBeenNthCalledWith(2, expect.objectContaining({ password: "typed-pw" }), expect.any(Number));
const { saveConnections } = await import("@/lib/backend/api");
expect(saveConnections).toHaveBeenLastCalledWith(expect.arrayContaining([expect.objectContaining({ id: "mysql-1", password: "typed-pw", save_password: true })]));
expect(store.getConfig("mysql-1")?.password).toBe("typed-pw");
});
it("does not persist a recovered password after the connection config changes", async () => {
const connected = deferred<string>();
const connectDb = vi
.fn()
.mockRejectedValueOnce(new Error("MySQL connection failed: Access denied for user 'root'@'192.168.100.133' (using password: NO)"))
.mockImplementationOnce(() => connected.promise);
const saveConnections = vi.fn().mockResolvedValue(undefined);
installApiMocks({ connectDb, saveConnections });
installPasswordPromptMock();
requestPassword.mockResolvedValue({ password: "old-endpoint-password", rememberPassword: true });
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = postgresConnection({
id: "mysql-1",
name: "Synced MySQL",
db_type: "mysql",
host: "old.example.com",
port: 3306,
username: "root",
save_password: true,
password: "",
});
store.connections = [connection];
const connecting = store.connect(connection);
await vi.waitFor(() => expect(connectDb).toHaveBeenCalledTimes(2));
await store.updateConnection({ ...connection, host: "new.example.com" });
connected.resolve("mysql-1");
await connecting;
expect(saveConnections).toHaveBeenCalledTimes(1);
expect(saveConnections).toHaveBeenLastCalledWith(
expect.arrayContaining([
expect.objectContaining({
id: "mysql-1",
host: "new.example.com",
password: "",
}),
]),
);
expect(store.getConfig("mysql-1")).toEqual(expect.objectContaining({ host: "new.example.com", password: "" }));
});
it("restores the latest config when it changes while a recovered password is being saved", async () => {
const passwordSave = deferred<void>();
const connectDb = vi.fn().mockRejectedValueOnce(new Error("MySQL connection failed: Access denied for user 'root'@'192.168.100.133' (using password: NO)")).mockResolvedValueOnce("mysql-1");
const saveConnections = vi
.fn()
.mockImplementationOnce(() => passwordSave.promise)
.mockResolvedValue(undefined);
installApiMocks({ connectDb, saveConnections });
installPasswordPromptMock();
requestPassword.mockResolvedValue({ password: "old-endpoint-password", rememberPassword: true });
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = postgresConnection({
id: "mysql-1",
name: "Synced MySQL",
db_type: "mysql",
host: "old.example.com",
port: 3306,
username: "root",
save_password: true,
password: "",
});
store.connections = [connection];
const connecting = store.connect(connection);
await vi.waitFor(() => expect(saveConnections).toHaveBeenCalledTimes(1));
await store.updateConnection({ ...connection, host: "new.example.com" });
passwordSave.resolve();
await connecting;
expect(saveConnections).toHaveBeenCalledTimes(3);
expect(saveConnections).toHaveBeenLastCalledWith(
expect.arrayContaining([
expect.objectContaining({
id: "mysql-1",
host: "new.example.com",
password: "",
}),
]),
);
expect(store.getConfig("mysql-1")).toEqual(expect.objectContaining({ host: "new.example.com", password: "" }));
});
it("keeps a successful connection when remembering the recovered password fails", async () => {
const connectDb = vi.fn().mockRejectedValueOnce(new Error("MySQL connection failed: Access denied for user 'root'@'192.168.100.133' (using password: NO)")).mockResolvedValueOnce("mysql-1");
const saveConnections = vi.fn().mockRejectedValue(new Error("disk full"));
installApiMocks({ connectDb, saveConnections });
installPasswordPromptMock();
requestPassword.mockResolvedValue({ password: "typed-pw", rememberPassword: true });
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = postgresConnection({
id: "mysql-1",
name: "Synced MySQL",
db_type: "mysql",
port: 3306,
username: "root",
save_password: true,
password: "",
});
store.connections = [connection];
await expect(store.connect(connection)).resolves.toBe("mysql-1");
expect(store.connectedIds.has("mysql-1")).toBe(true);
expect(store.activeConnectionId).toBe("mysql-1");
expect(store.getConfig("mysql-1")?.password).toBe("");
expect(store.connectionErrors["mysql-1"]).toContain("Connected, but DBX could not remember the password");
expect(store.connectionErrors["mysql-1"]).toContain("disk full");
});
it("keeps ensureConnected successful when remembering the recovered password fails", async () => {
const connectDb = vi.fn().mockRejectedValueOnce(new Error("MySQL connection failed: Access denied for user 'root'@'192.168.100.133' (using password: NO)")).mockResolvedValueOnce("mysql-1");
const saveConnections = vi.fn().mockRejectedValue(new Error("disk full"));
installApiMocks({ connectDb, saveConnections });
installPasswordPromptMock();
requestPassword.mockResolvedValue({ password: "typed-pw", rememberPassword: true });
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
const connection = postgresConnection({
id: "mysql-1",
name: "Synced MySQL",
db_type: "mysql",
port: 3306,
username: "root",
save_password: true,
password: "",
});
store.connections = [connection];
await expect(store.ensureConnected("mysql-1")).resolves.toBeUndefined();
expect(store.connectedIds.has("mysql-1")).toBe(true);
expect(store.getConfig("mysql-1")?.password).toBe("");
expect(store.connectionErrors["mysql-1"]).toContain("Connected, but DBX could not remember the password");
expect(store.connectionErrors["mysql-1"]).toContain("disk full");
});
});
@@ -6,25 +6,30 @@ export interface ConnectionPasswordPromptRequest {
connectionName: string;
}
export interface ConnectionPasswordPromptResult {
password: string;
rememberPassword: boolean;
}
interface QueuedPasswordPrompt {
request: ConnectionPasswordPromptRequest;
resolve: (password: string | null) => void;
resolve: (result: ConnectionPasswordPromptResult | null) => void;
}
/**
* Coordinates the single "enter password for a connection that is set to not
* save it locally" dialog shared by every connect surface. Mirrors the
* production-safety confirmation store: a request is transient, never
* persisted, and concurrent connects are queued so each prompt is shown and
* answered exactly once. A `null` resolution means the user cancelled.
* Coordinates the shared password dialog. The store only returns the password
* and the user's remember preference; the connection flow decides whether to
* persist it after authentication succeeds. Concurrent requests are queued so
* each prompt is shown and answered exactly once. A `null` result means the
* user cancelled.
*/
export const useConnectionPasswordPromptStore = defineStore("connectionPasswordPrompt", () => {
const pending = ref<ConnectionPasswordPromptRequest>();
const queue: QueuedPasswordPrompt[] = [];
let resolvePending: ((password: string | null) => void) | undefined;
let resolvePending: ((result: ConnectionPasswordPromptResult | null) => void) | undefined;
function requestPassword(request: ConnectionPasswordPromptRequest): Promise<string | null> {
return new Promise<string | null>((resolve) => {
function requestPassword(request: ConnectionPasswordPromptRequest): Promise<ConnectionPasswordPromptResult | null> {
return new Promise<ConnectionPasswordPromptResult | null>((resolve) => {
if (pending.value) {
queue.push({ request, resolve });
return;
@@ -33,23 +38,23 @@ export const useConnectionPasswordPromptStore = defineStore("connectionPasswordP
});
}
function beginRequest(request: ConnectionPasswordPromptRequest, resolve: (password: string | null) => void) {
function beginRequest(request: ConnectionPasswordPromptRequest, resolve: (result: ConnectionPasswordPromptResult | null) => void) {
pending.value = request;
resolvePending = resolve;
}
function settle(password: string | null) {
function settle(result: ConnectionPasswordPromptResult | null) {
const resolve = resolvePending;
resolvePending = undefined;
pending.value = undefined;
resolve?.(password);
resolve?.(result);
const next = queue.shift();
if (next) beginRequest(next.request, next.resolve);
}
function submit(password: string) {
settle(password);
function submit(password: string, rememberPassword: boolean) {
settle({ password, rememberPassword });
}
function cancel() {
+68 -15
View File
@@ -114,7 +114,7 @@ import { kvRootNodeLabel } from "@/lib/kv/kvRootPresentation";
import { REDIS_SCAN_PAGE_SIZE_DEFAULT } from "@/lib/redis/redisKeyPattern";
import { normalizeRedisDatabaseAliases, redisDatabaseAlias, redisDatabaseLabel } from "@/lib/redis/redisDatabaseAlias";
import { appendAgentDriverUpdateHint, hasAgentDriverUpdate, hasInstalledAgentVersion, type AgentDriverInstallState } from "@/lib/connection/agentDriverInstallHint";
import { appendConnectionErrorHints } from "@/lib/connection/connectionErrorHints";
import { appendConnectionErrorHints, isMysqlMissingPasswordFailure } from "@/lib/connection/connectionErrorHints";
import { appendVisibleDatabaseSelection } from "@/lib/connection/connectionVisibleDatabases";
import { buildXuguTypeMemberNodes, isXuguTypeMemberContainer } from "@/lib/sidebar/xuguTypeMembers";
import { isXuguPublicSynonymScope, xuguSchemaDisplayName, XUGU_PUBLIC_SYNONYM_SCOPE } from "@/lib/sidebar/xuguPublicSynonyms";
@@ -2878,37 +2878,73 @@ export const useConnectionStore = defineStore("connection", () => {
}
/**
* For a connection configured with `save_password === false` (password not
* persisted), prompt the user for the password and return a copy of the
* config carrying the typed value. The returned config is used only for the
* immediate `connectDb` call — it is never written back to the store, so the
* typed password is not persisted and the next connect prompts again.
* Prompt for a transient password when saving is disabled, or when a server
* confirms that a metadata-only synced connection sent no password. The
* password is used for the immediate `connectDb` call and is persisted only
* after a successful connection when the user selects "remember password".
*/
async function ensureConnectionPassword(config: ConnectionConfig): Promise<ConnectionConfig> {
if (config.save_password !== false || config.password) return config;
async function ensureConnectionPassword(config: ConnectionConfig, force = false): Promise<{ config: ConnectionConfig; rememberPassword: boolean }> {
if (!force && (config.save_password !== false || config.password)) return { config, rememberPassword: false };
const { useConnectionPasswordPromptStore } = await import("@/stores/connectionPasswordPromptStore");
const password = await useConnectionPasswordPromptStore().requestPassword({
const result = await useConnectionPasswordPromptStore().requestPassword({
connectionId: config.id,
connectionName: config.name,
});
if (!password) throw new Error(CONNECTION_PASSWORD_REQUIRED_MESSAGE);
return { ...config, password };
if (!result?.password) throw new Error(CONNECTION_PASSWORD_REQUIRED_MESSAGE);
return { config: { ...config, password: result.password }, rememberPassword: result.rememberPassword };
}
async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string): Promise<void> {
if (!rememberPassword || !config.password) return;
const index = connections.value.findIndex((connection) => connection.id === config.id);
if (index < 0) return;
if (connectionConfigFingerprint(connections.value[index]) !== expectedConfigFingerprint) return;
const nextConnections = [...connections.value];
nextConnections[index] = { ...nextConnections[index], password: config.password, save_password: true };
await persistConnections(nextConnections);
if (connectionConfigFingerprint(connections.value[index]) !== expectedConfigFingerprint) {
await persistConnections();
return;
}
connections.value = nextConnections;
rebuildTreeNodes();
}
async function connectDbWithMissingPasswordRetry(config: ConnectionConfig, localAttempt: number): Promise<{ config: ConnectionConfig; id: string; rememberPassword: boolean }> {
try {
const id = await withConnectionAttemptTimeout(api.connectDb(config, localAttempt), config);
return { config, id, rememberPassword: false };
} catch (error) {
if (!isMysqlMissingPasswordFailure(config, connectionErrorMessage(error))) throw error;
const prompted = await ensureConnectionPassword(config, true);
config = prompted.config;
ensureLocalConnectionAttemptActive(config.id, localAttempt);
const id = await withConnectionAttemptTimeout(api.connectDb(config, localAttempt), config);
return { config, id, rememberPassword: prompted.rememberPassword };
}
}
async function connect(config: ConnectionConfig) {
config = normalizeConnection(config);
const expectedConfigFingerprint = connectionConfigFingerprint(getConfig(config.id) ?? config);
if (getBlockingDisconnectInFlight(config.id)) await waitForBlockingDisconnectInFlight(config.id);
const localAttempt = beginLocalConnectionAttempt(config.id);
try {
let rememberPassword = false;
if (config.save_password === false && !config.password) {
config = await ensureConnectionPassword(config);
const prompted = await ensureConnectionPassword(config);
config = prompted.config;
rememberPassword = prompted.rememberPassword;
}
await beforeConnectHandler?.(config);
if (config.db_type === "sqlserver") {
await ensureSqlServerLegacyCompatibilityComponentInstalled(config);
}
ensureLocalConnectionAttemptActive(config.id, localAttempt);
const id = await withConnectionAttemptTimeout(api.connectDb(config, localAttempt), config);
const connection = await connectDbWithMissingPasswordRetry(config, localAttempt);
config = connection.config;
rememberPassword ||= connection.rememberPassword;
const id = connection.id;
await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
await syncMongoLegacyDriverFallback(id, config);
await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
@@ -2942,6 +2978,11 @@ export const useConnectionStore = defineStore("connection", () => {
comment: config.note || null,
});
}
try {
await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint);
} catch (error) {
setConnectionError(id, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) }));
}
return id;
} catch (e) {
if (isCancelledLocalConnectionAttempt(config.id, localAttempt)) {
@@ -3077,6 +3118,7 @@ export const useConnectionStore = defineStore("connection", () => {
recordConnectionError(connectionId, error);
throw error;
}
const expectedConfigFingerprint = connectionConfigFingerprint(config);
if (getBlockingDisconnectInFlight(connectionId)) await waitForBlockingDisconnectInFlight(connectionId);
const existingConnect = connectInFlight.get(connectionId);
if (existingConnect) {
@@ -3086,18 +3128,24 @@ export const useConnectionStore = defineStore("connection", () => {
}
const localAttempt = beginLocalConnectionAttempt(connectionId);
const connectPromise = (async () => {
let rememberPassword = false;
// Fast-path the common case (password saved or no password needed) so the
// in-flight dedup above keeps its exact microtask cadence; only await the
// interactive prompt when the connection actually needs a typed password.
if (config.save_password === false && !config.password) {
config = await ensureConnectionPassword(config);
const prompted = await ensureConnectionPassword(config);
config = prompted.config;
rememberPassword = prompted.rememberPassword;
}
await beforeConnectHandler?.(config);
if (config.db_type === "sqlserver") {
await ensureSqlServerLegacyCompatibilityComponentInstalled(config);
}
ensureLocalConnectionAttemptActive(connectionId, localAttempt);
const id = await withConnectionAttemptTimeout(api.connectDb(config, localAttempt), config);
const connection = await connectDbWithMissingPasswordRetry(config, localAttempt);
config = connection.config;
rememberPassword ||= connection.rememberPassword;
const id = connection.id;
await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
await syncMongoLegacyDriverFallback(connectionId, config);
await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
@@ -3107,6 +3155,11 @@ export const useConnectionStore = defineStore("connection", () => {
markSuccessfulLocalConnectionAttempt(connectionId, localAttempt);
markConnectionHealthChecked(connectionId);
clearConnectionError(connectionId);
try {
await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint);
} catch (error) {
setConnectionError(connectionId, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) }));
}
})();
connectInFlight.set(connectionId, connectPromise);
try {