@nexys/user-management-web 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.
Files changed (78) hide show
  1. package/README.md +61 -0
  2. package/components.json +21 -0
  3. package/package.json +66 -0
  4. package/src/components/audit/audit-log-table.test.tsx +98 -0
  5. package/src/components/audit/audit-log-table.tsx +227 -0
  6. package/src/components/auth/accept-invitation-card.tsx +104 -0
  7. package/src/components/auth/forgot-password-form.tsx +93 -0
  8. package/src/components/auth/reset-password-form.tsx +144 -0
  9. package/src/components/auth/sign-in-form.test.tsx +164 -0
  10. package/src/components/auth/sign-in-form.tsx +504 -0
  11. package/src/components/auth/sign-up-form.tsx +124 -0
  12. package/src/components/layout/app-shell.tsx +189 -0
  13. package/src/components/layout/auth-shell.tsx +28 -0
  14. package/src/components/layout/theme-toggle.tsx +55 -0
  15. package/src/components/layout/user-menu.tsx +84 -0
  16. package/src/components/primitives/empty-state.tsx +40 -0
  17. package/src/components/primitives/page-header.tsx +27 -0
  18. package/src/components/primitives/spinner.tsx +28 -0
  19. package/src/components/profile/api-tokens-card.tsx +238 -0
  20. package/src/components/profile/change-password-form.tsx +159 -0
  21. package/src/components/profile/passkeys-card.tsx +186 -0
  22. package/src/components/profile/profile-card.tsx +107 -0
  23. package/src/components/profile/refresh-tokens-list.tsx +176 -0
  24. package/src/components/profile/two-factor-card.tsx +230 -0
  25. package/src/components/projects/project-consents.tsx +577 -0
  26. package/src/components/projects/project-create-dialog.tsx +193 -0
  27. package/src/components/projects/project-detail-tabs.tsx +64 -0
  28. package/src/components/projects/project-email-templates.tsx +285 -0
  29. package/src/components/projects/project-notices.tsx +461 -0
  30. package/src/components/projects/project-settings.tsx +1059 -0
  31. package/src/components/projects/project-tenants.tsx +108 -0
  32. package/src/components/projects/projects-table.test.tsx +109 -0
  33. package/src/components/projects/projects-table.tsx +240 -0
  34. package/src/components/roles/role-badge.tsx +91 -0
  35. package/src/components/roles/role-select.tsx +76 -0
  36. package/src/components/tenants/tenant-create-dialog.tsx +164 -0
  37. package/src/components/tenants/tenant-detail-tabs.tsx +51 -0
  38. package/src/components/tenants/tenant-members.tsx +587 -0
  39. package/src/components/tenants/tenant-roles.test.tsx +107 -0
  40. package/src/components/tenants/tenant-roles.tsx +418 -0
  41. package/src/components/tenants/tenant-settings.tsx +392 -0
  42. package/src/components/tenants/tenants-table.test.tsx +81 -0
  43. package/src/components/tenants/tenants-table.tsx +247 -0
  44. package/src/components/ui/alert.tsx +52 -0
  45. package/src/components/ui/avatar.tsx +46 -0
  46. package/src/components/ui/badge.tsx +32 -0
  47. package/src/components/ui/button.tsx +64 -0
  48. package/src/components/ui/card.tsx +65 -0
  49. package/src/components/ui/dialog.tsx +99 -0
  50. package/src/components/ui/dropdown-menu.tsx +97 -0
  51. package/src/components/ui/field.tsx +44 -0
  52. package/src/components/ui/input.tsx +23 -0
  53. package/src/components/ui/label.tsx +19 -0
  54. package/src/components/ui/select.tsx +87 -0
  55. package/src/components/ui/separator.tsx +22 -0
  56. package/src/components/ui/skeleton.tsx +13 -0
  57. package/src/components/ui/switch.tsx +29 -0
  58. package/src/components/ui/table.tsx +87 -0
  59. package/src/components/ui/tabs.tsx +51 -0
  60. package/src/components/ui/textarea.tsx +22 -0
  61. package/src/components/ui/tooltip.tsx +27 -0
  62. package/src/components/users/user-create-dialog.tsx +229 -0
  63. package/src/components/users/user-delete-dialog.tsx +88 -0
  64. package/src/components/users/user-detail.tsx +818 -0
  65. package/src/components/users/users-table.test.tsx +107 -0
  66. package/src/components/users/users-table.tsx +386 -0
  67. package/src/context/auth-context.tsx +127 -0
  68. package/src/context/theme-context.test.tsx +78 -0
  69. package/src/context/theme-context.tsx +110 -0
  70. package/src/hooks/use-call.ts +60 -0
  71. package/src/index.ts +160 -0
  72. package/src/lib/error-message.ts +16 -0
  73. package/src/lib/utils.test.ts +61 -0
  74. package/src/lib/utils.ts +79 -0
  75. package/src/lib/webauthn.ts +36 -0
  76. package/src/styles.css +107 -0
  77. package/src/test-setup.ts +5 -0
  78. package/tailwind.preset.cjs +15 -0
