@kidecms/core 0.33.1 → 0.34.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/core/image.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ImagePreset } from "./define";
2
+ import { getStorage } from "./runtime";
2
3
 
3
4
  const ALLOWED_WIDTHS = [320, 480, 640, 768, 960, 1024, 1280, 1536, 1920];
4
5
  const ALLOWED_FORMATS = ["webp", "avif", "jpeg", "png"] as const;
@@ -175,18 +176,17 @@ export async function transformImage(
175
176
  const sharpModule = "sharp";
176
177
  const sharp = (await import(/* @vite-ignore */ sharpModule)).default;
177
178
 
178
- // Must match the storage adapter: the source lives wherever uploads are written.
179
- const uploadsDir = process.env.CMS_UPLOADS_DIR
180
- ? path.resolve(process.env.CMS_UPLOADS_DIR)
181
- : path.join(process.cwd(), "public", "uploads");
179
+ // Read through the storage adapter so the source can live on disk or in an object store.
180
+ // The adapter rejects traversal by throwing; that's the same miss as an absent file.
181
+ let source: ArrayBuffer | null;
182
+ try {
183
+ source = await getStorage().getFile(src);
184
+ } catch {
185
+ source = null;
186
+ }
187
+ if (!source) return null;
182
188
  const cacheDir = path.join(process.cwd(), ".cms-cache", "img");
183
189
 
184
- // Resolve the source safely under uploadsDir, rejecting traversal.
185
- const rel = src.replace(/^\/+/, "").replace(/^uploads(?:\/|$)/, "");
186
- const filePath = path.resolve(uploadsDir, rel);
187
- if (filePath !== uploadsDir && !filePath.startsWith(uploadsDir + path.sep)) return null;
188
- if (!existsSync(filePath)) return null;
189
-
190
190
  const resolvedFormat: Format = ALLOWED_FORMATS.includes(options.format as Format)
191
191
  ? (options.format as Format)
192
192
  : "webp";
@@ -213,7 +213,7 @@ export async function transformImage(
213
213
  };
214
214
  }
215
215
 
216
- let pipeline = sharp(readFileSync(filePath));
216
+ let pipeline = sharp(Buffer.from(source));
217
217
 
218
218
  if (autoCrop) {
219
219
  pipeline = pipeline.resize(resolvedWidth!, resolvedHeight!, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.33.1",
3
+ "version": "0.34.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",
@@ -73,6 +73,7 @@
73
73
  "@tiptap/starter-kit": "3.31.3",
74
74
  "@tiptap/suggestion": "3.31.3",
75
75
  "ai": "^6.0.286",
76
+ "aws4fetch": "^1.0.20",
76
77
  "better-auth": "1.7.7",
77
78
  "class-variance-authority": "^0.7.1",
78
79
  "clsx": "^2.1.1",
@@ -0,0 +1,79 @@
1
+ import { AwsClient } from "aws4fetch";
2
+
3
+ import { readEnv } from "../../core/runtime";
4
+
5
+ // Any S3-compatible object store: AWS S3, UpCloud Object Storage, Hetzner, MinIO, R2's S3 API...
6
+ // Credentials come from env so they never land in the repo; read per call so .env reloads apply.
7
+ type S3Config = { client: AwsClient; baseUrl: string; prefix: string };
8
+
9
+ let cached: { key: string; config: S3Config } | null = null;
10
+
11
+ function getConfig(): S3Config {
12
+ const env = (name: string) => readEnv(name)?.trim() || undefined;
13
+ const bucket = env("S3_BUCKET");
14
+ const accessKeyId = env("S3_ACCESS_KEY_ID");
15
+ const secretAccessKey = env("S3_SECRET_ACCESS_KEY");
16
+ if (!bucket || !accessKeyId || !secretAccessKey) {
17
+ throw new Error("S3 storage needs S3_BUCKET, S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY.");
18
+ }
19
+ const region = env("S3_REGION") ?? "us-east-1";
20
+ const endpoint = env("S3_ENDPOINT")?.replace(/\/+$/, "");
21
+ const prefix = (env("S3_PREFIX") ?? "").replace(/^\/+|\/+$/g, "");
22
+
23
+ const key = [bucket, accessKeyId, secretAccessKey, region, endpoint, prefix].join("\0");
24
+ if (cached?.key === key) return cached.config;
25
+
26
+ // Custom endpoints get path-style URLs (universally supported); AWS itself gets virtual-hosted.
27
+ const baseUrl = endpoint ? `${endpoint}/${bucket}` : `https://${bucket}.s3.${region}.amazonaws.com`;
28
+ const client = new AwsClient({ accessKeyId, secretAccessKey, region, service: "s3" });
29
+ const config = { client, baseUrl, prefix };
30
+ cached = { key, config };
31
+ return config;
32
+ }
33
+
34
+ // "/uploads/a.jpg" → "<prefix>/uploads/a.jpg". Dot segments would be normalized away by URL
35
+ // parsing and could address keys outside the prefix, so they're rejected outright.
36
+ function objectUrl(storagePath: string): { client: AwsClient; url: string } {
37
+ const segments = storagePath.split("/").filter(Boolean);
38
+ if (segments.length === 0 || segments.some((s) => s === "." || s === "..")) {
39
+ throw new Error(`Invalid storage path: ${storagePath}`);
40
+ }
41
+ const { client, baseUrl, prefix } = getConfig();
42
+ const key = [...(prefix ? prefix.split("/") : []), ...segments].map(encodeURIComponent).join("/");
43
+ return { client, url: `${baseUrl}/${key}` };
44
+ }
45
+
46
+ async function request(storagePath: string, init: RequestInit): Promise<Response | null> {
47
+ const { client, url } = objectUrl(storagePath);
48
+ const res = await client.fetch(url, init);
49
+ if (res.status === 404) {
50
+ await res.body?.cancel();
51
+ return null;
52
+ }
53
+ if (!res.ok) {
54
+ const detail = await res.text().catch(() => "");
55
+ throw new Error(`S3 ${init.method} ${storagePath} failed: ${res.status} ${detail.slice(0, 200)}`);
56
+ }
57
+ return res;
58
+ }
59
+
60
+ export async function putFile(storagePath: string, data: ArrayBuffer | Uint8Array): Promise<void> {
61
+ await request(storagePath, { method: "PUT", body: data as BodyInit });
62
+ }
63
+
64
+ export async function getFile(storagePath: string): Promise<ArrayBuffer | null> {
65
+ const res = await request(storagePath, { method: "GET" });
66
+ return res ? res.arrayBuffer() : null;
67
+ }
68
+
69
+ export async function getFileStream(storagePath: string): Promise<{ body: ReadableStream; size: number } | null> {
70
+ const res = await request(storagePath, { method: "GET" });
71
+ if (!res?.body) return null;
72
+ return { body: res.body, size: Number(res.headers.get("content-length") ?? 0) };
73
+ }
74
+
75
+ export async function deleteFile(storagePath: string): Promise<void> {
76
+ // S3 DELETE is idempotent (204 for missing keys); a 404 here means the bucket is wrong.
77
+ const res = await request(storagePath, { method: "DELETE" });
78
+ if (!res) throw new Error(`S3 bucket not found while deleting ${storagePath}`);
79
+ }