Deleted accounts: restore a kept account or destroy it now #173

Merged
jcoffey-dev merged 1 commits from feat/172-deleted-accounts into main 2026-11-08 07:04:52 +00:00
7 changed files with 515 additions and 0 deletions

No files matched your search

+4
View File
@@ -108,6 +108,10 @@ const CUSTOM_PAGES: Record<string, ComponentType> = {
() => 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,
@@ -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<Load>({ kind: 'loading' });
const [fetches, setFetches] = useState(0);
const [restoring, setRestoring] = useState<DeletedAccount | null>(null);
const [destroying, setDestroying] = useState<DeletedAccount | null>(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 (
<div className="mx-auto max-w-5xl space-y-5">
<PageHeader
icon="user-x"
title={t('deletedAccounts.title', 'Deleted accounts')}
subtitle={t(
'deletedAccounts.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.',
)}
/>
{load.kind === 'loading' && <LoadingFallback />}
{load.kind === 'error' && (
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">{load.message}</div>
)}
{load.kind === 'ready' && load.kept.length === 0 && (
<div className="rounded-lg border border-dashed p-12 text-center text-muted-foreground">
{t('deletedAccounts.none', 'No deleted account is being kept.')}
</div>
)}
{load.kind === 'ready' &&
load.kept.map((kept) => (
<div key={kept.id} className="rounded-xl border bg-card p-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2 font-medium">
<UserX className="h-4 w-4 text-muted-foreground" />
{kept.name}
</div>
{kept.addresses.length > 0 && <div className="truncate text-sm">{kept.addresses.join(', ')}</div>}
<div className="text-sm text-muted-foreground">
{t('deletedAccounts.dates', 'Deleted {{deleted}}. Destroyed for good on {{until}}.', {
deleted: when(kept.deletedAt),
until: when(kept.keptUntil),
})}
</div>
</div>
<div className="flex gap-2">
{canRestore && (
<Button variant="outline" size="sm" onClick={() => setRestoring(kept)}>
<RotateCcw className="mr-2 h-4 w-4" />
{t('deletedAccounts.restoreAction', 'Restore…')}
</Button>
)}
{canDestroy && (
<Button variant="outline" size="sm" onClick={() => setDestroying(kept)}>
<Trash2 className="mr-2 h-4 w-4" />
{t('deletedAccounts.destroyAction', 'Destroy now…')}
</Button>
)}
</div>
</div>
</div>
))}
{restoring && <RestoreDialog kept={restoring} onClose={() => setRestoring(null)} onDone={done} />}
{destroying && <DestroyDialog kept={destroying} onClose={() => setDestroying(null)} onDone={done} />}
</div>
);
}
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 (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('deletedAccounts.restoreTitle', 'Restore {{name}}', { name: kept.name })}</DialogTitle>
<DialogDescription>
{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.',
)}
</DialogDescription>
</DialogHeader>
<Input
type="password"
autoComplete="new-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={t('deletedAccounts.passwordPlaceholder', 'New password')}
aria-label={t('deletedAccounts.passwordPlaceholder', 'New password')}
/>
<DialogFooter>
<Button variant="ghost" onClick={onClose} disabled={busy}>
{t('deletedAccounts.cancel', 'Cancel')}
</Button>
<Button onClick={() => void run()} disabled={busy}>
{busy ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RotateCcw className="mr-2 h-4 w-4" />}
{t('deletedAccounts.restoreGo', 'Restore')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
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 (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('deletedAccounts.destroyTitle', 'Destroy {{name}} now', { name: kept.name })}</DialogTitle>
<DialogDescription>
{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.',
)}
</DialogDescription>
</DialogHeader>
<Input
value={typed}
onChange={(e) => setTyped(e.target.value)}
placeholder={kept.name}
aria-label={t('deletedAccounts.confirmName', 'Account name')}
autoComplete="off"
/>
<DialogFooter>
<Button variant="ghost" onClick={onClose} disabled={busy}>
{t('deletedAccounts.cancel', 'Cancel')}
</Button>
<Button variant="destructive" onClick={() => void run()} disabled={busy || typed.trim() !== kept.name}>
{busy ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Trash2 className="mr-2 h-4 w-4" />}
{t('deletedAccounts.destroyGo', 'Destroy')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -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<JmapMethodResponse[]>>(),
}));
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: ['[email protected]'],
memberTenantId: null,
deletedAt: '2026-11-07T10:00:00Z',
keptUntil: '2026-12-07T10:00:00Z',
}),
).toEqual({
id: 'b',
name: 'gone',
addresses: ['[email protected]'],
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');
});
});
@@ -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<string, Record<string, { description?: string; type?: string }> | undefined>)[
bucket
]?.[key];
return failed ? new Error(failed.description ?? failed.type ?? 'Not saved') : null;
}
export function fromServer(raw: Record<string, unknown>): 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<DeletedAccount[]> {
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<string, unknown>[] }).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<void> {
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<void> {
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;
}
+22
View File
@@ -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"
}
}
+1
View File
@@ -61,6 +61,7 @@ const PAGES: Record<string, PageRule> = {
'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
+1
View File
@@ -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'],