-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharborist.ts
More file actions
328 lines (310 loc) · 10.1 KB
/
Copy patharborist.ts
File metadata and controls
328 lines (310 loc) · 10.1 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
/**
* @file Safe Arborist wrapper for dlx installs and lockfile-only resolution.
* Every Arborist invocation in this module is configured with a fixed set of
* security-hardening options mirroring socket-cli v1.1.79 SafeArborist:
*
* - audit: false — no network call to the npm audit endpoint
* - fund: false — no collection/display of funding URLs
* - ignoreScripts: true — no preinstall/install/postinstall scripts
* - progress: false — no progress bar on stdout
* - saveBundle: false — never update bundledDependencies
* - silent: true — suppress Arborist's default log output `save` varies by
* operation: {@link safeIdealTree} uses `save: true` so Arborist writes
* `package-lock.json`; {@link safeReify} uses `save: false` so the caller's
* `package.json` is never rewritten. A `.npmrc` with the equivalent
* settings is also written into the install directory as a
* belt-and-suspenders defense for any downstream tool that reads it.
*/
import Arborist from '../external/@npmcli/arborist'
import { getSocketCacacheDir } from '../paths/socket'
import { ArrayPrototypePush } from '../primordials/array'
import { ErrorCtor } from '../primordials/error'
import { JSONParse } from '../primordials/json'
import { ObjectKeys } from '../primordials/object'
import { getNodeFs } from '../node/fs'
import { getNodePath } from '../node/path'
/**
* Shared options for the safe-arborist operations below.
*/
export interface SafeArboristOptions {
/**
* Install directory. Arborist reads `package.json` (and, for reify,
* `package-lock.json`) from this directory and creates `node_modules` here
* when installing.
*
* Must already exist before calling. The caller is responsible for its
* lifecycle (including cleanup of tmp directories).
*/
path: string
/**
* Refuse to resolve any version published after this date. Passed to Arborist
* (and pacote) as the `before` option. Matches npm's `min-release-age`
* semantics once a caller converts days → Date.
*/
before?: Date | undefined
/**
* Suppress Arborist's default log output.
*
* @default true
*/
quiet?: boolean | undefined
}
/**
* Result of {@link safeIdealTree}.
*/
export interface SafeIdealTreeResult {
/**
* SRI integrity of the top-level resolved package as advertised by the
* registry (sourced from Arborist's idealTree, not from a tarball).
*/
integrity: string
/**
* Resolved package name.
*/
name: string
/**
* Resolved package version.
*/
version: string
/**
* `package-lock.json` JSON content written by Arborist.
*/
lockfile: string
}
/**
* Options for {@link safeReify}.
*/
export interface SafeReifyOptions extends SafeArboristOptions {
/**
* When true, Arborist reifies against the existing `package-lock.json` in
* `path` without rewriting it. When false, Arborist may update the lockfile
* to match resolved dependencies.
*
* Pin-mode callers set this to true so committed lockfiles are the
* authoritative resolution.
*
* @default true
*/
packageLock?: boolean | undefined
}
/**
* Fixed Arborist options that must not be overridden by callers. Mirrors
* socket-cli v1.1.79's SafeArborist overrides: audit: false, fund: false,
* ignoreScripts: true, save: false, saveBundle: false, silent: true, progress:
* false.
*/
export function getBaseArboristOptions(
installPath: string,
options: { quiet: boolean },
) {
options = { __proto__: null, ...options } as typeof options
return {
__proto__: null,
path: installPath,
cache: getSocketCacacheDir(),
audit: false,
fund: false,
ignoreScripts: true,
progress: false,
save: false,
saveBundle: false,
silent: options.quiet,
} as unknown as ConstructorParameters<typeof Arborist>[0]
}
/**
* Read the single declared dependency from a package.json. We only support one
* top-level dep per snapshot, which keeps the result unambiguous (no "which of
* N deps did we pin?").
*/
export function readSingleDependency(packageJsonPath: string): string {
const fs = getNodeFs()
const raw = fs.readFileSync(packageJsonPath, 'utf8')
const pkg = JSONParse(raw) as {
dependencies?: Record<string, string> | undefined
}
const deps = pkg.dependencies ?? {}
const names = ObjectKeys(deps)
if (names.length !== 1) {
throw new ErrorCtor(
`safeIdealTree expects exactly one top-level dependency in ${packageJsonPath}, found ${names.length}`,
)
}
return names[0]!
}
/**
* Read the top-level package from an Arborist idealTree's inventory. Arborist's
* `Inventory` extends `Map`, so iteration yields `[key, node]` pairs — use
* `.values()` to get nodes directly.
*/
export function readTopLevelFromIdealTree(
tree: unknown,
targetName: string,
): {
name: string
version: string
integrity: string
} {
type Node = {
name?: string | undefined
version?: string | undefined
integrity?: string | undefined
depth?: number | undefined
isProjectRoot?: boolean | undefined
}
const root = tree as {
inventory?:
| (Map<string, Node> & { values(): IterableIterator<Node> })
| undefined
} | null
const inventory = root?.inventory
if (!inventory || typeof inventory.values !== 'function') {
throw new ErrorCtor('Arborist idealTree missing inventory')
}
for (const node of inventory.values()) {
if (node.isProjectRoot) {
continue
}
if (node.name === targetName && node.depth === 1) {
if (!node.version || !node.integrity) {
throw new ErrorCtor(
`Arborist idealTree node for ${targetName} missing version/integrity`,
)
}
return {
name: node.name,
version: node.version,
integrity: node.integrity,
}
}
}
throw new ErrorCtor(
`Arborist idealTree inventory has no top-level node for ${targetName}`,
)
}
/**
* Run Arborist in `packageLockOnly` mode against a directory that already
* contains a `package.json` with a single dependency. Resolves the graph
* against the registry and writes `package-lock.json` into `path`, but does NOT
* install into `node_modules`.
*
* Used by snapshot/bootstrap flows to obtain a lockfile + top-level integrity
* without paying for a full install.
*
* Uses `save: true` (rather than our usual `save: false`) so Arborist actually
* writes the lockfile — without that flag, `reify()` in `packageLockOnly` mode
* with no `add` list skips the write.
*/
export async function safeIdealTree(
options: SafeArboristOptions,
): Promise<SafeIdealTreeResult> {
const fs = getNodeFs()
const path = getNodePath()
const {
before,
path: installPath,
quiet = true,
} = { __proto__: null, ...options } as typeof options
const targetName = readSingleDependency(
path.join(installPath, 'package.json'),
)
const arb = new Arborist({
...(getBaseArboristOptions(installPath, { quiet }) as object),
...(before !== undefined ? { before } : {}),
packageLockOnly: true,
save: true,
} as unknown as ConstructorParameters<typeof Arborist>[0])
/* c8 ignore next - External Arborist call */
const tree = await arb.buildIdealTree()
/* c8 ignore next - External Arborist call */
await arb.reify()
const top = readTopLevelFromIdealTree(tree, targetName)
const lockfile = await fs.promises.readFile(
path.join(installPath, 'package-lock.json'),
'utf8',
)
return { ...top, lockfile }
}
/**
* Install into `node_modules` using Arborist's reify operation. Honors the
* committed `package-lock.json` in `path` when `packageLock: true`.
*
* Does not fetch registry metadata for versions already pinned by the lockfile
* — arborist uses the lockfile's `integrity` strings to fetch tarballs by ssri.
* This is the strongest form of pinning pnpm/npm offer.
*/
export async function safeReify(options: SafeReifyOptions): Promise<void> {
const {
packageLock = true,
path: installPath,
quiet = true,
} = { __proto__: null, ...options } as typeof options
const arb = new Arborist({
...(getBaseArboristOptions(installPath, { quiet }) as object),
packageLock,
} as unknown as ConstructorParameters<typeof Arborist>[0])
/* c8 ignore next - External Arborist call */
await arb.reify()
}
/**
* Options for {@link writeSafeNpmrc}. Optional release-age hints are echoed into
* the generated `.npmrc` as defense-in-depth for any downstream tool that
* shells out to npm/pnpm in the directory.
*/
export interface WriteSafeNpmrcOptions {
/**
* Npm `min-release-age` (days). Mutually exclusive with minReleaseMins.
*/
minReleaseDays?: number | undefined
/**
* Pnpm `minimumReleaseAge` (minutes). Mutually exclusive with minReleaseDays.
*/
minReleaseMins?: number | undefined
}
/**
* Write a hardened `.npmrc` into `path`. Used by both preview and pin flows as
* a second layer of protection alongside the Arborist options.
*
* Content written (always): ignore-scripts=true audit=false fund=false
* save=false save-bundle=false progress=false.
*
* When {@link WriteSafeNpmrcOptions.minReleaseDays} is set, also writes:
* min-release-age=<days>
*
* When {@link WriteSafeNpmrcOptions.minReleaseMins} is set, also writes the
* pnpm-style equivalent: minimum-release-age=<minutes>
*/
export async function writeSafeNpmrc(
installPath: string,
options?: WriteSafeNpmrcOptions | undefined,
): Promise<void> {
const fs = getNodeFs()
const path = getNodePath()
const { minReleaseDays, minReleaseMins } = {
__proto__: null,
...options,
} as WriteSafeNpmrcOptions
if (minReleaseDays !== undefined && minReleaseMins !== undefined) {
throw new ErrorCtor(
'writeSafeNpmrc: minReleaseDays and minReleaseMins are mutually exclusive',
)
}
const lines = [
'ignore-scripts=true',
'audit=false',
'fund=false',
'save=false',
'save-bundle=false',
'progress=false',
]
if (minReleaseDays !== undefined) {
ArrayPrototypePush(lines, `min-release-age=${minReleaseDays}`)
}
if (minReleaseMins !== undefined) {
ArrayPrototypePush(lines, `minimum-release-age=${minReleaseMins}`)
}
await fs.promises.writeFile(
path.join(installPath, '.npmrc'),
lines.join('\n') + '\n',
'utf8',
)
}