@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.
@@ -0,0 +1,153 @@
1
+ import type { APIRoute } from "astro";
2
+
3
+ import { auditRequestMeta, hitRateLimit, logAudit } from "virtual:kide/runtime";
4
+ import config from "virtual:kide/config";
5
+ import {
6
+ ADMIN_AUTH_BASE_PATH,
7
+ applySsoRoleMapping,
8
+ auditActor,
9
+ extensionAuthEndpoints,
10
+ getAdminAuth,
11
+ getSsoProvider,
12
+ loadAuthUser,
13
+ markSsoVerified,
14
+ mfaRequiredFor,
15
+ resolveAdminAuth,
16
+ resolveAdminSession,
17
+ } from "../../../core";
18
+ import { readJson } from "./_better-auth";
19
+
20
+ export const prerender = false;
21
+
22
+ // The part of Better Auth's HTTP surface the admin uses. Everything else (sign-up,
23
+ // email change, account deletion, …) stays unreachable; Kide's own routes cover
24
+ // password sign-in, reset and invites with its rate limits and audit trail.
25
+ const allowedEndpoint = (method: string, path: string) => {
26
+ const auth = resolveAdminAuth(config);
27
+ if (method === "GET" && /^\/callback\/[a-z0-9-]+$/.test(path)) return true;
28
+ if (auth.mfa.totp && method === "POST") {
29
+ if (
30
+ [
31
+ "/two-factor/enable",
32
+ "/two-factor/disable",
33
+ "/two-factor/verify-totp",
34
+ "/two-factor/generate-backup-codes",
35
+ ].includes(path)
36
+ ) {
37
+ return true;
38
+ }
39
+ }
40
+ if (auth.mfa.passkeys) {
41
+ if (
42
+ method === "GET" &&
43
+ [
44
+ "/passkey/generate-register-options",
45
+ "/passkey/generate-authenticate-options",
46
+ "/passkey/list-user-passkeys",
47
+ ].includes(path)
48
+ ) {
49
+ return true;
50
+ }
51
+ if (
52
+ method === "POST" &&
53
+ ["/passkey/verify-registration", "/passkey/verify-authentication", "/passkey/delete-passkey"].includes(path)
54
+ ) {
55
+ return true;
56
+ }
57
+ }
58
+ // Plugins the project added through `admin.auth.betterAuth` bring their own endpoints.
59
+ return extensionAuthEndpoints(config).some((rule) => rule.methods.includes(method) && rule.pattern.test(path));
60
+ };
61
+
62
+ const RATE_LIMITED = new Set(["/two-factor/verify-totp", "/passkey/verify-authentication"]);
63
+
64
+ const handle: APIRoute = async ({ request, clientAddress }) => {
65
+ const url = new URL(request.url);
66
+ const path = url.pathname.slice(ADMIN_AUTH_BASE_PATH.length);
67
+ if (!allowedEndpoint(request.method, path)) return Response.json({ error: "Not found" }, { status: 404 });
68
+
69
+ if (RATE_LIMITED.has(path)) {
70
+ const limit = await hitRateLimit(`auth:${path}`, clientAddress, {
71
+ max: 10,
72
+ windowMs: 15 * 60 * 1000,
73
+ failClosed: true,
74
+ });
75
+ if (!limit.ok) return Response.json({ error: "Too many attempts. Try again later." }, { status: 429 });
76
+ }
77
+
78
+ // `mfa.require` users can't switch their second factor off.
79
+ if (path === "/two-factor/disable") {
80
+ const session = await resolveAdminSession(request);
81
+ if (session && mfaRequiredFor(resolveAdminAuth(config), session.user.role)) {
82
+ return Response.json({ error: "Two-factor authentication is required for your role." }, { status: 403 });
83
+ }
84
+ }
85
+
86
+ const auth = await getAdminAuth(request);
87
+ const response = await auth.handler(request);
88
+
89
+ if (path.startsWith("/callback/")) return finishSsoCallback(path.slice("/callback/".length), request, response);
90
+
91
+ if (path === "/passkey/verify-authentication" && response.ok) {
92
+ const body = await readJson(response);
93
+ const userId = body?.session?.userId ?? body?.user?.id;
94
+ logAudit({
95
+ action: "auth.login",
96
+ resourceType: "session",
97
+ actor: auditActor(userId ? await loadAuthUser(String(userId)) : null),
98
+ ...auditRequestMeta(request),
99
+ });
100
+ // The body carries the session token; the HttpOnly cookie is all the page needs.
101
+ const ok = Response.json({ ok: true });
102
+ for (const cookie of response.headers.getSetCookie()) ok.headers.append("Set-Cookie", cookie);
103
+ return ok;
104
+ }
105
+ return response;
106
+ };
107
+
108
+ /**
109
+ * Better Auth answers a refused SSO sign-in (not invited, wrong domain) with JSON, and an
110
+ * OAuth error with a redirect. Either way the editor should land on the login page with a
111
+ * readable message; on success, apply the provider's role mapping before entering.
112
+ */
113
+ async function finishSsoCallback(providerId: string, request: Request, response: Response) {
114
+ const location = response.headers.get("location");
115
+ const isRedirect = response.status >= 300 && response.status < 400 && location;
116
+
117
+ if (!isRedirect) {
118
+ const body = await readJson(response);
119
+ const code = String(body?.code ?? "sso_failed").toLowerCase();
120
+ logAudit({ action: "auth.login_failed", resourceType: "session", ...auditRequestMeta(request) });
121
+ return new Response(null, { status: 303, headers: { Location: `/admin/login?error=${encodeURIComponent(code)}` } });
122
+ }
123
+
124
+ const target = new URL(location, request.url);
125
+ if (target.searchParams.has("error")) {
126
+ logAudit({ action: "auth.login_failed", resourceType: "session", ...auditRequestMeta(request) });
127
+ return response;
128
+ }
129
+
130
+ const provider = getSsoProvider(config, providerId);
131
+ const sessionCookie = response.headers
132
+ .getSetCookie()
133
+ .map((cookie) => cookie.split(";")[0])
134
+ .find((cookie) => /^(?:__Secure-)?kide\.session_token=/.test(cookie));
135
+ if (provider && sessionCookie) {
136
+ const auth = await getAdminAuth(request);
137
+ const session = await auth.api.getSession({ headers: new Headers({ cookie: sessionCookie }) });
138
+ if (session) {
139
+ await markSsoVerified(session.user.id, provider.id);
140
+ await applySsoRoleMapping(provider, session.user.id);
141
+ logAudit({
142
+ action: "auth.login",
143
+ resourceType: "session",
144
+ actor: auditActor(await loadAuthUser(session.user.id)),
145
+ ...auditRequestMeta(request),
146
+ });
147
+ }
148
+ }
149
+ return response;
150
+ }
151
+
152
+ export const GET = handle;
153
+ export const POST = handle;
@@ -0,0 +1,26 @@
1
+ import { isAPIError } from "better-auth/api";
2
+
3
+ /** Run a Better Auth `asResponse` call; an APIError thrown on the way becomes its JSON response. */
4
+ export const authResponse = async (call: () => Promise<Response>): Promise<Response> => {
5
+ try {
6
+ return await call();
7
+ } catch (error) {
8
+ if (!isAPIError(error)) throw error;
9
+ return Response.json(error.body ?? { message: error.message }, { status: error.statusCode });
10
+ }
11
+ };
12
+
13
+ export const readJson = async (response: Response): Promise<Record<string, any> | null> => {
14
+ try {
15
+ return await response.clone().json();
16
+ } catch {
17
+ return null;
18
+ }
19
+ };
20
+
21
+ /** 303 to `location`, carrying any cookies Better Auth set (session, two-factor, OAuth state). */
22
+ export const redirectWithCookies = (location: string, from?: Response | null) => {
23
+ const response = new Response(null, { status: 303, headers: { Location: location } });
24
+ for (const cookie of from?.headers.getSetCookie() ?? []) response.headers.append("Set-Cookie", cookie);
25
+ return response;
26
+ };
@@ -0,0 +1,69 @@
1
+ import type { APIRoute } from "astro";
2
+
3
+ import { auditRequestMeta, hitRateLimit, logAudit } from "virtual:kide/runtime";
4
+ import { auditActor, getAdminAuth, MIN_PASSWORD_LENGTH, resolveAdminSession } from "../../../core";
5
+ import { authResponse, redirectWithCookies } from "./_better-auth";
6
+
7
+ export const prerender = false;
8
+
9
+ const back = (params: Record<string, string>) =>
10
+ new Response(null, { status: 303, headers: { Location: `/admin/account?${new URLSearchParams(params)}` } });
11
+
12
+ export const POST: APIRoute = async ({ request }) => {
13
+ const session = await resolveAdminSession(request);
14
+ if (!session) return new Response(null, { status: 303, headers: { Location: "/admin/login" } });
15
+
16
+ const formData = await request.formData();
17
+ const action = String(formData.get("_action") ?? "");
18
+ const auth = await getAdminAuth(request);
19
+
20
+ if (action === "change-password") {
21
+ const limit = await hitRateLimit("account:password", session.user.id, { max: 10, windowMs: 15 * 60 * 1000 });
22
+ if (!limit.ok) return back({ _toast: "error", _msg: "Too many attempts. Try again later." });
23
+
24
+ const currentPassword = String(formData.get("currentPassword") ?? "");
25
+ const newPassword = String(formData.get("newPassword") ?? "");
26
+ const confirmPassword = String(formData.get("confirmPassword") ?? "");
27
+ if (!currentPassword || !newPassword) return back({ _toast: "error", _msg: "Fill in every password field." });
28
+ if (newPassword !== confirmPassword) return back({ _toast: "error", _msg: "The new passwords don't match." });
29
+ if (newPassword.length < MIN_PASSWORD_LENGTH) {
30
+ return back({ _toast: "error", _msg: `Use at least ${MIN_PASSWORD_LENGTH} characters.` });
31
+ }
32
+
33
+ const response = await authResponse(() =>
34
+ auth.api.changePassword({
35
+ body: { currentPassword, newPassword, revokeOtherSessions: true },
36
+ headers: request.headers,
37
+ asResponse: true,
38
+ }),
39
+ );
40
+ if (!response.ok) return back({ _toast: "error", _msg: "Your current password is incorrect." });
41
+
42
+ logAudit({
43
+ action: "auth.password_changed",
44
+ resourceType: "user",
45
+ resourceCollection: "users",
46
+ resourceId: session.user.id,
47
+ actor: auditActor(session.user),
48
+ ...auditRequestMeta(request),
49
+ });
50
+ // Revoking other sessions re-issues this one — keep the new cookie.
51
+ return redirectWithCookies(
52
+ `/admin/account?${new URLSearchParams({ _toast: "success", _msg: "Password changed. Other devices were signed out." })}`,
53
+ response,
54
+ );
55
+ }
56
+
57
+ if (action === "revoke-other-sessions") {
58
+ await authResponse(() => auth.api.revokeOtherSessions({ headers: request.headers, asResponse: true }));
59
+ logAudit({
60
+ action: "auth.sessions_revoked",
61
+ resourceType: "session",
62
+ actor: auditActor(session.user),
63
+ ...auditRequestMeta(request),
64
+ });
65
+ return back({ _toast: "success", _msg: "Signed out on every other device." });
66
+ }
67
+
68
+ return back({ _toast: "error", _msg: "Unknown action." });
69
+ };
@@ -2,16 +2,17 @@ import type { APIRoute } from "astro";
2
2
  import { eq } from "drizzle-orm";
