socket 0.14.40-alpha.9 → 0.14.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1501 +1,3 @@
1
- 'use strict';
1
+ 'use strict'
2
2
 
3
- function _socketInterop(e) {
4
- let c = 0
5
- for (const k in e ?? {}) {
6
- c = c === 0 && k === 'default' ? 1 : 0
7
- if (!c && k !== '__esModule') break
8
- }
9
- return c ? e.default : e
10
- }
11
-
12
- var events = require('node:events');
13
- var fs = require('node:fs');
14
- var https = require('node:https');
15
- var path = require('node:path');
16
- var readline = require('node:readline');
17
- var promises = require('node:timers/promises');
18
- var npa = _socketInterop(require('npm-package-arg'));
19
- var semver = _socketInterop(require('semver'));
20
- var config = require('@socketsecurity/config');
21
- var registry = require('@socketsecurity/registry');
22
- var objects = require('@socketsecurity/registry/lib/objects');
23
- var packages = require('@socketsecurity/registry/lib/packages');
24
- var prompts = require('@socketsecurity/registry/lib/prompts');
25
- var spinner = require('@socketsecurity/registry/lib/spinner');
26
- var constants = require('./constants.js');
27
- var sdk = require('./sdk.js');
28
- var pathResolve = require('./path-resolve.js');
29
-
30
- //#region UX Constants
31
-
32
- const IGNORE_UX = {
33
- block: false,
34
- display: false
35
- };
36
- const WARN_UX = {
37
- block: false,
38
- display: true
39
- };
40
- const ERROR_UX = {
41
- block: true,
42
- display: true
43
- };
44
- //#endregion
45
- //#region utils
46
-
47
- /**
48
- * Iterates over all entries with ordered issue rule for deferral. Iterates over
49
- * all issue rules and finds the first defined value that does not defer otherwise
50
- * uses the defaultValue. Takes the value and converts into a UX workflow.
51
- */
52
- function resolveAlertRuleUX(orderedRulesCollection, defaultValue) {
53
- if (defaultValue === true || defaultValue === null || defaultValue === undefined) {
54
- defaultValue = {
55
- action: 'error'
56
- };
57
- } else if (defaultValue === false) {
58
- defaultValue = {
59
- action: 'ignore'
60
- };
61
- }
62
- let block = false;
63
- let display = false;
64
- let needDefault = true;
65
- iterate_entries: for (const rules of orderedRulesCollection) {
66
- for (const rule of rules) {
67
- if (ruleValueDoesNotDefer(rule)) {
68
- needDefault = false;
69
- const narrowingFilter = uxForDefinedNonDeferValue(rule);
70
- block = block || narrowingFilter.block;
71
- display = display || narrowingFilter.display;
72
- continue iterate_entries;
73
- }
74
- }
75
- const narrowingFilter = uxForDefinedNonDeferValue(defaultValue);
76
- block = block || narrowingFilter.block;
77
- display = display || narrowingFilter.display;
78
- }
79
- if (needDefault) {
80
- const narrowingFilter = uxForDefinedNonDeferValue(defaultValue);
81
- block = block || narrowingFilter.block;
82
- display = display || narrowingFilter.display;
83
- }
84
- return {
85
- block,
86
- display
87
- };
88
- }
89
-
90
- /**
91
- * Negative form because it is narrowing the type.
92
- */
93
- function ruleValueDoesNotDefer(rule) {
94
- if (rule === undefined) {
95
- return false;
96
- }
97
- if (objects.isObject(rule)) {
98
- const {
99
- action
100
- } = rule;
101
- if (action === undefined || action === 'defer') {
102
- return false;
103
- }
104
- }
105
- return true;
106
- }
107
-
108
- /**
109
- * Handles booleans for backwards compatibility.
110
- */
111
- function uxForDefinedNonDeferValue(ruleValue) {
112
- if (typeof ruleValue === 'boolean') {
113
- return ruleValue ? ERROR_UX : IGNORE_UX;
114
- }
115
- const {
116
- action
117
- } = ruleValue;
118
- if (action === 'warn') {
119
- return WARN_UX;
120
- } else if (action === 'ignore') {
121
- return IGNORE_UX;
122
- }
123
- return ERROR_UX;
124
- }
125
- //#endregion
126
-
127
- //#region exports
128
-
129
- function createAlertUXLookup(settings) {
130
- const cachedUX = new Map();
131
- return context => {
132
- const {
133
- type
134
- } = context.alert;
135
- let ux = cachedUX.get(type);
136
- if (ux) {
137
- return ux;
138
- }
139
- const orderedRulesCollection = [];
140
- for (const settingsEntry of settings.entries) {
141
- const orderedRules = [];
142
- let target = settingsEntry.start;
143
- while (target !== null) {
144
- const resolvedTarget = settingsEntry.settings[target];
145
- if (!resolvedTarget) {
146
- break;
147
- }
148
- const issueRuleValue = resolvedTarget.issueRules?.[type];
149
- if (typeof issueRuleValue !== 'undefined') {
150
- orderedRules.push(issueRuleValue);
151
- }
152
- target = resolvedTarget.deferTo ?? null;
153
- }
154
- orderedRulesCollection.push(orderedRules);
155
- }
156
- const defaultValue = settings.defaults.issueRules[type];
157
- let resolvedDefaultValue = {
158
- action: 'error'
159
- };
160
- if (defaultValue === false) {
161
- resolvedDefaultValue = {
162
- action: 'ignore'
163
- };
164
- } else if (defaultValue && defaultValue !== true) {
165
- resolvedDefaultValue = {
166
- action: defaultValue.action ?? 'error'
167
- };
168
- }
169
- ux = resolveAlertRuleUX(orderedRulesCollection, resolvedDefaultValue);
170
- cachedUX.set(type, ux);
171
- return ux;
172
- };
173
- }
174
- //#endregion
175
-
176
- const {
177
- API_V0_URL,
178
- ENV,
179
- LOOP_SENTINEL,
180
- NPM,
181
- NPM_REGISTRY_URL,
182
- SOCKET_CLI_FIX_PACKAGE_LOCK_FILE,
183
- SOCKET_CLI_ISSUES_URL,
184
- SOCKET_CLI_UPDATE_OVERRIDES_IN_PACKAGE_LOCK_FILE,
185
- SOCKET_PUBLIC_API_KEY,
186
- abortSignal,
187
- rootPath
188
- } = constants;
189
- const POTENTIAL_BUG_ERROR_MESSAGE = `This is may be a bug with socket-npm related to changes to the npm CLI.\nPlease report to ${SOCKET_CLI_ISSUES_URL}.`;
190
- const npmEntrypoint = fs.realpathSync(process.argv[1]);
191
- const npmRootPath = pathResolve.findRoot(path.dirname(npmEntrypoint));
192
- function tryRequire(...ids) {
193
- for (const data of ids) {
194
- let id;
195
- let transformer;
196
- if (Array.isArray(data)) {
197
- id = data[0];
198
- transformer = data[1];
199
- } else {
200
- id = data;
201
- transformer = mod => mod;
202
- }
203
- try {
204
- // Check that the transformed value isn't `undefined` because older
205
- // versions of packages like 'proc-log' may not export a `log` method.
206
- const exported = transformer(require(id));
207
- if (exported !== undefined) {
208
- return exported;
209
- }
210
- } catch {}
211
- }
212
- return undefined;
213
- }
214
- if (npmRootPath === undefined) {
215
- console.error(`Unable to find npm CLI install directory.\nSearched parent directories of ${npmEntrypoint}.\n\n${POTENTIAL_BUG_ERROR_MESSAGE}`);
216
- // The exit code 127 indicates that the command or binary being executed
217
- // could not be found.
218
- process.exit(127);
219
- }
220
- const npmNmPath = path.join(npmRootPath, 'node_modules');
221
- const arboristPkgPath = path.join(npmNmPath, '@npmcli/arborist');
222
- const arboristClassPath = path.join(arboristPkgPath, 'lib/arborist/index.js');
223
- const arboristDepValidPath = path.join(arboristPkgPath, 'lib/dep-valid.js');
224
- const arboristEdgeClassPath = path.join(arboristPkgPath, 'lib/edge.js');
225
- const arboristNodeClassPath = path.join(arboristPkgPath, 'lib/node.js');
226
- const arboristOverrideSetClassPatch = path.join(arboristPkgPath, 'lib/override-set.js');
227
- const log = tryRequire([path.join(npmNmPath, 'proc-log/lib/index.js'),
228
- // The proc-log DefinitelyTyped definition is incorrect. The type definition
229
- // is really that of its export log.
230
- mod => mod.log], path.join(npmNmPath, 'npmlog/lib/log.js'));
231
- const pacote = require(path.join(npmNmPath, 'pacote'));
232
- const translations = require(path.join(rootPath, 'translations.json'));
233
- const Arborist = require(arboristClassPath);
234
- const depValid = require(arboristDepValidPath);
235
- const Edge = require(arboristEdgeClassPath);
236
- const Node = require(arboristNodeClassPath);
237
- const OverrideSet = require(arboristOverrideSetClassPatch);
238
- const kCtorArgs = Symbol('ctorArgs');
239
- const kRiskyReify = Symbol('riskyReify');
240
- const formatter = new sdk.ColorOrMarkdown(false);
241
- const pubToken = sdk.getDefaultKey() ?? SOCKET_PUBLIC_API_KEY;
242
- let _uxLookup;
243
- async function uxLookup(settings) {
244
- while (_uxLookup === undefined) {
245
- // eslint-disable-next-line no-await-in-loop
246
- await promises.setTimeout(1, {
247
- signal: abortSignal
248
- });
249
- }
250
- return _uxLookup(settings);
251
- }
252
- function packageAlertsToReport(alerts) {
253
- let report = null;
254
- for (const alert of alerts) {
255
- if (!isAlertFixableCve(alert.raw)) {
256
- continue;
257
- }
258
- const {
259
- name
260
- } = alert;
261
- if (!report) {
262
- report = {};
263
- }
264
- if (!report[name]) {
265
- report[name] = [];
266
- }
267
- const props = alert.raw?.props;
268
- report[name].push({
269
- id: -1,
270
- url: props?.url,
271
- title: props?.title,
272
- severity: alert.raw?.severity?.toLowerCase(),
273
- vulnerable_versions: props?.vulnerableVersionRange,
274
- cwe: props?.cwes,
275
- cvss: props?.csvs,
276
- name
277
- });
278
- }
279
- return report;
280
- }
281
- async function* batchScan(pkgIds) {
282
- const req = https.request(`${API_V0_URL}/purl?alerts=true`, {
283
- method: 'POST',
284
- headers: {
285
- Authorization: `Basic ${Buffer.from(`${pubToken}:`).toString('base64url')}`
286
- },
287
- signal: abortSignal
288
- }).end(JSON.stringify({
289
- components: pkgIds.map(id => ({
290
- purl: `pkg:npm/${id}`
291
- }))
292
- }));
293
- const {
294
- 0: res
295
- } = await events.once(req, 'response');
296
- const ok = res.statusCode >= 200 && res.statusCode <= 299;
297
- if (!ok) {
298
- throw new Error(`Socket API Error: ${res.statusCode}`);
299
- }
300
- const rli = readline.createInterface(res);
301
- for await (const line of rli) {
302
- yield JSON.parse(line);
303
- }
304
- }
305
-
306
- // Patch adding doOverrideSetsConflict is based on
307
- // https://github.com/npm/cli/pull/7025.
308
- function doOverrideSetsConflict(first, second) {
309
- // If override sets contain one another then we can try to use the more specific
310
- // one. However, if neither one is more specific, then we consider them to be
311
- // in conflict.
312
- return findSpecificOverrideSet(first, second) === undefined;
313
- }
314
- function findSocketYmlSync() {
315
- let prevDir = null;
316
- let dir = process.cwd();
317
- while (dir !== prevDir) {
318
- let ymlPath = path.join(dir, 'socket.yml');
319
- let yml = maybeReadfileSync(ymlPath);
320
- if (yml === undefined) {
321
- ymlPath = path.join(dir, 'socket.yaml');
322
- yml = maybeReadfileSync(ymlPath);
323
- }
324
- if (typeof yml === 'string') {
325
- try {
326
- return {
327
- path: ymlPath,
328
- parsed: config.parseSocketConfig(yml)
329
- };
330
- } catch {
331
- throw new Error(`Found file but was unable to parse ${ymlPath}`);
332
- }
333
- }
334
- prevDir = dir;
335
- dir = path.join(dir, '..');
336
- }
337
- return null;
338
- }
339
-
340
- // Patch adding findSpecificOverrideSet is based on
341
- // https://github.com/npm/cli/pull/7025.
342
- function findSpecificOverrideSet(first, second) {
343
- let overrideSet = second;
344
- while (overrideSet) {
345
- if (overrideSet.isEqual(first)) {
346
- return second;
347
- }
348
- overrideSet = overrideSet.parent;
349
- }
350
- overrideSet = first;
351
- while (overrideSet) {
352
- if (overrideSet.isEqual(second)) {
353
- return first;
354
- }
355
- overrideSet = overrideSet.parent;
356
- }
357
- // The override sets are incomparable. Neither one contains the other.
358
- log?.silly('Conflicting override sets', first, second);
359
- return undefined;
360
- }
361
- function isAlertFixable(alert) {
362
- return alert.type === 'socketUpgradeAvailable' || isAlertFixableCve(alert);
363
- }
364
- function isAlertFixableCve(alert) {
365
- const {
366
- type
367
- } = alert;
368
- return (type === 'cve' || type === 'mediumCVE' || type === 'mildCVE' || type === 'criticalCVE') && !!alert.props?.['firstPatchedVersionIdentifier'];
369
- }
370
- function maybeReadfileSync(filepath) {
371
- try {
372
- return fs.readFileSync(filepath, 'utf8');
373
- } catch {}
374
- return undefined;
375
- }
376
- async function getPackagesAlerts(safeArb, pkgs, output) {
377
- const spinner$1 = new spinner.Spinner({
378
- stream: output
379
- });
380
- let {
381
- length: remaining
382
- } = pkgs;
383
- const packageAlerts = [];
384
- if (!remaining) {
385
- spinner$1.success('No changes detected');
386
- return packageAlerts;
387
- }
388
- const getText = () => `Looking up data for ${remaining} packages`;
389
- spinner$1.start(getText());
390
- try {
391
- for await (const artifact of batchScan(pkgs.map(p => p.pkgid))) {
392
- if (!artifact.name || !artifact.version || !artifact.alerts?.length) {
393
- continue;
394
- }
395
- const {
396
- version
397
- } = artifact;
398
- const name = packages.resolvePackageName(artifact);
399
- const id = `${name}@${artifact.version}`;
400
- let blocked = false;
401
- let displayWarning = false;
402
- let alerts = [];
403
- for (const alert of artifact.alerts) {
404
- // eslint-disable-next-line no-await-in-loop
405
- const ux = await uxLookup({
406
- package: {
407
- name,
408
- version
409
- },
410
- alert: {
411
- type: alert.type
412
- }
413
- });
414
- if (ux.block) {
415
- blocked = true;
416
- }
417
- if (ux.display) {
418
- displayWarning = true;
419
- }
420
- if (ux.block || ux.display) {
421
- alerts.push({
422
- name,
423
- version,
424
- type: alert.type,
425
- block: ux.block,
426
- raw: alert,
427
- fixable: isAlertFixable(alert)
428
- });
429
- if (!ENV[SOCKET_CLI_FIX_PACKAGE_LOCK_FILE]) {
430
- // Before we ask about problematic issues, check to see if they
431
- // already existed in the old version if they did, be quiet.
432
- const existing = pkgs.find(p => p.existing?.startsWith(`${name}@`))?.existing;
433
- if (existing) {
434
- const oldArtifact =
435
- // eslint-disable-next-line no-await-in-loop
436
- (await batchScan([existing]).next()).value;
437
- if (oldArtifact?.alerts?.length) {
438
- alerts = alerts.filter(({
439
- type
440
- }) => !oldArtifact.alerts?.find(a => a.type === type));
441
- }
442
- }
443
- }
444
- }
445
- }
446
- if (!blocked) {
447
- const pkg = pkgs.find(p => p.pkgid === id);
448
- if (pkg) {
449
- await pacote.tarball.stream(id, stream => {
450
- stream.resume();
451
- return stream.promise();
452
- }, {
453
- ...safeArb[kCtorArgs][0]
454
- });
455
- }
456
- }
457
- if (displayWarning) {
458
- spinner$1.stop(`(socket) ${formatter.hyperlink(id, `https://socket.dev/npm/package/${name}/overview/${version}`)} contains risks:`);
459
- alerts.sort((a, b) => a.type < b.type ? -1 : 1);
460
- const lines = new Set();
461
- for (const alert of alerts) {
462
- // Based data from { pageProps: { alertTypes } } of:
463
- // https://socket.dev/_next/data/94666139314b6437ee4491a0864e72b264547585/en-US.json
464
- const info = translations.alerts[alert.type];
465
- const title = info?.title ?? alert.type;
466
- const attributes = [...(alert.fixable ? ['fixable'] : []), ...(alert.block ? [] : ['non-blocking'])];
467
- const maybeAttributes = attributes.length ? ` (${attributes.join('; ')})` : '';
468
- const maybeDesc = info?.description ? ` - ${info.description}` : '';
469
- // TODO: emoji seems to mis-align terminals sometimes
470
- lines.add(` ${title}${maybeAttributes}${maybeDesc}\n`);
471
- }
472
- for (const line of lines) {
473
- output?.write(line);
474
- }
475
- spinner$1.start();
476
- }
477
- remaining -= 1;
478
- spinner$1.text = remaining > 0 ? getText() : '';
479
- packageAlerts.push(...alerts);
480
- }
481
- } finally {
482
- spinner$1.stop();
483
- }
484
- return packageAlerts;
485
- }
486
- function toRepoUrl(resolved) {
487
- try {
488
- return URL.parse(resolved)?.origin ?? '';
489
- } catch {}
490
- return '';
491
- }
492
- function walk(diff_) {
493
- const needInfoOn = [];
494
- const queue = [...diff_.children];
495
- let pos = 0;
496
- let {
497
- length: queueLength
498
- } = queue;
499
- while (pos < queueLength) {
500
- if (pos === LOOP_SENTINEL) {
501
- throw new Error('Detected infinite loop while walking Arborist diff');
502
- }
503
- const diff = queue[pos++];
504
- const {
505
- action
506
- } = diff;
507
- if (action) {
508
- // The `pkgNode`, i.e. the `ideal` node, will be `undefined` if the diff
509
- // action is 'REMOVE'
510
- // The `oldNode`, i.e. the `actual` node, will be `undefined` if the diff
511
- // action is 'ADD'.
512
- const {
513
- actual: oldNode,
514
- ideal: pkgNode
515
- } = diff;
516
- let existing;
517
- let keep = false;
518
- if (action === 'CHANGE') {
519
- if (pkgNode?.package.version !== oldNode?.package.version) {
520
- keep = true;
521
- if (oldNode?.package.name && oldNode.package.name === pkgNode?.package.name) {
522
- existing = oldNode.pkgid;
523
- }
524
- }
525
- } else {
526
- keep = action !== 'REMOVE';
527
- }
528
- if (keep && pkgNode?.resolved && (!oldNode || oldNode.resolved)) {
529
- needInfoOn.push({
530
- existing,
531
- pkgid: pkgNode.pkgid,
532
- repository_url: toRepoUrl(pkgNode.resolved)
533
- });
534
- }
535
- }
536
- for (const child of diff.children) {
537
- queue[queueLength++] = child;
538
- }
539
- }
540
- if (ENV[SOCKET_CLI_FIX_PACKAGE_LOCK_FILE]) {
541
- const {
542
- unchanged
543
- } = diff_;
544
- for (let i = 0, {
545
- length
546
- } = unchanged; i < length; i += 1) {
547
- const pkgNode = unchanged[i];
548
- needInfoOn.push({
549
- existing: pkgNode.pkgid,
550
- pkgid: pkgNode.pkgid,
551
- repository_url: toRepoUrl(pkgNode.resolved)
552
- });
553
- }
554
- }
555
- return needInfoOn;
556
- }
557
-
558
- // The Edge class makes heavy use of private properties which subclasses do NOT
559
- // have access to. So we have to recreate any functionality that relies on those
560
- // private properties and use our own "safe" prefixed non-conflicting private
561
- // properties. Implementation code not related to patch https://github.com/npm/cli/pull/7025
562
- // is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/edge.js.
563
- //
564
- // The npm application
565
- // Copyright (c) npm, Inc. and Contributors
566
- // Licensed on the terms of The Artistic License 2.0
567
- //
568
- // An edge in the dependency graph.
569
- // Represents a dependency relationship of some kind.
570
- const initializedSafeEdges = new WeakSet();
571
- class SafeEdge extends Edge {
572
- #safeAccept;
573
- #safeError;
574
- #safeExplanation;
575
- #safeFrom;
576
- #safeName;
577
- #safeTo;
578
- constructor(options) {
579
- const {
580
- accept,
581
- from,
582
- name
583
- } = options;
584
- // Defer to supper to validate options and assign non-private values.
585
- super(options);
586
- if (accept !== undefined) {
587
- this.#safeAccept = accept || '*';
588
- }
589
- if (from.constructor !== SafeNode) {
590
- Reflect.setPrototypeOf(from, SafeNode.prototype);
591
- }
592
- this.#safeError = null;
593
- this.#safeExplanation = null;
594
- this.#safeFrom = from;
595
- this.#safeName = name;
596
- this.#safeTo = null;
597
- initializedSafeEdges.add(this);
598
- this.reload(true);
599
- }
600
- get accept() {
601
- return this.#safeAccept;
602
- }
603
- get bundled() {
604
- return !!this.#safeFrom?.package?.bundleDependencies?.includes(this.name);
605
- }
606
- get error() {
607
- if (!this.#safeError) {
608
- if (!this.#safeTo) {
609
- if (this.optional) {
610
- this.#safeError = null;
611
- } else {
612
- this.#safeError = 'MISSING';
613
- }
614
- } else if (this.peer && this.#safeFrom === this.#safeTo.parent && !this.#safeFrom?.isTop) {
615
- this.#safeError = 'PEER LOCAL';
616
- } else if (!this.satisfiedBy(this.#safeTo)) {
617
- this.#safeError = 'INVALID';
618
- }
619
- // Patch adding "else if" condition is based on
620
- // https://github.com/npm/cli/pull/7025.
621
- else if (this.overrides && this.#safeTo.edgesOut.size && doOverrideSetsConflict(this.overrides, this.#safeTo.overrides)) {
622
- // Any inconsistency between the edge's override set and the target's
623
- // override set is potentially problematic. But we only say the edge is
624
- // in error if the override sets are plainly conflicting. Note that if
625
- // the target doesn't have any dependencies of their own, then this
626
- // inconsistency is irrelevant.
627
- this.#safeError = 'INVALID';
628
- } else {
629
- this.#safeError = 'OK';
630
- }
631
- }
632
- if (this.#safeError === 'OK') {
633
- return null;
634
- }
635
- return this.#safeError;
636
- }
637
-
638
- // @ts-ignore: Incorrectly typed as a property instead of an accessor.
639
- get from() {
640
- return this.#safeFrom;
641
- }
642
-
643
- // @ts-ignore: Incorrectly typed as a property instead of an accessor.
644
- get spec() {
645
- if (this.overrides?.value && this.overrides.value !== '*' && this.overrides.name === this.name) {
646
- // Patch adding "if" condition is based on
647
- // https://github.com/npm/cli/pull/7025.
648
- //
649
- // If this edge has the same overrides field as the source, then we're not
650
- // applying an override for this edge.
651
- if (this.overrides === this.#safeFrom?.overrides) {
652
- // The Edge rawSpec getter will retrieve the private Edge #spec property.
653
- return this.rawSpec;
654
- }
655
- if (this.overrides.value.startsWith('$')) {
656
- const ref = this.overrides.value.slice(1);
657
- // We may be a virtual root, if we are we want to resolve reference
658
- // overrides from the real root, not the virtual one.
659
- const pkg = this.#safeFrom?.sourceReference ? this.#safeFrom.sourceReference.root.package : this.#safeFrom?.root?.package;
660
- if (pkg?.devDependencies?.[ref]) {
661
- return pkg.devDependencies[ref];
662
- }
663
- if (pkg?.optionalDependencies?.[ref]) {
664
- return pkg.optionalDependencies[ref];
665
- }
666
- if (pkg?.dependencies?.[ref]) {
667
- return pkg.dependencies[ref];
668
- }
669
- if (pkg?.peerDependencies?.[ref]) {
670
- return pkg.peerDependencies[ref];
671
- }
672
- throw new Error(`Unable to resolve reference ${this.overrides.value}`);
673
- }
674
- return this.overrides.value;
675
- }
676
- return this.rawSpec;
677
- }
678
-
679
- // @ts-ignore: Incorrectly typed as a property instead of an accessor.
680
- get to() {
681
- return this.#safeTo;
682
- }
683
- detach() {
684
- this.#safeExplanation = null;
685
- // Patch replacing
686
- // if (this.#safeTo) {
687
- // this.#safeTo.edgesIn.delete(this)
688
- // }
689
- // is based on https://github.com/npm/cli/pull/7025.
690
- this.#safeTo?.deleteEdgeIn(this);
691
- this.#safeFrom?.edgesOut.delete(this.name);
692
- this.#safeTo = null;
693
- this.#safeError = 'DETACHED';
694
- this.#safeFrom = null;
695
- }
696
-
697
- // Return the edge data, and an explanation of how that edge came to be here.
698
- // @ts-ignore: Edge#explain is defined with an unused `seen = []` param.
699
- explain() {
700
- if (!this.#safeExplanation) {
701
- const explanation = {
702
- type: this.type,
703
- name: this.name,
704
- spec: this.spec,
705
- bundled: false,
706
- overridden: false,
707
- error: undefined,
708
- from: undefined,
709
- rawSpec: undefined
710
- };
711
- if (this.rawSpec !== this.spec) {
712
- explanation.rawSpec = this.rawSpec;
713
- explanation.overridden = true;
714
- }
715
- if (this.bundled) {
716
- explanation.bundled = this.bundled;
717
- }
718
- if (this.error) {
719
- explanation.error = this.error;
720
- }
721
- if (this.#safeFrom) {
722
- explanation.from = this.#safeFrom.explain();
723
- }
724
- this.#safeExplanation = explanation;
725
- }
726
- return this.#safeExplanation;
727
- }
728
- reload(hard = false) {
729
- if (!initializedSafeEdges.has(this)) {
730
- // Skip if called during super constructor.
731
- return;
732
- }
733
- this.#safeExplanation = null;
734
- // Patch adding newOverrideSet and oldOverrideSet is based on
735
- // https://github.com/npm/cli/pull/7025.
736
- let newOverrideSet;
737
- let oldOverrideSet;
738
- if (this.#safeFrom?.overrides) {
739
- // Patch replacing
740
- // this.overrides = this.#safeFrom.overrides.getEdgeRule(this)
741
- // is based on https://github.com/npm/cli/pull/7025.
742
- const newOverrideSet = this.#safeFrom.overrides.getEdgeRule(this);
743
- if (newOverrideSet && !newOverrideSet.isEqual(this.overrides)) {
744
- // If there's a new different override set we need to propagate it to
745
- // the nodes. If we're deleting the override set then there's no point
746
- // propagating it right now since it will be filled with another value
747
- // later.
748
- oldOverrideSet = this.overrides;
749
- this.overrides = newOverrideSet;
750
- }
751
- } else {
752
- this.overrides = undefined;
753
- }
754
- const newTo = this.#safeFrom?.resolve(this.name);
755
- if (newTo !== this.#safeTo) {
756
- // Patch replacing
757
- // if (this.#safeTo) {
758
- // this.#safeTo.edgesIn.delete(this)
759
- // }
760
- // is based on https://github.com/npm/cli/pull/7025.
761
- this.#safeTo?.deleteEdgeIn(this);
762
- this.#safeTo = newTo ?? null;
763
- this.#safeError = null;
764
- this.#safeTo?.addEdgeIn(this);
765
- } else if (hard) {
766
- this.#safeError = null;
767
- }
768
- // Patch adding "else if" condition based on
769
- // https://github.com/npm/cli/pull/7025
770
- else if (oldOverrideSet) {
771
- // Propagate the new override set to the target node.
772
- this.#safeTo.updateOverridesEdgeInRemoved(oldOverrideSet);
773
- this.#safeTo.updateOverridesEdgeInAdded(newOverrideSet);
774
- }
775
- }
776
- satisfiedBy(node) {
777
- // Patch replacing
778
- // if (node.name !== this.#name) {
779
- // return false
780
- // }
781
- // is based on https://github.com/npm/cli/pull/7025.
782
- if (node.name !== this.#safeName || !this.#safeFrom) {
783
- return false;
784
- }
785
- // NOTE: this condition means we explicitly do not support overriding
786
- // bundled or shrinkwrapped dependencies
787
- if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) {
788
- return depValid(node, this.rawSpec, this.#safeAccept, this.#safeFrom);
789
- }
790
- // Patch replacing
791
- // return depValid(node, this.spec, this.#accept, this.#from)
792
- // is based on https://github.com/npm/cli/pull/7025.
793
- //
794
- // If there's no override we just use the spec.
795
- if (!this.overrides?.keySpec) {
796
- return depValid(node, this.spec, this.#safeAccept, this.#safeFrom);
797
- }
798
- // There's some override. If the target node satisfies the overriding spec
799
- // then it's okay.
800
- if (depValid(node, this.spec, this.#safeAccept, this.#safeFrom)) {
801
- return true;
802
- }
803
- // If it doesn't, then it should at least satisfy the original spec.
804
- if (!depValid(node, this.rawSpec, this.#safeAccept, this.#safeFrom)) {
805
- return false;
806
- }
807
- // It satisfies the original spec, not the overriding spec. We need to make
808
- // sure it doesn't use the overridden spec.
809
- // For example, we might have an ^8.0.0 rawSpec, and an override that makes
810
- // keySpec=8.23.0 and the override value spec=9.0.0.
811
- // If the node is 9.0.0, then it's okay because it's consistent with spec.
812
- // If the node is 8.24.0, then it's okay because it's consistent with the rawSpec.
813
- // If the node is 8.23.0, then it's not okay because even though it's consistent
814
- // with the rawSpec, it's also consistent with the keySpec.
815
- // So we're looking for ^8.0.0 or 9.0.0 and not 8.23.0.
816
- return !depValid(node, this.overrides.keySpec, this.#safeAccept, this.#safeFrom);
817
- }
818
- }
819
-
820
- // Implementation code not related to patch https://github.com/npm/cli/pull/7025
821
- // is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/node.js:
822
- class SafeNode extends Node {
823
- // Return true if it's safe to remove this node, because anything that is
824
- // depending on it would be fine with the thing that they would resolve to if
825
- // it was removed, or nothing is depending on it in the first place.
826
- canDedupe(preferDedupe = false) {
827
- // Not allowed to mess with shrinkwraps or bundles.
828
- if (this.inDepBundle || this.inShrinkwrap) {
829
- return false;
830
- }
831
- // It's a top level pkg, or a dep of one.
832
- if (!this.resolveParent?.resolveParent) {
833
- return false;
834
- }
835
- // No one wants it, remove it.
836
- if (this.edgesIn.size === 0) {
837
- return true;
838
- }
839
- const other = this.resolveParent.resolveParent.resolve(this.name);
840
- // Nothing else, need this one.
841
- if (!other) {
842
- return false;
843
- }
844
- // If it's the same thing, then always fine to remove.
845
- if (other.matches(this)) {
846
- return true;
847
- }
848
- // If the other thing can't replace this, then skip it.
849
- if (!other.canReplace(this)) {
850
- return false;
851
- }
852
- // Patch replacing
853
- // if (preferDedupe || semver.gte(other.version, this.version)) {
854
- // return true
855
- // }
856
- // is based on https://github.com/npm/cli/pull/7025.
857
- //
858
- // If we prefer dedupe, or if the version is equal, take the other.
859
- if (preferDedupe || semver.eq(other.version, this.version)) {
860
- return true;
861
- }
862
- // If our current version isn't the result of an override, then prefer to
863
- // take the greater version.
864
- if (!this.overridden && semver.gt(other.version, this.version)) {
865
- return true;
866
- }
867
- return false;
868
- }
869
-
870
- // Is it safe to replace one node with another? check the edges to
871
- // make sure no one will get upset. Note that the node might end up
872
- // having its own unmet dependencies, if the new node has new deps.
873
- // Note that there are cases where Arborist will opt to insert a node
874
- // into the tree even though this function returns false! This is
875
- // necessary when a root dependency is added or updated, or when a
876
- // root dependency brings peer deps along with it. In that case, we
877
- // will go ahead and create the invalid state, and then try to resolve
878
- // it with more tree construction, because it's a user request.
879
- canReplaceWith(node, ignorePeers) {
880
- if (this.name !== node.name || this.packageName !== node.packageName) {
881
- return false;
882
- }
883
- // Patch replacing
884
- // if (node.overrides !== this.overrides) {
885
- // return false
886
- // }
887
- // is based on https://github.com/npm/cli/pull/7025.
888
- //
889
- // If this node has no dependencies, then it's irrelevant to check the
890
- // override rules of the replacement node.
891
- if (this.edgesOut.size) {
892
- // XXX need to check for two root nodes?
893
- if (node.overrides) {
894
- if (!node.overrides.isEqual(this.overrides)) {
895
- return false;
896
- }
897
- } else {
898
- if (this.overrides) {
899
- return false;
900
- }
901
- }
902
- }
903
- // To satisfy the patch we ensure `node.overrides === this.overrides`
904
- // so that the condition we want to replace,
905
- // if (this.overrides !== node.overrides) {
906
- // , is not hit.`
907
- const oldOverrideSet = this.overrides;
908
- let result = true;
909
- if (oldOverrideSet !== node.overrides) {
910
- this.overrides = node.overrides;
911
- }
912
- try {
913
- result = super.canReplaceWith(node, ignorePeers);
914
- this.overrides = oldOverrideSet;
915
- } catch (e) {
916
- this.overrides = oldOverrideSet;
917
- throw e;
918
- }
919
- return result;
920
- }
921
-
922
- // Patch adding deleteEdgeIn is based on https://github.com/npm/cli/pull/7025.
923
- deleteEdgeIn(edge) {
924
- this.edgesIn.delete(edge);
925
- const {
926
- overrides
927
- } = edge;
928
- if (overrides) {
929
- this.updateOverridesEdgeInRemoved(overrides);
930
- }
931
- }
932
- addEdgeIn(edge) {
933
- // Patch replacing
934
- // if (edge.overrides) {
935
- // this.overrides = edge.overrides
936
- // }
937
- // is based on https://github.com/npm/cli/pull/7025.
938
- //
939
- // We need to handle the case where the new edge in has an overrides field
940
- // which is different from the current value.
941
- if (!this.overrides || !this.overrides.isEqual(edge.overrides)) {
942
- this.updateOverridesEdgeInAdded(edge.overrides);
943
- }
944
- this.edgesIn.add(edge);
945
- // Try to get metadata from the yarn.lock file.
946
- this.root.meta?.addEdge(edge);
947
- }
948
-
949
- // @ts-ignore: Incorrectly typed as a property instead of an accessor.
950
- get overridden() {
951
- // Patch replacing
952
- // return !!(this.overrides && this.overrides.value && this.overrides.name === this.name)
953
- // is based on https://github.com/npm/cli/pull/7025.
954
- if (!this.overrides || !this.overrides.value || this.overrides.name !== this.name) {
955
- return false;
956
- }
957
- // The overrides rule is for a package with this name, but some override rules
958
- // only apply to specific versions. To make sure this package was actually
959
- // overridden, we check whether any edge going in had the rule applied to it,
960
- // in which case its overrides set is different than its source node.
961
- for (const edge of this.edgesIn) {
962
- if (edge.overrides && edge.overrides.name === this.name && edge.overrides.value === this.version) {
963
- if (!edge.overrides?.isEqual(edge.from?.overrides)) {
964
- return true;
965
- }
966
- }
967
- }
968
- return false;
969
- }
970
-
971
- // Patch adding recalculateOutEdgesOverrides is based on
972
- // https://github.com/npm/cli/pull/7025.
973
- recalculateOutEdgesOverrides() {
974
- // For each edge out propagate the new overrides through.
975
- for (const edge of this.edgesOut.values()) {
976
- edge.reload(true);
977
- if (edge.to) {
978
- edge.to.updateOverridesEdgeInAdded(edge.overrides);
979
- }
980
- }
981
- }
982
-
983
- // @ts-ignore: Incorrectly typed to accept null.
984
- set root(newRoot) {
985
- // Patch removing
986
- // if (!this.overrides && this.parent && this.parent.overrides) {
987
- // this.overrides = this.parent.overrides.getNodeRule(this)
988
- // }
989
- // is based on https://github.com/npm/cli/pull/7025.
990
- //
991
- // The "root" setter is a really large and complex function. To satisfy the
992
- // patch we add a dummy value to `this.overrides` so that the condition we
993
- // want to remove,
994
- // if (!this.overrides && this.parent && this.parent.overrides) {
995
- // , is not hit.
996
- if (!this.overrides) {
997
- this.overrides = new OverrideSet({
998
- overrides: ''
999
- });
1000
- }
1001
- try {
1002
- super.root = newRoot;
1003
- this.overrides = undefined;
1004
- } catch (e) {
1005
- this.overrides = undefined;
1006
- throw e;
1007
- }
1008
- }
1009
-
1010
- // Patch adding updateOverridesEdgeInAdded is based on
1011
- // https://github.com/npm/cli/pull/7025.
1012
- //
1013
- // This logic isn't perfect either. When we have two edges in that have
1014
- // different override sets, then we have to decide which set is correct. This
1015
- // function assumes the more specific override set is applicable, so if we have
1016
- // dependencies A->B->C and A->C and an override set that specifies what happens
1017
- // for C under A->B, this will work even if the new A->C edge comes along and
1018
- // tries to change the override set. The strictly correct logic is not to allow
1019
- // two edges with different overrides to point to the same node, because even
1020
- // if this node can satisfy both, one of its dependencies might need to be
1021
- // different depending on the edge leading to it. However, this might cause a
1022
- // lot of duplication, because the conflict in the dependencies might never
1023
- // actually happen.
1024
- updateOverridesEdgeInAdded(otherOverrideSet) {
1025
- if (!otherOverrideSet) {
1026
- // Assuming there are any overrides at all, the overrides field is never
1027
- // undefined for any node at the end state of the tree. So if the new edge's
1028
- // overrides is undefined it will be updated later. So we can wait with
1029
- // updating the node's overrides field.
1030
- return false;
1031
- }
1032
- if (!this.overrides) {
1033
- this.overrides = otherOverrideSet;
1034
- this.recalculateOutEdgesOverrides();
1035
- return true;
1036
- }
1037
- if (this.overrides.isEqual(otherOverrideSet)) {
1038
- return false;
1039
- }
1040
- const newOverrideSet = findSpecificOverrideSet(this.overrides, otherOverrideSet);
1041
- if (newOverrideSet) {
1042
- if (this.overrides.isEqual(newOverrideSet)) {
1043
- return false;
1044
- }
1045
- this.overrides = newOverrideSet;
1046
- this.recalculateOutEdgesOverrides();
1047
- return true;
1048
- }
1049
- // This is an error condition. We can only get here if the new override set
1050
- // is in conflict with the existing.
1051
- log?.silly('Conflicting override sets', this.name);
1052
- return false;
1053
- }
1054
-
1055
- // Patch adding updateOverridesEdgeInRemoved is based on
1056
- // https://github.com/npm/cli/pull/7025.
1057
- updateOverridesEdgeInRemoved(otherOverrideSet) {
1058
- // If this edge's overrides isn't equal to this node's overrides,
1059
- // then removing it won't change newOverrideSet later.
1060
- if (!this.overrides || !this.overrides.isEqual(otherOverrideSet)) {
1061
- return false;
1062
- }
1063
- let newOverrideSet;
1064
- for (const edge of this.edgesIn) {
1065
- const {
1066
- overrides: edgeOverrides
1067
- } = edge;
1068
- if (newOverrideSet && edgeOverrides) {
1069
- newOverrideSet = findSpecificOverrideSet(edgeOverrides, newOverrideSet);
1070
- } else {
1071
- newOverrideSet = edgeOverrides;
1072
- }
1073
- }
1074
- if (this.overrides.isEqual(newOverrideSet)) {
1075
- return false;
1076
- }
1077
- this.overrides = newOverrideSet;
1078
- if (newOverrideSet) {
1079
- // Optimization: If there's any override set at all, then no non-extraneous
1080
- // node has an empty override set. So if we temporarily have no override set
1081
- // (for example, we removed all the edges in), there's no use updating all
1082
- // the edges out right now. Let's just wait until we have an actual override
1083
- // set later.
1084
- this.recalculateOutEdgesOverrides();
1085
- }
1086
- return true;
1087
- }
1088
- }
1089
-
1090
- // Implementation code not related to patch https://github.com/npm/cli/pull/7025
1091
- // is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/override-set.js:
1092
- class SafeOverrideSet extends OverrideSet {
1093
- // Patch adding childrenAreEqual is based on
1094
- // https://github.com/npm/cli/pull/7025.
1095
- childrenAreEqual(otherOverrideSet) {
1096
- const queue = [[this, otherOverrideSet]];
1097
- let pos = 0;
1098
- let {
1099
- length: queueLength
1100
- } = queue;
1101
- while (pos < queueLength) {
1102
- if (pos === LOOP_SENTINEL) {
1103
- throw new Error('Detected infinite loop while comparing override sets');
1104
- }
1105
- const {
1106
- 0: currSet,
1107
- 1: currOtherSet
1108
- } = queue[pos++];
1109
- const {
1110
- children
1111
- } = currSet;
1112
- const {
1113
- children: otherChildren
1114
- } = currOtherSet;
1115
- if (children.size !== otherChildren.size) {
1116
- return false;
1117
- }
1118
- for (const key of children.keys()) {
1119
- if (!otherChildren.has(key)) {
1120
- return false;
1121
- }
1122
- const child = children.get(key);
1123
- const otherChild = otherChildren.get(key);
1124
- if (child.value !== otherChild.value) {
1125
- return false;
1126
- }
1127
- queue[queueLength++] = [child, otherChild];
1128
- }
1129
- }
1130
- return true;
1131
- }
1132
- getEdgeRule(edge) {
1133
- for (const rule of this.ruleset.values()) {
1134
- if (rule.name !== edge.name) {
1135
- continue;
1136
- }
1137
- // If keySpec is * we found our override.
1138
- if (rule.keySpec === '*') {
1139
- return rule;
1140
- }
1141
- // Patch replacing
1142
- // let spec = npa(`${edge.name}@${edge.spec}`)
1143
- // is based on https://github.com/npm/cli/pull/7025.
1144
- //
1145
- // We need to use the rawSpec here, because the spec has the overrides
1146
- // applied to it already.
1147
- let spec = npa(`${edge.name}@${edge.rawSpec}`);
1148
- if (spec.type === 'alias') {
1149
- spec = spec.subSpec;
1150
- }
1151
- if (spec.type === 'git') {
1152
- if (spec.gitRange && rule.keySpec && semver.intersects(spec.gitRange, rule.keySpec)) {
1153
- return rule;
1154
- }
1155
- continue;
1156
- }
1157
- if (spec.type === 'range' || spec.type === 'version') {
1158
- if (rule.keySpec && semver.intersects(spec.fetchSpec, rule.keySpec)) {
1159
- return rule;
1160
- }
1161
- continue;
1162
- }
1163
- // If we got this far, the spec type is one of tag, directory or file
1164
- // which means we have no real way to make version comparisons, so we
1165
- // just accept the override.
1166
- return rule;
1167
- }
1168
- return this;
1169
- }
1170
-
1171
- // Patch adding isEqual is based on
1172
- // https://github.com/npm/cli/pull/7025.
1173
- isEqual(otherOverrideSet) {
1174
- if (this === otherOverrideSet) {
1175
- return true;
1176
- }
1177
- if (!otherOverrideSet) {
1178
- return false;
1179
- }
1180
- if (this.key !== otherOverrideSet.key || this.value !== otherOverrideSet.value) {
1181
- return false;
1182
- }
1183
- if (!this.childrenAreEqual(otherOverrideSet)) {
1184
- return false;
1185
- }
1186
- if (!this.parent) {
1187
- return !otherOverrideSet.parent;
1188
- }
1189
- return this.parent.isEqual(otherOverrideSet.parent);
1190
- }
1191
- }
1192
-
1193
- // Implementation code not related to our custom behavior is based on
1194
- // https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/arborist/index.js:
1195
- class SafeArborist extends Arborist {
1196
- constructor(...ctorArgs) {
1197
- const mutedArguments = [{
1198
- ...ctorArgs[0],
1199
- audit: true,
1200
- dryRun: true,
1201
- ignoreScripts: true,
1202
- save: false,
1203
- saveBundle: false,
1204
- // progress: false,
1205
- fund: false
1206
- }, ctorArgs.slice(1)];
1207
- super(...mutedArguments);
1208
- this[kCtorArgs] = ctorArgs;
1209
- }
1210
- async [kRiskyReify](...args) {
1211
- // SafeArborist has suffered side effects and must be rebuilt from scratch.
1212
- const arb = new Arborist(...this[kCtorArgs]);
1213
- arb.idealTree = this.idealTree;
1214
- const ret = await arb.reify(...args);
1215
- Object.assign(this, arb);
1216
- return ret;
1217
- }
1218
-
1219
- // @ts-ignore Incorrectly typed.
1220
- async reify(...args) {
1221
- const options = args[0] ? {
1222
- ...args[0]
1223
- } : {};
1224
- if (options.dryRun) {
1225
- return await this[kRiskyReify](...args);
1226
- }
1227
- const old = {
1228
- ...options,
1229
- dryRun: false,
1230
- save: Boolean(options['save'] ?? true),
1231
- saveBundle: Boolean(options['saveBundle'] ?? false)
1232
- };
1233
- args[0] = options;
1234
- options.dryRun = true;
1235
- options['save'] = false;
1236
- options['saveBundle'] = false;
1237
- // TODO: Make this deal with any refactor to private fields by punching the
1238
- // class itself.
1239
- await super.reify(...args);
1240
- options.dryRun = old.dryRun;
1241
- options['save'] = old.save;
1242
- options['saveBundle'] = old.saveBundle;
1243
- const {
1244
- diff
1245
- } = this;
1246
- // `diff` is `null` when `options.packageLockOnly`, --package-lock-only,
1247
- // is `true`.
1248
- const needInfoOn = diff ? walk(diff) : [];
1249
- if (needInfoOn.findIndex(c => c.repository_url === NPM_REGISTRY_URL) === -1) {
1250
- // Nothing to check, hmmm already installed or all private?
1251
- return await this[kRiskyReify](...args);
1252
- }
1253
- const input = process.stdin;
1254
- const output = process.stderr;
1255
- let alerts;
1256
- const proceed = ENV[SOCKET_CLI_UPDATE_OVERRIDES_IN_PACKAGE_LOCK_FILE] || (await (async () => {
1257
- alerts = await getPackagesAlerts(this, needInfoOn, output);
1258
- if (!alerts.length || ENV[SOCKET_CLI_FIX_PACKAGE_LOCK_FILE]) {
1259
- return true;
1260
- }
1261
- return await prompts.confirm({
1262
- message: 'Accept risks of installing these packages?',
1263
- default: false
1264
- }, {
1265
- input,
1266
- output,
1267
- signal: abortSignal
1268
- });
1269
- })());
1270
- if (proceed) {
1271
- const fix = !!alerts?.length && (ENV[SOCKET_CLI_FIX_PACKAGE_LOCK_FILE] || (await prompts.confirm({
1272
- message: 'Try to fix alerts?',
1273
- default: true
1274
- }, {
1275
- input,
1276
- output,
1277
- signal: abortSignal
1278
- })));
1279
- if (fix) {
1280
- await updateAdvisoryDependencies(this, alerts);
1281
- }
1282
- return await this[kRiskyReify](...args);
1283
- } else {
1284
- throw new Error('Socket npm exiting due to risks');
1285
- }
1286
- }
1287
- }
1288
- async function updateAdvisoryDependencies(arb, alerts) {
1289
- const report = packageAlertsToReport(alerts);
1290
- if (!report) {
1291
- // No advisories to process.
1292
- return;
1293
- }
1294
- await arb.buildIdealTree();
1295
- const tree = arb.idealTree;
1296
- for (const name of Object.keys(report)) {
1297
- const advisories = report[name];
1298
- const node = findPackageRecursively(tree, name);
1299
- if (!node) {
1300
- // Package not found in the tree.
1301
- continue;
1302
- }
1303
- const {
1304
- version
1305
- } = node;
1306
- const majorVerNum = semver.major(version);
1307
-
1308
- // Fetch packument to get available versions.
1309
- // eslint-disable-next-line no-await-in-loop
1310
- const packument = await packages.fetchPackagePackument(name);
1311
- const availableVersions = packument ? Object.keys(packument.versions) : [];
1312
- for (const advisory of advisories) {
1313
- const {
1314
- vulnerable_versions
1315
- } = advisory;
1316
- // Find the highest non-vulnerable version within the same major range
1317
- const targetVersion = findBestPatchVersion(name, availableVersions, majorVerNum, vulnerable_versions);
1318
- const targetPackument = targetVersion ? packument.versions[targetVersion] : undefined;
1319
- // Check !targetVersion to make TypeScript happy.
1320
- if (!targetVersion || !targetPackument) {
1321
- // No suitable patch version found.
1322
- continue;
1323
- }
1324
-
1325
- // Use Object.defineProperty to override the version.
1326
- Object.defineProperty(node, 'version', {
1327
- configurable: true,
1328
- enumerable: true,
1329
- get: () => targetVersion
1330
- });
1331
- node.package.version = targetVersion;
1332
- // Update resolved and clear integrity for the new version.
1333
- node.resolved = `https://registry.npmjs.org/${name}/-/${name}-${targetVersion}.tgz`;
1334
- if (node.integrity) {
1335
- delete node.integrity;
1336
- }
1337
- if ('deprecated' in targetPackument) {
1338
- node.package['deprecated'] = targetPackument.deprecated;
1339
- } else {
1340
- delete node.package['deprecated'];
1341
- }
1342
- const newDeps = {
1343
- ...targetPackument.dependencies
1344
- };
1345
- const {
1346
- dependencies: oldDeps
1347
- } = node.package;
1348
- node.package.dependencies = newDeps;
1349
- if (oldDeps) {
1350
- for (const oldDepName of Object.keys(oldDeps)) {
1351
- if (!objects.hasOwn(newDeps, oldDepName)) {
1352
- node.edgesOut.get(oldDepName)?.detach();
1353
- }
1354
- }
1355
- }
1356
- for (const newDepName of Object.keys(newDeps)) {
1357
- if (!objects.hasOwn(oldDeps, newDepName)) {
1358
- node.addEdgeOut(new Edge({
1359
- from: node,
1360
- name: newDepName,
1361
- spec: newDeps[newDepName],
1362
- type: 'prod'
1363
- }));
1364
- }
1365
- }
1366
- }
1367
- }
1368
- }
1369
- function findPackageRecursively(tree, packageName) {
1370
- const queue = [{
1371
- node: tree
1372
- }];
1373
- let sentinel = 0;
1374
- while (queue.length) {
1375
- if (sentinel++ === LOOP_SENTINEL) {
1376
- throw new Error('Detected infinite loop in findPackageRecursively');
1377
- }
1378
- const {
1379
- node: currentNode
1380
- } = queue.pop();
1381
- const node = currentNode.children.get(packageName);
1382
- if (node) {
1383
- // Found package.
1384
- return node;
1385
- }
1386
- const children = [...currentNode.children.values()];
1387
- for (let i = children.length - 1; i >= 0; i -= 1) {
1388
- queue.push({
1389
- node: children[i]
1390
- });
1391
- }
1392
- }
1393
- return null;
1394
- }
1395
- function findBestPatchVersion(name, availableVersions, currentMajorVersion, vulnerableRange) {
1396
- const manifestVersion = registry.getManifestData(NPM, name)?.version;
1397
- // Filter versions that are within the current major version and are not in the vulnerable range
1398
- const eligibleVersions = availableVersions.filter(version => {
1399
- const isSameMajor = semver.major(version) === currentMajorVersion;
1400
- const isNotVulnerable = !semver.satisfies(version, vulnerableRange);
1401
- if (isSameMajor && isNotVulnerable) {
1402
- return true;
1403
- }
1404
- return !!manifestVersion;
1405
- });
1406
- if (eligibleVersions.length === 0) {
1407
- return null;
1408
- }
1409
- // Use semver to find the max satisfying version.
1410
- return semver.maxSatisfying(eligibleVersions, '*');
1411
- }
1412
- function installSafeArborist() {
1413
- const cache = require.cache;
1414
- cache[arboristClassPath] = {
1415
- exports: SafeArborist
1416
- };
1417
- cache[arboristEdgeClassPath] = {
1418
- exports: SafeEdge
1419
- };
1420
- cache[arboristNodeClassPath] = {
1421
- exports: SafeNode
1422
- };
1423
- cache[arboristOverrideSetClassPatch] = {
1424
- exports: SafeOverrideSet
1425
- };
1426
- }
1427
- void (async () => {
1428
- const {
1429
- orgs,
1430
- settings
1431
- } = await (async () => {
1432
- try {
1433
- const socketSdk = await sdk.setupSdk(pubToken);
1434
- const orgResult = await socketSdk.getOrganizations();
1435
- if (!orgResult.success) {
1436
- throw new Error(`Failed to fetch Socket organization info: ${orgResult.error.message}`);
1437
- }
1438
- const orgs = [];
1439
- for (const org of Object.values(orgResult.data.organizations)) {
1440
- if (org) {
1441
- orgs.push(org);
1442
- }
1443
- }
1444
- const result = await socketSdk.postSettings(orgs.map(org => ({
1445
- organization: org.id
1446
- })));
1447
- if (!result.success) {
1448
- throw new Error(`Failed to fetch API key settings: ${result.error.message}`);
1449
- }
1450
- return {
1451
- orgs,
1452
- settings: result.data
1453
- };
1454
- } catch (e) {
1455
- if (objects.isObject(e) && 'cause' in e) {
1456
- const {
1457
- cause
1458
- } = e;
1459
- if (sdk.isErrnoException(cause)) {
1460
- if (cause.code === 'ENOTFOUND' || cause.code === 'ECONNREFUSED') {
1461
- throw new Error('Unable to connect to socket.dev, ensure internet connectivity before retrying', {
1462
- cause: e
1463
- });
1464
- }
1465
- }
1466
- }
1467
- throw e;
1468
- }
1469
- })();
1470
-
1471
- // Remove any organizations not being enforced.
1472
- const enforcedOrgs = sdk.getSetting('enforcedOrgs') ?? [];
1473
- for (const {
1474
- 0: i,
1475
- 1: org
1476
- } of orgs.entries()) {
1477
- if (!enforcedOrgs.includes(org.id)) {
1478
- settings.entries.splice(i, 1);
1479
- }
1480
- }
1481
- const socketYml = findSocketYmlSync();
1482
- if (socketYml) {
1483
- settings.entries.push({
1484
- start: socketYml.path,
1485
- settings: {
1486
- [socketYml.path]: {
1487
- deferTo: null,
1488
- // TODO: TypeScript complains about the type not matching. We should
1489
- // figure out why are providing
1490
- // issueRules: { [issueName: string]: boolean }
1491
- // but expecting
1492
- // issueRules: { [issueName: string]: { action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn' } }
1493
- issueRules: socketYml.parsed.issueRules
1494
- }
1495
- }
1496
- });
1497
- }
1498
- _uxLookup = createAlertUXLookup(settings);
1499
- })();
1500
-
1501
- installSafeArborist();
3
+ module.exports = require('../module-sync/npm-injection.js')