@aphexcms/cms-core 9.10.0 → 10.0.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.
Files changed (297) hide show
  1. package/dist/api/assets.d.ts +62 -7
  2. package/dist/api/assets.d.ts.map +1 -1
  3. package/dist/api/assets.js +116 -9
  4. package/dist/api/client.d.ts +1 -1
  5. package/dist/api/client.d.ts.map +1 -1
  6. package/dist/api/client.js +39 -9
  7. package/dist/api/limits.d.ts +55 -0
  8. package/dist/api/limits.d.ts.map +1 -0
  9. package/dist/api/limits.js +58 -0
  10. package/dist/api/schemas/assets.d.ts +94 -4
  11. package/dist/api/schemas/assets.d.ts.map +1 -1
  12. package/dist/api/schemas/assets.js +82 -5
  13. package/dist/api/types.d.ts +25 -0
  14. package/dist/api/types.d.ts.map +1 -1
  15. package/dist/api/upload-timeout.d.ts +17 -0
  16. package/dist/api/upload-timeout.d.ts.map +1 -0
  17. package/dist/api/upload-timeout.js +35 -0
  18. package/dist/api/upload.d.ts +42 -0
  19. package/dist/api/upload.d.ts.map +1 -0
  20. package/dist/api/upload.js +144 -0
  21. package/dist/components/AdminApp.svelte +130 -26
  22. package/dist/components/AdminApp.svelte.d.ts.map +1 -1
  23. package/dist/components/admin/AssetBrowserModal.svelte +4 -3
  24. package/dist/components/admin/AssetBrowserModal.svelte.d.ts +2 -1
  25. package/dist/components/admin/AssetBrowserModal.svelte.d.ts.map +1 -1
  26. package/dist/components/admin/MediaBrowser.svelte +1859 -281
  27. package/dist/components/admin/MediaBrowser.svelte.d.ts +21 -1
  28. package/dist/components/admin/MediaBrowser.svelte.d.ts.map +1 -1
  29. package/dist/components/admin/fields/ArrayField.svelte +21 -10
  30. package/dist/components/admin/fields/ArrayField.svelte.d.ts.map +1 -1
  31. package/dist/components/admin/fields/FileField.svelte +9 -2
  32. package/dist/components/admin/fields/FileField.svelte.d.ts.map +1 -1
  33. package/dist/components/admin/fields/ImageField.svelte +47 -12
  34. package/dist/components/admin/fields/ImageField.svelte.d.ts.map +1 -1
  35. package/dist/config.d.ts.map +1 -1
  36. package/dist/config.js +14 -0
  37. package/dist/db/interfaces/asset.d.ts +114 -5
  38. package/dist/db/interfaces/asset.d.ts.map +1 -1
  39. package/dist/db/interfaces/document.d.ts +98 -3
  40. package/dist/db/interfaces/document.d.ts.map +1 -1
  41. package/dist/hooks.d.ts.map +1 -1
  42. package/dist/hooks.js +2 -1
  43. package/dist/image/Image.svelte +72 -0
  44. package/dist/image/Image.svelte.d.ts +40 -0
  45. package/dist/image/Image.svelte.d.ts.map +1 -0
  46. package/dist/image/index.d.ts +3 -0
  47. package/dist/image/index.d.ts.map +1 -0
  48. package/dist/image/index.js +11 -0
  49. package/dist/image/types.d.ts +28 -0
  50. package/dist/image/types.d.ts.map +1 -0
  51. package/dist/image/types.js +1 -0
  52. package/dist/images/generate.d.ts +55 -0
  53. package/dist/images/generate.d.ts.map +1 -0
  54. package/dist/images/generate.js +243 -0
  55. package/dist/images/index.d.ts +2 -0
  56. package/dist/images/index.d.ts.map +1 -0
  57. package/dist/images/index.js +7 -0
  58. package/dist/images/variants.d.ts +82 -0
  59. package/dist/images/variants.d.ts.map +1 -0
  60. package/dist/images/variants.js +124 -0
  61. package/dist/jobs/asset-reference-jobs.d.ts +49 -0
  62. package/dist/jobs/asset-reference-jobs.d.ts.map +1 -0
  63. package/dist/jobs/asset-reference-jobs.js +74 -0
  64. package/dist/jobs/run-batch.d.ts.map +1 -1
  65. package/dist/jobs/run-batch.js +5 -0
  66. package/dist/lib/api/assets.d.ts +62 -7
  67. package/dist/lib/api/assets.d.ts.map +1 -1
  68. package/dist/lib/api/assets.js +116 -9
  69. package/dist/lib/api/assets.js.map +1 -1
  70. package/dist/lib/api/client.d.ts +1 -1
  71. package/dist/lib/api/client.d.ts.map +1 -1
  72. package/dist/lib/api/client.js +39 -9
  73. package/dist/lib/api/client.js.map +1 -1
  74. package/dist/lib/api/limits.d.ts +55 -0
  75. package/dist/lib/api/limits.d.ts.map +1 -0
  76. package/dist/lib/api/limits.js +59 -0
  77. package/dist/lib/api/limits.js.map +1 -0
  78. package/dist/lib/api/schemas/assets.d.ts +94 -4
  79. package/dist/lib/api/schemas/assets.d.ts.map +1 -1
  80. package/dist/lib/api/schemas/assets.js +82 -5
  81. package/dist/lib/api/schemas/assets.js.map +1 -1
  82. package/dist/lib/api/types.d.ts +25 -0
  83. package/dist/lib/api/types.d.ts.map +1 -1
  84. package/dist/lib/api/upload-timeout.d.ts +17 -0
  85. package/dist/lib/api/upload-timeout.d.ts.map +1 -0
  86. package/dist/lib/api/upload-timeout.js +36 -0
  87. package/dist/lib/api/upload-timeout.js.map +1 -0
  88. package/dist/lib/api/upload.d.ts +42 -0
  89. package/dist/lib/api/upload.d.ts.map +1 -0
  90. package/dist/lib/api/upload.js +145 -0
  91. package/dist/lib/api/upload.js.map +1 -0
  92. package/dist/lib/config.d.ts.map +1 -1
  93. package/dist/lib/config.js +14 -0
  94. package/dist/lib/config.js.map +1 -1
  95. package/dist/lib/db/interfaces/asset.d.ts +114 -5
  96. package/dist/lib/db/interfaces/asset.d.ts.map +1 -1
  97. package/dist/lib/db/interfaces/document.d.ts +98 -3
  98. package/dist/lib/db/interfaces/document.d.ts.map +1 -1
  99. package/dist/lib/hooks.d.ts.map +1 -1
  100. package/dist/lib/hooks.js +2 -1
  101. package/dist/lib/hooks.js.map +1 -1
  102. package/dist/lib/image/index.d.ts +3 -0
  103. package/dist/lib/image/index.d.ts.map +1 -0
  104. package/dist/lib/image/index.js +12 -0
  105. package/dist/lib/image/index.js.map +1 -0
  106. package/dist/lib/image/types.d.ts +28 -0
  107. package/dist/lib/image/types.d.ts.map +1 -0
  108. package/dist/lib/image/types.js +2 -0
  109. package/dist/lib/image/types.js.map +1 -0
  110. package/dist/lib/images/generate.d.ts +55 -0
  111. package/dist/lib/images/generate.d.ts.map +1 -0
  112. package/dist/lib/images/generate.js +244 -0
  113. package/dist/lib/images/generate.js.map +1 -0
  114. package/dist/lib/images/index.d.ts +2 -0
  115. package/dist/lib/images/index.d.ts.map +1 -0
  116. package/dist/lib/images/index.js +8 -0
  117. package/dist/lib/images/index.js.map +1 -0
  118. package/dist/lib/images/variants.d.ts +82 -0
  119. package/dist/lib/images/variants.d.ts.map +1 -0
  120. package/dist/lib/images/variants.js +125 -0
  121. package/dist/lib/images/variants.js.map +1 -0
  122. package/dist/lib/jobs/asset-reference-jobs.d.ts +49 -0
  123. package/dist/lib/jobs/asset-reference-jobs.d.ts.map +1 -0
  124. package/dist/lib/jobs/asset-reference-jobs.js +75 -0
  125. package/dist/lib/jobs/asset-reference-jobs.js.map +1 -0
  126. package/dist/lib/jobs/run-batch.d.ts.map +1 -1
  127. package/dist/lib/jobs/run-batch.js +5 -0
  128. package/dist/lib/jobs/run-batch.js.map +1 -1
  129. package/dist/lib/local-api/collection-api.d.ts +19 -2
  130. package/dist/lib/local-api/collection-api.d.ts.map +1 -1
  131. package/dist/lib/local-api/collection-api.js +65 -17
  132. package/dist/lib/local-api/collection-api.js.map +1 -1
  133. package/dist/lib/preview/assets.d.ts +19 -0
  134. package/dist/lib/preview/assets.d.ts.map +1 -1
  135. package/dist/lib/preview/assets.js +6 -0
  136. package/dist/lib/preview/assets.js.map +1 -1
  137. package/dist/lib/routes/assets-cdn.d.ts +19 -0
  138. package/dist/lib/routes/assets-cdn.d.ts.map +1 -1
  139. package/dist/lib/routes/assets-cdn.js +295 -17
  140. package/dist/lib/routes/assets-cdn.js.map +1 -1
  141. package/dist/lib/server/api/index.d.ts.map +1 -1
  142. package/dist/lib/server/api/index.js +87 -8
  143. package/dist/lib/server/api/index.js.map +1 -1
  144. package/dist/lib/server/api/routes/assets-bulk.d.ts.map +1 -1
  145. package/dist/lib/server/api/routes/assets-bulk.js +36 -7
  146. package/dist/lib/server/api/routes/assets-bulk.js.map +1 -1
  147. package/dist/lib/server/api/routes/assets-by-id.d.ts.map +1 -1
  148. package/dist/lib/server/api/routes/assets-by-id.js +32 -15
  149. package/dist/lib/server/api/routes/assets-by-id.js.map +1 -1
  150. package/dist/lib/server/api/routes/assets-direct-upload.d.ts +4 -0
  151. package/dist/lib/server/api/routes/assets-direct-upload.d.ts.map +1 -0
  152. package/dist/lib/server/api/routes/assets-direct-upload.js +164 -0
  153. package/dist/lib/server/api/routes/assets-direct-upload.js.map +1 -0
  154. package/dist/lib/server/api/routes/assets-poster.d.ts +4 -0
  155. package/dist/lib/server/api/routes/assets-poster.d.ts.map +1 -0
  156. package/dist/lib/server/api/routes/assets-poster.js +120 -0
  157. package/dist/lib/server/api/routes/assets-poster.js.map +1 -0
  158. package/dist/lib/server/api/routes/assets-references.d.ts.map +1 -1
  159. package/dist/lib/server/api/routes/assets-references.js +64 -5
  160. package/dist/lib/server/api/routes/assets-references.js.map +1 -1
  161. package/dist/lib/server/api/routes/assets.d.ts.map +1 -1
  162. package/dist/lib/server/api/routes/assets.js +116 -12
  163. package/dist/lib/server/api/routes/assets.js.map +1 -1
  164. package/dist/lib/server/api/routes/clear-asset-references.d.ts +18 -0
  165. package/dist/lib/server/api/routes/clear-asset-references.d.ts.map +1 -0
  166. package/dist/lib/server/api/routes/clear-asset-references.js +32 -0
  167. package/dist/lib/server/api/routes/clear-asset-references.js.map +1 -0
  168. package/dist/lib/server/api/routes/documents.d.ts.map +1 -1
  169. package/dist/lib/server/api/routes/documents.js +27 -1
  170. package/dist/lib/server/api/routes/documents.js.map +1 -1
  171. package/dist/lib/server/index.d.ts +2 -0
  172. package/dist/lib/server/index.d.ts.map +1 -1
  173. package/dist/lib/server/index.js +4 -0
  174. package/dist/lib/server/index.js.map +1 -1
  175. package/dist/lib/services/asset-references-service.d.ts +93 -0
  176. package/dist/lib/services/asset-references-service.d.ts.map +1 -0
  177. package/dist/lib/services/asset-references-service.js +198 -0
  178. package/dist/lib/services/asset-references-service.js.map +1 -0
  179. package/dist/lib/services/asset-service.d.ts +115 -14
  180. package/dist/lib/services/asset-service.d.ts.map +1 -1
  181. package/dist/lib/services/asset-service.js +312 -31
  182. package/dist/lib/services/asset-service.js.map +1 -1
  183. package/dist/lib/services/references-service.d.ts +19 -15
  184. package/dist/lib/services/references-service.d.ts.map +1 -1
  185. package/dist/lib/services/references-service.js +59 -31
  186. package/dist/lib/services/references-service.js.map +1 -1
  187. package/dist/lib/services/version-service.d.ts +10 -1
  188. package/dist/lib/services/version-service.d.ts.map +1 -1
  189. package/dist/lib/services/version-service.js +26 -4
  190. package/dist/lib/services/version-service.js.map +1 -1
  191. package/dist/lib/storage/adapters/local-storage-adapter.d.ts +38 -0
  192. package/dist/lib/storage/adapters/local-storage-adapter.d.ts.map +1 -1
  193. package/dist/lib/storage/adapters/local-storage-adapter.js +86 -19
  194. package/dist/lib/storage/adapters/local-storage-adapter.js.map +1 -1
  195. package/dist/lib/storage/index.d.ts +1 -0
  196. package/dist/lib/storage/index.d.ts.map +1 -1
  197. package/dist/lib/storage/index.js +2 -0
  198. package/dist/lib/storage/index.js.map +1 -1
  199. package/dist/lib/storage/interfaces/storage.d.ts +135 -5
  200. package/dist/lib/storage/interfaces/storage.d.ts.map +1 -1
  201. package/dist/lib/storage/keys.d.ts +96 -0
  202. package/dist/lib/storage/keys.d.ts.map +1 -0
  203. package/dist/lib/storage/keys.js +160 -0
  204. package/dist/lib/storage/keys.js.map +1 -0
  205. package/dist/lib/types/asset.d.ts +92 -12
  206. package/dist/lib/types/asset.d.ts.map +1 -1
  207. package/dist/lib/types/capabilities.d.ts +11 -0
  208. package/dist/lib/types/capabilities.d.ts.map +1 -1
  209. package/dist/lib/types/capabilities.js +20 -6
  210. package/dist/lib/types/capabilities.js.map +1 -1
  211. package/dist/lib/types/config.d.ts +127 -0
  212. package/dist/lib/types/config.d.ts.map +1 -1
  213. package/dist/lib/utils/asset-reference-walk.d.ts +44 -0
  214. package/dist/lib/utils/asset-reference-walk.d.ts.map +1 -0
  215. package/dist/lib/utils/asset-reference-walk.js +144 -0
  216. package/dist/lib/utils/asset-reference-walk.js.map +1 -0
  217. package/dist/lib/utils/image-url.d.ts +61 -26
  218. package/dist/lib/utils/image-url.d.ts.map +1 -1
  219. package/dist/lib/utils/image-url.js +143 -26
  220. package/dist/lib/utils/image-url.js.map +1 -1
  221. package/dist/lib/utils/video-metadata.d.ts +39 -0
  222. package/dist/lib/utils/video-metadata.d.ts.map +1 -0
  223. package/dist/lib/utils/video-metadata.js +161 -0
  224. package/dist/lib/utils/video-metadata.js.map +1 -0
  225. package/dist/local-api/collection-api.d.ts +19 -2
  226. package/dist/local-api/collection-api.d.ts.map +1 -1
  227. package/dist/local-api/collection-api.js +65 -17
  228. package/dist/preview/assets.d.ts +19 -0
  229. package/dist/preview/assets.d.ts.map +1 -1
  230. package/dist/preview/assets.js +6 -0
  231. package/dist/routes/assets-cdn.d.ts +19 -0
  232. package/dist/routes/assets-cdn.d.ts.map +1 -1
  233. package/dist/routes/assets-cdn.js +295 -17
  234. package/dist/server/api/index.d.ts.map +1 -1
  235. package/dist/server/api/index.js +87 -8
  236. package/dist/server/api/routes/assets-bulk.d.ts.map +1 -1
  237. package/dist/server/api/routes/assets-bulk.js +36 -7
  238. package/dist/server/api/routes/assets-by-id.d.ts.map +1 -1
  239. package/dist/server/api/routes/assets-by-id.js +32 -15
  240. package/dist/server/api/routes/assets-direct-upload.d.ts +4 -0
  241. package/dist/server/api/routes/assets-direct-upload.d.ts.map +1 -0
  242. package/dist/server/api/routes/assets-direct-upload.js +163 -0
  243. package/dist/server/api/routes/assets-poster.d.ts +4 -0
  244. package/dist/server/api/routes/assets-poster.d.ts.map +1 -0
  245. package/dist/server/api/routes/assets-poster.js +119 -0
  246. package/dist/server/api/routes/assets-references.d.ts.map +1 -1
  247. package/dist/server/api/routes/assets-references.js +64 -5
  248. package/dist/server/api/routes/assets.d.ts.map +1 -1
  249. package/dist/server/api/routes/assets.js +116 -12
  250. package/dist/server/api/routes/clear-asset-references.d.ts +18 -0
  251. package/dist/server/api/routes/clear-asset-references.d.ts.map +1 -0
  252. package/dist/server/api/routes/clear-asset-references.js +31 -0
  253. package/dist/server/api/routes/documents.d.ts.map +1 -1
  254. package/dist/server/api/routes/documents.js +27 -1
  255. package/dist/server/index.d.ts +2 -0
  256. package/dist/server/index.d.ts.map +1 -1
  257. package/dist/server/index.js +4 -0
  258. package/dist/services/asset-references-service.d.ts +93 -0
  259. package/dist/services/asset-references-service.d.ts.map +1 -0
  260. package/dist/services/asset-references-service.js +197 -0
  261. package/dist/services/asset-service.d.ts +115 -14
  262. package/dist/services/asset-service.d.ts.map +1 -1
  263. package/dist/services/asset-service.js +312 -31
  264. package/dist/services/references-service.d.ts +19 -15
  265. package/dist/services/references-service.d.ts.map +1 -1
  266. package/dist/services/references-service.js +59 -31
  267. package/dist/services/version-service.d.ts +10 -1
  268. package/dist/services/version-service.d.ts.map +1 -1
  269. package/dist/services/version-service.js +26 -4
  270. package/dist/storage/adapters/local-storage-adapter.d.ts +38 -0
  271. package/dist/storage/adapters/local-storage-adapter.d.ts.map +1 -1
  272. package/dist/storage/adapters/local-storage-adapter.js +86 -19
  273. package/dist/storage/index.d.ts +1 -0
  274. package/dist/storage/index.d.ts.map +1 -1
  275. package/dist/storage/index.js +2 -0
  276. package/dist/storage/interfaces/storage.d.ts +135 -5
  277. package/dist/storage/interfaces/storage.d.ts.map +1 -1
  278. package/dist/storage/keys.d.ts +96 -0
  279. package/dist/storage/keys.d.ts.map +1 -0
  280. package/dist/storage/keys.js +159 -0
  281. package/dist/types/asset.d.ts +92 -12
  282. package/dist/types/asset.d.ts.map +1 -1
  283. package/dist/types/capabilities.d.ts +11 -0
  284. package/dist/types/capabilities.d.ts.map +1 -1
  285. package/dist/types/capabilities.js +20 -6
  286. package/dist/types/config.d.ts +127 -0
  287. package/dist/types/config.d.ts.map +1 -1
  288. package/dist/utils/asset-reference-walk.d.ts +44 -0
  289. package/dist/utils/asset-reference-walk.d.ts.map +1 -0
  290. package/dist/utils/asset-reference-walk.js +143 -0
  291. package/dist/utils/image-url.d.ts +61 -26
  292. package/dist/utils/image-url.d.ts.map +1 -1
  293. package/dist/utils/image-url.js +143 -26
  294. package/dist/utils/video-metadata.d.ts +39 -0
  295. package/dist/utils/video-metadata.d.ts.map +1 -0
  296. package/dist/utils/video-metadata.js +160 -0
  297. package/package.json +6 -1
