@bevel-software/platform-core-frontend 0.27.0 → 0.28.0

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.
Files changed (42) hide show
  1. package/package.json +2 -2
  2. package/src/core/ProductName.tsx +4 -4
  3. package/src/core/__tests__/ProductName.test.tsx +46 -0
  4. package/src/core/maker-url.ts +30 -0
  5. package/src/core/registry.ts +27 -0
  6. package/src/lib/__tests__/latest-request.test.ts +48 -0
  7. package/src/lib/latest-request.ts +45 -0
  8. package/src/modules/access/__tests__/ManageAccessDialog.no-sso-invite.test.tsx +222 -0
  9. package/src/modules/access/api.ts +19 -3
  10. package/src/modules/access/components/ManageAccessDialog.tsx +60 -7
  11. package/src/modules/admin/__tests__/AdminRolesPage.fixed-admin.test.tsx +16 -1
  12. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +284 -39
  13. package/src/modules/admin/components/AdminRolesPage.tsx +13 -14
  14. package/src/modules/admin/components/UserAccountsPage.tsx +91 -107
  15. package/src/modules/admin/services/roles.api.ts +14 -1
  16. package/src/modules/auth/__tests__/LoginScreen.test.tsx +80 -5
  17. package/src/modules/auth/__tests__/sso-strict-probe.test.ts +66 -0
  18. package/src/modules/auth/components/LoginScreen.tsx +100 -75
  19. package/src/modules/auth/services/account.api.ts +31 -2
  20. package/src/modules/auth/services/sso.ts +29 -8
  21. package/src/modules/auth/state/use-sign-in-methods.ts +41 -0
  22. package/src/modules/onboarding/__tests__/InviteButton.test.tsx +214 -0
  23. package/src/modules/onboarding/__tests__/first-page-prompt.test.ts +56 -1
  24. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +538 -81
  25. package/src/modules/onboarding/__tests__/invite-dialog.test.tsx +543 -124
  26. package/src/modules/onboarding/__tests__/invite-emails.test.ts +247 -0
  27. package/src/modules/onboarding/components/GetStartedColumn.tsx +30 -11
  28. package/src/modules/onboarding/components/InviteButton.tsx +119 -15
  29. package/src/modules/onboarding/components/InviteDialog.tsx +392 -75
  30. package/src/modules/onboarding/first-page-prompt.ts +34 -0
  31. package/src/modules/onboarding/invite-emails.ts +171 -33
  32. package/src/modules/onboarding/state/invite-dialog.context.ts +7 -4
  33. package/src/modules/onboarding/state/invite-dialog.tsx +12 -4
  34. package/src/modules/toolbar/commands/actions.tsx +10 -4
  35. package/src/modules/toolbar/commands/useCommandActions.ts +5 -3
  36. package/src/modules/toolbar/components/AppSwitcher.tsx +19 -0
  37. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +46 -1
  38. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +34 -2
  39. package/src/modules/workspace/hooks/__tests__/useCreatePage.test.ts +137 -0
  40. package/src/modules/workspace/hooks/__tests__/useKnowledgeWriteTarget.test.ts +302 -0
  41. package/src/modules/workspace/hooks/useCreatePage.ts +118 -28
  42. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +238 -0
@@ -1,8 +1,11 @@
1
- import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react';
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { Users } from 'lucide-react';
2
3
  import { PageShell } from '../../../shared/components/PageShell';
3
4
  import { Dialog } from '../../../shared/components/Dialog';
4
5
  import { useAdmin } from '../state/admin.context';
5
6
  import { useAuth } from '../../auth/state/auth.context';
