@bevel-software/platform-core-frontend 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Open-source core UI of the Bevel platform (raw TS/TSX source): workspace explorer/viewer, branches & change requests, Library, secrets, tools, access control.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -38,7 +38,7 @@
38
38
  "tailwind-merge": "^3.5.0",
39
39
  "xlsx": "^0.18.5",
40
40
  "yaml": "^2.9.0",
41
- "@bevel-software/platform-shared": "0.2.1"
41
+ "@bevel-software/platform-shared": "0.3.1"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@testing-library/jest-dom": "^6.9.1",
@@ -43,6 +43,7 @@ import { SecretsPage } from '../modules/secrets-vault/components/SecretsPage';
43
43
  import { AccountPage } from '../modules/auth/components/AccountPage';
44
44
  import { ExternalAgentAccessPage } from '../modules/toolbar/components/ExternalAgentAccessPage';
45
45
  import { AdminRolesPage } from '../modules/admin/components/AdminRolesPage';
46
+ import { UserAccountsPage } from '../modules/admin/components/UserAccountsPage';
46
47
  import { ToolsExplorerPage } from '../modules/tools/ToolsExplorerPage';
47
48
  import { LibraryPage } from '../modules/library/components/LibraryPage';
48
49
  import { OpenChangeRequestDialog } from '../modules/pr/components/OpenChangeRequestDialog';
