-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovenance.ts
More file actions
276 lines (247 loc) · 7.73 KB
/
provenance.ts
File metadata and controls
276 lines (247 loc) · 7.73 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
/**
* @fileoverview Package provenance and attestation verification utilities.
*/
import { NPM_REGISTRY_URL } from '../constants/agents'
import { getPacoteCachePath } from '../constants/packages'
import makeFetchHappen from '../external/make-fetch-happen'
import {
createCompositeAbortSignal,
createTimeoutSignal,
} from '../abort/signal'
import { parseUrl } from '../url/parse'
import type { ProvenanceOptions } from './types'
import { ArrayIsArray } from '../primordials/array'
import { BufferFrom } from '../primordials/buffer'
import { JSONParse } from '../primordials/json'
import {
StringPrototypeEndsWith,
StringPrototypeIncludes,
StringPrototypeSplit,
} from '../primordials/string'
const SLSA_PROVENANCE_V0_2 = 'https://slsa.dev/provenance/v0.2'
const SLSA_PROVENANCE_V1_0 = 'https://slsa.dev/provenance/v1'
let _fetcher: ReturnType<typeof makeFetchHappen.defaults> | undefined
/**
* Fetch package provenance information from npm registry.
*
* @example
* ```typescript
* const provenance = await fetchPackageProvenance('lodash', '4.17.21')
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function fetchPackageProvenance(
pkgName: string,
pkgVersion: string,
options?: ProvenanceOptions,
): Promise<unknown> {
const { signal, timeout = 10_000 } = {
__proto__: null,
...options,
} as ProvenanceOptions
if (signal?.aborted) {
return undefined
}
// Create composite signal combining external signal with timeout
const timeoutSignal = createTimeoutSignal(timeout)
const compositeSignal = createCompositeAbortSignal(signal, timeoutSignal)
const fetcher = getFetcher()
try {
const response = await fetcher(
// The npm registry attestations API endpoint.
`${NPM_REGISTRY_URL}/-/npm/v1/attestations/${encodeURIComponent(pkgName)}@${encodeURIComponent(pkgVersion)}`,
{
method: 'GET',
signal: compositeSignal,
headers: {
'User-Agent': 'socket-registry',
},
} as {
method: string
signal: AbortSignal
headers: Record<string, string>
},
)
if (response.ok) {
return getProvenanceDetails(await response.json())
}
} catch {}
return undefined
}
/**
* Find the first attestation with valid provenance data.
*/
export function findProvenance(attestations: unknown[]): unknown {
for (const attestation of attestations) {
const att = attestation as {
bundle?: { dsseEnvelope?: { payload?: string } }
predicate?: unknown
}
try {
let predicate = att.predicate
// If predicate is not directly available, try to decode from DSSE envelope
if (!predicate && att.bundle?.dsseEnvelope?.payload) {
try {
const decodedPayload = BufferFrom!(
att.bundle.dsseEnvelope.payload,
'base64',
).toString('utf8')
const statement = JSONParse(decodedPayload)
predicate = statement.predicate
} catch {
// Failed to decode, continue to next attestation
continue
}
}
const predicateData = predicate as {
buildDefinition?: { externalParameters?: unknown }
}
if (predicateData?.buildDefinition?.externalParameters) {
return {
predicate,
externalParameters: predicateData.buildDefinition.externalParameters,
}
}
// c8 ignore start - Error handling for malformed attestation data should continue processing other attestations.
} catch {
// Continue checking other attestations if one fails to parse
}
// c8 ignore stop
}
return undefined
}
/**
* Extract and filter SLSA provenance attestations from attestation data.
*/
export function getAttestations(attestationData: unknown): unknown[] {
const data = attestationData as { attestations?: unknown[] }
if (!data.attestations || !ArrayIsArray(data.attestations)) {
return []
}
return data.attestations.filter((attestation: unknown) => {
const att = attestation as { predicateType?: string }
return (
att.predicateType === SLSA_PROVENANCE_V0_2 ||
att.predicateType === SLSA_PROVENANCE_V1_0
)
})
}
/*@__NO_SIDE_EFFECTS__*/
export function getFetcher() {
if (_fetcher === undefined) {
// module is imported at the top
_fetcher = makeFetchHappen.defaults({
cachePath: getPacoteCachePath(),
// Prefer-offline: Staleness checks for cached data will be bypassed, but
// missing data will be requested from the server.
// https://github.com/npm/make-fetch-happen?tab=readme-ov-file#--optscache
cache: 'force-cache',
})
}
return _fetcher
}
/**
* Convert raw attestation data to user-friendly provenance details.
*
* @example
* ```typescript
* const details = getProvenanceDetails(attestationData)
* // { level: 'trusted', repository: '...', commitSha: '...' }
* ```
*/
export function getProvenanceDetails(attestationData: unknown): unknown {
const attestations = getAttestations(attestationData)
if (!attestations.length) {
return undefined
}
// Find the first attestation with valid provenance data.
const provenance = findProvenance(attestations)
if (!provenance) {
return { level: 'attested' }
}
const provenanceData = provenance as {
externalParameters?: {
context?: string
ref?: string
repository?: string
run_id?: string
sha?: string
workflow?: {
ref?: string
repository?: string
}
workflow_ref?: string
}
predicate?: {
buildDefinition?: { buildType?: string }
}
}
const { externalParameters, predicate } = provenanceData
const def = predicate?.buildDefinition
// Handle both SLSA v0.2 (direct properties) and v1 (nested workflow object)
const workflow = externalParameters?.workflow
const workflowRef = workflow?.ref || externalParameters?.workflow_ref
const workflowUrl = externalParameters?.context
const workflowPlatform = def?.buildType
const repository = workflow?.repository || externalParameters?.repository
const gitRef = externalParameters?.ref || workflow?.ref
const commitSha = externalParameters?.sha
const workflowRunId = externalParameters?.run_id
// Check for trusted publishers (GitHub Actions, GitLab CI/CD).
const trusted =
isTrustedPublisher(workflowRef) ||
isTrustedPublisher(workflowUrl) ||
isTrustedPublisher(workflowPlatform) ||
isTrustedPublisher(repository)
return {
commitSha,
gitRef,
level: trusted ? 'trusted' : 'attested',
repository,
workflowRef,
workflowUrl,
workflowPlatform,
workflowRunId,
}
}
/**
* Check if a value indicates a trusted publisher (GitHub or GitLab).
*/
export function isTrustedPublisher(value: unknown): boolean {
if (typeof value !== 'string' || !value) {
return false
}
let url = parseUrl(value)
let hostname = url?.hostname
// Handle GitHub workflow refs with @ syntax by trying the first part.
// Example: "https://github.com/owner/repo/.github/workflows/ci.yml@refs/heads/main"
if (!url && StringPrototypeIncludes(value, '@')) {
const firstPart = StringPrototypeSplit(value, '@')[0]
if (firstPart) {
url = parseUrl(firstPart)
}
if (url) {
hostname = url.hostname
}
}
// Try common URL prefixes if not already a complete URL.
if (!url) {
const httpsUrl = parseUrl(`https://${value}`)
if (httpsUrl) {
hostname = httpsUrl.hostname
}
}
if (hostname) {
return (
hostname === 'github.com' ||
StringPrototypeEndsWith(hostname, '.github.com') ||
hostname === 'gitlab.com' ||
StringPrototypeEndsWith(hostname, '.gitlab.com')
)
}
// Fallback: check for provider keywords in non-URL strings.
return (
StringPrototypeIncludes(value, 'github') ||
StringPrototypeIncludes(value, 'gitlab')
)
}