-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcli.js
More file actions
427 lines (405 loc) · 11.8 KB
/
Copy pathcli.js
File metadata and controls
427 lines (405 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#!/usr/bin/env node
import fs from 'node:fs'
import * as path from "path";
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
import { getProjectLicense, getLicenseDetails } from './license/index.js'
import client, { selectTrustifyDABackend, generateSbom } from './index.js'
// command for component analysis take manifest type and content
const component = {
command: 'component </path/to/manifest>',
desc: 'produce component report for manifest path',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for analyzing',
type: 'string',
normalize: true,
}
).options({
workspaceDir: {
alias: 'w',
desc: 'Workspace root directory (for monorepos; lock file is expected here)',
type: 'string',
normalize: true,
}
}),
handler: async args => {
let manifestName = args['/path/to/manifest']
const opts = args.workspaceDir ? { TRUSTIFY_DA_WORKSPACE_DIR: args.workspaceDir } : {}
let res = await client.componentAnalysis(manifestName, opts)
console.log(JSON.stringify(res, null, 2))
}
}
const validateToken = {
command: 'validate-token <token-provider> [--token-value thevalue]',
desc: 'Validates input token if authentic and authorized',
builder: yargs => yargs.positional(
'token-provider',
{
desc: 'the token provider name',
type: 'string'
}
).options({
tokenValue: {
alias: 'value',
desc: 'the actual token value to be checked',
type: 'string',
}
}),
handler: async args => {
let tokenProvider = args['token-provider'].toUpperCase()
let opts={}
if(args['tokenValue'] !== undefined && args['tokenValue'].trim() !=="" ) {
let tokenValue = args['tokenValue'].trim()
opts[`TRUSTIFY_DA_PROVIDER_${tokenProvider}_TOKEN`] = tokenValue
}
let res = await client.validateToken(opts)
console.log(res)
}
}
// command for image analysis takes OCI image references
const image = {
command: 'image <image-refs..>',
desc: 'produce image analysis report for OCI image references',
builder: yargs => yargs.positional(
'image-refs',
{
desc: 'OCI image references to analyze (one or more)',
type: 'string',
array: true,
}
).options({
html: {
alias: 'r',
desc: 'Get the report as HTML instead of JSON',
type: 'boolean',
conflicts: 'summary'
},
summary: {
alias: 's',
desc: 'For JSON report, get only the \'summary\'',
type: 'boolean',
conflicts: 'html'
}
}),
handler: async args => {
let imageRefs = args['image-refs']
if (!Array.isArray(imageRefs)) {
imageRefs = [imageRefs]
}
let html = args['html']
let summary = args['summary']
let res = await client.imageAnalysis(imageRefs, html)
if(summary && !html) {
let summaries = {}
for (let [imageRef, report] of Object.entries(res)) {
for (let provider in report.providers) {
if (report.providers[provider].sources !== undefined) {
for (let source in report.providers[provider].sources) {
if (report.providers[provider].sources[source].summary) {
if (!summaries[imageRef]) {
summaries[imageRef] = {};
}
if (!summaries[imageRef][provider]) {
summaries[imageRef][provider] = {};
}
summaries[imageRef][provider][source] = report.providers[provider].sources[source].summary
}
}
}
}
}
res = summaries
}
console.log(html ? res : JSON.stringify(res, null, 2))
}
}
// command for stack analysis takes a manifest path
const stack = {
command: 'stack </path/to/manifest> [--html|--summary]',
desc: 'produce stack report for manifest path',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for analyzing',
type: 'string',
normalize: true,
}
).options({
html: {
alias: 'r',
desc: 'Get the report as HTML instead of JSON',
type: 'boolean',
conflicts: 'summary'
},
summary: {
alias: 's',
desc: 'For JSON report, get only the \'summary\'',
type: 'boolean',
conflicts: 'html'
},
workspaceDir: {
alias: 'w',
desc: 'Workspace root directory (for monorepos; lock file is expected here)',
type: 'string',
normalize: true,
}
}),
handler: async args => {
let manifest = args['/path/to/manifest']
let html = args['html']
let summary = args['summary']
const opts = args.workspaceDir ? { TRUSTIFY_DA_WORKSPACE_DIR: args.workspaceDir } : {}
let theProvidersSummary = new Map();
let theProvidersObject ={}
let res = await client.stackAnalysis(manifest, html, opts)
if(summary)
{
for (let provider in res.providers ) {
if (res.providers[provider].sources !== undefined) {
for(let source in res.providers[provider].sources ) {
if(res.providers[provider].sources[source].summary) {
theProvidersSummary.set(source,res.providers[provider].sources[source].summary)
}
}
}
}
for (let [provider, providerSummary] of theProvidersSummary) {
theProvidersObject[provider]=providerSummary
}
}
console.log(html ? res : JSON.stringify(
!html && summary ? theProvidersObject : res,
null,
2
))
}
}
// command for batch stack analysis (workspace)
const stackBatch = {
command: 'stack-batch </path/to/workspace-root> [--html|--summary] [--concurrency <n>] [--ignore <pattern>...] [--metadata] [--fail-fast]',
desc: 'produce stack report for all packages/crates in a workspace (Cargo or JS/TS)',
builder: yargs => yargs.positional(
'/path/to/workspace-root',
{
desc: 'workspace root directory (containing Cargo.toml+Cargo.lock or package.json+lock file)',
type: 'string',
normalize: true,
}
).options({
html: {
alias: 'r',
desc: 'Get the report as HTML instead of JSON',
type: 'boolean',
conflicts: 'summary'
},
summary: {
alias: 's',
desc: 'For JSON report, get only the \'summary\' per package',
type: 'boolean',
conflicts: 'html'
},
concurrency: {
alias: 'c',
desc: 'Max parallel SBOM generations (default: 10, env: TRUSTIFY_DA_BATCH_CONCURRENCY)',
type: 'number',
},
ignore: {
alias: 'i',
desc: 'Extra glob patterns excluded from workspace discovery (merged with defaults). Repeat flag per pattern. Env: TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE (comma-separated)',
type: 'string',
array: true,
},
metadata: {
alias: 'm',
desc: 'Return { analysis, metadata } with per-manifest errors (env: TRUSTIFY_DA_BATCH_METADATA=true)',
type: 'boolean',
default: false,
},
failFast: {
desc: 'Stop on first invalid package.json or SBOM error (env: TRUSTIFY_DA_CONTINUE_ON_ERROR=false)',
type: 'boolean',
default: false,
}
}),
handler: async args => {
const workspaceRoot = args['/path/to/workspace-root']
const html = args['html']
const summary = args['summary']
const opts = {}
if (args.concurrency != null) {
opts.batchConcurrency = args.concurrency
}
const extraIgnores = Array.isArray(args.ignore) ? args.ignore.filter(p => p != null && String(p).trim()) : []
if (extraIgnores.length > 0) {
opts.workspaceDiscoveryIgnore = extraIgnores
}
if (args.metadata) {
opts.batchMetadata = true
}
if (args.failFast) {
opts.continueOnError = false
}
let res = await client.stackAnalysisBatch(workspaceRoot, html, opts)
const batchAnalysis =
res && typeof res === 'object' && res != null && 'analysis' in res ? res.analysis : res
if (summary && !html && typeof batchAnalysis === 'object') {
const summaries = {}
for (const [purl, report] of Object.entries(batchAnalysis)) {
if (report?.providers) {
for (const provider of Object.keys(report.providers)) {
const sources = report.providers[provider]?.sources
if (sources) {
for (const [source, data] of Object.entries(sources)) {
if (data?.summary) {
if (!summaries[purl]) {
summaries[purl] = {}
}
if (!summaries[purl][provider]) {
summaries[purl][provider] = {}
}
summaries[purl][provider][source] = data.summary
}
}
}
}
}
}
if (res && typeof res === 'object' && res != null && 'metadata' in res) {
res = { analysis: summaries, metadata: res.metadata }
} else {
res = summaries
}
}
if (html) {
const htmlContent = res && typeof res === 'object' && 'analysis' in res ? res.analysis : res
console.log(htmlContent)
} else {
console.log(JSON.stringify(res, null, 2))
}
}
}
// command for license checking
const license = {
command: 'license </path/to/manifest>',
desc: 'Display project license information from manifest and LICENSE file in JSON format',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for license analysis',
type: 'string',
normalize: true,
}
),
handler: async args => {
let manifestPath = args['/path/to/manifest']
const opts = {} // CLI options can be extended in the future
try {
selectTrustifyDABackend(opts)
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2))
process.exit(1)
}
let localResult
try {
localResult = getProjectLicense(manifestPath)
} catch (err) {
console.error(JSON.stringify({ error: `Failed to read manifest: ${err.message}` }, null, 2))
process.exit(1)
}
const errors = []
// Build LicenseInfo objects
const buildLicenseInfo = async (spdxId) => {
if (!spdxId) {return null}
const licenseInfo = { spdxId }
try {
const details = await getLicenseDetails(spdxId, opts)
if (details) {
// Check if backend recognized the license as valid
if (details.category === 'UNKNOWN') {
errors.push(`"${spdxId}" is not a valid SPDX license identifier. Please use a valid SPDX expression (e.g., "Apache-2.0", "MIT"). See https://spdx.org/licenses/`)
} else {
Object.assign(licenseInfo, details)
}
} else {
errors.push(`No license details found for ${spdxId}`)
}
} catch (err) {
errors.push(`Failed to fetch details for ${spdxId}: ${err.message}`)
}
return licenseInfo
}
const output = {
manifestLicense: await buildLicenseInfo(localResult.fromManifest),
fileLicense: await buildLicenseInfo(localResult.fromFile),
mismatch: localResult.mismatch
}
if (errors.length > 0) {
output.errors = errors
}
console.log(JSON.stringify(output, null, 2))
}
}
const sbom = {
command: 'sbom </path/to/manifest> [--output]',
desc: 'generate a CycloneDX SBOM from a manifest file',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for SBOM generation',
type: 'string',
normalize: true,
}
).options({
output: {
alias: 'o',
desc: 'Write SBOM JSON to a file instead of stdout',
type: 'string',
normalize: true,
},
workspaceDir: {
alias: 'w',
desc: 'Workspace root directory (for monorepos; lock file is expected here)',
type: 'string',
normalize: true,
}
}),
handler: async args => {
let manifest = args['/path/to/manifest']
const opts = args.workspaceDir ? { TRUSTIFY_DA_WORKSPACE_DIR: args.workspaceDir } : {}
let result
try {
result = await generateSbom(manifest, opts)
} catch (err) {
console.error(JSON.stringify({ error: `Failed to generate SBOM: ${err.message}` }, null, 2))
process.exit(1)
}
const json = JSON.stringify(result, null, 2)
if (args.output) {
try {
fs.writeFileSync(args.output, json)
} catch (err) {
console.error(JSON.stringify({ error: `Failed to write output file: ${err.message}` }, null, 2))
process.exit(1)
}
} else {
console.log(json)
}
}
}
// parse and invoke the command
yargs(hideBin(process.argv))
.usage(`Usage: ${process.argv[0].includes("node") ? path.parse(process.argv[1]).base : path.parse(process.argv[0]).base} {component|stack|stack-batch|image|validate-token|license|sbom}`)
.command(stack)
.command(stackBatch)
.command(component)
.command(image)
.command(validateToken)
.command(license)
.command(sbom)
.scriptName('')
.version(false)
.demandCommand(1)
.wrap(null)
.parse()