Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
3569 lines (3281 loc) · 142 KB
/
Copy pathserver.js
File metadata and controls
3569 lines (3281 loc) · 142 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 path = require('path');
const fs = require('fs');
const os = require('os');
const multer = require('multer');
const crypto = require('crypto');
const { spawn } = require('child_process');
const { pipeline } = require('stream/promises');
const Tesseract = require('tesseract.js');
// Start the log file before anything else can fail, so a startup error is recorded too.
const { installLogFile, readRecentLog } = require('./lib/log-file');
const LOG_FILE = installLogFile(process.env.STUDIO_DATA_DIR
? path.resolve(process.env.STUDIO_DATA_DIR)
: path.join(__dirname, 'data'));
const dbApi = require('./db');
if (dbApi.catalogLock) {
require('./lib/move-catalog').listen({
port: Number(process.env.PORT || 3847),
message: dbApi.catalogLock,
dbPath: dbApi.DB_PATH,
dataDir: dbApi.DATA_DIR
});
return;
}
const {
db, DB_PATH, DATA_DIR, UPLOADS_DIR, initSchema,
enrichItem, enrichItems, setItemTags, sanitizeItemInput, getTagsForItem, getAssemblyTotals, itemUploadDir,
removeItemUploadDirs, resolveUploadPath, removeUploadFile, DEFAULT_CATEGORIES, DEFAULT_LOCATIONS,
ensureBrand, getBrandsWithCounts, syncBrandsFromItems, brandSlug, LOGOS_DIR,
isFormerStatus, ownedStatusSql, cascadeFormerStatus, restoreCascadedChildren,
recordItemChanges, recordReplacementValue, getValueEvents, getItemAudit,
addMaintenanceEntry, deleteMaintenanceEntry,
getActiveLoans, getRecentLoanHistory, checkoutItem, returnLoan, deleteLoanEntry,
getRacks, getSignalChains,
getFloorplans, getFloorplan, createFloorplan, updateFloorplanImage, clearFloorplanFloorImage,
updateFloorplanFloorView, updateFloorplanGeometry,
setFloorplanItems, updateFloorplanItems, deleteFloorplan, getItemMapPlacement, saveItemWallCutout, clearItemWallCutout, wallPhotoDir,
floorplanWallPhotosDir, updateFloorplanWallPhoto, updateFloorplanWallCalibration, resolveWallRehang,
SOFTWARE_CATEGORIES, LICENSE_TYPES, ACTIVATION_METHODS, PLUGIN_FORMATS,
softwareLicenseDir, getAllSoftware, getSoftware, createSoftware, updateSoftware,
updateSoftwareScreenshot, clearSoftwareScreenshot, deleteSoftware,
getSoftwareRenewals, getSoftwareTotals
} = require('./db');
const { parseLookupCode } = require('./lib/lookup-code');
const { summarizeCompleteness, computeItemCompleteness } = require('./lib/completeness');
const { parseCsv, mapRowToItem } = require('./lib/csv-import');
const { toCsv } = require('./lib/csv-export');
const { instrumentProfiles } = require('./lib/instrument-profiles');
const {
readSettings, writeSettings, commitCatalogEncryption, regenerateGuestToken, isValidGuestToken,
setOwnerPin, verifyOwnerPin, createOwnerSessionToken, revokeOwnerSessionToken,
isValidOwnerSessionToken, itemScanToken, isValidItemScanToken, ownerPinConfigured
} = require('./lib/studio-settings');
const { indexManualAttachment, searchManuals, pdfParseAvailable } = require('./lib/pdf-index');
const { findGearDocuments, DOCUMENT_KINDS } = require('./lib/manual-finder');
const { fetchBrandLogoFromWeb, fetchAllInventoryBrandLogos } = require('./lib/fetch-brand-logo');
const { getCurrentVersion, checkForUpdate } = require('./lib/version');
const {
validateBackupDir, backupDiskWarning, warmBackupDiskInfo, writeFolderBackup, writeRecoveryCopy, createDownloadZipStream,
openBackupZip, readZipEntry, verifyBackupZip, extractZipPrefixes, removeDecryptedLeftovers,
RECOVERY_NAME, RECOVERY_PREVIOUS_NAME
} = require('./lib/folder-backup');
const { isPlainSqlite } = require('./lib/open-database');
const { getDataKey } = require('./lib/data-key');
const { safeFetch } = require('./lib/safe-fetch');
const { isLocalRequest, hostGuard, crossSiteGuard } = require('./lib/request-guard');
const QRCode = require('qrcode');
const PORT = process.env.PORT || 3847;
const MAX_FILE_SIZE = 100 * 1024 * 1024;
const MAX_MANUAL_DOWNLOAD_SIZE = 50 * 1024 * 1024;
const FLOORPLANS_DIR = path.join(UPLOADS_DIR, 'floorplans');
const MANUAL_INBOX_DIR = path.join(DATA_DIR, 'manual-inbox');
const OCR_DATA_DIR = path.join(__dirname, 'ocr');
const OCR_CACHE_DIR = path.join(DATA_DIR, 'ocr-cache');
const LOGIN_ATTEMPT_LIMIT = 5;
const LOGIN_WINDOW_MS = 15 * 60 * 1000;
const DEFAULT_BACKUP_KEEP = 7;
process.on('unhandledRejection', (reason) => {
console.error(' Unexpected error (the server keeps running):', reason);
});
initSchema();
try {
readSettings();
} catch (err) {
// Keep serving the local catalog; settings-dependent requests will report this error.
console.error(`\n ${err.message}\n`);
}
if (!fs.existsSync(FLOORPLANS_DIR)) fs.mkdirSync(FLOORPLANS_DIR, { recursive: true });
if (!fs.existsSync(MANUAL_INBOX_DIR)) fs.mkdirSync(MANUAL_INBOX_DIR, { recursive: true });
if (!fs.existsSync(OCR_CACHE_DIR)) fs.mkdirSync(OCR_CACHE_DIR, { recursive: true });
const IMAGE_EXTENSIONS = new Map([
['image/jpeg', '.jpg'],
['image/png', '.png'],
['image/webp', '.webp'],
['image/gif', '.gif'],
['image/heic', '.heic'],
['image/heif', '.heif']
]);
/**
* Tags from a request: a list of names, or one comma-separated string.
* Anything else is refused rather than stored as nonsense.
*/
function tagListFromInput(value) {
if (value === undefined || value === null || value === '') return [];
const list = typeof value === 'string' ? value.split(',') : value;
if (!Array.isArray(list) || list.some(tag => typeof tag !== 'string' && typeof tag !== 'number')) {
throw clientError('Tags must be a list of words');
}
const names = [...new Set(list.map(tag => String(tag).trim().slice(0, 60)).filter(Boolean))];
if (names.length > 50) throw clientError('An item can have at most 50 tags');
return names;
}
/** Time plus randomness for stored file names, so two uploads in the same millisecond can't collide. */
function uniqueStamp() {
return `${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
}
/** An error caused by the request itself; the error handler answers 400 with its message. */
function clientError(message, status = 400) {
return Object.assign(new Error(message), { status, expose: true });
}
function imageExtension(file, { allowSvg = false } = {}) {
const mime = String(file?.mimetype || '').toLowerCase().split(';')[0];
if (allowSvg && mime === 'image/svg+xml') return '.svg';
return IMAGE_EXTENSIONS.get(mime) || '';
}
function isAcceptedImage(file, options) {
return !!imageExtension(file, options);
}
const softwareScreenshotUpload = multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: multer.diskStorage({
destination: (req, _file, cb) => cb(null, softwareLicenseDir(req.params.id)),
filename: (_req, file, cb) => {
const ext = imageExtension(file) || '.jpg';
cb(null, `screenshot-${uniqueStamp()}${ext}`);
}
}),
limits: { fileSize: 8 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
cb(null, isAcceptedImage(file));
}
});
syncBrandsFromItems();
function brandLogoLookupsEnabled() {
try { return !!readSettings().brandLogoLookups; } catch { return false; }
}
// DYMO publishes its Connect framework from this host. It is a third party, so
// the page is only allowed to load it once the owner turns label printing on.
const DYMO_SCRIPT_ORIGIN = 'https://qajavascriptsdktests.azurewebsites.net';
function dymoLabelPrintingEnabled() {
try { return !!readSettings().dymoLabelPrinting; } catch { return false; }
}
// Give brands without a logo one at startup. Online lookups only when the owner
// has turned them on; otherwise a local text badge, and nothing leaves this computer.
setTimeout(() => {
const offline = !brandLogoLookupsEnabled();
fetchAllInventoryBrandLogos({ offline }).then(r => {
if (r.fetched > 0) console.log(` Brand logos: ${offline ? 'generated' : 'fetched'} ${r.fetched}, skipped ${r.skipped}, failed ${r.failed}`);
}).catch(err => console.warn(' Brand logo batch:', err.message));
}, 2500);
const app = express();
app.disable('x-powered-by');
// Express 4 does not pass a rejected promise from an async route to the error
// handler, and on Node 22 an unhandled rejection stops the whole server. Every
// route and middleware registered on `app` goes through this wrapper, so a
// failing async route answers with an error instead of taking the app down.
function forwardAsyncErrors(handler) {
if (Array.isArray(handler)) return handler.map(forwardAsyncErrors);
// Leave error handlers (4 arguments), routers and sub-apps as they are.
if (typeof handler !== 'function' || handler.length > 3 || handler.handle || handler.stack) return handler;
return function asyncSafe(req, res, next) {
const result = handler(req, res, next);
if (result && typeof result.catch === 'function') result.catch(next);
};
}
for (const method of ['get', 'post', 'put', 'patch', 'delete', 'all', 'use']) {
const register = app[method].bind(app);
app[method] = (...args) => register(...args.map(forwardAsyncErrors));
}
// Refuse public DNS names in Host (DNS rebinding) before anything else runs.
app.use(hostGuard);
// Reject writes sent by another site, including from a browser on this computer.
app.use(crossSiteGuard);
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('Referrer-Policy', 'no-referrer');
res.setHeader('Permissions-Policy', 'camera=(self)');
// script-src has no 'unsafe-inline': injected <script>, onerror="…" and javascript: links
// cannot run even if some text slips through unescaped. The DYMO Connect framework is
// the one third-party script, and it is only allowed once the owner has turned on
// DYMO label printing — every other install runs on 'self' alone.
const scriptSrc = dymoLabelPrintingEnabled() ? `'self' ${DYMO_SCRIPT_ORIGIN}` : "'self'";
res.setHeader('Content-Security-Policy', [
`script-src ${scriptSrc}`,
"frame-ancestors 'self'",
"base-uri 'self'",
"object-src 'none'",
"form-action 'self'"
].join('; '));
next();
});
// Every :id in this API is a positive integer row id. Validate it before any
// route middleware (including multer, which builds folder paths from it) runs.
app.param('id', (req, res, next, value) => {
if (/^[1-9]\d{0,15}$/.test(String(value))) return next();
if (req.path.startsWith('/api/')) return res.status(404).json({ error: 'Not found' });
return res.status(404).type('text/plain').send('Not found');
});
app.param('edge', (req, res, next, value) => {
if (/^\d{1,2}$/.test(String(value)) && Number(value) <= 47) return next();
return res.status(400).json({ error: 'Invalid wall' });
});
/** Stop before an upload is written when the target record does not exist. */
function requireRow(table, message) {
const stmt = () => db.prepare(`SELECT id FROM ${table} WHERE id = ?`);
return (req, res, next) => {
if (stmt().get(req.params.id)) return next();
return res.status(404).json({ error: message });
};
}
const requireItem = requireRow('items', 'Item not found');
const requireFloorplan = requireRow('floorplans', 'Floorplan not found');
const requireSoftware = requireRow('software_licenses', 'Software license not found');
// One value per query parameter: ?brand=a&brand=b arrives as an array, which
// every endpoint here would otherwise pass straight into SQL or a comparison.
app.set('query parser', 'simple');
app.use((req, _res, next) => {
for (const [key, value] of Object.entries(req.query)) {
if (Array.isArray(value)) req.query[key] = String(value[0] ?? '');
}
next();
});
app.use(express.json({ limit: '10mb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', (req, res, next) => {
res.setHeader('Cache-Control', 'private, max-age=604800');
if (isLocalRequest(req) || isValidOwnerToken(ownerTokenFromRequest(req))) return next();
const isLogo = req.path.startsWith('/logos/');
// Guest links show gear photos and brand logos, never receipts or license files.
if (req.query.guest_token && (isLogo || req.path.startsWith('/photos/'))
&& isValidGuestToken(req.query.guest_token)) return next();
// A QR label unlocks the files its own item page shows: photos, manuals, software.
// The item is always taken from the file path, never from the query string.
const match = req.path.match(/^\/(photos|manuals|software)\/(\d+)\//);
const itemId = match ? match[2] : (isLogo ? req.query.item : '');
if (itemId && isValidItemScanToken(itemId, req.query.access)) return next();
return res.status(401).json({ error: 'Authentication or a valid share link is required.' });
}, express.static(UPLOADS_DIR, {
maxAge: '7d',
dotfiles: 'deny',
setHeaders: (res, filePath) => {
const ext = path.extname(filePath).toLowerCase();
if (ext === '.svg') res.setHeader('Content-Security-Policy', 'sandbox');
if (!['.jpg', '.jpeg', '.png', '.webp', '.gif', '.heic', '.heif', '.svg', '.pdf'].includes(ext)) {
res.setHeader('Content-Disposition', `attachment; filename="${path.basename(filePath).replace(/["\r\n]/g, '_')}"`);
}
}
}));
function safeFilename(name) {
return String(name).replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 200);
}
/** Keep a short alphanumeric extension (".exe", ".zip"); drop anything else. */
function plainExtension(name) {
const ext = path.extname(String(name || '')).toLowerCase();
return /^\.[a-z0-9]{1,12}$/.test(ext) ? ext : '';
}
function makeUploadStorage(type, options = {}) {
return multer.diskStorage({
destination: (req, _file, cb) => {
const itemId = req.params.id;
const { dir } = itemUploadDir(itemId, type);
cb(null, dir);
},
filename: (_req, file, cb) => {
const ext = typeof options.extension === 'function'
? options.extension(file)
: options.imageOnly
? imageExtension(file, { allowSvg: !!options.allowSvg })
: plainExtension(file.originalname);
cb(null, `${Date.now()}-${crypto.randomBytes(6).toString('hex')}${ext}`);
}
});
}
function createUploader(type, options = {}) {
return multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: makeUploadStorage(type, options),
limits: { fileSize: options.maxSize || MAX_FILE_SIZE },
fileFilter: (_req, file, cb) => {
if (options.filter) return options.filter(file, cb);
cb(null, true);
}
});
}
const photoUpload = createUploader('photo', {
maxSize: 25 * 1024 * 1024,
imageOnly: true,
filter: (file, cb) => {
if (isAcceptedImage(file)) cb(null, true);
else cb(clientError('Only image files allowed for photos'));
}
});
const manualUpload = createUploader('manual', {
maxSize: 50 * 1024 * 1024,
extension: (file) => ({
'application/pdf': '.pdf',
'application/msword': '.doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
'text/plain': '.txt'
})[file.mimetype] || imageExtension(file),
filter: (file, cb) => {
const ok = ['application/pdf', 'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'text/plain'].includes(file.mimetype) || isAcceptedImage(file);
cb(null, ok);
}
});
const receiptUpload = createUploader('receipt', {
maxSize: 25 * 1024 * 1024,
extension: (file) => file.mimetype === 'application/pdf' ? '.pdf' : imageExtension(file),
filter: (file, cb) => {
const ok = file.mimetype === 'application/pdf' || isAcceptedImage(file);
cb(null, ok);
}
});
const softwareUpload = createUploader('software', { maxSize: MAX_FILE_SIZE });
const wallPhotoUpload = multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: multer.diskStorage({
destination: (req, _file, cb) => cb(null, wallPhotoDir(req.params.id)),
filename: (_req, file, cb) => {
const ext = imageExtension(file) || '.png';
cb(null, `wall-${uniqueStamp()}${ext}`);
}
}),
limits: { fileSize: 12 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
cb(null, isAcceptedImage(file));
}
});
const wallBackgroundUpload = multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: multer.diskStorage({
destination: (req, _file, cb) => cb(null, floorplanWallPhotosDir(req.params.id)),
filename: (req, file, cb) => {
const ext = imageExtension(file) || '.jpg';
cb(null, `wall-${req.params.edge}-${uniqueStamp()}${ext}`);
}
}),
limits: { fileSize: 20 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
cb(null, isAcceptedImage(file));
}
});
const floorplanUpload = multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: multer.diskStorage({
destination: (_req, _file, cb) => cb(null, FLOORPLANS_DIR),
filename: (req, file, cb) => {
const ext = imageExtension(file) || '.jpg';
cb(null, `fp-${req.params.id}-${uniqueStamp()}${ext}`);
}
}),
limits: { fileSize: 15 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
cb(null, isAcceptedImage(file));
}
});
const logoUpload = multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: multer.diskStorage({
destination: (_req, _file, cb) => cb(null, LOGOS_DIR),
filename: (req, file, cb) => {
const name = req.body.name || req.params.name || 'custom';
const slug = brandSlug(name);
const ext = imageExtension(file, { allowSvg: true }) || '.png';
cb(null, `${slug}${ext}`);
}
}),
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
if (isAcceptedImage(file, { allowSvg: true })) cb(null, true);
else cb(clientError('Logo must be an image (PNG, SVG, WebP)'));
}
});
const BACKUP_INCOMING_DIR = path.join(DATA_DIR, 'backups', '.incoming');
if (!fs.existsSync(BACKUP_INCOMING_DIR)) fs.mkdirSync(BACKUP_INCOMING_DIR, { recursive: true });
/**
* Backups read the catalog and its files; restores, imports and encryption
* replace them. Any number of backups can run together, but a replacing job
* runs alone, so a backup never captures a half-restored catalog and a restore
* never swaps files out from under a backup. Returns a release function.
*/
const maintenance = { shared: 0, exclusive: '' };
function beginMaintenance(kind, label) {
if (maintenance.exclusive) {
throw clientError(`${maintenance.exclusive} is in progress. Try again when it finishes.`, 409);
}
if (kind === 'exclusive' && maintenance.shared > 0) {
throw clientError('A backup is running. Try again when it finishes.', 409);
}
if (kind === 'exclusive') maintenance.exclusive = label;
else maintenance.shared++;
let released = false;
return () => {
if (released) return;
released = true;
if (kind === 'exclusive') maintenance.exclusive = '';
else maintenance.shared--;
};
}
/** Run a route under the maintenance lock; answers 409 while a conflicting job runs. */
function withMaintenance(kind, label, handler) {
return async (req, res, next) => {
let release;
try {
release = beginMaintenance(kind, label);
} catch (err) {
return res.status(err.status).json({ error: err.message });
}
try {
return await handler(req, res, next);
} finally {
release();
}
};
}
/** Temporary files a crash during an earlier restore could leave behind. */
function sweepRestoreLeftovers() {
for (const name of safeReaddir(BACKUP_INCOMING_DIR)) {
if (/^restore-.*\.zip$/.test(name)) fs.rmSync(path.join(BACKUP_INCOMING_DIR, name), { force: true });
}
for (const name of safeReaddir(DATA_DIR)) {
if (name.startsWith('.restore-stage-')) {
fs.rmSync(path.join(DATA_DIR, name), { recursive: true, force: true });
} else if (name.startsWith('.restore-previous-')) {
// Could be the only copy of files from before an interrupted restore: keep it.
console.warn(` Found ${path.join(DATA_DIR, name)} from an interrupted restore. Check it before deleting it.`);
}
}
}
function safeReaddir(dir) {
try { return fs.readdirSync(dir); } catch { return []; }
}
const backupUpload = multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: multer.diskStorage({
destination: (_req, _file, cb) => cb(null, BACKUP_INCOMING_DIR),
filename: (_req, _file, cb) => {
cb(null, `restore-${Date.now()}-${crypto.randomBytes(8).toString('hex')}.zip`);
}
}),
// Restores stream from disk, so the only real limit is free space. Allow large studios.
limits: { fileSize: 64 * 1024 * 1024 * 1024 }
});
removeDecryptedLeftovers(BACKUP_INCOMING_DIR);
try {
sweepRestoreLeftovers();
} catch (err) {
console.warn(' Could not clean up after an earlier restore:', err.message);
}
const labelScanUpload = multer({
// Browsers send UTF-8 file names; without this, "Röde.pdf" is stored as "Röde.pdf".
defParamCharset: 'utf8',
storage: multer.memoryStorage(),
limits: { fileSize: 12 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
cb(null, isAcceptedImage(file));
}
});
const ATTACHMENT_FOLDERS = { photo: 'photos', manual: 'manuals', document: 'manuals', software: 'software', receipt: 'receipts' };
/**
* Record files that were just written to disk as attachments, in one
* transaction. If that fails (the item was deleted meanwhile, say), the files
* are removed again, so uploads/ never keeps files that no record points to.
* Each file needs { filename, originalname, mimetype, path }.
*/
function recordUploadedFiles(itemId, files, typeFor, extraFor = () => ({})) {
try {
return db.transaction(() => files.map(file => insertAttachment(itemId, file, typeFor(file), extraFor(file))))();
} catch (err) {
for (const file of files) {
try { if (file.path) fs.rmSync(file.path, { force: true }); } catch { /* best effort */ }
}
if (/FOREIGN KEY/i.test(err.message)) throw clientError('That item was deleted while the file was uploading.', 404);
throw err;
}
}
/** Delete an attachment's row and search entry, then its file unless another record still uses it. */
function deleteAttachment(att) {
db.transaction(() => {
db.prepare('DELETE FROM manual_fts WHERE attachment_id = ?').run(att.id);
db.prepare('DELETE FROM attachments WHERE id = ?').run(att.id);
})();
const relativePath = att.relative_path || att.filename;
const stillUsed = db.prepare('SELECT 1 FROM attachments WHERE relative_path = ? LIMIT 1').get(relativePath);
if (stillUsed) return;
try {
removeUploadFile(relativePath);
} catch (err) {
console.warn(` Could not remove ${relativePath}: ${err.message}`);
}
}
function insertAttachment(itemId, file, type, extra = {}) {
const sub = ATTACHMENT_FOLDERS[type] || 'manuals';
const relativePath = `${sub}/${itemId}/${file.filename}`;
const result = db.prepare(`
INSERT INTO attachments (
item_id, filename, original_name, relative_path, mime_type, type,
version, description, source_url, metadata
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
itemId, file.filename, file.originalname, relativePath, file.mimetype, type,
extra.version || '', extra.description || '', extra.source_url || '',
JSON.stringify(extra.metadata || {})
);
return {
id: result.lastInsertRowid,
filename: file.filename,
original_name: file.originalname,
relative_path: relativePath,
mime_type: file.mimetype,
type,
version: extra.version || '',
description: extra.description || '',
source_url: extra.source_url || ''
};
}
/** A number from the query string; a value that isn't one is a 400, not an empty list. */
function queryNumber(value, name, { integer = false } = {}) {
const n = Number(String(value).trim());
if (!Number.isFinite(n) || (integer && !Number.isInteger(n))) throw clientError(`${name} must be a number`);
return n;
}
function buildSearchQuery(params) {
const conditions = [];
const values = {};
if (params.q) {
conditions.push(`(
i.name LIKE @q OR i.common_name LIKE @q OR i.brand LIKE @q OR
i.model LIKE @q OR i.serial_number LIKE @q OR i.description LIKE @q OR
i.location LIKE @q OR i.category LIKE @q OR i.instrument_type LIKE @q OR
i.instrument_specs_json LIKE @q OR i.replacement_value_note LIKE @q OR
EXISTS (SELECT 1 FROM item_tags it JOIN tags t ON t.id = it.tag_id
WHERE it.item_id = i.id AND t.name LIKE @q)
)`);
values.q = `%${params.q}%`;
}
if (params.brand) {
conditions.push('i.brand = @brand COLLATE NOCASE');
values.brand = params.brand;
}
if (params.category) { conditions.push('i.category = @category'); values.category = params.category; }
if (params.location) { conditions.push('i.location = @location'); values.location = params.location; }
if (params.condition) { conditions.push('i.condition = @condition'); values.condition = params.condition; }
if (params.tag) {
conditions.push(`EXISTS (
SELECT 1 FROM item_tags it JOIN tags t ON t.id = it.tag_id
WHERE it.item_id = i.id AND t.name = @tag COLLATE NOCASE
)`);
values.tag = params.tag;
}
if (params.min_value) {
conditions.push('i.replacement_value >= @min_value');
values.min_value = queryNumber(params.min_value, 'min_value');
}
if (params.max_value) {
conditions.push('i.replacement_value <= @max_value');
values.max_value = queryNumber(params.max_value, 'max_value');
}
if (params.on_policy === '1') {
conditions.push('i.on_insurance_policy = 1');
}
if (params.include_accessories !== '1' && params.include_accessories !== 'true') {
conditions.push('(i.parent_item_id IS NULL)');
}
if (params.parent_id) {
conditions.push('i.parent_item_id = @parent_id');
values.parent_id = queryNumber(params.parent_id, 'parent_id', { integer: true });
}
if (params.include_former !== '1' && params.include_former !== 'true' && !params.parent_id) {
conditions.push(ownedStatusSql('i.studio_status'));
}
const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
const sortMap = {
name: 'i.name ASC', name_desc: 'i.name DESC',
value: 'i.replacement_value DESC', value_asc: 'i.replacement_value ASC',
purchase_date: 'i.purchase_date DESC', purchase_date_asc: 'i.purchase_date ASC',
category: 'i.category ASC, i.name ASC', location: 'i.location ASC, i.name ASC',
updated: 'i.updated_at DESC'
};
const orderBy = sortMap[params.sort] || 'i.name ASC';
return { where, values, orderBy };
}
function isValidDownloadUrl(urlStr) {
try {
const u = new URL(urlStr);
return u.protocol === 'http:' || u.protocol === 'https:';
} catch { return false; }
}
function filenameFromResponse(url, headers) {
const cd = headers.get('content-disposition') || '';
const match = cd.match(/filename\*?=(?:UTF-8''|")?([^";]+)/i);
if (match) {
const raw = match[1].replace(/"/g, '');
let decoded = raw;
try { decoded = decodeURIComponent(raw); } catch { /* malformed %-escape: keep it as sent */ }
return safeFilename(decoded);
}
const urlPath = new URL(url).pathname;
const base = path.basename(urlPath);
return safeFilename(base || 'download.bin');
}
function extensionForMime(mime) {
const map = {
'application/pdf': '.pdf',
'application/x-pdf': '.pdf',
'application/msword': '.doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
'text/plain': '.txt',
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
'image/gif': '.gif',
'image/svg+xml': '.svg'
};
return map[String(mime || '').toLowerCase()] || '';
}
function normalizeDownloadName(name, mime, fallback = 'manual.pdf') {
const clean = safeFilename(name || fallback) || fallback;
const ext = path.extname(clean);
const inferred = extensionForMime(mime);
if (!ext && inferred) return `${clean}${inferred}`;
if (clean === 'download.bin' && inferred) return `manual${inferred}`;
return clean;
}
function isManualDownloadAllowed(mime, filename) {
const type = String(mime || '').toLowerCase();
const ext = path.extname(String(filename || '')).toLowerCase();
if (type.includes('text/html')) return false;
if (type.startsWith('image/')) return true;
if (['.pdf', '.doc', '.docx', '.txt'].includes(ext)) return true;
return [
'application/pdf',
'application/x-pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'text/plain',
'application/octet-stream',
'binary/octet-stream',
'application/download',
'application/force-download'
].includes(type);
}
function mimeForManualFile(filename) {
const ext = path.extname(String(filename || '')).toLowerCase();
return {
'.pdf': 'application/pdf',
'.doc': 'application/msword',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.txt': 'text/plain',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.svg': 'image/svg+xml'
}[ext] || 'application/octet-stream';
}
function ensureManualInboxDir() {
if (!fs.existsSync(MANUAL_INBOX_DIR)) fs.mkdirSync(MANUAL_INBOX_DIR, { recursive: true });
return MANUAL_INBOX_DIR;
}
function manualInboxFiles() {
ensureManualInboxDir();
return fs.readdirSync(MANUAL_INBOX_DIR, { withFileTypes: true })
.filter(entry => entry.isFile())
.map(entry => {
const fullPath = path.join(MANUAL_INBOX_DIR, entry.name);
const stat = fs.statSync(fullPath);
return {
name: entry.name,
size: stat.size,
modified_at: stat.mtime.toISOString(),
mime_type: mimeForManualFile(entry.name),
allowed: isManualDownloadAllowed(mimeForManualFile(entry.name), entry.name)
};
})
.filter(file => file.allowed)
.sort((a, b) => new Date(b.modified_at) - new Date(a.modified_at));
}
function openFolder(folderPath) {
const target = path.resolve(folderPath);
if (!fs.existsSync(target)) fs.mkdirSync(target, { recursive: true });
const platform = process.platform;
const command = platform === 'win32' ? 'explorer.exe' : platform === 'darwin' ? 'open' : 'xdg-open';
const child = spawn(command, [target], { detached: true, stdio: 'ignore', windowsHide: true });
child.unref();
}
function moveFileIntoPlace(src, dest) {
try {
fs.renameSync(src, dest);
} catch {
fs.copyFileSync(src, dest);
fs.unlinkSync(src);
}
}
function decodeHtmlEntities(str = '') {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)))
.replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCharCode(parseInt(n, 16)));
}
function stripHtml(str = '') {
return decodeHtmlEntities(String(str).replace(/<[^>]*>/g, ' '))
.replace(/\s+/g, ' ')
.trim();
}
function directManualCandidate(url, mime = '') {
try {
const u = new URL(url);
const ext = path.extname(u.pathname).toLowerCase();
const allowedExt = ['.pdf', '.doc', '.docx', '.txt'];
return allowedExt.includes(ext) || String(mime).toLowerCase().includes('pdf');
} catch {
return false;
}
}
function extractManualLinksFromHtml(pageUrl, html) {
const candidates = [];
const seen = new Set();
const linkRe = /<a\b[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi;
let match;
while ((match = linkRe.exec(html)) && candidates.length < 20) {
const rawHref = decodeHtmlEntities(match[1]).trim();
if (!rawHref || rawHref.startsWith('#') || /^javascript:/i.test(rawHref) || /^mailto:/i.test(rawHref)) continue;
let url;
try { url = new URL(rawHref, pageUrl).href; } catch { continue; }
if (seen.has(url)) continue;
const label = stripHtml(match[2]);
const pathname = new URL(url).pathname.toLowerCase();
const likelyManual = pathname.endsWith('.pdf')
|| /manual|owner|user guide|guide|instructions|download/i.test(label)
|| /manual|owner|user[-_ ]?guide|instructions/i.test(pathname);
if (!likelyManual) continue;
seen.add(url);
candidates.push({
title: label || path.basename(new URL(url).pathname) || url,
url,
displayUrl: url.replace(/^https?:\/\//i, '').replace(/\/$/, ''),
isPdf: directManualCandidate(url)
});
}
return candidates;
}
const COMMON_GEAR_BRANDS = [
'Alesis', 'Akai', 'Allen & Heath', 'Ampeg', 'Arturia', 'Audient', 'Behringer',
'Boss', 'Casio', 'Crown', 'Denon', 'Digidesign', 'Elektron', 'Emu', 'Fender',
'Focusrite', 'Fostex', 'Fractal Audio', 'Hammond', 'Ibanez', 'IK Multimedia',
'Kemper', 'Korg', 'Line 6', 'Mackie', 'M-Audio', 'Moog', 'Native Instruments',
'Nord', 'Novation', 'Peavey', 'Pioneer', 'PreSonus', 'QSC', 'Roland', 'RME',
'Sennheiser', 'Shure', 'Solid State Logic', 'Steinberg', 'Tascam', 'TC Electronic',
'Universal Audio', 'Waldorf', 'Yamaha', 'Zoom'
];
function normalizedOcrLines(text) {
return String(text || '')
.replace(/\r/g, '\n')
.split('\n')
.map(line => line.replace(/\s+/g, ' ').trim())
.filter(Boolean);
}
function knownBrandNames() {
const fromDb = db.prepare(`
SELECT DISTINCT brand as name FROM items WHERE brand IS NOT NULL AND brand != ''
UNION
SELECT name FROM brands WHERE name IS NOT NULL AND name != ''
`).all().map(r => r.name);
return [...new Set([...fromDb, ...COMMON_GEAR_BRANDS].map(String).filter(Boolean))]
.sort((a, b) => b.length - a.length);
}
function findKnownBrand(lines) {
const text = ` ${lines.join(' ')} `.toLowerCase();
return knownBrandNames().find(brand => {
const escaped = String(brand).toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`(^|[^a-z0-9])${escaped}([^a-z0-9]|$)`, 'i').test(text);
}) || '';
}
function cleanLabelValue(value) {
return String(value || '')
.replace(/^[#:\-.\s]+/, '')
.replace(/[|]+/g, 'I')
.replace(/\s{2,}/g, ' ')
.trim()
.slice(0, 150);
}
function firstMatch(lines, patterns) {
for (const line of lines) {
for (const pattern of patterns) {
const match = line.match(pattern);
if (match?.[1]) return { value: cleanLabelValue(match[1]), line };
}
}
return { value: '', line: '' };
}
function parsePowerInfo(lines) {
const powerLines = lines.filter(line =>
/\b(input|output|power|adapter|adaptor|dc in|ac in|rating|rated)\b/i.test(line)
|| /\b\d+(?:\.\d+)?\s*(v|vdc|vac|a|ma)\b/i.test(line)
);
const source = powerLines.length ? powerLines : lines;
const voltageMatch = firstMatch(source, [
/\b(?:(?:dc\s*)?in(?:put)?[:\s-]*)?(\d+(?:\.\d+)?\s*(?:vdc|v\s*dc|v|vac|v\s*ac))(?:\b|[^a-z])/i,
/\b((?:ac|dc)\s*\d+(?:\.\d+)?\s*v)\b/i
]);
const currentMatch = firstMatch(source, [
/\b(\d+(?:\.\d+)?\s*(?:ma|mA|a|A))(?:\b|[^a-z])/,
/\bcurrent[:\s-]*(\d+(?:\.\d+)?\s*(?:ma|mA|a|A))/i
]);
const polarityLine = source.find(line => /center|centre|tip|polarity|negative|positive/i.test(line)) || '';
let polarity = '';
if (/center|centre|tip/i.test(polarityLine) && /neg/i.test(polarityLine)) polarity = 'center negative';
else if (/center|centre|tip/i.test(polarityLine) && /pos/i.test(polarityLine)) polarity = 'center positive';
else if (/negative/i.test(polarityLine)) polarity = 'negative';
else if (/positive/i.test(polarityLine)) polarity = 'positive';
const voltage = cleanLabelValue(voltageMatch.value || (voltageMatch.line.match(/(\d+(?:\.\d+)?\s*(?:vdc|v\s*dc|v|vac|v\s*ac))/i)?.[1] || ''));
const current = cleanLabelValue(currentMatch.value);
return {
requires_power: !!(voltage || current || powerLines.length),
power_adapter_voltage: voltage.toUpperCase().replace(/\s+/g, ' '),
power_adapter_current: current.replace(/\s+/g, ' '),
power_adapter_polarity: polarity,
power_adapter_notes: powerLines.slice(0, 4).join(' | ')
};
}
function parseLabelScanText(text) {
const lines = normalizedOcrLines(text);
const serial = firstMatch(lines, [
/\b(?:s\/?n|serial(?:\s*(?:no\.?|number|#))?|ser\.?\s*no\.?)[:\s#-]*([a-z0-9][a-z0-9\-/.]{3,})\b/i,
/\bSN[:\s#-]*([a-z0-9][a-z0-9\-/.]{3,})\b/i
]);
const model = firstMatch(lines, [
/\b(?:model|mod\.?|m\/n|type)[:\s#-]*([a-z0-9][a-z0-9\-/. ]{1,40})\b/i,
/\b(?:product|device)[:\s#-]*([a-z0-9][a-z0-9\-/. ]{2,40})\b/i
]);
const suggestions = {
brand: findKnownBrand(lines),
model: model.value.replace(/\b(serial|s\/?n|input|output|rating)\b.*$/i, '').trim(),
serial_number: serial.value,
...parsePowerInfo(lines)
};
if (suggestions.model && suggestions.serial_number && suggestions.model === suggestions.serial_number) {
suggestions.model = '';
}
return {
rawText: text,
lines,
suggestions,
matchedLines: {
model: model.line,
serial_number: serial.line,
power: suggestions.power_adapter_notes
}
};
}
// --- API ---
function requestBaseUrl(req) {
return `${req.protocol}://${req.get('host')}`;
}
function normalizedBaseUrl(value) {
try {
const parsed = new URL(String(value || ''));
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) return '';
return parsed.origin;
} catch {
return '';
}
}
function isLoopbackHostname(hostname) {
return ['localhost', '127.0.0.1', '::1', '[::1]'].includes(String(hostname || '').toLowerCase());
}
function preferredLanBaseUrl(req) {
const port = Number(req.socket?.localPort || PORT);
const candidates = Object.entries(os.networkInterfaces())
.flatMap(([name, entries]) => (entries || []).map(entry => ({ name, ...entry })))
.filter(entry => entry.family === 'IPv4' && !entry.internal && !entry.address.startsWith('169.254.'))
.sort((a, b) => {
const virtual = /virtual|vmware|vbox|docker|wsl|hyper-v|vethernet/i;
return Number(virtual.test(a.name)) - Number(virtual.test(b.name));
});
const chosen = candidates[0];
return chosen ? `${req.protocol}://${chosen.address}:${port}` : requestBaseUrl(req);
}
function shareBaseUrl(req, requested) {
const normalized = normalizedBaseUrl(requested);
if (!normalized) {
const current = normalizedBaseUrl(requestBaseUrl(req));
try {
return isLoopbackHostname(new URL(current).hostname) ? preferredLanBaseUrl(req) : current;
} catch {
return preferredLanBaseUrl(req);
}
}
return isLoopbackHostname(new URL(normalized).hostname) ? preferredLanBaseUrl(req) : normalized;
}
function scanUrlForItem(req, itemId, requestedBase = '') {
const base = shareBaseUrl(req, requestedBase);
return `${base}/scan/${encodeURIComponent(itemId)}?access=${encodeURIComponent(itemScanToken(itemId))}`;
}
app.get('/api/health', (req, res) => {