7
+ import { useInviteDialog } from '../../onboarding/state/invite-dialog.context';
8
+ import { useLatestRequest } from '../../../lib/latest-request';
6
9
  import {
7
10
  createAccount,
8
11
  deactivateAccount,
@@ -20,7 +23,7 @@ import {
20
23
  * can be true, and the environment credential is the one that survives.
21
24
  */
22
25
  function signInMethodLabel(account: Pick<AccountSummary, 'hasPassword' | 'isEnvAdmin'>): string {
23
- if (account.isEnvAdmin) return 'Password (deployment admin)';
26
+ if (account.isEnvAdmin) return 'Password (owner)';
24
27
  if (account.hasPassword) return 'Password';
25
28
  return 'No password — signs in with single sign-on';
26
29
  }
@@ -32,7 +35,7 @@ function signInMethodLabel(account: Pick<AccountSummary, 'hasPassword' | 'isEnvA
32
35
  function signInAfterDelete(account: AccountSummary): string {
33
36
  const label = signInMethodLabel(account);
34
37
  if (account.isEnvAdmin) {
35
- return `${label}: they can still sign in with the deployment admin password, but will start fresh.`;
38
+ return `${label}: they can still sign in with the owner password set on the server, but will start fresh.`;
36
39
  }
37
40
  if (account.hasPassword) {
38
41
  return `${label}: to sign in again they will need an admin to create a new account for them.`;
@@ -40,6 +43,14 @@ function signInAfterDelete(account: AccountSummary): string {
40
43
  return `${label}: they can sign in again later with single sign-on, but will start fresh.`;
41
44
  }
42
45
 
46
+ /**
47
+ * Why an owner's address is never removed from access files, said where the
48
+ * delete dialog would offer it, until the server's own reason
49
+ * (`user-access-removal.service.ts`) has arrived, or when it could not be
50
+ * fetched. The server's words win once they are here.
51
+ */
52
+ const OWNER_ACCESS_NOTE = 'The owner stays in roles and access rules.';
53
+
43
54
  function plural(n: number, one: string, many: string): string {
44
55
  return `${n} ${n === 1 ? one : many}`;
45
56
  }
@@ -109,18 +120,27 @@ function passwordAction(account: Pick<AccountSummary, 'hasPassword'>): PasswordA
109
120
  * per-user passwords can't sign in until an admin sets one) or reset the one
110
121
  * they have — two acts the page names apart, see {@link PasswordAction} —
111
122
  * permanently delete an account (the GDPR erasure path — overlays contribute
112
- * their data slices via erasure participants), and add a new account. Set,
113
- * reset and create all go through `POST /api/admin/accounts`, an
114
- * upsert-by-email that preserves an existing display name when none is
115
- * supplied. The signed-in admin's own row offers neither action — the backend
123
+ * their data slices via erasure participants). New accounts come from the
124
+ * Invite dialog, the one way to create an account: the list ends with an
125
+ * "Invite new users" row that opens it, and is read again after each send.
126
+ * Set and reset go through `POST /api/admin/accounts`, an upsert-by-email
127
+ * that preserves an existing display name when none is supplied. The signed-in admin's own row offers neither action — the backend
116
128
  * refuses self-erasure, and their own password lives on the Account page. The
117
129
  * deployment admin's row offers no password action either, from any admin:
118
130
  * that account's password is set in the deployment environment, and the
119
131
  * backend refuses to store one for it.
132
+ *
133
+ * An owner's row (`ADMIN_EMAIL`; on the cloud, whoever created the
134
+ * workspace) is labelled "Owner" and offers no password action and no Switch
135
+ * off, from any admin, and Delete account only where the owner could sign
136
+ * back in with the server's password (`ownerCanBeDeleted`). The server
137
+ * refuses the same, so this hides only controls that could never work.
120
138
  */
121
139
  export function UserAccountsPage() {
122
140
  const { isAdmin } = useAdmin();
123
141
  const { user: me } = useAuth();
142
+ const invite = useInviteDialog();
143
+ const invitedRevision = invite?.invitedRevision ?? 0;
124
144
  const [accounts, setAccounts] = useState<AccountSummary[] | null>(null);
125
145
  const [error, setError] = useState<string | null>(null);
126
146
  // The account awaiting delete confirmation; non-null drives the confirm
@@ -151,35 +171,42 @@ export function UserAccountsPage() {
151
171
  email: string;
152
172
  action: PasswordAction;
153
173
  } | null>(null);
154
- // Add-account form.
155
- const [addEmail, setAddEmail] = useState('');
156
- const [addName, setAddName] = useState('');
157
- const [addPassword, setAddPassword] = useState('');
158
- const [addError, setAddError] = useState<string | null>(null);
159
- const [adding, setAdding] = useState(false);
160
174
  // The account being switched off or on, while the request and the refresh after it are in flight.
161
175
  const [switching, setSwitching] = useState<string | null>(null);
162
176
  // The account awaiting confirmation before it is switched off; non-null drives that Dialog.
163
177
  const [pendingDeactivate, setPendingDeactivate] = useState<AccountSummary | null>(null);
164
178
 
165
- const refresh = useCallback(() => {
166
- return listAccounts()
167
- .then((rows) => {
168
- setAccounts(rows);
169
- setError(null);
170
- })
171
- .catch((err) => {
172
- setError(err instanceof Error ? err.message : "Couldn't load accounts.");
179
+ // Only the latest read lands: an older one answering late would otherwise
180
+ // put back a list without the people a send just invited. And a caller
181
+ // waiting on a read that was overtaken waits on to the latest one, so
182
+ // "busy until the list shows the new state" still holds (`LatestRequest`).
183
+ const reads = useLatestRequest<{ rows: AccountSummary[] } | { error: string }>();
184
+ const refresh = useCallback(async () => {
185
+ await reads.run(
186
+ () =>
187
+ listAccounts().then(
188
+ (rows) => ({ rows }),
189
+ (err: unknown) => ({ error: err instanceof Error ? err.message : "Couldn't load accounts." }),
190
+ ),
191
+ (read) => {
192
+ if ('rows' in read) {
193
+ setAccounts(read.rows);
194
+ setError(null);
195
+ return;
196
+ }
197
+ setError(read.error);
173
198
  // `accounts` is deliberately left alone. A RELOAD that fails keeps the
174
199
  // rows it already had; a FIRST load that fails stays `null`, because
175
200
  // storing `[]` would render "No user accounts." — an admin reading
176
201
  // that would take a deployment they cannot reach for one nobody is on.
177
- });
178
- }, []);
202
+ },
203
+ );
204
+ }, [reads]);
179
205
 
206
+ // Again after every send from the Invite dialog, so the people just invited appear.
180
207
  useEffect(() => {
181
208
  if (isAdmin) refresh();
182
- }, [isAdmin, refresh]);
209
+ }, [isAdmin, refresh, invitedRevision]);
183
210
 
184
211
  function openDeleteDialog(account: AccountSummary) {
185
212
  setPendingDelete(account);
@@ -199,7 +226,9 @@ export function UserAccountsPage() {
199
226
  });
200
227
  }
201
228
 
202
- const removalBlocked = references !== null && !references.removable;
229
+ // An owner is never removed from access files; the server refuses it, so
230
+ // the option is off from the start rather than after the count arrives.
231
+ const removalBlocked = pendingDelete?.isOwner === true || (references !== null && !references.removable);
203
232
  // Files naming them that this admin may not write: the cleanup skips those,
204
233
  // so say it before the delete rather than only in the outcome. `unwritable`
205
234
  // is null when that could not be judged — which is not "none".
@@ -290,24 +319,6 @@ export function UserAccountsPage() {
290
319
  }
291
320
  }
