@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.
@@ -1,18 +1,18 @@
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
- createSession,
8
- hashPassword,
9
- logAudit,
10
- setSessionCookie,
11
- tokenReference,
12
- verifyPassword,
13
- } from "virtual:kide/runtime";
3
+ import { auditRequestMeta, logAudit } from "virtual:kide/runtime";
14
4
  import config from "virtual:kide/config";
15
- import { clearRateLimit, peekRateLimit, recordRateLimit, resolveAdminAuth } from "../../../core";
5
+ import {
6
+ auditActor,
7
+ clearRateLimit,
8
+ enforcedSsoProvider,
9
+ getAdminAuth,
10
+ loadAuthUser,
11
+ peekRateLimit,
12
+ recordRateLimit,
13
+ resolveAdminAuth,
14
+ } from "../../../core";
15
+ import { authResponse, readJson, redirectWithCookies } from "./_better-auth";
16
16
 
17
17
  export const prerender = false;
18
18
 
@@ -24,27 +24,15 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
24
24
  const isJson = contentType.includes("application/json");
25
25
  const auth = resolveAdminAuth(config);
26
26
 
27
- const rateLimited = (retryAfterMs: number) => {
28
- if (isJson) {
29
- return Response.json(
30
- { error: "Too many login attempts. Try again later." },
31
- {
32
- status: 429,
33
- headers: { "Retry-After": String(Math.ceil(retryAfterMs / 1000)) },
34
- },
35
- );
36
- }
37
- return new Response(null, { status: 303, headers: { Location: "/admin/login?error=rate-limited" } });
38
- };
27
+ const fail = (error: string, status: number, message: string, headers?: HeadersInit) =>
28
+ isJson
29
+ ? Response.json({ error: message }, { status, headers })
30
+ : new Response(null, { status: 303, headers: { Location: `/admin/login?error=${error}` } });
39
31
 
40
- if (!auth.password.enabled) {
41
- if (isJson) return Response.json({ error: "Password login is disabled." }, { status: 404 });
42
- return new Response(null, { status: 303, headers: { Location: "/admin/login?error=disabled" } });
43
- }
32
+ if (!auth.password.enabled) return fail("disabled", 404, "Password login is disabled.");
44
33
 
45
34
  let email: string;
46
35
  let password: string;
47
-
48
36
  if (isJson) {
49
37
  const body = await request.json();
50
38
  email = String(body.email ?? "");
@@ -55,9 +43,18 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
55
43
  password = String(formData.get("password") ?? "");
56
44
  }
57
45
 