3
3
 
4
4
  import { getDb } from "virtual:kide/db";
5
+ import { auditRequestMeta, hitRateLimit, logAudit } from "virtual:kide/runtime";
5
6
  import {
6
- auditRequestMeta,
7
- hitRateLimit,
8
- createPasswordReset,
9
- getEmail,
10
- logAudit,
11
- tokenReference,
12
- } from "virtual:kide/runtime";
13
- import { publicOrigin, resolveAdminAuth } from "../../../core";
7
+ auditActor,
8
+ enforcedSsoProvider,
9
+ getAdminAuth,
10
+ listSignInMethods,
11
+ loadAuthUser,
12
+ resolveAdminAuth,
13
+ } from "../../../core";
14
14
  import config from "virtual:kide/config";
15
+ import { authResponse } from "./_better-auth";
15
16
 
16
17
  export const prerender = false;
17
18
 
@@ -20,7 +21,9 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
20
21
  if (!auth.password.forgotPassword) return Response.json({ error: "Not found" }, { status: 404 });
21
22
 
22
23
  const formData = await request.formData();
23
- const email = String(formData.get("email") ?? "").trim();
24
+ const email = String(formData.get("email") ?? "")
25
+ .trim()
26
+ .toLowerCase();
24
27
  const redirect = () =>
