-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathhandle-patch-list.mts
More file actions
218 lines (188 loc) · 5.77 KB
/
handle-patch-list.mts
File metadata and controls
218 lines (188 loc) · 5.77 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
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { UTF8 } from '@socketsecurity/lib/constants/encoding'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { DOT_SOCKET_DIR } from '@socketsecurity/lib/paths/dirnames'
import { MANIFEST_JSON } from '@socketsecurity/lib/paths/filenames'
import { normalizePath } from '@socketsecurity/lib/paths/normalize'
import { select } from '@socketsecurity/lib/stdio/prompts'
import { pluralize } from '@socketsecurity/lib/words'
import { handlePatchApply } from './handle-patch-apply.mts'
import { PatchManifestSchema } from './manifest-schema.mts'
import { outputPatchListResult } from './output-patch-list-result.mts'
import { getErrorCause } from '../../utils/error/errors.mjs'
import { getPurlObject } from '../../utils/purl/parse.mjs'
import type { OutputKind } from '../../types.mts'
import type { Spinner } from '@socketsecurity/lib/spinner'
const logger = getDefaultLogger()
export interface PatchListEntry {
appliedAt: string | undefined
description: string | undefined
exportedAt: string
fileCount: number
license: string | undefined
purl: string
status: 'downloaded' | 'applied' | 'failed' | undefined
tier: string | undefined
uuid: string | undefined
vulnerabilityCount: number
}
export interface HandlePatchListConfig {
cwd: string
interactive: boolean
outputKind: OutputKind
spinner: Spinner | null
}
export async function handlePatchList({
cwd,
interactive,
outputKind,
spinner,
}: HandlePatchListConfig): Promise<void> {
try {
spinner?.start('Reading patch manifest')
const dotSocketDirPath = normalizePath(path.join(cwd, DOT_SOCKET_DIR))
const manifestPath = normalizePath(
path.join(dotSocketDirPath, MANIFEST_JSON),
)
const manifestContent = await fs.readFile(manifestPath, UTF8)
const manifestData = JSON.parse(manifestContent)
const validated = PatchManifestSchema.parse(manifestData)
const patches: PatchListEntry[] = []
for (const { 0: purl, 1: patch } of Object.entries(validated.patches)) {
const fileCount = Object.keys(patch.files).length
const vulnerabilityCount = Object.keys(patch.vulnerabilities || {}).length
patches.push({
appliedAt: patch.appliedAt,
description: patch.description,
exportedAt: patch.exportedAt,
fileCount,
license: patch.license,
purl,
status: patch.status,
tier: patch.tier,
uuid: patch.uuid,
vulnerabilityCount,
})
}
spinner?.stop()
if (patches.length === 0) {
if (outputKind === 'text') {
logger.log('No patches found in manifest')
}
return
}
if (outputKind === 'text') {
logger.log(
`Found ${patches.length} ${pluralize('patch', { count: patches.length })} in manifest`,
)
}
// Interactive mode: Let user select patches to apply.
if (interactive) {
if (patches.length === 0) {
logger.log('No patches available to select')
return
}
// Show list first.
await outputPatchListResult(
{
ok: true,
data: { patches },
},
outputKind,
)
logger.log('')
logger.log('Select patches to apply (use arrow keys and Enter):')
logger.log('')
// Create choices for selection.
const choices = [
{
name: '✓ Apply All Patches',
value: '__ALL__',
},
...patches.map(patch => {
const statusIndicator =
patch.status === 'applied'
? '[✓]'
: patch.status === 'failed'
? '[✗]'
: '[○]'
const vulnText =
patch.vulnerabilityCount > 0
? ` - ${patch.vulnerabilityCount} ${pluralize('vuln', { count: patch.vulnerabilityCount })}`
: ''
return {
name: `${statusIndicator} ${patch.purl}${vulnText}`,
value: patch.purl,
description: patch.description || 'No description',
}
}),
{
name: '✗ Cancel',
value: '__CANCEL__',
},
]
const selectedValue = await select({
message: 'Select a patch to apply:',
choices,
})
if (selectedValue === '__CANCEL__') {
logger.log('Cancelled')
return
}
// Determine which patches to apply.
const purlsToApply: string[] = []
if (selectedValue === '__ALL__') {
purlsToApply.push(...patches.map(p => p.purl))
} else {
purlsToApply.push(selectedValue)
}
logger.log('')
logger.log(
`Applying ${purlsToApply.length} ${pluralize('patch', { count: purlsToApply.length })}...`,
)
logger.log('')
// Convert PURLs to PackageURL objects.
const purlObjs = purlsToApply
.map(purl => getPurlObject(purl, { throws: false }))
.filter((p): p is NonNullable<typeof p> => p !== null)
// Apply the selected patches.
await handlePatchApply({
cwd,
dryRun: false,
outputKind,
purlObjs,
spinner,
})
return
}
// Non-interactive mode: Just show the list.
await outputPatchListResult(
{
ok: true,
data: { patches },
},
outputKind,
)
} catch (e) {
spinner?.stop()
let message = 'Failed to list patches'
let cause = getErrorCause(e)
if (e instanceof SyntaxError) {
message = `Invalid JSON in ${MANIFEST_JSON}`
cause = e.message
} else if (e instanceof Error && 'issues' in e) {
message = 'Schema validation failed'
cause = String(e)
}
await outputPatchListResult(
{
ok: false,
code: 1,
message,
cause,
},
outputKind,
)
}
}