@kidecms/core 0.29.3 → 0.31.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 (50) hide show
  1. package/admin/components/BlockEditor.tsx +64 -45
  2. package/admin/components/CheckboxField.tsx +12 -3
  3. package/admin/components/ContentEditor.tsx +1 -1
  4. package/admin/components/DocumentActions.tsx +69 -0
  5. package/admin/components/DocumentsDataTable.tsx +28 -1
  6. package/admin/components/FieldControl.astro +35 -4
  7. package/admin/components/PasskeySettings.tsx +121 -0
  8. package/admin/components/PasskeySignIn.tsx +57 -0
  9. package/admin/components/SharedSectionBlockField.tsx +1 -1
  10. package/admin/components/SidebarUserMenu.tsx +7 -1
  11. package/admin/components/TwoFactorSettings.tsx +206 -0
  12. package/admin/components/UnsavedGuard.tsx +9 -2
  13. package/admin/components/block-fields.tsx +42 -25
  14. package/admin/components/block-values.ts +52 -0
  15. package/admin/layouts/AdminLayout.astro +42 -2
  16. package/admin/views/EditView.astro +75 -39
  17. package/admin/views/ListView.astro +43 -3
  18. package/admin/views/edit/EditScripts.astro +88 -2
  19. package/core/api.ts +49 -5
  20. package/core/auth-config.ts +53 -11
  21. package/core/auth-engine.ts +920 -0
  22. package/core/auth.ts +46 -152
  23. package/core/create-admin.ts +9 -5
  24. package/core/define.ts +75 -35
  25. package/core/generator.ts +80 -10
  26. package/core/index.ts +31 -3
  27. package/core/schema.ts +3 -1
  28. package/core/seed.ts +12 -2
  29. package/internals/integration.ts +34 -3
  30. package/internals/mcp.ts +3 -3
  31. package/internals/shared-deps.ts +126 -0
  32. package/internals/upgrade.ts +3 -0
  33. package/internals/virtual.d.ts +3 -2
  34. package/middleware/auth.ts +58 -18
  35. package/package.json +26 -21
  36. package/routes/admin/account.astro +138 -0
  37. package/routes/admin/login/verify.astro +90 -0
  38. package/routes/admin/login.astro +84 -33
  39. package/routes/api/auth/[...all].ts +153 -0
  40. package/routes/api/auth/_better-auth.ts +26 -0
  41. package/routes/api/auth/account.ts +69 -0
  42. package/routes/api/auth/forgot-password.ts +38 -32
  43. package/routes/api/auth/invite.ts +66 -98
  44. package/routes/api/auth/login/verify.ts +50 -0
  45. package/routes/api/auth/login.ts +68 -118
  46. package/routes/api/auth/logout.ts +13 -28
  47. package/routes/api/auth/reset-password.ts +17 -56
  48. package/routes/api/auth/setup.ts +14 -20
  49. package/routes/api/auth/sso/[provider]/start.ts +33 -25
  50. package/routes/api/forms/submit/[slug].ts +27 -2
