webspresso 0.0.108 → 0.0.110

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -3
  3. package/bin/commands/add-esbuild.js +7 -3
  4. package/bin/commands/add-tailwind.js +9 -5
  5. package/bin/commands/build.js +20 -4
  6. package/bin/commands/dev.js +57 -7
  7. package/bin/commands/doctor.js +42 -1
  8. package/bin/commands/favicon-generate.js +10 -3
  9. package/bin/commands/new.js +8 -3
  10. package/bin/commands/start.js +3 -1
  11. package/bin/utils/add-command.js +16 -0
  12. package/core/app.js +45 -3
  13. package/core/auth/authenticate.js +3 -3
  14. package/core/auth/hash.js +167 -43
  15. package/core/auth/index.js +13 -1
  16. package/core/auth/jwt.js +21 -2
  17. package/core/auth/manager.js +63 -14
  18. package/core/auth/middleware.js +4 -2
  19. package/core/auth/oauth.js +5 -1
  20. package/core/auth/tokens.js +7 -2
  21. package/core/auth/totp.js +42 -6
  22. package/core/auth/user-agent.js +2 -0
  23. package/core/client/adapter/datastar.js +1401 -0
  24. package/core/client/api.js +1337 -0
  25. package/core/client/controller.js +1706 -0
  26. package/core/client/debug.js +367 -0
  27. package/core/client/devtool.js +1134 -0
  28. package/core/client/forms.js +1164 -0
  29. package/core/client/fragments.js +894 -0
  30. package/core/client/index.d.ts +59 -0
  31. package/core/client/index.js +391 -0
  32. package/core/client/lite.js +175 -0
  33. package/core/client/server-fragments.js +868 -0
  34. package/core/client/storage.js +339 -0
  35. package/core/client/utils.js +281 -0
  36. package/core/compression/middleware.js +277 -26
  37. package/core/context/app-context.js +25 -3
  38. package/core/context/request.js +32 -4
  39. package/core/errors/middleware.js +14 -0
  40. package/core/events/dispatcher.js +33 -0
  41. package/core/forms/flash.js +136 -102
  42. package/core/health/middleware.js +36 -6
  43. package/core/http/pipeline.js +45 -6
  44. package/core/index.js +25 -7
  45. package/core/kernel/view.js +41 -10
  46. package/core/metrics/middleware.js +30 -6
  47. package/core/metrics/registry.js +13 -5
  48. package/core/orm/cache/fingerprint.js +32 -11
  49. package/core/orm/cache/layer.js +19 -2
  50. package/core/orm/hidden.js +145 -0
  51. package/core/orm/model.js +48 -2
  52. package/core/orm/query-builder.js +343 -6
  53. package/core/orm/query-filters.js +14 -2
  54. package/core/orm/repository.js +64 -13
  55. package/core/orm/schema-helpers.js +9 -6
  56. package/core/orm/transaction.js +50 -6
  57. package/core/orm/types.js +4 -0
  58. package/core/queue/adapters/database.js +184 -2
  59. package/core/queue/adapters/memory.js +153 -5
  60. package/core/queue/adapters/redis.js +59 -4
  61. package/core/queue/job.js +14 -1
  62. package/core/queue/manager.js +115 -0
  63. package/core/resilience/circuit-breaker.js +27 -8
  64. package/core/services/builtins/exchange.js +174 -7
  65. package/core/services/builtins/file-manager.js +36 -0
  66. package/core/services/builtins/mail.js +27 -0
  67. package/core/services/builtins/queue.js +144 -0
  68. package/core/services/builtins/security.js +118 -0
  69. package/core/services/builtins/webhook.js +110 -0
  70. package/core/services/executor.js +38 -16
  71. package/core/services/index.js +4 -1
  72. package/core/sse/stream.js +28 -5
  73. package/core/utils/timeout.js +8 -1
  74. package/core/validation/compiler.js +10 -7
  75. package/index.d.ts +1320 -74
  76. package/index.js +128 -8
  77. package/package.json +75 -27
  78. package/plugins/admin-panel/client/parts/08-record-list.js +717 -70
  79. package/plugins/admin-panel/index.js +19 -8
  80. package/plugins/csrf/index.js +3 -3
  81. package/plugins/data-exchange/export.js +214 -0
  82. package/plugins/data-exchange/import.js +48 -5
  83. package/plugins/data-exchange/index.js +70 -28
  84. package/plugins/data-exchange/preview.js +266 -0
  85. package/plugins/data-exchange/template.js +242 -0
  86. package/plugins/email/admin-component.js +783 -141
  87. package/plugins/email/api-handlers.js +51 -1
  88. package/plugins/email/index.js +5 -0
  89. package/plugins/email/service.js +48 -0
  90. package/plugins/file-manager/admin-component.js +1546 -70
  91. package/plugins/file-manager/api-handlers.js +166 -1
  92. package/plugins/file-manager/core.js +598 -8
  93. package/plugins/file-manager/index.js +8 -0
  94. package/plugins/index.js +7 -0
  95. package/plugins/mcp/auth.js +3 -3
  96. package/plugins/oauth/index.js +36 -3
  97. package/plugins/queue/admin-component.js +1092 -0
  98. package/plugins/queue/api-handlers.js +248 -0
  99. package/plugins/queue/index.js +69 -0
  100. package/plugins/rest-resources/index.js +7 -2
  101. package/plugins/security/admin-component.js +689 -0
  102. package/plugins/security/api-handlers.js +169 -0
  103. package/plugins/security/audit.js +153 -0
  104. package/plugins/security/bruteforce.js +244 -0
  105. package/plugins/security/firewall.js +459 -0
  106. package/plugins/security/headers.js +214 -0
  107. package/plugins/security/honeypot.js +234 -0
  108. package/plugins/security/incident-recorder.js +137 -0
  109. package/plugins/security/index.js +211 -0
  110. package/plugins/seo-checker/analyzer.js +20 -7
  111. package/plugins/upload/index.js +36 -0
  112. package/plugins/webhooks/admin-component.js +702 -175
  113. package/plugins/webhooks/api-handlers.js +75 -1
  114. package/plugins/webhooks/dispatcher.js +290 -11
  115. package/plugins/webhooks/index.js +37 -2
  116. package/plugins/webhooks/sender.js +56 -0
  117. package/plugins/xlsx/engine.js +19 -4
  118. package/src/api/api-loader.js +19 -1
  119. package/src/bundle/index.js +443 -17
  120. package/src/client-runtime/bootstrap-swup.js +9 -0
  121. package/src/client-runtime/mount.js +15 -20
  122. package/src/client-runtime/resolve.js +3 -2
  123. package/src/dev/api-typegen.js +1300 -0
  124. package/src/dev/banner.js +10 -1
  125. package/src/dev/colors.js +1 -1
  126. package/src/dev/index.js +7 -1
  127. package/src/dev/typegen.js +173 -17
  128. package/src/dev-reload/index.js +1 -1
  129. package/src/discovery/file-route-parser.js +17 -3
  130. package/src/discovery/scan-routes.js +4 -1
  131. package/src/file-router.js +253 -69
  132. package/src/helpers.js +46 -26
  133. package/src/njk-frontmatter.js +30 -4
  134. package/src/routing/cascading.js +26 -8
  135. package/src/routing/mount-discovered-routes.js +76 -0
  136. package/src/server.js +231 -70
  137. package/views/partials/webspresso-client-runtime.njk +1 -9
  138. package/.agents/ADMIN.md +0 -426
  139. package/.agents/AGENTS.md +0 -96
  140. package/.agents/ARCHITECTURE.md +0 -163
  141. package/.agents/AUTH.md +0 -581
  142. package/.agents/CACHE.md +0 -148
  143. package/.agents/CLI.md +0 -649
  144. package/.agents/COMPRESSION.md +0 -59
  145. package/.agents/CONTEXT.md +0 -152
  146. package/.agents/CONVENTIONS.md +0 -50
  147. package/.agents/EARLY_HINTS.md +0 -120
  148. package/.agents/EMAIL.md +0 -223
  149. package/.agents/ERRORS.md +0 -260
  150. package/.agents/EVENTS.md +0 -179
  151. package/.agents/FLAGS.md +0 -118
  152. package/.agents/HEALTH.md +0 -118
  153. package/.agents/LIMITS.md +0 -109
  154. package/.agents/LOGGING.md +0 -93
  155. package/.agents/MCP.md +0 -103
  156. package/.agents/METRICS.md +0 -127
  157. package/.agents/MIGRATION_JOBS.md +0 -95
  158. package/.agents/ORM.md +0 -700
  159. package/.agents/PLUGINS.md +0 -729
  160. package/.agents/QUEUE.md +0 -290
  161. package/.agents/RATE_LIMIT.md +0 -147
  162. package/.agents/REALTIME.md +0 -213
  163. package/.agents/RESILIENCE.md +0 -235
  164. package/.agents/ROUTING.md +0 -605
  165. package/.agents/SCALE_OUT.md +0 -109
  166. package/.agents/SECRETS.md +0 -117
  167. package/.agents/SERVICES.md +0 -341
  168. package/.agents/SHUTDOWN.md +0 -74
  169. package/.agents/STREAMING.md +0 -108
  170. package/.agents/WORKFLOW.md +0 -27
  171. package/.agents/internal/DOCUMENTATION_REVIEW.md +0 -485
  172. package/.agents/internal/TECHNICAL_REVIEW.md +0 -428
  173. package/.agents/skills/webspresso-admin-and-plugins/SKILL.md +0 -122
  174. package/.agents/skills/webspresso-framework/SKILL.md +0 -89
  175. package/.agents/skills/webspresso-orm-and-database/SKILL.md +0 -127
  176. package/.agents/skills/webspresso-routing-and-api/SKILL.md +0 -130
  177. package/.agents/skills/webspresso-services/SKILL.md +0 -134
  178. package/.cursorrules +0 -14
  179. package/AGENTS.md +0 -203
  180. package/CLAUDE.md +0 -54
  181. package/core/kernel/run-demo.js +0 -58
  182. package/plugins/admin-panel/styles.js +0 -9
  183. package/plugins/data-exchange/export-xlsx.js +0 -119
  184. package/src/client-runtime/bootstrap-alpine-swup.js +0 -34
