-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
2380 lines (2044 loc) · 78.8 KB
/
Copy pathindex.js
File metadata and controls
2380 lines (2044 loc) · 78.8 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const { Pool } = require('pg');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { authenticator } = require('otplib');
const { v4: uuidv4 } = require('uuid');
const axios = require('axios');
const redis = require('redis');
const { DOMParser } = require('@xmldom/xmldom');
const { SignedXml } = require('xml-crypto');
const { subtle } = crypto.webcrypto;
const {
generateRegistrationOptions,
verifyRegistrationResponse,
generateAuthenticationOptions,
verifyAuthenticationResponse,
} = require('@simplewebauthn/server');
const promClient = require('prom-client');
const httpRequestCount = new promClient.Counter({
name: 'atlas_http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'path', 'status_code'],
});
const httpRequestDuration = new promClient.Histogram({
name: 'atlas_http_request_duration_seconds',
help: 'HTTP request duration in seconds',
labelNames: ['method', 'path', 'status_code'],
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
});
const httpRequestsInProgress = new promClient.Gauge({
name: 'atlas_http_requests_in_progress',
help: 'Number of HTTP requests in progress',
labelNames: ['method', 'path'],
});
promClient.collectDefaultMetrics();
const app = express();
app.use(helmet());
app.use(cookieParser());
app.use(express.json({ limit: '1mb' }));
const allowedOrigins = (process.env.ALLOWED_ORIGINS || 'http://localhost:3000')
.split(',')
.map((o) => o.trim())
.filter(Boolean);
app.use(
cors({
origin(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
})
);
function metricsMiddleware(req, res, next) {
if (req.path === '/metrics' || req.path === '/health') {
return next();
}
const path = req.path.replace(/\/[0-9a-fA-F-]{36}|\/\d+/g, '/:param');
httpRequestsInProgress.labels({ method: req.method, path }).inc();
const start = Date.now();
res.on('finish', () => {
const duration = (Date.now() - start) / 1000;
httpRequestsInProgress.labels({ method: req.method, path }).dec();
httpRequestCount.labels({ method: req.method, path, status_code: res.statusCode }).inc();
httpRequestDuration.labels({ method: req.method, path, status_code: res.statusCode }).observe(duration);
});
next();
}
app.use(metricsMiddleware);
const PORT = process.env.PORT || 8010;
const NODE_ENV = process.env.NODE_ENV || 'development';
const JWT_SECRET = process.env.JWT_SECRET;
const ADMIN_DEFAULT_PASSWORD = process.env.ADMIN_DEFAULT_PASSWORD;
const ACCESS_EXPIRY = '15m';
const REFRESH_EXPIRY_DAYS = 7;
const MAX_FAILED_ATTEMPTS = 5;
const LOCKOUT_MINUTES = 15;
const AUDIT_SERVICE_URL = process.env.AUDIT_SERVICE_URL || 'http://audit-compliance-service:8011';
const AUDIT_INTERNAL_KEY = process.env.AUDIT_INTERNAL_KEY;
const SAML_IDP_SSO_URL = process.env.SAML_IDP_SSO_URL || 'https://idp.example.com/sso';
const SAML_IDP_ENTITY_ID = process.env.SAML_IDP_ENTITY_ID || 'https://idp.example.com/metadata';
const SAML_IDP_CERT = (process.env.SAML_IDP_CERT || '').replace(/\\n/g, '\n');
const SCIM_API_KEY = process.env.SCIM_API_KEY;
if (!JWT_SECRET) {
console.error('FATAL: JWT_SECRET environment variable is required');
process.exit(1);
}
if (!ADMIN_DEFAULT_PASSWORD) {
console.error('FATAL: ADMIN_DEFAULT_PASSWORD environment variable is required');
process.exit(1);
}
if (!AUDIT_INTERNAL_KEY) {
console.error('FATAL: AUDIT_INTERNAL_KEY environment variable is required');
process.exit(1);
}
if (!SCIM_API_KEY) {
console.error('FATAL: SCIM_API_KEY environment variable is required');
process.exit(1);
}
const jwtSecret = JWT_SECRET;
if (!process.env.POSTGRES_URL) {
console.error('FATAL: POSTGRES_URL environment variable is required');
process.exit(1);
}
const sslConfig = process.env.POSTGRES_SSL === 'true' || NODE_ENV === 'production'
? { rejectUnauthorized: true }
: false;
const pool = new Pool({
connectionString: process.env.POSTGRES_URL,
ssl: sslConfig,
});
const REDIS_URL = process.env.REDIS_URL || 'redis://redis:6379';
const redisClient = redis.createClient({ url: REDIS_URL });
redisClient.on('error', (err) => console.log('Auth Redis Client Error', err));
(async () => {
try {
await redisClient.connect();
} catch (err) {
console.error('Auth Redis connection failed, nonce check disabled:', err);
}
})();
const BCRYPT_COST = 12;
function sanitizeForLogs(obj) {
const sensitiveKeys = new Set(['password', 'token', 'secret', 'authorization', 'cookie', 'mfa_secret', 'backup_codes', 'client_secret', 'access_token', 'refresh_token']);
if (!obj || typeof obj !== 'object') return obj;
const sanitized = Array.isArray(obj) ? [...obj] : { ...obj };
for (const [key, value] of Object.entries(sanitized)) {
if (sensitiveKeys.has(key.toLowerCase())) {
sanitized[key] = '[REDACTED]';
} else if (typeof value === 'object' && value !== null) {
sanitized[key] = sanitizeForLogs(value);
}
}
return sanitized;
}
function safeLog(logFn, msg, data) {
if (data) {
logFn(msg, sanitizeForLogs(data));
} else {
logFn(msg);
}
}
function validatePassword(password) {
if (!password || password.length < 8) {
return 'Password must be at least 8 characters';
}
if (!/[A-Z]/.test(password)) {
return 'Password must contain at least one uppercase letter';
}
if (!/[0-9]/.test(password)) {
return 'Password must contain at least one number';
}
return null;
}
function hashToken(token) {
return crypto.createHash('sha256').update(token).digest('hex');
}
function signAccessToken(user) {
return jwt.sign(
{ id: user.id, email: user.email, role: user.role, tenant_id: user.tenant_id || 'default' },
jwtSecret,
{ algorithm: 'HS256', expiresIn: ACCESS_EXPIRY }
);
}
function signMfaToken(userId) {
return jwt.sign(
{ id: userId, mfa_validated: true, purpose: 'mfa_step_up' },
jwtSecret,
{ algorithm: 'HS256', expiresIn: '5m' }
);
}
async function createRefreshToken(userId) {
const token = crypto.randomBytes(48).toString('hex');
const tokenHash = hashToken(token);
const expiresAt = new Date();
expiresAt.setDate(expiresAt.getDate() + REFRESH_EXPIRY_DAYS);
await pool.query(
'INSERT INTO refresh_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
[userId, tokenHash, expiresAt]
);
return token;
}
async function revokeRefreshToken(refreshToken) {
if (!refreshToken) return;
const tokenHash = hashToken(refreshToken);
await pool.query('DELETE FROM refresh_tokens WHERE token_hash = $1', [tokenHash]);
}
async function verifyRefreshToken(refreshToken) {
const tokenHash = hashToken(refreshToken);
const result = await pool.query(
`SELECT rt.*, u.id, u.email, u.name, u.role, u.department, u.position, u.tenant_id
FROM refresh_tokens rt
JOIN users u ON u.id = rt.user_id
WHERE rt.token_hash = $1 AND rt.expires_at > NOW()`,
[tokenHash]
);
return result.rows[0] || null;
}
async function revokeAllUserSessions(userId) {
await pool.query('UPDATE sessions SET is_active = false WHERE user_id = $1', [userId]);
await pool.query('DELETE FROM refresh_tokens WHERE user_id = $1', [userId]);
}
async function recordFailedAttempt(email) {
const lockedUntil = new Date();
lockedUntil.setMinutes(lockedUntil.getMinutes() + LOCKOUT_MINUTES);
await pool.query(
`INSERT INTO failed_attempts (email, attempts, locked_until)
VALUES ($1, 1, NULL)
ON CONFLICT (email) DO UPDATE SET
attempts = failed_attempts.attempts + 1,
locked_until = CASE
WHEN failed_attempts.attempts + 1 >= $2 THEN $3
ELSE failed_attempts.locked_until
END`,
[email, MAX_FAILED_ATTEMPTS, lockedUntil]
);
}
async function clearFailedAttempts(email) {
await pool.query('DELETE FROM failed_attempts WHERE email = $1', [email]);
}
async function isAccountLocked(email) {
const result = await pool.query(
'SELECT attempts, locked_until FROM failed_attempts WHERE email = $1',
[email]
);
const row = result.rows[0];
if (!row) return false;
if (row.locked_until && new Date(row.locked_until) > new Date()) {
return true;
}
if (row.locked_until && new Date(row.locked_until) <= new Date()) {
await pool.query('DELETE FROM failed_attempts WHERE email = $1', [email]);
return false;
}
return false;
}
function sanitizeUser(user) {
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
department: user.department,
position: user.position,
tenant_id: user.tenant_id || 'default',
};
}
function requireRole(...roles) {
return (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ message: 'Authentication required' });
}
try {
const token = authHeader.slice(7);
const payload = jwt.verify(token, jwtSecret, { algorithms: ['HS256'] });
if (roles.length && !roles.includes(payload.role)) {
return res.status(403).json({ message: 'Insufficient permissions' });
}
req.user = payload;
next();
} catch {
return res.status(401).json({ message: 'Invalid or expired token' });
}
};
}
function requireScimAuth(req, res, next) {
const apiKey = req.headers['x-api-key'];
const authHeader = req.headers.authorization;
if (apiKey && apiKey === SCIM_API_KEY) {
return next();
}
if (authHeader?.startsWith('Bearer ')) {
try {
const payload = jwt.verify(authHeader.slice(7), jwtSecret, { algorithms: ['HS256'] });
req.user = payload;
return next();
} catch {
// Fall through to error
}
}
return res.status(401).json({
schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],
detail: 'Authentication required',
status: '401'
});
}
const rateLimitStore = new Map();
function createUserRateLimiter(action, maxRequests = 20, windowMs = 15 * 60 * 1000) {
return (req, res, next) => {
const identifier = req.user?.id || req.ip;
const key = `${identifier}:${action}`;
const now = Date.now();
let entry = rateLimitStore.get(key);
if (!entry) {
entry = { count: 1, startTime: now };
rateLimitStore.set(key, entry);
} else {
if (now - entry.startTime > windowMs) {
entry.count = 1;
entry.startTime = now;
} else {
entry.count++;
}
}
res.setHeader('X-RateLimit-Limit', maxRequests);
res.setHeader('X-RateLimit-Remaining', Math.max(0, maxRequests - entry.count));
res.setHeader('X-RateLimit-Reset', Math.ceil((entry.startTime + windowMs) / 1000));
if (entry.count > maxRequests) {
return res.status(429).json({
message: 'Too many requests. Please try again later.',
retryAfter: Math.ceil((entry.startTime + windowMs - now) / 1000)
});
}
next();
};
}
setInterval(() => {
const now = Date.now();
for (const [key, entry] of rateLimitStore.entries()) {
if (now - entry.startTime > 30 * 60 * 1000) {
rateLimitStore.delete(key);
}
}
}, 60 * 1000);
async function sendAuditEvent(eventType, userId, email, details = {}) {
try {
await axios.post(`${AUDIT_SERVICE_URL}/api/v1/audit/log`, {
event_type: eventType,
user_id: userId,
email,
timestamp: new Date().toISOString(),
details,
service: 'auth-service'
}, {
headers: { 'X-Internal-Key': AUDIT_INTERNAL_KEY },
timeout: 3000
});
} catch (err) {
console.error(`Audit log failed for ${eventType}:`, err.message);
}
}
function formatScimUser(user, baseUrl) {
const nameParts = (user.name || '').split(' ');
return {
schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
id: String(user.id),
userName: user.email,
name: {
formatted: user.name || '',
givenName: nameParts[0] || '',
familyName: nameParts.slice(1).join(' ') || ''
},
emails: [
{
value: user.email,
primary: true,
type: 'work'
}
],
roles: [
{
value: user.role || 'employee',
type: 'default'
}
],
active: user.active !== false,
meta: {
resourceType: 'User',
created: user.created_at || new Date().toISOString(),
lastModified: user.updated_at || user.created_at || new Date().toISOString(),
version: `W/"${user.id}"`,
location: `${baseUrl}/scim/v2/Users/${user.id}`
}
};
}
async function sendScimError(res, status, detail) {
return res.status(status).json({
schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],
detail,
status: String(status)
});
}
async function initDB() {
await pool.query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
role VARCHAR(50) DEFAULT 'employee',
department VARCHAR(100),
position VARCHAR(100),
tenant_id VARCHAR(50) DEFAULT 'default',
active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
`);
const columnsToAdd = [
"ALTER TABLE users ADD COLUMN IF NOT EXISTS active BOOLEAN DEFAULT true;",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS created_at TIMESTAMP DEFAULT NOW();",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP DEFAULT NOW();"
];
for (const sql of columnsToAdd) {
try { await pool.query(sql); } catch (err) { /* column may exist */ }
}
try {
await pool.query("ALTER TABLE users ADD COLUMN tenant_id VARCHAR(50) DEFAULT 'default';");
} catch (err) { /* column may exist */ }
await pool.query(`
CREATE TABLE IF NOT EXISTS refresh_tokens (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(64) NOT NULL UNIQUE,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS failed_attempts (
email VARCHAR(255) PRIMARY KEY,
attempts INTEGER DEFAULT 0,
locked_until TIMESTAMP
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS user_mfa (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
mfa_secret VARCHAR(255) NOT NULL,
backup_codes JSONB DEFAULT '[]'::jsonb,
mfa_enabled BOOLEAN DEFAULT false,
backup_codes_shown BOOLEAN DEFAULT false
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS user_devices (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
device_id VARCHAR(255) NOT NULL,
device_name VARCHAR(200),
device_type VARCHAR(50),
os VARCHAR(50),
browser VARCHAR(50),
ip_address VARCHAR(45),
fingerprint VARCHAR(255),
is_trusted BOOLEAN DEFAULT false,
last_used_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(user_id, device_id)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS sessions (
id UUID PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(64),
ip_address VARCHAR(45),
user_agent TEXT,
device_id VARCHAR(255),
is_active BOOLEAN DEFAULT true,
expires_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS passwordless_tokens (
token VARCHAR(64) PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
email VARCHAR(255) NOT NULL,
expires_at TIMESTAMP NOT NULL,
used BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS webauthn_credentials (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
credential_id VARCHAR(255) NOT NULL UNIQUE,
public_key TEXT NOT NULL,
counter INTEGER DEFAULT 0,
device_name VARCHAR(200),
device_type VARCHAR(50),
transports JSONB DEFAULT '[]'::jsonb,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
last_used_at TIMESTAMP
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS oauth_providers (
id SERIAL PRIMARY KEY,
provider VARCHAR(50) NOT NULL,
client_id VARCHAR(255) NOT NULL,
client_secret VARCHAR(255) NOT NULL,
redirect_uri VARCHAR(500),
scopes VARCHAR(500) DEFAULT 'openid email profile',
enabled BOOLEAN DEFAULT true,
tenant_id VARCHAR(50) DEFAULT 'default',
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(provider, tenant_id)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS oauth_states (
state VARCHAR(64) PRIMARY KEY,
provider VARCHAR(50) NOT NULL,
tenant_id VARCHAR(50) DEFAULT 'default',
redirect_to VARCHAR(500),
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS oauth_links (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider VARCHAR(50) NOT NULL,
provider_user_id VARCHAR(255) NOT NULL,
access_token TEXT,
refresh_token TEXT,
expires_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(provider, provider_user_id)
);
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS rotated_tokens (
id SERIAL PRIMARY KEY,
token_hash VARCHAR(64) NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT NOW()
);
`);
const adminCheck = await pool.query('SELECT * FROM users WHERE email = $1', [
'admin@atlas.io',
]);
if (adminCheck.rows.length === 0) {
const hashedPass = await bcrypt.hash(ADMIN_DEFAULT_PASSWORD, BCRYPT_COST);
await pool.query(
'INSERT INTO users (email, password, name, role, department, position, tenant_id) VALUES ($1, $2, $3, $4, $5, $6, $7)',
[
'admin@atlas.io',
hashedPass,
'Super Admin',
'admin',
'Global',
'System Administrator',
'default'
]
);
console.log('Default admin user created (admin@atlas.io)');
}
console.log('Database initialized successfully.');
}
initDB().catch((err) => {
console.error('Database initialization failed:', err);
});
app.post('/register', createUserRateLimiter('register', 10), async (req, res) => {
const { email, password, name, department, position, tenant_id } = req.body;
if (!email || !password || !name) {
return res.status(400).json({ message: 'Email, password, and name are required' });
}
const passwordError = validatePassword(password);
if (passwordError) {
return res.status(400).json({ message: passwordError });
}
try {
const userExists = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
if (userExists.rows.length > 0) {
return res.status(400).json({ message: 'User already exists' });
}
const hashedPassword = await bcrypt.hash(password, BCRYPT_COST);
const result = await pool.query(
'INSERT INTO users (email, password, name, role, department, position, tenant_id) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id, email, name, role, department, position, tenant_id',
[
email,
hashedPassword,
name,
'employee',
department || 'General',
position || 'Staff',
tenant_id || 'default'
]
);
await sendAuditEvent('auth.register', result.rows[0].id, email, {
role: 'employee',
tenant_id: tenant_id || 'default'
});
res.status(201).json({
message: 'User registered successfully',
user: sanitizeUser(result.rows[0]),
});
} catch (error) {
console.error(error);
if (error.code === '23505') {
return res.status(409).json({ message: 'User already exists' });
}
res.status(500).json({ message: 'Server error during registration' });
}
});
app.post('/login', createUserRateLimiter('login', 20), async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ message: 'Email and password are required' });
}
try {
if (await isAccountLocked(email)) {
return res.status(423).json({
message: `Account locked. Try again in ${LOCKOUT_MINUTES} minutes.`,
});
}
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
const user = result.rows[0];
if (!user) {
await recordFailedAttempt(email);
return res.status(401).json({ message: 'Invalid credentials' });
}
if (!user.active) {
return res.status(403).json({ message: 'Account is deactivated' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
await recordFailedAttempt(email);
return res.status(401).json({ message: 'Invalid credentials' });
}
await clearFailedAttempts(email);
const deviceId = req.headers['x-device-id'];
const deviceFingerprint = req.headers['x-device-fingerprint'];
let deviceTrusted = false;
if (deviceId && deviceFingerprint) {
const deviceResult = await pool.query(
'SELECT is_trusted FROM user_devices WHERE user_id = $1 AND device_id = $2 AND fingerprint = $3',
[user.id, deviceId, deviceFingerprint]
);
if (deviceResult.rows[0]) {
deviceTrusted = deviceResult.rows[0].is_trusted;
await pool.query(
'UPDATE user_devices SET last_used_at = NOW(), ip_address = $1 WHERE user_id = $2 AND device_id = $3',
[req.ip, user.id, deviceId]
);
}
}
const mfaResult = await pool.query(
'SELECT mfa_enabled FROM user_mfa WHERE user_id = $1',
[user.id]
);
const mfaRequired = mfaResult.rows[0]?.mfa_enabled || false;
const token = signAccessToken(user);
const refreshToken = await createRefreshToken(user.id);
const sessionId = uuidv4();
await pool.query(
`INSERT INTO sessions (id, user_id, token_hash, ip_address, user_agent, device_id, is_active, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, true, $7)`,
[sessionId, user.id, hashToken(refreshToken), req.ip, req.headers['user-agent'] || '', deviceId || null,
new Date(Date.now() + REFRESH_EXPIRY_DAYS * 24 * 60 * 60 * 1000)]
);
res.cookie('refreshToken', refreshToken, {
httpOnly: true,
secure: NODE_ENV === 'production',
sameSite: 'strict',
maxAge: REFRESH_EXPIRY_DAYS * 24 * 60 * 60 * 1000,
});
await sendAuditEvent('auth.login', user.id, email, {
device_trusted: deviceTrusted,
mfa_required: mfaRequired,
device_id: deviceId,
ip_address: req.ip,
user_agent: req.headers['user-agent'],
session_id: sessionId
});
res.status(200).json({
message: 'Logged in successfully',
token,
session_id: sessionId,
user: sanitizeUser(user),
device_trusted: deviceTrusted,
mfa_required: mfaRequired
});
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server error during login' });
}
});
app.post('/refresh', async (req, res) => {
const refreshToken = req.cookies?.refreshToken;
if (!refreshToken) {
return res.status(400).json({ message: 'Refresh token is required' });
}
try {
const row = await verifyRefreshToken(refreshToken);
if (!row) {
const tokenHash = hashToken(refreshToken);
const rotatedCheck = await pool.query(
'SELECT user_id FROM rotated_tokens WHERE token_hash = $1',
[tokenHash]
);
if (rotatedCheck.rows[0]) {
const userId = rotatedCheck.rows[0].user_id;
await revokeAllUserSessions(userId);
await pool.query('DELETE FROM rotated_tokens WHERE token_hash = $1', [tokenHash]);
await sendAuditEvent('auth.refresh_token_reuse', userId, null, { action: 'all_sessions_revoked' });
return res.status(401).json({ message: 'Token reuse detected. All sessions revoked.' });
}
return res.status(401).json({ message: 'Invalid or expired refresh token' });
}
const oldTokenHash = hashToken(refreshToken);
await pool.query(
'INSERT INTO rotated_tokens (token_hash, user_id) VALUES ($1, $2)',
[oldTokenHash, row.id]
);
await pool.query("DELETE FROM rotated_tokens WHERE created_at < NOW() - INTERVAL '1 hour'");
await revokeRefreshToken(refreshToken);
const user = {
id: row.id,
email: row.email,
role: row.role,
};
const token = signAccessToken(user);
const newRefreshToken = await createRefreshToken(row.user_id);
res.cookie('refreshToken', newRefreshToken, {
httpOnly: true,
secure: NODE_ENV === 'production',
sameSite: 'strict',
maxAge: REFRESH_EXPIRY_DAYS * 24 * 60 * 60 * 1000,
});
res.status(200).json({
message: 'Token refreshed',
token,
user: sanitizeUser(row),
});
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server error during token refresh' });
}
});
app.post('/logout', async (req, res) => {
const refreshToken = req.cookies?.refreshToken;
const sessionId = req.headers['x-session-id'];
let userId = null;
let userEmail = null;
try {
if (refreshToken) {
const row = await verifyRefreshToken(refreshToken);
if (row) {
userId = row.id;
userEmail = row.email;
}
await revokeRefreshToken(refreshToken);
}
if (sessionId) {
await pool.query('UPDATE sessions SET is_active = false WHERE id = $1', [sessionId]);
} else if (refreshToken) {
await pool.query('UPDATE sessions SET is_active = false WHERE token_hash = $1', [hashToken(refreshToken)]);
}
res.clearCookie('refreshToken');
if (userId) {
await sendAuditEvent('auth.logout', userId, userEmail, {
session_id: sessionId,
ip_address: req.ip
});
}
res.status(200).json({ message: 'Logged out successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server error during logout' });
}
});
app.post('/mfa/setup', requireRole(), createUserRateLimiter('mfa_setup', 5), async (req, res) => {
try {
const userId = req.user.id;
const secret = authenticator.generateSecret();
const backupCodes = Array.from({ length: 10 }, () => crypto.randomBytes(5).toString('hex').slice(0, 8).toUpperCase());
const existing = await pool.query('SELECT backup_codes_shown FROM user_mfa WHERE user_id = $1', [userId]);
const alreadyShown = existing.rows[0]?.backup_codes_shown === true;
await pool.query(`
INSERT INTO user_mfa (user_id, mfa_secret, backup_codes, mfa_enabled)
VALUES ($1, $2, $3::jsonb, false)
ON CONFLICT (user_id) DO UPDATE SET
mfa_secret = EXCLUDED.mfa_secret,
backup_codes = EXCLUDED.backup_codes,
mfa_enabled = false,
backup_codes_shown = false
`, [userId, secret, JSON.stringify(backupCodes)]);
const otpauth = authenticator.keyuri(req.user.email, 'Atlas Workforce', secret);
const response = { secret, qr_code_uri: otpauth };
if (alreadyShown) {
response.message = 'Backup codes were regenerated. Use /mfa/rotate-backup-codes to view new codes with re-authentication.';
} else {
await pool.query('UPDATE user_mfa SET backup_codes_shown = true WHERE user_id = $1', [userId]);
response.backup_codes = backupCodes;
response.message = 'Save these backup codes. They will not be shown again.';
}
res.json(response);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'MFA setup failed' });
}
});
app.post('/mfa/rotate-backup-codes', requireRole(), createUserRateLimiter('mfa_verify', 5), async (req, res) => {
try {
const { token } = req.body;
if (!token) {
return res.status(400).json({ message: 'Current TOTP token is required to rotate backup codes' });
}
const userId = req.user.id;
const result = await pool.query('SELECT * FROM user_mfa WHERE user_id = $1', [userId]);
if (!result.rows[0]) {
return res.status(400).json({ message: 'MFA not set up' });
}
const isValid = authenticator.check(token, result.rows[0].mfa_secret);
if (!isValid) {
return res.status(400).json({ message: 'Invalid token' });
}
const newCodes = Array.from({ length: 10 }, () => crypto.randomBytes(5).toString('hex').slice(0, 8).toUpperCase());
await pool.query(`
UPDATE user_mfa SET backup_codes = $1::jsonb, backup_codes_shown = true WHERE user_id = $2
`, [JSON.stringify(newCodes), userId]);
await sendAuditEvent('auth.mfa_rotate_codes', userId, req.user.email);
res.json({ message: 'Backup codes rotated successfully. Save these codes as they will not be shown again.', backup_codes: newCodes });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Failed to rotate backup codes' });
}
});
app.post('/mfa/verify', requireRole(), createUserRateLimiter('mfa_verify', 10), async (req, res) => {
try {
const { token } = req.body;
if (!token) {
return res.status(400).json({ message: 'Token is required' });
}
const userId = req.user.id;
const result = await pool.query('SELECT * FROM user_mfa WHERE user_id = $1', [userId]);
if (!result.rows[0] || !result.rows[0].mfa_secret) {
return res.status(400).json({ message: 'MFA not set up. Call /mfa/setup first.' });
}
const isValid = authenticator.check(token, result.rows[0].mfa_secret);
if (!isValid) {
return res.status(400).json({ message: 'Invalid token' });
}
await pool.query('UPDATE user_mfa SET mfa_enabled = true WHERE user_id = $1', [userId]);
await sendAuditEvent('auth.mfa_enabled', userId, req.user.email);
res.json({ message: 'MFA enabled successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'MFA verification failed' });
}
});
app.post('/mfa/validate', requireRole(), createUserRateLimiter('mfa_validate', 10), async (req, res) => {
try {
const { token, backup_code } = req.body;
if (!token && !backup_code) {
return res.status(400).json({ message: 'Token or backup code is required' });
}
const userId = req.user.id;
const result = await pool.query('SELECT * FROM user_mfa WHERE user_id = $1 AND mfa_enabled = true', [userId]);
if (!result.rows[0]) {
return res.status(400).json({ message: 'MFA is not enabled for this user' });
}
const mfa = result.rows[0];
if (token) {
const isValid = authenticator.check(token, mfa.mfa_secret);
if (isValid) {
const mfaToken = signMfaToken(userId);
await sendAuditEvent('auth.mfa_validate', userId, req.user.email, { method: 'totp' });
return res.json({ message: 'Token validated', validated: true, mfa_token: mfaToken });
}