-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathhandle-patch-status.mts
More file actions
284 lines (244 loc) · 7.38 KB
/
handle-patch-status.mts
File metadata and controls
284 lines (244 loc) · 7.38 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
import crypto from 'node:crypto'
import { existsSync, 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,
NODE_MODULES,
} from '@socketsecurity/lib/paths/dirnames'
import { MANIFEST_JSON } from '@socketsecurity/lib/paths/filenames'
import { normalizePath } from '@socketsecurity/lib/paths/normalize'
import { pluralize } from '@socketsecurity/lib/words'
import { PatchManifestSchema } from './manifest-schema.mts'
import { outputPatchStatusResult } from './output-patch-status-result.mts'
import { getErrorCause } from '../../utils/error/errors.mjs'
import { findUp } from '../../utils/fs/find-up.mjs'
import { hasBackupForPatch } from '../../utils/manifest/patch-backup.mts'
import type { PatchRecord } from './manifest-schema.mts'
import type { OutputKind } from '../../types.mts'
import type { Spinner } from '@socketsecurity/lib/spinner'
const logger = getDefaultLogger()
export interface PatchStatus {
appliedAt: string | undefined
appliedLocations: string[]
backupAvailable: boolean
description: string | undefined
downloadedAt: string | undefined
fileCount: number
purl: string
status: 'downloaded' | 'applied' | 'failed' | 'unknown'
uuid: string | undefined
vulnerabilityCount: number
}
export interface HandlePatchStatusConfig {
cwd: string
filters: {
applied: boolean
downloaded: boolean
failed: boolean
}
outputKind: OutputKind
spinner: Spinner | null
}
/**
* Compute SHA256 hash of file contents.
*/
async function computeSHA256(filepath: string): Promise<string | null> {
try {
const content = await fs.readFile(filepath)
const hash = crypto.createHash('sha256')
hash.update(content)
return hash.digest('hex')
} catch (_e) {
return null
}
}
/**
* Find all locations where a package exists in node_modules.
*/
async function findPackageLocations(
cwd: string,
packageName: string,
): Promise<string[]> {
const locations: string[] = []
const rootNmPath = await findUp(NODE_MODULES, { cwd, onlyDirectories: true })
if (!rootNmPath) {
return locations
}
// Check root node_modules.
const rootPkgPath = normalizePath(path.join(rootNmPath, packageName))
if (existsSync(rootPkgPath)) {
locations.push(rootPkgPath)
}
// Note: Currently only checks root-level node_modules.
// Nested node_modules scanning could be added if needed for complex dependency trees.
return locations
}
/**
* Verify if a patch is actually applied by checking file hashes.
*/
async function verifyPatchApplied(
pkgPath: string,
patch: PatchRecord,
): Promise<boolean> {
let allMatch = true
for (const { 0: fileName, 1: fileInfo } of Object.entries(patch.files)) {
const filePath = normalizePath(path.join(pkgPath, fileName))
if (!existsSync(filePath)) {
return false
}
// eslint-disable-next-line no-await-in-loop
const currentHash = await computeSHA256(filePath)
if (currentHash !== fileInfo.afterHash) {
allMatch = false
break
}
}
return allMatch
}
/**
* Determine the actual status of a patch by checking the filesystem.
*/
async function determinePatchStatus(
cwd: string,
purl: string,
patch: PatchRecord,
): Promise<{
appliedLocations: string[]
backupAvailable: boolean
status: 'downloaded' | 'applied' | 'failed' | 'unknown'
}> {
// Extract package name from PURL.
// Format: pkg:npm/package-name@version.
const match = purl.match(/pkg:npm\/([^@]+)/)
if (!match) {
return {
appliedLocations: [],
backupAvailable: false,
status: 'unknown',
}
}
const packageName = match[1]!
const locations = await findPackageLocations(cwd, packageName)
if (locations.length === 0) {
// Package not found in node_modules.
return {
appliedLocations: [],
backupAvailable: patch.uuid ? await hasBackupForPatch(patch.uuid) : false,
status: patch.status || 'downloaded',
}
}
// Check if patch is applied in any location.
const appliedLocations: string[] = []
for (const location of locations) {
// eslint-disable-next-line no-await-in-loop
const isApplied = await verifyPatchApplied(location, patch)
if (isApplied) {
appliedLocations.push(location)
}
}
let backupAvailable = false
if (patch.uuid) {
backupAvailable = await hasBackupForPatch(patch.uuid)
}
if (appliedLocations.length > 0) {
return {
appliedLocations,
backupAvailable,
status: 'applied',
}
}
// Package exists but patch not applied.
return {
appliedLocations: [],
backupAvailable,
status: patch.status || 'downloaded',
}
}
export async function handlePatchStatus({
cwd,
filters,
outputKind,
spinner,
}: HandlePatchStatusConfig): 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)
spinner?.start('Checking patch status')
const statuses: PatchStatus[] = []
for (const { 0: purl, 1: patch } of Object.entries(validated.patches)) {
const { appliedLocations, backupAvailable, status } =
// eslint-disable-next-line no-await-in-loop
await determinePatchStatus(cwd, purl, patch)
const fileCount = Object.keys(patch.files).length
const vulnerabilityCount = Object.keys(patch.vulnerabilities || {}).length
statuses.push({
appliedAt: patch.appliedAt,
appliedLocations,
backupAvailable,
description: patch.description,
downloadedAt: patch.downloadedAt,
fileCount,
purl,
status,
uuid: patch.uuid,
vulnerabilityCount,
})
}
spinner?.stop()
// Apply filters.
let filteredStatuses = statuses
if (filters.applied) {
filteredStatuses = filteredStatuses.filter(s => s.status === 'applied')
} else if (filters.downloaded) {
filteredStatuses = filteredStatuses.filter(s => s.status === 'downloaded')
} else if (filters.failed) {
filteredStatuses = filteredStatuses.filter(s => s.status === 'failed')
}
if (outputKind === 'text') {
if (statuses.length === 0) {
logger.log('No patches found in manifest')
} else if (filteredStatuses.length === 0) {
logger.log('No patches match the filter criteria')
} else {
logger.log(
`Found ${filteredStatuses.length} ${pluralize('patch', { count: filteredStatuses.length })}`,
)
}
}
await outputPatchStatusResult(
{
ok: true,
data: { statuses: filteredStatuses },
},
outputKind,
)
} catch (e) {
spinner?.stop()
let message = 'Failed to get patch status'
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 outputPatchStatusResult(
{
ok: false,
code: 1,
message,
cause,
},
outputKind,
)
}
}