-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1556 lines (1334 loc) · 61.3 KB
/
server.js
File metadata and controls
1556 lines (1334 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const path = require('path');
const os = require('os');
const fs = require('fs-extra');
const DirectoryBrowser = require('./src/utils/directoryBrowser');
const FileAnalyzer = require('./src/services/fileAnalyzer');
const FileCleanup = require('./src/services/fileCleanup');
const ImportService = require('./src/services/importService');
const MergeService = require('./src/services/mergeService');
const StackExportService = require('./src/services/stackExportService');
const DiskSpaceValidator = require('./src/utils/diskSpaceValidator');
const FileRenamer = require('./src/utils/fileRenamer');
const logger = require('./src/utils/logger');
// Detect if running as a pkg-bundled executable
const isPackaged = typeof process.pkg !== 'undefined';
// Read version from sslm.iss (source of truth), fall back to package.json
function readAppVersion() {
try {
const issPath = path.join(__dirname, 'installer', 'sslm.iss');
const issContent = fs.readFileSync(issPath, 'utf8');
const match = issContent.match(/#define AppVersion\s+"([^"]+)"/);
if (match) return match[1];
} catch (_) { /* file not found or unreadable */ }
return require('./package.json').version;
}
const APP_VERSION = readAppVersion();
// Compare two version strings (e.g. "1.0.0-beta.4").
// Returns 1 if a > b, -1 if a < b, 0 if equal.
function compareVersions(a, b) {
const parse = v => v.replace(/^v/, '').split(/[.\-]/).map(s => isNaN(s) ? s : Number(s));
const pa = parse(a), pb = parse(b);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const x = pa[i], y = pb[i];
if (x === undefined) return -1;
if (y === undefined) return 1;
if (typeof x === 'number' && typeof y === 'number') {
if (x !== y) return x > y ? 1 : -1;
} else {
const xs = String(x), ys = String(y);
if (xs !== ys) return xs > ys ? 1 : -1;
}
}
return 0;
}
// Session-level cache for update check result (one GitHub API call per server run)
let updateCheckCache = null;
// Create Express app
const app = express();
// HTTP is intentional — this server listens on localhost only and is never exposed
// to a network, so HTTPS/TLS provides no meaningful security benefit here.
const server = http.createServer(app);
const io = socketIO(server);
// Load configuration
// When packaged, store user config in %APPDATA%\SSLM (writable).
// In development, use the local config/ directory.
const configDir = isPackaged
? path.join(process.env.APPDATA || process.env.HOME || '.', 'SSLM')
: path.join(__dirname, 'config');
const configPath = path.join(configDir, 'settings.json');
const operationStatePath = path.join(configDir, 'last-operation.json');
// Initialise file logging — %APPDATA%\SSLM\logs\ (packaged) or config/logs/ (dev).
// Must happen before the first console.log so startup messages are captured.
logger.init(path.join(configDir, 'logs'));
// Redirect all console output through the logger so every module's
// console.log/warn/error calls are automatically timestamped and persisted.
console.log = (...args) => logger.info(...args);
console.warn = (...args) => logger.warn(...args);
console.error = (...args) => logger.error(...args);
const defaultConfig = {
configVersion: 1,
server: { port: 3000, host: 'localhost' },
mode: { online: false },
seestar: { directoryName: 'MyWorks' },
paths: { lastSourcePath: '', lastDestinationPath: '' },
preferences: { defaultImportStrategy: 'incremental' },
engagement: { welcomeShown: false, dismissCount: 0, lastShown: null }
};
// Custom schema validator to ensure type safety without external dependencies
function validateConfigTypes(rawConfig) {
const result = { ...rawConfig };
// Helper to coerce or default types securely
const ensureNumber = (val, def) => (typeof val === 'number' && !isNaN(val) ? val : def);
const ensureString = (val, def) => (typeof val === 'string' ? val : def);
const ensureBoolean = (val, def) => (typeof val === 'boolean' ? val : def);
if (result.server) {
result.server.port = ensureNumber(result.server.port, defaultConfig.server.port);
result.server.host = ensureString(result.server.host, defaultConfig.server.host);
}
if (result.mode) {
result.mode.online = ensureBoolean(result.mode.online, defaultConfig.mode.online);
}
if (result.seestar) {
result.seestar.directoryName = ensureString(result.seestar.directoryName, defaultConfig.seestar.directoryName);
}
if (result.paths) {
result.paths.lastSourcePath = ensureString(result.paths.lastSourcePath, defaultConfig.paths.lastSourcePath);
result.paths.lastDestinationPath = ensureString(result.paths.lastDestinationPath, defaultConfig.paths.lastDestinationPath);
}
if (result.preferences) {
result.preferences.defaultImportStrategy = ensureString(result.preferences.defaultImportStrategy, defaultConfig.preferences.defaultImportStrategy);
}
// Enforce config versioning
result.configVersion = defaultConfig.configVersion;
return result;
}
// Deep-merge loaded config with defaults:
// - Missing or wrong-typed sections fall back to a fresh copy of the default (never a shared reference).
// - Extra top-level keys not in defaultConfig are preserved so no user data is silently dropped.
function applyConfigDefaults(raw) {
let result = {};
for (const key of Object.keys(defaultConfig)) {
const def = defaultConfig[key];
const val = raw[key];
if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
result[key] = { ...def, ...val }; // merge: user values win, defaults fill gaps
} else if (val !== undefined && val !== null) {
result[key] = val; // primitive override (unusual but keep it)
} else {
result[key] = { ...def }; // missing key — fresh copy, not a shared ref
}
}
// Preserve any extra top-level keys not in defaultConfig (e.g. keys written by POST /api/config)
for (const key of Object.keys(raw)) {
if (!(key in result)) result[key] = raw[key];
}
// Validate basic types and handle version migrations
result = validateConfigTypes(result);
return result;
}
let config = {};
// Write/clear/read a small JSON file that tracks the currently-running operation.
// On the next startup the presence of this file indicates the previous run was
// interrupted (crash, power loss) before the operation could finish cleanly.
function writeOperationState(state) {
try {
fs.ensureDirSync(configDir);
fs.writeJSONSync(operationStatePath, { ...state, startedAt: new Date().toISOString() }, { spaces: 2 });
} catch (err) {
console.warn('Could not write operation state:', err.message);
}
}
function clearOperationState() {
try { fs.removeSync(operationStatePath); } catch (_) { }
}
function readOperationState() {
try { return fs.readJSONSync(operationStatePath); } catch (_) { return null; }
}
try {
const raw = fs.readJSONSync(configPath);
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
throw new Error('settings.json is not a JSON object — resetting to defaults');
}
config = applyConfigDefaults(raw);
} catch (error) {
console.warn('Config invalid or not found, using defaults:', error.message);
config = applyConfigDefaults({});
// When packaged, persist the default config to APPDATA on first run / after reset
if (isPackaged) {
try {
fs.ensureDirSync(configDir);
fs.writeJSONSync(configPath, config, { spaces: 2 });
} catch (err) {
console.warn('Could not write default config to APPDATA:', err.message);
}
}
}
// Always start in offline mode — user must explicitly enable online features each session
config.mode.online = false;
// Check for an operation that was interrupted by a crash or unexpected shutdown.
// If last-operation.json exists at startup it was never cleared by a clean finish.
const interruptedOperation = readOperationState();
if (interruptedOperation) {
console.warn(`[STARTUP] Interrupted operation detected: ${interruptedOperation.type} started at ${interruptedOperation.startedAt}`);
}
// ─── Operation status store ──────────────────────────────────────────────────
// Keeps the last progress snapshot and final outcome for each active operation
// so that clients can poll after a Socket.IO disconnect and not miss completion.
const operationStore = new Map();
function initOperation(operationId, type, clientId) {
operationStore.set(operationId, { type, clientId, status: 'in_progress', lastProgress: null, result: null });
}
// Wrap io.to() so every emit to a clientId room is automatically snapshotted.
// Services call this.io.to(clientId).emit(event, data) — the wrapper intercepts
// those calls transparently without requiring changes to any service file.
const _realIoTo = io.to.bind(io);
io.to = function (room) {
const broadcaster = _realIoTo(room);
const _realEmit = broadcaster.emit.bind(broadcaster);
broadcaster.emit = function (event, data) {
if (data && typeof data.operationId === 'string') {
const entry = operationStore.get(data.operationId);
if (entry) {
if (event.endsWith(':progress')) {
entry.lastProgress = { event, data };
} else if (event.endsWith(':complete') || event.endsWith(':error') || event.endsWith(':cancelled')) {
entry.status = event;
entry.result = data;
entry.completedAt = Date.now();
// Auto-remove after 10 minutes so the Map doesn't grow unbounded
setTimeout(() => operationStore.delete(data.operationId), 10 * 60 * 1000);
}
}
}
return _realEmit(event, data);
};
return broadcaster;
};
// Initialize services with Socket.IO and config
const importService = new ImportService(io, config);
const mergeService = new MergeService(io, config);
const stackExportService = new StackExportService(io, config);
const PORT = process.env.PORT || config.server.port || 3000;
const HOST = config.server.host || 'localhost';
// Middleware
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.disable('x-powered-by'); // Do not advertise the framework in response headers
// Simple in-memory rate limiter for expensive endpoints (CWE-770)
// windowMs: rolling window length; max: max requests per window per IP
function createRateLimiter({ windowMs = 60_000, max = 10 } = {}) {
const hits = new Map(); // ip -> [timestamps]
// Periodically evict entries whose timestamps have all expired, bounding Map growth (CWE-770)
const cleanupTimer = setInterval(() => {
const now = Date.now();
for (const [ip, timestamps] of hits.entries()) {
if (timestamps.every(t => now - t >= windowMs)) {
hits.delete(ip);
}
}
}, windowMs * 2);
cleanupTimer.unref(); // Don't prevent process exit
return (req, res, next) => {
const ip = req.ip || req.connection.remoteAddress || 'unknown';
const now = Date.now();
const window = (hits.get(ip) || []).filter(t => now - t < windowMs);
if (window.length >= max) {
return res.status(429).json({ success: false, error: { code: 'API_ERROR', message: 'Too many requests, please try again later.' } });
}
window.push(now);
hits.set(ip, window);
next();
};
}
// Rate limiters for expensive file-system operations
const heavyOpLimiter = createRateLimiter({ windowMs: 60_000, max: 10 }); // import/merge start
const analysisLimiter = createRateLimiter({ windowMs: 60_000, max: 30 }); // analyze / space checks
const lightLimiter = createRateLimiter({ windowMs: 60_000, max: 200 }); // static pages / image serving
// Path allowlist — rejects any path that does not resolve to a recognised Windows root.
// Allows any drive letter (A-Z:\) and UNC paths (\\server\share) so the user can
// browse and operate on any drive they have authorised, while blocking anything that
// resolves outside a real Windows filesystem root (CWE-22).
function isAllowedPath(resolvedPath) {
if (!path.isAbsolute(resolvedPath)) return false;
if (/^[A-Za-z]:[/\\]/.test(resolvedPath)) return true; // drive-letter root
if (resolvedPath.startsWith('\\\\')) return true; // UNC / network path
return false;
}
// Routes
app.get('/', lightLimiter, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/api/status', lightLimiter, (req, res) => {
res.json({
status: 'running',
version: '1.0.0',
mode: config.mode.online ? 'online' : 'offline',
timestamp: new Date().toISOString()
});
});
// GET /api/operations/:id/status — poll the last-known state of a long-running
// operation so the client can recover after a Socket.IO disconnect.
app.get('/api/operations/:id/status', lightLimiter, (req, res) => {
const entry = operationStore.get(req.params.id);
if (!entry) {
return res.json({ status: 'unknown' });
}
res.json({
status: entry.status, // 'in_progress' | '<event>:complete' | '<event>:error' | '<event>:cancelled'
type: entry.type,
lastProgress: entry.lastProgress,
result: entry.result,
completedAt: entry.completedAt || null,
});
});
app.get('/api/config', lightLimiter, (req, res) => {
res.json({
version: APP_VERSION,
mode: config.mode,
preferences: config.preferences,
seestar: config.seestar,
interruptedOperation: interruptedOperation || null,
paths: {
hasLastSource: !!config.paths.lastSourcePath,
hasLastDestination: !!config.paths.lastDestinationPath
}
});
});
app.post('/api/config', analysisLimiter, async (req, res) => {
try {
// Update config with new values
config = { ...config, ...req.body };
// Save to file
await fs.writeJSON(configPath, config, { spaces: 2 });
res.json({ success: true, config });
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// Image serving endpoint
app.get('/api/image', lightLimiter, async (req, res) => {
try {
const imagePath = req.query.path;
if (!imagePath || typeof imagePath !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Image path is required' } });
}
// Resolve then allowlist-check to prevent traversal (CWE-22)
const resolvedPath = path.resolve(imagePath);
if (!isAllowedPath(resolvedPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid image path' } });
}
// Only serve explicitly allowed image extensions — no fallback to arbitrary files
const ext = path.extname(resolvedPath).toLowerCase();
const contentTypes = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.bmp': 'image/bmp',
'.tif': 'image/tiff',
'.tiff': 'image/tiff'
};
const contentType = contentTypes[ext];
if (!contentType) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'File type not allowed' } });
}
// Check if file exists
const exists = await fs.pathExists(resolvedPath);
if (!exists) {
return res.status(404).json({ success: false, error: { code: 'API_ERROR', message: 'Image not found' } });
}
// Send file using absolute resolved path
res.setHeader('Content-Type', contentType);
res.sendFile(resolvedPath);
} catch (error) {
console.error('Error serving image:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// Favorites API Routes
app.get('/api/favorites', lightLimiter, (req, res) => {
try {
const favorites = config.favorites || [];
res.json({ success: true, favorites });
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/favorites/add', analysisLimiter, async (req, res) => {
try {
const { path: favPath, name } = req.body;
if (!favPath) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Path required' } });
}
// Initialize favorites if not exists
if (!config.favorites) {
config.favorites = [];
}
// Check if already exists
const exists = config.favorites.some(fav => fav.path === favPath);
if (exists) {
return res.json({ success: true, message: 'Path already in favorites', favorites: config.favorites });
}
// Add to favorites
config.favorites.push({
path: favPath,
name: name || path.basename(favPath),
addedAt: new Date().toISOString()
});
// Save to file
await fs.writeJSON(configPath, config, { spaces: 2 });
res.json({ success: true, favorites: config.favorites });
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/favorites/remove', analysisLimiter, async (req, res) => {
try {
const { path: favPath } = req.body;
if (!favPath) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Path required' } });
}
if (!config.favorites) {
config.favorites = [];
}
// Remove from favorites
config.favorites = config.favorites.filter(fav => fav.path !== favPath);
// Save to file
await fs.writeJSON(configPath, config, { spaces: 2 });
res.json({ success: true, favorites: config.favorites });
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// Directory Browser API Routes
app.get('/api/browse/drives', lightLimiter, async (req, res) => {
try {
const drives = await DirectoryBrowser.getWindowsDrives();
const common = DirectoryBrowser.getCommonDirectories();
res.json({
success: true,
drives,
common
});
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.get('/api/browse/directory', analysisLimiter, async (req, res) => {
try {
const rawPath = req.query.path;
if (!rawPath || typeof rawPath !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Path parameter required' } });
}
const directoryPath = path.resolve(rawPath);
if (!isAllowedPath(directoryPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
const result = await DirectoryBrowser.getDirectoryContents(directoryPath);
res.json({
success: !result.error,
currentPath: result.currentPath,
parentPath: result.parentPath,
directories: result.items || [],
error: result.error
});
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/browse/create-directory', analysisLimiter, async (req, res) => {
try {
const { parentPath, folderName } = req.body;
if (!parentPath || !folderName) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'parentPath and folderName required' } });
}
// Validate parent path exists
const parentExists = await fs.pathExists(parentPath);
if (!parentExists) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Parent directory does not exist' } });
}
// Create the new directory path
const newDirPath = path.join(parentPath, folderName);
// Check if it already exists
const alreadyExists = await fs.pathExists(newDirPath);
if (alreadyExists) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Directory already exists' } });
}
// Create the directory
await fs.ensureDir(newDirPath);
res.json({
success: true,
path: newDirPath,
message: 'Directory created successfully'
});
} catch (error) {
console.error('Error creating directory:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.get('/api/browse/validate', analysisLimiter, async (req, res) => {
try {
const { path: rawValidatePath, checkMyWork } = req.query;
if (!rawValidatePath || typeof rawValidatePath !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Path parameter required' } });
}
const directoryPath = path.resolve(rawValidatePath);
if (!isAllowedPath(directoryPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
const exists = await fs.pathExists(directoryPath);
let hasMyWork = false;
if (exists && checkMyWork === 'true') {
hasMyWork = await DirectoryBrowser.hasMyWorkDirectory(directoryPath);
}
res.json({
success: true,
exists,
hasMyWork,
path: directoryPath
});
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// File Analysis API Routes
app.get('/api/analyze', analysisLimiter, async (req, res) => {
try {
const rawPath = req.query.path;
if (!rawPath || typeof rawPath !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Path parameter required' } });
}
const directoryPath = path.resolve(rawPath);
if (!isAllowedPath(directoryPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
console.log(`\n=== ANALYZE REQUEST ===`);
console.log(`Raw path from query: "${directoryPath}"`);
console.log(`Path length: ${directoryPath.length}`);
console.log(`Path exists check...`);
// Check if directory exists
const exists = await fs.pathExists(directoryPath);
console.log(`Directory exists: ${exists}`);
if (!exists) {
console.error(`ERROR: Directory not found at path: "${directoryPath}"`);
return res.status(404).json({ success: false, error: { code: 'API_ERROR', message: `Directory does not exist: ${directoryPath}` } });
}
console.log(`Starting analysis...`);
const result = await FileAnalyzer.analyzeDirectory(directoryPath);
if (result.success) {
console.log(`Analysis complete: ${result.summary.totalObjects} objects found in ${result.analysisTime}ms`);
}
res.json(result);
} catch (error) {
console.error(`Analysis error:`, error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.get('/api/analyze/cleanup-suggestions', analysisLimiter, async (req, res) => {
try {
const rawPath = req.query.path;
if (!rawPath || typeof rawPath !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Path parameter required' } });
}
const directoryPath = path.resolve(rawPath);
if (!isAllowedPath(directoryPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
const analysisResult = await FileAnalyzer.analyzeDirectory(directoryPath);
if (!analysisResult.success) {
return res.status(400).json(analysisResult);
}
const suggestions = FileAnalyzer.getSuggestedCleanup(analysisResult);
res.json({
success: true,
suggestions
});
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// Cleanup API Routes
app.post('/api/cleanup/empty-directories', heavyOpLimiter, async (req, res) => {
try {
console.log('Empty directories cleanup request received');
const { directories } = req.body;
if (!directories || !Array.isArray(directories)) {
console.error('Invalid request: directories array missing or not an array');
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Directories array required' } });
}
console.log(`Deleting ${directories.length} empty directories...`);
const result = await FileCleanup.deleteEmptyDirectories(directories);
console.log(`Deleted ${result.totalDeleted} directories, ${result.totalFailed} failed`);
res.json(result);
} catch (error) {
console.error('Error in empty directories cleanup:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message, stack: error.stack } });
}
});
app.post('/api/cleanup/subframe-directories', heavyOpLimiter, async (req, res) => {
try {
console.log('Sub-frame cleanup request received');
const { objects } = req.body;
if (!objects || !Array.isArray(objects)) {
console.error('Invalid request: objects array missing or not an array');
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Objects array required' } });
}
console.log(`Cleaning up sub-frame directories for ${objects.length} objects...`);
const result = await FileCleanup.cleanupSubFrameDirectories(objects);
console.log(`Deleted ${result.totalFilesDeleted} files, freed ${FileCleanup.formatBytes(result.totalSpaceFreed)}`);
res.json(result);
} catch (error) {
console.error('Error in sub-frame cleanup:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message, stack: error.stack } });
}
});
app.get('/api/cleanup/subframe-info', analysisLimiter, async (req, res) => {
try {
const rawPath = req.query.path;
if (!rawPath || typeof rawPath !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Path parameter required' } });
}
const directoryPath = path.resolve(rawPath);
if (!isAllowedPath(directoryPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
const analysisResult = await FileAnalyzer.analyzeDirectory(directoryPath);
if (!analysisResult.success) {
return res.status(400).json(analysisResult);
}
const info = FileCleanup.getSubFrameCleanupInfo(analysisResult.objects);
res.json({
success: true,
info
});
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// Delete Session Files
app.post('/api/cleanup/session', heavyOpLimiter, async (req, res) => {
try {
const { mainFolderPath, mainFiles, subFiles } = req.body;
if (!mainFolderPath || !mainFiles) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'mainFolderPath and mainFiles are required' } });
}
// subFiles is an array of { folder, file } objects — each entry carries its own
// folder path, supporting files from both _sub (Eq) and -sub (Alt/Az) directories.
const result = await FileCleanup.deleteSessionFiles({
mainFolderPath,
mainFiles,
subFiles: subFiles || []
});
res.json(result);
} catch (error) {
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// Import API Routes
app.get('/api/import/detect-seestar', analysisLimiter, async (req, res) => {
try {
console.log('Detecting SeeStar devices...');
const devices = await importService.detectSeeStarDevices();
console.log(`Found ${devices.length} devices`);
res.json({ success: true, devices });
} catch (error) {
console.error('Error detecting devices:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/import/validate-space', analysisLimiter, async (req, res) => {
try {
const { strategy, subframeMode } = req.body;
const rawSource = req.body.sourcePath;
const rawDest = req.body.destinationPath;
if (!rawSource || typeof rawSource !== 'string' || !rawDest || typeof rawDest !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'sourcePath and destinationPath required' } });
}
const sourcePath = path.resolve(rawSource);
const destinationPath = path.resolve(rawDest);
if (!isAllowedPath(sourcePath) || !isAllowedPath(destinationPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
const importStrategy = strategy || 'full'; // Default to full if not specified
const importSubframeMode = subframeMode || 'all';
console.log(`Validating disk space (${importStrategy}, ${importSubframeMode}): ${sourcePath} -> ${destinationPath}`);
const result = await DiskSpaceValidator.hasEnoughSpace(
sourcePath,
destinationPath,
importStrategy,
1.1, // 10% safety buffer
importSubframeMode
);
console.log(`Space validation: ${result.hasEnoughSpace ? 'OK' : 'INSUFFICIENT'} - Required: ${result.requiredFormatted}`);
res.json({ success: true, ...result });
} catch (error) {
console.error('Error validating space:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/import/start', heavyOpLimiter, async (req, res) => {
try {
const { strategy, clientId, subframeMode } = req.body;
const rawSource = req.body.sourcePath;
const rawDest = req.body.destinationPath;
if (!rawSource || typeof rawSource !== 'string' || !rawDest || typeof rawDest !== 'string' ||
!strategy || !clientId) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'sourcePath, destinationPath, strategy, and clientId required' } });
}
const sourcePath = path.resolve(rawSource);
const destinationPath = path.resolve(rawDest);
if (!isAllowedPath(sourcePath) || !isAllowedPath(destinationPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
const importSubframeMode = subframeMode || 'all';
console.log(`Starting import: ${sourcePath} -> ${destinationPath} (${strategy}, ${importSubframeMode})`);
// Start import asynchronously (don't await - it's long-running)
const operationId = Date.now().toString();
initOperation(operationId, 'import', clientId);
writeOperationState({ type: 'import', sourcePath, destinationPath, strategy, operationId });
importService.startImport(sourcePath, destinationPath, strategy, clientId, operationId, importSubframeMode)
.then(() => {
clearOperationState();
console.log(`Import completed successfully`);
})
.catch(error => {
clearOperationState();
console.error(`Import failed:`, error);
io.to(clientId).emit('import:error', {
error: error.message,
operationId
});
});
res.json({ success: true, operationId, message: 'Import started' });
} catch (error) {
console.error('Error starting import:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/import/cancel', lightLimiter, async (req, res) => {
try {
console.log('Cancelling import...');
const result = await importService.cancelImport();
clearOperationState();
console.log(`Import ${result.cancelled ? 'cancelled' : 'not active'}`);
res.json(result);
} catch (error) {
console.error('Error cancelling import:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/import/validate', analysisLimiter, async (req, res) => {
try {
const { clientId, subframeMode = 'all' } = req.body;
const rawSource = req.body.sourcePath;
const rawDest = req.body.destinationPath;
if (!rawSource || typeof rawSource !== 'string' || !rawDest || typeof rawDest !== 'string' ||
!clientId) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'sourcePath, destinationPath, and clientId required' } });
}
const sourcePath = path.resolve(rawSource);
const destinationPath = path.resolve(rawDest);
if (!isAllowedPath(sourcePath) || !isAllowedPath(destinationPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid path' } });
}
const operationId = Date.now().toString();
console.log(`Starting transfer validation: ${sourcePath} -> ${destinationPath} (subframeMode: ${subframeMode})`);
// Start validation asynchronously
importService.validateTransfer(sourcePath, destinationPath, clientId, operationId, subframeMode)
.catch(error => {
io.to(clientId).emit('validate:error', {
error: error.message,
operationId
});
});
res.json({ success: true, operationId, message: 'Validation started' });
} catch (error) {
console.error('Error starting validation:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
// Merge API Routes
app.post('/api/merge/analyze', analysisLimiter, async (req, res) => {
try {
const { clientId, subframeMode, forceOverwrite } = req.body;
const sourcePaths = (Array.isArray(req.body.sourcePaths) ? req.body.sourcePaths : [])
.filter(p => p && typeof p === 'string')
.map(p => path.resolve(p))
.filter(p => isAllowedPath(p));
const rawDest = req.body.destinationPath;
if (!sourcePaths.length || sourcePaths.length < 2) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'At least 2 source paths required' } });
}
if (!rawDest || typeof rawDest !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'destinationPath required' } });
}
const destinationPath = path.resolve(rawDest);
if (!isAllowedPath(destinationPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid destinationPath' } });
}
const mergeSubframeMode = subframeMode || 'all';
console.log(`Analyzing ${sourcePaths.length} libraries for merge (${mergeSubframeMode})...`);
const result = await mergeService.analyzeSources(sourcePaths, destinationPath, clientId, mergeSubframeMode, forceOverwrite === true);
res.json({ success: true, ...result });
} catch (error) {
console.error('Error analyzing merge:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/merge/validate-space', analysisLimiter, async (req, res) => {
try {
const { subframeMode } = req.body;
const sourcePaths = (Array.isArray(req.body.sourcePaths) ? req.body.sourcePaths : [])
.filter(p => typeof p === 'string')
.map(p => path.resolve(p))
.filter(p => isAllowedPath(p));
const rawDest = req.body.destinationPath;
if (!sourcePaths.length || !rawDest || typeof rawDest !== 'string') {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'sourcePaths and destinationPath required' } });
}
const destinationPath = path.resolve(rawDest);
if (!isAllowedPath(destinationPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid destinationPath' } });
}
const mergeSubframeMode = subframeMode || 'all';
console.log(`Validating disk space for merge: ${sourcePaths.length} sources (${mergeSubframeMode})`);
// Calculate deduplicated space required
const required = await DiskSpaceValidator.getMergeRequiredSpace(sourcePaths, mergeSubframeMode);
const requiredWithBuffer = Math.ceil(required * 1.1); // 10% buffer
// Get available space
const available = await DiskSpaceValidator.getAvailableSpace(destinationPath);
const result = {
hasEnoughSpace: available >= requiredWithBuffer,
required: requiredWithBuffer,
requiredFormatted: DiskSpaceValidator.formatBytes(requiredWithBuffer),
available,
availableFormatted: DiskSpaceValidator.formatBytes(available),
bufferApplied: 1.1,
requiredWithoutBuffer: required,
requiredWithoutBufferFormatted: DiskSpaceValidator.formatBytes(required)
};
console.log(`Merge space validation: ${result.hasEnoughSpace ? 'OK' : 'INSUFFICIENT'} - Required: ${result.requiredFormatted}`);
res.json({ success: true, ...result });
} catch (error) {
console.error('Error validating merge space:', error);
res.status(500).json({ success: false, error: { code: 'API_ERROR', message: error.message } });
}
});
app.post('/api/merge/start', heavyOpLimiter, async (req, res) => {
try {
const { mergePlan, clientId } = req.body;
const sourcePaths = (Array.isArray(req.body.sourcePaths) ? req.body.sourcePaths : [])
.filter(p => p && typeof p === 'string')
.map(p => path.resolve(p))
.filter(p => isAllowedPath(p));
const rawDest = req.body.destinationPath;
if (!sourcePaths.length || !rawDest || typeof rawDest !== 'string' ||
!mergePlan || !clientId) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'sourcePaths, destinationPath, mergePlan, and clientId required' } });
}
const destinationPath = path.resolve(rawDest);
if (!isAllowedPath(destinationPath)) {
return res.status(400).json({ success: false, error: { code: 'API_ERROR', message: 'Invalid destinationPath' } });
}
console.log(`Starting merge: ${sourcePaths.length} sources -> ${destinationPath}`);
// Sanitize paths nested inside mergePlan.filesToCopy (CWE-22).
// sourcePath must resolve to a recognised Windows root; relativePath must not
// contain traversal sequences (it is joined with destinationPath server-side).
if (Array.isArray(mergePlan.filesToCopy)) {
mergePlan.filesToCopy = mergePlan.filesToCopy.map(item => {
if (!item.sourcePath || typeof item.sourcePath !== 'string') return null;
const resolvedSource = path.resolve(item.sourcePath);
if (!isAllowedPath(resolvedSource)) return null;
if (item.relativePath !== undefined) {
if (typeof item.relativePath !== 'string' || item.relativePath.includes('..')) return null;
}
return { ...item, sourcePath: resolvedSource };
}).filter(Boolean);
}
const operationId = Date.now().toString();
initOperation(operationId, 'merge', clientId);
writeOperationState({ type: 'merge', sourcePaths, destinationPath, operationId });
mergeService.executeMerge(sourcePaths, destinationPath, mergePlan, clientId, operationId)
.then(() => {
clearOperationState();
console.log(`Merge completed successfully`);