@@ -46,21 +46,29 @@ type SharedSectionOption = {
46
46
 
47
47
  type Props = {
48
48
  name: string;
49
- value?: string;
49
+ /** Serialized JSON from the form, or the array itself when nested inside another block. */
50
+ value?: string | unknown[];
51
+ /** The field's label — names the items in the empty state ("No fields added yet"). */
52
+ label?: string;
50
53
  types: BlockTypesMeta;
51
54
  linkOptions?: LinkableCollection[];
52
55
  sharedSections?: SharedSectionOption[];
53
56
  sharedEnabled?: boolean;
57
+ /**
58
+ * Controlled mode, for a `blocks` sub-field inside another block: the parent owns
59
+ * the value, form serialization and live preview, so no hidden input or broadcast.
60
+ */
61
+ onChange?: (blocks: unknown[]) => void;
54
62
  };
55
63
 
56
64
  const SHARED_BLOCK_TYPE = "__shared";
57
65
 
58
66
  const isSharedBlock = (block: Block) => block.type === SHARED_BLOCK_TYPE && typeof block.ref === "string";
59
67
 
60
- function parseBlocks(value: string | undefined, types: BlockTypesMeta): Block[] {
68
+ function parseBlocks(value: string | unknown[] | undefined, types: BlockTypesMeta): Block[] {
61
69
  if (!value) return [];
62
70
  try {
63
- const parsed = JSON.parse(value);
71
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
64
72
  if (!Array.isArray(parsed)) return [];
65
73
  return parsed.map((item: Record<string, unknown>) => ({
66
74
  ...item,
@@ -72,8 +80,10 @@ function parseBlocks(value: string | undefined, types: BlockTypesMeta): Block[]
72
80
  }
73
81
  }
74
82
 
83
+ const stripKeys = (blocks: Block[]) => blocks.map(({ _key, ...rest }) => rest);
84
+
75
85
  function serializeBlocks(blocks: Block[]): string {
76
- return JSON.stringify(blocks.map(({ _key, ...rest }) => rest));
86
+ return JSON.stringify(stripKeys(blocks));
77
87
  }
78
88
 
79
89
  // -----------------------------------------------
@@ -221,7 +231,7 @@ function SortableBlock({
221
231
 
222
232
  {/* Content */}
223
233
  {isExpanded && (
224
- <div ref={contentRef} className="space-y-4 border-t px-4 py-4">
234
+ <div ref={contentRef} className="space-y-6 border-t px-4 py-5">
225
235
  {shared ? (
226
236
  <div className="space-y-3">
227
237
  <div>
@@ -286,11 +296,14 @@ function SortableBlock({
286
296
  export default function BlockEditor({
287
297
  name,
288
298
  value,
299
+ label,
289
300
  types,
290
301
  linkOptions = [],
291
302
  sharedSections = [],
292
303
  sharedEnabled = true,
304
+ onChange,
293
305
  }: Props) {
306
+ const controlled = Boolean(onChange);
294
307
  const [blocks, setBlocks] = useState<Block[]>(() => parseBlocks(value, types));
295
308
  const [expandedKeys, setExpandedKeys] = useState<Set<string>>(() => new Set());
296
309
  const [newBlockKey, setNewBlockKey] = useState<string | null>(null);
@@ -320,6 +333,7 @@ export default function BlockEditor({
320
333
  // Live preview: broadcast block data for server-side rendering. Also replay the
321
334
  // current value when a preview tab opened after edits announces itself.
322
335
  useEffect(() => {
336
+ if (controlled) return;
323
337
  if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
324
338
  const channel = previewChannelRef.current;
325
339
  if (!channel) return;
@@ -328,17 +342,18 @@ export default function BlockEditor({
328
342
  channel.onmessage = (e: MessageEvent) => {
329
343
  if (e.data?.type === "preview-ready") broadcast();
330
344
  };
331
- }, [blocks, name]);
345
+ }, [blocks, name, controlled]);
332
346
 
333
347
  const updateBlocks = useCallback(
334
348
  (updater: (prev: Block[]) => Block[]) => {
335
349
  setBlocks((prev) => {
336
350
  const next = updater(prev);
337
- setTimeout(dispatchChange, 0);
351
+ // Deferred: never update a parent from inside this state updater.
352
+ setTimeout(() => (onChange ? onChange(stripKeys(next)) : dispatchChange()), 0);
338
353
  return next;
339
354
  });
340
355
  },
341
- [dispatchChange],
356
+ [dispatchChange, onChange],
342
357
  );
343
358
 
344
359
  const handleDragStart = useCallback(() => {
@@ -495,48 +510,52 @@ export default function BlockEditor({
495
510
  const serialized = serializeBlocks(blocks);
496
511
 
497
512
  return (
498
- <div className="space-y-3">
499
- <input type="hidden" ref={hiddenRef} name={name} value={serialized} />
513
+ // Nested lists sit tighter: they're one group inside a block, not a page-level field.
514
+ <div className={controlled ? "space-y-2" : "space-y-3"}>
515
+ {!controlled && <input type="hidden" ref={hiddenRef} name={name} value={serialized} />}
500
516
 
501
- {blocks.length === 0 && (
517
+ {blocks.length === 0 && !controlled && (
502
518
  <div className="bg-field-subtle flex h-20 items-center justify-center rounded-lg border border-dashed">
503
- <p className="text-muted-foreground text-sm">No blocks added yet</p>
519
+ <p className="text-muted-foreground text-sm">No {label ? label.toLowerCase() : "blocks"} added yet</p>
504
520
  </div>
505
521
  )}
506
522
 
507
- <DndContext
508
- sensors={sensors}
509
- collisionDetection={closestCenter}
510
- onDragStart={handleDragStart}
511
- onDragEnd={handleDragEnd}
512
- >
513
- <SortableContext items={blocks.map((b) => b._key)} strategy={verticalListSortingStrategy}>
514
- <div className="space-y-3">
515
- {blocks.map((block) => {
516
- const fieldsMeta = isSharedBlock(block) ? {} : (types[block.type] ?? {});
517
- const sharedSection = isSharedBlock(block) ? sharedSectionsById.get(String(block.ref)) : undefined;
518
- return (
519
- <SortableBlock
520
- key={block._key}
521
- block={block}
522
- fieldsMeta={fieldsMeta}
523
- isExpanded={expandedKeys.has(block._key)}
524
- autoFocus={newBlockKey === block._key}
525
- onAutoFocused={() => setNewBlockKey(null)}
526
- onToggle={() => toggleExpanded(block._key)}
527
- onRemove={() => removeBlock(block._key)}
528
- onDetach={() => detachSharedBlock(block._key)}
529
- onSaveShared={() => saveAsShared(block._key)}
530
- sharedEnabled={sharedEnabled}
531
- onUpdateField={(fn, v) => updateField(block._key, fn, v)}
532
- linkOptions={linkOptions}
533
- sharedSection={sharedSection}
534
- />
535
- );
536
- })}
537
- </div>
538
- </SortableContext>
539
- </DndContext>
523
+ {/* An empty nested list renders nothing, so no stray gap sits above the add buttons. */}
524
+ {(blocks.length > 0 || !controlled) && (
525
+ <DndContext
526
+ sensors={sensors}
527
+ collisionDetection={closestCenter}
528
+ onDragStart={handleDragStart}
529
+ onDragEnd={handleDragEnd}
530
+ >
531
+ <SortableContext items={blocks.map((b) => b._key)} strategy={verticalListSortingStrategy}>
532
+ <div className={controlled ? "space-y-2" : "space-y-3"}>
533
+ {blocks.map((block) => {
534
+ const fieldsMeta = isSharedBlock(block) ? {} : (types[block.type] ?? {});
535
+ const sharedSection = isSharedBlock(block) ? sharedSectionsById.get(String(block.ref)) : undefined;
536
+ return (
537
+ <SortableBlock
538
+ key={block._key}
539
+ block={block}
540
+ fieldsMeta={fieldsMeta}
541
+ isExpanded={expandedKeys.has(block._key)}
542
+ autoFocus={newBlockKey === block._key}
543
+ onAutoFocused={() => setNewBlockKey(null)}
544
+ onToggle={() => toggleExpanded(block._key)}
545
+ onRemove={() => removeBlock(block._key)}
546
+ onDetach={() => detachSharedBlock(block._key)}
547
+ onSaveShared={() => saveAsShared(block._key)}
548
+ sharedEnabled={sharedEnabled}
549
+ onUpdateField={(fn, v) => updateField(block._key, fn, v)}
550
+ linkOptions={linkOptions}
551
+ sharedSection={sharedSection}
552
+ />
553
+ );
554
+ })}
555
+ </div>
556
+ </SortableContext>
557
+ </DndContext>
558
+ )}
540
559
 
541
560
  {/* Add block buttons */}
542
561
  <div className="flex flex-wrap gap-2">
@@ -5,16 +5,20 @@ type Props = {
5
5
  name: string;
6
6
  checked?: boolean;
7
7
  disabled?: boolean;
8
+ /** Shown beside the box — a checkbox names itself instead of taking a label above it. */
9
+ label?: string;
10
+ required?: boolean;
8
11
  };
9
12
 
10
- export default function CheckboxField({ name, checked: initial = false, disabled }: Props) {
13
+ export default function CheckboxField({ name, checked: initial = false, disabled, label, required }: Props) {
11
14
  const [checked, setChecked] = useState(initial);
12
15
  const hiddenRef = useRef<HTMLInputElement>(null);
13
16
 
14
17
  return (
15
- <label className="group inline-flex cursor-pointer items-center gap-3 text-sm">
18
+ <label className="group inline-flex w-fit cursor-pointer items-center gap-3 text-sm has-disabled:cursor-not-allowed">
16
19
  <input type="hidden" name={name} value={checked ? "true" : "false"} ref={hiddenRef} />
17
20
  <Checkbox
21
+ id={name}
18
22
  className="group-hover:border-primary/60 disabled:group-hover:border-input"
19
23
  checked={checked}
20
24
  onCheckedChange={(v) => {
@@ -25,7 +29,12 @@ export default function CheckboxField({ name, checked: initial = false, disabled
25
29
  }}
26
30
  disabled={disabled}
27
31
  />
28
- <span className="text-muted-foreground select-none">{checked ? "true" : "false"}</span>
32
+ {label && (
33
+ <span className="text-foreground/80 leading-none font-medium select-none">
34
+ {label}
35
+ {required ? " *" : ""}
36
+ </span>
37
+ )}
29
38
  </label>
30
39
  );
31
40
  }
@@ -260,7 +260,7 @@ function BlockNodeView(props: NodeViewProps) {
260
260
  </div>
261
261
 
262
262
  {expanded && (
263
- <div className="space-y-4 border-t px-4 py-4" contentEditable={false}>
263
+ <div className="space-y-6 border-t px-4 py-5" contentEditable={false}>
264
264
  {isShared ? (
265
265
  <div className="space-y-3">
266
266
  <div>
@@ -59,6 +59,13 @@ type Props = {
59
59
  entityLabel?: string;
60
60
  /** Adds `_force=1` to the delete submit, telling the API the warning was shown and accepted. */
61
61
  forceOnConfirm?: boolean;
62
+ /**
63
+ * Offers "Change language…" — only passed while the document exists in one language
64
+ * (with a translation, the API refuses to move the original to that locale).
65
+ */
66
+ languages?: Array<{ value: string; label: string }>;
67
+ /** The language the document is currently written in. */
68
+ contentLanguage?: string;
62
69
  };
63
70
 
64
71
  export default function DocumentActions({
@@ -79,8 +86,12 @@ export default function DocumentActions({
79
86
  referencesEndpoint,
80
87
  entityLabel = "document",
81
88
  forceOnConfirm,
89
+ languages,
90
+ contentLanguage,
82
91
  }: Props) {
83
92
  const [scheduleOpen, setScheduleOpen] = useState(false);
93
+ const [languageOpen, setLanguageOpen] = useState(false);
94
+ const [language, setLanguage] = useState(contentLanguage ?? "");
84
95
  const [deleteOpen, setDeleteOpen] = useState(false);
85
96
  const [refWarning, setRefWarning] = useState<{ tone: "warn" | "muted"; message: string } | null>(null);
86
97
  const [publishAt, setPublishAt] = useState(currentPublishAt ? toLocalDatetime(currentPublishAt) : "");
@@ -94,6 +105,7 @@ export default function DocumentActions({
94
105
  showDelete ||
95
106
  showSchedule ||
96
107
  showCancelSchedule ||
108
+ Boolean(languages?.length) ||
97
109
  versions.length > 0;
98
110
  if (!hasActions) return null;
99
111
 
@@ -170,6 +182,21 @@ export default function DocumentActions({
170
182
  form.submit();
171
183
  };
172
184
 
185
+ // Saves the document with its new original language (and any pending edits).
186
+ const submitLanguage = () => {
187
+ const form = document.getElementById(formId) as HTMLFormElement | null;
188
+ if (!form || !language || language === contentLanguage) return;
189
+ let input = form.querySelector<HTMLInputElement>('input[name="_sourceLocale"]');
190
+ if (!input) {
191
+ input = document.createElement("input");
192
+ input.type = "hidden";
193
+ input.name = "_sourceLocale";
194
+ form.appendChild(input);
195
+ }
196
+ input.value = language;
197
+ form.submit();
198
+ };
199
+
173
200
  const restoreVersion = (version: number) => {
174
201
  if (!restoreEndpoint) return;
175
202
  const form = document.createElement("form");
@@ -206,6 +233,9 @@ export default function DocumentActions({
206
233
  <DropdownMenuContent align="end" className="w-48">
207
234
  {canDuplicate && <DropdownMenuItem onClick={duplicate}>Duplicate</DropdownMenuItem>}
208
235
  {showSchedule && <DropdownMenuItem onClick={() => setScheduleOpen(true)}>Schedule publish</DropdownMenuItem>}
236
+ {languages && languages.length > 1 && (
237
+ <DropdownMenuItem onClick={() => setLanguageOpen(true)}>Change language…</DropdownMenuItem>
238
+ )}
209
239
  {showCancelSchedule && (
210
240
  <DropdownMenuItem onClick={() => submitAction("unpublish")}>Cancel schedule</DropdownMenuItem>
211
241
  )}
@@ -341,6 +371,45 @@ export default function DocumentActions({
341
371
  </DialogContent>
342
372
  </Dialog>
343
373
 
374
+ {languages && languages.length > 1 && (
375
+ <Dialog open={languageOpen} onOpenChange={setLanguageOpen}>
376
+ <DialogContent>
377
+ <DialogHeader>
378
+ <DialogTitle>Change language</DialogTitle>
379
+ <DialogDescription>
380
+ Marks the language this document is written in. The content is not translated — use this when it was
381
+ saved under the wrong language.
382
+ </DialogDescription>
383
+ </DialogHeader>
384
+ <div className="grid gap-2 py-2">
385
+ <label htmlFor="document-language" className="text-sm font-medium">
386
+ Language
387
+ </label>
388
+ <select
389
+ id="document-language"
390
+ value={language}
391
+ onChange={(e) => setLanguage(e.target.value)}
392
+ className="border-input bg-background flex h-9 w-full rounded-md border px-3 py-1 text-sm shadow-sm"
393
+ >
394
+ {languages.map((option) => (
395
+ <option key={option.value} value={option.value}>
396
+ {option.label}
397
+ </option>
398
+ ))}
399
+ </select>
400
+ </div>
401
+ <DialogFooter>
402
+ <DialogClose>
403
+ <Button variant="outline">Cancel</Button>
404
+ </DialogClose>
405
+ <Button onClick={submitLanguage} disabled={!language || language === contentLanguage}>
406
+ Change language
407
+ </Button>
408
+ </DialogFooter>
409
+ </DialogContent>
410
+ </Dialog>
411
+ )}
412
+
344
413
  <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
345
414
  <AlertDialogContent>
346
415
  <AlertDialogHeader>
@@ -21,6 +21,7 @@ import {
21
21
  ChevronDown,
22
22
  ChevronLeft,
23
23
  ChevronRight,
24
+ Check,
24
25
  Loader2,
25
26
  MoreHorizontal,
26
27
  Search,
@@ -96,6 +97,8 @@ type DocumentsDataTableProps = {
96
97
  serverPagination?: ServerPaginationConfig;
97
98
  /** Bulk status change: if provided, renders "Mark as <status>" entries in the selection menu. */
98
99
  statusOptions?: string[];
100
+ /** Language filter in the toolbar (multilingual collections only); each option is a server-side link. */
101
+ languageFilter?: { active: string; options: Array<{ value: string; label: string; href: string }> };
99
102
  };
100
103
 
101
104
  const formatDateClient = (value: unknown): string => {
@@ -163,6 +166,7 @@ export default function DocumentsDataTable({
163
166
  data,
164
167
  serverPagination,
165
168
  statusOptions,
169
+ languageFilter,
166
170
  }: DocumentsDataTableProps) {
167
171
  const isServerMode = !!serverPagination;
168
172
 
@@ -552,7 +556,7 @@ export default function DocumentsDataTable({
552
556
  {row.original.locales.map((locale) => (
553
557
  <a
554
558
  key={locale}
555
- href={`${row.original.editHref}?locale=${locale}`}
559
+ href={`${row.original.editHref.split("?")[0]}?locale=${locale}`}
556
560
  onClick={(e) => e.stopPropagation()}
557
561
  >
558
562
  <Badge
@@ -710,6 +714,29 @@ export default function DocumentsDataTable({
710
714
  </div>
711
715
 
712
716
  <div className="flex flex-wrap items-center gap-2">
717
+ {languageFilter && (
718
+ <DropdownMenu>
719
+ <DropdownMenuTrigger asChild>
720
+ <Button variant="outline" size="sm">
721
+ {languageFilter.active
722
+ ? (languageFilter.options.find((option) => option.value === languageFilter.active)?.label ??
723
+ "All languages")
724
+ : "All languages"}
725
+ <ChevronDown className="size-4" />
726
+ </Button>
727
+ </DropdownMenuTrigger>
728
+ <DropdownMenuContent align="end" className="w-44">
729
+ {languageFilter.options.map((option) => (
730
+ <DropdownMenuItem key={option.value} onClick={() => window.location.assign(option.href)}>
731
+ <Check
732
+ className={cn("size-4", option.value === languageFilter.active ? "opacity-100" : "opacity-0")}
733
+ />
734
+ {option.label}
735
+ </DropdownMenuItem>
736
+ ))}
737
+ </DropdownMenuContent>
738
+ </DropdownMenu>
739
+ )}
713
740
  {selectedRows.length > 0 && (
714
741
  <DropdownMenu>
715
742
  <DropdownMenuTrigger asChild>
@@ -117,6 +117,16 @@ const toSubFieldMeta = (subField: FieldConfig): SubFieldMeta => ({
117
117
  "itemFields" in subField && subField.itemFields
118
118
  ? Object.fromEntries(Object.entries(subField.itemFields).map(([name, f]) => [name, toSubFieldMeta(f)]))
119
119
  : undefined,
120
+ // A `blocks` sub-field inside a block renders its own nested block editor.
121
+ types:
122
+ subField.type === "blocks"
123
+ ? Object.fromEntries(
124
+ Object.entries(subField.types).map(([typeName, typeFields]) => [
125
+ typeName,
126
+ Object.fromEntries(Object.entries(typeFields).map(([name, f]) => [name, toSubFieldMeta(f)])),
127
+ ]),
128
+ )
129
+ : undefined,
120
130
  });
121
131
 
122
132
  const toBlockTypesMeta = (source: Record<string, Record<string, FieldConfig>> | null | undefined) =>
@@ -147,15 +157,23 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
147
157
  : {}}
148
158
  >
149
159
  {
150
- !isTreeEditor && (
160
+ !isTreeEditor && field.type !== "boolean" && (
151
161
  <Label htmlFor={name}>
152
162
  {label}
153
163
  {field.required ? " *" : ""}
154
164
  </Label>
155
165
  )
156
166
  }
157
- {field.description && <p class="text-muted-foreground -mt-1 text-xs leading-5">{field.description}</p>}
158
- {field.admin?.help && <p class="text-muted-foreground -mt-1 -mb-0.5 text-xs leading-5">{field.admin.help}</p>}
167
+ {
168
+ field.type !== "boolean" && field.description && (
169
+ <p class="text-muted-foreground -mt-1 text-xs leading-5">{field.description}</p>
170
+ )
171
+ }
172
+ {
173
+ field.type !== "boolean" && field.admin?.help && (
174
+ <p class="text-muted-foreground -mt-1 -mb-0.5 text-xs leading-5">{field.admin.help}</p>
175
+ )
176
+ }
159
177
 
160
178
  {
161
179
  CustomComponent && (
@@ -255,7 +273,19 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
255
273
  )}
256
274
 
257
275
  {field.type === "boolean" && (
258
- <CheckboxField client:load name={name} checked={Boolean(value)} disabled={readOnly} />
276
+ <div class="grid gap-1.5">
277
+ <CheckboxField
278
+ client:load
279
+ name={name}
280
+ checked={Boolean(value)}
281
+ disabled={readOnly}
282
+ label={label}
283
+ required={field.required}
284
+ />
285
+ {/* Indented to the label text: box (1rem) + gap (0.75rem). */}
286
+ {field.description && <p class="text-muted-foreground pl-7 text-xs leading-5">{field.description}</p>}
287
+ {field.admin?.help && <p class="text-muted-foreground pl-7 text-xs leading-5">{field.admin.help}</p>}
288
+ </div>
259
289
  )}
260
290
 
261
291
  {field.type === "select" && field.admin?.component !== "radio" && (
@@ -414,6 +444,7 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
414
444
  client:load
415
445
  name={name}
416
446
  value={serializedValue}
447
+ label={label}
417
448
  types={blockTypesMeta}
418
449
  linkOptions={linkableCollections}
419
450
  sharedSections={"shared" in field && field.shared === false ? [] : sharedSectionOptions}
@@ -0,0 +1,121 @@
1
+ "use client";
2
+
3
+ import { browserSupportsWebAuthn, startRegistration } from "@simplewebauthn/browser";
4
+ import { KeyRound, Trash2 } from "lucide-react";
5
+ import { useEffect, useState } from "react";
6
+
7
+ import { Button } from "./ui/button";
8
+
9
+ const AUTH_BASE = "/api/cms/auth";
10
+
11
+ type Passkey = { id: string; name: string | null; createdAt: string | null };
12
+
13
+ const reloadWith = (message: string) => {
14
+ const url = new URL(window.location.href);
15
+ url.search = new URLSearchParams({ _toast: "success", _msg: message }).toString();
16
+ window.location.assign(url.toString());
17
+ };
18
+
19
+ const deviceName = () => {
20
+ const ua = navigator.userAgent;
21
+ if (/iPhone|iPad/.test(ua)) return "iPhone or iPad";
22
+ if (/Android/.test(ua)) return "Android";
23
+ if (/Mac OS X/.test(ua)) return "Mac";
24
+ if (/Windows/.test(ua)) return "Windows";
25
+ return "Passkey";
26
+ };
27
+
28
+ export default function PasskeySettings({ passkeys, dateLocale }: { passkeys: Passkey[]; dateLocale?: string }) {
29
+ const [supported, setSupported] = useState(true);
30
+ const [busy, setBusy] = useState(false);
31
+ const [error, setError] = useState<string | null>(null);
32
+
33
+ useEffect(() => {
34
+ // eslint-disable-next-line react-hooks/set-state-in-effect
35
+ setSupported(browserSupportsWebAuthn());
36
+ }, []);
37
+
38
+ const add = async () => {
39
+ setBusy(true);
40
+ setError(null);
41
+ try {
42
+ const optionsResponse = await fetch(`${AUTH_BASE}/passkey/generate-register-options`, {
43
+ credentials: "same-origin",
44
+ });
45
+ if (optionsResponse.status === 403 || optionsResponse.status === 401) {
46
+ throw new Error("For security, sign out and back in before adding a passkey.");
47
+ }
48
+ if (!optionsResponse.ok) throw new Error("Couldn't start passkey setup.");
49
+ const attestation = await startRegistration({ optionsJSON: await optionsResponse.json() });
50
+ const verify = await fetch(`${AUTH_BASE}/passkey/verify-registration`, {
51
+ method: "POST",
52
+ credentials: "same-origin",
53
+ headers: { "Content-Type": "application/json" },
54
+ body: JSON.stringify({ response: attestation, name: deviceName() }),
55
+ });
56
+ if (!verify.ok) throw new Error("The passkey couldn't be saved. Try again.");
57
+ reloadWith("Passkey added.");
58
+ } catch (cause) {
59
+ if (!(cause instanceof Error && cause.name === "NotAllowedError")) {
60
+ setError(cause instanceof Error ? cause.message : "Something went wrong.");
61
+ }
62
+ setBusy(false);
63
+ }
64
+ };
65
+
66
+ const remove = async (id: string) => {
67
+ setBusy(true);
68
+ setError(null);
69
+ const response = await fetch(`${AUTH_BASE}/passkey/delete-passkey`, {
70
+ method: "POST",
71
+ credentials: "same-origin",
72
+ headers: { "Content-Type": "application/json" },
73
+ body: JSON.stringify({ id }),
74
+ });
75
+ if (response.ok) reloadWith("Passkey removed.");
76
+ else {
77
+ setError("The passkey couldn't be removed.");
78
+ setBusy(false);
79
+ }
80
+ };
81
+
82
+ return (
83
+ <div className="grid gap-3">
84
+ {passkeys.length > 0 && (
85
+ <ul className="divide-border divide-y rounded-md border">
86
+ {passkeys.map((passkey) => (
87
+ <li key={passkey.id} className="flex items-center gap-3 px-3 py-2 text-sm">
88
+ <KeyRound className="text-muted-foreground size-4 shrink-0" />
89
+ <span className="min-w-0 flex-1 truncate">{passkey.name ?? "Passkey"}</span>
90
+ {passkey.createdAt && (
91
+ <span className="text-muted-foreground text-xs">
92
+ Added {new Date(passkey.createdAt).toLocaleDateString(dateLocale)}
93
+ </span>
94
+ )}
95
+ <Button
96
+ type="button"
97
+ variant="ghost"
98
+ size="icon"
99
+ aria-label={`Remove ${passkey.name ?? "passkey"}`}
100
+ disabled={busy}
101
+ onClick={() => void remove(passkey.id)}
102
+ >
103
+ <Trash2 className="size-4" />
104
+ </Button>
105
+ </li>
106
+ ))}
107
+ </ul>
108
+ )}
109
+ {supported ? (
110
+ <div>
111
+ <Button type="button" variant={passkeys.length ? "outline" : "default"} disabled={busy} onClick={add}>
112
+ Add a passkey
113
+ </Button>
114
+ </div>
115
+ ) : (
116
+ <p className="text-muted-foreground text-sm">This browser doesn't support passkeys.</p>
117
+ )}
118
+ {error && <p className="text-destructive text-sm">{error}</p>}
119
+ </div>
120
+ );
121
+ }
@@ -0,0 +1,57 @@
1
+ "use client";
2
+
3
+ import { browserSupportsWebAuthn, startAuthentication } from "@simplewebauthn/browser";
4
+ import { KeyRound } from "lucide-react";
5
+ import { useEffect, useState } from "react";
6
+
7
+ import { Button } from "./ui/button";
8
+
9
+ const AUTH_BASE = "/api/cms/auth";
10
+
11
+ export default function PasskeySignIn() {
12
+ const [supported, setSupported] = useState(false);
13
+ const [busy, setBusy] = useState(false);
14
+ const [error, setError] = useState<string | null>(null);
15
+
16
+ useEffect(() => {
17
+ // eslint-disable-next-line react-hooks/set-state-in-effect
18
+ setSupported(browserSupportsWebAuthn());
19
+ }, []);
20
+
21
+ if (!supported) return null;
22
+
23
+ const signIn = async () => {
24
+ setBusy(true);
25
+ setError(null);
26
+ try {
27
+ const optionsResponse = await fetch(`${AUTH_BASE}/passkey/generate-authenticate-options`, {
28
+ credentials: "same-origin",
29
+ });
30
+ if (!optionsResponse.ok) throw new Error("options");
31
+ const assertion = await startAuthentication({ optionsJSON: await optionsResponse.json() });
32
+ const verify = await fetch(`${AUTH_BASE}/passkey/verify-authentication`, {
33
+ method: "POST",
34
+ credentials: "same-origin",
35
+ headers: { "Content-Type": "application/json" },
36
+ body: JSON.stringify({ response: assertion }),
37
+ });
38
+ if (!verify.ok) throw new Error("verify");
39
+ window.location.assign("/admin");
40
+ } catch (cause) {
41
+ // Closing the browser prompt is not an error worth shouting about.
42
+ if (cause instanceof Error && cause.name === "NotAllowedError") setError(null);
43
+ else setError("That passkey didn't work. Try again or use another sign-in method.");
44
+ setBusy(false);
45
+ }
46
+ };
47
+
48
+ return (
49
+ <div className="mt-4 grid gap-2">
50
+ <Button type="button" variant="outline" size="lg" className="w-full" disabled={busy} onClick={signIn}>
51
+ <KeyRound className="size-4" />
52
+ {busy ? "Waiting for passkey…" : "Sign in with a passkey"}
53
+ </Button>
54
+ {error && <p className="text-destructive text-sm">{error}</p>}
55
+ </div>
56
+ );
57
+ }
@@ -71,7 +71,7 @@ export default function SharedSectionBlockField({ name, value, types }: Props) {
71
71
  />
72
72
 
73
73
  {selectedType && Object.keys(fieldsMeta).length > 0 && (
74
- <div className="space-y-4 rounded-lg border px-4 py-4">
74
+ <div className="space-y-6 rounded-lg border px-4 py-5">
75
75
  {Object.entries(fieldsMeta).map(([fieldName, meta]) => (
76
76
  <SubField
77
77
  key={fieldName}