-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
4027 lines (3678 loc) · 171 KB
/
server.js
File metadata and controls
4027 lines (3678 loc) · 171 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const morgan = require('morgan');
const compression = require('compression');
const multer = require('multer');
const PDFDocument = require('pdfkit');
const path = require('path');
const fs = require('fs');
const fsp = require('fs').promises;
const { v4: uuidv4 } = require('uuid');
require('dotenv').config();
const app = express();
const PORT = Number(process.env.PORT || 3000);
const JWT_SECRET = process.env.JWT_SECRET || 'change-me-in-production';
const uploadsDir = path.join(__dirname, 'uploads');
const reportsDir = path.join(__dirname, 'reports');
const MAX_EVIDENCE_FILE_SIZE_BYTES = 10 * 1024 * 1024;
const MAX_EVIDENCE_FILES = 20;
const PLATFORM_FRAMEWORK = 'OCTAVE Allegro';
const dbConfig = {
host: process.env.DB_HOST || '127.0.0.1',
port: Number(process.env.DB_PORT || 3306),
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_NAME || 'cybersecurity_audit'
};
let db;
if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
if (!fs.existsSync(reportsDir)) fs.mkdirSync(reportsDir, { recursive: true });
app.use(helmet({ crossOriginEmbedderPolicy: false, contentSecurityPolicy: false }));
app.use(compression());
app.use(morgan('dev'));
app.use(cors({
origin: ['http://localhost:3001', 'http://127.0.0.1:3001'],
credentials: true
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use('/uploads', express.static(uploadsDir));
app.use('/reports', express.static(reportsDir));
app.use('/api', rateLimit({ windowMs: 15 * 60 * 1000, max: 1000 }));
const upload = multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => cb(null, uploadsDir),
filename: (_req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`)
}),
limits: {
fileSize: MAX_EVIDENCE_FILE_SIZE_BYTES,
files: MAX_EVIDENCE_FILES
}
});
function evidenceUploadSingle(req, res, next) {
upload.single('file')(req, res, (error) => {
if (!error) return next();
if (error instanceof multer.MulterError) {
if (error.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({ error: `File is too large. Maximum file size is ${Math.floor(MAX_EVIDENCE_FILE_SIZE_BYTES / (1024 * 1024))} MB` });
}
if (error.code === 'LIMIT_FILE_COUNT') {
return res.status(400).json({ error: `Maximum number of files reached (${MAX_EVIDENCE_FILES})` });
}
}
return res.status(400).json({ error: error.message || 'File upload failed' });
});
}
function evidenceUploadMultiple(req, res, next) {
upload.array('files', MAX_EVIDENCE_FILES)(req, res, (error) => {
if (!error) return next();
if (error instanceof multer.MulterError) {
if (error.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({ error: `File is too large. Maximum file size is ${Math.floor(MAX_EVIDENCE_FILE_SIZE_BYTES / (1024 * 1024))} MB` });
}
if (error.code === 'LIMIT_FILE_COUNT') {
return res.status(400).json({ error: `Too many files selected. Maximum number of files is ${MAX_EVIDENCE_FILES}` });
}
}
return res.status(400).json({ error: error.message || 'File upload failed' });
});
}
const LIKELIHOOD_MAP = { Low: 1, Medium: 2, High: 3, 'Very High': 4, Critical: 5 };
const IMPACT_MAP = { Low: 1, Medium: 2, High: 3, 'Very High': 4, Critical: 5 };
function numericLikelihood(value) {
if (typeof value === 'number') return Math.max(1, Math.min(5, value));
return LIKELIHOOD_MAP[value] || 2;
}
function numericImpact(value) {
if (typeof value === 'number') return Math.max(1, Math.min(5, value));
return IMPACT_MAP[value] || 2;
}
function riskLevelFromScore(score) {
// Keep thresholds aligned with risk engine defaults:
// Critical >= 12, High >= 8, Medium >= 4, else Low
if (score >= 12) return 'Critical';
if (score >= 8) return 'High';
if (score >= 4) return 'Medium';
return 'Low';
}
function calculateExposureLevel({ sector, employeeCount, environment }) {
const sectorWeights = {
'Financial Services': 5,
Healthcare: 5,
Government: 5,
Energy: 4,
Telecommunications: 4,
Technology: 3,
Manufacturing: 3,
Retail: 2,
Education: 2,
Other: 2
};
let score = sectorWeights[sector] || 2;
const size = Number(employeeCount || 0);
if (size >= 5000) score += 5;
else if (size >= 1000) score += 4;
else if (size >= 250) score += 3;
else if (size >= 50) score += 2;
else score += 1;
const env = String(environment || '').toLowerCase();
if (env.includes('internet') || env.includes('public') || env.includes('web')) score += 4;
if (env.includes('cloud')) score += 3;
if (env.includes('hybrid')) score += 2;
if (env.includes('internal')) score += 1;
if (score >= 12) return 'Critical';
if (score >= 9) return 'High';
if (score >= 6) return 'Medium';
return 'Low';
}
function calculateCriticalityScore({ confidentiality, integrity, availability, businessCriticality }) {
const c = Number(confidentiality || 3);
const i = Number(integrity || 3);
const a = Number(availability || 3);
const base = (c + i + a) / 3;
const businessWeight = { Low: 0.8, Medium: 1, High: 1.2, Critical: 1.4 }[businessCriticality || 'Medium'];
return Number((base * 20 * businessWeight).toFixed(2));
}
function criticalityFromScore(score) {
const value = Number(score || 0);
if (value >= 85) return 'Critical';
if (value >= 70) return 'High';
if (value >= 45) return 'Medium';
return 'Low';
}
function toCompliancePercent(stats) {
const total = Number(stats.total_controls || 0);
if (!total) return 0;
const compliant = Number(stats.compliant_controls || 0);
return Number(((compliant / total) * 100).toFixed(2));
}
function sanitizeFilename(name) {
return String(name || 'report').replace(/[^a-zA-Z0-9-_]/g, '_');
}
function normalizeContainerType(value) {
const raw = String(value || '').trim().toLowerCase();
if (raw.startsWith('tech')) return 'Technical';
if (raw.startsWith('phys')) return 'Physical';
if (raw.startsWith('peop') || raw.startsWith('person')) return 'People';
return null;
}
function isDbConnectionError(error) {
const code = error?.code || '';
const msg = String(error?.message || '').toLowerCase();
return (
code === 'PROTOCOL_CONNECTION_LOST' ||
code === 'ECONNRESET' ||
code === 'ECONNREFUSED' ||
code === 'ETIMEDOUT' ||
msg.includes('cannot enqueue') ||
msg.includes('closed state') ||
msg.includes('lost connection')
);
}
async function reconnectDb() {
try {
if (db) await db.end();
} catch (_e) {
// ignore
}
db = await mysql.createConnection(dbConfig);
}
async function dbExecute(query, params = []) {
try {
return await db.execute(query, params);
} catch (error) {
if (isDbConnectionError(error)) {
await reconnectDb();
return db.execute(query, params);
}
throw error;
}
}
const VULNERABILITY_RISK_MAPPING = {
'SQL Injection': { likelihood: 4, impact: 5, business_impact: 'Database theft and unauthorized data modification.' },
'Command Injection': { likelihood: 4, impact: 5, business_impact: 'Remote command execution on application server.' },
'LDAP Injection': { likelihood: 3, impact: 4, business_impact: 'Unauthorized directory data access.' },
'Weak Password Policy': { likelihood: 4, impact: 4, business_impact: 'Account takeover risk due to weak credentials.' },
'No Account Lockout': { likelihood: 4, impact: 4, business_impact: 'Brute-force attack success probability increased.' },
'Session Hijacking': { likelihood: 3, impact: 4, business_impact: 'Unauthorized session usage by attackers.' },
'No HTTPS / TLS': { likelihood: 3, impact: 4, business_impact: 'Sensitive data interception during transit.' },
'Weak Encryption': { likelihood: 3, impact: 4, business_impact: 'Data confidentiality compromise.' },
'Exposed Database Backup': { likelihood: 4, impact: 5, business_impact: 'Bulk data leakage from backup storage.' },
'IDOR (Insecure Direct Object Reference)': { likelihood: 4, impact: 4, business_impact: 'Unauthorized access to user records.' },
'Privilege Escalation': { likelihood: 3, impact: 5, business_impact: 'Administrative takeover and full compromise.' },
'Default Credentials': { likelihood: 5, impact: 5, business_impact: 'Immediate unauthorized access using known defaults.' },
'Directory Listing Enabled': { likelihood: 3, impact: 3, business_impact: 'Information disclosure about internal structure.' },
'Exposed Admin Panel': { likelihood: 4, impact: 4, business_impact: 'Direct attack surface for privilege abuse.' },
'Open Unnecessary Ports': { likelihood: 3, impact: 3, business_impact: 'Expanded attack surface and lateral movement.' },
'Cross-Site Scripting (XSS)': { likelihood: 4, impact: 4, business_impact: 'Account hijacking and client-side script abuse.' },
'Cross-Site Request Forgery (CSRF)': { likelihood: 3, impact: 4, business_impact: 'Unauthorized user actions and transactions.' },
'No Audit Logs': { likelihood: 3, impact: 3, business_impact: 'Delayed incident detection and investigation failures.' },
'Outdated Server Software': { likelihood: 4, impact: 4, business_impact: 'Exploitation of known vulnerabilities.' }
};
const VULNERABILITY_CHECKLIST_MAPPING = {
'Weak Password Policy': {
control_id: 'PWD-001',
control_name: 'Password Policy Enforcement',
control_description: 'Verify password policy enforces minimum 8 characters and complexity.'
},
'No HTTPS / TLS': {
control_id: 'TLS-001',
control_name: 'TLS Enforcement',
control_description: 'Verify TLS certificate installed and HTTPS enforced for all external endpoints.'
},
'No Account Lockout': {
control_id: 'AUTH-002',
control_name: 'Account Lockout',
control_description: 'Verify account lockout is enabled after repeated failed login attempts.'
},
'No Audit Logs': {
control_id: 'LOG-001',
control_name: 'Audit Logging',
control_description: 'Verify critical activities are logged and centrally monitored.'
},
'Outdated Server Software': {
control_id: 'PATCH-001',
control_name: 'Patch Management',
control_description: 'Verify servers and components are updated based on patch policy.'
}
};
const OCTAVE_ALLEGRO_CHECKLIST_TEMPLATE = [
{
control_id: 'OA-CRIT-001',
control_name: 'Risk Measurement Criteria Definition',
control_description: 'Confirm OCTAVE Allegro impact criteria (Confidentiality, Integrity, Availability and business impact) are defined before risk analysis.',
category: 'Risk Governance'
},
{
control_id: 'OA-ASSET-001',
control_name: 'Information Asset Identification',
control_description: 'Verify critical information assets are identified, named, and assigned clear ownership.',
category: 'Asset Profiling'
},
{
control_id: 'OA-CONT-TECH-001',
control_name: 'Technical Container Profiling',
control_description: 'Verify technical containers (servers, databases, applications, networks) are documented for each information asset.',
category: 'Container Profiling'
},
{
control_id: 'OA-CONT-PHYS-001',
control_name: 'Physical Container Profiling',
control_description: 'Verify physical containers (rooms, facilities, hardware locations) are identified for each information asset.',
category: 'Container Profiling'
},
{
control_id: 'OA-CONT-PEOPLE-001',
control_name: 'People Container Profiling',
control_description: 'Verify people containers (employees, contractors, third parties) with access to information assets are documented.',
category: 'Container Profiling'
},
{
control_id: 'OA-THREAT-001',
control_name: 'Threat Scenario Documentation',
control_description: 'Verify realistic threat scenarios are defined per asset/container, including source, access path, and potential event.',
category: 'Threat Analysis'
},
{
control_id: 'OA-VULN-001',
control_name: 'Vulnerability Linkage (OWASP-Aligned)',
control_description: 'Verify relevant vulnerabilities (e.g., SQLi, XSS, command injection) are mapped to impacted information assets.',
category: 'Threat Analysis'
},
{
control_id: 'OA-RISK-001',
control_name: 'Likelihood x Impact Scoring',
control_description: 'Verify each risk scenario is scored using Risk = Likelihood x Impact and retains score justification.',
category: 'Risk Analysis'
},
{
control_id: 'OA-RISK-002',
control_name: 'Risk Matrix Classification',
control_description: 'Verify risks are categorized into Low/Medium/High/Critical using defined matrix thresholds.',
category: 'Risk Analysis'
},
{
control_id: 'OA-MIT-001',
control_name: 'Risk Mitigation Strategy Selection',
control_description: 'Verify mitigation decisions are recorded for each significant risk (accept, reduce, transfer, avoid).',
category: 'Mitigation Planning'
},
{
control_id: 'OA-EVID-001',
control_name: 'Evidence and Traceability',
control_description: 'Verify audit evidence is attached to checklist controls and remains traceable to findings and recommendations.',
category: 'Evidence Management'
},
{
control_id: 'OA-FIND-001',
control_name: 'Findings & Recommendation Quality',
control_description: 'Verify each finding includes issue, risk, affected asset, and actionable recommendation aligned to OCTAVE Allegro outputs.',
category: 'Reporting'
}
];
function normalizeFrameworkName(input) {
const raw = String(input || '').trim().toLowerCase();
if (!raw) return 'OCTAVE Allegro';
if (raw.includes('octave')) return 'OCTAVE Allegro';
return 'OCTAVE Allegro';
}
async function ensureFrameworkChecklistTemplate({ framework, auditTaskId }) {
const normalizedFramework = 'OCTAVE Allegro';
const template = OCTAVE_ALLEGRO_CHECKLIST_TEMPLATE;
const checklistColumns = await getTableColumns('audit_checklist');
const hasAuditTaskId = checklistColumns.has('audit_task_id');
const targetAuditTaskId = hasAuditTaskId
? (Number(auditTaskId) > 0 ? Number(auditTaskId) : await getDefaultAuditTaskIdForChecklist())
: null;
const allowedStatus = await getChecklistStatusEnumValues();
const defaultStatus = normalizeChecklistStatusForDb('Not Assessed', allowedStatus);
const hasControlId = checklistColumns.has('control_id');
const hasControlName = checklistColumns.has('control_name');
const hasControlTitle = checklistColumns.has('control_title');
const selectFields = [
hasControlId ? 'control_id' : 'NULL AS control_id',
hasControlName ? 'control_name' : (hasControlTitle ? 'control_title AS control_name' : 'NULL AS control_name')
].join(', ');
const [existingRows] = hasAuditTaskId
? await db.execute(
`SELECT ${selectFields} FROM audit_checklist WHERE audit_task_id = ?`,
[targetAuditTaskId]
)
: await db.execute(`SELECT ${selectFields} FROM audit_checklist`);
const existingKeys = new Set(
existingRows.map((row) => `${String(row.control_id || '').trim()}::${String(row.control_name || '').trim()}`)
);
for (const item of template) {
const key = `${String(item.control_id || '').trim()}::${String(item.control_name || '').trim()}`;
if (existingKeys.has(key)) continue;
const cols = [];
const vals = [];
if (hasAuditTaskId) {
cols.push('audit_task_id');
vals.push(targetAuditTaskId);
}
if (checklistColumns.has('control_id')) {
cols.push('control_id');
vals.push(item.control_id || null);
}
if (checklistColumns.has('control_number')) {
cols.push('control_number');
vals.push(item.control_id || 'CTRL-001');
}
if (checklistColumns.has('control_name')) {
cols.push('control_name');
vals.push(item.control_name || 'Control');
}
if (checklistColumns.has('control_title')) {
cols.push('control_title');
vals.push(item.control_name || 'Control');
}
if (checklistColumns.has('control_description')) {
cols.push('control_description');
vals.push(item.control_description || '');
}
if (checklistColumns.has('category')) {
cols.push('category');
vals.push(item.category || normalizedFramework);
}
if (checklistColumns.has('compliance_status')) {
cols.push('compliance_status');
vals.push(defaultStatus);
}
if (checklistColumns.has('evidence_required')) {
cols.push('evidence_required');
vals.push(1);
}
if (checklistColumns.has('findings')) {
cols.push('findings');
vals.push('');
}
if (checklistColumns.has('evidence_notes')) {
cols.push('evidence_notes');
vals.push('');
}
const placeholders = cols.map(() => '?').join(', ');
await db.execute(
`INSERT INTO audit_checklist (${cols.join(', ')}) VALUES (${placeholders})`,
vals
);
}
return { auditTaskId: hasAuditTaskId ? targetAuditTaskId : null, framework: normalizedFramework };
}
async function ensureColumn(tableName, columnName, definition) {
const [rows] = await db.execute(
`SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
[dbConfig.database, tableName, columnName]
);
if (!rows.length) await db.execute(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${definition}`);
}
const tableColumnsCache = new Map();
async function getTableColumns(tableName) {
if (tableColumnsCache.has(tableName)) return tableColumnsCache.get(tableName);
const [rows] = await db.execute(
`SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`,
[dbConfig.database, tableName]
);
const set = new Set(rows.map((r) => r.COLUMN_NAME));
tableColumnsCache.set(tableName, set);
return set;
}
async function getChecklistStatusEnumValues() {
const [rows] = await db.execute(
`SELECT COLUMN_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'audit_checklist' AND COLUMN_NAME = 'compliance_status'`,
[dbConfig.database]
);
const raw = rows[0]?.COLUMN_TYPE || '';
const matches = [...raw.matchAll(/'([^']+)'/g)].map((m) => m[1]);
return new Set(matches);
}
function normalizeChecklistStatusForDb(status, allowed) {
const value = status || 'Not Assessed';
const map = {
'Partially Compliant': 'Partial',
'Not Assessed': 'Not Applicable'
};
const mapped = map[value] || value;
if (allowed.has(mapped)) return mapped;
if (allowed.has(value)) return value;
if (allowed.has('Not Assessed')) return 'Not Assessed';
if (allowed.has('Not Applicable')) return 'Not Applicable';
return [...allowed][0] || value;
}
function normalizeChecklistStatusForApi(status) {
if (status === 'Partial') return 'Partially Compliant';
if (status === 'Not Applicable') return 'Not Assessed';
return status || 'Not Assessed';
}
async function getDefaultAuditTaskIdForChecklist() {
const [existing] = await db.execute('SELECT id FROM audit_tasks ORDER BY created_at DESC LIMIT 1');
if (existing.length) return existing[0].id;
const taskColumns = await getTableColumns('audit_tasks');
const [frameworkMeta] = await db.execute(
`SELECT COLUMN_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'audit_tasks' AND COLUMN_NAME = 'framework'`,
[dbConfig.database]
);
const frameworkValues = [...String(frameworkMeta[0]?.COLUMN_TYPE || '').matchAll(/'([^']+)'/g)].map((m) => m[1]);
const frameworkValue = frameworkValues.includes('OCTAVE Allegro')
? 'OCTAVE Allegro'
: (frameworkValues.includes('OCTAVE') ? 'OCTAVE' : (frameworkValues[0] || 'ISO-27001'));
const [orgRows] = await db.execute('SELECT id FROM organizations ORDER BY id ASC LIMIT 1');
const fallbackOrgId = orgRows[0]?.id || null;
const cols = [];
const vals = [];
if (taskColumns.has('title')) { cols.push('title'); vals.push('Default Audit Task'); }
if (taskColumns.has('organization_id')) { cols.push('organization_id'); vals.push(fallbackOrgId); }
if (taskColumns.has('auditor_id')) { cols.push('auditor_id'); vals.push(null); }
if (taskColumns.has('framework')) { cols.push('framework'); vals.push(frameworkValue); }
if (taskColumns.has('status')) { cols.push('status'); vals.push('pending'); }
if (taskColumns.has('start_date')) { cols.push('start_date'); vals.push(new Date()); }
if (taskColumns.has('end_date')) { cols.push('end_date'); vals.push(null); }
const placeholders = cols.map(() => '?').join(', ');
const [result] = await db.execute(`INSERT INTO audit_tasks (${cols.join(', ')}) VALUES (${placeholders})`, vals);
return result.insertId;
}
async function resolveAuditTaskIdForEvidence(body) {
if (body.audit_task_id) return Number(body.audit_task_id);
if (body.checklist_item_id) {
const [rows] = await db.execute('SELECT audit_task_id FROM audit_checklist WHERE id = ? LIMIT 1', [body.checklist_item_id]);
const taskId = rows[0]?.audit_task_id;
if (taskId) return Number(taskId);
}
return getDefaultAuditTaskIdForChecklist();
}
async function resolveUploadedByUserId(inputUserId, fallbackUserId) {
const candidate = Number(inputUserId);
if (Number.isInteger(candidate) && candidate > 0) {
const [rows] = await db.execute('SELECT id FROM users WHERE id = ? LIMIT 1', [candidate]);
if (rows.length) return candidate;
}
return Number(fallbackUserId);
}
function inferEvidenceType({ evidence_type, file_type, file_name, file_path }) {
const explicit = String(evidence_type || '').trim();
if (explicit) return explicit;
const mime = String(file_type || '').toLowerCase();
if (mime.startsWith('image/')) return 'Screenshot';
if (mime.includes('pdf') || mime.includes('word') || mime.includes('text')) return 'Document';
if (mime.includes('log')) return 'Log File';
const fileRef = String(file_name || file_path || '').toLowerCase();
const ext = fileRef.includes('.') ? fileRef.split('.').pop() : '';
if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) return 'Screenshot';
if (['pdf', 'doc', 'docx', 'txt', 'rtf', 'md'].includes(ext)) return 'Document';
if (['log'].includes(ext)) return 'Log File';
if (['conf', 'ini', 'yaml', 'yml', 'json', 'xml'].includes(ext)) return 'Configuration';
return 'Other';
}
async function resolveAuditTaskIdForFinding(body, preferredTaskId) {
const taskId = Number(preferredTaskId || body?.audit_task_id || 0);
if (Number.isInteger(taskId) && taskId > 0) return taskId;
return getDefaultAuditTaskIdForChecklist();
}
async function getOrCreateLatestAuditTaskForOrganization(organizationId) {
const orgId = Number(organizationId || 0);
if (!Number.isInteger(orgId) || orgId <= 0) return getDefaultAuditTaskIdForChecklist();
const [rows] = await db.execute(
'SELECT id FROM audit_tasks WHERE organization_id = ? ORDER BY created_at DESC LIMIT 1',
[orgId]
);
if (rows.length) return rows[0].id;
// Last resort: create a task with schema-aware inserts.
const taskColumns = await getTableColumns('audit_tasks');
const [frameworkMeta] = await db.execute(
`SELECT COLUMN_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'audit_tasks' AND COLUMN_NAME = 'framework'`,
[dbConfig.database]
);
const frameworkValues = [...String(frameworkMeta[0]?.COLUMN_TYPE || '').matchAll(/'([^']+)'/g)].map((m) => m[1]);
const frameworkValue = frameworkValues.includes('OCTAVE Allegro')
? 'OCTAVE Allegro'
: (frameworkValues.includes('OCTAVE') ? 'OCTAVE' : (frameworkValues[0] || 'ISO-27001'));
const [auditors] = await db.execute("SELECT id FROM users WHERE role = 'auditor' ORDER BY id ASC LIMIT 1");
const [anyUsers] = await db.execute('SELECT id FROM users ORDER BY id ASC LIMIT 1');
const fallbackAuditorId = auditors[0]?.id || anyUsers[0]?.id || 1;
const cols = [];
const vals = [];
if (taskColumns.has('title')) { cols.push('title'); vals.push(`Auto Audit Task - Org ${orgId}`); }
if (taskColumns.has('organization_id')) { cols.push('organization_id'); vals.push(orgId); }
if (taskColumns.has('auditor_id')) { cols.push('auditor_id'); vals.push(fallbackAuditorId); }
if (taskColumns.has('framework')) { cols.push('framework'); vals.push(frameworkValue); }
if (taskColumns.has('status')) { cols.push('status'); vals.push('pending'); }
if (taskColumns.has('start_date')) { cols.push('start_date'); vals.push(new Date()); }
if (taskColumns.has('end_date')) { cols.push('end_date'); vals.push(null); }
const placeholders = cols.map(() => '?').join(', ');
const [result] = await db.execute(`INSERT INTO audit_tasks (${cols.join(', ')}) VALUES (${placeholders})`, vals);
return result.insertId;
}
async function ensureOrganizationReportBaselineData(organizationId, organizationName) {
const orgId = Number(organizationId || 0);
if (!Number.isInteger(orgId) || orgId <= 0) return { auditTaskId: null };
const auditTaskId = await getOrCreateLatestAuditTaskForOrganization(orgId);
await ensureFrameworkChecklistTemplate({ framework: PLATFORM_FRAMEWORK, auditTaskId });
const [existingAssets] = await db.execute(
'SELECT id FROM assets WHERE organization_id = ? ORDER BY id ASC LIMIT 1',
[orgId]
);
let primaryAssetId = existingAssets[0]?.id || null;
if (!primaryAssetId) {
const assetColumns = await getTableColumns('assets');
const cols = [];
const vals = [];
if (assetColumns.has('name')) { cols.push('name'); vals.push(`${organizationName || `Organization ${orgId}`} Core Information Asset`); }
if (assetColumns.has('asset_type')) { cols.push('asset_type'); vals.push('Information'); }
if (assetColumns.has('asset_class')) { cols.push('asset_class'); vals.push('Application'); }
if (assetColumns.has('container_type')) { cols.push('container_type'); vals.push('Technical'); }
if (assetColumns.has('description')) { cols.push('description'); vals.push('Auto-created baseline asset for organization-specific reporting.'); }
if (assetColumns.has('owner')) { cols.push('owner'); vals.push('Security Team'); }
if (assetColumns.has('location')) { cols.push('location'); vals.push('Primary Data Center'); }
if (assetColumns.has('cia_value')) { cols.push('cia_value'); vals.push('Medium'); }
if (assetColumns.has('criticality')) { cols.push('criticality'); vals.push('Medium'); }
if (assetColumns.has('confidentiality')) { cols.push('confidentiality'); vals.push(3); }
if (assetColumns.has('integrity')) { cols.push('integrity'); vals.push(3); }
if (assetColumns.has('availability')) { cols.push('availability'); vals.push(3); }
if (assetColumns.has('criticality_score')) { cols.push('criticality_score'); vals.push(60); }
if (assetColumns.has('security_requirements')) { cols.push('security_requirements'); vals.push('Access control, encryption in transit, periodic backup.'); }
if (assetColumns.has('organization_id')) { cols.push('organization_id'); vals.push(orgId); }
if (cols.length) {
const placeholders = cols.map(() => '?').join(', ');
const [result] = await db.execute(`INSERT INTO assets (${cols.join(', ')}) VALUES (${placeholders})`, vals);
primaryAssetId = result.insertId;
}
}
if (primaryAssetId) {
const [existingRisks] = await db.execute(
'SELECT id FROM octave_risk_assessments WHERE organization_id = ? ORDER BY id ASC LIMIT 1',
[orgId]
);
if (!existingRisks.length) {
const riskColumns = await getTableColumns('octave_risk_assessments');
const cols = [];
const vals = [];
if (riskColumns.has('organization_id')) { cols.push('organization_id'); vals.push(orgId); }
if (riskColumns.has('asset_id')) { cols.push('asset_id'); vals.push(primaryAssetId); }
if (riskColumns.has('threat_scenario')) { cols.push('threat_scenario'); vals.push('Unauthorized access to critical information due to weak authentication controls.'); }
if (riskColumns.has('impact_area')) { cols.push('impact_area'); vals.push('Data/Information'); }
if (riskColumns.has('impact_level')) { cols.push('impact_level'); vals.push('Medium'); }
if (riskColumns.has('probability')) { cols.push('probability'); vals.push('Medium'); }
if (riskColumns.has('certainty')) { cols.push('certainty'); vals.push('Medium'); }
if (riskColumns.has('likelihood')) { cols.push('likelihood'); vals.push(2); }
if (riskColumns.has('impact')) { cols.push('impact'); vals.push(3); }
if (riskColumns.has('risk_score')) { cols.push('risk_score'); vals.push(6); }
if (riskColumns.has('risk_level')) { cols.push('risk_level'); vals.push('Medium'); }
if (riskColumns.has('relative_risk_score')) { cols.push('relative_risk_score'); vals.push(6); }
if (riskColumns.has('mitigation_strategy')) { cols.push('mitigation_strategy'); vals.push('Enforce MFA and periodic access reviews.'); }
if (riskColumns.has('assessment_phase')) { cols.push('assessment_phase'); vals.push('Identify Risks'); }
if (cols.length) {
const placeholders = cols.map(() => '?').join(', ');
await db.execute(`INSERT INTO octave_risk_assessments (${cols.join(', ')}) VALUES (${placeholders})`, vals);
}
}
}
const findingColumns = await getTableColumns('audit_findings');
const hasFindingOrgId = findingColumns.has('organization_id');
const hasFindingTaskId = findingColumns.has('audit_task_id');
let hasFindingData = false;
if (hasFindingOrgId) {
const [rows] = await db.execute('SELECT id FROM audit_findings WHERE organization_id = ? LIMIT 1', [orgId]);
hasFindingData = rows.length > 0;
} else if (hasFindingTaskId) {
const [rows] = await db.execute('SELECT id FROM audit_findings WHERE audit_task_id = ? LIMIT 1', [auditTaskId]);
hasFindingData = rows.length > 0;
}
if (!hasFindingData && findingColumns.size > 0) {
const cols = [];
const vals = [];
if (hasFindingTaskId) { cols.push('audit_task_id'); vals.push(auditTaskId); }
if (hasFindingOrgId) { cols.push('organization_id'); vals.push(orgId); }
if (findingColumns.has('title')) { cols.push('title'); vals.push('Baseline Security Finding'); }
if (findingColumns.has('issue')) { cols.push('issue'); vals.push('Initial control baseline has not been fully validated.'); }
if (findingColumns.has('risk')) { cols.push('risk'); vals.push('Potential control effectiveness gap.'); }
if (findingColumns.has('description')) { cols.push('description'); vals.push('Auto-generated baseline finding to initialize organization-specific reporting data.'); }
if (findingColumns.has('risk_level')) { cols.push('risk_level'); vals.push('Medium'); }
if (findingColumns.has('category')) { cols.push('category'); vals.push('Security'); }
if (findingColumns.has('affected_asset')) { cols.push('affected_asset'); vals.push('Core Information Asset'); }
if (findingColumns.has('recommendation')) { cols.push('recommendation'); vals.push('Complete checklist review and attach supporting evidence.'); }
if (findingColumns.has('status')) { cols.push('status'); vals.push('Open'); }
if (findingColumns.has('finding_date')) { cols.push('finding_date'); vals.push(new Date().toISOString().slice(0, 10)); }
if (cols.length) {
const placeholders = cols.map(() => '?').join(', ');
await db.execute(`INSERT INTO audit_findings (${cols.join(', ')}) VALUES (${placeholders})`, vals);
}
}
return { auditTaskId };
}
async function getOrganizationComplianceStats(organizationId) {
const orgId = Number(organizationId || 0);
if (!Number.isInteger(orgId) || orgId <= 0) {
return { organization_id: null, total_controls: 0, compliant_controls: 0, compliance_percentage: 0 };
}
const checklistColumns = await getTableColumns('audit_checklist');
if (!checklistColumns.has('audit_task_id') || !checklistColumns.has('compliance_status')) {
return { organization_id: orgId, total_controls: 0, compliant_controls: 0, compliance_percentage: 0 };
}
const [rows] = await db.execute(
`SELECT
COUNT(*) AS total_controls,
SUM(CASE WHEN LOWER(TRIM(ac.compliance_status)) = 'compliant' THEN 1 ELSE 0 END) AS compliant_controls
FROM audit_checklist ac
INNER JOIN audit_tasks at ON at.id = ac.audit_task_id
WHERE at.organization_id = ?`,
[orgId]
);
const total = Number(rows[0]?.total_controls || 0);
const compliant = Number(rows[0]?.compliant_controls || 0);
const percentage = total ? Number(((compliant / total) * 100).toFixed(2)) : 0;
return {
organization_id: orgId,
total_controls: total,
compliant_controls: compliant,
compliance_percentage: percentage
};
}
async function bootstrapDatabase() {
const rootConfig = { ...dbConfig };
delete rootConfig.database;
const root = await mysql.createConnection(rootConfig);
await root.execute(`CREATE DATABASE IF NOT EXISTS \`${dbConfig.database}\``);
await root.end();
db = await mysql.createConnection(dbConfig);
await db.execute(`
CREATE TABLE IF NOT EXISTS organizations (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
business_sector VARCHAR(120) DEFAULT 'Technology',
employee_count INT DEFAULT 0,
system_type TEXT,
exposure_level ENUM('Low','Medium','High','Critical') DEFAULT 'Medium',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
full_name VARCHAR(255) NOT NULL,
role ENUM('admin','auditor','auditee') NOT NULL DEFAULT 'auditee',
organization_id INT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS assets (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
asset_type ENUM('Information') DEFAULT 'Information',
asset_class ENUM('Application','Server','Data') DEFAULT 'Application',
container_type ENUM('Technical','Physical','People') DEFAULT 'Technical',
description TEXT,
owner VARCHAR(255),
location VARCHAR(255),
cia_value ENUM('Low','Medium','High') DEFAULT 'Medium',
criticality ENUM('Low','Medium','High','Critical') DEFAULT 'Medium',
confidentiality TINYINT DEFAULT 3,
integrity TINYINT DEFAULT 3,
availability TINYINT DEFAULT 3,
criticality_score DECIMAL(8,2) DEFAULT 60.00,
security_requirements TEXT,
organization_id INT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS vulnerabilities (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
category VARCHAR(120) NOT NULL,
description TEXT,
cwe_id VARCHAR(25),
owasp_rank INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS asset_vulnerabilities (
id INT AUTO_INCREMENT PRIMARY KEY,
asset_id INT NOT NULL,
vulnerability_id INT NOT NULL,
likelihood INT DEFAULT 2,
impact INT DEFAULT 2,
risk_score DECIMAL(8,2) DEFAULT 4,
risk_level ENUM('Low','Medium','High','Critical') DEFAULT 'Medium',
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uniq_asset_vuln (asset_id, vulnerability_id),
FOREIGN KEY (asset_id) REFERENCES assets(id) ON DELETE CASCADE,
FOREIGN KEY (vulnerability_id) REFERENCES vulnerabilities(id) ON DELETE CASCADE
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS threat_actors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
type ENUM('External','Internal','Accidental') DEFAULT 'External',
motivation ENUM('Financial','Ideological','Revenge','Espionage','Opportunistic','Unknown') DEFAULT 'Unknown',
capability_level ENUM('Low','Medium','High') DEFAULT 'Medium',
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS octave_risk_assessments (
id INT AUTO_INCREMENT PRIMARY KEY,
organization_id INT NULL,
asset_id INT NOT NULL,
threat_actor_id INT NULL,
threat_scenario TEXT NOT NULL,
impact_area ENUM('Reputation','Financial','Productivity','Safety','Legal/Regulatory','Data/Information') DEFAULT 'Financial',
impact_level ENUM('Very Low','Low','Medium','High','Very High') DEFAULT 'Medium',
probability ENUM('Very Low','Low','Medium','High','Very High') DEFAULT 'Medium',
certainty ENUM('Very Low','Low','Medium','High','Very High') DEFAULT 'Medium',
likelihood INT DEFAULT 2,
impact INT DEFAULT 2,
risk_score DECIMAL(8,2) DEFAULT 4,
risk_level ENUM('Low','Medium','High','Critical') DEFAULT 'Medium',
relative_risk_score DECIMAL(8,2) DEFAULT 4,
mitigation_strategy TEXT,
residual_risk_score DECIMAL(8,2) DEFAULT 0,
assessment_phase ENUM('Establish Criteria','Profile Assets','Identify Threats','Identify Risks','Analyze Risks','Select Mitigation') DEFAULT 'Identify Threats',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE SET NULL,
FOREIGN KEY (asset_id) REFERENCES assets(id) ON DELETE CASCADE,
FOREIGN KEY (threat_actor_id) REFERENCES threat_actors(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS audit_tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
organization_id INT NULL,
auditor_id INT NULL,
framework ENUM('OCTAVE Allegro') DEFAULT 'OCTAVE Allegro',
status ENUM('pending','in_progress','completed') DEFAULT 'pending',
start_date DATE NULL,
end_date DATE NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE SET NULL,
FOREIGN KEY (auditor_id) REFERENCES users(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS audit_checklist (
id INT AUTO_INCREMENT PRIMARY KEY,
audit_task_id INT NULL,
control_id VARCHAR(60),
control_name VARCHAR(255) NOT NULL,
control_description TEXT,
category VARCHAR(120) DEFAULT 'Access Control',
compliance_status ENUM('Compliant','Partially Compliant','Non-Compliant','Not Assessed') DEFAULT 'Not Assessed',
evidence_required BOOLEAN DEFAULT TRUE,
findings TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE CASCADE
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS audit_evidence (
id INT AUTO_INCREMENT PRIMARY KEY,
audit_task_id INT NULL,
checklist_item_id INT NULL,
evidence_type VARCHAR(120),
file_name VARCHAR(255) NOT NULL,
file_path VARCHAR(500) NOT NULL,
file_type VARCHAR(120),
file_size BIGINT DEFAULT 0,
description TEXT,
upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
uploaded_by INT NULL,
evidence_references TEXT,
FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE CASCADE,
FOREIGN KEY (checklist_item_id) REFERENCES audit_checklist(id) ON DELETE SET NULL,
FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS audit_findings (
id INT AUTO_INCREMENT PRIMARY KEY,
audit_task_id INT NULL,
organization_id INT NULL,
title VARCHAR(255) NOT NULL,
issue TEXT,
risk TEXT,
description TEXT NOT NULL,
risk_level ENUM('Low','Medium','High','Critical') DEFAULT 'Medium',
category VARCHAR(120) DEFAULT 'Security',
affected_asset VARCHAR(255),
recommendation TEXT,
status ENUM('Open','In Progress','Resolved') DEFAULT 'Open',
finding_date DATE DEFAULT (CURRENT_DATE),
due_date DATE NULL,
assigned_to VARCHAR(255),
evidence_references TEXT,
ai_generated BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE CASCADE,
FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS compliance_scores (
id INT AUTO_INCREMENT PRIMARY KEY,
organization_id INT NULL,
audit_task_id INT NULL,
assessment_date DATE NOT NULL,
overall_score DECIMAL(8,2) NOT NULL,
recommendations TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE SET NULL,
FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS reports (
id INT AUTO_INCREMENT PRIMARY KEY,
organization_id INT NULL,
audit_task_id INT NULL,
report_type ENUM('Security Audit','Risk Assessment','Compliance','Executive') DEFAULT 'Security Audit',
format ENUM('PDF','DOCX') DEFAULT 'PDF',
file_name VARCHAR(255) NOT NULL,
file_path VARCHAR(500) NOT NULL,
generated_by VARCHAR(255) NOT NULL,
generated_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status ENUM('Generating','Completed','Failed') DEFAULT 'Completed',
FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE SET NULL,
FOREIGN KEY (audit_task_id) REFERENCES audit_tasks(id) ON DELETE SET NULL
)
`);
await db.execute(`
CREATE TABLE IF NOT EXISTS ai_consultations (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
query TEXT NOT NULL,
response TEXT,
consultation_type ENUM('vulnerability_explanation','risk_assessment','control_recommendation','audit_advice') NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
`);
await ensureColumn('organizations', 'system_type', 'TEXT');
await ensureColumn('assets', 'criticality_score', 'DECIMAL(8,2) DEFAULT 60.00');
await ensureColumn('assets', 'confidentiality', 'TINYINT DEFAULT 3');
await ensureColumn('assets', 'integrity', 'TINYINT DEFAULT 3');