@@ -0,0 +1,1059 @@
1
+ import {
2
+ createSocialConnection,
3
+ deleteProject,
4
+ deleteSocialConnection,
5
+ getProject,
6
+ getProviders,
7
+ listSocialConnections,
8
+ updateSocialConnection,
9
+ updateProject,
10
+ type SocialConnectionRow,
11
+ type TenancyMode,
12
+ } from "@nexys/user-management-client";
13
+ import { AlertCircle, Check, Copy, Pencil, Save, Trash2 } from "lucide-react";
14
+ import { useEffect, useState, type FormEvent } from "react";
15
+
16
+ import { useUmClient } from "../../context/auth-context.js";
17
+ import { useCall } from "../../hooks/use-call.js";
18
+ import { errorMessage } from "../../lib/error-message.js";
19
+ import { Alert, AlertDescription } from "../ui/alert.js";
20
+ import { Badge } from "../ui/badge.js";
21
+ import { Button } from "../ui/button.js";
22
+ import {
23
+ Card,
24
+ CardContent,
25
+ CardDescription,
26
+ CardHeader,
27
+ CardTitle,
28
+ } from "../ui/card.js";
29
+ import {
30
+ Dialog,
31
+ DialogClose,
32
+ DialogContent,
33
+ DialogDescription,
34
+ DialogFooter,
35
+ DialogHeader,
36
+ DialogTitle,
37
+ DialogTrigger,
38
+ } from "../ui/dialog.js";
39
+ import { Field } from "../ui/field.js";
40
+ import { Input } from "../ui/input.js";
41
+ import { Label } from "../ui/label.js";
42
+ import {
43
+ Select,
44
+ SelectContent,
45
+ SelectItem,
46
+ SelectTrigger,
47
+ SelectValue,
48
+ } from "../ui/select.js";
49
+ import { Skeleton } from "../ui/skeleton.js";
50
+ import { Textarea } from "../ui/textarea.js";
51
+ import { Switch } from "../ui/switch.js";
52
+
53
+ export interface ProjectSettingsProps {
54
+ projectId: string;
55
+ /** Allow editing (project owner or superadmin). */
56
+ canManage?: boolean;
57
+ canDelete?: boolean;
58
+ onDeleted?: () => void;
59
+ }
60
+
61
+ export const ProjectSettings = ({
62
+ projectId,
63
+ canManage = false,
64
+ canDelete = false,
65
+ onDeleted,
66
+ }: ProjectSettingsProps) => {
67
+ const client = useUmClient();
68
+ const { data, loading, error, refresh } = useCall(getProject, { projectId });
69
+ const [copied, setCopied] = useState(false);
70
+ const [deleting, setDeleting] = useState(false);
71
+ const [deleteError, setDeleteError] = useState<string | null>(null);
72
+
73
+ const copyId = async () => {
74
+ await navigator.clipboard.writeText(projectId);
75
+ setCopied(true);
76
+ setTimeout(() => setCopied(false), 2000);
77
+ };
78
+
79
+ const handleDelete = async () => {
80
+ setDeleting(true);
81
+ setDeleteError(null);
82
+ const res = await client.call(deleteProject, { projectId });
83
+ setDeleting(false);
84
+ if (res.ok) {
85
+ onDeleted?.();
86
+ } else {
87
+ setDeleteError(errorMessage(res.error, "Failed to delete product."));
88
+ }
89
+ };
90
+
91
+ if (error) {
92
+ return (
93
+ <Alert variant="destructive">
94
+ <AlertCircle />
95
+ <AlertDescription>{errorMessage(error)}</AlertDescription>
96
+ </Alert>
97
+ );
98
+ }
99
+
100
+ return (
101
+ <div className="grid gap-6">
102
+ <Card>
103
+ <CardHeader>
104
+ <CardTitle>General</CardTitle>
105
+ <CardDescription>
106
+ {canManage ? "Update product information" : "Product information"}
107
+ </CardDescription>
108
+ </CardHeader>
109
+ <CardContent className="grid gap-4">
110
+ {loading ? (
111
+ <>
112
+ <Skeleton className="h-5 w-48" />
113
+ <Skeleton className="h-5 w-32" />
114
+ <Skeleton className="h-5 w-64" />
115
+ </>
116
+ ) : data ? (
117
+ <>
118
+ {canManage ? (
119
+ <GeneralForm
120
+ projectId={projectId}
121
+ name={data.name}
122
+ slug={data.slug}
123
+ onSaved={refresh}
124
+ />
125
+ ) : (
126
+ <>
127
+ <div className="grid gap-1">
128
+ <Label className="text-muted-foreground text-xs">Name</Label>
129
+ <p className="text-sm font-medium">{data.name}</p>
130
+ </div>
131
+ <div className="grid gap-1">
132
+ <Label className="text-muted-foreground text-xs">Slug</Label>
133
+ <p className="font-mono text-sm">{data.slug}</p>
134
+ </div>
135
+ </>
136
+ )}
137
+ <div className="grid gap-1">
138
+ <Label className="text-muted-foreground text-xs">UUID</Label>
139
+ <div className="flex items-center gap-2">
140
+ <code className="rounded bg-muted px-2 py-1 font-mono text-xs">
141
+ {projectId}
142
+ </code>
143
+ <Button
144
+ variant="ghost"
145
+ size="icon"
146
+ className="size-7"
147
+ onClick={copyId}
148
+ aria-label="Copy UUID"
149
+ >
150
+ {copied ? (
151
+ <Check className="size-3.5 text-green-600" />
152
+ ) : (
153
+ <Copy className="size-3.5" />
154
+ )}
155
+ </Button>
156
+ </div>
157
+ </div>
158
+ </>
159
+ ) : null}
160
+ </CardContent>
161
+ </Card>
162
+
163
+ {data ? (
164
+ <Card>
165
+ <CardHeader>
166
+ <CardTitle>Tenancy &amp; access</CardTitle>
167
+ <CardDescription>
168
+ How tenants and sign-ups behave inside this product.
169
+ </CardDescription>
170
+ </CardHeader>
171
+ <CardContent>
172
+ <TenancyForm
173
+ key={data.updatedAt}
174
+ projectId={projectId}
175
+ tenancyMode={data.tenancyMode}
176
+ allowSignup={data.allowSignup}
177
+ allowTenantCreation={data.allowTenantCreation}
178
+ canManage={canManage}
179
+ onSaved={refresh}
180
+ />
181
+ </CardContent>
182
+ </Card>
183
+ ) : null}
184
+
185
+ {data ? (
186
+ <Card>
187
+ <CardHeader>
188
+ <CardTitle>Localisation &amp; retention</CardTitle>
189
+ <CardDescription>
190
+ The locale users inherit when they set none of their own, and
191
+ how long this product keeps its audit logs.
192
+ </CardDescription>
193
+ </CardHeader>
194
+ <CardContent>
195
+ <LocaleRetentionForm
196
+ key={data.updatedAt}
197
+ projectId={projectId}
198
+ defaultLocale={data.defaultLocale}
199
+ logRetentionDays={data.logRetentionDays}
200
+ canManage={canManage}
201
+ onSaved={refresh}
202
+ />
203
+ </CardContent>
204
+ </Card>
205
+ ) : null}
206
+
207
+ {data ? (
208
+ <Card>
209
+ <CardHeader>
210
+ <CardTitle>Single sign-on</CardTitle>
211
+ <CardDescription>
212
+ Social login providers for this product, each with its own
213
+ OAuth client.
214
+ </CardDescription>
215
+ </CardHeader>
216
+ <CardContent>
217
+ <SocialConnections projectId={projectId} canManage={canManage} />
218
+ </CardContent>
219
+ </Card>
220
+ ) : null}
221
+
222
+ {canDelete && (
223
+ <Card className="border-destructive/50">
224
+ <CardHeader>
225
+ <CardTitle className="text-destructive">Danger zone</CardTitle>
226
+ <CardDescription>
227
+ Deleting a product removes every tenant inside it (cascade).
228
+ This action cannot be undone.
229
+ </CardDescription>
230
+ </CardHeader>
231
+ <CardContent>
232
+ {deleteError && (
233
+ <Alert variant="destructive" className="mb-4">
234
+ <AlertCircle />
235
+ <AlertDescription>{deleteError}</AlertDescription>
236
+ </Alert>
237
+ )}
238
+ <Dialog>
239
+ <DialogTrigger asChild>
240
+ <Button variant="destructive">
241
+ <Trash2 /> Delete product
242
+ </Button>
243
+ </DialogTrigger>
244
+ <DialogContent>
245
+ <DialogHeader>
246
+ <DialogTitle>Delete product?</DialogTitle>
247
+ <DialogDescription>
248
+ This will permanently delete{" "}
249
+ <strong>{data?.name ?? "this product"}</strong> and every
250
+ tenant inside it. This action cannot be undone.
251
+ </DialogDescription>
252
+ </DialogHeader>
253
+ <DialogFooter>
254
+ <DialogClose asChild>
255
+ <Button variant="outline">Cancel</Button>
256
+ </DialogClose>
257
+ <Button
258
+ variant="destructive"
259
+ onClick={handleDelete}
260
+ loading={deleting}
261
+ >
262
+ Delete permanently
263
+ </Button>
264
+ </DialogFooter>
265
+ </DialogContent>
266
+ </Dialog>
267
+ </CardContent>
268
+ </Card>
269
+ )}
270
+ </div>
271
+ );
272
+ };
273
+
274
+ const GeneralForm = ({
275
+ projectId,
276
+ name: initialName,
277
+ slug: initialSlug,
278
+ onSaved,
279
+ }: {
280
+ projectId: string;
281
+ name: string;
282
+ slug: string;
283
+ onSaved: () => void;
284
+ }) => {
285
+ const client = useUmClient();
286
+ const [name, setName] = useState(initialName);
287
+ const [slug, setSlug] = useState(initialSlug);
288
+ const [saving, setSaving] = useState(false);
289
+ const [saved, setSaved] = useState(false);
290
+ const [error, setError] = useState<string | null>(null);
291
+
292
+ // Server data refreshed underneath us (e.g. another tab saved) —
293
+ // resync untouched fields.
294
+ useEffect(() => setName(initialName), [initialName]);
295
+ useEffect(() => setSlug(initialSlug), [initialSlug]);
296
+
297
+ const dirty = name.trim() !== initialName || slug.trim() !== initialSlug;
298
+
299
+ const submit = async (e: FormEvent) => {
300
+ e.preventDefault();
301
+ setSaving(true);
302
+ setError(null);
303
+ setSaved(false);
304
+ const res = await client.call(updateProject, {
305
+ projectId,
306
+ name: name.trim(),
307
+ slug: slug.trim(),
308
+ });
309
+ setSaving(false);
310
+ if (res.ok) {
311
+ setSaved(true);
312
+ setTimeout(() => setSaved(false), 2000);
313
+ onSaved();
314
+ } else {
315
+ setError(errorMessage(res.error, "Couldn't save product settings."));
316
+ }
317
+ };
318
+
319
+ return (
320
+ <form onSubmit={submit} className="grid gap-4">
321
+ {error ? (
322
+ <Alert variant="destructive">
323
+ <AlertCircle />
324
+ <AlertDescription>{error}</AlertDescription>
325
+ </Alert>
326
+ ) : null}
327
+ <div className="grid gap-4 sm:grid-cols-2">
328
+ <Field label="Name" htmlFor="project-name">
329
+ <Input
330
+ id="project-name"
331
+ required
332
+ value={name}
333
+ onChange={(e) => setName(e.target.value)}
334
+ />
335
+ </Field>
336
+ <Field label="Slug" htmlFor="project-slug">
337
+ <Input
338
+ id="project-slug"
339
+ required
340
+ value={slug}
341
+ onChange={(e) => setSlug(e.target.value)}
342
+ className="font-mono"
343
+ />
344
+ </Field>
345
+ </div>
346
+ <div className="flex items-center gap-3">
347
+ <Button
348
+ type="submit"
349
+ loading={saving}
350
+ disabled={!dirty || !name.trim() || !slug.trim()}
351
+ >
352
+ {saved ? <Check /> : <Save />}
353
+ {saved ? "Saved" : "Save changes"}
354
+ </Button>
355
+ </div>
356
+ </form>
357
+ );
358
+ };
359
+
360
+ const TenancyForm = ({
361
+ projectId,
362
+ tenancyMode: initialMode,
363
+ allowSignup: initialSignup,
364
+ allowTenantCreation: initialTenantCreation,
365
+ canManage,
366
+ onSaved,
367
+ }: {
368
+ projectId: string;
369
+ tenancyMode: TenancyMode;
370
+ allowSignup: boolean;
371
+ allowTenantCreation: boolean;
372
+ canManage: boolean;
373
+ onSaved: () => void;
374
+ }) => {
375
+ const client = useUmClient();
376
+ const [mode, setMode] = useState<TenancyMode>(initialMode);
377
+ const [signup, setSignup] = useState(initialSignup);
378
+ const [tenantCreation, setTenantCreation] = useState(initialTenantCreation);
379
+ const [saving, setSaving] = useState(false);
380
+ const [saved, setSaved] = useState(false);
381
+ const [error, setError] = useState<string | null>(null);
382
+
383
+ const dirty =
384
+ mode !== initialMode ||
385
+ signup !== initialSignup ||
386
+ tenantCreation !== initialTenantCreation;
387
+
388
+ const submit = async (e: FormEvent) => {
389
+ e.preventDefault();
390
+ setSaving(true);
391
+ setError(null);
392
+ setSaved(false);
393
+ const res = await client.call(updateProject, {
394
+ projectId,
395
+ tenancyMode: mode,
396
+ allowSignup: signup,
397
+ allowTenantCreation: tenantCreation,
398
+ });
399
+ setSaving(false);
400
+ if (res.ok) {
401
+ setSaved(true);
402
+ setTimeout(() => setSaved(false), 2000);
403
+ onSaved();
404
+ } else {
405
+ setError(errorMessage(res.error, "Couldn't save tenancy settings."));
406
+ }
407
+ };
408
+
409
+ return (
410
+ <form onSubmit={submit} className="grid gap-4">
411
+ {error ? (
412
+ <Alert variant="destructive">
413
+ <AlertCircle />
414
+ <AlertDescription>{error}</AlertDescription>
415
+ </Alert>
416
+ ) : null}
417
+ <Field
418
+ label="Tenancy mode"
419
+ htmlFor="project-tenancy-mode"
420
+ description="Single keeps the product to exactly one tenant. Narrowing to single is refused while the product holds more than one tenant."
421
+ >
422
+ <Select
423
+ value={mode}
424
+ onValueChange={(v) => setMode(v as TenancyMode)}
425
+ disabled={!canManage}
426
+ >
427
+ <SelectTrigger id="project-tenancy-mode" className="w-[12rem]">
428
+ <SelectValue />
429
+ </SelectTrigger>
430
+ <SelectContent>
431
+ <SelectItem value="multi">Multi-tenant</SelectItem>
432
+ <SelectItem value="single">Single tenant</SelectItem>
433
+ </SelectContent>
434
+ </Select>
435
+ </Field>
436
+ <div className="flex items-center justify-between gap-4">
437
+ <div className="grid gap-0.5">
438
+ <Label htmlFor="project-signup">Open sign-up</Label>
439
+ <p className="text-muted-foreground text-xs">
440
+ Allow self-service sign-up scoped to this product.
441
+ </p>
442
+ </div>
443
+ <Switch
444
+ id="project-signup"
445
+ checked={signup}
446
+ onCheckedChange={setSignup}
447
+ disabled={!canManage}
448
+ />
449
+ </div>
450
+ <div className="flex items-center justify-between gap-4">
451
+ <div className="grid gap-0.5">
452
+ <Label htmlFor="project-tenant-creation">Self-serve tenants</Label>
453
+ <p className="text-muted-foreground text-xs">
454
+ Allow any authenticated user to create a tenant inside this
455
+ product.
456
+ </p>
457
+ </div>
458
+ <Switch
459
+ id="project-tenant-creation"
460
+ checked={tenantCreation}
461
+ onCheckedChange={setTenantCreation}
462
+ disabled={!canManage}
463
+ />
464
+ </div>
465
+ {canManage ? (
466
+ <div className="flex items-center gap-3">
467
+ <Button type="submit" loading={saving} disabled={!dirty}>
468
+ {saved ? <Check /> : <Save />}
469
+ {saved ? "Saved" : "Save changes"}
470
+ </Button>
471
+ </div>
472
+ ) : null}
473
+ </form>
474
+ );
475
+ };
476
+
477
+ /// Product default locale (which email-template variant its users get)
478
+ /// plus how long its audit logs are kept.
479
+ const LocaleRetentionForm = ({
480
+ projectId,
481
+ defaultLocale: initialLocale,
482
+ logRetentionDays: initialRetention,
483
+ canManage,
484
+ onSaved,
485
+ }: {
486
+ projectId: string;
487
+ defaultLocale: string;
488
+ logRetentionDays: number;
489
+ canManage: boolean;
490
+ onSaved: () => void;
491
+ }) => {
492
+ const client = useUmClient();
493
+ const [locale, setLocale] = useState(initialLocale);
494
+ const [retention, setRetention] = useState(String(initialRetention));
495
+ const [saving, setSaving] = useState(false);
496
+ const [saved, setSaved] = useState(false);
497
+ const [error, setError] = useState<string | null>(null);
498
+
499
+ const retentionNum = Number(retention);
500
+ const retentionValid =
501
+ retention.trim() !== "" &&
502
+ Number.isInteger(retentionNum) &&
503
+ retentionNum >= 0 &&
504
+ retentionNum <= 3650;
505
+ const dirty =
506
+ locale.trim().toLowerCase() !== initialLocale ||
507
+ retentionNum !== initialRetention;
508
+
509
+ const submit = async (e: FormEvent) => {
510
+ e.preventDefault();
511
+ setSaving(true);
512
+ setError(null);
513
+ setSaved(false);
514
+ const res = await client.call(updateProject, {
515
+ projectId,
516
+ defaultLocale: locale.trim().toLowerCase(),
517
+ logRetentionDays: retentionNum,
518
+ });
519
+ setSaving(false);
520
+ if (res.ok) {
521
+ setSaved(true);
522
+ setTimeout(() => setSaved(false), 2000);
523
+ onSaved();
524
+ } else {
525
+ setError(errorMessage(res.error, "Couldn't save these settings."));
526
+ }
527
+ };
528
+
529
+ return (
530
+ <form onSubmit={submit} className="grid gap-4">
531
+ {error ? (
532
+ <Alert variant="destructive">
533
+ <AlertCircle />
534
+ <AlertDescription>{error}</AlertDescription>
535
+ </Alert>
536
+ ) : null}
537
+ <div className="grid gap-4 sm:grid-cols-2">
538
+ <Field
539
+ label="Default locale"
540
+ htmlFor="project-locale"
541
+ description="Language tag (e.g. en, fr-CA) for users who set none of their own."
542
+ >
543
+ <Input
544
+ id="project-locale"
545
+ value={locale}
546
+ onChange={(e) => setLocale(e.target.value)}
547
+ disabled={!canManage}
548
+ placeholder="en"
549
+ className="font-mono"
550
+ />
551
+ </Field>
552
+ <Field
553
+ label="Log retention (days)"
554
+ htmlFor="project-log-retention"
555
+ description="How long audit logs for this product's tenants are kept. 0 keeps them forever."
556
+ >
557
+ <Input
558
+ id="project-log-retention"
559
+ type="number"
560
+ min={0}
561
+ max={3650}
562
+ value={retention}
563
+ onChange={(e) => setRetention(e.target.value)}
564
+ disabled={!canManage}
565
+ aria-invalid={!retentionValid}
566
+ />
567
+ </Field>
568
+ </div>
569
+ {canManage ? (
570
+ <div className="flex items-center gap-3">
571
+ <Button
572
+ type="submit"
573
+ loading={saving}
574
+ disabled={!dirty || !locale.trim() || !retentionValid}
575
+ >
576
+ {saved ? <Check /> : <Save />}
577
+ {saved ? "Saved" : "Save changes"}
578
+ </Button>
579
+ </div>
580
+ ) : null}
581
+ </form>
582
+ );
583
+ };
584
+
585
+ /// One redirect URL per textarea line, trimmed, blanks dropped.
586
+ const parseUrlLines = (text: string): string[] =>
587
+ text
588
+ .split("\n")
589
+ .map((l) => l.trim())
590
+ .filter((l) => l.length > 0);
591
+
592
+ /// Per-product social-login connection manager: list existing
593
+ /// connections, add one (provider dropdown from the catalog + client
594
+ /// id/secret/redirect URLs), edit, toggle enabled, delete. Secrets are
595
+ /// write-only.
596
+ const SocialConnections = ({
597
+ projectId,
598
+ canManage,
599
+ }: {
600
+ projectId: string;
601
+ canManage: boolean;
602
+ }) => {
603
+ const client = useUmClient();
604
+ const { data, loading, error, refresh } = useCall(listSocialConnections, {
605
+ projectId,
606
+ });
607
+ const catalog = useCall(getProviders);
608
+ const [busyId, setBusyId] = useState<string | null>(null);
609
+
610
+ const connections = data?.connections ?? [];
611
+
612
+ const toggleEnabled = async (c: SocialConnectionRow) => {
613
+ setBusyId(c.id);
614
+ await client.call(updateSocialConnection, {
615
+ projectId,
616
+ connectionId: c.id,
617
+ enabled: !c.enabled,
618
+ });
619
+ setBusyId(null);
620
+ refresh();
621
+ };
622
+
623
+ const remove = async (c: SocialConnectionRow) => {
624
+ setBusyId(c.id);
625
+ await client.call(deleteSocialConnection, { projectId, connectionId: c.id });
626
+ setBusyId(null);
627
+ refresh();
628
+ };
629
+
630
+ if (error) {
631
+ return (
632
+ <Alert variant="destructive">
633
+ <AlertCircle />
634
+ <AlertDescription>{errorMessage(error)}</AlertDescription>
635
+ </Alert>
636
+ );
637
+ }
638
+
639
+ return (
640
+ <div className="grid gap-4">
641
+ {loading ? (
642
+ <Skeleton className="h-16 w-full" />
643
+ ) : connections.length === 0 ? (
644
+ <p className="text-muted-foreground text-sm">
645
+ No social login providers configured for this product yet.
646
+ </p>
647
+ ) : (
648
+ <div className="grid gap-2">
649
+ {connections.map((c) => (
650
+ <div
651
+ key={c.id}
652
+ className="flex items-center justify-between gap-3 rounded-lg border bg-card p-3"
653
+ >
654
+ <div className="min-w-0">
655
+ <div className="flex items-center gap-2">
656
+ <span className="text-sm font-medium capitalize">{c.provider}</span>
657
+ <Badge variant={c.enabled ? "default" : "muted"}>
658
+ {c.enabled ? "enabled" : "disabled"}
659
+ </Badge>
660
+ </div>
661
+ <p className="truncate font-mono text-xs text-muted-foreground">
662
+ {c.clientId} · {c.redirectUri}
663
+ </p>
664
+ {c.redirectUrls.length > 0 ? (
665
+ <p className="truncate font-mono text-xs text-muted-foreground">
666
+ → {c.redirectUrls.join(", ")}
667
+ </p>
668
+ ) : null}
669
+ </div>
670
+ {canManage ? (
671
+ <div className="flex shrink-0 items-center gap-2">
672
+ <Switch
673
+ checked={c.enabled}
674
+ onCheckedChange={() => void toggleEnabled(c)}
675
+ disabled={busyId === c.id}
676
+ aria-label="Toggle enabled"
677
+ />
678
+ <EditConnectionDialog
679
+ projectId={projectId}
680
+ connection={c}
681
+ onSaved={refresh}
682
+ />
683
+ <Button
684
+ variant="ghost"
685
+ size="icon"
686
+ className="size-8"
687
+ onClick={() => void remove(c)}
688
+ disabled={busyId === c.id}
689
+ aria-label="Delete connection"
690
+ >
691
+ <Trash2 className="size-4" />
692
+ </Button>
693
+ </div>
694
+ ) : null}
695
+ </div>
696
+ ))}
697
+ </div>
698
+ )}
699
+ {canManage ? (
700
+ <AddConnectionDialog
701
+ projectId={projectId}
702
+ catalog={catalog.data?.providers ?? []}
703
+ existing={connections.map((c) => c.provider)}
704
+ onAdded={refresh}
705
+ />
706
+ ) : null}
707
+ </div>
708
+ );
709
+ };
710
+
711
+ const AddConnectionDialog = ({
712
+ projectId,
713
+ catalog,
714
+ existing,
715
+ onAdded,
716
+ }: {
717
+ projectId: string;
718
+ catalog: string[];
719
+ existing: string[];
720
+ onAdded: () => void;
721
+ }) => {
722
+ const client = useUmClient();
723
+ const available = catalog.filter((p) => !existing.includes(p));
724
+ // The SPA is served by the API in production, so its origin is the
725
+ // server's BASE_URL — the same value the server derives from.
726
+ const derivedRedirect = (p: string) =>
727
+ typeof window === "undefined" || !p
728
+ ? ""
729
+ : `${window.location.origin}/api/auth/callback/${p}`;
730
+ const [copiedRedirect, setCopiedRedirect] = useState(false);
731
+ const [open, setOpen] = useState(false);
732
+ const [provider, setProvider] = useState("");
733
+ const [clientId, setClientId] = useState("");
734
+ const [clientSecret, setClientSecret] = useState("");
735
+ const [redirectUri, setRedirectUri] = useState("");
736
+ const [redirectUrls, setRedirectUrls] = useState("");
737
+ const [scopes, setScopes] = useState("");
738
+ const [loading, setLoading] = useState(false);
739
+ const [error, setError] = useState<string | null>(null);
740
+
741
+ const reset = () => {
742
+ setProvider("");
743
+ setClientId("");
744
+ setClientSecret("");
745
+ setRedirectUri("");
746
+ setRedirectUrls("");
747
+ setScopes("");
748
+ setError(null);
749
+ setLoading(false);
750
+ };
751
+
752
+ const submit = async (e: FormEvent) => {
753
+ e.preventDefault();
754
+ setLoading(true);
755
+ setError(null);
756
+ const res = await client.call(createSocialConnection, {
757
+ projectId,
758
+ provider,
759
+ clientId: clientId.trim(),
760
+ clientSecret,
761
+ // Blank → the server derives {BASE_URL}/api/auth/callback/{provider}.
762
+ redirectUri: redirectUri.trim() || undefined,
763
+ redirectUrls: parseUrlLines(redirectUrls),
764
+ scopes: scopes.trim() || null,
765
+ });
766
+ setLoading(false);
767
+ if (res.ok) {
768
+ onAdded();
769
+ reset();
770
+ setOpen(false);
771
+ } else {
772
+ setError(errorMessage(res.error, "Couldn't add the connection."));
773
+ }
774
+ };
775
+
776
+ return (
777
+ <Dialog
778
+ open={open}
779
+ onOpenChange={(o) => {
780
+ setOpen(o);
781
+ if (!o) reset();
782
+ }}
783
+ >
784
+ <DialogTrigger asChild>
785
+ <Button variant="outline" size="sm" disabled={available.length === 0}>
786
+ Add social login
787
+ </Button>
788
+ </DialogTrigger>
789
+ <DialogContent>
790
+ <DialogHeader>
791
+ <DialogTitle>Add a social login</DialogTitle>
792
+ <DialogDescription>
793
+ Pick a provider and paste this product's own OAuth client. The
794
+ secret is stored encrypted and never shown again.
795
+ </DialogDescription>
796
+ </DialogHeader>
797
+ <form onSubmit={submit} className="grid gap-4" noValidate>
798
+ <Field label="Provider" htmlFor="conn-provider" required>
799
+ <Select value={provider} onValueChange={setProvider}>
800
+ <SelectTrigger id="conn-provider">
801
+ <SelectValue placeholder="Choose a provider" />
802
+ </SelectTrigger>
803
+ <SelectContent>
804
+ {available.map((p) => (
805
+ <SelectItem key={p} value={p} className="capitalize">
806
+ {p}
807
+ </SelectItem>
808
+ ))}
809
+ </SelectContent>
810
+ </Select>
811
+ </Field>
812
+ <Field label="Client ID" htmlFor="conn-client-id" required>
813
+ <Input
814
+ id="conn-client-id"
815
+ value={clientId}
816
+ onChange={(e) => setClientId(e.target.value)}
817
+ className="font-mono"
818
+ />
819
+ </Field>
820
+ <Field label="Client secret" htmlFor="conn-client-secret" required>
821
+ <Input
822
+ id="conn-client-secret"
823
+ type="password"
824
+ value={clientSecret}
825
+ onChange={(e) => setClientSecret(e.target.value)}
826
+ className="font-mono"
827
+ />
828
+ </Field>
829
+ <Field
830
+ label="Redirect URI"
831
+ htmlFor="conn-redirect"
832
+ description="Register this exact URL with the provider. Leave blank to use the default; override only if the API runs behind a custom domain."
833
+ >
834
+ <div className="flex items-center gap-2">
835
+ <Input
836
+ id="conn-redirect"
837
+ value={redirectUri}
838
+ onChange={(e) => setRedirectUri(e.target.value)}
839
+ placeholder={derivedRedirect(provider) || "Choose a provider first"}
840
+ className="font-mono"
841
+ />
842
+ <Button
843
+ type="button"
844
+ variant="outline"
845
+ size="icon"
846
+ aria-label="Copy redirect URI"
847
+ disabled={!provider && !redirectUri.trim()}
848
+ onClick={async () => {
849
+ const value = redirectUri.trim() || derivedRedirect(provider);
850
+ if (!value) return;
851
+ await navigator.clipboard?.writeText(value);
852
+ setCopiedRedirect(true);
853
+ setTimeout(() => setCopiedRedirect(false), 1500);
854
+ }}
855
+ >
856
+ {copiedRedirect ? <Check /> : <Copy />}
857
+ </Button>
858
+ </div>
859
+ </Field>
860
+ <Field
861
+ label="Redirect URLs"
862
+ htmlFor="conn-redirect-urls"
863
+ description="Where users may land after sign-in — one full URL per line, like a Google OAuth client. Sign-ins return to the URL matching the caller's origin; the first entry is the default. Leave empty to always return to this console."
864
+ >
865
+ <Textarea
866
+ id="conn-redirect-urls"
867
+ value={redirectUrls}
868
+ onChange={(e) => setRedirectUrls(e.target.value)}
869
+ rows={3}
870
+ placeholder={"https://app.example.com/welcome"}
871
+ className="font-mono"
872
+ />
873
+ </Field>
874
+ <Field
875
+ label="Scopes"
876
+ htmlFor="conn-scopes"
877
+ description="Optional space-separated override; leave blank for the provider defaults."
878
+ >
879
+ <Input
880
+ id="conn-scopes"
881
+ value={scopes}
882
+ onChange={(e) => setScopes(e.target.value)}
883
+ className="font-mono"
884
+ />
885
+ </Field>
886
+ {error ? (
887
+ <Alert variant="destructive">
888
+ <AlertCircle />
889
+ <AlertDescription>{error}</AlertDescription>
890
+ </Alert>
891
+ ) : null}
892
+ <DialogFooter>
893
+ <Button type="button" variant="ghost" onClick={() => setOpen(false)} disabled={loading}>
894
+ Cancel
895
+ </Button>
896
+ <Button
897
+ type="submit"
898
+ loading={loading}
899
+ disabled={!provider || !clientId.trim() || !clientSecret}
900
+ >
901
+ Add connection
902
+ </Button>
903
+ </DialogFooter>
904
+ </form>
905
+ </DialogContent>
906
+ </Dialog>
907
+ );
908
+ };
909
+
910
+ /// Edit an existing connection: client id, a replacement secret
911
+ /// (blank keeps the stored one), the redirect URL list and scopes.
912
+ const EditConnectionDialog = ({
913
+ projectId,
914
+ connection,
915
+ onSaved,
916
+ }: {
917
+ projectId: string;
918
+ connection: SocialConnectionRow;
919
+ onSaved: () => void;
920
+ }) => {
921
+ const client = useUmClient();
922
+ const [open, setOpen] = useState(false);
923
+ const [clientId, setClientId] = useState(connection.clientId);
924
+ const [clientSecret, setClientSecret] = useState("");
925
+ const [redirectUrls, setRedirectUrls] = useState(
926
+ connection.redirectUrls.join("\n")
927
+ );
928
+ const [scopes, setScopes] = useState(connection.scopes ?? "");
929
+ const [loading, setLoading] = useState(false);
930
+ const [error, setError] = useState<string | null>(null);
931
+
932
+ const reset = () => {
933
+ setClientId(connection.clientId);
934
+ setClientSecret("");
935
+ setRedirectUrls(connection.redirectUrls.join("\n"));
936
+ setScopes(connection.scopes ?? "");
937
+ setError(null);
938
+ setLoading(false);
939
+ };
940
+
941
+ const submit = async (e: FormEvent) => {
942
+ e.preventDefault();
943
+ setLoading(true);
944
+ setError(null);
945
+ const res = await client.call(updateSocialConnection, {
946
+ projectId,
947
+ connectionId: connection.id,
948
+ clientId: clientId.trim(),
949
+ // Blank keeps the stored secret.
950
+ ...(clientSecret ? { clientSecret } : {}),
951
+ redirectUrls: parseUrlLines(redirectUrls),
952
+ scopes: scopes.trim() || null,
953
+ });
954
+ setLoading(false);
955
+ if (res.ok) {
956
+ onSaved();
957
+ setOpen(false);
958
+ } else {
959
+ setError(errorMessage(res.error, "Couldn't save the connection."));
960
+ }
961
+ };
962
+
963
+ return (
964
+ <Dialog
965
+ open={open}
966
+ onOpenChange={(o) => {
967
+ setOpen(o);
968
+ if (o) reset();
969
+ }}
970
+ >
971
+ <DialogTrigger asChild>
972
+ <Button
973
+ variant="ghost"
974
+ size="icon"
975
+ className="size-8"
976
+ aria-label={`Edit ${connection.provider} connection`}
977
+ >
978
+ <Pencil className="size-4" />
979
+ </Button>
980
+ </DialogTrigger>
981
+ <DialogContent>
982
+ <DialogHeader>
983
+ <DialogTitle className="capitalize">
984
+ Edit {connection.provider} connection
985
+ </DialogTitle>
986
+ <DialogDescription>
987
+ The client secret is write-only: leave it blank to keep the
988
+ stored one.
989
+ </DialogDescription>
990
+ </DialogHeader>
991
+ <form onSubmit={submit} className="grid gap-4" noValidate>
992
+ <Field label="Client ID" htmlFor="edit-conn-client-id" required>
993
+ <Input
994
+ id="edit-conn-client-id"
995
+ value={clientId}
996
+ onChange={(e) => setClientId(e.target.value)}
997
+ className="font-mono"
998
+ />
999
+ </Field>
1000
+ <Field label="Client secret" htmlFor="edit-conn-client-secret">
1001
+ <Input
1002
+ id="edit-conn-client-secret"
1003
+ type="password"
1004
+ value={clientSecret}
1005
+ onChange={(e) => setClientSecret(e.target.value)}
1006
+ placeholder="Unchanged"
1007
+ className="font-mono"
1008
+ />
1009
+ </Field>
1010
+ <Field
1011
+ label="Redirect URLs"
1012
+ htmlFor="edit-conn-redirect-urls"
1013
+ description="Where users may land after sign-in — one full URL per line. Sign-ins return to the URL matching the caller's origin; the first entry is the default. Empty always returns to this console."
1014
+ >
1015
+ <Textarea
1016
+ id="edit-conn-redirect-urls"
1017
+ value={redirectUrls}
1018
+ onChange={(e) => setRedirectUrls(e.target.value)}
1019
+ rows={3}
1020
+ placeholder={"https://app.example.com/welcome"}
1021
+ className="font-mono"
1022
+ />
1023
+ </Field>
1024
+ <Field
1025
+ label="Scopes"
1026
+ htmlFor="edit-conn-scopes"
1027
+ description="Optional space-separated override; leave blank for the provider defaults."
1028
+ >
1029
+ <Input
1030
+ id="edit-conn-scopes"
1031
+ value={scopes}
1032
+ onChange={(e) => setScopes(e.target.value)}
1033
+ className="font-mono"
1034
+ />
1035
+ </Field>
1036
+ {error ? (
1037
+ <Alert variant="destructive">
1038
+ <AlertCircle />
1039
+ <AlertDescription>{error}</AlertDescription>
1040
+ </Alert>
1041
+ ) : null}
1042
+ <DialogFooter>
1043
+ <Button
1044
+ type="button"
1045
+ variant="ghost"
1046
+ onClick={() => setOpen(false)}
1047
+ disabled={loading}
1048
+ >
1049
+ Cancel
1050
+ </Button>
1051
+ <Button type="submit" loading={loading} disabled={!clientId.trim()}>
1052
+ Save
1053
+ </Button>
1054
+ </DialogFooter>
1055
+ </form>
1056
+ </DialogContent>
1057
+ </Dialog>
1058
+ );
1059
+ };