feat(security): encrypt local credentials and guide data migration

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-23 11:02:52 +08:00
1 parent 19f36557b9
commit 250e0c0a10
58 files changed
+8831 -435

No files matched your search

+21 -38
View File
@@ -56,7 +56,6 @@ import {
expandGroups as expandGroupsOp,
collapseAllGroups as collapseAllGroupsOp,
moveConnectionToGroup as moveConnectionToGroupOp,
remapSidebarLayoutConnectionIds,
mergeSidebarLayout,
reorderEntry as reorderEntryOp,
reorderEntries as reorderEntriesOp,
@@ -94,11 +93,11 @@ import {
} from "@/lib/table/tableVGroup";
import {
buildConnectionConfigBundle,
filterSidebarLayoutByConnectionIds,
filterTunnelProfilesByIds,
parseConnectionConfigObject,
referencedTunnelProfileIds,
prepareConnectionConfigImport,
selectConnectionConfigBundle,
scrubConnectionForPlaintextExport,
scrubTunnelProfileForPlaintextExport,
snapshotConnectionsForExport,
type ConnectionConfigBundle,
type ConnectionExportProtection,
@@ -9305,7 +9304,12 @@ export const useConnectionStore = defineStore("connection", () => {
const payload = await encryptConfig(json, protection.passphrase);
content = JSON.stringify(payload, null, 2);
} else {
content = JSON.stringify(exportData, null, 2);
const scrubbedData = {
...exportData,
connections: exportData.connections.map(scrubConnectionForPlaintextExport),
tunnelProfiles: exportData.tunnelProfiles?.map(scrubTunnelProfileForPlaintextExport),
};
content = JSON.stringify(scrubbedData, null, 2);
}
if (isTauriRuntime()) {
@@ -9545,40 +9549,19 @@ export const useConnectionStore = defineStore("connection", () => {
async function applyConnectionsImport(preview: ConnectionConfigBundle, selectedConnectionIds?: Iterable<string>): Promise<{ count: number; layout?: SidebarLayout }> {
const selected = selectConnectionConfigBundle(preview, selectedConnectionIds);
const imported = selected.connections.map((connection) => ({ ...connection }));
let importedLayout = selected.layout;
const importedConnections: ConnectionConfig[] = [];
const importedConnectionIdMap = new Map<string, string>();
for (const config of imported) {
const duplicate = [...connections.value, ...importedConnections].find((connection) => connection.name === config.name && connection.host === config.host && connection.port === config.port);
if (duplicate) {
if (typeof config.id === "string") importedConnectionIdMap.set(config.id, duplicate.id);
continue;
}
const importedId = config.id;
config.id = uuid();
if (typeof importedId === "string") importedConnectionIdMap.set(importedId, config.id);
importedConnections.push(normalizeConnection(config));
const importedTunnelProfileStore = useTunnelProfileStore();
await importedTunnelProfileStore.init();
const imported = prepareConnectionConfigImport(
selected,
connections.value,
importedTunnelProfileStore.profiles.map((profile) => profile.id),
uuid,
);
if (imported.tunnelProfiles?.length) {
await importedTunnelProfileStore.saveProfiles([...importedTunnelProfileStore.profiles, ...imported.tunnelProfiles]);
}
const importedTunnelProfileIds = referencedTunnelProfileIds(importedConnections);
const importedTunnelProfiles = filterTunnelProfilesByIds(selected.tunnelProfiles ?? [], importedTunnelProfileIds);
if (importedTunnelProfiles.length) {
const importedTunnelProfileStore = useTunnelProfileStore();
await importedTunnelProfileStore.init();
const merged = [...importedTunnelProfileStore.profiles];
for (const profile of importedTunnelProfiles) {
if (!profile || typeof profile.id !== "string" || !profile.id) continue;
const index = merged.findIndex((existing) => existing.id === profile.id);
if (index >= 0) merged[index] = profile;
else merged.push(profile);
}
await importedTunnelProfileStore.saveProfiles(merged);
}
for (const connection of importedConnections) await addConnection(connection);
if (importedLayout) {
importedLayout = filterSidebarLayoutByConnectionIds(remapSidebarLayoutConnectionIds(importedLayout, importedConnectionIdMap), importedConnectionIdMap.values());
}
return { count: importedConnections.length, layout: importedLayout };
for (const connection of imported.connections) await addConnection(normalizeConnection(connection));
return { count: imported.connections.length, layout: imported.layout };
}
async function importConnectionsFromFile(content: string, passphrase: string | null, selectedConnectionIds?: Iterable<string>): Promise<{ count: number; layout?: SidebarLayout }> {
+161
View File
@@ -0,0 +1,161 @@
import { describe, expect, it, vi } from "vitest";
import { useMigrationStore } from "./migrationStore";
import type { MigrationPreflight, MigrationReport } from "@/lib/backend/migration";
const pending = (): MigrationPreflight => ({
migrationId: "secret-store-v1",
state: "pending",
needsMigration: true,
keyProviderAvailable: true,
keyCreationAllowed: false,
databasePlaintextCount: 2,
connectionCount: 1,
pluginSecretCount: 0,
aiSecretCount: 0,
tunnelSecretCount: 0,
syncCredentialCount: 0,
legacyJsonFiles: [],
backupRequired: true,
});
const done = (): MigrationPreflight => ({ ...pending(), state: "succeeded", needsMigration: false, databasePlaintextCount: 0, backupPath: "/tmp/backup" });
const report: MigrationReport = { migrationId: "secret-store-v1", state: "succeeded", backupPath: "/tmp/backup", databasePlaintextCount: 2, legacyJsonFiles: [], verifiedSecretCount: 2 };
describe("migration store", () => {
it("keeps the wizard blocked until explicit entry after a successful migration", async () => {
const status = vi.fn().mockResolvedValueOnce(pending()).mockResolvedValue(done());
const store = useMigrationStore({ migrationStatus: status, migrationStart: vi.fn().mockResolvedValue(report), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
await store.initialize();
expect(store.blocking.value).toBe(true);
await store.start();
expect(store.state.report).toEqual(report);
expect(store.blocking.value).toBe(true);
store.enter();
expect(store.blocking.value).toBe(false);
});
it("preserves the report and status when cleanup fails", async () => {
const cleanup = vi.fn().mockRejectedValue(new Error("failed"));
const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: cleanup });
await store.initialize();
store.state.report = report;
await store.cleanup();
expect(store.state.error).toBe("cleanupFailed");
expect(store.state.report).toEqual(report);
});
it("allows a completed migration with a retained backup to enter after restart", async () => {
const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
await store.initialize();
expect(store.completed.value).toBe(true);
expect(store.blocking.value).toBe(false);
});
it("keeps status failures on the status retry path", async () => {
const status = vi
.fn()
.mockRejectedValueOnce(Object.assign(new Error("unavailable"), { backendError: { code: "KEY_PROVIDER_UNAVAILABLE", detail: "safe detail" } }))
.mockResolvedValue(done());
const store = useMigrationStore({ migrationStatus: status, migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
await store.initialize();
expect(store.state.error).toBe("statusFailed");
expect(store.state.errorCode).toBeNull();
expect(store.state.errorMessage).toBeNull();
await store.initialize();
expect(store.state.error).toBeNull();
expect(store.completed.value).toBe(true);
});
it("discards arbitrary transport exception values in state and diagnostics", async () => {
const secret = "password=DO_NOT_EXPOSE";
const failure = Object.assign(new Error(secret), { backendError: { code: secret, detail: secret } });
const status = vi.fn().mockRejectedValue(failure);
const store = useMigrationStore({ migrationStatus: status, migrationStart: vi.fn().mockRejectedValue(failure), migrationRetry: vi.fn().mockRejectedValue(failure), migrationCleanupBackups: vi.fn().mockRejectedValue(failure) });
for (const action of [store.initialize, store.start, store.retry, store.cleanup]) {
await action();
expect(JSON.stringify(store.state)).not.toContain(secret);
expect(JSON.stringify(store.diagnostic())).not.toContain(secret);
}
});
it("shows safe preflight errors even when the migration is pending", async () => {
const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue({ ...pending(), errorCode: "MISSING_PERSISTENT_KEY", errorMessage: "Configure a persistent key." }), migrationStart: vi.fn(), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
await store.initialize();
expect(store.state.error).toBe("migrationFailed");
expect(store.state.errorCode).toBe("MISSING_PERSISTENT_KEY");
expect(store.state.errorMessage).toBe("Configure a persistent key.");
});
it("does not show a failure for a managed key created by migration", async () => {
const store = useMigrationStore({
migrationStatus: vi.fn().mockResolvedValue({
...pending(),
keyProviderAvailable: false,
keyCreationAllowed: true,
errorCode: "MISSING_MANAGED_KEY",
errorMessage: "A managed data-directory secret key will be created when migration starts",
}),
migrationStart: vi.fn(),
migrationRetry: vi.fn(),
migrationCleanupBackups: vi.fn(),
});
await store.initialize();
expect(store.state.error).toBeNull();
expect(store.state.errorCode).toBe("MISSING_MANAGED_KEY");
});
it("keeps completion through a failed cleanup and successful cleanup retry", async () => {
let finishCleanup!: () => void;
const cleanup = vi
.fn()
.mockRejectedValueOnce(new Error("password=secret"))
.mockImplementationOnce(
() =>
new Promise<void>((resolve) => {
finishCleanup = resolve;
}),
);
const retry = vi.fn();
const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn(), migrationRetry: retry, migrationCleanupBackups: cleanup });
await store.initialize();
await store.cleanup();
expect(store.state.error).toBe("cleanupFailed");
expect(store.state.step).toBe(3);
expect(store.completed.value).toBe(true);
expect(store.state.status?.backupPath).toBe("/tmp/backup");
const cleanupAttempt = store.cleanup();
expect(store.state.busy).toBe(true);
await store.cleanup();
expect(cleanup).toHaveBeenCalledTimes(2);
store.enter();
expect(store.state.entered).toBe(true);
finishCleanup();
await cleanupAttempt;
expect(store.state.busy).toBe(false);
expect(store.state.step).toBe(3);
expect(store.state.error).toBeNull();
expect(store.completed.value).toBe(true);
expect(store.state.status?.backupPath).toBeNull();
expect(retry).not.toHaveBeenCalled();
});
it("recovers when a lost action response is followed by verified completion", async () => {
const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValue(done()), migrationStart: vi.fn().mockRejectedValue(new Error("response lost")), migrationRetry: vi.fn(), migrationCleanupBackups: vi.fn() });
await store.start();
expect(store.state.step).toBe(3);
expect(store.state.error).toBeNull();
expect(store.state.busy).toBe(false);
});
it("retries a failed migration and completes without losing the error report", async () => {
const failed = { ...pending(), state: "failed" as const, errorCode: "BACKUP_FAILED", errorMessage: "Cannot create backup" };
const retry = vi.fn().mockResolvedValue(report);
const store = useMigrationStore({ migrationStatus: vi.fn().mockResolvedValueOnce(failed).mockResolvedValue(done()), migrationStart: vi.fn().mockRejectedValue(new Error("failure")), migrationRetry: retry, migrationCleanupBackups: vi.fn() });
await store.start();
expect(store.state.errorCode).toBe("BACKUP_FAILED");
expect(store.diagnostic().actionError).toBe("migrationFailed");
await store.retry();
expect(retry).toHaveBeenCalledOnce();
expect(store.state.step).toBe(3);
expect(store.state.error).toBeNull();
});
});
+111
View File
@@ -0,0 +1,111 @@
import { computed, reactive } from "vue";
import * as api from "@/lib/backend/api";
import type { MigrationPreflight, MigrationReport } from "@/lib/backend/migration";
type MigrationApi = Pick<typeof api, "migrationStatus" | "migrationStart" | "migrationRetry" | "migrationCleanupBackups">;
// Each startup boundary owns its state; an action failure never erases its report.
export function useMigrationStore(backend: MigrationApi = api) {
const state = reactive<{
status: MigrationPreflight | null;
report: MigrationReport | null;
loading: boolean;
busy: boolean;
error: "statusFailed" | "migrationFailed" | "cleanupFailed" | null;
errorCode: string | null;
errorMessage: string | null;
entered: boolean;
step: 1 | 2 | 3;
}>({ status: null, report: null, loading: true, busy: false, error: null, errorCode: null, errorMessage: null, entered: false, step: 1 });
const completed = computed(() => state.status !== null && !state.status.needsMigration && ["succeeded", "not_required"].includes(state.status.state));
// A managed data-directory key is intentionally created when migration
// starts. Its absence during the read-only preflight is actionable, not a
// migration failure, as long as the backend explicitly allows creation.
const hasBlockingError = () => Boolean(state.errorCode && !(state.errorCode === "MISSING_MANAGED_KEY" && state.status?.keyCreationAllowed === true));
const blocking = computed(() => state.loading || state.busy || state.error === "statusFailed" || !completed.value || (!state.entered && Boolean(state.report || state.status?.backupPath)));
function clearError() {
state.error = null;
state.errorCode = null;
state.errorMessage = null;
}
async function refreshStatus() {
// Only this endpoint returns classified, redacted migration errors. Transport
// exceptions may contain configuration values and must never enter UI state.
state.status = await backend.migrationStatus();
state.errorCode = state.status.errorCode ?? null;
state.errorMessage = state.status.errorMessage ?? null;
}
async function initialize() {
state.loading = true;
clearError();
try {
await refreshStatus();
state.step = completed.value ? 3 : 1;
// A completed migration only needs the success page in the session that
// performed it. On later launches, retained backups are recovery assets,
// not a reason to block the normal application startup.
state.entered = completed.value;
if (state.status?.state === "failed" || hasBlockingError()) state.error = "migrationFailed";
} catch {
state.error = "statusFailed";
} finally {
state.loading = false;
}
}
async function run(retry: boolean) {
if (state.busy) return;
state.busy = true;
state.step = 2;
clearError();
try {
state.report = await (retry ? backend.migrationRetry() : backend.migrationStart());
} catch {
state.error = "migrationFailed";
}
try {
await refreshStatus();
if (completed.value) {
state.step = 3;
state.error = null;
}
if (!completed.value || hasBlockingError()) state.error = "migrationFailed";
} catch {
state.error = "statusFailed";
} finally {
state.busy = false;
}
}
async function cleanup() {
if (state.busy) return;
state.busy = true;
clearError();
try {
await backend.migrationCleanupBackups();
if (state.status) state.status.backupPath = null;
if (state.report) state.report.backupPath = null;
} catch {
state.error = "cleanupFailed";
} finally {
state.busy = false;
}
}
function diagnostic() {
const s = state.status;
return {
migrationId: s?.migrationId,
actionError: state.error,
step: state.step,
needsMigration: s?.needsMigration,
legacyJsonFiles: s?.legacyJsonFiles,
state: s?.state,
counts: s ? { connections: s.connectionCount, databasePlaintext: s.databasePlaintextCount, plugin: s.pluginSecretCount, ai: s.aiSecretCount, tunnel: s.tunnelSecretCount, sync: s.syncCredentialCount } : {},
keyProviderAvailable: s?.keyProviderAvailable,
backupPath: s?.backupPath,
errorCode: state.errorCode,
};
}
function enter() {
if (completed.value && !state.busy) state.entered = true;
}
return { state, blocking, completed, initialize, start: () => run(false), retry: () => run(true), cleanup, diagnostic, enter };
}