@kidecms/core 0.1.11 → 0.13.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 (181) hide show
  1. package/LICENSE +21 -0
  2. package/admin/components/AssetsGrid.tsx +366 -173
  3. package/admin/components/BlockEditor.tsx +260 -679
  4. package/admin/components/CheckboxField.tsx +2 -2
  5. package/admin/components/CollaborationReviewBar.tsx +384 -0
  6. package/admin/components/ColorField.tsx +87 -0
  7. package/admin/components/CommandPalette.tsx +169 -0
  8. package/admin/components/ContentEditor.tsx +687 -0
  9. package/admin/components/DocumentActions.tsx +4 -2
  10. package/admin/components/DocumentsDataTable.tsx +91 -10
  11. package/admin/components/FieldControl.astro +151 -26
  12. package/admin/components/FocalPointSelector.tsx +27 -1
  13. package/admin/components/InternalLinkPicker.tsx +4 -3
  14. package/admin/components/LinkField.tsx +126 -0
  15. package/admin/components/RelationField.tsx +105 -26
  16. package/admin/components/RepeaterInput.tsx +46 -0
  17. package/admin/components/RichTextEditor.tsx +44 -9
  18. package/admin/components/SharedSectionBlockField.tsx +93 -0
  19. package/admin/components/SidebarUserMenu.tsx +1 -1
  20. package/admin/components/Toast.astro +1 -1
  21. package/admin/components/TreeItemsEditor.tsx +20 -19
  22. package/admin/components/TreeSelect.tsx +2 -2
  23. package/admin/components/YoutubeField.tsx +48 -0
  24. package/admin/components/block-fields.tsx +777 -0
  25. package/admin/components/content-block-spec.ts +114 -0
  26. package/admin/components/slash-command.tsx +242 -0
  27. package/admin/components/tree-utils.ts +14 -2
  28. package/admin/components/ui/badge.tsx +2 -3
  29. package/admin/components/ui/button.tsx +5 -4
  30. package/admin/components/ui/checkbox.tsx +1 -1
  31. package/admin/components/ui/input.tsx +1 -1
  32. package/admin/components/ui/select.tsx +1 -1
  33. package/admin/components/ui/table.tsx +1 -1
  34. package/admin/components/ui/textarea.tsx +1 -1
  35. package/admin/layouts/AdminLayout.astro +323 -123
  36. package/admin/lib/access.ts +54 -0
  37. package/admin/lib/collaboration.ts +178 -0
  38. package/admin/lib/edit-data.ts +448 -0
  39. package/admin/views/AccessDeniedView.astro +8 -0
  40. package/admin/views/EditView.astro +706 -0
  41. package/admin/views/ListView.astro +202 -0
  42. package/admin/views/RecentView.astro +76 -0
  43. package/admin/views/SinglesView.astro +65 -0
  44. package/admin/views/edit/EditScripts.astro +145 -0
  45. package/admin/views/edit/ReverseReferencesList.astro +68 -0
  46. package/core/admin.ts +193 -0
  47. package/core/ai.ts +87 -0
  48. package/core/api.ts +1392 -0
  49. package/core/assets.ts +336 -0
  50. package/core/audit.ts +84 -0
  51. package/core/auth-config.ts +44 -0
  52. package/core/auth.ts +303 -0
  53. package/core/collaboration.ts +276 -0
  54. package/core/content.ts +27 -0
  55. package/core/create-admin.ts +28 -0
  56. package/core/define.ts +625 -0
  57. package/core/field-model.ts +172 -0
  58. package/core/generator.ts +519 -0
  59. package/core/http.ts +42 -0
  60. package/core/image.ts +219 -0
  61. package/core/index.ts +211 -0
  62. package/core/locks.ts +52 -0
  63. package/core/log.ts +37 -0
  64. package/core/migrate.ts +278 -0
  65. package/core/rate-limit.ts +110 -0
  66. package/core/request-scope.ts +33 -0
  67. package/core/richtext.ts +1 -0
  68. package/core/runtime.ts +63 -0
  69. package/core/schema.ts +32 -0
  70. package/core/search.ts +489 -0
  71. package/core/seed.ts +101 -0
  72. package/core/shared-sections.ts +96 -0
  73. package/core/tasks.ts +176 -0
  74. package/core/values.ts +433 -0
  75. package/core/webhooks.ts +85 -0
  76. package/core/youtube.ts +39 -0
  77. package/internals/cli.mjs +34 -0
  78. package/internals/context.ts +67 -0
  79. package/internals/create-admin.ts +40 -0
  80. package/internals/describe.ts +25 -0
  81. package/internals/eject.ts +144 -0
  82. package/internals/generator.ts +11 -0
  83. package/internals/integration.ts +481 -0
  84. package/internals/mcp.ts +397 -0
  85. package/internals/project.ts +26 -0
  86. package/internals/push.ts +160 -0
  87. package/internals/reindex.ts +11 -0
  88. package/internals/restore.ts +257 -0
  89. package/internals/seed.data.ts +7 -0
  90. package/internals/seed.ts +11 -0
  91. package/internals/upgrade.ts +776 -0
  92. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  93. package/middleware/auth.ts +130 -17
  94. package/middleware/push.ts +121 -0
  95. package/package.json +55 -67
  96. package/platform/cloudflare/cf-env.ts +60 -0
  97. package/platform/cloudflare/database.ts +28 -0
  98. package/platform/cloudflare/globals.d.ts +5 -0
  99. package/platform/cloudflare/storage.ts +33 -0
  100. package/platform/cloudflare/uploads-route.ts +37 -0
  101. package/platform/node/database.ts +39 -0
  102. package/platform/node/storage.ts +52 -0
  103. package/routes/admin/[...path].astro +71 -0
  104. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  105. package/routes/admin/assets/index.astro +90 -0
  106. package/routes/{pages/admin/login.astro → admin/forgot-password.astro} +21 -19
  107. package/routes/{pages/admin → admin}/invite.astro +6 -6
  108. package/routes/admin/login.astro +103 -0
  109. package/routes/admin/reset-password.astro +73 -0
  110. package/routes/{pages/admin → admin}/setup.astro +31 -8
  111. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
  112. package/routes/api/admin/search.ts +89 -0
  113. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  114. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  115. package/routes/api/assets/upload.ts +147 -0
  116. package/routes/api/auth/forgot-password.ts +77 -0
  117. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  118. package/routes/api/auth/login.ts +167 -0
  119. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  120. package/routes/api/auth/reset-password.ts +85 -0
  121. package/routes/api/auth/setup.ts +110 -0
  122. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  123. package/routes/api/collaboration/index.ts +106 -0
  124. package/routes/api/cron/_authorize.ts +25 -0
  125. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  126. package/routes/api/cron/tasks.ts +33 -0
  127. package/routes/api/forms/submit/[slug].ts +143 -0
  128. package/routes/api/img/[...path].ts +65 -0
  129. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  130. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  131. package/routes/api/webhooks/[provider].ts +54 -0
  132. package/README.md +0 -28
  133. package/dist/admin.d.ts +0 -33
  134. package/dist/admin.js +0 -92
  135. package/dist/ai.d.ts +0 -15
  136. package/dist/ai.js +0 -70
  137. package/dist/api.d.ts +0 -14
  138. package/dist/api.js +0 -833
  139. package/dist/assets.d.ts +0 -51
  140. package/dist/assets.js +0 -163
  141. package/dist/auth.d.ts +0 -30
  142. package/dist/auth.js +0 -132
  143. package/dist/content.d.ts +0 -3
  144. package/dist/content.js +0 -29
  145. package/dist/create-admin.d.ts +0 -5
  146. package/dist/create-admin.js +0 -23
  147. package/dist/define.d.ts +0 -254
  148. package/dist/define.js +0 -36
  149. package/dist/generator.d.ts +0 -9
  150. package/dist/generator.js +0 -370
  151. package/dist/image.d.ts +0 -9
  152. package/dist/image.js +0 -69
  153. package/dist/index.d.ts +0 -28
  154. package/dist/index.js +0 -16
  155. package/dist/integration.d.ts +0 -14
  156. package/dist/integration.js +0 -327
  157. package/dist/locks.d.ts +0 -7
  158. package/dist/locks.js +0 -37
  159. package/dist/richtext.d.ts +0 -1
  160. package/dist/richtext.js +0 -1
  161. package/dist/runtime.d.ts +0 -24
  162. package/dist/runtime.js +0 -26
  163. package/dist/schema.d.ts +0 -17
  164. package/dist/schema.js +0 -13
  165. package/dist/seed.d.ts +0 -2
  166. package/dist/seed.js +0 -84
  167. package/dist/values.d.ts +0 -8
  168. package/dist/values.js +0 -102
  169. package/dist/webhooks.d.ts +0 -2
  170. package/dist/webhooks.js +0 -73
  171. package/routes/api/cms/assets/upload.ts +0 -112
  172. package/routes/api/cms/auth/login.ts +0 -124
  173. package/routes/api/cms/auth/setup.ts +0 -77
  174. package/routes/api/cms/img/[...path].ts +0 -24
  175. package/routes/pages/admin/[...path].astro +0 -1107
  176. package/routes/pages/admin/assets/index.astro +0 -63
  177. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  178. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  179. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  180. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  181. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
