@kidecms/core 0.30.1 → 0.31.1

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.
@@ -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
  };