@alepha/ui 0.25.1 → 0.25.2

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 (74) hide show
  1. package/package.json +3 -3
  2. package/src/components/account/__tests__/account-router.spec.ts +201 -0
  3. package/src/components/account/account-connections.tsx +103 -0
  4. package/src/components/account/account-delete-dialog.tsx +184 -0
  5. package/src/components/account/account-header.tsx +57 -0
  6. package/src/components/account/account-keys.tsx +221 -0
  7. package/src/components/account/account-layout.tsx +63 -0
  8. package/src/components/account/account-password-dialog.tsx +152 -0
  9. package/src/components/account/account-profile.tsx +229 -0
  10. package/src/components/account/account-router-options.tsx +74 -0
  11. package/src/components/account/account-router-page.tsx +69 -0
  12. package/src/components/account/account-router.tsx +214 -0
  13. package/src/components/account/account-security.tsx +150 -0
  14. package/src/components/account/account-sessions.tsx +140 -0
  15. package/src/components/admin/__tests__/admin-keys-token-dialog.browser.spec.tsx +62 -0
  16. package/src/components/admin/__tests__/admin-layout.browser.spec.tsx +82 -0
  17. package/src/components/admin/__tests__/admin-router-page.spec.ts +54 -0
  18. package/src/components/admin/__tests__/admin-router.spec.ts +208 -0
  19. package/src/components/admin/__tests__/admin-user-cell.browser.spec.tsx +99 -0
  20. package/src/components/admin/__tests__/admin-user-detail.spec.ts +29 -0
  21. package/src/components/admin/admin-analytics-query-panel.tsx +149 -0
  22. package/src/components/admin/admin-analytics-results.tsx +95 -0
  23. package/src/components/admin/admin-analytics.tsx +104 -0
  24. package/src/components/admin/admin-audits.tsx +12 -15
  25. package/src/components/admin/admin-files.tsx +10 -18
  26. package/src/components/admin/admin-jobs-executions-panel.tsx +2 -1
  27. package/src/components/admin/admin-jobs.tsx +3 -1
  28. package/src/components/admin/admin-keys-token-dialog.tsx +123 -0
  29. package/src/components/admin/admin-keys.tsx +54 -3
  30. package/src/components/admin/admin-layout.tsx +107 -0
  31. package/src/components/admin/admin-payments.tsx +4 -5
  32. package/src/components/admin/admin-router-options.tsx +130 -0
  33. package/src/components/admin/admin-router-page.tsx +74 -0
  34. package/src/components/admin/admin-router.tsx +379 -0
  35. package/src/components/admin/admin-sessions.tsx +2 -16
  36. package/src/components/admin/admin-user-cell.tsx +70 -0
  37. package/src/components/admin/admin-user-detail-overview-tab.tsx +28 -0
  38. package/src/components/admin/admin-user-detail-profile-policy.spec.ts +146 -0
  39. package/src/components/admin/admin-user-detail-profile-policy.ts +147 -0
  40. package/src/components/admin/admin-user-detail-security-tab.tsx +1 -1
  41. package/src/components/admin/admin-user-detail.tsx +76 -32
  42. package/src/components/admin/admin-users-status-filter.tsx +2 -0
  43. package/src/components/admin/admin-workflows-execution-sheet.tsx +277 -0
  44. package/src/components/admin/admin-workflows-executions-panel.tsx +170 -0
  45. package/src/components/admin/admin-workflows-status-badge.tsx +40 -0
  46. package/src/components/admin/admin-workflows.tsx +207 -0
  47. package/src/components/alepha-table/alepha-table.tsx +73 -17
  48. package/src/components/app-actions/__tests__/app-actions.browser.spec.tsx +79 -0
  49. package/src/components/app-actions/app-actions.tsx +113 -0
  50. package/src/components/app-shell/app-shell.tsx +122 -0
  51. package/src/components/auth/auth-reset-password.tsx +81 -8
  52. package/src/components/button-user/button-user.tsx +58 -1
  53. package/src/components/control/control.tsx +14 -71
  54. package/src/components/control-password/control-password.tsx +87 -0
  55. package/src/components/control-select/__tests__/control-select-clear-label.browser.spec.tsx +101 -0
  56. package/src/components/control-select/__tests__/control-select-searchable.browser.spec.tsx +142 -0
  57. package/src/components/control-select/control-select.tsx +78 -111
  58. package/src/components/control-upload/control-upload.tsx +27 -1
  59. package/src/components/markdown-view/markdown-view.tsx +6 -0
  60. package/src/components/nav-shell/nav-page.tsx +3 -3
  61. package/src/components/settings/__tests__/settings-nav.browser.spec.tsx +123 -0
  62. package/src/components/settings/__tests__/settings-section.browser.spec.tsx +130 -0
  63. package/src/components/settings/settings-danger-section.tsx +59 -0
  64. package/src/components/settings/settings-layout.tsx +56 -0
  65. package/src/components/settings/settings-nav.tsx +131 -0
  66. package/src/components/settings/settings-row.tsx +81 -0
  67. package/src/components/settings/settings-section.tsx +64 -0
  68. package/src/components/ui/dropdown-menu.tsx +9 -1
  69. package/src/lib/__tests__/rehype-safe-img.spec.ts +121 -0
  70. package/src/lib/i18n-fr.ts +68 -0
  71. package/src/lib/rehype-safe-img.ts +150 -0
  72. package/src/lib/resize-image.ts +135 -0
  73. package/src/styles.css +126 -1
  74. /package/src/components/{admin/admin-user-detail-provider-labels.ts → auth/provider-labels.ts} +0 -0
