@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.
@@ -5,7 +5,8 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../..
5
5
  import { Input } from "../../admin/components/ui/input";
6
6
  import { Label } from "../../admin/components/ui/label";
7
7
  import { buttonVariants } from "../../admin/components/ui/button";
8
- import { resolveAdminAuth } from "../../core";
8
+ import PasskeySignIn from "../../admin/components/PasskeySignIn";
9
+ import { getSsoProvider, passwordResetDelivery, resolveAdminAuth } from "../../core";
9
10
  import config from "virtual:kide/config";
10
11
 
11
12
  export const prerender = false;
@@ -15,10 +16,33 @@ const ERROR_MESSAGES: Record<string, string> = {
15
16
  missing: "Email and password are required.",
16
17
  disabled: "Password login is disabled.",
17
18
  "rate-limited": "Too many attempts. Try again in a few minutes.",
19
+ "two-factor-expired": "The sign-in took too long. Start again.",
20
+ not_invited: "There's no Kide account for that user. Ask an admin to invite you.",
21
+ domain_not_allowed: "That account's email domain isn't allowed here.",
22
+ account_not_linked:
23
+ "An account with this email exists, but your identity provider didn't confirm the address. Ask an admin to check the SSO setup.",
24
+ signup_disabled: "There's no Kide account for that user. Ask an admin to invite you.",
25
+ "sso-unknown": "That sign-in option doesn't exist.",
26
+ "sso-unavailable": "Single sign-on isn't available right now. Try again later or contact an admin.",
27
+ access_denied: "Sign-in was cancelled.",
28
+ sso_access_revoked: "Your organization account no longer has access. Contact your administrator.",
18
29
  };
19
- const error = Astro.url.searchParams.get("error");
20
- const errorMessage = error ? (ERROR_MESSAGES[error] ?? "Sign-in failed. Try again.") : null;
30
+ const STATUS_MESSAGES: Record<string, string> = {
31
+ "password-reset": "Your password was changed. Sign in with the new one.",
32
+ };
33
+ // Better Auth reports SSO refusals as upper-case codes (NOT_INVITED); Kide's own are kebab-case.
34
+ const rawError = Astro.url.searchParams.get("error");
35
+ const error = rawError && rawError === rawError.toUpperCase() ? rawError.toLowerCase() : rawError;
21
36
  const auth = resolveAdminAuth(config);
37
+ const requiredSso = error === "sso-required" ? getSsoProvider(config, Astro.url.searchParams.get("sso") ?? "") : null;
38
+ const errorMessage = requiredSso
39
+ ? `Your organization signs in with ${requiredSso.label}. Use the button above.`
40
+ : error
41
+ ? (ERROR_MESSAGES[error] ?? "Sign-in failed. Try again.")
42
+ : null;
43
+ const status = Astro.url.searchParams.get("status");
44
+ const statusMessage = status ? (STATUS_MESSAGES[status] ?? null) : null;
45
+ const hasSso = auth.ssoProviders.length > 0;
22
46
  ---
23
47
 
24
48
  <!doctype html>
@@ -37,7 +61,9 @@ const auth = resolveAdminAuth(config);
37
61
  <Card>
38
62
  <CardHeader>
39
63
  <CardTitle>Sign in</CardTitle>
40
- <CardDescription>Enter your credentials to continue</CardDescription>
64
+ <CardDescription>
65
+ {auth.password.enabled ? "Enter your credentials to continue" : "Continue with your organization account"}
66
+ </CardDescription>
41
67
  </CardHeader>
42
68
  <CardContent>
43
69
  {
@@ -47,53 +73,78 @@ const auth = resolveAdminAuth(config);
47
73
  </div>
48
74
  )
49
75
  }