@@ -1,5 +1,6 @@
1
1
  import { Hono } from 'hono';
2
2
  import { bodyLimit } from 'hono/body-limit';
3
+ import { formatMegabytes, resolveMaxUploadBytes } from '../../api/limits.js';
3
4
  import { schemasRouter } from './routes/schemas.js';
4
5
  import { documentsRouter } from './routes/documents.js';
5
6
  import { documentsByIdRouter } from './routes/documents-by-id.js';
@@ -9,6 +10,8 @@ import { documentVersionsRouter } from './routes/document-versions.js';
9
10
  import { assetsRouter } from './routes/assets.js';
10
11
  import { assetsByIdRouter } from './routes/assets-by-id.js';
11
12
  import { assetsBulkRouter } from './routes/assets-bulk.js';
13
+ import { assetsDirectUploadRouter } from './routes/assets-direct-upload.js';
14
+ import { assetsPosterRouter } from './routes/assets-poster.js';
12
15
  import { assetsReferencesRouter } from './routes/assets-references.js';
13
16
  import { organizationsRouter } from './routes/organizations.js';
14
17
  import { organizationsByIdRouter } from './routes/organizations-by-id.js';
@@ -34,10 +37,25 @@ import { agentChangeSetsRouter } from './routes/agent-change-sets.js';
34
37
  export function createAphexApi() {
35
38
  const app = new Hono().basePath('/api');
36
39
  // Reject oversized request bodies before they're fully buffered.
37
- app.use('*', bodyLimit({
38
- maxSize: 10 * 1024 * 1024, // 10MB for JSON endpoints
39
- onError: (c) => c.json({ success: false, error: 'Request body too large (max 10MB)' }, 413)
40
- }));
40
+ //
41
+ // This applies to uploads as much as to JSON, and it is the *first* ceiling a
42
+ // large upload meets — lower than the 50MB the assets route checks against,
43
+ // which is why that check never fires. The admin UI pre-checks file sizes
44
+ // against the same constant so an oversized file is refused before it's sent.
45
+ // Read per-request rather than closing over a value at construction time:
46
+ // `createAphexApi()` runs once at module scope, before any config exists, but
47
+ // `c.env.aphexCMS` is supplied on every `app.fetch(req, env)` call. Building
48
+ // the middleware per request is negligible next to handling the body.
49
+ app.use('*', async (c, next) => {
50
+ const maxSize = resolveMaxUploadBytes(c.env?.aphexCMS);
51
+ return bodyLimit({
52
+ maxSize,
53
+ onError: (ctx) => ctx.json({
54
+ success: false,
55
+ error: `Request body too large (max ${formatMegabytes(maxSize)})`
56
+ }, 413)
57
+ })(c, next);
58
+ });
41
59
  // Bridge: lift values passed via app.fetch(req, env) onto c.var so
42
60
  // handlers can read c.var.aphexCMS / c.var.auth directly.
43
61
  app.use('*', async (c, next) => {
@@ -70,7 +88,11 @@ export function mountAphexBuiltins(app) {
70
88
  // Assets — same precedence rule: specific paths before parametric.
71
89
  // `/assets/bulk` and `/assets/references/counts` must register before
72
90
  // `/assets/:id` or Hono will capture them as `:id = "bulk"` etc.
91
+ // Before assets-by-id: Hono matches in registration order, and `/:id` would
92
+ // otherwise claim `/upload-url` and `/confirm`.
93
+ app.route('/assets', assetsDirectUploadRouter);
73
94
  app.route('/assets', assetsBulkRouter);
95
+ app.route('/assets', assetsPosterRouter);
74
96
  app.route('/assets', assetsReferencesRouter);
75
97
  app.route('/assets', assetsByIdRouter);
76
98
  app.route('/assets', assetsRouter);
@@ -103,18 +125,75 @@ export function mountAphexBuiltins(app) {
103
125
  // POST /api/agent/change-sets/:id/undo
104
126
  app.route('/agent', agentChangeSetsRouter);
105
127
  // Health check — unauthenticated, used by load balancers and uptime monitors.
128
+ //
129
+ // The database decides the status code: without it nothing can be served, so
130
+ // a failure is a genuine 503 and the node should leave rotation. Storage is
131
+ // reported but never fails the check — when object storage is down the site
132
+ // still renders, only uploads and media break, and 503-ing would pull healthy
133
+ // nodes out of the load balancer over a dependency they don't need to answer
134
+ // a page request. That case surfaces as `status: 'degraded'` with HTTP 200,
135
+ // which an uptime monitor can alert on without a proxy treating it as death.
136
+ //
137
+ // Storage is probed only when `config.storageHealthCheck` is enabled, since
138
+ // the probe bills against metered object storage on an unauthenticated route.
106
139
  app.get('/aphex-health', async (c) => {
107
140
  try {
108
- const { databaseAdapter } = c.var.aphexCMS;
109
- const dbHealthy = await databaseAdapter.isHealthy();
110
- const status = dbHealthy ? 'healthy' : 'degraded';
111
- return c.json({ status, database: dbHealthy }, dbHealthy ? 200 : 503);
141
+ const { databaseAdapter, storageAdapter, config } = c.var.aphexCMS;
142
+ const probeStorage = config?.storageHealthCheck === true;
143
+ const [dbHealthy, storageHealthy] = await Promise.all([
144
+ databaseAdapter.isHealthy(),
145
+ probeStorage ? checkStorageHealth(storageAdapter) : Promise.resolve(null)
146
+ ]);
147
+ const status = dbHealthy ? (storageHealthy === false ? 'degraded' : 'healthy') : 'degraded';
148
+ return c.json({
149
+ status,
150
+ database: dbHealthy,
151
+ // Omitted rather than reported false when not probed, so a monitor
152
+ // can't mistake "not checked" for "storage is down".
153
+ ...(probeStorage ? { storage: storageHealthy } : {})
154
+ }, dbHealthy ? 200 : 503);
112
155
  }
113
156
  catch {
114
157
  return c.json({ status: 'unhealthy', database: false }, 503);
115
158
  }
116
159
  });
117
160
  }
161
+ /**
162
+ * How long a storage health result is reused before the adapter is probed again.
163
+ */
164
+ const STORAGE_HEALTH_TTL_MS = 30_000;
165
+ let storageHealthCache = null;
166
+ /**
167
+ * Probe storage health, at most once per {@link STORAGE_HEALTH_TTL_MS}.
168
+ *
169
+ * The cache is the point, not an optimization. `/aphex-health` is
170
+ * unauthenticated by design, and a remote storage adapter answers `isHealthy()`
171
+ * with a real network round-trip to the bucket — on S3/R2 a billable one. Probing
172
+ * per request would let anyone turn an uptime endpoint into someone else's
173
+ * storage bill, and would put load on the bucket proportional to how aggressively
174
+ * the site is scraped. Thirty seconds is far below any useful alerting interval
175
+ * while collapsing a flood of requests into one probe.
176
+ *
177
+ * A throwing adapter reads as unhealthy rather than propagating: storage must not
178
+ * be able to turn a 200 into a 503 (see the route comment).
179
+ */
180
+ async function checkStorageHealth(storageAdapter) {
181
+ if (!storageAdapter)
182
+ return false;
183
+ const now = Date.now();
184
+ if (storageHealthCache && now - storageHealthCache.checkedAt < STORAGE_HEALTH_TTL_MS) {
185
+ return storageHealthCache.healthy;
186
+ }
187
+ let healthy;
188
+ try {
189
+ healthy = await storageAdapter.isHealthy();
190
+ }
191
+ catch {
192
+ healthy = false;
193
+ }
194
+ storageHealthCache = { healthy, checkedAt: now };
195
+ return healthy;
196
+ }
118
197
  /**
119
198
  * Adapter: wrap a SvelteKit-style `RequestHandler` so it can be mounted
120
199
  * onto a Hono router.
@@ -1 +1 @@
1
- {"version":3,"file":"assets-bulk.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-bulk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAyE3C,CAAC"}
1
+ {"version":3,"file":"assets-bulk.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-bulk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAM5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAsG3C,CAAC"}
@@ -3,6 +3,7 @@ import { zValidator } from '@hono/zod-validator';
3
3
  import { cmsLogger } from '../../../utils/logger.js';
4
4
  import { bulkDeleteAssetsRequest } from '../../../api/schemas/assets.js';
5
5
  import { hasCapability } from '../../../types/capabilities.js';
6
+ import { clearAssetReferences } from './clear-asset-references.js';
6
7
  export const assetsBulkRouter = new Hono().delete('/bulk', zValidator('json', bulkDeleteAssetsRequest, (result, c) => {
7
8
  if (!result.success) {
8
9
  return c.json({
@@ -13,7 +14,7 @@ export const assetsBulkRouter = new Hono().delete('/bulk', zValidator('json', bu
13
14
  }
14
15
  }), async (c) => {
15
16
  try {
16
- const { assetService, databaseAdapter } = c.var.aphexCMS;
17
+ const { assetService, databaseAdapter, localAPI } = c.var.aphexCMS;
17
18
  const auth = c.var.auth;
18
19
  if (!auth || auth.type === 'partial_session') {
19
20
  return c.json({ success: false, error: 'Unauthorized' }, 401);
@@ -22,17 +23,42 @@ export const assetsBulkRouter = new Hono().delete('/bulk', zValidator('json', bu
22
23
  return c.json({ success: false, error: 'Forbidden: asset.delete capability required' }, 403);
23
24
  }
24
25
  const { ids } = c.req.valid('json');
26
+ const force = c.req.query('force') === 'true';
27
+ // Scanned WITHOUT `knownTypes`, like the single-asset guard: a document
28
+ // whose schema type was removed from the codebase still exists in the DB
29
+ // and still holds the reference, so filtering it out would let the delete
30
+ // through and leave a dangling `_ref` that renders as a blank image.
25
31
  let referencedIds = [];
26
- if (databaseAdapter.countDocumentReferencesForAssets) {
32
+ let unregisteredTypes = [];
33
+ if (databaseAdapter.countDocumentReferencesForAssets && !force) {
27
34
  const counts = await databaseAdapter.countDocumentReferencesForAssets(auth.organizationId, ids);
28
35
  referencedIds = ids.filter((id) => (counts[id] || 0) > 0);
36
+ // Which of those blockers are documents nobody can open?
37
+ //
38
+ // Without this the message is a dead end — the same dead end the
39
+ // single-asset path already fixed and this one didn't inherit. An
40
+ // editor told "still referenced by documents" goes looking for the
41
+ // document, finds nothing in the admin because its type is gone, and
42
+ // has no way to proceed. Naming the orphaned types, and honouring
43
+ // `force`, is the difference between a refusal and a trap.
44
+ if (referencedIds.length > 0 && databaseAdapter.findDocumentsReferencingAsset) {
45
+ const known = new Set(localAPI.getCollectionNames());
46
+ const types = new Set();
47
+ for (const id of referencedIds) {
48
+ const refs = await databaseAdapter.findDocumentsReferencingAsset(auth.organizationId, id);
49
+ for (const ref of refs)
50
+ if (!known.has(ref.type))
51
+ types.add(ref.type);
52
+ }
53
+ unregisteredTypes = [...types];
54
+ }
29
55
  }
30
56
  if (referencedIds.length > 0) {
31
- return c.json({
32
- success: false,
33
- error: `Cannot delete ${referencedIds.length} asset${referencedIds.length > 1 ? 's' : ''} because ${referencedIds.length > 1 ? 'they are' : 'it is'} still referenced by documents`,
34
- referencedIds
35
- }, 409);
57
+ let error = `Cannot delete ${referencedIds.length} asset${referencedIds.length > 1 ? 's' : ''} because ${referencedIds.length > 1 ? 'they are' : 'it is'} still referenced by documents`;
58
+ if (unregisteredTypes.length > 0) {
59
+ error += `. Some are used by documents of type ${unregisteredTypes.join(', ')}, which no longer ${unregisteredTypes.length > 1 ? 'exist' : 'exists'} in the schema — delete with force to remove those references.`;
60
+ }
61
+ return c.json({ success: false, error, referencedIds, unregisteredTypes }, 409);
36
62
  }
37
63
  const results = { deleted: 0, failed: 0 };
38
64
  for (const id of ids) {
@@ -40,6 +66,9 @@ export const assetsBulkRouter = new Hono().delete('/bulk', zValidator('json', bu
40
66
  const result = await assetService.deleteAsset(auth.organizationId, id);
41
67
  if (result) {
42
68
  results.deleted++;
69
+ // Bulk delete used to skip this, so a batch left every
70
+ // reference behind while an identical single delete cleaned up.
71
+ await clearAssetReferences(databaseAdapter, auth.organizationId, id);
43
72
  }
44
73
  else {
45
74
  results.failed++;
@@ -1 +1 @@
1
- {"version":3,"file":"assets-by-id.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-by-id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAM5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAsJ1C,CAAC"}
1
+ {"version":3,"file":"assets-by-id.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-by-id.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAO5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAqK1C,CAAC"}
@@ -3,6 +3,7 @@ import { zValidator } from '@hono/zod-validator';
3
3
  import { cmsLogger } from '../../../utils/logger.js';
4
4
  import { updateAssetRequest } from '../../../api/schemas/assets.js';
5
5
  import { hasCapability } from '../../../types/capabilities.js';
6
+ import { clearAssetReferences } from './clear-asset-references.js';
6
7
  export const assetsByIdRouter = new Hono()
7
8
  .get('/:id', async (c) => {
8
9
  try {
@@ -12,6 +13,9 @@ export const assetsByIdRouter = new Hono()
12
13
  if (!auth || auth.type === 'partial_session') {
13
14
  return c.json({ success: false, error: 'Unauthorized' }, 401);
14
15
  }
16
+ if (!hasCapability(auth, 'asset.read')) {
17
+ return c.json({ success: false, error: 'Forbidden: asset.read capability required' }, 403);
18
+ }
15
19
  if (!id) {
16
20
  return c.json({ success: false, error: 'Asset ID is required' }, 400);
17
21
  }
@@ -40,27 +44,38 @@ export const assetsByIdRouter = new Hono()
40
44
  if (!id) {
41
45
  return c.json({ success: false, error: 'Asset ID is required' }, 400);
42
46
  }
43
- if (databaseAdapter.findDocumentsReferencingAsset) {
44
- const knownTypes = localAPI.getCollectionNames();
45
- const refs = await databaseAdapter.findDocumentsReferencingAsset(auth.organizationId, id, knownTypes);
47
+ // `?force=true` bypasses the reference guard. It is the only escape for a
48
+ // reference held by a document whose schema type is no longer registered:
49
+ // such a document can't be opened in the admin, so the reference can't be
50
+ // removed by hand and the asset would otherwise be undeletable forever.
51
+ const force = c.req.query('force') === 'true';
52
+ if (databaseAdapter.findDocumentsReferencingAsset && !force) {
53
+ // Deliberately scanned WITHOUT `knownTypes`. Type-filtering is correct
54
+ // for *display* (assets-references.ts) but wrong for the delete guard:
55
+ // a document whose type was removed from the codebase still exists in
56
+ // the DB and still holds the reference, so filtering it out lets the
57
+ // delete through and leaves a permanently dangling `_ref` that renders
58
+ // as a silently blank image.
59
+ const refs = await databaseAdapter.findDocumentsReferencingAsset(auth.organizationId, id);
46
60
  if (refs.length > 0) {
47
- return c.json({
48
- success: false,
49
- error: `Cannot delete asset — it is referenced by ${refs.length} document${refs.length > 1 ? 's' : ''}`
50
- }, 409);
61
+ const knownTypes = new Set(localAPI.getCollectionNames());
62
+ const orphanRefs = refs.filter((ref) => !knownTypes.has(ref.type));
63
+ const unregisteredTypes = [...new Set(orphanRefs.map((ref) => ref.type))];
64
+ let error = `Cannot delete asset — it is referenced by ${refs.length} document${refs.length > 1 ? 's' : ''}`;
65
+ if (unregisteredTypes.length > 0) {
66
+ // Without this the message is a dead end: the blocking document
67
+ // doesn't appear anywhere in the admin, so "remove the reference
68
+ // first" is impossible advice.
69
+ error += `, ${orphanRefs.length} of them of type ${unregisteredTypes.join(', ')}, which no longer ${unregisteredTypes.length > 1 ? 'exist' : 'exists'} in the schema — delete with force to remove those references.`;
70
+ }
71
+ return c.json({ success: false, error, references: refs, unregisteredTypes }, 409);
51
72
  }
52
73
  }
53
74
  const result = await assetService.deleteAsset(auth.organizationId, id);
54
75
  if (!result) {
55
76
  return c.json({ success: false, error: 'Asset not found or could not be deleted' }, 404);
56
77
  }
57
- if (databaseAdapter.clearAssetFromPublishedData) {
58
- const cleared = await databaseAdapter.clearAssetFromPublishedData(auth.organizationId, id);
59
- console.log(`[Asset Delete] Cleared asset ${id} from ${cleared} document(s) publishedData`);
60
- }
61
- else {
62
- console.log(`[Asset Delete] clearAssetFromPublishedData not available on adapter`);
63
- }
78
+ await clearAssetReferences(databaseAdapter, auth.organizationId, id);
64
79
  return c.json({ success: true });
65
80
  }
66
81
  catch (error) {
@@ -90,10 +105,11 @@ export const assetsByIdRouter = new Hono()
90
105
  if (!id) {
91
106
  return c.json({ success: false, error: 'Asset ID is required' }, 400);
92
107
  }
93
- const { title, description, alt, creditLine } = c.req.valid('json');
108
+ const { originalFilename, title, description, alt, creditLine } = c.req.valid('json');
94
109
  let updatedAsset;
95
110
  if (auth.type === 'session') {
96
111
  updatedAsset = await assetService.updateAssetMetadata(auth.organizationId, id, {
112
+ originalFilename,
97
113
  title,
98
114
  description,
99
115
  alt,
@@ -103,6 +119,7 @@ export const assetsByIdRouter = new Hono()
103
119
  }
104
120
  else {
105
121
  updatedAsset = await assetService.updateAssetMetadata(auth.organizationId, id, {
122
+ originalFilename,
106
123
  title,
107
124
  description,
108
125
  alt,
@@ -0,0 +1,4 @@
1
+ import { Hono } from 'hono';
2
+ import type { AphexEnv } from '../index.js';
3
+ export declare const assetsDirectUploadRouter: Hono<AphexEnv>;
4
+ //# sourceMappingURL=assets-direct-upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assets-direct-upload.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-direct-upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAQ5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AA0CzC,eAAO,MAAM,wBAAwB,EAAE,IAAI,CAAC,QAAQ,CAuKlD,CAAC"}
@@ -0,0 +1,163 @@
1
+ import { Hono } from 'hono';
2
+ import { zValidator } from '@hono/zod-validator';
3
+ import { cmsLogger } from '../../../utils/logger.js';
4
+ import { confirmUploadRequest, createUploadUrlRequest } from '../../../api/schemas/assets.js';
5
+ import { hasCapability } from '../../../types/capabilities.js';
6
+ import { resolveMaxUploadBytes, formatMegabytes } from '../../../api/limits.js';
7
+ import { buildOriginalKey } from '../../../storage/keys.js';
8
+ import { encryptSecret, decryptSecret } from '../../../security/secret-crypto.js';
9
+ /**
10
+ * Direct-to-storage upload.
11
+ *
12
+ * Exists because of a hard platform limit, not for speed: a serverless host
13
+ * caps the *request* body it accepts (Vercel Functions: 4.5 MB) and, unlike
14
+ * responses, there is no streaming escape. An ordinary large photo therefore
15
+ * cannot reach the app at all. The browser PUTs it to the bucket instead, and
16
+ * the app only ever handles the intent and the confirmation.
17
+ *
18
+ * Two steps, both authorized:
19
+ *
20
+ * POST /assets/upload-url → { assetId, uploadUrl, ticket }
21
+ * PUT <uploadUrl> → browser to bucket, app not involved
22
+ * POST /assets/confirm → { ticket } → the asset row
23
+ *
24
+ * The `ticket` is the upload intent, sealed with the app's own encryption key.
25
+ * It exists because `confirm` must not trust the client about *what was
26
+ * uploaded* — the key, filename and mime type all decide where bytes live and
27
+ * how they're served — and a serverless deployment cannot keep that intent in
28
+ * process memory, since a different instance will handle the confirmation.
29
+ * Sealing it means no table, no shared cache, and no trust.
30
+ */
31
+ /** Write grants are short-lived by design; this is only long enough to upload. */
32
+ const UPLOAD_URL_TTL_SECONDS = 15 * 60;
33
+ /** How long a ticket stays redeemable. Slightly beyond the URL's own life. */
34
+ const TICKET_TTL_MS = 20 * 60 * 1000;
35
+ export const assetsDirectUploadRouter = new Hono()
36
+ .post('/upload-url', zValidator('json', createUploadUrlRequest, (result, c) => {
37
+ if (!result.success) {
38
+ return c.json({ success: false, error: 'Invalid request body', issues: result.error.issues }, 400);
39
+ }
40
+ }), async (c) => {
41
+ try {
42
+ const { storageAdapter, config } = c.var.aphexCMS;
43
+ const auth = c.var.auth;
44
+ if (!auth || auth.type === 'partial_session') {
45
+ return c.json({ success: false, error: 'Unauthorized' }, 401);
46
+ }
47
+ if (!hasCapability(auth, 'asset.upload')) {
48
+ return c.json({ success: false, error: 'Forbidden: asset.upload capability required' }, 403);
49
+ }
50
+ // Unavailable rather than broken: an adapter that can't sign, or an
51
+ // app with no encryption key, simply doesn't offer this path, and the
52
+ // client falls back to uploading through the app. 404 keeps it from
53
+ // looking like a transient failure worth retrying.
54
+ const secret = config.security?.secretEncryptionKey;
55
+ if (!storageAdapter?.getSignedUploadUrl || !storageAdapter.resolvePath || !secret) {
56
+ return c.json({ success: false, error: 'Direct upload is not available' }, 404);
57
+ }
58
+ const { filename, mimeType, size, schemaType, fieldPath } = c.req.valid('json');
59
+ const maxBytes = resolveMaxUploadBytes(c.var.aphexCMS);
60
+ if (size > maxBytes) {
61
+ // Refused before a write grant is issued at all. The declared size
62
+ // is only a claim — the real one is checked on confirm — but there
63
+ // is no reason to hand out a URL for an upload already known to be
64
+ // too large.
65
+ return c.json({ success: false, error: `File exceeds the ${formatMegabytes(maxBytes)} limit` }, 413);
66
+ }
67
+ // The id, and therefore the key, is minted here. Accepting a
68
+ // client-supplied key would let anyone holding `asset.upload` write
69
+ // anywhere in the bucket, including over an existing asset's original.
70
+ const assetId = crypto.randomUUID();
71
+ const key = buildOriginalKey(assetId, filename, mimeType);
72
+ const path = storageAdapter.resolvePath(key);
73
+ const uploadUrl = await storageAdapter.getSignedUploadUrl(path, UPLOAD_URL_TTL_SECONDS, mimeType);
74
+ const ticket = {
75
+ assetId,
76
+ key,
77
+ originalFilename: filename,
78
+ mimeType,
79
+ organizationId: auth.organizationId,
80
+ schemaType,
81
+ fieldPath,
82
+ exp: Date.now() + TICKET_TTL_MS
83
+ };
84
+ return c.json({
85
+ success: true,
86
+ data: {
87
+ assetId,
88
+ uploadUrl,
89
+ // The browser must send the same Content-Type the URL was signed
90
+ // with, or the storage service rejects the PUT.
91
+ headers: { 'Content-Type': mimeType },
92
+ ticket: encryptSecret(JSON.stringify(ticket), secret)
93
+ }
94
+ });
95
+ }
96
+ catch (error) {
97
+ cmsLogger.error('[Asset API] Could not create upload URL:', error);
98
+ return c.json({ success: false, error: 'Could not create upload URL' }, 500);
99
+ }
100
+ })
101
+ .post('/confirm', zValidator('json', confirmUploadRequest, (result, c) => {
102
+ if (!result.success) {
103
+ return c.json({ success: false, error: 'Invalid request body', issues: result.error.issues }, 400);
104
+ }
105
+ }), async (c) => {
106
+ try {
107
+ const { assetService, config } = c.var.aphexCMS;
108
+ const auth = c.var.auth;
109
+ if (!auth || auth.type === 'partial_session') {
110
+ return c.json({ success: false, error: 'Unauthorized' }, 401);
111
+ }
112
+ if (!hasCapability(auth, 'asset.upload')) {
113
+ return c.json({ success: false, error: 'Forbidden: asset.upload capability required' }, 403);
114
+ }
115
+ const secret = config.security?.secretEncryptionKey;
116
+ if (!secret) {
117
+ return c.json({ success: false, error: 'Direct upload is not available' }, 404);
118
+ }
119
+ const body = c.req.valid('json');
120
+ const rawTicket = c.req.header('x-upload-ticket');
121
+ if (!rawTicket) {
122
+ return c.json({ success: false, error: 'Missing upload ticket' }, 400);
123
+ }
124
+ let ticket;
125
+ try {
126
+ ticket = JSON.parse(decryptSecret(rawTicket, secret));
127
+ }
128
+ catch {
129
+ // AES-GCM is authenticated, so a failure here means the ticket was
130
+ // forged or tampered with, not merely malformed.
131
+ return c.json({ success: false, error: 'Invalid upload ticket' }, 400);
132
+ }
133
+ if (!ticket.exp || ticket.exp < Date.now()) {
134
+ return c.json({ success: false, error: 'Upload ticket has expired' }, 400);
135
+ }
136
+ if (ticket.assetId !== body.assetId) {
137
+ return c.json({ success: false, error: 'Upload ticket does not match' }, 400);
138
+ }
139
+ // A ticket is bound to the organization that requested it. Without
140
+ // this, a user who switched organizations — or a stolen ticket — could
141
+ // land an asset in an organization that never authorized the upload.
142
+ if (ticket.organizationId !== auth.organizationId) {
143
+ return c.json({ success: false, error: 'Upload ticket does not match' }, 403);
144
+ }
145
+ const asset = await assetService.finalizeDirectUpload(auth.organizationId, ticket, {
146
+ maxBytes: resolveMaxUploadBytes(c.var.aphexCMS),
147
+ title: body.title,
148
+ description: body.description,
149
+ alt: body.alt,
150
+ creditLine: body.creditLine,
151
+ createdBy: auth.type === 'session' ? auth.user.id : auth.keyId
152
+ });
153
+ return c.json({ success: true, data: asset });
154
+ }
155
+ catch (error) {
156
+ const message = error instanceof Error ? error.message : 'Could not confirm upload';
157
+ cmsLogger.error('[Asset API] Could not confirm direct upload:', error);
158
+ // Verification failures are the caller's problem (nothing was
159
+ // uploaded, or it was too large), not a server fault.
160
+ const isClientFault = /not found in storage|exceeds the/i.test(message);
161
+ return c.json({ success: false, error: message }, isClientFault ? 400 : 500);
162
+ }
163
+ });
@@ -0,0 +1,4 @@
1
+ import { Hono } from 'hono';
2
+ import type { AphexEnv } from '../index.js';
3
+ export declare const assetsPosterRouter: Hono<AphexEnv>;
4
+ //# sourceMappingURL=assets-poster.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assets-poster.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-poster.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAkBzC,eAAO,MAAM,kBAAkB,EAAE,IAAI,CAAC,QAAQ,CA+G7C,CAAC"}
@@ -0,0 +1,119 @@
1
+ import { Hono } from 'hono';
2
+ import { cmsLogger } from '../../../utils/logger.js';
3
+ import { hasCapability } from '../../../types/capabilities.js';
4
+ import { buildPosterKey } from '../../../storage/keys.js';
5
+ import { validateFile } from '../../../utils/mime-detect.js';
6
+ /**
7
+ * Attach a poster frame to an existing video asset.
8
+ *
9
+ * Separate from upload because the frame is extracted in the browser *from the
10
+ * file being uploaded*, and the storage key it lives at (`{assetId}/poster.webp`)
11
+ * is derived from an id that doesn't exist until the asset row does. So the
12
+ * client uploads the video, learns the id, then posts the frame here.
13
+ *
14
+ * A poster is optional by construction — a codec the browser can't decode, or an
15
+ * upload that never went through a browser at all, simply has none. Nothing here
16
+ * should ever make a video's own upload fail.
17
+ */
18
+ /** A frame is a thumbnail. Anything larger is not a frame we produced. */
19
+ const MAX_POSTER_BYTES = 2 * 1024 * 1024;
20
+ export const assetsPosterRouter = new Hono().post('/:id/poster', async (c) => {
21
+ try {
22
+ const { assetService, storageAdapter, databaseAdapter } = c.var.aphexCMS;
23
+ const auth = c.var.auth;
24
+ if (!auth || auth.type === 'partial_session') {
25
+ return c.json({ success: false, error: 'Unauthorized' }, 401);
26
+ }
27
+ // Writing a derivative of an asset is an asset write, not a read.
28
+ if (!hasCapability(auth, 'asset.upload')) {
29
+ return c.json({ success: false, error: 'Forbidden: asset.upload required' }, 403);
30
+ }
31
+ const id = c.req.param('id');
32
+ const asset = await assetService.findAssetById(auth.organizationId, id);
33
+ if (!asset) {
34
+ return c.json({ success: false, error: 'Asset not found' }, 404);
35
+ }
36
+ // Media only. Without this the endpoint is a way to write an arbitrary
37
+ // image under any asset's key prefix.
38
+ //
39
+ // Audio is admitted alongside video because it carries a duration and no
40
+ // frame: a browser can read how long a WAV is, and that is worth storing
41
+ // even though there is nothing to look at. Such a request sends no
42
+ // poster, which is why the file below is optional.
43
+ const isVideo = asset.mimeType?.startsWith('video/') ?? false;
44
+ const isAudio = asset.mimeType?.startsWith('audio/') ?? false;
45
+ if (!isVideo && !isAudio) {
46
+ return c.json({ success: false, error: 'Asset is not video or audio' }, 400);
47
+ }
48
+ const formData = await c.req.formData();
49
+ // Duration and dimensions ride along, because the browser reads all three
50
+ // from one `loadedmetadata` and splitting them would mean decoding the
51
+ // video twice. Bounded, not trusted — 24h and 16K.
52
+ const bounded = (raw, max) => {
53
+ const value = raw == null ? NaN : Number(raw);
54
+ return Number.isFinite(value) && value > 0 && value <= max ? value : undefined;
55
+ };
56
+ const duration = bounded(formData.get('duration'), 86_400);
57
+ const width = bounded(formData.get('width'), 16_384);
58
+ const height = bounded(formData.get('height'), 16_384);
59
+ const file = formData.get('poster');
60
+ if (!(file instanceof File) && duration == null) {
61
+ return c.json({ success: false, error: 'Nothing to store' }, 400);
62
+ }
63
+ let storedPoster = false;
64
+ if (file instanceof File) {
65
+ if (!isVideo) {
66
+ return c.json({ success: false, error: 'Only video can carry a poster' }, 400);
67
+ }
68
+ if (file.size > MAX_POSTER_BYTES) {
69
+ return c.json({ success: false, error: 'Poster too large' }, 400);
70
+ }
71
+ // Sniffed, not trusted: the client says "image/webp", and a route that
72
+ // believed it would happily store anything under a name the CDN serves
73
+ // with `Content-Type: image/webp`.
74
+ const buffer = Buffer.from(await file.arrayBuffer());
75
+ const validation = validateFile(buffer, file.name, file.type, {
76
+ allowedMimeTypes: ['image/webp', 'image/jpeg', 'image/png'],
77
+ maxSize: MAX_POSTER_BYTES
78
+ });
79
+ if (!validation.valid) {
80
+ return c.json({ success: false, error: validation.error }, 400);
81
+ }
82
+ await storageAdapter.store({
83
+ buffer,
84
+ filename: 'poster.webp',
85
+ mimeType: 'image/webp',
86
+ size: buffer.length,
87
+ key: buildPosterKey(asset.id)
88
+ });
89
+ storedPoster = true;
90
+ }
91
+ // Recorded so a client knows a poster exists without probing for a 404.
92
+ // Written through the database adapter rather than
93
+ // `assetService.updateAssetMetadata`, which covers only the editorial
94
+ // fields (title/alt/description) and has no `metadata` argument.
95
+ //
96
+ // The whole JSON object is rewritten because it is one column, so the
97
+ // current value has to be merged onto — sending a fragment would drop
98
+ // whatever the upload path recorded (dimensions, privacy fields).
99
+ await databaseAdapter.updateAsset(auth.organizationId, asset.id, {
100
+ // `??` not `||`: a caller that sends no duration must not erase one
101
+ // recorded at upload.
102
+ width: width ?? asset.width ?? undefined,
103
+ height: height ?? asset.height ?? undefined,
104
+ metadata: {
105
+ ...(asset.metadata ?? {}),
106
+ // Only claimed when a frame was actually written — an audio asset
107
+ // records a duration and no poster, and a flag set regardless would
108
+ // point the grid at a URL that 404s.
109
+ poster: storedPoster || asset.metadata?.poster === true,
110
+ duration: duration ?? asset.metadata?.duration
111
+ }
112
+ });
113
+ return c.json({ success: true });
114
+ }
115
+ catch (error) {
116
+ cmsLogger.error('Failed to attach poster:', error);
117
+ return c.json({ success: false, error: 'Failed to attach poster' }, 500);
118
+ }
119
+ });
@@ -1 +1 @@
1
- {"version":3,"file":"assets-references.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-references.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAI5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,sBAAsB,EAAE,IAAI,CAAC,QAAQ,CAsFhD,CAAC"}
1
+ {"version":3,"file":"assets-references.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-references.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,sBAAsB,EAAE,IAAI,CAAC,QAAQ,CAuJhD,CAAC"}