@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
@@ -1,18 +1,9 @@
1
1
  import type { APIRoute } from "astro";
2
- import { eq } from "drizzle-orm";
3
2
 
4
- import { getDb } from "virtual:kide/db";
5
- import {
6
- auditRequestMeta,
7
- hitRateLimit,
8
- consumePasswordReset,
9
- createSession,
10
- hashPassword,
11
- logAudit,
12
- setSessionCookie,
13
- } from "virtual:kide/runtime";
14
- import { resolveAdminAuth, MIN_PASSWORD_LENGTH } from "../../../core";
3
+ import { hitRateLimit } from "virtual:kide/runtime";
4
+ import { getAdminAuth, resolveAdminAuth, MIN_PASSWORD_LENGTH } from "../../../core";
15
5
  import config from "virtual:kide/config";
6
+ import { authResponse } from "./_better-auth";
16
7
 
17
8
  export const prerender = false;
18
9
 
@@ -38,48 +29,18 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
38
29
  if (password !== confirmPassword) return redirectWithError(token, "password");
39
30
  if (password.length < MIN_PASSWORD_LENGTH) return redirectWithError(token, "short");
40
31
 
41
- // Hash before claiming the token: the token is single-use, so anything fallible must run
42
- // before we burn it — otherwise a hashing failure would strand the account with a spent
43
- // token. Consume is then the atomic single-winner gate against double-submit.
44
- const hashedPassword = await hashPassword(password);
45
- const reset = await consumePasswordReset(token);
46
- if (!reset) return redirectWithError(token, "invalid");
47
-
48
- const db = await getDb();
49
- const schema = await import("virtual:kide/schema");
50
- const tables = schema.cmsTables as Record<string, { main: any }>;
51
- if (!tables.users) return redirectWithError(token, "invalid");
52
-
53
- const userRows = await db.select().from(tables.users.main).where(eq(tables.users.main._id, reset.userId)).limit(1);
54
- if (userRows.length === 0) return redirectWithError(token, "invalid");
55
-
56
- const user = userRows[0] as Record<string, unknown>;
57
- await db
58
- .update(tables.users.main)
59
- .set({ password: hashedPassword, _updatedAt: new Date().toISOString() })
60
- .where(eq(tables.users.main._id, reset.userId));
61
- await db.delete(schema.cmsSessions).where(eq(schema.cmsSessions.userId, reset.userId));
62
-
63
- const session = await createSession(reset.userId);
64
-
65
- logAudit({
66
- action: "auth.password_reset_completed",
67
- resourceType: "user",
68
- resourceCollection: "users",
69
- resourceId: reset.userId,
70
- actor: {
71
- id: reset.userId,
72
- email: String(user.email ?? ""),
73
- role: String(user.role ?? ""),
74
- },
75
- ...auditRequestMeta(request),
76
- });
77
-
78
- return new Response(null, {
79
- status: 303,
80
- headers: {
81
- Location: "/admin",
82
- "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
83
- },
84
- });
32
+ // Better Auth consumes the (hashed-at-rest, single-use) token atomically, writes the
33
+ // credential and revokes every session the user had.
34
+ const betterAuth = await getAdminAuth(request);
35
+ const response = await authResponse(() =>
36
+ betterAuth.api.resetPassword({
37
+ body: { newPassword: password, token },
38
+ headers: request.headers,
39
+ asResponse: true,
40
+ }),
41
+ );
42
+ if (!response.ok) return redirectWithError(token, "invalid");
43
+
44
+ // Sign in again rather than straight in: a second factor, if enrolled, still applies.
45
+ return new Response(null, { status: 303, headers: { Location: "/admin/login?status=password-reset" } });
85
46
  };
@@ -3,15 +3,9 @@ import { eq, sql } from "drizzle-orm";
3
3
  import { nanoid } from "nanoid";
4
4
 
5
5
  import { getDb } from "virtual:kide/db";