@@ -0,0 +1,74 @@
1
+ import { $atom, z } from "alepha";
2
+ import type { ReactNode } from "react";
3
+ import type { AccountConnectionsProps } from "./account-connections.tsx";
4
+ import type { AccountKeysProps } from "./account-keys.tsx";
5
+ import type { AccountProfileProps } from "./account-profile.tsx";
6
+ import type { AccountSecurityProps } from "./account-security.tsx";
7
+ import type { AccountSessionsProps } from "./account-sessions.tsx";
8
+
9
+ /**
10
+ * Everything an application can change about `AccountRouter` without writing
11
+ * its own.
12
+ *
13
+ * The seam is narrower than the admin one, and deliberately so — an account
14
+ * area is a handful of forms, not a console. An application wanting different
15
+ * URLs or a different page set writes its own router; the same trade
16
+ * `AuthRouter` documents.
17
+ */
18
+ export interface AccountRouterOptions {
19
+ /**
20
+ * Replaces the default {@link AccountHeader} — the back link plus the
21
+ * ambient controls — entirely. Supply the whole bar, not an addition to it.
22
+ *
23
+ * Set it to `null` for an account area nested inside an application's own
24
+ * chrome, where a second header would just be a second row of the same
25
+ * controls.
26
+ */
27
+ header?: ReactNode;
28
+
29
+ /**
30
+ * Route name the default header's back link points at. Ignored when
31
+ * `header` is supplied, since that replaces the link too.
32
+ *
33
+ * @default "home"
34
+ */
35
+ homeRouteName?: string;
36
+
37
+ /**
38
+ * Extra class(es) merged onto the shell's root element, for an account area
39
+ * living inside a document the application does not fully own.
40
+ */
41
+ className?: string;
42
+
43
+ /**
44
+ * Props forwarded to the pages, keyed by page.
45
+ *
46
+ * Each entry reuses that component's own exported props interface rather
47
+ * than restating its fields, so a prop added to a page is passable the day
48
+ * it exists.
49
+ */
50
+ pages?: {
51
+ profile?: AccountProfileProps;
52
+ security?: AccountSecurityProps;
53
+ sessions?: AccountSessionsProps;
54
+ keys?: AccountKeysProps;
55
+ connections?: AccountConnectionsProps;
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Boot-time configuration for `AccountRouter`, following the
61
+ * `adminRouterOptionsAtom` pattern: the application calls
62
+ * `alepha.set(accountRouterOptionsAtom, { … })` once, before start.
63
+ *
64
+ * `z.custom` passthrough because the value carries React nodes, whose shape
65
+ * TypeScript already owns. Being boot-configured also keeps it out of the SSR
66
+ * payload — `StateManager.exportAtoms()` reads request scope only, and a
67
+ * `ReactNode` would not survive JSON serialization.
68
+ */
69
+ export const accountRouterOptionsAtom = $atom({
70
+ name: "alepha.ui.account.router.options",
71
+ description: "Chrome slot and per-page props for the account router.",
72
+ schema: z.custom<AccountRouterOptions>(),
73
+ default: {} satisfies AccountRouterOptions,
74
+ });
@@ -0,0 +1,69 @@
1
+ import { $context } from "alepha";
2
+ import type {
3
+ PageConfigSchema,
4
+ PagePrimitive,
5
+ TPropsDefault,
6
+ TPropsParentDefault,
7
+ } from "alepha/react/router";
8
+ import { $pageNav, type PageNavOptions } from "../nav-shell/nav-page.tsx";
9
+ import { AccountRouter } from "./account-router.tsx";
10
+
11
+ /**
12
+ * `$pageNav` already parented to {@link AccountRouter}'s `/account` shell —
13
+ * the one-call form of "a page inside the shared account area".
14
+ *
15
+ * It carries the `$` prefix to sit with the framework's other declarations at
16
+ * a call site, but it is a plain function wrapping `$pageNav`, which wraps
17
+ * `$page`. Nothing about its lifecycle differs from declaring `$page`
18
+ * yourself.
19
+ *
20
+ * The page appears in the rail with no separate registration: the layout
21
+ * reads `useNavEntries({ root: "account" })`, which walks the parent chain
22
+ * and reads each page's own `nav`.
23
+ *
24
+ * **Calling this registers `AccountRouter`.** Declaring even one page this
25
+ * way mounts the whole `/account` shell including its five built-in pages —
26
+ * an account page without the account area around it is not a thing. That is
27
+ * the intended reading, but it is a real side effect: an application wanting
28
+ * `/account` to carry only its own pages must build its own layout instead.
29
+ *
30
+ * **Take `order: 100` or above, or declare your own `nav.group`.** The
31
+ * built-ins occupy `Account` (order 1) and `Security` (orders 2-5), and
32
+ * `useNavEntries` sorts groups by their smallest member — a page at a lower
33
+ * order silently reshuffles the shared rail.
34
+ *
35
+ * **Gate with `can: () => this.someApi.someAction.can()`, not `permission`
36
+ * alone.** A permission named by this page's own `$secure` is self-declaring:
37
+ * `$secure` registers it into `SecurityProvider` at definition time, so it
38
+ * exists whether or not any controller backing the page does. An action name
39
+ * resolves against `/api/_links`, which is built only from actions the server
40
+ * actually registered.
41
+ *
42
+ * ```tsx
43
+ * class LoreAccountRouter {
44
+ * protected readonly invitationApi = $client<InvitationController>();
45
+ *
46
+ * invitations = $pageAccount({
47
+ * path: "/invitations",
48
+ * name: "accountInvitations",
49
+ * nav: { label: "Invitations", icon: <Mail />, group: "Lore", order: 100 },
50
+ * can: () => this.invitationApi.listMyInvitations.can(),
51
+ * lazy: () => import("./MyInvitations.tsx"),
52
+ * });
53
+ * }
54
+ * ```
55
+ */
56
+ export const $pageAccount = <
57
+ TConfig extends PageConfigSchema = PageConfigSchema,
58
+ TProps extends object = TPropsDefault,
59
+ TPropsParent extends object = TPropsParentDefault,
60
+ >(
61
+ options: Omit<PageNavOptions<TConfig, TProps, TPropsParent>, "parent">,
62
+ ): PagePrimitive<TConfig, TProps, TPropsParent> => {
63
+ const { alepha } = $context();
64
+ const account = alepha.inject(AccountRouter);
65
+ return $pageNav<TConfig, TProps, TPropsParent>({
66
+ ...options,
67
+ parent: account.layout,
68
+ } as PageNavOptions<TConfig, TProps, TPropsParent>);
69
+ };
@@ -0,0 +1,214 @@
1
+ import { $pageNav } from "@alepha/ui/components/nav-shell/nav-page";
2
+ import { $store } from "alepha";
3
+ import type { ApiKeyController } from "alepha/api/keys";
4
+ import type {
5
+ MyConnectionController,
6
+ MyIdentityController,
7
+ MyProfileController,
8
+ MySessionController,
9
+ } from "alepha/api/users";
10
+ import { $page } from "alepha/react/router";
11
+ import { $secure } from "alepha/security";
12
+ import { $client } from "alepha/server/links";
13
+ import { KeyRound, Plug, RadioTower, ShieldCheck, User } from "lucide-react";
14
+ import { createElement } from "react";
15
+ import { accountRouterOptionsAtom } from "./account-router-options.tsx";
16
+
17
+ /**
18
+ * The whole `/account` surface — five pages and their shell — mounted and
19
+ * wired. The user-facing counterpart of `AdminRouter`.
20
+ *
21
+ * ⚠️ **Nav icons are `createElement(Icon)`, never `<Icon />`.** Same reason as
22
+ * `AdminRouter`: this module is evaluated *eagerly* in the server graph, and
23
+ * `alepha db migrations create` imports that graph under `tsx`, which applies
24
+ * a tsconfig resolved from the app root. A file outside that tsconfig's
25
+ * `include` — which this one is, living in a sibling workspace — gets
26
+ * esbuild's defaults, whose JSX transform is the *classic* one. The emitted
27
+ * `React.createElement` then fails with `ReferenceError: React is not
28
+ * defined`, breaking migration generation for the whole app.
29
+ *
30
+ * ```ts
31
+ * import { AccountRouter } from "@alepha/ui/components/account/account-router";
32
+ *
33
+ * export const MyWeb = $module({
34
+ * name: "my.web",
35
+ * services: [MyRouter, AuthRouter, AccountRouter],
36
+ * });
37
+ * ```
38
+ *
39
+ * ### Mount it standalone, or inside your own layout
40
+ *
41
+ * {@link AccountRouter.layout} is a root `$page`, so registering the service
42
+ * puts `/account` at the root with only the `header` slot for chrome. An
43
+ * application that wants it *inside* its own header and footer adds
44
+ * `accountRouter.layout` to that layout's `children`:
45
+ *
46
+ * ```ts
47
+ * layout = $page({
48
+ * children: () => [this.home, this.account.layout, this.notFound],
49
+ * lazy: () => import("./Layout.tsx"),
50
+ * });
51
+ * ```
52
+ *
53
+ * `ReactPageProvider` excludes an adopted page from the root set, so it
54
+ * renders nested. This is why the options atom has no `parent` field: a
55
+ * boot-time atom carrying a `PagePrimitive` would be order-fragile, and the
56
+ * mechanism already exists.
57
+ *
58
+ * ### Every page is mounted; none is conditionally registered
59
+ *
60
+ * A page whose backing module is not registered hides itself through `can`,
61
+ * which resolves an action name against `/api/_links` — a registry built from
62
+ * the actions the server actually registered. `permission` could not do this:
63
+ * `$secure` registers a permission at definition time whether or not any
64
+ * controller backs it, so an admin holding `*` would be granted it over a
65
+ * dead API. The API-keys page is the clearest case — it disappears entirely
66
+ * for an application that never mounts `AlephaApiKeys`.
67
+ *
68
+ * (Connections is *not* an example of that any more. `MyConnectionController`
69
+ * had to move from `api/oauth` into `api/users` to break a circular module
70
+ * dependency, so its action exists wherever `api/users` does — see that
71
+ * controller's own JSDoc.)
72
+ *
73
+ * There is deliberately no `pages: [...]` allowlist: a second gate on top of
74
+ * one that already works goes stale.
75
+ *
76
+ * ### These five route names are prefixed on purpose
77
+ *
78
+ * `AdminRouter` already claims `sessions` and `keys` globally, and
79
+ * `ReactPageProvider.page()` returns the *first* match on a duplicate — so
80
+ * bare names here would shadow the admin ones, or be shadowed by them,
81
+ * silently, depending on mount order. `accountProfile`, `accountSecurity`,
82
+ * `accountSessions`, `accountKeys` and `accountConnections` each carry an
83
+ * explicit `name:` so renaming a field later never changes the public route
84
+ * name.
85
+ *
86
+ * ### Extending the shell
87
+ *
88
+ * `$pageAccount` is the one-call way to add a page. Take `order: 100` or
89
+ * above, or declare your own `nav.group` — the built-ins occupy `Account`
90
+ * (order 1) and `Security` (orders 2-5), and `useNavEntries` sorts groups by
91
+ * their smallest member, so a page at a lower order silently reshuffles the
92
+ * shared rail.
93
+ */
94
+ export class AccountRouter {
95
+ protected readonly options = $store(accountRouterOptionsAtom);
96
+
97
+ protected readonly profileApi = $client<MyProfileController>();
98
+ protected readonly identityApi = $client<MyIdentityController>();
99
+ protected readonly sessionApi = $client<MySessionController>();
100
+ protected readonly apiKeyApi = $client<ApiKeyController>();
101
+ protected readonly connectionApi = $client<MyConnectionController>();
102
+
103
+ /**
104
+ * Anchors the shell. Not itself a nav entry — a shell root is excluded from
105
+ * its own rail.
106
+ *
107
+ * `$secure()` with no permission means signed-in only, which is both the
108
+ * right gate (nothing here means anything to an anonymous visitor) and what
109
+ * puts the subtree in CSR.
110
+ *
111
+ * Unlike `/admin` there is no index redirect: {@link profile} sits at
112
+ * `path: "/"`, so a bare `/account` resolves to it directly.
113
+ */
114
+ layout = $page({
115
+ name: "account",
116
+ path: "/account",
117
+ use: [$secure()],
118
+ nav: { label: "Account" },
119
+ lazy: () => import("./account-layout.tsx"),
120
+ });
121
+
122
+ profile = $pageNav({
123
+ parent: this.layout,
124
+ path: "/",
125
+ name: "accountProfile",
126
+ head: { title: "Profile" },
127
+ can: () => this.profileApi.getMyProfile.can(),
128
+ nav: {
129
+ label: "Profile",
130
+ icon: createElement(User),
131
+ group: "Account",
132
+ order: 1,
133
+ },
134
+ loader: async () => ({ profile: await this.profileApi.getMyProfile() }),
135
+ lazy: () => import("./account-profile.tsx"),
136
+ props: () => this.options.pages?.profile ?? {},
137
+ });
138
+
139
+ security = $pageNav({
140
+ parent: this.layout,
141
+ path: "/security",
142
+ name: "accountSecurity",
143
+ head: { title: "Security" },
144
+ can: () => this.identityApi.listMyIdentities.can(),
145
+ nav: {
146
+ label: "Security",
147
+ icon: createElement(ShieldCheck),
148
+ group: "Security",
149
+ order: 2,
150
+ keywords: ["password", "identities", "sign-in", "delete account"],
151
+ },
152
+ loader: async () => ({
153
+ identities: await this.identityApi.listMyIdentities(),
154
+ }),
155
+ lazy: () => import("./account-security.tsx"),
156
+ props: () => this.options.pages?.security ?? {},
157
+ });
158
+
159
+ sessions = $pageNav({
160
+ parent: this.layout,
161
+ path: "/sessions",
162
+ name: "accountSessions",
163
+ head: { title: "Sessions" },
164
+ can: () => this.sessionApi.listMySessions.can(),
165
+ nav: {
166
+ label: "Sessions",
167
+ icon: createElement(RadioTower),
168
+ group: "Security",
169
+ order: 3,
170
+ keywords: ["devices", "sign out"],
171
+ },
172
+ loader: async () => ({ sessions: await this.sessionApi.listMySessions() }),
173
+ lazy: () => import("./account-sessions.tsx"),
174
+ props: () => this.options.pages?.sessions ?? {},
175
+ });
176
+
177
+ keys = $pageNav({
178
+ parent: this.layout,
179
+ path: "/keys",
180
+ name: "accountKeys",
181
+ head: { title: "API keys" },
182
+ can: () => this.apiKeyApi.listApiKeys.can(),
183
+ nav: {
184
+ label: "API keys",
185
+ icon: createElement(KeyRound),
186
+ group: "Security",
187
+ order: 4,
188
+ keywords: ["tokens", "credentials"],
189
+ },
190
+ loader: async () => ({ apiKeys: await this.apiKeyApi.listApiKeys() }),
191
+ lazy: () => import("./account-keys.tsx"),
192
+ props: () => this.options.pages?.keys ?? {},
193
+ });
194
+
195
+ connections = $pageNav({
196
+ parent: this.layout,
197
+ path: "/connections",
198
+ name: "accountConnections",
199
+ head: { title: "Connected apps" },
200
+ can: () => this.connectionApi.listMyConnections.can(),
201
+ nav: {
202
+ label: "Connected apps",
203
+ icon: createElement(Plug),
204
+ group: "Security",
205
+ order: 5,
206
+ keywords: ["oauth", "mcp", "integrations"],
207
+ },
208
+ loader: async () => ({
209
+ connections: await this.connectionApi.listMyConnections(),
210
+ }),
211
+ lazy: () => import("./account-connections.tsx"),
212
+ props: () => this.options.pages?.connections ?? {},
213
+ });
214
+ }
@@ -0,0 +1,150 @@
1
+ import { AccountDeleteDialog } from "@alepha/ui/components/account/account-delete-dialog";
2
+ import { AccountPasswordDialog } from "@alepha/ui/components/account/account-password-dialog";
3
+ import { SettingsDangerSection } from "@alepha/ui/components/settings/settings-danger-section";
4
+ import { SettingsRow } from "@alepha/ui/components/settings/settings-row";
5
+ import { SettingsSection } from "@alepha/ui/components/settings/settings-section";
6
+ import { Button } from "@alepha/ui/components/ui/button";
7
+ import { useDialog } from "@alepha/ui/components/use-dialog/use-dialog";
8
+ import { useToast } from "@alepha/ui/components/use-toast/use-toast";
9
+ import type { MyIdentity, MyIdentityController } from "alepha/api/users";
10
+ import { useClient } from "alepha/react";
11
+ import { useAuth } from "alepha/react/auth";
12
+ import { useI18n } from "alepha/react/i18n";
13
+ import { KeyRound, Trash2 } from "lucide-react";
14
+ import { type ReactNode, useState } from "react";
15
+ import { PROVIDER_LABELS } from "../auth/provider-labels.ts";
16
+
17
+ export interface AccountSecurityProps {
18
+ identities?: MyIdentity[];
19
+
20
+ /**
21
+ * Rendered inside the delete-account dialog, above the confirmation field.
22
+ * See {@link AccountDeleteDialogProps.warning} — this is how an application
23
+ * states what deletion costs in *its* data.
24
+ */
25
+ deleteWarning?: ReactNode;
26
+ }
27
+
28
+ /**
29
+ * How you get in, and how to stop existing.
30
+ *
31
+ * The delete-account row lives here rather than on Profile because the
32
+ * re-authentication it demands is the same material as everything else on
33
+ * this page — and because a destructive action on the page you land on by
34
+ * default is a worse default than one behind a deliberate click.
35
+ */
36
+ const AccountSecurity = (props: AccountSecurityProps) => {
37
+ const api = useClient<MyIdentityController>();
38
+ const auth = useAuth();
39
+ const dialog = useDialog();
40
+ const toaster = useToast();
41
+ const { l } = useI18n();
42
+
43
+ const [identities, setIdentities] = useState<MyIdentity[]>(
44
+ props.identities ?? [],
45
+ );
46
+ const [passwordOpen, setPasswordOpen] = useState(false);
47
+ const [deleteOpen, setDeleteOpen] = useState(false);
48
+
49
+ const hasPassword = identities.some((it) => it.provider === "credentials");
50
+
51
+ const reload = async () => setIdentities(await api.listMyIdentities());
52
+
53
+ const unlink = async (identity: MyIdentity) => {
54
+ const label = PROVIDER_LABELS[identity.provider] ?? identity.provider;
55
+ const ok = await dialog.confirm({
56
+ title: `Remove ${label}?`,
57
+ description: `You will no longer be able to sign in with ${label}.`,
58
+ confirmLabel: "Remove",
59
+ destructive: true,
60
+ });
61
+ if (!ok) {
62
+ return;
63
+ }
64
+ try {
65
+ await api.unlinkMyIdentity({ params: { id: identity.id } });
66
+ await reload();
67
+ } catch (error: any) {
68
+ // Includes the last-identity refusal, whose message is the whole point.
69
+ toaster.show(error?.message ?? "Could not remove that method", "danger");
70
+ }
71
+ };
72
+
73
+ return (
74
+ <>
75
+ <SettingsSection
76
+ title="Sign-in methods"
77
+ description="At least one must remain — removing the last would lock you out permanently."
78
+ >
79
+ {identities.map((identity) => (
80
+ <SettingsRow
81
+ key={identity.id}
82
+ label={PROVIDER_LABELS[identity.provider] ?? identity.provider}
83
+ description={`Added ${String(l(identity.createdAt, { date: "ll" }))}`}
84
+ >
85
+ {identities.length > 1 ? (
86
+ <Button
87
+ variant="ghost"
88
+ size="sm"
89
+ onClick={() => unlink(identity)}
90
+ aria-label={`Remove ${identity.provider}`}
91
+ >
92
+ <Trash2 className="size-4" />
93
+ </Button>
94
+ ) : null}
95
+ </SettingsRow>
96
+ ))}
97
+
98
+ <SettingsRow
99
+ label="Password"
100
+ description={
101
+ hasPassword
102
+ ? "Changing it signs out every other device."
103
+ : "This account signs in without a password. Add one as a fallback."
104
+ }
105
+ >
106
+ <Button
107
+ variant="secondary"
108
+ size="sm"
109
+ onClick={() => setPasswordOpen(true)}
110
+ >
111
+ <KeyRound className="size-4" />
112
+ {hasPassword ? "Change password" : "Set a password"}
113
+ </Button>
114
+ </SettingsRow>
115
+ </SettingsSection>
116
+
117
+ <SettingsDangerSection description="This cannot be undone.">
118
+ <SettingsRow
119
+ label="Delete this account"
120
+ description="Removes your account, its sign-in methods and every session."
121
+ >
122
+ <Button
123
+ variant="destructive"
124
+ size="sm"
125
+ onClick={() => setDeleteOpen(true)}
126
+ >
127
+ Delete account
128
+ </Button>
129
+ </SettingsRow>
130
+ </SettingsDangerSection>
131
+
132
+ <AccountPasswordDialog
133
+ open={passwordOpen}
134
+ hasPassword={hasPassword}
135
+ onOpenChange={setPasswordOpen}
136
+ onDone={reload}
137
+ />
138
+
139
+ <AccountDeleteDialog
140
+ open={deleteOpen}
141
+ hasPassword={hasPassword}
142
+ onOpenChange={setDeleteOpen}
143
+ warning={props.deleteWarning}
144
+ onDeleted={() => auth.logout()}
145
+ />
146
+ </>
147
+ );
148
+ };
149
+
150
+ export default AccountSecurity;
@@ -0,0 +1,140 @@
1
+ import { SettingsRow } from "@alepha/ui/components/settings/settings-row";
2
+ import { SettingsSection } from "@alepha/ui/components/settings/settings-section";
3
+ import { Button } from "@alepha/ui/components/ui/button";
4
+ import { useDialog } from "@alepha/ui/components/use-dialog/use-dialog";
5
+ import { useToast } from "@alepha/ui/components/use-toast/use-toast";
6
+ import type { MySession, MySessionController } from "alepha/api/users";
7
+ import { DateTimeProvider } from "alepha/datetime";
8
+ import { useClient, useInject } from "alepha/react";
9
+ import { Circle, Monitor, Smartphone, Tablet } from "lucide-react";
10
+ import { useState } from "react";
11
+
12
+ export interface AccountSessionsProps {
13
+ sessions?: MySession[];
14
+ }
15
+
16
+ /**
17
+ * Where you are signed in, and how to stop being.
18
+ *
19
+ * Revoking a *single* session is unconfirmed; "sign out everywhere else" is
20
+ * confirmed. The difference is reach, not reversibility — one session comes
21
+ * back by signing in again, whereas the bulk action ends every other device
22
+ * at once and there is no undo affordance to reach for afterwards. A prompt
23
+ * on the per-row action would be click-through noise, which is what makes a
24
+ * rare prompt worth reading.
25
+ */
26
+ const AccountSessions = (props: AccountSessionsProps) => {
27
+ const api = useClient<MySessionController>();
28
+ const dt = useInject(DateTimeProvider);
29
+ const dialog = useDialog();
30
+ const toaster = useToast();
31
+ const [sessions, setSessions] = useState<MySession[]>(props.sessions ?? []);
32
+
33
+ const deviceIcon = (session: MySession) => {
34
+ if (session.userAgent?.device === "MOBILE") {
35
+ return <Smartphone className="size-4" />;
36
+ }
37
+ if (session.userAgent?.device === "TABLET") {
38
+ return <Tablet className="size-4" />;
39
+ }
40
+ return <Monitor className="size-4" />;
41
+ };
42
+
43
+ const label = (session: MySession) => {
44
+ const agent = session.userAgent;
45
+ if (!agent) {
46
+ return "Unknown device";
47
+ }
48
+ return `${agent.browser} on ${agent.os}`;
49
+ };
50
+
51
+ const revoke = async (session: MySession) => {
52
+ try {
53
+ await api.deleteMySession({ params: { id: session.id } });
54
+ setSessions((prev) => prev.filter((it) => it.id !== session.id));
55
+ } catch (error: any) {
56
+ toaster.show(error?.message ?? "Could not revoke that session", "danger");
57
+ }
58
+ };
59
+
60
+ const revokeOthers = async () => {
61
+ const ok = await dialog.confirm({
62
+ title: "Sign out everywhere else?",
63
+ description:
64
+ "Every other browser and device will be signed out. This one stays signed in.",
65
+ confirmLabel: "Sign out everywhere else",
66
+ destructive: true,
67
+ });
68
+ if (!ok) {
69
+ return;
70
+ }
71
+ try {
72
+ const { revoked } = await api.deleteMyOtherSessions();
73
+ setSessions((prev) => prev.filter((it) => it.current));
74
+ toaster.show(
75
+ revoked === 1
76
+ ? "1 session signed out"
77
+ : `${revoked} sessions signed out`,
78
+ "success",
79
+ );
80
+ } catch (error: any) {
81
+ toaster.show(error?.message ?? "Could not sign out the others", "danger");
82
+ }
83
+ };
84
+
85
+ const others = sessions.filter((it) => !it.current).length;
86
+
87
+ return (
88
+ <SettingsSection
89
+ title="Active sessions"
90
+ description="Revoke any session you do not recognise."
91
+ >
92
+ {sessions.map((session) => (
93
+ <SettingsRow
94
+ key={session.id}
95
+ label={
96
+ <span className="flex items-center gap-2">
97
+ <Circle
98
+ aria-hidden
99
+ className={
100
+ session.current
101
+ ? "size-2 fill-green-500 text-green-500"
102
+ : "size-2 fill-muted-foreground text-muted-foreground"
103
+ }
104
+ />
105
+ {deviceIcon(session)}
106
+ {label(session)}
107
+ {session.current ? (
108
+ <span className="text-muted-foreground text-xs">
109
+ (this device)
110
+ </span>
111
+ ) : null}
112
+ </span>
113
+ }
114
+ description={`${session.ip ?? "unknown IP"} · signed in ${dt
115
+ .of(session.createdAt)
116
+ .fromNow()}`}
117
+ >
118
+ {session.current ? null : (
119
+ <Button variant="ghost" size="sm" onClick={() => revoke(session)}>
120
+ Revoke
121
+ </Button>
122
+ )}
123
+ </SettingsRow>
124
+ ))}
125
+
126
+ {others > 0 ? (
127
+ <SettingsRow
128
+ label="Sign out everywhere else"
129
+ description="Ends every session except this one."
130
+ >
131
+ <Button variant="destructive" size="sm" onClick={revokeOthers}>
132
+ Sign out {others} other{others === 1 ? "" : "s"}
133
+ </Button>
134
+ </SettingsRow>
135
+ ) : null}
136
+ </SettingsSection>
137
+ );
138
+ };
139
+
140
+ export default AccountSessions;