@kidecms/core 0.30.1 → 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.
@@ -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
+ }
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { ChevronsUpDown, LogOut, Monitor, Moon, Sun } from "lucide-react";
3
+ import { ChevronsUpDown, LogOut, Monitor, Moon, Sun, UserRound } from "lucide-react";
4
4
  import { useEffect, useState } from "react";
5
5
 
6
6
  import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from "./ui/dropdown-menu";
@@ -18,10 +18,12 @@ export default function SidebarUserMenu({
18
18
  userName,
19
19
  userEmail,
20
20
  logoutAction,
21
+ accountHref = "/admin/account",
21
22
  }: {
22
23
  userName: string;
23
24
  userEmail: string;
24
25
  logoutAction: string;
26
+ accountHref?: string;
25
27
  }) {
26
28
  const [theme, setTheme] = useState<Theme>("system");
27
29
 
@@ -81,6 +83,10 @@ export default function SidebarUserMenu({
81
83
 
82
84
  <DropdownMenuSeparator />
83
85
 
86
+ <DropdownMenuItem onClick={() => window.location.assign(accountHref)}>
87
+ <UserRound className="text-muted-foreground size-3.5" />
88
+ Account &amp; security
89
+ </DropdownMenuItem>
84
90
  <DropdownMenuItem
85
91
  onClick={() => {
86
92
  const form = document.createElement("form");
@@ -0,0 +1,206 @@
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import { renderSVG } from "uqr";
5
+
6
+ import { Button } from "./ui/button";
7
+ import { Input } from "./ui/input";
8
+ import { Label } from "./ui/label";
9
+
10
+ const AUTH_BASE = "/api/cms/auth";
11
+
12
+ type Step =
13
+ | { kind: "idle" }
14
+ | { kind: "password"; intent: "enable" | "disable" | "codes" }
15
+ | { kind: "scan"; totpURI: string; backupCodes: string[] }
16
+ | { kind: "codes"; backupCodes: string[] };
17
+
18
+ const post = async (path: string, body: Record<string, unknown>) => {
19
+ const response = await fetch(`${AUTH_BASE}${path}`, {
20
+ method: "POST",
21
+ credentials: "same-origin",
22
+ headers: { "Content-Type": "application/json" },
23
+ body: JSON.stringify(body),
24
+ });
25
+ const data = await response.json().catch(() => ({}));
26
+ if (!response.ok) throw new Error(data?.message ?? data?.error ?? "Request failed");
27
+ return data;
28
+ };
29
+
30
+ const reloadWith = (message: string) => {
31
+ const url = new URL(window.location.href);
32
+ url.search = new URLSearchParams({ _toast: "success", _msg: message }).toString();
33
+ window.location.assign(url.toString());
34
+ };
35
+
36
+ function BackupCodes({ codes }: { codes: string[] }) {
37
+ return (
38
+ <div className="grid gap-2">
39
+ <p className="text-muted-foreground text-sm">
40
+ Save these backup codes somewhere safe. Each one signs you in once if you lose your authenticator.
41
+ </p>
42
+ <pre className="bg-muted rounded-md px-3 py-2 font-mono text-sm leading-6 select-all">{codes.join("\n")}</pre>
43
+ </div>
44
+ );
45
+ }
46
+
47
+ export default function TwoFactorSettings({ enabled, required }: { enabled: boolean; required: boolean }) {
48
+ const [step, setStep] = useState<Step>(
49
+ required && !enabled ? { kind: "password", intent: "enable" } : { kind: "idle" },
50
+ );
51
+ const [password, setPassword] = useState("");
52
+ const [code, setCode] = useState("");
53
+ const [busy, setBusy] = useState(false);
54
+ const [error, setError] = useState<string | null>(null);
55
+
56
+ const run = async (task: () => Promise<void>) => {
57
+ setBusy(true);
58
+ setError(null);
59
+ try {
60
+ await task();
61
+ } catch (cause) {
62
+ setError(cause instanceof Error ? cause.message : "Something went wrong.");
63
+ } finally {
64
+ setBusy(false);
65
+ }
66
+ };
67
+
68
+ const submitPassword = (intent: "enable" | "disable" | "codes") =>
69
+ run(async () => {
70
+ if (intent === "enable") {
71
+ const data = await post("/two-factor/enable", { password });
72
+ setStep({ kind: "scan", totpURI: data.totpURI, backupCodes: data.backupCodes ?? [] });
73
+ } else if (intent === "disable") {
74
+ await post("/two-factor/disable", { password });
75
+ reloadWith("Two-factor authentication turned off.");
76
+ } else {
77
+ const data = await post("/two-factor/generate-backup-codes", { password });
78
+ setStep({ kind: "codes", backupCodes: data.backupCodes ?? [] });
79
+ }
80
+ setPassword("");
81
+ });
82
+
83
+ const confirmCode = () =>
84
+ run(async () => {
85
+ await post("/two-factor/verify-totp", { code: code.replace(/\s+/g, "") });
86
+ reloadWith("Two-factor authentication is on.");
87
+ });
88
+
89
+ if (step.kind === "password") {
90
+ const label = step.intent === "enable" ? "Continue" : step.intent === "disable" ? "Turn off" : "Generate new codes";
91
+ return (
92
+ <form
93
+ className="grid max-w-sm gap-3"
94
+ onSubmit={(event) => {
95
+ event.preventDefault();
96
+ void submitPassword(step.intent);
97
+ }}
98
+ >
99
+ <div className="grid gap-2">
100
+ <Label htmlFor="tf-password">Confirm your password</Label>
101
+ <Input
102
+ id="tf-password"
103
+ type="password"
104
+ autoComplete="current-password"
105
+ value={password}
106
+ onChange={(event) => setPassword(event.target.value)}
107
+ required
108
+ autoFocus
109
+ />
110
+ </div>
111
+ {error && <p className="text-destructive text-sm">{error}</p>}
112
+ <div className="flex gap-2">
113
+ <Button type="submit" disabled={busy}>
114
+ {label}
115
+ </Button>
116
+ {!(required && !enabled) && (
117
+ <Button type="button" variant="ghost" onClick={() => setStep({ kind: "idle" })}>
118
+ Cancel
119
+ </Button>
120
+ )}
121
+ </div>
122
+ </form>
123
+ );
124
+ }
125
+
126
+ if (step.kind === "scan") {
127
+ const secret = new URL(step.totpURI).searchParams.get("secret") ?? "";
128
+ return (
129
+ <div className="grid gap-5">
130
+ <div className="grid gap-3 sm:grid-cols-[auto_1fr] sm:items-start">
131
+ <div
132
+ className="size-44 rounded-md bg-white p-2 [&_svg]:size-full"
133
+ // uqr renders an SVG string from the otpauth URI the server returned.
134
+ dangerouslySetInnerHTML={{ __html: renderSVG(step.totpURI) }}
135
+ />
136
+ <div className="grid gap-2 text-sm">
137
+ <p>Scan the code with an authenticator app (1Password, Google Authenticator, Microsoft Authenticator…).</p>
138
+ <p className="text-muted-foreground">Can't scan? Enter this key:</p>
139
+ <code className="bg-muted rounded-md px-2 py-1 font-mono text-xs break-all select-all">{secret}</code>
140
+ </div>
141
+ </div>
142
+ <BackupCodes codes={step.backupCodes} />
143
+ <form
144
+ className="grid max-w-sm gap-3"
145
+ onSubmit={(event) => {
146
+ event.preventDefault();
147
+ void confirmCode();
148
+ }}
149
+ >
150
+ <div className="grid gap-2">
151
+ <Label htmlFor="tf-code">Enter the 6-digit code to finish</Label>
152
+ <Input
153
+ id="tf-code"
154
+ inputMode="numeric"
155
+ autoComplete="one-time-code"
156
+ value={code}
157
+ onChange={(event) => setCode(event.target.value)}
158
+ required
159
+ />
160
+ </div>
161
+ {error && <p className="text-destructive text-sm">{error}</p>}
162
+ <div>
163
+ <Button type="submit" disabled={busy}>
164
+ Turn on
165
+ </Button>
166
+ </div>
167
+ </form>
168
+ </div>
169
+ );
170
+ }
171
+
172
+ if (step.kind === "codes") {
173
+ return (
174
+ <div className="grid gap-3">
175
+ <BackupCodes codes={step.backupCodes} />
176
+ <p className="text-muted-foreground text-sm">Your previous backup codes no longer work.</p>
177
+ <div>
178
+ <Button type="button" variant="outline" onClick={() => setStep({ kind: "idle" })}>
179
+ Done
180
+ </Button>
181
+ </div>
182
+ </div>
183
+ );
184
+ }
185
+
186
+ return (
187
+ <div className="flex flex-wrap items-center gap-3">
188
+ {enabled ? (
189
+ <>
190
+ <Button type="button" variant="outline" onClick={() => setStep({ kind: "password", intent: "codes" })}>
191
+ New backup codes
192
+ </Button>
193
+ {!required && (
194
+ <Button type="button" variant="ghost" onClick={() => setStep({ kind: "password", intent: "disable" })}>
195
+ Turn off
196
+ </Button>
197
+ )}
198
+ </>
199
+ ) : (
200
+ <Button type="button" onClick={() => setStep({ kind: "password", intent: "enable" })}>
201
+ Set up authenticator app
202
+ </Button>
203
+ )}
204
+ </div>
205
+ );
206
+ }
@@ -457,6 +457,20 @@ const publishBlocked =
457
457
  />
458
458
  </div>
459
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
+ )}
460
474
  {collection.slug === "users" && mode === "edit" && Astro.url.searchParams.get("inviteToken") && (
461
475
  <AdminCard title={Astro.url.searchParams.get("emailSent") === "true" ? "Invitation sent" : "Invite link"}>
462
476
  {Astro.url.searchParams.get("emailSent") === "true" ? (
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";
@@ -426,6 +433,22 @@ const getTableRefs = async (collectionSlug: string) => {
426
433
  return tables;
427
434
  };
428
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
+
429
452
  /**
430
453
  * A validation failure that knows which field caused it, so the admin can point at
431
454
  * the offending input instead of showing a toast and leaving the editor to hunt.
@@ -442,6 +465,7 @@ export const createCms = (config: CMSConfig) => {
442
465
  '"my.task": () => import("@/lib/handler").then((mod) => mod.run()).',
443
466
  );
444
467
  }
468
+ registerAuthConfig(config);
445
469
  const collectionMap = getCollectionMap(config);
446
470
 
447
471
  // Lets assets.delete() check whether a file is still referenced without every
@@ -780,6 +804,7 @@ export const createCms = (config: CMSConfig) => {
780
804
  const transformedInput = collection.hooks?.beforeCreate
781
805
  ? await collection.hooks.beforeCreate(preparedInput, hookContext)
782
806
  : preparedInput;
807
+ const credentialHash = takeCredentialHash(collection, transformedInput);
783
808
 
784
809
  const createdAt = now();
785
810
  const docId = typeof data._id === "string" ? String(data._id) : nanoid();
@@ -787,6 +812,8 @@ export const createCms = (config: CMSConfig) => {
787
812
  _id: docId,
788
813
  ...serializeForDb(collection, transformedInput),
789
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;
790
817
 
791
818
  if (collection.drafts) {
792
819
  const status = data._status === "published" ? "published" : getDefaultStatus(collection);
@@ -800,6 +827,7 @@ export const createCms = (config: CMSConfig) => {
800
827
  }
801
828
 
802
829
  await db.insert(tables.main).values(docValues);
830
+ if (credentialHash) await setCredentialPassword(docId, credentialHash);
803
831
 
804
832
  if (collection.versions && tables.versions) {
805
833
  await db.insert(tables.versions).values({
@@ -878,6 +906,7 @@ export const createCms = (config: CMSConfig) => {
878
906
  const transformedInput = collection.hooks?.beforeUpdate
879
907
  ? await collection.hooks.beforeUpdate(preparedInput, existing, hookContext)
880
908
  : preparedInput;
909
+ const credentialHash = takeCredentialHash(collection, transformedInput);
881
910
 
882
911
  if (collection.drafts && existing._status === "published" && !(existingRows[0] as any)._published) {
883
912
  const snapshot: Record<string, unknown> = {};
@@ -931,6 +960,10 @@ export const createCms = (config: CMSConfig) => {
931
960
  } else {
932
961
  await db.update(tables.main).set(updateValues).where(eq(tables.main._id, id));
933
962
  }
963
+ if (credentialHash) {
964
+ await setCredentialPassword(id, credentialHash);
965
+ await revokeUserSessions(id);
966
+ }
934
967
 
935
968
  if (collection.versions && tables.versions) {
936
969
  const versionRows = await db
@@ -998,6 +1031,7 @@ export const createCms = (config: CMSConfig) => {
998
1031
  }
999
1032
  if (tables.translations) await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
1000
1033
  if (tables.versions) await db.delete(tables.versions).where(eq(tables.versions._docId, id));
1034
+ if (isAdminAuthCollection(collection)) await deleteUserAuthData(id);
1001
1035
  // Collaboration rows outlive their document otherwise, and an orphaned
1002
1036
  // review row still counts towards the "Needs you" badge.
1003
1037
  await removeCollaborationFor(slug, id);
@@ -1081,6 +1115,7 @@ export const createCms = (config: CMSConfig) => {
1081
1115
  for (const id of deletedIds) {
1082
1116
  if (tables.translations) await db.delete(tables.translations).where(eq(tables.translations._entityId, id));
1083
1117
  if (tables.versions) await db.delete(tables.versions).where(eq(tables.versions._docId, id));
1118
+ if (isAdminAuthCollection(collection)) await deleteUserAuthData(id);
1084
1119
  }
1085
1120
  } else {
1086
1121
  const CHUNK = 200; // stay well under SQLite's bound-variable limit
@@ -1090,6 +1125,7 @@ export const createCms = (config: CMSConfig) => {
1090
1125
  await db.delete(tables.translations).where(inArray(tables.translations._entityId, chunk));
1091
1126
  if (tables.versions) await db.delete(tables.versions).where(inArray(tables.versions._docId, chunk));
1092
1127
  await db.delete(tables.main).where(inArray(tables.main._id, chunk));
1128
+ if (isAdminAuthCollection(collection)) for (const id of chunk) await deleteUserAuthData(id);
1093
1129
  }
1094
1130
  deletedIds = ids;
1095
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;