@@ -5,6 +5,7 @@
5
5
 
6
6
  const fs = require('fs/promises');
7
7
  const path = require('path');
8
+ const zlib = require('zlib');
8
9
  const { randomBytes } = require('crypto');
9
10
  const { ValidationError, SecurityError, NotFoundError } = require('../../core/errors');
10
11
  const { normalizePublicBase, canonicalExtFromMime } = require('../upload/local-file-provider');
@@ -504,23 +505,44 @@ function invalidateStorageCache(baseDir) {
504
505
  }
505
506
  }
506
507
 
508
+ function formatBytes(bytes) {
509
+ if (bytes === 0 || !bytes) return '0 B';
510
+ const k = 1024;
511
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
512
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
513
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
514
+ }
515
+
507
516
  /**
508
- * Calculate total disk usage in bytes under baseDir
517
+ * Detailed storage statistics including category breakdown and quota
509
518
  * @param {string} baseDir
510
519
  * @param {Object} [options]
511
520
  * @param {boolean} [options.forceRefresh=false]
512
- * @returns {Promise<number>}
521
+ * @param {number|null} [options.maxTotalStorageBytes]
522
+ * @returns {Promise<Object>}
513
523
  */
514
- async function calculateStorageUsage(baseDir, options = {}) {
524
+ async function getDetailedStorageStats(baseDir, options = {}) {
515
525
  const resolvedBase = path.resolve(baseDir);
516
526
  const now = Date.now();
517
527
  const cached = storageCache.get(resolvedBase);
518
528
 
519
- if (!options.forceRefresh && cached && (now - cached.timestamp) < STORAGE_CACHE_TTL) {
520
- return cached.bytes;
529
+ if (!options.forceRefresh && cached && cached.stats && (now - cached.timestamp) < STORAGE_CACHE_TTL) {
530
+ return applyQuota(cached.stats, options.maxTotalStorageBytes);
521
531
  }
522
532
 
523
533
  let totalBytes = 0;
534
+ let fileCount = 0;
535
+ let folderCount = 0;
536
+
537
+ const categories = {
538
+ images: { count: 0, bytes: 0, percent: 0, label: 'Images', color: '#10b981', formattedBytes: '0 B' },
539
+ documents: { count: 0, bytes: 0, percent: 0, label: 'Documents', color: '#6366f1', formattedBytes: '0 B' },
540
+ code: { count: 0, bytes: 0, percent: 0, label: 'Code & Text', color: '#f59e0b', formattedBytes: '0 B' },
541
+ media: { count: 0, bytes: 0, percent: 0, label: 'Video & Audio', color: '#ec4899', formattedBytes: '0 B' },
542
+ archives: { count: 0, bytes: 0, percent: 0, label: 'Archives', color: '#8b5cf6', formattedBytes: '0 B' },
543
+ other: { count: 0, bytes: 0, percent: 0, label: 'Other', color: '#94a3b8', formattedBytes: '0 B' },
544
+ };
545
+
524
546
  async function scan(dir) {
525
547
  try {
526
548
  const entries = await fs.readdir(dir, { withFileTypes: true });
@@ -528,17 +550,92 @@ async function calculateStorageUsage(baseDir, options = {}) {
528
550
  if (entry.name.startsWith('.')) continue;
529
551
  const full = path.join(dir, entry.name);
530
552
  if (entry.isDirectory()) {
553
+ folderCount++;
531
554
  await scan(full);
532
555
  } else if (entry.isFile()) {
556
+ fileCount++;
533
557
  const st = await fs.stat(full);
534
- totalBytes += st.size;
558
+ const size = st.size;
559
+ totalBytes += size;
560
+
561
+ const ext = (path.extname(entry.name) || '').toLowerCase().replace(/^\./, '');
562
+ const catType = EXTENSION_CATEGORIES[ext] || 'other';
563
+
564
+ if (catType === 'image') {
565
+ categories.images.count++;
566
+ categories.images.bytes += size;
567
+ } else if (catType === 'document') {
568
+ categories.documents.count++;
569
+ categories.documents.bytes += size;
570
+ } else if (catType === 'text' || catType === 'code') {
571
+ categories.code.count++;
572
+ categories.code.bytes += size;
573
+ } else if (catType === 'video' || catType === 'audio') {
574
+ categories.media.count++;
575
+ categories.media.bytes += size;
576
+ } else if (catType === 'archive') {
577
+ categories.archives.count++;
578
+ categories.archives.bytes += size;
579
+ } else {
580
+ categories.other.count++;
581
+ categories.other.bytes += size;
582
+ }
535
583
  }
536
584
  }
537
585
  } catch (e) {}
538
586
  }
587
+
539
588
  await scan(resolvedBase);
540
- storageCache.set(resolvedBase, { bytes: totalBytes, timestamp: now });
541
- return totalBytes;
589
+
590
+ // Compute category percentages and format strings
591
+ if (totalBytes > 0) {
592
+ for (const key of Object.keys(categories)) {
593
+ categories[key].percent = Math.round((categories[key].bytes / totalBytes) * 1000) / 10;
594
+ categories[key].formattedBytes = formatBytes(categories[key].bytes);
595
+ }
596
+ }
597
+
598
+ const rawStats = {
599
+ totalBytes,
600
+ fileCount,
601
+ folderCount,
602
+ categories,
603
+ formattedTotal: formatBytes(totalBytes),
604
+ };
605
+
606
+ storageCache.set(resolvedBase, { bytes: totalBytes, stats: rawStats, timestamp: now });
607
+ return applyQuota(rawStats, options.maxTotalStorageBytes);
608
+ }
609
+
610
+ function applyQuota(stats, quotaBytes) {
611
+ const quota = typeof quotaBytes === 'number' && quotaBytes > 0 ? quotaBytes : (1024 * 1024 * 1024); // 1 GB default quota
612
+ const hasCustomQuota = typeof quotaBytes === 'number' && quotaBytes > 0;
613
+ const usagePercent = quota > 0 ? Math.min(100, Math.round((stats.totalBytes / quota) * 1000) / 10) : 0;
614
+ const freeBytes = Math.max(0, quota - stats.totalBytes);
615
+
616
+ return {
617
+ ...stats,
618
+ quotaBytes: quota,
619
+ hasCustomQuota,
620
+ freeBytes,
621
+ formattedFree: formatBytes(freeBytes),
622
+ formattedQuota: formatBytes(quota),
623
+ usagePercent,
624
+ isNearLimit: usagePercent >= 80,
625
+ isOverLimit: stats.totalBytes >= quota,
626
+ };
627
+ }
628
+
629
+ /**
630
+ * Calculate total disk usage in bytes under baseDir
631
+ * @param {string} baseDir
632
+ * @param {Object} [options]
633
+ * @param {boolean} [options.forceRefresh=false]
634
+ * @returns {Promise<number>}
635
+ */
636
+ async function calculateStorageUsage(baseDir, options = {}) {
637
+ const stats = await getDetailedStorageStats(baseDir, options);
638
+ return stats.totalBytes;
542
639
  }
543
640
 
544
641
  /**
@@ -614,11 +711,493 @@ async function saveUploadedFile(baseDir, targetDirRelPath, buffer, originalName,
614
711
  };
615
712
  }
616
713
 
714
+ /**
715
+ * Save an edited image (from data URL or buffer)
716
+ * @param {string} baseDir - Base root directory
717
+ * @param {string} itemPath - Relative file path of the image
718
+ * @param {string|Buffer} data - Base64 Data URL or raw Buffer
719
+ * @param {Object} [options] - Options: overwrite, newName, publicBasePath
720
+ * @returns {Promise<Object>}
721
+ */
722
+ async function saveEditedImage(baseDir, itemPath, data, options = {}) {
723
+ const { overwrite = false, newName, publicBasePath = '' } = options;
724
+ const currentPath = resolveSafePath(baseDir, itemPath);
725
+
726
+ let buffer;
727
+ let mimeType = '';
728
+ if (typeof data === 'string') {
729
+ const match = data.match(/^data:([^;]+);base64,(.+)$/);
730
+ if (match) {
731
+ mimeType = match[1];
732
+ buffer = Buffer.from(match[2], 'base64');
733
+ } else {
734
+ buffer = Buffer.from(data, 'base64');
735
+ }
736
+ } else if (Buffer.isBuffer(data)) {
737
+ buffer = data;
738
+ } else {
739
+ throw new ValidationError('Invalid image data provided');
740
+ }
741
+
742
+ const dir = path.dirname(currentPath);
743
+ const origExt = path.extname(currentPath);
744
+ const baseName = path.basename(currentPath, origExt);
745
+
746
+ let finalTarget;
747
+ let finalFileName;
748
+
749
+ if (overwrite) {
750
+ finalTarget = currentPath;
751
+ finalFileName = path.basename(currentPath);
752
+ } else {
753
+ const ext = mimeType === 'image/webp' ? '.webp' : (mimeType === 'image/jpeg' ? '.jpg' : (mimeType === 'image/png' ? '.png' : origExt));
754
+ const targetName = newName ? sanitizeName(newName) : `${baseName}-edited${ext}`;
755
+ finalFileName = targetName;
756
+ finalTarget = path.join(dir, targetName);
757
+
758
+ try {
759
+ await fs.access(finalTarget);
760
+ finalFileName = `${baseName}-edited-${Date.now()}${ext}`;
761
+ finalTarget = path.join(dir, finalFileName);
762
+ } catch {}
763
+ }
764
+
765
+ resolveSafePath(baseDir, path.relative(baseDir, finalTarget));
766
+
767
+ await fs.writeFile(finalTarget, buffer);
768
+ invalidateStorageCache(baseDir);
769
+
770
+ const relFilePath = path.relative(path.resolve(baseDir), finalTarget).replace(/\\/g, '/');
771
+ const publicBase = normalizePublicBase(publicBasePath);
772
+ const publicUrl = `${publicBase}/${relFilePath}`.replace(/\/{2,}/g, '/');
773
+ const ext = path.extname(finalFileName).replace(/^\./, '').toLowerCase();
774
+
775
+ return {
776
+ name: finalFileName,
777
+ path: relFilePath,
778
+ publicUrl,
779
+ size: buffer.length,
780
+ mimeType: mimeType || getMimeType(ext),
781
+ ext,
782
+ type: 'image',
783
+ };
784
+ }
785
+
786
+ const TEXT_EXTENSIONS = new Set([
787
+ 'txt', 'csv', 'md', 'markdown', 'json', 'xml', 'html', 'htm',
788
+ 'css', 'scss', 'sass', 'less', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx',
789
+ 'sql', 'yaml', 'yml', 'env', 'sh', 'bash', 'log', 'ini', 'toml',
790
+ 'svg', 'gitignore', 'conf', 'config',
791
+ ]);
792
+
793
+ /**
794
+ * Check if a file extension is eligible for text/code editing
795
+ * @param {string} ext
796
+ * @returns {boolean}
797
+ */
798
+ function isTextEditable(ext) {
799
+ if (!ext) return false;
800
+ const cleanExt = ext.replace(/^\./, '').toLowerCase();
801
+ return TEXT_EXTENSIONS.has(cleanExt);
802
+ }
803
+
804
+ /**
805
+ * Safely read a text/configuration file's content
806
+ * @param {string} baseDir
807
+ * @param {string} itemPath
808
+ * @param {Object} [options]
809
+ * @param {number} [options.maxTextBytes=5242880] (5MB default)
810
+ * @returns {Promise<Object>}
811
+ */
812
+ async function getFileContent(baseDir, itemPath, options = {}) {
813
+ const target = resolveSafePath(baseDir, itemPath);
814
+ const maxBytes = options.maxTextBytes || 5 * 1024 * 1024;
815
+
816
+ let stat;
817
+ try {
818
+ stat = await fs.stat(target);
819
+ } catch (err) {
820
+ if (err.code === 'ENOENT') {
821
+ throw new NotFoundError(`File not found: ${itemPath}`);
822
+ }
823
+ throw err;
824
+ }
825
+
826
+ if (!stat.isFile()) {
827
+ throw new ValidationError('Target is not a regular file');
828
+ }
829
+
830
+ if (stat.size > maxBytes) {
831
+ throw new ValidationError(`File is too large to open in editor (${(stat.size / 1024 / 1024).toFixed(2)} MB, max ${maxBytes / 1024 / 1024} MB)`);
832
+ }
833
+
834
+ const ext = path.extname(target).replace(/^\./, '').toLowerCase();
835
+
836
+ // Read buffer and check for null bytes if not an explicitly known text extension
837
+ const buffer = await fs.readFile(target);
838
+ if (!isTextEditable(ext)) {
839
+ const checkLength = Math.min(buffer.length, 512);
840
+ for (let i = 0; i < checkLength; i++) {
841
+ if (buffer[i] === 0) {
842
+ throw new ValidationError('File appears to be binary and cannot be edited as text');
843
+ }
844
+ }
845
+ }
846
+
847
+ const content = buffer.toString('utf8');
848
+ const fileName = path.basename(target);
849
+ const relFilePath = path.relative(path.resolve(baseDir), target).replace(/\\/g, '/');
850
+
851
+ return {
852
+ name: fileName,
853
+ path: relFilePath,
854
+ content,
855
+ size: stat.size,
856
+ ext,
857
+ mimeType: getMimeType(ext),
858
+ modifiedAt: stat.mtime.toISOString(),
859
+ };
860
+ }
861
+
862
+ /**
863
+ * Safely save updated text content to file
864
+ * @param {string} baseDir
865
+ * @param {string} itemPath
866
+ * @param {string} content
867
+ * @param {Object} [options]
868
+ * @param {boolean} [options.overwrite=true]
869
+ * @param {string} [options.newName]
870
+ * @param {string} [options.publicBasePath='/uploads']
871
+ * @returns {Promise<Object>}
872
+ */
873
+ async function saveFileContent(baseDir, itemPath, content, options = {}) {
874
+ if (typeof content !== 'string') {
875
+ throw new ValidationError('Content must be a string');
876
+ }
877
+
878
+ const target = resolveSafePath(baseDir, itemPath);
879
+ const { overwrite = true, newName, publicBasePath = '/uploads' } = options;
880
+
881
+ let stat;
882
+ try {
883
+ stat = await fs.stat(target);
884
+ } catch (err) {
885
+ if (err.code === 'ENOENT') {
886
+ await fs.mkdir(path.dirname(target), { recursive: true });
887
+ } else {
888
+ throw err;
889
+ }
890
+ }
891
+
892
+ if (stat && !stat.isFile()) {
893
+ throw new ValidationError('Target path exists but is not a regular file');
894
+ }
895
+
896
+ const originalExt = path.extname(target).replace(/^\./, '').toLowerCase();
897
+ let contentToSave = content;
898
+ if (originalExt === 'svg') {
899
+ contentToSave = sanitizeSvgContent(contentToSave);
900
+ }
901
+
902
+ let finalTarget = target;
903
+ let finalFileName = path.basename(target);
904
+
905
+ if (newName) {
906
+ const cleanNewName = sanitizeName(newName);
907
+ finalFileName = cleanNewName;
908
+ finalTarget = path.join(path.dirname(target), cleanNewName);
909
+ } else if (!overwrite) {
910
+ const dir = path.dirname(target);
911
+ const extWithDot = path.extname(target);
912
+ const baseNameWithoutExt = path.basename(target, extWithDot);
913
+
914
+ let candidateName = `${baseNameWithoutExt}-copy${extWithDot}`;
915
+ let candidatePath = path.join(dir, candidateName);
916
+ let counter = 1;
917
+
918
+ while (true) {
919
+ try {
920
+ await fs.access(candidatePath);
921
+ candidateName = `${baseNameWithoutExt}-copy-${counter}${extWithDot}`;
922
+ candidatePath = path.join(dir, candidateName);
923
+ counter++;
924
+ } catch {
925
+ break;
926
+ }
927
+ }
928
+
929
+ finalTarget = candidatePath;
930
+ finalFileName = candidateName;
931
+ }
932
+
933
+ const buffer = Buffer.from(contentToSave, 'utf8');
934
+ await fs.writeFile(finalTarget, buffer);
935
+ invalidateStorageCache(baseDir);
936
+
937
+ const relFilePath = path.relative(path.resolve(baseDir), finalTarget).replace(/\\/g, '/');
938
+ const publicBase = normalizePublicBase(publicBasePath);
939
+ const publicUrl = `${publicBase}/${relFilePath}`.replace(/\/{2,}/g, '/');
940
+ const ext = path.extname(finalFileName).replace(/^\./, '').toLowerCase();
941
+
942
+ return {
943
+ name: finalFileName,
944
+ path: relFilePath,
945
+ publicUrl,
946
+ size: buffer.length,
947
+ mimeType: getMimeType(ext),
948
+ ext,
949
+ type: getFileType(finalFileName, false),
950
+ };
951
+ }
952
+
953
+ /**
954
+ * Standard IEEE 802.3 CRC32 calculation for ZIP local file headers
955
+ * @param {Buffer} buf
956
+ * @returns {number}
957
+ */
958
+ function crc32(buf) {
959
+ let crc = -1;
960
+ for (let i = 0; i < buf.length; i++) {
961
+ crc ^= buf[i];
962
+ for (let j = 0; j < 8; j++) {
963
+ crc = (crc >>> 1) ^ (crc & 1 ? 0xEDB88320 : 0);
964
+ }
965
+ }
966
+ return (crc ^ -1) >>> 0;
967
+ }
968
+
969
+ /**
970
+ * Native PKWARE ZIP archive builder using Buffer and zlib.deflateRawSync
971
+ * @param {Array<{ path: string, data: Buffer|string }>} entries
972
+ * @returns {Buffer}
973
+ */
974
+ function createZip(entries) {
975
+ const localHeaders = [];
976
+ const centralHeaders = [];
977
+ let offset = 0;
978
+
979
+ for (const entry of entries) {
980
+ const cleanRelPath = (entry.path || '').replace(/\\/g, '/').replace(/^\/+/, '');
981
+ const nameBuf = Buffer.from(cleanRelPath, 'utf8');
982
+ const uncompressedData = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data || '', 'utf8');
983
+ const compressedData = zlib.deflateRawSync(uncompressedData);
984
+ const checksum = crc32(uncompressedData);
985
+
986
+ const localHeader = Buffer.alloc(30 + nameBuf.length);
987
+ localHeader.writeUInt32LE(0x04034b50, 0); // Local header signature
988
+ localHeader.writeUInt16LE(20, 4); // Min version (2.0)
989
+ localHeader.writeUInt16LE(0, 6); // General flags
990
+ localHeader.writeUInt16LE(8, 8); // Compression method: 8 (Deflate)
991
+ localHeader.writeUInt16LE(0, 10); // Mod time
992
+ localHeader.writeUInt16LE(0, 12); // Mod date
993
+ localHeader.writeUInt32LE(checksum, 14); // CRC-32
994
+ localHeader.writeUInt32LE(compressedData.length, 18); // Compressed size
995
+ localHeader.writeUInt32LE(uncompressedData.length, 22); // Uncompressed size
996
+ localHeader.writeUInt16LE(nameBuf.length, 26); // Filename length
997
+ localHeader.writeUInt16LE(0, 28); // Extra field length
998
+ nameBuf.copy(localHeader, 30);
999
+
1000
+ const centralHeader = Buffer.alloc(46 + nameBuf.length);
1001
+ centralHeader.writeUInt32LE(0x02014b50, 0); // Central directory signature
1002
+ centralHeader.writeUInt16LE(20, 4); // Version made by
1003
+ centralHeader.writeUInt16LE(20, 6); // Min version to extract
1004
+ centralHeader.writeUInt16LE(0, 8); // Flags
1005
+ centralHeader.writeUInt16LE(8, 10); // Compression method: Deflate
1006
+ centralHeader.writeUInt16LE(0, 12); // Mod time
1007
+ centralHeader.writeUInt16LE(0, 14); // Mod date
1008
+ centralHeader.writeUInt32LE(checksum, 16); // CRC-32
1009
+ centralHeader.writeUInt32LE(compressedData.length, 20); // Compressed size
1010
+ centralHeader.writeUInt32LE(uncompressedData.length, 24); // Uncompressed size
1011
+ centralHeader.writeUInt16LE(nameBuf.length, 28); // Filename length
1012
+ centralHeader.writeUInt16LE(0, 30); // Extra field length
1013
+ centralHeader.writeUInt16LE(0, 32); // File comment length
1014
+ centralHeader.writeUInt16LE(0, 34); // Disk number start
1015
+ centralHeader.writeUInt16LE(0, 36); // Internal file attributes
1016
+ centralHeader.writeUInt32LE(0, 38); // External file attributes
1017
+ centralHeader.writeUInt32LE(offset, 42); // Local header relative offset
1018
+ nameBuf.copy(centralHeader, 46);
1019
+
1020
+ localHeaders.push(localHeader, compressedData);
1021
+ centralHeaders.push(centralHeader);
1022
+ offset += localHeader.length + compressedData.length;
1023
+ }
1024
+
1025
+ const centralDirSize = centralHeaders.reduce((sum, h) => sum + h.length, 0);
1026
+ const endRecord = Buffer.alloc(22);
1027
+ endRecord.writeUInt32LE(0x06054b50, 0); // End of central directory signature
1028
+ endRecord.writeUInt16LE(0, 4); // Number of this disk
1029
+ endRecord.writeUInt16LE(0, 6); // Disk with start of central directory
1030
+ endRecord.writeUInt16LE(entries.length, 8); // Number of entries on disk
1031
+ endRecord.writeUInt16LE(entries.length, 10); // Total number of entries
1032
+ endRecord.writeUInt32LE(centralDirSize, 12); // Central directory size in bytes
1033
+ endRecord.writeUInt32LE(offset, 16); // Central directory offset
1034
+ endRecord.writeUInt16LE(0, 20); // ZIP comment length
1035
+
1036
+ return Buffer.concat([...localHeaders, ...centralHeaders, endRecord]);
1037
+ }
1038
+
1039
+ /**
1040
+ * Recursively collect files into zip entries
1041
+ * @param {string} baseDir
1042
+ * @param {string} targetFullPath
1043
+ * @param {string} baseRel
1044
+ * @returns {Promise<Array<{ path: string, data: Buffer }>>}
1045
+ */
1046
+ async function collectFilesForZip(baseDir, targetFullPath, baseRel = '') {
1047
+ const stat = await fs.stat(targetFullPath);
1048
+ const entries = [];
1049
+ if (stat.isDirectory()) {
1050
+ const items = await fs.readdir(targetFullPath, { withFileTypes: true });
1051
+ for (const item of items) {
1052
+ const childFullPath = path.join(targetFullPath, item.name);
1053
+ const childRelPath = baseRel ? `${baseRel}/${item.name}` : item.name;
1054
+ const childEntries = await collectFilesForZip(baseDir, childFullPath, childRelPath);
1055
+ entries.push(...childEntries);
1056
+ }
1057
+ } else {
1058
+ const data = await fs.readFile(targetFullPath);
1059
+ entries.push({ path: baseRel, data });
1060
+ }
1061
+ return entries;
1062
+ }
1063
+
1064
+ /**
1065
+ * Bundle multiple files and folders into a ZIP archive buffer
1066
+ * @param {string} baseDir
1067
+ * @param {string[]} itemPaths
1068
+ * @returns {Promise<{ buffer: Buffer, filename: string, fileCount: number, size: number }>}
1069
+ */
1070
+ async function createZipFromPaths(baseDir, itemPaths) {
1071
+ if (!Array.isArray(itemPaths) || itemPaths.length === 0) {
1072
+ throw new ValidationError('itemPaths array is required for ZIP download');
1073
+ }
1074
+
1075
+ const allEntries = [];
1076
+ for (const itemPath of itemPaths) {
1077
+ const safePath = resolveSafePath(baseDir, itemPath);
1078
+ const itemName = path.basename(safePath);
1079
+ const entries = await collectFilesForZip(baseDir, safePath, itemName);
1080
+ allEntries.push(...entries);
1081
+ }
1082
+
1083
+ if (allEntries.length === 0) {
1084
+ throw new ValidationError('Selected items do not contain any downloadable files');
1085
+ }
1086
+
1087
+ const zipBuffer = createZip(allEntries);
1088
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
1089
+ const filename = `archive-${timestamp}.zip`;
1090
+
1091
+ return {
1092
+ buffer: zipBuffer,
1093
+ filename,
1094
+ fileCount: allEntries.length,
1095
+ size: zipBuffer.length,
1096
+ };
1097
+ }
1098
+
1099
+ /**
1100
+ * Batch delete multiple files or directories
1101
+ * @param {string} baseDir
1102
+ * @param {string[]} itemPaths
1103
+ * @returns {Promise<{ success: boolean, deleted: string[], failed: Array<{ path: string, error: string }>, count: number }>}
1104
+ */
1105
+ async function batchDelete(baseDir, itemPaths) {
1106
+ if (!Array.isArray(itemPaths) || itemPaths.length === 0) {
1107
+ throw new ValidationError('itemPaths array is required for batch delete');
1108
+ }
1109
+
1110
+ const deleted = [];
1111
+ const failed = [];
1112
+
1113
+ for (const itemPath of itemPaths) {
1114
+ try {
1115
+ const safePath = resolveSafePath(baseDir, itemPath);
1116
+ const rootResolved = path.resolve(baseDir);
1117
+ if (safePath === rootResolved) {
1118
+ throw new SecurityError('Cannot delete the root directory');
1119
+ }
1120
+ const stat = await fs.stat(safePath);
1121
+ if (stat.isDirectory()) {
1122
+ await fs.rm(safePath, { recursive: true, force: true });
1123
+ } else {
1124
+ await fs.unlink(safePath);
1125
+ }
1126
+ deleted.push(itemPath);
1127
+ } catch (err) {
1128
+ failed.push({ path: itemPath, error: err.message });
1129
+ }
1130
+ }
1131
+
1132
+ invalidateStorageCache(baseDir);
1133
+
1134
+ return {
1135
+ success: failed.length === 0,
1136
+ deleted,
1137
+ failed,
1138
+ count: deleted.length,
1139
+ };
1140
+ }
1141
+
1142
+ /**
1143
+ * Batch move multiple files or directories into a target destination directory
1144
+ * @param {string} baseDir
1145
+ * @param {string[]} itemPaths
1146
+ * @param {string} destinationRelPath
1147
+ * @returns {Promise<{ success: boolean, moved: Array<{ from: string, to: string }>, failed: Array<{ path: string, error: string }>, count: number }>}
1148
+ */
1149
+ async function batchMove(baseDir, itemPaths, destinationRelPath = '') {
1150
+ if (!Array.isArray(itemPaths) || itemPaths.length === 0) {
1151
+ throw new ValidationError('itemPaths array is required for batch move');
1152
+ }
1153
+
1154
+ const destSafeDir = resolveSafePath(baseDir, destinationRelPath);
1155
+ const destStat = await fs.stat(destSafeDir);
1156
+ if (!destStat.isDirectory()) {
1157
+ throw new ValidationError('Destination must be an existing directory');
1158
+ }
1159
+
1160
+ const moved = [];
1161
+ const failed = [];
1162
+
1163
+ for (const itemPath of itemPaths) {
1164
+ try {
1165
+ const safeSrc = resolveSafePath(baseDir, itemPath);
1166
+ const rootResolved = path.resolve(baseDir);
1167
+ if (safeSrc === rootResolved) {
1168
+ throw new SecurityError('Cannot move root directory');
1169
+ }
1170
+ const itemName = path.basename(safeSrc);
1171
+ const safeDest = path.join(destSafeDir, itemName);
1172
+
1173
+ if (safeDest.startsWith(safeSrc + path.sep)) {
1174
+ throw new ValidationError('Cannot move a directory into its own subdirectory');
1175
+ }
1176
+
1177
+ await fs.rename(safeSrc, safeDest);
1178
+ const newRelPath = path.relative(path.resolve(baseDir), safeDest).replace(/\\/g, '/');
1179
+ moved.push({ from: itemPath, to: newRelPath });
1180
+ } catch (err) {
1181
+ failed.push({ path: itemPath, error: err.message });
1182
+ }
1183
+ }
1184
+
1185
+ invalidateStorageCache(baseDir);
1186
+
1187
+ return {
1188
+ success: failed.length === 0,
1189
+ moved,
1190
+ failed,
1191
+ count: moved.length,
1192
+ };
1193
+ }
1194
+
617
1195
  module.exports = {
618
1196
  resolveSafePath,
619
1197
  sanitizeName,
620
1198
  getFileType,
621
1199
  getMimeType,
1200
+ isTextEditable,
622
1201
  buildBreadcrumbs,
623
1202
  listFiles,
624
1203
  createDirectory,
@@ -626,6 +1205,17 @@ module.exports = {
626
1205
  deleteItem,
627
1206
  moveItem,
628
1207
  saveUploadedFile,
1208
+ saveEditedImage,
1209
+ getFileContent,
1210
+ saveFileContent,
629
1211
  calculateStorageUsage,
1212
+ getDetailedStorageStats,
1213
+ formatBytes,
630
1214
  invalidateStorageCache,
1215
+ crc32,
1216
+ createZip,
1217
+ createZipFromPaths,
1218
+ batchDelete,
1219
+ batchMove,
631
1220
  };
1221
+
@@ -158,6 +158,14 @@ function fileManagerPlugin(options = {}) {
158
158
  { method: 'post', path: '/move', handler: handlers.move },
159
159
  { method: 'post', path: '/delete', handler: handlers.delete },
160
160
  { method: 'post', path: '/upload', handler: handlers.upload },
161
+ { method: 'post', path: '/save-image', handler: handlers.saveImage },
162
+ { method: 'get', path: '/content', handler: handlers.getFileContent },
163
+ { method: 'post', path: '/save-content', handler: handlers.saveFileContent },
164
+ { method: 'post', path: '/batch-delete', handler: handlers.batchDelete },
165
+ { method: 'post', path: '/batch-move', handler: handlers.batchMove },
166
+ { method: 'get', path: '/download-zip', handler: handlers.downloadZip },
167
+ { method: 'post', path: '/download-zip', handler: handlers.downloadZip },
168
+ { method: 'get', path: '/storage-stats', handler: handlers.getStorageStats },
161
169
  ],
162
170
  },
163
171
  });
