@socketsecurity/cli 0.14.38 → 0.14.40

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