6
- import {
7
- auditRequestMeta,
8
- hitRateLimit,
9
- createSession,
10
- hashPassword,
11
- logAudit,
12
- setSessionCookie,
13
- } from "virtual:kide/runtime";
14
- import { MIN_PASSWORD_LENGTH } from "../../../core";
6
+ import { auditRequestMeta, hitRateLimit, hashPassword, logAudit } from "virtual:kide/runtime";
7
+ import { getAdminAuth, MIN_PASSWORD_LENGTH, setCredentialPassword } from "../../../core";
8
+ import { authResponse, redirectWithCookies } from "./_better-auth";
15
9
 
16
10
  export const prerender = false;
17
11
 
@@ -27,7 +21,9 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
27
21
 
28
22
  const formData = await request.formData();
29
23
  const name = String(formData.get("name") ?? "").trim();
30
- const email = String(formData.get("email") ?? "").trim();
24
+ const email = String(formData.get("email") ?? "")
25
+ .trim()
26
+ .toLowerCase();
31
27
  const password = String(formData.get("password") ?? "");
32
28
  const confirmPassword = String(formData.get("confirmPassword") ?? "");
33
29
 
@@ -79,8 +75,8 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
79
75
  // the first admin only if none exists yet. Self-recovering — if anything fails there's no
80
76
  // marker to strand setup, and a retry just runs the same guarded insert.
81
77
  await db.run(sql`
82
- INSERT INTO cms_users (_id, name, email, role, password, _created_at, _updated_at)
83
- SELECT ${id}, ${name}, ${email}, 'admin', ${hashedPassword}, ${now}, ${now}
78
+ INSERT INTO cms_users (_id, name, email, role, _auth_email_verified, _created_at, _updated_at)
79
+ SELECT ${id}, ${name}, ${email}, 'admin', 1, ${now}, ${now}
84
80
  WHERE NOT EXISTS (SELECT 1 FROM cms_users WHERE role = 'admin')
85
81
  `);
86
82
 
@@ -91,7 +87,7 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
91
87
  return new Response(null, { status: 303, headers: { Location: "/admin/login" } });
92
88
  }
93
89
 
94
- const session = await createSession(id);
90
+ await setCredentialPassword(id, hashedPassword);
95
91
 
96
92
  logAudit({
97
93
  action: "auth.setup_completed",
@@ -102,11 +98,9 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
102
98
  ...auditRequestMeta(request),
103
99
  });
104
100
 
105
- return new Response(null, {
106
- status: 303,
107
- headers: {
108
- Location: "/admin",
109
- "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
110
- },
111
- });
101
+ const auth = await getAdminAuth(request);
102
+ const signIn = await authResponse(() =>
103
+ auth.api.signInEmail({ body: { email, password, rememberMe: true }, headers: request.headers, asResponse: true }),
104
+ );
105
+ return redirectWithCookies(signIn.ok ? "/admin" : "/admin/login", signIn);
112
106
  };
@@ -1,35 +1,43 @@
1
1
  import type { APIRoute } from "astro";
2
2
 
3
- import { getSsoProvider, publicOrigin, resolveAdminAuth } from "../../../../../core";
3
+ import { hitRateLimit } from "virtual:kide/runtime";
4
4
  import config from "virtual:kide/config";
5
+ import { getAdminAuth, getSsoProvider } from "../../../../../core";
6
+ import { authResponse, readJson, redirectWithCookies } from "../../_better-auth";
5
7
 
6
8
  export const prerender = false;
7
9
 
