Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2873 lines (2514 loc) · 98.7 KB
/
Copy pathserver.js
File metadata and controls
2873 lines (2514 loc) · 98.7 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 fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const http = require('http');
const https = require('https');
const net = require('net');
const dns = require('dns');
const zlib = require('zlib');
const { URL } = require('url');
const app = express();
let boundServerPort = null;
const PORT = process.env.PORT || 3000;
// API Security Middleware registered before any route
app.use('/api', (req, res, next) => {
const boundPort = req.socket?.localPort || boundServerPort || app.get('port') || PORT;
const host = req.headers.host;
const allowedHosts = [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`];
// 1. Rejects unless the Host header is exactly 127.0.0.1:<boundPort> or localhost:<boundPort>
if (!host || !allowedHosts.includes(host)) {
return res.status(403).json({ error: 'Forbidden: invalid Host header' });
}
// Reject Sec-Fetch-Site: cross-site for all /api requests, GET included
const secFetchSite = req.headers['sec-fetch-site'];
if (secFetchSite === 'cross-site') {
return res.status(403).json({ error: 'Forbidden: cross-site request rejected' });
}
// Reject opaque / null origins for all /api requests
const origin = req.headers.origin;
if (origin === 'null') {
return res.status(403).json({ error: 'Forbidden: null origin rejected' });
}
// 2. Rejects state-changing methods (POST/PUT/PATCH/DELETE) unless Origin is absent or equals the app origin,
// and Sec-Fetch-Site (when present) is same-origin or none
const method = req.method ? req.method.toUpperCase() : '';
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
const allowedOrigins = [`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`];
if (origin && !allowedOrigins.includes(origin)) {
return res.status(403).json({ error: 'Forbidden: cross-origin request rejected' });
}
if (secFetchSite && secFetchSite !== 'same-origin' && secFetchSite !== 'none') {
return res.status(403).json({ error: 'Forbidden: invalid Sec-Fetch-Site' });
}
}
next();
});
// Enable JSON body parser with generous limit for large image collections & review history
app.use(express.json({ limit: '50mb' }));
// CSP header on the app HTML
const APP_CSP = "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'";
app.use((req, res, next) => {
if (req.path === '/' || req.path.endsWith('.html')) {
res.setHeader('Content-Security-Policy', APP_CSP);
}
next();
});
// Serve static files from public/
app.use(express.static(path.join(__dirname, 'public'), {
setHeaders: (res, filePath) => {
if (filePath.endsWith('.html')) {
res.setHeader('Content-Security-Policy', APP_CSP);
}
}
}));
// Serve static assets from assets/
app.use('/assets', express.static(path.join(__dirname, 'assets')));
// Persistent Disk Storage for SRS Database & Visual Sketch History
const USERDATA_DIR = process.env.USER_DATA_DIR || path.join(__dirname, 'userdata');
const STATE_FILE = path.join(USERDATA_DIR, 'srs_state.json');
const SKETCHES_DIR = path.join(USERDATA_DIR, 'sketches');
const BACKUPS_DIR = path.join(USERDATA_DIR, 'backups');
const PACKS_DIR = path.join(USERDATA_DIR, 'packs');
const PACKS_MANIFEST_FILE = path.join(PACKS_DIR, 'manifest.json');
// Ensure userdata, sketches, backups, and packs directories exist on startup
fs.mkdirSync(SKETCHES_DIR, { recursive: true });
fs.mkdirSync(BACKUPS_DIR, { recursive: true });
fs.mkdirSync(PACKS_DIR, { recursive: true });
// In-memory set of folders explicitly trusted (e.g. chosen via native folder picker this session)
const trustedFolders = new Set();
const extensionAllowedFolders = new Set();
/**
* Registers an absolute folder path into the trusted folders Set.
* Canonicalizes via fs.realpathSync (or path.resolve if realpath fails).
*/
function registerTrustedFolder(absPath) {
if (!absPath || typeof absPath !== 'string') return;
try {
const real = fs.realpathSync(absPath);
trustedFolders.add(real);
} catch (e) {
trustedFolders.add(path.resolve(absPath));
}
}
function clearTrustedFolders() {
trustedFolders.clear();
}
/**
* Returns a Set of resolved real paths for all registered deck folders
* as the union of folders from STATE_FILE and in-memory trustedFolders.
*/
function getRegisteredDeckFolders() {
const folders = new Set(trustedFolders);
if (fs.existsSync(STATE_FILE)) {
try {
const raw = fs.readFileSync(STATE_FILE, 'utf8');
const state = JSON.parse(raw);
const decks = Array.isArray(state.decks)
? state.decks
: (state.data && Array.isArray(state.data.decks) ? state.data.decks : []);
for (const d of decks) {
if (d && d.folderPath) {
try {
folders.add(fs.realpathSync(d.folderPath));
} catch (e) {
folders.add(path.resolve(d.folderPath));
}
}
}
} catch (e) {
console.warn('[Server] Error reading registered deck folders from STATE_FILE:', e.message);
}
}
return folders;
}
function isPathInside(childPath, parentPath) {
const rel = path.relative(parentPath, childPath);
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
}
function isPathAllowedInRegisteredDecks(targetPath) {
let realTarget;
try {
realTarget = fs.realpathSync(targetPath);
} catch (e) {
realTarget = path.resolve(targetPath);
}
const deckFolders = getRegisteredDeckFolders();
for (const df of deckFolders) {
if (realTarget === df || isPathInside(realTarget, df)) {
return true;
}
}
for (const ef of extensionAllowedFolders) {
if (realTarget === ef || isPathInside(realTarget, ef)) {
return true;
}
}
return false;
}
/**
* Startup helper: checks userdata/srs_state.json once when the server starts
* and converts any old data:image/... strings inside attempts into files inside userdata/sketches/.
*/
function migrateBase64SketchesOnStartup() {
if (!fs.existsSync(STATE_FILE)) return;
try {
const raw = fs.readFileSync(STATE_FILE, 'utf8');
const state = JSON.parse(raw);
const cards = state.cards || (state.data && state.data.cards);
if (!cards || typeof cards !== 'object') return;
let migratedCount = 0;
for (const deckId of Object.keys(cards)) {
const deckCards = cards[deckId];
if (!deckCards || typeof deckCards !== 'object') continue;
for (const cardId of Object.keys(deckCards)) {
const card = deckCards[cardId];
if (!card || !Array.isArray(card.attempts)) continue;
for (const attempt of card.attempts) {
if (attempt && typeof attempt.sketchUrl === 'string') {
if (attempt.sketchUrl.startsWith('data:image/')) {
try {
const base64Data = attempt.sketchUrl.replace(/^data:image\/[a-zA-Z0-9+]+;base64,/, '');
const buffer = Buffer.from(base64Data, 'base64');
const filename = `sk_migrated_${Date.now()}_${Math.random().toString(36).slice(2, 6)}.png`;
const filePath = path.join(SKETCHES_DIR, filename);
fs.writeFileSync(filePath, buffer);
attempt.sketchUrl = `/api/sketch/${filename}`;
migratedCount++;
} catch (err) {
console.warn(`[Migration] Failed to migrate sketch for card ${cardId}:`, err.message);
}
} else if (attempt.sketchUrl.startsWith('/api/sketch?file=')) {
try {
const urlObj = new URL(attempt.sketchUrl, 'http://localhost');
const fileParam = urlObj.searchParams.get('file');
if (fileParam) {
attempt.sketchUrl = `/api/sketch/${path.basename(fileParam)}`;
migratedCount++;
}
} catch (err) {
console.warn(`[Migration] Failed to migrate legacy sketchUrl for card ${cardId}:`, err.message);
}
}
}
}
}
}
if (migratedCount > 0) {
state.lastSaved = new Date().toISOString();
const tempFile = path.join(USERDATA_DIR, `srs_state_${Date.now()}_${Math.random().toString(36).substring(2, 8)}.tmp`);
fs.writeFileSync(tempFile, JSON.stringify(state, null, 2), 'utf8');
fs.renameSync(tempFile, STATE_FILE);
console.log(`[Startup] Migrated ${migratedCount} Base64 sketch(es) to disk in userdata/sketches/`);
}
} catch (err) {
console.error('[Startup] Error during Base64 sketch migration:', err);
}
}
migrateBase64SketchesOnStartup();
// In-memory hash caches for file-move resilience:
// fileHashCache: filePath -> { mtimeMs, size, hash }
// hashToPathMap: hash -> filePath
const fileHashCache = new Map();
const hashToPathMap = new Map();
/**
* Compute a fast content hash for an image file:
* SHA-1 of (file size + first 64KB).
* Takes ~0.02ms per file and survives renaming, moving between subfolders,
* or moving the entire reference directory.
*/
function computeFileHash(filePath) {
try {
const stat = fs.statSync(filePath);
const cached = fileHashCache.get(filePath);
if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
hashToPathMap.set(cached.hash, filePath);
return cached.hash;
}
const size = stat.size;
const bufferSize = Math.min(size, 64 * 1024); // read up to 64KB
const fd = fs.openSync(filePath, 'r');
const buffer = Buffer.alloc(bufferSize);
fs.readSync(fd, buffer, 0, bufferSize, 0);
fs.closeSync(fd);
const hash = crypto.createHash('sha1');
hash.update(`${size}:`);
hash.update(buffer);
const digest = 'ch_' + hash.digest('hex');
fileHashCache.set(filePath, { mtimeMs: stat.mtimeMs, size, hash: digest });
hashToPathMap.set(digest, filePath);
return digest;
} catch (err) {
// Fallback deterministic hash if file cannot be opened directly
const fallback = 'ch_' + crypto.createHash('sha1').update(filePath).digest('hex');
hashToPathMap.set(fallback, filePath);
return fallback;
}
}
// Supported image extensions
const IMAGE_EXTENSIONS = new Set([
'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.tiff', '.tif'
]);
/**
* Recursively scan a directory for image files.
* Returns an array of absolute file paths.
*/
function scanForImages(dirPath, results = []) {
let entries;
try {
entries = fs.readdirSync(dirPath, { withFileTypes: true });
} catch (err) {
return results;
}
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
// Skip hidden directories, _crops subdirectories, and macOS __MACOSX metadata folders
const dirLower = entry.name.toLowerCase();
if (!entry.name.startsWith('.') && dirLower !== '_crops' && dirLower !== '__macosx') {
scanForImages(fullPath, results);
}
} else if (entry.isFile()) {
// Skip hidden files, dotfiles, and macOS AppleDouble ._* metadata files
if (entry.name.startsWith('.')) {
continue;
}
const ext = path.extname(entry.name).toLowerCase();
if (IMAGE_EXTENSIONS.has(ext)) {
results.push(fullPath);
}
}
}
return results;
}
// ============================================================
// Extension Discovery & Plugin API Subsystem
// ============================================================
const loadedExtensions = new Map();
function getExtensionSearchDirs() {
const dirs = [
path.join(USERDATA_DIR, 'extensions'),
path.join(__dirname, 'pro'),
path.resolve('./pro')
];
const unique = [];
for (const d of dirs) {
try {
if (fs.existsSync(d)) {
const real = fs.realpathSync(d);
if (!unique.includes(real)) {
unique.push(real);
}
}
} catch (e) { }
}
return unique;
}
function discoverExtensionManifestDirs(searchDirs) {
const manifestDirs = [];
for (const baseDir of searchDirs) {
try {
const stat = fs.statSync(baseDir);
if (!stat.isDirectory()) continue;
// Check if baseDir itself contains manifest.json
const directManifest = path.join(baseDir, 'manifest.json');
if (fs.existsSync(directManifest)) {
if (!manifestDirs.includes(baseDir)) {
manifestDirs.push(baseDir);
}
}
// Check immediate subdirectories
const entries = fs.readdirSync(baseDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory() && path.basename(entry.name) === entry.name) {
const subDir = path.join(baseDir, entry.name);
try {
const realSub = fs.realpathSync(subDir);
const subManifest = path.join(realSub, 'manifest.json');
if (fs.existsSync(subManifest) && !manifestDirs.includes(realSub)) {
manifestDirs.push(realSub);
}
} catch (e) { }
}
}
} catch (e) { }
}
return manifestDirs;
}
function loadExtensions(options = {}) {
const searchDirs = options.searchDirs || getExtensionSearchDirs();
const extDirs = discoverExtensionManifestDirs(searchDirs);
for (const extDir of extDirs) {
try {
const realExtDir = fs.realpathSync(extDir);
const manifestPath = path.join(realExtDir, 'manifest.json');
if (!fs.existsSync(manifestPath)) continue;
let manifest;
try {
const raw = fs.readFileSync(manifestPath, 'utf8');
manifest = JSON.parse(raw);
} catch (err) {
console.warn(`[Extensions] Invalid JSON in manifest at ${manifestPath}:`, err.message);
continue;
}
if (!manifest || typeof manifest !== 'object') {
console.warn(`[Extensions] Manifest at ${manifestPath} must be a JSON object.`);
continue;
}
const { id, name, version, serverEntry, clientEntry, mainEntry } = manifest;
if (typeof id !== 'string' || !/^[a-z0-9-]+$/.test(id) || path.basename(id) !== id) {
console.warn(`[Extensions] Invalid extension id '${id}' at ${manifestPath}. Must match /^[a-z0-9-]+$/`);
continue;
}
if (typeof name !== 'string' || !name.trim()) {
console.warn(`[Extensions] Extension '${id}' must have a valid non-empty name.`);
continue;
}
if (typeof version !== 'string' || !version.trim()) {
console.warn(`[Extensions] Extension '${id}' must have a valid non-empty version.`);
continue;
}
if (loadedExtensions.has(id)) {
console.warn(`[Extensions] Extension '${id}' is already loaded; skipping duplicate at ${realExtDir}`);
continue;
}
// Validate clientEntry if defined
let validClientEntryPath = null;
if (clientEntry !== undefined && clientEntry !== null) {
if (typeof clientEntry !== 'string') {
console.warn(`[Extensions] Extension '${id}' clientEntry must be a string.`);
continue;
}
const normalizedClient = path.normalize(clientEntry);
if (path.isAbsolute(normalizedClient) || normalizedClient.startsWith('..')) {
console.warn(`[Extensions] Extension '${id}' clientEntry escapes extension folder: ${clientEntry}`);
continue;
}
const resolvedClient = path.resolve(realExtDir, normalizedClient);
try {
const realClient = fs.realpathSync(resolvedClient);
if (isPathInside(realClient, realExtDir) && fs.statSync(realClient).isFile()) {
validClientEntryPath = realClient;
} else {
console.warn(`[Extensions] Extension '${id}' clientEntry escapes extension folder: ${clientEntry}`);
continue;
}
} catch (e) {
console.warn(`[Extensions] Extension '${id}' clientEntry file not found: ${clientEntry}`);
continue;
}
}
// Validate and invoke serverEntry if defined
if (serverEntry !== undefined && serverEntry !== null) {
if (typeof serverEntry !== 'string') {
console.warn(`[Extensions] Extension '${id}' serverEntry must be a string.`);
continue;
}
const normalizedServer = path.normalize(serverEntry);
if (path.isAbsolute(normalizedServer) || normalizedServer.startsWith('..')) {
console.warn(`[Extensions] Extension '${id}' serverEntry escapes extension folder: ${serverEntry}`);
continue;
}
const resolvedServer = path.resolve(realExtDir, normalizedServer);
let realServer;
try {
realServer = fs.realpathSync(resolvedServer);
} catch (e) {
console.warn(`[Extensions] Extension '${id}' serverEntry file not found: ${serverEntry}`);
continue;
}
if (!isPathInside(realServer, realExtDir) || !fs.statSync(realServer).isFile()) {
console.warn(`[Extensions] Extension '${id}' serverEntry escapes extension folder: ${serverEntry}`);
continue;
}
const api = {
registerRoute: (method, subPath, handler) => {
if (typeof method !== 'string') {
throw new TypeError('HTTP method must be a string (GET, POST, DELETE)');
}
const httpMethod = method.toUpperCase();
if (!['GET', 'POST', 'DELETE'].includes(httpMethod)) {
throw new Error(`Unsupported HTTP method: ${method}. Allowed: GET, POST, DELETE`);
}
if (typeof handler !== 'function') {
throw new TypeError('Route handler must be a function');
}
if (typeof subPath !== 'string') {
throw new TypeError('Route subPath must be a string');
}
const posixSubPath = subPath.replace(/\\/g, '/');
const normalizedSub = path.posix.normalize('/' + posixSubPath);
if (normalizedSub.startsWith('/..') || normalizedSub.includes('/../')) {
throw new Error(`Path traversal detected in subPath: ${subPath}`);
}
const routePath = `/api/ext/${id}${normalizedSub === '/' ? '' : normalizedSub}`;
if (normalizedSub === '/') {
app[httpMethod.toLowerCase()](`/api/ext/${id}`, handler);
app[httpMethod.toLowerCase()](`/api/ext/${id}/`, handler);
} else {
app[httpMethod.toLowerCase()](routePath, handler);
}
},
registerAllowedFolder: (dirPath) => {
if (!dirPath || typeof dirPath !== 'string') {
throw new TypeError('Allowed directory path must be a non-empty string');
}
let realDir;
try {
realDir = fs.realpathSync(dirPath);
} catch (e) {
throw new Error(`Allowed folder does not exist or cannot be accessed: ${dirPath}`);
}
const stat = fs.statSync(realDir);
if (!stat.isDirectory()) {
throw new Error(`Allowed folder must be a directory: ${dirPath}`);
}
extensionAllowedFolders.add(realDir);
},
userDataDir: USERDATA_DIR
};
const extModule = require(realServer);
if (typeof extModule.registerFeature === 'function') {
extModule.registerFeature(api);
} else if (typeof extModule === 'function') {
extModule(api);
} else {
console.warn(`[Extensions] Extension '${id}' serverEntry does not export registerFeature function.`);
}
}
loadedExtensions.set(id, {
id,
name,
version,
extDir: realExtDir,
clientEntryPath: validClientEntryPath,
hasClient: Boolean(validClientEntryPath)
});
console.log(`[Extensions] Loaded extension: ${id} v${version} (${name})`);
} catch (err) {
console.warn(`[Extensions] Error loading extension at ${extDir}:`, err.message);
}
}
}
// GET /api/extensions - Return loaded client extension metadata
app.get('/api/extensions', (req, res) => {
const list = Array.from(loadedExtensions.values()).map(ext => ({
id: ext.id,
name: ext.name,
version: ext.version,
hasClient: Boolean(ext.clientEntryPath)
}));
res.json(list);
});
// GET /api/ext/:extId/client.js - Serve validated clientEntry file
app.get('/api/ext/:extId/client.js', (req, res) => {
const extId = req.params.extId;
if (!extId || typeof extId !== 'string' || !/^[a-z0-9-]+$/.test(extId) || path.basename(extId) !== extId) {
return res.status(400).json({ error: 'Invalid extension ID' });
}
const ext = loadedExtensions.get(extId);
if (!ext || !ext.clientEntryPath) {
return res.status(404).json({ error: 'Extension client script not found' });
}
try {
const realClient = fs.realpathSync(ext.clientEntryPath);
if (!isPathInside(realClient, ext.extDir) || !fs.statSync(realClient).isFile()) {
return res.status(404).json({ error: 'Extension client script not accessible' });
}
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Cache-Control', 'no-store');
res.sendFile(realClient);
} catch (err) {
return res.status(404).json({ error: 'Extension client script not found' });
}
});
// Run extension discovery hook during server initialization
try {
loadExtensions();
} catch (err) {
console.warn('[Extensions] Initial extension discovery warning:', err.message);
}
/**
* GET /api/browse?path=<absolute_path>
* Lists subdirectories and image count at a given path.
* Defaults to user's home directory if no path given.
*/
app.get('/api/browse', (req, res) => {
if (process.env.APP_RUNTIME === 'electron') {
return res.status(404).json({ error: 'Endpoint not available in desktop runtime' });
}
const os = require('os');
const requestedPath = req.query.path || os.homedir();
const resolved = path.resolve(requestedPath);
if (!fs.existsSync(resolved)) {
return res.status(404).json({ error: `Path not found: ${resolved}` });
}
const stat = fs.statSync(resolved);
if (!stat.isDirectory()) {
return res.status(400).json({ error: `Not a directory: ${resolved}` });
}
let entries;
try {
entries = fs.readdirSync(resolved, { withFileTypes: true });
} catch (err) {
return res.status(403).json({ error: `Cannot read directory: ${err.message}` });
}
const dirs = [];
let imageCount = 0;
for (const entry of entries) {
// Skip hidden files/dirs, _crops, and __MACOSX metadata
const nameLower = entry.name.toLowerCase();
if (entry.name.startsWith('.') || nameLower === '_crops' || nameLower === '__macosx') continue;
if (entry.isDirectory()) {
dirs.push(entry.name);
} else if (entry.isFile()) {
const ext = path.extname(entry.name).toLowerCase();
if (IMAGE_EXTENSIONS.has(ext)) {
imageCount++;
}
}
}
dirs.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
res.json({
current: resolved,
parent: path.dirname(resolved),
dirs,
imageCount
});
});
/**
* GET /api/images?folder=<absolute_path>
* Returns JSON array of image file paths found in the given folder (recursive).
*/
app.get('/api/images', (req, res) => {
const folderPath = req.query.folder;
if (!folderPath) {
return res.status(400).json({ error: 'Missing "folder" query parameter' });
}
// Resolve to absolute path
const resolved = path.resolve(folderPath);
if (process.env.APP_RUNTIME === 'electron') {
if (!isPathAllowedInRegisteredDecks(resolved)) {
return res.status(403).json({ error: 'Access denied: folder is not a registered deck folder' });
}
}
// Check if the directory exists
if (!fs.existsSync(resolved)) {
return res.status(404).json({ error: `Folder not found: ${resolved}` });
}
const stat = fs.statSync(resolved);
if (!stat.isDirectory()) {
return res.status(400).json({ error: `Not a directory: ${resolved}` });
}
const images = scanForImages(resolved);
// Return relative display names along with resilient content-hash IDs
const result = images.map(imgPath => {
const hash = computeFileHash(imgPath);
return {
id: hash,
hash: hash,
path: imgPath,
name: path.relative(resolved, imgPath),
folder: resolved
};
});
res.json(result);
});
/**
* GET /api/deck-meta?folder=<absolute_path>
* Lightweight deck summary used by the home screen:
* total image count + up to 3 random cover image paths.
* Scan results are cached briefly so re-renders stay instant.
*/
const metaCache = new Map();
const META_TTL_MS = 60 * 1000;
app.get('/api/deck-meta', (req, res) => {
const folderPath = req.query.folder;
if (!folderPath) {
return res.status(400).json({ error: 'Missing "folder" query parameter' });
}
const resolved = path.resolve(folderPath);
if (process.env.APP_RUNTIME === 'electron') {
if (!isPathAllowedInRegisteredDecks(resolved)) {
return res.status(403).json({ error: 'Access denied: folder is not a registered deck folder' });
}
}
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
return res.status(404).json({ error: `Folder not found: ${resolved}` });
}
let cached = metaCache.get(resolved);
if (!cached || Date.now() - cached.time > META_TTL_MS) {
cached = { time: Date.now(), images: scanForImages(resolved) };
metaCache.set(resolved, cached);
}
// Pick up to 3 distinct random covers
const pool = [...cached.images];
const covers = [];
while (covers.length < 3 && pool.length > 0) {
const idx = Math.floor(Math.random() * pool.length);
covers.push(pool.splice(idx, 1)[0]);
}
res.json({ total: cached.images.length, covers });
});
/**
* GET /api/image?path=<absolute_path>&hash=<content_hash>
* Serves a single image file from disk. Supports both file paths and content hashes.
*/
app.get('/api/image', (req, res) => {
let target = req.query.path || req.query.hash;
if (!target) {
return res.status(400).json({ error: 'Missing "path" or "hash" query parameter' });
}
// If a content hash was requested (starts with 'ch_'), resolve from hashToPathMap
if (target.startsWith('ch_') && hashToPathMap.has(target)) {
target = hashToPathMap.get(target);
}
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.tif', '.tiff', '.svg'];
const ext = path.extname(target).toLowerCase();
if (!allowedExtensions.includes(ext)) {
return res.status(415).json({ error: `Unsupported media type: ${ext || 'none'}` });
}
const resolved = path.resolve(target);
let realPath;
try {
realPath = fs.realpathSync(resolved);
} catch (err) {
return res.status(404).json({ error: `File not found: ${resolved}` });
}
const realExt = path.extname(realPath).toLowerCase();
if (!allowedExtensions.includes(realExt)) {
return res.status(415).json({ error: `Unsupported media type: ${realExt || 'none'}` });
}
// When APP_RUNTIME === 'electron', require resolved real path to be inside a folder in getRegisteredDeckFolders() or inside USERDATA_DIR
if (process.env.APP_RUNTIME === 'electron') {
let realUserDataDir;
try {
realUserDataDir = fs.realpathSync(USERDATA_DIR);
} catch (e) {
realUserDataDir = path.resolve(USERDATA_DIR);
}
let realLocalUserdata;
try {
realLocalUserdata = fs.realpathSync(path.join(__dirname, 'userdata'));
} catch (e) {
realLocalUserdata = path.resolve(path.join(__dirname, 'userdata'));
}
const isAllowed = isPathInside(realPath, realUserDataDir) ||
isPathInside(realPath, realLocalUserdata) ||
isPathAllowedInRegisteredDecks(realPath);
if (!isAllowed) {
return res.status(403).json({ error: 'Access denied: path is not inside a registered deck folder or userdata directory' });
}
}
// Determine MIME type
const mimeTypes = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.svg': 'image/svg+xml',
'.tiff': 'image/tiff',
'.tif': 'image/tiff'
};
const contentType = mimeTypes[realExt] || 'application/octet-stream';
res.setHeader('Content-Type', contentType);
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
try {
const fileStat = fs.statSync(realPath);
const etag = `"${fileStat.size.toString(16)}-${Math.floor(fileStat.mtimeMs).toString(16)}"`;
if (req.headers['if-none-match'] === etag) {
return res.status(304).end();
}
res.setHeader('ETag', etag);
} catch (e) { }
if (req.query.hash) {
res.setHeader('Cache-Control', 'public, max-age=86400');
} else {
res.setHeader('Cache-Control', 'public, max-age=604800, stale-while-revalidate=86400');
}
res.sendFile(realPath);
});
/**
* Backup rotation & state writing utilities:
* - Rotates srs_state.json.bak1..bak5 (shifted on write, throttled to at most once per 10 minutes)
* - Keeps one daily snapshot for the last 7 days in userdata/backups/
* - Logs all rotations
*/
let stateWriteQueue = Promise.resolve();
let lastRotationTime = 0;
let customClock = null;
const ROTATION_WINDOW_MS = 10 * 60 * 1000; // 10 minutes default
const BACKUP_COUNT = 5;
function setRotationClock(clockFn) {
customClock = clockFn;
}
function resetRotationState() {
lastRotationTime = 0;
customClock = null;
}
function getNow(options = {}) {
if (typeof options.now === 'number') return options.now;
if (typeof options.clock === 'function') return options.clock();
if (typeof customClock === 'function') return customClock();
return Date.now();
}
function getLocalDateString(dateInput = new Date()) {
const d = dateInput instanceof Date ? dateInput : new Date(dateInput);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function pruneDailySnapshots(backupsDir, maxDays = 7) {
try {
if (!fs.existsSync(backupsDir)) return;
const files = fs.readdirSync(backupsDir)
.filter(f => /^srs_state_\d{4}-\d{2}-\d{2}\.json$/.test(f))
.sort(); // chronological sort for YYYY-MM-DD
if (files.length > maxDays) {
const toDelete = files.slice(0, files.length - maxDays);
for (const f of toDelete) {
try {
fs.unlinkSync(path.join(backupsDir, f));
console.log(`[Sync] Pruned old daily snapshot: ${f}`);
} catch (e) {}
}
}
} catch (err) {
console.warn('[Sync] Error pruning daily snapshots:', err.message);
}
}
function rotateBackups(options = {}) {
if (!fs.existsSync(STATE_FILE)) return;
const now = getNow(options);
let lastMtime = 0;
const bak1 = `${STATE_FILE}.bak1`;
if (fs.existsSync(bak1)) {
try {
lastMtime = fs.statSync(bak1).mtimeMs;
} catch (e) {}
}
const lastTime = Math.max(lastRotationTime, lastMtime);
const minInterval = options.minRotationIntervalMs !== undefined
? options.minRotationIntervalMs
: (process.env.SYNC_ROTATION_INTERVAL_MS !== undefined ? parseInt(process.env.SYNC_ROTATION_INTERVAL_MS, 10) : ROTATION_WINDOW_MS);
const shouldRotate = options.forceRotation || (now - lastTime >= minInterval);
if (!shouldRotate) {
return;
}
try {
// 1. Shift bak1..bak5
const bak5 = `${STATE_FILE}.bak5`;
if (fs.existsSync(bak5)) {
try { fs.unlinkSync(bak5); } catch (e) {}
}
for (let i = BACKUP_COUNT - 1; i >= 1; i--) {
const src = `${STATE_FILE}.bak${i}`;
const dest = `${STATE_FILE}.bak${i + 1}`;
if (fs.existsSync(src)) {
try {
fs.renameSync(src, dest);
} catch (err) {
console.warn(`[Sync] Error shifting backup ${src} to ${dest}:`, err.message);
}
}
}
// Copy current STATE_FILE to bak1
fs.copyFileSync(STATE_FILE, bak1);
lastRotationTime = now;
if (options.clock || options.now || customClock) {
try {
fs.utimesSync(bak1, new Date(now), new Date(now));
} catch (e) {}
}
console.log(`[Sync] Rotated backups: ${path.basename(STATE_FILE)} -> .bak1 (holding up to .bak${BACKUP_COUNT})`);
} catch (err) {
console.warn('[Sync] Failed during backup rotation:', err.message);
}
}
function createDailySnapshot(options = {}) {
try {
if (!fs.existsSync(BACKUPS_DIR)) {
fs.mkdirSync(BACKUPS_DIR, { recursive: true });
}
if (!fs.existsSync(STATE_FILE)) return;
const now = getNow(options);
const todayStr = getLocalDateString(new Date(now));
const dailySnapshotPath = path.join(BACKUPS_DIR, `srs_state_${todayStr}.json`);
// Only create if today's snapshot doesn't exist yet
if (!fs.existsSync(dailySnapshotPath)) {
// Taken from the new state (STATE_FILE was just atomically replaced with new state)
fs.copyFileSync(STATE_FILE, dailySnapshotPath);
console.log(`[Sync] Created daily snapshot: ${path.basename(dailySnapshotPath)}`);
}
// Prune daily snapshots older than 7 days
pruneDailySnapshots(BACKUPS_DIR, 7);
} catch (err) {
console.warn('[Sync] Failed creating daily snapshot:', err.message);
}
}
function getBackupCandidates() {
const candidates = [];
// 1. srs_state.json.bak1..bak5
for (let i = 1; i <= BACKUP_COUNT; i++) {
candidates.push(`${STATE_FILE}.bak${i}`);
}
// 2. Legacy srs_state.json.bak
candidates.push(`${STATE_FILE}.bak`);
// 3. Daily snapshots in userdata/backups/ (newest first)
if (fs.existsSync(BACKUPS_DIR)) {
try {
const dailyFiles = fs.readdirSync(BACKUPS_DIR)
.filter(f => /^srs_state_\d{4}-\d{2}-\d{2}\.json$/.test(f))
.sort()
.reverse();
for (const f of dailyFiles) {
candidates.push(path.join(BACKUPS_DIR, f));
}