@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
package/core/auth.ts CHANGED
@@ -100,97 +100,7 @@ export const hashToken = async (token: string): Promise<string> => {
100
100
  return `sha256:${hex}`;
101
101
  };
102
102
 
103
- export const createSession = async (userId: string): Promise<{ token: string; expiresAt: string }> => {
104
- const db = await getDb();
105
- const schema = getSchema();
106
- const token = nanoid(32);
107
- const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
108
-
109
- await db.insert(schema.cmsSessions).values({
110
- _id: await hashToken(token),
111
- userId,
112
- expiresAt,
113
- });
114
-
115
- return { token, expiresAt };
116
- };
117
-
118
- export const validateSession = async (token: string): Promise<{ userId: string; expiresAt: string } | null> => {
119
- const db = await getDb();
120
- const schema = getSchema();
121
- const tokenHash = await hashToken(token);
122
- const rows = await db.select().from(schema.cmsSessions).where(eq(schema.cmsSessions._id, tokenHash)).limit(1);
123
-
124
- if (rows.length === 0) return null;
125
-
126
- const session = rows[0] as { _id: string; userId: string; expiresAt: string };
127
- if (new Date(session.expiresAt) < new Date()) {
128
- await db.delete(schema.cmsSessions).where(eq(schema.cmsSessions._id, tokenHash));
129
- return null;
130
- }
131
-
132
- return { userId: session.userId, expiresAt: session.expiresAt };
133
- };
134
-
135
- export const destroySession = async (token: string) => {
136
- const db = await getDb();
137
- const schema = getSchema();
138
- await db.delete(schema.cmsSessions).where(eq(schema.cmsSessions._id, await hashToken(token)));
139
- };
140
-
141
- export type SessionUser = {
142
- id: string;
143
- email: string;
144
- name: string;
145
- role: string;
146
- [key: string]: unknown;
147
- };
148
-
149
- const parseSessionValue = (value: unknown) => {
150
- if (typeof value !== "string") return value;
151
- const trimmed = value.trim();
152
- if (!trimmed.startsWith("[") && !trimmed.startsWith("{")) return value;
153
- try {
154
- return JSON.parse(trimmed);
155
- } catch {
156
- return value;
157
- }
158
- };
159
-
160
- export const getSessionUser = async (request: Request): Promise<SessionUser | null> => {
161
- const cookieHeader = request.headers.get("cookie") ?? "";
162
- const match = cookieHeader.match(/cms_session=([^;]+)/);
163
- if (!match) return null;
164
-
165
- const session = await validateSession(match[1]);
166
- if (!session) return null;
167
-
168
- const db = await getDb();
169
- const schema = getSchema();
170
- const tables = schema.cmsTables as Record<string, { main: any }>;
171
-
172
- if (!tables.users) return null;
173
-
174
- const userRows = await db.select().from(tables.users.main).where(eq(tables.users.main._id, session.userId)).limit(1);
175
- if (userRows.length === 0) return null;
176
-
177
- const user = userRows[0] as Record<string, unknown>;
178
- const publicFields = Object.fromEntries(
179
- Object.entries(user)
180
- .filter(([key]) => key !== "_id" && key !== "password")
181
- .map(([key, value]) => [key, parseSessionValue(value)]),
182
- );
183
- return {
184
- ...publicFields,
185
- id: String(user._id),
186
- email: String(user.email),
187
- name: String(user.name),
188
- role: String(user.role),
189
- };
190
- };
191
-
192
103
  const INVITE_EXPIRY_DAYS = 7;
193
- const PASSWORD_RESET_EXPIRY_HOURS = 1;
194
104
 
195
105
  export const createInvite = async (userId: string): Promise<{ token: string; expiresAt: string }> => {
196
106
  const db = await getDb();
@@ -250,65 +160,49 @@ export const consumeInvite = async (token: string): Promise<{ userId: string } |
250
160
  return rows.length > 0 ? { userId: rows[0].userId as string } : null;
251
161
  };