292
321
 
293
- async function handleAdd(e: FormEvent<HTMLFormElement>) {
294
- e.preventDefault();
295
- if (adding) return;
296
- setAdding(true);
297
- setAddError(null);
298
- try {
299
- await createAccount(addEmail.trim(), addName.trim(), addPassword);
300
- setAddEmail('');
301
- setAddName('');
302
- setAddPassword('');
303
- refresh();
304
- } catch (err) {
305
- setAddError(err instanceof Error ? err.message : "Couldn't add the account.");
306
- } finally {
307
- setAdding(false);
308
- }
309
- }
310
-
311
322
  if (!isAdmin) {
312
323
  return (
313
324
  <PageShell title="User accounts">
@@ -392,6 +403,11 @@ export function UserAccountsPage() {
392
403
  {isSelf && (
393
404
  <span className="ml-1.5 text-meta font-normal text-ink-muted">(you)</span>
394
405
  )}
406
+ {account.isOwner && (
407
+ <span className="ml-1.5 rounded-sm border border-line px-1 text-meta font-normal text-ink-muted">
408
+ Owner
409
+ </span>
410
+ )}
395
411
  {account.deactivatedAt && (
396
412
  <span className="ml-1.5 text-meta font-normal text-ink-muted">(switched off)</span>
397
413
  )}
@@ -412,7 +428,10 @@ export function UserAccountsPage() {
412
428
  <span className="text-meta text-ink-muted text-right max-w-[13rem]">
413
429
  Password set in the deployment environment
414
430
  </span>
415
- ) : (
431
+ ) : account.isOwner ? null : (
432
+ // Nor for any other owner: another admin setting the
433
+ // owner's password could then sign in as them. The
434
+ // owner sets their own on the Account page.
416
435
  <button
417
436
  onClick={() => openPasswordDialog(account)}
418
437
  className="text-xs px-2 py-1 rounded-sm text-ink hover:bg-hover border border-line"
@@ -422,12 +441,14 @@ export function UserAccountsPage() {
422
441
  {passwordAction(account).label}
423
442
  </button>
424
443
  ))}
425
- {!isSelf && !account.isEnvAdmin && !account.isSystem && (
444
+ {!isSelf && (!account.isOwner || account.deactivatedAt) && !account.isSystem && (
426
445
  // Not for your own account (the backend refuses it, so
427
- // an admin always remains who can sign in), nor the
428
- // deployment admin's (its environment password is the
429
- // way back in), nor one the platform runs its own work
430
- // as. Switching off asks first; switching on does not.
446
+ // an admin always remains who can sign in), nor an
447
+ // owner's (switching them off locks them out of their
448
+ // own workspace; one switched off before the server
449
+ // refused it can still be switched back on), nor one
450
+ // the platform runs its own work as. Switching off asks
451
+ // first; switching on does not.
431
452
  <button
432
453
  onClick={() => (account.deactivatedAt ? toggleActive(account) : setPendingDeactivate(account))}
433
454
  disabled={switching !== null}
@@ -442,7 +463,9 @@ export function UserAccountsPage() {
442
463
  {account.deactivatedAt ? 'Switch on' : 'Switch off'}
443
464
  </button>
444
465
  )}
445
- {!isSelf && (
466
+ {!isSelf && (!account.isOwner || account.ownerCanBeDeleted) && (
467
+ // An owner only where they can sign back in with the
468
+ // server's password; elsewhere the server refuses it.
446
469
  <button
447
470
  onClick={() => openDeleteDialog(account)}
448
471
  className="text-xs px-2 py-1 rounded-sm text-red-700 hover:bg-red-50 border border-red-200"
@@ -455,63 +478,21 @@ export function UserAccountsPage() {
455
478
  </li>
456
479
  );
457
480
  })}
481
+ {invite && (
482
+ <li>
483
+ <button
484
+ type="button"
485
+ onClick={() => invite.open()}
486
+ className="flex w-full items-center gap-2 px-3 py-2.5 text-sm text-accent hover:bg-hover"
487
+ >
488
+ <Users size={14} aria-hidden />
489
+ Invite new users
490
+ </button>
491
+ </li>
492
+ )}
458
493
  </ul>
459
494
  )}
460
495
 
461
- <form onSubmit={handleAdd} className="border-t border-line pt-3 space-y-2 max-w-md">
462
- <div className="text-xs font-semibold uppercase tracking-wide text-ink-muted">
463
- Add account
464
- </div>
465
- <div className="grid grid-cols-2 gap-2">
466
- <label className="block space-y-1">
467
- <span className="text-xs text-ink-muted">Email</span>
468
- <input
469
- type="email"
470
- required
471
- value={addEmail}
472
- onChange={(e) => setAddEmail(e.target.value)}
473
- className={inputClass}
474
- />
475
- </label>
476
- <label className="block space-y-1">
477
- <span className="text-xs text-ink-muted">
478
- Name <span className="text-ink-faint">(optional)</span>
479
- </span>
480
- <input
481
- type="text"
482
- value={addName}
483
- onChange={(e) => setAddName(e.target.value)}
484
- className={inputClass}
485
- />
486
- </label>
487
- </div>
488
- <label className="block space-y-1">
489
- <span className="text-xs text-ink-muted">Password</span>
490
- <input
491
- type="password"
492
- autoComplete="new-password"
493
- aria-describedby="add-account-password-hint"
494
- value={addPassword}
495
- onChange={(e) => setAddPassword(e.target.value)}
496
- className={inputClass}
497
- />
498
- </label>
499
- <p id="add-account-password-hint" className="text-meta text-ink-faint">
500
- Optional. Leave it empty and they sign in with single sign-on.
501
- </p>
502
- {addError && (
503
- <div className="text-xs text-red-600" role="alert">
504
- {addError}
505
- </div>
506
- )}
507
- <button
508
- type="submit"
509
- disabled={adding}
510
- className="rounded-md bg-accent text-white text-sm font-medium px-3 py-1.5 hover:bg-accent-hover disabled:opacity-60 disabled:cursor-not-allowed"
511
- >
512
- {adding ? 'Adding…' : 'Add account'}
513
- </button>
514
- </form>
515
496
  </div>
516
497
  </PageShell>
517
498
 
@@ -620,8 +601,11 @@ export function UserAccountsPage() {
620
601
  />
621
602
  <span>Also remove them from roles, groups and access rules</span>
622
603
  </label>
623
- {removalBlocked && references?.blockedReason && (
624
- <p className="text-ink-muted">{references.blockedReason}</p>
604
+ {removalBlocked && pendingDelete?.isOwner ? (
605
+ <p className="text-ink-muted">{references?.blockedReason ?? OWNER_ACCESS_NOTE}</p>
606
+ ) : (
607
+ removalBlocked &&
608
+ references?.blockedReason && <p className="text-ink-muted">{references.blockedReason}</p>
625
609
  )}
626
610
  {!removalBlocked && removeFromAccess && unwritableCount > 0 && (
627
611
  <p className="text-ink-muted">
@@ -635,7 +619,7 @@ export function UserAccountsPage() {
635
619
  keep the address, and are listed afterwards.
636
620
  </p>
637
621
  )}
638
- {(!removeFromAccess || removalBlocked) && (
622
+ {(!removeFromAccess || removalBlocked) && !pendingDelete?.isOwner && (
639
623
  <p className="text-ink-muted">
640
624
  Their address will remain in those files.
641
625
  </p>
@@ -23,6 +23,13 @@ export interface RoleRosterEntry {
23
23
  * to today's behaviour instead of crashing on `undefined.map`.
24
24
  */
25
25
  fixedMembers?: string[];
26
+ /**
27
+ * The server's note for {@link fixedMembers} ("Owner; cannot be removed
28
+ * here"), also the sentence its refusal to add or remove one leads with.
29
+ * The page prints it as sent rather than keeping its own copy. Null or
30
+ * absent when the role has no fixed members.
31
+ */
32
+ fixedMembersNote?: string | null;
26
33
  /** Canonical names of groups assigned to this role. */
27
34
  groups: string[];
28
35
  isAdmin: boolean;
@@ -105,16 +112,22 @@ export async function recoverRoles(): Promise<RoleRosterEntry[]> {
105
112
  // now 404). Membership (members + group assignments) is what this client edits;
106
113
  // legacy people-set roles migrate out via convertRoleToGroup.
107
114
 
115
+ /**
116
+ * `ifActive`: refuse (409, kind `deactivated`) when the address's account is
117
+ * switched off at the time of the write — an invite leaves such an account
118
+ * unchanged, its role included.
119
+ */
108
120
  export async function addMember(
109
121
  canonical: string,
110
122
  email: string,
123
+ options: { ifActive?: boolean } = {},
111
124
  ): Promise<RoleRosterEntry[]> {
112
125
  const res = await authFetch(
113
126
  `/api/access/roles/${encodeURIComponent(canonical)}/members`,
114
127
  {
115
128
  method: 'POST',
116
129
  headers: { 'Content-Type': 'application/json' },
117
- body: JSON.stringify({ email }),
130
+ body: JSON.stringify(options.ifActive ? { email, ifActive: true } : { email }),
118
131
  },
119
132
  );
120
133
  return parseRoster(res);
@@ -1,8 +1,10 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { render, screen, waitFor } from '@testing-library/react';
3
+ import { renderToStaticMarkup } from 'react-dom/server';
3
4
  import userEvent from '@testing-library/user-event';
4
5
  import { LoginScreen } from '../components/LoginScreen';
5
6
  import { AuthContext, type AuthContextValue } from '../state/auth.context';
7
+ import { AppRegistryContext, makeRegistry, type AppRegistry } from '../../../core/registry';
6
8
  import { fetchLoginProviders, startSsoLogin } from '../services/sso';
7
9
 
8
10
  vi.mock('../services/sso', () => ({
@@ -13,7 +15,8 @@ vi.mock('../services/sso', () => ({
13
15
 
14
16
  const login = vi.fn(async () => {});
15
17
 
16
- function renderScreen() {
18
+ /** The login screen inside the contexts it reads. */
19
+ function loginTree(registry?: Partial<AppRegistry>) {
17
20
  const value: AuthContextValue = {
18
21
  user: null,
19
22
  token: null,
@@ -21,13 +24,19 @@ function renderScreen() {
21
24
  login,
22
25
  logout: vi.fn(),
23
26
  };
24
- return render(
25
- <AuthContext.Provider value={value}>
26
- <LoginScreen />
27
- </AuthContext.Provider>,
27
+ return (
28
+ <AppRegistryContext.Provider value={makeRegistry(registry ?? {})}>
29
+ <AuthContext.Provider value={value}>
30
+ <LoginScreen />
31
+ </AuthContext.Provider>
32
+ </AppRegistryContext.Provider>
28
33
  );
29
34
  }
30
35
 
36
+ function renderScreen(registry?: Partial<AppRegistry>) {
37
+ return render(loginTree(registry));
38
+ }
39
+
31
40
  beforeEach(() => {
32
41
  vi.mocked(fetchLoginProviders).mockReset();
33
42
  vi.mocked(startSsoLogin).mockReset();
@@ -35,6 +44,72 @@ beforeEach(() => {
35
44
  });
36
45
 
37
46
  describe('LoginScreen', () => {
47
+ it('lists the links a deployment names under the sign-in card, and none when it names none', async () => {
48
+ vi.mocked(fetchLoginProviders).mockResolvedValue({ password: true, sso: [] });
49
+ const { unmount } = renderScreen({
50
+ loginLinks: [
51
+ { label: 'Impressum', href: '/impressum' },
52
+ { label: 'Privacy', href: '/privacy' },
53
+ ],
54
+ });
55
+ const nav = screen.getByRole('navigation', { name: 'Legal' });
56
+ expect(nav).toBeInTheDocument();
57
+ expect(screen.getByRole('link', { name: 'Impressum' })).toHaveAttribute('href', '/impressum');
58
+ expect(screen.getByRole('link', { name: 'Privacy' })).toHaveAttribute('href', '/privacy');
59
+ // Outside the form: they are not part of signing in.
60
+ expect(nav.closest('form')).toBeNull();
61
+ unmount();
62
+ // Absent and empty both mean none: no empty landmark under the card.
63
+ for (const registry of [{}, { loginLinks: [] }]) {
64
+ const { unmount: unmountNone } = renderScreen(registry);
65
+ expect(screen.queryByRole('navigation', { name: 'Legal' })).toBeNull();
66
+ unmountNone();
67
+ }
68
+ });
69
+
70
+ it('scrolls on a screen too short for the card, and centres a card that fits', () => {
71
+ // happy-dom resolves no styles, so the layout is read off the utilities
72
+ // that make it (see SidebarFooterGrid.test.tsx). The root never scrolls
73
+ // (index.css), so the page must: otherwise a card taller than the screen,
74
+ // such as on a phone held sideways, is cut off with no way to reach it.
75
+ vi.mocked(fetchLoginProviders).mockResolvedValue({ password: true, sso: [] });
76
+ const { container } = renderScreen({ loginLinks: [{ label: 'Impressum', href: '/impressum' }] });
77
+ const page = container.firstElementChild as HTMLElement;
78
+ expect(page.classList).toContain('h-full');
79
+ expect(page.classList).toContain('overflow-y-auto');
80
+ // The column with the card and its links grows past the page rather than
81
+ // overflowing it, and is centred while it fits.
82
+ const column = screen.getByRole('navigation', { name: 'Legal' }).parentElement as HTMLElement;
83
+ expect(column.parentElement).toBe(page);
84
+ expect(column).toContainElement(container.querySelector('form'));
85
+ expect(column.classList).toContain('min-h-full');
86
+ expect(column.classList).not.toContain('h-full');
87
+ expect(column.classList).toContain('justify-center');
88
+ });
89
+
90
+ // Rendered to markup, which runs no effect: what the first render holds.
91
+ // Testing Library's render flushes the mount effects before it returns, so
92
+ // it would not tell a first-render message from one an effect sets.
93
+ it("shows an SSO callback's error on the first render, before any effect has run", () => {
94
+ sessionStorage.setItem('bevel_oauth_error', 'not_invited');
95
+ try {
96
+ expect(renderToStaticMarkup(loginTree())).toContain('You do not have an account in this workspace yet.');
97
+ } finally {
98
+ sessionStorage.removeItem('bevel_oauth_error');
99
+ }
100
+ });
101
+
102
+ it("clears an SSO callback's error once shown, so a later visit does not show it again", async () => {
103
+ vi.mocked(fetchLoginProviders).mockResolvedValue({ password: true, sso: [] });
104
+ sessionStorage.setItem('bevel_oauth_error', 'not_invited');
105
+ const { unmount } = renderScreen();
106
+ expect(screen.getByRole('alert')).toHaveTextContent('You do not have an account in this workspace yet.');
107
+ expect(sessionStorage.getItem('bevel_oauth_error')).toBeNull();
108
+ unmount();
109
+ renderScreen();
110
+ expect(screen.queryByRole('alert')).toBeNull();
111
+ });
112
+
38
113
  it('renders the password form and one button per advertised SSO provider', async () => {
39
114
  vi.mocked(fetchLoginProviders).mockResolvedValue({
40
115
  password: true,
@@ -0,0 +1,66 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { fetchLoginProviders, fetchLoginProvidersStrict } from '../services/sso';
3
+
4
+ /**
5
+ * The strict sign-in-methods probe answers only what the server said: a
6
+ * failed request, a non-OK status or a body missing either answer is
7
+ * "couldn't check", never a guess of password-only.
8
+ */
9
+
10
+ function answer(body: unknown, status = 200) {
11
+ vi.stubGlobal(
12
+ 'fetch',
13
+ vi.fn(async () => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })),
14
+ );
15
+ }
16
+
17
+ afterEach(() => {
18
+ vi.unstubAllGlobals();
19
+ });
20
+
21
+ describe('fetchLoginProvidersStrict', () => {
22
+ it('returns what the server says', async () => {
23
+ const sso = [{ key: 'oidc', label: 'Duende Demo', startPath: '/api/auth/oidc/start' }];
24
+ answer({ password: false, sso });
25
+ await expect(fetchLoginProvidersStrict()).resolves.toEqual({ password: false, sso });
26
+ });
27
+
28
+ it('rejects a non-OK answer', async () => {
29
+ answer({}, 503);
30
+ await expect(fetchLoginProvidersStrict()).rejects.toThrow();
31
+ });
32
+
33
+ it.each([
34
+ ['an empty body', {}],
35
+ ['no password answer', { sso: [] }],
36
+ ['no single sign-on list', { password: true }],
37
+ ['a password answer that is not a boolean', { password: 'yes', sso: [] }],
38
+ ['a provider without a label', { password: true, sso: [{ key: 'oidc' }] }],
39
+ ['a provider without a start path', { password: true, sso: [{ key: 'oidc', label: 'Duende Demo' }] }],
40
+ ['null', null],
41
+ ])('rejects %s rather than guessing', async (_label, body) => {
42
+ answer(body);
43
+ await expect(fetchLoginProvidersStrict()).rejects.toThrow("Couldn't read the sign-in methods");
44
+ });
45
+ });
46
+
47
+ describe('fetchLoginProviders', () => {
48
+ it('returns what the strict probe reads', async () => {
49
+ const sso = [{ key: 'oidc', label: 'Duende Demo', startPath: '/api/auth/oidc/start' }];
50
+ answer({ password: false, sso });
51
+ await expect(fetchLoginProviders()).resolves.toEqual({ password: false, sso });
52
+ });
53
+
54
+ it.each([
55
+ ['a non-OK answer', {}, 503],
56
+ ['a body the strict probe rejects', { sso: [{ key: 'oidc' }] }, 200],
57
+ ])('falls back to password only on %s', async (_label, body, status) => {
58
+ answer(body, status);
59
+ await expect(fetchLoginProviders()).resolves.toEqual({ password: true, sso: [] });
60
+ });
61
+
62
+ it('falls back to password only when the request fails', async () => {
63
+ vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('offline'); }));
64
+ await expect(fetchLoginProviders()).resolves.toEqual({ password: true, sso: [] });
65
+ });
66
+ });