@@ -302,6 +303,7 @@ export function ShellRoutes({ apps }: { apps: AppDef[] }) {
302
303
  <Route path="/account" element={<AccountPage />} />
303
304
  <Route path="/external-agent-access" element={<ExternalAgentAccessPage />} />
304
305
  <Route path="/roles-and-members" element={<AdminRolesPage />} />
306
+ <Route path="/user-accounts" element={<UserAccountsPage />} />
305
307
  <Route path="/tools" element={<ToolsExplorerPage />} />
306
308
  <Route path="/" element={<Navigate to={KB_ROUTE_PREFIX} replace />} />
307
309
  <Route path="*" element={<Navigate to={KB_ROUTE_PREFIX} replace />} />
@@ -0,0 +1,156 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { render, screen, waitFor, within } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { UserAccountsPage } from '../components/UserAccountsPage';
5
+ import { AdminContext } from '../state/admin.context';
6
+ import { AuthContext, type AuthContextValue } from '../../auth/state/auth.context';
7
+ import {
8
+ createAccount,
9
+ deleteAccount,
10
+ listAccounts,
11
+ } from '../../auth/services/account.api';
12
+
13
+ vi.mock('../../auth/services/account.api', () => ({
14
+ createAccount: vi.fn(),
15
+ deleteAccount: vi.fn(),
16
+ listAccounts: vi.fn(),
17
+ }));
18
+
19
+ const ME = { id: 'admin-1', email: 'admin@example.com', name: 'Admin' };
20
+ const ALICE = {
21
+ id: 'u-alice',
22
+ email: 'alice@example.com',
23
+ name: 'Alice',
24
+ hasPassword: false,
25
+ createdAt: '2026-01-01T00:00:00Z',
26
+ };
27
+
28
+ function renderPage(opts: { isAdmin?: boolean } = {}) {
29
+ const auth: AuthContextValue = {
30
+ user: ME,
31
+ token: 't',
32
+ isLoading: false,
33
+ login: vi.fn(async () => {}),
34
+ logout: vi.fn(),
35
+ };
36
+ return render(
37
+ <AuthContext.Provider value={auth}>
38
+ <AdminContext.Provider
39
+ value={{
40
+ isAdmin: opts.isAdmin ?? true,
41
+ unreadCount: 0,
42
+ lastSeen: null,
43
+ markSeen: () => {},
44
+ refresh: () => {},
45
+ rolesConfigCorrupted: false,
46
+ rolesConfigErrors: [],
47
+ runRolesRecovery: async () => {},
48
+ }}
49
+ >
50
+ <UserAccountsPage />
51
+ </AdminContext.Provider>
52
+ </AuthContext.Provider>,
53
+ );
54
+ }
55
+
56
+ beforeEach(() => {
57
+ vi.mocked(listAccounts)
58
+ .mockReset()
59
+ .mockResolvedValue([
60
+ { ...ME, hasPassword: true, createdAt: '2026-01-01T00:00:00Z' },
61
+ ALICE,
62
+ ]);
63
+ vi.mocked(deleteAccount).mockReset().mockResolvedValue(undefined);
64
+ vi.mocked(createAccount).mockReset().mockResolvedValue(undefined);
65
+ });
66
+
67
+ describe('UserAccountsPage', () => {
68
+ it('shows the admins-only state (and never loads) for non-admins', () => {
69
+ renderPage({ isAdmin: false });
70
+ expect(screen.getByText(/Admins only/)).toBeInTheDocument();
71
+ expect(listAccounts).not.toHaveBeenCalled();
72
+ });
73
+
74
+ it('lists accounts with sign-in method; own row offers no actions', async () => {
75
+ renderPage();
76
+ await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument());
77
+ expect(screen.getByText(/Single sign-on only/)).toBeInTheDocument();
78
+ expect(
79
+ screen.getByRole('button', { name: 'Set password for alice@example.com' }),
80
+ ).toBeInTheDocument();
81
+ expect(
82
+ screen.getByRole('button', { name: 'Delete account alice@example.com' }),
83
+ ).toBeInTheDocument();
84
+ expect(
85
+ screen.queryByRole('button', { name: 'Set password for admin@example.com' }),
86
+ ).not.toBeInTheDocument();
87
+ expect(
88
+ screen.queryByRole('button', { name: 'Delete account admin@example.com' }),
89
+ ).not.toBeInTheDocument();
90
+ });
91
+
92
+ it('sets a password for a user WITHOUT touching their name', async () => {
93
+ renderPage();
94
+ await waitFor(() => screen.getByText('Alice'));
95
+ await userEvent.click(screen.getByRole('button', { name: 'Set password for alice@example.com' }));
96
+ const dialog = within(screen.getByRole('dialog'));
97
+ // Empty password → the confirm button stays disabled; nothing is sent.
98
+ expect(dialog.getByRole('button', { name: 'Set password' })).toBeDisabled();
99
+ await userEvent.type(dialog.getByLabelText('New password'), 'fresh-password-1');
100
+ await userEvent.click(dialog.getByRole('button', { name: 'Set password' }));
101
+ await waitFor(() =>
102
+ expect(createAccount).toHaveBeenCalledWith('alice@example.com', '', 'fresh-password-1'),
103
+ );
104
+ expect(await screen.findByRole('status')).toHaveTextContent(
105
+ 'Password set for alice@example.com',
106
+ );
107
+ });
108
+
109
+ it('deletes an account after confirmation', async () => {
110
+ renderPage();
111
+ await waitFor(() => screen.getByText('Alice'));
112
+ await userEvent.click(screen.getByRole('button', { name: 'Delete account alice@example.com' }));
113
+ const dialog = within(screen.getByRole('dialog'));
114
+ await userEvent.click(dialog.getByRole('button', { name: 'Delete account' }));
115
+ await waitFor(() => expect(deleteAccount).toHaveBeenCalledWith('u-alice'));
116
+ // List reloaded after the delete.
117
+ expect(listAccounts).toHaveBeenCalledTimes(2);
118
+ });
119
+
120
+ it('a failed delete closes the dialog, surfaces the error, and does not reload', async () => {
121
+ vi.mocked(deleteAccount).mockRejectedValueOnce(new Error('Failed to erase user'));
122
+ renderPage();
123
+ await waitFor(() => screen.getByText('Alice'));
124
+ await userEvent.click(screen.getByRole('button', { name: 'Delete account alice@example.com' }));
125
+ const dialog = within(screen.getByRole('dialog'));
126
+ await userEvent.click(dialog.getByRole('button', { name: 'Delete account' }));
127
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
128
+ expect(screen.getByText('Failed to erase user')).toBeInTheDocument();
129
+ expect(listAccounts).toHaveBeenCalledTimes(1);
130
+ });
131
+
132
+ it('adds a new account and refreshes the list', async () => {
133
+ renderPage();
134
+ await waitFor(() => screen.getByText('Alice'));
135
+ await userEvent.type(screen.getByLabelText('Email'), 'bob@example.com');
136
+ await userEvent.type(screen.getByLabelText(/Name/), 'Bob');
137
+ await userEvent.type(screen.getByLabelText('Password'), 'bobs-password-1');
138
+ await userEvent.click(screen.getByRole('button', { name: 'Add account' }));
139
+ await waitFor(() =>
140
+ expect(createAccount).toHaveBeenCalledWith('bob@example.com', 'Bob', 'bobs-password-1'),
141
+ );
142
+ expect(listAccounts).toHaveBeenCalledTimes(2);
143
+ });
144
+
145
+ it('surfaces an add failure inline', async () => {
146
+ vi.mocked(createAccount).mockRejectedValueOnce(
147
+ new Error('Password must be at least 8 characters'),
148
+ );
149
+ renderPage();
150
+ await waitFor(() => screen.getByText('Alice'));
151
+ await userEvent.type(screen.getByLabelText('Email'), 'bob@example.com');
152
+ await userEvent.type(screen.getByLabelText('Password'), 'short');
153
+ await userEvent.click(screen.getByRole('button', { name: 'Add account' }));
154
+ expect(await screen.findByRole('alert')).toHaveTextContent('at least 8 characters');
155
+ });
156
+ });
@@ -14,7 +14,6 @@ import {
14
14
  type RoleRosterEntry,
15
15
  } from '../services/roles.api';
