@socketsecurity/cli 0.14.3 → 0.14.5

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.
@@ -0,0 +1,1437 @@
1
+ 'use strict';
2
+
3
+ var vendor = require('./vendor.js');
4
+ var require$$0 = require('node:fs');
5
+ var require$$1 = require('node:path');
6
+ var link = require('./link.js');
7
+ var require$$0$1 = require('node:events');
8
+ var require$$4 = require('node:https');
9
+ var require$$3 = require('node:readline');
10
+ var require$$1$2 = require('node:stream');
11
+ var require$$8 = require('node:timers/promises');
12
+ var require$$3$1 = require('@socketsecurity/config');
13
+ var require$$1$1 = require('node:net');
14
+ var require$$2 = require('node:os');
15
+ var sdk = require('./sdk.js');
16
+ var pathResolve = require('./path-resolve.js');
17
+ var require$$21 = require('pacote');
18
+
19
+ var npmInjection$1 = {};
20
+
21
+ var npmInjection = {};
22
+
23
+ var arborist = {};
24
+
25
+ var ttyServer$1 = {};
26
+
27
+ var name = "@socketsecurity/cli";
28
+ var version = "0.14.5";
29
+ var description = "CLI tool for Socket.dev";
30
+ var homepage = "http://github.com/SocketDev/socket-cli-js";
31
+ var license = "MIT";
32
+ var repository = {
33
+ type: "git",
34
+ url: "git+https://github.com/SocketDev/socket-cli-js.git"
35
+ };
36
+ var author = {
37
+ name: "Socket Inc",
38
+ email: "eng@socket.dev",
39
+ url: "https://socket.dev"
40
+ };
41
+ var bin = {
42
+ cli: "dist/cli.js",
43
+ socket: "dist/cli.js",
44
+ "socket-npm": "dist/npm-cli.js",
45
+ "socket-npx": "dist/npx-cli.js"
46
+ };
47
+ var scripts = {
48
+ build: "npm run build:dist && npm run build:test",
49
+ "build:dist": "rollup -c .config/rollup.dist.config.mjs",
50
+ "build:test": "rollup -c .config/rollup.test.config.mjs",
51
+ check: "run-p -c --aggregate-output check:*",
52
+ "check:lint": "eslint --report-unused-disable-directives .",
53
+ "check:tsc": "tsc",
54
+ "check:type-coverage": "type-coverage --detail --strict --at-least 95 --ignore-files 'test/*'",
55
+ "knip:dependencies": "knip --dependencies",
56
+ "knip:exports": "knip --include exports,duplicates",
57
+ lint: "oxlint -c=./.oxlintrc.json --ignore-path=./.prettierignore --tsconfig=./tsconfig.json . -D correctness -D perf -D suspicious --promise-plugin --import-plugin",
58
+ "lint:fix": "npm run lint -- --fix && npm run lint:fix:fast",
59
+ "lint:fix:fast": "prettier --cache --log-level warn --write .",
60
+ prepare: "husky",
61
+ test: "run-s check build:* test:*",
62
+ "test:c8": "c8 --reporter=none node --test 'test/socket-npm.test.cjs'",
63
+ "test-ci": "run-s build:* test:*",
64
+ "test:unit": "tap",
65
+ "test:coverage": "cp -r .tap/coverage/*.json coverage/tmp && c8 --reporter=lcov --reporter=text --include 'dist/*.js' --exclude 'dist/vendor.js' report"
66
+ };
67
+ var dependencies = {
68
+ "@apideck/better-ajv-errors": "^0.3.6",
69
+ "@cyclonedx/cdxgen": "^10.10.4",
70
+ "@inquirer/prompts": "^7.0.0",
71
+ "@npmcli/package-json": "6.0.1",
72
+ "@npmcli/promise-spawn": "^8.0.1",
73
+ "@socketregistry/hyrious__bun.lockb": "1.0.0",
74
+ "@socketsecurity/config": "^2.1.3",
75
+ "@socketsecurity/registry": "^1.0.4",
76
+ "@socketsecurity/sdk": "^1.3.0",
77
+ "ansi-align": "^3.0.1",
78
+ blessed: "^0.1.81",
79
+ "blessed-contrib": "^4.11.0",
80
+ browserslist: "4.24.0",
81
+ "chalk-table": "^1.0.2",
82
+ "cli-boxes": "^4.0.1",
83
+ "cli-spinners": "^3.2.0",
84
+ "cross-spawn": "^7.0.3",
85
+ "dot-prop": "^9.0.0",
86
+ eastasianwidth: "^0.3.0",
87
+ "emoji-regex": "^10.4.0",
88
+ "fast-glob": "^3.3.2",
89
+ "graceful-fs": "^4.2.11",
90
+ "has-flag": "^5.0.1",
91
+ hpagent: "^1.2.0",
92
+ ignore: "^6.0.2",
93
+ ini: "5.0.0",
94
+ onetime: "^7.0.0",
95
+ pacote: "^19.0.0",
96
+ "pony-cause": "^2.1.11",
97
+ rc: "1.2.8",
98
+ "registry-auth-token": "^5.0.2",
99
+ semver: "^7.6.3",
100
+ "signal-exit": "^4.1.0",
101
+ "supports-color": "^9.4.0",
102
+ "supports-hyperlinks": "^3.1.0",
103
+ synp: "^1.9.13",
104
+ which: "^5.0.0",
105
+ "write-file-atomic": "^6.0.0",
106
+ "yargs-parser": "^21.1.1"
107
+ };
108
+ var devDependencies = {
109
+ "@babel/core": "^7.25.8",
110
+ "@babel/plugin-proposal-export-default-from": "^7.25.8",
111
+ "@babel/plugin-syntax-dynamic-import": "^7.8.3",
112
+ "@babel/plugin-transform-export-namespace-from": "^7.25.8",
113
+ "@babel/plugin-transform-modules-commonjs": "^7.25.7",
114
+ "@babel/plugin-transform-runtime": "^7.25.7",
115
+ "@babel/preset-env": "^7.25.8",
116
+ "@babel/preset-typescript": "^7.25.7",
117
+ "@babel/runtime": "^7.25.7",
118
+ "@eslint/compat": "^1.2.0",
119
+ "@rollup/plugin-commonjs": "^28.0.0",
120
+ "@rollup/plugin-json": "^6.1.0",
121
+ "@rollup/plugin-node-resolve": "^15.3.0",
122
+ "@rollup/plugin-replace": "^6.0.1",
123
+ "@rollup/pluginutils": "^5.1.2",
124
+ "@types/blessed": "^0.1.25",
125
+ "@types/micromatch": "^4.0.9",
126
+ "@types/mocha": "^10.0.9",
127
+ "@types/mock-fs": "^4.13.4",
128
+ "@types/node": "^22.7.5",
129
+ "@types/npmcli__arborist": "^5.6.11",
130
+ "@types/npmcli__package-json": "^4.0.4",
131
+ "@types/npmcli__promise-spawn": "^6.0.3",
132
+ "@types/semver": "^7.5.8",
133
+ "@types/update-notifier": "^6.0.8",
134
+ "@types/which": "^3.0.4",
135
+ "@types/yargs-parser": "^21.0.3",
136
+ "@typescript-eslint/eslint-plugin": "^8.8.1",
137
+ "@typescript-eslint/parser": "^8.8.1",
138
+ c8: "^10.1.2",
139
+ chalk: "^5.3.0",
140
+ eslint: "^9.12.0",
141
+ "eslint-plugin-depend": "^0.11.0",
142
+ globby: "^14.0.2",
143
+ husky: "^9.1.6",
144
+ "is-interactive": "^2.0.0",
145
+ "is-unicode-supported": "^2.1.0",
146
+ knip: "^5.33.3",
147
+ "magic-string": "^0.30.11",
148
+ meow: "^13.2.0",
149
+ "mock-fs": "^5.3.0",
150
+ nock: "^13.5.5",
151
+ "normalize-package-data": "^7.0.0",
152
+ "npm-run-all2": "^6.2.3",
153
+ open: "^10.1.0",
154
+ ora: "^8.1.0",
155
+ oxlint: "^0.9.10",
156
+ prettier: "3.3.3",
157
+ "read-package-up": "^11.0.0",
158
+ rollup: "4.24.0",
159
+ "rollup-plugin-ts": "^3.4.5",
160
+ tap: "^21.0.1",
161
+ "terminal-link": "^3.0.0",
162
+ "type-coverage": "^2.29.1",
163
+ typescript: "5.4.5",
164
+ "typescript-eslint": "^8.8.1",
165
+ "unplugin-purge-polyfills": "^0.0.7",
166
+ "update-notifier": "^7.3.1",
167
+ "validate-npm-package-name": "^6.0.0"
168
+ };
169
+ var overrides = {
170
+ "@cyclonedx/cdxgen": {
171
+ "packageurl-js": "https://registry.npmjs.org/packageurl-js/-/packageurl-js-2.0.1.tgz"
172
+ },
173
+ "aggregate-error": "npm:@socketregistry/aggregate-error@^1",
174
+ "es-define-property": "npm:@socketregistry/es-define-property@^1",
175
+ "function-bind": "npm:@socketregistry/function-bind@^1",
176
+ globalthis: "npm:@socketregistry/globalthis@^1",
177
+ gopd: "npm:@socketregistry/gopd@^1",
178
+ "has-property-descriptors": "npm:@socketregistry/has-property-descriptors@^1",
179
+ "has-proto": "npm:@socketregistry/has-proto@^1",
180
+ "has-symbols": "npm:@socketregistry/has-symbols@^1",
181
+ hasown: "npm:@socketregistry/hasown@^1",
182
+ "indent-string": "npm:@socketregistry/indent-string@^1",
183
+ "is-core-module": "npm:@socketregistry/is-core-module@^1",
184
+ isarray: "npm:@socketregistry/isarray@^1",
185
+ "path-parse": "npm:@socketregistry/path-parse@^1",
186
+ "safe-buffer": "npm:@socketregistry/safe-buffer@^1",
187
+ "safer-buffer": "npm:@socketregistry/safer-buffer@^1",
188
+ "set-function-length": "npm:@socketregistry/set-function-length@^1",
189
+ "side-channel": "npm:@socketregistry/side-channel@^1"
190
+ };
191
+ var engines = {
192
+ node: "^20.9.0 || >=22.0.0"
193
+ };
194
+ var files = [
195
+ "bin/**",
196
+ "dist/**",
197
+ "translations.json"
198
+ ];
199
+ var require$$6 = {
200
+ name: name,
201
+ version: version,
202
+ description: description,
203
+ homepage: homepage,
204
+ license: license,
205
+ repository: repository,
206
+ author: author,
207
+ bin: bin,
208
+ scripts: scripts,
209
+ dependencies: dependencies,
210
+ devDependencies: devDependencies,
211
+ overrides: overrides,
212
+ engines: engines,
213
+ files: files
214
+ };
215
+
216
+ Object.defineProperty(ttyServer$1, "__esModule", {
217
+ value: true
218
+ });
219
+ ttyServer$1.createTTYServer = createTTYServer;
220
+ var _nodeFs$2 = require$$0;
221
+ var _nodeNet = require$$1$1;
222
+ var _nodeOs = require$$2;
223
+ var _nodePath$2 = require$$1;
224
+ var _nodeReadline$1 = require$$3;
225
+ var _nodeStream$1 = require$$1$2;
226
+ var _package = require$$6;
227
+ var _misc$1 = sdk.misc;
228
+ const NEWLINE_CHAR_CODE = 10; /*'\n'*/
229
+
230
+ const TTY_IPC = process.env['SOCKET_SECURITY_TTY_IPC'];
231
+ const sock = _nodePath$2.join(_nodeOs.tmpdir(), `socket-security-tty-${process.pid}.sock`);
232
+ process.env['SOCKET_SECURITY_TTY_IPC'] = sock;
233
+ function createNonStandardTTYServer() {
234
+ return {
235
+ async captureTTY(mutexFn) {
236
+ return await new Promise((resolve, reject) => {
237
+ const conn = _nodeNet.createConnection({
238
+ path: TTY_IPC
239
+ }).on('error', reject);
240
+ let captured = false;
241
+ const buffs = [];
242
+ conn.on('data', function awaitCapture(chunk) {
243
+ buffs.push(chunk);
244
+ let lineBuff = Buffer.concat(buffs);
245
+ if (captured) return;
246
+ try {
247
+ const eolIndex = lineBuff.indexOf(NEWLINE_CHAR_CODE);
248
+ if (eolIndex !== -1) {
249
+ conn.removeListener('data', awaitCapture);
250
+ conn.push(lineBuff.slice(eolIndex + 1));
251
+ const {
252
+ ipc_version: remote_ipc_version,
253
+ capabilities: {
254
+ input: hasInput,
255
+ output: hasOutput,
256
+ colorLevel: ipcColorLevel
257
+ }
258
+ } = JSON.parse(lineBuff.slice(0, eolIndex).toString('utf-8'));
259
+ lineBuff = null;
260
+ captured = true;
261
+ if (remote_ipc_version !== _package.version) {
262
+ throw new Error('Mismatched STDIO tunnel IPC version, ensure you only have 1 version of socket CLI being called.');
263
+ }
264
+ const input = hasInput ? new _nodeStream$1.PassThrough() : null;
265
+ input?.pause();
266
+ if (input) conn.pipe(input);
267
+ const output = hasOutput ? new _nodeStream$1.PassThrough() : null;
268
+ if (output) {
269
+ output.pipe(conn)
270
+ // Make ora happy
271
+ ;
272
+ output.isTTY = true;
273
+ output.cursorTo = function cursorTo(x, y, callback) {
274
+ _nodeReadline$1.cursorTo(this, x, y, callback);
275
+ };
276
+ output.clearLine = function clearLine(dir, callback) {
277
+ _nodeReadline$1.clearLine(this, dir, callback);
278
+ };
279
+ }
280
+ mutexFn(ipcColorLevel, hasInput ? input : undefined, hasOutput ? output : undefined).then(resolve, reject).finally(() => {
281
+ conn.unref();
282
+ conn.end();
283
+ input?.end();
284
+ output?.end();
285
+ // process.exit(13)
286
+ });
287
+ }
288
+ } catch (e) {
289
+ reject(e);
290
+ }
291
+ });
292
+ });
293
+ }
294
+ };
295
+ }
296
+ function createIPCServer(colorLevel, captureState, npmlog) {
297
+ const input = process.stdin;
298
+ const output = process.stderr;
299
+ return new Promise((resolve, reject) => {
300
+ const server = _nodeNet
301
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
302
+ .createServer(async conn => {
303
+ if (captureState.captured) {
304
+ await new Promise(resolve => {
305
+ captureState.pendingCaptures.push({
306
+ resolve() {
307
+ resolve();
308
+ }
309
+ });
310
+ });
311
+ } else {
312
+ captureState.captured = true;
313
+ }
314
+ const wasProgressEnabled = npmlog.progressEnabled;
315
+ npmlog.pause();
316
+ if (wasProgressEnabled) {
317
+ npmlog.disableProgress();
318
+ }
319
+ conn.write(`${JSON.stringify({
320
+ ipc_version: _package.version,
321
+ capabilities: {
322
+ input: Boolean(input),
323
+ output: true,
324
+ colorLevel
325
+ }
326
+ })}\n`);
327
+ conn.on('data', data => {
328
+ output.write(data);
329
+ }).on('error', e => {
330
+ output.write(`there was an error prompting from a sub shell (${e?.message}), socket npm closing`);
331
+ process.exit(1);
332
+ });
333
+ input.on('data', data => {
334
+ conn.write(data);
335
+ }).on('end', () => {
336
+ conn.unref();
337
+ conn.end();
338
+ if (wasProgressEnabled) {
339
+ npmlog.enableProgress();
340
+ }
341
+ npmlog.resume();
342
+ captureState.nextCapture();
343
+ });
344
+ }).listen(sock, () => resolve(server)).on('error', reject).unref();
345
+ process.on('exit', () => {
346
+ server.close();
347
+ tryUnlinkSync(sock);
348
+ });
349
+ resolve(server);
350
+ });
351
+ }
352
+ function createStandardTTYServer(colorLevel, isInteractive, npmlog) {
353
+ const captureState = {
354
+ captured: false,
355
+ nextCapture: () => {
356
+ if (captureState.pendingCaptures.length > 0) {
357
+ const pendingCapture = captureState.pendingCaptures.shift();
358
+ pendingCapture?.resolve();
359
+ } else {
360
+ captureState.captured = false;
361
+ }
362
+ },
363
+ pendingCaptures: []
364
+ };
365
+ tryUnlinkSync(sock);
366
+ const input = isInteractive ? process.stdin : undefined;
367
+ const output = process.stderr;
368
+ let ipcServerPromise;
369
+ if (input) {
370
+ ipcServerPromise = createIPCServer(colorLevel, captureState, npmlog);
371
+ }
372
+ return {
373
+ async captureTTY(mutexFn) {
374
+ await ipcServerPromise;
375
+ if (captureState.captured) {
376
+ const captured = new Promise(resolve => {
377
+ captureState.pendingCaptures.push({
378
+ resolve() {
379
+ resolve();
380
+ }
381
+ });
382
+ });
383
+ await captured;
384
+ } else {
385
+ captureState.captured = true;
386
+ }
387
+ const wasProgressEnabled = npmlog.progressEnabled;
388
+ try {
389
+ npmlog.pause();
390
+ if (wasProgressEnabled) {
391
+ npmlog.disableProgress();
392
+ }
393
+ return await mutexFn(colorLevel, input, output);
394
+ } finally {
395
+ if (wasProgressEnabled) {
396
+ npmlog.enableProgress();
397
+ }
398
+ npmlog.resume();
399
+ captureState.nextCapture();
400
+ }
401
+ }
402
+ };
403
+ }
404
+ function tryUnlinkSync(filepath) {
405
+ try {
406
+ (0, _nodeFs$2.unlinkSync)(filepath);
407
+ } catch (e) {
408
+ if ((0, _misc$1.isErrnoException)(e) && e.code !== 'ENOENT') {
409
+ throw e;
410
+ }
411
+ }
412
+ }
413
+ function createTTYServer(colorLevel, isInteractive, npmlog) {
414
+ return !isInteractive && TTY_IPC ? createNonStandardTTYServer() : createStandardTTYServer(colorLevel, isInteractive, npmlog);
415
+ }
416
+
417
+ var issueRules = {};
418
+
419
+ Object.defineProperty(issueRules, "__esModule", {
420
+ value: true
421
+ });
422
+ issueRules.createIssueUXLookup = createIssueUXLookup;
423
+ //#region UX Constants
424
+
425
+ const IGNORE_UX = {
426
+ block: false,
427
+ display: false
428
+ };
429
+ const WARN_UX = {
430
+ block: false,
431
+ display: true
432
+ };
433
+ const ERROR_UX = {
434
+ block: true,
435
+ display: true
436
+ };
437
+ //#endregion
438
+ //#region utils
439
+
440
+ /**
441
+ * Iterates over all entries with ordered issue rule for deferral. Iterates over
442
+ * all issue rules and finds the first defined value that does not defer otherwise
443
+ * uses the defaultValue. Takes the value and converts into a UX workflow
444
+ */
445
+ function resolveIssueRuleUX(entriesOrderedIssueRules, defaultValue) {
446
+ if (defaultValue === true || defaultValue == null) {
447
+ defaultValue = {
448
+ action: 'error'
449
+ };
450
+ } else if (defaultValue === false) {
451
+ defaultValue = {
452
+ action: 'ignore'
453
+ };
454
+ }
455
+ let block = false;
456
+ let display = false;
457
+ let needDefault = true;
458
+ iterate_entries: for (const issueRuleArr of entriesOrderedIssueRules) {
459
+ for (const rule of issueRuleArr) {
460
+ if (issueRuleValueDoesNotDefer(rule)) {
461
+ needDefault = false;
462
+ const narrowingFilter = uxForDefinedNonDeferValue(rule);
463
+ block = block || narrowingFilter.block;
464
+ display = display || narrowingFilter.display;
465
+ continue iterate_entries;
466
+ }
467
+ }
468
+ const narrowingFilter = uxForDefinedNonDeferValue(defaultValue);
469
+ block = block || narrowingFilter.block;
470
+ display = display || narrowingFilter.display;
471
+ }
472
+ if (needDefault) {
473
+ const narrowingFilter = uxForDefinedNonDeferValue(defaultValue);
474
+ block = block || narrowingFilter.block;
475
+ display = display || narrowingFilter.display;
476
+ }
477
+ return {
478
+ block,
479
+ display
480
+ };
481
+ }
482
+
483
+ /**
484
+ * Negative form because it is narrowing the type
485
+ */
486
+ function issueRuleValueDoesNotDefer(issueRule) {
487
+ if (issueRule === undefined) {
488
+ return false;
489
+ } else if (typeof issueRule === 'object' && issueRule) {
490
+ const {
491
+ action
492
+ } = issueRule;
493
+ if (action === undefined || action === 'defer') {
494
+ return false;
495
+ }
496
+ }
497
+ return true;
498
+ }
499
+
500
+ /**
501
+ * Handles booleans for backwards compatibility
502
+
503
+ */
504
+ function uxForDefinedNonDeferValue(issueRuleValue) {
505
+ if (typeof issueRuleValue === 'boolean') {
506
+ return issueRuleValue ? ERROR_UX : IGNORE_UX;
507
+ }
508
+ const {
509
+ action
510
+ } = issueRuleValue;
511
+ if (action === 'warn') {
512
+ return WARN_UX;
513
+ } else if (action === 'ignore') {
514
+ return IGNORE_UX;
515
+ }
516
+ return ERROR_UX;
517
+ }
518
+ //#endregion
519
+
520
+ //#region exports
521
+
522
+ function createIssueUXLookup(settings) {
523
+ const cachedUX = new Map();
524
+ return context => {
525
+ const key = context.issue.type;
526
+ let ux = cachedUX.get(key);
527
+ if (ux) {
528
+ return ux;
529
+ }
530
+ const entriesOrderedIssueRules = [];
531
+ for (const settingsEntry of settings.entries) {
532
+ const orderedIssueRules = [];
533
+ let target = settingsEntry.start;
534
+ while (target !== null) {
535
+ const resolvedTarget = settingsEntry.settings[target];
536
+ if (!resolvedTarget) {
537
+ break;
538
+ }
539
+ const issueRuleValue = resolvedTarget.issueRules?.[key];
540
+ if (typeof issueRuleValue !== 'undefined') {
541
+ orderedIssueRules.push(issueRuleValue);
542
+ }
543
+ target = resolvedTarget.deferTo ?? null;
544
+ }
545
+ entriesOrderedIssueRules.push(orderedIssueRules);
546
+ }
547
+ const defaultValue = settings.defaults.issueRules[key];
548
+ let resolvedDefaultValue = {
549
+ action: 'error'
550
+ };
551
+ if (defaultValue === false) {
552
+ resolvedDefaultValue = {
553
+ action: 'ignore'
554
+ };
555
+ } else if (defaultValue && defaultValue !== true) {
556
+ resolvedDefaultValue = {
557
+ action: defaultValue.action ?? 'error'
558
+ };
559
+ }
560
+ ux = resolveIssueRuleUX(entriesOrderedIssueRules, resolvedDefaultValue);
561
+ cachedUX.set(key, ux);
562
+ return ux;
563
+ };
564
+ }
565
+
566
+ var _interopRequireWildcard = vendor.interopRequireWildcard.default;
567
+ var _interopRequireDefault = vendor.interopRequireDefault.default;
568
+ Object.defineProperty(arborist, "__esModule", {
569
+ value: true
570
+ });
571
+ arborist.SafeArborist = void 0;
572
+ arborist.installSafeArborist = installSafeArborist;
573
+ var _nodeEvents = require$$0$1;
574
+ var _nodeFs$1 = require$$0;
575
+ var _nodeHttps = require$$4;
576
+ var _nodePath$1 = require$$1;
577
+ var _nodeReadline = require$$3;
578
+ var _nodeStream = require$$1$2;
579
+ var _promises = require$$8;
580
+ var _config = require$$3$1;
581
+ var _chalk = _interopRequireDefault(vendor.source);
582
+ var _isInteractive = _interopRequireDefault(vendor.isInteractive);
583
+ var _ora = _interopRequireWildcard(vendor.ora);
584
+ var _ttyServer = ttyServer$1;
585
+ var _chalkMarkdown = sdk.chalkMarkdown;
586
+ var _issueRules = issueRules;
587
+ var _misc = sdk.misc;
588
+ var _pathResolve = pathResolve.pathResolve;
589
+ var _sdk = sdk.sdk;
590
+ var _settings = sdk.settings;
591
+ var _constants = sdk.constants;
592
+ const LOOP_SENTINEL = 1_000_000;
593
+ const POTENTIALLY_BUG_ERROR_SNIPPET = 'this is potentially a bug with socket-npm caused by changes to the npm cli';
594
+ const distPath$1 = __dirname;
595
+ const rootPath$1 = _nodePath$1.resolve(distPath$1, '..');
596
+ const translations = require(_nodePath$1.join(rootPath$1, 'translations.json'));
597
+ const npmEntrypoint = (0, _nodeFs$1.realpathSync)(`${process.argv[1]}`);
598
+ const npmRootPath = (0, _pathResolve.findRoot)(_nodePath$1.dirname(npmEntrypoint));
599
+ const abortController = new AbortController();
600
+ const {
601
+ signal: abortSignal
602
+ } = abortController;
603
+ if (npmRootPath === undefined) {
604
+ console.error(`Unable to find npm cli install directory, ${POTENTIALLY_BUG_ERROR_SNIPPET}.`);
605
+ console.error(`Searched parent directories of ${npmEntrypoint}`);
606
+ process.exit(127);
607
+ }
608
+ const npmNmPath = _nodePath$1.join(npmRootPath, 'node_modules');
609
+ const arboristClassPath = _nodePath$1.join(npmNmPath, '@npmcli/arborist/lib/arborist/index.js');
610
+ const arboristEdgeClassPath = _nodePath$1.join(npmNmPath, '@npmcli/arborist/lib/edge.js');
611
+ let npmlog;
612
+ try {
613
+ npmlog = require(_nodePath$1.join(npmNmPath, 'proc-log/lib/index.js')).log;
614
+ } catch {}
615
+ if (npmlog === undefined) {
616
+ try {
617
+ npmlog = require(_nodePath$1.join(npmNmPath, 'npmlog/lib/log.js'));
618
+ } catch {}
619
+ }
620
+ if (npmlog === undefined) {
621
+ console.error(`Unable to integrate with npm cli logging infrastructure, ${POTENTIALLY_BUG_ERROR_SNIPPET}.`);
622
+ process.exit(127);
623
+ }
624
+ let tarball;
625
+ try {
626
+ tarball = require(_nodePath$1.join(npmNmPath, 'pacote')).tarball;
627
+ } catch {
628
+ tarball = require$$21.tarball;
629
+ }
630
+ const Arborist = require(arboristClassPath);
631
+ const Edge = require(arboristEdgeClassPath);
632
+ const kCtorArgs = Symbol('ctorArgs');
633
+ const kRiskyReify = Symbol('riskyReify');
634
+ const formatter = new _chalkMarkdown.ChalkOrMarkdown(false);
635
+ const pubToken = (0, _sdk.getDefaultKey)() ?? _sdk.FREE_API_KEY;
636
+ const ttyServer = (0, _ttyServer.createTTYServer)(_chalk.default.level, (0, _isInteractive.default)({
637
+ stream: process.stdin
638
+ }), npmlog);
639
+ let _uxLookup;
640
+ async function uxLookup(settings) {
641
+ while (_uxLookup === undefined) {
642
+ await (0, _promises.setTimeout)(1, {
643
+ signal: abortSignal
644
+ });
645
+ }
646
+ return _uxLookup(settings);
647
+ }
648
+ async function* batchScan(pkgIds) {
649
+ const query = {
650
+ packages: pkgIds.map(pkgid => {
651
+ const {
652
+ name,
653
+ version
654
+ } = pkgidParts(pkgid);
655
+ return {
656
+ eco: 'npm',
657
+ pkg: name,
658
+ ver: version,
659
+ top: true
660
+ };
661
+ })
662
+ };
663
+ // TODO: Migrate to SDK.
664
+ const pkgDataReq = _nodeHttps.request(`${_constants.API_V0_URL}/scan/batch`, {
665
+ method: 'POST',
666
+ headers: {
667
+ Authorization: `Basic ${Buffer.from(`${pubToken}:`).toString('base64url')}`
668
+ },
669
+ signal: abortSignal
670
+ }).end(JSON.stringify(query));
671
+ const {
672
+ 0: res
673
+ } = await _nodeEvents.once(pkgDataReq, 'response');
674
+ const ok = res.statusCode >= 200 && res.statusCode <= 299;
675
+ if (!ok) {
676
+ throw new Error(`Socket API Error: ${res.statusCode}`);
677
+ }
678
+ const rli = _nodeReadline.createInterface(res);
679
+ for await (const line of rli) {
680
+ yield JSON.parse(line);
681
+ }
682
+ }
683
+ function deleteEdgeIn(node, edge) {
684
+ node.edgesIn.delete(edge);
685
+ const {
686
+ overrides
687
+ } = edge;
688
+ if (overrides) {
689
+ updateNodeOverrideSetDueToEdgeRemoval(node, overrides);
690
+ }
691
+ }
692
+ function findSocketYmlSync() {
693
+ let prevDir = null;
694
+ let dir = process.cwd();
695
+ while (dir !== prevDir) {
696
+ let ymlPath = _nodePath$1.join(dir, 'socket.yml');
697
+ let yml = maybeReadfileSync(ymlPath);
698
+ if (yml === undefined) {
699
+ ymlPath = _nodePath$1.join(dir, 'socket.yaml');
700
+ yml = maybeReadfileSync(ymlPath);
701
+ }
702
+ if (typeof yml === 'string') {
703
+ try {
704
+ return {
705
+ path: ymlPath,
706
+ parsed: _config.parseSocketConfig(yml)
707
+ };
708
+ } catch {
709
+ throw new Error(`Found file but was unable to parse ${ymlPath}`);
710
+ }
711
+ }
712
+ prevDir = dir;
713
+ dir = _nodePath$1.join(dir, '..');
714
+ }
715
+ return null;
716
+ }
717
+ function findSpecificOverrideSet(first, second) {
718
+ let overrideSet = second;
719
+ while (overrideSet) {
720
+ if (overrideSetsEqual(overrideSet, first)) {
721
+ return second;
722
+ }
723
+ overrideSet = overrideSet.parent;
724
+ }
725
+ overrideSet = first;
726
+ while (overrideSet) {
727
+ if (overrideSetsEqual(overrideSet, second)) {
728
+ return first;
729
+ }
730
+ overrideSet = overrideSet.parent;
731
+ }
732
+ console.error('Conflicting override sets');
733
+ return undefined;
734
+ }
735
+ function maybeReadfileSync(filepath) {
736
+ try {
737
+ return (0, _nodeFs$1.readFileSync)(filepath, 'utf8');
738
+ } catch {}
739
+ return undefined;
740
+ }
741
+ function overrideSetsChildrenAreEqual(overrideSet, other) {
742
+ const queue = [[overrideSet, other]];
743
+ let pos = 0;
744
+ let {
745
+ length: queueLength
746
+ } = queue;
747
+ while (pos < queueLength) {
748
+ if (pos === LOOP_SENTINEL) {
749
+ throw new Error('Detected infinite loop while comparing override sets');
750
+ }
751
+ const {
752
+ 0: currSet,
753
+ 1: currOtherSet
754
+ } = queue[pos++];
755
+ const {
756
+ children
757
+ } = currSet;
758
+ const {
759
+ children: otherChildren
760
+ } = currOtherSet;
761
+ if (children.size !== otherChildren.size) {
762
+ return false;
763
+ }
764
+ for (const key of children.keys()) {
765
+ if (!otherChildren.has(key)) {
766
+ return false;
767
+ }
768
+ const child = children.get(key);
769
+ const otherChild = otherChildren.get(key);
770
+ if (child.value !== otherChild.value) {
771
+ return false;
772
+ }
773
+ queue[queueLength++] = [child, otherChild];
774
+ }
775
+ }
776
+ return true;
777
+ }
778
+ function overrideSetsEqual(overrideSet, other) {
779
+ if (overrideSet === other) {
780
+ return true;
781
+ }
782
+ if (!other) {
783
+ return false;
784
+ }
785
+ if (overrideSet.key !== other.key || overrideSet.value !== other.value) {
786
+ return false;
787
+ }
788
+ if (!overrideSetsChildrenAreEqual(overrideSet, other)) {
789
+ return false;
790
+ }
791
+ if (!overrideSet.parent) {
792
+ return !other.parent;
793
+ }
794
+ return overrideSetsEqual(overrideSet.parent, other.parent);
795
+ }
796
+ async function packagesHaveRiskyIssues(safeArb, _registry, pkgs, output) {
797
+ let result = false;
798
+ let remaining = pkgs.length;
799
+ if (!remaining) {
800
+ (0, _ora.default)('').succeed('No changes detected');
801
+ return result;
802
+ }
803
+ const getText = () => `Looking up data for ${remaining} packages`;
804
+ const spinner = (0, _ora.default)({
805
+ color: 'cyan',
806
+ stream: output,
807
+ isEnabled: true,
808
+ isSilent: false,
809
+ hideCursor: true,
810
+ discardStdin: true,
811
+ spinner: _ora.spinners.dots
812
+ }).start(getText());
813
+ try {
814
+ for await (const pkgData of batchScan(pkgs.map(pkg => pkg.pkgid))) {
815
+ let failures = [];
816
+ let displayWarning = false;
817
+ const name = pkgData.pkg;
818
+ const version = pkgData.ver;
819
+ const id = `${name}@${version}`;
820
+ if (pkgData.type === 'missing') {
821
+ result = true;
822
+ failures.push({
823
+ type: 'missingDependency'
824
+ });
825
+ } else {
826
+ let blocked = false;
827
+ for (const failure of pkgData.value.issues) {
828
+ const ux = await uxLookup({
829
+ package: {
830
+ name,
831
+ version
832
+ },
833
+ issue: {
834
+ type: failure.type
835
+ }
836
+ });
837
+ if (ux.display || ux.block) {
838
+ failures.push({
839
+ raw: failure,
840
+ block: ux.block
841
+ });
842
+ // Before we ask about problematic issues, check to see if they
843
+ // already existed in the old version if they did, be quiet.
844
+ const pkg = pkgs.find(pkg => pkg.pkgid === id && pkg.existing?.startsWith(`${name}@`));
845
+ if (pkg?.existing) {
846
+ for await (const oldPkgData of batchScan([pkg.existing])) {
847
+ if (oldPkgData.type === 'success') {
848
+ failures = failures.filter(issue => oldPkgData.value.issues.find(oldIssue => oldIssue.type === issue.raw.type) == null);
849
+ }
850
+ }
851
+ }
852
+ }
853
+ if (ux.block) {
854
+ result = true;
855
+ blocked = true;
856
+ }
857
+ if (ux.display) {
858
+ displayWarning = true;
859
+ }
860
+ }
861
+ if (!blocked) {
862
+ const pkg = pkgs.find(pkg => pkg.pkgid === id);
863
+ if (pkg) {
864
+ await tarball.stream(id, stream => {
865
+ stream.resume();
866
+ return stream.promise();
867
+ }, {
868
+ ...safeArb[kCtorArgs][0]
869
+ });
870
+ }
871
+ }
872
+ }
873
+ if (displayWarning) {
874
+ spinner.stop();
875
+ output?.write(`(socket) ${formatter.hyperlink(id, `https://socket.dev/npm/package/${name}/overview/${version}`)} contains risks:\n`);
876
+ failures.sort((a, b) => a.raw.type < b.raw.type ? -1 : 1);
877
+ const lines = new Set();
878
+ for (const failure of failures) {
879
+ const type = failure.raw.type;
880
+ if (type) {
881
+ const issueTypeTranslation = translations.issues[type];
882
+ // TODO: emoji seems to mis-align terminals sometimes
883
+ lines.add(` ${issueTypeTranslation?.title ?? type}${failure.block ? '' : ' (non-blocking)'} - ${issueTypeTranslation?.description ?? ''}\n`);
884
+ }
885
+ }
886
+ for (const line of lines) {
887
+ output?.write(line);
888
+ }
889
+ spinner.start();
890
+ }
891
+ remaining -= 1;
892
+ spinner.text = remaining > 0 ? getText() : '';
893
+ }
894
+ return result;
895
+ } finally {
896
+ if (spinner.isSpinning) {
897
+ spinner.stop();
898
+ }
899
+ }
900
+ }
901
+ function pkgidParts(pkgid) {
902
+ const delimiter = pkgid.lastIndexOf('@');
903
+ const name = pkgid.slice(0, delimiter);
904
+ const version = pkgid.slice(delimiter + 1);
905
+ return {
906
+ name,
907
+ version
908
+ };
909
+ }
910
+ function recalculateOutEdgesOverrides(node) {
911
+ // For each edge out propagate the new overrides through.
912
+ for (const edge of node.edgesOut.values()) {
913
+ edge.reload(true);
914
+ if (edge.to) {
915
+ updateNodeOverrideSet(edge.to, edge.overrides);
916
+ }
917
+ }
918
+ }
919
+ function toPURL(pkgid, resolved) {
920
+ const repo = resolved.replace(/#[\s\S]*$/u, '').replace(/\?[\s\S]*$/u, '').replace(/\/[^/]*\/-\/[\s\S]*$/u, '');
921
+ const {
922
+ name,
923
+ version
924
+ } = pkgidParts(pkgid);
925
+ return {
926
+ type: 'npm',
927
+ namespace_and_name: name,
928
+ version,
929
+ repository_url: repo
930
+ };
931
+ }
932
+ function updateNodeOverrideSetDueToEdgeRemoval(node, other) {
933
+ const {
934
+ overrides
935
+ } = node;
936
+ // If this edge's overrides isn't equal to this node's overrides, then removing
937
+ // it won't change newOverrideSet later.
938
+ if (!overrides || !overrideSetsEqual(overrides, other)) {
939
+ return false;
940
+ }
941
+ let newOverrideSet;
942
+ for (const edge of node.edgesIn) {
943
+ const {
944
+ overrides: edgeOverrides
945
+ } = edge;
946
+ if (newOverrideSet) {
947
+ newOverrideSet = findSpecificOverrideSet(edgeOverrides, newOverrideSet);
948
+ } else {
949
+ newOverrideSet = edgeOverrides;
950
+ }
951
+ }
952
+ if (overrideSetsEqual(overrides, newOverrideSet)) {
953
+ return false;
954
+ }
955
+ node.overrides = newOverrideSet;
956
+ if (newOverrideSet) {
957
+ // Optimization: If there's any override set at all, then no non-extraneous
958
+ // node has an empty override set. So if we temporarily have no override set
959
+ // (for example, we removed all the edges in), there's no use updating all
960
+ // the edges out right now. Let's just wait until we have an actual override
961
+ // set later.
962
+ recalculateOutEdgesOverrides(node);
963
+ }
964
+ return true;
965
+ }
966
+
967
+ // This logic isn't perfect either. When we have two edges in that have different
968
+ // override sets, then we have to decide which set is correct. This function
969
+ // assumes the more specific override set is applicable, so if we have dependencies
970
+ // A->B->C and A->C and an override set that specifies what happens for C under
971
+ // A->B, this will work even if the new A->C edge comes along and tries to change
972
+ // the override set. The strictly correct logic is not to allow two edges with
973
+ // different overrides to point to the same node, because even if this node can
974
+ // satisfy both, one of its dependencies might need to be different depending on
975
+ // the edge leading to it. However, this might cause a lot of duplication, because
976
+ // the conflict in the dependencies might never actually happen.
977
+ function updateNodeOverrideSet(node, otherOverrideSet) {
978
+ if (!node.overrides) {
979
+ // Assuming there are any overrides at all, the overrides field is never
980
+ // undefined for any node at the end state of the tree. So if the new edge's
981
+ // overrides is undefined it will be updated later. So we can wait with
982
+ // updating the node's overrides field.
983
+ if (!otherOverrideSet) {
984
+ return false;
985
+ }
986
+ node.overrides = otherOverrideSet;
987
+ recalculateOutEdgesOverrides(node);
988
+ return true;
989
+ }
990
+ const {
991
+ overrides
992
+ } = node;
993
+ if (overrideSetsEqual(overrides, otherOverrideSet)) {
994
+ return false;
995
+ }
996
+ const newOverrideSet = findSpecificOverrideSet(overrides, otherOverrideSet);
997
+ if (newOverrideSet) {
998
+ if (overrideSetsEqual(overrides, newOverrideSet)) {
999
+ return false;
1000
+ }
1001
+ node.overrides = newOverrideSet;
1002
+ recalculateOutEdgesOverrides(node);
1003
+ return true;
1004
+ }
1005
+ // This is an error condition. We can only get here if the new override set is
1006
+ // in conflict with the existing.
1007
+ console.error('Conflicting override sets');
1008
+ return false;
1009
+ }
1010
+ function walk(diff_, needInfoOn = []) {
1011
+ const queue = [diff_];
1012
+ let pos = 0;
1013
+ let {
1014
+ length: queueLength
1015
+ } = queue;
1016
+ while (pos < queueLength) {
1017
+ if (pos === LOOP_SENTINEL) {
1018
+ throw new Error('Detected infinite loop while walking Arborist diff');
1019
+ }
1020
+ const diff = queue[pos++];
1021
+ if (!diff) {
1022
+ continue;
1023
+ }
1024
+ if (diff.action) {
1025
+ const sameVersion = diff.actual?.package.version === diff.ideal?.package.version;
1026
+ let keep = false;
1027
+ let existing = null;
1028
+ if (diff.action === 'CHANGE') {
1029
+ if (!sameVersion) {
1030
+ existing = diff.actual.pkgid;
1031
+ keep = true;
1032
+ }
1033
+ } else {
1034
+ keep = diff.action !== 'REMOVE';
1035
+ }
1036
+ if (keep && diff.ideal?.pkgid && diff.ideal.resolved && (!diff.actual || diff.actual.resolved)) {
1037
+ needInfoOn.push({
1038
+ existing,
1039
+ action: diff.action,
1040
+ location: diff.ideal.location,
1041
+ pkgid: diff.ideal.pkgid,
1042
+ newPackage: toPURL(diff.ideal.pkgid, diff.ideal.resolved),
1043
+ oldPackage: diff.actual && diff.actual.resolved ? toPURL(diff.actual.pkgid, diff.actual.resolved) : null,
1044
+ resolved: diff.ideal.resolved
1045
+ });
1046
+ }
1047
+ }
1048
+ if (diff.children) {
1049
+ for (const child of diff.children) {
1050
+ queue[queueLength++] = child;
1051
+ }
1052
+ }
1053
+ }
1054
+ return needInfoOn;
1055
+ }
1056
+
1057
+ // Copied from
1058
+ // https://github.com/npm/cli/blob/v10.9.0/workspaces/arborist/lib/edge.js:
1059
+ // The npm application
1060
+ // Copyright (c) npm, Inc. and Contributors
1061
+ // Licensed on the terms of The Artistic License 2.0
1062
+ //
1063
+ // An edge in the dependency graph.
1064
+ // Represents a dependency relationship of some kind.
1065
+
1066
+ class SafeEdge extends Edge {
1067
+ #safeAccept;
1068
+ #safeError;
1069
+ #safeExplanation;
1070
+ #safeFrom;
1071
+ #safeTo;
1072
+ constructor(options) {
1073
+ const {
1074
+ accept,
1075
+ from
1076
+ } = options;
1077
+ // Defer to supper to validate options and assign non-private values.
1078
+ super(options);
1079
+ if (accept !== undefined) {
1080
+ this.#safeAccept = accept || '*';
1081
+ }
1082
+ this.#safeError = null;
1083
+ this.#safeExplanation = null;
1084
+ this.#safeFrom = from;
1085
+ this.#safeTo = null;
1086
+ this.reload(true);
1087
+ }
1088
+
1089
+ // Return the edge data, and an explanation of how that edge came to be here.
1090
+ // @ts-ignore: Edge#explain is defined with an unused `seen = []` param.
1091
+ explain() {
1092
+ if (!this.#safeExplanation) {
1093
+ const explanation = {
1094
+ type: this.type,
1095
+ name: this.name,
1096
+ spec: this.spec,
1097
+ bundled: false,
1098
+ overridden: false,
1099
+ error: undefined,
1100
+ from: undefined,
1101
+ rawSpec: undefined
1102
+ };
1103
+ if (this.rawSpec !== this.spec) {
1104
+ explanation.rawSpec = this.rawSpec;
1105
+ explanation.overridden = true;
1106
+ }
1107
+ if (this.bundled) {
1108
+ explanation.bundled = this.bundled;
1109
+ }
1110
+ if (this.error) {
1111
+ explanation.error = this.error;
1112
+ }
1113
+ if (this.#safeFrom) {
1114
+ explanation.from = this.#safeFrom.explain();
1115
+ }
1116
+ this.#safeExplanation = explanation;
1117
+ }
1118
+ return this.#safeExplanation;
1119
+ }
1120
+ get bundled() {
1121
+ return !!this.#safeFrom?.package?.bundleDependencies?.includes(this.name);
1122
+ }
1123
+
1124
+ // @ts-ignore: Incorrectly typed as a property instead of an accessor.
1125
+ get spec() {
1126
+ if (this.overrides?.value && this.overrides.value !== '*' && this.overrides.name === this.name) {
1127
+ if (this.overrides.value.startsWith('$')) {
1128
+ const ref = this.overrides.value.slice(1);
1129
+ // We may be a virtual root, if we are we want to resolve reference
1130
+ // overrides from the real root, not the virtual one.
1131
+ const pkg = this.#safeFrom?.sourceReference ? this.#safeFrom.sourceReference.root.package : this.#safeFrom?.root.package;
1132
+ if (pkg?.devDependencies?.[ref]) {
1133
+ return pkg.devDependencies[ref];
1134
+ }
1135
+ if (pkg?.optionalDependencies?.[ref]) {
1136
+ return pkg.optionalDependencies[ref];
1137
+ }
1138
+ if (pkg?.dependencies?.[ref]) {
1139
+ return pkg.dependencies[ref];
1140
+ }
1141
+ if (pkg?.peerDependencies?.[ref]) {
1142
+ return pkg.peerDependencies[ref];
1143
+ }
1144
+ throw new Error(`Unable to resolve reference ${this.overrides.value}`);
1145
+ }
1146
+ return this.overrides.value;
1147
+ }
1148
+ return this.rawSpec;
1149
+ }
1150
+ get accept() {
1151
+ return this.#safeAccept;
1152
+ }
1153
+ get error() {
1154
+ if (!this.#safeError) {
1155
+ if (!this.#safeTo) {
1156
+ if (this.optional) {
1157
+ this.#safeError = null;
1158
+ } else {
1159
+ this.#safeError = 'MISSING';
1160
+ }
1161
+ } else if (this.peer && this.#safeFrom === this.#safeTo.parent && !this.#safeFrom?.isTop) {
1162
+ this.#safeError = 'PEER LOCAL';
1163
+ } else if (!this.satisfiedBy(this.#safeTo)) {
1164
+ this.#safeError = 'INVALID';
1165
+ } else {
1166
+ this.#safeError = 'OK';
1167
+ }
1168
+ }
1169
+ if (this.#safeError === 'OK') {
1170
+ return null;
1171
+ }
1172
+ return this.#safeError;
1173
+ }
1174
+ reload(hard = false) {
1175
+ this.#safeExplanation = null;
1176
+ if (this.#safeFrom?.overrides) {
1177
+ this.overrides = this.#safeFrom.overrides.getEdgeRule(this);
1178
+ } else {
1179
+ this.overrides = undefined;
1180
+ }
1181
+ const newTo = this.#safeFrom?.resolve(this.name);
1182
+ if (newTo !== this.#safeTo) {
1183
+ if (this.#safeTo) {
1184
+ // Instead of `this.#safeTo.edgesIn.delete(this)` we patch based on
1185
+ // https://github.com/npm/cli/pull/7025.
1186
+ deleteEdgeIn(this.#safeTo, this);
1187
+ }
1188
+ this.#safeTo = newTo ?? null;
1189
+ this.#safeError = null;
1190
+ if (this.#safeTo) {
1191
+ this.#safeTo.addEdgeIn(this);
1192
+ }
1193
+ } else if (hard) {
1194
+ this.#safeError = null;
1195
+ }
1196
+ }
1197
+ detach() {
1198
+ this.#safeExplanation = null;
1199
+ if (this.#safeTo) {
1200
+ // Instead of `this.#safeTo.edgesIn.delete(this)` we patch based on
1201
+ // https://github.com/npm/cli/pull/7025.
1202
+ deleteEdgeIn(this.#safeTo, this);
1203
+ }
1204
+ if (this.#safeFrom) {
1205
+ this.#safeFrom.edgesOut.delete(this.name);
1206
+ }
1207
+ this.#safeTo = null;
1208
+ this.#safeError = 'DETACHED';
1209
+ this.#safeFrom = null;
1210
+ }
1211
+
1212
+ // @ts-ignore: Incorrectly typed as a property instead of an accessor.
1213
+ get from() {
1214
+ return this.#safeFrom;
1215
+ }
1216
+
1217
+ // @ts-ignore: Incorrectly typed as a property instead of an accessor.
1218
+ get to() {
1219
+ return this.#safeTo;
1220
+ }
1221
+ }
1222
+ class SafeArborist extends Arborist {
1223
+ constructor(...ctorArgs) {
1224
+ const mutedArguments = [{
1225
+ ...ctorArgs[0],
1226
+ audit: true,
1227
+ dryRun: true,
1228
+ ignoreScripts: true,
1229
+ save: false,
1230
+ saveBundle: false,
1231
+ // progress: false,
1232
+ fund: false
1233
+ }, ctorArgs.slice(1)];
1234
+ super(...mutedArguments);
1235
+ this[kCtorArgs] = ctorArgs;
1236
+ }
1237
+ async [kRiskyReify](...args) {
1238
+ // SafeArborist has suffered side effects and must be rebuilt from scratch.
1239
+ const arb = new Arborist(...this[kCtorArgs]);
1240
+ const ret = await arb.reify(...args);
1241
+ Object.assign(this, arb);
1242
+ return ret;
1243
+ }
1244
+
1245
+ // @ts-ignore Incorrectly typed.
1246
+ async reify(...args) {
1247
+ const options = args[0] ? {
1248
+ ...args[0]
1249
+ } : {};
1250
+ if (options.dryRun) {
1251
+ return await this[kRiskyReify](...args);
1252
+ }
1253
+ const old = {
1254
+ ...options,
1255
+ dryRun: false,
1256
+ save: Boolean(options['save'] ?? true),
1257
+ saveBundle: Boolean(options['saveBundle'] ?? false)
1258
+ };
1259
+ args[0] = options;
1260
+ options.dryRun = true;
1261
+ options['save'] = false;
1262
+ options['saveBundle'] = false;
1263
+ // TODO: Make this deal w/ any refactor to private fields by punching the
1264
+ // class itself.
1265
+ await super.reify(...args);
1266
+ const diff = walk(this['diff']);
1267
+ options.dryRun = old.dryRun;
1268
+ options['save'] = old.save;
1269
+ options['saveBundle'] = old.saveBundle;
1270
+ // Nothing to check, mmm already installed or all private?
1271
+ if (diff.findIndex(c => c.newPackage.repository_url === 'https://registry.npmjs.org') === -1) {
1272
+ return await this[kRiskyReify](...args);
1273
+ }
1274
+ let proceed = _constants.ENV.UPDATE_SOCKET_OVERRIDES_IN_PACKAGE_LOCK_FILE;
1275
+ if (!proceed) {
1276
+ proceed = await ttyServer.captureTTY(async (colorLevel, input, output) => {
1277
+ _chalk.default.level = colorLevel;
1278
+ if (input && output) {
1279
+ const risky = await packagesHaveRiskyIssues(this, this['registry'], diff, output);
1280
+ if (!risky) {
1281
+ return true;
1282
+ }
1283
+ const rlin = new _nodeStream.PassThrough();
1284
+ input.pipe(rlin);
1285
+ const rlout = new _nodeStream.PassThrough();
1286
+ rlout.pipe(output, {
1287
+ end: false
1288
+ });
1289
+ const rli = _nodeReadline.createInterface(rlin, rlout);
1290
+ try {
1291
+ while (true) {
1292
+ const answer = await new Promise(resolve => {
1293
+ rli.question('Accept risks of installing these packages (y/N)?\n', {
1294
+ signal: abortSignal
1295
+ }, resolve);
1296
+ });
1297
+ if (/^\s*y(?:es)?\s*$/i.test(answer)) {
1298
+ return true;
1299
+ }
1300
+ if (/^(?:\s*no?\s*|)$/i.test(answer)) {
1301
+ return false;
1302
+ }
1303
+ }
1304
+ } finally {
1305
+ rli.close();
1306
+ }
1307
+ } else if (await packagesHaveRiskyIssues(this, this['registry'], diff, output)) {
1308
+ throw new Error('Socket npm Unable to prompt to accept risk, need TTY to do so');
1309
+ }
1310
+ return true;
1311
+ });
1312
+ }
1313
+ if (proceed) {
1314
+ return await this[kRiskyReify](...args);
1315
+ } else {
1316
+ throw new Error('Socket npm exiting due to risks');
1317
+ }
1318
+ }
1319
+ }
1320
+ arborist.SafeArborist = SafeArborist;
1321
+ function installSafeArborist() {
1322
+ require.cache[arboristEdgeClassPath].exports = SafeEdge;
1323
+ require.cache[arboristClassPath].exports = SafeArborist;
1324
+ }
1325
+ void (async () => {
1326
+ const remoteSettings = await (async () => {
1327
+ try {
1328
+ const socketSdk = await (0, _sdk.setupSdk)(pubToken);
1329
+ const orgResult = await socketSdk.getOrganizations();
1330
+ if (!orgResult.success) {
1331
+ throw new Error('Failed to fetch Socket organization info: ' + orgResult.error.message);
1332
+ }
1333
+ const orgs = [];
1334
+ for (const org of Object.values(orgResult.data.organizations)) {
1335
+ if (org) {
1336
+ orgs.push(org);
1337
+ }
1338
+ }
1339
+ const result = await socketSdk.postSettings(orgs.map(org => {
1340
+ return {
1341
+ organization: org.id
1342
+ };
1343
+ }));
1344
+ if (!result.success) {
1345
+ throw new Error('Failed to fetch API key settings: ' + result.error.message);
1346
+ }
1347
+ return {
1348
+ orgs,
1349
+ settings: result.data
1350
+ };
1351
+ } catch (e) {
1352
+ if (typeof e === 'object' && e !== null && 'cause' in e) {
1353
+ const {
1354
+ cause
1355
+ } = e;
1356
+ if ((0, _misc.isErrnoException)(cause)) {
1357
+ if (cause.code === 'ENOTFOUND' || cause.code === 'ECONNREFUSED') {
1358
+ throw new Error('Unable to connect to socket.dev, ensure internet connectivity before retrying', {
1359
+ cause: e
1360
+ });
1361
+ }
1362
+ }
1363
+ }
1364
+ throw e;
1365
+ }
1366
+ })();
1367
+ const {
1368
+ orgs,
1369
+ settings
1370
+ } = remoteSettings;
1371
+ const enforcedOrgs = (0, _settings.getSetting)('enforcedOrgs') ?? [];
1372
+
1373
+ // remove any organizations not being enforced
1374
+ for (const {
1375
+ 0: i,
1376
+ 1: org
1377
+ } of orgs.entries()) {
1378
+ if (!enforcedOrgs.includes(org.id)) {
1379
+ settings.entries.splice(i, 1);
1380
+ }
1381
+ }
1382
+ const socketYml = findSocketYmlSync();
1383
+ if (socketYml) {
1384
+ settings.entries.push({
1385
+ start: socketYml.path,
1386
+ // @ts-ignore
1387
+ settings: {
1388
+ [socketYml.path]: {
1389
+ deferTo: null,
1390
+ issueRules: socketYml.parsed.issueRules
1391
+ }
1392
+ }
1393
+ });
1394
+ }
1395
+ _uxLookup = (0, _issueRules.createIssueUXLookup)(settings);
1396
+ })();
1397
+
1398
+ var _nodeFs = require$$0;
1399
+ var _nodePath = require$$1;
1400
+ var _link = link.link;
1401
+ var _arborist = arborist;
1402
+ const distPath = __dirname;
1403
+ const rootPath = _nodePath.resolve(distPath, '..');
1404
+ const binPath = _nodePath.join(rootPath, 'bin');
1405
+
1406
+ // shadow `npm` and `npx` to mitigate subshells
1407
+ (0, _link.installLinks)((0, _nodeFs.realpathSync)(binPath), 'npm');
1408
+ (0, _arborist.installSafeArborist)();
1409
+
1410
+ (function (exports) {
1411
+
1412
+ var _interopRequireWildcard = vendor.interopRequireWildcard.default;
1413
+ Object.defineProperty(exports, "__esModule", {
1414
+ value: true
1415
+ });
1416
+ var _exportNames = {};
1417
+ Object.defineProperty(exports, "default", {
1418
+ enumerable: true,
1419
+ get: function () {
1420
+ return _npmInjection.default;
1421
+ }
1422
+ });
1423
+ var _npmInjection = _interopRequireWildcard(npmInjection, true);
1424
+ Object.keys(_npmInjection).forEach(function (key) {
1425
+ if (key === "default" || key === "__esModule") return;
1426
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
1427
+ if (key in exports && exports[key] === _npmInjection[key]) return;
1428
+ Object.defineProperty(exports, key, {
1429
+ enumerable: true,
1430
+ get: function () {
1431
+ return _npmInjection[key];
1432
+ }
1433
+ });
1434
+ });
1435
+ } (npmInjection$1));
1436
+
1437
+ module.exports = npmInjection$1;