@opscompass/opscompass-cli 1.3.2 → 1.3.4

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.
package/updates.js CHANGED
@@ -1,81 +1,433 @@
1
1
  import pkg from "./package.json" with { type: "json" };
2
- import semver from "semver";
3
- import { exec } from "child_process";
2
+ import axios from "axios";
4
3
  import { yellowText, redText } from "./colors.js";
5
4
  import { opscompassHome } from "./environment/current.js";
6
5
  import fs from "fs";
6
+ import os from "os";
7
7
  import path from "path";
8
8
 
9
+ const HOURS_24_MS = 24 * 60 * 60 * 1000;
10
+ const VERSION_CHECK_TIMEOUT_MS = 6000;
11
+ const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org/";
12
+ const LOCAL_REGISTRY_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
13
+
14
+ function isAuthConfigKey(key) {
15
+ return [":_authToken", ":_auth", ":_password", ":username"].some((suffix) =>
16
+ key.endsWith(suffix),
17
+ );
18
+ }
19
+
20
+ function parseRegistryUrl(registryUrl, sourceLabel = "npm registry") {
21
+ try {
22
+ return new URL(registryUrl);
23
+ } catch {
24
+ throw new Error(`Invalid npm registry URL '${registryUrl}' from ${sourceLabel}`);
25
+ }
26
+ }
27
+
28
+ function normalizeRegistryUrl(
29
+ configuredRegistry = DEFAULT_NPM_REGISTRY_URL,
30
+ sourceLabel = "npm registry",
31
+ ) {
32
+ let normalized = configuredRegistry.trim();
33
+ if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) {
34
+ normalized = `https://${normalized}`;
35
+ }
36
+
37
+ const registryUrl = parseRegistryUrl(normalized, sourceLabel);
38
+ registryUrl.pathname = registryUrl.pathname.replace(/\/+$/, "");
39
+ return registryUrl.toString();
40
+ }
41
+
42
+ function joinRegistryUrl(registryBaseUrl, packagePath) {
43
+ const separator = registryBaseUrl.endsWith("/") ? "" : "/";
44
+ return `${registryBaseUrl}${separator}${packagePath}`;
45
+ }
46
+
47
+ function getPackageScope(packageName) {
48
+ if (!packageName?.startsWith("@")) {
49
+ return undefined;
50
+ }
51
+
52
+ const slashIndex = packageName.indexOf("/");
53
+ return slashIndex === -1 ? undefined : packageName.slice(0, slashIndex);
54
+ }
55
+
56
+ function expandEnvPlaceholders(value, env = process.env) {
57
+ return value.replace(/\$\{([^}]+)\}/g, (match, key) => env[key] ?? match);
58
+ }
59
+
60
+ function parseNpmrc(contents, env = process.env) {
61
+ const config = {};
62
+
63
+ for (const line of contents.split(/\r?\n/u)) {
64
+ const trimmedLine = line.trim();
65
+ if (
66
+ trimmedLine.length === 0 ||
67
+ trimmedLine.startsWith("#") ||
68
+ trimmedLine.startsWith(";")
69
+ ) {
70
+ continue;
71
+ }
72
+
73
+ const separatorIndex = trimmedLine.indexOf("=");
74
+ if (separatorIndex === -1) {
75
+ continue;
76
+ }
77
+
78
+ const key = trimmedLine.slice(0, separatorIndex).trim();
79
+ let value = trimmedLine.slice(separatorIndex + 1).trim();
80
+ if (
81
+ (value.startsWith('"') && value.endsWith('"')) ||
82
+ (value.startsWith("'") && value.endsWith("'"))
83
+ ) {
84
+ value = value.slice(1, -1);
85
+ }
86
+
87
+ config[key] = expandEnvPlaceholders(value, env);
88
+ }
89
+
90
+ return config;
91
+ }
92
+
93
+ function readNpmConfigFile(
94
+ filePath,
95
+ { fileSystem = fs, env = process.env, allowAuthKeys = true } = {},
96
+ ) {
97
+ try {
98
+ if (!filePath || !fileSystem.existsSync(filePath)) {
99
+ return {};
100
+ }
101
+
102
+ const parsedConfig = parseNpmrc(fileSystem.readFileSync(filePath, "utf8"), env);
103
+ if (allowAuthKeys) {
104
+ return parsedConfig;
105
+ }
106
+
107
+ return Object.fromEntries(
108
+ Object.entries(parsedConfig).filter(([key]) => !isAuthConfigKey(key)),
109
+ );
110
+ } catch {
111
+ return {};
112
+ }
113
+ }
114
+
115
+ function getNpmConfig({
116
+ cwd = process.cwd(),
117
+ env = process.env,
118
+ fileSystem = fs,
119
+ } = {}) {
120
+ const projectConfigPath = path.join(cwd, ".npmrc");
121
+ const globalConfigPath = env.npm_config_globalconfig || env.NPM_CONFIG_GLOBALCONFIG;
122
+ const userConfigPath =
123
+ env.npm_config_userconfig ||
124
+ env.NPM_CONFIG_USERCONFIG ||
125
+ path.join(os.homedir(), ".npmrc");
126
+
127
+ return {
128
+ ...readNpmConfigFile(globalConfigPath, { fileSystem, env }),
129
+ ...readNpmConfigFile(userConfigPath, { fileSystem, env }),
130
+ ...readNpmConfigFile(projectConfigPath, {
131
+ fileSystem,
132
+ env,
133
+ allowAuthKeys: false,
134
+ }),
135
+ };
136
+ }
137
+
138
+ function getConfigValue(keys, { env = process.env, npmConfig = {} } = {}) {
139
+ for (const key of keys) {
140
+ if (Object.prototype.hasOwnProperty.call(env, key)) {
141
+ return env[key];
142
+ }
143
+
144
+ if (Object.prototype.hasOwnProperty.call(npmConfig, key)) {
145
+ return npmConfig[key];
146
+ }
147
+ }
148
+ }
149
+
150
+ function resolveRegistrySetting(
151
+ packageName = pkg.name,
152
+ { env = process.env, npmConfig = {}, packageJson = pkg } = {},
153
+ ) {
154
+ const packageScope = getPackageScope(packageName);
155
+ const scopedRegistry = packageScope
156
+ ? getConfigValue(
157
+ [
158
+ `${packageScope}:registry`,
159
+ `npm_config_${packageScope}:registry`,
160
+ `NPM_CONFIG_${packageScope}:registry`,
161
+ ],
162
+ { env, npmConfig },
163
+ )
164
+ : undefined;
165
+
166
+ if (scopedRegistry !== undefined) {
167
+ return {
168
+ registry: scopedRegistry,
169
+ sourceLabel: `${packageScope}:registry`,
170
+ };
171
+ }
172
+
173
+ if (packageJson.publishConfig?.registry !== undefined) {
174
+ return {
175
+ registry: packageJson.publishConfig.registry,
176
+ sourceLabel: "publishConfig.registry",
177
+ };
178
+ }
179
+
180
+ const configuredRegistry = getConfigValue(
181
+ ["npm_config_registry", "NPM_CONFIG_REGISTRY", "registry"],
182
+ { env, npmConfig },
183
+ );
184
+
185
+ if (configuredRegistry !== undefined) {
186
+ return {
187
+ registry: configuredRegistry,
188
+ sourceLabel: Object.prototype.hasOwnProperty.call(env, "npm_config_registry")
189
+ ? "npm_config_registry"
190
+ : Object.prototype.hasOwnProperty.call(env, "NPM_CONFIG_REGISTRY")
191
+ ? "NPM_CONFIG_REGISTRY"
192
+ : "registry",
193
+ };
194
+ }
195
+
196
+ return {
197
+ registry: DEFAULT_NPM_REGISTRY_URL,
198
+ sourceLabel: "default registry",
199
+ };
200
+ }
201
+
202
+ function getNpmRegistryUrl(
203
+ packageName = pkg.name,
204
+ {
205
+ env = process.env,
206
+ packageJson = pkg,
207
+ npmConfig,
208
+ } = {},
209
+ ) {
210
+ const effectiveNpmConfig = npmConfig || getNpmConfig({ env });
211
+ const registrySetting = resolveRegistrySetting(packageName, {
212
+ env,
213
+ npmConfig: effectiveNpmConfig,
214
+ packageJson,
215
+ });
216
+
217
+ return normalizeRegistryUrl(registrySetting.registry, registrySetting.sourceLabel);
218
+ }
219
+
220
+ function getRegistryConfigBases(registryUrl) {
221
+ const parsedUrl = parseRegistryUrl(registryUrl, "resolved npm registry");
222
+ const normalizedPath =
223
+ parsedUrl.pathname === "/"
224
+ ? "/"
225
+ : `${parsedUrl.pathname.replace(/\/+$/, "")}/`;
226
+ const exactBase = `//${parsedUrl.host}${normalizedPath === "/" ? "/" : normalizedPath}`;
227
+ const hostBase = `//${parsedUrl.host}/`;
228
+
229
+ return Array.from(new Set([exactBase, hostBase]));
230
+ }
231
+
232
+ function shouldSendRegistryAuth(registryUrl) {
233
+ const parsedUrl = parseRegistryUrl(registryUrl, "resolved npm registry");
234
+ return (
235
+ parsedUrl.protocol === "https:" ||
236
+ LOCAL_REGISTRY_HOSTNAMES.has(parsedUrl.hostname)
237
+ );
238
+ }
239
+
240
+ function getRegistryAuthHeaders(
241
+ registryUrl,
242
+ {
243
+ cwd = process.cwd(),
244
+ env = process.env,
245
+ fileSystem = fs,
246
+ npmConfig,
247
+ } = {},
248
+ ) {
249
+ const effectiveNpmConfig = npmConfig || getNpmConfig({ cwd, env, fileSystem });
250
+ const registryConfigBases = getRegistryConfigBases(registryUrl);
251
+ const token = getConfigValue(
252
+ registryConfigBases.map((base) => `${base}:_authToken`),
253
+ { env, npmConfig: effectiveNpmConfig },
254
+ );
255
+
256
+ if (token) {
257
+ return {
258
+ Authorization: `Bearer ${token}`,
259
+ };
260
+ }
261
+
262
+ const auth = getConfigValue(
263
+ registryConfigBases.map((base) => `${base}:_auth`),
264
+ { env, npmConfig: effectiveNpmConfig },
265
+ );
266
+ if (auth) {
267
+ return {
268
+ Authorization: `Basic ${auth}`,
269
+ };
270
+ }
271
+
272
+ const username = getConfigValue(
273
+ registryConfigBases.map((base) => `${base}:username`),
274
+ { env, npmConfig: effectiveNpmConfig },
275
+ );
276
+ const encodedPassword = getConfigValue(
277
+ registryConfigBases.map((base) => `${base}:_password`),
278
+ { env, npmConfig: effectiveNpmConfig },
279
+ );
280
+ if (username && encodedPassword) {
281
+ const password = Buffer.from(encodedPassword, "base64").toString("utf8");
282
+ const basicAuth = Buffer.from(`${username}:${password}`, "utf8").toString(
283
+ "base64",
284
+ );
285
+
286
+ return {
287
+ Authorization: `Basic ${basicAuth}`,
288
+ };
289
+ }
290
+
291
+ return {};
292
+ }
293
+
294
+ function writeVersionCacheAtomic(filePath, data) {
295
+ const tempFilePath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
296
+ fs.writeFileSync(tempFilePath, JSON.stringify(data, null, 2) + "\n");
297
+ fs.renameSync(tempFilePath, filePath);
298
+ }
299
+
300
+ async function fetchLatestVersionFromRegistry(
301
+ packageName,
302
+ {
303
+ cwd = process.cwd(),
304
+ env = process.env,
305
+ fileSystem = fs,
306
+ packageJson = pkg,
307
+ stderr = console.error,
308
+ } = {},
309
+ ) {
310
+ const npmConfig = getNpmConfig({ cwd, env, fileSystem });
311
+ const registryBaseUrl = getNpmRegistryUrl(packageName, {
312
+ env,
313
+ packageJson,
314
+ npmConfig,
315
+ });
316
+ const authHeaders = getRegistryAuthHeaders(registryBaseUrl, {
317
+ cwd,
318
+ env,
319
+ fileSystem,
320
+ npmConfig,
321
+ });
322
+ const headers = shouldSendRegistryAuth(registryBaseUrl) ? authHeaders : {};
323
+
324
+ if (!shouldSendRegistryAuth(registryBaseUrl) && Object.keys(authHeaders).length > 0) {
325
+ stderr(
326
+ yellowText,
327
+ "CLI Version check warning: refusing to send registry credentials over insecure HTTP.",
328
+ );
329
+ }
330
+
331
+ const packagePath = encodeURIComponent(packageName);
332
+ const url = joinRegistryUrl(registryBaseUrl, packagePath);
333
+
334
+ const response = await axios.get(url, {
335
+ timeout: VERSION_CHECK_TIMEOUT_MS,
336
+ ...(Object.keys(headers).length > 0 ? { headers } : {}),
337
+ });
338
+
339
+ const latestVersion = response?.data?.["dist-tags"]?.latest;
340
+ if (!latestVersion) {
341
+ throw new Error(`No latest dist-tag found for ${packageName}`);
342
+ }
343
+
344
+ return latestVersion;
345
+ }
346
+
9
347
  /* versionCheck sends a command to the terminal to check the latest package version and compares it to the current version specified in package.json, prompting the user to upgrade if it is out of date. */
