From dc1cb56ba7d4a0b6a87f50caaa393441d09d298d Mon Sep 17 00:00:00 2001 From: John Coffey Date: Sun, 8 Nov 2026 00:01:58 -0700 Subject: [PATCH] Deleted accounts: restore a kept account or destroy it now With account retention set, a deleted account is kept for the period with its name and addresses held, and until now the only way to restore it or free them early was a raw inbuxa:DeletedAccount call. The new page under Management > Directory lists kept accounts, soonest to go first, and restores one (a person with a new password, a group with none) or destroys it now after the name is typed to confirm. The server's reasons for a refusal, such as a legal hold or a weak password, are shown as they come. Shown to whoever may read accounts; restore needs sysAccountCreate and destroy sysAccountDestroy, the same checks the server makes. The menu link comes from the server's schema (inbuxa-server #315). Fixes #172 --- src/components/layout/MainContent.tsx | 4 + .../deletedAccounts/DeletedAccountsPage.tsx | 249 ++++++++++++++++++ .../deletedAccounts/deletedAccount.test.ts | 124 +++++++++ .../deletedAccounts/deletedAccount.ts | 114 ++++++++ src/i18n/en.json | 22 ++ src/lib/layout.ts | 1 + src/lib/layoutRules.test.ts | 1 + 7 files changed, 515 insertions(+) create mode 100644 src/features/deletedAccounts/DeletedAccountsPage.tsx create mode 100644 src/features/deletedAccounts/deletedAccount.test.ts create mode 100644 src/features/deletedAccounts/deletedAccount.ts diff --git a/src/components/layout/MainContent.tsx b/src/components/layout/MainContent.tsx index 81184a8..6b791db 100644 --- a/src/components/layout/MainContent.tsx +++ b/src/components/layout/MainContent.tsx @@ -108,6 +108,10 @@ const CUSTOM_PAGES: Record = { () => import('@/features/lock/SharedMailboxesPage'), (m) => m.SharedMailboxesPage, ), + DeletedAccounts: onDemand( + () => import('@/features/deletedAccounts/DeletedAccountsPage'), + (m) => m.DeletedAccountsPage, + ), Deliverability: onDemand( () => import('@/features/deliverability/DeliverabilityPage'), (m) => m.DeliverabilityPage, diff --git a/src/features/deletedAccounts/DeletedAccountsPage.tsx b/src/features/deletedAccounts/DeletedAccountsPage.tsx new file mode 100644 index 0000000..af81ffd --- /dev/null +++ b/src/features/deletedAccounts/DeletedAccountsPage.tsx @@ -0,0 +1,249 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** + * INBUXA: Management › Directory › Deleted accounts (undelete spec, UD-15 to + * UD-17a). Accounts kept after deletion because account retention is set, + * each restored or destroyed now from here. + */ + +import { useCallback, useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Loader2, RotateCcw, Trash2, UserX } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { PageHeader } from '@/components/common/PageHeader'; +import { LoadingFallback } from '@/components/common/LoadingFallback'; +import { toast } from '@/hooks/use-toast'; +import { useAccountStore } from '@/stores/accountStore'; +import { + DeletedAccountsUnavailable, + destroyDeletedAccount, + fetchDeletedAccounts, + restoreDeletedAccount, + type DeletedAccount, +} from './deletedAccount'; + +type Load = { kind: 'loading' } | { kind: 'ready'; kept: DeletedAccount[] } | { kind: 'error'; message: string }; + +const when = (value: string) => (value ? new Date(value).toLocaleString() : ''); + +export function DeletedAccountsPage() { + const { t } = useTranslation(); + const canRestore = useAccountStore((s) => s.hasPermission('sysAccountCreate')); + const canDestroy = useAccountStore((s) => s.hasPermission('sysAccountDestroy')); + const [load, setLoad] = useState({ kind: 'loading' }); + const [fetches, setFetches] = useState(0); + const [restoring, setRestoring] = useState(null); + const [destroying, setDestroying] = useState(null); + const refetch = useCallback(() => setFetches((n) => n + 1), []); + + useEffect(() => { + const controller = new AbortController(); + fetchDeletedAccounts(controller.signal) + .then((kept) => { + if (!controller.signal.aborted) setLoad({ kind: 'ready', kept }); + }) + .catch((e: unknown) => { + if (controller.signal.aborted) return; + setLoad({ + kind: 'error', + message: + e instanceof DeletedAccountsUnavailable + ? t('deletedAccounts.unavailable', 'This server doesn’t keep deleted accounts.') + : e instanceof Error + ? e.message + : String(e), + }); + }); + return () => controller.abort(); + }, [fetches, t]); + + const done = () => { + setRestoring(null); + setDestroying(null); + refetch(); + }; + + return ( +
+ + + {load.kind === 'loading' && } + {load.kind === 'error' && ( +
{load.message}
+ )} + {load.kind === 'ready' && load.kept.length === 0 && ( +
+ {t('deletedAccounts.none', 'No deleted account is being kept.')} +
+ )} + {load.kind === 'ready' && + load.kept.map((kept) => ( +
+
+
+
+ + {kept.name} +
+ {kept.addresses.length > 0 &&
{kept.addresses.join(', ')}
} +
+ {t('deletedAccounts.dates', 'Deleted {{deleted}}. Destroyed for good on {{until}}.', { + deleted: when(kept.deletedAt), + until: when(kept.keptUntil), + })} +
+
+
+ {canRestore && ( + + )} + {canDestroy && ( + + )} +
+
+
+ ))} + + {restoring && setRestoring(null)} onDone={done} />} + {destroying && setDestroying(null)} onDone={done} />} +
+ ); +} + +function RestoreDialog({ kept, onClose, onDone }: { kept: DeletedAccount; onClose: () => void; onDone: () => void }) { + const { t } = useTranslation(); + const [password, setPassword] = useState(''); + const [busy, setBusy] = useState(false); + + const run = async () => { + setBusy(true); + try { + await restoreDeletedAccount(kept.id, password); + toast({ title: t('deletedAccounts.restored', '{{name}} is back', { name: kept.name }) }); + onDone(); + } catch (e) { + toast({ + variant: 'destructive', + title: t('deletedAccounts.restoreFailed', 'The account wasn’t restored'), + description: e instanceof Error ? e.message : String(e), + }); + } finally { + setBusy(false); + } + }; + + return ( + !open && onClose()}> + + + {t('deletedAccounts.restoreTitle', 'Restore {{name}}', { name: kept.name })} + + {t( + 'deletedAccounts.restoreBody', + 'The account comes back as it was, with its mail, addresses and shares. A person signs in with the new password below; their other sign-in methods stay as they were. A group needs no password.', + )} + + + setPassword(e.target.value)} + placeholder={t('deletedAccounts.passwordPlaceholder', 'New password')} + aria-label={t('deletedAccounts.passwordPlaceholder', 'New password')} + /> + + + + + + + ); +} + +function DestroyDialog({ kept, onClose, onDone }: { kept: DeletedAccount; onClose: () => void; onDone: () => void }) { + const { t } = useTranslation(); + const [typed, setTyped] = useState(''); + const [busy, setBusy] = useState(false); + + const run = async () => { + setBusy(true); + try { + await destroyDeletedAccount(kept.id); + toast({ title: t('deletedAccounts.destroyed', '{{name}} was destroyed', { name: kept.name }) }); + onDone(); + } catch (e) { + toast({ + variant: 'destructive', + title: t('deletedAccounts.destroyFailed', 'The account wasn’t destroyed'), + description: e instanceof Error ? e.message : String(e), + }); + } finally { + setBusy(false); + } + }; + + return ( + !open && onClose()}> + + + {t('deletedAccounts.destroyTitle', 'Destroy {{name}} now', { name: kept.name })} + + {t( + 'deletedAccounts.destroyBody', + 'Its mail and data are destroyed now instead of when its time runs out, and its name and addresses can be used again. This can’t be undone. An account under a legal hold can’t be destroyed. Type the account’s name to confirm.', + )} + + + setTyped(e.target.value)} + placeholder={kept.name} + aria-label={t('deletedAccounts.confirmName', 'Account name')} + autoComplete="off" + /> + + + + + + + ); +} diff --git a/src/features/deletedAccounts/deletedAccount.test.ts b/src/features/deletedAccounts/deletedAccount.test.ts new file mode 100644 index 0000000..9857899 --- /dev/null +++ b/src/features/deletedAccounts/deletedAccount.test.ts @@ -0,0 +1,124 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { JmapMethodCall, JmapMethodResponse } from '@/types/jmap'; + +const mocks = vi.hoisted(() => ({ + jmapRequest: vi.fn<(calls: JmapMethodCall[]) => Promise>(), +})); + +vi.mock('@/services/jmap/client', () => ({ + getAccountId: () => 'admin', + jmapRequest: mocks.jmapRequest, +})); + +import { + DeletedAccountsUnavailable, + destroyDeletedAccount, + fetchDeletedAccounts, + fromServer, + restoreDeletedAccount, +} from './deletedAccount'; + +const sent = () => mocks.jmapRequest.mock.calls[0]![0][0]!; + +beforeEach(() => mocks.jmapRequest.mockReset()); + +describe('fromServer', () => { + it('reads what the server sends', () => { + expect( + fromServer({ + id: 'b', + name: 'gone', + addresses: ['gone@example.org'], + memberTenantId: null, + deletedAt: '2026-11-07T10:00:00Z', + keptUntil: '2026-12-07T10:00:00Z', + }), + ).toEqual({ + id: 'b', + name: 'gone', + addresses: ['gone@example.org'], + memberTenantId: null, + deletedAt: '2026-11-07T10:00:00Z', + keptUntil: '2026-12-07T10:00:00Z', + }); + }); + + it('copes with missing fields', () => { + expect(fromServer({ id: 'c' })).toMatchObject({ name: '', addresses: [], memberTenantId: null }); + }); +}); + +describe('fetchDeletedAccounts', () => { + it('lists them all, soonest to go first', async () => { + mocks.jmapRequest.mockResolvedValue([ + [ + 'inbuxa:DeletedAccount/get', + { + list: [ + { id: 'late', name: 'b', keptUntil: '2026-12-31T00:00:00Z' }, + { id: 'soon', name: 'a', keptUntil: '2026-11-30T00:00:00Z' }, + ], + }, + '0', + ], + ]); + const kept = await fetchDeletedAccounts(); + expect(kept.map((k) => k.id)).toEqual(['soon', 'late']); + expect(sent()).toEqual(['inbuxa:DeletedAccount/get', { accountId: 'admin', ids: null }, '0']); + }); + + it('says so when the server has no such method', async () => { + mocks.jmapRequest.mockResolvedValue([['error', { type: 'unknownMethod' }, '0']]); + await expect(fetchDeletedAccounts()).rejects.toBeInstanceOf(DeletedAccountsUnavailable); + }); +}); + +describe('restoreDeletedAccount', () => { + it('sends the new password', async () => { + mocks.jmapRequest.mockResolvedValue([['inbuxa:DeletedAccount/set', { updated: { b: null } }, '0']]); + await restoreDeletedAccount('b', 'a new passphrase'); + expect(sent()[1]).toEqual({ accountId: 'admin', update: { b: { restore: true, password: 'a new passphrase' } } }); + }); + + it('sends none for a group', async () => { + mocks.jmapRequest.mockResolvedValue([['inbuxa:DeletedAccount/set', { updated: { g: null } }, '0']]); + await restoreDeletedAccount('g', ''); + expect(sent()[1]).toEqual({ accountId: 'admin', update: { g: { restore: true } } }); + }); + + it('passes on why the server refused', async () => { + mocks.jmapRequest.mockResolvedValue([ + [ + 'inbuxa:DeletedAccount/set', + { notUpdated: { b: { type: 'invalidProperties', description: 'A restored account needs a new password.' } } }, + '0', + ], + ]); + await expect(restoreDeletedAccount('b', '')).rejects.toThrow('needs a new password'); + }); +}); + +describe('destroyDeletedAccount', () => { + it('destroys it', async () => { + mocks.jmapRequest.mockResolvedValue([['inbuxa:DeletedAccount/set', { destroyed: ['b'] }, '0']]); + await destroyDeletedAccount('b'); + expect(sent()[1]).toEqual({ accountId: 'admin', destroy: ['b'] }); + }); + + it('passes on a legal hold refusal', async () => { + mocks.jmapRequest.mockResolvedValue([ + [ + 'inbuxa:DeletedAccount/set', + { notDestroyed: { b: { type: 'forbidden', description: 'Under a legal hold.' } } }, + '0', + ], + ]); + await expect(destroyDeletedAccount('b')).rejects.toThrow('legal hold'); + }); +}); diff --git a/src/features/deletedAccounts/deletedAccount.ts b/src/features/deletedAccounts/deletedAccount.ts new file mode 100644 index 0000000..a3e170f --- /dev/null +++ b/src/features/deletedAccounts/deletedAccount.ts @@ -0,0 +1,114 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +/** + * INBUXA: `inbuxa:DeletedAccount` over JMAP (undelete spec, UD-15 to + * UD-17a). With account retention set, a deleted account is kept for the + * period with its name and addresses held. It can be restored, with a new + * password for a person, or destroyed now, which frees them. + */ + +import { getAccountId, jmapRequest } from '@/services/jmap/client'; + +export const INBUXA_CAPABILITY = 'urn:inbuxa:jmap'; +const OBJECT = 'inbuxa:DeletedAccount'; + +export interface DeletedAccount { + id: string; + name: string; + addresses: string[]; + memberTenantId: string | null; + /** RFC 3339. */ + deletedAt: string; + /** RFC 3339: when it's destroyed for good. */ + keptUntil: string; +} + +/** The server doesn't keep deleted accounts (an older server). */ +export class DeletedAccountsUnavailable extends Error { + constructor(reason: string) { + super(`Deleted accounts unavailable: ${reason}`); + } +} + +function methodError(name: string | undefined, result: unknown): Error { + const r = result as { type?: string; description?: string } | undefined; + if (r?.type === 'unknownMethod' || r?.type === 'unknownCapability') return new DeletedAccountsUnavailable(r.type); + return new Error(r?.description ?? r?.type ?? `${name ?? 'Request'} failed`); +} + +function setError(result: unknown, bucket: string, key: string): Error | null { + const failed = (result as Record | undefined>)[ + bucket + ]?.[key]; + return failed ? new Error(failed.description ?? failed.type ?? 'Not saved') : null; +} + +export function fromServer(raw: Record): DeletedAccount { + return { + id: String(raw.id ?? ''), + name: String(raw.name ?? ''), + addresses: Array.isArray(raw.addresses) ? raw.addresses.map(String) : [], + memberTenantId: typeof raw.memberTenantId === 'string' ? raw.memberTenantId : null, + deletedAt: String(raw.deletedAt ?? ''), + keptUntil: String(raw.keptUntil ?? ''), + }; +} + +/** Soonest to be destroyed first. */ +export function byKeptUntil(a: DeletedAccount, b: DeletedAccount): number { + return a.keptUntil.localeCompare(b.keptUntil) || a.name.localeCompare(b.name); +} + +/** Every kept account in reach. */ +export async function fetchDeletedAccounts(signal?: AbortSignal): Promise { + const responses = await jmapRequest( + [[`${OBJECT}/get`, { accountId: getAccountId('x:Account'), ids: null }, '0']], + signal, + [INBUXA_CAPABILITY], + ); + const [name, result] = responses[0] ?? []; + if (name !== `${OBJECT}/get`) throw methodError(name, result); + return ((result as { list?: Record[] }).list ?? []).map(fromServer).sort(byKeptUntil); +} + +/** + * Brings a kept account back under the same id. A person needs a new + * password; a group needs none, so an empty one isn't sent. + */ +export async function restoreDeletedAccount(id: string, password: string): Promise { + const responses = await jmapRequest( + [ + [ + `${OBJECT}/set`, + { + accountId: getAccountId('x:Account'), + update: { [id]: { restore: true, ...(password ? { password } : {}) } }, + }, + '0', + ], + ], + undefined, + [INBUXA_CAPABILITY], + ); + const [name, result] = responses[0] ?? []; + if (name !== `${OBJECT}/set`) throw methodError(name, result); + const failed = setError(result, 'notUpdated', id); + if (failed) throw failed; +} + +/** Destroys a kept account now, which frees its name and addresses. */ +export async function destroyDeletedAccount(id: string): Promise { + const responses = await jmapRequest( + [[`${OBJECT}/set`, { accountId: getAccountId('x:Account'), destroy: [id] }, '0']], + undefined, + [INBUXA_CAPABILITY], + ); + const [name, result] = responses[0] ?? []; + if (name !== `${OBJECT}/set`) throw methodError(name, result); + const failed = setError(result, 'notDestroyed', id); + if (failed) throw failed; +} diff --git a/src/i18n/en.json b/src/i18n/en.json index 225d9fa..4ae0835 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -2729,5 +2729,27 @@ "makeDefault": "Make it the default certificate", "failedNext": "Fix what the reason says, then use Order again on the Certificates page.", "tabTitle": "Order a certificate" + }, + "deletedAccounts": { + "unavailable": "This server doesn’t keep deleted accounts.", + "title": "Deleted accounts", + "subtitle": "With account retention set, a deleted account is kept for that time before it’s destroyed. Its name and addresses stay taken until then. Restore it, or destroy it now to free them.", + "none": "No deleted account is being kept.", + "dates": "Deleted {{deleted}}. Destroyed for good on {{until}}.", + "restoreAction": "Restore…", + "destroyAction": "Destroy now…", + "restored": "{{name}} is back", + "restoreFailed": "The account wasn’t restored", + "restoreTitle": "Restore {{name}}", + "restoreBody": "The account comes back as it was, with its mail, addresses and shares. A person signs in with the new password below; their other sign-in methods stay as they were. A group needs no password.", + "passwordPlaceholder": "New password", + "cancel": "Cancel", + "restoreGo": "Restore", + "destroyed": "{{name}} was destroyed", + "destroyFailed": "The account wasn’t destroyed", + "destroyTitle": "Destroy {{name}} now", + "destroyBody": "Its mail and data are destroyed now instead of when its time runs out, and its name and addresses can be used again. This can’t be undone. An account under a legal hold can’t be destroyed. Type the account’s name to confirm.", + "confirmName": "Account name", + "destroyGo": "Destroy" } } diff --git a/src/lib/layout.ts b/src/lib/layout.ts index e292f4a..4c19b47 100644 --- a/src/lib/layout.ts +++ b/src/lib/layout.ts @@ -61,6 +61,7 @@ const PAGES: Record = { 'CustomComponent/Relays': readOnly('sysRelay'), 'CustomComponent/AccountLocks': readOnly('sysAccountLock'), 'CustomComponent/SharedMailboxes': readOnly('sysAccountLock'), + 'CustomComponent/DeletedAccounts': readOnly('sysAccount'), 'CustomComponent/Deliverability': readOnly('sysDeliverability'), 'CustomComponent/ScheduledReports': readOnly('sysScheduledReport'), // A migration has no read permission of its own: running one is the right diff --git a/src/lib/layoutRules.test.ts b/src/lib/layoutRules.test.ts index 9ba448f..a0127a3 100644 --- a/src/lib/layoutRules.test.ts +++ b/src/lib/layoutRules.test.ts @@ -102,6 +102,7 @@ describe('isLinkVisible for the console’s own pages', () => { ['CustomComponent/Relays', 'sysRelay'], ['CustomComponent/AccountLocks', 'sysAccountLock'], ['CustomComponent/SharedMailboxes', 'sysAccountLock'], + ['CustomComponent/DeletedAccounts', 'sysAccount'], ['CustomComponent/Deliverability', 'sysDeliverability'], ['CustomComponent/ScheduledReports', 'sysScheduledReport'], ['Wizard/dns/connect', 'sysDomain'], -- 2.54.0