25
28
  new Response(null, {
26
29
  status: 303,
@@ -28,6 +31,8 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
28
31
  });
29
32
 
30
33
  if (!email) return redirect();
34
+ // Domain-bound users have no password to recover; their provider is the way in.
35
+ if (enforcedSsoProvider(auth, email)) return redirect();
31
36
 
32
37
  // Throttle by IP, then email. On limit, return the same "sent" response (never reveal)
33
38
  // and skip the email send — fail-open so a DB hiccup can't block recovery. Check the IP
@@ -35,7 +40,7 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
35
40
  // inserting new limiter rows by varying the email.
36
41
  const opts = { max: 5, windowMs: 15 * 60 * 1000, failClosed: false };
37
42
  if (!(await hitRateLimit("forgot:ip", clientAddress, opts)).ok) return redirect();
38
- if (!(await hitRateLimit("forgot:email", email.toLowerCase(), opts)).ok) return redirect();
43
+ if (!(await hitRateLimit("forgot:email", email, opts)).ok) return redirect();
39
44
 
40
45
  const db = await getDb();
41
46
  const schema = await import("virtual:kide/schema");
@@ -43,36 +48,37 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
43
48
  if (!tables.users) return redirect();
44
49
 
45
50
  const rows = await db.select().from(tables.users.main).where(eq(tables.users.main.email, email)).limit(1);
