@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
@@ -7,18 +7,30 @@ import {
7
7
  hitRateLimit,
8
8
  createInvite,
9
9
  consumeInvite,
10
+ validateInvite,
10
11
  hashPassword,
11
- createSession,
12
- setSessionCookie,
13
- getSessionUser,
14
12
  logAudit,
15
13
  tokenReference,
16
14
  } from "virtual:kide/runtime";
17
15
  import { sendInviteEmail, isEmailConfigured } from "virtual:kide/email";
18
- import { MIN_PASSWORD_LENGTH, publicOrigin } from "../../../core";
16
+ import config from "virtual:kide/config";
17
+ import {
18
+ auditActor,
19
+ enforcedSsoProvider,
20
+ getAdminAuth,
21
+ loadAuthUser,
22
+ MIN_PASSWORD_LENGTH,
23
+ publicOrigin,
24
+ resolveAdminAuth,
25
+ resolveAdminSession,
26
+ setCredentialPassword,
27
+ } from "../../../core";
28
+ import { authResponse, redirectWithCookies } from "./_better-auth";
19
29
 
20
30
  export const prerender = false;
21
31
 
32
+ const seeOther = (location: string) => new Response(null, { status: 303, headers: { Location: location } });
33
+
22
34
  export const POST: APIRoute = async ({ request, clientAddress }) => {
23
35
  const formData = await request.formData();
24
36
  const action = String(formData.get("_action") ?? "create");
@@ -31,42 +43,28 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
31
43
  };
32
44
 
