@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.
@@ -0,0 +1,83 @@
1
+ import { styleText } from "node:util";
2
+
3
+ function supportsStyling(stream = process.stderr) {
4
+ return Boolean(stream?.isTTY) && process.env.NO_COLOR === undefined;
5
+ }
6
+
7
+ function renderStyledText(styles, text, stream = process.stderr) {
8
+ if (!supportsStyling(stream)) {
9
+ return text;
10
+ }
11
+
12
+ try {
13
+ return styleText(styles, text);
14
+ } catch {
15
+ return text;
16
+ }
17
+ }
18
+
19
+ function createDataGatheringUi({
20
+ write = (line = "") => console.error(line),
21
+ stream = process.stderr,
22
+ } = {}) {
23
+ function label(kind, text) {
24
+ const styles = {
25
+ title: ["bold"],
26
+ section: ["bold", "cyan"],
27
+ info: ["bold", "cyan"],
28
+ success: ["bold", "green"],
29
+ warn: ["bold", "yellow"],
30
+ error: ["bold", "red"],
31
+ step: ["bold", "blue"],
32
+ note: ["bold", "magenta"],
33
+ };
34
+
35
+ return renderStyledText(styles[kind] || ["bold"], text, stream);
36
+ }
37
+
38
+ return {
39
+ blank() {
40
+ write("");
41
+ },
42
+ title(text) {
43
+ write(label("title", text));
44
+ },
45
+ section(text) {
46
+ write(label("section", text));
47
+ },
48
+ info(text) {
49
+ write(`${label("info", "INFO")} ${text}`);
50
+ },
51
+ success(text) {
52
+ write(`${label("success", "OK")} ${text}`);
53
+ },
54
+ warn(text) {
55
+ write(`${label("warn", "WARN")} ${text}`);
56
+ },
57
+ error(text) {
58
+ write(`${label("error", "ERROR")} ${text}`);
59
+ },
60
+ step(index, total, text) {
61
+ write(`${label("step", "STEP")} ${index}/${total} ${text}`);
62
+ },
63
+ note(text) {
64
+ write(`${label("note", "NOTE")} ${text}`);
65
+ },
66
+ item(name, value) {
67
+ write(`- ${name}: ${value}`);
68
+ },
69
+ text(text) {
70
+ write(text);
71
+ },
72
+ command(command, description = "") {
73
+ const suffix = description ? ` ${description}` : "";
74
+ write(` ${command}${suffix}`);
75
+ },
76
+ };
77
+ }
78
+
79
+ export {
80
+ createDataGatheringUi,
81
+ renderStyledText,
82
+ supportsStyling,
83
+ };
@@ -0,0 +1,210 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ DATA_GATHERING_EXIT_CODES,
6
+ DataGatheringError,
7
+ } from "./events.js";
8
+ import { createDataGatheringUi } from "./ui.js";
9
+
10
+ const BASE_REQUIREMENTS = Object.freeze([
11
+ "jq",
12
+ "tar",
13
+ "gzip",
14
+ "zip",
15
+ "unzip",
16
+ ]);
17
+ const ALTERNATE_REQUIREMENTS = Object.freeze([Object.freeze(["curl", "wget"])]);
18
+ const MODULE_REQUIREMENTS = Object.freeze({
19
+ "msql-license": ["sqlcmd"],
20
+ "msql-compliance": ["sqlcmd"],
21
+ vsphere: ["pwsh"],
22
+ "oracle-features": ["sqlplus"],
23
+ });
24
+ const LEGACY_INSTALLER_PATH =
25
+ "data-gathering/scripts-base/Package/Config/Opscompass_install.sh";
26
+
27
+ function getPathDirectories(envPath = process.env.PATH || "") {
28
+ return envPath.split(path.delimiter).filter(Boolean);
29
+ }
30
+
31
+ function resolveExecutable(executable, envPath = process.env.PATH || "") {
32
+ const pathDirectories = getPathDirectories(envPath);
33
+ const pathExts = process.platform === "win32"
34
+ ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM")
35
+ .split(";")
36
+ .filter(Boolean)
37
+ : [""];
38
+
39
+ for (const directory of pathDirectories) {
40
+ for (const extension of pathExts) {
41
+ const candidate = path.join(directory, `${executable}${extension}`);
42
+ try {
43
+ fs.accessSync(candidate, fs.constants.X_OK);
44
+ return candidate;
45
+ } catch {
46
+ // keep searching
47
+ }
48
+ }
49
+ }
50
+
51
+ return null;
52
+ }
53
+
54
+ function collectRequirements(modules = []) {
55
+ const requiredExecutables = new Set(BASE_REQUIREMENTS);
56
+ for (const group of ALTERNATE_REQUIREMENTS) {
57
+ requiredExecutables.add(group.join("|"));
58
+ }
59
+
60
+ for (const moduleName of modules) {
61
+ for (const executable of MODULE_REQUIREMENTS[moduleName] || []) {
62
+ requiredExecutables.add(executable);
63
+ }
64
+ }
65
+
66
+ return Array.from(requiredExecutables);
67
+ }
68
+
69
+ function validateInstall({ modules = [], envPath = process.env.PATH || "" } = {}) {
70
+ const missing = [];
71
+ const resolved = {};
72
+
73
+ for (const requirement of collectRequirements(modules)) {
74
+ if (requirement.includes("|")) {
75
+ const choices = requirement.split("|");
76
+ const winner = choices.find((name) => resolveExecutable(name, envPath));
77
+ if (!winner) {
78
+ missing.push({ requirement: choices.join(" or "), anyOf: choices });
79
+ } else {
80
+ resolved[winner] = resolveExecutable(winner, envPath);
81
+ }
82
+ continue;
83
+ }
84
+
85
+ const executablePath = resolveExecutable(requirement, envPath);
86
+ if (!executablePath) {
87
+ missing.push({ requirement });
88
+ } else {
89
+ resolved[requirement] = executablePath;
90
+ }
91
+ }
92
+
93
+ return {
94
+ ok: missing.length === 0,
95
+ missing,
96
+ resolved,
97
+ modules,
98
+ };
99
+ }
100
+
101
+ function parseValidateInstallArgs(args) {
102
+ const modules = [];
103
+
104
+ for (let index = 0; index < args.length; index += 1) {
105
+ if (args[index] === "--module" && args[index + 1]) {
106
+ modules.push(args[index + 1]);
107
+ index += 1;
108
+ }
109
+ }
110
+
111
+ return {
112
+ modules,
113
+ };
114
+ }
115
+
116
+ function formatMissingRequirement(requirement) {
117
+ return requirement.anyOf?.join(" or ") || requirement.requirement;
118
+ }
119
+
120
+ function printValidateInstallSummary(result, ui = createDataGatheringUi()) {
121
+ ui.blank();
122
+ ui.section("Validation");
123
+
124
+ if (result.ok) {
125
+ ui.success("All required data-gathering prerequisites are installed.");
126
+ const resolvedEntries = Object.entries(result.resolved).sort(([left], [right]) =>
127
+ left.localeCompare(right),
128
+ );
129
+ for (const [name, resolvedPath] of resolvedEntries) {
130
+ ui.item(name, resolvedPath);
131
+ }
132
+ return;
133
+ }
134
+
135
+ ui.warn("Missing required data-gathering prerequisites.");
136
+ for (const requirement of result.missing) {
137
+ ui.item("Missing", formatMissingRequirement(requirement));
138
+ }
139
+ if (result.remediation) {
140
+ ui.note(result.remediation);
141
+ }
142
+ }
143
+
144
+ async function runValidateInstallCommand(
145
+ args,
146
+ logger,
147
+ { ui = createDataGatheringUi(), envPath = process.env.PATH || "" } = {},
148
+ ) {
149
+ const options = parseValidateInstallArgs(args);
150
+ logger.emit("validate-install.started", {
151
+ modules: options.modules,
152
+ });
153
+
154
+ const result = validateInstall({
155
+ ...options,
156
+ envPath,
157
+ });
158
+ if (!result.ok) {
159
+ const remediation =
160
+ `Install the required prerequisites, then rerun setup or validation. Legacy installer reference: ${LEGACY_INSTALLER_PATH}`;
161
+ printValidateInstallSummary(
162
+ {
163
+ ...result,
164
+ remediation,
165
+ },
166
+ ui,
167
+ );
168
+ logger.emit("validate-install.completed", {
169
+ status: "failed",
170
+ exitCode: DATA_GATHERING_EXIT_CODES.missingDependency,
171
+ missingDependencies: result.missing,
172
+ remediation,
173
+ });
174
+ const error = new DataGatheringError("Missing runtime dependencies", {
175
+ exitCode: DATA_GATHERING_EXIT_CODES.missingDependency,
176
+ type: "validate-install.failed",
177
+ data: {
178
+ missingDependencies: result.missing,
179
+ },
180
+ });
181
+ error.humanOutputHandled = true;
182
+ throw error;
183
+ }
184
+
185
+ logger.emit("validate-install.completed", {
186
+ status: "success",
187
+ exitCode: DATA_GATHERING_EXIT_CODES.success,
188
+ modules: result.modules,
189
+ resolved: result.resolved,
190
+ });
191
+ printValidateInstallSummary(result, ui);
192
+
193
+ return {
194
+ exitCode: DATA_GATHERING_EXIT_CODES.success,
195
+ result,
196
+ };
197
+ }
198
+
199
+ export {
200
+ BASE_REQUIREMENTS,
201
+ LEGACY_INSTALLER_PATH,
202
+ MODULE_REQUIREMENTS,
203
+ collectRequirements,
204
+ formatMissingRequirement,
205
+ parseValidateInstallArgs,
206
+ printValidateInstallSummary,
207
+ resolveExecutable,
208
+ runValidateInstallCommand,
209
+ validateInstall,
210
+ };
@@ -1,6 +1,9 @@
1
1
  import fs from "fs-extra";