package/plugins/index.js CHANGED
@@ -20,6 +20,7 @@ module.exports = {
20
20
  get apiDocsPlugin() { return require('./swagger'); },
21
21
  get healthCheckPlugin() { return require('./health-check'); },
22
22
  get restResourcePlugin() { return require('./rest-resources'); },
23
+ get restResourcesPlugin() { return require('./rest-resources'); },
23
24
  get ormCacheAdminPlugin() { return require('./orm-cache-admin'); },
24
25
  get uploadPlugin() { return require('./upload').uploadPlugin; },
25
26
  get createLocalFileProvider() { return require('./upload').createLocalFileProvider; },
@@ -68,6 +69,12 @@ module.exports = {
68
69
  get defineLazyPlugin() { return require('./lazy').defineLazyPlugin; },
69
70
  get rlsPlugin() { return require('./rls').rlsPlugin; },
70
71
  get createRlsMiddleware() { return require('./rls').createRlsMiddleware; },
72
+ get securityPlugin() { return require('./security').securityPlugin; },
73
+ get createSecurityHeadersMiddleware() { return require('./security').createSecurityHeadersMiddleware; },
74
+ get createFirewallMiddleware() { return require('./security').createFirewallMiddleware; },
75
+ get FirewallManager() { return require('./security').FirewallManager; },
76
+ get IncidentRecorder() { return require('./security').IncidentRecorder; },
77
+ get auditSecurityPosture() { return require('./security').auditSecurityPosture; },
71
78
  };
72
79
 
73
80