@conloca/content-api 0.1.16 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +21 -28
  10. package/dist/asset-operations.d.ts.map +1 -1
  11. package/dist/asset-operations.js +268 -305
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +23 -7
  14. package/dist/asset-types.d.ts.map +1 -1
  15. package/dist/asset-types.js +8 -2
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +11 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +50 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +8 -2
  22. package/dist/base-content-index.d.ts.map +1 -1
  23. package/dist/base-content-index.js +24 -3
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.js +1 -0
  26. package/dist/cf-access.js.map +1 -0
  27. package/dist/component-registry.d.ts +1 -1
  28. package/dist/component-registry.d.ts.map +1 -1
  29. package/dist/component-registry.js +2 -1
  30. package/dist/component-registry.js.map +1 -0
  31. package/dist/component-registry.types.js +1 -0
  32. package/dist/component-registry.types.js.map +1 -0
  33. package/dist/component-vocabulary.d.ts +33 -0
  34. package/dist/component-vocabulary.d.ts.map +1 -0
  35. package/dist/component-vocabulary.js +105 -0
  36. package/dist/component-vocabulary.js.map +1 -0
  37. package/dist/content-api.interface.d.ts +5 -5
  38. package/dist/content-api.interface.d.ts.map +1 -1
  39. package/dist/content-api.interface.js +1 -0
  40. package/dist/content-api.interface.js.map +1 -0
  41. package/dist/content-filters.d.ts +2 -2
  42. package/dist/content-filters.d.ts.map +1 -1
  43. package/dist/content-filters.js +9 -8
  44. package/dist/content-filters.js.map +1 -0
  45. package/dist/content-index.d.ts +74 -16
  46. package/dist/content-index.d.ts.map +1 -1
  47. package/dist/content-index.js +183 -55
  48. package/dist/content-index.js.map +1 -0
  49. package/dist/content-operations.d.ts +71 -7
  50. package/dist/content-operations.d.ts.map +1 -1
  51. package/dist/content-operations.js +166 -82
  52. package/dist/content-operations.js.map +1 -0
  53. package/dist/content-path.d.ts +64 -0
  54. package/dist/content-path.d.ts.map +1 -0
  55. package/dist/content-path.js +95 -0
  56. package/dist/content-path.js.map +1 -0
  57. package/dist/content-reader.d.ts +2 -2
  58. package/dist/content-reader.d.ts.map +1 -1
  59. package/dist/content-reader.js +2 -1
  60. package/dist/content-reader.js.map +1 -0
  61. package/dist/content-utils.d.ts +53 -10
  62. package/dist/content-utils.d.ts.map +1 -1
  63. package/dist/content-utils.js +103 -34
  64. package/dist/content-utils.js.map +1 -0
  65. package/dist/content-watcher.d.ts +3 -3
  66. package/dist/content-watcher.d.ts.map +1 -1
  67. package/dist/content-watcher.js +13 -10
  68. package/dist/content-watcher.js.map +1 -0
  69. package/dist/data-index.d.ts +1 -1
  70. package/dist/data-index.d.ts.map +1 -1
  71. package/dist/data-index.js +2 -1
  72. package/dist/data-index.js.map +1 -0
  73. package/dist/data.d.ts +5 -13
  74. package/dist/data.d.ts.map +1 -1
  75. package/dist/data.js +7 -6
  76. package/dist/data.js.map +1 -0
  77. package/dist/editor-data-bindings.d.ts +10 -0
  78. package/dist/editor-data-bindings.d.ts.map +1 -0
  79. package/dist/editor-data-bindings.js +67 -0
  80. package/dist/editor-data-bindings.js.map +1 -0
  81. package/dist/etag-utils.d.ts.map +1 -1
  82. package/dist/etag-utils.js +5 -4
  83. package/dist/etag-utils.js.map +1 -0
  84. package/dist/filesystem-content-api.d.ts +45 -18
  85. package/dist/filesystem-content-api.d.ts.map +1 -1
  86. package/dist/filesystem-content-api.js +455 -286
  87. package/dist/filesystem-content-api.js.map +1 -0
  88. package/dist/filesystem-reader-backend.d.ts +46 -0
  89. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  90. package/dist/filesystem-reader-backend.js +119 -0
  91. package/dist/filesystem-reader-backend.js.map +1 -0
  92. package/dist/fragment-index.d.ts +8 -0
  93. package/dist/fragment-index.d.ts.map +1 -0
  94. package/dist/fragment-index.js +8 -0
  95. package/dist/fragment-index.js.map +1 -0
  96. package/dist/fragments.d.ts +16 -0
  97. package/dist/fragments.d.ts.map +1 -0
  98. package/dist/fragments.js +104 -0
  99. package/dist/fragments.js.map +1 -0
  100. package/dist/git-operations.d.ts.map +1 -1
  101. package/dist/git-operations.js +5 -1
  102. package/dist/git-operations.js.map +1 -0
  103. package/dist/header-parser.d.ts +4 -4
  104. package/dist/header-parser.d.ts.map +1 -1
  105. package/dist/header-parser.js +8 -61
  106. package/dist/header-parser.js.map +1 -0
  107. package/dist/in-memory-content-api.d.ts +7 -7
  108. package/dist/in-memory-content-api.d.ts.map +1 -1
  109. package/dist/in-memory-content-api.js +74 -56
  110. package/dist/in-memory-content-api.js.map +1 -0
  111. package/dist/index.d.ts +19 -12
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js +21 -9
  114. package/dist/index.js.map +1 -0
  115. package/dist/indexing.d.ts +4 -4
  116. package/dist/indexing.d.ts.map +1 -1
  117. package/dist/indexing.js +6 -5
  118. package/dist/indexing.js.map +1 -0
  119. package/dist/json-whitespace-view.js +1 -0
  120. package/dist/json-whitespace-view.js.map +1 -0
  121. package/dist/middleware.d.ts +8 -6
  122. package/dist/middleware.d.ts.map +1 -1
  123. package/dist/middleware.js +178 -142
  124. package/dist/middleware.js.map +1 -0
  125. package/dist/node.d.ts +24 -17
  126. package/dist/node.d.ts.map +1 -1
  127. package/dist/node.js +17 -14
  128. package/dist/node.js.map +1 -0
  129. package/dist/page-references.d.ts +21 -0
  130. package/dist/page-references.d.ts.map +1 -0
  131. package/dist/page-references.js +50 -0
  132. package/dist/page-references.js.map +1 -0
  133. package/dist/read-date.d.ts +3 -0
  134. package/dist/read-date.d.ts.map +1 -0
  135. package/dist/read-date.js +9 -0
  136. package/dist/read-date.js.map +1 -0
  137. package/dist/reader-backend.d.ts +54 -0
  138. package/dist/reader-backend.d.ts.map +1 -0
  139. package/dist/reader-backend.js +2 -0
  140. package/dist/reader-backend.js.map +1 -0
  141. package/dist/reader.d.ts +8 -8
  142. package/dist/reader.d.ts.map +1 -1
  143. package/dist/reader.js +8 -7
  144. package/dist/reader.js.map +1 -0
  145. package/dist/schemas/index.d.ts +6 -6
  146. package/dist/schemas/index.d.ts.map +1 -1
  147. package/dist/schemas/index.js +9 -8
  148. package/dist/schemas/index.js.map +1 -0
  149. package/dist/site-index.d.ts +3 -3
  150. package/dist/site-index.d.ts.map +1 -1
  151. package/dist/site-index.js +9 -5
  152. package/dist/site-index.js.map +1 -0
  153. package/dist/site.d.ts +5 -3
  154. package/dist/site.d.ts.map +1 -1
  155. package/dist/site.js +14 -2
  156. package/dist/site.js.map +1 -0
  157. package/dist/types.d.ts +203 -15
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/types.js +9 -0
  160. package/dist/types.js.map +1 -0
  161. package/dist/url-safe-base64.js +1 -0
  162. package/dist/url-safe-base64.js.map +1 -0
  163. package/dist/url-validation.d.ts +14 -0
  164. package/dist/url-validation.d.ts.map +1 -1
  165. package/dist/url-validation.js +56 -14
  166. package/dist/url-validation.js.map +1 -0
  167. package/dist/utils/atomic-write.js +1 -0
  168. package/dist/utils/atomic-write.js.map +1 -0
  169. package/dist/utils.d.ts +1 -1
  170. package/dist/utils.js +2 -1
  171. package/dist/utils.js.map +1 -0
  172. package/dist/vite-plugin.d.ts +2 -2
  173. package/dist/vite-plugin.js +5 -4
  174. package/dist/vite-plugin.js.map +1 -0
  175. package/dist/vxjson-serialize.d.ts +5 -6
  176. package/dist/vxjson-serialize.d.ts.map +1 -1
  177. package/dist/vxjson-serialize.js +13 -10
  178. package/dist/vxjson-serialize.js.map +1 -0
  179. package/dist/vxjson.d.ts +4 -3
  180. package/dist/vxjson.d.ts.map +1 -1
  181. package/dist/vxjson.js +10 -20
  182. package/dist/vxjson.js.map +1 -0
  183. package/dist/xxhash.d.ts.map +1 -1
  184. package/dist/xxhash.js +6 -2
  185. package/dist/xxhash.js.map +1 -0
  186. package/package.json +92 -56
  187. package/src/asset-constraints.ts +33 -0
  188. package/src/asset-metadata-store.ts +401 -0
  189. package/src/asset-operations.ts +814 -0
  190. package/src/asset-types.ts +74 -0
  191. package/src/asset-usage.ts +48 -0
  192. package/src/base-content-index.ts +227 -0
  193. package/src/cf-access.ts +85 -0
  194. package/src/component-registry.ts +145 -0
  195. package/src/component-registry.types.ts +12 -0
  196. package/src/component-vocabulary.ts +87 -0
  197. package/src/content-api.interface.ts +94 -0
  198. package/src/content-filters.ts +278 -0
  199. package/src/content-index.ts +642 -0
  200. package/src/content-operations.ts +497 -0
  201. package/src/content-path.ts +121 -0
  202. package/src/content-reader.ts +18 -0
  203. package/src/content-utils.ts +474 -0
  204. package/src/content-watcher.ts +122 -0
  205. package/src/data-index.ts +7 -0
  206. package/src/data.ts +134 -0
  207. package/src/editor-data-bindings.ts +66 -0
  208. package/src/etag-utils.ts +204 -0
  209. package/src/filesystem-content-api.ts +2740 -0
  210. package/src/filesystem-reader-backend.ts +135 -0
  211. package/src/fragment-index.ts +7 -0
  212. package/src/fragments.ts +113 -0
  213. package/src/git-operations.ts +340 -0
  214. package/src/header-parser.ts +272 -0
  215. package/src/in-memory-content-api.ts +760 -0
  216. package/src/index.ts +45 -0
  217. package/src/indexing.ts +8 -0
  218. package/src/json-whitespace-view.ts +155 -0
  219. package/src/middleware.ts +1322 -0
  220. package/src/node.ts +40 -0
  221. package/src/page-references.ts +76 -0
  222. package/src/read-date.ts +7 -0
  223. package/src/reader-backend.ts +54 -0
  224. package/src/reader.ts +15 -0
  225. package/src/schemas/index.ts +113 -0
  226. package/src/site-index.ts +330 -0
  227. package/src/site.ts +198 -0
  228. package/src/types.ts +759 -0
  229. package/src/url-safe-base64.ts +38 -0
  230. package/src/url-validation.ts +121 -0
  231. package/src/utils/atomic-write.ts +20 -0
  232. package/src/utils.ts +84 -0
  233. package/src/vite-plugin.ts +45 -0
  234. package/src/vxjson-serialize.ts +66 -0
  235. package/src/vxjson.ts +442 -0
  236. package/src/xxhash.ts +43 -0
  237. package/dist/asset-manifest.d.ts +0 -23
  238. package/dist/asset-manifest.d.ts.map +0 -1
  239. package/dist/asset-manifest.js +0 -73
  240. package/dist/block-index.d.ts +0 -9
  241. package/dist/block-index.d.ts.map +0 -1
  242. package/dist/block-index.js +0 -11
  243. package/dist/blocks.d.ts +0 -16
  244. package/dist/blocks.d.ts.map +0 -1
  245. package/dist/blocks.js +0 -103
  246. package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
  247. package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
  248. package/dist/content-index-D092_vk1.mjs +0 -629
  249. package/dist/content-index-D092_vk1.mjs.map +0 -1
  250. package/dist/content-index-D6IVMmAB.d.mts +0 -127
  251. package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
  252. package/dist/content-operations-DIbsxG5A.d.mts +0 -354
  253. package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
  254. package/dist/content-utils-fWNHTrPy.mjs +0 -280
  255. package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
  256. package/dist/data-DquNIEnQ.mjs +0 -62
  257. package/dist/data-DquNIEnQ.mjs.map +0 -1
  258. package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
  259. package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
  260. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
  261. package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
  262. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
  263. package/dist/index-DxVTFK66.d.mts +0 -105
  264. package/dist/index-DxVTFK66.d.mts.map +0 -1
  265. package/dist/index.d.mts +0 -80
  266. package/dist/index.d.mts.map +0 -1
  267. package/dist/index.mjs +0 -78
  268. package/dist/index.mjs.map +0 -1
  269. package/dist/indexing.d.mts +0 -152
  270. package/dist/indexing.d.mts.map +0 -1
  271. package/dist/indexing.mjs +0 -255
  272. package/dist/indexing.mjs.map +0 -1
  273. package/dist/node.d.mts +0 -373
  274. package/dist/node.d.mts.map +0 -1
  275. package/dist/node.mjs +0 -2572
  276. package/dist/node.mjs.map +0 -1
  277. package/dist/reader.d.mts +0 -15
  278. package/dist/reader.d.mts.map +0 -1
  279. package/dist/reader.mjs +0 -22
  280. package/dist/reader.mjs.map +0 -1
  281. package/dist/schemas/index.d.mts +0 -2
  282. package/dist/schemas/index.mjs +0 -2
  283. package/dist/schemas-CFRD0FIQ.mjs +0 -84
  284. package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
  285. package/dist/site-8oaj1Q60.mjs +0 -366
  286. package/dist/site-8oaj1Q60.mjs.map +0 -1
  287. package/dist/site-index-B_254bCc.d.mts +0 -136
  288. package/dist/site-index-B_254bCc.d.mts.map +0 -1
  289. package/dist/types-DOdldbfD.mjs +0 -34
  290. package/dist/types-DOdldbfD.mjs.map +0 -1
  291. package/dist/types-DjfhS272.d.mts +0 -456
  292. package/dist/types-DjfhS272.d.mts.map +0 -1
  293. package/dist/vxjson-qHrgLGip.mjs +0 -555
  294. package/dist/vxjson-qHrgLGip.mjs.map +0 -1
  295. package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
  296. package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
  297. package/dist/vxjson-serialize.d.mts +0 -17
  298. package/dist/vxjson-serialize.d.mts.map +0 -1
  299. package/dist/vxjson-serialize.mjs +0 -2