@@ -0,0 +1,77 @@
1
+ import type { APIRoute } from "astro";
2
+ import { eq } from "drizzle-orm";
3
+
4
+ import { getDb } from "virtual:kide/db";
5
+ import {
6
+ auditRequestMeta,
7
+ hitRateLimit,
8
+ createPasswordReset,
9
+ getEmail,
10
+ logAudit,
11
+ tokenReference,
12
+ } from "virtual:kide/runtime";
13
+ import { resolveAdminAuth } from "../../../core";
14
+ import config from "virtual:kide/config";
15
+
16
+ export const prerender = false;
17
+
18
+ export const POST: APIRoute = async ({ request, clientAddress }) => {
19
+ const auth = resolveAdminAuth(config);
20
+ if (!auth.password.forgotPassword) return Response.json({ error: "Not found" }, { status: 404 });
21
+
22
+ const formData = await request.formData();
23
+ const email = String(formData.get("email") ?? "").trim();
24
+ const redirect = () =>
25
+ new Response(null, {
26
+ status: 303,
27
+ headers: { Location: "/admin/forgot-password?status=sent" },
28
+ });
29
+
30
+ if (!email) return redirect();
31
+
32
+ // Throttle by IP, then email. On limit, return the same "sent" response (never reveal)
33
+ // and skip the email send — fail-open so a DB hiccup can't block recovery. Check the IP
34
+ // bucket FIRST and return before touching the email bucket, so a blocked IP can't keep
35
+ // inserting new limiter rows by varying the email.
36
+ const opts = { max: 5, windowMs: 15 * 60 * 1000, failClosed: false };
37
+ if (!(await hitRateLimit("forgot:ip", clientAddress, opts)).ok) return redirect();
38
+ if (!(await hitRateLimit("forgot:email", email.toLowerCase(), opts)).ok) return redirect();
39
+
40
+ const db = await getDb();
41
+ const schema = await import("virtual:kide/schema");
42
+ const tables = schema.cmsTables as Record<string, { main: any }>;
43
+ if (!tables.users) return redirect();
44
+
45
+ const rows = await db.select().from(tables.users.main).where(eq(tables.users.main.email, email)).limit(1);
46
+ if (rows.length === 0) {
47
+ logAudit({
48
+ action: "auth.password_reset_requested",
49
+ resourceType: "password_reset",
50
+ attemptedEmail: email,
51
+ ...auditRequestMeta(request),
52
+ });
53
+ return redirect();
54
+ }
55
+
56
+ const user = rows[0] as Record<string, unknown>;
57
+ const reset = await createPasswordReset(String(user._id));
58
+ const resetUrl = new URL("/admin/reset-password", request.url);
59
+ resetUrl.searchParams.set("token", reset.token);
60
+
61
+ const emailAdapter = getEmail();
62
+ await emailAdapter.sendPasswordResetEmail?.(String(user.email), resetUrl.toString());
63
+
64
+ logAudit({
65
+ action: "auth.password_reset_requested",
66
+ resourceType: "password_reset",
67
+ resourceId: await tokenReference(reset.token),
68
+ actor: {
69
+ id: String(user._id),
70
+ email: String(user.email ?? ""),
71
+ role: String(user.role ?? ""),
72
+ },
73
+ ...auditRequestMeta(request),
74
+ });
75
+
76
+ return redirect();
77
+ };
@@ -3,24 +3,28 @@ import { eq } from "drizzle-orm";
3
3
 
