@kidecms/core 0.27.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ import { useRef } from "react";
2
+ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "./ui/sheet";
3
+
4
+ export type EditedAsset = { _id: string; alt: string | null; focalX: number | null; focalY: number | null };
5
+
6
+ type Props = {
7
+ assetId: string | null;
8
+ open: boolean;
9
+ onOpenChange: (open: boolean) => void;
10
+ onSaved?: (asset: EditedAsset) => void;
11
+ onDeleted?: () => void;
12
+ };
13
+
14
+ /**
15
+ * The asset's own edit page in a side panel. Its form posts redirect inside the iframe,
16
+ * so a successful save or delete shows up as a same-origin navigation.
17
+ */
18
+ export default function AssetEditSheet({ assetId, open, onOpenChange, onSaved, onDeleted }: Props) {
19
+ const frameRef = useRef<HTMLIFrameElement>(null);
20
+
21
+ const handleLoad = () => {
22
+ const location = frameRef.current?.contentWindow?.location;
23
+ if (!location || !assetId) return;
24
+ if (new URLSearchParams(location.search).get("_toast") !== "success") return;
25
+
26
+ if (location.pathname === `/admin/assets/${assetId}`) {
27
+ onOpenChange(false);
28
+ fetch(`/api/cms/assets/${assetId}`)
29
+ .then((res) => (res.ok ? res.json() : null))
30
+ .then((asset) => {
31
+ if (asset) onSaved?.(asset);
32
+ })
33
+ .catch(() => {});
34
+ } else if (location.pathname === "/admin/assets") {
35
+ onOpenChange(false);
36
+ onDeleted?.();
37
+ }
38
+ };
39
+
40
+ return (
41
+ <Sheet open={open} onOpenChange={onOpenChange}>
42
+ <SheetContent
43
+ side="right"
44
+ className="data-[side=right]:w-[90vw] data-[side=right]:sm:max-w-[90vw] data-[side=right]:lg:w-[50vw] data-[side=right]:lg:max-w-[50vw]"
45
+ >
46
+ <SheetHeader className="sr-only">
47
+ <SheetTitle>Edit image</SheetTitle>
48
+ </SheetHeader>
49
+ <div className="flex-1 overflow-hidden">
50
+ {open && assetId && (
51
+ <iframe
52
+ ref={frameRef}
53
+ src={`/admin/assets/${assetId}?_embed=1`}
54
+ title="Edit image"
55
+ className="size-full"
56
+ onLoad={handleLoad}
57
+ />
58
+ )}
59
+ </div>
60
+ </SheetContent>
61
+ </Sheet>
62
+ );
63
+ }
@@ -711,7 +711,11 @@ export default function ContentEditor({
711
711
  open={imageBrowseOpen}
712
712
  onOpenChange={setImageBrowseOpen}
713
713
  onSelect={(asset) => {
714
- editor?.chain().focus().setImage({ src: asset.url, alt: asset.filename }).run();
714
+ editor
715
+ ?.chain()
716
+ .focus()
717
+ .setImage({ src: asset.url, alt: asset.alt ?? "" })
718
+ .run();
715
719
  }}
716
720
  />
717
721
 
@@ -4,9 +4,9 @@ import { useEffect, useRef, useState, type RefObject } from "react";
4
4
  import type { Editor } from "@tiptap/core";
5
5
  import Image from "@tiptap/extension-image";
6
6
  import { NodeViewWrapper, ReactNodeViewRenderer, type NodeViewProps } from "@tiptap/react";
7
- import { ImageIcon, Trash2 } from "lucide-react";
7
+ import { ImageIcon, Pencil, Trash2 } from "lucide-react";
8
8
  import { Button } from "./ui/button";
9
- import { Input } from "./ui/input";
9
+ import AssetEditSheet from "./AssetEditSheet";
10
10
  import ImageBrowseDialog from "./ImageBrowseDialog";
11
11
  import { cn, thumbnail } from "../lib/utils";
12
12
 
@@ -37,17 +37,27 @@ function useEditorFocus(editor: Editor, within: RefObject<HTMLElement | null>) {
37
37
  }
38
38
 
39
39
  /**
40
- * Inline image in rich text / content fields. Selecting it reveals alt text,
41
- * replace (asset browser) and remove, so an image is editable rather than a
42
- * fixed blob that can only be deleted.
40
+ * Inline image in rich text / content fields. Selecting it reveals edit (the asset's
41
+ * own edit view, where alt text and focal point live), replace, and remove.
43
42
  */
44
43
  function ImageNodeView({ node, selected, editor, getPos, updateAttributes, deleteNode }: NodeViewProps) {
45
44
  const [browseOpen, setBrowseOpen] = useState(false);
45
+ const [editAssetId, setEditAssetId] = useState<string | null>(null);
46
46
  const [focusWithin, setFocusWithin] = useState(false);
47
47
  const wrapperRef = useRef<HTMLDivElement>(null);
48
48
  const focused = useEditorFocus(editor, wrapperRef);
49
49
  const src = String(node.attrs.src ?? "");
50
50
  const alt = String(node.attrs.alt ?? "");
51
+ const isUpload = src.startsWith("/uploads/");
52
+
53
+ const openEdit = () => {
54
+ fetch(`/api/cms/assets?url=${encodeURIComponent(src)}`)
55
+ .then((res) => (res.ok ? res.json() : null))
56
+ .then((asset) => {
57
+ if (asset?._id) setEditAssetId(asset._id);
58
+ })
59
+ .catch(() => {});
60
+ };
51
61
 
52
62
  // On load the initial selection sits on the first block, so `selected` alone
53
63
  // would show the controls before anyone clicked — require editor focus too.
@@ -108,15 +118,14 @@ function ImageNodeView({ node, selected, editor, getPos, updateAttributes, delet
108
118
  {active && (
109
119
  <div
110
120
  contentEditable={false}
111
- className="bg-popover mt-2 flex flex-wrap items-center gap-2 rounded-md border p-1.5 shadow-xs"
121
+ className="bg-popover mt-2 flex flex-wrap items-center justify-end gap-2 rounded-md border p-1.5 shadow-xs"
112
122
  >
113
- <Input
114
- value={alt}
115
- onChange={(e) => updateAttributes({ alt: e.target.value })}
116
- placeholder="Alt text"
117
- aria-label="Alt text"
118
- className="h-8 min-w-40 flex-1"
119
- />
123
+ {isUpload && (
124
+ <Button type="button" variant="outline" size="sm" onClick={openEdit}>
125
+ <Pencil className="size-3.5" />
126
+ Edit
127
+ </Button>
128
+ )}
120
129
  <Button type="button" variant="outline" size="sm" onClick={() => setBrowseOpen(true)}>
121
130
  <ImageIcon className="size-3.5" />
122
131
  Replace
@@ -130,7 +139,15 @@ function ImageNodeView({ node, selected, editor, getPos, updateAttributes, delet
130
139
  <ImageBrowseDialog
131
140
  open={browseOpen}
132
141
  onOpenChange={setBrowseOpen}
133
- onSelect={(asset) => updateAttributes({ src: asset.url, alt: alt || asset.filename })}
142
+ onSelect={(asset) => updateAttributes({ src: asset.url, alt: asset.alt ?? "" })}
143
+ />
144
+ <AssetEditSheet
145
+ assetId={editAssetId}
146
+ open={editAssetId !== null}
147
+ onOpenChange={(open) => {
148
+ if (!open) setEditAssetId(null);
149
+ }}
150
+ onDeleted={deleteNode}
134
151
  />
135
152
  </NodeViewWrapper>
136
153
  );
@@ -8,6 +8,7 @@ type AssetRecord = {
8
8
  filename: string;
9
9
  mimeType: string;
10
10
  url: string;
11
+ alt?: string | null;
11
12
  focalX?: number | null;
12
13
  focalY?: number | null;
13
14
  _createdAt: string;
@@ -1,7 +1,8 @@
1
1
  import { useState, useRef, useCallback, useEffect } from "react";
2
2
  import { ImagePlus, Loader2, Upload, X } from "lucide-react";
3
- import { cn, focalPointStyle, thumbnail } from "../lib/utils";
3
+ import { cn, thumbnail } from "../lib/utils";
4
4
  import { Button } from "./ui/button";
5
+ import AssetEditSheet from "./AssetEditSheet";
5
6
  import ImageBrowseDialog from "./ImageBrowseDialog";
6
7
 
7
8
  type Props = {
@@ -14,10 +15,10 @@ type Props = {
14
15
  export default function ImagePicker({ name, value: initialValue, onChange: onChangeProp }: Props) {
15
16
  const [value, setValue] = useState(initialValue ?? "");
16
17
  const [assetId, setAssetId] = useState<string | null>(null);
17
- const [focal, setFocal] = useState<{ focalX: number | null; focalY: number | null } | null>(null);
18
18
  const [localPreview, setLocalPreview] = useState<string | null>(null);
19
19
  const [uploading, setUploading] = useState(false);
20
20
  const [open, setOpen] = useState(false);
21
+ const [editOpen, setEditOpen] = useState(false);
21
22
  const fileInputRef = useRef<HTMLInputElement>(null);
22
23
  const hiddenRef = useRef<HTMLInputElement>(null);
23
24
 
@@ -29,7 +30,6 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
29
30
  .then((asset) => {
30
31
  if (asset?._id) {
31
32
  setAssetId(asset._id);
32
- setFocal({ focalX: asset.focalX ?? null, focalY: asset.focalY ?? null });
33
33
  }
34
34
  })
35
35
  .catch(() => {});
@@ -57,7 +57,6 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
57
57
  const asset = await res.json();
58
58
  setValue(asset.url);
59
59
  setAssetId(asset._id);
60
- setFocal({ focalX: asset.focalX ?? null, focalY: asset.focalY ?? null });
61
60
  onChangeProp?.(asset.url);
62
61
  } catch (e) {
63
62
  console.error("Upload failed:", e);
@@ -88,21 +87,18 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
88
87
  {value && (
89
88
  <div className="group relative inline-block">
90
89
  {isImage ? (
91
- <a
92
- href={assetId ? `/admin/assets/${assetId}` : undefined}
93
- target="_blank"
90
+ <button
91
+ type="button"
92
+ title={assetId ? "Edit image" : undefined}
93
+ disabled={!assetId}
94
+ onClick={() => setEditOpen(true)}
94
95
  className={cn(
95
96
  "block size-40 overflow-hidden rounded-lg border",
96
97
  assetId && "hover:border-foreground/50 cursor-pointer",
97
98
  )}
98
99
  >
99
- <img
100
- src={imgSrc}
101
- alt=""
102
- className="size-full object-cover"
103
- style={localPreview ? undefined : focal ? focalPointStyle(focal) : undefined}
104
- />
105
- </a>
100
+ <img src={imgSrc} alt="" className="size-full object-cover" />
101
+ </button>
106
102
  ) : (
107
103
  <div className="bg-field flex size-40 items-center justify-center rounded-lg border">
108
104
  <span className="text-muted-foreground truncate px-4 text-sm">{value}</span>
@@ -143,6 +139,17 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
143
139
  </Button>
144
140
  </div>
145
141
 
142
+ <AssetEditSheet
143
+ assetId={assetId}
144
+ open={editOpen}
145
+ onOpenChange={setEditOpen}
146
+ onDeleted={() => {
147
+ setValue("");
148
+ setAssetId(null);
149
+ onChangeProp?.("");
150
+ }}
151
+ />
152
+
146
153
  <ImageBrowseDialog
147
154
  open={open}
148
155
  onOpenChange={setOpen}
@@ -151,7 +158,6 @@ export default function ImagePicker({ name, value: initialValue, onChange: onCha
151
158
  setLocalPreview(null);
152
159
  setValue(asset.url);
153
160
  setAssetId(asset._id);
154
- setFocal({ focalX: asset.focalX ?? null, focalY: asset.focalY ?? null });
155
161
  onChangeProp?.(asset.url);
156
162
  }}
157
163
  />
@@ -711,7 +711,11 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
711
711
  open={imageBrowseOpen}
712
712
  onOpenChange={setImageBrowseOpen}
713
713
  onSelect={(asset) => {
714
- editor?.chain().focus().setImage({ src: asset.url, alt: asset.filename }).run();
714
+ editor
715
+ ?.chain()
716
+ .focus()
717
+ .setImage({ src: asset.url, alt: asset.alt ?? "" })
718
+ .run();
715
719
  }}
716
720
  />
717
721
 
package/core/assets.ts CHANGED
@@ -382,47 +382,64 @@ const collectLocalImageSrcs = (node: unknown, into: Set<string>): void => {
382
382
  if (Array.isArray(candidate.children)) collectLocalImageSrcs(candidate.children, into);
383
383
  };
384
384
 
385
- const withoutMissingImages = <T>(node: T, missing: Set<string>): T => {
385
+ /** Rebuilds a document with missing images dropped and alt text taken from the asset record. */
386
+ const resolveImages = <T>(node: T, found: Map<string, AssetRecord | null>, changed: { value: boolean }): T => {
386
387
  if (Array.isArray(node)) {
387
- return node
388
- .filter((child) => {
389
- const candidate = child as RichTextLikeNode | null;
390
- return !(
391
- candidate &&
392
- typeof candidate === "object" &&
393
- candidate.type === "image" &&
394
- typeof candidate.src === "string" &&
395
- missing.has(candidate.src)
396
- );
397
- })
398
- .map((child) => withoutMissingImages(child, missing)) as unknown as T;
388
+ const next: unknown[] = [];
389
+ for (const child of node) {
390
+ const candidate = child as RichTextLikeNode | null;
391
+ const src = candidate && typeof candidate === "object" && candidate.type === "image" ? candidate.src : undefined;
392
+ if (typeof src === "string" && found.has(src)) {
393
+ const asset = found.get(src);
394
+ if (!asset) {
395
+ changed.value = true;
396
+ continue;
397
+ }
398
+ const alt = imageAlt(asset, (candidate as { alt?: unknown }).alt);
399
+ if (alt !== (candidate as { alt?: unknown }).alt) {
400
+ changed.value = true;
401
+ next.push({ ...candidate, alt });
402
+ continue;
403
+ }
404
+ }
405
+ next.push(resolveImages(child, found, changed));
406
+ }
407
+ return next as unknown as T;
399
408
  }
400
409
  if (!node || typeof node !== "object") return node;
401
410
 
402
411
  const candidate = node as RichTextLikeNode;
403
412
  if (!Array.isArray(candidate.children)) return node;
404
- return { ...candidate, children: withoutMissingImages(candidate.children, missing) } as unknown as T;
413
+ return { ...candidate, children: resolveImages(candidate.children, found, changed) } as unknown as T;
414
+ };
415
+
416
+ /**
417
+ * The asset's alt text wins. The node's own alt is only a fallback, and not when it is just
418
+ * the filename the editor used to fill in on insert.
419
+ */
420
+ const imageAlt = (asset: AssetRecord, nodeAlt: unknown): string => {
421
+ if (asset.alt) return asset.alt;
422
+ const own = typeof nodeAlt === "string" ? nodeAlt : "";
423
+ return own === asset.filename ? "" : own;
405
424
  };
406
425
 
407
426
  /**
408
- * Drops `image` nodes whose upload no longer exists from a rich-text / content
409
- * document. The renderers are synchronous string builders, so this is the async
410
- * pass that keeps a deleted asset from emitting a <picture> of 404s.
427
+ * Resolves inline `image` nodes in a rich-text / content document against the asset
428
+ * records: images whose upload no longer exists are dropped (so a deleted asset doesn't
429
+ * emit a <picture> of 404s), and alt text comes from the asset. The renderers are
430
+ * synchronous string builders, so this is their async pass.
411
431
  *
412
- * Returns the document unchanged when nothing is missing (the common case).
432
+ * Returns the document unchanged when nothing needs resolving.
413
433
  */
414
434
  export const stripMissingAssetImages = async <T>(document: T): Promise<T> => {
415
435
  const srcs = new Set<string>();
416
436
  collectLocalImageSrcs(document, srcs);
417
437
  if (srcs.size === 0) return document;
418
438
 
419
- const missing = new Set<string>();
420
- await Promise.all(
421
- [...srcs].map(async (src) => {
422
- if (!(await assets.findByUrl(src))) missing.add(src);
423
- }),
424
- );
425
- if (missing.size === 0) return document;
439
+ const found = new Map<string, AssetRecord | null>();
440
+ await Promise.all([...srcs].map(async (src) => found.set(src, await assets.findByUrl(src))));
426
441
 
427
- return withoutMissingImages(document, missing);
442
+ const changed = { value: false };
443
+ const resolved = resolveImages(document, found, changed);
444
+ return changed.value ? resolved : document;
428
445
  };
package/core/http.ts CHANGED
@@ -1,5 +1,70 @@
1
+ import { readEnv } from "./runtime";
2
+
1
3
  export class PayloadTooLargeError extends Error {}
2
4
 
5
+ /**
6
+ * The origin to put in links we hand out (password-reset and invite emails, SSO
7
+ * redirect_uri). `request.url` is built from the incoming Host header on the Node
8
+ * adapter unless Astro's `security.allowedDomains` is set, so a forged Host would
9
+ * otherwise land in the victim's reset email pointing at the attacker's domain.
10
+ * `CMS_TRUSTED_ORIGIN` pins it; the same value anchors the middleware's CSRF check.
11
+ */
12
+ export const publicOrigin = (request: Request): string => {
13
+ const configured = readEnv("CMS_TRUSTED_ORIGIN");
14
+ if (configured) {
15
+ try {
16
+ return new URL(configured).origin;
17
+ } catch {
18
+ // Malformed value — fall through to the request's own origin.
19
+ }
20
+ }
21
+ return new URL(request.url).origin;
22
+ };
23
+
24
+ /**
25
+ * Whether a storage path is one the unauthenticated file routes may read. Assets are
26
+ * always written as `/uploads/<id>.<ext>`; anything else (another prefix, an empty or
27
+ * dot segment) is never a served upload. Node's storage adapter rejects traversal on
28
+ * its own, but object stores treat any key as valid — without this, `/api/cms/img/x`
29
+ * would read arbitrary objects from a shared R2 bucket.
30
+ */
31
+ export const isPublicUploadPath = (storagePath: string): boolean => {
32
+ if (!storagePath.startsWith("/uploads/")) return false;
33
+ const segments = storagePath.slice("/uploads/".length).split("/");
34
+ return segments.every((segment) => segment !== "" && segment !== "." && segment !== "..");
35
+ };
36
+
37
+ /**
38
+ * Reads a request body as text while enforcing a byte cap on the stream itself (see
39
+ * readLimitedFormData for why Content-Length is not enough). Rejects with
40
+ * `PayloadTooLargeError` when exceeded.
41
+ */
42
+ export const readLimitedText = async (request: Request, maxBytes: number): Promise<string> => {
43
+ if (!request.body) return "";
44
+
45
+ const chunks: Uint8Array[] = [];
46
+ let total = 0;
47
+ const reader = request.body.getReader();
48
+ for (;;) {
49
+ const { done, value } = await reader.read();
50
+ if (done) break;
51
+ total += value.byteLength;
52
+ if (total > maxBytes) {
53
+ await reader.cancel().catch(() => {});
54
+ throw new PayloadTooLargeError(`Body exceeds ${maxBytes} bytes`);
55
+ }
56
+ chunks.push(value);
57
+ }
58
+
59
+ const joined = new Uint8Array(total);
60
+ let offset = 0;
61
+ for (const chunk of chunks) {
62
+ joined.set(chunk, offset);
63
+ offset += chunk.byteLength;
64
+ }
65
+ return new TextDecoder().decode(joined);
66
+ };
67
+
3
68
  /**
4
69
  * Parses a request body as FormData while enforcing a hard byte cap on the stream itself —
5
70
  * unlike checking `Content-Length` (optional, and absent on chunked-encoded requests) or
@@ -40,3 +105,33 @@ export const readLimitedFormData = async (request: Request, maxBytes: number): P
40
105
  });
41
106
  return limitedRequest.formData();
42
107
  };
108
+
109
+ const startsWith = (header: Uint8Array, bytes: number[], offset = 0) =>
110
+ bytes.every((byte, i) => header[offset + i] === byte);
111
+
112
+ const ascii = (header: Uint8Array, from: number, to: number) => String.fromCharCode(...header.slice(from, to));
113
+
114
+ const HEADER_CHECKS: Record<string, (header: Uint8Array) => boolean> = {
115
+ "image/jpeg": (h) => startsWith(h, [0xff, 0xd8, 0xff]),
116
+ "image/png": (h) => startsWith(h, [0x89, 0x50, 0x4e, 0x47]),
117
+ "image/gif": (h) => startsWith(h, [0x47, 0x49, 0x46, 0x38]),
118
+ "image/webp": (h) => startsWith(h, [0x52, 0x49, 0x46, 0x46]),
119
+ "image/avif": (h) => ascii(h, 4, 8) === "ftyp" && ascii(h, 8, 12).includes("avif"),
120
+ "application/pdf": (h) => startsWith(h, [0x25, 0x50, 0x44, 0x46]),
121
+ "video/mp4": (h) => startsWith(h, [0x66, 0x74, 0x79, 0x70], 4),
122
+ "video/webm": (h) => startsWith(h, [0x1a, 0x45, 0xdf, 0xa3]),
123
+ "image/svg+xml": (h) => {
124
+ const text = new TextDecoder().decode(h);
125
+ return text.includes("<svg") || text.trimStart().startsWith("<?xml");
126
+ },
127
+ };
128
+
129
+ /**
130
+ * Whether an upload's first bytes match its declared MIME type. Types without a known
131
+ * signature (added through `admin.uploads.allowedTypes`) pass; their stored extension is
132
+ * sanitised separately so they can't be served as active content.
133
+ */
134
+ export const headerMatchesType = (header: ArrayBuffer, declaredType: string): boolean => {
135
+ const check = HEADER_CHECKS[declaredType];
136
+ return check ? check(new Uint8Array(header)) : true;
137
+ };
package/core/index.ts CHANGED
@@ -192,7 +192,14 @@ export type { AdminRoute } from "./admin";
192
192
 
193
193
  export { acquireLock, releaseLock } from "./locks";
194
194
 
195
- export { readLimitedFormData, PayloadTooLargeError } from "./http";
195
+ export {
196
+ readLimitedFormData,
197
+ readLimitedText,
198
+ publicOrigin,
199
+ isPublicUploadPath,
200
+ headerMatchesType,
201
+ PayloadTooLargeError,
202
+ } from "./http";
196
203
 
197
204
  export { recordAudit, logAudit, pruneAuditLog, auditRequestMeta, tokenReference } from "./audit";
198
205
  export type { AuditEvent, AuditActor } from "./audit";
@@ -1,6 +1,6 @@
1
1
  import { defineMiddleware } from "astro:middleware";
2
2
  import type { APIContext, MiddlewareNext } from "astro";
3
- import { readEnv, resolveAdminAuth, runWithRequestScope } from "../core";
3
+ import { publicOrigin, resolveAdminAuth, runWithRequestScope } from "../core";
4
4
  import type { RequestScope, SessionUser } from "../core";
5
5
  import { eq } from "drizzle-orm";
6
6
 
@@ -38,8 +38,16 @@ export const onRequest = defineMiddleware(async (context, next) => {
38
38
  return runWithRequestScope(scope, async () => {
39
39
  const response = await handle(context, next);
40
40
  // Draft responses must never enter the shared cache. Runs after the page
41
- // rendered because a page-level cache.set() would re-enable caching.
42
- if (context.url.searchParams.has("preview")) context.cache?.set(false);
41
+ // rendered because a page-level cache.set() would re-enable caching. The
42
+ // explicit header covers CDNs/proxies that cache HTML on their own terms.
43
+ if (context.url.searchParams.has("preview")) {
44
+ context.cache?.set(false);
45
+ try {
46
+ response.headers.set("Cache-Control", "no-store");
47
+ } catch {
48
+ // Immutable response (e.g. a static asset) — nothing draft-bearing in it.
49
+ }
50
+ }
43
51
  return response;
44
52
  });
45
53
  });
@@ -113,7 +121,7 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
113
121
  if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && !isMachineEndpoint) {
114
122
  // Compare against an explicitly configured origin when set (robust behind a proxy that
115
123
  // may rewrite Host); otherwise fall back to the request's own origin.
116
- const host = readEnv("CMS_TRUSTED_ORIGIN") ?? context.url.origin;
124
+ const host = publicOrigin(context.request);
117
125
  const origin = context.request.headers.get("origin");
118
126
  const referer = context.request.headers.get("referer");
119
127
  const secFetchSite = context.request.headers.get("sec-fetch-site");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.27.2",
3
+ "version": "0.28.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -32,6 +32,7 @@ if (!id) return Astro.redirect("/admin/assets");
32
32
  const asset = await assets.findById(id);
33
33
  if (!asset) return Astro.redirect("/admin/assets");
34
34
 
35
+ const isEmbed = Astro.url.searchParams.get("_embed") === "1";
35
36
  const aiEnabled = isAiEnabled();
36
37
  const isImage = asset.mimeType.startsWith("image/");
37
38
 
@@ -69,17 +70,22 @@ const folderItems = flattenByParent(
69
70
  collections={accessibleCollections}
70
71
  activeCollection="assets"
71
72
  customNav={config.admin?.nav}
73
+ embed={isEmbed}
72
74
  >
73
75
  <section class="space-y-6 px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
74
76
  <div class="flex items-start justify-between gap-4">
75
77
  <div>
76
- <a
77
- href={asset.folder ? `/admin/assets?folder=${asset.folder}` : "/admin/assets"}
78
- class="text-muted-foreground hover:text-foreground mb-2 inline-flex items-center gap-1 text-sm transition-colors"
79
- >
80
- <ArrowLeft className="size-3.5" />
81
- {currentFolder ? currentFolder.name : "Assets"}
82
- </a>
78
+ {
79
+ !isEmbed && (
80
+ <a
81
+ href={asset.folder ? `/admin/assets?folder=${asset.folder}` : "/admin/assets"}
82
+ class="text-muted-foreground hover:text-foreground mb-2 inline-flex items-center gap-1 text-sm transition-colors"
83
+ >
84
+ <ArrowLeft className="size-3.5" />
85
+ {currentFolder ? currentFolder.name : "Assets"}
86
+ </a>
87
+ )
88
+ }
83
89
  <h1 class="text-2xl font-semibold tracking-tight">{asset.filename}</h1>
84
90
  </div>
85
91
  </div>
@@ -101,6 +107,7 @@ const folderItems = flattenByParent(
101
107
  <UnsavedGuard client:load formId="asset-form" isNew={false} isDraft={false} />
102
108
  <form id="asset-form" method="post" action={`/api/cms/assets/${asset._id}`}>
103
109
  <input type="hidden" name="_action" value="update" />
110
+ {isEmbed && <input type="hidden" name="_embed" value="1" />}
104
111
  <div class="grid gap-6 2xl:grid-cols-[minmax(0,1.55fr)_minmax(380px,460px)]">
105
112
  <div class="space-y-6">
106
113
  {
@@ -1,5 +1,6 @@
1
1
  import type { APIRoute } from "astro";
2
2
  import { isAiEnabled, streamAltText } from "virtual:kide/runtime";
3
+ import { isPublicUploadPath } from "../../../core";
3
4
 
4
5
  export const prerender = false;
5
6
 
@@ -15,6 +16,12 @@ export const POST: APIRoute = async ({ request }) => {
15
16
  return Response.json({ error: "imageUrl and filename are required." }, { status: 400 });
16
17
  }
17
18
 
19
+ // The path goes straight to the storage adapter; only uploads may be read and
20
+ // forwarded to the AI provider (an object store would return any key otherwise).
21
+ if (typeof imageUrl !== "string" || !isPublicUploadPath(imageUrl)) {
22
+ return Response.json({ error: "imageUrl must be an uploaded asset path." }, { status: 400 });
23
+ }
24
+
18
25
  try {
19
26
  const result = await streamAltText(imageUrl, filename);
20
27
  return result.toTextStreamResponse();
@@ -69,6 +69,8 @@ export const POST: APIRoute = async ({ params, request, locals }) => {
69
69
  const method = formData.get("_method");
70
70
  const action = formData.get("_action");
71
71
  const actor = getActor(locals);
72
+ // Keep the side-panel (iframe) layout across the redirect.
73
+ const embed = formData.get("_embed") === "1" ? "&_embed=1" : "";
72
74
 
73
75
  if (method === "DELETE" || action === "delete") {
74
76
  try {
@@ -77,14 +79,14 @@ export const POST: APIRoute = async ({ params, request, locals }) => {
77
79
  if (error instanceof AssetInUseError) {
78
80
  return new Response(null, {
79
81
  status: 303,
80
- headers: { Location: `/admin/assets/${id}?_toast=error&_msg=${encodeURIComponent(error.message)}` },
82
+ headers: { Location: `/admin/assets/${id}?_toast=error&_msg=${encodeURIComponent(error.message)}${embed}` },
81
83
  });
82
84
  }
83
85
  throw error;
84
86
  }
85
87
  return new Response(null, {
86
88
  status: 303,
87
- headers: { Location: "/admin/assets?_toast=success&_msg=Asset+deleted" },
89
+ headers: { Location: `/admin/assets?_toast=success&_msg=Asset+deleted${embed}` },
88
90
  });
89
91
  }
90
92
 
@@ -105,7 +107,7 @@ export const POST: APIRoute = async ({ params, request, locals }) => {
105
107
  );
106
108
  return new Response(null, {
107
109
  status: 303,
108
- headers: { Location: `/admin/assets/${id}?_toast=success&_msg=Asset+updated` },
110
+ headers: { Location: `/admin/assets/${id}?_toast=success&_msg=Asset+updated${embed}` },
109
111
  });
110
112
  }
111
113
 
@@ -1,7 +1,7 @@
1
1
  import type { APIRoute } from "astro";
2
2
  import { assets } from "virtual:kide/runtime";
3
3
  import config from "virtual:kide/config";
4
- import { PayloadTooLargeError, readLimitedFormData } from "../../../core";
4
+ import { PayloadTooLargeError, headerMatchesType, readLimitedFormData } from "../../../core";
5
5
 
6
6
  export const prerender = false;
7
7
 
@@ -22,46 +22,6 @@ const ALLOWED_TYPES = new Set(config.admin?.uploads?.allowedTypes ?? DEFAULT_ALL
22
22
  const MAX_FILE_SIZE = config.admin?.uploads?.maxFileSize ?? 50 * 1024 * 1024; // 50 MB
23
23
  const MAX_FILES_PER_UPLOAD = 20;
24
24
 
25
- // Magic number signatures for binary file type verification
26
- const MAGIC_SIGNATURES: Array<{ type: string; bytes: number[]; offset?: number }> = [
27
- { type: "image/jpeg", bytes: [0xff, 0xd8, 0xff] },
28
- { type: "image/png", bytes: [0x89, 0x50, 0x4e, 0x47] },
29
- { type: "image/gif", bytes: [0x47, 0x49, 0x46, 0x38] },
30
- { type: "image/webp", bytes: [0x52, 0x49, 0x46, 0x46], offset: 0 }, // RIFF....WEBP
31
- { type: "application/pdf", bytes: [0x25, 0x50, 0x44, 0x46] },
32
- { type: "video/mp4", bytes: [0x66, 0x74, 0x79, 0x70], offset: 4 }, // ....ftyp
33
- ];
34
-
35
- function verifyMagicBytes(buffer: ArrayBuffer, declaredType: string): boolean {
36
- // SVG and text-based formats can't be verified by magic bytes
37
- if (declaredType === "image/svg+xml") {
38
- const text = new TextDecoder().decode(buffer.slice(0, 256));
39
- return text.includes("<svg") || text.trimStart().startsWith("<?xml");
40
- }
41
-
42
- const header = new Uint8Array(buffer.slice(0, 16));
43
- for (const sig of MAGIC_SIGNATURES) {
44
- if (sig.type !== declaredType) continue;
45
- const offset = sig.offset ?? 0;
46
- const match = sig.bytes.every((byte, i) => header[offset + i] === byte);
47
- if (match) return true;
48
- }
49
-
50
- // AVIF is an ISOBMFF container — check for ftyp box with avif brand
51
- if (declaredType === "image/avif") {
52
- const offset4 = new Uint8Array(buffer.slice(4, 12));
53
- const ftypStr = String.fromCharCode(...offset4);
54
- return ftypStr.startsWith("ftyp") && ftypStr.includes("avif");
55
- }
56
-
57
- // video/webm starts with EBML header
58
- if (declaredType === "video/webm") {
59
- return header[0] === 0x1a && header[1] === 0x45 && header[2] === 0xdf && header[3] === 0xa3;
60
- }
61
-
62
- return false;
63
- }
64
-
65
25
  export const POST: APIRoute = async ({ request, locals }) => {
66
26
  const contentType = request.headers.get("content-type") ?? "";
67
27
 
@@ -109,7 +69,7 @@ export const POST: APIRoute = async ({ request, locals }) => {
109
69
 
110
70
  // Verify via the header only (slice leaves `file` unconsumed → assets.upload reads it once).
111
71
  const header = await file.slice(0, 256).arrayBuffer();
112
- if (!verifyMagicBytes(header, file.type)) {
72
+ if (!headerMatchesType(header, file.type)) {
113
73
  return Response.json({ error: `"${file.name}" content does not match declared type.` }, { status: 400 });
114
74
  }
115
75
  }
@@ -10,7 +10,7 @@ import {
10
10
  logAudit,
11
11
  tokenReference,
12
12
  } from "virtual:kide/runtime";
13
- import { resolveAdminAuth } from "../../../core";
13
+ import { publicOrigin, resolveAdminAuth } from "../../../core";
14
14
  import config from "virtual:kide/config";
15
15
 
16
16
  export const prerender = false;
@@ -55,7 +55,8 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
55
55
 
56
56
  const user = rows[0] as Record<string, unknown>;
57
57
  const reset = await createPasswordReset(String(user._id));
58
- const resetUrl = new URL("/admin/reset-password", request.url);
58
+ // Anchored on the trusted origin, not the Host header — see publicOrigin.
59
+ const resetUrl = new URL("/admin/reset-password", publicOrigin(request));
59
60
  resetUrl.searchParams.set("token", reset.token);
60
61
 
61
62
  const emailAdapter = getEmail();
@@ -15,11 +15,11 @@ import {
15
15
  tokenReference,
16
16
  } from "virtual:kide/runtime";
17
17
  import { sendInviteEmail, isEmailConfigured } from "virtual:kide/email";
18
- import { MIN_PASSWORD_LENGTH } from "../../../core";
18
+ import { MIN_PASSWORD_LENGTH, publicOrigin } from "../../../core";
19
19
 
20
20
  export const prerender = false;
21
21
 
22
- export const POST: APIRoute = async ({ request, url, clientAddress }) => {
22
+ export const POST: APIRoute = async ({ request, clientAddress }) => {
23
23
  const formData = await request.formData();
24
24
  const action = String(formData.get("_action") ?? "create");
25
25
 
@@ -27,10 +27,10 @@ export const POST: APIRoute = async ({ request, url, clientAddress }) => {
27
27
  return handleAccept(formData, request, clientAddress);
28
28
  }
29
29
 
30
- return handleCreate(formData, url, request);
30
+ return handleCreate(formData, request);
31
31
  };
32
32
 
33
- async function handleCreate(formData: FormData, url: URL, request: Request) {
33
+ async function handleCreate(formData: FormData, request: Request) {
34
34
  const user = await getSessionUser(request);
35
35
  if (!user || user.role !== "admin") {
36
36
  return new Response(null, {
@@ -84,7 +84,8 @@ async function handleCreate(formData: FormData, url: URL, request: Request) {
84
84
  });
85
85
 
86
86
  const invite = await createInvite(id);
87
- const inviteUrl = `${url.origin}/admin/invite?token=${invite.token}`;
87
+ // Anchored on the trusted origin, not the Host header — see publicOrigin.
88
+ const inviteUrl = `${publicOrigin(request)}/admin/invite?token=${encodeURIComponent(invite.token)}`;
88
89
 
89
90
  let emailSent = false;
90
91
  if (isEmailConfigured()) {
@@ -124,24 +125,28 @@ async function handleAccept(formData: FormData, request: Request, clientAddress:
124
125
  return new Response(null, { status: 303, headers: { Location: "/admin/invite?error=invalid" } });
125
126
  }
126
127
 
128
+ // The token is caller-supplied form input: encode it so it can't smuggle extra
129
+ // query params or header-breaking characters into the redirect.
130
+ const encodedToken = encodeURIComponent(token);
131
+
127
132
  if (!name || !password) {
128
133
  return new Response(null, {
129
134
  status: 303,
130
- headers: { Location: `/admin/invite?token=${token}&error=missing` },
135
+ headers: { Location: `/admin/invite?token=${encodedToken}&error=missing` },
131
136
  });
132
137
  }
133
138
 
134
139
  if (password !== confirmPassword) {
135
140
  return new Response(null, {
136
141
  status: 303,
137
- headers: { Location: `/admin/invite?token=${token}&error=password` },
142
+ headers: { Location: `/admin/invite?token=${encodedToken}&error=password` },
138
143
  });
139
144
  }
140
145
 
141
146
  if (password.length < MIN_PASSWORD_LENGTH) {
142
147
  return new Response(null, {
143
148
  status: 303,
144
- headers: { Location: `/admin/invite?token=${token}&error=short` },
149
+ headers: { Location: `/admin/invite?token=${encodedToken}&error=short` },
145
150
  });
146
151
  }
147
152
 
@@ -5,6 +5,7 @@ import { getDb } from "virtual:kide/db";
5
5
  import {
6
6
  auditRequestMeta,
7
7
  createSession,
8
+ hashPassword,
8
9
  logAudit,
9
10
  setSessionCookie,
10
11
  tokenReference,
@@ -87,6 +88,10 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
87
88
  const requestMeta = auditRequestMeta(request);
88
89
 
89
90
  if (rows.length === 0) {
91
+ // Burn the same PBKDF2 cost as a real verification so an unknown email can't be
92
+ // told apart from a wrong password by response time (the failure response and
93
+ // the limiter bookkeeping are already identical).
94
+ await hashPassword(password).catch(() => {});
90
95
  await recordFailure();
91
96
  logAudit({
92
97
  action: "auth.login_failed",
@@ -1,6 +1,6 @@
1
1
  import type { APIRoute } from "astro";
2
2
 
3
- import { getSsoProvider, resolveAdminAuth } from "../../../../../core";
3
+ import { getSsoProvider, publicOrigin, resolveAdminAuth } from "../../../../../core";
4
4
  import config from "virtual:kide/config";
5
5
 
6
6
  export const prerender = false;
@@ -16,7 +16,8 @@ export const GET: APIRoute = async ({ params, request }) => {
16
16
  url.searchParams.set("provider", provider.id);
17
17
  url.searchParams.set(
18
18
  "redirect_uri",
19
- provider.callbackUrl ?? new URL("/api/cms/auth/sso/callback", request.url).toString(),
19
+ // Anchored on the trusted origin, not the Host header — see publicOrigin.
20
+ provider.callbackUrl ?? new URL("/api/cms/auth/sso/callback", publicOrigin(request)).toString(),
20
21
  );
21
22
  return new Response(null, {
22
23
  status: 303,
@@ -1,5 +1,5 @@
1
1
  import type { APIRoute } from "astro";
2
- import { getStorage, transformImage } from "../../../core";
2
+ import { getStorage, isPublicUploadPath, transformImage } from "../../../core";
3
3
  import * as storage from "virtual:kide/storage";
4
4
 
5
5
  export const prerender = false;
@@ -21,6 +21,9 @@ const originalContentType = (src: string) =>
21
21
 
22
22
  export const GET: APIRoute = async ({ params, request, url }) => {
23
23
  const src = `/${params.path}`;
24
+ // Public route: only ever serve what assets.upload() wrote. The storage adapters
25
+ // are handed this path as-is, and an object store would happily return any key.
26
+ if (!isPublicUploadPath(src)) return new Response("Not found", { status: 404 });
24
27
  const num = (key: string) => (url.searchParams.get(key) ? Number(url.searchParams.get(key)) : undefined);
25
28
 
26
29
  const options = {
@@ -62,7 +65,12 @@ export const GET: APIRoute = async ({ params, request, url }) => {
62
65
  // sharp unavailable — serve the original.
63
66
  }
64
67
 
65
- const data = await getStorage().getFile(src);
68
+ let data: ArrayBuffer | null;
69
+ try {
70
+ data = await getStorage().getFile(src);
71
+ } catch {
72
+ data = null; // adapter rejected the path — same 404 as a missing file
73
+ }
66
74
  if (!data) return new Response("Not found", { status: 404 });
67
75
 
68
76
  // Untransformed, so the type comes from the stored extension. Only rasters render inline.
@@ -2,11 +2,17 @@ import type { APIRoute } from "astro";
2
2
 
3
3
  import { cms } from "virtual:kide/api";
4
4
  import { readEnv } from "virtual:kide/runtime";
5
+ import { PayloadTooLargeError, readLimitedText } from "../../../core";
5
6
 
6
7
  export const prerender = false;
7
8
 
8
9
  const cmsRuntime = cms as Record<string, any> & { tasks: typeof cms.tasks };
9
10
 
11
+ // Unauthenticated until the signature checks out, and the whole body has to be read
12
+ // before it can — so cap it on the stream, or a peer with no secret at all could push
13
+ // arbitrarily large payloads into memory (and, once signed, into the outbox row).
14
+ const MAX_BODY_BYTES = 1024 * 1024;
15
+
10
16
  const hexToBytes = (hex: string) => {
11
17
  if (!/^[0-9a-f]*$/i.test(hex) || hex.length === 0 || hex.length % 2 !== 0) return null;
12
18
  const bytes = new Uint8Array(hex.length / 2);
@@ -36,7 +42,15 @@ export const POST: APIRoute = async ({ request, params }) => {
36
42
  return Response.json({ error: "Unknown webhook provider" }, { status: 404 });
37
43
  }
38
44
 
39
- const body = await request.text();
45
+ let body: string;
46
+ try {
47
+ body = await readLimitedText(request, MAX_BODY_BYTES);
48
+ } catch (error) {
49
+ if (error instanceof PayloadTooLargeError) {
50
+ return Response.json({ error: "Payload too large" }, { status: 413 });
51
+ }
52
+ throw error;
53
+ }
40
54
  const signature = request.headers.get("x-webhook-signature") ?? "";
41
55
  if (!(await verifySignature(body, signature, secret))) {
42
56
  return Response.json({ error: "Invalid signature" }, { status: 401 });
@@ -51,11 +51,17 @@ export const GET: APIRoute = async ({ params }) => {
51
51
  const ext = storagePath.substring(storagePath.lastIndexOf(".")).toLowerCase();
52
52
  const contentType = MIME_TYPES[ext] || "application/octet-stream";
53
53
 
54
- return new Response(body, {
55
- headers: {
56
- "Content-Type": contentType,
57
- "Content-Length": String(size),
58
- "Cache-Control": "public, max-age=31536000, immutable",
59
- },
60
- });
54
+ const headers: Record<string, string> = {
55
+ "Content-Type": contentType,
56
+ "Content-Length": String(size),
57
+ "Cache-Control": "public, max-age=31536000, immutable",
58
+ // Uploaded bytes are untrusted: never let the browser sniff them into HTML.
59
+ "X-Content-Type-Options": "nosniff",
60
+ };
61
+ // SVG is off by default (see api/assets/upload.ts). When a project opts in, the file
62
+ // still renders through <img> as usual, but a direct navigation gets a sandboxed,
63
+ // opaque-origin document — no script execution, no same-origin access to the site.
64
+ if (contentType === "image/svg+xml") headers["Content-Security-Policy"] = "sandbox";
65
+
66
+ return new Response(body, { headers });
61
67
  };