@conloca/content-api 0.1.13 → 0.1.14

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/dist/node.mjs CHANGED
@@ -2,11 +2,9 @@ import { C as normalizePathname, D as Blocks, E as serializeMdxWithFrontmatter,
2
2
  import sortKeys from "sort-keys";
3
3
  import { access, mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, extname, join, parse, resolve } from "node:path";
5
- import { existsSync } from "node:fs";
6
5
  import { imageSize } from "image-size";
7
6
  import { spawn } from "node:child_process";
8
7
  import { createRemoteJWKSet, jwtVerify } from "jose";
9
- import { mkdir as mkdir$1, readFile as readFile$1, rename as rename$1, unlink as unlink$1, writeFile as writeFile$1 } from "fs/promises";
10
8
  import { dirname as dirname$1, join as join$1, normalize, resolve as resolve$1 } from "path";
11
9
  import { xxh3 } from "@node-rs/xxhash";
12
10
  import matter from "gray-matter";
@@ -15,10 +13,31 @@ import { Hono } from "hono";
15
13
  import { cors } from "hono/cors";
16
14
  import { getRequestListener } from "@hono/node-server";
17
15
 
16
+ //#region src/utils/atomic-write.ts
17
+ /**
18
+ * Write file atomically via temp file + rename to prevent corruption on crash.
19
+ * Callers are responsible for ensuring the parent directory exists.
20
+ */
21
+ async function atomicWriteFile(filePath, content) {
22
+ const hrtime = process.hrtime.bigint();
23
+ const tempFile = `${filePath}.tmp.${process.pid}.${hrtime}`;
24
+ try {
25
+ await writeFile(tempFile, content);
26
+ await rename(tempFile, filePath);
27
+ } catch (error) {
28
+ try {
29
+ await unlink(tempFile);
30
+ } catch {}
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ //#endregion
18
36
  //#region src/asset-manifest.ts
19
37
  const MANIFEST_FILENAME = ".asset-manifest.json";
20
38
  var AssetManifest = class {
21
39
  manifestPath;
40
+ _lock = Promise.resolve();
22
41
  constructor(assetsPath) {
23
42
  this.manifestPath = join(assetsPath, MANIFEST_FILENAME);
24
43
  }
@@ -31,19 +50,37 @@ var AssetManifest = class {
31
50
  }
32
51
  }
33
52
  async write(data) {
34
- await writeFile(this.manifestPath, JSON.stringify(data, null, 2), "utf-8");
53
+ await atomicWriteFile(this.manifestPath, JSON.stringify(data, null, 2));
54
+ }
55
+ /** Atomic read-modify-write with promise-based mutex to prevent concurrent corruption */
56
+ async withManifest(fn) {
57
+ const prev = this._lock;
58
+ let release;
59
+ this._lock = new Promise((r) => {
60
+ release = r;
61
+ });
62
+ await prev;
63
+ try {
64
+ const updated = fn(await this.read());
65
+ await this.write(updated);
66
+ } finally {
67
+ release();
68
+ }
35
69
  }
36
70
  async add(relativePath, data) {
37
- const manifest = await this.read();
38
- manifest[relativePath] = data;
39
- await this.write(manifest);
71
+ await this.withManifest((manifest) => {
72
+ manifest[relativePath] = data;
73
+ return manifest;
74
+ });
40
75
  }
41
76
  async remove(relativePath) {
42
- const manifest = await this.read();
43
- if (!(relativePath in manifest)) return false;
44
- delete manifest[relativePath];
45
- await this.write(manifest);
46
- return true;
77
+ let existed = false;
78
+ await this.withManifest((manifest) => {
79
+ existed = relativePath in manifest;
80
+ if (existed) delete manifest[relativePath];
81
+ return manifest;
82
+ });
83
+ return existed;
47
84
  }
48
85
  async get(relativePath) {
49
86
  return (await this.read())[relativePath];
@@ -106,10 +143,15 @@ async function resolveRepoRoot(contentPath) {
106
143
  */
107
144
  function createGitOperations(config) {
108
145
  const { contentPath, branch } = config;
146
+ let cachedRepoRoot;
147
+ async function getCachedRepoRoot() {
148
+ if (cachedRepoRoot === void 0) cachedRepoRoot = await resolveRepoRoot(contentPath);
149
+ return cachedRepoRoot;
150
+ }
109
151
  return {
110
152
  async getStatus() {
111
153
  try {
112
- const repoRoot = await resolveRepoRoot(contentPath);
154
+ const repoRoot = await getCachedRepoRoot();
113
155
  if (!repoRoot) return {
114
156
  isRepo: false,
115
157
  hasChanges: false,
@@ -124,7 +166,12 @@ function createGitOperations(config) {
124
166
  "HEAD"
125
167
  ]);
126
168
  const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : "unknown";
127
- const statusResult = await runGitCommand(repoRoot, ["status", "--porcelain"]);
169
+ const statusResult = await runGitCommand(repoRoot, [
170
+ "status",
171
+ "--porcelain",
172
+ "--",
173
+ contentPath
174
+ ]);
128
175
  const changedFiles = (statusResult.stdout ? statusResult.stdout.split("\n").filter((l) => l.trim()) : []).length;
129
176
  const hasChanges = changedFiles > 0;
130
177
  const remoteConfigured = (await runGitCommand(repoRoot, [
@@ -169,12 +216,17 @@ function createGitOperations(config) {
169
216
  },
170
217
  async commitAll(message, author) {
171
218
  try {
172
- const repoRoot = await resolveRepoRoot(contentPath);
219
+ const repoRoot = await getCachedRepoRoot();
173
220
  if (!repoRoot) return {
174
221
  success: false,
175
222
  error: "Not a git repository"
176
223
  };
177
- const addResult = await runGitCommand(repoRoot, ["add", "-A"]);
224
+ const addResult = await runGitCommand(repoRoot, [
225
+ "add",
226
+ "-A",
227
+ "--",
228
+ contentPath
229
+ ]);
178
230
  if (addResult.exitCode !== 0) return {
179
231
  success: false,
180
232
  error: addResult.stderr || "Failed to stage changes"
@@ -182,7 +234,9 @@ function createGitOperations(config) {
182
234
  if ((await runGitCommand(repoRoot, [
183
235
  "diff",
184
236
  "--cached",
185
- "--quiet"
237
+ "--quiet",
238
+ "--",
239
+ contentPath
186
240
  ])).exitCode === 0) return {
187
241
  success: false,
188
242
  error: "No changes to commit"
@@ -190,7 +244,9 @@ function createGitOperations(config) {
190
244
  const diffStatResult = await runGitCommand(repoRoot, [
191
245
  "diff",
192
246
  "--cached",
193
- "--numstat"
247
+ "--numstat",
248
+ "--",
249
+ contentPath
194
250
  ]);
195
251
  const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split("\n").filter((l) => l.trim()).length : 0;
196
252
  const commitArgs = [
@@ -218,7 +274,7 @@ function createGitOperations(config) {
218
274
  },
219
275
  async pushOrigin() {
220
276
  try {
221
- const repoRoot = await resolveRepoRoot(contentPath);
277
+ const repoRoot = await getCachedRepoRoot();
222
278
  if (!repoRoot) return {
223
279
  success: false,
224
280
  error: "Not a git repository"
@@ -271,7 +327,7 @@ function createGitOperations(config) {
271
327
  },
272
328
  async pull() {
273
329
  try {
274
- const repoRoot = await resolveRepoRoot(contentPath);
330
+ const repoRoot = await getCachedRepoRoot();
275
331
  if (!repoRoot) return {
276
332
  success: false,
277
333
  error: "Not a git repository"
@@ -332,6 +388,55 @@ async function setupGitLfsAttributes(contentRoot) {
332
388
  await writeFile(gitattributesPath, existing ? `${existing.trimEnd()}\n${missingPatterns.join("\n")}\n` : `${missingPatterns.join("\n")}\n`, "utf-8");
333
389
  }
334
390
 
391
+ //#endregion
392
+ //#region src/url-validation.ts
393
+ /**
394
+ * URL validation for SSRF prevention in server-side fetch operations.
395
+ * Blocks private/reserved IP addresses and non-http(s) schemes.
396
+ */
397
+ const BLOCKED_HOSTNAMES = new Set(["localhost"]);
398
+ /** Check if an IPv4 address string points to a private/reserved range */
399
+ function isPrivateIPv4(hostname) {
400
+ const parts = hostname.split(".");
401
+ if (parts.length !== 4) return false;
402
+ const octets = parts.map((p) => Number.parseInt(p, 10));
403
+ if (octets.some((o) => Number.isNaN(o) || o < 0 || o > 255)) return false;
404
+ const [first, second] = octets;
405
+ if (first === 0) return true;
406
+ if (first === 10) return true;
407
+ if (first === 127) return true;
408
+ if (first === 169 && second === 254) return true;
409
+ if (first === 172 && second >= 16 && second <= 31) return true;
410
+ if (first === 192 && second === 168) return true;
411
+ return false;
412
+ }
413
+ /** Check if an IPv6 address string points to a private/reserved range */
414
+ function isPrivateIPv6(hostname) {
415
+ const lower = hostname.toLowerCase();
416
+ if (lower === "::1") return true;
417
+ if (lower === "::") return true;
418
+ if (lower.startsWith("fe80:") || lower.startsWith("fe80%")) return true;
419
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
420
+ return false;
421
+ }
422
+ /**
423
+ * Validate that a URL is safe to fetch server-side.
424
+ * Blocks private/reserved IP addresses and non-http(s) schemes.
425
+ *
426
+ * @param url The URL string to validate
427
+ * @returns The parsed URL object if valid
428
+ * @throws Error if the URL is invalid, uses a blocked scheme, or points to a private IP
429
+ */
430
+ function validateFetchUrl(url) {
431
+ const parsed = new URL(url);
432
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("URL scheme must be http or https");
433
+ const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
434
+ if (BLOCKED_HOSTNAMES.has(hostname.toLowerCase())) throw new Error("URL points to a private/reserved IP address");
435
+ if (isPrivateIPv4(hostname)) throw new Error("URL points to a private/reserved IP address");
436
+ if (isPrivateIPv6(hostname)) throw new Error("URL points to a private/reserved IP address");
437
+ return parsed;
438
+ }
439
+
335
440
  //#endregion
336
441
  //#region src/asset-operations.ts
337
442
  const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
@@ -426,16 +531,19 @@ var AssetOperations = class {
426
531
  * @param originalName Original filename
427
532
  * @param folder Optional folder path (relative to assets root)
428
533
  */
429
- resolveFilename(originalName, folder) {
534
+ async resolveFilename(originalName, folder) {
430
535
  const { name, ext } = parse(originalName);
431
536
  const sanitized = name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
432
537
  const safeExt = ext.toLowerCase();
433
538
  const baseDir = folder && folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\/+|\/+$/g, "")) : this.config.assetsPath;
434
539
  let candidate = `${sanitized}${safeExt}`;
435
540
  let counter = 0;
436
- while (existsSync(join(baseDir, candidate))) {
541
+ while (true) try {
542
+ await access(join(baseDir, candidate));
437
543
  counter++;
438
544
  candidate = `${sanitized}-${counter}${safeExt}`;
545
+ } catch {
546
+ break;
439
547
  }
440
548
  return candidate;
441
549
  }
@@ -525,7 +633,7 @@ var AssetOperations = class {
525
633
  await setupGitLfsAttributes(this.config.assetsPath);
526
634
  this.lfsSetup = true;
527
635
  }
528
- const filename = this.resolveFilename(file.name, folder);
636
+ const filename = await this.resolveFilename(file.name, folder);
529
637
  const filePath = folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\//, ""), filename) : join(this.config.assetsPath, filename);
530
638
  const arrayBuffer = await file.arrayBuffer();
531
639
  await writeFile(filePath, new Uint8Array(arrayBuffer));
@@ -634,24 +742,46 @@ var AssetOperations = class {
634
742
  }
635
743
  /**
636
744
  * Import an image from a URL (server-side fetch, no CORS issues)
745
+ * Validates URL against SSRF, enforces 30s timeout, and checks response size.
637
746
  */
638
747
  async importFromUrl(url, metadata) {
748
+ try {
749
+ validateFetchUrl(url);
750
+ } catch (err) {
751
+ return {
752
+ success: false,
753
+ error: err instanceof Error ? err.message : "Invalid URL"
754
+ };
755
+ }
756
+ const controller = new AbortController();
757
+ const timeout = setTimeout(() => controller.abort(), 3e4);
639
758
  let response;
640
759
  try {
641
- response = await fetch(url);
760
+ response = await fetch(url, { signal: controller.signal });
642
761
  } catch {
643
762
  return {
644
763
  success: false,
645
764
  error: "Failed to fetch URL"
646
765
  };
766
+ } finally {
767
+ clearTimeout(timeout);
647
768
  }
648
769
  if (!response.ok) return {
649
770
  success: false,
650
771
  error: `Fetch failed with status ${response.status}`
651
772
  };
773
+ const contentLength = response.headers.get("content-length");
774
+ if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) return {
775
+ success: false,
776
+ error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
777
+ };
652
778
  const contentType = response.headers.get("content-type") || "";
653
779
  const urlFilename = new URL(url).pathname.split("/").pop() || "imported-image.jpg";
654
780
  const arrayBuffer = await response.arrayBuffer();
781
+ if (arrayBuffer.byteLength > this.config.maxFileSize) return {
782
+ success: false,
783
+ error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
784
+ };
655
785
  const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });
656
786
  return this.upload(file, metadata);
657
787
  }
@@ -887,7 +1017,7 @@ var AssetOperations = class {
887
1017
  error: "Target folder does not exist"
888
1018
  };
889
1019
  }
890
- let movedCount = 0;
1020
+ const moves = [];
891
1021
  for (const filename of filenames) {
892
1022
  const sourceFile = join(sourcePath, filename);
893
1023
  const targetFile = join(targetPath, filename);
@@ -895,19 +1025,27 @@ var AssetOperations = class {
895
1025
  const newRelativePath = normalizedTarget === "/" ? filename : `${normalizedTarget.slice(1)}/${filename}`;
896
1026
  try {
897
1027
  await rename(sourceFile, targetFile);
898
- const oldEntry = (await this.manifest.read())[oldRelativePath];
899
- if (oldEntry) {
900
- await this.manifest.remove(oldRelativePath);
901
- await this.manifest.add(newRelativePath, oldEntry);
902
- }
903
- movedCount++;
1028
+ moves.push({
1029
+ oldPath: oldRelativePath,
1030
+ newPath: newRelativePath
1031
+ });
904
1032
  } catch (err) {
905
1033
  console.error(`[AssetOperations] Failed to move ${filename}:`, err);
906
1034
  }
907
1035
  }
1036
+ if (moves.length > 0) await this.manifest.withManifest((data) => {
1037
+ for (const { oldPath, newPath } of moves) {
1038
+ const entry = data[oldPath];
1039
+ if (entry) {
1040
+ delete data[oldPath];
1041
+ data[newPath] = entry;
1042
+ }
1043
+ }
1044
+ return data;
1045
+ });
908
1046
  return {
909
1047
  success: true,
910
- moved: movedCount
1048
+ moved: moves.length
911
1049
  };
912
1050
  }
913
1051
  /**
@@ -1006,8 +1144,8 @@ async function validateCFAccessRequest(request) {
1006
1144
  valid: true,
1007
1145
  required: true,
1008
1146
  user: {
1009
- email: payload.email || "",
1010
- sub: payload.sub || ""
1147
+ email: typeof payload.email === "string" && payload.email ? payload.email : void 0,
1148
+ sub: typeof payload.sub === "string" && payload.sub ? payload.sub : void 0
1011
1149
  }
1012
1150
  };
1013
1151
  } catch (error) {
@@ -1032,7 +1170,7 @@ var ComponentRegistry = class {
1032
1170
  registry = {};
1033
1171
  initialized = false;
1034
1172
  constructor(canvasDir) {
1035
- this.registryPath = join$1(canvasDir, "components", "registry.json");
1173
+ this.registryPath = join(canvasDir, "components", "registry.json");
1036
1174
  }
1037
1175
  /**
1038
1176
  * Initialize the registry by loading from disk or creating new
@@ -1040,7 +1178,7 @@ var ComponentRegistry = class {
1040
1178
  async initialize() {
1041
1179
  if (this.initialized) return;
1042
1180
  try {
1043
- const content = await readFile$1(this.registryPath, "utf-8");
1181
+ const content = await readFile(this.registryPath, "utf-8");
1044
1182
  this.registry = JSON.parse(content);
1045
1183
  } catch (error) {
1046
1184
  if (error.code === "ENOENT") await this.save();
@@ -1058,18 +1196,10 @@ var ComponentRegistry = class {
1058
1196
  * Save registry to disk atomically
1059
1197
  */
1060
1198
  async save() {
1061
- const tempPath = `${this.registryPath}.tmp.${Date.now()}.${Math.random().toString(36).substring(2, 9)}`;
1062
- try {
1063
- await mkdir$1(dirname$1(this.registryPath), { recursive: true });
1064
- const sorted = sortKeys(this.registry, { deep: true });
1065
- await writeFile$1(tempPath, JSON.stringify(sorted, null, 2));
1066
- await rename$1(tempPath, this.registryPath);
1067
- } catch (error) {
1068
- try {
1069
- await unlink$1(tempPath);
1070
- } catch {}
1071
- throw error;
1072
- }
1199
+ await mkdir(dirname(this.registryPath), { recursive: true });
1200
+ const sorted = sortKeys(this.registry, { deep: true });
1201
+ const content = JSON.stringify(sorted, null, 2);
1202
+ await atomicWriteFile(this.registryPath, content);
1073
1203
  }
1074
1204
  /**
1075
1205
  * Register a new component or update existing
@@ -3347,17 +3477,7 @@ var FileSystemContentAPI = class FileSystemContentAPI {
3347
3477
  mdxContentPart = contentOnly;
3348
3478
  }
3349
3479
  const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
3350
- const hrtime = process.hrtime.bigint();
3351
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3352
- try {
3353
- await writeFile(tempFile, mdxContent);
3354
- await rename(tempFile, targetFilePath);
3355
- } catch (error) {
3356
- try {
3357
- await unlink(tempFile);
3358
- } catch {}
3359
- throw error;
3360
- }
3480
+ await atomicWriteFile(targetFilePath, mdxContent);
3361
3481
  } else if (targetFilePath.endsWith(".json")) {
3362
3482
  const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3363
3483
  const updatedFile = {
@@ -3375,17 +3495,7 @@ var FileSystemContentAPI = class FileSystemContentAPI {
3375
3495
  if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3376
3496
  else delete updatedFile.unpublishAt;
3377
3497
  const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, " ");
3378
- const hrtime = process.hrtime.bigint();
3379
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3380
- try {
3381
- await writeFile(tempFile, serializedContent);
3382
- await rename(tempFile, targetFilePath);
3383
- } catch (error) {
3384
- try {
3385
- await unlink(tempFile);
3386
- } catch {}
3387
- throw error;
3388
- }
3498
+ await atomicWriteFile(targetFilePath, serializedContent);
3389
3499
  } else {
3390
3500
  const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3391
3501
  const updatedFile = {
@@ -3410,17 +3520,7 @@ var FileSystemContentAPI = class FileSystemContentAPI {
3410
3520
  if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3411
3521
  else delete updatedFile.unpublishAt;
3412
3522
  const serializedContent = VXJSON.serialize(updatedFile);
3413
- const hrtime = process.hrtime.bigint();
3414
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3415
- try {
3416
- await writeFile(tempFile, serializedContent);
3417
- await rename(tempFile, targetFilePath);
3418
- } catch (error) {
3419
- try {
3420
- await unlink(tempFile);
3421
- } catch {}
3422
- throw error;
3423
- }
3523
+ await atomicWriteFile(targetFilePath, serializedContent);
3424
3524
  }
3425
3525
  const writtenBuffer = await readFile(targetFilePath);
3426
3526
  let newEtag;