10
348
  /* This is turned off by default when using the local environment. To turn it on for dev purposes, comment out isLocal check in index.js */
11
349
 
12
- function versionCheck() {
350
+ async function versionCheck({
351
+ cwd = process.cwd(),
352
+ env = process.env,
353
+ fileSystem = fs,
354
+ stderr = console.error,
355
+ } = {}) {
13
356
  if (global.isOffline) {
14
- console.error(yellowText, "Using CLI in offline mode");
15
- return Promise.resolve();
357
+ stderr(yellowText, "Using CLI in offline mode");
358
+ return;
16
359
  }
17
360
  const checkPath = path.join(opscompassHome, ".versioncheck");
18
361
 
19
- // If .versioncheck exists and is less than 24 hours old, return the cached version
20
- if (fs.existsSync(checkPath)) {
21
- const stats = fs.statSync(checkPath);
362
+ if (fileSystem.existsSync(checkPath)) {
363
+ const stats = fileSystem.statSync(checkPath);
22
364
  const now = Date.now();
23
365
  const mtime = new Date(stats.mtime).getTime();
24
- const hours24 = 24 * 60 * 60 * 1000;
25
- if (now - mtime < hours24) {
366
+ if (now - mtime < HOURS_24_MS) {
26
367
  try {
27
- const cachedVersionData = fs.readFileSync(checkPath, "utf8").trim();
368
+ const cachedVersionData = fileSystem.readFileSync(checkPath, "utf8").trim();
28
369
  const versionObject = JSON.parse(cachedVersionData);
29
- return Promise.resolve(versionObject);
30
- } catch (err) {
31
- // If we can't read or parse the file, fall through to do a fresh check
370
+ return versionObject;
371
+ } catch {
372
+ // fall through to a fresh check
32
373
  }
33
374
  }
34
375
  }
35
376
 
36
- // Remove the existing .versioncheck file since we need to check the version
37
377
  try {
38
- fs.unlinkSync(checkPath);
39
- } catch (err) {
40
- // Ignore errors when removing the file
41
- }
42
-
43
- // Return a Promise that resolves when version check completes
44
- return new Promise((resolve) => {
45
- const environmentSpecificPackageVersion = `npm view ${pkg.name} version`;
46
- /* latestVersion is the standard output(stdout)
47
- This is usually fast, but it can hang, so we set a timeout.
48
- On error, we just resolve without doing anything further.
49
- */
50
- exec(
51
- environmentSpecificPackageVersion,
52
- { timeout: 6000 },
53
- (error, latestVersion, stderr) => {
54
- if (error) {
55
- if (error.killed) {
56
- console.error(yellowText, "CLI Version check warning: timed out.");
57
- } else {
58
- console.error(redText, `CLI Version check error: ${error.message}`);
59
- }
60
- resolve();
61
- return;
62
- }
63
-
64
- const result = {
65
- pkg: pkg.name,
66
- latest: latestVersion.trim(),
67
- };
68
-
69
- // Update the .versioncheck file with the versions after successful check
70
- try {
71
- fs.writeFileSync(checkPath, JSON.stringify(result, null, 2) + "\n");
72
- } catch (err) {
73
- // Ignore errors when writing the version file
74
- }
75
- resolve(result);
76
- },
77
- );
78
- });
378
+ fileSystem.unlinkSync(checkPath);
379
+ } catch {
380
+ // ignore when removing the cache file
381
+ }
382
+
383
+ try {
384
+ const latestVersion = await fetchLatestVersionFromRegistry(pkg.name, {
385
+ cwd,
386
+ env,
387
+ fileSystem,
388
+ stderr,
389
+ });
390
+ const result = {
391
+ pkg: pkg.name,
392
+ latest: latestVersion.trim(),
393
+ };
394
+
395
+ try {
396
+ writeVersionCacheAtomic(checkPath, result);
397
+ } catch {
398
+ // ignore cache write failures
399
+ }
400
+
401
+ return result;
402
+ } catch (error) {
403
+ if (error?.code === "ECONNABORTED") {
404
+ stderr(yellowText, "CLI Version check warning: timed out.");
405
+ } else if ([401, 403, 404].includes(error?.response?.status)) {
406
+ stderr(
407
+ yellowText,
408
+ `CLI Version check warning: package metadata unavailable from registry (${error.response.status}).`,
409
+ );
410
+ } else {
411
+ stderr(redText, `CLI Version check error: ${error.message}`);
412
+ }
413
+ return;
414
+ }
79
415
  }
80
416
 
81
- export { versionCheck };
417
+ export {
418
+ versionCheck,
419
+ fetchLatestVersionFromRegistry,
420
+ VERSION_CHECK_TIMEOUT_MS,
421
+ getConfigValue,
422
+ getNpmConfig,
423
+ getNpmRegistryUrl,
424
+ getRegistryAuthHeaders,
425
+ getPackageScope,
426
+ isAuthConfigKey,
427
+ joinRegistryUrl,
428
+ normalizeRegistryUrl,
429
+ parseNpmrc,
430
+ resolveRegistrySetting,
431
+ shouldSendRegistryAuth,
432
+ writeVersionCacheAtomic,
433
+ };
@@ -1,30 +0,0 @@
1
- // demo: @opscompass/opscompass-api-demo
2
-
3
- import {
4
- OpsCompassClient,
5
- ScriptType,
6
- OAuthHandler,
7
- licenseManagerConfigurationTypes,
8
- } from "@opscompass/opscompass-api-demo";
9
-
10
- import path from "path";
11
- import { homedir } from "os";
12
- const opscompassHome = path.join(homedir(), ".opscompassdemo");
13
- const cliCommand = "opscompassdemo";
14
-
15
- const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
16
- const authDomain = "auth-dev.opscompass.com";
17
- const audience = "https://opscompass-api-demo.azure-api.net";
18
- const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
19
- const isLocal = false;
20
-
21
- export {
22
- OpsCompassClient,
23
- licenseManagerConfigurationTypes,
24
- ScriptType,
25
- oAuthClient,
26
- opscompassHome,
27
- isLocal,
28
- cliCommand,
29
- };
30
- export const decoder = "TjFXOWhWdnppb2Zoa2ZFcmd1TWI";
@@ -1,30 +0,0 @@
1
- // dev: @opscompass/opscompass-api-dev
2
-
3
- import {
4
- OpsCompassClient,
5
- ScriptType,
6
- OAuthHandler,
7
- licenseManagerConfigurationTypes,
8
- } from "@opscompass/opscompass-api-dev";
9
-
10
- import path from "path";
11
- import { homedir } from "os";
12
- const opscompassHome = path.join(homedir(), ".opscompassdev");
13
- const cliCommand = "opscompassdev";
14
-
15
- const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
16
- const authDomain = "auth-dev.opscompass.com";
17
- const audience = "https://fa-sampleapi-cus-dev.azurewebsites.net";
18
- const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
19
- const isLocal = false;
20
-
21
- export {
22
- OpsCompassClient,
23
- licenseManagerConfigurationTypes,
24
- ScriptType,
25
- oAuthClient,
26
- opscompassHome,
27
- isLocal,
28
- cliCommand,
29
- };
30
- export const decoder = "TjFXOWhWdnppb2Zoa2ZFcmd1TWI";
@@ -1,31 +0,0 @@
1
- // local: @opscompass/opscompass-api is pointing to the local file system.
2
- // set up your local functions to use dev's token settings.
3
-
4
- import {
5
- OpsCompassClient,
6
- ScriptType,
7
- OAuthHandler,
8
- licenseManagerConfigurationTypes,
9
- } from "@opscompass/opscompass-api";
10
-
11
- import path from "path";
12
- import { homedir } from "os";
13
- const opscompassHome = path.join(homedir(), ".opscompassdev");
14
- const cliCommand = "opscompassdev";
15
-
16
- const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
17
- const authDomain = "auth-dev.opscompass.com";
18
- const audience = "https://fa-sampleapi-cus-dev.azurewebsites.net";
19
- const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
20
- const isLocal = true;
21
-
22
- export {
23
- OpsCompassClient,
24
- licenseManagerConfigurationTypes,
25
- ScriptType,
26
- oAuthClient,
27
- opscompassHome,
28
- isLocal,
29
- cliCommand,
30
- };
31
- export const decoder = "TjFXOWhWdnppb2Zoa2ZFcmd1TWI";
@@ -1,30 +0,0 @@
1
- // production: OpsCompassClient is referenced from npm package
2
-
3
- import {
4
- OpsCompassClient,
5
- ScriptType,
6
- OAuthHandler,
7
- licenseManagerConfigurationTypes,
8
- } from "@opscompass/opscompass-api";
9
-
10
- import path from "path";
11
- import { homedir } from "os";
12
- const opscompassHome = path.join(homedir(), ".opscompass");
13
- const cliCommand = "opscompass";
14
-
15
- const clientId = "vOakDaOv4L26f3uuI4sp3KC1Sov3nsW2";
16
- // default authDomain
17
- // default audience
18
- const oAuthClient = new OAuthHandler(clientId);
19
- const isLocal = false;
20
-
21
- export {
22
- OpsCompassClient,
23
- licenseManagerConfigurationTypes,
24
- ScriptType,
25
- oAuthClient,
26
- opscompassHome,
27
- isLocal,
28
- cliCommand,
29
- };
30
- export const decoder = "TjFXOWhWdnppb2Zoa2ZFcmd1TWI";