252
162
 
253
- export const createPasswordReset = async (userId: string): Promise<{ token: string; expiresAt: string }> => {
254
- const db = await getDb();
255
- const schema = getSchema();
256
- const token = nanoid(40);
257
- const expiresAt = new Date(Date.now() + PASSWORD_RESET_EXPIRY_HOURS * 60 * 60 * 1000).toISOString();
258
-
259
- await db.insert(schema.cmsPasswordResets).values({
260
- _id: nanoid(),
261
- userId,
262
- token: await hashToken(token),
263
- expiresAt,
264
- });
265
-
266
- return { token, expiresAt };
267
- };
268
-
269
- /** Read-only check for rendering the reset page. Does NOT consume — see consumePasswordReset. */
270
- export const validatePasswordReset = async (token: string): Promise<{ userId: string; expiresAt: string } | null> => {
271
- const db = await getDb();
272
- const schema = getSchema();
273
- const rows = await db
274
- .select()
275
- .from(schema.cmsPasswordResets)
276
- .where(eq(schema.cmsPasswordResets.token, await hashToken(token)))
277
- .limit(1);
278
-
279
- if (rows.length === 0) return null;
280
-
281
- const reset = rows[0] as { userId: string; expiresAt: string; usedAt: string | null };
282
- if (reset.usedAt) return null;
283
- if (new Date(reset.expiresAt) < new Date()) return null;
284
-
285
- return { userId: reset.userId, expiresAt: reset.expiresAt };
286
- };
287
-
288
- /** Atomically claim a reset token; returns the userId only if it won the race. */
289
- export const consumePasswordReset = async (token: string): Promise<{ userId: string } | null> => {
290
- const db = await getDb();
291
- const schema = getSchema();
292
- const now = new Date().toISOString();
293
- const rows = await db
294
- .update(schema.cmsPasswordResets)
295
- .set({ usedAt: now })
296
- .where(
297
- and(
298
- eq(schema.cmsPasswordResets.token, await hashToken(token)),
299
- isNull(schema.cmsPasswordResets.usedAt),
300
- gt(schema.cmsPasswordResets.expiresAt, now),
301
- ),
302
- )
303
- .returning({ userId: schema.cmsPasswordResets.userId });
304
- return rows.length > 0 ? { userId: rows[0].userId as string } : null;
305
- };
306
-
307
- export const SESSION_COOKIE_NAME = "cms_session";
308
-
309
- export const setSessionCookie = (token: string, expiresAt: string) => {
310
- const secure = process.env.NODE_ENV === "production" ? "; Secure" : "";
311
- return `${SESSION_COOKIE_NAME}=${token}; Path=/; HttpOnly; SameSite=Strict${secure}; Expires=${new Date(expiresAt).toUTCString()}`;
312
- };
313
-
314
- export const clearSessionCookie = () => `${SESSION_COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`;
163
+ const removed = (name: string, replacement: string) => () => {
164
+ throw new Error(`[kide] ${name}() was removed when admin auth moved to Better Auth. ${replacement}`);
165
+ };
166
+
167
+ /** @deprecated Sessions are issued by Better Auth — sign in through `getAdminAuth(request).api`. */
168
+ export const createSession: (userId: string) => Promise<{ token: string; expiresAt: string }> = removed(
169
+ "createSession",
170
+ "Sign users in through getAdminAuth(request).api.",
171
+ ) as never;
172
+ /** @deprecated Use `getSessionUser(request)`. */
173
+ export const validateSession: (token: string) => Promise<{ userId: string; expiresAt: string } | null> = removed(
174
+ "validateSession",
175
+ "Use getSessionUser(request).",
176
+ ) as never;
177
+ /** @deprecated Use `getAdminAuth(request).api.signOut`. */
178
+ export const destroySession: (token: string) => Promise<void> = removed(
179
+ "destroySession",
180
+ "Use getAdminAuth(request).api.signOut.",
181
+ ) as never;
182
+ /** @deprecated Password resets are Better Auth verification tokens. */
183
+ export const createPasswordReset: (userId: string) => Promise<{ token: string; expiresAt: string }> = removed(
184
+ "createPasswordReset",
185
+ "Use getAdminAuth(request).api.requestPasswordReset.",
186
+ ) as never;
187
+ /** @deprecated Password resets are Better Auth verification tokens. */
188
+ export const validatePasswordReset: (token: string) => Promise<{ userId: string; expiresAt: string } | null> = removed(
189
+ "validatePasswordReset",
190
+ "Use getAdminAuth(request).api.resetPassword.",
191
+ ) as never;
192
+ /** @deprecated Password resets are Better Auth verification tokens. */
193
+ export const consumePasswordReset: (token: string) => Promise<{ userId: string } | null> = removed(
194
+ "consumePasswordReset",
195
+ "Use getAdminAuth(request).api.resetPassword.",
196
+ ) as never;
197
+ /** @deprecated Better Auth names the cookie `kide.session_token`. */
198
+ export const SESSION_COOKIE_NAME = "kide.session_token";
199
+ /** @deprecated Better Auth sets session cookies. */
200
+ export const setSessionCookie: (token: string, expiresAt: string) => string = removed(
201
+ "setSessionCookie",
202
+ "Better Auth sets session cookies.",
203
+ ) as never;
204
+ /** @deprecated Better Auth clears session cookies on sign-out. */
205
+ export const clearSessionCookie: () => string = removed(
206
+ "clearSessionCookie",
207
+ "Better Auth clears session cookies on sign-out.",
208
+ ) as never;
@@ -1,6 +1,7 @@
1
1
  import { nanoid } from "nanoid";
