@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.
- package/admin/components/PasskeySettings.tsx +121 -0
- package/admin/components/PasskeySignIn.tsx +57 -0
- package/admin/components/SidebarUserMenu.tsx +7 -1
- package/admin/components/TwoFactorSettings.tsx +206 -0
- package/admin/views/EditView.astro +14 -0
- package/core/api.ts +36 -0
- package/core/auth-config.ts +53 -11
- package/core/auth-engine.ts +920 -0
- package/core/auth.ts +46 -152
- package/core/create-admin.ts +9 -5
- package/core/define.ts +75 -35
- package/core/generator.ts +80 -10
- package/core/index.ts +31 -3
- package/core/schema.ts +3 -1
- package/core/seed.ts +12 -2
- package/internals/integration.ts +21 -0
- package/internals/virtual.d.ts +3 -2
- package/middleware/auth.ts +58 -18
- package/package.json +7 -2
- package/routes/admin/account.astro +138 -0
- package/routes/admin/login/verify.astro +90 -0
- package/routes/admin/login.astro +84 -33
- package/routes/api/auth/[...all].ts +153 -0
- package/routes/api/auth/_better-auth.ts +26 -0
- package/routes/api/auth/account.ts +69 -0
- package/routes/api/auth/forgot-password.ts +38 -32
- package/routes/api/auth/invite.ts +66 -98
- package/routes/api/auth/login/verify.ts +50 -0
- package/routes/api/auth/login.ts +68 -118
- package/routes/api/auth/logout.ts +13 -28
- package/routes/api/auth/reset-password.ts +17 -56
- package/routes/api/auth/setup.ts +14 -20
- package/routes/api/auth/sso/[provider]/start.ts +33 -25
package/routes/api/auth/login.ts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import type { APIRoute } from "astro";
|
|
2
|
-
import { eq } from "drizzle-orm";
|
|
3
2
|
|
|
4
|
-
import {
|
|
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 {
|
|
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
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
60
|
-
|
|
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
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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
|
|
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 (
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
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
|
-
|
|
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
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
|
133
|
-
status: 303,
|
|
134
|
-
headers: { Location: "/admin/login?error=invalid" },
|
|
135
|
-
});
|
|
105
|
+
return redirectWithCookies("/admin/login/verify", response);
|
|
136
106
|
}
|
|
137
107
|
|
|
138
|
-
|
|
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
|
-
|
|
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 (
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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,
|
|
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
|
|
8
|
-
const
|
|
9
|
-
const
|
|
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
|
-
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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 {
|
|
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
|
-
//
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
if (!
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
};
|
package/routes/api/auth/setup.ts
CHANGED
|
@@ -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
|
-
|
|
8
|
-
|
|
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") ?? "")
|
|
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,
|
|
83
|
-
SELECT ${id}, ${name}, ${email}, 'admin',
|
|
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
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
headers:
|
|
108
|
-
|
|
109
|
-
|
|
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 {
|
|
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
|
-
|
|
9
|
-
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
{
|
|
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
|
};
|