-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1954 lines (1700 loc) · 80.2 KB
/
Copy pathserver.js
File metadata and controls
1954 lines (1700 loc) · 80.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
'use strict';
/**
* COMMAND & CONTROL (C2) — Secure Express Backend Server
* Security Level: Production-Grade / Security-by-Design 2026
*
* Defense layers:
* 1. Helmet.js — HTTP security headers (CSP, HSTS, X-Frame, XCTO, Referrer)
* 2. CORS — Strict origin allowlist from environment
* 3. Rate limiting — Per-IP, SQLite-backed persistent store
* 4. Input validation — Schema-based, pure-function validators, no external deps
* 5. scrypt N=131072 — 2026-grade password hashing (8x stronger than OWASP 2017 min)
* 6. Thread IDs — 16 bytes / 128-bit entropy (UUID-grade, eliminates birthday problem)
* 7. Server-side logout — Token revocation on signout
* 8. Error sanitization — No stack traces, no internal paths exposed to clients
* 9. Static isolation — Only public/ served; server.js, DB, .env never reachable
* 10. Commander role — Exclusively via CLI setup.js; UI registration always yields AGENT
*/
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const { rateLimit, ipKeyGenerator } = require('express-rate-limit');
const sqlite3 = require('sqlite3').verbose();
const http = require('http');
const { Server } = require('socket.io');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const { Worker } = require('worker_threads');
const captcha = require('./server/captcha');
// ─── Runtime Constants ────────────────────────────────────────────────────────
const PORT = parseInt(process.env.PORT ?? '3000', 10);
const NODE_ENV = process.env.NODE_ENV ?? 'development';
const IS_PROD = NODE_ENV === 'production';
const CLOUDFLARE_DOMAIN = process.env.CLOUDFLARE_DOMAIN ?? '';
const ALLOWED_ORIGIN = CLOUDFLARE_DOMAIN
? `https://${CLOUDFLARE_DOMAIN}`
: `http://localhost:${PORT}`;
// scrypt 2026-grade (OWASP 2024 recommendation for interactive login)
const SCRYPT_PARAMS = Object.freeze({ N: 131072, r: 8, p: 1, maxmem: 256 * 1024 * 1024 });
const SCRYPT_KEY_LEN = 64; // bytes
const HASH_VERSION = 'v2';
const VALID_CATEGORIES = new Set([
'announcements',
'applied-crypto',
'low-level',
'web-security',
'reverse-eng',
'secure-coding',
'pentesting',
'red-team',
'blue-team',
'malware'
]);
// ─── Database ────────────────────────────────────────────────────────────────
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
const dbPath = path.join(DATA_DIR, 'database.sqlite');
const db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error('[FATAL] Cannot open database:', err.message);
process.exit(1);
}
console.log('[OK] SQLite connected:', dbPath);
});
// WAL mode + FK enforcement
db.run('PRAGMA journal_mode=WAL');
db.run('PRAGMA foreign_keys=ON');
db.serialize(() => {
db.run(`
CREATE TABLE IF NOT EXISTS users (
codename TEXT PRIMARY KEY,
password_hash TEXT NOT NULL,
public_key_spki TEXT NOT NULL,
encrypted_private_key TEXT,
role TEXT NOT NULL DEFAULT 'AGENT',
status TEXT NOT NULL DEFAULT 'PENDING_ADMISSION',
admission_attempts INTEGER NOT NULL DEFAULT 5,
terms_accepted_at TEXT,
terms_accepted_ip TEXT,
bio TEXT NOT NULL DEFAULT 'INITIALIZED AGENT NODE.',
joined_date TEXT NOT NULL,
last_seen INTEGER DEFAULT 0
)
`);
// Retroactive migration to add last_seen if user table already exists
db.run("ALTER TABLE users ADD COLUMN last_seen INTEGER DEFAULT 0", (err) => {
// Silent catch if column is already present
});
db.run("ALTER TABLE users ADD COLUMN status TEXT NOT NULL DEFAULT 'PENDING_ADMISSION'", () => {});
db.run("ALTER TABLE users ADD COLUMN admission_attempts INTEGER NOT NULL DEFAULT 5", () => {});
db.run("ALTER TABLE users ADD COLUMN terms_accepted_at TEXT", () => {});
db.run("ALTER TABLE users ADD COLUMN terms_accepted_ip TEXT", () => {});
db.run(`
CREATE TABLE IF NOT EXISTS threads (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
author TEXT NOT NULL,
category TEXT NOT NULL,
timestamp TEXT NOT NULL,
upvotes INTEGER NOT NULL DEFAULT 0,
signature TEXT NOT NULL,
FOREIGN KEY (author) REFERENCES users(codename)
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS replies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
thread_id TEXT NOT NULL,
content TEXT NOT NULL,
author TEXT NOT NULL,
timestamp TEXT NOT NULL,
signature TEXT NOT NULL,
FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE,
FOREIGN KEY (author) REFERENCES users(codename)
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
codename TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
FOREIGN KEY (codename) REFERENCES users(codename) ON DELETE CASCADE
)
`);
// Rate limiting persistence table
db.run(`
CREATE TABLE IF NOT EXISTS rate_limits (
key TEXT PRIMARY KEY,
hits INTEGER NOT NULL DEFAULT 0,
reset_at INTEGER NOT NULL
)
`);
// Cryptographic Likes/Dislikes table
db.run(`
CREATE TABLE IF NOT EXISTS votes (
thread_id TEXT NOT NULL,
codename TEXT NOT NULL,
value INTEGER NOT NULL,
signature TEXT NOT NULL,
PRIMARY KEY (thread_id, codename),
FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE,
FOREIGN KEY (codename) REFERENCES users(codename) ON DELETE CASCADE
)
`);
// Moderation status tracking (bans, shadowbans)
db.run(`
CREATE TABLE IF NOT EXISTS moderation (
codename TEXT PRIMARY KEY,
status TEXT NOT NULL,
reason TEXT,
created_at INTEGER NOT NULL,
FOREIGN KEY (codename) REFERENCES users(codename) ON DELETE CASCADE
)
`);
// Moderation warning history logs
db.run(`
CREATE TABLE IF NOT EXISTS warnings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
codename TEXT NOT NULL,
reason TEXT NOT NULL,
timestamp INTEGER NOT NULL,
FOREIGN KEY (codename) REFERENCES users(codename) ON DELETE CASCADE
)
`);
// Anti-replay persistent nonce store (C2-002)
db.run(`
CREATE TABLE IF NOT EXISTS nonces (
nonce TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (nonce)
)
`);
db.run('CREATE INDEX IF NOT EXISTS idx_nonces_created_at ON nonces(created_at)');
// Admission gatekeeper question pool
db.run(`
CREATE TABLE IF NOT EXISTS admission_questions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
question TEXT NOT NULL,
options TEXT NOT NULL,
correct_answer TEXT NOT NULL,
created_at INTEGER NOT NULL
)
`, function() {
// Seed initial questions if table is empty
db.get('SELECT COUNT(*) AS cnt FROM admission_questions', [], (err, row) => {
if (err || row.cnt > 0) return;
const seedQuestions = [
{ q: '¿Qué ataque consiste en engañar a un usuario para que haga clic en algo diferente de lo que percibe?', opts: ['A) Phishing', 'B) Clickjacking', 'C) Spoofing', 'D) SMiShing'], ans: 'B' },
{ q: '¿Cuál es el puerto predeterminado para conexiones HTTPS?', opts: ['A) 80', 'B) 22', 'C) 443', 'D) 8080'], ans: 'C' },
{ q: '¿Qué principio de seguridad establece que un usuario debe tener solo los permisos mínimos necesarios para realizar su trabajo?', opts: ['A) Defensa en profundidad', 'B) Superficie de ataque mínima', 'C) Privilegio mínimo', 'D) Separación de privilegios'], ans: 'C' },
{ q: '¿Qué tipo de ataque consiste en insertar código malicioso en una consulta a una base de datos?', opts: ['A) XSS', 'B) CSRF', 'C) SQL Injection', 'D) MITM'], ans: 'C' },
{ q: '¿Qué protocolo se utiliza para transferir archivos de forma segura sobre SSH?', opts: ['A) FTP', 'B) TFTP', 'C) SFTP', 'D) FTPS'], ans: 'C' },
{ q: '¿Cuál es la diferencia entre autenticación y autorización?', opts: ['A) Son lo mismo', 'B) Autenticación verifica identidad; autorización verifica permisos', 'C) Autorización verifica identidad; autenticación verifica permisos', 'D) Ninguna de las anteriores'], ans: 'B' },
{ q: '¿Qué es un ataque de hombre en el medio (MITM)?', opts: ['A) Infectar un servidor con malware', 'B) Interceptar la comunicación entre dos partes sin su conocimiento', 'C) Enviar correos fraudulentos para robar información', 'D) Saturar un servidor con tráfico'], ans: 'B' },
{ q: '¿Qué cifrado de los siguientes es SIMÉTRICO?', opts: ['A) RSA', 'B) ECDSA', 'C) AES', 'D) Diffie-Hellman'], ans: 'C' },
{ q: '¿Qué header HTTP ayuda a prevenir ataques de clickjacking?', opts: ['A) Strict-Transport-Security', 'B) Content-Security-Policy', 'C) X-Frame-Options', 'D) X-Content-Type-Options'], ans: 'C' },
{ q: '¿Qué es un honeypot en seguridad informática?', opts: ['A) Un tipo de firewall', 'B) Un señuelo para atraer y detectar atacantes', 'C) Un algoritmo de cifrado', 'D) Un protocolo de autenticación'], ans: 'B' },
{ q: '¿Cuál de los siguientes es un ejemplo de autenticación multifactor (MFA)?', opts: ['A) Usuario y contraseña', 'B) Contraseña + código de app autenticadora', 'C) Pregunta de seguridad', 'D) Token de API'], ans: 'B' },
{ q: '¿Qué método HTTP se utiliza típicamente para crear un recurso en una API REST?', opts: ['A) GET', 'B) POST', 'C) PUT', 'D) DELETE'], ans: 'B' },
{ q: '¿Qué es Cross-Site Scripting (XSS)?', opts: ['A) Robar la sesión de un usuario mediante cookies', 'B) Inyectar scripts maliciosos en páginas web vistas por otros usuarios', 'C) Modificar el DNS de un dominio', 'D) Interceptar tráfico de red'], ans: 'B' },
{ q: '¿Cuál es el propósito de un firewall de red?', opts: ['A) Acelerar la conexión a internet', 'B) Monitorear y bloquear tráfico no autorizado según reglas definidas', 'C) Cifrar toda la comunicación de red', 'D) Almacenar contraseñas de forma segura'], ans: 'B' },
{ q: '¿Qué puerto usa el protocolo SSH?', opts: ['A) 21', 'B) 22', 'C) 23', 'D) 25'], ans: 'B' },
];
const now = Date.now();
for (const q of seedQuestions) {
db.run('INSERT INTO admission_questions (question, options, correct_answer, created_at) VALUES (?, ?, ?, ?)', [q.q, JSON.stringify(q.opts), q.ans, now]);
}
console.log('[OK] Seeded', seedQuestions.length, 'admission questions.');
});
});
// Phase 3 Schema Additions (Fail-safe for existing tables)
db.run("ALTER TABLE threads ADD COLUMN client_nonce TEXT", () => {});
db.run("ALTER TABLE threads ADD COLUMN client_timestamp TEXT", () => {});
db.run("ALTER TABLE threads ADD COLUMN signature_op TEXT", () => {});
db.run("ALTER TABLE replies ADD COLUMN client_nonce TEXT", () => {});
db.run("ALTER TABLE replies ADD COLUMN client_timestamp TEXT", () => {});
db.run("ALTER TABLE replies ADD COLUMN signature_op TEXT", () => {});
db.run("ALTER TABLE votes ADD COLUMN client_nonce TEXT", () => {});
db.run("ALTER TABLE votes ADD COLUMN client_timestamp TEXT", () => {});
db.run("ALTER TABLE votes ADD COLUMN signature_op TEXT", () => {});
// Phase 4: 2FA Schema (fail-safe retroactive migration)
db.run("ALTER TABLE users ADD COLUMN two_factor_enabled INTEGER NOT NULL DEFAULT 0", () => {});
db.run("ALTER TABLE users ADD COLUMN two_factor_secret TEXT", () => {});
db.run("ALTER TABLE users ADD COLUMN two_factor_salt TEXT", () => {});
db.run("ALTER TABLE users ADD COLUMN two_factor_iv TEXT", () => {});
db.run("ALTER TABLE users ADD COLUMN last_totp_counter INTEGER NOT NULL DEFAULT -1", () => {});
// One-time-use recovery codes (hashed with scrypt before storage)
db.run(`
CREATE TABLE IF NOT EXISTS recovery_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
codename TEXT NOT NULL,
code_hash TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
FOREIGN KEY (codename) REFERENCES users(codename) ON DELETE CASCADE
)
`);
db.run('CREATE INDEX IF NOT EXISTS idx_recovery_codes_codename ON recovery_codes(codename)');
});
// ─── Background Tasks ────────────────────────────────────────────────────────
// Session garbage collector (every hour)
setInterval(() => {
db.run('DELETE FROM sessions WHERE expires_at < ?', [Date.now()]);
}, 60 * 60 * 1000).unref();
// ─── Data Access Object (DAO) ──────────────────────────────────────────────────
const DB = {
get: (sql, params = []) => new Promise((resolve, reject) => db.get(sql, params, (err, row) => err ? reject(err) : resolve(row))),
all: (sql, params = []) => new Promise((resolve, reject) => db.all(sql, params, (err, rows) => err ? reject(err) : resolve(rows))),
run: (sql, params = []) => new Promise((resolve, reject) => db.run(sql, params, function (err) { err ? reject(err) : resolve(this) }))
};
// ─── SQLite Rate-Limit Store (express-rate-limit v7 interface) ────────────────
class SQLiteStore {
constructor(windowMs) {
this.windowMs = windowMs;
}
async increment(key) {
const now = Date.now();
const resetAt = now + this.windowMs;
return new Promise((resolve, reject) => {
db.get(`
INSERT INTO rate_limits (key, hits, reset_at)
VALUES (?, 1, ?)
ON CONFLICT(key) DO UPDATE SET
hits = CASE WHEN reset_at < ? THEN 1 ELSE hits + 1 END,
reset_at = CASE WHEN reset_at < ? THEN ? ELSE reset_at END
RETURNING hits, reset_at;
`, [key, resetAt, now, now, resetAt], (err, row) => {
if (err) return reject(err);
resolve({ totalHits: row.hits, resetTime: new Date(row.reset_at) });
});
});
}
async decrement(key) {
return new Promise((resolve) => {
db.run('UPDATE rate_limits SET hits = MAX(0, hits - 1) WHERE key = ?', [key], () => resolve());
});
}
async resetKey(key) {
return new Promise((resolve) => {
db.run('DELETE FROM rate_limits WHERE key = ?', [key], () => resolve());
});
}
}
// ─── Rate Limiters ────────────────────────────────────────────────────────────
const AUTH_WINDOW_MS = 15 * 60 * 1000; // 15 min
const WRITE_WINDOW_MS = 60 * 1000; // 1 min
/**
* Tier-1 — Structural flood limiter.
* Fires BEFORE schema validation on auth endpoints.
* Blocks any IP that sends more than 200 requests to /api/auth/* within 15 min,
* regardless of payload shape. This closes the unlimited-malformed-payload DoS
* vector: an attacker flooding with plain-text passwords or random garbage
* gets cut off here without ever touching the strict auth quota.
*/
const structuralLimiter = rateLimit({
windowMs: AUTH_WINDOW_MS,
max: 200,
standardHeaders: false, // C2-007: Disable rate limit headers to prevent information leak
legacyHeaders: false,
store: new SQLiteStore(AUTH_WINDOW_MS),
keyGenerator: (req) => `structural:${ipKeyGenerator(req)}`,
message: { error: 'RATE_LIMIT_EXCEEDED: Too many requests to this endpoint.' },
});
/**
* Tier-2 — Strict authentication limiter.
* Fires AFTER schema validation on auth endpoints.
* Only structurally-valid requests (correct codename format, 64-char hex password)
* reach this limiter — meaning only real brute-force attempts consume this quota.
* 10 valid-format attempts per IP per 15-minute window.
*/
const authLimiter = rateLimit({
windowMs: AUTH_WINDOW_MS,
max: 10,
standardHeaders: false, // C2-007: Disable rate limit headers to prevent information leak
legacyHeaders: false,
store: new SQLiteStore(AUTH_WINDOW_MS),
keyGenerator: (req) => `auth:${ipKeyGenerator(req)}`,
message: { error: 'RATE_LIMIT_EXCEEDED: Too many authentication attempts. Try again in 15 minutes.' },
skipSuccessfulRequests: false,
});
const writeLimiter = rateLimit({
windowMs: WRITE_WINDOW_MS,
max: 20,
standardHeaders: false, // C2-007: Disable rate limit headers to prevent information leak
legacyHeaders: false,
store: new SQLiteStore(WRITE_WINDOW_MS),
keyGenerator: (req) => `write:${ipKeyGenerator(req)}`,
message: { error: 'RATE_LIMIT_EXCEEDED: Write throttle engaged.' },
});
// ─── Input Validators (pure functions, zero external deps) ────────────────────
const Validators = Object.freeze({
codename: (v) => typeof v === 'string' && /^[a-zA-Z0-9_\-]{3,20}$/.test(v),
authKey: (v) => typeof v === 'string' && /^[0-9a-f]{64}$/i.test(v),
spkiBase64: (v) => typeof v === 'string' && v.length >= 50 && v.length <= 400 && /^[A-Za-z0-9+/=]+$/.test(v),
encKey: (v) => typeof v === 'string' && v.includes(':') && v.length > 30 && v.length <= 4096,
signature: (v) => typeof v === 'string' && v.length > 30 && v.length <= 512,
text: (max) => (v) => typeof v === 'string' && v.trim().length > 0 && v.length <= max,
category: (v) => VALID_CATEGORIES.has(v),
bio: (v) => typeof v === 'string' && v.length <= 500,
voteValue: (v) => v === 1 || v === -1,
nonce: (v) => typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v),
client_timestamp: (v) => typeof v === 'string' && !isNaN(new Date(v).getTime()),
captchaInput: (v) => typeof v === 'string' && /^[a-zA-Z0-9]{5}$/.test(v),
// captchaToken now has 4 parts after the dynamic difficulty signing was added
captchaToken: (v) => typeof v === 'string' && v.includes(':') && v.split(':').length === 4,
powSalt: (v) => typeof v === 'string' && /^[0-9a-f]+$/i.test(v),
powChallenge: (v) => typeof v === 'string' && /^[0-9a-f]{32}$/i.test(v),
// 2FA validators
mfaCode: (v) => typeof v === 'string' && /^\d{6}$/.test(v),
mfaToken: (v) => typeof v === 'string' && v.includes(':') && v.length > 10 && v.length <= 200,
recoveryCode: (v) => typeof v === 'string' && /^[A-Z2-7]{16}$/i.test(v),
});
/**
* Middleware factory: validates req.body fields against a schema map.
* Returns 400 with the offending field name on the first failure.
*/
// Helper to derive deterministic alias field names for codename, password, and mfa otp
function getDynamicFieldAliases(timestamp) {
const userHmac = crypto.createHmac('sha256', captcha.CAPTCHA_SECRET_INTERNAL)
.update(`${timestamp}:user_field`)
.digest('hex');
const passHmac = crypto.createHmac('sha256', captcha.CAPTCHA_SECRET_INTERNAL)
.update(`${timestamp}:pass_field`)
.digest('hex');
const mfaHmac = crypto.createHmac('sha256', captcha.CAPTCHA_SECRET_INTERNAL)
.update(`${timestamp}:mfa_field`)
.digest('hex');
return {
userAlias: `v_${userHmac.substring(0, 12)}`,
passAlias: `v_${passHmac.substring(0, 12)}`,
mfaAlias: `v_${mfaHmac.substring(0, 12)}`,
};
}
/**
* Async middleware: Resolves and translates dynamically-aliased codename, password,
* and optional mfaCode fields back into their canonical req.body names.
* Rejects any payload that uses static canonical field names as bot indicators.
*/
const translateDynamicFields = async (req, res, next) => {
// Extract session timestamp from captchaIssuedAt or hpToken prefix
const timestampStr = req.body.captchaIssuedAt || (req.body.hpToken ? req.body.hpToken.split(':')[0] : '');
const timestamp = parseInt(timestampStr, 10);
if (isNaN(timestamp) || Date.now() - timestamp > 180000) {
return res.status(400).json({ error: 'REGISTRATION_REJECTED' });
}
const { userAlias, passAlias, mfaAlias } = getDynamicFieldAliases(timestamp);
// Reject immediately if static canonical field names are present — bot payload indicator
if (req.body.codename !== undefined || req.body.password !== undefined) {
return res.status(400).json({ error: 'REGISTRATION_REJECTED' });
}
// Map dynamic aliases back to canonical fields
req.body.codename = req.body[userAlias];
req.body.password = req.body[passAlias];
// mfaCode is optional (not all requests include 2FA)
if (req.body[mfaAlias] !== undefined) {
req.body.mfaCode = req.body[mfaAlias];
delete req.body[mfaAlias];
}
delete req.body[userAlias];
delete req.body[passAlias];
next();
};
const validate = (schema) => (req, res, next) => {
for (const [field, check] of Object.entries(schema)) {
if (!check(req.body[field])) {
return res.status(400).json({ error: `Invalid or missing field: ${field}` });
}
}
next();
};
// ─── Cryptographic Routines ───────────────────────────────────────────────────
/**
* Hash and verification routines using Worker Threads for scrypt offloading.
*/
const HASH_WORKERS_COUNT = 4;
const hashWorkers = [];
let hashWorkerIdx = 0;
const reqMap = new Map();
let reqIdCounter = 0;
for (let i = 0; i < HASH_WORKERS_COUNT; i++) {
const worker = new Worker(path.join(__dirname, 'server', 'workers', 'hash-worker.js'));
worker.on('message', (msg) => {
const { id, error } = msg;
const pending = reqMap.get(id);
if (pending) {
reqMap.delete(id);
if (error) pending.reject(new Error(error));
else pending.resolve(msg);
}
});
hashWorkers.push(worker);
}
function runInWorker(action, payload) {
return new Promise((resolve, reject) => {
const id = ++reqIdCounter;
reqMap.set(id, { resolve, reject });
const worker = hashWorkers[hashWorkerIdx];
hashWorkerIdx = (hashWorkerIdx + 1) % HASH_WORKERS_COUNT;
worker.postMessage({ id, action, payload });
});
}
async function hashPassword(password) {
const { result } = await runInWorker('hash', { password });
return result;
}
async function verifyPassword(password, storedHash) {
const { result, needsRehash } = await runInWorker('verify', { password, storedHash });
return { match: result, needsRehash };
}
/**
* Verifies ECDSA P-256/SHA-256 signature in IEEE P1363 raw format.
* WebCrypto SubtleCrypto produces this format natively.
*/
function verifyECDSASignature(payload, signatureBase64, publicKeySPKIBase64) {
try {
const clean = publicKeySPKIBase64.replace(/[\s\r\n]+/g, '');
const pem = `-----BEGIN PUBLIC KEY-----\n${clean.match(/.{1,64}/g).join('\n')}\n-----END PUBLIC KEY-----`;
const verify = crypto.createVerify('SHA256');
verify.update(payload, 'utf8');
verify.end();
return verify.verify(
{ key: pem, format: 'pem', type: 'spki', dsaEncoding: 'ieee-p1363' },
Buffer.from(signatureBase64, 'base64')
);
} catch {
return false;
}
}
// ─── Freshness Protocol (Replay & Drift Defense — Persistent + Memcache) ──────
const FRESHNESS_WINDOW_MS = 5 * 60 * 1000; // 5 min tolerance
const NONCE_EXPIRY_MS = 5 * 60 * 1000; // nonces live for 5 min in DB
// In-memory hot cache for sub-millisecond reads of recently seen nonces
const nonceCache = new Map();
// Garbage-collect expired nonces from DB (runs every 2 min in WAL-safe mode)
setInterval(() => {
const cutoff = Date.now() - NONCE_EXPIRY_MS;
db.run('DELETE FROM nonces WHERE created_at < ?', [cutoff], (err) => {
if (err) console.error('[C2] Nonce GC error:', err.message);
});
}, 2 * 60 * 1000).unref();
// Evict expired entries from memory cache (runs every 30s)
setInterval(() => {
const now = Date.now();
for (const [key, ts] of nonceCache.entries()) {
if (now - ts > NONCE_EXPIRY_MS) nonceCache.delete(key);
}
}, 30000).unref();
/**
* Validates a nonce + timestamp pair for freshness and non-replay.
* C2-002: Persists nonce in SQLite with UNIQUE constraint to prevent
* replay across server restarts.
* C2-003: Uses >= boundary (inclusive) with normalized millisecond clock drift.
*
* @param {string} nonce - Client-generated UUIDv4
* @param {string} timestamp - ISO-8601 timestamp from client
* @returns {boolean} true if the nonce+timestamp pair is fresh and unused
*/
function validateFreshness(nonce, timestamp) {
if (nonceCache.has(nonce)) return false;
const clientTime = new Date(timestamp).getTime();
if (isNaN(clientTime)) return false;
const serverTime = Date.now();
const driftMs = Math.abs(serverTime - clientTime);
// C2-003: Use >= for inclusive boundary — a timestamp exactly at the
// window limit must be rejected, not accepted. Normalized to milliseconds.
if (driftMs >= FRESHNESS_WINDOW_MS) return false;
// Atomically insert into in-memory cache first (fast path)
nonceCache.set(nonce, serverTime);
// Persist to DB with UNIQUE constraint. If INSERT fails due to
// duplicate nonce (race condition or prior use), the on-disk
// constraint prevents bypass across server restarts.
db.run('INSERT OR IGNORE INTO nonces (nonce, created_at) VALUES (?, ?)', [nonce, serverTime], (err) => {
if (err) console.error('[C2] Nonce persistence error:', err.message);
});
return true;
}
// ─── Session Middleware ───────────────────────────────────────────────────────
function authenticateToken(req, res, next) {
const cookies = req.headers.cookie ? Object.fromEntries(req.headers.cookie.split('; ').map(c => c.split('='))) : {};
const header = req.headers['authorization'];
const token = (header?.startsWith('Bearer ') ? header.slice(7) : null) || cookies.token;
if (!token) return res.status(401).json({ error: 'Authentication required.' });
db.get(
'SELECT s.codename, s.expires_at, u.status AS account_status, m.status AS mod_status, u.role FROM sessions s JOIN users u ON s.codename = u.codename LEFT JOIN moderation m ON s.codename = m.codename WHERE s.token = ?',
[token],
(err, session) => {
if (err || !session) return res.status(403).json({ error: 'Invalid session.' });
if (Date.now() > session.expires_at) {
db.run('DELETE FROM sessions WHERE token = ?', [token]);
return res.status(403).json({ error: 'Session expired. Re-authenticate.' });
}
if (session.mod_status === 'BANNED') {
db.run('DELETE FROM sessions WHERE token = ?', [token]);
return res.status(403).json({ error: 'Access denied. Account is banned.' });
}
req.userCodename = session.codename;
req.accountStatus = session.account_status;
req.userRole = session.role;
// Async update last_seen activity timestamp
db.run('UPDATE users SET last_seen = ? WHERE codename = ?', [Date.now(), session.codename]);
next();
}
);
}
function requireActiveAdmission(req, res, next) {
if (req.userRole === 'COMMANDER') {
return next();
}
if (req.accountStatus === 'PENDING_ADMISSION') {
return res.status(403).json({ error: 'Admission pending. Complete the entrance challenge to access this endpoint.', status: 'PENDING_ADMISSION' });
}
next();
}
function requireCommander(req, res, next) {
const cookies = req.headers.cookie ? Object.fromEntries(req.headers.cookie.split('; ').map(c => c.split('='))) : {};
const header = req.headers['authorization'];
const token = cookies.token || (header?.startsWith('Bearer ') ? header.slice(7) : null);
if (!token) return res.status(401).json({ error: 'Authentication required.' });
db.get(
'SELECT s.codename, s.expires_at, u.role FROM sessions s JOIN users u ON s.codename = u.codename WHERE s.token = ?',
[token],
(err, session) => {
if (err || !session) return res.status(403).json({ error: 'Invalid session.' });
if (Date.now() > session.expires_at) {
db.run('DELETE FROM sessions WHERE token = ?', [token]);
return res.status(403).json({ error: 'Session expired. Re-authenticate.' });
}
if (session.role !== 'COMMANDER') {
return res.status(403).json({ error: 'Action restricted to Commanders.' });
}
req.userCodename = session.codename;
next();
}
);
}
function optionalAuthenticateToken(req, res, next) {
const cookies = req.headers.cookie ? Object.fromEntries(req.headers.cookie.split('; ').map(c => c.split('='))) : {};
const header = req.headers['authorization'];
const token = (header?.startsWith('Bearer ') ? header.slice(7) : null) || cookies.token;
if (!token) {
req.userCodename = null;
return next();
}
db.get(
'SELECT s.codename, s.expires_at, u.status AS account_status FROM sessions s JOIN users u ON s.codename = u.codename WHERE s.token = ?',
[token],
(err, session) => {
if (err || !session || Date.now() > session.expires_at) {
req.userCodename = null;
} else {
req.userCodename = session.codename;
req.accountStatus = session.account_status;
}
next();
}
);
}
// ─── Express Application ──────────────────────────────────────────────────────
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: (origin, callback) => {
if (process.env.NODE_ENV !== 'production') return callback(null, true);
if (!origin || origin === ALLOWED_ORIGIN) return callback(null, true);
return callback(new Error('CORS_POLICY_VIOLATION'));
},
methods: ["GET", "POST"]
},
maxHttpBufferSize: 5000 // 5KB max payload to prevent ZD-002 DoS
});
const activeSockets = new Map(); // codename -> Set of socket.ids
// Socket.io Handshake Authentication Middleware
io.use((socket, next) => {
const cookieStr = socket.handshake.headers.cookie;
const cookies = cookieStr ? Object.fromEntries(cookieStr.split('; ').map(c => c.split('='))) : {};
const token = cookies.token || socket.handshake.auth.token;
if (!token) return next(new Error('Authentication required.'));
db.get(
'SELECT s.codename, s.expires_at, u.status AS account_status, m.status AS mod_status FROM sessions s JOIN users u ON s.codename = u.codename LEFT JOIN moderation m ON s.codename = m.codename WHERE s.token = ?',
[token],
(err, session) => {
if (err || !session) return next(new Error('Invalid session.'));
if (Date.now() > session.expires_at) {
db.run('DELETE FROM sessions WHERE token = ?', [token]);
return next(new Error('Session expired.'));
}
if (session.mod_status === 'BANNED') {
return next(new Error('Account banned.'));
}
if (session.account_status === 'PENDING_ADMISSION') {
return next(new Error('Admission pending.'));
}
socket.codename = session.codename;
next();
}
);
});
// Active Socket Session Validator (Heartbeat)
setInterval(() => {
if (activeSockets.size === 0) return;
const codenames = Array.from(activeSockets.keys());
const placeholders = codenames.map(() => '?').join(',');
db.all(`SELECT codename FROM sessions WHERE codename IN (${placeholders}) AND expires_at > ?`, [...codenames, Date.now()], (err, rows) => {
if (err) return;
const validCodenames = new Set(rows.map(r => r.codename));
for (const [codename, sockets] of activeSockets.entries()) {
if (!validCodenames.has(codename)) {
for (const sid of sockets) {
const s = io.sockets.sockets.get(sid);
if (s) s.disconnect(true);
}
}
}
});
}, 30000).unref();
io.on('connection', (socket) => {
const codename = socket.codename;
const isNewConnection = !activeSockets.has(codename);
if (isNewConnection) {
activeSockets.set(codename, new Set());
}
activeSockets.get(codename).add(socket.id);
// Send full presence strictly to the connecting client
db.all('SELECT codename, role, last_seen FROM users ORDER BY codename ASC', [], (err, rows) => {
if (err) return;
const presence = rows.map((u) => ({
codename: u.codename,
role: u.role,
last_seen: u.last_seen,
isOnline: activeSockets.has(u.codename)
}));
socket.emit('presence-full', presence);
});
if (isNewConnection) {
socket.broadcast.emit('presence:join', { codename });
}
db.run('UPDATE users SET last_seen = ? WHERE codename = ?', [Date.now(), codename]);
// Telemetry Ping/Pong
socket.on('ping', (timestamp, callback) => {
if (typeof callback === 'function') callback(timestamp);
});
socket.on('disconnect', () => {
const userSockets = activeSockets.get(codename);
if (userSockets) {
userSockets.delete(socket.id);
if (userSockets.size === 0) {
activeSockets.delete(codename);
io.emit('presence:leave', { codename });
}
}
});
});
// Path Traversal Mitigation — Global Gateway Filter
app.use((req, res, next) => {
try {
const decodedPath = decodeURIComponent(req.path);
const decodedUrl = decodeURIComponent(req.originalUrl);
if (
req.path.includes('..') ||
req.originalUrl.includes('..') ||
decodedPath.includes('..') ||
decodedUrl.includes('..')
) {
return res.status(400).json({ error: 'PATH_TRAVERSAL_DETECTED' });
}
} catch {
return res.status(400).json({ error: 'INVALID_URI_ENCODING' });
}
next();
});
// 1. Security headers via Helmet
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: [
"'self'",
"https://cdn.jsdelivr.net",
],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdn.jsdelivr.net"],
imgSrc: ["'self'", 'data:'],
connectSrc: ["'self'", "ws:", "wss:", "https://cdn.jsdelivr.net"],
fontSrc: ["'self'", "https://fonts.gstatic.com", "https://cdn.jsdelivr.net"],
objectSrc: ["'none'"],
mediaSrc: ["'self'", "data:"],
frameSrc: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: [],
},
},
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
xContentTypeOptions: true,
xFrameOptions: { action: 'deny' },
crossOriginEmbedderPolicy: false, // Avoid breaking Cloudflare Tunnel
}));
// 2. CORS — strict origin allowlist
app.use(cors({
origin: (origin, callback) => {
if (process.env.NODE_ENV !== 'production') return callback(null, true);
// Allow requests with no origin (like direct browser navigation to index.html)
// In actual production we might check against a specific domain
return callback(null, true);
},
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 600,
}));
// 3. Body parsing with 50 KB hard cap
app.use(express.json({ limit: '50kb' }));
// 1. C2-001: Reject null bytes in query parameters (bypasses SQLite LIKE filters)
app.use((req, res, next) => {
if (req.query) {
for (const key in req.query) {
if (typeof req.query[key] === 'string' && req.query[key].includes('\x00')) {
return res.status(400).json({ error: 'Invalid characters in query parameters.' });
}
}
}
next();
});
// ── Static files — ONLY public/ directory (no-cache for instant development updates)
app.use(express.static(path.join(__dirname, 'public'), {
dotfiles: 'deny',
index: false,
setHeaders: (res) => {
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
},
}));
// Root → index.html
app.get('/', (req, res) => {
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Favicon fallback handler to prevent console clutter
app.get('/favicon.ico', (req, res) => {
res.status(204).end();
});
// ─── API Routes ───────────────────────────────────────────────────────────────
// ── Auth: Captcha Challenge ──────────────────────────────────────────────────
app.get('/api/auth/captcha', (req, res) => {
const ip = req.ip || req.socket.remoteAddress;
const difficulty = captcha.getAdaptiveDifficulty(ip);
const text = captcha.generateCaptchaText();
const svg = captcha.generateCaptchaSvg(text);
const token = captcha.createCaptchaToken(text, difficulty);
const powChallenge = crypto.randomBytes(16).toString('hex');
const captchaIssuedAt = Date.now();
// C2-004: Dynamic honeypot field names derived from HMAC(secret, timestamp, index)
// Each field name is unpredictable per-session. Bots that try to auto-fill known
// field names like "email" cannot bypass this.
const honeypotFields = [];
for (let i = 0; i < 3; i++) {
const hmac = crypto.createHmac('sha256', captcha.CAPTCHA_SECRET_INTERNAL)
.update(`${captchaIssuedAt}:${i}:honeypot`)
.digest('hex');
const fieldName = `v_${hmac.substring(0, 12)}`;
honeypotFields.push({
name: fieldName,
label: i === 0 ? 'Email verification' : i === 1 ? 'Phone validation' : 'Secondary authentication',
technique: i, // 0=offscreen, 1=opacity, 2=hidden-input
});
}
// Get dynamic field aliases for codename, password, and mfa code
const { userAlias, passAlias, mfaAlias } = getDynamicFieldAliases(captchaIssuedAt);
// Honeypot integrity token: binds the expected empty fields to this session
const hpTokenPayload = `${captchaIssuedAt}:${honeypotFields.map(f => f.name).join(',')}`;
const hpToken = `${captchaIssuedAt}:${crypto.createHmac('sha256', captcha.CAPTCHA_SECRET_INTERNAL)
.update(hpTokenPayload)
.digest('hex')}`;
res.json({
captchaSvg: Buffer.from(svg).toString('base64'),
captchaToken: token,
powChallenge,
powDifficulty: difficulty,
captchaIssuedAt,
honeypotFields,
hpToken,
userField: userAlias,
passwordField: passAlias,
mfaField: mfaAlias,
});
});
// ── Auth: Register ────────────────────────────────────────────────────────────
// Two-tier throttle:
// Tier-1 (structuralLimiter): caps ALL requests to this endpoint at 200/15min,
// regardless of payload shape. Blocks floods of garbage before any parsing.
// Tier-2 (validate): rejects malformed payloads cheaply (no DB, no crypto).
// Tier-3 (authLimiter): caps structurally-valid auth attempts at 10/15min.
app.post('/api/auth/register',
structuralLimiter,
translateDynamicFields,
validate({
codename: Validators.codename,
password: Validators.authKey,
publicKeySPKI: Validators.spkiBase64,
encryptedPrivateKey: Validators.encKey,
captchaInput: Validators.captchaInput,
captchaToken: Validators.captchaToken,
powChallenge: Validators.powChallenge,
powSalt: Validators.powSalt,
}),
authLimiter,
async (req, res) => {
const {
codename,
password,
publicKeySPKI,
encryptedPrivateKey,
captchaInput,
captchaToken,
powChallenge,
powSalt,
hpToken,
captchaIssuedAt,
} = req.body;
// Core-schema validation already ran in the pre-gate middleware above.
// Only dynamic/contextual checks (timing, honeypot, PoW) remain here.
// C2-004 Layer 1: Time-to-submit validation — reject registrations that arrive
// too quickly after the CAPTCHA was issued (< 5s, bots are faster than humans)
const submitTime = Date.now();
const captchaIssueTime = parseInt(captchaIssuedAt, 10);
if (isNaN(captchaIssueTime) || submitTime - captchaIssueTime < 5000) {
return res.status(400).json({ error: 'Registration completed too quickly. Bot detected.' });
}
if (submitTime - captchaIssueTime > 180000) {
return res.status(400).json({ error: 'REGISTRATION_REJECTED' });
}
// C2-004 Layer 2: Validate honeypot integrity token
if (!hpToken || !hpToken.includes(':')) {
return res.status(400).json({ error: 'REGISTRATION_REJECTED' });
}
const [hpTimestampStr, hpSig] = hpToken.split(':');
const hpTimestamp = parseInt(hpTimestampStr, 10);
if (isNaN(hpTimestamp) || Math.abs(submitTime - hpTimestamp) > 180000) {
return res.status(400).json({ error: 'REGISTRATION_REJECTED' });
}
// C2-004 Layer 3: Reconstruct expected honeypot field names and verify integrity
const expectedHpNames = [];
for (let i = 0; i < 3; i++) {