50
- <form method="post" action="/api/cms/auth/login" class="grid gap-4">
51
- {
52
- auth.password.enabled && (
53
- <>
76
+ {
77
+ statusMessage && (
78
+ <div class="border-border bg-muted mb-4 rounded-lg border px-3 py-2 text-sm">{statusMessage}</div>
79
+ )
80
+ }
81
+ {
82
+ hasSso && (
83
+ <div class="grid gap-3">
84
+ {auth.ssoProviders.map((provider) => (
85
+ <a
86
+ class={buttonVariants({
87
+ variant: auth.password.enabled ? "outline" : "default",
88
+ size: "lg",
89
+ className: "w-full",
90
+ })}
91
+ href={`/api/cms/auth/sso/${provider.id}/start`}
92
+ >
93
+ Continue with {provider.label}
94
+ </a>
95
+ ))}
96
+ </div>
97
+ )
98
+ }
99
+ {
100
+ auth.password.enabled && (
101
+ <>
102
+ {hasSso && (
103
+ <div class="text-muted-foreground my-4 flex items-center gap-3 text-xs">
104
+ <div class="bg-border h-px flex-1" />
105
+ <span>or</span>
106
+ <div class="bg-border h-px flex-1" />
107
+ </div>
108
+ )}
109
+ <form method="post" action="/api/cms/auth/login" class="grid gap-4">
54
110
  <div class="grid gap-2">
55
111
  <Label htmlFor="email">Email</Label>
56
- <Input id="email" name="email" type="email" placeholder="admin@example.com" required autoFocus />
112
+ <Input
113
+ id="email"
114
+ name="email"
115
+ type="email"
116
+ placeholder="admin@example.com"
117
+ autoComplete="username webauthn"
118
+ required
119
+ autoFocus={!hasSso}
120
+ />
57
121
  </div>
58
122
  <div class="grid gap-2">
59
123
  <div class="flex items-center justify-between gap-3">
60
124
  <Label htmlFor="password">Password</Label>
61
- {auth.password.forgotPassword && (
125
+ {auth.password.forgotPassword && passwordResetDelivery() && (
62
126
  <a class="text-muted-foreground hover:text-foreground text-xs" href="/admin/forgot-password">
63
127
  Forgot password?
64
128
  </a>
65
129
  )}
66
130
  </div>
67
- <Input id="password" name="password" type="password" placeholder="Enter password" required />
131
+ <Input
132
+ id="password"
133
+ name="password"
134
+ type="password"
135
+ placeholder="Enter password"
136
+ autoComplete="current-password"
137
+ required
138
+ />
68
139
  </div>
69
140
  <button class={buttonVariants({ size: "lg", className: "w-full" })} type="submit">
70
141
  Sign in
71
142
  </button>
72
- </>
73
- )
74
- }
75
- </form>
76
- {
77
- auth.ssoProviders.length > 0 && (
78
- <div class="mt-4 grid gap-3">
79
- {auth.password.enabled && (
80
- <div class="text-muted-foreground flex items-center gap-3 text-xs">
81
- <div class="bg-border h-px flex-1" />
82
- <span>or</span>
83
- <div class="bg-border h-px flex-1" />
84
- </div>
85
- )}
86
- {auth.ssoProviders.map((provider) => (
87
- <a
88
- class={buttonVariants({ variant: "outline", size: "lg", className: "w-full" })}
89
- href={`/api/cms/auth/sso/${provider.id}/start`}
90
- >
91
- Continue with {provider.label}
92
- </a>
93
- ))}
94
- </div>
143
+ </form>
144
+ </>
95
145
  )
96
146
  }
147
+ {auth.mfa.passkeys && <PasskeySignIn client:load />}
97
148
  </CardContent>
98
149
  </Card>
99
150
  </div>
@@ -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,25 +2,33 @@ 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
+ passwordResetDelivery,
13
+ resolveAdminAuth,
14
+ } from "../../../core";
14
15
  import config from "virtual:kide/config";
16
+ import { authResponse } from "./_better-auth";
15
17
 
16
18
  export const prerender = false;
17
19
 
18
20
  export const POST: APIRoute = async ({ request, clientAddress }) => {
19
21
  const auth = resolveAdminAuth(config);
20
22
  if (!auth.password.forgotPassword) return Response.json({ error: "Not found" }, { status: 404 });
23
+ // No way to deliver a link: the page explains that instead of pretending to send one.
24
+ if (!passwordResetDelivery()) {
25
+ return new Response(null, { status: 303, headers: { Location: "/admin/forgot-password" } });
26
+ }
21
27
 
22
28
  const formData = await request.formData();
23
- const email = String(formData.get("email") ?? "").trim();
29
+ const email = String(formData.get("email") ?? "")
30
+ .trim()
31
+ .toLowerCase();
24
32
  const redirect = () =>
25
33
  new Response(null, {
26
34
  status: 303,
@@ -28,6 +36,8 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
28
36
  });
29
37
 
30
38
  if (!email) return redirect();
39
+ // Domain-bound users have no password to recover; their provider is the way in.
40
+ if (enforcedSsoProvider(auth, email)) return redirect();
31
41
 
32
42
  // Throttle by IP, then email. On limit, return the same "sent" response (never reveal)
33
43
  // and skip the email send — fail-open so a DB hiccup can't block recovery. Check the IP
@@ -35,7 +45,7 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
35
45
  // inserting new limiter rows by varying the email.
36
46
  const opts = { max: 5, windowMs: 15 * 60 * 1000, failClosed: false };
37
47
  if (!(await hitRateLimit("forgot:ip", clientAddress, opts)).ok) return redirect();
38
- if (!(await hitRateLimit("forgot:email", email.toLowerCase(), opts)).ok) return redirect();
48
+ if (!(await hitRateLimit("forgot:email", email, opts)).ok) return redirect();
39
49
 
40
50
  const db = await getDb();
41
51
  const schema = await import("virtual:kide/schema");
@@ -43,36 +53,37 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
43
53
  if (!tables.users) return redirect();
44
54
 
45
55
  const rows = await db.select().from(tables.users.main).where(eq(tables.users.main.email, email)).limit(1);
46
- if (rows.length === 0) {
56
+ const user = rows.length > 0 ? await loadAuthUser(String((rows[0] as Record<string, unknown>)._id)) : null;
57
+ const audit = () =>
47
58
  logAudit({
48
59
  action: "auth.password_reset_requested",
49
60
  resourceType: "password_reset",
50
- attemptedEmail: email,
61
+ ...(user ? { actor: auditActor(user) } : { attemptedEmail: email }),
51
62
  ...auditRequestMeta(request),
52
63
  });
64
+
65
+ if (!user) {
66
+ audit();
53
67
  return redirect();
54
68
  }
55
69
 
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
- });
70
+ // SSO-only accounts don't get a password through the back door: their identity
71
+ // provider (and its offboarding) stays the only way in. Invited users who haven't
72
+ // accepted yet have no accounts at all and may reset.
73
+ const methods = await listSignInMethods(user.id);
74
+ if (methods.length > 0 && !methods.includes("credential")) {
75
+ audit();
76
+ return redirect();
77
+ }
76
78
 
79
+ const betterAuth = await getAdminAuth(request);
80
+ await authResponse(() =>
81
+ betterAuth.api.requestPasswordReset({
82
+ body: { email, redirectTo: "/admin/reset-password" },
83
+ headers: request.headers,
84
+ asResponse: true,
85
+ }),
86
+ );
87
+ audit();
77
88
  return redirect();
78
89
  };