Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2595 lines (2384 loc) · 98.2 KB
/
Copy pathserver.js
File metadata and controls
2595 lines (2384 loc) · 98.2 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 JSZip = require('jszip');
const QRCode = require('qrcode');
const VLPFormatter = require('./public/vlp-formatter.js');
const app = express();
app.disable('x-powered-by');
if (process.env.TRUST_PROXY === 'true') {
app.set('trust proxy', 1);
}
const PORT = Number(process.env.PORT) || 8080;
const DATA_DIR = process.env.DATA_DIR
? path.resolve(process.env.DATA_DIR)
: path.join(__dirname, 'data');
const SESSIONS_DIR = path.join(DATA_DIR, 'sessions');
const PROJECTS_DIR = path.join(DATA_DIR, 'projects');
const USERS_DATA_DIR = path.join(DATA_DIR, 'users');
const SHARED_SESSIONS_DIR = path.join(DATA_DIR, 'shared-sessions');
const IMAGES_DIR = path.join(DATA_DIR, 'images');
const AUTOSAVE_FILE = path.join(SESSIONS_DIR, 'autosave.json');
const SECRET_KEY_FILE = path.join(DATA_DIR, '.secret_key');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
const GROUPS_FILE = path.join(DATA_DIR, 'groups.json');
const AUTH_CONFIG_FILE = path.join(DATA_DIR, 'auth-config.json');
const AUDIT_FILE = path.join(DATA_DIR, 'audit-log.json');
fs.mkdirSync(SESSIONS_DIR, { recursive: true });
fs.mkdirSync(PROJECTS_DIR, { recursive: true });
fs.mkdirSync(USERS_DATA_DIR, { recursive: true });
fs.mkdirSync(SHARED_SESSIONS_DIR, { recursive: true });
fs.mkdirSync(IMAGES_DIR, { recursive: true });
/* =========================================================================
* Cryptographic Master Key, HKDF Subkeys, AES-256-GCM PII & Async scrypt
* ========================================================================= */
function loadOrCreateMasterKey() {
if (process.env.APP_SECRET_KEY !== undefined && String(process.env.APP_SECRET_KEY).trim() !== '') {
const rawSecret = String(process.env.APP_SECRET_KEY).trim();
if (rawSecret.length < 32) {
throw new Error('APP_SECRET_KEY must be at least 32 characters long');
}
return crypto.createHash('sha256').update(rawSecret, 'utf8').digest();
}
if (fs.existsSync(SECRET_KEY_FILE)) {
try { fs.chmodSync(SECRET_KEY_FILE, 0o600); } catch (_ignore) {}
const rawHex = fs.readFileSync(SECRET_KEY_FILE, 'utf8').trim();
if (/^[0-9a-fA-F]{64}$/.test(rawHex)) {
return Buffer.from(rawHex, 'hex');
}
}
const key = crypto.randomBytes(32);
fs.writeFileSync(SECRET_KEY_FILE, key.toString('hex'), { encoding: 'utf8', mode: 0o600 });
try { fs.chmodSync(SECRET_KEY_FILE, 0o600); } catch (_ignore) {}
return key;
}
function deriveSubkey(masterKey, info) {
return Buffer.from(
crypto.hkdfSync(
'sha256',
masterKey,
Buffer.from('vlp-hkdf-salt-v2', 'utf8'),
Buffer.from(info, 'utf8'),
32
)
);
}
const MASTER_KEY = loadOrCreateMasterKey();
const PII_ENC_KEY = deriveSubkey(MASTER_KEY, 'vlp-aes-256-gcm-pii-v2');
const BLIND_IDX_KEY = deriveSubkey(MASTER_KEY, 'vlp-hmac-blind-index-v2');
const SESSION_JWT_KEY = deriveSubkey(MASTER_KEY, 'vlp-hmac-session-jwt-v2');
const API_KEY_HMAC_KEY = deriveSubkey(MASTER_KEY, 'vlp-hmac-api-key-v2');
const PII_AAD_V1 = Buffer.from('vlp-pii-v1', 'utf8');
const PII_AAD_V2 = Buffer.from('vlp-pii-v2', 'utf8');
function timingSafeHexEqual(a, b) {
if (!a || !b || typeof a !== 'string' || typeof b !== 'string') return false;
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
if (bufA.length !== bufB.length) return false;
return crypto.timingSafeEqual(bufA, bufB);
}
function encryptPii(plaintext) {
if (plaintext == null || plaintext === '') return '';
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', PII_ENC_KEY, iv);
cipher.setAAD(PII_AAD_V2);
const encrypted = Buffer.concat([cipher.update(String(plaintext), 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return 'enc:v2:' + iv.toString('hex') + ':' + tag.toString('hex') + ':' + encrypted.toString('hex');
}
function decryptPii(payload) {
if (!payload || typeof payload !== 'string') return '';
const isV2 = payload.startsWith('enc:v2:');
const isV1 = payload.startsWith('enc:v1:');
if (!isV2 && !isV1) return '';
try {
const parts = payload.split(':');
if (parts.length !== 5) return '';
const iv = Buffer.from(parts[2], 'hex');
const tag = Buffer.from(parts[3], 'hex');
const enc = Buffer.from(parts[4], 'hex');
const key = isV2 ? PII_ENC_KEY : MASTER_KEY;
const aad = isV2 ? PII_AAD_V2 : PII_AAD_V1;
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAAD(aad);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
} catch (_err) {
return '';
}
}
function blindIndex(value) {
return crypto.createHmac('sha256', BLIND_IDX_KEY)
.update('idx:' + String(value || '').trim().toLowerCase(), 'utf8')
.digest('hex');
}
function blindIndexLegacyV1(value) {
return crypto.createHmac('sha256', MASTER_KEY)
.update('idx:' + String(value || '').trim().toLowerCase(), 'utf8')
.digest('hex');
}
function matchesUserIdentifierIndex(user, value) {
const v2 = blindIndex(value);
const v1 = blindIndexLegacyV1(value);
return (
timingSafeHexEqual(user.emailIndex, v2) ||
timingSafeHexEqual(user.emailIndex, v1) ||
timingSafeHexEqual(user.usernameIndex, v2) ||
timingSafeHexEqual(user.usernameIndex, v1)
);
}
function matchesEmailIndex(user, email) {
return timingSafeHexEqual(user.emailIndex, blindIndex(email)) ||
timingSafeHexEqual(user.emailIndex, blindIndexLegacyV1(email));
}
function matchesUsernameIndex(user, username) {
return timingSafeHexEqual(user.usernameIndex, blindIndex(username)) ||
timingSafeHexEqual(user.usernameIndex, blindIndexLegacyV1(username));
}
function upgradeLegacyUserToV2(user) {
if (!user || typeof user !== 'object') return false;
let changed = false;
['nameEnc', 'emailEnc', 'usernameEnc', 'mfaSecretEnc', 'pendingMfaSecretEnc'].forEach(function (field) {
if (typeof user[field] === 'string' && user[field].startsWith('enc:v1:')) {
const plain = decryptPii(user[field]);
if (plain) {
user[field] = encryptPii(plain);
changed = true;
}
}
});
const emailPlain = decryptPii(user.emailEnc);
if (emailPlain) {
const v2EmailIdx = blindIndex(emailPlain);
if (!timingSafeHexEqual(user.emailIndex, v2EmailIdx)) {
user.emailIndex = v2EmailIdx;
changed = true;
}
}
const usernamePlain = decryptPii(user.usernameEnc);
if (usernamePlain) {
const v2UserIdx = blindIndex(usernamePlain);
if (!timingSafeHexEqual(user.usernameIndex, v2UserIdx)) {
user.usernameIndex = v2UserIdx;
changed = true;
}
}
return changed;
}
const SCRYPT_OPTS = { N: 16384, r: 8, p: 1, maxmem: 33554432 };
function hashPasswordSync(password) {
const pw = String(password || '');
const salt = crypto.randomBytes(32);
const derived = crypto.scryptSync(pw, salt, 64, SCRYPT_OPTS);
return 'scrypt$' + salt.toString('hex') + '$' + derived.toString('hex');
}
function hashPasswordAsync(password) {
return new Promise(function (resolve, reject) {
const pw = String(password || '');
const salt = crypto.randomBytes(32);
crypto.scrypt(pw, salt, 64, SCRYPT_OPTS, function (err, derived) {
if (err) return reject(err);
resolve('scrypt$' + salt.toString('hex') + '$' + derived.toString('hex'));
});
});
}
function verifyPasswordAsync(password, storedHash) {
return new Promise(function (resolve) {
if (!storedHash || typeof storedHash !== 'string') return resolve(false);
const parts = storedHash.split('$');
if (parts.length !== 3 || parts[0] !== 'scrypt') return resolve(false);
try {
const salt = Buffer.from(parts[1], 'hex');
const expected = Buffer.from(parts[2], 'hex');
if (salt.length !== 32 || expected.length !== 64) return resolve(false);
crypto.scrypt(String(password || ''), salt, 64, SCRYPT_OPTS, function (err, actual) {
if (err || !actual || actual.length !== expected.length) return resolve(false);
resolve(crypto.timingSafeEqual(actual, expected));
});
} catch (_err) {
resolve(false);
}
});
}
function hashApiKey(rawKey) {
return crypto.createHmac('sha256', API_KEY_HMAC_KEY).update('apikey:' + String(rawKey || ''), 'utf8').digest('hex');
}
function hashApiKeyLegacyV1(rawKey) {
return crypto.createHmac('sha256', MASTER_KEY).update('apikey:' + String(rawKey || ''), 'utf8').digest('hex');
}
let usersLockChain = Promise.resolve();
function withUsersLock(fn) {
const next = usersLockChain.then(fn, fn);
usersLockChain = next.catch(function () {});
return next;
}
/* =========================================================================
* Offline RFC 6238 TOTP Multi-Factor Authentication Helpers
* ========================================================================= */
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
function generateBase32Secret(byteLen) {
const bytes = crypto.randomBytes(byteLen || 20);
let bits = 0;
let value = 0;
let out = '';
for (let i = 0; i < bytes.length; i++) {
value = (value << 8) | bytes[i];
bits += 8;
while (bits >= 5) {
out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31];
return out;
}
function decodeBase32(str) {
const clean = String(str || '').toUpperCase().replace(/[^A-Z2-7]/g, '');
let bits = 0;
let value = 0;
const bytes = [];
for (let i = 0; i < clean.length; i++) {
const idx = BASE32_ALPHABET.indexOf(clean[i]);
if (idx === -1) continue;
value = (value << 5) | idx;
bits += 5;
if (bits >= 8) {
bytes.push((value >>> (bits - 8)) & 255);
bits -= 8;
}
}
return Buffer.from(bytes);
}
function computeTotpCode(secretBase32, counter) {
const key = decodeBase32(secretBase32);
const msg = Buffer.alloc(8);
msg.writeUInt32BE(Math.floor(counter / 0x100000000), 0);
msg.writeUInt32BE(counter >>> 0, 4);
const hmac = crypto.createHmac('sha1', key).update(msg).digest();
const offset = hmac[hmac.length - 1] & 0x0f;
const bin =
((hmac[offset] & 0x7f) << 24) |
((hmac[offset + 1] & 0xff) << 16) |
((hmac[offset + 2] & 0xff) << 8) |
(hmac[offset + 3] & 0xff);
return String(bin % 1000000).padStart(6, '0');
}
function verifyTotpCodeDetailed(secretBase32, code) {
const clean = String(code || '').replace(/\s+/g, '');
if (!/^\d{6}$/.test(clean) || !secretBase32) return { valid: false, step: null };
const step = Math.floor(Date.now() / 30000);
const codeBuf = Buffer.from(clean, 'utf8');
let matchedStep = null;
for (let w = -1; w <= 1; w++) {
const candidateStep = step + w;
const expected = Buffer.from(computeTotpCode(secretBase32, candidateStep), 'utf8');
if (crypto.timingSafeEqual(codeBuf, expected) && matchedStep === null) {
matchedStep = candidateStep;
}
}
return { valid: matchedStep !== null, step: matchedStep };
}
function verifyTotpCode(secretBase32, code) {
return verifyTotpCodeDetailed(secretBase32, code).valid;
}
/* =========================================================================
* Duration Parsing, Signed Session Tokens & Cookies
* ========================================================================= */
function parseDurationMs(expr) {
const s = String(expr || '4w').trim().toLowerCase();
if (s === '-1') return 90 * 24 * 60 * 60 * 1000;
const m = s.match(/^(\d+)\s*([smhdw])$/);
if (!m) return 28 * 24 * 60 * 60 * 1000;
const n = Number(m[1]);
const mult = {
s: 1000,
m: 60 * 1000,
h: 60 * 60 * 1000,
d: 24 * 60 * 60 * 1000,
w: 7 * 24 * 60 * 60 * 1000
}[m[2]];
return Math.min(90 * 24 * 60 * 60 * 1000, Math.max(60 * 1000, n * mult));
}
function toBase64Url(input) {
return Buffer.from(input).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
}
function fromBase64Url(input) {
const padded = String(input || '').replace(/-/g, '+').replace(/_/g, '/');
return Buffer.from(padded, 'base64');
}
function signSessionToken(user, durationExpr) {
const now = Date.now();
const ttlMs = parseDurationMs(durationExpr);
const headerB64 = toBase64Url(JSON.stringify({ alg: 'HS256', typ: 'VLP', kid: 'v2' }));
const payloadB64 = toBase64Url(JSON.stringify({
sub: user.id,
role: user.role,
sv: user.sessionVersion || 1,
iat: now,
exp: now + ttlMs
}));
const signingInput = headerB64 + '.' + payloadB64;
const sigB64 = toBase64Url(crypto.createHmac('sha256', SESSION_JWT_KEY).update(signingInput).digest());
return { token: signingInput + '.' + sigB64, maxAgeSec: Math.floor(ttlMs / 1000) };
}
function verifyTokenSignature(token) {
if (!token || typeof token !== 'string') return null;
const parts = token.split('.');
if (parts.length !== 3) return null;
try {
const header = JSON.parse(fromBase64Url(parts[0]).toString('utf8'));
if (!header || header.alg !== 'HS256') return null;
const key = header.kid === 'v2' ? SESSION_JWT_KEY : MASTER_KEY;
const signingInput = parts[0] + '.' + parts[1];
const expectedSig = toBase64Url(crypto.createHmac('sha256', key).update(signingInput).digest());
const a = Buffer.from(parts[2], 'utf8');
const b = Buffer.from(expectedSig, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null;
const payload = JSON.parse(fromBase64Url(parts[1]).toString('utf8'));
if (!payload || !payload.sub || typeof payload.exp !== 'number' || payload.exp <= Date.now()) {
return null;
}
return payload;
} catch (_err) {
return null;
}
}
function parseCookies(req) {
const header = req.headers && req.headers.cookie;
const out = {};
if (!header) return out;
String(header).split(';').forEach(function (pair) {
const idx = pair.indexOf('=');
if (idx === -1) return;
const k = pair.slice(0, idx).trim();
const v = pair.slice(idx + 1).trim();
if (k) {
try { out[k] = decodeURIComponent(v); } catch (_e) { out[k] = v; }
}
});
return out;
}
function setSessionCookie(req, res, token, maxAgeSec) {
const isHttps = Boolean(req.secure);
const attrs = [
'vlp_session=' + encodeURIComponent(token),
'Path=/',
'HttpOnly',
'SameSite=Strict',
'Max-Age=' + String(Math.max(0, maxAgeSec || 0))
];
if (isHttps) attrs.push('Secure');
res.setHeader('Set-Cookie', attrs.join('; '));
}
function clearSessionCookie(req, res) {
const isHttps = Boolean(req.secure);
const attrs = ['vlp_session=', 'Path=/', 'HttpOnly', 'SameSite=Strict', 'Max-Age=0'];
if (isHttps) attrs.push('Secure');
res.setHeader('Set-Cookie', attrs.join('; '));
}
/* =========================================================================
* File Utilities & Persistent Auth/Group/Config Stores
* ========================================================================= */
function sanitizeId(input) {
const cleaned = String(input || '').replace(/[^a-zA-Z0-9._-]/g, '_').replace(/^\.+/, '');
return cleaned || ('session-' + Date.now());
}
function sanitizeFilename(input) {
const base = path.basename(String(input || '').trim());
const cleaned = base.replace(/[^a-zA-Z0-9._-]/g, '_');
if (!cleaned || cleaned === '.' || cleaned === '..') {
return crypto.randomUUID() + '.png';
}
return cleaned;
}
function atomicWriteJson(filePath, data) {
const suffix = '.' + process.pid + '.' + crypto.randomBytes(4).toString('hex') + '.tmp';
const tmpPath = filePath + suffix;
fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: 'utf8', mode: 0o600 });
fs.renameSync(tmpPath, filePath);
}
function readJsonSafe(filePath) {
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (_err) {
return null;
}
}
function listDirFilesSafe(dir) {
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir).filter(function (f) {
const full = path.join(dir, f);
return fs.statSync(full).isFile();
});
}
function defaultAuthConfig() {
return {
defaultUserRole: 'pending',
defaultGroupId: '',
enableLoginForm: true,
enableSignUp: true,
enableApiKeys: false,
jwtExpiration: '4w',
requireMfa: false,
showAdminDetails: true,
adminContactEmail: '',
pendingOverlayTitle: '',
pendingOverlayContent: '',
ldapEnabled: false,
ldapServerUrl: '',
ldapBindDn: '',
ldapBindPasswordEnc: '',
ldapSearchBase: '',
ldapSearchAttr: 'mail',
enableOauthPersistentConfig: process.env.ENABLE_OAUTH_PERSISTENT_CONFIG === 'true',
oauthEnabled: false,
oauthProviderName: 'SSO',
oauthProviderUrl: 'https://accounts.google.com/.well-known/openid-configuration',
oauthClientId: '',
oauthClientSecretEnc: '',
oauthRedirectUri: '',
oauthScopes: 'openid email profile',
oauthEmailClaim: 'email',
oauthUsernameClaim: 'name',
oauthPictureClaim: 'picture',
oauthSubClaim: 'sub',
oauthSignup: false,
oauthMergeByEmail: false,
oauthAutoRedirect: false,
oauthAllowedDomains: '*',
oauthRoleMapping: false,
oauthGroupMapping: false,
oauthUpdateEmail: false,
oauthUpdateName: false,
oauthUpdatePicture: false
};
}
function loadAuthConfig() {
const stored = readJsonSafe(AUTH_CONFIG_FILE);
return Object.assign(defaultAuthConfig(), stored || {});
}
function saveAuthConfig(cfg) {
atomicWriteJson(AUTH_CONFIG_FILE, cfg);
}
function getSafeAuthConfigForAdmin(cfg) {
const copy = Object.assign({}, cfg);
copy.hasOauthClientSecret = Boolean(cfg.oauthClientSecretEnc);
copy.oauthClientSecret = '';
delete copy.oauthClientSecretEnc;
copy.hasLdapBindPassword = Boolean(cfg.ldapBindPasswordEnc);
copy.ldapBindPassword = '';
delete copy.ldapBindPasswordEnc;
return copy;
}
function getPublicAuthConfig(cfg, users) {
let contactEmail = cfg.adminContactEmail || '';
if (!contactEmail && cfg.showAdminDetails && Array.isArray(users)) {
const firstAdmin = users.find(function (u) { return u.role === 'admin'; });
if (firstAdmin) contactEmail = decryptPii(firstAdmin.emailEnc);
}
return {
defaultUserRole: cfg.defaultUserRole,
enableLoginForm: Boolean(cfg.enableLoginForm),
enableSignUp: Boolean(cfg.enableSignUp),
enableApiKeys: Boolean(cfg.enableApiKeys),
requireMfa: Boolean(cfg.requireMfa),
showAdminDetails: Boolean(cfg.showAdminDetails),
adminContactEmail: cfg.showAdminDetails ? contactEmail : '',
pendingOverlayTitle: cfg.pendingOverlayTitle || '',
pendingOverlayContent: cfg.pendingOverlayContent || '',
ldapEnabled: Boolean(cfg.ldapEnabled),
oauthEnabled: Boolean(cfg.oauthEnabled),
oauthProviderName: cfg.oauthProviderName || 'SSO'
};
}
function loadUsers() {
const data = readJsonSafe(USERS_FILE);
return Array.isArray(data) ? data : [];
}
function saveUsers(users) {
atomicWriteJson(USERS_FILE, users);
}
function loadGroups() {
const data = readJsonSafe(GROUPS_FILE);
return Array.isArray(data) ? data : [];
}
function saveGroups(groups) {
atomicWriteJson(GROUPS_FILE, groups);
}
function appendAuditEvent(eventType, actorId, targetId, detail) {
const list = readJsonSafe(AUDIT_FILE);
const events = Array.isArray(list) ? list : [];
events.unshift({
id: crypto.randomUUID(),
timestamp: new Date().toISOString(),
event: String(eventType || 'INFO'),
actorId: actorId || 'system',
targetId: targetId || '',
detail: String(detail || '')
});
if (events.length > 200) events.length = 200;
try { atomicWriteJson(AUDIT_FILE, events); } catch (_ignore) {}
}
function sanitizeUserView(user) {
if (!user) return null;
return {
id: user.id,
name: decryptPii(user.nameEnc),
email: decryptPii(user.emailEnc),
username: decryptPii(user.usernameEnc),
role: user.role || 'pending',
groupId: user.groupId || '',
hasApiKey: Boolean(user.apiKeyHash),
mfaEnabled: Boolean(user.mfaEnabled && user.mfaSecretEnc),
createdAt: user.createdAt || '',
lastActiveAt: user.lastActiveAt || ''
};
}
function bootstrapAdminFromEnvIfNeeded() {
const users = loadUsers();
if (users.length > 0) return;
const email = process.env.ADMIN_EMAIL && String(process.env.ADMIN_EMAIL).trim();
const password = process.env.ADMIN_PASSWORD && String(process.env.ADMIN_PASSWORD);
if (!email || !password || password.length < 8) return;
const username = (process.env.ADMIN_USERNAME && String(process.env.ADMIN_USERNAME).trim()) || email.split('@')[0] || 'admin';
const name = (process.env.ADMIN_NAME && String(process.env.ADMIN_NAME).trim()) || 'Administrator';
const adminUser = {
id: crypto.randomUUID(),
nameEnc: encryptPii(name),
emailEnc: encryptPii(email.toLowerCase()),
usernameEnc: encryptPii(username.toLowerCase()),
emailIndex: blindIndex(email),
usernameIndex: blindIndex(username),
passwordHash: hashPasswordSync(password),
role: 'admin',
groupId: '',
apiKeyHash: '',
apiKeySessionVersion: 1,
mfaEnabled: false,
mfaSecretEnc: '',
lastLoginTotpStep: -1,
sessionVersion: 1,
createdAt: new Date().toISOString(),
lastActiveAt: new Date().toISOString()
};
saveUsers([adminUser]);
appendAuditEvent('ADMIN_ENV_BOOTSTRAP', 'system', adminUser.id, 'Bootstrapped initial admin from environment variables');
}
bootstrapAdminFromEnvIfNeeded();
/* =========================================================================
* Bounded Rate Limiter (Memory-Backed Brute-Force Protection)
* ========================================================================= */
const loginAttempts = new Map();
const MAX_RATE_ENTRIES = 5000;
const MAX_LOGIN_FAILS = 8;
const LOCK_WINDOW_MS = 15 * 60 * 1000;
const LOCK_DURATION_MS = 5 * 60 * 1000;
function pruneRateLimiterMap(now) {
if (loginAttempts.size < MAX_RATE_ENTRIES) return;
for (const [k, rec] of loginAttempts.entries()) {
if ((rec.lockedUntil && rec.lockedUntil <= now) || (now - rec.firstAttemptAt > LOCK_WINDOW_MS)) {
loginAttempts.delete(k);
}
if (loginAttempts.size < MAX_RATE_ENTRIES) return;
}
const oldestKey = loginAttempts.keys().next().value;
if (oldestKey !== undefined) loginAttempts.delete(oldestKey);
}
function checkLoginRateLimit(key, maxFailsOverride) {
const rec = loginAttempts.get(key);
if (!rec) return { blocked: false };
const now = Date.now();
if (rec.lockedUntil && rec.lockedUntil > now) {
return { blocked: true, retryAfterSec: Math.ceil((rec.lockedUntil - now) / 1000) };
}
if (now - rec.firstAttemptAt > LOCK_WINDOW_MS) {
loginAttempts.delete(key);
return { blocked: false };
}
if (typeof maxFailsOverride === 'number' && rec.count >= maxFailsOverride) {
rec.lockedUntil = now + LOCK_DURATION_MS;
return { blocked: true, retryAfterSec: Math.ceil(LOCK_DURATION_MS / 1000) };
}
return { blocked: false };
}
function recordLoginFailure(key, maxFailsOverride) {
const now = Date.now();
const limit = typeof maxFailsOverride === 'number' ? maxFailsOverride : MAX_LOGIN_FAILS;
let rec = loginAttempts.get(key);
if (!rec || now - rec.firstAttemptAt > LOCK_WINDOW_MS) {
pruneRateLimiterMap(now);
rec = { count: 0, firstAttemptAt: now, lockedUntil: 0 };
}
rec.count += 1;
if (rec.count >= limit) {
rec.lockedUntil = now + LOCK_DURATION_MS;
}
loginAttempts.set(key, rec);
}
function clearLoginFailure(key) {
loginAttempts.delete(key);
}
/* =========================================================================
* Middleware: Security Headers, CVE-2026-111497 Mitigation, CSRF & Auth
* ========================================================================= */
const APP_CSP = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob:",
"font-src 'self' data:",
"connect-src 'self'",
"frame-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'self'"
].join('; ');
app.use(function (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=(), microphone=(), geolocation=()');
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
if (!req.path.startsWith('/api/images/')) {
res.setHeader('Content-Security-Policy', APP_CSP);
}
if (req.secure) {
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
if (req.path.startsWith('/api/')) {
res.setHeader('Cache-Control', 'no-store');
}
next();
});
// Neutralize CVE-2026-111497 ("Node2Shell") compressed body inflation on API endpoints
app.use('/api', function (req, res, next) {
const enc = String(req.headers['content-encoding'] || '').trim().toLowerCase();
if (enc && enc !== 'identity') {
return res.status(415).json({ ok: false, error: 'Compressed request bodies are not supported' });
}
next();
});
const smallJsonParser = express.json({ limit: '64kb', inflate: false });
const largeJsonParser = express.json({ limit: '100mb', inflate: false });
const largeZipParser = express.raw({ type: ['application/zip', 'application/octet-stream'], limit: '100mb', inflate: false });
// Attach req.user & req.authConfig on every request
app.use(function (req, _res, next) {
const users = loadUsers();
const cfg = loadAuthConfig();
req.authConfig = cfg;
req.usersList = users;
req.user = null;
req.authViaApiKey = false;
const cookies = parseCookies(req);
let token = cookies.vlp_session || '';
const authHeader = String(req.headers.authorization || '');
if (!token && authHeader.startsWith('Bearer ')) {
const bearerVal = authHeader.slice(7).trim();
if (bearerVal.startsWith('vlp_sk_')) {
const kHashV2 = hashApiKey(bearerVal);
const kHashV1 = hashApiKeyLegacyV1(bearerVal);
const matched = users.find(function (u) {
if (!u.apiKeyHash) return false;
if (!cfg.enableApiKeys && u.role !== 'admin') return false;
if (u.apiKeySessionVersion !== undefined && (u.apiKeySessionVersion || 1) !== (u.sessionVersion || 1)) {
return false;
}
return timingSafeHexEqual(u.apiKeyHash, kHashV2) || timingSafeHexEqual(u.apiKeyHash, kHashV1);
});
if (matched) {
req.user = matched;
req.authViaApiKey = true;
}
return next();
}
token = bearerVal;
}
if (token) {
const payload = verifyTokenSignature(token);
if (payload) {
const matched = users.find(function (u) { return u.id === payload.sub; });
if (matched && (matched.sessionVersion || 1) === payload.sv) {
req.user = matched;
}
}
}
next();
});
// CSRF defense-in-depth on state-changing API calls authenticated by cookies
app.use('/api', function (req, res, next) {
const method = String(req.method || 'GET').toUpperCase();
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS' || req.authViaApiKey) {
return next();
}
const sfs = String(req.headers['sec-fetch-site'] || '').trim().toLowerCase();
if (sfs && sfs !== 'same-origin' && sfs !== 'none') {
return res.status(403).json({ ok: false, error: 'Cross-site request blocked' });
}
const origin = req.headers.origin;
if (origin) {
try {
const parsed = new URL(String(origin));
const host = String(req.headers.host || '').toLowerCase();
if (!host || parsed.host.toLowerCase() !== host) {
return res.status(403).json({ ok: false, error: 'Origin mismatch blocked' });
}
} catch (_err) {
return res.status(403).json({ ok: false, error: 'Invalid request origin' });
}
}
next();
});
function requireActiveUser(req, res, next) {
// Preserve pre-bootstrap behavior when zero accounts have been registered (e.g. initial setup or clean CI tests)
if (req.usersList.length === 0) return next();
if (!req.user) {
return res.status(401).json({ ok: false, error: 'Authentication required' });
}
if (req.user.role === 'pending') {
return res.status(403).json({ ok: false, error: 'Account pending administrator approval' });
}
if (req.authConfig && req.authConfig.requireMfa && !req.user.mfaEnabled) {
return res.status(403).json({
ok: false,
mfaEnrollmentRequired: true,
error: 'Multi-factor authentication enrollment is required by the administrator'
});
}
return next();
}
function requireSignedInUser(req, res, next) {
if (!req.user) {
return res.status(401).json({ ok: false, error: 'Authentication required' });
}
return next();
}
function requireAdminUser(req, res, next) {
if (!req.user) {
return res.status(401).json({ ok: false, error: 'Authentication required' });
}
if (req.user.role !== 'admin') {
return res.status(403).json({ ok: false, error: 'Administrator privileges required' });
}
return next();
}
// Mount size-capped body parsers: 64 KB on auth/admin, 100 MB only behind requireActiveUser
app.use('/api/auth', smallJsonParser);
app.use('/api/admin', smallJsonParser);
app.use('/api/sessions', requireActiveUser, largeJsonParser);
app.use('/api/sessions-shared', requireActiveUser, largeJsonParser);
app.use('/api/projects', requireActiveUser, largeJsonParser);
app.use('/api/images', requireActiveUser, largeJsonParser);
app.use('/api/export-zip', requireActiveUser, largeJsonParser);
app.use('/api/export-document', requireActiveUser, largeJsonParser);
app.use('/api/import-zip', requireActiveUser, largeZipParser, largeJsonParser);
function getUserSessionsDir(req) {
if (!req.user) return SESSIONS_DIR;
const userDir = path.join(USERS_DATA_DIR, sanitizeId(req.user.id), 'sessions');
fs.mkdirSync(userDir, { recursive: true });
return userDir;
}
function getUserProjectsDir(req) {
if (!req.user) return PROJECTS_DIR;
const userDir = path.join(USERS_DATA_DIR, sanitizeId(req.user.id), 'projects');
fs.mkdirSync(userDir, { recursive: true });
return userDir;
}
// Static application & bundled offline assets (zero CDNs)
app.use(express.static(path.join(__dirname, 'public')));
app.use('/samples/annexb/images', express.static(path.join(__dirname, 'dsac.annexb.lab01-en', 'images')));
app.use('/samples/annexc/images', express.static(path.join(__dirname, 'dsac.annexc.lab01-en', 'images')));
function countContentNodes(nodes) {
let count = 0;
(nodes || []).forEach(function (n) {
count += 1 + countContentNodes(n.children || []);
});
return count;
}
function countManualStats(manual) {
let nodeCount = 0;
let stepCount = 0;
const imageNames = new Set();
function walk(nodes) {
(nodes || []).forEach(function (n) {
nodeCount += 1;
if (n.overview && n.overview.bannerSrc) {
const bfn = VLPFormatter.extractFilenameFromSrc(n.overview.bannerSrc);
if (bfn) imageNames.add(bfn);
}
if (n.stepsData && Array.isArray(n.stepsData.steps)) {
stepCount += n.stepsData.steps.length;
n.stepsData.steps.forEach(function (s) {
(s.images || []).forEach(function (im) {
if (im && im.src) {
const fn = im.filename || VLPFormatter.extractFilenameFromSrc(im.src);
if (fn) imageNames.add(fn);
}
});
});
}
(n.images || []).forEach(function (im) {
const fn = im.filename || VLPFormatter.extractFilenameFromSrc(im.src);
if (fn) imageNames.add(fn);
});
walk(n.children || []);
});
}
walk((manual && manual.contentNodes) || []);
return { nodeCount: nodeCount, stepCount: stepCount, imageCount: imageNames.size };
}
function extFromMimeType(mimeType) {
const m = String(mimeType || '').toLowerCase();
if (m.includes('jpeg') || m.includes('jpg')) return '.jpg';
if (m.includes('gif')) return '.gif';
if (m.includes('webp')) return '.webp';
if (m.includes('svg')) return '.svg';
return '.png';
}
const MAX_IMAGE_BYTES = 15 * 1024 * 1024;
function validateAndSanitizeImageBuffer(buf, filenameHint) {
if (!Buffer.isBuffer(buf) || buf.length === 0 || buf.length > MAX_IMAGE_BYTES) {
return null;
}
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (
buf.length >= 8 &&
buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4E && buf[3] === 0x47 &&
buf[4] === 0x0D && buf[5] === 0x0A && buf[6] === 0x1A && buf[7] === 0x0A
) {
return { ext: '.png', buffer: buf };
}
// JPEG: FF D8 FF
if (buf.length >= 3 && buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF) {
const hintExt = path.extname(String(filenameHint || '')).toLowerCase();
return { ext: hintExt === '.jpeg' ? '.jpeg' : '.jpg', buffer: buf };
}
// GIF: GIF87a / GIF89a
if (buf.length >= 6) {
const hdr6 = buf.slice(0, 6).toString('ascii');
if (hdr6 === 'GIF87a' || hdr6 === 'GIF89a') {
return { ext: '.gif', buffer: buf };
}
}
// WebP: RIFF....WEBP
if (
buf.length >= 12 &&
buf.slice(0, 4).toString('ascii') === 'RIFF' &&
buf.slice(8, 12).toString('ascii') === 'WEBP'
) {
return { ext: '.webp', buffer: buf };
}
// SVG: XML/text starting with <svg
const sampleText = buf.toString('utf8', 0, Math.min(buf.length, 4096))
.replace(/^\uFEFF/, '')
.replace(/<\?xml[\s\S]*?\?>/gi, '')
.replace(/<!--[\s\S]*?-->/g, '')
.trim();
if (/^<svg[\s>]/i.test(sampleText)) {
const fullText = buf.toString('utf8');
const cleaned = VLPFormatter.sanitizeHtmlFragment(fullText);
if (!/<svg[\s>]/i.test(cleaned)) return null;
return { ext: '.svg', buffer: Buffer.from(cleaned, 'utf8') };
}
return null;
}
function sha256Buffer(buf) {
return crypto.createHash('sha256').update(buf).digest('hex');
}
function writeImageImmutable(buf, preferredFilename) {
const validated = validateAndSanitizeImageBuffer(buf, preferredFilename);
if (!validated) {
const err = new Error('Invalid or unsupported image file');
err.status = 400;
throw err;
}
let fn = sanitizeFilename(preferredFilename || (crypto.randomUUID() + validated.ext));
const curExt = path.extname(fn).toLowerCase();
const extMatches =
curExt === validated.ext ||
(validated.ext === '.jpg' && curExt === '.jpeg') ||
(validated.ext === '.jpeg' && curExt === '.jpg');
if (!extMatches) {
const base = curExt ? fn.slice(0, -curExt.length) : fn;
fn = (base || crypto.randomUUID()) + validated.ext;
}
let outPath = path.join(IMAGES_DIR, fn);
if (fs.existsSync(outPath)) {
const existingBuf = fs.readFileSync(outPath);
if (sha256Buffer(existingBuf) !== sha256Buffer(validated.buffer)) {
fn = crypto.randomUUID() + validated.ext;
outPath = path.join(IMAGES_DIR, fn);
fs.writeFileSync(outPath, validated.buffer);