@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.
- package/LICENSE +21 -0
- package/admin/components/AssetsGrid.tsx +366 -173
- package/admin/components/BlockEditor.tsx +260 -679
- package/admin/components/CheckboxField.tsx +2 -2
- package/admin/components/CollaborationReviewBar.tsx +384 -0
- package/admin/components/ColorField.tsx +87 -0
- package/admin/components/CommandPalette.tsx +169 -0
- package/admin/components/ContentEditor.tsx +687 -0
- package/admin/components/DocumentActions.tsx +4 -2
- package/admin/components/DocumentsDataTable.tsx +91 -10
- package/admin/components/FieldControl.astro +151 -26
- package/admin/components/FocalPointSelector.tsx +27 -1
- package/admin/components/InternalLinkPicker.tsx +4 -3
- package/admin/components/LinkField.tsx +126 -0
- package/admin/components/RelationField.tsx +105 -26
- package/admin/components/RepeaterInput.tsx +46 -0
- package/admin/components/RichTextEditor.tsx +44 -9
- package/admin/components/SharedSectionBlockField.tsx +93 -0
- package/admin/components/SidebarUserMenu.tsx +1 -1
- package/admin/components/Toast.astro +1 -1
- package/admin/components/TreeItemsEditor.tsx +20 -19
- package/admin/components/TreeSelect.tsx +2 -2
- package/admin/components/YoutubeField.tsx +48 -0
- package/admin/components/block-fields.tsx +777 -0
- package/admin/components/content-block-spec.ts +114 -0
- package/admin/components/slash-command.tsx +242 -0
- package/admin/components/tree-utils.ts +14 -2
- package/admin/components/ui/badge.tsx +2 -3
- package/admin/components/ui/button.tsx +5 -4
- package/admin/components/ui/checkbox.tsx +1 -1
- package/admin/components/ui/input.tsx +1 -1
- package/admin/components/ui/select.tsx +1 -1
- package/admin/components/ui/table.tsx +1 -1
- package/admin/components/ui/textarea.tsx +1 -1
- package/admin/layouts/AdminLayout.astro +323 -123
- package/admin/lib/access.ts +54 -0
- package/admin/lib/collaboration.ts +178 -0
- package/admin/lib/edit-data.ts +448 -0
- package/admin/views/AccessDeniedView.astro +8 -0
- package/admin/views/EditView.astro +706 -0
- package/admin/views/ListView.astro +202 -0
- package/admin/views/RecentView.astro +76 -0
- package/admin/views/SinglesView.astro +65 -0
- package/admin/views/edit/EditScripts.astro +145 -0
- package/admin/views/edit/ReverseReferencesList.astro +68 -0
- package/core/admin.ts +193 -0
- package/core/ai.ts +87 -0
- package/core/api.ts +1392 -0
- package/core/assets.ts +336 -0
- package/core/audit.ts +84 -0
- package/core/auth-config.ts +44 -0
- package/core/auth.ts +303 -0
- package/core/collaboration.ts +276 -0
- package/core/content.ts +27 -0
- package/core/create-admin.ts +28 -0
- package/core/define.ts +625 -0
- package/core/field-model.ts +172 -0
- package/core/generator.ts +519 -0
- package/core/http.ts +42 -0
- package/core/image.ts +219 -0
- package/core/index.ts +211 -0
- package/core/locks.ts +52 -0
- package/core/log.ts +37 -0
- package/core/migrate.ts +278 -0
- package/core/rate-limit.ts +110 -0
- package/core/request-scope.ts +33 -0
- package/core/richtext.ts +1 -0
- package/core/runtime.ts +63 -0
- package/core/schema.ts +32 -0
- package/core/search.ts +489 -0
- package/core/seed.ts +101 -0
- package/core/shared-sections.ts +96 -0
- package/core/tasks.ts +176 -0
- package/core/values.ts +433 -0
- package/core/webhooks.ts +85 -0
- package/core/youtube.ts +39 -0
- package/internals/cli.mjs +34 -0
- package/internals/context.ts +67 -0
- package/internals/create-admin.ts +40 -0
- package/internals/describe.ts +25 -0
- package/internals/eject.ts +144 -0
- package/internals/generator.ts +11 -0
- package/internals/integration.ts +481 -0
- package/internals/mcp.ts +397 -0
- package/internals/project.ts +26 -0
- package/internals/push.ts +160 -0
- package/internals/reindex.ts +11 -0
- package/internals/restore.ts +257 -0
- package/internals/seed.data.ts +7 -0
- package/internals/seed.ts +11 -0
- package/internals/upgrade.ts +776 -0
- package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
- package/middleware/auth.ts +130 -17
- package/middleware/push.ts +121 -0
- package/package.json +55 -67
- package/platform/cloudflare/cf-env.ts +60 -0
- package/platform/cloudflare/database.ts +28 -0
- package/platform/cloudflare/globals.d.ts +5 -0
- package/platform/cloudflare/storage.ts +33 -0
- package/platform/cloudflare/uploads-route.ts +37 -0
- package/platform/node/database.ts +39 -0
- package/platform/node/storage.ts +52 -0
- package/routes/admin/[...path].astro +71 -0
- package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
- package/routes/admin/assets/index.astro +90 -0
- package/routes/{pages/admin/login.astro → admin/forgot-password.astro} +21 -19
- package/routes/{pages/admin → admin}/invite.astro +6 -6
- package/routes/admin/login.astro +103 -0
- package/routes/admin/reset-password.astro +73 -0
- package/routes/{pages/admin → admin}/setup.astro +31 -8
- package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
- package/routes/api/admin/search.ts +89 -0
- package/routes/api/{cms/assets → assets}/[id].ts +24 -14
- package/routes/api/{cms/assets → assets}/index.ts +4 -2
- package/routes/api/assets/upload.ts +147 -0
- package/routes/api/auth/forgot-password.ts +77 -0
- package/routes/api/{cms/auth → auth}/invite.ts +41 -9
- package/routes/api/auth/login.ts +167 -0
- package/routes/api/{cms/auth → auth}/logout.ts +11 -2
- package/routes/api/auth/reset-password.ts +85 -0
- package/routes/api/auth/setup.ts +110 -0
- package/routes/api/auth/sso/[provider]/start.ts +34 -0
- package/routes/api/collaboration/index.ts +106 -0
- package/routes/api/cron/_authorize.ts +25 -0
- package/routes/api/{cms/cron → cron}/publish.ts +3 -9
- package/routes/api/cron/tasks.ts +33 -0
- package/routes/api/forms/submit/[slug].ts +143 -0
- package/routes/api/img/[...path].ts +65 -0
- package/routes/api/{cms/preview → preview}/render.ts +8 -3
- package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
- package/routes/api/webhooks/[provider].ts +54 -0
- package/README.md +0 -28
- package/dist/admin.d.ts +0 -33
- package/dist/admin.js +0 -92
- package/dist/ai.d.ts +0 -15
- package/dist/ai.js +0 -70
- package/dist/api.d.ts +0 -14
- package/dist/api.js +0 -833
- package/dist/assets.d.ts +0 -51
- package/dist/assets.js +0 -163
- package/dist/auth.d.ts +0 -30
- package/dist/auth.js +0 -132
- package/dist/content.d.ts +0 -3
- package/dist/content.js +0 -29
- package/dist/create-admin.d.ts +0 -5
- package/dist/create-admin.js +0 -23
- package/dist/define.d.ts +0 -254
- package/dist/define.js +0 -36
- package/dist/generator.d.ts +0 -9
- package/dist/generator.js +0 -370
- package/dist/image.d.ts +0 -9
- package/dist/image.js +0 -69
- package/dist/index.d.ts +0 -28
- package/dist/index.js +0 -16
- package/dist/integration.d.ts +0 -14
- package/dist/integration.js +0 -327
- package/dist/locks.d.ts +0 -7
- package/dist/locks.js +0 -37
- package/dist/richtext.d.ts +0 -1
- package/dist/richtext.js +0 -1
- package/dist/runtime.d.ts +0 -24
- package/dist/runtime.js +0 -26
- package/dist/schema.d.ts +0 -17
- package/dist/schema.js +0 -13
- package/dist/seed.d.ts +0 -2
- package/dist/seed.js +0 -84
- package/dist/values.d.ts +0 -8
- package/dist/values.js +0 -102
- package/dist/webhooks.d.ts +0 -2
- package/dist/webhooks.js +0 -73
- package/routes/api/cms/assets/upload.ts +0 -112
- package/routes/api/cms/auth/login.ts +0 -124
- package/routes/api/cms/auth/setup.ts +0 -77
- package/routes/api/cms/img/[...path].ts +0 -24
- package/routes/pages/admin/[...path].astro +0 -1107
- package/routes/pages/admin/assets/index.astro +0 -63
- /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
- /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
- /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
- /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
- /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
import config from "virtual:kide/config";
|
|
3
|
+
import { collaboration } from "virtual:kide/runtime";
|
|
4
|
+
import { isApprover, resolveCollaboration } from "../../../core";
|
|
5
|
+
|
|
6
|
+
export const prerender = false;
|
|
7
|
+
|
|
8
|
+
const isEnabled = (collection: string) => resolveCollaboration(config, collection).enabled;
|
|
9
|
+
|
|
10
|
+
// Reviewer verdicts — only these gate publishing, so only approvers may set them.
|
|
11
|
+
// Requesting review (ready_for_review) and returning to draft (in_progress) stay open.
|
|
12
|
+
const APPROVER_ONLY_STATES = new Set(["approved", "changes_requested"]);
|
|
13
|
+
|
|
14
|
+
const getActor = (locals: App.Locals) => {
|
|
15
|
+
const user = locals.user;
|
|
16
|
+
return user ? { id: user.id, email: user.email, role: user.role } : null;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const notFound = () => Response.json({ error: "Not found." }, { status: 404 });
|
|
20
|
+
const forbidden = () => Response.json({ error: "Forbidden." }, { status: 403 });
|
|
21
|
+
|
|
22
|
+
// A comment id alone is attacker-controlled, so resolve/delete must confirm the comment
|
|
23
|
+
// lives in a collab-enabled collection and the actor authored it or is an approver —
|
|
24
|
+
// otherwise any signed-in user could act on any comment in any collection.
|
|
25
|
+
const authorizeComment = async (commentId: string, actor: { id: string; role?: string }) => {
|
|
26
|
+
const comment = await collaboration.getComment(commentId);
|
|
27
|
+
if (!comment || !isEnabled(comment.collection)) return null;
|
|
28
|
+
if (comment.authorId === actor.id || isApprover(config, actor.role)) return comment;
|
|
29
|
+
return null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// GET /api/cms/collaboration?collection=<slug>&id=<docId>
|
|
33
|
+
// Returns the full collaboration snapshot for one document.
|
|
34
|
+
export const GET: APIRoute = async ({ url }) => {
|
|
35
|
+
const collection = url.searchParams.get("collection");
|
|
36
|
+
const id = url.searchParams.get("id");
|
|
37
|
+
if (!collection || !id) return Response.json({ error: "collection and id are required." }, { status: 400 });
|
|
38
|
+
if (!isEnabled(collection)) return notFound();
|
|
39
|
+
|
|
40
|
+
const [state, comments, activity] = await Promise.all([
|
|
41
|
+
collaboration.getState(collection, id),
|
|
42
|
+
collaboration.listComments(collection, id),
|
|
43
|
+
collaboration.getActivity(collection, id),
|
|
44
|
+
]);
|
|
45
|
+
return Response.json({ state, comments, activity });
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// POST /api/cms/collaboration { collection, id, action, ...payload }
|
|
49
|
+
export const POST: APIRoute = async ({ request, locals }) => {
|
|
50
|
+
const actor = getActor(locals);
|
|
51
|
+
if (!actor) return Response.json({ error: "Authentication required." }, { status: 401 });
|
|
52
|
+
|
|
53
|
+
const body = await request.json().catch(() => null);
|
|
54
|
+
if (!body || typeof body !== "object") return Response.json({ error: "Invalid body." }, { status: 400 });
|
|
55
|
+
|
|
56
|
+
const { collection, id, action } = body as Record<string, unknown>;
|
|
57
|
+
if (typeof collection !== "string" || typeof id !== "string" || typeof action !== "string") {
|
|
58
|
+
return Response.json({ error: "collection, id and action are required." }, { status: 400 });
|
|
59
|
+
}
|
|
60
|
+
if (!isEnabled(collection)) return notFound();
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
switch (action) {
|
|
64
|
+
case "setReviewState": {
|
|
65
|
+
const reviewState = String((body as any).reviewState);
|
|
66
|
+
// The approval gate is server-side: without this any signed-in user could set
|
|
67
|
+
// their own draft to "approved" and publish it, bypassing review entirely.
|
|
68
|
+
if (APPROVER_ONLY_STATES.has(reviewState) && !isApprover(config, actor.role)) {
|
|
69
|
+
return forbidden();
|
|
70
|
+
}
|
|
71
|
+
const state = await collaboration.setReviewState(collection, id, reviewState as any, actor);
|
|
72
|
+
return Response.json({ state });
|
|
73
|
+
}
|
|
74
|
+
case "setEditor": {
|
|
75
|
+
const editor = (body as any).editor;
|
|
76
|
+
const state = await collaboration.setEditor(collection, id, editor ? String(editor) : null, actor);
|
|
77
|
+
return Response.json({ state });
|
|
78
|
+
}
|
|
79
|
+
case "addComment": {
|
|
80
|
+
const comment = await collaboration.addComment(
|
|
81
|
+
collection,
|
|
82
|
+
id,
|
|
83
|
+
{ body: String((body as any).body ?? ""), field: (body as any).field ?? null },
|
|
84
|
+
actor,
|
|
85
|
+
);
|
|
86
|
+
return Response.json({ comment });
|
|
87
|
+
}
|
|
88
|
+
case "resolveComment": {
|
|
89
|
+
const comment = await authorizeComment(String((body as any).commentId), actor);
|
|
90
|
+
if (!comment) return forbidden();
|
|
91
|
+
await collaboration.resolveComment(comment._id, Boolean((body as any).resolved), actor);
|
|
92
|
+
return Response.json({ ok: true });
|
|
93
|
+
}
|
|
94
|
+
case "deleteComment": {
|
|
95
|
+
const comment = await authorizeComment(String((body as any).commentId), actor);
|
|
96
|
+
if (!comment) return forbidden();
|
|
97
|
+
await collaboration.deleteComment(comment._id, actor);
|
|
98
|
+
return Response.json({ ok: true });
|
|
99
|
+
}
|
|
100
|
+
default:
|
|
101
|
+
return Response.json({ error: `Unknown action "${action}".` }, { status: 400 });
|
|
102
|
+
}
|
|
103
|
+
} catch (error) {
|
|
104
|
+
return Response.json({ error: error instanceof Error ? error.message : "Request failed." }, { status: 400 });
|
|
105
|
+
}
|
|
106
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { readEnv } from "virtual:kide/runtime";
|
|
2
|
+
|
|
3
|
+
const timingSafeEqual = (a: string, b: string) => {
|
|
4
|
+
const left = new TextEncoder().encode(a);
|
|
5
|
+
const right = new TextEncoder().encode(b);
|
|
6
|
+
if (left.length !== right.length) return false;
|
|
7
|
+
let diff = 0;
|
|
8
|
+
for (let i = 0; i < left.length; i++) diff |= left[i] ^ right[i];
|
|
9
|
+
return diff === 0;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Nothing in this module may reference `import.meta.env`, not even `DEV`: Vite then emits
|
|
14
|
+
* the whole env object, filling in every key named as a string literal here — so
|
|
15
|
+
* `"CRON_SECRET"` would be baked into `dist/`. Read it through `readEnv` at runtime.
|
|
16
|
+
*/
|
|
17
|
+
export const isAuthorized = (request: Request) => {
|
|
18
|
+
const secret = readEnv("CRON_SECRET");
|
|
19
|
+
if (!secret) return process.env.NODE_ENV === "development";
|
|
20
|
+
|
|
21
|
+
const authHeader = request.headers.get("authorization") ?? "";
|
|
22
|
+
return timingSafeEqual(authHeader, `Bearer ${secret}`);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export const unauthorized = () => Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
@@ -2,21 +2,15 @@ import type { APIRoute } from "astro";
|
|
|
2
2
|
|
|
3
3
|
import { cms } from "virtual:kide/api";
|
|
4
4
|
|
|
5
|
+
import { isAuthorized, unauthorized } from "./_authorize";
|
|
6
|
+
|
|
5
7
|
export const prerender = false;
|
|
6
8
|
|
|
7
9
|
const cmsRuntime = cms as Record<string, any> & { scheduled: typeof cms.scheduled };
|
|
8
10
|
|
|
9
|
-
const isAuthorized = (request: Request) => {
|
|
10
|
-
const secret = import.meta.env.CRON_SECRET;
|
|
11
|
-
if (!secret) return true;
|
|
12
|
-
|
|
13
|
-
const authHeader = request.headers.get("authorization") ?? "";
|
|
14
|
-
return authHeader === `Bearer ${secret}`;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
11
|
const handler: APIRoute = async ({ request, cache }) => {
|
|
18
12
|
if (!isAuthorized(request)) {
|
|
19
|
-
return
|
|
13
|
+
return unauthorized();
|
|
20
14
|
}
|
|
21
15
|
|
|
22
16
|
const result = await cmsRuntime.scheduled.processPublishing(cache);
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
|
|
3
|
+
import { cms } from "virtual:kide/api";
|
|
4
|
+
import { pruneRateLimits } from "../../../core";
|
|
5
|
+
|
|
6
|
+
import { isAuthorized, unauthorized } from "./_authorize";
|
|
7
|
+
|
|
8
|
+
export const prerender = false;
|
|
9
|
+
|
|
10
|
+
const cmsRuntime = cms as Record<string, any> & { tasks: typeof cms.tasks };
|
|
11
|
+
|
|
12
|
+
const handler: APIRoute = async ({ request }) => {
|
|
13
|
+
if (!isAuthorized(request)) {
|
|
14
|
+
return unauthorized();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const scheduled = await cmsRuntime.tasks.tick();
|
|
18
|
+
const result = await cmsRuntime.tasks.drain();
|
|
19
|
+
await cmsRuntime.tasks.prune();
|
|
20
|
+
await pruneRateLimits();
|
|
21
|
+
|
|
22
|
+
return Response.json({
|
|
23
|
+
ok: true,
|
|
24
|
+
scheduled,
|
|
25
|
+
processed: result.processed,
|
|
26
|
+
succeeded: result.succeeded,
|
|
27
|
+
failed: result.failed,
|
|
28
|
+
processedAt: new Date().toISOString(),
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const GET = handler;
|
|
33
|
+
export const POST = handler;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
import { cms } from "virtual:kide/api";
|
|
3
|
+
import { sendFormSubmissionEmail, isEmailConfigured } from "virtual:kide/email";
|
|
4
|
+
import { hitRateLimit, PayloadTooLargeError, readLimitedFormData } from "../../../../core";
|
|
5
|
+
|
|
6
|
+
export const prerender = false;
|
|
7
|
+
|
|
8
|
+
// Abuse bounds for this public endpoint (beyond the honeypot).
|
|
9
|
+
const MAX_BODY_BYTES = 100 * 1024;
|
|
10
|
+
const MAX_FIELDS = 100;
|
|
11
|
+
const MAX_VALUE_LENGTH = 10_000;
|
|
12
|
+
const RATE_MAX = 10; // submissions per IP per window
|
|
13
|
+
const RATE_WINDOW_MS = 10 * 60 * 1000;
|
|
14
|
+
|
|
15
|
+
type FormFieldConfig = {
|
|
16
|
+
type: "text" | "email" | "textarea" | "select" | "checkbox";
|
|
17
|
+
name: string;
|
|
18
|
+
label: string;
|
|
19
|
+
required?: boolean;
|
|
20
|
+
maxLength?: number;
|
|
21
|
+
options?: string[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const POST: APIRoute = async ({ request, params, redirect, clientAddress }) => {
|
|
25
|
+
const slug = String(params.slug ?? "");
|
|
26
|
+
if (!slug) return new Response("Not found", { status: 404 });
|
|
27
|
+
|
|
28
|
+
// Durable per-IP throttle (keyed on Astro's trusted clientAddress, not a spoofable header).
|
|
29
|
+
const limit = await hitRateLimit("forms:ip", clientAddress, {
|
|
30
|
+
max: RATE_MAX,
|
|
31
|
+
windowMs: RATE_WINDOW_MS,
|
|
32
|
+
failClosed: true,
|
|
33
|
+
});
|
|
34
|
+
if (!limit.ok) {
|
|
35
|
+
return new Response("Too many submissions. Try again later.", {
|
|
36
|
+
status: 429,
|
|
37
|
+
headers: { "Retry-After": String(Math.ceil(limit.retryAfterMs / 1000)) },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Enforce the body cap on the raw byte stream — Content-Length is optional (absent on
|
|
42
|
+
// chunked requests), so a header-only check can't stop an unbounded body.
|
|
43
|
+
let formData: FormData;
|
|
44
|
+
try {
|
|
45
|
+
formData = await readLimitedFormData(request, MAX_BODY_BYTES);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (error instanceof PayloadTooLargeError) return new Response("Payload too large", { status: 413 });
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Bound the number of submitted fields.
|
|
52
|
+
if ([...formData.keys()].length > MAX_FIELDS) {
|
|
53
|
+
return new Response("Too many fields", { status: 413 });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Honeypot — silently accept bot submissions without storing
|
|
57
|
+
if (String(formData.get("_hp") ?? "").trim()) {
|
|
58
|
+
return redirect(buildRedirectUrl(request, null, true), 303);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const form = await cms.forms.findOne({ where: { slug } }, { _system: true });
|
|
62
|
+
if (!form) return new Response("Form not found", { status: 404 });
|
|
63
|
+
|
|
64
|
+
const fieldConfigs = Array.isArray(form.fields) ? (form.fields as FormFieldConfig[]) : [];
|
|
65
|
+
const errors: string[] = [];
|
|
66
|
+
const data: Record<string, unknown> = {};
|
|
67
|
+
|
|
68
|
+
for (const field of fieldConfigs) {
|
|
69
|
+
const raw = formData.get(field.name);
|
|
70
|
+
const value = field.type === "checkbox" ? raw === "on" || raw === "true" : String(raw ?? "").trim();
|
|
71
|
+
|
|
72
|
+
if (field.required && (field.type === "checkbox" ? value === false : value === "")) {
|
|
73
|
+
errors.push(`${field.label} is required`);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (typeof value === "string" && value.length > MAX_VALUE_LENGTH) {
|
|
78
|
+
errors.push(`${field.label} is too long`);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (field.type === "email" && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value))) {
|
|
83
|
+
errors.push(`${field.label} must be a valid email`);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (field.type === "text" && field.maxLength && typeof value === "string" && value.length > field.maxLength) {
|
|
88
|
+
errors.push(`${field.label} must be ${field.maxLength} characters or fewer`);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (field.type === "select" && value && Array.isArray(field.options) && !field.options.includes(String(value))) {
|
|
93
|
+
errors.push(`${field.label} has an invalid value`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
data[field.name] = value;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (errors.length > 0) {
|
|
101
|
+
return redirect(buildRedirectUrl(request, errors.join(", "), false), 303);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Collect context fields set by the host page via <CmsForm context={{...}} />.
|
|
105
|
+
const context: Record<string, string> = {};
|
|
106
|
+
for (const [key, value] of formData.entries()) {
|
|
107
|
+
if (key.startsWith("_ctx_")) context[key.slice(5)] = String(value);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
try {
|
|
111
|
+
await cms["form-submissions"].create(
|
|
112
|
+
{
|
|
113
|
+
form: form._id,
|
|
114
|
+
status: "new",
|
|
115
|
+
data: Object.keys(context).length > 0 ? { ...data, _context: context } : data,
|
|
116
|
+
},
|
|
117
|
+
{ _system: true },
|
|
118
|
+
);
|
|
119
|
+
} catch (err) {
|
|
120
|
+
console.error("[forms] Failed to save submission:", err);
|
|
121
|
+
return redirect(buildRedirectUrl(request, "Could not save submission", false), 303);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (form.notificationEmail && isEmailConfigured()) {
|
|
125
|
+
await sendFormSubmissionEmail(String(form.notificationEmail), String(form.title), data);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (form.submitRedirect) {
|
|
129
|
+
return redirect(String(form.submitRedirect), 303);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return redirect(buildRedirectUrl(request, null, true), 303);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
function buildRedirectUrl(request: Request, errorMessage: string | null, success: boolean): string {
|
|
136
|
+
const referer = request.headers.get("referer");
|
|
137
|
+
const url = new URL(referer ?? "/", new URL(request.url).origin);
|
|
138
|
+
url.searchParams.delete("submitted");
|
|
139
|
+
url.searchParams.delete("formError");
|
|
140
|
+
if (success) url.searchParams.set("submitted", "1");
|
|
141
|
+
if (errorMessage) url.searchParams.set("formError", errorMessage);
|
|
142
|
+
return url.pathname + url.search;
|
|
143
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
import { getStorage, transformImage } from "../../../core";
|
|
3
|
+
|
|
4
|
+
export const prerender = false;
|
|
5
|
+
|
|
6
|
+
const MIME_TYPES: Record<string, string> = {
|
|
7
|
+
".jpg": "image/jpeg",
|
|
8
|
+
".jpeg": "image/jpeg",
|
|
9
|
+
".png": "image/png",
|
|
10
|
+
".gif": "image/gif",
|
|
11
|
+
".webp": "image/webp",
|
|
12
|
+
".avif": "image/avif",
|
|
13
|
+
".svg": "image/svg+xml",
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const INLINE_SAFE_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp", "image/avif"]);
|
|
17
|
+
|
|
18
|
+
const originalContentType = (src: string) =>
|
|
19
|
+
MIME_TYPES[src.slice(src.lastIndexOf(".")).toLowerCase()] ?? "application/octet-stream";
|
|
20
|
+
|
|
21
|
+
export const GET: APIRoute = async ({ params, url }) => {
|
|
22
|
+
const src = `/${params.path}`;
|
|
23
|
+
const num = (key: string) => (url.searchParams.get(key) ? Number(url.searchParams.get(key)) : undefined);
|
|
24
|
+
|
|
25
|
+
// On-the-fly resizing needs sharp + a real filesystem (public/). On the
|
|
26
|
+
// Cloudflare target sharp is removed and the dev runtime is workerd (no fs),
|
|
27
|
+
// and uploads live in object storage rather than public/ — so transformImage
|
|
28
|
+
// can't run. Attempt it, but fall back to streaming the untransformed original
|
|
29
|
+
// from storage so images still load. (In production on Cloudflare this route
|
|
30
|
+
// is bypassed entirely: cmsImage() emits /cdn-cgi/image URLs there.)
|
|
31
|
+
try {
|
|
32
|
+
const result = await transformImage(src, {
|
|
33
|
+
width: num("w"),
|
|
34
|
+
height: num("h"),
|
|
35
|
+
format: url.searchParams.get("f") || "webp",
|
|
36
|
+
quality: num("q"),
|
|
37
|
+
focalX: num("fx") ?? null,
|
|
38
|
+
focalY: num("fy") ?? null,
|
|
39
|
+
});
|
|
40
|
+
if (result) {
|
|
41
|
+
return new Response(new Uint8Array(result.buffer), {
|
|
42
|
+
headers: {
|
|
43
|
+
"Content-Type": result.contentType,
|
|
44
|
+
"Cache-Control": "public, max-age=31536000, immutable",
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
} catch {
|
|
49
|
+
// sharp unavailable / no filesystem in this runtime — serve the original.
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const data = await getStorage().getFile(src);
|
|
53
|
+
if (!data) return new Response("Not found", { status: 404 });
|
|
54
|
+
|
|
55
|
+
// Untransformed, so the type comes from the stored extension. Only rasters render inline.
|
|
56
|
+
const contentType = originalContentType(src);
|
|
57
|
+
const headers: Record<string, string> = {
|
|
58
|
+
"Content-Type": contentType,
|
|
59
|
+
"Cache-Control": "public, max-age=31536000, immutable",
|
|
60
|
+
"X-Content-Type-Options": "nosniff",
|
|
61
|
+
};
|
|
62
|
+
if (!INLINE_SAFE_TYPES.has(contentType)) headers["Content-Disposition"] = "attachment";
|
|
63
|
+
|
|
64
|
+
return new Response(data, { headers });
|
|
65
|
+
};
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { APIRoute } from "astro";
|
|
2
2
|
import { experimental_AstroContainer as AstroContainer } from "astro/container";
|
|
3
3
|
import { loadRenderers } from "astro:container";
|
|
4
|
-
import { getContainerRenderer } from "@astrojs/react";
|
|
4
|
+
import { getContainerRenderer } from "@astrojs/react/container-renderer";
|
|
5
5
|
|
|
6
6
|
import BlockRenderer from "virtual:kide/block-renderer";
|
|
7
|
-
import
|
|
7
|
+
import ContentRenderer from "virtual:kide/content-renderer";
|
|
8
|
+
import { renderRichText, parseBlocks } from "../../../core";
|
|
8
9
|
|
|
9
10
|
export const prerender = false;
|
|
10
11
|
|
|
@@ -26,7 +27,11 @@ export const POST: APIRoute = async ({ request }) => {
|
|
|
26
27
|
if (type === "blocks") {
|
|
27
28
|
const blocks = parseBlocks(data);
|
|
28
29
|
const container = await getContainer();
|
|
29
|
-
html = await container.renderToString(BlockRenderer, { props: { blocks } });
|
|
30
|
+
html = await container.renderToString(BlockRenderer, { props: { blocks, status: "any" } });
|
|
31
|
+
} else if (type === "content") {
|
|
32
|
+
const parsed = typeof data === "string" ? JSON.parse(data) : data;
|
|
33
|
+
const container = await getContainer();
|
|
34
|
+
html = await container.renderToString(ContentRenderer, { props: { content: parsed, status: "any" } });
|
|
30
35
|
} else if (type === "richText") {
|
|
31
36
|
const parsed = typeof data === "string" ? JSON.parse(data) : data;
|
|
32
37
|
html = renderRichText(parsed) ?? "";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { APIRoute } from "astro";
|
|
2
2
|
import config from "virtual:kide/config";
|
|
3
3
|
import { cms } from "virtual:kide/api";
|
|
4
|
-
import { getLabelField } from "
|
|
4
|
+
import { SHARED_SECTIONS_COLLECTION, extractSharedSectionRefsFromDocument, getLabelField } from "../../../../core";
|
|
5
5
|
|
|
6
6
|
export const prerender = false;
|
|
7
7
|
|
|
@@ -18,6 +18,36 @@ export const GET: APIRoute = async ({ params }) => {
|
|
|
18
18
|
|
|
19
19
|
const refs: Array<{ collection: string; label: string; count: number }> = [];
|
|
20
20
|
|
|
21
|
+
if (collectionSlug === SHARED_SECTIONS_COLLECTION) {
|
|
22
|
+
for (const otherCollection of config.collections) {
|
|
23
|
+
if (otherCollection.slug === SHARED_SECTIONS_COLLECTION) continue;
|
|
24
|
+
const hasSharedCapableField = Object.values(otherCollection.fields).some(
|
|
25
|
+
(field: any) => (field.type === "blocks" && field.shared !== false) || field.type === "content",
|
|
26
|
+
);
|
|
27
|
+
if (!hasSharedCapableField) continue;
|
|
28
|
+
|
|
29
|
+
const otherApi = cmsRuntime[otherCollection.slug];
|
|
30
|
+
if (!otherApi) continue;
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
const allDocs = await otherApi.find({ status: "any", limit: 500 });
|
|
34
|
+
const count = allDocs.filter((doc: Record<string, unknown>) =>
|
|
35
|
+
extractSharedSectionRefsFromDocument(otherCollection, doc).includes(documentId),
|
|
36
|
+
).length;
|
|
37
|
+
|
|
38
|
+
if (count > 0) {
|
|
39
|
+
refs.push({
|
|
40
|
+
collection: otherCollection.labels.plural,
|
|
41
|
+
label: getLabelField(otherCollection),
|
|
42
|
+
count,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
} catch {}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return Response.json({ refs, total: refs.reduce((sum, r) => sum + r.count, 0) });
|
|
49
|
+
}
|
|
50
|
+
|
|
21
51
|
for (const otherCollection of config.collections) {
|
|
22
52
|
if (otherCollection.slug === collectionSlug) continue;
|
|
23
53
|
const relationFields = Object.entries(otherCollection.fields).filter(
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { APIRoute } from "astro";
|
|
2
|
+
|
|
3
|
+
import { cms } from "virtual:kide/api";
|
|
4
|
+
import { readEnv } from "virtual:kide/runtime";
|
|
5
|
+
|
|
6
|
+
export const prerender = false;
|
|
7
|
+
|
|
8
|
+
const cmsRuntime = cms as Record<string, any> & { tasks: typeof cms.tasks };
|
|
9
|
+
|
|
10
|
+
const hexToBytes = (hex: string) => {
|
|
11
|
+
if (!/^[0-9a-f]*$/i.test(hex) || hex.length === 0 || hex.length % 2 !== 0) return null;
|
|
12
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
13
|
+
for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
14
|
+
return bytes;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const verifySignature = async (body: string, signatureHeader: string, secret: string): Promise<boolean> => {
|
|
18
|
+
const bytes = hexToBytes(signatureHeader.replace(/^sha256=/, "").trim());
|
|
19
|
+
if (!bytes) return false;
|
|
20
|
+
const key = await crypto.subtle.importKey(
|
|
21
|
+
"raw",
|
|
22
|
+
new TextEncoder().encode(secret),
|
|
23
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
24
|
+
false,
|
|
25
|
+
["verify"],
|
|
26
|
+
);
|
|
27
|
+
return crypto.subtle.verify("HMAC", key, bytes, new TextEncoder().encode(body));
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// Verify-then-enqueue: a valid HMAC-signed POST becomes a durable
|
|
31
|
+
// `webhook.<provider>` task; the app handles it in config.integrations.tasks.
|
|
32
|
+
export const POST: APIRoute = async ({ request, params }) => {
|
|
33
|
+
const provider = String(params.provider ?? "").replace(/[^a-zA-Z0-9_-]/g, "");
|
|
34
|
+
const secret = provider ? readEnv(`WEBHOOK_SECRET_${provider.toUpperCase().replace(/-/g, "_")}`) : undefined;
|
|
35
|
+
if (!secret) {
|
|
36
|
+
return Response.json({ error: "Unknown webhook provider" }, { status: 404 });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const body = await request.text();
|
|
40
|
+
const signature = request.headers.get("x-webhook-signature") ?? "";
|
|
41
|
+
if (!(await verifySignature(body, signature, secret))) {
|
|
42
|
+
return Response.json({ error: "Invalid signature" }, { status: 401 });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let payload: unknown;
|
|
46
|
+
try {
|
|
47
|
+
payload = JSON.parse(body);
|
|
48
|
+
} catch {
|
|
49
|
+
return Response.json({ error: "Invalid JSON" }, { status: 400 });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
await cmsRuntime.tasks.enqueue(`webhook.${provider}`, payload);
|
|
53
|
+
return Response.json({ received: true });
|
|
54
|
+
};
|
package/README.md
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
# `@kidecms/core`
|
|
2
|
-
|
|
3
|
-
Kide's runtime and admin package.
|
|
4
|
-
|
|
5
|
-
## Install shape
|
|
6
|
-
|
|
7
|
-
The goal is to keep onboarding simple:
|
|
8
|
-
|
|
9
|
-
- `@kidecms/core` brings its own CMS runtime, generator, and admin UI dependencies.
|
|
10
|
-
- The host app provides `react` and `react-dom`.
|
|
11
|
-
- Some features are optional:
|
|
12
|
-
- `@ai-sdk/openai` only when AI generation is enabled
|
|
13
|
-
- `sharp` only when local image transforms are enabled
|
|
14
|
-
|
|
15
|
-
## Why some packages still exist in the app
|
|
16
|
-
|
|
17
|
-
Kide keeps project-specific code inside the app:
|
|
18
|
-
|
|
19
|
-
- database adapters
|
|
20
|
-
- storage adapters
|
|
21
|
-
- email adapters
|
|
22
|
-
- generated schema files
|
|
23
|
-
- framework route glue
|
|
24
|
-
|
|
25
|
-
Because those files live in the app, the app may still depend on packages like
|
|
26
|
-
`drizzle-orm`, `zod`, or `nanoid` when it imports them directly.
|
|
27
|
-
|
|
28
|
-
That is separate from `@kidecms/core`'s own package contract.
|
package/dist/admin.d.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import type { CMSConfig, CollectionConfig, FieldConfig } from "./define";
|
|
2
|
-
export declare const initDateFormat: (config: CMSConfig, nextTimeZone?: string) => void;
|
|
3
|
-
export declare const formatDate: (value: unknown) => string;
|
|
4
|
-
export type AdminRoute = {
|
|
5
|
-
kind: "dashboard";
|
|
6
|
-
} | {
|
|
7
|
-
kind: "recent";
|
|
8
|
-
} | {
|
|
9
|
-
kind: "singles";
|
|
10
|
-
} | {
|
|
11
|
-
kind: "list";
|
|
12
|
-
collectionSlug: string;
|
|
13
|
-
} | {
|
|
14
|
-
kind: "new";
|
|
15
|
-
collectionSlug: string;
|
|
16
|
-
} | {
|
|
17
|
-
kind: "edit";
|
|
18
|
-
collectionSlug: string;
|
|
19
|
-
documentId: string;
|
|
20
|
-
};
|
|
21
|
-
export declare const resolveAdminRoute: (path: string | undefined) => AdminRoute;
|
|
22
|
-
export declare const humanize: (value: string) => string;
|
|
23
|
-
export declare const formatFieldValue: (field: FieldConfig | undefined, value: unknown, relationLabels?: Record<string, string>) => string;
|
|
24
|
-
export declare const getListColumns: (collection: CollectionConfig, viewConfig?: {
|
|
25
|
-
columns?: string[];
|
|
26
|
-
}) => string[];
|
|
27
|
-
export declare const getFieldSets: (collection: CollectionConfig) => ({
|
|
28
|
-
fields: string[];
|
|
29
|
-
position: "content";
|
|
30
|
-
} | {
|
|
31
|
-
fields: string[];
|
|
32
|
-
position: "sidebar";
|
|
33
|
-
})[];
|