-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathspdx-to-cdx.ts
More file actions
250 lines (218 loc) · 7.64 KB
/
Copy pathspdx-to-cdx.ts
File metadata and controls
250 lines (218 loc) · 7.64 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
import { Enums } from '@cyclonedx/cyclonedx-library';
import type * as CDX from '@cyclonedx/cyclonedx-library';
import type { SPDX23 } from './types/bom/spdx-2.3.schema.js';
type CdxBom = CDX.Serialize.JSON.Types.Normalized.Bom;
type Component = CDX.Serialize.JSON.Types.Normalized.Component;
type Dependency = CDX.Serialize.JSON.Types.Normalized.Dependency;
type Hash = CDX.Serialize.JSON.Types.Normalized.Hash;
type License = CDX.Serialize.JSON.Types.Normalized.License;
type ExternalReference = CDX.Serialize.JSON.Types.Normalized.ExternalReference;
type Scope =
| Enums.ComponentScope.Required
| Enums.ComponentScope.Optional
| Enums.ComponentScope.Excluded;
const rank: Record<Scope, number> = {
[Enums.ComponentScope.Required]: 3,
[Enums.ComponentScope.Optional]: 2,
[Enums.ComponentScope.Excluded]: 1,
};
const algorithmMap: Record<string, Enums.HashAlgorithm> = {
MD5: Enums.HashAlgorithm.MD5,
SHA1: Enums.HashAlgorithm['SHA-1'],
SHA256: Enums.HashAlgorithm['SHA-256'],
SHA384: Enums.HashAlgorithm['SHA-384'],
SHA512: Enums.HashAlgorithm['SHA-512'],
'SHA3-256': Enums.HashAlgorithm['SHA3-256'],
'SHA3-384': Enums.HashAlgorithm['SHA3-384'],
'SHA3-512': Enums.HashAlgorithm['SHA3-512'],
'BLAKE2b-256': Enums.HashAlgorithm['BLAKE2b-256'],
'BLAKE2b-384': Enums.HashAlgorithm['BLAKE2b-384'],
'BLAKE2b-512': Enums.HashAlgorithm['BLAKE2b-512'],
BLAKE3: Enums.HashAlgorithm.BLAKE3,
};
const LICENSE_EXPRESSION_REGEX = /\b(AND|OR|WITH)\b|\(|\)/;
const TOOL_NAME_REGEX = /^(.+)[-@](\d.*)$/;
// Remove common trailing version suffixes like "App v1.2.3", "pkg@1.0.0", "(version 2)" etc.
const TRAILING_VERSION_REGEXES = [
/(?:^|[\s\-_.()\[\]@])v(?:ersion)?\.?\s*\d+(?:\.\d+)*(?:[-+_.][0-9A-Za-z.-]+)?(?:\s*[\)\]\}])?$/i,
/(?:^|[\s\-_.()\[\]@])\d+\.\d+(?:\.\d+)*(?:[-+_.][0-9A-Za-z.-]+)?(?:\s*[\)\]\}])?$/i,
];
function upgrade(c: Component, next: Scope) {
if (!c.scope || rank[next] > rank[c.scope]) c.scope = next;
}
function mapScope(rel: string): Scope {
switch (rel) {
case 'OPTIONAL_DEPENDENCY_OF':
case 'OPTIONAL_DEPENDENCY':
return Enums.ComponentScope.Optional;
case 'DEV_DEPENDENCY_OF':
case 'BUILD_DEPENDENCY_OF':
case 'TEST_DEPENDENCY_OF':
case 'DEVELOPMENT_DEPENDENCY_OF':
case 'BUILD_TOOL_OF':
return Enums.ComponentScope.Excluded;
default:
return Enums.ComponentScope.Required;
}
}
function stripVersionSuffix(name?: string): string | null {
const trimmedName = name?.trim();
if (!trimmedName) return null;
for (const regex of TRAILING_VERSION_REGEXES) {
const sanitized = trimmedName.replace(regex, '').trim();
if (sanitized !== trimmedName) {
return sanitized || null;
}
}
return trimmedName;
}
function resolveMetadataComponentName(
spdxDocumentName: string | undefined,
rootComponentName: string | null,
): string | null {
const documentName = spdxDocumentName?.trim();
if (documentName) return documentName;
if (rootComponentName) {
return stripVersionSuffix(rootComponentName) || rootComponentName;
}
return null;
}
/**
* Converts an SPDX BOM to CycloneDX format.
* Takes the most important package and relationship data from SPDX and translates them into CycloneDX components and dependencies as closely as possible.
* @param spdx - The SPDX BOM object to convert
* @returns A CycloneDX BOM object
*/
export function spdxToCdxBom(spdx: SPDX23): CdxBom {
const bom: CdxBom = {
$schema: 'http://cyclonedx.org/schema/bom-1.5.schema.json',
bomFormat: 'CycloneDX',
specVersion: '1.5',
serialNumber: `urn:uuid:${crypto.randomUUID()}`,
version: 1,
metadata: {
timestamp: spdx.creationInfo.created,
tools: spdx.creationInfo.creators
.filter((c) => c.startsWith('Tool: '))
.map((c) => {
const toolString = c.substring(6);
const versionMatch = toolString.match(TOOL_NAME_REGEX);
return versionMatch
? { name: versionMatch[1] || '', version: versionMatch[2] || '' }
: { name: toolString || '', version: '' };
}),
},
components: [],
dependencies: [],
};
const idx = new Map<string, Component>();
let rootComponent: Component | null = null;
for (const p of spdx.packages ?? []) {
const purl =
p.externalRefs?.find((ref) => ref.referenceType === 'purl')
?.referenceLocator ?? '';
const component: Component = {
'bom-ref': `${p.name}@${p.versionInfo || ''}`,
type: Enums.ComponentType.Library,
name: p.name,
version: p.versionInfo || '',
description: p.description || '',
purl,
};
if (spdx.documentDescribes?.includes(p.SPDXID)) {
rootComponent = component;
} else {
bom.components!.push(component);
}
if (p.checksums) {
component.hashes = p.checksums
.map((checksum) => {
const alg = algorithmMap[checksum.algorithm];
if (!alg) return undefined;
return { alg, content: checksum.checksumValue };
})
.filter((h): h is Hash => h !== undefined);
}
if (p.licenseDeclared && p.licenseDeclared !== 'NOASSERTION') {
const license: License = LICENSE_EXPRESSION_REGEX.test(p.licenseDeclared)
? {
expression: p.licenseDeclared,
acknowledgement: Enums.LicenseAcknowledgement.Declared,
}
: {
license: {
id: p.licenseDeclared,
acknowledgement: Enums.LicenseAcknowledgement.Declared,
},
};
component.licenses = [license];
}
const externalReferences: ExternalReference[] = [];
if (p.homepage && p.homepage !== 'NOASSERTION') {
externalReferences.push({
type: Enums.ExternalReferenceType.Website,
url: p.homepage,
});
}
if (p.downloadLocation && p.downloadLocation !== 'NOASSERTION') {
externalReferences.push({
type: Enums.ExternalReferenceType.Distribution,
url: p.downloadLocation,
});
}
if (externalReferences.length > 0) {
component.externalReferences = externalReferences;
}
idx.set(p.SPDXID, component);
}
const metadataName = resolveMetadataComponentName(
spdx.name,
rootComponent?.name ?? null,
);
if (rootComponent && metadataName) {
rootComponent.name = metadataName;
}
if (rootComponent || metadataName) {
bom.metadata!.component =
rootComponent ||
({
'bom-ref': metadataName,
type: Enums.ComponentType.Application,
name: metadataName,
version: '',
description: '',
} as Component);
}
const deps = new Map<string, Dependency>();
for (const component of idx.values()) {
const dependency: Dependency = {
ref: component['bom-ref'] as string,
dependsOn: [],
};
deps.set(component['bom-ref'] as string, dependency);
bom.dependencies!.push(dependency);
}
for (const r of spdx.relationships ?? []) {
const from = idx.get(r.spdxElementId);
const to = idx.get(r.relatedSpdxElement);
if (!from || !to) continue;
const fromBomRef = from['bom-ref'] as string;
const toBomRef = to['bom-ref'] as string;
const scope = mapScope(r.relationshipType);
upgrade(to, scope);
if (r.relationshipType.includes('DEPENDENCY_OF')) {
const dependentRef = toBomRef;
const dependencyRef = fromBomRef;
// Optional dependencies aren't included in CycloneDx relationships.
// This was validated and tested with the reference BOMs.
if (scope === Enums.ComponentScope.Optional) {
continue;
}
const d = deps.get(dependentRef);
if (d && !d.dependsOn!.includes(dependencyRef)) {
d.dependsOn!.push(dependencyRef);
}
}
}
return bom;
}