46
- if (rows.length === 0) {
51
+ const user = rows.length > 0 ? await loadAuthUser(String((rows[0] as Record<string, unknown>)._id)) : null;
52
+ const audit = () =>
47
53
  logAudit({
48
54
  action: "auth.password_reset_requested",
49
55
  resourceType: "password_reset",
50
- attemptedEmail: email,
56
+ ...(user ? { actor: auditActor(user) } : { attemptedEmail: email }),
51
57
  ...auditRequestMeta(request),
52
58
  });
59
+
60
+ if (!user) {
61
+ audit();
53
62
  return redirect();
54
63
  }
55
64
 
56
- const user = rows[0] as Record<string, unknown>;
57
- const reset = await createPasswordReset(String(user._id));
58
- // Anchored on the trusted origin, not the Host header — see publicOrigin.
59
- const resetUrl = new URL("/admin/reset-password", publicOrigin(request));
60
- resetUrl.searchParams.set("token", reset.token);
61
-
62
- const emailAdapter = getEmail();
63
- await emailAdapter.sendPasswordResetEmail?.(String(user.email), resetUrl.toString());
64
-
65
- logAudit({
66
- action: "auth.password_reset_requested",
67
- resourceType: "password_reset",
68
- resourceId: await tokenReference(reset.token),
69
- actor: {
70
- id: String(user._id),
71
- email: String(user.email ?? ""),
72
- role: String(user.role ?? ""),
73
- },
74
- ...auditRequestMeta(request),
75
- });
65
+ // SSO-only accounts don't get a password through the back door: their identity
66
+ // provider (and its offboarding) stays the only way in. Invited users who haven't
67
+ // accepted yet have no accounts at all and may reset.
68
+ const methods = await listSignInMethods(user.id);
69
+ if (methods.length > 0 && !methods.includes("credential")) {
70
+ audit();
71
+ return redirect();
72
+ }
76
73
 
74
+ const betterAuth = await getAdminAuth(request);
75
+ await authResponse(() =>
76
+ betterAuth.api.requestPasswordReset({
77
+ body: { email, redirectTo: "/admin/reset-password" },
78
+ headers: request.headers,
79
+ asResponse: true,
80
+ }),
81
+ );
82
+ audit();
77
83
  return redirect();
78
84
  };
@@ -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
+ };