58
- if (!email || !password) {
59
- if (isJson) return Response.json({ error: "Email and password are required." }, { status: 400 });
60
- return new Response(null, { status: 303, headers: { Location: "/admin/login?error=missing" } });
46
+ if (!email || !password) return fail("missing", 400, "Email and password are required.");
47
+
48
+ // Domain-bound users sign in through their provider. Decided by domain alone, so it
49
+ // reveals nothing about which accounts exist.
50
+ const enforcing = enforcedSsoProvider(auth, email);
51
+ if (enforcing) {
52
+ return isJson
53
+ ? Response.json({ error: `Sign in with ${enforcing.label}.`, sso: enforcing.id }, { status: 403 })
54
+ : new Response(null, {
55
+ status: 303,
56
+ headers: { Location: `/admin/login?error=sso-required&sso=${enforcing.id}` },
57
+ });
61
58
  }
62
59
 
63
60
  // Rate limit FAILED logins only: peek (read-only) before verifying, record on failure,
@@ -66,107 +63,60 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
66
63
  // can't reset the throttle and keep spraying other accounts.
67
64
  const emailKey = email.toLowerCase();
68
65
  const opts = { max: MAX_ATTEMPTS, windowMs: WINDOW_MS, failClosed: true };
69
- const ipPeek = await peekRateLimit("login:ip", clientAddress, opts);
70
- if (!ipPeek.ok) return rateLimited(ipPeek.retryAfterMs);
71
- const emailPeek = await peekRateLimit("login:email", emailKey, opts);
72
- if (!emailPeek.ok) return rateLimited(emailPeek.retryAfterMs);
73
-
74
- const recordFailure = async () => {
75
- await recordRateLimit("login:ip", clientAddress, opts);
76
- await recordRateLimit("login:email", emailKey, opts);
77
- };
78
-
79
- const db = await getDb();
80
- const schema = await import("virtual:kide/schema");
81
- const tables = schema.cmsTables as Record<string, { main: any }>;
82
-
83
- if (!tables.users) {
84
- return Response.json({ error: "Users collection not configured." }, { status: 500 });
66
+ for (const [bucket, key] of [
67
+ ["login:ip", clientAddress],
68
+ ["login:email", emailKey],
69
+ ] as const) {
70
+ const peek = await peekRateLimit(bucket, key, opts);
71
+ if (!peek.ok) {
72
+ return fail("rate-limited", 429, "Too many login attempts. Try again later.", {
73
+ "Retry-After": String(Math.ceil(peek.retryAfterMs / 1000)),
74
+ });
75
+ }
85
76
  }
86
77
 
87
- const rows = await db.select().from(tables.users.main).where(eq(tables.users.main.email, email)).limit(1);
78
+ const betterAuth = await getAdminAuth(request);
79
+ const response = await authResponse(() =>
80
+ betterAuth.api.signInEmail({
81
+ body: { email, password, rememberMe: true },
82
+ headers: request.headers,
83
+ asResponse: true,
84
+ }),
85
+ );
86
+ const body = await readJson(response);
88
87
  const requestMeta = auditRequestMeta(request);
89
88
 
90
- if (rows.length === 0) {
91
- // Burn the same PBKDF2 cost as a real verification so an unknown email can't be
92
- // told apart from a wrong password by response time (the failure response and
93
- // the limiter bookkeeping are already identical).
94
- await hashPassword(password).catch(() => {});
95
- await recordFailure();
96
- logAudit({
97
- action: "auth.login_failed",
98
- resourceType: "session",
99
- attemptedEmail: email,
100
- ...requestMeta,
101
- });
102
- if (contentType.includes("application/json")) {
103
- return Response.json({ error: "Invalid credentials." }, { status: 401 });
104
- }
105
- return new Response(null, {
106
- status: 303,
107
- headers: { Location: "/admin/login?error=invalid" },
108
- });
89
+ if (!response.ok) {
90
+ await recordRateLimit("login:ip", clientAddress, opts);
91
+ await recordRateLimit("login:email", emailKey, opts);
92
+ logAudit({ action: "auth.login_failed", resourceType: "session", attemptedEmail: email, ...requestMeta });
93
+ return fail("invalid", 401, "Invalid credentials.");
109
94
  }
110
95
 
111
- const user = rows[0] as Record<string, unknown>;
112
- const storedHash = String(user.password ?? "");
113
-
114
- let valid = false;
115
- try {
116
- valid = await verifyPassword(storedHash, password);
117
- } catch {
118
- // valid remains false
119
- }
96
+ await clearRateLimit("login:email", emailKey);
120
97
 
121
- if (!valid) {
122
- await recordFailure();
123
- logAudit({
124
- action: "auth.login_failed",
125
- resourceType: "session",
126
- attemptedEmail: email,
127
- ...requestMeta,
128
- });
129
- if (contentType.includes("application/json")) {
130
- return Response.json({ error: "Invalid credentials." }, { status: 401 });
98
+ // Password accepted, second factor pending: Better Auth set a short-lived two-factor cookie.
99
+ if (body?.twoFactorRedirect) {
100
+ if (isJson) {
101
+ const pending = Response.json({ twoFactorRequired: true });
102
+ for (const cookie of response.headers.getSetCookie()) pending.headers.append("Set-Cookie", cookie);
103
+ return pending;
131
104
  }
132
- return new Response(null, {
133
- status: 303,
134
- headers: { Location: "/admin/login?error=invalid" },
135
- });
105
+ return redirectWithCookies("/admin/login/verify", response);
136
106
  }
137
107
 
138
- // Success — clear this account's failed-login budget (but not the IP bucket).
139
- await clearRateLimit("login:email", emailKey);
140
-
141
- const session = await createSession(String(user._id));
142
-
108
+ const userId = (body?.user as { id?: string } | undefined)?.id;
143
109
  logAudit({
144
110
  action: "auth.login",
145
111
  resourceType: "session",
146
- resourceId: await tokenReference(session.token),
147
- actor: {
148
- id: String(user._id),
149
- email: String(user.email ?? ""),
150
- role: String(user.role ?? ""),
151
- },
112
+ actor: auditActor(userId ? await loadAuthUser(userId) : null),
152
113
  ...requestMeta,
153
114
  });
154
115
 
155
- if (contentType.includes("application/json")) {
156
- return new Response(JSON.stringify({ ok: true }), {
157
- status: 200,
158
- headers: {
159
- "Content-Type": "application/json",
160
- "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
161
- },
162
- });
116
+ if (isJson) {
117
+ const ok = Response.json({ ok: true });
118
+ for (const cookie of response.headers.getSetCookie()) ok.headers.append("Set-Cookie", cookie);
119
+ return ok;
163
120
  }
164
-
165
- return new Response(null, {
166
- status: 303,
167
- headers: {
168
- Location: "/admin",
169
- "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
170
- },
171
- });
121
+ return redirectWithCookies("/admin", response);
172
122
  };
@@ -1,42 +1,27 @@
1
1
  import type { APIRoute } from "astro";
2
2
 
3
- import { auditRequestMeta, clearSessionCookie, destroySession, logAudit, tokenReference } from "virtual:kide/runtime";
3
+ import { auditRequestMeta, logAudit } from "virtual:kide/runtime";
4
+ import { auditActor, getAdminAuth, resolveAdminSession } from "../../../core";
5
+ import { authResponse } from "./_better-auth";
4
6
 
5
7
  export const prerender = false;
6
8
 
7
- export const POST: APIRoute = async ({ request, locals }) => {
8
- const cookieHeader = request.headers.get("cookie") ?? "";
9
- const match = cookieHeader.match(/cms_session=([^;]+)/);
9
+ export const POST: APIRoute = async ({ request }) => {
10
+ const session = await resolveAdminSession(request);
11
+ const auth = await getAdminAuth(request);
12
+ const response = await authResponse(() => auth.api.signOut({ headers: request.headers, asResponse: true }));
10
13
 
11
- if (match) {
12
- await destroySession(match[1]);
13
- }
14
-
15
- const user = locals.user;
16
14
  logAudit({
17
15
  action: "auth.logout",
18
16
  resourceType: "session",
19
- resourceId: match ? await tokenReference(match[1]) : null,
20
- actor: user ? { id: user.id, email: user.email, role: user.role } : null,
17
+ actor: auditActor(session?.user ?? null),
21
18
  ...auditRequestMeta(request),
22
19
  });
23
20
 
24
21
  const contentType = request.headers.get("content-type") ?? "";
25
- if (contentType.includes("application/json")) {
26
- return new Response(JSON.stringify({ ok: true }), {
27
- status: 200,
28
- headers: {
29
- "Content-Type": "application/json",
30
- "Set-Cookie": clearSessionCookie(),
31
- },
32
- });
33
- }
34
-
35
- return new Response(null, {
36
- status: 303,
37
- headers: {
38
- Location: "/admin/login",
39
- "Set-Cookie": clearSessionCookie(),
40
- },
41
- });
22
+ const result = contentType.includes("application/json")
23
+ ? Response.json({ ok: true })
24
+ : new Response(null, { status: 303, headers: { Location: "/admin/login" } });
25
+ for (const cookie of response.headers.getSetCookie()) result.headers.append("Set-Cookie", cookie);
26
+ return result;
42
27
  };
@@ -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
  };