2
2
  import path from "path";
3
- import { Verify } from "./pgpTools.js";
3
+ import {
4
+ Verify,
5
+ SCRIPT_BUNDLE_VERIFICATION_STATUS,
6
+ } from "./pgpTools.js";
4
7
 
5
8
  import {
6
9
  opscompassHome,
@@ -16,16 +19,18 @@ import {
16
19
  moveFolder,
17
20
  writeFile,
18
21
  canReadFile,
19
- FilePermissions,
20
22
  getAllFilesInFolder,
21
23
  } from "./cliHelpers.js";
22
- import { nextTick } from "process";
23
24
 
24
25
  import semver from "semver";
25
26
 
26
27
  const SRC_FOLDER_NAME = "src";
27
28
  const METADATA_FILE_NAME = "metadata.json";
28
29
  const BASE_SCRIPTS_RUN_ALL_RELATIVE_PATH = "scripts/runall.sh";
30
+ const SCRIPT_VERIFICATION_FALLBACK = {
31
+ status: SCRIPT_BUNDLE_VERIFICATION_STATUS.unverified,
32
+ reason: "verification-not-run",
33
+ };
29
34
 
30
35
  /**
31
36
  * Writes provided data to the specified file in the home directory.
@@ -138,6 +143,7 @@ async function downloadScriptsToHome(
138
143
  companySlug,
139
144
  client,
140
145
  scriptsRemote = undefined,
146
+ output = console,
141
147
  ) {
142
148
  // If scriptsRemote is provided, use it instead of fetching from api
143
149
  if (!!scriptsRemote) {
@@ -152,7 +158,7 @@ async function downloadScriptsToHome(
152
158
 
153
159
  // Determine what is available
154
160
  if (!scriptsAvailable) {
155
- console.log("Fetching remote versions...");
161
+ output.log?.("Fetching remote versions...");
156
162
  scriptsAvailable =
157
163
  await client.dataGatheringScripts.getScriptVersions(companySlug);
158
164
  }
@@ -178,8 +184,10 @@ async function downloadScriptsToHome(
178
184
  undefined,
179
185
  companySlug,
180
186
  client,
187
+ undefined,
188
+ output,
181
189
  );
182
- console.log("Base scripts updated (v%s)", baseVersion);
190
+ output.log?.("Base scripts updated (v%s)", baseVersion);
183
191
  }
184
192
  }
185
193
 
@@ -189,29 +197,44 @@ async function downloadScriptsToHome(
189
197
  scriptType,
190
198
  scriptVersion,
191
199
  );
192
- const scriptTypeFolderPath = findOrCreateScriptTypeFolder(scriptType);
200
+ const scriptTypePath = findOrCreateScriptTypeFolder(scriptType);
193
201
  const fileName = scriptDownloadInfo.fileName;
194
202
  scriptVersion = fileName.replace(".zip", "");
195
203
 
196
- removeCurrentlyInstalledScript(scriptType);
197
204
  await downloadFile(
198
205
  scriptDownloadInfo.downloadUrl,
199
- scriptTypeFolderPath,
206
+ scriptTypePath,
200
207
  fileName,
201
208
  );
202
209
 
203
- // Attempt to verify the download - returns true if signed and verified
204
- // outputs validation error(s) and returns false otherwise
205
- // - we continue regardless of validation for now...
206
- scriptDownloadInfo.filePath = path.join(scriptTypeFolderPath, fileName);
207
- const zipValidated = await Verify(scriptDownloadInfo);
210
+ scriptDownloadInfo.filePath = path.join(scriptTypePath, fileName);
211
+ const verification =
212
+ (await Verify(scriptDownloadInfo, output)) || SCRIPT_VERIFICATION_FALLBACK;
213
+
214
+ // Signature present but invalid must fail closed and not install.
215
+ if (verification.status === SCRIPT_BUNDLE_VERIFICATION_STATUS.invalid) {
216
+ deleteFile(scriptDownloadInfo.filePath);
217
+ throw new Error(
218
+ `Script bundle verification failed for ${scriptType}: ${verification.reason || "invalid signature"}`,
219
+ );
220
+ }
221
+
222
+ if (verification.status !== SCRIPT_BUNDLE_VERIFICATION_STATUS.verified) {
223
+ output.warn?.(
224
+ "Downloaded %s bundle is unverified (%s)",
225
+ scriptType,
226
+ verification.reason || "unknown",
227
+ );
228
+ }
208
229
 
209
- await unzipFile(scriptTypeFolderPath, fileName);
230
+ removeCurrentlyInstalledScript(scriptType);
231
+
232
+ await unzipFile(scriptTypePath, fileName);
210
233
 
211
234
  // Move contents from script version folder to src
212
- const destinationPath = path.join(scriptTypeFolderPath, SRC_FOLDER_NAME);
235
+ const destinationPath = path.join(scriptTypePath, SRC_FOLDER_NAME);
213
236
  await moveFolder(
214
- path.join(scriptTypeFolderPath, scriptVersion),
237
+ path.join(scriptTypePath, scriptVersion),
215
238
  destinationPath,
216
239
  );
217
240
 
@@ -241,9 +264,9 @@ async function downloadScriptsToHome(
241
264
  });
242
265
 
243
266
  // Set the script's metadata
244
- await setScriptMetadata(scriptTypeFolderPath, scriptVersion);
267
+ await setScriptMetadata(scriptTypePath, scriptVersion, verification);
245
268
 
246
- deleteFile(path.join(scriptTypeFolderPath, fileName));
269
+ deleteFile(path.join(scriptTypePath, fileName));
247
270
 
248
271
  // Return the version downloaded
249
272
  return scriptVersion;
@@ -268,9 +291,21 @@ function previousScriptsDownloaded(scriptType) {
268
291
  * @param {string} scriptFolderPath path to the script folder
269
292
  * @param {string} scriptVersion the version of the downloaded script
270
293
  */
271
- async function setScriptMetadata(scriptFolderPath, scriptVersion) {
294
+ async function setScriptMetadata(
295
+ scriptFolderPath,
296
+ scriptVersion,
297
+ verification = SCRIPT_VERIFICATION_FALLBACK,
298
+ ) {
272
299
  const scriptMetadata = {
273
300
  version: scriptVersion,
301
+ verification: {
302
+ status:
303
+ verification?.status || SCRIPT_BUNDLE_VERIFICATION_STATUS.unverified,
304
+ signer: verification?.signer,
305
+ signerFingerprint: verification?.signerFingerprint,
306
+ reason: verification?.reason,
307
+ checkedAt: new Date().toISOString(),
308
+ },
274
309
  };
275
310
 
276
311
  const metadataFilePath = path.join(scriptFolderPath, METADATA_FILE_NAME);
@@ -283,13 +318,43 @@ async function setScriptMetadata(scriptFolderPath, scriptVersion) {
283
318
  await writeFile(metadataFilePath, scriptMetadata);
284
319
  }
285
320
 
321
+ async function getScriptVerificationState(scriptType) {
322
+ const scriptMetadata = await getScriptMetadata(scriptType);
323
+ return scriptMetadata?.verification || SCRIPT_VERIFICATION_FALLBACK;
324
+ }
325
+
326
+ async function assertScriptBundleVerified(
327
+ scriptType,
328
+ { allowUnverified = false } = {},
329
+ ) {
330
+ const verification = await getScriptVerificationState(scriptType);
331
+ if (verification.status === SCRIPT_BUNDLE_VERIFICATION_STATUS.verified) {
332
+ return verification;
333
+ }
334
+
335
+ if (allowUnverified) {
336
+ console.warn(
337
+ "SECURITY WARNING: running with unverified scripts for %s (--allow-unverified break-glass mode)",
338
+ scriptType,
339
+ );
340
+ return verification;
341
+ }
342
+
343
+ throw new Error(
344
+ `Refusing to execute unverified scripts for ${scriptType}. Re-download a signed bundle or rerun with --allow-unverified for emergency/dev use.`,
345
+ );
346
+ }
347
+
286
348
  export {
287
349
  SRC_FOLDER_NAME,
288
350
  BASE_SCRIPTS_RUN_ALL_RELATIVE_PATH,
289
351
  writeFileToHome,
290
352
  findOrCreateScriptTypeFolder,
291
353
  findOrCreateScriptsFolder,
354
+ getScriptMetadata,
292
355
  getInstalledScriptVersion,
356
+ getScriptVerificationState,
357
+ assertScriptBundleVerified,
293
358
  removeCurrentlyInstalledScript,
294
359
  downloadScriptsToHome,
295
360
  previousScriptsDownloaded,