4
4
  import { getDb } from "virtual:kide/db";
5
5
  import {
6
+ auditRequestMeta,
7
+ hitRateLimit,
6
8
  createInvite,
7
- validateInvite,
8
9
  consumeInvite,
9
10
  hashPassword,
10
11
  createSession,
11
12
  setSessionCookie,
12
13
  getSessionUser,
14
+ logAudit,
15
+ tokenReference,
13
16
  } from "virtual:kide/runtime";
14
17
  import { sendInviteEmail, isEmailConfigured } from "virtual:kide/email";
18
+ import { MIN_PASSWORD_LENGTH } from "../../../core";
15
19
 
16
20
  export const prerender = false;
17
21
 
18
- export const POST: APIRoute = async ({ request, url }) => {
22
+ export const POST: APIRoute = async ({ request, url, clientAddress }) => {
19
23
  const formData = await request.formData();
20
24
  const action = String(formData.get("_action") ?? "create");
21
25
 
22
26
  if (action === "accept") {
23
- return handleAccept(formData);
27
+ return handleAccept(formData, request, clientAddress);
24
28
  }
25
29
 
26
30
  return handleCreate(formData, url, request);
@@ -100,7 +104,7 @@ async function handleCreate(formData: FormData, url: URL, request: Request) {
100
104
  });
101
105
  }
