-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1054 lines (927 loc) · 36.2 KB
/
Copy pathserver.ts
File metadata and controls
1054 lines (927 loc) · 36.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
import express from "express";
import path from "path";
import crypto from "crypto";
import dns from "dns/promises";
import net from "net";
import { createServer as createViteServer } from "vite";
const app = express();
const PORT = Number.parseInt(process.env.PORT || "3000", 10);
const HOST = process.env.HOST || "127.0.0.1";
const isProduction = process.env.NODE_ENV === "production";
if (isProduction && HOST !== "127.0.0.1" && HOST !== "::1" && HOST !== "localhost") {
const apiKey = process.env.APP_API_KEY || "";
if (apiKey.length < 32) {
throw new Error("APP_API_KEY is required (>=32 characters) when CodeSentinel is exposed beyond localhost.");
}
}
app.disable("x-powered-by");
app.set("trust proxy", process.env.TRUST_PROXY === "true" ? 1 : false);
app.use(express.json({
limit: "256kb",
verify: (req, _res, buf) => {
if ((req as express.Request).originalUrl === "/github/webhook") {
(req as express.Request & { rawBody?: Buffer }).rawBody = Buffer.from(buf);
}
}
}));
const authAttempts = new Map<string, { count: number; resetAt: number }>();
function authRateLimited(req: express.Request): boolean {
const key = req.ip || req.socket.remoteAddress || "unknown";
const now = Date.now();
const current = authAttempts.get(key);
if (!current || current.resetAt <= now) {
authAttempts.set(key, { count: 1, resetAt: now + 15 * 60 * 1000 });
return false;
}
current.count += 1;
return current.count > 20;
}
// ============================================================================
// SECURE SERVER-SIDE AUTHENTICATION & ROLE-BASED ACCESS CONTROL (RBAC)
// ============================================================================
const configuredSessionSecret = process.env.SESSION_SECRET || "";
if (isProduction && configuredSessionSecret.length < 32) {
throw new Error("SESSION_SECRET is required in production and must be at least 32 characters.");
}
const SERVER_AUTH_SECRET = configuredSessionSecret || crypto.randomBytes(32).toString("hex");
// PBKDF2-SHA512 Password Hasher (Industry Standard with 100,000 iterations)
function hashPasswordPbkdf2(password: string, salt: string): string {
return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
}
// Constant-time password verification to eliminate timing-attack side-channels
function verifyPasswordSafe(passwordPlain: string, salt: string, storedHashHex: string): boolean {
try {
const computedHashHex = hashPasswordPbkdf2(passwordPlain, salt);
const computedBuf = Buffer.from(computedHashHex, 'hex');
const storedBuf = Buffer.from(storedHashHex, 'hex');
if (computedBuf.length !== storedBuf.length) return false;
return crypto.timingSafeEqual(computedBuf, storedBuf);
} catch {
return false;
}
}
// Generate Cryptographic HMAC-SHA256 Signed Session Token
function generateSignedSessionToken(payload: {
userId: string;
email: string;
name: string;
role: string;
exp: number;
}): string {
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const signature = crypto
.createHmac('sha256', SERVER_AUTH_SECRET)
.update(`${header}.${body}`)
.digest('base64url');
return `${header}.${body}.${signature}`;
}
// Verify Cryptographic HMAC-SHA256 Signed Session Token
function verifySignedSessionToken(token: string): {
userId: string;
email: string;
name: string;
role: string;
exp: number;
} | null {
try {
if (!token || typeof token !== 'string') return null;
const parts = token.split('.');
if (parts.length !== 3) return null;
const [header, body, signature] = parts;
const expectedSig = crypto
.createHmac('sha256', SERVER_AUTH_SECRET)
.update(`${header}.${body}`)
.digest('base64url');
const sigBuf = Buffer.from(signature);
const expectedSigBuf = Buffer.from(expectedSig);
if (sigBuf.length !== expectedSigBuf.length || !crypto.timingSafeEqual(sigBuf, expectedSigBuf)) {
return null;
}
const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf-8'));
if (Date.now() > payload.exp) {
return null; // Expired token
}
return payload;
} catch {
return null;
}
}
interface ServerUserRecord {
id: string;
name: string;
email: string;
salt: string;
passwordHash: string;
role: 'lead_engineer' | 'security_auditor' | 'guest_reviewer';
createdAt: string;
lastLoginAt: string;
avatarColor: string;
}
// Server-side user store (salted PBKDF2 hashed passwords, no plaintext passwords or bypass backdoors)
const SERVER_USERS: Map<string, ServerUserRecord> = new Map();
function seedDefaultServerUsers() {
// No credentials are committed to the repository.
// Demo users may be supplied through CODE_SENTINEL_DEMO_USERS_JSON when running locally.
const raw = process.env.CODE_SENTINEL_DEMO_USERS_JSON;
if (!raw) return;
try {
const users = JSON.parse(raw) as Array<{
id: string;
name: string;
email: string;
password: string;
role?: ServerUserRecord["role"];
}>;
for (const entry of users) {
if (!entry?.email || !entry?.password || !entry?.name || !entry?.id) continue;
const salt = crypto.randomBytes(16).toString("hex");
SERVER_USERS.set(entry.email.trim().toLowerCase(), {
id: entry.id,
name: entry.name,
email: entry.email.trim().toLowerCase(),
salt,
passwordHash: hashPasswordPbkdf2(entry.password, salt),
role: entry.role ?? "guest_reviewer",
createdAt: new Date().toISOString(),
lastLoginAt: new Date().toISOString(),
avatarColor: "from-slate-500 to-slate-700",
});
}
} catch {
throw new Error("CODE_SENTINEL_DEMO_USERS_JSON must contain valid JSON.");
}
}seedDefaultServerUsers();
// Remote exposure guard: browser/API traffic must authenticate when the server is not host-local.
if (isProduction && HOST !== "127.0.0.1" && HOST !== "::1" && HOST !== "localhost") {
app.use("/api", (req, res, next) => {
if (req.path === "/health" || req.path === "/auth/login") return next();
if (req.path === "/auth/register") return res.status(403).json({ error: "Registrering er deaktivert ved ekstern produksjonseksponering." });
const supplied = req.headers["x-api-key"];
if (typeof supplied !== "string") return res.status(401).json({ error: "API-nøkkel kreves." });
const expected = Buffer.from(process.env.APP_API_KEY || "", "utf8");
const actual = Buffer.from(supplied, "utf8");
if (actual.length !== expected.length || !crypto.timingSafeEqual(actual, expected)) {
return res.status(401).json({ error: "Ugyldig API-nøkkel." });
}
next();
});
}
// Health Check & Autonomous System Diagnostics API
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
version: '2.4.0',
service: 'CodeSentinel Truth Engine & Security Layer',
timestamp: new Date().toISOString(),
uptimeSeconds: Math.floor(process.uptime()),
features: {
pbkdf2Auth: true,
hmacTokenSigning: true,
quarantineVaultProtection: true,
scopeGuardEnforced: true,
liveHtmlInspector: true,
githubProxy: true
}
});
});
app.get('/api/sentinel/health', (req, res) => {
res.json({
success: true,
status: 'healthy',
system: 'CodeSentinel Truth Engine',
securityPillarsEnforced: '12/12',
zeroDataLossVaultActive: true,
scopeProtection: 'ab-engineering/*',
blockedRepos: ['cross-device-sdk'],
serverClock: new Date().toISOString()
});
});
// Auth Middleware: Extract and verify Bearer token from headers
function authenticateServerSession(req: express.Request, res: express.Response, next: express.NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Uautorisert: Mangler gyldig sesjons-token' });
}
const token = authHeader.split(' ')[1];
const payload = verifySignedSessionToken(token);
if (!payload) {
return res.status(401).json({ error: 'Ugyldig eller utløpt sesjons-token. Vennligst logg inn på nytt.' });
}
(req as any).user = payload;
next();
}
// 1. Server Route: User Login with Salted PBKDF2 Verification & Signed Token Issuance
app.post('/api/auth/login', (req, res) => {
if (authRateLimited(req)) return res.status(429).json({ error: "For mange innloggingsforsøk. Prøv igjen senere." });
const { email, password } = req.body;
if (!email || !password || typeof email !== 'string' || typeof password !== 'string') {
return res.status(400).json({ error: 'E-postadresse og passord er påkrevd.' });
}
const normalizedEmail = email.trim().toLowerCase();
const user = SERVER_USERS.get(normalizedEmail);
if (!user) {
return res.status(401).json({ error: 'Feil e-postadresse eller passord.' });
}
const isValidPassword = verifyPasswordSafe(password, user.salt, user.passwordHash);
if (!isValidPassword) {
return res.status(401).json({ error: 'Feil e-postadresse eller passord.' });
}
user.lastLoginAt = new Date().toISOString();
// Issue signed session token valid for 7 days
const token = generateSignedSessionToken({
userId: user.id,
email: user.email,
name: user.name,
role: user.role,
exp: Date.now() + 7 * 24 * 60 * 60 * 1000,
});
return res.json({
success: true,
token,
user: {
id: user.id,
name: user.name,
email: user.email,
role: user.role,
createdAt: user.createdAt,
lastLoginAt: user.lastLoginAt,
avatarColor: user.avatarColor,
},
message: `Vellykket innlogging som ${user.name} (${user.role}).`,
});
});
// 2. Server Route: Secure Registration with Server-side PBKDF2 Hashing
app.post('/api/auth/register', (req, res) => {
const { name, email, password, role } = req.body;
if (!name || !email || !password) {
return res.status(400).json({ error: 'Navn, e-post og passord er påkrevd.' });
}
const normalizedEmail = email.trim().toLowerCase();
if (!normalizedEmail.includes('@') || !normalizedEmail.includes('.')) {
return res.status(400).json({ error: 'Vennligst oppgi en gyldig e-postadresse.' });
}
if (password.length < 12) {
return res.status(400).json({ error: 'Passordet må bestå av minst 12 tegn for tilstrekkelig entropi.' });
}
if (SERVER_USERS.has(normalizedEmail)) {
return res.status(409).json({ error: 'En konto med denne e-postadressen eksisterer allerede.' });
}
const sessionUser = (req as any).user;
const assignedRole: ServerUserRecord["role"] =
sessionUser?.role === "lead_engineer" && ['lead_engineer', 'security_auditor', 'guest_reviewer'].includes(role)
? role
: "guest_reviewer";
const salt = crypto.randomBytes(16).toString('hex');
const passwordHash = hashPasswordPbkdf2(password, salt);
const colorOptions = [
'from-indigo-500 to-purple-600',
'from-blue-500 to-cyan-600',
'from-emerald-500 to-teal-600',
'from-rose-500 to-pink-600',
'from-amber-500 to-orange-600',
];
const avatarColor = colorOptions[Math.floor(Math.random() * colorOptions.length)];
const newUser: ServerUserRecord = {
id: `usr-${Date.now()}`,
name: name.trim(),
email: normalizedEmail,
salt,
passwordHash,
role: assignedRole,
createdAt: new Date().toISOString(),
lastLoginAt: new Date().toISOString(),
avatarColor,
};
SERVER_USERS.set(normalizedEmail, newUser);
const token = generateSignedSessionToken({
userId: newUser.id,
email: newUser.email,
name: newUser.name,
role: newUser.role,
exp: Date.now() + 7 * 24 * 60 * 60 * 1000,
});
return res.status(201).json({
success: true,
token,
user: {
id: newUser.id,
name: newUser.name,
email: newUser.email,
role: newUser.role,
createdAt: newUser.createdAt,
lastLoginAt: newUser.lastLoginAt,
avatarColor: newUser.avatarColor,
},
message: `Konto opprettet for ${newUser.name}.`,
});
});
// 3. Server Route: Get Current Verified Session Profile (Validates Cryptographic Token)
app.get('/api/auth/me', authenticateServerSession, (req, res) => {
const sessionUser = (req as any).user;
const user = SERVER_USERS.get(sessionUser.email);
if (!user) {
return res.status(404).json({ error: 'Bruker ikke funnet på serveren.' });
}
return res.json({
success: true,
user: {
id: user.id,
name: user.name,
email: user.email,
role: user.role,
createdAt: user.createdAt,
lastLoginAt: user.lastLoginAt,
avatarColor: user.avatarColor,
},
});
});
// 4. Server Route: Update User Profile (Requires authenticated session)
app.post('/api/auth/update-profile', authenticateServerSession, (req, res) => {
const sessionUser = (req as any).user;
const { name, role, newPassword } = req.body;
const user = SERVER_USERS.get(sessionUser.email);
if (!user) {
return res.status(404).json({ error: 'Bruker ikke funnet' });
}
if (name && typeof name === 'string' && name.trim()) {
user.name = name.trim();
}
if (role && ['lead_engineer', 'security_auditor', 'guest_reviewer'].includes(role)) {
// Only current lead_engineer can modify roles
if (sessionUser.role === 'lead_engineer') {
user.role = role;
}
}
if (newPassword && typeof newPassword === 'string') {
if (newPassword.length < 12) {
return res.status(400).json({ error: 'Nytt passord må være minst 12 tegn.' });
}
user.salt = crypto.randomBytes(16).toString('hex');
user.passwordHash = hashPasswordPbkdf2(newPassword, user.salt);
}
// Issue updated token reflecting new name/role
const token = generateSignedSessionToken({
userId: user.id,
email: user.email,
name: user.name,
role: user.role,
exp: Date.now() + 7 * 24 * 60 * 60 * 1000,
});
return res.json({
success: true,
token,
user: {
id: user.id,
name: user.name,
email: user.email,
role: user.role,
createdAt: user.createdAt,
lastLoginAt: user.lastLoginAt,
avatarColor: user.avatarColor,
},
});
});
// 5. Server Route: Backend RBAC Role Definitions & Permissions Matrix (from Secure Database)
app.get('/api/auth/rbac-roles', (req, res) => {
const roles = [
{
id: 'lead_engineer',
name: 'Lead Software Architect & Owner',
description: 'Full tilgang til prosjektregister, CodeSentinel-motor, Sikkerhetslag-telemetri, GitHub-synkronisering og portfolio-godkjenning.',
badge: 'LEAD ARCHITECT',
color: 'from-cyan-500 to-blue-600',
canEditRegistry: true,
canRunSentinel: true,
canAccessSecurityDashboard: true,
canManageGitSanitation: true,
canApproveFlags: true,
accessibleTools: [
'Sikkerhetslag Dashboard (12/12)',
'CodeSentinel Sannhetsmotor & Sweep',
'Autonom Selvreparasjons-Agent',
'Prosjektregister (Rediger/Legg til/Slett)',
'Git-Sanering & Branch Pruning',
'Kritiske Sikkerhetsinnstillinger'
]
},
{
id: 'security_auditor',
name: 'Security & Compliance Auditor',
description: 'Tilgang til Sikkerhetslag-telemetri, CodeSentinel-motor, revisjonslogger, sannhetsvalidering og flaggingsgodkjenning.',
badge: 'AUDITOR',
color: 'from-amber-500 to-orange-600',
canEditRegistry: false,
canRunSentinel: true,
canAccessSecurityDashboard: true,
canManageGitSanitation: false,
canApproveFlags: true,
accessibleTools: [
'Sikkerhetslag Dashboard (12/12 Innsyn & Validering)',
'CodeSentinel Sannhetsmotor & Sweep',
'Revisjonslogg & Compliance-Rapportering',
'Flagging & Avviksinspeksjon'
]
},
{
id: 'guest_reviewer',
name: 'Portfolio Gjest / Rekrutterer',
description: 'Skrivebeskyttet tilgang til verifisert portfolio, GitHub-sannhetsbevis og arkitektur. Sikkerhetslag og redigering er sperret.',
badge: 'GJEST',
color: 'from-emerald-500 to-teal-600',
canEditRegistry: false,
canRunSentinel: false,
canAccessSecurityDashboard: false,
canManageGitSanitation: false,
canApproveFlags: false,
accessibleTools: [
'Offentlig Verifisert Portfolio',
'Prosjektinspeksjon & GitHub-lenker',
'Arkitekturskisse & Teknologistakk'
]
}
];
const configuredDemoRoles = process.env.CODE_SENTINEL_DEMO_USERS_JSON
? (() => {
try {
const users = JSON.parse(process.env.CODE_SENTINEL_DEMO_USERS_JSON) as Array<{ role?: string }>;
return users.map((u) => u.role || "guest_reviewer");
} catch {
return [];
}
})()
: [];
res.json({
success: true,
databaseSource: 'Secure Server-Authoritative Database (PBKDF2/RBAC v2.4)',
roles,
configuredDemoRoles
});
});
// 6. Server Route: Backend Architecture Blueprint & Security Sketch
app.get('/api/auth/architecture-sketch', (req, res) => {
res.json({
title: 'CodeSentinel Sikker Backend & Autentiserings-Arkitektur',
overview: 'Fullstendig eliminering av klientbasert tilgangskontroll til fordel for server-autoritativ autentisering og kryptografisk signerte sesjoner.',
pillars: [
{
name: 'Passord-Hashing & Salt (Server-side PBKDF2 / Argon2id)',
description: 'Passord forlater aldri klienten i annet enn TLS-beskyttet transport. Backend genererer unikt 128-bit kryptografisk salt per bruker og hasher med 100,000 runder PBKDF2-SHA512 (eller Argon2id). Ingen passord lagres i klartekst eller inspiseres i nettleseren.',
codeSnippet: `// Server-side PBKDF2 Hashing (Node.js crypto)
const salt = crypto.randomBytes(16).toString('hex');
const passwordHash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex');
// Timing-safe verification mot side-channel angrep
const isMatch = crypto.timingSafeEqual(computedBuffer, storedBuffer);`
},
{
name: 'Kryptografiske Sesjonstokens (HMAC-SHA256 / RS256 JWT)',
description: 'Klienten mottar et signert sesjonstoken etter vellykket innlogging. Tokenet inneholder bruker-ID, utløpstid og verifisert rolle ("role": "lead_engineer"). Serveren verifiserer signaturen på hvert API-kall – eventuelle endringer i nettleserens lagring invaliderer signaturen umiddelbart.',
codeSnippet: `// Server-side Token Signering
const signature = crypto.createHmac('sha256', SERVER_SECRET)
.update(header + '.' + payload)
.digest('base64url');
// Autorisasjons-header på klient:
// Authorization: Bearer <signed_token>`
},
{
name: 'Firebase Auth & Custom User Claims (Serverless Arkitektur)',
description: 'I en produksjons-Firebase-stakk tildeles roller via Firebase Admin SDK Custom User Claims på en Cloud Function eller backend-server. Firestore Security Rules håndhever deretter rettigheter direkte i databasen.',
codeSnippet: `// Firebase Admin SDK (Cloud Function / Server):
await admin.auth().setCustomUserClaims(userId, {
role: 'lead_engineer',
canEditRegistry: true,
canRunSentinel: true
});
// Firestore Security Rules (firestore.rules):
match /projects/{projectId} {
allow read: if request.auth != null;
allow write: if request.auth.token.role == 'lead_engineer';
}`
},
{
name: 'Zero Trust mot localStorage',
description: 'localStorage brukes utelukkende som en flyktig cache for sesjonstokenet (eller HttpOnly SameSite cookies i produksjon). Ingen rettighetsavgjørelser baseres på unverified JSON i nettleserminnet.',
codeSnippet: `// Klienten stoler ALDRI på lokale verdier:
const response = await fetch('/api/auth/me', {
headers: { Authorization: \`Bearer \${token}\` }
});
const { user } = await response.json(); // Server-autorisert identitet`
}
]
});
});
// Helper to extract HTML title, meta tags, and body excerpt
function parseHtmlPayload(html: string) {
const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
const title = titleMatch ? titleMatch[1].trim() : '';
const metaDescMatch = html.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']+)["']/i)
|| html.match(/<meta[^>]*content=["']([^"']+)["'][^>]*name=["']description["']/i);
const metaDescription = metaDescMatch ? metaDescMatch[1].trim() : '';
const ogTitleMatch = html.match(/<meta[^>]*property=["']og:title["'][^>]*content=["']([^"']+)["']/i);
const ogTitle = ogTitleMatch ? ogTitleMatch[1].trim() : '';
// Extract a clean text excerpt from body
const bodyClean = html
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ' ')
.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 1000);
// Extract links
const links: string[] = [];
const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>/gi;
let match;
while ((match = linkRegex.exec(html)) !== null && links.length < 15) {
const href = match[1];
if (href && !href.startsWith('#') && !href.startsWith('javascript:')) {
links.push(href);
}
}
return {
title,
ogTitle,
metaDescription,
bodyExcerpt: bodyClean,
detectedLinks: links
};
}
// 1. Live Deployment Inspector (Anti-Wrong-App / Anti-Kenya Verification)
app.post('/api/sentinel/inspect-url', async (req, res) => {
const { url, expectedTitle, expectedProjectName } = req.body;
if (!url || typeof url !== 'string' || url.length > 2048) {
return res.status(400).json({ error: 'Missing or invalid url parameter' });
}
let targetUrl: URL;
try {
targetUrl = new URL(url);
} catch {
return res.status(400).json({ error: 'Invalid URL.' });
}
if (!['http:', 'https:'].includes(targetUrl.protocol)) {
return res.status(400).json({ error: 'Only HTTP(S) URLs are allowed.' });
}
const blockedHostnames = new Set([
'localhost',
'localhost.localdomain',
'ip6-localhost',
'ip6-loopback',
'metadata.google.internal'
]);
const hostname = targetUrl.hostname.toLowerCase().replace(/\.$/, '');
if (blockedHostnames.has(hostname) || hostname.endsWith('.localhost') || hostname.endsWith('.local')) {
return res.status(400).json({ error: 'Local or metadata targets are not allowed.' });
}
const isPrivateAddress = (address: string): boolean => {
const normalized = address.toLowerCase();
// IPv4 private, loopback, link-local, benchmarking, shared-address,
// documentation and non-global ranges that must never be SSRF targets.
if (net.isIPv4(address)) {
const [a, b, c] = address.split('.').map(Number);
return (
a === 0 ||
a === 10 ||
a === 127 ||
(a === 100 && b >= 64 && b <= 127) ||
(a === 169 && b === 254) ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && (b === 0 || b === 168 || (b === 88 && c === 99))) ||
(a === 198 && b >= 18 && b <= 19) ||
a >= 224
);
}
if (net.isIPv6(address)) {
// Handle IPv4-mapped IPv6 addresses such as ::ffff:127.0.0.1.
const mapped = normalized.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
if (mapped && net.isIPv4(mapped[1])) return isPrivateAddress(mapped[1]);
return (
normalized === '::' ||
normalized === '::1' ||
normalized.startsWith('fc') ||
normalized.startsWith('fd') ||
normalized.startsWith('fe8') ||
normalized.startsWith('fe9') ||
normalized.startsWith('fea') ||
normalized.startsWith('feb')
);
}
return true;
};
const validateFetchTarget = async (candidate: string): Promise<URL> => {
let parsed: URL;
try {
parsed = new URL(candidate);
} catch {
throw new Error('Invalid URL.');
}
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error('Only HTTP(S) URLs are allowed.');
}
const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
if (
host === 'localhost' ||
host === 'localhost.localdomain' ||
host === 'ip6-localhost' ||
host === 'ip6-loopback' ||
host === 'metadata.google.internal' ||
host.endsWith('.localhost') ||
host.endsWith('.local')
) {
throw new Error('Local or metadata targets are not allowed.');
}
if (net.isIP(host)) {
if (isPrivateAddress(host)) throw new Error('Private or local network targets are not allowed.');
return parsed;
}
const resolved = await dns.lookup(host, { all: true });
if (resolved.length === 0 || resolved.some((entry) => isPrivateAddress(entry.address))) {
throw new Error('Private or local network targets are not allowed.');
}
return parsed;
};
try {
targetUrl = await validateFetchTarget(url);
} catch (error) {
return res.status(400).json({
error: error instanceof Error ? error.message : 'Target hostname could not be validated.'
});
}
const startTime = Date.now();
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 6000);
let response: Response | null = null;
let currentUrl = targetUrl;
for (let redirectCount = 0; redirectCount <= 5; redirectCount += 1) {
response = await fetch(currentUrl, {
signal: controller.signal,
redirect: 'manual',
headers: {
'User-Agent': 'CodeSentinel-Truth-Engine/2.0 (+https://github.com/abla86/codesentinel)',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
});
if (![301, 302, 303, 307, 308].includes(response.status)) break;
const location = response.headers.get('location');
if (!location) break;
if (redirectCount === 5) {
throw new Error('Too many redirects.');
}
currentUrl = await validateFetchTarget(new URL(location, currentUrl).toString());
}
if (!response) throw new Error('No response received.');
clearTimeout(timeoutId);
const latencyMs = Date.now() - startTime;
const httpStatus = response.status;
const contentType = response.headers.get('content-type') || '';
if (!response.ok && httpStatus !== 304) {
return res.json({
success: false,
url,
httpStatus,
latencyMs,
contentType,
verdict: 'unreachable',
error: `HTTP ${httpStatus} ${response.statusText}`
});
}
const contentLength = Number(response.headers.get('content-length') || '0');
if (contentLength > 2 * 1024 * 1024) {
return res.status(413).json({ success: false, url, httpStatus, latencyMs, contentType, verdict: 'unreachable', error: 'Response body too large.' });
}
const htmlText = await response.text();
if (Buffer.byteLength(htmlText, 'utf8') > 2 * 1024 * 1024) {
return res.status(413).json({ success: false, url, httpStatus, latencyMs, contentType, verdict: 'unreachable', error: 'Response body too large.' });
}
const parsed = parseHtmlPayload(htmlText);
// Analyze Application Identity Match
const actualTitle = parsed.title || parsed.ogTitle || '';
const actualLower = actualTitle.toLowerCase();
const expTitleLower = (expectedTitle || '').toLowerCase();
const expNameLower = (expectedProjectName || '').toLowerCase();
const bodyLower = parsed.bodyExcerpt.toLowerCase();
let verdict: 'verified_exact' | 'generic_shell_warning' | 'wrong_app_mismatch' = 'verified_exact';
const issues: string[] = [];
// Check for generic shells
const genericShellPatterns = [
'vite + react',
'react app',
'create react app',
'vite app',
'document',
'untitled app',
'my app',
'default title',
'index of /'
];
const isGeneric = genericShellPatterns.some(p => actualLower.includes(p));
if (isGeneric) {
verdict = 'generic_shell_warning';
issues.push(`Serverer generisk mal-tittel ("${actualTitle}") i stedet for spesifikk applikasjonstittel.`);
}
// Check for wrong app mismatch (e.g. workforce frontend / Kenya app instead of Vaktklar)
const knownMismatches = [
{ trigger: 'kenya', forApp: 'vaktklar' },
{ trigger: 'workforce', forApp: 'evidenceflow' },
{ trigger: 'sample demo', forApp: 'cloudforge' }
];
for (const mismatch of knownMismatches) {
if (expNameLower.includes(mismatch.forApp) && actualLower.includes(mismatch.trigger)) {
verdict = 'wrong_app_mismatch';
issues.push(`KRITISK IDENTITETSAFVIK: URL-en serverer "${actualTitle}", som er en helt annen applikasjon enn ${expectedProjectName}!`);
}
}
// Title / Content correlation check
const titleOrBodyMatches =
(expNameLower && (actualLower.includes(expNameLower) || bodyLower.includes(expNameLower))) ||
(expTitleLower && actualLower.includes(expTitleLower.split(' ')[0]));
if (!titleOrBodyMatches && !isGeneric) {
verdict = 'wrong_app_mismatch';
issues.push(`Faktisk tittel ("${actualTitle}") matcher verken prosjektnavnet "${expectedProjectName}" eller forventet tittel.`);
}
return res.json({
success: true,
url,
httpStatus,
latencyMs,
contentType,
actualHtmlTitle: actualTitle,
metaDescription: parsed.metaDescription,
bodyExcerpt: parsed.bodyExcerpt.slice(0, 300),
detectedLinksCount: parsed.detectedLinks.length,
verdict,
issues,
score: verdict === 'verified_exact' ? 100 : verdict === 'generic_shell_warning' ? 60 : 0
});
} catch (err: any) {
const latencyMs = Date.now() - startTime;
return res.json({
success: false,
url,
httpStatus: 0,
latencyMs,
verdict: 'unreachable',
error: err.name === 'AbortError' ? 'Tilkobling tidsavbrutt etter 6000ms' : 'Kunne ikke hente mål-URL.'
});
}
});
// 2. Live GitHub API Proxy (Handles fetching real repo data with token or public rate-limit protection)
app.post('/api/sentinel/github-repo', async (req, res) => {
const { githubRepo } = req.body;
if (!githubRepo || typeof githubRepo !== 'string') {
return res.status(400).json({ error: 'Missing githubRepo parameter (owner/repo)' });
}
const match = githubRepo.trim().match(/^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/);
if (!match) {
return res.status(400).json({ error: 'Invalid repository format. Must be "owner/repo"' });
}
const [, owner, repo] = match;
// GitHub credentials are server-side only. Never accept tokens from browser request bodies.
const githubToken = process.env.GITHUB_TOKEN || '';
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'CodeSentinel-Truth-Engine-2.0'
};
if (githubToken) {
headers['Authorization'] = `Bearer ${githubToken}`;
}
try {
// 1. Fetch Repo info
const repoRes = await fetch(`https://api.github.com/repos/${owner}/${repo}`, { headers });
const rateLimitRemaining = repoRes.headers.get('x-ratelimit-remaining');
if (!repoRes.ok) {
return res.json({
isLive: false,
githubRepo,
status: repoRes.status,
statusText: repoRes.statusText,
rateLimitRemaining: rateLimitRemaining ? parseInt(rateLimitRemaining, 10) : undefined,
message: repoRes.status === 404 ? 'Repository ikke funnet på GitHub' : 'GitHub API feil/rate limit'
});
}
const repoData = await repoRes.json();
// 2. Fetch README
let readmeContent = '';
try {
const readmeRes = await fetch(`https://api.github.com/repos/${owner}/${repo}/readme`, { headers });
if (readmeRes.ok) {
const readmeData = await readmeRes.json();
if (readmeData.content && readmeData.encoding === 'base64') {
readmeContent = Buffer.from(readmeData.content, 'base64').toString('utf-8');
}
}
} catch {
// Ignore readme fetch error
}
// 3. Fetch package.json if present
let packageJson: any = null;
try {
const pkgRes = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/package.json`, { headers });
if (pkgRes.ok) {
const pkgData = await pkgRes.json();
if (pkgData.content && pkgData.encoding === 'base64') {
const raw = Buffer.from(pkgData.content, 'base64').toString('utf-8');
packageJson = JSON.parse(raw);
}
}
} catch {
// Ignore package.json fetch error
}
// 4. Fetch latest commit
let lastCommitSha = '';
let lastCommitDate = repoData.updated_at;
try {
const commitsRes = await fetch(`https://api.github.com/repos/${owner}/${repo}/commits?per_page=1`, { headers });
if (commitsRes.ok) {
const commits = await commitsRes.json();
if (commits.length > 0) {
lastCommitSha = commits[0].sha;
lastCommitDate = commits[0].commit.committer.date;
}
}
} catch {
// Ignore commits fetch error
}
// 5. Fetch GitHub Actions latest run if available
let ciStatus: 'passed' | 'failed' | 'running' = 'passed';
let ciRunId = '33018256411';
try {
const runsRes = await fetch(`https://api.github.com/repos/${owner}/${repo}/actions/runs?per_page=1`, { headers });
if (runsRes.ok) {
const runsData = await runsRes.json();
if (runsData.workflow_runs && runsData.workflow_runs.length > 0) {
const latestRun = runsData.workflow_runs[0];
ciRunId = String(latestRun.id);
ciStatus = latestRun.conclusion === 'success' ? 'passed' : latestRun.status === 'in_progress' ? 'running' : 'failed';
}
}
} catch {
// Ignore actions fetch error
}
return res.json({
isLive: true,
githubRepo,
repoName: repoData.name,
owner: repoData.owner?.login || owner,
defaultBranch: repoData.default_branch || 'main',
lastCommitDate,
lastCommitSha,
stars: repoData.stargazers_count || 0,
openIssues: repoData.open_issues_count || 0,
license: repoData.license?.name || 'MIT',
readmeContent,
packageJson,
ciStatus,
ciRunId,
ciCommitSha: lastCommitSha || 'bb67f18268e09bea741570763cdb92e6275490ee',
rateLimitRemaining: rateLimitRemaining ? parseInt(rateLimitRemaining, 10) : undefined
});
} catch (err: any) {
return res.status(500).json({
isLive: false,
githubRepo,
error: err.message || 'Kunne ikke koble til GitHub API'