2
2
 
3
3
  import { hashPassword } from "./auth";
4
+ import { AUTH_USERS_COLLECTION, setCredentialPassword } from "./auth-engine";
4
5
  import { getDb } from "./runtime";
5
6
  import { getSchema } from "./schema";
6
7
 
@@ -8,21 +9,24 @@ export const createAdminUser = async (input: { name: string; email: string; pass
8
9
  const db = await getDb();
9
10
  const schema = getSchema();
10
11
  const tables = schema.cmsTables as Record<string, { main: any }>;
12
+ const users = tables[AUTH_USERS_COLLECTION]?.main;
11
13
 
12
- if (!tables.users) {
14
+ if (!users) {
13
15
  throw new Error("No users collection found.");
14
16
  }
15
17
 
18
+ const id = nanoid();
16
19
  const now = new Date().toISOString();
17
20
  const hashedPassword = await hashPassword(input.password);
18
21
 
19
- await db.insert(tables.users.main).values({
20
- _id: nanoid(),
22
+ await db.insert(users).values({
23
+ _id: id,
21
24
  name: input.name,
22
- email: input.email,
23
- password: hashedPassword,
25
+ email: input.email.trim().toLowerCase(),
24
26
  role: "admin",
25
27
  _createdAt: now,
26
28
  _updatedAt: now,
29
+ ...(users._authEmailVerified ? { _authEmailVerified: true } : {}),
27
30
  });
31
+ await setCredentialPassword(id, hashedPassword);
28
32
  };
package/core/define.ts CHANGED
@@ -291,44 +291,79 @@ export type AdminRateLimitConfig = {
291
291
  export type AdminAuthPasswordConfig = {
292
292
  /** Enable email/password sign-in. Default true. */
293
293
  enabled?: boolean;
294
- /** Enable forgot-password reset flow. Default true for local/better-auth providers. */
294
+ /** Enable the forgot-password email flow. Default true. */
295
295
  forgotPassword?: boolean;
296
- /** Require or expose email verification in auth providers that support it. Default false. */
297
- emailVerification?: boolean;
298
296
  };
299
297
 
300
298
  export type AdminAuthMfaConfig = {
301
- /** Enable authenticator-app TOTP where supported by the auth provider. */
299
+ /** Let password users enable an authenticator app (TOTP) with backup codes. Default false. */
302
300
  totp?: boolean;
303
- /** Enable single-use recovery codes where supported by the auth provider. */
304
- backupCodes?: boolean;
305
- /** Enable passkey/WebAuthn sign-in where supported by the auth provider. */
301
+ /** Let users register passkeys and sign in with them. Default false. */
306
302
  passkeys?: boolean;
303
+ /**
304
+ * Require password users to enroll TOTP before using the admin: `true` for everyone,
305
+ * or a list of roles. SSO users are exempt — their identity provider enforces MFA.
306
+ */
307
+ require?: boolean | string[];
307
308
  };
308
309
 
309
- export type AdminAuthSsoProviderConfig = {
310
- /** Stable provider id used in URLs, e.g. "azure" or "okta". */
310
+ type AdminAuthSsoProviderBase = {
311
+ /** Stable id used in URLs (`/api/cms/auth/sso/<id>/start`). Letters, digits, dashes. */
311
312
  id: string;
312
- /** Human label shown on the login screen. */
313
+ /** Button label on the login screen, e.g. "Microsoft". Rendered as "Continue with <label>". */
313
314
  label: string;
314
- /** Protocol/backend used by the auth provider. */
315
- type: "oidc" | "saml" | "oauth" | "workos" | "custom";
316
- /** OIDC issuer/discovery URL, SAML entity ID, or broker-specific issuer. */
317
- issuer?: string;
315
+ /** Defaults to env `KIDE_SSO_<ID>_CLIENT_ID` (id uppercased, dashes → underscores). */
318
316
  clientId?: string;
317
+ /** Defaults to env `KIDE_SSO_<ID>_CLIENT_SECRET`. Prefer the env var over a literal. */
319
318
  clientSecret?: string;
320
- /** Optional explicit authorization URL for custom/broker flows. */
321
- authorizationUrl?: string;
322
- /** Optional callback URL override. Defaults to Kide's callback route. */
323
- callbackUrl?: string;
324
319
  scopes?: string[];
325
- /** Restrict JIT sign-in/provisioning to these email domains. */
320
+ /**
321
+ * Email domains this identity provider is authoritative for. Emails at these domains
322
+ * are trusted for linking to existing Kide users even when the provider omits
323
+ * `email_verified` (Entra does), and `"jit"` provisioning is limited to them.
324
+ */
326
325
  allowedDomains?: string[];
327
- /** Default Kide role for newly provisioned users. */
326
+ /**
327
+ * "invite-only" (default): only users that already exist in Kide can sign in.
328
+ * "jit": create a Kide user on first sign-in (requires `allowedDomains`).
329
+ */
330
+ provisioning?: "invite-only" | "jit";
331
+ /** Role for users created by `"jit"` provisioning. Default "editor". */
328
332
  role?: string;
329
- /** Provider-specific options passed through to the selected auth backend. */
330
- options?: Record<string, unknown>;
331
- };
333
+ /**
334
+ * Users with an email at `allowedDomains` must sign in through this provider: password
335
+ * sign-in and password reset are refused for them, and every session they hold lasts
336
+ * only while the provider keeps vouching for them. Default true (when `allowedDomains`
337
+ * is set). Keep a break-glass admin outside these domains (`pnpm cms:admin`).
338
+ */
339
+ enforce?: boolean;
340
+ /**
341
+ * Map ID-token claims to a Kide role, on every sign-in and every background re-check
342
+ * (e.g. Entra app roles or groups). Return a role to set it, or null/undefined to leave
343
+ * the current role unchanged.
344
+ */
345
+ mapRole?: (claims: Record<string, unknown>) => string | null | undefined;
346
+ };
347
+
348
+ export type AdminAuthSsoProviderConfig =
349
+ | (AdminAuthSsoProviderBase & {
350
+ /** Microsoft Entra ID, single tenant. */
351
+ type: "microsoft";
352
+ /** Directory (tenant) GUID. Multi-tenant endpoints are not supported. */
353
+ tenantId: string;
354
+ })
355
+ | (AdminAuthSsoProviderBase & {
356
+ /** Google Workspace / Google accounts. */
357
+ type: "google";
358
+ /** Restrict the Google account chooser to this Workspace domain (`hd`). */
359
+ hostedDomain?: string;
360
+ })
361
+ | (AdminAuthSsoProviderBase & {
362
+ /** Any OpenID Connect provider (Okta, Keycloak, Auth0, Authentik, Idura, …). */
363
+ type: "oidc";
364
+ /** Issuer URL; discovery is read from `<issuer>/.well-known/openid-configuration`. */
365
+ issuer: string;
366
+ });
332
367
 
333
368
  export type AdminCustomAuthProvider = {
334
369
  kind: "custom";
@@ -339,24 +374,29 @@ export type AdminCustomAuthProvider = {
339
374
 
340
375
  export type AdminAuthConfig = {
341
376
  /**
342
- * Auth backend. "local" keeps Kide's built-in session/password flow.
343
- * "better-auth" is the batteries-included backend for MFA, passkeys, OIDC/SAML,
344
- * and forgot-password flows. "workos" and "custom" are escape hatches.
377
+ * "local" (default) is Kide's built-in auth, powered by Better Auth: password,
378
+ * forgot-password, SSO, TOTP and passkeys as configured below. A custom provider
379
+ * replaces it entirely — Kide then only reads the session through `getSession`.
345
380
  */
346
- provider?: "local" | "better-auth" | "workos" | AdminCustomAuthProvider;
381
+ provider?: "local" | AdminCustomAuthProvider;
347
382
  password?: AdminAuthPasswordConfig;
348
383
  mfa?: AdminAuthMfaConfig;
349
384
  sso?: {
350
385
  providers?: AdminAuthSsoProviderConfig[];
386
+ /**
387
+ * How often an SSO user's standing is re-checked with their provider, in minutes
388
+ * (default 60). The check refreshes the provider's token in the background; a provider
389
+ * that refuses (user disabled or deleted) ends all of the user's sessions.
390
+ */
391
+ verifyEveryMinutes?: number;
351
392
  };
352
- workos?: {
353
- clientId?: string;
354
- apiKey?: string;
355
- organizationId?: string;
356
- defaultRole?: string;
357
- };
358
- /** Escape hatch for provider-specific options, e.g. raw Better Auth config. */
359
- advanced?: Record<string, unknown>;
393
+ /** Session lifetime in days. Default 30. */
394
+ sessionDays?: number;
395
+ /**
396
+ * Escape hatch: adjust the generated Better Auth options (add plugins, providers, …).
397
+ * Tables that added plugins need are picked up by `cms:generate` like any other.
398
+ */
399
+ betterAuth?: (options: Record<string, any>) => Record<string, any>;
360
400
  };
361
401
 
362
402
  /** A named colour offered by `fields.color()` pickers. */
package/core/generator.ts CHANGED
@@ -2,6 +2,14 @@ import { mkdir, rename, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
 
5
+ import {
6
+ authColumnSource,
7
+ authTableSpecs,
8
+ authUserExtraColumns,
9
+ AUTH_USERS_COLLECTION,
10
+ buildAdminAuthOptions,
11
+ } from "./auth-engine";
12
+ import type { AuthTableSpec } from "./auth-engine";
5
13
  import type { CMSConfig, CollectionConfig, FieldConfig } from "./define";
6
14
  import { getTranslatableFieldNames } from "./define";
7
15
 
@@ -62,7 +70,38 @@ const generateColumnDef = (fieldName: string, field: FieldConfig, options: { bar
62
70
  return ` ${fieldName}: ${col},`;
63
71
  };
64
72
 
65
- const generateMainTable = (config: CMSConfig, collection: CollectionConfig): string => {
73
+ const isAuthUsersCollection = (collection: CollectionConfig) =>
74
+ !!collection.auth && collection.slug === AUTH_USERS_COLLECTION;
75
+
76
+ /** Better Auth's table layout for the admin audience, or null when there is no users collection. */
77
+ const getAuthSpecs = (config: CMSConfig): AuthTableSpec[] | null => {
78
+ const users = config.collections.find(isAuthUsersCollection);
79
+ if (!users) return null;
80
+ for (const required of ["name", "email"]) {
81
+ if (!users.fields[required]) {
82
+ throw new Error(`[kide] The users collection needs a "${required}" field — admin sign-in relies on it.`);
83
+ }
84
+ }
85
+ if (users.timestamps === false) {
86
+ throw new Error("[kide] The users collection must keep timestamps — admin sign-in relies on them.");
87
+ }
88
+ const specs = authTableSpecs(buildAdminAuthOptions(config));
89
+ for (const spec of specs) {
90
+ const clash = !spec.isUser && config.collections.find((c) => `cms_${snakeCase(c.slug)}` === spec.table);
91
+ if (clash) {
92
+ throw new Error(
93
+ `[kide] Collection "${clash.slug}" would share the table ${spec.table} with admin auth. Rename it.`,
94
+ );
95
+ }
96
+ }
97
+ return specs;
98
+ };
99
+
100
+ const generateMainTable = (
101
+ config: CMSConfig,
102
+ collection: CollectionConfig,
103
+ authSpecs: AuthTableSpec[] | null,
104
+ ): string => {
66
105
  const tableName = `cms_${snakeCase(collection.slug)}`;
67
106
  const varName = `cms${pascalCase(collection.slug)}`;
68
107
  const columns: string[] = [` _id: text("_id").primaryKey(),`];
@@ -71,6 +110,12 @@ const generateMainTable = (config: CMSConfig, collection: CollectionConfig): str
71
110
  columns.push(generateColumnDef(fieldName, field));
72
111
  }
73
112
 
113
+ if (authSpecs && isAuthUsersCollection(collection)) {
114
+ for (const column of authUserExtraColumns(authSpecs)) {
115
+ columns.push(` ${column.schemaKey}: ${authColumnSource(column, { userTable: true })},`);
116
+ }
117
+ }
118
+
74
119
  // The language the base row is written in. A document exists in this locale
75
120
  // plus every locale it has a translation row for; the default keeps existing
76
121
  // rows on today's "base row = default locale" behaviour.
@@ -159,8 +204,10 @@ const generateSchemaFile = (config: CMSConfig): string => {
159
204
  ``,
160
205
  ];
161
206
 
207
+ const authSpecs = getAuthSpecs(config);
208
+
162
209
  for (const collection of config.collections) {
163
- parts.push(generateMainTable(config, collection));
210
+ parts.push(generateMainTable(config, collection, authSpecs));
164
211
  const translationsTable = generateTranslationsTable(config, collection);
165
212
  if (translationsTable) parts.push("", translationsTable);
166
213
  const versionsTable = generateVersionsTable(collection);
@@ -193,12 +240,6 @@ const generateSchemaFile = (config: CMSConfig): string => {
193
240
  name: text("name").notNull(),
194
241
  parent: text("parent"),
195
242
  _createdAt: text("_created_at").notNull(),
196
- });`);
197
- parts.push("");
198
- parts.push(`export const cmsSessions = sqliteTable("cms_sessions", {
199
- _id: text("_id").primaryKey(),
200
- userId: text("user_id").notNull(),
201
- expiresAt: text("expires_at").notNull(),
202
243
  });`);
203
244
  parts.push("");
204
245
  parts.push(`export const cmsLocks = sqliteTable("cms_locks", {
@@ -212,7 +253,17 @@ const generateSchemaFile = (config: CMSConfig): string => {
212
253
  docIdx: index("locks_doc_idx").on(table.collection, table.documentId),
213
254
  }));`);
214
255
  parts.push("");
215
- parts.push(`export const cmsInvites = sqliteTable("cms_invites", {
256
+ // Retired in 0.31 (sessions and resets moved to Better Auth) but still emitted: dropping
257
+ // them in the same diff that adds cms_auth_* makes drizzle-kit ask whether the new tables
258
+ // are renames — an interactive prompt that breaks `cms:push` and `drizzle-kit generate`.
259
+ // Nothing reads them anymore; drop them in the next major.
260
+ parts.push(`export const cmsSessions = sqliteTable("cms_sessions", {
261
+ _id: text("_id").primaryKey(),
262
+ userId: text("user_id").notNull(),
263
+ expiresAt: text("expires_at").notNull(),
264
+ });`);
265
+ parts.push("");
266
+ parts.push(`export const cmsPasswordResets = sqliteTable("cms_password_resets", {
216
267
  _id: text("_id").primaryKey(),
217
268
  userId: text("user_id").notNull(),
218
269
  token: text("token").notNull().unique(),
@@ -220,7 +271,7 @@ const generateSchemaFile = (config: CMSConfig): string => {
220
271
  usedAt: text("used_at"),
221
272
  });`);
222
273
  parts.push("");
223
- parts.push(`export const cmsPasswordResets = sqliteTable("cms_password_resets", {
274
+ parts.push(`export const cmsInvites = sqliteTable("cms_invites", {
224
275
  _id: text("_id").primaryKey(),
225
276
  userId: text("user_id").notNull(),
226
277
  token: text("token").notNull().unique(),
@@ -300,6 +351,25 @@ const generateSchemaFile = (config: CMSConfig): string => {
300
351
  }));`);
301
352
  parts.push("");
302
353
 
354
+ // Better Auth's tables (sessions, credential/SSO accounts, verification tokens, plus
355
+ // whatever enabled plugins add). Users live in the users collection's own table.
356
+ for (const spec of authSpecs ?? []) {
357
+ if (spec.isUser) continue;
358
+ const columns = spec.columns.map((column) => ` ${column.schemaKey}: ${authColumnSource(column)},`);
359
+ const indexed = spec.columns.filter((column) => column.index && !column.unique);
360
+ const indexes = indexed.map(
361
+ (column) =>
362
+ ` ${column.schemaKey}Idx: index("${spec.table.replace(/^cms_/, "")}_${column.column}_idx").on(table.${column.schemaKey}),`,
363
+ );
364
+ const body = `{\n${columns.join("\n")}\n}`;
365
+ parts.push(
366
+ indexes.length
367
+ ? `export const ${spec.exportName} = sqliteTable("${spec.table}", ${body}, (table) => ({\n${indexes.join("\n")}\n}));`
368
+ : `export const ${spec.exportName} = sqliteTable("${spec.table}", ${body});`,
369
+ );
370
+ parts.push("");
371
+ }
372
+
303
373
  const tableExports: string[] = [];
304
374
  for (const collection of config.collections) {
305
375
  const varName = `cms${pascalCase(collection.slug)}`;
package/core/index.ts CHANGED
@@ -43,7 +43,14 @@ export {
43
43
  resolveCollaboration,
44
44
  isApprover,
45
45
  } from "./define";
46
- export { customAuth, getSsoProvider, resolveAdminAuth } from "./auth-config";
46
+ export {
47
+ customAuth,
48
+ enforcedSsoProvider,
49
+ enforcedSsoProviders,
50
+ getSsoProvider,
51
+ mfaRequiredFor,
52
+ resolveAdminAuth,
53
+ } from "./auth-config";
47
54
  export type { ResolvedAdminAuthConfig } from "./auth-config";
48
55
  export type {
49
56
  CMSConfig,
@@ -127,7 +134,6 @@ export {
127
134
  createSession,
128
135
  validateSession,
129
136
  destroySession,
130
- getSessionUser,
131
137
  createInvite,
132
138
  validateInvite,
133
139
  consumeInvite,
@@ -138,7 +144,29 @@ export {
138
144
  setSessionCookie,
139
145
  clearSessionCookie,
140
146
  } from "./auth";
141
- export type { SessionUser } from "./auth";
147
+ export {
148
+ ADMIN_AUTH_BASE_PATH,
149
+ applySsoRoleMapping,
150
+ auditActor,
151
+ buildAdminAuthOptions,
152
+ deleteUserAuthData,
153
+ extensionAuthEndpoints,
154
+ getAccountSecurity,
155
+ getAdminAuth,
156
+ getSessionUser,
157
+ getSsoDenial,
158
+ hasCredentialPassword,
159
+ listSignInMethods,
160
+ loadAuthUser,
161
+ markSsoVerified,
162
+ migrateLegacyAuth,
163
+ registerAuthConfig,
164
+ resetAuthEngine,
165
+ resolveAdminSession,
166
+ revokeUserSessions,
167
+ setCredentialPassword,
168
+ } from "./auth-engine";
169
+ export type { AccountSecurity, AdminSession, AuthEndpointRule, SessionUser, SsoDenial } from "./auth-engine";
142
170
 
143
171
  export { assets, folders, stripMissingAssetImages } from "./assets";
144
172
  export type { AssetRecord, FolderRecord } from "./assets";
package/core/schema.ts CHANGED
@@ -2,7 +2,9 @@ type SchemaModule = {
2
2
  cmsTables: Record<string, { main: any; translations?: any; versions?: any }>;
3
3
  cmsAssets: any;
4
4
  cmsAssetFolders: any;
5
- cmsSessions: any;
5
+ cmsAuthSessions: any;
6
+ cmsAuthAccounts: any;
7
+ cmsAuthVerifications: any;
6
8
  cmsLocks: any;
7
9
  cmsInvites: any;
8
10
  cmsRateLimits: any;
package/core/seed.ts CHANGED
@@ -2,6 +2,7 @@ import { sql } from "drizzle-orm";
2
2
  import { nanoid } from "nanoid";
3
3
 
4
4
  import { hashPassword } from "./auth";
5
+ import { AUTH_USERS_COLLECTION, setCredentialPassword } from "./auth-engine";
5
6
  import type { CMSConfig, CollectionConfig, FieldConfig, SeedDocument } from "./define";
6
7
  import { getDb } from "./runtime";
7
8
  import { getSchema } from "./schema";
@@ -65,8 +66,14 @@ export const seedDatabase = async (config: CMSConfig, seedData: Record<string, S
65
66
  }
66
67
  }
67
68
 
68
- if (collection.auth && typeof fieldData.password === "string") {
69
- fieldData.password = await hashPassword(fieldData.password);
69
+ const isAuthUsers = !!collection.auth && collection.slug === AUTH_USERS_COLLECTION;
70
+ let credentialHash: string | null = null;
71
+ if (isAuthUsers && typeof fieldData.email === "string") fieldData.email = fieldData.email.toLowerCase();
72
+ if (isAuthUsers && "password" in fieldData) {
73
+ if (typeof fieldData.password === "string" && fieldData.password) {
74
+ credentialHash = await hashPassword(fieldData.password);
75
+ }
76
+ delete fieldData.password;
70
77
  }
71
78
 
72
79
  const serialized = serializeForDb(collection, fieldData);
@@ -85,7 +92,10 @@ export const seedDatabase = async (config: CMSConfig, seedData: Record<string, S
85
92
  docValues._updatedAt = timestamp;
86
93
  }
87
94
 
95
+ if (isAuthUsers && tables.main._authEmailVerified) docValues._authEmailVerified = true;
96
+
88
97
  await db.insert(tables.main).values(docValues);
98
+ if (credentialHash) await setCredentialPassword(docId, credentialHash);
89
99
 
90
100
  if (collection.versions && tables.versions) {
91
101
  await db.insert(tables.versions).values({