33
45
  async function handleCreate(formData: FormData, request: Request) {
34
- const user = await getSessionUser(request);
35
- if (!user || user.role !== "admin") {
36
- return new Response(null, {
37
- status: 303,
38
- headers: { Location: "/admin/users?_toast=error&_msg=Only+admins+can+invite+users" },
39
- });
46
+ const session = await resolveAdminSession(request);
47
+ if (!session || session.user.role !== "admin") {
48
+ return seeOther("/admin/users?_toast=error&_msg=Only+admins+can+invite+users");
40
49
  }
41
50
 
42
- const email = String(formData.get("email") ?? "").trim();
51
+ const email = String(formData.get("email") ?? "")
52
+ .trim()
53
+ .toLowerCase();
43
54
  const role = String(formData.get("role") ?? "editor");
44
55
  const name = String(formData.get("name") ?? email.split("@")[0]).trim();
45
56
 
46
- if (!email) {
47
- return new Response(null, {
48
- status: 303,
49
- headers: { Location: "/admin/users/new?_toast=error&_msg=Email+is+required" },
50
- });
51
- }
57
+ if (!email) return seeOther("/admin/users/new?_toast=error&_msg=Email+is+required");
52
58
 
53
59
  const db = await getDb();
54
60
  const schema = await import("virtual:kide/schema");
55
61
  const tables = schema.cmsTables as Record<string, { main: any }>;
56
- if (!tables.users) {
57
- return new Response(null, {
58
- status: 303,
59
- headers: { Location: "/admin/users?_toast=error&_msg=Users+collection+not+configured" },
60
- });
61
- }
62
+ if (!tables.users) return seeOther("/admin/users?_toast=error&_msg=Users+collection+not+configured");
62
63
 
63
64
  // Check for duplicate email
64
65
  const existing = await db.select().from(tables.users.main).where(eq(tables.users.main.email, email)).limit(1);
65
66
  if (existing.length > 0) {
66
- return new Response(null, {
67
- status: 303,
68
- headers: { Location: "/admin/users/new?_toast=error&_msg=A+user+with+this+email+already+exists" },
69
- });
67
+ return seeOther("/admin/users/new?_toast=error&_msg=A+user+with+this+email+already+exists");
70
68
  }
71
69
 
72
70
  const { nanoid } = await import("nanoid");
@@ -77,32 +75,35 @@ async function handleCreate(formData: FormData, request: Request) {
77
75
  _id: id,
78
76
  name,
79
77
  email,
80
- password: "",
81
78
  role,
79
+ // The admin vouched for the address — SSO sign-ins may link to it.
80
+ _authEmailVerified: true,
82
81
  _createdAt: now,
83
82
  _updatedAt: now,
84
83
  });
85
84
 
86
- const invite = await createInvite(id);
87
- // Anchored on the trusted origin, not the Host header — see publicOrigin.
88
- const inviteUrl = `${publicOrigin(request)}/admin/invite?token=${encodeURIComponent(invite.token)}`;
89
-
90
- let emailSent = false;
91
- if (isEmailConfigured()) {
92
- emailSent = await sendInviteEmail(email, inviteUrl);
85
+ // Without password sign-in (or for a domain bound to an SSO provider) there's nothing
86
+ // to set up: the invitee signs in with SSO.
87
+ const auth = resolveAdminAuth(config);
88
+ const origin = publicOrigin(request);
89
+ let inviteToken: string | null = null;
90
+ let inviteUrl = `${origin}/admin/login`;
91
+ if (auth.password.enabled && !enforcedSsoProvider(auth, email)) {
92
+ inviteToken = (await createInvite(id)).token;
93
+ inviteUrl = `${origin}/admin/invite?token=${encodeURIComponent(inviteToken)}`;
93
94
  }
94
95
 
96
+ const emailSent = isEmailConfigured() ? await sendInviteEmail(email, inviteUrl) : false;
97
+
95
98
  const params = new URLSearchParams({
96
99
  _toast: "success",
97
100
  _msg: emailSent ? `Invitation sent to ${email}` : "User created",
98
- inviteToken: invite.token,
99
101
  emailSent: String(emailSent),
100
102
  });
103
+ if (inviteToken) params.set("inviteToken", inviteToken);
104
+ else params.set("signInInvite", "1");
101
105
 
102
- return new Response(null, {
103
- status: 303,
104
- headers: { Location: `/admin/users/${id}?${params}` },
105
- });
106
+ return seeOther(`/admin/users/${id}?${params}`);
106
107
  }
107
108
 
108
109
  async function handleAccept(formData: FormData, request: Request, clientAddress: string) {
@@ -111,55 +112,32 @@ async function handleAccept(formData: FormData, request: Request, clientAddress:
111
112
  const password = String(formData.get("password") ?? "");
112
113
  const confirmPassword = String(formData.get("confirmPassword") ?? "");
113
114
 
114
- if (!token) {
115
- return new Response(null, {
116
- status: 303,
117
- headers: { Location: "/admin/invite?error=invalid" },
118
- });
119
- }
115
+ if (!token) return seeOther("/admin/invite?error=invalid");
120
116
 
121
117
  // Key on Astro's clientAddress (trusted), not the spoofable X-Forwarded-For header.
122
118
  const opts = { max: 10, windowMs: 15 * 60 * 1000, failClosed: true };
123
119
  const ipLimit = await hitRateLimit("invite:ip", clientAddress, opts);
124
- if (!ipLimit.ok) {
125
- return new Response(null, { status: 303, headers: { Location: "/admin/invite?error=invalid" } });
126
- }
120
+ if (!ipLimit.ok) return seeOther("/admin/invite?error=invalid");
127
121
 
128
122
  // The token is caller-supplied form input: encode it so it can't smuggle extra
129
123
  // query params or header-breaking characters into the redirect.
130
124
  const encodedToken = encodeURIComponent(token);
131
125
 
132
- if (!name || !password) {
133
- return new Response(null, {
134
- status: 303,
135
- headers: { Location: `/admin/invite?token=${encodedToken}&error=missing` },
136
- });
137
- }
138
-
139
- if (password !== confirmPassword) {
140
- return new Response(null, {
141
- status: 303,
142
- headers: { Location: `/admin/invite?token=${encodedToken}&error=password` },
143
- });
144
- }
126
+ if (!name || !password) return seeOther(`/admin/invite?token=${encodedToken}&error=missing`);
127
+ if (password !== confirmPassword) return seeOther(`/admin/invite?token=${encodedToken}&error=password`);
128
+ if (password.length < MIN_PASSWORD_LENGTH) return seeOther(`/admin/invite?token=${encodedToken}&error=short`);
145
129
 
146
- if (password.length < MIN_PASSWORD_LENGTH) {
147
- return new Response(null, {
148
- status: 303,
149
- headers: { Location: `/admin/invite?token=${encodedToken}&error=short` },
150
- });
151
- }
130
+ // An invite issued before the user's domain was bound to an SSO provider can't set a password.
131
+ const pending = await validateInvite(token);
132
+ const invitee = pending ? await loadAuthUser(pending.userId) : null;
133
+ const enforcing = invitee ? enforcedSsoProvider(resolveAdminAuth(config), invitee.email) : null;
134
+ if (enforcing) return seeOther(`/admin/login?error=sso-required&sso=${enforcing.id}`);
152
135
 
153
136
  // Hash before claiming: the token is single-use, so run the fallible work first, then
154
137
  // consume as the atomic single-winner gate against a double-submit.
155
138
  const hashedPassword = await hashPassword(password);
156
139
  const invite = await consumeInvite(token);
157
- if (!invite) {
158
- return new Response(null, {
159
- status: 303,
160
- headers: { Location: "/admin/invite?error=expired" },
161
- });
162
- }
140
+ if (!invite) return seeOther("/admin/invite?error=expired");
163
141
 
164
142
  const db = await getDb();
165
143
  const schema = await import("virtual:kide/schema");
@@ -167,37 +145,27 @@ async function handleAccept(formData: FormData, request: Request, clientAddress:
167
145
 
168
146
  await db
169
147
  .update(tables.users.main)
170
- .set({ name, password: hashedPassword, _updatedAt: new Date().toISOString() })
148
+ .set({ name, _updatedAt: new Date().toISOString() })
171
149
  .where(eq(tables.users.main._id, invite.userId));
150
+ await setCredentialPassword(invite.userId, hashedPassword);
172
151
 
173
- const session = await createSession(invite.userId);
174
-
175
- const acceptedUserRows = await db
176
- .select()
177
- .from(tables.users.main)
178
- .where(eq(tables.users.main._id, invite.userId))
179
- .limit(1);
180
- const acceptedUser = acceptedUserRows[0] as Record<string, unknown> | undefined;
181
-
152
+ const acceptedUser = await loadAuthUser(invite.userId);
182
153
  logAudit({
183
154
  action: "auth.invite_accepted",
184
155
  resourceType: "invite",
185
156
  resourceId: await tokenReference(token),
186
- actor: acceptedUser
187
- ? {
188
- id: String(acceptedUser._id),
189
- email: String(acceptedUser.email ?? ""),
190
- role: String(acceptedUser.role ?? ""),
191
- }
192
- : null,
157
+ actor: auditActor(acceptedUser),
193
158
  ...auditRequestMeta(request),
194
159
  });
195
160
 
196
- return new Response(null, {
197
- status: 303,
198
- headers: {
199
- Location: "/admin",
200
- "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
201
- },
202
- });
161
+ if (!acceptedUser) return seeOther("/admin/login");
162
+ const auth = await getAdminAuth(request);
163
+ const signIn = await authResponse(() =>
164
+ auth.api.signInEmail({
165
+ body: { email: acceptedUser.email, password, rememberMe: true },
166
+ headers: request.headers,
167
+ asResponse: true,
168
+ }),
169
+ );
170
+ return redirectWithCookies(signIn.ok ? "/admin" : "/admin/login", signIn);
203
171
  }
@@ -0,0 +1,50 @@
1
+ import type { APIRoute } from "astro";
2
+
3
+ import { auditRequestMeta, hitRateLimit, logAudit } from "virtual:kide/runtime";
4
+ import { auditActor, getAdminAuth, loadAuthUser } from "../../../../core";
5
+ import { authResponse, readJson, redirectWithCookies } from "../_better-auth";
6
+
7
+ export const prerender = false;
8
+
9
+ export const POST: APIRoute = async ({ request, clientAddress }) => {
10
+ const formData = await request.formData();
11
+ const code = String(formData.get("code") ?? "").replace(/\s+/g, "");
12
+ const useBackupCode = formData.get("method") === "backup";
13
+ const trustDevice = formData.get("trustDevice") === "on";
14
+ const back = (error: string) => `/admin/login/verify?error=${error}${useBackupCode ? "&method=backup" : ""}`;
15
+
16
+ if (!code) return new Response(null, { status: 303, headers: { Location: back("missing") } });
17
+
18
+ // Better Auth also locks the user's second factor after repeated failures.
19
+ const limit = await hitRateLimit("two-factor:ip", clientAddress, {
20
+ max: 10,
21
+ windowMs: 15 * 60 * 1000,
22
+ failClosed: true,
23
+ });
24
+ if (!limit.ok) return new Response(null, { status: 303, headers: { Location: back("rate-limited") } });
25
+
26
+ const auth = await getAdminAuth(request);
27
+ const response = await authResponse(() =>
28
+ useBackupCode
29
+ ? auth.api.verifyBackupCode({ body: { code, trustDevice }, headers: request.headers, asResponse: true })
30
+ : auth.api.verifyTOTP({ body: { code, trustDevice }, headers: request.headers, asResponse: true }),
31
+ );
32
+ const body = await readJson(response);
33
+
34
+ if (!response.ok) {
35
+ logAudit({ action: "auth.login_failed", resourceType: "session", ...auditRequestMeta(request) });
36
+ // Without the (10-minute) two-factor cookie the whole sign-in has to restart.
37
+ const pending = /(?:^|;\s*)(?:__Secure-)?kide\.two_factor=/.test(request.headers.get("cookie") ?? "");
38
+ const location = pending ? back("invalid") : "/admin/login?error=two-factor-expired";
39
+ return new Response(null, { status: 303, headers: { Location: location } });
40
+ }
41
+
42
+ const userId = (body?.user as { id?: string } | undefined)?.id;
43
+ logAudit({
44
+ action: "auth.login",
45
+ resourceType: "session",
46
+ actor: auditActor(userId ? await loadAuthUser(userId) : null),
47
+ ...auditRequestMeta(request),
48
+ });
49
+ return redirectWithCookies("/admin", response);
50
+ };
@@ -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
  };