8
- export const GET: APIRoute = async ({ params, request }) => {
9
- const providerId = params.provider ?? "";
10
- const provider = getSsoProvider(config, providerId);
11
- if (!provider) return Response.json({ error: "SSO provider not found." }, { status: 404 });
10
+ const toLogin = (error: string) =>
11
+ new Response(null, { status: 303, headers: { Location: `/admin/login?error=${error}` } });
12
12
 
13
- const auth = resolveAdminAuth(config);
14
- if (provider.authorizationUrl) {
15
- const url = new URL(provider.authorizationUrl);
16
- url.searchParams.set("provider", provider.id);
17
- url.searchParams.set(
18
- "redirect_uri",
19
- // Anchored on the trusted origin, not the Host header — see publicOrigin.
20
- provider.callbackUrl ?? new URL("/api/cms/auth/sso/callback", publicOrigin(request)).toString(),
21
- );
22
- return new Response(null, {
23
- status: 303,
24
- headers: { Location: url.toString() },
25
- });
26
- }
13
+ // Only same-site admin paths: a returnTo is attacker-controllable via a crafted link.
14
+ const safeReturnTo = (value: string | null) =>
15
+ value && /^\/admin(?:[/?#]|$)/.test(value) && !value.startsWith("//") ? value : "/admin";
16
+
17
+ export const GET: APIRoute = async ({ params, request, url, clientAddress }) => {
18
+ const provider = getSsoProvider(config, params.provider ?? "");
19
+ if (!provider) return toLogin("sso-unknown");
27
20
 
28
- return Response.json(
29
- {
30
- error: `SSO provider "${provider.id}" is configured, but ${auth.provider} does not expose a start URL for it yet.`,
31
- hint: "Set authorizationUrl for a broker/custom flow, or use the Better Auth/WorkOS adapter when it is installed.",
32
- },
33
- { status: 501 },
21
+ const limit = await hitRateLimit("sso:ip", clientAddress, { max: 30, windowMs: 15 * 60 * 1000 });
22
+ if (!limit.ok) return toLogin("rate-limited");
23
+
24
+ const auth = await getAdminAuth(request);
25
+ const response = await authResponse(() =>
26
+ auth.api.signInSocial({
27
+ body: {
28
+ provider: provider.id,
29
+ callbackURL: safeReturnTo(url.searchParams.get("returnTo")),
30
+ errorCallbackURL: "/admin/login",
31
+ },
32
+ headers: request.headers,
33
+ asResponse: true,
34
+ }),
34
35
  );
36
+ const body = await readJson(response);
37
+ if (!response.ok || typeof body?.url !== "string") {
38
+ console.error(`[kide] SSO provider "${provider.id}" could not start sign-in:`, body?.message ?? response.status);
39
+ return toLogin("sso-unavailable");
40
+ }
41
+ // Carries the OAuth state / PKCE cookies the callback checks.
42
+ return redirectWithCookies(body.url, response);
35
43
  };
@@ -13,11 +13,13 @@ const RATE_MAX = 10; // submissions per IP per window
13
13
  const RATE_WINDOW_MS = 10 * 60 * 1000;
14
14
 
15
15
  type FormFieldConfig = {
16
- type: "text" | "email" | "textarea" | "select" | "checkbox";
16
+ type: "text" | "email" | "tel" | "number" | "textarea" | "select" | "radio" | "checkbox";
17
17
  name: string;
18
18
  label: string;
19
19
  required?: boolean;
20
20
  maxLength?: number;
21
+ min?: number;
22
+ max?: number;
21
23
  options?: string[];
22
24
  };
23
25
 
@@ -89,11 +91,34 @@ export const POST: APIRoute = async ({ request, params, redirect, clientAddress
89
91
  continue;
90
92
  }
91
93
 
92
- if (field.type === "select" && value && Array.isArray(field.options) && !field.options.includes(String(value))) {
94
+ // A choice field only ever accepts one of its declared options — the browser
95
+ // constrains the visible control, the server is what makes it true.
96
+ if (
97
+ (field.type === "select" || field.type === "radio") &&
98
+ value &&
99
+ Array.isArray(field.options) &&
100
+ !field.options.includes(String(value))
101
+ ) {
93
102
  errors.push(`${field.label} has an invalid value`);
94
103
  continue;
95
104
  }
96
105
 
106
+ if (field.type === "number" && value !== "") {
107
+ const parsed = Number(value);
108
+ if (!Number.isFinite(parsed)) {
109
+ errors.push(`${field.label} must be a number`);
110
+ continue;
111
+ }
112
+ if (field.min !== undefined && parsed < field.min) {
113
+ errors.push(`${field.label} must be ${field.min} or more`);
114
+ continue;
115
+ }
116
+ if (field.max !== undefined && parsed > field.max) {
117
+ errors.push(`${field.label} must be ${field.max} or less`);
118
+ continue;
119
+ }
120
+ }
121
+
97
122
  data[field.name] = value;
98
123
  }
99
124