@@ -1,25 +1,16 @@
1
- import { access, mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
- import { extname, join, parse, resolve } from 'node:path';
3
- import { imageSize } from 'image-size';
4
- import { AssetManifest, } from './asset-manifest';
5
- import { setupGitLfsAttributes } from './git-operations';
6
- import { validateFetchUrl } from './url-validation';
7
- const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
8
- const DEFAULT_ACCEPTED_FORMATS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg', 'ico'];
9
- const MIME_MAP = {
10
- jpg: 'image/jpeg',
11
- jpeg: 'image/jpeg',
12
- png: 'image/png',
13
- gif: 'image/gif',
14
- webp: 'image/webp',
15
- avif: 'image/avif',
16
- svg: 'image/svg+xml',
17
- ico: 'image/x-icon',
18
- };
19
- /** Recognized web image extensions for filesystem scanning */
20
- const RECOGNIZED_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'avif', 'ico']);
1
+ import { lstat, mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { extname, join, parse, resolve, sep } from 'node:path';
3
+ import { imageSizeFromFile } from 'image-size/fromFile';
4
+ import { DEFAULT_ACCEPTED_FORMATS, DEFAULT_MAX_FILE_SIZE, IMAGE_EXTENSION_MIME } from './asset-constraints.js';
5
+ import * as assetMetadata from './asset-metadata-store.js';
6
+ import { setupGitLfsAttributes } from './git-operations.js';
7
+ import { validateFetchUrl } from './url-validation.js';
8
+ /** Recognized web image extensions for filesystem scanning — the accepted upload formats */
9
+ const RECOGNIZED_IMAGE_EXTENSIONS = new Set(DEFAULT_ACCEPTED_FORMATS);
21
10
  /** System files to skip during filesystem scanning */
22
11
  const SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini', '.asset-manifest.json']);
12
+ /** Max redirect hops a URL import may follow (each re-validated before it is requested) */
13
+ const MAX_IMPORT_REDIRECTS = 5;
23
14
  /** Check if filename has a recognized web image extension */
24
15
  function isRecognizedImageExtension(filename) {
25
16
  const ext = extname(filename).slice(1).toLowerCase();
@@ -29,28 +20,27 @@ function isRecognizedImageExtension(filename) {
29
20
  function isSystemFile(filename) {
30
21
  return filename.startsWith('.') || SYSTEM_FILES.has(filename.toLowerCase());
31
22
  }
23
+ /**
24
+ * Check that a name is one file in its folder, not a path that could step out of it. The names come
25
+ * straight from a request body, so anything that is not a string is refused too.
26
+ */
27
+ function isBareFilename(filename) {
28
+ return (typeof filename === 'string' && filename !== '' && filename !== '.' && filename !== '..' && !/[/\\]/.test(filename));
29
+ }
32
30
  export class AssetOperations {
33
31
  config;
34
- manifest;
35
32
  dirEnsured = false;
36
33
  lfsSetup = false;
37
34
  constructor(config) {
38
35
  this.config = {
39
36
  assetsPath: config.assetsPath,
40
37
  maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
41
- acceptedFormats: config.acceptedFormats ?? DEFAULT_ACCEPTED_FORMATS,
38
+ // Copy: the shared default is frozen, but AssetConfig stays a plain string[]
39
+ acceptedFormats: config.acceptedFormats ?? [...DEFAULT_ACCEPTED_FORMATS],
42
40
  contentRoot: config.contentRoot,
43
41
  };
44
- this.manifest = new AssetManifest(config.assetsPath);
45
- }
46
- /** Resolve folder from manifest when only filename is known */
47
- async resolveFolder(filename) {
48
- const entry = await this.manifest.getByFilename(filename);
49
- if (!entry)
50
- return '/';
51
- const lastSlash = entry.relativePath.lastIndexOf('/');
52
- return lastSlash > 0 ? `/${entry.relativePath.slice(0, lastSlash)}` : '/';
53
42
  }
43
+ /** A bare filename always means the assets root; subfolder assets are addressed with their folder. */
54
44
  async ensureDir(subpath) {
55
45
  const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;
56
46
  if (!subpath && this.dirEnsured)
@@ -69,8 +59,9 @@ export class AssetOperations {
69
59
  // Resolve both paths to absolute to ensure consistent comparison
70
60
  const assetsAbsolute = resolve(this.config.assetsPath);
71
61
  const fullPath = resolve(assetsAbsolute, normalizedSubpath);
72
- // Security check: ensure resolved path is within assetsPath
73
- if (!fullPath.startsWith(assetsAbsolute)) {
62
+ // Security check: ensure resolved path is assetsPath or inside it. The separator matters:
63
+ // a bare prefix check lets `../assets-evil` through as if it were inside `assets`.
64
+ if (fullPath !== assetsAbsolute && !fullPath.startsWith(`${assetsAbsolute}${sep}`)) {
74
65
  throw new Error('Path traversal detected');
75
66
  }
76
67
  return fullPath;
@@ -82,11 +73,14 @@ export class AssetOperations {
82
73
  */
83
74
  async resolveFilename(originalName, folder) {
84
75
  const { name, ext } = parse(originalName);
85
- // Sanitize: lowercase, replace spaces with dashes, remove non-alphanumeric except dash/dot
86
- const sanitized = name
76
+ // Normalize compatibility forms and accents before restricting the stored filename.
77
+ const cleaned = name
78
+ .normalize('NFKD')
87
79
  .toLowerCase()
88
80
  .replace(/\s+/g, '-')
89
- .replace(/[^a-z0-9-]/g, '');
81
+ .replace(/[^a-z0-9-]/g, '')
82
+ .slice(0, 200);
83
+ const sanitized = /[a-z0-9]/.test(cleaned) ? cleaned : 'file';
90
84
  const safeExt = ext.toLowerCase();
91
85
  // Determine base directory (assetsPath or assetsPath/folder)
92
86
  const baseDir = folder && folder !== '/'
@@ -97,7 +91,8 @@ export class AssetOperations {
97
91
  // eslint-disable-next-line no-constant-condition
98
92
  while (true) {
99
93
  try {
100
- await access(join(baseDir, candidate));
94
+ // lstat also reserves the name of a broken symlink.
95
+ await lstat(join(baseDir, candidate));
101
96
  counter++;
102
97
  candidate = `${sanitized}-${counter}${safeExt}`;
103
98
  }
@@ -115,58 +110,46 @@ export class AssetOperations {
115
110
  return size <= this.config.maxFileSize;
116
111
  }
117
112
  /**
118
- * Get image dimensions from manifest cache or by reading file headers
113
+ * Measure an image by reading its header. Never cached: the image is the only
114
+ * honest source, and writing the numbers back turned every listing into a write.
119
115
  */
120
- async getDimensions(filePath, manifestEntry) {
121
- // Check manifest cache first
122
- if (manifestEntry?.width && manifestEntry?.height) {
123
- return { width: manifestEntry.width, height: manifestEntry.height, fromCache: true };
124
- }
125
- // Read from file headers
116
+ async getDimensions(filePath) {
126
117
  try {
127
- const buffer = await readFile(filePath);
128
- const result = imageSize(new Uint8Array(buffer));
129
- return { width: result.width, height: result.height, fromCache: false };
118
+ const result = await imageSizeFromFile(filePath);
119
+ return { width: result.width, height: result.height };
130
120
  }
131
121
  catch {
132
- // SVGs and some formats may fail - return undefined dimensions
133
- return { width: undefined, height: undefined, fromCache: false };
122
+ // SVGs without intrinsic size and unsupported formats have no dimensions
123
+ return { width: undefined, height: undefined };
134
124
  }
135
125
  }
136
126
  /**
137
- * Build an AssetEntry from a directory entry, enriching with manifest metadata
127
+ * One AssetEntry: the file as it is on disk, plus whatever a person has
128
+ * written about it. Shared by every read, so they cannot drift.
138
129
  */
139
- async buildAssetEntry(dirent, folder, manifestData) {
140
- // Compute relative path for manifest lookup
141
- const relativePath = folder === '/' ? dirent.name : `${folder.slice(1)}/${dirent.name}`;
142
- const manifestEntry = manifestData[relativePath];
143
- // Build full file path
144
- const fullPath = this.getAssetPath(dirent.name, folder);
145
- // Get file stats
146
- const stats = await stat(fullPath);
147
- // Get dimensions (from cache or file)
148
- const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
149
- // Progressive caching: if dimensions were computed from file, cache them
150
- if (!fromCache && width && height) {
151
- this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => { });
152
- }
153
- // Derive mimeType from extension
154
- const ext = extname(dirent.name).slice(1).toLowerCase();
155
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
130
+ async assetEntry(filename, folder, stats, metadata) {
131
+ const { width, height } = await this.getDimensions(this.getAssetPath(filename, folder));
132
+ const ext = extname(filename).slice(1).toLowerCase();
156
133
  return {
157
- filename: dirent.name,
158
- originalName: manifestEntry?.originalName || dirent.name,
159
- mimeType,
134
+ filename,
135
+ originalName: metadata?.originalName || filename,
136
+ mimeType: IMAGE_EXTENSION_MIME[ext] || `image/${ext}`,
160
137
  size: stats.size,
161
138
  width,
162
139
  height,
163
- alt: manifestEntry?.alt,
164
- uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
165
- uploadedBy: manifestEntry?.uploadedBy,
140
+ alt: metadata?.alt,
141
+ uploadedAt: metadata?.uploadedAt || stats.birthtime.toISOString(),
142
+ uploadedBy: metadata?.uploadedBy,
166
143
  folder,
167
- tags: manifestEntry?.tags,
144
+ tags: metadata?.tags,
168
145
  };
169
146
  }
147
+ /** Build an AssetEntry from a directory entry and the records already read for its folder */
148
+ async buildAssetEntry(dirent, folder, records) {
149
+ const relativePath = folder === '/' ? dirent.name : `${folder.slice(1)}/${dirent.name}`;
150
+ const stats = await stat(this.getAssetPath(dirent.name, folder));
151
+ return this.assetEntry(dirent.name, folder, stats, records.get(relativePath));
152
+ }
170
153
  async upload(file, metadata) {
171
154
  if (!this.validateFormat(file.name)) {
172
155
  const allowed = this.config.acceptedFormats.join(', ');
@@ -177,7 +160,7 @@ export class AssetOperations {
177
160
  return { success: false, error: `File too large. Maximum: ${maxMB}MB` };
178
161
  }
179
162
  // Normalize folder path
180
- const folder = metadata?.folder && metadata.folder !== '/' ? '/' + metadata.folder.replace(/^\/+|\/+$/g, '') : '/';
163
+ const folder = metadata?.folder && metadata.folder !== '/' ? `/${metadata.folder.replace(/^\/+|\/+$/g, '')}` : '/';
181
164
  // Validate folder path (prevent path traversal)
182
165
  if (folder !== '/') {
183
166
  try {
@@ -187,6 +170,12 @@ export class AssetOperations {
187
170
  return { success: false, error: 'Invalid folder path' };
188
171
  }
189
172
  }
173
+ try {
174
+ await assetMetadata.migrateLegacyManifest(this.config);
175
+ }
176
+ catch (err) {
177
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
178
+ }
190
179
  await this.ensureDir();
191
180
  // Ensure target folder exists
192
181
  if (folder !== '/') {
@@ -196,36 +185,46 @@ export class AssetOperations {
196
185
  await setupGitLfsAttributes(this.config.assetsPath);
197
186
  this.lfsSetup = true;
198
187
  }
199
- const filename = await this.resolveFilename(file.name, folder);
200
- // Determine file path (in folder if specified)
201
- const filePath = folder !== '/'
202
- ? join(this.config.assetsPath, folder.replace(/^\//, ''), filename)
203
- : join(this.config.assetsPath, filename);
204
- const arrayBuffer = await file.arrayBuffer();
205
- await writeFile(filePath, new Uint8Array(arrayBuffer));
206
- // Compute relative path for manifest
188
+ const data = new Uint8Array(await file.arrayBuffer());
189
+ let filename;
190
+ let filePath;
191
+ for (;;) {
192
+ filename = await this.resolveFilename(file.name, folder);
193
+ filePath = this.getAssetPath(filename, folder);
194
+ try {
195
+ // oxlint-disable-next-line no-await-in-loop -- each exclusive create depends on the filename collision found by the preceding attempt.
196
+ await writeFile(filePath, data, { flag: 'wx' });
197
+ break;
198
+ }
199
+ catch (error) {
200
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST')
201
+ throw error;
202
+ }
203
+ }
207
204
  const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
208
- // Create manifest entry
209
- const manifestEntry = {
205
+ const uploadedAt = new Date().toISOString();
206
+ const uploaded = {
210
207
  alt: metadata?.alt,
211
- width: metadata?.width,
212
- height: metadata?.height,
213
- uploadedAt: new Date().toISOString(),
208
+ uploadedAt,
214
209
  uploadedBy: metadata?.uploadedBy,
215
210
  originalName: file.name,
216
211
  };
217
- await this.manifest.add(relativePath, manifestEntry);
218
- // Build full AssetEntry for return
212
+ // Replace, never merge: a new file landing on a freed filename must not
213
+ // inherit the alt text of the picture that used to be there.
214
+ await assetMetadata.write(this.config, relativePath, uploaded);
215
+ // Measure the file that was just written, so URL imports and API clients
216
+ // that send no dimensions still get the real ones back
217
+ const { width, height } = await this.getDimensions(filePath);
219
218
  const ext = extname(filename).slice(1).toLowerCase();
220
219
  const entry = {
221
220
  filename,
222
221
  originalName: file.name,
223
- mimeType: MIME_MAP[ext] || `image/${ext}`,
222
+ mimeType: IMAGE_EXTENSION_MIME[ext] || `image/${ext}`,
224
223
  size: file.size,
225
- width: metadata?.width,
226
- height: metadata?.height,
224
+ width,
225
+ height,
227
226
  alt: metadata?.alt,
228
- uploadedAt: manifestEntry.uploadedAt,
227
+ uploadedAt,
229
228
  uploadedBy: metadata?.uploadedBy,
230
229
  folder,
231
230
  };
@@ -235,8 +234,6 @@ export class AssetOperations {
235
234
  * List all assets recursively from filesystem
236
235
  */
237
236
  async list() {
238
- // Load manifest once for enrichment
239
- const manifestData = await this.manifest.read();
240
237
  const assets = [];
241
238
  // Recursive scanning helper
242
239
  const scanFolder = async (folderPath, folder) => {
@@ -247,21 +244,23 @@ export class AssetOperations {
247
244
  catch {
248
245
  return;
249
246
  }
250
- for (const entry of entries) {
251
- // Skip hidden files, system files, and symlinks
252
- if (isSystemFile(entry.name) || entry.isSymbolicLink()) {
253
- continue;
254
- }
255
- const entryPath = join(folderPath, entry.name);
247
+ // Skip hidden files, system files, and symlinks
248
+ const visible = entries.filter((entry) => !isSystemFile(entry.name) && !entry.isSymbolicLink());
249
+ const imageFiles = visible.filter((entry) => entry.isFile() && isRecognizedImageExtension(entry.name));
250
+ if (imageFiles.length > 0) {
251
+ // Records are gathered per folder: one folder's records say nothing
252
+ // about another's, so a single read of the root would blank every
253
+ // subfolder image's alt text.
254
+ const records = await assetMetadata.readFolder(this.config, folder);
255
+ const folderAssets = await Promise.all(imageFiles.map((entry) => this.buildAssetEntry(entry, folder, records)));
256
+ for (const asset of folderAssets)
257
+ assets.push(asset);
258
+ }
259
+ for (const entry of visible) {
256
260
  if (entry.isDirectory()) {
257
- // Recurse into subdirectories
258
261
  const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;
259
- await scanFolder(entryPath, subFolder);
260
- }
261
- else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {
262
- // Build asset entry from filesystem + manifest
263
- const assetEntry = await this.buildAssetEntry(entry, folder, manifestData);
264
- assets.push(assetEntry);
262
+ // oxlint-disable-next-line no-await-in-loop -- preserve deterministic depth-first asset ordering across folders.
263
+ await scanFolder(join(folderPath, entry.name), subFolder);
265
264
  }
266
265
  }
267
266
  };
@@ -269,76 +268,57 @@ export class AssetOperations {
269
268
  return assets;
270
269
  }
271
270
  /**
272
- * Get asset by filename and optional folder
271
+ * Get asset by filename and folder; the default '/' is the top of the assets folder, never a
272
+ * same-named file in another folder
273
273
  */
274
274
  async getAsset(filename, folder = '/') {
275
- // Resolve actual folder from manifest when caller only provides filename
276
- const resolvedFolder = folder === '/' ? await this.resolveFolder(filename) : folder;
277
- // Compute relative path and full file path
278
- const relativePath = resolvedFolder === '/' ? filename : `${resolvedFolder.slice(1)}/${filename}`;
279
- const fullPath = this.getAssetPath(filename, resolvedFolder);
280
- // Check if file exists on disk
275
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
281
276
  let stats;
282
277
  try {
283
- stats = await stat(fullPath);
278
+ stats = await stat(this.getAssetPath(filename, folder));
284
279
  }
285
280
  catch {
286
- // File doesn't exist
287
281
  return undefined;
288
282
  }
289
- if (!stats.isFile()) {
283
+ if (!stats.isFile())
290
284
  return undefined;
291
- }
292
- // Load manifest for enrichment
293
- const manifestData = await this.manifest.read();
294
- const manifestEntry = manifestData[relativePath];
295
- // Get dimensions
296
- const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
297
- // Progressive caching
298
- if (!fromCache && width && height) {
299
- this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => { });
300
- }
301
- // Derive mimeType from extension
302
- const ext = extname(filename).slice(1).toLowerCase();
303
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
304
- return {
305
- filename,
306
- originalName: manifestEntry?.originalName || filename,
307
- mimeType,
308
- size: stats.size,
309
- width,
310
- height,
311
- alt: manifestEntry?.alt,
312
- uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
313
- uploadedBy: manifestEntry?.uploadedBy,
314
- folder: resolvedFolder,
315
- tags: manifestEntry?.tags,
316
- };
285
+ const metadata = await assetMetadata.read(this.config, relativePath);
286
+ return this.assetEntry(filename, folder, stats, metadata);
317
287
  }
318
288
  /**
319
289
  * Delete asset file and manifest entry
320
290
  */
321
291
  async delete(filename, folder = '/') {
322
- // Resolve actual folder from manifest when caller only provides filename
323
- const resolvedFolder = folder === '/' ? await this.resolveFolder(filename) : folder;
324
- // Compute relative path for manifest
325
- const relativePath = resolvedFolder === '/' ? filename : `${resolvedFolder.slice(1)}/${filename}`;
326
- // Build full file path
327
- const filePath = this.getAssetPath(filename, resolvedFolder);
292
+ // Resolve the path BEFORE the catch that forgives a missing file: a path
293
+ // that climbs out of the media library names nothing we may delete.
294
+ let assetPath;
295
+ try {
296
+ assetPath = this.getAssetPath(filename, folder);
297
+ }
298
+ catch {
299
+ return { success: false, error: 'Asset not found' };
300
+ }
301
+ try {
302
+ await assetMetadata.migrateLegacyManifest(this.config);
303
+ }
304
+ catch (err) {
305
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
306
+ }
307
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
328
308
  // Delete file from disk (ignore if already gone)
329
309
  try {
330
- await unlink(filePath);
310
+ await unlink(assetPath);
331
311
  }
332
312
  catch {
333
- // File may already be gone, continue with manifest cleanup
313
+ // File may already be gone, continue with metadata cleanup
334
314
  }
335
- // Remove manifest entry
336
- await this.manifest.remove(relativePath);
315
+ await assetMetadata.remove(this.config, relativePath);
337
316
  return { success: true };
338
317
  }
339
318
  /**
340
319
  * Import an image from a URL (server-side fetch, no CORS issues)
341
- * Validates URL against SSRF, enforces 30s timeout, and checks response size.
320
+ * Validates the URL and every redirect hop against SSRF, enforces 30s timeout,
321
+ * and checks response size.
342
322
  */
343
323
  async importFromUrl(url, metadata) {
344
324
  // Validate URL: block private IPs and non-http(s) schemes
@@ -348,12 +328,34 @@ export class AssetOperations {
348
328
  catch (err) {
349
329
  return { success: false, error: err instanceof Error ? err.message : 'Invalid URL' };
350
330
  }
351
- // Fetch with 30-second timeout
331
+ // Fetch with 30-second timeout, following redirects MANUALLY so every hop's
332
+ // target runs through the SSRF guard BEFORE it is requested — otherwise a
333
+ // public URL can redirect into a loopback or link-local (cloud metadata)
334
+ // address that the initial check would have rejected.
352
335
  const controller = new AbortController();
353
336
  const timeout = setTimeout(() => controller.abort(), 30_000);
354
337
  let response;
338
+ let current = url;
355
339
  try {
356
- response = await fetch(url, { signal: controller.signal });
340
+ for (let hop = 0; hop <= MAX_IMPORT_REDIRECTS; hop += 1) {
341
+ const hopResponse = await fetch(current, { signal: controller.signal, redirect: 'manual' });
342
+ if (hopResponse.status < 300 || hopResponse.status >= 400) {
343
+ response = hopResponse;
344
+ break;
345
+ }
346
+ const location = hopResponse.headers.get('location');
347
+ if (location === null) {
348
+ return { success: false, error: 'Redirect missing Location header' };
349
+ }
350
+ try {
351
+ // A relative Location is legal and common; resolve it against the URL
352
+ // that produced it, then validate the absolute result.
353
+ current = validateFetchUrl(new URL(location, current).toString()).toString();
354
+ }
355
+ catch (err) {
356
+ return { success: false, error: `Redirect blocked: ${err instanceof Error ? err.message : 'Invalid URL'}` };
357
+ }
358
+ }
357
359
  }
358
360
  catch {
359
361
  return { success: false, error: 'Failed to fetch URL' };
@@ -361,6 +363,11 @@ export class AssetOperations {
361
363
  finally {
362
364
  clearTimeout(timeout);
363
365
  }
366
+ // Budget exhausted without a final response — fail closed rather than
367
+ // treating the last redirect as content
368
+ if (!response) {
369
+ return { success: false, error: 'Too many redirects' };
370
+ }
364
371
  if (!response.ok) {
365
372
  return { success: false, error: `Fetch failed with status ${response.status}` };
366
373
  }
@@ -371,8 +378,16 @@ export class AssetOperations {
371
378
  return { success: false, error: `Remote file too large. Maximum: ${maxMB}MB` };
372
379
  }
373
380
  const contentType = response.headers.get('content-type') || '';
374
- const urlPath = new URL(url).pathname;
375
- const urlFilename = urlPath.split('/').pop() || 'imported-image.jpg';
381
+ const lastSegment = new URL(url).pathname.split('/').pop() || 'imported-image.jpg';
382
+ let urlFilename = lastSegment;
383
+ try {
384
+ const decoded = decodeURIComponent(lastSegment);
385
+ if (!/\p{Cc}/u.test(decoded))
386
+ urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
387
+ }
388
+ catch {
389
+ // A malformed escape keeps the filename as written in the address.
390
+ }
376
391
  // Read response body and verify actual size
377
392
  const arrayBuffer = await response.arrayBuffer();
378
393
  if (arrayBuffer.byteLength > this.config.maxFileSize) {
@@ -388,7 +403,7 @@ export class AssetOperations {
388
403
  */
389
404
  async listFolder(subpath = '/') {
390
405
  // Normalize subpath
391
- const normalizedSubpath = subpath === '/' ? '/' : '/' + subpath.replace(/^\/+|\/+$/g, '');
406
+ const normalizedSubpath = subpath === '/' ? '/' : `/${subpath.replace(/^\/+|\/+$/g, '')}`;
392
407
  // Validate path (prevent path traversal)
393
408
  let fullPath;
394
409
  if (normalizedSubpath === '/') {
@@ -408,17 +423,16 @@ export class AssetOperations {
408
423
  }
409
424
  // Get subfolders (exclude hidden, symlinks)
410
425
  const folders = entries
411
- .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !e.isSymbolicLink())
426
+ .filter((e) => e.isDirectory() && !isSystemFile(e.name) && !e.isSymbolicLink())
412
427
  .map((e) => ({
413
428
  name: e.name,
414
429
  path: normalizedSubpath === '/' ? `/${e.name}` : `${normalizedSubpath}/${e.name}`,
415
430
  }));
416
431
  // Get image files (exclude hidden, system files, symlinks, non-images)
417
432
  const imageFiles = entries.filter((e) => e.isFile() && !isSystemFile(e.name) && !e.isSymbolicLink() && isRecognizedImageExtension(e.name));
418
- // Load manifest for enrichment
419
- const manifestData = await this.manifest.read();
433
+ const records = await assetMetadata.readFolder(this.config, normalizedSubpath);
420
434
  // Build asset entries from filesystem
421
- const assets = await Promise.all(imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, manifestData)));
435
+ const assets = await Promise.all(imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, records)));
422
436
  return { assets, folders };
423
437
  }
424
438
  /**
@@ -426,7 +440,7 @@ export class AssetOperations {
426
440
  * @param subpath Folder path relative to assets root
427
441
  */
428
442
  async createFolder(subpath) {
429
- if (!subpath || subpath === '/') {
443
+ if (!subpath || /^\/+$/.test(subpath)) {
430
444
  return { success: false, error: 'Cannot create root folder' };
431
445
  }
432
446
  // Validate path (prevent path traversal)
@@ -437,6 +451,16 @@ export class AssetOperations {
437
451
  catch {
438
452
  return { success: false, error: 'Invalid folder path' };
439
453
  }
454
+ const folderSegments = subpath.split('/').filter(Boolean);
455
+ if (folderSegments.some(isSystemFile)) {
456
+ return { success: false, error: "Folder names can't start with a dot or be a system file name like Thumbs.db" };
457
+ }
458
+ if (/[#?%\\]/.test(subpath)) {
459
+ return { success: false, error: "Folder names can't contain #, ?, % or \\" };
460
+ }
461
+ if (/[\t\n\r]/.test(subpath)) {
462
+ return { success: false, error: "Folder names can't contain tabs or line breaks" };
463
+ }
440
464
  try {
441
465
  await mkdir(fullPath, { recursive: true });
442
466
  return { success: true };
@@ -449,105 +473,38 @@ export class AssetOperations {
449
473
  }
450
474
  }
451
475
  /**
452
- * Update asset metadata (alt text, tags)
476
+ * Update asset metadata (alt text, tags). The merge happens inside the
477
+ * record's lock and the saved value is what comes back — the old re-read
478
+ * afterwards is how a success could report alt text another save had
479
+ * already written over.
453
480
  * @param filename Asset filename
454
481
  * @param updates Metadata updates (alt, tags)
455
482
  * @param folder Optional folder path (default '/')
456
483
  */
457
484
  async updateMetadata(filename, updates, folder = '/') {
458
- // Resolve actual folder from manifest when caller only provides filename
459
- const resolvedFolder = folder === '/' ? await this.resolveFolder(filename) : folder;
460
- // Compute relative path
461
- const relativePath = resolvedFolder === '/' ? filename : `${resolvedFolder.slice(1)}/${filename}`;
462
- // Check if file exists on disk
463
- const fullPath = this.getAssetPath(filename, resolvedFolder);
485
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
486
+ let stats;
464
487
  try {
465
- await stat(fullPath);
488
+ stats = await stat(this.getAssetPath(filename, folder));
466
489
  }
467
490
  catch {
468
- return { success: false, error: 'Asset not found' };
491
+ return { success: false, reason: 'not-found', error: 'Asset not found' };
469
492
  }
470
- // Get existing manifest entry
471
- const manifestData = await this.manifest.read();
472
- const existing = manifestData[relativePath] || {};
473
- // Merge updates
474
- const merged = { ...existing, ...updates };
475
- // Write back to manifest
476
- await this.manifest.add(relativePath, merged);
477
- // Return updated asset entry
478
- const asset = await this.getAsset(filename, resolvedFolder);
479
- if (!asset) {
480
- return { success: false, error: 'Failed to retrieve updated asset' };
481
- }
482
- return { success: true, asset };
483
- }
484
- /**
485
- * Get usage information for an asset (which pages reference it)
486
- * @param filename Asset filename
487
- */
488
- async getUsage(filename) {
489
- if (!this.config.contentRoot) {
490
- return [];
491
- }
492
- const usages = [];
493
- // Search patterns for the asset
494
- const searchPatterns = [filename, `/assets/uploads/${filename}`, `assets/uploads/${filename}`];
495
- // Recursively walk the content directory to find all .vxjson files
496
- const walkDir = async (dir) => {
497
- const files = [];
498
- let entries;
499
- try {
500
- entries = await readdir(dir, { withFileTypes: true });
501
- }
502
- catch {
503
- return files;
504
- }
505
- for (const entry of entries) {
506
- const fullPath = join(dir, entry.name);
507
- if (entry.isDirectory() && !entry.name.startsWith('.')) {
508
- files.push(...(await walkDir(fullPath)));
509
- }
510
- else if (entry.isFile() && entry.name.endsWith('.vxjson')) {
511
- files.push(fullPath);
512
- }
513
- }
514
- return files;
515
- };
516
- const vxjsonFiles = await walkDir(this.config.contentRoot);
517
- for (const filePath of vxjsonFiles) {
518
- try {
519
- const content = await readFile(filePath, 'utf-8');
520
- // Check if any search pattern is found in the file content
521
- const found = searchPatterns.some((pattern) => content.includes(pattern));
522
- if (found) {
523
- // Extract page name from file path (remove .vxjson extension)
524
- const relativePath = filePath.replace(this.config.contentRoot, '').replace(/^[/\\]/, '');
525
- const pageName = relativePath.replace(/\.vxjson$/, '');
526
- // Try to identify which field contains the reference
527
- // Simple approach: look for the pattern in JSON structure
528
- let field = 'unknown';
529
- try {
530
- const json = JSON.parse(content);
531
- field = this.findFieldWithAsset(json, searchPatterns) || 'content';
532
- }
533
- catch {
534
- // If JSON parsing fails, just mark as content
535
- field = 'content';
536
- }
537
- usages.push({ page: pageName, field });
538
- }
539
- }
540
- catch {
541
- // Skip files that can't be read
542
- }
493
+ let metadata;
494
+ try {
495
+ await assetMetadata.migrateLegacyManifest(this.config);
496
+ metadata = await assetMetadata.update(this.config, relativePath, updates);
497
+ }
498
+ catch (err) {
499
+ return {
500
+ success: false,
501
+ reason: 'write-failed',
502
+ error: err instanceof Error ? err.message : 'Failed to save asset metadata',
503
+ };
543
504
  }
544
- return usages;
505
+ return { success: true, asset: await this.assetEntry(filename, folder, stats, metadata) };
545
506
  }
546
- /**
547
- * Get the file path for an asset
548
- * @param filename Asset filename
549
- * @param folder Optional folder path (defaults to asset's stored folder)
550
- */
507
+ /** The file path of an asset in a folder; no folder, or '/', is the top of the assets folder. */
551
508
  getAssetPath(filename, folder) {
552
509
  const subpath = folder && folder !== '/' ? folder.replace(/^\/+|\/+$/g, '') : '';
553
510
  const combined = subpath ? `${subpath}/${filename}` : filename;
@@ -559,11 +516,16 @@ export class AssetOperations {
559
516
  * @param folder Optional folder path (default '/')
560
517
  */
561
518
  async readAssetFile(filename, folder = '/') {
519
+ // Serve images only: the metadata records live under the same tree and are
520
+ // nobody's business, and neither is any other file that lands in there.
521
+ if (!isRecognizedImageExtension(filename)) {
522
+ return { success: false, error: 'Asset not found' };
523
+ }
562
524
  // Build path from folder + filename
563
525
  const filePath = this.getAssetPath(filename, folder);
564
- // Derive mimeType from extension (don't require manifest entry)
526
+ // Derive mimeType from extension (don't require a metadata record)
565
527
  const ext = extname(filename).slice(1).toLowerCase();
566
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
528
+ const mimeType = IMAGE_EXTENSION_MIME[ext] || `image/${ext}`;
567
529
  try {
568
530
  const buffer = await readFile(filePath);
569
531
  return { success: true, buffer, mimeType };
@@ -572,33 +534,6 @@ export class AssetOperations {
572
534
  return { success: false, error: 'Asset not found' };
573
535
  }
574
536
  }
575
- /**
576
- * Helper to find which field contains an asset reference
577
- */
578
- findFieldWithAsset(obj, patterns, path = '') {
579
- if (typeof obj === 'string') {
580
- if (patterns.some((p) => obj.includes(p))) {
581
- return path || 'root';
582
- }
583
- return null;
584
- }
585
- if (Array.isArray(obj)) {
586
- for (let i = 0; i < obj.length; i++) {
587
- const result = this.findFieldWithAsset(obj[i], patterns, path ? `${path}[${i}]` : `[${i}]`);
588
- if (result)
589
- return result;
590
- }
591
- return null;
592
- }
593
- if (obj && typeof obj === 'object') {
594
- for (const [key, value] of Object.entries(obj)) {
595
- const result = this.findFieldWithAsset(value, patterns, path ? `${path}.${key}` : key);
596
- if (result)
597
- return result;
598
- }
599
- }
600
- return null;
601
- }
602
537
  /**
603
538
  * Move assets from one folder to another
604
539
  * @param filenames List of filenames to move
@@ -607,8 +542,8 @@ export class AssetOperations {
607
542
  */
608
543
  async moveAssets(filenames, sourceFolder, targetFolder) {
609
544
  // Normalize folder paths
610
- const normalizedSource = sourceFolder === '/' ? '/' : '/' + sourceFolder.replace(/^\/+|\/+$/g, '');
611
- const normalizedTarget = targetFolder === '/' ? '/' : '/' + targetFolder.replace(/^\/+|\/+$/g, '');
545
+ const normalizedSource = sourceFolder === '/' ? '/' : `/${sourceFolder.replace(/^\/+|\/+$/g, '')}`;
546
+ const normalizedTarget = targetFolder === '/' ? '/' : `/${targetFolder.replace(/^\/+|\/+$/g, '')}`;
612
547
  // Validate both folders exist (for non-root folders)
613
548
  let sourcePath;
614
549
  let targetPath;
@@ -619,6 +554,14 @@ export class AssetOperations {
619
554
  catch {
620
555
  return { success: false, error: 'Invalid folder path' };
621
556
  }
557
+ // Each name is joined onto both folders, so one with a separator or `..` would reach outside them
558
+ if (!filenames.every(isBareFilename)) {
559
+ return { success: false, error: 'Invalid filename' };
560
+ }
561
+ // The listing hides system files, and moving the folder's own manifest would drop every asset's metadata
562
+ if (filenames.some(isSystemFile)) {
563
+ return { success: false, error: 'Invalid filename' };
564
+ }
622
565
  // Verify source folder exists
623
566
  try {
624
567
  const sourceStat = await stat(sourcePath);
@@ -639,35 +582,54 @@ export class AssetOperations {
639
582
  catch {
640
583
  return { success: false, error: 'Target folder does not exist' };
641
584
  }
642
- // Move files on disk first, collect successful moves
643
- const moves = [];
585
+ if (normalizedSource === normalizedTarget)
586
+ return { success: true, moved: 0 };
587
+ const found = await Promise.all(filenames.map((filename) => lstat(join(sourcePath, filename)).catch(() => null)));
588
+ const notFiles = filenames.filter((_, index) => found[index]?.isFile() === false);
589
+ if (notFiles.length > 0)
590
+ return { success: false, error: `Not a file: ${notFiles.join(', ')}` };
591
+ const taken = new Set((await readdir(targetPath)).map((name) => name.toLowerCase()));
592
+ const conflicts = filenames.filter((filename) => taken.has(filename.toLowerCase()));
593
+ if (conflicts.length > 0) {
594
+ return { success: false, error: `Already in the target folder: ${conflicts.join(', ')}` };
595
+ }
596
+ try {
597
+ await assetMetadata.migrateLegacyManifest(this.config);
598
+ }
599
+ catch (err) {
600
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
601
+ }
602
+ // Move each file with its own record, so one failure cannot take the rest
603
+ // of the folder's metadata with it
604
+ let moved = 0;
644
605
  for (const filename of filenames) {
645
- const sourceFile = join(sourcePath, filename);
646
- const targetFile = join(targetPath, filename);
647
606
  const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;
648
607
  const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;
608
+ // Both folders are checked above, but the names come straight off the
609
+ // request and a name is free to carry `../` of its own
610
+ let from;
611
+ let to;
649
612
  try {
650
- await rename(sourceFile, targetFile);
651
- moves.push({ oldPath: oldRelativePath, newPath: newRelativePath });
613
+ from = this.getAssetPath(filename, normalizedSource);
614
+ to = this.getAssetPath(filename, normalizedTarget);
615
+ }
616
+ catch {
617
+ console.error(`[AssetOperations] Refusing to move ${filename}: it points outside the media library`);
618
+ continue;
619
+ }
620
+ try {
621
+ // oxlint-disable-next-line no-await-in-loop -- each move is committed before its metadata follows; partial failure stays attributable to one filename.
622
+ await rename(from, to);
652
623
  }
653
624
  catch (err) {
654
625
  console.error(`[AssetOperations] Failed to move ${filename}:`, err);
626
+ continue;
655
627
  }
628
+ // oxlint-disable-next-line no-await-in-loop -- metadata must follow the file that just moved before the next file starts.
629
+ await assetMetadata.move(this.config, oldRelativePath, newRelativePath);
630
+ moved += 1;
656
631
  }
657
- // Single atomic manifest update for all moves (1 read + 1 write)
658
- if (moves.length > 0) {
659
- await this.manifest.withManifest((data) => {
660
- for (const { oldPath, newPath } of moves) {
661
- const entry = data[oldPath];
662
- if (entry) {
663
- delete data[oldPath];
664
- data[newPath] = entry;
665
- }
666
- }
667
- return data;
668
- });
669
- }
670
- return { success: true, moved: moves.length };
632
+ return { success: true, moved };
671
633
  }
672
634
  /**
673
635
  * Get the complete folder tree with asset counts
@@ -734,3 +696,4 @@ export class AssetOperations {
734
696
  ];
735
697
  }
736
698
  }
699
+ //# sourceMappingURL=asset-operations.js.map