@socketsecurity/cli 0.14.28 → 0.14.29

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