16
16
  import { suggestPrincipals } from '../../access/api';
17
- import { AccountsSection } from './AccountsSection';
18
17
 
19
18
  /** The default-branch workspace id — roles are managed there (admin status derives from it). */
20
19
  const ROLES_WORKSPACE_ID = encodeURIComponent(DEFAULT_BRANCH);
@@ -254,7 +253,6 @@ export function AdminRolesPage() {
254
253
  ))}
255
254
  </div>
256
255
  )}
257
- <AccountsSection />
258
256
  </PageShell>
259
257
  );
260
258
  }
@@ -0,0 +1,353 @@
1
+ import { useCallback, useEffect, useState, type FormEvent } from 'react';
2
+ import { PageShell } from '../../../shared/components/PageShell';
3
+ import { Dialog } from '../../../shared/components/Dialog';
4
+ import { useAdmin } from '../state/admin.context';
5
+ import { useAuth } from '../../auth/state/auth.context';
6
+ import {
7
+ createAccount,
8
+ deleteAccount,
9
+ listAccounts,
10
+ type AccountSummary,
11
+ } from '../../auth/services/account.api';
12
+
13
+ /**
14
+ * The User Accounts page (`/user-accounts`, admins only) — the ONE
15
+ * account-management surface: every account on the deployment, whether it can
16
+ * sign in with a password, set a user's password (accounts that predate
17
+ * per-user passwords can't sign in until an admin sets one), permanently
18
+ * delete an account (the GDPR erasure path — overlays contribute their data
19
+ * slices via erasure participants), and add a new account. Password
20
+ * set/create both go through `POST /api/admin/accounts`, an upsert-by-email
21
+ * that preserves an existing display name when none is supplied. The
22
+ * signed-in admin's own row offers neither action — the backend refuses
23
+ * self-erasure, and their own password lives on the Account page.
24
+ */
25
+ export function UserAccountsPage() {
26
+ const { isAdmin } = useAdmin();
27
+ const { user: me } = useAuth();
28
+ const [accounts, setAccounts] = useState<AccountSummary[] | null>(null);
29
+ const [error, setError] = useState<string | null>(null);
30
+ // The account awaiting delete confirmation; non-null drives the confirm
31
+ // Dialog. `deleting` keeps the confirm open while the request is in flight.
32
+ const [pendingDelete, setPendingDelete] = useState<AccountSummary | null>(null);
33
+ const [deleting, setDeleting] = useState(false);
34
+ // The account whose password is being set; non-null drives the password
35
+ // Dialog. Success feedback surfaces inline above the list.
36
+ const [passwordTarget, setPasswordTarget] = useState<AccountSummary | null>(null);
37
+ const [newPassword, setNewPassword] = useState('');
38
+ const [passwordError, setPasswordError] = useState<string | null>(null);
39
+ const [savingPassword, setSavingPassword] = useState(false);
40
+ const [passwordSetFor, setPasswordSetFor] = useState<string | null>(null);
41
+ // Add-account form.
42
+ const [addEmail, setAddEmail] = useState('');
43
+ const [addName, setAddName] = useState('');
44
+ const [addPassword, setAddPassword] = useState('');
45
+ const [addError, setAddError] = useState<string | null>(null);
46
+ const [adding, setAdding] = useState(false);
47
+
48
+ const refresh = useCallback(() => {
49
+ listAccounts()
50
+ .then((rows) => {
51
+ setAccounts(rows);
52
+ setError(null);
53
+ })
54
+ .catch((err) => {
55
+ setError(err instanceof Error ? err.message : "Couldn't load accounts.");
56
+ // Leave no eternal "Loading…" next to the error banner.
57
+ setAccounts((prev) => prev ?? []);
58
+ });
59
+ }, []);
60
+
61
+ useEffect(() => {
62
+ if (isAdmin) refresh();
63
+ }, [isAdmin, refresh]);
64
+
65
+ async function confirmDelete() {
66
+ if (!pendingDelete || deleting) return;
67
+ setDeleting(true);
68
+ setError(null);
69
+ try {
70
+ await deleteAccount(pendingDelete.id);
71
+ setPendingDelete(null);
72
+ refresh();
73
+ } catch (err) {
74
+ setPendingDelete(null);
75
+ setError(err instanceof Error ? err.message : "Couldn't delete this account.");
76
+ } finally {
77
+ setDeleting(false);
78
+ }
79
+ }
80
+
81
+ function openPasswordDialog(account: AccountSummary) {
82
+ setPasswordTarget(account);
83
+ setNewPassword('');
84
+ setPasswordError(null);
85
+ setPasswordSetFor(null);
86
+ }
87
+
88
+ async function confirmSetPassword() {
89
+ if (!passwordTarget || savingPassword || newPassword.length === 0) return;
90
+ setSavingPassword(true);
91
+ setPasswordError(null);
92
+ try {
93
+ // No name → the upsert keeps the account's existing display name.
94
+ await createAccount(passwordTarget.email, '', newPassword);
95
+ setPasswordSetFor(passwordTarget.email);
96
+ setPasswordTarget(null);
97
+ refresh();
98
+ } catch (err) {
99
+ setPasswordError(err instanceof Error ? err.message : "Couldn't set the password.");
100
+ } finally {
101
+ setSavingPassword(false);
102
+ }
103
+ }
104
+
105
+ async function handleAdd(e: FormEvent<HTMLFormElement>) {
106
+ e.preventDefault();
107
+ if (adding) return;
108
+ setAdding(true);
109
+ setAddError(null);
110
+ try {
111
+ await createAccount(addEmail.trim(), addName.trim(), addPassword);
112
+ setAddEmail('');
113
+ setAddName('');
114
+ setAddPassword('');
115
+ refresh();
116
+ } catch (err) {
117
+ setAddError(err instanceof Error ? err.message : "Couldn't add the account.");
118
+ } finally {
119
+ setAdding(false);
120
+ }
121
+ }
122
+
123
+ if (!isAdmin) {
124
+ return (
125
+ <PageShell title="User accounts">
126
+ <div className="text-sm text-slate-600">
127
+ Admins only. Ask an admin if you need an account created or changed.
128
+ </div>
129
+ </PageShell>
130
+ );
131
+ }
132
+
133
+ const inputClass =
134
+ 'w-full rounded-md bg-slate-100 border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:outline-none focus:border-slate-400';
135
+
136
+ return (
137
+ <>
138
+ <PageShell title="User accounts">
139
+ <div className="space-y-4">
140
+ <p className="text-xs text-slate-600 leading-snug">
141
+ Everyone with an account on this deployment. Deleting an account permanently removes
142
+ the person&apos;s data and anonymizes their past review activity; their saves in the
143
+ knowledge base keep their history. Setting a password lets someone sign in with
144
+ email + password (existing accounts keep everything else).
145
+ </p>
146
+
147
+ {error && (
148
+ <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1.5">
149
+ {error}
150
+ </div>
151
+ )}
152
+ {passwordSetFor && (
153
+ <div
154
+ className="text-xs text-emerald-700 bg-emerald-50 border border-emerald-200 rounded px-2 py-1.5"
155
+ role="status"
156
+ >
157
+ Password set for {passwordSetFor}.
158
+ </div>
159
+ )}
160
+
161
+ {accounts === null ? (
162
+ <div className="text-xs text-slate-600">Loading…</div>
163
+ ) : accounts.length === 0 ? (
164
+ <div className="text-xs text-slate-600">No user accounts.</div>
165
+ ) : (
166
+ <ul className="divide-y divide-slate-200 border border-slate-200 rounded">
167
+ {accounts.map((account) => {
168
+ const isSelf = account.id === me?.id;
169
+ return (
170
+ <li key={account.id} className="flex items-center gap-3 px-3 py-2 text-sm">
171
+ <div className="flex-1 min-w-0">
172
+ <div className="font-medium truncate">
173
+ {account.name}
174
+ {isSelf && (
175
+ <span className="ml-1.5 text-[11px] font-normal text-slate-500">(you)</span>
176
+ )}
177
+ </div>
178
+ <div className="text-[11px] text-slate-600 truncate">
179
+ {account.email} · Joined {new Date(account.createdAt).toLocaleDateString()} ·{' '}
180
+ {account.hasPassword ? 'Password sign-in' : 'Single sign-on only'}
181
+ </div>
182
+ </div>
183
+ {!isSelf && (
184
+ <button
185
+ onClick={() => openPasswordDialog(account)}
186
+ className="text-xs px-2 py-1 rounded text-slate-700 hover:bg-slate-100 border border-slate-200"
187
+ title="Set a new sign-in password for this account."
188
+ aria-label={`Set password for ${account.email}`}
189
+ >
190
+ Set password
191
+ </button>
192
+ )}
193
+ {!isSelf && (
194
+ <button
195
+ onClick={() => setPendingDelete(account)}
196
+ className="text-xs px-2 py-1 rounded text-red-700 hover:bg-red-50 border border-red-200"
197
+ title="Permanently delete this account and its personal data."
198
+ aria-label={`Delete account ${account.email}`}
199
+ >
200
+ Delete account
201
+ </button>
202
+ )}
203
+ </li>
204
+ );
205
+ })}
206
+ </ul>
207
+ )}
208
+
209
+ <form onSubmit={handleAdd} className="border-t border-slate-200 pt-3 space-y-2 max-w-md">
210
+ <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">
211
+ Add account
212
+ </div>
213
+ <div className="grid grid-cols-2 gap-2">
214
+ <label className="block space-y-1">
215
+ <span className="text-xs text-slate-600">Email</span>
216
+ <input
217
+ type="email"
218
+ required
219
+ value={addEmail}
220
+ onChange={(e) => setAddEmail(e.target.value)}
221
+ className={inputClass}
222
+ />
223
+ </label>
224
+ <label className="block space-y-1">
225
+ <span className="text-xs text-slate-600">
226
+ Name <span className="text-slate-400">(optional)</span>
227
+ </span>
228
+ <input
229
+ type="text"
230
+ value={addName}
231
+ onChange={(e) => setAddName(e.target.value)}
232
+ className={inputClass}
233
+ />
234
+ </label>
235
+ </div>
236
+ <label className="block space-y-1">
237
+ <span className="text-xs text-slate-600">Password</span>
238
+ <input
239
+ type="password"
240
+ required
241
+ autoComplete="new-password"
242
+ value={addPassword}
243
+ onChange={(e) => setAddPassword(e.target.value)}
244
+ className={inputClass}
245
+ />
246
+ </label>
247
+ {addError && (
248
+ <div className="text-xs text-red-600" role="alert">
249
+ {addError}
250
+ </div>
251
+ )}
252
+ <button
253
+ type="submit"
254
+ disabled={adding}
255
+ className="rounded-md bg-bevel text-white text-sm font-medium px-3 py-1.5 hover:bg-bevel-deep disabled:opacity-60 disabled:cursor-not-allowed"
256
+ >
257
+ {adding ? 'Adding…' : 'Add account'}
258
+ </button>
259
+ </form>
260
+ </div>
261
+ </PageShell>
262
+
263
+ <Dialog
264
+ open={passwordTarget !== null}
265
+ onClose={() => setPasswordTarget(null)}
266
+ title="Set password"
267
+ size="sm"
268
+ busy={savingPassword}
269
+ footer={
270
+ <>
271
+ <button
272
+ onClick={() => setPasswordTarget(null)}
273
+ disabled={savingPassword}
274
+ className="px-3 py-1.5 text-sm rounded text-slate-700 hover:bg-slate-100 border border-slate-200 disabled:opacity-50"
275
+ >
276
+ Cancel
277
+ </button>
278
+ <button
279
+ onClick={confirmSetPassword}
280
+ disabled={savingPassword || newPassword.length === 0}
281
+ className="px-3 py-1.5 text-sm rounded bg-bevel hover:bg-bevel-deep text-white disabled:opacity-50"
282
+ >
283
+ {savingPassword ? 'Saving…' : 'Set password'}
284
+ </button>
285
+ </>
286
+ }
287
+ >
288
+ <div className="space-y-2">
289
+ <p className="text-xs text-slate-700 leading-snug">
290
+ New sign-in password for{' '}
291
+ <span className="font-medium">
292
+ {passwordTarget?.name} ({passwordTarget?.email})
293
+ </span>
294
+ . Share it with them out-of-band; they can change it later on their Account page.
295
+ </p>
296
+ <label className="block space-y-1">
297
+ <span className="text-xs text-slate-600">New password</span>
298
+ <input
299
+ type="password"
300
+ autoComplete="new-password"
301
+ value={newPassword}
302
+ onChange={(e) => setNewPassword(e.target.value)}
303
+ className={inputClass}
304
+ />
305
+ </label>
306
+ {passwordError && (
307
+ <div className="text-xs text-red-600" role="alert">
308
+ {passwordError}
309
+ </div>
310
+ )}
311
+ </div>
312
+ </Dialog>
313
+
314
+ <Dialog
315
+ open={pendingDelete !== null}
316
+ onClose={() => setPendingDelete(null)}
317
+ title="Delete user account"
318
+ size="sm"
319
+ busy={deleting}
320
+ footer={
321
+ <>
322
+ <button
323
+ onClick={() => setPendingDelete(null)}
324
+ disabled={deleting}
325
+ className="px-3 py-1.5 text-sm rounded text-slate-700 hover:bg-slate-100 border border-slate-200 disabled:opacity-50"
326
+ >
327
+ Cancel
328
+ </button>
329
+ <button
330
+ onClick={confirmDelete}
331
+ disabled={deleting}
332
+ className="px-3 py-1.5 text-sm rounded bg-red-600 hover:bg-red-700 text-white disabled:opacity-50 disabled:hover:bg-red-600"
333
+ >
334
+ {deleting ? 'Deleting…' : 'Delete account'}
335
+ </button>
336
+ </>
337
+ }
338
+ >
339
+ <p className="text-xs text-slate-700 leading-snug">
340
+ Permanently delete{' '}
341
+ <span className="font-medium">
342
+ {pendingDelete?.name} ({pendingDelete?.email})
343
+ </span>
344
+ ? This removes their personal data for good and anonymizes their past review activity.
345
+ Their saves in the knowledge base keep their history.{' '}
346
+ {pendingDelete?.hasPassword
347
+ ? 'To sign in again they will need an admin to create a new account for them.'
348
+ : 'They can sign in again later with single sign-on, but will start fresh.'}
349
+ </p>
350
+ </Dialog>
351
+ </>
352
+ );
353
+ }
@@ -32,43 +32,6 @@ export async function fetchAdminAccess(): Promise<{ isAdmin: boolean }> {
32
32
  return res.json();
33
33
  }
