@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
@@ -180,7 +180,7 @@ const hasSidebarFields =
180
180
  effectiveSidebarFieldSets.some((set) =>
181
181
  set.fields.some((fieldName) => collection.fields[fieldName] && !isFieldHidden(fieldName)),
182
182
  ) ||
183
- (hasLocales && !translationMode);
183
+ (hasLocales && mode === "new");
184
184
  const hasSidebarMeta = reverseRefs.length > 0 || hasDocMeta;
185
185
 
186
186
  // Whether to render the right-hand sidebar column at all (avoids a stray sticky
@@ -236,7 +236,7 @@ const publishBlocked =
236
236
  >
237
237
  <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
238
238
  <div class="min-w-0 flex-1">
239
- <div class="flex items-center gap-2.5">
239
+ <div class="flex items-center gap-2.5" data-kide-refresh="title">
240
240
  <h1 class="truncate text-lg font-semibold tracking-tight md:text-xl">
241
241
  {mode === "new" && <LiveHeading client:load initial={`New ${collection.labels.singular}`} />}
242
242
  {
@@ -267,7 +267,7 @@ const publishBlocked =
267
267
 
268
268
  {
269
269
  formTab !== "submissions" && (
270
- <div class="flex flex-wrap items-center gap-2 sm:flex-shrink-0 sm:justify-end">
270
+ <div class="flex flex-wrap items-center gap-2 sm:flex-shrink-0 sm:justify-end" data-kide-refresh="actions">
271
271
  {hasPreview && previewUrl && !translationMode && (
272
272
  <>
273
273
  <a href={previewUrl} target="_blank" class={buttonVariants({ variant: "outline" })}>
@@ -279,28 +279,32 @@ const publishBlocked =
279
279
  )}
280
280
  {hasLocales && mode === "edit" && (
281
281
  <>
282
- {locales.map((locale) => (
283
- <a
284
- href={`/admin/${collection.slug}/${documentId}?locale=${locale}`}
285
- title={
286
- locale === baseLocale
287
- ? "Content language"
288
- : availableLocales.has(locale)
289
- ? undefined
290
- : "Not translated yet"
291
- }
292
- class:list={[
293
- buttonVariants({ variant: "outline", size: "sm" }),
294
- selectedLocale === locale
295
- ? "border-primary/50 bg-background ring-ring/30 font-medium ring-2"
296
- : availableLocales.has(locale)
297
- ? "text-muted-foreground"
298
- : "text-muted-foreground/50 border-dashed",
299
- ]}
300
- >
301
- {locale.toUpperCase()}
302
- </a>
303
- ))}
282
+ {/* One segmented control: the language being edited is the raised segment. */}
283
+ <div class="bg-muted inline-flex h-8 items-center gap-0.5 rounded-lg border p-0.5">
284
+ {locales.map((locale) => (
285
+ <a
286
+ href={`/admin/${collection.slug}/${documentId}?locale=${locale}`}
287
+ title={
288
+ locale === baseLocale
289
+ ? "Original language"
290
+ : availableLocales.has(locale)
291
+ ? undefined
292
+ : "Not translated yet"
293
+ }
294
+ aria-current={selectedLocale === locale ? "page" : undefined}
295
+ class:list={[
296
+ "inline-flex h-full min-w-9 items-center justify-center rounded-md px-2.5 text-xs font-medium transition-colors",
297
+ selectedLocale === locale
298
+ ? "bg-background text-foreground shadow-sm"
299
+ : availableLocales.has(locale)
300
+ ? "text-muted-foreground hover:text-foreground"
301
+ : "text-muted-foreground/50 hover:text-muted-foreground",
302
+ ]}
303
+ >
304
+ {locale.toUpperCase()}
305
+ </a>
306
+ ))}
307
+ </div>
304
308
  <div class="bg-border mx-1 h-6 w-px" />
305
309
  </>
306
310
  )}
@@ -387,6 +391,14 @@ const publishBlocked =
387
391
  currentPublishAt={doc?._publishAt ? String(doc._publishAt) : undefined}
388
392
  currentUnpublishAt={doc?._unpublishAt ? String(doc._unpublishAt) : undefined}
389
393
  versions={versions}
394
+ languages={
395
+ // Only while the document exists in one language: a translation would
396
+ // collide with the new original language, so the API refuses the change.
397
+ hasLocales && availableLocales.size === 1
398
+ ? locales.map((locale) => ({ value: locale, label: locale.toUpperCase() }))
399
+ : undefined
400
+ }
401
+ contentLanguage={baseLocale}
390
402
  restoreEndpoint={getFormAction(collection.slug, documentId)}
391
403
  redirectTo={Astro.url.pathname + Astro.url.search}
392
404
  />
@@ -408,7 +420,7 @@ const publishBlocked =
408
420
  }
409
421
  {
410
422
  showCollab && collabData && documentId && (
411
- <div class="-mt-6 mb-8 2xl:-mx-8">
423
+ <div class="-mt-6 mb-8 2xl:-mx-8" data-kide-refresh="collab">
412
424
  <CollaborationReviewBar
413
425
  client:load
414
426
  collection={collection.slug}
@@ -430,17 +442,35 @@ const publishBlocked =
430
442
  {mode === "edit" && documentId && (
431
443
  <DocumentLock client:load collection={collection.slug} documentId={documentId} />
432
444
  )}
433
- <UnsavedGuard
434
- client:load
435
- formId={translationMode ? "translation-form" : "document-form"}
436
- isNew={mode === "new"}
437
- isDraft={Boolean(
438
- !translationMode &&
439
- collection.drafts &&
440
- (doc?._status === "draft" || doc?._status === "scheduled" || (doc && getVisualStatus(doc) === "changed")),
441
- )}
442
- />
445
+ <div class="contents" data-kide-refresh="guard">
446
+ <UnsavedGuard
447
+ client:load
448
+ formId={translationMode ? "translation-form" : "document-form"}
449
+ isNew={mode === "new"}
450
+ isDraft={Boolean(
451
+ !translationMode &&
452
+ collection.drafts &&
453
+ (doc?._status === "draft" ||
454
+ doc?._status === "scheduled" ||
455
+ (doc && getVisualStatus(doc) === "changed")),
456
+ )}
457
+ />
458
+ </div>
443
459
  <div id="document-edit-area" data-preview-channel={!translationMode ? previewKey : undefined}>
460
+ {collection.slug === "users" && mode === "edit" && Astro.url.searchParams.get("signInInvite") && (
461
+ <AdminCard
462
+ title={Astro.url.searchParams.get("emailSent") === "true" ? "Invitation sent" : "Sign-in link"}
463
+ >
464
+ <p class="text-muted-foreground text-sm">
465
+ {Astro.url.searchParams.get("emailSent") === "true"
466
+ ? "An invitation email has been sent. They sign in with single sign-on here:"
467
+ : "Email is not configured. Share this link — they sign in with single sign-on:"}
468
+ </p>
469
+ <code class="bg-muted mt-2 block rounded-md px-3 py-2 text-sm break-all select-all">
470
+ {Astro.url.origin}/admin/login
471
+ </code>
472
+ </AdminCard>
473
+ )}
444
474
  {collection.slug === "users" && mode === "edit" && Astro.url.searchParams.get("inviteToken") && (
445
475
  <AdminCard title={Astro.url.searchParams.get("emailSent") === "true" ? "Invitation sent" : "Invite link"}>
446
476
  {Astro.url.searchParams.get("emailSent") === "true" ? (
@@ -615,10 +645,13 @@ const publishBlocked =
615
645
  );
616
646
  return variant === "record" ? <AdminCard title="Settings">{fields}</AdminCard> : fields;
617
647
  })}
618
- {hasLocales && !translationMode && !isSubmissionView && (
648
+ {/* The language is chosen when the document is created; afterwards the
649
+ top switcher is the one language control (changing it later lives
650
+ in the ⋯ menu, offered only while no translation exists). */}
651
+ {hasLocales && mode === "new" && !isSubmissionView && (
619
652
  <div class="grid gap-1.5">
620
653
  <label for="_sourceLocale" class="text-foreground/80 text-sm leading-none font-medium">
621
- Content language
654
+ Language
622
655
  </label>
623
656
  <SelectField
624
657
  client:load
@@ -627,11 +660,14 @@ const publishBlocked =
627
660
  placeholder="Select a language"
628
661
  items={locales.map((locale) => ({ value: locale, label: locale.toUpperCase() }))}
629
662
  />
630
- <p class="text-muted-foreground text-xs">The language this document is written in.</p>
663
+ <p class="text-muted-foreground text-xs">
664
+ The language this document is written in. Translations can be added after saving.
665
+ </p>
631
666
  </div>
632
667
  )}
633
668
  {hasSidebarMeta && (
634
669
  <div
670
+ data-kide-refresh="meta"
635
671
  class:list={[
636
672
  variant === "record" ? "space-y-6" : "grid gap-6",
637
673
  variant !== "record" && hasSidebarFields && "border-t pt-6",
@@ -42,6 +42,35 @@ const locales = config.locales?.supported ?? [];
42
42
  // and this collection actually has translatable fields to show per-locale.
43
43
  const showLocalesColumn = locales.length > 1 && getTranslatableFieldNames(collection).length > 0;
44
44
 
45
+ // Language filter (?lang=en → documents that exist in English, shown in English;
46
+ // ?lang=missing:en → documents not translated to English yet). Only offered when
47
+ // the collection is actually multilingual.
48
+ const langParam = showLocalesColumn ? (Astro.url.searchParams.get("lang") ?? "") : "";
49
+ const missingLocale = langParam.startsWith("missing:") ? langParam.slice("missing:".length) : "";
50
+ const langFilter = locales.includes(langParam)
51
+ ? { locale: langParam, availability: "exact" as const }
52
+ : locales.includes(missingLocale)
53
+ ? { locale: missingLocale, availability: "missing" as const }
54
+ : null;
55
+ const langHref = (value: string) => {
56
+ const url = new URL(Astro.url);
57
+ if (value) url.searchParams.set("lang", value);
58
+ else url.searchParams.delete("lang");
59
+ url.searchParams.delete("page");
60
+ return url.pathname + url.search;
61
+ };
62
+ // "fi" → "Finnish" (the admin UI is English); unknown codes fall back to the code.
63
+ const languageNames = new Intl.DisplayNames(["en"], { type: "language", fallback: "code" });
64
+ const languageName = (locale: string) => languageNames.of(locale) ?? locale.toUpperCase();
65
+ const langOptions = [
66
+ { value: "", label: "All languages" },
67
+ ...locales.map((locale) => ({ value: locale, label: `In ${languageName(locale)}` })),
68
+ ...locales
69
+ .filter((locale) => locale !== defaultLocale)
70
+ .map((locale) => ({ value: `missing:${locale}`, label: `Missing ${languageName(locale)}` })),
71
+ ].map((option) => ({ ...option, href: langHref(option.value) }));
72
+ const activeLang = langFilter ? langParam : "";
73
+
45
74
  const viewConfig = collection.views ?? {};
46
75
  const defaultSort = viewConfig.list?.defaultSort ?? { field: "_updatedAt", direction: "desc" };
47
76
  const sortParam = Astro.url.searchParams.get("sort");
@@ -58,7 +87,8 @@ const [docs, totalDocs] = await Promise.all([
58
87
  collectionApi.find(
59
88
  {
60
89
  status: "any",
61
- locale: defaultLocale,
90
+ locale: langFilter?.locale ?? defaultLocale,
91
+ availability: langFilter?.availability,
62
92
  sort: currentSort,
63
93
  limit: PAGE_SIZE,
64
94
  offset,
@@ -66,7 +96,15 @@ const [docs, totalDocs] = await Promise.all([
66
96
  },
67
97
  runtimeContext,
68
98
  ),
69
- collectionApi.count({ status: "any", locale: defaultLocale, search: searchParam || undefined }, runtimeContext),
99
+ collectionApi.count(
100
+ {
101
+ status: "any",
102
+ locale: langFilter?.locale ?? defaultLocale,
103
+ availability: langFilter?.availability,
104
+ search: searchParam || undefined,
105
+ },
106
+ runtimeContext,
107
+ ),
70
108
  ]);
71
109
  const totalPages = Math.max(1, Math.ceil(totalDocs / PAGE_SIZE));
72
110
 
@@ -169,7 +207,8 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
169
207
  const pagePath = getPagePath(entry);
170
208
  return {
171
209
  id: String(entry._id),
172
- editHref: `/admin/${collection.slug}/${entry._id}`,
210
+ // Filtered by a language: open that language's tab (for "Missing …", the translation form).
211
+ editHref: `/admin/${collection.slug}/${entry._id}${langFilter ? `?locale=${langFilter.locale}` : ""}`,
173
212
  status: getVisualStatus(entry),
174
213
  locales: Array.isArray(entry._availableLocales) ? entry._availableLocales.map((l) => String(l)) : [defaultLocale],
175
214
  searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
@@ -212,6 +251,7 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
212
251
  }))}
213
252
  data={tableRows}
214
253
  searchPlaceholder={`Filter ${collection.labels.plural.toLowerCase()}...`}
254
+ languageFilter={showLocalesColumn ? { active: activeLang, options: langOptions } : undefined}
215
255
  serverPagination={{
216
256
  totalDocs,
217
257
  totalPages,
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  // Client-side glue for the edit form: conditional field visibility, autofocus on new,
3
- // AJAX form submit (so validation errors surface as toasts without losing form state),
3
+ // AJAX form submit (validation errors surface as toasts, and a successful save updates
4
+ // the page in place instead of reloading it),
4
5
  // and collapsible field-group state persistence.
5
6
  ---
6
7
 
@@ -167,6 +168,68 @@
167
168
  return false;
168
169
  }
169
170
 
171
+ // Values a field shows after saving, as the server rendered them. JSON-backed fields
172
+ // (blocks, rich text, relations) are skipped — their serialization isn't stable
173
+ // across renders, and the server doesn't rewrite them.
174
+ function plainValues(form) {
175
+ var out = {};
176
+ new FormData(form).forEach(function (value, name) {
177
+ if (name.charAt(0) === "_" || name === "redirectTo" || typeof value !== "string") return;
178
+ var trimmed = value.trim();
179
+ if (trimmed.charAt(0) === "{" || trimmed.charAt(0) === "[") return;
180
+ out[name] = (out[name] ? out[name] + "\u0000" : "") + value;
181
+ });
182
+ return out;
183
+ }
184
+
185
+ // Replaces the [data-kide-refresh] regions (title + status, header actions, review
186
+ // bar, unsaved-changes guard, sidebar info) with the freshly rendered ones and shows
187
+ // the response's toast. Returns false — so the caller reloads instead — when the
188
+ // server changed a field value (e.g. a hook rewrote the slug) or the page structure.
189
+ function swapInPlace(form, html) {
190
+ var next = new DOMParser().parseFromString(html, "text/html");
191
+ var nextForm = next.getElementById("document-form");
192
+ if (!nextForm) return false;
193
+
194
+ var mine = plainValues(form);
195
+ var theirs = plainValues(nextForm);
196
+ for (var name in theirs) {
197
+ if (name in mine && mine[name] !== theirs[name]) return false;
198
+ }
199
+
200
+ var regions = document.querySelectorAll("[data-kide-refresh]");
201
+ var nextRegions = next.querySelectorAll("[data-kide-refresh]");
202
+ if (regions.length !== nextRegions.length) return false;
203
+ var byName = {};
204
+ nextRegions.forEach(function (el) {
205
+ byName[el.getAttribute("data-kide-refresh")] = el;
206
+ });
207
+ for (var i = 0; i < regions.length; i++) {
208
+ if (!byName[regions[i].getAttribute("data-kide-refresh")]) return false;
209
+ }
210
+
211
+ regions.forEach(function (el) {
212
+ // Unmount the React islands first so their listeners (e.g. the unsaved-changes
213
+ // guard) go away; the imported islands hydrate themselves when connected.
214
+ el.querySelectorAll("astro-island").forEach(function (island) {
215
+ island.dispatchEvent(new CustomEvent("astro:unmount"));
216
+ });
217
+ el.replaceWith(document.importNode(byName[el.getAttribute("data-kide-refresh")], true));
218
+ });
219
+
220
+ var toast = next.getElementById("admin-toast");
221
+ if (toast && toast.parentElement) {
222
+ var current = document.getElementById("admin-toast");
223
+ if (current && current.parentElement) current.parentElement.remove();
224
+ var wrapper = document.importNode(toast.parentElement, true);
225
+ document.body.appendChild(wrapper);
226
+ setTimeout(function () {
227
+ wrapper.remove();
228
+ }, 3200);
229
+ }
230
+ return true;
231
+ }
232
+
170
233
  (function () {
171
234
  var form = document.getElementById("document-form");
172
235
  if (!form) return;
@@ -212,7 +275,30 @@
212
275
  return;
213
276
  }
214
277
  }
215
- window.location.assign(res.url);
278
+ // Saving an existing document keeps the page: only the parts a save can change are
279
+ // swapped in from the response, so open blocks, scroll, focus and undo survive.
280
+ var intent = sub && sub.name === "_intent" ? sub.value : "";
281
+ var inPlace =
282
+ u.searchParams.get("_toast") === "success" &&
283
+ u.pathname === location.pathname &&
284
+ f.querySelector('input[name="_action"]').value === "update" &&
285
+ (intent === "save" || intent === "publish");
286
+ if (!inPlace) {
287
+ window.location.assign(res.url);
288
+ return;
289
+ }
290
+ return res.text().then(function (html) {
291
+ var swapped = false;
292
+ try {
293
+ // The swapped-in unsaved-changes guard measures "dirty" against what was saved.
294
+ window.__kideSubmittedForm = fd;
295
+ swapped = swapInPlace(f, html);
296
+ } catch (err) {
297
+ // Never let a swap bug reach .catch below — that re-submits (saves twice).
298
+ console.error("[kide] in-place save update failed; reloading", err);
299
+ }
300
+ if (!swapped) window.location.assign(res.url);
301
+ });
216
302
  })
217
303
  .catch(function () {
218
304
  f.submit();
package/core/api.ts CHANGED
@@ -6,6 +6,13 @@ import { setUsageConfig } from "./asset-usage";
6
6
  import { removeCollaborationFor } from "./collaboration";
7
7
  import { recordAudit, type AuditActor } from "./audit";
8
8
  import { hashPassword, MIN_PASSWORD_LENGTH } from "./auth";
9
+ import {
10
+ AUTH_USERS_COLLECTION,
11
+ deleteUserAuthData,
12
+ registerAuthConfig,
13
+ revokeUserSessions,
14
+ setCredentialPassword,
15
+ } from "./auth-engine";
9
16
  import type { CMSConfig, CollectionConfig, FieldConfig, RichTextDocument } from "./define";
10
17
  import { getCollectionMap, getTranslatableFieldNames, isStructuralField } from "./define";
11
18
  import { getDb, trackTask } from "./runtime";
@@ -29,9 +36,11 @@ export type FindOptions = {
29
36
  * With `locale`: `"fallback"` (default) returns every document, overlaying the
30
37
  * translation when one exists; `"exact"` returns only documents that exist in
31
38
  * that locale — their source locale, or a translation row. Use `"exact"` for
32
- * listings and `"fallback"` for single-document routes.
39
+ * listings and `"fallback"` for single-document routes. `"missing"` is the
40
+ * complement of `"exact"`: documents that don't exist in that locale yet
41
+ * (e.g. a translation to-do list).
33
42
  */
34
- availability?: "fallback" | "exact";
43
+ availability?: "fallback" | "exact" | "missing";
35
44
  search?: string;
36
45
  };
37
46
 
@@ -424,6 +433,22 @@ const getTableRefs = async (collectionSlug: string) => {
424
433
  return tables;
425
434
  };
426
435
 
436
+ const isAdminAuthCollection = (collection: CollectionConfig) =>
437
+ !!collection.auth && collection.slug === AUTH_USERS_COLLECTION;
438
+
439
+ /**
440
+ * Passwords live in Better Auth's credential accounts, never on the users row (or its
441
+ * versions); emails are stored lowercased because that's how sign-in looks them up.
442
+ */
443
+ const takeCredentialHash = (collection: CollectionConfig, input: Record<string, unknown>) => {
444
+ if (!isAdminAuthCollection(collection)) return null;
445
+ if (typeof input.email === "string") input.email = input.email.trim().toLowerCase();
446
+ if (!("password" in input)) return null;
447
+ const value = input.password;
448
+ delete input.password;
449
+ return typeof value === "string" && value ? value : null;
450
+ };
451
+
427
452
  /**
428
453
  * A validation failure that knows which field caused it, so the admin can point at
429
454
  * the offending input instead of showing a toast and leaving the editor to hunt.
@@ -440,6 +465,7 @@ export const createCms = (config: CMSConfig) => {
440
465
  '"my.task": () => import("@/lib/handler").then((mod) => mod.run()).',
441
466
  );
442
467
  }
468
+ registerAuthConfig(config);
443
469
  const collectionMap = getCollectionMap(config);
444
470
 
445
471
  // Lets assets.delete() check whether a file is still referenced without every
@@ -473,11 +499,17 @@ export const createCms = (config: CMSConfig) => {
473
499
  if (!supportedLocales.includes(locale)) throw new Error(`Locale "${locale}" is not in locales.supported.`);
474
500
  return locale;
475
501
  };
476
- /** `availability: "exact"` — the document must exist in the requested locale. */
502
+ /**
503
+ * `availability: "exact"` — the document must exist in the requested locale;
504
+ * `"missing"` — it must not (neither its source locale nor a translation).
505
+ */
477
506
  const availabilityCondition = (tables: any, options: { locale?: string; availability?: string }) => {
478
- if (!options.locale || options.availability !== "exact" || !tables.translations || !config.locales) return null;
507
+ const { availability } = options;
508
+ if (!options.locale || (availability !== "exact" && availability !== "missing")) return null;
509
+ if (!tables.translations || !config.locales) return null;
479
510
  const tr = tables.translations;
480
- return sql`(${tables.main._sourceLocale} = ${options.locale} OR EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale}))`;
511
+ const exists = sql`(${tables.main._sourceLocale} = ${options.locale} OR EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale}))`;
512
+ return availability === "exact" ? exists : sql`NOT ${exists}`;
481
513
  };
482
514
 
483
515
  const overlayLocale = (
@@ -772,6 +804,7 @@ export const createCms = (config: CMSConfig) => {
772
804
  const transformedInput = collection.hooks?.beforeCreate
773
805
  ? await collection.hooks.beforeCreate(preparedInput, hookContext)
774
806
  : preparedInput;
807
+ const credentialHash = takeCredentialHash(collection, transformedInput);
775
808
 
776
809
  const createdAt = now();
777
810
  const docId = typeof data._id === "string" ? String(data._id) : nanoid();
@@ -779,6 +812,8 @@ export const createCms = (config: CMSConfig) => {
779
812
  _id: docId,
780
813
  ...serializeForDb(collection, transformedInput),
781
814
  };
815
+ // Admin-created accounts: an admin vouched for the address, so SSO may link to it.
816
+ if (isAdminAuthCollection(collection) && tables.main._authEmailVerified) docValues._authEmailVerified = true;
782
817
 
783
818
  if (collection.drafts) {
784
819
  const status = data._status === "published" ? "published" : getDefaultStatus(collection);
@@ -792,6 +827,7 @@ export const createCms = (config: CMSConfig) => {
792
827
  }
793
828
 
794
829
  await db.insert(tables.main).values(docValues);
830
+ if (credentialHash) await setCredentialPassword(docId, credentialHash);
795
831
 
796
832
  if (collection.versions && tables.versions) {
797
833
  await db.insert(tables.versions).values({
@@ -870,6 +906,7 @@ export const createCms = (config: CMSConfig) => {
870
906
  const transformedInput = collection.hooks?.beforeUpdate
871
907
  ? await collection.hooks.beforeUpdate(preparedInput, existing, hookContext)
872
908
  : preparedInput;
909
+ const credentialHash = takeCredentialHash(collection, transformedInput);
873
910
 
874
911
  if (collection.drafts && existing._status === "published" && !(existingRows[0] as any)._published) {
875
912
  const snapshot: Record<string, unknown> = {};
@@ -923,6 +960,10 @@ export const createCms = (config: CMSConfig) => {
923
960
  } else {
924
961
  await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
925
962
  }
963
+ if (credentialHash) {
964
+ await setCredentialPassword(id, credentialHash);
965
+ await revokeUserSessions(id);
966
+ }
926
967
 
927
968
  if (collection.versions && tables.versions) {
928
969
  const versionRows = await db
@@ -990,6 +1031,7 @@ export const createCms = (config: CMSConfig) => {
990
1031
  }
991
1032
  if (tables.translations) await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
992
1033
  if (tables.versions) await db.delete(tables.versions).where(eq(tables.versions._docId, id));
1034
+ if (isAdminAuthCollection(collection)) await deleteUserAuthData(id);
993
1035
  // Collaboration rows outlive their document otherwise, and an orphaned
994
1036
  // review row still counts towards the "Needs you" badge.
995
1037
  await removeCollaborationFor(slug, id);
@@ -1073,6 +1115,7 @@ export const createCms = (config: CMSConfig) => {
1073
1115
  for (const id of deletedIds) {
1074
1116
  if (tables.translations) await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
1075
1117
  if (tables.versions) await db.delete(tables.versions).where(eq(tables.versions._docId, id));
1118
+ if (isAdminAuthCollection(collection)) await deleteUserAuthData(id);
1076
1119
  }
1077
1120
  } else {
1078
1121
  const CHUNK = 200; // stay well under SQLite's bound-variable limit
@@ -1082,6 +1125,7 @@ export const createCms = (config: CMSConfig) => {
1082
1125
  await db.delete(tables.translations).where(inArray(tables.translations._entityId, chunk));
1083
1126
  if (tables.versions) await db.delete(tables.versions).where(inArray(tables.versions._docId, chunk));
1084
1127
  await db.delete(tables.main).where(inArray(tables.main._id, chunk));
1128
+ if (isAdminAuthCollection(collection)) for (const id of chunk) await deleteUserAuthData(id);
1085
1129
  }
1086
1130
  deletedIds = ids;
1087
1131
  }
@@ -1,44 +1,86 @@
1
1
  import type { AdminAuthConfig, AdminAuthSsoProviderConfig, CMSConfig } from "./define";
2
2
 
3
3
  export type ResolvedAdminAuthConfig = {
4
- provider: "local" | "better-auth" | "workos" | "custom";
4
+ provider: "local" | "custom";
5
5
  password: {
6
6
  enabled: boolean;
7
7
  forgotPassword: boolean;
8
- emailVerification: boolean;
9
8
  };
10
9
  mfa: {
11
10
  totp: boolean;
12
- backupCodes: boolean;
13
11
  passkeys: boolean;
12
+ require: boolean | string[];
14
13
  };
15
14
  ssoProviders: AdminAuthSsoProviderConfig[];
15
+ ssoVerifyEveryMinutes: number;
16
+ sessionDays: number;
16
17
  };
17
18
 
18
19
  export const customAuth = (provider: Extract<NonNullable<AdminAuthConfig["provider"]>, { kind: "custom" }>) => provider;
19
20
 
21
+ const SSO_ID = /^[a-z0-9][a-z0-9-]*$/;
22
+ const TENANT_GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
+
20
24
  export const resolveAdminAuth = (config: CMSConfig): ResolvedAdminAuthConfig => {
21
25
  const auth = config.admin?.auth;
22
- const providerConfig = auth?.provider;
23
- const provider = typeof providerConfig === "object" ? "custom" : (providerConfig ?? "local");
24
- const passwordEnabled = auth?.password?.enabled ?? provider !== "workos";
25
- const forgotPassword = auth?.password?.forgotPassword ?? (provider === "local" || provider === "better-auth");
26
+ const provider = typeof auth?.provider === "object" ? "custom" : "local";
27
+ const passwordEnabled = auth?.password?.enabled ?? true;
28
+ const ssoProviders = auth?.sso?.providers ?? [];
29
+
30
+ for (const sso of ssoProviders) {
31
+ if (!SSO_ID.test(sso.id)) {
32
+ throw new Error(`[kide] SSO provider id "${sso.id}" must be lowercase letters, digits and dashes.`);
33
+ }
34
+ if (sso.type === "microsoft" && !TENANT_GUID.test(sso.tenantId)) {
35
+ throw new Error(
36
+ `[kide] SSO provider "${sso.id}": tenantId must be the directory (tenant) GUID — ` +
37
+ "multi-tenant endpoints (common/organizations) can't vouch for email addresses.",
38
+ );
39
+ }
40
+ if (sso.provisioning === "jit" && !sso.allowedDomains?.length) {
41
+ throw new Error(`[kide] SSO provider "${sso.id}" uses jit provisioning, which requires allowedDomains.`);
42
+ }
43
+ }
44
+ if (new Set(ssoProviders.map((sso) => sso.id)).size !== ssoProviders.length) {
45
+ throw new Error("[kide] SSO provider ids must be unique.");
46
+ }
26
47
 
27
48
  return {
28
49
  provider,
29
50
  password: {
30
51
  enabled: passwordEnabled,
31
- forgotPassword: passwordEnabled && forgotPassword,
32
- emailVerification: auth?.password?.emailVerification ?? false,
52
+ forgotPassword: passwordEnabled && (auth?.password?.forgotPassword ?? true),
33
53
  },
34
54
  mfa: {
35
55
  totp: auth?.mfa?.totp ?? false,
36
- backupCodes: auth?.mfa?.backupCodes ?? false,
37
56
  passkeys: auth?.mfa?.passkeys ?? false,
57
+ require: auth?.mfa?.require ?? false,
38
58
  },
39
- ssoProviders: auth?.sso?.providers ?? [],
59
+ ssoProviders,
60
+ ssoVerifyEveryMinutes: Math.max(5, auth?.sso?.verifyEveryMinutes ?? 60),
61
+ sessionDays: auth?.sessionDays ?? 30,
40
62
  };
41
63
  };
42
64
 
43
65
  export const getSsoProvider = (config: CMSConfig, providerId: string) =>
44
66
  resolveAdminAuth(config).ssoProviders.find((provider) => provider.id === providerId) ?? null;
67
+
68
+ /** Whether MFA enrollment is mandatory for a user with this role. */
69
+ export const mfaRequiredFor = (auth: ResolvedAdminAuthConfig, role: string) =>
70
+ auth.mfa.totp && (auth.mfa.require === true || (Array.isArray(auth.mfa.require) && auth.mfa.require.includes(role)));
71
+
72
+ const emailDomain = (email: string) => email.split("@")[1]?.trim().toLowerCase() ?? "";
73
+
74
+ /** SSO providers a user's email domain is bound to (`allowedDomains` + `enforce`). */
75
+ export const enforcedSsoProviders = (auth: ResolvedAdminAuthConfig, email: string) => {
76
+ const domain = emailDomain(email);
77
+ if (!domain) return [];
78
+ return auth.ssoProviders.filter(
79
+ (provider) =>
80
+ provider.enforce !== false && (provider.allowedDomains ?? []).some((allowed) => allowed.toLowerCase() === domain),
81
+ );
82
+ };
83
+
84
+ /** The provider a domain-bound user should be sent to, if any. */
85
+ export const enforcedSsoProvider = (auth: ResolvedAdminAuthConfig, email: string) =>
86
+ enforcedSsoProviders(auth, email)[0] ?? null;