Repository navigation
Expand file tree
/
Copy pathsspComparisonV3.js
More file actions
876 lines (789 loc) · 29.7 KB
/
Copy pathsspComparisonV3.js
File metadata and controls
876 lines (789 loc) · 29.7 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
/**
* Copyright 2025 Adobe. All rights reserved.
* Copyright (c) 2025 Mukesh Kesharwani
*
* Licensed under the MIT License. See LICENSE file for details.
*/
import { normalizeAdobeTeamResponsibleSlots } from './utils/adobeTeamResponsible.js';
import { getDefaultSystemStatus } from './utils/constants.js';
/**
* SSP Comparison Module - Direct Catalog Comparison
*
* @author Mukesh Kesharwani <mukesh.kesharwani@adobe.com>
* @copyright Copyright (c) 2025 Mukesh Kesharwani
* @license MIT
*
* Inspired by roscal (https://github.com/gborough/roscal) and NIST approaches
*
* Compare catalog with existing SSP by directly comparing control definitions
* @param {Array} catalogControls - Controls from the new catalog
* @param {Object} existingSSP - Existing OSCAL SSP data
* @param {Object} catalogData - Full catalog data
* @returns {Object} - Comparison results with marked controls
*/
export function compareWithExistingSSP(catalogControls, existingSSP, catalogData) {
try {
console.log('Starting OSCAL catalog comparison...');
// Extract existing control data from SSP
const existingControls = extractControlsFromSSP(existingSSP);
const existingControlsMap = new Map();
existingControls.forEach(control => {
existingControlsMap.set(control.id, control);
});
// Extract system information from SSP
const systemInfo = extractSystemInfoFromSSP(existingSSP);
console.log(`Comparing ${catalogControls.length} catalog controls with ${existingControls.length} SSP controls`);
// Compare each control
const comparedControls = catalogControls.map(catalogControl => {
const existingControl = existingControlsMap.get(catalogControl.id);
if (!existingControl) {
// New control - doesn't exist in old SSP
return {
...catalogControl,
changeStatus: 'new',
changeReason: 'New control added in catalog',
status: 'not-assessed',
implementation: '',
remarks: '',
adobeTeamResponsible: normalizeAdobeTeamResponsibleSlots(catalogControl.adobeTeamResponsible)
};
}
// Control exists - compare CATALOG definitions only (not implementation data)
const titleChanged = !compareStrings(
catalogControl.title,
existingControl.catalogTitle
);
const descriptionChanged = !compareStrings(
catalogControl.description,
existingControl.catalogDescription
);
let changeStatus = 'unchanged';
let changeReason = null;
let changeDetails = [];
if (titleChanged || descriptionChanged) {
changeStatus = 'changed';
if (titleChanged && descriptionChanged) {
changeReason = 'Control title and description updated';
changeDetails = ['title', 'description'];
} else if (titleChanged) {
changeReason = 'Control title updated';
changeDetails = ['title'];
} else {
changeReason = 'Control description updated';
changeDetails = ['description'];
}
}
// Always merge: new catalog definition + ALL existing user data
return {
// New catalog control definition (title, description, parts)
...catalogControl,
// Change tracking
changeStatus,
changeReason,
...(changeDetails.length > 0 && { changeDetails }),
// Pre-populate ALL existing user data (implementation, status, etc.)
status: existingControl.status || 'not-assessed',
implementation: existingControl.implementation || '',
remarks: existingControl.remarks || '',
responsibleParty: existingControl.responsibleParty || '',
adobeTeamResponsible: normalizeAdobeTeamResponsibleSlots(existingControl.adobeTeamResponsible),
controlOwner: existingControl.controlOwner || '',
consumerGuidance: existingControl.consumerGuidance || '',
implementationDate: existingControl.implementationDate || '',
reviewDate: existingControl.reviewDate || '',
nextReviewDate: existingControl.nextReviewDate || '',
controlType: existingControl.controlType || '',
evidence: existingControl.evidence || '',
testingProcedure: existingControl.testingProcedure || '',
testingFrequency: existingControl.testingFrequency || '',
lastTestDate: existingControl.lastTestDate || '',
apiUrl: existingControl.apiUrl || '',
apiCredentialId: existingControl.apiCredentialId || '',
apiResponseData: existingControl.apiResponseData || null,
apiDataHistory: existingControl.apiDataHistory || [],
riskRating: existingControl.riskRating || '',
frameworks: existingControl.frameworks || '',
compensatingControls: existingControl.compensatingControls || '',
exceptions: existingControl.exceptions || '',
// Store old catalog values for reference if changed
...(changeStatus === 'changed' && {
oldTitle: existingControl.catalogTitle,
oldDescription: existingControl.catalogDescription
})
};
});
// Generate statistics
const stats = {
total: comparedControls.length,
new: comparedControls.filter(c => c.changeStatus === 'new').length,
changed: comparedControls.filter(c => c.changeStatus === 'changed').length,
unchanged: comparedControls.filter(c => c.changeStatus === 'unchanged').length,
existingTotal: existingControls.length
};
console.log('Comparison complete:', stats);
return {
controls: comparedControls,
stats,
systemInfo,
comparisonDate: new Date().toISOString()
};
} catch (error) {
console.error('Error in catalog comparison:', error);
throw error;
}
}
/**
* Compare two strings with normalization
* Returns true if strings are considered equal
*/
function compareStrings(str1, str2) {
// Handle null/undefined
if (!str1 && !str2) return true;
if (!str1 || !str2) return false;
// Normalize strings for comparison
const normalize = (text) => {
if (!text) return '';
return text
.trim()
.replace(/\s+/g, ' ') // Normalize whitespace
.replace(/[\r\n]+/g, '\n') // Normalize line breaks
.toLowerCase();
};
return normalize(str1) === normalize(str2);
}
/**
* Extract controls and their data from existing SSP
* @param {Object} sspData - OSCAL SSP JSON
* @returns {Array} - Array of control objects with implementation data
*/
export function extractControlsFromSSP(sspData) {
const controls = [];
try {
let implementedRequirements = [];
// Handle OSCAL SSP format
if (sspData['system-security-plan']) {
const ssp = sspData['system-security-plan'];
if (ssp['control-implementation']?.['implemented-requirements']) {
implementedRequirements = ssp['control-implementation']['implemented-requirements'];
}
}
// Handle our simplified format
if (sspData.controls && Array.isArray(sspData.controls)) {
implementedRequirements = sspData.controls;
}
// Also check for catalog stored in SSP (from our exports)
if (sspData.catalog) {
// Extract controls from catalog structure
const catalogControls = extractControlsFromCatalog(sspData.catalog);
return catalogControls;
}
implementedRequirements.forEach(req => {
// Extract catalog metadata and custom fields from props
let catalogTitle = '';
let catalogDescription = '';
let groupTitle = '';
let status = 'not-assessed';
let responsibleParty = '';
let controlOwner = '';
let consumerGuidance = '';
let implementationDate = '';
let reviewDate = '';
let nextReviewDate = '';
let controlType = '';
let evidence = '';
let testingProcedure = '';
let testingFrequency = '';
let lastTestDate = '';
let apiUrl = '';
let apiCredentialId = '';
let apiResponseData = null;
let apiDataHistory = [];
let riskRating = '';
let frameworks = '';
let compensatingControls = '';
let exceptions = '';
let adobeTeamResponsible = ['', '', ''];
if (req.props && Array.isArray(req.props)) {
req.props.forEach(prop => {
if (prop.name === 'catalog-control-title') {
catalogTitle = prop.value || '';
} else if (prop.name === 'catalog-control-description') {
catalogDescription = prop.value || '';
} else if (prop.name === 'group-title' || prop.name === 'control-group') {
groupTitle = prop.value || '';
} else if (prop.name === 'implementation-status') {
status = prop.value || 'not-assessed';
} else if (prop.name === 'responsible-party') {
responsibleParty = prop.value || '';
} else if (prop.name === 'adobe-team-responsible') {
adobeTeamResponsible = normalizeAdobeTeamResponsibleSlots(prop.value);
} else if (prop.name === 'control-owner') {
controlOwner = prop.value || '';
} else if (prop.name === 'consumer-guidance') {
consumerGuidance = prop.value || '';
} else if (prop.name === 'implementation-date') {
implementationDate = prop.value || '';
} else if (prop.name === 'review-date') {
reviewDate = prop.value || '';
} else if (prop.name === 'next-review-date') {
nextReviewDate = prop.value || '';
} else if (prop.name === 'control-type') {
controlType = prop.value || '';
} else if (prop.name === 'evidence') {
evidence = prop.value || '';
} else if (prop.name === 'testing-procedure') {
testingProcedure = prop.value || '';
} else if (prop.name === 'testing-frequency') {
testingFrequency = prop.value || '';
} else if (prop.name === 'last-test-date') {
lastTestDate = prop.value || '';
} else if (prop.name === 'api-url') {
apiUrl = prop.value || '';
} else if (prop.name === 'api-credential-id') {
apiCredentialId = prop.value || '';
} else if (prop.name === 'api-response-data') {
try {
apiResponseData = JSON.parse(prop.value);
} catch (e) {
apiResponseData = prop.value;
}
} else if (prop.name === 'api-data-history') {
try {
apiDataHistory = JSON.parse(prop.value);
} catch (e) {
apiDataHistory = [];
}
} else if (prop.name === 'risk-rating') {
riskRating = prop.value || '';
} else if (prop.name === 'frameworks') {
frameworks = prop.value || '';
} else if (prop.name === 'compensating-controls') {
compensatingControls = prop.value || '';
} else if (prop.name === 'exceptions') {
exceptions = prop.value || '';
}
});
}
// Fallback: try to extract from other fields
if (!catalogTitle && req.title) {
catalogTitle = req.title;
}
if (!catalogDescription) {
catalogDescription = extractDescription(req);
}
const controlData = {
id: req['control-id'] || req.id,
catalogTitle,
catalogDescription,
groupTitle,
// User implementation data (from props or fallback to direct properties)
status,
implementation: req.implementation || req.description || '',
remarks: req.remarks || '',
responsibleParty: responsibleParty || req.responsibleParty || req['responsible-roles']?.[0] || '',
adobeTeamResponsible: normalizeAdobeTeamResponsibleSlots(
adobeTeamResponsible.some((x) => String(x).trim()) ? adobeTeamResponsible : req.adobeTeamResponsible
),
controlOwner: controlOwner || req.controlOwner || '',
consumerGuidance: consumerGuidance || req.consumerGuidance || '',
implementationDate: implementationDate || req.implementationDate || '',
reviewDate: reviewDate || req.reviewDate || '',
nextReviewDate: nextReviewDate || req.nextReviewDate || '',
controlType: controlType || req.controlType || '',
evidence: evidence || req.evidence || '',
testingProcedure: testingProcedure || req.testingProcedure || '',
testingFrequency: testingFrequency || req.testingFrequency || '',
lastTestDate: lastTestDate || req.lastTestDate || '',
apiUrl: apiUrl || req.apiUrl || '',
apiCredentialId: apiCredentialId || req.apiCredentialId || '',
apiResponseData: apiResponseData || req.apiResponseData || null,
apiDataHistory: apiDataHistory || req.apiDataHistory || [],
riskRating: riskRating || req.riskRating || '',
frameworks: frameworks || req.frameworks || '',
compensatingControls: compensatingControls || req.compensatingControls || '',
exceptions: exceptions || req.exceptions || ''
};
controls.push(controlData);
});
} catch (error) {
console.error('Error extracting controls from SSP:', error);
}
return controls;
}
/**
* Extract controls from catalog structure if present in SSP
*/
function extractControlsFromCatalog(catalog) {
const controls = [];
const processCatalog = (cat) => {
if (!cat) return;
// Process groups
if (cat.groups && Array.isArray(cat.groups)) {
cat.groups.forEach(group => {
if (group.controls) {
group.controls.forEach(control => {
controls.push({
id: control.id,
catalogTitle: control.title || '',
catalogDescription: extractControlDescription(control),
groupTitle: group.title || '',
status: 'not-assessed'
});
});
}
// Recursive for nested groups
if (group.groups) {
processCatalog({ groups: group.groups });
}
});
}
// Process root-level controls
if (cat.controls && Array.isArray(cat.controls)) {
cat.controls.forEach(control => {
controls.push({
id: control.id,
catalogTitle: control.title || '',
catalogDescription: extractControlDescription(control),
groupTitle: '',
status: 'not-assessed'
});
});
}
};
processCatalog(catalog.catalog || catalog);
return controls;
}
/**
* Extract control description from parts
*/
function extractControlDescription(control) {
if (!control.parts || control.parts.length === 0) {
return '';
}
// Find statement or description parts
const descParts = control.parts.filter(part =>
part.name === 'statement' || part.name === 'description' || part.name === 'guidance'
);
if (descParts.length === 0) {
// Try to get prose from any part
const proseParts = control.parts.filter(part => part.prose);
if (proseParts.length > 0) {
return proseParts.map(p => p.prose).join('\n\n');
}
return '';
}
// Extract prose from description parts
return descParts.map(part => part.prose || '').filter(Boolean).join('\n\n');
}
/**
* Extract description from various OSCAL formats
*/
function extractDescription(req) {
if (req.description && typeof req.description === 'string') {
return req.description;
}
if (req.statements && Array.isArray(req.statements)) {
return req.statements.map(s => s.description || '').join('\n');
}
if (req['control-description']) {
return req['control-description'];
}
if (req.parts && Array.isArray(req.parts)) {
return extractControlDescription({ parts: req.parts });
}
return '';
}
/**
* Extract system information from SSP
* @param {Object} sspData - OSCAL SSP JSON
* @returns {Object} - System information object
*/
function extractSystemInfoFromSSP(sspData) {
const systemInfo = {
systemName: '',
systemId: '',
description: '',
authorizationBoundary: '',
securityLevel: 'moderate',
confidentiality: 'moderate',
integrity: 'moderate',
availability: 'moderate',
status: getDefaultSystemStatus(),
systemType: '',
authorizationDate: '',
organization: '',
systemOwner: '',
assessorDetails: '',
cspIaaS: '',
cspPaaS: '',
cspSaaS: ''
};
try {
// Handle OSCAL SSP format
if (sspData['system-security-plan']) {
const ssp = sspData['system-security-plan'];
// Extract from system-characteristics
if (ssp['system-characteristics']) {
const sysChar = ssp['system-characteristics'];
// System Name
if (sysChar['system-name']) {
systemInfo.systemName = sysChar['system-name'];
}
// System ID
if (sysChar['system-ids'] && Array.isArray(sysChar['system-ids']) && sysChar['system-ids'].length > 0) {
systemInfo.systemId = sysChar['system-ids'][0].id || sysChar['system-ids'][0].identifier || '';
}
// Description
if (sysChar.description) {
systemInfo.description = sysChar.description;
}
// Security Sensitivity Level
if (sysChar['security-sensitivity-level']) {
systemInfo.securityLevel = sysChar['security-sensitivity-level'];
}
// Security Impact Level
if (sysChar['security-impact-level']) {
const impact = sysChar['security-impact-level'];
if (impact['security-objective-confidentiality']) {
systemInfo.confidentiality = impact['security-objective-confidentiality'];
}
if (impact['security-objective-integrity']) {
systemInfo.integrity = impact['security-objective-integrity'];
}
if (impact['security-objective-availability']) {
systemInfo.availability = impact['security-objective-availability'];
}
}
// System Status
if (sysChar.status) {
if (typeof sysChar.status === 'string') {
systemInfo.status = sysChar.status;
} else if (sysChar.status.state) {
systemInfo.status = sysChar.status.state;
}
}
// System Type
if (sysChar['system-type']) {
systemInfo.systemType = sysChar['system-type'];
}
// Authorization Boundary
if (sysChar['authorization-boundary']) {
if (sysChar['authorization-boundary'].description) {
systemInfo.authorizationBoundary = sysChar['authorization-boundary'].description;
}
if (sysChar['authorization-boundary'].date) {
systemInfo.authorizationDate = sysChar['authorization-boundary'].date;
}
}
// Extract from props
if (sysChar.props && Array.isArray(sysChar.props)) {
sysChar.props.forEach(prop => {
if (prop.name === 'organization' && prop.value) {
systemInfo.organization = prop.value;
} else if (prop.name === 'system-owner' && prop.value) {
systemInfo.systemOwner = prop.value;
} else if (prop.name === 'assessor-details' && prop.value) {
systemInfo.assessorDetails = prop.value;
} else if (prop.name === 'csp-iaas' && prop.value) {
systemInfo.cspIaaS = prop.value;
} else if (prop.name === 'csp-paas' && prop.value) {
systemInfo.cspPaaS = prop.value;
} else if (prop.name === 'csp-saas' && prop.value) {
systemInfo.cspSaaS = prop.value;
}
});
}
}
// Extract from metadata (only if not already set from props)
if (ssp.metadata) {
// Organization - only extract from metadata if not already set from system-characteristics.props
// This prevents overwriting the implementing organization with the catalog publisher
if (!systemInfo.organization && ssp.metadata.parties && Array.isArray(ssp.metadata.parties)) {
// Look for organization in responsible-parties first (more specific)
if (ssp.metadata['responsible-parties']) {
const orgRole = ssp.metadata['responsible-parties'].find(rp =>
rp['role-id'] === 'system-owner' || rp['role-id'] === 'prepared-by'
);
if (orgRole) {
const partyUuid = orgRole['party-uuids'] && orgRole['party-uuids'][0];
if (partyUuid) {
const party = ssp.metadata.parties.find(p => p.uuid === partyUuid && p.type === 'organization');
if (party && party.name) {
systemInfo.organization = party.name;
}
}
}
}
// Fallback: use first organization only if still not found
if (!systemInfo.organization) {
const orgParty = ssp.metadata.parties.find(p => p.type === 'organization');
if (orgParty && orgParty.name) {
systemInfo.organization = orgParty.name;
}
}
}
// System Owner from responsible parties
if (ssp.metadata['responsible-parties'] && Array.isArray(ssp.metadata['responsible-parties'])) {
const ownerRole = ssp.metadata['responsible-parties'].find(rp =>
rp['role-id'] === 'system-owner' || rp.role === 'system-owner'
);
if (ownerRole) {
// Get party name
const partyUuid = ownerRole['party-uuids'] && ownerRole['party-uuids'][0];
if (partyUuid && ssp.metadata.parties) {
const party = ssp.metadata.parties.find(p => p.uuid === partyUuid);
if (party && party.name) {
systemInfo.systemOwner = party.name;
}
}
}
// Assessor Details from responsible parties with role-id "prepared-by"
// Find the organization party that is specifically the assessor (has the assessment remarks)
const assessorRoles = ssp.metadata['responsible-parties'].filter(rp =>
rp['role-id'] === 'prepared-by' || rp.role === 'prepared-by'
);
if (assessorRoles && assessorRoles.length > 0 && ssp.metadata.parties) {
// Look for the party that is type "organization" AND has assessor-specific remarks
for (const assessorRole of assessorRoles) {
const partyUuid = assessorRole['party-uuids'] && assessorRole['party-uuids'][0];
if (partyUuid) {
const party = ssp.metadata.parties.find(p =>
p.uuid === partyUuid &&
p.type === 'organization' &&
p.remarks &&
p.remarks.includes('Assessment organization')
);
if (party && party.name) {
systemInfo.assessorDetails = party.name;
break; // Found the assessor organization
}
}
}
}
}
}
}
// Handle our simplified format (if exists)
if (sspData.systemInfo) {
return { ...systemInfo, ...sspData.systemInfo };
}
} catch (error) {
console.error('Error extracting system info from SSP:', error);
}
return systemInfo;
}
const IMPLEMENTATION_PROP_NAMES = new Set([
'implementation-status',
'catalog-control-title',
'catalog-control-description',
'group-title',
'control-group',
'responsible-party',
'adobe-team-responsible',
'control-owner',
'consumer-guidance',
'implementation-date',
'review-date',
'next-review-date',
'control-type',
'evidence',
'testing-objective',
'testing-procedure',
'testing-frequency',
'last-test-date',
'api-url',
'api-credential-id',
'api-response-data',
'api-data-history',
'risk-rating',
'frameworks',
'compensating-controls',
'exceptions',
]);
function readPropValue(props, name) {
const entry = (props || []).find((p) => p?.name === name);
return entry?.value != null ? String(entry.value) : '';
}
/**
* Extract catalog-shaped controls (title, description, parts, params, props) from embedded catalog.
* @param {Object} catalogRoot
* @returns {Array}
*/
function extractCatalogControlsFromEmbeddedCatalog(catalogRoot) {
const controls = [];
const catalog = catalogRoot?.catalog || catalogRoot;
if (!catalog) {
return controls;
}
const processGroup = (group, parentId = null) => {
if (group.controls) {
group.controls.forEach((control) => {
controls.push({
id: control.id,
class: control.class,
title: control.title,
description: extractControlDescription(control),
params: control.params || [],
props: control.props || [],
parts: control.parts || [],
groupId: group.id,
groupTitle: group.title,
parentId,
});
if (control.controls) {
control.controls.forEach((subControl) => {
controls.push({
id: subControl.id,
class: subControl.class,
title: subControl.title,
description: extractControlDescription(subControl),
params: subControl.params || [],
props: subControl.props || [],
parts: subControl.parts || [],
groupId: group.id,
groupTitle: group.title,
parentId: control.id,
});
});
}
});
}
if (group.groups) {
group.groups.forEach((nested) => processGroup(nested, group.id));
}
};
if (catalog.groups) {
catalog.groups.forEach((group) => processGroup(group));
}
if (catalog.controls) {
catalog.controls.forEach((control) => {
controls.push({
id: control.id,
class: control.class,
title: control.title,
description: extractControlDescription(control),
params: control.params || [],
props: control.props || [],
parts: control.parts || [],
groupId: null,
groupTitle: '',
parentId: null,
});
});
}
return controls;
}
/**
* Build catalog-control rows from an implemented-requirement (preserves parts/params/class).
* @param {Object} req
* @returns {Object|null}
*/
function implementedRequirementToCatalogControl(req) {
const id = req?.['control-id'] || req?.id;
if (!id) {
return null;
}
const props = Array.isArray(req.props) ? req.props : [];
const catalogOnlyProps = props.filter((p) => p?.name && !IMPLEMENTATION_PROP_NAMES.has(p.name));
return {
id,
class: req.class,
title: readPropValue(props, 'catalog-control-title') || req.title || '',
description: readPropValue(props, 'catalog-control-description') || extractDescription(req),
parts: req.parts || [],
params: req.params || [],
props: catalogOnlyProps,
groupTitle: readPropValue(props, 'group-title') || readPropValue(props, 'control-group') || '',
};
}
/**
* Catalog controls for export — embedded catalog, or implemented-requirements with OSCAL structure.
* @param {Object} sspData
* @returns {Array}
*/
export function buildCatalogControlsForExport(sspData) {
if (!sspData || typeof sspData !== 'object') {
return [];
}
if (sspData.catalog) {
return extractCatalogControlsFromEmbeddedCatalog(sspData.catalog);
}
const ssp = sspData['system-security-plan'] || sspData;
const reqs = ssp?.['control-implementation']?.['implemented-requirements'];
if (Array.isArray(reqs) && reqs.length > 0) {
return reqs.map(implementedRequirementToCatalogControl).filter(Boolean);
}
return extractControlsFromSSP(sspData).map((c) => ({
id: c.id,
title: c.catalogTitle || '',
description: c.catalogDescription || '',
parts: [],
params: [],
props: [],
groupTitle: c.groupTitle || '',
}));
}
/**
* Merge Multi-Report Comparison edits onto export controls without dropping catalog fields.
* @param {Array} controls
* @param {Object} controlEdits
* @returns {Array}
*/
export function applyMrcControlEdits(controls, controlEdits) {
if (!Array.isArray(controls)) {
return [];
}
if (!controlEdits || typeof controlEdits !== 'object' || Array.isArray(controlEdits)) {
return controls;
}
return controls.map((control) => {
const edit = controlEdits[control.id];
if (!edit || typeof edit !== 'object') {
return control;
}
const merged = { ...control };
for (const [key, value] of Object.entries(edit)) {
if (value !== undefined) {
merged[key] = value;
}
}
if (edit.catalogTitle) {
merged.title = edit.catalogTitle;
}
if (edit.catalogDescription) {
merged.description = edit.catalogDescription;
}
return merged;
});
}
/**
* Build generate-ssp payload from baseline SSP + optional MRC edits (same shape as main workflow).
* @param {Object} sspData
* @param {Object} [controlEdits]
* @returns {{ controls: Array, systemInfo: Object, metadata: Object }}
*/
export function prepareSspExportPayload(sspData, controlEdits = {}) {
const catalogControls = buildCatalogControlsForExport(sspData);
const compared = compareWithExistingSSP(catalogControls, sspData, null);
const controls = applyMrcControlEdits(
compared.controls.map(({
changeStatus,
changeReason,
changeDetails,
oldTitle,
oldDescription,
...rest
}) => rest),
controlEdits,
);
const root = sspData['system-security-plan'] ? sspData : { 'system-security-plan': sspData };
const metadata = root['system-security-plan']?.metadata || {};
const catalogueUrl = root['system-security-plan']?.['import-profile']?.href || '';
const systemInfo = {
...(compared.systemInfo || {}),
catalogueUrl,
title: compared.systemInfo?.title || metadata.title,
version: compared.systemInfo?.version || metadata.version,
};
return { controls, systemInfo, metadata };
}