34
34
 
35
- /** One user account, as the admin user-administration dialog lists them. */
36
- export interface AdminUser {
37
- id: string;
38
- email: string;
39
- name: string;
40
- /** Epoch ms of account creation. */
41
- createdAt: number;
42
- }
43
-
44
- export async function fetchAdminUsers(): Promise<AdminUser[]> {
45
- const res = await authFetch('/api/admin/users');
46
- if (!res.ok) throw new Error('Failed to load user accounts');
47
- const body = (await res.json()) as { users: AdminUser[] };
48
- return body.users;
49
- }
50
-
51
- /**
52
- * Permanently erase a user account (GDPR erasure path). The backend deletes
53
- * the account and its personal data and anonymizes the user's past review
54
- * activity; it refuses self-deletion (400).
55
- */
56
- export async function deleteAdminUser(userId: string): Promise<void> {
57
- const res = await authFetch(`/api/admin/users/${encodeURIComponent(userId)}`, {
58
- method: 'DELETE',
59
- });
60
- if (!res.ok) {
61
- let serverError: string | undefined;
62
- try {
63
- const body = (await res.json()) as { error?: string };
64
- if (typeof body.error === 'string' && body.error.length > 0) serverError = body.error;
65
- } catch {
66
- // Non-JSON error body — fall through to the fallback message.
67
- }
68
- throw new Error(serverError ?? 'Failed to delete this account');
69
- }
70
- }
71
-
72
35
  export async function fetchFeedbackList(
73
36
  params: FeedbackListParams,
74
37
  ): Promise<FeedbackListItem[]> {
@@ -48,3 +48,15 @@ export async function createAccount(
48
48
  });
