Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(account): Isolate account deletion from device data (#1812)

Chad Pihafb7496e13703
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 29e6bb101..36ec893cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Data safety
+
+- **Deleting one account no longer erases another account's local content.** Account deletion now removes only that account's private notes and folders, preserves workspace-owned spaces and content with former-user attribution cleared, and leaves downloaded models and device settings intact. A separate unchecked option erases all app data from the device when leaving OpenWhispr permanently.
+
## [1.9.0] - 2026-08-24
The chat agent and the voice agent become one Voice Assistant behind a redesigned dictation pill, guided setup is rebuilt end to end, and the notes surface gets a design pass with @mention tagging and real speaker identity in meeting notes. Meetings you forget to stop now end themselves. Linux gains push-to-talk on Wayland, Windows pastes back into the window you dictated into, and local transcription stops thanking you for watching.
diff --git a/main.js b/main.js
index 366d12ca4..7d54809fe 100644
--- a/main.js
+++ b/main.js
@@ -431,6 +431,16 @@ function initializeCoreManagers() {
windowManager = new WindowManager();
hotkeyManager = windowManager.hotkeyManager;
databaseManager = new DatabaseManager();
+ // Restore the last validated account scope before any window, IPC handler,
+ // or meeting flow can read or create notes. Offline launches keep the
+ // account's data visible; a stale or rotated credential fails the hash
+ // check and restores nothing.
+ const accountScopeBinding = require("./src/helpers/accountScopeBinding");
+ const bootAccountId = accountScopeBinding.resolveBootAccountScope({
+ token: require("./src/helpers/tokenStore").get(),
+ binding: accountScopeBinding.read(),
+ });
+ if (bootAccountId) databaseManager.setActiveAccountId(bootAccountId);
clipboardManager = new ClipboardManager();
whisperManager = new WhisperManager();
if (process.platform !== "darwin") {
@@ -541,6 +551,7 @@ function initializeCoreManagers() {
linuxPortalAudioManager,
windowsLoopbackAudioManager,
meetingAecManager,
+ getQdrantManager: () => qdrantManager,
getTrayManager: () => trayManager,
oauthProtocolRegistered: protocolRegistered,
oauthProtocol: OAUTH_PROTOCOL,
diff --git a/preload.js b/preload.js
index d81a7e1e3..fd5df000f 100644
--- a/preload.js
+++ b/preload.js
@@ -185,6 +185,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Space functions
getSpaces: () => ipcRenderer.invoke("db-get-spaces"),
+ setActiveAccountScope: (accountId, expectedAuthGeneration) =>
+ ipcRenderer.invoke("set-active-account-scope", accountId, expectedAuthGeneration),
+ deleteAccountData: (accountId, expectedAuthGeneration) =>
+ ipcRenderer.invoke("delete-account-data", accountId, expectedAuthGeneration),
updateSpace: (id, updates) => ipcRenderer.invoke("db-update-space", id, updates),
purgeSpace: (id, options) => ipcRenderer.invoke("db-purge-space", id, options),
upsertSpaceFromCloud: (space) => ipcRenderer.invoke("db-upsert-space-from-cloud", space),
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index c2e0b01fa..3d5f38484 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -37,7 +37,10 @@ import {
Languages,
} from "lucide-react";
import { useAuth } from "../hooks/useAuth";
-import { AUTH_URL, signOut, deleteAccount } from "../lib/auth";
+import { AUTH_URL, signOut } from "../lib/auth";
+import { deleteAccount } from "../lib/accountDeletionRequest";
+import { executeAccountDeletion } from "../lib/accountDeletionFlow";
+import { getValidatedAuthGeneration } from "../lib/authRequestContext";
import { useBillingPortal } from "../hooks/useBillingPortal";
import MicPermissionWarning from "./ui/MicPermissionWarning";
import MicrophoneSettings from "./ui/MicrophoneSettings";
@@ -1692,6 +1695,8 @@ export default function SettingsPage({
});
const [isSigningOut, setIsSigningOut] = useState(false);
const [isDeletingAccount, setIsDeletingAccount] = useState(false);
+ const [isDeleteAccountDialogOpen, setIsDeleteAccountDialogOpen] = useState(false);
+ const [eraseDeviceData, setEraseDeviceData] = useState(false);
const { openBillingPortal, isOpening: isOpeningBilling } = useBillingPortal(usage);
const [billingState, setBillingState] = useState<Record<string, boolean>>({
pro: true,
@@ -1781,8 +1786,8 @@ export default function SettingsPage({
const handleSignOut = useCallback(async () => {
setIsSigningOut(true);
try {
- // Team content is membership-scoped, not account data: drop it locally
- // before the session ends (never blocks sign-out).
+ // Clear account-scoped renderer/session state before ending the session.
+ // Workspace-owned rows remain cached behind their membership boundary.
await syncService.purgeTeamSpacesForSignOut();
await signOut();
window.location.reload();
@@ -1798,47 +1803,65 @@ export default function SettingsPage({
}, [showAlertDialog, t]);
const handleDeleteAccount = useCallback(() => {
- showConfirmDialog({
- title: t("settingsPage.account.deleteAccount.title"),
- description: t("settingsPage.account.deleteAccount.description"),
- onConfirm: async () => {
- setIsDeletingAccount(true);
- try {
- // Best-effort cloud cleanup (needs session cookies before sign-out)
- try {
- const { NotesService } = await import("../services/NotesService");
- await NotesService.deleteAll();
- } catch {}
-
- const result = await deleteAccount();
- if (result.error) {
- logger.error("Server account deletion failed", result.error, "auth");
- }
+ setEraseDeviceData(false);
+ setIsDeleteAccountDialogOpen(true);
+ }, []);
- try {
- await signOut();
- } catch {}
- await window.electronAPI?.cleanupApp();
+ const confirmDeleteAccount = useCallback(async () => {
+ const accountId = user?.id;
+ const authGeneration = getValidatedAuthGeneration();
+ if (!accountId || authGeneration == null) {
+ showAlertDialog({
+ title: t("settingsPage.account.deleteAccount.failedTitle"),
+ description: t("settingsPage.account.deleteAccount.failedDescription"),
+ });
+ return;
+ }
- showAlertDialog({
- title: t("settingsPage.account.deleteAccount.successTitle"),
- description: t("settingsPage.account.deleteAccount.successDescription"),
- });
- setTimeout(() => window.location.reload(), 1000);
- } catch (error) {
- logger.error("Account deletion failed", error, "auth");
- showAlertDialog({
- title: t("settingsPage.account.deleteAccount.failedTitle"),
- description: t("settingsPage.account.deleteAccount.failedDescription"),
- });
- } finally {
- setIsDeletingAccount(false);
- }
- },
- variant: "destructive",
- confirmText: t("settingsPage.account.deleteAccount.confirmText"),
- });
- }, [showConfirmDialog, showAlertDialog, t]);
+ setIsDeletingAccount(true);
+ try {
+ const result = await executeAccountDeletion({
+ eraseDeviceData,
+ dependencies: {
+ deleteRemoteAccount: deleteAccount,
+ deleteLocalAccountData: async () => {
+ const cleanup = await window.electronAPI?.deleteAccountData?.(
+ accountId,
+ authGeneration
+ );
+ if (!cleanup?.success) {
+ throw new Error(cleanup?.error ?? "Could not remove local account data");
+ }
+ },
+ clearWorkspaceSessionState: () => syncService.purgeTeamSpacesForSignOut(),
+ signOut,
+ eraseDeviceData: async () => {
+ const cleanup = await window.electronAPI?.cleanupApp();
+ if (!cleanup?.success) {
+ throw new Error(cleanup?.errors?.join(", ") || "Could not erase device data");
+ }
+ },
+ },
+ });
+
+ showAlertDialog({
+ title: t("settingsPage.account.deleteAccount.successTitle"),
+ description:
+ result.localCleanupFailures.length > 0
+ ? t("settingsPage.account.deleteAccount.partialCleanupDescription")
+ : t("settingsPage.account.deleteAccount.successDescription"),
+ });
+ setTimeout(() => window.location.reload(), 1000);
+ } catch (error) {
+ logger.error("Account deletion failed", error, "auth");
+ showAlertDialog({
+ title: t("settingsPage.account.deleteAccount.failedTitle"),
+ description: t("settingsPage.account.deleteAccount.failedDescription"),
+ });
+ } finally {
+ setIsDeletingAccount(false);
+ }
+ }, [eraseDeviceData, showAlertDialog, t, user?.id]);
const renderWhisperVadSettings = () => (
<div>
@@ -4551,6 +4574,42 @@ EOF`,
cancelText={confirmDialog.cancelText}
/>
+ <ConfirmDialog
+ open={isDeleteAccountDialogOpen}
+ onOpenChange={(open) => {
+ setIsDeleteAccountDialogOpen(open);
+ if (!open) setEraseDeviceData(false);
+ }}
+ title={t("settingsPage.account.deleteAccount.title")}
+ description={t("settingsPage.account.deleteAccount.description")}
+ onConfirm={() => void confirmDeleteAccount()}
+ variant="destructive"
+ confirmText={t("settingsPage.account.deleteAccount.confirmText")}
+ confirmDisabled={isDeletingAccount}
+ >
+ <label className="flex cursor-pointer items-start gap-3 rounded-lg border border-border p-3">
+ <input
+ type="checkbox"
+ className="mt-1 h-4 w-4 rounded border-border accent-destructive"
+ checked={eraseDeviceData}
+ onChange={(event) => setEraseDeviceData(event.target.checked)}
+ />
+ <span className="space-y-1">
+ <span className="block text-sm font-medium">
+ {t("settingsPage.account.deleteAccount.eraseDeviceLabel")}
+ </span>
+ <span className="block text-xs text-muted-foreground">
+ {t("settingsPage.account.deleteAccount.eraseDeviceDescription")}
+ </span>
+ {eraseDeviceData && (
+ <span className="block text-xs font-medium text-destructive">
+ {t("settingsPage.account.deleteAccount.eraseDeviceWarning")}
+ </span>
+ )}
+ </span>
+ </label>
+ </ConfirmDialog>
+
<AlertDialog
open={alertDialog.open}
onOpenChange={(open) => !open && hideAlertDialog()}
diff --git a/src/helpers/accountScopeBinding.js b/src/helpers/accountScopeBinding.js
new file mode 100644
index 000000000..24c083f0b
--- /dev/null
+++ b/src/helpers/accountScopeBinding.js
@@ -0,0 +1,80 @@
+// Persists the last VALIDATED account-scope binding so a boot without a
+// resolvable session (offline, expired lease) can restore note visibility
+// for the credential still on disk. The sha256 token fingerprint makes the
+// file self-verifying: a rotated or replaced bearer no longer matches, so a
+// stale binding degrades to "no restore", never to restoring the wrong
+// account.
+const { app } = require("electron");
+const crypto = require("crypto");
+const fs = require("fs");
+const path = require("path");
+const debugLogger = require("./debugLogger");
+
+const BINDING_VERSION = 1;
+
+const bindingFile = () => path.join(app.getPath("userData"), "account-scope-binding.json");
+
+function hashToken(token) {
+ return crypto.createHash("sha256").update(token, "utf8").digest("hex");
+}
+
+// Pure gate for the set-active-account-scope IPC request. A null accountId
+// arriving while a token exists is a "validated signed-out" transition and
+// must carry the current generation, so a stray early null call cannot
+// discard a valid binding.
+function evaluateScopeRequest({ accountId, expectedGeneration, token, generation }) {
+ if (accountId !== null && (typeof accountId !== "string" || accountId.trim().length === 0)) {
+ return { ok: false, code: "INVALID_ACCOUNT" };
+ }
+ if (accountId !== null && !token) {
+ return { ok: false, code: "AUTH_CONTEXT_CHANGED" };
+ }
+ if (token && generation !== expectedGeneration) {
+ return { ok: false, code: "AUTH_CONTEXT_CHANGED" };
+ }
+ return { ok: true };
+}
+
+// Pure boot decision: restore only when the persisted bearer is the exact
+// credential this binding was validated under.
+function resolveBootAccountScope({ token, binding }) {
+ if (typeof token !== "string" || token.length === 0) return null;
+ if (!binding || binding.version !== BINDING_VERSION) return null;
+ if (typeof binding.accountId !== "string" || binding.accountId.trim().length === 0) return null;
+ if (binding.tokenHash !== hashToken(token)) return null;
+ return binding.accountId;
+}
+
+function read() {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(bindingFile(), "utf8"));
+ return parsed && typeof parsed === "object" ? parsed : null;
+ } catch (err) {
+ if (err?.code !== "ENOENT") {
+ debugLogger.error("accountScopeBinding.read failed", { error: err?.message });
+ }
+ return null;
+ }
+}
+
+function persist(accountId, token) {
+ try {
+ fs.writeFileSync(
+ bindingFile(),
+ JSON.stringify({ version: BINDING_VERSION, accountId, tokenHash: hashToken(token) }),
+ { mode: 0o600 }
+ );
+ } catch (err) {
+ debugLogger.error("accountScopeBinding.persist failed", { error: err?.message });
+ }
+}
+
+function clear() {
+ try {
+ fs.rmSync(bindingFile(), { force: true });
+ } catch (err) {
+ debugLogger.error("accountScopeBinding.clear failed", { error: err?.message });
+ }
+}
+
+module.exports = { clear, evaluateScopeRequest, hashToken, persist, read, resolveBootAccountScope };
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 9a48f23de..c826e0321 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -112,9 +112,94 @@ const SELECTED_CALENDAR_EVENT_FILTER = `(
class DatabaseManager {
constructor() {
this.db = null;
+ this.activeAccountId = null;
this.initDatabase();
}
+ setActiveAccountId(accountId) {
+ this.activeAccountId =
+ typeof accountId === "string" && accountId.trim().length > 0 ? accountId.trim() : null;
+ }
+
+ _accountScopeCondition(tableName) {
+ return {
+ sql: `((${tableName}.account_id IS NULL AND EXISTS (
+ SELECT 1 FROM spaces account_scope_space
+ WHERE account_scope_space.id = ${tableName}.space_id
+ AND account_scope_space.kind = 'private'
+ )) OR ${tableName}.account_id = ? OR EXISTS (
+ SELECT 1
+ FROM spaces account_scope_space
+ JOIN space_accounts account_scope_membership
+ ON account_scope_membership.space_id = account_scope_space.id
+ WHERE account_scope_space.id = ${tableName}.space_id
+ AND account_scope_space.kind = 'team'
+ AND account_scope_membership.account_id = ?
+ ))`,
+ params: [this.activeAccountId, this.activeAccountId],
+ };
+ }
+
+ _accountIdForSpace(spaceId) {
+ const space = this.db.prepare("SELECT kind FROM spaces WHERE id = ?").get(spaceId);
+ return space?.kind === "team" ? null : this.activeAccountId;
+ }
+
+ _getFolderInAccountScope(id) {
+ const accountScope = this._accountScopeCondition("folders");
+ return (
+ this.db
+ .prepare(`SELECT * FROM folders WHERE id = ? AND ${accountScope.sql}`)
+ .get(id, ...accountScope.params) || null
+ );
+ }
+
+ // Child notes owned by another local account are invisible to the active
+ // scope, so a folder removal must release them to the space root — never
+ // delete them (or their conversations, speaker rows, or cloud tombstones)
+ // with the folder. Run this before any statement that targets the folder's
+ // children, so plain `folder_id = ?` filters only ever see in-scope rows.
+ _releaseOutOfScopeChildNotes(folderId) {
+ const accountScope = this._accountScopeCondition("notes");
+ const outOfScopeIds = this.db
+ .prepare(
+ `SELECT id FROM notes
+ WHERE folder_id = ? AND id NOT IN (
+ SELECT id FROM notes WHERE folder_id = ? AND ${accountScope.sql}
+ )`
+ )
+ .all(folderId, folderId, ...accountScope.params)
+ .map((row) => row.id);
+ if (outOfScopeIds.length === 0) return [];
+ const placeholders = outOfScopeIds.map(() => "?").join(", ");
+ this.db
+ .prepare(
+ `UPDATE notes
+ SET folder_id = NULL, sync_status = 'pending', updated_at = datetime('now')
+ WHERE id IN (${placeholders})`
+ )
+ .run(...outOfScopeIds);
+ return this.db
+ .prepare(`SELECT * FROM notes WHERE id IN (${placeholders})`)
+ .all(...outOfScopeIds);
+ }
+
+ _releaseActiveSpaceMembershipIfShared(spaceId) {
+ if (!this.activeAccountId) return false;
+ const otherMembership = this.db
+ .prepare(
+ `SELECT 1 FROM space_accounts
+ WHERE space_id = ? AND account_id != ?
+ LIMIT 1`
+ )
+ .get(spaceId, this.activeAccountId);
+ if (!otherMembership) return false;
+ this.db
+ .prepare("DELETE FROM space_accounts WHERE space_id = ? AND account_id = ?")
+ .run(spaceId, this.activeAccountId);
+ return true;
+ }
+
initDatabase() {
try {
const dbFileName =
@@ -1031,6 +1116,44 @@ class DatabaseManager {
"CREATE INDEX IF NOT EXISTS idx_folders_space_sort ON folders(space_id, sort_order)"
);
+ // Account attribution is intentionally nullable. Existing rows remain
+ // device-owned legacy content; workspace rows are never attributed to a
+ // personal account and therefore cannot be erased with that account.
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN account_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE folders ADD COLUMN account_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_notes_account_id ON notes(account_id)");
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_folders_account_id ON folders(account_id)");
+ this.db.exec("DROP INDEX IF EXISTS idx_folders_space_name");
+ this.db.exec(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_folders_space_legacy_name ON folders(space_id, name) WHERE deleted_at IS NULL AND account_id IS NULL"
+ );
+ this.db.exec(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_folders_space_account_name ON folders(space_id, account_id, name) WHERE deleted_at IS NULL AND account_id IS NOT NULL"
+ );
+
+ // A cloud space is workspace-owned, while visibility is account-specific.
+ // Keep the many-to-many membership separate so signing out one local
+ // account cannot delete or expose another account's workspace cache.
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS space_accounts (
+ space_id INTEGER NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,
+ account_id TEXT NOT NULL,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (space_id, account_id)
+ )
+ `);
+ this.db.exec(
+ "CREATE INDEX IF NOT EXISTS idx_space_accounts_account_id ON space_accounts(account_id)"
+ );
+
// Cloud-backed rows that just LEFT a team must keep pushing their scope
// retraction (D6) even in the backup-off team-only pass, where the
// pending queues otherwise filter on the row's CURRENT space kind.
@@ -1072,6 +1195,11 @@ class DatabaseManager {
} catch (err) {
if (!err.message.includes("duplicate column")) throw err;
}
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN created_by_user_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
// Space vector purges owed to Qdrant while the sidecar was down/booting;
// drained once the vector index is ready.
@@ -1959,19 +2087,26 @@ class DatabaseManager {
}
if (folderId) {
// D2: a note's space always follows its folder's space.
- const folder = this.db.prepare("SELECT space_id FROM folders WHERE id = ?").get(folderId);
- spaceId = folder?.space_id ?? spaceId ?? this.getPrivateSpaceId();
+ const folder = this._getFolderInAccountScope(folderId);
+ if (!folder) throw new Error("Folder not found in the active account scope");
+ spaceId = folder.space_id;
} else {
if (spaceId == null) spaceId = this.getPrivateSpaceId();
+ if (!this.getSpace(spaceId)) throw new Error("Space not found in the active account scope");
const defaultFolderName = noteType === "meeting" ? "Meetings" : "Personal";
+ const folderScope = this._accountScopeCondition("folders");
const defaultFolder = this.db
- .prepare("SELECT id FROM folders WHERE name = ? AND is_default = 1 AND space_id = ?")
- .get(defaultFolderName, spaceId);
+ .prepare(
+ `SELECT id FROM folders
+ WHERE name = ? AND is_default = 1 AND space_id = ? AND ${folderScope.sql}`
+ )
+ .get(defaultFolderName, spaceId, ...folderScope.params);
folderId = defaultFolder?.id || null;
}
const clientNoteId = randomUUID();
+ const accountId = this._accountIdForSpace(spaceId);
const stmt = this.db.prepare(
- "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id, space_id, client_note_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
+ "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id, space_id, client_note_id, account_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
const result = stmt.run(
title,
@@ -1981,7 +2116,8 @@ class DatabaseManager {
audioDuration,
folderId,
spaceId,
- clientNoteId
+ clientNoteId,
+ accountId
);
const fetchStmt = this.db.prepare("SELECT * FROM notes WHERE id = ?");
@@ -2004,12 +2140,17 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
const spaceId = this.getPrivateSpaceId();
+ const accountId = this._accountIdForSpace(spaceId);
let folderId = null;
try {
+ const folderScope = this._accountScopeCondition("folders");
const existing = this.db
- .prepare("SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL")
- .get(folderName, spaceId);
+ .prepare(
+ `SELECT id FROM folders
+ WHERE name = ? AND space_id = ? AND deleted_at IS NULL AND ${folderScope.sql}`
+ )
+ .get(folderName, spaceId, ...folderScope.params);
folderId = existing?.id ?? this.createFolder(folderName, spaceId)?.folder?.id ?? null;
} catch (folderError) {
debugLogger.error(
@@ -2021,8 +2162,8 @@ class DatabaseManager {
const insert = this.db.prepare(`
INSERT INTO notes (client_note_id, title, content, note_type, source_file,
- folder_id, space_id, transcript, participants, sync_status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending',
+ folder_id, space_id, account_id, transcript, participants, sync_status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending',
COALESCE(?, datetime('now')), COALESCE(?, datetime('now')))
ON CONFLICT(client_note_id) DO NOTHING
`);
@@ -2042,6 +2183,7 @@ class DatabaseManager {
row.sourceFile,
folderId,
spaceId,
+ accountId,
row.transcript,
row.participants,
row.createdAt,
@@ -2090,8 +2232,9 @@ class DatabaseManager {
if (!this.db) {
throw new Error("Database not initialized");
}
- const stmt = this.db.prepare("SELECT * FROM notes WHERE id = ?");
- return stmt.get(id) || null;
+ const accountScope = this._accountScopeCondition("notes");
+ const stmt = this.db.prepare(`SELECT * FROM notes WHERE id = ? AND ${accountScope.sql}`);
+ return stmt.get(id, ...accountScope.params) || null;
} catch (error) {
debugLogger.error("Error getting note", { error: error.message }, "notes");
throw error;
@@ -2103,10 +2246,13 @@ class DatabaseManager {
if (!this.db) {
throw new Error("Database not initialized");
}
+ const accountScope = this._accountScopeCondition("notes");
const stmt = this.db.prepare(
- "SELECT * FROM notes WHERE cloud_id = ? AND deleted_at IS NULL LIMIT 1"
+ `SELECT * FROM notes
+ WHERE cloud_id = ? AND deleted_at IS NULL AND ${accountScope.sql}
+ LIMIT 1`
);
- return stmt.get(cloudId) || null;
+ return stmt.get(cloudId, ...accountScope.params) || null;
} catch (error) {
debugLogger.error("Error getting note by cloud_id", { error: error.message }, "notes");
throw error;
@@ -2120,6 +2266,9 @@ class DatabaseManager {
}
const conditions = ["deleted_at IS NULL"];
const params = [];
+ const accountScope = this._accountScopeCondition("notes");
+ conditions.push(accountScope.sql);
+ params.push(...accountScope.params);
if (noteType) {
conditions.push("note_type = ?");
params.push(noteType);
@@ -2150,11 +2299,14 @@ class DatabaseManager {
getNotesForSpace(spaceId, limit = 50) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("notes");
return this.db
.prepare(
- "SELECT * FROM notes WHERE space_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC LIMIT ?"
+ `SELECT * FROM notes
+ WHERE space_id = ? AND deleted_at IS NULL AND ${accountScope.sql}
+ ORDER BY updated_at DESC LIMIT ?`
)
- .all(spaceId, limit);
+ .all(spaceId, ...accountScope.params, limit);
} catch (error) {
debugLogger.error("Error getting notes for space", { error: error.message }, "notes");
throw error;
@@ -2174,6 +2326,9 @@ class DatabaseManager {
if (candidateIds && candidateIds.length === 0) return [];
const conditions = ["deleted_at IS NULL"];
const params = [];
+ const accountScope = this._accountScopeCondition("notes");
+ conditions.push(accountScope.sql);
+ params.push(...accountScope.params);
if (candidateIds) {
conditions.push(`id IN (${candidateIds.map(() => "?").join(", ")})`);
params.push(...candidateIds);
@@ -2199,14 +2354,20 @@ class DatabaseManager {
updateNote(id, updates) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return { success: false, error: "Note not found" };
+ updates = { ...updates };
+ delete updates.account_id;
if (updates.folder_id != null) {
// D2: a note's space always follows its folder's space.
- const folder = this.db
- .prepare("SELECT space_id FROM folders WHERE id = ?")
- .get(updates.folder_id);
+ const folder = this._getFolderInAccountScope(updates.folder_id);
if (folder) updates = { ...updates, space_id: folder.space_id };
+ else return { success: false, error: "Folder not found" };
}
if (updates.space_id !== undefined) {
+ if (!this.getSpace(updates.space_id)) {
+ return { success: false, error: "Space not found" };
+ }
+ updates.account_id = this._accountIdForSpace(updates.space_id);
// D6: a cloud-backed note leaving a team must keep pushing until the
// scope retraction lands, even when cloud backup is off (left_team
// keeps it in the team-only pending queue). Identity forks null the
@@ -2250,6 +2411,7 @@ class DatabaseManager {
"owner_user_id",
"updated_by_user_id",
"left_team",
+ "account_id",
];
const fields = [];
const values = [];
@@ -2267,8 +2429,12 @@ class DatabaseManager {
}
fields.push("updated_at = CURRENT_TIMESTAMP");
values.push(id);
- const stmt = this.db.prepare(`UPDATE notes SET ${fields.join(", ")} WHERE id = ?`);
- stmt.run(...values);
+ const accountScope = this._accountScopeCondition("notes");
+ const stmt = this.db.prepare(
+ `UPDATE notes SET ${fields.join(", ")} WHERE id = ? AND ${accountScope.sql}`
+ );
+ const result = stmt.run(...values, ...accountScope.params);
+ if (result.changes === 0) return { success: false, error: "Note not found" };
const fetchStmt = this.db.prepare("SELECT * FROM notes WHERE id = ?");
const note = fetchStmt.get(id);
return { success: true, note };
@@ -2283,6 +2449,9 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
const conditions = ["deleted_at IS NULL"];
const params = [];
+ const accountScope = this._accountScopeCondition("folders");
+ conditions.push(accountScope.sql);
+ params.push(...accountScope.params);
if (spaceId != null) {
conditions.push("space_id = ?");
params.push(spaceId);
@@ -2304,23 +2473,29 @@ class DatabaseManager {
const trimmed = (name || "").trim();
if (!trimmed) return { success: false, error: "Folder name is required" };
if (spaceId == null) spaceId = this.getPrivateSpaceId();
+ if (!this.getSpace(spaceId)) {
+ return { success: false, error: "Space not found" };
+ }
+ const accountScope = this._accountScopeCondition("folders");
const existing = this.db
.prepare(
`SELECT id FROM folders
- WHERE name = ? AND space_id = ? AND ${FOLDER_NAME_TAKEN_FILTER}`
+ WHERE name = ? AND space_id = ? AND ${FOLDER_NAME_TAKEN_FILTER}
+ AND ${accountScope.sql}`
)
- .get(trimmed, spaceId);
+ .get(trimmed, spaceId, ...accountScope.params);
if (existing) return { success: false, error: "A folder with that name already exists" };
const maxOrder = this.db
.prepare("SELECT MAX(sort_order) as max_order FROM folders WHERE space_id = ?")
.get(spaceId);
const sortOrder = (maxOrder?.max_order ?? 0) + 1;
const clientFolderId = randomUUID();
+ const accountId = this._accountIdForSpace(spaceId);
const result = this.db
.prepare(
- "INSERT INTO folders (name, sort_order, space_id, client_folder_id) VALUES (?, ?, ?, ?)"
+ "INSERT INTO folders (name, sort_order, space_id, client_folder_id, account_id) VALUES (?, ?, ?, ?, ?)"
)
- .run(trimmed, sortOrder, spaceId, clientFolderId);
+ .run(trimmed, sortOrder, spaceId, clientFolderId, accountId);
const folder = this.db
.prepare("SELECT * FROM folders WHERE id = ?")
.get(result.lastInsertRowid);
@@ -2331,21 +2506,123 @@ class DatabaseManager {
}
}
+ deleteAccountData(accountId) {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!accountId || accountId !== this.activeAccountId) {
+ throw new Error("Account deletion must match the active account scope");
+ }
+
+ const deletedNoteIds = this.db
+ .prepare(
+ `SELECT notes.id
+ FROM notes
+ JOIN spaces ON spaces.id = notes.space_id
+ WHERE notes.account_id = ? AND spaces.kind = 'private'
+ ORDER BY notes.id`
+ )
+ .all(accountId)
+ .map((row) => row.id);
+ const deletedFolderIds = this.db
+ .prepare(
+ `SELECT folders.id
+ FROM folders
+ JOIN spaces ON spaces.id = folders.space_id
+ WHERE folders.account_id = ? AND spaces.kind = 'private'
+ ORDER BY folders.id`
+ )
+ .all(accountId)
+ .map((row) => row.id);
+
+ const notePlaceholders = deletedNoteIds.map(() => "?").join(", ");
+ const folderPlaceholders = deletedFolderIds.map(() => "?").join(", ");
+ const deleteRows = () => {
+ const conversationConditions = [];
+ const conversationParams = [];
+ if (deletedNoteIds.length > 0) {
+ conversationConditions.push(`note_id IN (${notePlaceholders})`);
+ conversationParams.push(...deletedNoteIds);
+ }
+ if (deletedFolderIds.length > 0) {
+ conversationConditions.push(`folder_id IN (${folderPlaceholders})`);
+ conversationParams.push(...deletedFolderIds);
+ }
+ if (conversationConditions.length > 0) {
+ const conversationIds = this.db
+ .prepare(
+ `SELECT id FROM agent_conversations WHERE ${conversationConditions.join(" OR ")}`
+ )
+ .all(...conversationParams)
+ .map((row) => row.id);
+ if (conversationIds.length > 0) {
+ const conversationPlaceholders = conversationIds.map(() => "?").join(", ");
+ this.db
+ .prepare(
+ `DELETE FROM agent_messages WHERE conversation_id IN (${conversationPlaceholders})`
+ )
+ .run(...conversationIds);
+ this.db
+ .prepare(`DELETE FROM agent_conversations WHERE id IN (${conversationPlaceholders})`)
+ .run(...conversationIds);
+ }
+ }
+
+ if (deletedNoteIds.length > 0) {
+ this.db
+ .prepare(`DELETE FROM speaker_mappings WHERE note_id IN (${notePlaceholders})`)
+ .run(...deletedNoteIds);
+ this.db
+ .prepare(`DELETE FROM note_speaker_embeddings WHERE note_id IN (${notePlaceholders})`)
+ .run(...deletedNoteIds);
+ this.db
+ .prepare(`DELETE FROM notes WHERE id IN (${notePlaceholders})`)
+ .run(...deletedNoteIds);
+ }
+ if (deletedFolderIds.length > 0) {
+ this.db
+ .prepare(
+ `DELETE FROM optimistic_folder_delete_rows WHERE folder_id IN (${folderPlaceholders})`
+ )
+ .run(...deletedFolderIds);
+ this.db
+ .prepare(`DELETE FROM folders WHERE id IN (${folderPlaceholders})`)
+ .run(...deletedFolderIds);
+ }
+ this.db.prepare("DELETE FROM space_accounts WHERE account_id = ?").run(accountId);
+ };
+
+ if (typeof this.db.transaction === "function") {
+ this.db.transaction(deleteRows)();
+ } else {
+ this.db.exec("BEGIN");
+ try {
+ deleteRows();
+ this.db.exec("COMMIT");
+ } catch (error) {
+ this.db.exec("ROLLBACK");
+ throw error;
+ }
+ }
+
+ return { deletedNoteIds, deletedFolderIds };
+ }
+
deleteFolder(id) {
try {
if (!this.db) throw new Error("Database not initialized");
- const folder = this.db
- .prepare("SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL")
- .get(id);
+ const folder = this._getFolderInAccountScope(id);
+ if (folder?.deleted_at) return { success: false, error: "Folder not found" };
if (!folder) return { success: false, error: "Folder not found" };
if (folder.is_default) return { success: false, error: "Cannot delete default folders" };
const allChildNotes = "SELECT id FROM notes WHERE folder_id = ?";
const childNotes = `${allChildNotes} AND deleted_at IS NULL`;
+ const accountScope = this._accountScopeCondition("notes");
const noteIds = this.db
- .prepare(childNotes)
- .all(id)
+ .prepare(`${childNotes} AND ${accountScope.sql}`)
+ .all(id, ...accountScope.params)
.map((row) => row.id);
+ let relocatedNotes = [];
this.db.transaction(() => {
+ relocatedNotes = this._releaseOutOfScopeChildNotes(id);
if (!folder.cloud_id) {
// There is no server operation to deny. Local-only folders can
// finalize immediately, including their local-only child content.
@@ -2445,7 +2722,7 @@ class DatabaseManager {
)
.run(id);
})();
- return { success: true, id, noteIds };
+ return { success: true, id, noteIds, relocatedNotes };
} catch (error) {
debugLogger.error("Error deleting folder", { error: error.message }, "notes");
throw error;
@@ -2455,19 +2732,20 @@ class DatabaseManager {
renameFolder(id, name) {
try {
if (!this.db) throw new Error("Database not initialized");
- const folder = this.db
- .prepare("SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL")
- .get(id);
+ const folder = this._getFolderInAccountScope(id);
+ if (folder?.deleted_at) return { success: false, error: "Folder not found" };
if (!folder) return { success: false, error: "Folder not found" };
if (folder.is_default) return { success: false, error: "Cannot rename default folders" };
const trimmed = (name || "").trim();
if (!trimmed) return { success: false, error: "Folder name is required" };
+ const folderScope = this._accountScopeCondition("folders");
const existing = this.db
.prepare(
`SELECT id FROM folders
- WHERE name = ? AND space_id = ? AND id != ? AND ${FOLDER_NAME_TAKEN_FILTER}`
+ WHERE name = ? AND space_id = ? AND id != ? AND ${FOLDER_NAME_TAKEN_FILTER}
+ AND ${folderScope.sql}`
)
- .get(trimmed, folder.space_id, id);
+ .get(trimmed, folder.space_id, id, ...folderScope.params);
if (existing) return { success: false, error: "A folder with that name already exists" };
this.db
.prepare(
@@ -2485,22 +2763,21 @@ class DatabaseManager {
moveFolderToSpace(id, spaceId) {
try {
if (!this.db) throw new Error("Database not initialized");
- const folder = this.db
- .prepare("SELECT * FROM folders WHERE id = ? AND deleted_at IS NULL")
- .get(id);
+ const folder = this._getFolderInAccountScope(id);
+ if (folder?.deleted_at) return { success: false, error: "Folder not found" };
if (!folder) return { success: false, error: "Folder not found" };
if (folder.is_default) return { success: false, error: "Cannot move default folders" };
- const space = this.db
- .prepare("SELECT id, kind FROM spaces WHERE id = ? AND deleted_at IS NULL")
- .get(spaceId);
+ const space = this.getSpace(spaceId);
if (!space) return { success: false, error: "Space not found" };
if (folder.space_id === spaceId) return { success: true, folder, notes: [] };
+ const folderScope = this._accountScopeCondition("folders");
const existing = this.db
.prepare(
`SELECT id FROM folders
- WHERE name = ? AND space_id = ? AND id != ? AND ${FOLDER_NAME_TAKEN_FILTER}`
+ WHERE name = ? AND space_id = ? AND id != ? AND ${FOLDER_NAME_TAKEN_FILTER}
+ AND ${folderScope.sql}`
)
- .get(folder.name, spaceId, id);
+ .get(folder.name, spaceId, id, ...folderScope.params);
if (existing) return { success: false, error: "A folder with that name already exists" };
// D6: cloud-backed rows leaving a team must keep pushing their scope
// retraction even in the backup-off team-only pass (left_team).
@@ -2508,17 +2785,18 @@ class DatabaseManager {
.prepare("SELECT kind FROM spaces WHERE id = ?")
.get(folder.space_id)?.kind;
const leftTeam = oldKind === "team" && space.kind === "private" ? 1 : 0;
+ const nextAccountId = this._accountIdForSpace(spaceId);
const notes = this.db.transaction(() => {
this.db
.prepare(
- "UPDATE folders SET space_id = ?, sync_status = 'pending', updated_at = datetime('now'), left_team = ? WHERE id = ?"
+ "UPDATE folders SET space_id = ?, account_id = ?, sync_status = 'pending', updated_at = datetime('now'), left_team = ? WHERE id = ?"
)
- .run(spaceId, leftTeam && folder.cloud_id ? 1 : 0, id);
+ .run(spaceId, nextAccountId, leftTeam && folder.cloud_id ? 1 : 0, id);
this.db
.prepare(
- "UPDATE notes SET space_id = ?, sync_status = 'pending', updated_at = datetime('now'), left_team = (CASE WHEN ? = 1 AND cloud_id IS NOT NULL THEN 1 ELSE 0 END) WHERE folder_id = ? AND deleted_at IS NULL"
+ "UPDATE notes SET space_id = ?, account_id = ?, sync_status = 'pending', updated_at = datetime('now'), left_team = (CASE WHEN ? = 1 AND cloud_id IS NOT NULL THEN 1 ELSE 0 END) WHERE folder_id = ? AND deleted_at IS NULL"
)
- .run(spaceId, leftTeam, id);
+ .run(spaceId, nextAccountId, leftTeam, id);
return this.db
.prepare("SELECT * FROM notes WHERE folder_id = ? AND deleted_at IS NULL")
.all(id);
@@ -2536,11 +2814,15 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
// folder_id NULL rows are space-root notes; grouping by space_id too
// attributes them per space so the tree shows true space totals.
+ const accountScope = this._accountScopeCondition("notes");
return this.db
.prepare(
- "SELECT space_id, folder_id, COUNT(*) as count FROM notes WHERE deleted_at IS NULL GROUP BY space_id, folder_id"
+ `SELECT space_id, folder_id, COUNT(*) as count
+ FROM notes
+ WHERE deleted_at IS NULL AND ${accountScope.sql}
+ GROUP BY space_id, folder_id`
)
- .all();
+ .all(...accountScope.params);
} catch (error) {
debugLogger.error("Error getting folder note counts", { error: error.message }, "notes");
throw error;
@@ -2576,9 +2858,16 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
return this.db
.prepare(
- "SELECT * FROM spaces WHERE deleted_at IS NULL ORDER BY CASE WHEN kind = 'private' THEN 0 ELSE 1 END, sort_order ASC, name ASC"
+ `SELECT * FROM spaces
+ WHERE deleted_at IS NULL
+ AND (kind = 'private' OR EXISTS (
+ SELECT 1 FROM space_accounts
+ WHERE space_accounts.space_id = spaces.id
+ AND space_accounts.account_id = ?
+ ))
+ ORDER BY CASE WHEN kind = 'private' THEN 0 ELSE 1 END, sort_order ASC, name ASC`
)
- .all()
+ .all(this.activeAccountId)
.map((row) => this._spaceRow(row));
} catch (error) {
debugLogger.error("Error getting spaces", { error: error.message }, "spaces");
@@ -2590,8 +2879,16 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
const row = this.db
- .prepare("SELECT * FROM spaces WHERE id = ? AND deleted_at IS NULL")
- .get(id);
+ .prepare(
+ `SELECT * FROM spaces
+ WHERE id = ? AND deleted_at IS NULL
+ AND (kind = 'private' OR EXISTS (
+ SELECT 1 FROM space_accounts
+ WHERE space_accounts.space_id = spaces.id
+ AND space_accounts.account_id = ?
+ ))`
+ )
+ .get(id, this.activeAccountId);
return row ? this._spaceRow(row) : null;
} catch (error) {
debugLogger.error("Error getting space", { error: error.message }, "spaces");
@@ -2602,7 +2899,7 @@ class DatabaseManager {
updateSpace(id, { name, emoji } = {}) {
try {
if (!this.db) throw new Error("Database not initialized");
- const space = this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(id);
+ const space = this.getSpace(id);
if (!space) return { success: false, error: "Space not found" };
const fields = [];
const values = [];
@@ -2634,6 +2931,7 @@ class DatabaseManager {
setSpaceSyncStatus(id, status) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getSpace(id)) return { success: false, space: null };
const result = this.db
.prepare("UPDATE spaces SET sync_status = ? WHERE id = ? AND deleted_at IS NULL")
.run(status, id);
@@ -2665,6 +2963,9 @@ class DatabaseManager {
upsertSpaceFromCloud(space) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.activeAccountId) {
+ throw new Error("Cannot cache a cloud space without an active account scope");
+ }
const updatedAt = space.updated_at || space.created_at || new Date().toISOString();
const teams = Array.isArray(space.teams) ? space.teams : [];
const teamsJson = JSON.stringify(teams);
@@ -2694,6 +2995,9 @@ class DatabaseManager {
updatedAt,
existing.id
);
+ this.db
+ .prepare("INSERT OR IGNORE INTO space_accounts (space_id, account_id) VALUES (?, ?)")
+ .run(existing.id, this.activeAccountId);
return this._spaceRow(
this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(existing.id)
);
@@ -2721,6 +3025,9 @@ class DatabaseManager {
space.created_at || updatedAt,
updatedAt
);
+ this.db
+ .prepare("INSERT OR IGNORE INTO space_accounts (space_id, account_id) VALUES (?, ?)")
+ .run(result.lastInsertRowid, this.activeAccountId);
return this._spaceRow(
this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(result.lastInsertRowid)
);
@@ -2788,11 +3095,23 @@ class DatabaseManager {
return { success: false, error: "Invalid purge mode" };
}
const destructive = mode === "destructive";
- const space = this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(localSpaceId);
+ const space = this.getSpace(localSpaceId);
if (!space) return { success: false, error: "Space not found" };
if (space.kind === "private") {
return { success: false, error: "Cannot purge the private space" };
}
+ if (this._releaseActiveSpaceMembershipIfShared(localSpaceId)) {
+ return {
+ success: true,
+ noteIds: [],
+ folderNames: [],
+ spaceId: localSpaceId,
+ relocatedNotes: [],
+ relocatedCount: 0,
+ relocatedTitles: [],
+ preservedForOtherAccounts: true,
+ };
+ }
if (!destructive) {
// Space revocation supersedes any unresolved folder delete. Recover
// the held rows first so dirty/local-only children are classified by
@@ -3034,10 +3353,13 @@ class DatabaseManager {
if (!this.db) {
throw new Error("Database not initialized");
}
+ const accountScope = this._accountScopeCondition("notes");
const stmt = this.db.prepare(
- "UPDATE notes SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now') WHERE id = ? AND deleted_at IS NULL"
+ `UPDATE notes
+ SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now')
+ WHERE id = ? AND deleted_at IS NULL AND ${accountScope.sql}`
);
- const result = stmt.run(id);
+ const result = stmt.run(id, ...accountScope.params);
return { success: result.changes > 0, id };
} catch (error) {
debugLogger.error("Error deleting note", { error: error.message }, "notes");
@@ -3054,34 +3376,22 @@ class DatabaseManager {
let folder = null;
if (noteId != null) {
- note = this.db
- .prepare(
- `SELECT n.id, n.space_id, n.folder_id
- FROM notes n
- JOIN spaces s ON s.id = n.space_id AND s.deleted_at IS NULL
- LEFT JOIN folders f ON f.id = n.folder_id AND f.deleted_at IS NULL
- WHERE n.id = ? AND n.deleted_at IS NULL
- AND (n.folder_id IS NULL OR (f.id IS NOT NULL AND f.space_id = n.space_id))`
- )
- .get(noteId);
- if (!note) return null;
+ note = this.getNote(noteId);
+ if (!note || note.deleted_at) return null;
+ if (note.folder_id != null) {
+ const noteFolder = this._getFolderInAccountScope(note.folder_id);
+ if (!noteFolder || noteFolder.deleted_at || noteFolder.space_id !== note.space_id) {
+ return null;
+ }
+ }
}
if (spaceId != null) {
- space = this.db
- .prepare("SELECT id FROM spaces WHERE id = ? AND deleted_at IS NULL")
- .get(spaceId);
+ space = this.getSpace(spaceId);
if (!space) return null;
}
if (folderId != null) {
- folder = this.db
- .prepare(
- `SELECT f.id, f.space_id
- FROM folders f
- JOIN spaces s ON s.id = f.space_id AND s.deleted_at IS NULL
- WHERE f.id = ? AND f.deleted_at IS NULL`
- )
- .get(folderId);
- if (!folder) return null;
+ folder = this._getFolderInAccountScope(folderId);
+ if (!folder || folder.deleted_at || !this.getSpace(folder.space_id)) return null;
}
if (folder && spaceId != null && folder.space_id !== spaceId) return null;
if (note && spaceId != null && note.space_id !== spaceId) return null;
@@ -3106,6 +3416,7 @@ class DatabaseManager {
getConversationsForNote(noteId, limit = 20) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(noteId)) return [];
return this.db
.prepare(
`SELECT c.id, c.title, c.created_at, c.updated_at,
@@ -3133,6 +3444,12 @@ class DatabaseManager {
getConversationsForContainer(spaceId, folderId = null, limit = 20) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (folderId != null) {
+ const folder = this._getFolderInAccountScope(folderId);
+ if (!folder || folder.deleted_at) return [];
+ } else if (!this.getSpace(spaceId)) {
+ return [];
+ }
const scopeFilter =
folderId != null ? "c.folder_id = ?" : "c.space_id = ? AND c.folder_id IS NULL";
const params = folderId != null ? [folderId, limit] : [spaceId, limit];
@@ -3520,7 +3837,8 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
const ftsQuery = buildNoteSearchQuery(query);
if (!ftsQuery) return [];
- const params = [ftsQuery];
+ const accountScope = this._accountScopeCondition("n");
+ const params = [ftsQuery, ...accountScope.params];
let scopeFilter = "";
if (spaceId != null) {
scopeFilter += " AND n.space_id = ?";
@@ -3537,7 +3855,7 @@ class DatabaseManager {
SELECT n.*
FROM notes n
JOIN notes_fts ON notes_fts.rowid = n.id
- WHERE notes_fts MATCH ? AND n.deleted_at IS NULL${scopeFilter}
+ WHERE notes_fts MATCH ? AND n.deleted_at IS NULL AND ${accountScope.sql}${scopeFilter}
ORDER BY notes_fts.rank
LIMIT ?
`
@@ -3623,11 +3941,18 @@ class DatabaseManager {
getNoteByCalendarEventId(eventId, excludeNoteId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
- const base = "SELECT * FROM notes WHERE calendar_event_id = ? AND deleted_at IS NULL";
+ const accountScope = this._accountScopeCondition("notes");
+ const base = `SELECT * FROM notes
+ WHERE calendar_event_id = ? AND deleted_at IS NULL
+ AND ${accountScope.sql}`;
if (excludeNoteId) {
- return this.db.prepare(`${base} AND id != ? LIMIT 1`).get(eventId, excludeNoteId) || null;
+ return (
+ this.db
+ .prepare(`${base} AND id != ? LIMIT 1`)
+ .get(eventId, ...accountScope.params, excludeNoteId) || null
+ );
}
- return this.db.prepare(`${base} LIMIT 1`).get(eventId) || null;
+ return this.db.prepare(`${base} LIMIT 1`).get(eventId, ...accountScope.params) || null;
} catch (error) {
debugLogger.error(
"Error getting note by calendar event id",
@@ -4037,12 +4362,15 @@ class DatabaseManager {
getMeetingsFolder(spaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("folders");
return (
this.db
.prepare(
- "SELECT id FROM folders WHERE name = 'Meetings' AND is_default = 1 AND space_id = ?"
+ `SELECT id FROM folders
+ WHERE name = 'Meetings' AND is_default = 1 AND space_id = ?
+ AND ${accountScope.sql}`
)
- .get(spaceId ?? this.getPrivateSpaceId()) || null
+ .get(spaceId ?? this.getPrivateSpaceId(), ...accountScope.params) || null
);
} catch (error) {
debugLogger.error("Error getting meetings folder", { error: error.message }, "gcal");
@@ -4053,6 +4381,7 @@ class DatabaseManager {
updateNoteCloudId(id, cloudId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return null;
this.db.prepare("UPDATE notes SET cloud_id = ? WHERE id = ?").run(cloudId, id);
return this.db.prepare("SELECT * FROM notes WHERE id = ?").get(id);
} catch (error) {
@@ -4066,6 +4395,7 @@ class DatabaseManager {
updateNoteShareState(id, { is_shared, share_token }) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return null;
if (share_token !== undefined) {
this.db
.prepare("UPDATE notes SET is_shared = ?, share_token = ? WHERE id = ?")
@@ -4383,6 +4713,7 @@ class DatabaseManager {
setSpeakerMapping(noteId, speakerId, profileId, displayName) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(noteId)) return { success: false, error: "Note not found" };
this.db
.prepare(
"INSERT OR REPLACE INTO speaker_mappings (note_id, speaker_id, profile_id, display_name) VALUES (?, ?, ?, ?)"
@@ -4398,6 +4729,7 @@ class DatabaseManager {
getSpeakerMappings(noteId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(noteId)) return [];
return this.db.prepare("SELECT * FROM speaker_mappings WHERE note_id = ?").all(noteId);
} catch (error) {
debugLogger.error("Error getting speaker mappings", { error: error.message }, "database");
@@ -4408,6 +4740,7 @@ class DatabaseManager {
saveNoteSpeakerEmbeddings(noteId, embeddings) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(noteId)) return { success: false, error: "Note not found" };
const transaction = this.db.transaction((entries) => {
const stmt = this.db.prepare(
"INSERT OR REPLACE INTO note_speaker_embeddings (note_id, speaker_id, embedding) VALUES (?, ?, ?)"
@@ -4431,6 +4764,7 @@ class DatabaseManager {
getNoteSpeakerEmbeddings(noteId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(noteId)) return [];
return this.db.prepare("SELECT * FROM note_speaker_embeddings WHERE note_id = ?").all(noteId);
} catch (error) {
debugLogger.error(
@@ -4445,6 +4779,7 @@ class DatabaseManager {
getPendingNotes(spaceKind = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("n");
if (spaceKind != null) {
// 'team' also returns cloud-backed rows that just LEFT a team: their
// scope retraction must push even when cloud backup is off (D6).
@@ -4452,17 +4787,21 @@ class DatabaseManager {
spaceKind === "team" ? " OR (n.left_team = 1 AND n.cloud_id IS NOT NULL)" : "";
return this.db
.prepare(
- `SELECT n.* FROM notes n JOIN spaces s ON s.id = n.space_id WHERE n.sync_status IN ('pending', 'error') AND n.deleted_at IS NULL AND (s.kind = ?${leftTeam})`
+ `SELECT n.* FROM notes n JOIN spaces s ON s.id = n.space_id
+ WHERE n.sync_status IN ('pending', 'error') AND n.deleted_at IS NULL
+ AND ${accountScope.sql} AND (s.kind = ?${leftTeam})`
)
- .all(spaceKind);
+ .all(...accountScope.params, spaceKind);
}
// 'error' rows retry too: a transient failure (e.g. one offline pass)
// must not strand a note until its next local edit.
return this.db
.prepare(
- "SELECT * FROM notes WHERE sync_status IN ('pending', 'error') AND deleted_at IS NULL"
+ `SELECT n.* FROM notes n
+ WHERE n.sync_status IN ('pending', 'error') AND n.deleted_at IS NULL
+ AND ${accountScope.sql}`
)
- .all();
+ .all(...accountScope.params);
} catch (error) {
debugLogger.error("Error getting pending notes", { error: error.message }, "database");
throw error;
@@ -4472,17 +4811,19 @@ class DatabaseManager {
getPendingNoteDeletes() {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("n");
return this.db
.prepare(
`SELECT * FROM notes n
WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL
AND sync_status = 'pending'
+ AND ${accountScope.sql}
AND NOT EXISTS (
SELECT 1 FROM optimistic_folder_delete_rows r
WHERE r.entity_type = 'note' AND r.entity_id = n.id
)`
)
- .all();
+ .all(...accountScope.params);
} catch (error) {
debugLogger.error("Error getting pending note deletes", { error: error.message }, "database");
throw error;
@@ -4492,6 +4833,7 @@ class DatabaseManager {
getNoteByClientId(clientNoteId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("n");
return (
this.db
.prepare(
@@ -4501,9 +4843,9 @@ class DatabaseManager {
WHERE r.entity_type = 'note' AND r.entity_id = n.id
) AS folder_delete_pending
FROM notes n
- WHERE n.client_note_id = ?`
+ WHERE n.client_note_id = ? AND ${accountScope.sql}`
)
- .get(clientNoteId) || null
+ .get(clientNoteId, ...accountScope.params) || null
);
} catch (error) {
debugLogger.error("Error getting note by client id", { error: error.message }, "database");
@@ -4514,6 +4856,25 @@ class DatabaseManager {
upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const spaceId = localSpaceId ?? this.getPrivateSpaceId();
+ const accountId = this._accountIdForSpace(spaceId);
+ const hasExplicitCreator = Object.prototype.hasOwnProperty.call(
+ cloudNote,
+ "created_by_user_id"
+ );
+ const hasLegacyCreator = Object.prototype.hasOwnProperty.call(cloudNote, "user_id");
+ const createdByUserId = hasExplicitCreator ? cloudNote.created_by_user_id : cloudNote.user_id;
+ const creatorUpdate =
+ hasExplicitCreator || hasLegacyCreator
+ ? "excluded.created_by_user_id"
+ : "created_by_user_id";
+ const hasExplicitUpdater = Object.prototype.hasOwnProperty.call(
+ cloudNote,
+ "updated_by_user_id"
+ );
+ const updaterUpdate = hasExplicitUpdater
+ ? "excluded.updated_by_user_id"
+ : "updated_by_user_id";
// Sync must never replace non-empty local content/enhanced_content/
// transcript with an empty cloud value (#1290, the #938 invariant).
// The enhancement prompt/hash travel with enhanced_content.
@@ -4521,9 +4882,9 @@ class DatabaseManager {
INSERT INTO notes (client_note_id, cloud_id, title, content, enhanced_content,
enhancement_prompt, enhanced_at_content_hash, note_type, source_file,
audio_duration_seconds, transcript, folder_id, space_id, participants, calendar_event_id,
- diarization_enabled, expected_speaker_count, updated_by_user_id, owner_user_id, sync_status, created_at, updated_at,
- cloud_updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?, ?)
+ diarization_enabled, expected_speaker_count, updated_by_user_id, owner_user_id, created_by_user_id, sync_status, created_at, updated_at,
+ cloud_updated_at, account_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?, ?, ?)
ON CONFLICT(client_note_id) DO UPDATE SET
cloud_id = excluded.cloud_id,
title = excluded.title,
@@ -4544,12 +4905,14 @@ class DatabaseManager {
THEN transcript ELSE excluded.transcript END,
folder_id = excluded.folder_id,
space_id = excluded.space_id,
+ account_id = excluded.account_id,
participants = COALESCE(excluded.participants, participants),
calendar_event_id = COALESCE(excluded.calendar_event_id, calendar_event_id),
diarization_enabled = COALESCE(excluded.diarization_enabled, diarization_enabled),
expected_speaker_count = COALESCE(excluded.expected_speaker_count, expected_speaker_count),
- updated_by_user_id = COALESCE(excluded.updated_by_user_id, updated_by_user_id),
+ updated_by_user_id = ${updaterUpdate},
owner_user_id = COALESCE(excluded.owner_user_id, owner_user_id),
+ created_by_user_id = ${creatorUpdate},
sync_status = 'synced',
left_team = 0,
updated_at = excluded.updated_at,
@@ -4568,16 +4931,18 @@ class DatabaseManager {
cloudNote.audio_duration_seconds || null,
cloudNote.transcript || null,
localFolderId,
- localSpaceId ?? this.getPrivateSpaceId(),
+ spaceId,
cloudNote.participants || null,
cloudNote.calendar_event_id || null,
cloudNote.diarization_enabled ?? null,
normalizeStoredSpeakerCount(cloudNote.expected_speaker_count),
cloudNote.updated_by_user_id || null,
- cloudNote.user_id || null,
+ cloudNote.user_id ?? null,
+ createdByUserId ?? null,
cloudNote.created_at,
cloudNote.updated_at,
- cloudNote.updated_at
+ cloudNote.updated_at,
+ accountId
);
return this.db
.prepare("SELECT * FROM notes WHERE client_note_id = ?")
@@ -4591,6 +4956,7 @@ class DatabaseManager {
markNoteSynced(id, cloudId, cloudUpdatedAt = null, ownerUserId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return { success: false, changes: 0 };
// cloud_updated_at and owner_user_id are overwritten even with null: a
// forked row that re-creates under a new cloud_id must not keep the old
// note's base or its previous owner (a null base settles last-write-wins
@@ -4635,6 +5001,9 @@ class DatabaseManager {
) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) {
+ return { success: true, outcome: "identity-changed", changes: 0 };
+ }
const expectedClientNoteId = snapshot?.client_note_id;
if (!expectedClientNoteId || !cloudId) {
return { success: false, outcome: "unresolved" };
@@ -4716,6 +5085,9 @@ class DatabaseManager {
) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) {
+ return { success: true, outcome: "identity-changed", changes: 0 };
+ }
if (!snapshot?.client_note_id || !expectedCloudId) {
return { success: false, outcome: "identity-changed", changes: 0 };
}
@@ -4787,6 +5159,7 @@ class DatabaseManager {
setNoteOwnerFromCloud(id, ownerUserId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return { success: false };
this.db.prepare("UPDATE notes SET owner_user_id = ? WHERE id = ?").run(ownerUserId, id);
return { success: true };
} catch (error) {
@@ -4804,14 +5177,16 @@ class DatabaseManager {
countTeamNotesMissingOwner() {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("n");
const row = this.db
.prepare(
`SELECT COUNT(*) AS count FROM notes n
JOIN spaces s ON s.id = n.space_id
WHERE s.kind = 'team' AND n.deleted_at IS NULL
- AND n.cloud_id IS NOT NULL AND n.owner_user_id IS NULL`
+ AND n.cloud_id IS NOT NULL AND n.owner_user_id IS NULL
+ AND ${accountScope.sql}`
)
- .get();
+ .get(...accountScope.params);
return row?.count ?? 0;
} catch (error) {
debugLogger.error(
@@ -4829,6 +5204,7 @@ class DatabaseManager {
setNoteCloudBase(id, cloudUpdatedAt) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return { success: false };
this.db.prepare("UPDATE notes SET cloud_updated_at = ? WHERE id = ?").run(cloudUpdatedAt, id);
return { success: true };
} catch (error) {
@@ -4840,6 +5216,7 @@ class DatabaseManager {
markNoteSyncError(id) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return { success: false };
this.db.prepare("UPDATE notes SET sync_status = 'error' WHERE id = ?").run(id);
return { success: true };
} catch (error) {
@@ -4855,14 +5232,15 @@ class DatabaseManager {
restoreNoteAfterDeniedDelete(id) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("notes");
const result = this.db
.prepare(
`UPDATE notes
SET deleted_at = NULL, sync_status = 'synced',
updated_at = '1970-01-01 00:00:00'
- WHERE id = ? AND deleted_at IS NOT NULL`
+ WHERE id = ? AND deleted_at IS NOT NULL AND ${accountScope.sql}`
)
- .run(id);
+ .run(id, ...accountScope.params);
return { success: result.changes > 0, id };
} catch (error) {
debugLogger.error(
@@ -4879,6 +5257,7 @@ class DatabaseManager {
hardDeleteNote(id) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(id)) return { success: false, id, error: "Note not found" };
const result = this.db.transaction(() => {
this._retireConversationsWhere("note_id = ?", [id], {
scrubSyncedMessages: true,
@@ -4896,6 +5275,7 @@ class DatabaseManager {
getPendingFolders(spaceKind = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("f");
if (spaceKind != null) {
// 'team' also returns cloud-backed rows that just LEFT a team: their
// scope retraction must push even when cloud backup is off (D6).
@@ -4903,13 +5283,21 @@ class DatabaseManager {
spaceKind === "team" ? " OR (f.left_team = 1 AND f.cloud_id IS NOT NULL)" : "";
return this.db
.prepare(
- `SELECT f.* FROM folders f JOIN spaces s ON s.id = f.space_id WHERE f.sync_status = 'pending' AND f.deleted_at IS NULL AND (s.kind = ?${leftTeam})`
+ `SELECT f.* FROM folders f JOIN spaces s ON s.id = f.space_id
+ WHERE f.sync_status = 'pending' AND f.deleted_at IS NULL
+ AND ${accountScope.sql} AND (s.kind = ?${leftTeam})
+ ORDER BY f.space_id, f.name`
)
- .all(spaceKind);
+ .all(...accountScope.params, spaceKind);
}
return this.db
- .prepare("SELECT * FROM folders WHERE sync_status = 'pending' AND deleted_at IS NULL")
- .all();
+ .prepare(
+ `SELECT f.* FROM folders f
+ WHERE f.sync_status = 'pending' AND f.deleted_at IS NULL
+ AND ${accountScope.sql}
+ ORDER BY f.space_id, f.name`
+ )
+ .all(...accountScope.params);
} catch (error) {
debugLogger.error("Error getting pending folders", { error: error.message }, "database");
throw error;
@@ -4919,16 +5307,18 @@ class DatabaseManager {
getPendingFolderDeletes() {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("f");
return this.db
.prepare(
`SELECT * FROM folders f
WHERE deleted_at IS NOT NULL AND cloud_id IS NOT NULL
+ AND ${accountScope.sql}
AND (sync_status = 'pending' OR EXISTS (
SELECT 1 FROM optimistic_folder_delete_rows r
WHERE r.folder_id = f.id AND r.entity_type = 'folder'
))`
)
- .all();
+ .all(...accountScope.params);
} catch (error) {
debugLogger.error(
"Error getting pending folder deletes",
@@ -4945,6 +5335,9 @@ class DatabaseManager {
restoreFolderAfterDeniedDelete(id) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this._getFolderInAccountScope(id)) {
+ return { success: false, id, error: "Folder not found" };
+ }
return this.db.transaction(() => {
const journalRows = this.db
.prepare(
@@ -5052,18 +5445,21 @@ class DatabaseManager {
hardDeleteFolder(id) {
try {
if (!this.db) throw new Error("Database not initialized");
- const folder = this.db.prepare("SELECT name FROM folders WHERE id = ?").get(id);
+ const folder = this._getFolderInAccountScope(id);
if (!folder) return { success: false, id, error: "Folder not found" };
const childNotes = "SELECT id FROM notes WHERE folder_id = ?";
const heldNotes =
"SELECT entity_id FROM optimistic_folder_delete_rows WHERE folder_id = ? AND entity_type = 'note'";
const heldConversations =
"SELECT entity_id FROM optimistic_folder_delete_rows WHERE folder_id = ? AND entity_type = 'conversation'";
+ const accountScope = this._accountScopeCondition("notes");
const noteIds = this.db
- .prepare(childNotes)
- .all(id)
+ .prepare(`${childNotes} AND ${accountScope.sql}`)
+ .all(id, ...accountScope.params)
.map((row) => row.id);
+ let relocatedNotes = [];
const result = this.db.transaction(() => {
+ relocatedNotes = this._releaseOutOfScopeChildNotes(id);
// Note chats normally have note_id only. Retire them while the child
// rows still identify which chats belong to this folder cleanup, then
// handle independently folder-scoped conversations.
@@ -5107,7 +5503,13 @@ class DatabaseManager {
this.db.prepare("DELETE FROM optimistic_folder_delete_rows WHERE folder_id = ?").run(id);
return deleted;
})();
- return { success: result.changes > 0, id, noteIds, name: folder?.name ?? null };
+ return {
+ success: result.changes > 0,
+ id,
+ noteIds,
+ relocatedNotes,
+ name: folder?.name ?? null,
+ };
} catch (error) {
debugLogger.error("Error hard deleting folder", { error: error.message }, "database");
throw error;
@@ -5126,6 +5528,9 @@ class DatabaseManager {
relocateRevokedFolder(id, privateSpaceId, preserveFolder = false) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this._getFolderInAccountScope(id)) {
+ return { success: false, error: "Folder not found" };
+ }
// If access revocation overtakes an optimistic delete, first recover the
// held rows so the normal dirty-note preservation rules can classify
// them from their real pre-delete state.
@@ -5216,9 +5621,11 @@ class DatabaseManager {
getFolderByClientId(clientFolderId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("folders");
return (
- this.db.prepare("SELECT * FROM folders WHERE client_folder_id = ?").get(clientFolderId) ||
- null
+ this.db
+ .prepare(`SELECT * FROM folders WHERE client_folder_id = ? AND ${accountScope.sql}`)
+ .get(clientFolderId, ...accountScope.params) || null
);
} catch (error) {
debugLogger.error("Error getting folder by client id", { error: error.message }, "database");
@@ -5230,15 +5637,17 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
const spaceId = localSpaceId ?? this.getPrivateSpaceId();
+ const accountId = this._accountIdForSpace(spaceId);
const updatedAt = cloudFolder.updated_at || cloudFolder.created_at;
const stmt = this.db.prepare(`
- INSERT INTO folders (client_folder_id, cloud_id, name, is_default, sort_order, space_id, sync_status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, 'synced', ?, ?)
+ INSERT INTO folders (client_folder_id, cloud_id, name, is_default, sort_order, space_id, account_id, sync_status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?)
ON CONFLICT(client_folder_id) DO UPDATE SET
cloud_id = excluded.cloud_id,
name = excluded.name,
sort_order = excluded.sort_order,
space_id = excluded.space_id,
+ account_id = excluded.account_id,
sync_status = 'synced',
left_team = 0,
updated_at = excluded.updated_at
@@ -5251,6 +5660,7 @@ class DatabaseManager {
cloudFolder.is_default ? 1 : 0,
cloudFolder.sort_order || 0,
spaceId,
+ accountId,
cloudFolder.created_at,
updatedAt
);
@@ -5266,8 +5676,10 @@ class DatabaseManager {
throw err;
}
const existing = this.db
- .prepare("SELECT id FROM folders WHERE space_id = ? AND name = ? AND deleted_at IS NULL")
- .get(spaceId, cloudFolder.name);
+ .prepare(
+ "SELECT id FROM folders WHERE space_id = ? AND name = ? AND account_id IS ? AND deleted_at IS NULL"
+ )
+ .get(spaceId, cloudFolder.name, accountId);
if (!existing) throw err;
this.db.transaction(() => {
const holder = this.db
@@ -5302,6 +5714,7 @@ class DatabaseManager {
markFolderSynced(id, cloudId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this._getFolderInAccountScope(id)) return { success: false };
this.db
.prepare(
"UPDATE folders SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ?"
@@ -5329,6 +5742,9 @@ class DatabaseManager {
) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this._getFolderInAccountScope(id)) {
+ return { success: true, outcome: "identity-changed", changes: 0 };
+ }
if (
!snapshot?.client_folder_id ||
(expectedCloudId !== null && typeof expectedCloudId !== "string") ||
@@ -5408,6 +5824,9 @@ class DatabaseManager {
markFolderSyncedIfUnchanged(id, snapshot, expectedCloudId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this._getFolderInAccountScope(id)) {
+ return { success: true, outcome: "identity-changed", changes: 0 };
+ }
if (!snapshot?.client_folder_id || !expectedCloudId) {
return { success: false, outcome: "identity-changed", changes: 0 };
}
@@ -5449,6 +5868,7 @@ class DatabaseManager {
forkFolderIdentity(id) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this._getFolderInAccountScope(id)) return { success: false };
const result = this.db
.prepare(
"UPDATE folders SET client_folder_id = ?, cloud_id = NULL, sync_status = 'pending', left_team = 0 WHERE id = ?"
@@ -5464,7 +5884,10 @@ class DatabaseManager {
getFolderIdMap() {
try {
if (!this.db) throw new Error("Database not initialized");
- return this.db.prepare("SELECT * FROM folders WHERE deleted_at IS NULL").all();
+ const accountScope = this._accountScopeCondition("folders");
+ return this.db
+ .prepare(`SELECT * FROM folders WHERE deleted_at IS NULL AND ${accountScope.sql}`)
+ .all(...accountScope.params);
} catch (error) {
debugLogger.error("Error getting folder id map", { error: error.message }, "database");
throw error;
@@ -5831,14 +6254,16 @@ class DatabaseManager {
getNotesWithUnmappedSpeakers() {
try {
if (!this.db) throw new Error("Database not initialized");
+ const accountScope = this._accountScopeCondition("notes");
return this.db
.prepare(
`SELECT DISTINCT nse.note_id
FROM note_speaker_embeddings nse
+ JOIN notes ON notes.id = nse.note_id
LEFT JOIN speaker_mappings sm ON nse.note_id = sm.note_id AND nse.speaker_id = sm.speaker_id
- WHERE sm.note_id IS NULL`
+ WHERE sm.note_id IS NULL AND ${accountScope.sql}`
)
- .all()
+ .all(...accountScope.params)
.map((row) => row.note_id);
} catch (error) {
debugLogger.error(
@@ -5853,6 +6278,7 @@ class DatabaseManager {
removeSpeakerMapping(noteId, speakerId) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (!this.getNote(noteId)) return { success: false };
this.db
.prepare("DELETE FROM speaker_mappings WHERE note_id = ? AND speaker_id = ?")
.run(noteId, speakerId);
diff --git a/src/helpers/environment.js b/src/helpers/environment.js
index a01651c10..bbb960a5f 100644
--- a/src/helpers/environment.js
+++ b/src/helpers/environment.js
@@ -503,6 +503,19 @@ class EnvironmentManager {
return { success: true, path: envPath };
}
+ async clearAllPersistedData() {
+ for (const envVarName of PERSISTED_KEYS) {
+ delete process.env[envVarName];
+ }
+ delete process.env.CUSTOM_REASONING_API_KEY;
+
+ await Promise.all([
+ fsPromises.rm(path.join(app.getPath("userData"), ".env"), { force: true }),
+ fsPromises.rm(this._getSecureKeysDir(), { recursive: true, force: true }),
+ ]);
+ return { success: true };
+ }
+
// Removes a single key's line from .env, preserving every other line
// verbatim. saveAllKeysToEnvFile() would instead regenerate the file from
// PERSISTED_KEYS, dropping hand-added lines (e.g. OPENWHISPR_LOG_LEVEL) and
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 4a8dfd797..c10cb38b0 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -10,6 +10,7 @@ const { openExternalUrl } = require("./externalUrlOpener");
const { resolveFailedGpuBackends } = require("./whisper");
const { BYOK_API_KEYS } = require("../config/secretKeys");
const tokenStore = require("./tokenStore");
+const accountScopeBinding = require("./accountScopeBinding");
const { createCloudApiRequestHandler } = require("./cloudApiRequest");
const { withPolicyRequestHeaders } = require("./policyRequestHeaders");
const {
@@ -577,6 +578,7 @@ class IPCHandlers {
this.linuxPortalAudioManager = managers.linuxPortalAudioManager;
this.windowsLoopbackAudioManager = managers.windowsLoopbackAudioManager;
this.meetingAecManager = managers.meetingAecManager;
+ this.getQdrantManager = managers.getQdrantManager;
this.oauthProtocolRegistered = managers.oauthProtocolRegistered === true;
this.oauthProtocol = managers.oauthProtocol || "openwhispr";
this.sessionId = crypto.randomUUID();
@@ -627,6 +629,10 @@ class IPCHandlers {
// Lives for the app's lifetime; IPCHandlers has no teardown path.
tokenStore.subscribe(({ generation, token }) => {
this.enterpriseIdentityManager?.clear();
+ if (!token) {
+ this.databaseManager.setActiveAccountId(null);
+ accountScopeBinding.clear();
+ }
broadcastToWindows("auth-token-state-changed", {
generation,
hasToken: Boolean(token),
@@ -1872,6 +1878,11 @@ class IPCHandlers {
for (const noteId of result.noteIds ?? []) {
this._asyncVectorDelete(noteId);
}
+ // Other accounts' notes were released to the space root; their mirror
+ // files leave with the folder directory, so rewrite the live ones.
+ for (const note of result.relocatedNotes ?? []) {
+ if (!note.deleted_at) this._asyncMirrorWrite(note);
+ }
setImmediate(() => {
broadcastToWindows("folder-deleted", { id });
if (folderName) this._mirrorDeleteFolderIfUnshared(folderName);
@@ -1917,6 +1928,56 @@ class IPCHandlers {
return this.databaseManager.getSpaces();
});
+ ipcMain.handle("set-active-account-scope", async (_event, accountId, expectedGeneration) => {
+ const state = tokenStore.getState();
+ const verdict = accountScopeBinding.evaluateScopeRequest({
+ accountId,
+ expectedGeneration,
+ token: state.token,
+ generation: state.generation,
+ });
+ if (!verdict.ok) {
+ return {
+ success: false,
+ code: verdict.code,
+ error:
+ verdict.code === "INVALID_ACCOUNT"
+ ? "Invalid account scope"
+ : "Authentication context changed before account scoping",
+ };
+ }
+ this.databaseManager.setActiveAccountId(accountId);
+ if (accountId !== null) accountScopeBinding.persist(accountId, state.token);
+ else accountScopeBinding.clear();
+ return { success: true };
+ });
+
+ ipcMain.handle("delete-account-data", async (_event, accountId, expectedGeneration) => {
+ const state = tokenStore.getState();
+ if (
+ typeof accountId !== "string" ||
+ accountId.trim().length === 0 ||
+ !state.token ||
+ state.generation !== expectedGeneration
+ ) {
+ return {
+ success: false,
+ code: "AUTH_CONTEXT_CHANGED",
+ error: "Authentication context changed before local account cleanup",
+ };
+ }
+ try {
+ const result = this.databaseManager.deleteAccountData(accountId);
+ for (const noteId of result.deletedNoteIds) {
+ this._asyncVectorDelete(noteId);
+ this._asyncMirrorDelete(noteId);
+ }
+ return { success: true, ...result };
+ } catch (error) {
+ return { success: false, code: "LOCAL_ACCOUNT_CLEANUP_FAILED", error: error.message };
+ }
+ });
+
ipcMain.handle("db-update-space", async (event, id, updates) => {
const result = this.databaseManager.updateSpace(id, updates);
if (result?.success && result.space) {
@@ -1938,14 +1999,16 @@ class IPCHandlers {
}
const result = this.databaseManager.purgeSpace(id, options);
if (result?.success) {
- this.databaseManager.addPendingVectorPurge(result.spaceId);
- this.drainPendingVectorPurges();
- for (const note of result.relocatedNotes ?? []) {
- this._asyncVectorUpsert(note);
- this._asyncMirrorWrite(note);
- }
- for (const noteId of result.noteIds ?? []) {
- this._asyncMirrorDelete(noteId);
+ if (!result.preservedForOtherAccounts) {
+ this.databaseManager.addPendingVectorPurge(result.spaceId);
+ this.drainPendingVectorPurges();
+ for (const note of result.relocatedNotes ?? []) {
+ this._asyncVectorUpsert(note);
+ this._asyncMirrorWrite(note);
+ }
+ for (const noteId of result.noteIds ?? []) {
+ this._asyncMirrorDelete(noteId);
+ }
}
setImmediate(() => {
broadcastToWindows("space-purged", { spaceId: result.spaceId });
@@ -2228,6 +2291,11 @@ class IPCHandlers {
for (const noteId of result.noteIds ?? []) {
this._asyncVectorDelete(noteId);
}
+ // Other accounts' notes were released to the space root; their mirror
+ // files leave with the folder directory, so rewrite the live ones.
+ for (const note of result.relocatedNotes ?? []) {
+ if (!note.deleted_at) this._asyncMirrorWrite(note);
+ }
setImmediate(() => {
broadcastToWindows("folder-deleted", { id });
if (result.name) this._mirrorDeleteFolderIfUnshared(result.name);
@@ -3436,6 +3504,22 @@ class IPCHandlers {
} catch (e) {
errors.push(`ACal stop: ${e.message}`);
}
+ try {
+ await this.diarizationManager?.shutdown();
+ } catch (e) {
+ errors.push(`Diarization stop: ${e.message}`);
+ }
+ try {
+ await this.getQdrantManager?.()?.stop();
+ } catch (e) {
+ errors.push(`Vector index stop: ${e.message}`);
+ }
+ try {
+ const onnxWorkerClient = require("./onnxWorkerClient");
+ await onnxWorkerClient.stop();
+ } catch (e) {
+ errors.push(`Embedding worker stop: ${e.message}`);
+ }
// Revoke Google OAuth tokens before DB is closed
try {
@@ -3471,6 +3555,11 @@ class IPCHandlers {
} catch (e) {
errors.push(`Parakeet models: ${e.message}`);
}
+ try {
+ await this.diarizationManager?.deleteModels();
+ } catch (e) {
+ errors.push(`Diarization models: ${e.message}`);
+ }
try {
const modelManager = require("./modelManagerBridge").default;
await modelManager.deleteAllModels();
@@ -3478,6 +3567,17 @@ class IPCHandlers {
errors.push(`LLM models: ${e.message}`);
}
+ // These caches are not owned by one account. Remove them only through
+ // the explicit device-erasure path, never during normal account deletion.
+ const homeCacheRoot = path.join(os.homedir(), ".cache", "openwhispr");
+ for (const cacheName of ["embedding-models", "qdrant-data", "qdrant-data-dev", "yt-dlp"]) {
+ try {
+ fs.rmSync(path.join(homeCacheRoot, cacheName), { recursive: true, force: true });
+ } catch (e) {
+ errors.push(`${cacheName} cache: ${e.message}`);
+ }
+ }
+
// Delete database file + WAL/SHM
try {
const dbPath = path.join(
@@ -3491,20 +3591,62 @@ class IPCHandlers {
errors.push(`DB file: ${e.message}`);
}
- // Delete .env file
+ // Delete device-wide settings and encrypted credentials.
try {
- const envPath = path.join(app.getPath("userData"), ".env");
- if (fs.existsSync(envPath)) fs.unlinkSync(envPath);
+ await this.environmentManager?.clearAllPersistedData();
+ } catch (e) {
+ errors.push(`Environment settings: ${e.message}`);
+ }
+ try {
+ const tokenCleanup = tokenStore.clear();
+ if (!tokenCleanup.success) throw new Error("Could not clear the stored bearer token");
+ } catch (e) {
+ errors.push(`Authentication token: ${e.message}`);
+ }
+ try {
+ this.enterpriseIdentityManager?.clear();
} catch (e) {
- errors.push(`Env file: ${e.message}`);
+ errors.push(`Enterprise settings: ${e.message}`);
+ }
+ try {
+ for (const fileName of [
+ "workspace-policy.json",
+ "managed-enterprise-config.json",
+ "globe-preference-state.json",
+ ".system-audio-permission",
+ "account-scope-binding.json",
+ ]) {
+ fs.rmSync(path.join(app.getPath("userData"), fileName), { force: true });
+ }
+ } catch (e) {
+ errors.push(`Device setting files: ${e.message}`);
+ }
+ for (const directoryName of ["bin", "llama-cpp"]) {
+ try {
+ fs.rmSync(path.join(app.getPath("userData"), directoryName), {
+ recursive: true,
+ force: true,
+ });
+ } catch (e) {
+ errors.push(`${directoryName} runtime: ${e.message}`);
+ }
+ }
+ try {
+ autoStart.setAutoStartEnabled(false);
+ } catch (e) {
+ errors.push(`Launch at login: ${e.message}`);
}
- // Clear session cookies
+ // Clear browser-held account/session state, including cookies, IndexedDB,
+ // Cache Storage and localStorage persisted by any app window.
try {
const win = BrowserWindow.fromWebContents(event.sender);
- if (win) await win.webContents.session.clearStorageData({ storages: ["cookies"] });
+ if (win) {
+ await win.webContents.session.clearStorageData();
+ await win.webContents.session.clearCache();
+ }
} catch (e) {
- errors.push(`Cookies: ${e.message}`);
+ errors.push(`Browser data: ${e.message}`);
}
// Clear localStorage
diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts
index 966cef0cb..938f2fcea 100644
--- a/src/hooks/useAuth.ts
+++ b/src/hooks/useAuth.ts
@@ -161,26 +161,17 @@ export function useAuth() {
let cancelled = false;
const run = async () => {
const { syncService, resetRendererCaches } = await loadAccountDependencies();
+ const scopeResult = await window.electronAPI?.setActiveAccountScope?.(
+ resolvedUserId,
+ boundGeneration
+ );
+ if (!scopeResult?.success) {
+ throw new Error(scopeResult?.error ?? "Could not establish the local account scope");
+ }
const purgeCachedTeamContent = async () => {
resetRendererCaches();
- let lastError: unknown;
- for (let attempt = 0; attempt < 3; attempt += 1) {
- try {
- await syncService.purgeTeamSpacesForSignOut();
- const spaces = await window.electronAPI?.getSpaces?.();
- if (!spaces) {
- throw new Error("Cannot verify account cleanup: database bridge unavailable");
- }
- if (!spaces.some((space) => space.kind === "team")) {
- resetRendererCaches();
- return;
- }
- lastError = new Error("Team content remained after account cleanup");
- } catch (error) {
- lastError = error;
- }
- }
- throw lastError ?? new Error("Team content remained after account cleanup");
+ await syncService.purgeTeamSpacesForSignOut();
+ resetRendererCaches();
};
const verifyCachedTeamContent = async () => {
const purged = await syncService.verifyTeamSpacesForAccount(boundGeneration);
diff --git a/src/lib/accountDeletionFlow.ts b/src/lib/accountDeletionFlow.ts
new file mode 100644
index 000000000..0b325efba
--- /dev/null
+++ b/src/lib/accountDeletionFlow.ts
@@ -0,0 +1,57 @@
+export type LocalCleanupFailure =
+ "local-account-data" | "workspace-session-state" | "auth-session" | "device-data";
+
+export interface AccountDeletionDependencies {
+ deleteRemoteAccount: () => Promise<void>;
+ deleteLocalAccountData: () => Promise<void>;
+ clearWorkspaceSessionState: () => Promise<void>;
+ signOut: () => Promise<void>;
+ eraseDeviceData: () => Promise<void>;
+}
+
+export interface AccountDeletionResult {
+ localCleanupFailures: LocalCleanupFailure[];
+}
+
+interface ExecuteAccountDeletionOptions {
+ eraseDeviceData: boolean;
+ dependencies: AccountDeletionDependencies;
+}
+
+async function recordLocalFailure(
+ operation: () => Promise<void>,
+ failure: LocalCleanupFailure,
+ failures: LocalCleanupFailure[]
+): Promise<void> {
+ try {
+ await operation();
+ } catch {
+ failures.push(failure);
+ }
+}
+
+export async function executeAccountDeletion({
+ eraseDeviceData,
+ dependencies,
+}: ExecuteAccountDeletionOptions): Promise<AccountDeletionResult> {
+ await dependencies.deleteRemoteAccount();
+
+ const localCleanupFailures: LocalCleanupFailure[] = [];
+ await recordLocalFailure(
+ dependencies.deleteLocalAccountData,
+ "local-account-data",
+ localCleanupFailures
+ );
+ await recordLocalFailure(
+ dependencies.clearWorkspaceSessionState,
+ "workspace-session-state",
+ localCleanupFailures
+ );
+ await recordLocalFailure(dependencies.signOut, "auth-session", localCleanupFailures);
+
+ if (eraseDeviceData) {
+ await recordLocalFailure(dependencies.eraseDeviceData, "device-data", localCleanupFailures);
+ }
+
+ return { localCleanupFailures };
+}
diff --git a/src/lib/accountDeletionRequest.ts b/src/lib/accountDeletionRequest.ts
new file mode 100644
index 000000000..54464ef41
--- /dev/null
+++ b/src/lib/accountDeletionRequest.ts
@@ -0,0 +1,5 @@
+import { cloudDelete } from "../services/cloudApi";
+
+export async function deleteAccount(): Promise<void> {
+ await cloudDelete("/api/auth/delete-account");
+}
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index d62fee9ac..b65f0ee62 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -1,6 +1,5 @@
import { createAuthClient } from "better-auth/react";
import { ssoClient } from "@better-auth/sso/client";
-import { OPENWHISPR_API_URL } from "../config/constants";
import { openExternalLink } from "../utils/externalLinks";
import {
authContextFetch,
@@ -132,28 +131,6 @@ export function getGracePeriodRemainingMs(): number {
return Math.max(0, GRACE_PERIOD_MS - Math.max(0, Date.now() - startedAt));
}
-export async function deleteAccount(): Promise<{ error?: Error }> {
- if (!OPENWHISPR_API_URL) {
- return { error: new Error("API not configured") };
- }
-
- try {
- const res = await fetch(`${OPENWHISPR_API_URL}/api/auth/delete-account`, {
- method: "DELETE",
- credentials: "include",
- });
-
- if (!res.ok) {
- const data = await res.json().catch(() => ({}));
- throw new Error(data.error || "Failed to delete account");
- }
-
- return {};
- } catch (error) {
- return { error: error instanceof Error ? error : new Error("Failed to delete account") };
- }
-}
-
export async function signOut(): Promise<void> {
credentialAccountCache = null;
try {
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 08ed20461..707cd8bb2 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1917,16 +1917,20 @@
"wordsRemaining": "{{remaining}} verbleibend",
"deleteAccount": {
"label": "Konto löschen",
- "labelDescription": "Konto, alle Cloud-Daten und lokale Daten dauerhaft löschen. Diese Aktion kann nicht rückgängig gemacht werden.",
+ "labelDescription": "Konto und persönliche Cloud-Daten dauerhaft löschen. Andere lokale Benutzer und Arbeitsbereichsdaten bleiben erhalten.",
"button": "Mein Konto löschen",
"deleting": "Wird gelöscht...",
"title": "Konto löschen?",
- "description": "Dies löscht dauerhaft Ihr OpenWhispr-Konto, alle in der Cloud synchronisierten Notizen und alle lokalen Daten, einschließlich Transkriptionen, Audioaufnahmen, heruntergeladene Modelle, Kalenderverbindungen und Einstellungen. Diese Aktion kann nicht rückgängig gemacht werden.",
- "confirmText": "Alles löschen",
+ "description": "Dies löscht dauerhaft Ihr OpenWhispr-Konto und Ihre persönlichen Daten. Arbeitsbereichsdaten und Daten anderer lokaler Benutzer bleiben auf diesem Gerät erhalten.",
+ "confirmText": "Konto löschen",
+ "eraseDeviceLabel": "Auch alle Daten von diesem Gerät löschen",
+ "eraseDeviceDescription": "Löscht Notizen und Arbeitsbereichscaches aller lokalen Benutzer, heruntergeladene Modelle, Einstellungen, Kalenderverbindungen, Anmeldedaten und Aufnahmen.",
+ "eraseDeviceWarning": "Diese geräteweite Löschung kann nicht rückgängig gemacht werden und betrifft alle lokalen Benutzer.",
"successTitle": "Konto gelöscht",
- "successDescription": "Ihr Konto und alle Daten wurden gelöscht. Die App wird jetzt neu geladen.",
+ "successDescription": "Ihr Konto und Ihre persönlichen Daten wurden gelöscht. Andere lokale Benutzer, Arbeitsbereiche, Modelle und Geräteeinstellungen blieben erhalten.",
+ "partialCleanupDescription": "Ihr Konto wurde gelöscht, aber ein Teil der lokalen Bereinigung konnte nicht abgeschlossen werden. Andere Benutzer und Arbeitsbereichsdaten blieben erhalten.",
"failedTitle": "Löschung fehlgeschlagen",
- "failedDescription": "Beim Löschen Ihres Kontos ist ein Fehler aufgetreten. Ihre lokalen Daten wurden möglicherweise teilweise entfernt. Bitte versuchen Sie es erneut."
+ "failedDescription": "Die Kontolöschung konnte nicht abgeschlossen werden. Es wurde keine geräteweite Löschung gestartet. Bitte versuchen Sie es erneut."
},
"profile": {
"name": {
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 2a41b6db7..d934396a4 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1917,16 +1917,20 @@
"wordsRemaining": "{{remaining}} remaining",
"deleteAccount": {
"label": "Delete Account",
- "labelDescription": "Permanently delete your account, all cloud data, and local data. This action cannot be undone.",
+ "labelDescription": "Permanently delete your account and personal cloud data. Other local users and workspace-owned content are preserved.",
"button": "Delete My Account",
"deleting": "Deleting...",
"title": "Delete Your Account?",
- "description": "This will permanently delete your OpenWhispr account, all cloud-synced notes, and all local data including transcriptions, audio recordings, downloaded models, calendar connections, and settings. This action cannot be undone.",
- "confirmText": "Delete Everything",
+ "description": "This permanently deletes your OpenWhispr account and personal data. Workspace-owned content and data belonging to other local users stay on this device.",
+ "confirmText": "Delete Account",
+ "eraseDeviceLabel": "Also erase all data from this device",
+ "eraseDeviceDescription": "Deletes every local user's notes and workspace cache, downloaded models, settings, calendar connections, credentials, and recordings.",
+ "eraseDeviceWarning": "This device-wide erasure cannot be undone and affects every local user.",
"successTitle": "Account Deleted",
- "successDescription": "Your account and all data have been deleted. The app will now reload.",
+ "successDescription": "Your account and personal data were deleted. Other local users, workspaces, models, and device settings were preserved.",
+ "partialCleanupDescription": "Your account was deleted, but some local cleanup could not finish. Other users and workspace-owned content were preserved.",
"failedTitle": "Deletion Failed",
- "failedDescription": "Something went wrong deleting your account. Your local data may have been partially removed. Please try again."
+ "failedDescription": "Account deletion could not complete. No device-wide erasure was started. Please try again."
},
"profile": {
"name": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 5959bbebb..35e4d302d 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1676,16 +1676,20 @@
"wordsRemaining": "{{remaining}} restantes",
"deleteAccount": {
"label": "Eliminar cuenta",
- "labelDescription": "Eliminar permanentemente tu cuenta, todos los datos en la nube y los datos locales. Esta acción no se puede deshacer.",
+ "labelDescription": "Eliminar permanentemente tu cuenta y datos personales en la nube. Se conservan los demás usuarios locales y el contenido de los espacios de trabajo.",
"button": "Eliminar mi cuenta",
"deleting": "Eliminando...",
"title": "¿Eliminar tu cuenta?",
- "description": "Esto eliminará permanentemente tu cuenta de OpenWhispr, todas las notas sincronizadas en la nube y todos los datos locales, incluyendo transcripciones, grabaciones de audio, modelos descargados, conexiones de calendario y configuraciones. Esta acción no se puede deshacer.",
- "confirmText": "Eliminar todo",
+ "description": "Esto elimina permanentemente tu cuenta de OpenWhispr y tus datos personales. El contenido de los espacios de trabajo y los datos de otros usuarios locales permanecen en este dispositivo.",
+ "confirmText": "Eliminar cuenta",
+ "eraseDeviceLabel": "Eliminar también todos los datos de este dispositivo",
+ "eraseDeviceDescription": "Elimina las notas y cachés de espacios de todos los usuarios locales, modelos descargados, ajustes, calendarios, credenciales y grabaciones.",
+ "eraseDeviceWarning": "Este borrado de todo el dispositivo no se puede deshacer y afecta a todos los usuarios locales.",
"successTitle": "Cuenta eliminada",
- "successDescription": "Tu cuenta y todos los datos han sido eliminados. La aplicación se recargará ahora.",
+ "successDescription": "Tu cuenta y datos personales se eliminaron. Se conservaron los demás usuarios locales, espacios de trabajo, modelos y ajustes del dispositivo.",
+ "partialCleanupDescription": "Tu cuenta se eliminó, pero parte de la limpieza local no pudo finalizar. Se conservaron otros usuarios y el contenido de los espacios de trabajo.",
"failedTitle": "Error al eliminar",
- "failedDescription": "Algo salió mal al eliminar tu cuenta. Es posible que tus datos locales se hayan eliminado parcialmente. Inténtalo de nuevo."
+ "failedDescription": "No se pudo completar la eliminación de la cuenta. No se inició ningún borrado de todo el dispositivo. Inténtalo de nuevo."
},
"profile": {
"name": {
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 60174dc68..feba506f9 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1917,16 +1917,20 @@
"wordsRemaining": "{{remaining}} restants",
"deleteAccount": {
"label": "Supprimer le compte",
- "labelDescription": "Supprimer définitivement votre compte, toutes les données cloud et les données locales. Cette action est irréversible.",
+ "labelDescription": "Supprimer définitivement votre compte et vos données cloud personnelles. Les autres utilisateurs locaux et le contenu des espaces de travail sont conservés.",
"button": "Supprimer mon compte",
"deleting": "Suppression...",
"title": "Supprimer votre compte ?",
- "description": "Cela supprimera définitivement votre compte OpenWhispr, toutes les notes synchronisées dans le cloud et toutes les données locales, y compris les transcriptions, les enregistrements audio, les modèles téléchargés, les connexions de calendrier et les paramètres. Cette action est irréversible.",
- "confirmText": "Tout supprimer",
+ "description": "Cela supprime définitivement votre compte OpenWhispr et vos données personnelles. Le contenu des espaces de travail et les données des autres utilisateurs locaux restent sur cet appareil.",
+ "confirmText": "Supprimer le compte",
+ "eraseDeviceLabel": "Effacer aussi toutes les données de cet appareil",
+ "eraseDeviceDescription": "Supprime les notes et caches d’espaces de tous les utilisateurs locaux, les modèles téléchargés, paramètres, calendriers, identifiants et enregistrements.",
+ "eraseDeviceWarning": "Cet effacement de l’appareil est irréversible et affecte tous les utilisateurs locaux.",
"successTitle": "Compte supprimé",
- "successDescription": "Votre compte et toutes les données ont été supprimés. L'application va maintenant se recharger.",
+ "successDescription": "Votre compte et vos données personnelles ont été supprimés. Les autres utilisateurs locaux, espaces de travail, modèles et paramètres ont été conservés.",
+ "partialCleanupDescription": "Votre compte a été supprimé, mais une partie du nettoyage local n’a pas pu aboutir. Les autres utilisateurs et le contenu des espaces de travail ont été conservés.",
"failedTitle": "Échec de la suppression",
- "failedDescription": "Une erreur s'est produite lors de la suppression de votre compte. Vos données locales ont peut-être été partiellement supprimées. Veuillez réessayer."
+ "failedDescription": "La suppression du compte n’a pas pu aboutir. Aucun effacement global de l’appareil n’a été lancé. Veuillez réessayer."
},
"profile": {
"name": {
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 3a3d1b75a..498eb5c10 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1628,16 +1628,20 @@
"wordsRemaining": "{{remaining}} rimanenti",
"deleteAccount": {
"label": "Elimina account",
- "labelDescription": "Elimina permanentemente il tuo account, tutti i dati cloud e i dati locali. Questa azione non può essere annullata.",
+ "labelDescription": "Elimina permanentemente il tuo account e i dati cloud personali. Gli altri utenti locali e i contenuti degli spazi di lavoro vengono conservati.",
"button": "Elimina il mio account",
"deleting": "Eliminazione...",
"title": "Eliminare il tuo account?",
- "description": "Questo eliminerà permanentemente il tuo account OpenWhispr, tutte le note sincronizzate nel cloud e tutti i dati locali, incluse trascrizioni, registrazioni audio, modelli scaricati, connessioni calendario e impostazioni. Questa azione non può essere annullata.",
- "confirmText": "Elimina tutto",
+ "description": "Questo elimina permanentemente il tuo account OpenWhispr e i dati personali. I contenuti degli spazi di lavoro e i dati degli altri utenti locali restano su questo dispositivo.",
+ "confirmText": "Elimina account",
+ "eraseDeviceLabel": "Elimina anche tutti i dati da questo dispositivo",
+ "eraseDeviceDescription": "Elimina note e cache degli spazi di tutti gli utenti locali, modelli scaricati, impostazioni, calendari, credenziali e registrazioni.",
+ "eraseDeviceWarning": "Questa cancellazione dell’intero dispositivo non può essere annullata e riguarda tutti gli utenti locali.",
"successTitle": "Account eliminato",
- "successDescription": "Il tuo account e tutti i dati sono stati eliminati. L'app si ricaricherà ora.",
+ "successDescription": "Il tuo account e i dati personali sono stati eliminati. Gli altri utenti locali, spazi di lavoro, modelli e impostazioni sono stati conservati.",
+ "partialCleanupDescription": "Il tuo account è stato eliminato, ma parte della pulizia locale non è stata completata. Gli altri utenti e i contenuti degli spazi di lavoro sono stati conservati.",
"failedTitle": "Eliminazione fallita",
- "failedDescription": "Qualcosa è andato storto durante l'eliminazione del tuo account. I tuoi dati locali potrebbero essere stati parzialmente rimossi. Riprova."
+ "failedDescription": "Impossibile completare l’eliminazione dell’account. Non è stata avviata alcuna cancellazione dell’intero dispositivo. Riprova."
},
"profile": {
"name": {
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 19f48c9bc..3a8aa2994 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1628,16 +1628,20 @@
"wordsRemaining": "残り {{remaining}}",
"deleteAccount": {
"label": "アカウントを削除",
- "labelDescription": "アカウント、すべてのクラウドデータ、ローカルデータを完全に削除します。この操作は元に戻せません。",
+ "labelDescription": "アカウントと個人のクラウドデータを完全に削除します。他のローカルユーザーとワークスペース所有のコンテンツは保持されます。",
"button": "アカウントを削除",
"deleting": "削除中...",
"title": "アカウントを削除しますか?",
- "description": "OpenWhispr アカウント、すべてのクラウド同期ノート、すべてのローカルデータ(文字起こし、音声録音、ダウンロード済みモデル、カレンダー接続、設定を含む)が完全に削除されます。この操作は元に戻せません。",
- "confirmText": "すべて削除",
+ "description": "OpenWhispr アカウントと個人データを完全に削除します。ワークスペース所有のコンテンツと他のローカルユーザーのデータはこのデバイスに残ります。",
+ "confirmText": "アカウントを削除",
+ "eraseDeviceLabel": "このデバイス上のすべてのデータも消去する",
+ "eraseDeviceDescription": "すべてのローカルユーザーのノートとワークスペースキャッシュ、ダウンロード済みモデル、設定、カレンダー接続、認証情報、録音を削除します。",
+ "eraseDeviceWarning": "このデバイス全体の消去は元に戻せず、すべてのローカルユーザーに影響します。",
"successTitle": "アカウントが削除されました",
- "successDescription": "アカウントとすべてのデータが削除されました。アプリが再読み込みされます。",
+ "successDescription": "アカウントと個人データが削除されました。他のローカルユーザー、ワークスペース、モデル、デバイス設定は保持されました。",
+ "partialCleanupDescription": "アカウントは削除されましたが、一部のローカルクリーンアップを完了できませんでした。他のユーザーとワークスペース所有のコンテンツは保持されました。",
"failedTitle": "削除に失敗しました",
- "failedDescription": "アカウントの削除中にエラーが発生しました。ローカルデータが部分的に削除された可能性があります。もう一度お試しください。"
+ "failedDescription": "アカウントの削除を完了できませんでした。デバイス全体の消去は開始されていません。もう一度お試しください。"
},
"profile": {
"name": {
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 64c9b834b..597608435 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1607,16 +1607,20 @@
"wordsRemaining": "{{remaining}} restantes",
"deleteAccount": {
"label": "Excluir conta",
- "labelDescription": "Excluir permanentemente sua conta, todos os dados na nuvem e dados locais. Esta ação não pode ser desfeita.",
+ "labelDescription": "Excluir permanentemente sua conta e dados pessoais na nuvem. Outros usuários locais e conteúdos dos espaços de trabalho são preservados.",
"button": "Excluir minha conta",
"deleting": "Excluindo...",
"title": "Excluir sua conta?",
- "description": "Isso excluirá permanentemente sua conta OpenWhispr, todas as notas sincronizadas na nuvem e todos os dados locais, incluindo transcrições, gravações de áudio, modelos baixados, conexões de calendário e configurações. Esta ação não pode ser desfeita.",
- "confirmText": "Excluir tudo",
+ "description": "Isso exclui permanentemente sua conta OpenWhispr e seus dados pessoais. Conteúdos dos espaços de trabalho e dados de outros usuários locais permanecem neste dispositivo.",
+ "confirmText": "Excluir conta",
+ "eraseDeviceLabel": "Também apagar todos os dados deste dispositivo",
+ "eraseDeviceDescription": "Exclui notas e caches de espaços de todos os usuários locais, modelos baixados, configurações, calendários, credenciais e gravações.",
+ "eraseDeviceWarning": "Esta exclusão de todo o dispositivo não pode ser desfeita e afeta todos os usuários locais.",
"successTitle": "Conta excluída",
- "successDescription": "Sua conta e todos os dados foram excluídos. O aplicativo será recarregado agora.",
+ "successDescription": "Sua conta e dados pessoais foram excluídos. Outros usuários locais, espaços de trabalho, modelos e configurações foram preservados.",
+ "partialCleanupDescription": "Sua conta foi excluída, mas parte da limpeza local não pôde ser concluída. Outros usuários e conteúdos dos espaços de trabalho foram preservados.",
"failedTitle": "Falha na exclusão",
- "failedDescription": "Algo deu errado ao excluir sua conta. Seus dados locais podem ter sido parcialmente removidos. Tente novamente."
+ "failedDescription": "Não foi possível concluir a exclusão da conta. Nenhuma exclusão de todo o dispositivo foi iniciada. Tente novamente."
},
"profile": {
"name": {
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index f0fc5b3bf..a6f16c1de 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1632,16 +1632,20 @@
"wordsRemaining": "Осталось {{remaining}}",
"deleteAccount": {
"label": "Удалить аккаунт",
- "labelDescription": "Навсегда удалить ваш аккаунт, все облачные и локальные данные. Это действие нельзя отменить.",
+ "labelDescription": "Навсегда удалить ваш аккаунт и личные облачные данные. Другие локальные пользователи и содержимое рабочих пространств сохранятся.",
"button": "Удалить мой аккаунт",
"deleting": "Удаление...",
"title": "Удалить ваш аккаунт?",
- "description": "Это навсегда удалит ваш аккаунт OpenWhispr, все синхронизированные облачные заметки и все локальные данные, включая транскрипции, аудиозаписи, загруженные модели, подключения календаря и настройки. Это действие нельзя отменить.",
- "confirmText": "Удалить всё",
+ "description": "Это навсегда удалит ваш аккаунт OpenWhispr и личные данные. Содержимое рабочих пространств и данные других локальных пользователей останутся на устройстве.",
+ "confirmText": "Удалить аккаунт",
+ "eraseDeviceLabel": "Также удалить все данные с этого устройства",
+ "eraseDeviceDescription": "Удаляет заметки и кэши пространств всех локальных пользователей, загруженные модели, настройки, календари, учётные данные и записи.",
+ "eraseDeviceWarning": "Это удаление данных всего устройства нельзя отменить; оно затрагивает всех локальных пользователей.",
"successTitle": "Аккаунт удалён",
- "successDescription": "Ваш аккаунт и все данные были удалены. Приложение сейчас перезагрузится.",
+ "successDescription": "Ваш аккаунт и личные данные удалены. Другие локальные пользователи, рабочие пространства, модели и настройки устройства сохранены.",
+ "partialCleanupDescription": "Ваш аккаунт удалён, но локальную очистку не удалось завершить полностью. Другие пользователи и содержимое рабочих пространств сохранены.",
"failedTitle": "Ошибка удаления",
- "failedDescription": "Что-то пошло не так при удалении вашего аккаунта. Ваши локальные данные могли быть частично удалены. Попробуйте снова."
+ "failedDescription": "Не удалось завершить удаление аккаунта. Удаление данных всего устройства не запускалось. Попробуйте снова."
},
"profile": {
"name": {
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index c7edf54be..351e1792b 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1628,16 +1628,20 @@
"wordsRemaining": "剩余 {{remaining}} 个词",
"deleteAccount": {
"label": "删除账户",
- "labelDescription": "永久删除您的账户、所有云端数据和本地数据。此操作无法撤销。",
+ "labelDescription": "永久删除您的账户和个人云端数据。其他本地用户和工作区所有的内容将被保留。",
"button": "删除我的账户",
"deleting": "正在删除...",
"title": "删除您的账户?",
- "description": "这将永久删除您的 OpenWhispr 账户、所有云端同步笔记和所有本地数据,包括转录、音频录制、下载的模型、日历连接和设置。此操作无法撤销。",
- "confirmText": "删除所有内容",
+ "description": "这将永久删除您的 OpenWhispr 账户和个人数据。工作区所有的内容及其他本地用户的数据会保留在此设备上。",
+ "confirmText": "删除账户",
+ "eraseDeviceLabel": "同时清除此设备上的所有数据",
+ "eraseDeviceDescription": "删除所有本地用户的笔记和工作区缓存、已下载模型、设置、日历连接、凭据和录音。",
+ "eraseDeviceWarning": "此设备级清除无法撤销,并会影响所有本地用户。",
"successTitle": "账户已删除",
- "successDescription": "您的账户和所有数据已被删除。应用将立即重新加载。",
+ "successDescription": "您的账户和个人数据已删除。其他本地用户、工作区、模型和设备设置均已保留。",
+ "partialCleanupDescription": "您的账户已删除,但部分本地清理未能完成。其他用户和工作区所有的内容均已保留。",
"failedTitle": "删除失败",
- "failedDescription": "删除您的账户时出错。您的本地数据可能已被部分删除。请重试。"
+ "failedDescription": "无法完成账户删除。未启动设备级清除。请重试。"
},
"profile": {
"name": {
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 39270f302..9a720b6b9 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1628,16 +1628,20 @@
"wordsRemaining": "剩餘 {{remaining}} 字",
"deleteAccount": {
"label": "刪除帳戶",
- "labelDescription": "永久刪除您的帳戶、所有雲端資料和本地資料。此操作無法復原。",
+ "labelDescription": "永久刪除您的帳戶和個人雲端資料。其他本地使用者和工作區擁有的內容將被保留。",
"button": "刪除我的帳戶",
"deleting": "正在刪除...",
"title": "刪除您的帳戶?",
- "description": "這將永久刪除您的 OpenWhispr 帳戶、所有雲端同步筆記和所有本地資料,包括轉錄、音訊錄製、下載的模型、行事曆連線和設定。此操作無法復原。",
- "confirmText": "刪除所有內容",
+ "description": "這將永久刪除您的 OpenWhispr 帳戶和個人資料。工作區擁有的內容及其他本地使用者的資料會保留在此裝置上。",
+ "confirmText": "刪除帳戶",
+ "eraseDeviceLabel": "同時清除此裝置上的所有資料",
+ "eraseDeviceDescription": "刪除所有本地使用者的筆記和工作區快取、已下載模型、設定、行事曆連線、憑證和錄音。",
+ "eraseDeviceWarning": "此裝置級清除無法復原,並會影響所有本地使用者。",
"successTitle": "帳戶已刪除",
- "successDescription": "您的帳戶和所有資料已被刪除。應用程式將立即重新載入。",
+ "successDescription": "您的帳戶和個人資料已刪除。其他本地使用者、工作區、模型和裝置設定均已保留。",
+ "partialCleanupDescription": "您的帳戶已刪除,但部分本地清理未能完成。其他使用者和工作區擁有的內容均已保留。",
"failedTitle": "刪除失敗",
- "failedDescription": "刪除您的帳戶時發生錯誤。您的本地資料可能已被部分刪除。請重試。"
+ "failedDescription": "無法完成帳戶刪除。未啟動裝置級清除。請重試。"
},
"profile": {
"name": {
diff --git a/src/services/NotesService.ts b/src/services/NotesService.ts
index 918ff6662..150ad94ed 100644
--- a/src/services/NotesService.ts
+++ b/src/services/NotesService.ts
@@ -49,6 +49,9 @@ export interface CloudNote {
// The note's owner (creator), not its last editor. Absent on access_removed
// stubs and on API versions that predate ownership.
user_id?: string | null;
+ // Creator attribution is separate from the operational custodian. It is
+ // explicitly null after the creator deletes their account.
+ created_by_user_id?: string | null;
updated_by_user_id: string | null;
previous_space_id?: string | null;
// Redacted stub for a row that moved out of one of the caller's spaces —
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 227f45148..212d33331 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -180,8 +180,7 @@ function readPurgedSpaceIds(): Record<string, PurgedSpaceEntry> {
}
}
-// Call BEFORE purgeSpace, from every purge path (sync revocation, sign-out,
-// and the UI's delete-space flow).
+// Call BEFORE purgeSpace from revocation and UI delete-space flows.
export async function markSpacePurged(
cloudSpaceId: string,
reason: PurgedSpaceReason
@@ -298,21 +297,18 @@ export class SyncService {
localStorage.setItem("teamSpacesCapability.probedAt", new Date().toISOString());
}
- // Sign-out leaves no team content behind: purge every team space locally and
- // forget the capability probe + team cursors so the next account re-probes
- // and backfills from scratch. Never throws — a failed purge must not block
- // signing out.
+ // Sign-out clears account-scoped renderer/session state without deleting
+ // workspace-owned rows. The main-process account scope hides those rows as
+ // soon as the bearer token is cleared.
async purgeTeamSpacesForSignOut(): Promise<void> {
- // Wait for the sync lock: an in-flight pass (often in another window)
- // still holds a pre-purge space map, and its remaining rows would
- // re-insert team content after the purge — unreachable by any later
- // cleanup once the guard entries below are gone.
+ // Wait for the sync lock so an in-flight pass cannot repopulate renderer
+ // state after this account boundary has been cleared.
try {
- await navigator.locks.request(SYNC_ALL_LOCK, () => this.purgeAllTeamSpaces());
+ await navigator.locks.request(SYNC_ALL_LOCK, () => this.clearTeamSpaceSessionState());
} catch (err) {
- console.error("Sign-out purge could not take the sync lock:", err);
- // Never block sign-out: purge unfenced rather than not at all.
- await this.purgeAllTeamSpaces();
+ console.error("Sign-out cleanup could not take the sync lock:", err);
+ // Never block sign-out: clear session state even if the lock failed.
+ await this.clearTeamSpaceSessionState();
}
}
@@ -325,15 +321,13 @@ export class SyncService {
let purgedCount = 0;
await navigator.locks.request(SYNC_ALL_LOCK, async () => {
await assertAuthGenerationCurrent(authGeneration);
- let localSpaces = (await window.electronAPI.getSpaces?.()) ?? [];
- const localTeamSpaces = localSpaces.filter((space) => space.kind === "team");
- if (localTeamSpaces.length === 0) {
- await assertAuthGenerationCurrent(authGeneration);
- return;
- }
-
const remoteSpaces = await SpacesService.mySpacesForAuthValidation(authGeneration);
await assertAuthGenerationCurrent(authGeneration);
+ await prunePurgedSpaceIds(new Set(remoteSpaces.map((space) => space.id)));
+ await upsertCloudSpaces(remoteSpaces);
+ await assertAuthGenerationCurrent(authGeneration);
+ let localSpaces = (await window.electronAPI.getSpaces?.()) ?? [];
+ const localTeamSpaces = localSpaces.filter((space) => space.kind === "team");
const initial = partitionLocalTeamSpaces(localTeamSpaces, remoteSpaces);
for (const space of initial.unproven) {
await assertAuthGenerationCurrent(authGeneration);
@@ -367,30 +361,12 @@ export class SyncService {
return purgedCount;
}
- private async purgeAllTeamSpaces(): Promise<void> {
- try {
- const spaces = (await window.electronAPI.getSpaces?.()) ?? [];
- for (const space of spaces) {
- if (space.kind !== "team") continue;
- try {
- // "revoked", not "deleted": the whole guard key is removed once the
- // sign-out purge completes, and if that removal ever fails a revoked
- // entry self-heals on the next pass instead of locking the space out.
- if (space.cloud_space_id) await markSpacePurged(space.cloud_space_id, "revoked");
- await window.electronAPI.purgeSpace?.(space.id, { mode: "destructive" });
- } catch (err) {
- console.error(`Purging space ${space.id} on sign-out failed:`, err);
- }
- }
- } catch (err) {
- console.error("Team space purge on sign-out failed:", err);
- }
+ private async clearTeamSpaceSessionState(): Promise<void> {
clearTeamSpacesCapability();
localStorage.removeItem("teamSpacesCapability.probedAt");
localStorage.removeItem("lastSyncedAt.notes.team");
localStorage.removeItem("lastSyncedAt.folders.team");
- // The guard protected any pass still in flight during the purge; drop it
- // so the next account (possibly a member of the same spaces) starts clean.
+ // The next account must establish its own remote membership view.
localStorage.removeItem(PURGED_SPACE_GUARD_KEY);
// Pre-spaces guard key; stale entries are meaningless now.
localStorage.removeItem("purgedTeamIds");
diff --git a/src/types/electron.ts b/src/types/electron.ts
index e6405b0d3..7e1208b1a 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -165,6 +165,7 @@ export interface NoteItem {
// team notes mirrored before ownership shipped (the UI fails closed on
// those until the owner backfill fills them).
owner_user_id?: string | null;
+ created_by_user_id?: string | null;
// Last cloud editor; only populated on cloud pull (local edits don't set it).
updated_by_user_id?: string | null;
// Server updated_at this device last acked (push response or pull); echoed
@@ -1210,6 +1211,20 @@ declare global {
// Space operations
getSpaces?: () => Promise<SpaceItem[]>;
+ setActiveAccountScope?: (
+ accountId: string | null,
+ expectedAuthGeneration?: number
+ ) => Promise<{ success: boolean; code?: string; error?: string }>;
+ deleteAccountData?: (
+ accountId: string,
+ expectedAuthGeneration: number
+ ) => Promise<{
+ success: boolean;
+ code?: string;
+ error?: string;
+ deletedNoteIds?: number[];
+ deletedFolderIds?: number[];
+ }>;
updateSpace?: (
id: number,
updates: { name?: string; emoji?: string | null }
@@ -1230,6 +1245,7 @@ declare global {
relocatedNotes?: NoteItem[];
relocatedCount?: number;
relocatedTitles?: string[];
+ preservedForOtherAccounts?: boolean;
}>;
upsertSpaceFromCloud?: (space: Record<string, unknown>) => Promise<SpaceItem>;
setSpaceSyncStatus?: (
diff --git a/test/helpers/accountOwnershipDatabase.test.js b/test/helpers/accountOwnershipDatabase.test.js
new file mode 100644
index 000000000..ddeaafbf4
--- /dev/null
+++ b/test/helpers/accountOwnershipDatabase.test.js
@@ -0,0 +1,517 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { DatabaseSync } = require("node:sqlite");
+const Module = require("node:module");
+
+const originalLoad = Module._load;
+Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") return { app: {} };
+ return originalLoad.call(this, request, parent, isMain);
+};
+const DatabaseManager = require("../../src/helpers/database.js");
+Module._load = originalLoad;
+
+function createDatabaseManager() {
+ const sqlite = new DatabaseSync(":memory:");
+ sqlite.exec(`
+ PRAGMA foreign_keys = ON;
+ CREATE TABLE spaces (
+ id INTEGER PRIMARY KEY,
+ kind TEXT NOT NULL,
+ name TEXT,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ sync_status TEXT NOT NULL DEFAULT 'synced',
+ deleted_at TEXT
+ );
+ CREATE TABLE space_accounts (
+ space_id INTEGER NOT NULL,
+ account_id TEXT NOT NULL,
+ PRIMARY KEY (space_id, account_id)
+ );
+ CREATE TABLE folders (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL,
+ is_default INTEGER NOT NULL DEFAULT 0,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ client_folder_id TEXT,
+ cloud_id TEXT,
+ sync_status TEXT NOT NULL DEFAULT 'synced',
+ space_id INTEGER,
+ account_id TEXT,
+ deleted_at TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE notes (
+ id INTEGER PRIMARY KEY,
+ title TEXT NOT NULL,
+ content TEXT NOT NULL,
+ note_type TEXT NOT NULL DEFAULT 'personal',
+ source_file TEXT,
+ audio_duration_seconds REAL,
+ folder_id INTEGER,
+ space_id INTEGER,
+ client_note_id TEXT,
+ cloud_id TEXT,
+ sync_status TEXT NOT NULL DEFAULT 'synced',
+ account_id TEXT,
+ transcript TEXT,
+ participants TEXT,
+ deleted_at TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE UNIQUE INDEX idx_notes_client_note_id ON notes(client_note_id);
+ CREATE TABLE agent_conversations (
+ id INTEGER PRIMARY KEY,
+ note_id INTEGER,
+ folder_id INTEGER,
+ cloud_id TEXT,
+ sync_status TEXT NOT NULL DEFAULT 'synced',
+ deleted_at TEXT,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ );
+ CREATE TABLE agent_messages (
+ id INTEGER PRIMARY KEY,
+ conversation_id INTEGER NOT NULL REFERENCES agent_conversations(id) ON DELETE CASCADE
+ );
+ CREATE TABLE speaker_mappings (note_id INTEGER NOT NULL);
+ CREATE TABLE note_speaker_embeddings (note_id INTEGER NOT NULL);
+ CREATE TABLE optimistic_folder_delete_rows (
+ folder_id INTEGER NOT NULL,
+ entity_type TEXT NOT NULL,
+ entity_id INTEGER,
+ original_sync_status TEXT,
+ original_deleted_at TEXT,
+ original_updated_at TEXT,
+ PRIMARY KEY (folder_id, entity_type, entity_id)
+ );
+ INSERT INTO spaces (id, kind) VALUES (1, 'private'), (2, 'team'), (3, 'team');
+ INSERT INTO space_accounts (space_id, account_id) VALUES
+ (2, 'account-a'),
+ (3, 'account-b');
+ `);
+
+ const manager = Object.create(DatabaseManager.prototype);
+ manager.db = sqlite;
+ manager.activeAccountId = null;
+ return { manager, sqlite };
+}
+
+// node:sqlite has no better-sqlite3-style transaction(); the folder deletion
+// paths require one.
+function installTransactionShim(sqlite) {
+ sqlite.transaction =
+ (fn) =>
+ (...args) => {
+ sqlite.exec("BEGIN");
+ try {
+ const result = fn(...args);
+ sqlite.exec("COMMIT");
+ return result;
+ } catch (error) {
+ sqlite.exec("ROLLBACK");
+ throw error;
+ }
+ };
+}
+
+test("account scope shows legacy and active personal rows plus every workspace row", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+
+ sqlite.exec(`
+ INSERT INTO folders (id, name, space_id, account_id) VALUES
+ (1, 'Legacy', 1, NULL),
+ (2, 'Personal A', 1, 'account-a'),
+ (3, 'Personal B', 1, 'account-b'),
+ (4, 'Workspace A', 2, NULL),
+ (5, 'Workspace B', 3, NULL);
+ INSERT INTO notes (id, title, content, folder_id, space_id, account_id) VALUES
+ (1, 'Legacy', '', 1, 1, NULL),
+ (2, 'Personal A', '', 2, 1, 'account-a'),
+ (3, 'Personal B', '', 3, 1, 'account-b'),
+ (4, 'Workspace A', '', 4, 2, NULL),
+ (5, 'Workspace B', '', 5, 3, NULL);
+ `);
+
+ manager.setActiveAccountId("account-a");
+
+ assert.deepEqual(
+ manager
+ .getNotes(null, 100)
+ .map((note) => note.title)
+ .sort(),
+ ["Legacy", "Personal A", "Workspace A"]
+ );
+ assert.deepEqual(
+ manager
+ .getFolders()
+ .map((folder) => folder.name)
+ .sort(),
+ ["Legacy", "Personal A", "Workspace A"]
+ );
+
+ manager.setActiveAccountId("account-b");
+ assert.deepEqual(
+ manager
+ .getNotes(null, 100)
+ .map((note) => note.title)
+ .sort(),
+ ["Legacy", "Personal B", "Workspace B"]
+ );
+ assert.deepEqual(
+ manager
+ .getSpaces()
+ .filter((space) => space.kind === "team")
+ .map((space) => space.id),
+ [3]
+ );
+});
+
+test("new personal content is attributed to the active account but workspace content is not", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ manager.setActiveAccountId("account-a");
+
+ const personalFolder = manager.createFolder("Personal A", 1).folder;
+ const workspaceFolder = manager.createFolder("Workspace", 2).folder;
+ const personalNote = manager.saveNote("Personal A", "", "personal", null, null, null, 1).note;
+ const workspaceNote = manager.saveNote("Workspace", "", "personal", null, null, null, 2).note;
+
+ assert.equal(personalFolder.account_id, "account-a");
+ assert.equal(personalNote.account_id, "account-a");
+ assert.equal(workspaceFolder.account_id, null);
+ assert.equal(workspaceNote.account_id, null);
+});
+
+test("deleting one account removes only its personal rows and dependent private content", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ sqlite.exec(`
+ INSERT INTO folders (id, name, space_id, account_id) VALUES
+ (1, 'Legacy', 1, NULL),
+ (2, 'Personal A', 1, 'account-a'),
+ (3, 'Personal B', 1, 'account-b'),
+ (4, 'Workspace A', 2, 'account-a');
+ INSERT INTO notes (id, title, content, folder_id, space_id, account_id) VALUES
+ (1, 'Legacy', '', 1, 1, NULL),
+ (2, 'Personal A', '', 2, 1, 'account-a'),
+ (3, 'Personal B', '', 3, 1, 'account-b'),
+ (4, 'Workspace A', '', 4, 2, 'account-a');
+ INSERT INTO agent_conversations (id, note_id, folder_id) VALUES (1, 2, 2);
+ INSERT INTO agent_messages (id, conversation_id) VALUES (1, 1);
+ INSERT INTO speaker_mappings (note_id) VALUES (2);
+ INSERT INTO note_speaker_embeddings (note_id) VALUES (2);
+ INSERT INTO optimistic_folder_delete_rows (folder_id, entity_type, entity_id)
+ VALUES (2, 'note', 2);
+ `);
+ manager.setActiveAccountId("account-a");
+
+ const result = manager.deleteAccountData("account-a");
+
+ assert.deepEqual(result.deletedNoteIds, [2]);
+ assert.deepEqual(result.deletedFolderIds, [2]);
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT title FROM notes ORDER BY id")
+ .all()
+ .map((row) => row.title),
+ ["Legacy", "Personal B", "Workspace A"]
+ );
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT name FROM folders ORDER BY id")
+ .all()
+ .map((row) => row.name),
+ ["Legacy", "Personal B", "Workspace A"]
+ );
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM agent_conversations").get().count, 0);
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM agent_messages").get().count, 0);
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM speaker_mappings").get().count, 0);
+ assert.equal(
+ sqlite.prepare("SELECT COUNT(*) AS count FROM note_speaker_embeddings").get().count,
+ 0
+ );
+ assert.equal(
+ sqlite
+ .prepare("SELECT COUNT(*) AS count FROM space_accounts WHERE account_id = 'account-b'")
+ .get().count,
+ 1
+ );
+ assert.equal(
+ sqlite.prepare("SELECT COUNT(*) AS count FROM optimistic_folder_delete_rows").get().count,
+ 0
+ );
+ assert.equal(
+ sqlite
+ .prepare("SELECT COUNT(*) AS count FROM space_accounts WHERE account_id = 'account-a'")
+ .get().count,
+ 0
+ );
+});
+
+test("account deletion refuses to target an account outside the active scope", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ manager.setActiveAccountId("account-a");
+
+ assert.throws(() => manager.deleteAccountData("account-b"), /active account scope/);
+});
+
+test("revoking one local account preserves a workspace used by another account", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ sqlite.exec(`
+ INSERT INTO space_accounts (space_id, account_id) VALUES (2, 'account-b');
+ INSERT INTO folders (id, name, space_id, account_id) VALUES
+ (1, 'Shared workspace folder', 2, NULL);
+ INSERT INTO notes (id, title, content, folder_id, space_id, account_id) VALUES
+ (1, 'Shared workspace note', '', 1, 2, NULL);
+ `);
+ manager.setActiveAccountId("account-a");
+
+ assert.equal(manager._releaseActiveSpaceMembershipIfShared(2), true);
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM spaces WHERE id = 2").get().count, 1);
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM folders WHERE id = 1").get().count, 1);
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM notes WHERE id = 1").get().count, 1);
+ assert.equal(
+ sqlite
+ .prepare(
+ "SELECT COUNT(*) AS count FROM space_accounts WHERE space_id = 2 AND account_id = 'account-a'"
+ )
+ .get().count,
+ 0
+ );
+ assert.equal(
+ sqlite
+ .prepare(
+ "SELECT COUNT(*) AS count FROM space_accounts WHERE space_id = 2 AND account_id = 'account-b'"
+ )
+ .get().count,
+ 1
+ );
+});
+
+test("stale space mutations cannot target another account's workspace", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ manager.setActiveAccountId("account-a");
+
+ assert.deepEqual(manager.updateSpace(3, { name: "Wrong account" }), {
+ success: false,
+ error: "Space not found",
+ });
+ assert.deepEqual(manager.setSpaceSyncStatus(3, "pending"), {
+ success: false,
+ space: null,
+ });
+ assert.deepEqual(manager.purgeSpace(3, { mode: "destructive" }), {
+ success: false,
+ error: "Space not found",
+ });
+ assert.equal(sqlite.prepare("SELECT name FROM spaces WHERE id = 3").get().name, null);
+ assert.equal(
+ sqlite.prepare("SELECT sync_status FROM spaces WHERE id = 3").get().sync_status,
+ "synced"
+ );
+});
+
+test("deleting a folder releases other accounts' notes to the space root instead of deleting them", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ installTransactionShim(sqlite);
+ sqlite.exec(`
+ INSERT INTO folders (id, name, space_id, account_id) VALUES (10, 'Projects', 1, NULL);
+ INSERT INTO notes (id, title, content, folder_id, space_id, account_id) VALUES
+ (1, 'A note', '', 10, 1, 'account-a'),
+ (2, 'Legacy note', '', 10, 1, NULL),
+ (3, 'B note', '', 10, 1, 'account-b');
+ INSERT INTO agent_conversations (id, note_id) VALUES (1, 1), (2, 3);
+ INSERT INTO agent_messages (id, conversation_id) VALUES (1, 1), (2, 2);
+ INSERT INTO speaker_mappings (note_id) VALUES (1), (3);
+ INSERT INTO note_speaker_embeddings (note_id) VALUES (1), (3);
+ `);
+ manager.setActiveAccountId("account-a");
+
+ const result = manager.deleteFolder(10);
+
+ assert.equal(result.success, true);
+ assert.deepEqual(result.noteIds.sort(), [1, 2]);
+ assert.deepEqual(
+ result.relocatedNotes.map((note) => note.id),
+ [3]
+ );
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT id, folder_id, space_id, deleted_at, sync_status FROM notes")
+ .all()
+ .map((row) => ({ ...row })),
+ [{ id: 3, folder_id: null, space_id: 1, deleted_at: null, sync_status: "pending" }]
+ );
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM folders").get().count, 0);
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT id, note_id FROM agent_conversations")
+ .all()
+ .map((row) => ({ ...row })),
+ [{ id: 2, note_id: 3 }]
+ );
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT id FROM agent_messages")
+ .all()
+ .map((row) => ({ ...row })),
+ [{ id: 2 }]
+ );
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT note_id FROM speaker_mappings")
+ .all()
+ .map((row) => ({ ...row })),
+ [{ note_id: 3 }]
+ );
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT note_id FROM note_speaker_embeddings")
+ .all()
+ .map((row) => ({ ...row })),
+ [{ note_id: 3 }]
+ );
+});
+
+test("an optimistic cloud folder delete never journals or hides other accounts' notes", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ installTransactionShim(sqlite);
+ sqlite.exec(`
+ INSERT INTO folders (id, name, space_id, account_id, cloud_id) VALUES
+ (10, 'Projects', 1, NULL, 'cf-1');
+ INSERT INTO notes (id, title, content, folder_id, space_id, account_id, cloud_id) VALUES
+ (1, 'A note', '', 10, 1, 'account-a', 'cn-a'),
+ (3, 'B note', '', 10, 1, 'account-b', 'cn-b');
+ `);
+ manager.setActiveAccountId("account-a");
+
+ const result = manager.deleteFolder(10);
+
+ assert.equal(result.success, true);
+ assert.deepEqual(result.noteIds, [1]);
+ assert.deepEqual(
+ result.relocatedNotes.map((note) => note.id),
+ [3]
+ );
+ const own = sqlite.prepare("SELECT deleted_at, sync_status FROM notes WHERE id = 1").get();
+ assert.ok(own.deleted_at != null);
+ assert.equal(own.sync_status, "folder_delete_pending");
+ assert.deepEqual(
+ {
+ ...sqlite.prepare("SELECT folder_id, deleted_at, sync_status FROM notes WHERE id = 3").get(),
+ },
+ { folder_id: null, deleted_at: null, sync_status: "pending" }
+ );
+ assert.deepEqual(
+ sqlite
+ .prepare(
+ "SELECT entity_id FROM optimistic_folder_delete_rows WHERE entity_type = 'note' ORDER BY entity_id"
+ )
+ .all()
+ .map((row) => ({ ...row })),
+ [{ entity_id: 1 }]
+ );
+});
+
+test("hard folder deletion preserves other accounts' notes, tombstones included", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ installTransactionShim(sqlite);
+ sqlite.exec(`
+ INSERT INTO folders (id, name, space_id, account_id, cloud_id) VALUES
+ (10, 'Projects', 1, NULL, 'cf-1');
+ INSERT INTO notes (id, title, content, folder_id, space_id, account_id, cloud_id, sync_status, deleted_at) VALUES
+ (1, 'A note', '', 10, 1, 'account-a', 'cn-a', 'synced', NULL),
+ (3, 'B note', '', 10, 1, 'account-b', 'cn-b', 'synced', NULL),
+ (4, 'B tombstone', '', 10, 1, 'account-b', 'cn-b2', 'pending', '2026-08-01 00:00:00');
+ `);
+ manager.setActiveAccountId("account-a");
+
+ const result = manager.hardDeleteFolder(10);
+
+ assert.equal(result.success, true);
+ assert.deepEqual(result.noteIds, [1]);
+ assert.deepEqual(result.relocatedNotes.map((note) => note.id).sort(), [3, 4]);
+ assert.deepEqual(
+ sqlite
+ .prepare("SELECT id, folder_id, deleted_at FROM notes ORDER BY id")
+ .all()
+ .map((row) => ({ ...row })),
+ [
+ { id: 3, folder_id: null, deleted_at: null },
+ { id: 4, folder_id: null, deleted_at: "2026-08-01 00:00:00" },
+ ]
+ );
+ assert.equal(sqlite.prepare("SELECT COUNT(*) AS count FROM folders").get().count, 0);
+});
+
+function importRow(clientNoteId, title) {
+ return {
+ clientNoteId,
+ title,
+ content: "",
+ sourceFile: null,
+ transcript: null,
+ participants: null,
+ createdAt: null,
+ };
+}
+
+test("imported notes carry the active account and never land in another account's folder", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ installTransactionShim(sqlite);
+ sqlite.exec(
+ "INSERT INTO folders (id, name, space_id, account_id) VALUES (20, 'Imported', 1, 'account-b')"
+ );
+ manager.setActiveAccountId("account-a");
+
+ const result = manager.importNotes([importRow("import-1", "Imported note")]);
+
+ assert.equal(result.success, true);
+ assert.equal(result.imported, 1);
+ const note = sqlite
+ .prepare("SELECT account_id, folder_id, space_id FROM notes WHERE client_note_id = 'import-1'")
+ .get();
+ assert.equal(note.account_id, "account-a");
+ assert.equal(note.space_id, 1);
+ assert.notEqual(note.folder_id, 20);
+ const folder = sqlite
+ .prepare("SELECT name, account_id FROM folders WHERE id = ?")
+ .get(note.folder_id);
+ assert.deepEqual({ ...folder }, { name: "Imported", account_id: "account-a" });
+
+ const again = manager.importNotes([importRow("import-2", "Second import")]);
+ assert.equal(again.folderId, note.folder_id);
+});
+
+test("a guest import stays device-owned and cannot reuse an account's folder", (t) => {
+ const { manager, sqlite } = createDatabaseManager();
+ t.after(() => sqlite.close());
+ installTransactionShim(sqlite);
+ sqlite.exec(
+ "INSERT INTO folders (id, name, space_id, account_id) VALUES (20, 'Imported', 1, 'account-b')"
+ );
+ manager.setActiveAccountId(null);
+
+ const result = manager.importNotes([importRow("import-guest", "Guest import")]);
+
+ assert.equal(result.imported, 1);
+ const note = sqlite
+ .prepare("SELECT account_id, folder_id FROM notes WHERE client_note_id = 'import-guest'")
+ .get();
+ assert.equal(note.account_id, null);
+ assert.notEqual(note.folder_id, 20);
+ const folder = sqlite
+ .prepare("SELECT name, account_id FROM folders WHERE id = ?")
+ .get(note.folder_id);
+ assert.deepEqual({ ...folder }, { name: "Imported", account_id: null });
+});
diff --git a/test/helpers/accountScopeBinding.test.js b/test/helpers/accountScopeBinding.test.js
new file mode 100644
index 000000000..9fb0c8a1e
--- /dev/null
+++ b/test/helpers/accountScopeBinding.test.js
@@ -0,0 +1,132 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const crypto = require("node:crypto");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const Module = require("node:module");
+
+let userDataDirectory = os.tmpdir();
+const originalLoad = Module._load;
+Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") {
+ return { app: { getPath: () => userDataDirectory } };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+const binding = require("../../src/helpers/accountScopeBinding.js");
+Module._load = originalLoad;
+
+function freshUserData(t) {
+ userDataDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "account-scope-binding-"));
+ t.after(() => fs.rmSync(userDataDirectory, { recursive: true, force: true }));
+ return userDataDirectory;
+}
+
+const sha256 = (value) => crypto.createHash("sha256").update(value, "utf8").digest("hex");
+
+test("resolveBootAccountScope restores only a hash-matching binding", () => {
+ const valid = { version: 1, accountId: "account-a", tokenHash: sha256("token-a") };
+ assert.equal(binding.resolveBootAccountScope({ token: "token-a", binding: valid }), "account-a");
+ assert.equal(binding.resolveBootAccountScope({ token: null, binding: valid }), null);
+ assert.equal(binding.resolveBootAccountScope({ token: "", binding: valid }), null);
+ assert.equal(binding.resolveBootAccountScope({ token: "token-a", binding: null }), null);
+ assert.equal(binding.resolveBootAccountScope({ token: "rotated-token", binding: valid }), null);
+ assert.equal(
+ binding.resolveBootAccountScope({ token: "token-a", binding: { ...valid, version: 2 } }),
+ null
+ );
+ assert.equal(
+ binding.resolveBootAccountScope({ token: "token-a", binding: { ...valid, accountId: " " } }),
+ null
+ );
+});
+
+test("evaluateScopeRequest fences null scope calls made under a live credential", () => {
+ assert.deepEqual(
+ binding.evaluateScopeRequest({
+ accountId: " ",
+ expectedGeneration: 1,
+ token: "t",
+ generation: 1,
+ }),
+ { ok: false, code: "INVALID_ACCOUNT" }
+ );
+ assert.deepEqual(
+ binding.evaluateScopeRequest({
+ accountId: "a",
+ expectedGeneration: 1,
+ token: null,
+ generation: 1,
+ }),
+ { ok: false, code: "AUTH_CONTEXT_CHANGED" }
+ );
+ assert.deepEqual(
+ binding.evaluateScopeRequest({
+ accountId: "a",
+ expectedGeneration: 1,
+ token: "t",
+ generation: 2,
+ }),
+ { ok: false, code: "AUTH_CONTEXT_CHANGED" }
+ );
+ assert.deepEqual(
+ binding.evaluateScopeRequest({
+ accountId: null,
+ expectedGeneration: 1,
+ token: "t",
+ generation: 2,
+ }),
+ { ok: false, code: "AUTH_CONTEXT_CHANGED" }
+ );
+ assert.deepEqual(
+ binding.evaluateScopeRequest({
+ accountId: null,
+ expectedGeneration: undefined,
+ token: null,
+ generation: 7,
+ }),
+ { ok: true }
+ );
+ assert.deepEqual(
+ binding.evaluateScopeRequest({
+ accountId: "a",
+ expectedGeneration: 7,
+ token: "t",
+ generation: 7,
+ }),
+ { ok: true }
+ );
+ assert.deepEqual(
+ binding.evaluateScopeRequest({
+ accountId: null,
+ expectedGeneration: 7,
+ token: "t",
+ generation: 7,
+ }),
+ { ok: true }
+ );
+});
+
+test("persist, read, and resolve round-trip through the binding file", (t) => {
+ const dir = freshUserData(t);
+ binding.persist("account-a", "token-a");
+ const stored = binding.read();
+ assert.deepEqual(stored, { version: 1, accountId: "account-a", tokenHash: sha256("token-a") });
+ assert.equal(binding.resolveBootAccountScope({ token: "token-a", binding: stored }), "account-a");
+ if (process.platform !== "win32") {
+ const mode = fs.statSync(path.join(dir, "account-scope-binding.json")).mode & 0o777;
+ assert.equal(mode, 0o600);
+ }
+});
+
+test("clear removes the binding and read tolerates absence and corruption", (t) => {
+ const dir = freshUserData(t);
+ assert.equal(binding.read(), null);
+ binding.persist("account-a", "token-a");
+ binding.clear();
+ assert.equal(binding.read(), null);
+ fs.writeFileSync(path.join(dir, "account-scope-binding.json"), "{not json");
+ assert.equal(binding.read(), null);
+ binding.clear();
+});
diff --git a/test/helpers/accountScopeRestoreContract.test.js b/test/helpers/accountScopeRestoreContract.test.js
new file mode 100644
index 000000000..ea54629a2
--- /dev/null
+++ b/test/helpers/accountScopeRestoreContract.test.js
@@ -0,0 +1,48 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+const read = (relativePath) => fs.readFileSync(path.join(__dirname, "../..", relativePath), "utf8");
+
+// The offline scope-restore behavior hangs off wiring points that unit
+// tests cannot reach; pin them at the source level.
+test("scope handler evaluates requests through the binding policy and persists validated bindings", () => {
+ const source = read("src/helpers/ipcHandlers.js");
+ const handler = source.match(
+ /ipcMain\.handle\("set-active-account-scope"([\s\S]*?)ipcMain\.handle\("delete-account-data"/
+ );
+ assert.ok(handler, "set-active-account-scope handler is present");
+ assert.ok(
+ handler[1].includes("accountScopeBinding.evaluateScopeRequest"),
+ "handler delegates its gate to evaluateScopeRequest"
+ );
+ assert.ok(
+ handler[1].includes("accountScopeBinding.persist(accountId, state.token)"),
+ "validated non-null scope persists the binding"
+ );
+ assert.ok(
+ handler[1].includes("accountScopeBinding.clear()"),
+ "validated signed-out scope clears the binding"
+ );
+});
+
+test("clearing the bearer token also clears the persisted scope binding", () => {
+ const source = read("src/helpers/ipcHandlers.js");
+ const subscription = source.match(
+ /tokenStore\.subscribe\(\(\{ generation, token \}\) => \{([\s\S]*?)broadcastToWindows/
+ );
+ assert.ok(subscription, "token subscription is present");
+ assert.ok(subscription[1].includes("setActiveAccountId(null)"));
+ assert.ok(subscription[1].includes("accountScopeBinding.clear()"));
+});
+
+test("boot restores the validated scope before any main-process consumer constructs", () => {
+ const source = read("main.js");
+ const bootWindow = source.match(
+ /databaseManager = new DatabaseManager\(\);([\s\S]*?)new IPCHandlers\(/
+ );
+ assert.ok(bootWindow, "DatabaseManager constructs before IPCHandlers");
+ assert.ok(bootWindow[1].includes("resolveBootAccountScope"));
+ assert.ok(bootWindow[1].includes("databaseManager.setActiveAccountId(bootAccountId)"));
+});
diff --git a/test/helpers/containerConversationsDatabase.test.js b/test/helpers/containerConversationsDatabase.test.js
index 7c4f54c8b..400d28b32 100644
--- a/test/helpers/containerConversationsDatabase.test.js
+++ b/test/helpers/containerConversationsDatabase.test.js
@@ -49,7 +49,9 @@ function createDb(t) {
}
try {
- return new DatabaseManager();
+ const database = new DatabaseManager();
+ database.setActiveAccountId("test-account");
+ return database;
} catch (error) {
if (isNativeBindingUnavailable(error)) {
t.skip("better-sqlite3 native binding is not available for this Node runtime");
@@ -73,6 +75,9 @@ function createTestTeamSpace(db, { name, emoji = null } = {}) {
emoji,
(maxOrder?.max_order ?? 0) + 1
);
+ db.db
+ .prepare("INSERT INTO space_accounts (space_id, account_id) VALUES (?, ?)")
+ .run(result.lastInsertRowid, "test-account");
return { success: true, space: db.getSpace(result.lastInsertRowid) };
}
@@ -300,7 +305,7 @@ test("getNoteIdsInScope validates vector candidates against the current SQLite s
);
});
-test("upsertNoteFromCloud round-trips updated_by_user_id", (t) => {
+test("upsertNoteFromCloud preserves omitted and clears explicit-null updated_by_user_id", (t) => {
const db = createDb(t);
if (!db) return;
const privateId = db.getPrivateSpaceId();
@@ -324,13 +329,24 @@ test("upsertNoteFromCloud round-trips updated_by_user_id", (t) => {
);
assert.equal(updated.updated_by_user_id, "user-b");
- // A pull without the field must keep the last known editor.
+ const cloudNoteWithoutUpdater = { ...cloudNote };
+ delete cloudNoteWithoutUpdater.updated_by_user_id;
+
+ // Older API responses that omit the field must keep the last known editor.
const unchanged = db.upsertNoteFromCloud(
- { ...cloudNote, updated_by_user_id: null, updated_at: "2026-07-03 10:00:00" },
+ { ...cloudNoteWithoutUpdater, updated_at: "2026-07-03 10:00:00" },
null,
privateId
);
assert.equal(unchanged.updated_by_user_id, "user-b");
+
+ // Explicit null clears attribution after the former user is deleted.
+ const cleared = db.upsertNoteFromCloud(
+ { ...cloudNote, updated_by_user_id: null, updated_at: "2026-07-04 10:00:00" },
+ null,
+ privateId
+ );
+ assert.equal(cleared.updated_by_user_id, null);
});
// Container conversations die with their container (space purge, folder
@@ -699,6 +715,7 @@ test("denied folder delete restores the same notes, speakers, and conversations
db.db.close();
db = new DatabaseManager();
+ db.setActiveAccountId("test-account");
const restored = db.restoreFolderAfterDeniedDelete(folder.id);
assert.equal(restored.success, true);
assert.equal(restored.folder.id, folder.id);
diff --git a/test/helpers/deviceCleanupContract.test.js b/test/helpers/deviceCleanupContract.test.js
new file mode 100644
index 000000000..e07231f75
--- /dev/null
+++ b/test/helpers/deviceCleanupContract.test.js
@@ -0,0 +1,40 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+const ipcHandlersSource = fs.readFileSync(
+ path.join(__dirname, "../../src/helpers/ipcHandlers.js"),
+ "utf8"
+);
+
+const cleanupHandler = ipcHandlersSource.match(
+ /ipcMain\.handle\("cleanup-app", async \(event\) => \{([\s\S]*?)ipcMain\.handle\("update-hotkey"/
+);
+
+test("explicit device cleanup covers models, credentials, caches, and browser settings", () => {
+ assert.ok(cleanupHandler, "cleanup-app handler is present");
+ const source = cleanupHandler[1];
+
+ for (const operation of [
+ "deleteAllParakeetModels",
+ "diarizationManager?.deleteModels",
+ "modelManager.deleteAllModels",
+ "environmentManager?.clearAllPersistedData",
+ "tokenStore.clear",
+ "clearStorageData",
+ "clearCache",
+ "setAutoStartEnabled(false)",
+ ]) {
+ assert.ok(source.includes(operation), `device cleanup includes ${operation}`);
+ }
+
+ for (const cacheName of ["embedding-models", "qdrant-data", "qdrant-data-dev", "yt-dlp"]) {
+ assert.ok(source.includes(`"${cacheName}"`), `device cleanup removes ${cacheName}`);
+ }
+
+ assert.ok(
+ source.includes('"account-scope-binding.json"'),
+ "device cleanup removes the account scope binding"
+ );
+});
diff --git a/test/helpers/environmentVoiceAgentHotkey.test.js b/test/helpers/environmentVoiceAgentHotkey.test.js
index e8259d255..c3d3c9303 100644
--- a/test/helpers/environmentVoiceAgentHotkey.test.js
+++ b/test/helpers/environmentVoiceAgentHotkey.test.js
@@ -110,3 +110,39 @@ test("adopts a legacy chat-agent hotkey as the voice-agent hotkey", async (t) =>
assert.match(persistedEnv, /^VOICE_AGENT_KEY=CommandOrControl\+;$/m);
assert.doesNotMatch(persistedEnv, /^CHAT_AGENT_KEY=/m);
});
+
+test("device cleanup clears persisted settings and encrypted secret files", async (t) => {
+ const userDataDirectory = fs.mkdtempSync(
+ path.join(os.tmpdir(), "openwhispr-device-settings-cleanup-")
+ );
+ const environmentSnapshot = new Map(
+ ["OPENAI_API_KEY", "START_MINIMIZED"].map((name) => [
+ name,
+ { present: Object.hasOwn(process.env, name), value: process.env[name] },
+ ])
+ );
+ const originalResourcesPath = process.resourcesPath;
+ process.resourcesPath = userDataDirectory;
+ t.after(() => {
+ restoreEnvironment(environmentSnapshot);
+ process.resourcesPath = originalResourcesPath;
+ fs.rmSync(userDataDirectory, { recursive: true, force: true });
+ });
+
+ installDotenvStub(t);
+ const EnvironmentManager = loadEnvironmentManager(t, userDataDirectory);
+ const environmentManager = new EnvironmentManager();
+ const secureKeysDirectory = path.join(userDataDirectory, "secure-keys");
+ fs.mkdirSync(secureKeysDirectory, { recursive: true });
+ fs.writeFileSync(path.join(userDataDirectory, ".env"), "START_MINIMIZED=true\n");
+ fs.writeFileSync(path.join(secureKeysDirectory, "OPENAI_API_KEY.enc"), "secret");
+ process.env.OPENAI_API_KEY = "test-key";
+ process.env.START_MINIMIZED = "true";
+
+ await environmentManager.clearAllPersistedData();
+
+ assert.equal(process.env.OPENAI_API_KEY, undefined);
+ assert.equal(process.env.START_MINIMIZED, undefined);
+ assert.equal(fs.existsSync(path.join(userDataDirectory, ".env")), false);
+ assert.equal(fs.existsSync(secureKeysDirectory), false);
+});
diff --git a/test/helpers/folderDeleteRelocationContract.test.js b/test/helpers/folderDeleteRelocationContract.test.js
new file mode 100644
index 000000000..056c4369c
--- /dev/null
+++ b/test/helpers/folderDeleteRelocationContract.test.js
@@ -0,0 +1,32 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+const ipcHandlersSource = fs.readFileSync(
+ path.join(__dirname, "../../src/helpers/ipcHandlers.js"),
+ "utf8"
+);
+
+function handlerBody(channel, nextChannel) {
+ const match = ipcHandlersSource.match(
+ new RegExp(`ipcMain\\.handle\\("${channel}"([\\s\\S]*?)ipcMain\\.handle\\("${nextChannel}"`)
+ );
+ assert.ok(match, `${channel} handler is present`);
+ return match[1];
+}
+
+// Folder deletion releases other accounts' notes to the space root instead of
+// deleting them. Their markdown mirror files live under the folder's mirror
+// directory, which is removed with the folder — so the handlers must rewrite
+// every live relocated note at its new location.
+test("folder delete handlers rewrite relocated notes into the markdown mirror", () => {
+ for (const [channel, nextChannel] of [
+ ["db-delete-folder", "db-rename-folder"],
+ ["db-hard-delete-folder", "db-relocate-revoked-folder"],
+ ]) {
+ const source = handlerBody(channel, nextChannel);
+ assert.ok(source.includes("relocatedNotes"), `${channel} consumes relocatedNotes`);
+ assert.ok(source.includes("_asyncMirrorWrite"), `${channel} rewrites relocated mirror files`);
+ }
+});
diff --git a/test/helpers/noteSearch.test.js b/test/helpers/noteSearch.test.js
index ba783725f..357eb2b31 100644
--- a/test/helpers/noteSearch.test.js
+++ b/test/helpers/noteSearch.test.js
@@ -56,8 +56,17 @@ function createSearchDatabase() {
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
- deleted_at TEXT
+ deleted_at TEXT,
+ space_id INTEGER NOT NULL DEFAULT 1,
+ account_id TEXT
);
+ CREATE TABLE spaces (id INTEGER PRIMARY KEY, kind TEXT NOT NULL);
+ CREATE TABLE space_accounts (
+ space_id INTEGER NOT NULL,
+ account_id TEXT NOT NULL,
+ PRIMARY KEY (space_id, account_id)
+ );
+ INSERT INTO spaces (id, kind) VALUES (1, 'private');
CREATE VIRTUAL TABLE notes_fts USING fts5(title, content);
`);
@@ -81,6 +90,7 @@ function createSearchDatabase() {
const manager = Object.create(DatabaseManager.prototype);
manager.db = sqlite;
+ manager.activeAccountId = null;
return { manager, sqlite };
}
diff --git a/test/helpers/notesOwnerDatabase.test.js b/test/helpers/notesOwnerDatabase.test.js
index d7c50df64..6c185270f 100644
--- a/test/helpers/notesOwnerDatabase.test.js
+++ b/test/helpers/notesOwnerDatabase.test.js
@@ -49,7 +49,9 @@ function createDb(t) {
}
try {
- return new DatabaseManager();
+ const database = new DatabaseManager();
+ database.setActiveAccountId("test-account");
+ return database;
} catch (error) {
if (isNativeBindingUnavailable(error)) {
t.skip("better-sqlite3 native binding is not available for this Node runtime");
@@ -68,6 +70,9 @@ function createTestTeamSpace(db, name) {
"INSERT INTO spaces (client_space_id, kind, name, sort_order) VALUES (?, 'team', ?, ?)"
)
.run(`test-owner-space-${++nextSpaceId}`, name, (maxOrder?.max_order ?? 0) + 1);
+ db.db
+ .prepare("INSERT INTO space_accounts (space_id, account_id) VALUES (?, ?)")
+ .run(result.lastInsertRowid, "test-account");
return db.getSpace(result.lastInsertRowid);
}
@@ -89,11 +94,13 @@ test("owner_user_id migration is idempotent across launches", (t) => {
const columns = db.db.pragma("table_info('notes')").map((col) => col.name);
assert.ok(columns.includes("owner_user_id"));
+ assert.ok(columns.includes("created_by_user_id"));
db.db.close();
const db2 = new DatabaseManager();
const columns2 = db2.db.pragma("table_info('notes')").map((col) => col.name);
assert.ok(columns2.includes("owner_user_id"));
+ assert.ok(columns2.includes("created_by_user_id"));
db2.db.close();
});
@@ -114,6 +121,37 @@ test("upsertNoteFromCloud stores the cloud owner and never erases a known one",
db.db.close();
});
+test("cloud creator attribution clears without changing the operational owner", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ let note = db.upsertNoteFromCloud(
+ cloudNote({
+ user_id: "workspace-owner",
+ created_by_user_id: "departing-user",
+ updated_by_user_id: "departing-user",
+ }),
+ null
+ );
+ assert.equal(note.owner_user_id, "workspace-owner");
+ assert.equal(note.created_by_user_id, "departing-user");
+
+ note = db.upsertNoteFromCloud(
+ cloudNote({
+ user_id: "workspace-owner",
+ created_by_user_id: null,
+ updated_by_user_id: null,
+ updated_at: "2026-07-03T10:00:00.000Z",
+ }),
+ null
+ );
+ assert.equal(note.owner_user_id, "workspace-owner");
+ assert.equal(note.created_by_user_id, null);
+ assert.equal(note.updated_by_user_id, null);
+
+ db.db.close();
+});
+
test("setNoteOwnerFromCloud fills ownership without touching updated_at or sync_status", (t) => {
const db = createDb(t);
if (!db) return;
diff --git a/test/helpers/preloadAuthBridge.test.js b/test/helpers/preloadAuthBridge.test.js
index 60ef06c52..33c96cf6d 100644
--- a/test/helpers/preloadAuthBridge.test.js
+++ b/test/helpers/preloadAuthBridge.test.js
@@ -56,6 +56,18 @@ test("auth token-state listener strips the Electron event object", () => {
assert.equal(listeners.has("auth-token-state-changed"), false);
});
+test("account ownership operations forward the account and credential generation", async () => {
+ const { api, invocations } = loadPreloadApi();
+
+ await api.setActiveAccountScope("account-a", 7);
+ await api.deleteAccountData("account-a", 7);
+
+ assert.deepEqual(invocations, [
+ ["set-active-account-scope", "account-a", 7],
+ ["delete-account-data", "account-a", 7],
+ ]);
+});
+
test("meeting stop forwards the optional expected recording session ID", async () => {
const { api, invocations } = loadPreloadApi();
diff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.js
index 8edd9433b..12bb0213b 100644
--- a/test/helpers/spacesDatabase.test.js
+++ b/test/helpers/spacesDatabase.test.js
@@ -49,7 +49,9 @@ function createDb(t) {
}
try {
- return new DatabaseManager();
+ const database = new DatabaseManager();
+ database.setActiveAccountId("test-account");
+ return database;
} catch (error) {
if (isNativeBindingUnavailable(error)) {
t.skip("better-sqlite3 native binding is not available for this Node runtime");
@@ -68,6 +70,9 @@ function createTestTeamSpace(db, { name, emoji = null } = {}) {
"INSERT INTO spaces (client_space_id, kind, name, emoji, sort_order) VALUES (?, 'team', ?, ?, ?)"
)
.run(`test-team-space-${++nextTestTeamSpaceId}`, name, emoji, (maxOrder?.max_order ?? 0) + 1);
+ db.db
+ .prepare("INSERT INTO space_accounts (space_id, account_id) VALUES (?, ?)")
+ .run(result.lastInsertRowid, "test-account");
return { success: true, space: db.getSpace(result.lastInsertRowid) };
}
@@ -100,7 +105,8 @@ test("spaces migration is idempotent across launches", (t) => {
.all()
.map((row) => row.name);
assert.ok(indexes.includes("idx_folders_client_folder_id"));
- assert.ok(indexes.includes("idx_folders_space_name"));
+ assert.ok(indexes.includes("idx_folders_space_legacy_name"));
+ assert.ok(indexes.includes("idx_folders_space_account_name"));
const privates = db2.db
.prepare("SELECT COUNT(*) as count FROM spaces WHERE kind = 'private'")
diff --git a/test/lib/accountDeletionFlow.test.js b/test/lib/accountDeletionFlow.test.js
new file mode 100644
index 000000000..d87712557
--- /dev/null
+++ b/test/lib/accountDeletionFlow.test.js
@@ -0,0 +1,72 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { executeAccountDeletion } = require("../../src/lib/accountDeletionFlow.ts");
+
+function operations(overrides = {}) {
+ const calls = [];
+ return {
+ calls,
+ dependencies: {
+ deleteRemoteAccount: async () => calls.push("remote"),
+ deleteLocalAccountData: async () => calls.push("local-account"),
+ clearWorkspaceSessionState: async () => calls.push("workspace-session"),
+ signOut: async () => calls.push("sign-out"),
+ eraseDeviceData: async () => calls.push("erase-device"),
+ ...overrides,
+ },
+ };
+}
+
+test("a rejected server deletion leaves every local and auth boundary untouched", async () => {
+ const { calls, dependencies } = operations({
+ deleteRemoteAccount: async () => {
+ calls.push("remote");
+ throw new Error("server rejected deletion");
+ },
+ });
+
+ await assert.rejects(
+ executeAccountDeletion({ eraseDeviceData: true, dependencies }),
+ /server rejected deletion/
+ );
+ assert.deepEqual(calls, ["remote"]);
+});
+
+test("default account deletion preserves device-wide data", async () => {
+ const { calls, dependencies } = operations();
+
+ const result = await executeAccountDeletion({ eraseDeviceData: false, dependencies });
+
+ assert.deepEqual(calls, ["remote", "local-account", "workspace-session", "sign-out"]);
+ assert.deepEqual(result.localCleanupFailures, []);
+});
+
+test("explicit device erasure runs only after account cleanup and sign-out", async () => {
+ const { calls, dependencies } = operations();
+
+ const result = await executeAccountDeletion({ eraseDeviceData: true, dependencies });
+
+ assert.deepEqual(calls, [
+ "remote",
+ "local-account",
+ "workspace-session",
+ "sign-out",
+ "erase-device",
+ ]);
+ assert.deepEqual(result.localCleanupFailures, []);
+});
+
+test("a local account cleanup failure cannot strand the deleted remote session", async () => {
+ const { calls, dependencies } = operations({
+ deleteLocalAccountData: async () => {
+ calls.push("local-account");
+ throw new Error("database busy");
+ },
+ });
+
+ const result = await executeAccountDeletion({ eraseDeviceData: false, dependencies });
+
+ assert.deepEqual(calls, ["remote", "local-account", "workspace-session", "sign-out"]);
+ assert.deepEqual(result.localCleanupFailures, ["local-account-data"]);
+});
diff --git a/test/lib/authDeleteAccount.test.js b/test/lib/authDeleteAccount.test.js
new file mode 100644
index 000000000..30bd83f75
--- /dev/null
+++ b/test/lib/authDeleteAccount.test.js
@@ -0,0 +1,74 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+function installWindow(state) {
+ const previousWindow = global.window;
+ const values = new Map();
+ global.window = {
+ location: {
+ origin: "https://desktop.openwhispr.test",
+ href: "https://desktop.openwhispr.test",
+ },
+ localStorage: {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ },
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ electronAPI: {
+ onAuthTokenStateChanged: () => () => {},
+ authGetTokenState: async () => ({ ...state.tokenState }),
+ authSetToken: async () => ({ success: true, ...state.tokenState }),
+ cloudApiRequest: async (request) => {
+ state.requests.push(request);
+ return { success: true, data: { deleted: true } };
+ },
+ },
+ };
+ return () => {
+ global.window = previousWindow;
+ };
+}
+
+test("account deletion uses the validated bearer-generation cloud boundary", async (t) => {
+ const authContext = await import("../../src/lib/authRequestContext.ts");
+ authContext.resetAuthRequestContextForTests();
+ const state = {
+ tokenState: { token: "token-a", generation: 7 },
+ requests: [],
+ };
+ t.after(installWindow(state));
+
+ await authContext.handleAuthRequestSuccess({
+ data: { user: { id: "user-a" } },
+ response: new Response("{}", { status: 200 }),
+ request: {
+ url: "https://auth.openwhispr.test/api/auth/get-session",
+ headers: new Headers({ Authorization: "Bearer token-a" }),
+ openWhisprAuthGeneration: 7,
+ },
+ });
+ assert.equal(authContext.commitValidatedAuthContext(7, "user-a"), true);
+
+ const previousFetch = global.fetch;
+ global.fetch = async () => {
+ throw new Error("account deletion bypassed the main-process auth fence");
+ };
+ t.after(() => {
+ global.fetch = previousFetch;
+ });
+
+ const { deleteAccount } = await import("../../src/lib/accountDeletionRequest.ts");
+ await deleteAccount();
+
+ assert.deepEqual(state.requests, [
+ {
+ method: "DELETE",
+ path: "/api/auth/delete-account",
+ body: undefined,
+ public: undefined,
+ expectedAuthGeneration: 7,
+ },
+ ]);
+});