102
106
 
103
- async function handleAccept(formData: FormData) {
107
+ async function handleAccept(formData: FormData, request: Request, clientAddress: string) {
104
108
  const token = String(formData.get("token") ?? "");
105
109
  const name = String(formData.get("name") ?? "").trim();
106
110
  const password = String(formData.get("password") ?? "");
@@ -113,6 +117,13 @@ async function handleAccept(formData: FormData) {
113
117
  });
114
118
  }
115
119
 
120
+ // Key on Astro's clientAddress (trusted), not the spoofable X-Forwarded-For header.
121
+ const opts = { max: 10, windowMs: 15 * 60 * 1000, failClosed: true };
122
+ const ipLimit = await hitRateLimit("invite:ip", clientAddress, opts);
123
+ if (!ipLimit.ok) {
124
+ return new Response(null, { status: 303, headers: { Location: "/admin/invite?error=invalid" } });
125
+ }
126
+
116
127
  if (!name || !password) {
117
128
  return new Response(null, {
118
129
  status: 303,
@@ -127,14 +138,17 @@ async function handleAccept(formData: FormData) {
127
138
  });
128
139
  }
129
140
 
130
- if (password.length < 8) {
141
+ if (password.length < MIN_PASSWORD_LENGTH) {
131
142
  return new Response(null, {
132
143
  status: 303,
133
144
  headers: { Location: `/admin/invite?token=${token}&error=short` },
134
145
  });
135
146
  }
136
147
 
137
- const invite = await validateInvite(token);
148
+ // Hash before claiming: the token is single-use, so run the fallible work first, then
149
+ // consume as the atomic single-winner gate against a double-submit.
150
+ const hashedPassword = await hashPassword(password);
151
+ const invite = await consumeInvite(token);
138
152
  if (!invite) {
139
153
  return new Response(null, {
140
154
  status: 303,
@@ -146,16 +160,34 @@ async function handleAccept(formData: FormData) {
146
160
  const schema = await import("virtual:kide/schema");
147
161
  const tables = schema.cmsTables as Record<string, { main: any }>;
148
162
 
149
- const hashedPassword = await hashPassword(password);
150
163
  await db
151
164
  .update(tables.users.main)
152
165
  .set({ name, password: hashedPassword, _updatedAt: new Date().toISOString() })
153
166
  .where(eq(tables.users.main._id, invite.userId));
154
167
 
155
- await consumeInvite(token);
156
-
157
168
  const session = await createSession(invite.userId);
158
169
 
170
+ const acceptedUserRows = await db
171
+ .select()
172
+ .from(tables.users.main)
173
+ .where(eq(tables.users.main._id, invite.userId))
174
+ .limit(1);
175
+ const acceptedUser = acceptedUserRows[0] as Record<string, unknown> | undefined;
176
+
177
+ logAudit({
178
+ action: "auth.invite_accepted",
179
+ resourceType: "invite",
180
+ resourceId: await tokenReference(token),
181
+ actor: acceptedUser
182
+ ? {
183
+ id: String(acceptedUser._id),
184
+ email: String(acceptedUser.email ?? ""),
185
+ role: String(acceptedUser.role ?? ""),
186
+ }
187
+ : null,
188
+ ...auditRequestMeta(request),
189
+ });
190
+
159
191
  return new Response(null, {
160
192
  status: 303,
161
193
  headers: {
@@ -0,0 +1,167 @@
1
+ import type { APIRoute } from "astro";
2
+ import { eq } from "drizzle-orm";
3
+
4
+ import { getDb } from "virtual:kide/db";
5
+ import {
6
+ auditRequestMeta,
7
+ createSession,
8
+ logAudit,
9
+ setSessionCookie,
10
+ tokenReference,
11
+ verifyPassword,
12
+ } from "virtual:kide/runtime";
13
+ import config from "virtual:kide/config";
14
+ import { clearRateLimit, peekRateLimit, recordRateLimit, resolveAdminAuth } from "../../../core";
15
+
16
+ export const prerender = false;
17
+
18
+ const MAX_ATTEMPTS = config.admin?.rateLimit?.maxAttempts ?? 5;
19
+ const WINDOW_MS = config.admin?.rateLimit?.windowMs ?? 15 * 60 * 1000;
20
+
21
+ export const POST: APIRoute = async ({ request, clientAddress }) => {
22
+ const contentType = request.headers.get("content-type") ?? "";
23
+ const isJson = contentType.includes("application/json");
24
+ const auth = resolveAdminAuth(config);
25
+
26
+ const rateLimited = (retryAfterMs: number) => {
27
+ if (isJson) {
28
+ return Response.json(
29
+ { error: "Too many login attempts. Try again later." },
30
+ {
31
+ status: 429,
32
+ headers: { "Retry-After": String(Math.ceil(retryAfterMs / 1000)) },
33
+ },
34
+ );
35
+ }
36
+ return new Response(null, { status: 303, headers: { Location: "/admin/login?error=rate-limited" } });
37
+ };
38
+
39
+ if (!auth.password.enabled) {
40
+ if (isJson) return Response.json({ error: "Password login is disabled." }, { status: 404 });
41
+ return new Response(null, { status: 303, headers: { Location: "/admin/login?error=disabled" } });
42
+ }
43
+
44
+ let email: string;
45
+ let password: string;
46
+
47
+ if (isJson) {
48
+ const body = await request.json();
49
+ email = String(body.email ?? "");
50
+ password = String(body.password ?? "");
51
+ } else {
52
+ const formData = await request.formData();
53
+ email = String(formData.get("email") ?? "");
54
+ password = String(formData.get("password") ?? "");
55
+ }
56
+
57
+ if (!email || !password) {
58
+ if (isJson) return Response.json({ error: "Email and password are required." }, { status: 400 });
59
+ return new Response(null, { status: 303, headers: { Location: "/admin/login?error=missing" } });
60
+ }
61
+
62
+ // Rate limit FAILED logins only: peek (read-only) before verifying, record on failure,
63
+ // and clear the account budget on success. Both the client IP (spraying) and the email
64
+ // (targeted) are throttled; a success never touches the IP bucket, so one valid credential
65
+ // can't reset the throttle and keep spraying other accounts.
66
+ const emailKey = email.toLowerCase();
67
+ const opts = { max: MAX_ATTEMPTS, windowMs: WINDOW_MS, failClosed: true };
68
+ const ipPeek = await peekRateLimit("login:ip", clientAddress, opts);
69
+ if (!ipPeek.ok) return rateLimited(ipPeek.retryAfterMs);
70
+ const emailPeek = await peekRateLimit("login:email", emailKey, opts);
71
+ if (!emailPeek.ok) return rateLimited(emailPeek.retryAfterMs);
72
+
73
+ const recordFailure = async () => {
74
+ await recordRateLimit("login:ip", clientAddress, opts);
75
+ await recordRateLimit("login:email", emailKey, opts);
76
+ };
77
+
78
+ const db = await getDb();
79
+ const schema = await import("virtual:kide/schema");
80
+ const tables = schema.cmsTables as Record<string, { main: any }>;
81
+
82
+ if (!tables.users) {
83
+ return Response.json({ error: "Users collection not configured." }, { status: 500 });
84
+ }
85
+
86
+ const rows = await db.select().from(tables.users.main).where(eq(tables.users.main.email, email)).limit(1);
87
+ const requestMeta = auditRequestMeta(request);
88
+
89
+ if (rows.length === 0) {
90
+ await recordFailure();
91
+ logAudit({
92
+ action: "auth.login_failed",
93
+ resourceType: "session",
94
+ attemptedEmail: email,
95
+ ...requestMeta,
96
+ });
97
+ if (contentType.includes("application/json")) {
98
+ return Response.json({ error: "Invalid credentials." }, { status: 401 });
99
+ }
100
+ return new Response(null, {
101
+ status: 303,
102
+ headers: { Location: "/admin/login?error=invalid" },
103
+ });
104
+ }
105
+
106
+ const user = rows[0] as Record<string, unknown>;
107
+ const storedHash = String(user.password ?? "");
108
+
109
+ let valid = false;
110
+ try {
111
+ valid = await verifyPassword(storedHash, password);
112
+ } catch {
113
+ // valid remains false
114
+ }
115
+
116
+ if (!valid) {
117
+ await recordFailure();
118
+ logAudit({
119
+ action: "auth.login_failed",
120
+ resourceType: "session",
121
+ attemptedEmail: email,
122
+ ...requestMeta,
123
+ });
124
+ if (contentType.includes("application/json")) {
125
+ return Response.json({ error: "Invalid credentials." }, { status: 401 });
126
+ }
127
+ return new Response(null, {
128
+ status: 303,
129
+ headers: { Location: "/admin/login?error=invalid" },
130
+ });
131
+ }
132
+
133
+ // Success — clear this account's failed-login budget (but not the IP bucket).
134
+ await clearRateLimit("login:email", emailKey);
135
+
136
+ const session = await createSession(String(user._id));
137
+
138
+ logAudit({
139
+ action: "auth.login",
140
+ resourceType: "session",
141
+ resourceId: await tokenReference(session.token),
142
+ actor: {
143
+ id: String(user._id),
144
+ email: String(user.email ?? ""),
145
+ role: String(user.role ?? ""),
146
+ },
147
+ ...requestMeta,
148
+ });
149
+
150
+ if (contentType.includes("application/json")) {
151
+ return new Response(JSON.stringify({ ok: true }), {
152
+ status: 200,
153
+ headers: {
154
+ "Content-Type": "application/json",
155
+ "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
156
+ },
157
+ });
158
+ }
159
+
160
+ return new Response(null, {
161
+ status: 303,
162
+ headers: {
163
+ Location: "/admin",
164
+ "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
165
+ },
166
+ });
167
+ };
@@ -1,10 +1,10 @@
1
1
  import type { APIRoute } from "astro";
2
2
 
3
- import { destroySession, clearSessionCookie } from "virtual:kide/runtime";
3
+ import { auditRequestMeta, clearSessionCookie, destroySession, logAudit, tokenReference } from "virtual:kide/runtime";
4
4
 
5
5
  export const prerender = false;
6
6
 
7
- export const POST: APIRoute = async ({ request }) => {
7
+ export const POST: APIRoute = async ({ request, locals }) => {
8
8
  const cookieHeader = request.headers.get("cookie") ?? "";
9
9
  const match = cookieHeader.match(/cms_session=([^;]+)/);
10
10
 
@@ -12,6 +12,15 @@ export const POST: APIRoute = async ({ request }) => {
12
12
  await destroySession(match[1]);
13
13
  }
14
14
 
15
+ const user = locals.user;
16
+ logAudit({
17
+ action: "auth.logout",
18
+ resourceType: "session",
19
+ resourceId: match ? await tokenReference(match[1]) : null,
20
+ actor: user ? { id: user.id, email: user.email, role: user.role } : null,
21
+ ...auditRequestMeta(request),
22
+ });
23
+
15
24
  const contentType = request.headers.get("content-type") ?? "";
16
25
  if (contentType.includes("application/json")) {
17
26
  return new Response(JSON.stringify({ ok: true }), {
@@ -0,0 +1,85 @@
1
+ import type { APIRoute } from "astro";
2
+ import { eq } from "drizzle-orm";
3
+
4
+ import { getDb } from "virtual:kide/db";
5
+ import {
6
+ auditRequestMeta,
7
+ hitRateLimit,
8
+ consumePasswordReset,
9
+ createSession,
10
+ hashPassword,
11
+ logAudit,
12
+ setSessionCookie,
13
+ } from "virtual:kide/runtime";
14
+ import { resolveAdminAuth, MIN_PASSWORD_LENGTH } from "../../../core";
15
+ import config from "virtual:kide/config";
16
+
17
+ export const prerender = false;
18
+
19
+ const redirectWithError = (token: string, error: string) =>
20
+ new Response(null, {
21
+ status: 303,
22
+ headers: { Location: `/admin/reset-password?token=${encodeURIComponent(token)}&error=${error}` },
23
+ });
24
+
25
+ export const POST: APIRoute = async ({ request, clientAddress }) => {
26
+ const auth = resolveAdminAuth(config);
27
+ if (!auth.password.forgotPassword) return Response.json({ error: "Not found" }, { status: 404 });
28
+
29
+ const ipLimit = await hitRateLimit("reset:ip", clientAddress, { max: 10, windowMs: 15 * 60 * 1000 });
30
+ if (!ipLimit.ok) return redirectWithError("", "invalid");
31
+
32
+ const formData = await request.formData();
33
+ const token = String(formData.get("token") ?? "");
34
+ const password = String(formData.get("password") ?? "");
35
+ const confirmPassword = String(formData.get("confirmPassword") ?? "");
36
+
37
+ if (!token || !password) return redirectWithError(token, "missing");
38
+ if (password !== confirmPassword) return redirectWithError(token, "password");
39
+ if (password.length < MIN_PASSWORD_LENGTH) return redirectWithError(token, "short");
40
+
41
+ // Hash before claiming the token: the token is single-use, so anything fallible must run
42
+ // before we burn it — otherwise a hashing failure would strand the account with a spent
43
+ // token. Consume is then the atomic single-winner gate against double-submit.
44
+ const hashedPassword = await hashPassword(password);
45
+ const reset = await consumePasswordReset(token);
46
+ if (!reset) return redirectWithError(token, "invalid");
47
+
48
+ const db = await getDb();
49
+ const schema = await import("virtual:kide/schema");
50
+ const tables = schema.cmsTables as Record<string, { main: any }>;
51
+ if (!tables.users) return redirectWithError(token, "invalid");
52
+
53
+ const userRows = await db.select().from(tables.users.main).where(eq(tables.users.main._id, reset.userId)).limit(1);
54
+ if (userRows.length === 0) return redirectWithError(token, "invalid");
55
+
56
+ const user = userRows[0] as Record<string, unknown>;
57
+ await db
58
+ .update(tables.users.main)
59
+ .set({ password: hashedPassword, _updatedAt: new Date().toISOString() })
60
+ .where(eq(tables.users.main._id, reset.userId));
61
+ await db.delete(schema.cmsSessions).where(eq(schema.cmsSessions.userId, reset.userId));
62
+
63
+ const session = await createSession(reset.userId);
64
+
65
+ logAudit({
66
+ action: "auth.password_reset_completed",
67
+ resourceType: "user",
68
+ resourceCollection: "users",
69
+ resourceId: reset.userId,
70
+ actor: {
71
+ id: reset.userId,
72
+ email: String(user.email ?? ""),
73
+ role: String(user.role ?? ""),
74
+ },
75
+ ...auditRequestMeta(request),
76
+ });
77
+
78
+ return new Response(null, {
79
+ status: 303,
80
+ headers: {
81
+ Location: "/admin",
82
+ "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
83
+ },
84
+ });
85
+ };
@@ -0,0 +1,110 @@
1
+ import type { APIRoute } from "astro";
2
+ import { eq, sql } from "drizzle-orm";
3
+ import { nanoid } from "nanoid";
4
+
5
+ import { getDb } from "virtual:kide/db";
6
+ import {
7
+ auditRequestMeta,
8
+ hitRateLimit,
9
+ createSession,
10
+ hashPassword,
11
+ logAudit,
12
+ setSessionCookie,
13
+ } from "virtual:kide/runtime";
14
+ import { MIN_PASSWORD_LENGTH } from "../../../core";
15
+
16
+ export const prerender = false;
17
+
18
+ export const POST: APIRoute = async ({ request, clientAddress }) => {
19
+ const ipLimit = await hitRateLimit("setup:ip", clientAddress, {
20
+ max: 10,
21
+ windowMs: 15 * 60 * 1000,
22
+ failClosed: true,
23
+ });
24
+ if (!ipLimit.ok) {
25
+ return new Response(null, { status: 303, headers: { Location: "/admin/setup?error=missing" } });
26
+ }
27
+
28
+ const formData = await request.formData();
29
+ const name = String(formData.get("name") ?? "").trim();
30
+ const email = String(formData.get("email") ?? "").trim();
31
+ const password = String(formData.get("password") ?? "");
32
+ const confirmPassword = String(formData.get("confirmPassword") ?? "");
33
+
34
+ if (!name || !email || !password) {
35
+ return new Response(null, {
36
+ status: 303,
37
+ headers: { Location: "/admin/setup?error=missing" },
38
+ });
39
+ }
40
+
41
+ if (password !== confirmPassword) {
42
+ return new Response(null, {
43
+ status: 303,
44
+ headers: { Location: "/admin/setup?error=password" },
45
+ });
46
+ }
47
+
48
+ if (password.length < MIN_PASSWORD_LENGTH) {
49
+ return new Response(null, {
50
+ status: 303,
51
+ headers: { Location: "/admin/setup?error=short" },
52
+ });
53
+ }
54
+
55
+ const db = await getDb();
56
+ const schema = await import("virtual:kide/schema");
57
+ const tables = schema.cmsTables as Record<string, { main: any }>;
58
+
59
+ if (!tables.users) {
60
+ return Response.json({ error: "Users collection not configured." }, { status: 500 });
61
+ }
62
+
63
+ // Prevent setup if users already exist (fast path / friendly redirect).
64
+ const existing = await db.select().from(tables.users.main).limit(1);
65
+ if (existing.length > 0) {
66
+ return new Response(null, {
67
+ status: 303,
68
+ headers: { Location: "/admin/login" },
69
+ });
70
+ }
71
+
72
+ const id = nanoid();
73
+ const now = new Date().toISOString();
74
+ const hashedPassword = await hashPassword(password);
75
+
76
+ // Atomic winner election that leaves no orphan state: a single conditional insert creates
77
+ // the first admin only if the table is still empty. Self-recovering — if anything fails
78
+ // there's no marker to strand setup, and a retry just runs the same guarded insert.
79
+ await db.run(sql`
80
+ INSERT INTO cms_users (_id, name, email, role, password, _created_at, _updated_at)
81
+ SELECT ${id}, ${name}, ${email}, 'admin', ${hashedPassword}, ${now}, ${now}
82
+ WHERE NOT EXISTS (SELECT 1 FROM cms_users)
83
+ `);
84
+
85
+ // Confirm we won the race (our row exists). If not, another concurrent setup created the
86
+ // first admin — send this request to login.
87
+ const mine = await db.select().from(tables.users.main).where(eq(tables.users.main._id, id)).limit(1);
88
+ if (mine.length === 0) {
89
+ return new Response(null, { status: 303, headers: { Location: "/admin/login" } });
90
+ }
91
+
92
+ const session = await createSession(id);
93
+
94
+ logAudit({
95
+ action: "auth.setup_completed",
96
+ resourceType: "user",
97
+ resourceCollection: "users",
98
+ resourceId: id,
99
+ actor: { id, email, role: "admin" },
100
+ ...auditRequestMeta(request),
101
+ });
102
+
103
+ return new Response(null, {
104
+ status: 303,
105
+ headers: {
106
+ Location: "/admin",
107
+ "Set-Cookie": setSessionCookie(session.token, session.expiresAt),
108
+ },
109
+ });
110
+ };
@@ -0,0 +1,34 @@
1
+ import type { APIRoute } from "astro";
2
+
3
+ import { getSsoProvider, resolveAdminAuth } from "../../../../../core";
4
+ import config from "virtual:kide/config";
5
+
6
+ export const prerender = false;
7
+
8
+ export const GET: APIRoute = async ({ params, request }) => {
9
+ const providerId = params.provider ?? "";
10
+ const provider = getSsoProvider(config, providerId);
11
+ if (!provider) return Response.json({ error: "SSO provider not found." }, { status: 404 });
12
+
13
+ const auth = resolveAdminAuth(config);
14
+ if (provider.authorizationUrl) {
15
+ const url = new URL(provider.authorizationUrl);
16
+ url.searchParams.set("provider", provider.id);
17
+ url.searchParams.set(
18
+ "redirect_uri",
19
+ provider.callbackUrl ?? new URL("/api/cms/auth/sso/callback", request.url).toString(),
20
+ );
21
+ return new Response(null, {
22
+ status: 303,
23
+ headers: { Location: url.toString() },
24
+ });
25
+ }
26
+
27
+ return Response.json(
28
+ {
29
+ error: `SSO provider "${provider.id}" is configured, but ${auth.provider} does not expose a start URL for it yet.`,
30
+ hint: "Set authorizationUrl for a broker/custom flow, or use the Better Auth/WorkOS adapter when it is installed.",
31
+ },
32
+ { status: 501 },
33
+ );
34
+ };