49
49
  if (!res.ok) throw new Error(await readError(res, 'Could not create account'));
50
50
  }
51
+
52
+ /**
53
+ * Permanently erase an account (GDPR erasure path). The backend deletes the
54
+ * account and its personal data and anonymizes the user's past review
55
+ * activity; it refuses self-deletion (400).
56
+ */
57
+ export async function deleteAccount(userId: string): Promise<void> {
58
+ const res = await authFetch(`/api/admin/accounts/${encodeURIComponent(userId)}`, {
59
+ method: 'DELETE',
60
+ });
61
+ if (!res.ok) throw new Error(await readError(res, 'Could not delete this account'));
62
+ }
@@ -99,6 +99,17 @@ const CORE_MENU_ITEMS: AdminMenuItem[] = [
99
99
  closeMenu();
100
100
  },
101
101
  },
102
+ {
103
+ id: 'user-accounts',
104
+ section: 'admin',
105
+ order: 20,
106
+ icon: <CircleUserRound size={14} />,
107
+ label: 'User accounts',
108
+ onSelect: ({ navigate, closeMenu }) => {
109
+ navigate('/user-accounts');
110
+ closeMenu();
111
+ },
112
+ },
102
113
  ];
103
114
 
104
115
  /**
@@ -1,151 +0,0 @@
1
- import { useCallback, useEffect, useState, type FormEvent } from 'react';
2
- import { Loader2 } from 'lucide-react';
3
- import {
4
- createAccount,
5
- listAccounts,
6
- type AccountSummary,
7
- } from '../../auth/services/account.api';
8
-
9
- /**
10
- * The Accounts block of the Roles & Members page (admins only — the page
11
- * itself gates): every known user, whether they can sign in with a password,
12
- * and a create form. "Create" is an upsert by email — entering an existing
13
- * account's email (re)sets that account's password, which doubles as the
14
- * admin reset flow for a locked-out user.
15
- */
16
- export function AccountsSection() {
17
- const [accounts, setAccounts] = useState<AccountSummary[] | null>(null);
18
- const [loadError, setLoadError] = useState<string | null>(null);
19
-
20
- const [email, setEmail] = useState('');
21
- const [name, setName] = useState('');
22
- const [password, setPassword] = useState('');
23
- const [formError, setFormError] = useState<string | null>(null);
24
- const [created, setCreated] = useState<string | null>(null);
25
- const [submitting, setSubmitting] = useState(false);
26
-
27
- const reload = useCallback(() => {
28
- listAccounts()
29
- .then((rows) => {
30
- setAccounts(rows);
31
- setLoadError(null);
32
- })
33
- .catch((err) => setLoadError(err instanceof Error ? err.message : 'Could not load accounts'));
34
- }, []);
35
-
36
- useEffect(() => {
37
- reload();
38
- }, [reload]);
39
-
40
- async function handleSubmit(e: FormEvent<HTMLFormElement>) {
41
- e.preventDefault();
42
- setFormError(null);
43
- setCreated(null);
44
- setSubmitting(true);
45
- try {
46
- await createAccount(email.trim(), name.trim(), password);
47
- setCreated(email.trim());
48
- setEmail('');
49
- setName('');
50
- setPassword('');
51
- reload();
52
- } catch (err) {
53
- setFormError(err instanceof Error ? err.message : 'Could not create account');
54
- } finally {
55
- setSubmitting(false);
56
- }
57
- }
58
-
59
- return (
60
- <div className="mt-6 border-t border-slate-200 pt-4 space-y-4">
61
- <div>
62
- <h2 className="text-sm font-semibold text-slate-800">Accounts</h2>
63
- <p className="text-xs text-slate-500 mt-0.5">
64
- Who can sign in with a password. Creating an account with an existing
65
- email resets that account's password.
66
- </p>
67
- </div>
68
-
69
- {loadError ? (
70
- <div className="p-3 text-sm text-red-700 bg-red-50 border border-red-200 rounded">
71
- {loadError}
72
- </div>
73
- ) : accounts === null ? (
74
- <div className="flex items-center gap-2 p-2 text-sm text-slate-600">
75
- <Loader2 size={14} className="animate-spin" /> Loading…
76
- </div>
77
- ) : accounts.length === 0 ? (
78
- <div className="p-2 text-sm text-slate-600">No accounts yet.</div>
79
- ) : (
80
- <ul className="divide-y divide-slate-100 border border-slate-200 rounded-md">
81
- {accounts.map((account) => (
82
- <li key={account.id} className="flex items-center gap-3 px-3 py-2 text-sm">
83
- <span className="font-medium text-slate-800">{account.name}</span>
84
- <span className="text-slate-500 truncate">{account.email}</span>
85
- <span className="ml-auto shrink-0 text-xs text-slate-500">
86
- {account.hasPassword ? 'Password sign-in' : 'Single sign-on only'}
87
- </span>
88
- </li>
89
- ))}
90
- </ul>
91
- )}
92
-
93
- <form onSubmit={handleSubmit} className="space-y-3 max-w-sm">
94
- <h3 className="text-xs font-semibold uppercase tracking-wide text-slate-500">
95
- Create account
96
- </h3>
97
- <label className="block space-y-1">
98
- <span className="text-xs text-slate-600">Email</span>
99
- <input
100
- type="email"
101
- required
102
- value={email}
103
- onChange={(e) => setEmail(e.target.value)}
104
- className="w-full rounded-md bg-slate-100 border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:outline-none focus:border-slate-400"
105
- />
106
- </label>
107
- <label className="block space-y-1">
108
- <span className="text-xs text-slate-600">
109
- Name <span className="text-slate-400">(optional)</span>
110
- </span>
111
- <input
112
- type="text"
113
- value={name}
114
- onChange={(e) => setName(e.target.value)}
115
- className="w-full rounded-md bg-slate-100 border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:outline-none focus:border-slate-400"
116
- />
117
- </label>
118
- <label className="block space-y-1">
119
- <span className="text-xs text-slate-600">Password</span>
120
- <input
121
- type="password"
122
- required
123
- autoComplete="new-password"
124
- value={password}
125
- onChange={(e) => setPassword(e.target.value)}
126
- className="w-full rounded-md bg-slate-100 border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:outline-none focus:border-slate-400"
127
- />
128
- </label>
129
-
130
- {formError && (
131
- <div className="text-sm text-red-600" role="alert">
132
- {formError}
133
- </div>
134
- )}
135
- {created && (
136
- <div className="text-sm text-emerald-700" role="status">
137
- Account for {created} saved.
138
- </div>
139
- )}
140
-
141
- <button
142
- type="submit"
143
- disabled={submitting}
144
- className="rounded-md bg-bevel text-white text-sm font-medium px-4 py-2 hover:bg-bevel-deep disabled:opacity-60 disabled:cursor-not-allowed"
145
- >
146
- {submitting ? 'Saving…' : 'Create account'}
147
- </button>
148
- </form>
149
- </div>
150
- );
151
- }