@socketsecurity/cli 0.14.39 → 0.14.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,6 @@ declare function findBinPathDetails(binName: string): Promise<{
8
8
  path: string | undefined;
9
9
  shadowed: boolean;
10
10
  }>;
11
- declare function getPackageFiles(cwd: string, inputPaths: string[], config: SocketYml | undefined, supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data'], debugLog?: typeof console.error): Promise<string[]>;
11
+ declare function getPackageFiles(cwd: string, inputPaths: string[], config: SocketYml | undefined, supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data']): Promise<string[]>;
12
12
  declare function getPackageFilesFullScans(cwd: string, inputPaths: string[], supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data'], debugLog?: typeof console.error): Promise<string[]>;
13
13
  export { directoryPatterns, findRoot, findBinPathDetails, getPackageFiles, getPackageFilesFullScans };
@@ -11,12 +11,56 @@ function _socketInterop(e) {
11
11
 
12
12
  var fs = require('node:fs');
13
13
  var path = require('node:path');
14
+ var process = require('node:process');
14
15
  var ignore = _socketInterop(require('ignore'));
15
16
  var micromatch = _socketInterop(require('micromatch'));
16
17
  var tinyglobby = _socketInterop(require('tinyglobby'));
17
18
  var which = _socketInterop(require('which'));
19
+ var colors = _socketInterop(require('yoctocolors-cjs'));
20
+ var isUnicodeSupported = require('@socketregistry/is-unicode-supported/index.cjs');
21
+ var spinner = require('@socketsecurity/registry/lib/spinner');
18
22
  var constants = require('./constants.js');
19
23
 
24
+ const logSymbols = isUnicodeSupported() ? {
25
+ __proto__: null,
26
+ info: colors.blue('ℹ'),
27
+ success: colors.green('✔'),
28
+ warning: colors.yellow('⚠'),
29
+ error: colors.red('✖️')
30
+ } : {
31
+ __proto__: null,
32
+ info: colors.blue('i'),
33
+ success: colors.green('√'),
34
+ warning: colors.yellow('‼'),
35
+ error: colors.red('×')
36
+ };
37
+ class Logger {
38
+ #spinnerLogger;
39
+ constructor() {
40
+ this.#spinnerLogger = new spinner.Spinner();
41
+ }
42
+ error(text) {
43
+ this.#spinnerLogger.error(text);
44
+ }
45
+ info(text) {
46
+ this.#spinnerLogger.info(text);
47
+ }
48
+ warn(text) {
49
+ this.#spinnerLogger.warning(text);
50
+ }
51
+ }
52
+ const logger = new Logger();
53
+
54
+ function isDebug() {
55
+ // Lazily access constants.ENV.
56
+ return constants.ENV.SOCKET_CLI_DEBUG;
57
+ }
58
+ function debugLog(...args) {
59
+ if (isDebug()) {
60
+ console.error(logSymbols.info, ...args);
61
+ }
62
+ }
63
+
20
64
  const ignoredDirs = [
21
65
  // Taken from ignore-by-default:
22
66
  // https://github.com/novemberborn/ignore-by-default/blob/v2.1.0/index.js
@@ -134,6 +178,7 @@ function ignorePatternToMinimatch(pattern) {
134
178
  return `${negatedPrefix}${matchEverywherePrefix}${escapedPatternWithoutLeadingSlash}${matchInsideSuffix}`;
135
179
  }
136
180
  function pathsToPatterns(paths) {
181
+ // TODO: Does not support `~/` paths.
137
182
  return paths.map(p => p === '.' ? '**/*' : p);
138
183
  }
139
184
  function findRoot(filepath) {
@@ -169,10 +214,8 @@ async function findBinPathDetails(binName) {
169
214
  shadowed: shadowIndex !== -1
170
215
  };
171
216
  }
172
- async function getPackageFiles(cwd, inputPaths, config, supportedFiles, debugLog = () => {}) {
217
+ async function getPackageFiles(cwd, inputPaths, config, supportedFiles) {
173
218
  debugLog(`Globbed resolving ${inputPaths.length} paths:`, inputPaths);
174
-
175
- // TODO: Does not support `~/` paths
176
219
  const entries = await globWithGitIgnore(pathsToPatterns(inputPaths), {
177
220
  cwd,
178
221
  socketConfig: config
@@ -184,8 +227,6 @@ async function getPackageFiles(cwd, inputPaths, config, supportedFiles, debugLog
184
227
  }
185
228
  async function getPackageFilesFullScans(cwd, inputPaths, supportedFiles, debugLog = () => {}) {
186
229
  debugLog(`Globbed resolving ${inputPaths.length} paths:`, inputPaths);
187
-
188
- // TODO: Does not support `~/` paths
189
230
  const entries = await globWithGitIgnore(pathsToPatterns(inputPaths), {
190
231
  cwd
191
232
  });
@@ -195,7 +236,11 @@ async function getPackageFilesFullScans(cwd, inputPaths, supportedFiles, debugLo
195
236
  return packageFiles;
196
237
  }
197
238
 
239
+ exports.debugLog = debugLog;
198
240
  exports.findBinPathDetails = findBinPathDetails;
199
241
  exports.findRoot = findRoot;
200
242
  exports.getPackageFiles = getPackageFiles;
201
243
  exports.getPackageFilesFullScans = getPackageFilesFullScans;
244
+ exports.isDebug = isDebug;
245
+ exports.logSymbols = logSymbols;
246
+ exports.logger = logger;
@@ -1,2 +1,2 @@
1
- declare function shadow(binName: 'npm' | 'npx', binArgs?: string[]): Promise<void>;
2
- export { shadow as default };
1
+ declare function shadowBin(binName: 'npm' | 'npx', binArgs?: string[]): Promise<void>;
2
+ export { shadowBin as default };
@@ -9,17 +9,13 @@ function _socketInterop(e) {
9
9
  return c ? e.default : e
10
10
  }
11
11
 
12
- var fs = require('node:fs');
13
12
  var path = require('node:path');
13
+ var process = require('node:process');
14
14
  var spawn = _socketInterop(require('@npmcli/promise-spawn'));
15
- var constants = require('./constants.js');
16
15
  var cmdShim = _socketInterop(require('cmd-shim'));
16
+ var constants = require('./constants.js');
17
17
  var pathResolve = require('./path-resolve.js');
18
18
 
19
- const {
20
- WIN32,
21
- rootDistPath
22
- } = constants;
23
19
  async function installLinks(realBinPath, binName) {
24
20
  // Find package manager being shadowed by this process.
25
21
  const {
@@ -32,6 +28,10 @@ async function installLinks(realBinPath, binName) {
32
28
  console.error(`Socket unable to locate ${binName}; ensure it is available in the PATH environment variable.`);
33
29
  process.exit(127);
34
30
  }
31
+ // Lazily access constants.WIN32.
32
+ const {
33
+ WIN32
34
+ } = constants;
35
35
  // TODO: Is this early exit needed?
36
36
  if (WIN32 && binPath) {
37
37
  return binPath;
@@ -39,7 +39,9 @@ async function installLinks(realBinPath, binName) {
39
39
  // Move our bin directory to front of PATH so its found first.
40
40
  if (!shadowed) {
41
41
  if (WIN32) {
42
- await cmdShim(path.join(rootDistPath, `${binName}-cli.js`), path.join(realBinPath, binName));
42
+ await cmdShim(
43
+ // Lazily access constants.rootDistPath.
44
+ path.join(constants.rootDistPath, `${binName}-cli.js`), path.join(realBinPath, binName));
43
45
  }
44
46
  process.env['PATH'] = `${realBinPath}${path.delimiter}${process.env['PATH']}`;
45
47
  }
@@ -48,41 +50,22 @@ async function installLinks(realBinPath, binName) {
48
50
 
49
51
  const {
50
52
  NPM,
51
- abortSignal,
52
- distPath,
53
- execPath,
54
- shadowBinPath
53
+ abortSignal
55
54
  } = constants;
56
- const injectionPath = path.join(distPath, 'npm-injection.js');
57
- async function shadow(binName, binArgs = process.argv.slice(2)) {
58
- const binPath = await installLinks(shadowBinPath, binName);
59
- if (abortSignal.aborted) {
60
- return;
61
- }
62
- // Adding the `--quiet` and `--no-progress` flags when the `proc-log` module
63
- // is found to fix a UX issue when running the command with recent versions of
64
- // npm (input swallowed by the standard npm spinner)
65
- if (binName === NPM && binArgs.includes('install') && !binArgs.includes('--no-progress') && !binArgs.includes('--quiet')) {
66
- const npmEntrypoint = fs.realpathSync(binPath);
67
- const npmRootPath = pathResolve.findRoot(path.dirname(npmEntrypoint));
68
- if (npmRootPath === undefined) {
69
- // The exit code 127 indicates that the command or binary being executed
70
- // could not be found.
71
- process.exit(127);
72
- }
73
- const npmDepPath = path.join(npmRootPath, 'node_modules');
74
- let procLog;
75
- try {
76
- procLog = require(path.join(npmDepPath, 'proc-log/lib/index.js')).log;
77
- } catch {}
78
- if (procLog) {
79
- binArgs.push('--no-progress', '--quiet');
80
- }
81
- }
55
+ async function shadowBin(binName, binArgs = process.argv.slice(2)) {
82
56
  process.exitCode = 1;
83
- const spawnPromise = spawn(execPath, [
57
+ const spawnPromise = spawn(
58
+ // Lazily access constants.execPath.
59
+ constants.execPath, [
84
60
  // Lazily access constants.nodeNoWarningsFlags.
85
- ...constants.nodeNoWarningsFlags, '--require', injectionPath, binPath, ...binArgs], {
61
+ ...constants.nodeNoWarningsFlags, '--require',
62
+ // Lazily access constants.distPath.
63
+ path.join(constants.distPath, 'npm-injection.js'),
64
+ // Lazily access constants.shadowBinPath.
65
+ await installLinks(constants.shadowBinPath, binName), ...binArgs,
66
+ // Add the `--quiet` and `--no-progress` flags to fix input being swallowed
67
+ // by the spinner when running the command with recent versions of npm.
68
+ ...(binName === NPM && binArgs.includes('install') && !binArgs.includes('--no-progress') && !binArgs.includes('--quiet') ? ['--no-progress', '--quiet'] : [])], {
86
69
  signal: abortSignal,
87
70
  stdio: 'inherit'
88
71
  });
@@ -100,4 +83,4 @@ async function shadow(binName, binArgs = process.argv.slice(2)) {
100
83
  await spawnPromise;
101
84
  }
102
85
 
103
- module.exports = shadow;
86
+ module.exports = shadowBin;
@@ -0,0 +1,24 @@
1
+ import { SocketSdk } from "@socketsecurity/sdk";
2
+ import indentString from "@socketregistry/indent-string/index.cjs";
3
+ import { logSymbols } from "./logging.js";
4
+ declare function getDefaultToken(): string | undefined;
5
+ declare function getPublicToken(): string;
6
+ declare function setupSdk(apiToken?: string | undefined, apiBaseUrl?: string | undefined, proxy?: string | undefined): Promise<SocketSdk>;
7
+ declare class ColorOrMarkdown {
8
+ useMarkdown: boolean;
9
+ constructor(useMarkdown: boolean);
10
+ bold(text: string): string;
11
+ header(text: string, level?: number): string;
12
+ hyperlink(text: string, url: string | undefined, { fallback, fallbackToUrl }?: {
13
+ fallback?: boolean;
14
+ fallbackToUrl?: boolean;
15
+ }): string;
16
+ indent(...args: Parameters<typeof indentString>): ReturnType<typeof indentString>;
17
+ italic(text: string): string;
18
+ json(value: any): string;
19
+ list(items: string[]): string;
20
+ get logSymbols(): typeof logSymbols;
21
+ }
22
+ declare function getSocketDevAlertUrl(alertType: string): string;
23
+ declare function getSocketDevPackageOverviewUrl(eco: string, name: string, version?: string): string;
24
+ export { getDefaultToken, getPublicToken, setupSdk, ColorOrMarkdown, getSocketDevAlertUrl, getSocketDevPackageOverviewUrl };
@@ -0,0 +1,222 @@
1
+ 'use strict';
2
+
3
+ function _socketInterop(e) {
4
+ let c = 0
5
+ for (const k in e ?? {}) {
6
+ c = c === 0 && k === 'default' ? 1 : 0
7
+ if (!c && k !== '__esModule') break
8
+ }
9
+ return c ? e.default : e
10
+ }
11
+
12
+ var terminalLink = _socketInterop(require('terminal-link'));
13
+ var colors = _socketInterop(require('yoctocolors-cjs'));
14
+ var indentString = require('@socketregistry/indent-string/index.cjs');
15
+ var pathResolve = require('./path-resolve.js');
16
+ var process = require('node:process');
17
+ var hpagent = _socketInterop(require('hpagent'));
18
+ var isInteractive = require('@socketregistry/is-interactive/index.cjs');
19
+ var registryConstants = require('@socketsecurity/registry/lib/constants');
20
+ var prompts = require('@socketsecurity/registry/lib/prompts');
21
+ var strings = require('@socketsecurity/registry/lib/strings');
22
+ var sdk = require('@socketsecurity/sdk');
23
+ var fs = require('node:fs');
24
+ var os = require('node:os');
25
+ var path = require('node:path');
26
+ var constants = require('./constants.js');
27
+
28
+ class AuthError extends Error {}
29
+ class InputError extends Error {
30
+ constructor(message, body) {
31
+ super(message);
32
+ this.body = body;
33
+ }
34
+ }
35
+ function isErrnoException(value) {
36
+ if (!(value instanceof Error)) {
37
+ return false;
38
+ }
39
+ return value.code !== undefined;
40
+ }
41
+
42
+ const markdownLogSymbols = {
43
+ __proto__: null,
44
+ info: ':information_source:',
45
+ error: ':stop_sign:',
46
+ success: ':white_check_mark:',
47
+ warning: ':warning:'
48
+ };
49
+ class ColorOrMarkdown {
50
+ constructor(useMarkdown) {
51
+ this.useMarkdown = !!useMarkdown;
52
+ }
53
+ bold(text) {
54
+ return this.useMarkdown ? `**${text}**` : colors.bold(`${text}`);
55
+ }
56
+ header(text, level = 1) {
57
+ return this.useMarkdown ? `\n${''.padStart(level, '#')} ${text}\n` : colors.underline(`\n${level === 1 ? colors.bold(text) : text}\n`);
58
+ }
59
+ hyperlink(text, url, {
60
+ fallback = true,
61
+ fallbackToUrl
62
+ } = {}) {
63
+ if (url) {
64
+ return this.useMarkdown ? `[${text}](${url})` : terminalLink(text, url, {
65
+ fallback: fallbackToUrl ? (_text, url) => url : fallback
66
+ });
67
+ }
68
+ return text;
69
+ }
70
+ indent(...args) {
71
+ return indentString(...args);
72
+ }
73
+ italic(text) {
74
+ return this.useMarkdown ? `_${text}_` : colors.italic(`${text}`);
75
+ }
76
+ json(value) {
77
+ return this.useMarkdown ? '```json\n' + JSON.stringify(value) + '\n```' : JSON.stringify(value);
78
+ }
79
+ list(items) {
80
+ const indentedContent = items.map(item => this.indent(item).trimStart());
81
+ return this.useMarkdown ? `* ${indentedContent.join('\n* ')}\n` : `${indentedContent.join('\n')}\n`;
82
+ }
83
+ get logSymbols() {
84
+ return this.useMarkdown ? markdownLogSymbols : pathResolve.logSymbols;
85
+ }
86
+ }
87
+
88
+ const LOCALAPPDATA = 'LOCALAPPDATA';
89
+ let _settings;
90
+ function getSettings() {
91
+ if (_settings === undefined) {
92
+ _settings = {};
93
+ const settingsPath = getSettingsPath();
94
+ if (settingsPath) {
95
+ if (fs.existsSync(settingsPath)) {
96
+ const raw = fs.readFileSync(settingsPath, 'utf8');
97
+ try {
98
+ Object.assign(_settings, JSON.parse(Buffer.from(raw, 'base64').toString()));
99
+ } catch {
100
+ pathResolve.logger.warn(`Failed to parse settings at ${settingsPath}`);
101
+ }
102
+ } else {
103
+ fs.mkdirSync(path.dirname(settingsPath), {
104
+ recursive: true
105
+ });
106
+ }
107
+ }
108
+ }
109
+ return _settings;
110
+ }
111
+ let _settingsPath;
112
+ let _warnedSettingPathWin32Missing = false;
113
+ function getSettingsPath() {
114
+ if (_settingsPath === undefined) {
115
+ // Lazily access constants.WIN32.
116
+ const {
117
+ WIN32
118
+ } = constants;
119
+ let dataHome = WIN32 ? process.env[LOCALAPPDATA] : process.env['XDG_DATA_HOME'];
120
+ if (!dataHome) {
121
+ if (WIN32) {
122
+ if (!_warnedSettingPathWin32Missing) {
123
+ _warnedSettingPathWin32Missing = true;
124
+ pathResolve.logger.warn(`Missing %${LOCALAPPDATA}%`);
125
+ }
126
+ } else {
127
+ dataHome = path.join(os.homedir(), ...(process.platform === 'darwin' ? ['Library', 'Application Support'] : ['.local', 'share']));
128
+ }
129
+ }
130
+ _settingsPath = dataHome ? path.join(dataHome, 'socket', 'settings') : undefined;
131
+ }
132
+ return _settingsPath;
133
+ }
134
+ function getSetting(key) {
135
+ return getSettings()[key];
136
+ }
137
+ let pendingSave = false;
138
+ function updateSetting(key, value) {
139
+ const settings = getSettings();
140
+ settings[key] = value;
141
+ if (!pendingSave) {
142
+ pendingSave = true;
143
+ process.nextTick(() => {
144
+ pendingSave = false;
145
+ const settingsPath = getSettingsPath();
146
+ if (settingsPath) {
147
+ fs.writeFileSync(settingsPath, Buffer.from(JSON.stringify(settings)).toString('base64'));
148
+ }
149
+ });
150
+ }
151
+ }
152
+
153
+ // The API server that should be used for operations.
154
+ function getDefaultApiBaseUrl() {
155
+ const baseUrl = process.env['SOCKET_SECURITY_API_BASE_URL'] || getSetting('apiBaseUrl');
156
+ return strings.isNonEmptyString(baseUrl) ? baseUrl : undefined;
157
+ }
158
+
159
+ // The API server that should be used for operations.
160
+ function getDefaultHttpProxy() {
161
+ const apiProxy = process.env['SOCKET_SECURITY_API_PROXY'] || getSetting('apiProxy');
162
+ return strings.isNonEmptyString(apiProxy) ? apiProxy : undefined;
163
+ }
164
+
165
+ // This API key should be stored globally for the duration of the CLI execution.
166
+ let _defaultToken;
167
+ function getDefaultToken() {
168
+ const key = process.env['SOCKET_SECURITY_API_TOKEN'] ||
169
+ // Keep 'SOCKET_SECURITY_API_KEY' as an alias of 'SOCKET_SECURITY_API_TOKEN'.
170
+ // TODO: Remove 'SOCKET_SECURITY_API_KEY' alias.
171
+ process.env['SOCKET_SECURITY_API_KEY'] ||
172
+ // TODO: Rename the 'apiKey' setting to 'apiToken'.
173
+ getSetting('apiKey') || _defaultToken;
174
+ _defaultToken = strings.isNonEmptyString(key) ? key : undefined;
175
+ return _defaultToken;
176
+ }
177
+ function getPublicToken() {
178
+ return getDefaultToken() ?? registryConstants.SOCKET_PUBLIC_API_TOKEN;
179
+ }
180
+ async function setupSdk(apiToken = getDefaultToken(), apiBaseUrl = getDefaultApiBaseUrl(), proxy = getDefaultHttpProxy()) {
181
+ if (typeof apiToken !== 'string' && isInteractive()) {
182
+ apiToken = await prompts.password({
183
+ message: 'Enter your Socket.dev API key (not saved, use socket login to persist)'
184
+ });
185
+ _defaultToken = apiToken;
186
+ }
187
+ if (!apiToken) {
188
+ throw new AuthError('You need to provide an API key');
189
+ }
190
+ return new sdk.SocketSdk(apiToken, {
191
+ agent: proxy ? {
192
+ http: new hpagent.HttpProxyAgent({
193
+ proxy
194
+ }),
195
+ https: new hpagent.HttpsProxyAgent({
196
+ proxy
197
+ })
198
+ } : undefined,
199
+ baseUrl: apiBaseUrl,
200
+ // Lazily access constants.rootPkgJsonPath.
201
+ userAgent: sdk.createUserAgentFromPkgJson(require(constants.rootPkgJsonPath))
202
+ });
203
+ }
204
+
205
+ function getSocketDevAlertUrl(alertType) {
206
+ return `https://socket.dev/alerts/${alertType}`;
207
+ }
208
+ function getSocketDevPackageOverviewUrl(eco, name, version) {
209
+ return `https://socket.dev/${eco}/package/${name}${version ? `/overview/${version}` : ''}`;
210
+ }
211
+
212
+ exports.AuthError = AuthError;
213
+ exports.ColorOrMarkdown = ColorOrMarkdown;
214
+ exports.InputError = InputError;
215
+ exports.getDefaultToken = getDefaultToken;
216
+ exports.getPublicToken = getPublicToken;
217
+ exports.getSetting = getSetting;
218
+ exports.getSocketDevAlertUrl = getSocketDevAlertUrl;
219
+ exports.getSocketDevPackageOverviewUrl = getSocketDevPackageOverviewUrl;
220
+ exports.isErrnoException = isErrnoException;
221
+ exports.setupSdk = setupSdk;
222
+ exports.updateSetting = updateSetting;