@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,971 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ import tar from "tar";
5
+ import * as openpgp from "openpgp";
6
+
7
+ import { getOpsCompassClient } from "../../opscompass.js";
8
+ import { utilsModule } from "../utils.js";
9
+ import { DataGatheringError, DATA_GATHERING_EXIT_CODES } from "./events.js";
10
+
11
+ const STATE_DIR_NAME = path.join(utilsModule.opscompassHome, "state", "filemon");
12
+ const STATE_FILE = path.join(STATE_DIR_NAME, "state.json");
13
+ const STATE_LOCK_FILE = path.join(STATE_DIR_NAME, "state.lock");
14
+ const DATA_DIR_NAME = path.join(utilsModule.opscompassHome, "data");
15
+ const PENDING_SEND_STALE_MS = 15 * 60 * 1000;
16
+
17
+ const METADATA_TYPE_ALIASES = Object.freeze({
18
+ "sql-server-database": "sql-server-database-metadata",
19
+ "sql-server-database-metadata": "sql-server-database-metadata",
20
+ "oracle-database": "oracle-database-metadata",
21
+ "oracle-database-metadata": "oracle-database-metadata",
22
+ "vmware-vsphere": "vmware-vsphere-metadata",
23
+ "vmware-vsphere-metadata": "vmware-vsphere-metadata",
24
+ "network-discovery": "network-discovery-metadata",
25
+ "network-discovery-metadata": "network-discovery-metadata",
26
+ "nutanix-prism": "nutanix-prism-metadata",
27
+ "nutanix-prism-metadata": "nutanix-prism-metadata",
28
+ });
29
+
30
+ const FILE_TYPE_RULES = Object.freeze({
31
+ "sql-server-database-metadata": Object.freeze({
32
+ required: true,
33
+ allowed: new Set(["licensing", "compliance"]),
34
+ }),
35
+ "oracle-database-metadata": Object.freeze({
36
+ required: true,
37
+ allowed: new Set(["ebusiness", "licensing", "compliance"]),
38
+ }),
39
+ });
40
+
41
+ function ensureStateDir() {
42
+ fs.mkdirSync(STATE_DIR_NAME, { recursive: true, mode: 0o700 });
43
+ }
44
+
45
+ function ensureDataDir() {
46
+ fs.mkdirSync(DATA_DIR_NAME, { recursive: true, mode: 0o700 });
47
+ return DATA_DIR_NAME;
48
+ }
49
+
50
+ function normalizeArchiveBasename(baseName) {
51
+ if (process.platform === "win32" || process.platform === "darwin") {
52
+ return baseName.toLowerCase();
53
+ }
54
+ return baseName;
55
+ }
56
+
57
+ function stagePlainFilesForArchive(sourcePaths) {
58
+ const stagingDir = fs.mkdtempSync(path.join(os.tmpdir(), "opscompass-send-dg-archive-"));
59
+ const seen = new Set();
60
+ const duplicates = new Set();
61
+ const basenames = [];
62
+
63
+ for (const sourcePath of sourcePaths) {
64
+ const baseName = path.basename(sourcePath);
65
+ const normalizedBaseName = normalizeArchiveBasename(baseName);
66
+ if (seen.has(normalizedBaseName)) {
67
+ duplicates.add(baseName);
68
+ continue;
69
+ }
70
+ seen.add(normalizedBaseName);
71
+ basenames.push(baseName);
72
+ }
73
+
74
+ if (duplicates.size > 0) {
75
+ fs.rmSync(stagingDir, { recursive: true, force: true });
76
+ throw new DataGatheringError(
77
+ `Cannot archive files with duplicate basenames: ${Array.from(duplicates).sort().join(", ")}`,
78
+ {
79
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
80
+ type: "send-dg.duplicate-basenames",
81
+ data: {
82
+ duplicates: Array.from(duplicates).sort(),
83
+ },
84
+ },
85
+ );
86
+ }
87
+
88
+ for (const sourcePath of sourcePaths) {
89
+ const baseName = path.basename(sourcePath);
90
+ const destPath = path.join(stagingDir, baseName);
91
+ try {
92
+ fs.linkSync(sourcePath, destPath);
93
+ } catch {
94
+ fs.copyFileSync(sourcePath, destPath);
95
+ }
96
+ }
97
+
98
+ return { stagingDir, basenames };
99
+ }
100
+
101
+ function isProcessAlive(pid) {
102
+ if (!Number.isInteger(pid) || pid <= 0) return false;
103
+ try {
104
+ process.kill(pid, 0);
105
+ return true;
106
+ } catch (err) {
107
+ if (err?.code === "EPERM") return true;
108
+ return false;
109
+ }
110
+ }
111
+
112
+ function reclaimCorruptStateFile() {
113
+ const backupPath = `${STATE_FILE}.corrupt.${Date.now()}`;
114
+ try {
115
+ fs.renameSync(STATE_FILE, backupPath);
116
+ return backupPath;
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ }
121
+
122
+ function loadState() {
123
+ ensureStateDir();
124
+ if (!fs.existsSync(STATE_FILE)) {
125
+ return { files: [] };
126
+ }
127
+
128
+ const raw = fs.readFileSync(STATE_FILE, "utf8");
129
+ try {
130
+ return JSON.parse(raw);
131
+ } catch {
132
+ const backupPath = reclaimCorruptStateFile();
133
+ throw new DataGatheringError("Filemon state file is corrupt; refusing to continue", {
134
+ exitCode: DATA_GATHERING_EXIT_CODES.internalError,
135
+ type: "send-dg.state-corrupt",
136
+ data: {
137
+ stateFile: STATE_FILE,
138
+ backupFile: backupPath,
139
+ },
140
+ });
141
+ }
142
+ }
143
+
144
+ function saveState(state) {
145
+ ensureStateDir();
146
+ const tempFile = `${STATE_FILE}.tmp.${process.pid}.${Date.now()}`;
147
+ try {
148
+ fs.writeFileSync(tempFile, JSON.stringify(state, null, 2), { mode: 0o600 });
149
+ fs.renameSync(tempFile, STATE_FILE);
150
+ } finally {
151
+ try {
152
+ if (fs.existsSync(tempFile)) {
153
+ fs.rmSync(tempFile, { force: true });
154
+ }
155
+ } catch {
156
+ // ignore temp cleanup errors
157
+ }
158
+ }
159
+ }
160
+
161
+ function tryReclaimStaleLock(staleLockMs) {
162
+ try {
163
+ if (!fs.existsSync(STATE_LOCK_FILE)) return false;
164
+ const stat = fs.statSync(STATE_LOCK_FILE);
165
+ const ageMs = Date.now() - stat.mtimeMs;
166
+ if (ageMs < staleLockMs) return false;
167
+
168
+ let lockInfo;
169
+ try {
170
+ lockInfo = JSON.parse(fs.readFileSync(STATE_LOCK_FILE, "utf8"));
171
+ } catch {
172
+ lockInfo = undefined;
173
+ }
174
+
175
+ if (lockInfo?.pid && isProcessAlive(lockInfo.pid)) {
176
+ return false;
177
+ }
178
+
179
+ fs.rmSync(STATE_LOCK_FILE, { force: false });
180
+ return true;
181
+ } catch {
182
+ return false;
183
+ }
184
+ }
185
+
186
+ async function withStateLock(callback, options = {}) {
187
+ ensureStateDir();
188
+ const retryDelayMs = Number.isFinite(options.retryDelayMs) ? options.retryDelayMs : 50;
189
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 5000;
190
+ const staleLockMs = Number.isFinite(options.staleLockMs) ? options.staleLockMs : Math.max(timeoutMs, 5000);
191
+ const start = Date.now();
192
+
193
+ while (true) {
194
+ let lockFd;
195
+ let lockHeld = false;
196
+ try {
197
+ lockFd = fs.openSync(STATE_LOCK_FILE, "wx", 0o600);
198
+ fs.writeFileSync(lockFd, JSON.stringify({ pid: process.pid, createdAt: Date.now() }));
199
+ lockHeld = true;
200
+ return await callback();
201
+ } catch (err) {
202
+ if (err?.code === "EEXIST") {
203
+ if (tryReclaimStaleLock(staleLockMs)) {
204
+ continue;
205
+ }
206
+ if (Date.now() - start >= timeoutMs) {
207
+ throw new DataGatheringError("Timed out waiting for filemon state lock", {
208
+ exitCode: DATA_GATHERING_EXIT_CODES.internalError,
209
+ type: "send-dg.state-lock-timeout",
210
+ });
211
+ }
212
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
213
+ continue;
214
+ }
215
+ throw err;
216
+ } finally {
217
+ if (lockHeld) {
218
+ if (lockFd !== undefined) {
219
+ try {
220
+ fs.closeSync(lockFd);
221
+ } catch {
222
+ // ignore close errors
223
+ }
224
+ }
225
+ try {
226
+ fs.rmSync(STATE_LOCK_FILE, { force: true });
227
+ } catch {
228
+ // ignore lock cleanup errors
229
+ }
230
+ }
231
+ }
232
+ }
233
+ }
234
+
235
+ function normalizeMetadataType(metadataType) {
236
+ const normalized = String(metadataType || "")
237
+ .trim()
238
+ .toLowerCase()
239
+ .replace(/^transfer-/, "");
240
+ if (!normalized) return undefined;
241
+ if (METADATA_TYPE_ALIASES[normalized]) return METADATA_TYPE_ALIASES[normalized];
242
+ const withSuffix = `${normalized.replace(/-metadata$/, "")}-metadata`;
243
+ return METADATA_TYPE_ALIASES[withSuffix];
244
+ }
245
+
246
+ function normalizeFileType(fileType) {
247
+ if (typeof fileType !== "string") return undefined;
248
+ const normalized = fileType.trim().toLowerCase();
249
+ if (!normalized) return undefined;
250
+ if (normalized === "license") return "licensing";
251
+ return normalized;
252
+ }
253
+
254
+ function validateFileType(metadataType, fileType) {
255
+ const rule = FILE_TYPE_RULES[metadataType];
256
+ if (!rule) {
257
+ return undefined;
258
+ }
259
+
260
+ if (!fileType) {
261
+ throw new DataGatheringError("--file-type is required for oracle and sql-server metadata", {
262
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
263
+ type: "send-dg.missing-file-type",
264
+ data: {
265
+ metadataType,
266
+ },
267
+ });
268
+ }
269
+
270
+ if (!rule.allowed.has(fileType)) {
271
+ throw new DataGatheringError(`Invalid --file-type '${fileType}' for ${metadataType}`, {
272
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
273
+ type: "send-dg.invalid-file-type",
274
+ data: {
275
+ metadataType,
276
+ fileType,
277
+ allowedValues: Array.from(rule.allowed),
278
+ },
279
+ });
280
+ }
281
+
282
+ return fileType;
283
+ }
284
+
285
+ function normalizeMetadataTypeForState(metadataType) {
286
+ return normalizeMetadataType(metadataType) || String(metadataType || "").trim().toLowerCase();
287
+ }
288
+
289
+ function hasPreviouslySent(state, baseName, metadataType, destination = "oc") {
290
+ const entry = findStateEntry(state, baseName, metadataType);
291
+ return entry?.destinations?.[destination]?.success === true;
292
+ }
293
+
294
+ function findStateEntry(state, baseName, metadataType) {
295
+ if (!Array.isArray(state.files)) return undefined;
296
+ const normalizedType = normalizeMetadataTypeForState(metadataType);
297
+ return state.files.find((entry) => {
298
+ const legacyBase = entry.baseName ? String(entry.baseName).replace(/\.gpg$/i, "") : entry.baseName;
299
+ const entryKey = entry.logicalName || legacyBase;
300
+ return entryKey === baseName && normalizeMetadataTypeForState(entry.metadataType) === normalizedType;
301
+ });
302
+ }
303
+
304
+ function ensureStateEntry(state, baseName, metadataType) {
305
+ const normalizedType = normalizeMetadataTypeForState(metadataType);
306
+ let found = findStateEntry(state, baseName, normalizedType);
307
+ if (!found) {
308
+ found = { logicalName: baseName, metadataType: normalizedType, destinations: {} };
309
+ state.files.push(found);
310
+ }
311
+ found.metadataType = normalizedType;
312
+ if (!found.destinations || typeof found.destinations !== "object") {
313
+ found.destinations = {};
314
+ }
315
+ return found;
316
+ }
317
+
318
+ function sameContents(left, right) {
319
+ if (!Array.isArray(left) || !Array.isArray(right)) return false;
320
+ if (left.length !== right.length) return false;
321
+ return left.every((value, index) => value === right[index]);
322
+ }
323
+
324
+ function normalizePathForState(filePath, rootDir) {
325
+ const rel = path.relative(rootDir, path.resolve(filePath));
326
+ if (!rel || rel === ".") {
327
+ return path.basename(filePath);
328
+ }
329
+ return rel;
330
+ }
331
+
332
+ function hasPreviouslySentPlainFile(state, plainRelativePath, metadataType, destination = "oc") {
333
+ if (!Array.isArray(state.files)) return false;
334
+ const normalizedType = normalizeMetadataTypeForState(metadataType);
335
+ const plainBaseName = path.basename(plainRelativePath);
336
+ for (const entry of state.files) {
337
+ if (normalizeMetadataTypeForState(entry.metadataType) !== normalizedType) continue;
338
+ if (!entry.destinations?.[destination]?.success) continue;
339
+ if (!Array.isArray(entry.contents)) continue;
340
+ if (entry.contents.includes(plainBaseName)) return true;
341
+ if (entry.legacyImported === true && entry.contents.some((item) => path.basename(item) === plainBaseName)) {
342
+ return true;
343
+ }
344
+ }
345
+ return false;
346
+ }
347
+
348
+ function markSent(state, baseName, metadataType, destination = "oc", response) {
349
+ const found = ensureStateEntry(state, baseName, metadataType);
350
+ found.destinations[destination] = { success: true, response };
351
+ saveState(state);
352
+ }
353
+
354
+ function markSentWithContents(state, baseName, metadataType, contents, destination = "oc", response, options = {}) {
355
+ const found = ensureStateEntry(state, baseName, metadataType);
356
+ if (Array.isArray(contents) && contents.length > 0) {
357
+ found.contents = contents;
358
+ }
359
+ if (options.legacyImported === true) {
360
+ found.legacyImported = true;
361
+ }
362
+ found.destinations[destination] = { success: true, response };
363
+ saveState(state);
364
+ }
365
+
366
+ function markPossiblySent(state, baseName, metadataType, destination = "oc", response, errorMessage) {
367
+ const found = ensureStateEntry(state, baseName, metadataType);
368
+ found.destinations[destination] = {
369
+ success: false,
370
+ possiblySent: true,
371
+ response,
372
+ errorMessage,
373
+ recordedAt: Date.now(),
374
+ };
375
+ saveState(state);
376
+ }
377
+
378
+ function claimPendingSend(state, baseName, metadataType, destination = "oc", staleMs = PENDING_SEND_STALE_MS) {
379
+ const found = ensureStateEntry(state, baseName, metadataType);
380
+ const status = found.destinations[destination];
381
+ if (status?.success === true) {
382
+ return { claimed: false, reason: "previously-sent" };
383
+ }
384
+ if (status?.pending === true) {
385
+ const claimedAt = Number(status.claimedAt);
386
+ const isFresh = Number.isFinite(claimedAt) && Date.now() - claimedAt < staleMs;
387
+ if (isFresh) {
388
+ return { claimed: false, reason: "currently-sending" };
389
+ }
390
+ }
391
+ found.destinations[destination] = {
392
+ success: false,
393
+ pending: true,
394
+ claimedAt: Date.now(),
395
+ pid: process.pid,
396
+ };
397
+ saveState(state);
398
+ return { claimed: true };
399
+ }
400
+
401
+ function clearPendingSend(state, baseName, metadataType, destination = "oc") {
402
+ const found = findStateEntry(state, baseName, metadataType);
403
+ if (!found?.destinations?.[destination]) return;
404
+ const status = found.destinations[destination];
405
+ if (status?.success === true) return;
406
+ if (status?.possiblySent === true) return;
407
+ if (status?.pending !== true) return;
408
+ delete found.destinations[destination];
409
+ const hasDestinations = found.destinations && Object.keys(found.destinations).length > 0;
410
+ const hasContents = Array.isArray(found.contents) && found.contents.length > 0;
411
+ if (!hasDestinations && !hasContents) {
412
+ const idx = state.files.indexOf(found);
413
+ if (idx >= 0) {
414
+ state.files.splice(idx, 1);
415
+ }
416
+ }
417
+ saveState(state);
418
+ }
419
+
420
+ function toTimestamp() {
421
+ return new Date().toISOString().replace(/T/, "_").replace(/\..+/, "Z").replace(/[-:]/g, "");
422
+ }
423
+
424
+ function writeOldFormatPacket(tag, body) {
425
+ if (!Number.isInteger(tag) || tag < 0 || tag > 15) {
426
+ throw new Error(`Cannot write old-format packet header for tag ${tag}`);
427
+ }
428
+
429
+ const payload = Buffer.isBuffer(body) ? body : Buffer.from(body);
430
+ const length = payload.length;
431
+
432
+ let lengthType;
433
+ let lengthBytes;
434
+ if (length < 256) {
435
+ lengthType = 0;
436
+ lengthBytes = Buffer.from([length]);
437
+ } else if (length < 65536) {
438
+ lengthType = 1;
439
+ lengthBytes = Buffer.from([(length >> 8) & 0xff, length & 0xff]);
440
+ } else {
441
+ lengthType = 2;
442
+ lengthBytes = Buffer.from([
443
+ (length >>> 24) & 0xff,
444
+ (length >>> 16) & 0xff,
445
+ (length >>> 8) & 0xff,
446
+ length & 0xff,
447
+ ]);
448
+ }
449
+
450
+ const headerByte = 0x80 | ((tag & 0x0f) << 2) | (lengthType & 0x03);
451
+ return Buffer.concat([Buffer.from([headerByte]), lengthBytes, payload]);
452
+ }
453
+
454
+ function encodeNewFormatLength(length) {
455
+ if (length < 0) {
456
+ throw new Error("Length must be non-negative");
457
+ }
458
+ if (length < 192) {
459
+ return Buffer.from([length]);
460
+ }
461
+ if (length < 8384) {
462
+ const x = length - 192;
463
+ return Buffer.from([((x >> 8) & 0xff) + 192, x & 0xff]);
464
+ }
465
+ return Buffer.from([
466
+ 255,
467
+ (length >>> 24) & 0xff,
468
+ (length >>> 16) & 0xff,
469
+ (length >>> 8) & 0xff,
470
+ length & 0xff,
471
+ ]);
472
+ }
473
+
474
+ function writeNewFormatPacketWithPartialLengths(tag, body, partialPower = 10) {
475
+ const payload = Buffer.isBuffer(body) ? body : Buffer.from(body);
476
+ const headerByte = 0xc0 | (tag & 0x3f);
477
+
478
+ const chunkLen = 1 << partialPower;
479
+ const partialLenByte = 224 + partialPower;
480
+
481
+ const chunks = [Buffer.from([headerByte])];
482
+ let offset = 0;
483
+ while (offset + chunkLen <= payload.length) {
484
+ chunks.push(Buffer.from([partialLenByte]));
485
+ chunks.push(payload.subarray(offset, offset + chunkLen));
486
+ offset += chunkLen;
487
+ }
488
+
489
+ const remaining = payload.length - offset;
490
+ chunks.push(encodeNewFormatLength(remaining));
491
+ if (remaining > 0) {
492
+ chunks.push(payload.subarray(offset));
493
+ }
494
+
495
+ return Buffer.concat(chunks);
496
+ }
497
+
498
+ async function encryptFile(filePath, account) {
499
+ const customerToken = typeof account === "string" && account.trim() !== ""
500
+ ? account.trim()
501
+ : global.account || process.env.OC_DEFAULT_account;
502
+ if (!customerToken) {
503
+ throw new DataGatheringError("--account is required (or set a default account) for send-dg encryption", {
504
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
505
+ type: "send-dg.missing-account",
506
+ });
507
+ }
508
+
509
+ const outFile = `${filePath}.gpg`;
510
+ const input = fs.readFileSync(filePath);
511
+ const password = `${utilsModule.hobKey}${customerToken}`;
512
+ const filename = path.basename(filePath);
513
+
514
+ const config = {
515
+ preferredSymmetricAlgorithm: openpgp.enums.symmetric.aes256,
516
+ preferredCompressionAlgorithm: openpgp.enums.compression.uncompressed,
517
+ };
518
+ const mergedConfig = { ...openpgp.config, ...config };
519
+
520
+ try {
521
+ const skesk = new openpgp.SymEncryptedSessionKeyPacket(mergedConfig);
522
+ skesk.sessionKeyAlgorithm = openpgp.enums.symmetric.aes256;
523
+ await skesk.encrypt(password, mergedConfig);
524
+
525
+ const derivedKey = await skesk.s2k.produceKey(password, 32);
526
+
527
+ skesk.encrypted = null;
528
+ skesk.sessionKeyEncryptionAlgorithm = null;
529
+ skesk.sessionKey = null;
530
+
531
+ const skeskPacket = writeOldFormatPacket(
532
+ openpgp.enums.packet.symEncryptedSessionKey,
533
+ Buffer.from(skesk.write()),
534
+ );
535
+
536
+ const message = await openpgp.createMessage({ binary: input, filename });
537
+ const seipd = openpgp.SymEncryptedIntegrityProtectedDataPacket.fromObject({
538
+ version: 1,
539
+ aeadAlgorithm: null,
540
+ });
541
+ seipd.packets = message.packets;
542
+ await seipd.encrypt(openpgp.enums.symmetric.aes256, derivedKey, mergedConfig);
543
+
544
+ const seipdPacket = writeNewFormatPacketWithPartialLengths(
545
+ openpgp.enums.packet.symEncryptedIntegrityProtectedData,
546
+ Buffer.from(seipd.write()),
547
+ 10,
548
+ );
549
+
550
+ fs.writeFileSync(outFile, Buffer.concat([skeskPacket, seipdPacket]));
551
+ } catch (err) {
552
+ throw new DataGatheringError(`Failed to encrypt ${path.basename(filePath)} for legacy uploader compatibility`, {
553
+ exitCode: DATA_GATHERING_EXIT_CODES.internalError,
554
+ type: "send-dg.encryption-failed",
555
+ data: {
556
+ file: path.basename(filePath),
557
+ cause: err?.message || String(err),
558
+ },
559
+ });
560
+ }
561
+ return outFile;
562
+ }
563
+
564
+ function buildArchiveName(company, seq = "aa") {
565
+ const ts = toTimestamp();
566
+ return `${company}_filemonArchive_${ts}.${seq}.tgz`;
567
+ }
568
+
569
+ function splitIntoChunks(files, chunkSize = 200) {
570
+ const chunks = [];
571
+ for (let i = 0; i < files.length; i += chunkSize) chunks.push(files.slice(i, i + chunkSize));
572
+ return chunks;
573
+ }
574
+
575
+ function resolveCompany(company) {
576
+ if (typeof company === "string" && company.trim() !== "") {
577
+ return company;
578
+ }
579
+ if (typeof global.company === "string" && global.company.trim() !== "") {
580
+ return global.company;
581
+ }
582
+ if (typeof global.companySlug === "string" && global.companySlug.trim() !== "") {
583
+ return global.companySlug;
584
+ }
585
+ return undefined;
586
+ }
587
+
588
+ function resolveAccount(account) {
589
+ if (typeof account === "string" && account.trim() !== "") {
590
+ return account;
591
+ }
592
+ if (typeof global.account === "string" && global.account.trim() !== "") {
593
+ return global.account;
594
+ }
595
+ if (typeof process.env.OC_DEFAULT_account === "string" && process.env.OC_DEFAULT_account.trim() !== "") {
596
+ return process.env.OC_DEFAULT_account;
597
+ }
598
+ return undefined;
599
+ }
600
+
601
+ function transferSucceeded(response) {
602
+ return response?.saveInfo?.success === true;
603
+ }
604
+
605
+ async function sendToOc(client, metadataType, fileType, filePath, company) {
606
+ switch (metadataType) {
607
+ case "sql-server-database-metadata":
608
+ return client.compliance.transferSqlServerDatabaseMetadata(company, fileType, filePath);
609
+ case "oracle-database-metadata":
610
+ return client.compliance.transferOracleDatabaseMetadata(company, fileType, filePath);
611
+ case "vmware-vsphere-metadata":
612
+ return client.compliance.transferVMwareVsphereMetadata(company, filePath);
613
+ case "network-discovery-metadata":
614
+ return client.compliance.transferNetworkDiscoveryMetadata(company, filePath);
615
+ case "nutanix-prism-metadata":
616
+ return client.compliance.transferNutanixPrismMetadata(company, filePath);
617
+ default:
618
+ throw new DataGatheringError(`Unsupported metadata type: ${metadataType}`, {
619
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
620
+ type: "send-dg.invalid-metadata-type",
621
+ data: { metadataType },
622
+ });
623
+ }
624
+ }
625
+
626
+ function collectLegacyImportDirectories(monDir, files) {
627
+ const candidates = new Set();
628
+ if (typeof monDir === "string" && monDir.trim() !== "" && path.resolve(monDir) !== process.cwd()) {
629
+ candidates.add(path.resolve(monDir));
630
+ }
631
+ for (const file of files) {
632
+ candidates.add(path.dirname(path.resolve(file)));
633
+ }
634
+ if (candidates.size === 0) {
635
+ candidates.add(process.cwd());
636
+ }
637
+ return Array.from(candidates);
638
+ }
639
+
640
+ async function importLegacyFilemonState(monDirs, logger = { emit: () => {} }) {
641
+ for (const monDir of monDirs) {
642
+ try {
643
+ const legacyPath = path.join(monDir, ".filemon.js");
644
+ if (!fs.existsSync(legacyPath)) {
645
+ continue;
646
+ }
647
+ const control = JSON.parse(fs.readFileSync(legacyPath, "utf8"));
648
+ await withStateLock(async () => {
649
+ const state = loadState();
650
+ if (Array.isArray(control.files)) {
651
+ for (const fileRecord of control.files) {
652
+ if (fileRecord.response?.saveInfo?.success !== true) {
653
+ continue;
654
+ }
655
+ const baseName = path.basename(fileRecord.fPath);
656
+ const logicalName = baseName.replace(/\.gpg$/i, "");
657
+ const metadataType = normalizeMetadataTypeForState(fileRecord.mType);
658
+ if (hasPreviouslySent(state, logicalName, metadataType, "oc")) {
659
+ continue;
660
+ }
661
+ if (Array.isArray(fileRecord.contents) && fileRecord.contents.length > 0) {
662
+ markSentWithContents(state, logicalName, metadataType, fileRecord.contents, "oc", fileRecord.response, {
663
+ legacyImported: true,
664
+ });
665
+ } else {
666
+ markSent(state, logicalName, metadataType, "oc", fileRecord.response);
667
+ }
668
+ }
669
+ }
670
+ });
671
+ } catch (err) {
672
+ if (err instanceof DataGatheringError) {
673
+ throw err;
674
+ }
675
+ logger.emit("send-dg.legacy-import-warning", {
676
+ directory: monDir,
677
+ legacyPath: path.join(monDir, ".filemon.js"),
678
+ message: err?.message || String(err),
679
+ });
680
+ }
681
+ }
682
+ }
683
+
684
+ function isEncryptedFile(filePath) {
685
+ return filePath.toLowerCase().endsWith(".gpg");
686
+ }
687
+
688
+ function isArchiveFile(filePath) {
689
+ const lower = filePath.toLowerCase();
690
+ return lower.endsWith(".tgz") || lower.endsWith(".tar.gz");
691
+ }
692
+
693
+ async function sendDgAction(args = [], logger = { emit: () => {} }) {
694
+ const params = {
695
+ metadataType: undefined,
696
+ fileType: undefined,
697
+ destinations: "oc",
698
+ files: [],
699
+ company: undefined,
700
+ account: undefined,
701
+ directory: process.cwd(),
702
+ };
703
+
704
+ function readFlagValue(arr, idx, flag) {
705
+ const val = arr[idx + 1];
706
+ if (typeof val === "undefined" || (typeof val === "string" && val.startsWith("--"))) {
707
+ throw new DataGatheringError(`Flag ${flag} requires a value`, {
708
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
709
+ type: "send-dg.missing-flag-value",
710
+ data: { flag },
711
+ });
712
+ }
713
+ return val;
714
+ }
715
+
716
+ for (let i = 0; i < args.length; i += 1) {
717
+ const arg = args[i];
718
+ switch (arg) {
719
+ case "--metadata-type":
720
+ params.metadataType = readFlagValue(args, i, arg);
721
+ i += 1;
722
+ break;
723
+ case "--file-type":
724
+ params.fileType = readFlagValue(args, i, arg);
725
+ i += 1;
726
+ break;
727
+ case "--destinations":
728
+ params.destinations = readFlagValue(args, i, arg);
729
+ i += 1;
730
+ break;
731
+ case "--company":
732
+ params.company = readFlagValue(args, i, arg);
733
+ i += 1;
734
+ break;
735
+ case "--account":
736
+ params.account = readFlagValue(args, i, arg);
737
+ i += 1;
738
+ break;
739
+ case "--directory":
740
+ params.directory = readFlagValue(args, i, arg);
741
+ i += 1;
742
+ break;
743
+ default:
744
+ if (arg.startsWith("--")) {
745
+ throw new DataGatheringError(`Unknown flag: ${arg}`, {
746
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
747
+ type: "send-dg.invalid-flag",
748
+ data: { flag: arg },
749
+ });
750
+ }
751
+ params.files.push(arg);
752
+ break;
753
+ }
754
+ }
755
+
756
+ if (params.files.length === 0) {
757
+ throw new DataGatheringError("send-dg requires one or more files", {
758
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
759
+ type: "send-dg.invalid-input",
760
+ });
761
+ }
762
+
763
+ const canonicalMetadataType = normalizeMetadataType(params.metadataType);
764
+ if (!canonicalMetadataType) {
765
+ throw new DataGatheringError(`Unsupported metadata type: ${params.metadataType}`, {
766
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
767
+ type: "send-dg.invalid-metadata-type",
768
+ data: { metadataType: params.metadataType },
769
+ });
770
+ }
771
+ params.metadataType = canonicalMetadataType;
772
+ params.fileType = validateFileType(params.metadataType, normalizeFileType(params.fileType));
773
+
774
+ if (String(params.destinations).toLowerCase() !== "oc") {
775
+ throw new DataGatheringError("send-dg currently supports only --destinations oc", {
776
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
777
+ type: "send-dg.invalid-destination",
778
+ data: { destinations: params.destinations },
779
+ });
780
+ }
781
+
782
+ params.company = resolveCompany(params.company);
783
+ if (!params.company) {
784
+ throw new DataGatheringError("--company is required (or set a default company)", {
785
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
786
+ type: "send-dg.missing-company",
787
+ });
788
+ }
789
+
790
+ params.account = resolveAccount(params.account);
791
+
792
+ const client = await getOpsCompassClient();
793
+
794
+ const resolvedInputFiles = params.files.map((file) => (path.isAbsolute(file) ? file : path.join(params.directory, file)));
795
+ await importLegacyFilemonState(collectLegacyImportDirectories(params.directory, resolvedInputFiles), logger);
796
+ const state = await withStateLock(async () => loadState());
797
+
798
+ const toSend = [];
799
+ const plainFiles = [];
800
+ const generatedArchives = new Set();
801
+
802
+ for (const resolved of resolvedInputFiles) {
803
+ if (!fs.existsSync(resolved)) {
804
+ throw new DataGatheringError(`File not found: ${resolved}`, {
805
+ exitCode: DATA_GATHERING_EXIT_CODES.invalidInput,
806
+ type: "send-dg.file-not-found",
807
+ data: { file: resolved },
808
+ });
809
+ }
810
+ if (isEncryptedFile(resolved) || isArchiveFile(resolved)) {
811
+ toSend.push({ filePath: resolved, contents: [] });
812
+ continue;
813
+ }
814
+ plainFiles.push(resolved);
815
+ }
816
+
817
+ const plainFilesToArchive = plainFiles.filter((plainPath) => {
818
+ const normalizedPlainPath = normalizePathForState(plainPath, params.directory);
819
+ if (hasPreviouslySentPlainFile(state, normalizedPlainPath, params.metadataType, "oc")) {
820
+ logger.emit("send-dg.skipped", {
821
+ file: normalizedPlainPath,
822
+ reason: "previously-sent-plain-file",
823
+ });
824
+ return false;
825
+ }
826
+ return true;
827
+ });
828
+
829
+ if (plainFilesToArchive.length > 0) {
830
+ const archiveOutputDir = ensureDataDir();
831
+ const chunks = splitIntoChunks(plainFilesToArchive, 200);
832
+ let seq = "aa";
833
+ for (const chunk of chunks) {
834
+ const chunkBasenames = chunk.map((entry) => path.basename(entry));
835
+ let archiveSeq = seq;
836
+ let archiveName;
837
+ while (true) {
838
+ archiveName = path.join(archiveOutputDir, buildArchiveName(params.company, archiveSeq));
839
+ const logicalName = path.basename(archiveName);
840
+ const existingEntry = findStateEntry(state, logicalName, params.metadataType);
841
+ const hasStateCollision = existingEntry && !sameContents(existingEntry.contents, chunkBasenames);
842
+ const hasFileCollision = fs.existsSync(archiveName) || fs.existsSync(`${archiveName}.gpg`);
843
+ if (!hasStateCollision && !hasFileCollision) {
844
+ break;
845
+ }
846
+ archiveSeq = nextSeq(archiveSeq);
847
+ }
848
+
849
+ const { stagingDir, basenames } = stagePlainFilesForArchive(chunk);
850
+ try {
851
+ await tar.create({ file: archiveName, gzip: true, cwd: stagingDir }, basenames);
852
+ } finally {
853
+ fs.rmSync(stagingDir, { recursive: true, force: true });
854
+ }
855
+ toSend.push({ filePath: archiveName, contents: chunkBasenames });
856
+ generatedArchives.add(archiveName);
857
+ seq = nextSeq(archiveSeq);
858
+ }
859
+ }
860
+
861
+ for (const sendItem of toSend) {
862
+ const filePath = sendItem.filePath;
863
+ const baseName = path.basename(filePath);
864
+ const logicalName = baseName.replace(/\.gpg$/i, "");
865
+
866
+ const claimResult = await withStateLock(async () => {
867
+ const currentState = loadState();
868
+ return claimPendingSend(currentState, logicalName, params.metadataType, "oc");
869
+ });
870
+ if (!claimResult.claimed) {
871
+ logger.emit("send-dg.skipped", { file: logicalName, reason: claimResult.reason || "previously-sent" });
872
+ continue;
873
+ }
874
+
875
+ let encrypted = filePath;
876
+ try {
877
+ if (!isEncryptedFile(filePath)) {
878
+ encrypted = await encryptFile(filePath, params.account);
879
+ }
880
+
881
+ const response = await sendToOc(client, params.metadataType, params.fileType, encrypted, params.company);
882
+ if (!transferSucceeded(response)) {
883
+ throw new DataGatheringError(`Upload failed for ${path.basename(encrypted)}`, {
884
+ exitCode: DATA_GATHERING_EXIT_CODES.internalError,
885
+ type: "send-dg.transfer-failed",
886
+ data: {
887
+ file: path.basename(encrypted),
888
+ metadataType: params.metadataType,
889
+ response,
890
+ },
891
+ });
892
+ }
893
+
894
+ const responseWithEncrypted = Object.assign({}, response, { encryptedFile: path.basename(encrypted) });
895
+ try {
896
+ await withStateLock(async () => {
897
+ const currentState = loadState();
898
+ if (Array.isArray(sendItem.contents) && sendItem.contents.length > 0) {
899
+ markSentWithContents(
900
+ currentState,
901
+ logicalName,
902
+ params.metadataType,
903
+ sendItem.contents,
904
+ "oc",
905
+ responseWithEncrypted,
906
+ );
907
+ } else {
908
+ markSent(currentState, logicalName, params.metadataType, "oc", responseWithEncrypted);
909
+ }
910
+ });
911
+ } catch (stateErr) {
912
+ await withStateLock(async () => {
913
+ const currentState = loadState();
914
+ markPossiblySent(
915
+ currentState,
916
+ logicalName,
917
+ params.metadataType,
918
+ "oc",
919
+ responseWithEncrypted,
920
+ stateErr?.message || String(stateErr),
921
+ );
922
+ });
923
+ throw new DataGatheringError(
924
+ `Upload succeeded for ${path.basename(encrypted)}, but send-dg could not persist local state safely`,
925
+ {
926
+ exitCode: DATA_GATHERING_EXIT_CODES.internalError,
927
+ type: "send-dg.state-persist-failed-after-transfer",
928
+ data: {
929
+ file: path.basename(encrypted),
930
+ metadataType: params.metadataType,
931
+ response: responseWithEncrypted,
932
+ cause: stateErr?.message || String(stateErr),
933
+ },
934
+ },
935
+ );
936
+ }
937
+ logger.emit("send-dg.sent", { file: path.basename(encrypted), logicalName });
938
+
939
+ try {
940
+ if (!isEncryptedFile(filePath) && generatedArchives.has(filePath) && fs.existsSync(filePath)) {
941
+ fs.rmSync(filePath, { force: true });
942
+ }
943
+ } catch {
944
+ // ignore cleanup failures
945
+ }
946
+ } catch (err) {
947
+ await withStateLock(async () => {
948
+ const currentState = loadState();
949
+ clearPendingSend(currentState, logicalName, params.metadataType, "oc");
950
+ });
951
+ throw err;
952
+ }
953
+ }
954
+
955
+ return { exitCode: DATA_GATHERING_EXIT_CODES.success };
956
+ }
957
+
958
+ function nextSeq(value) {
959
+ const letters = value.split("").map((char) => char.charCodeAt(0) - 97);
960
+ let index = letters.length - 1;
961
+ while (index >= 0) {
962
+ letters[index] += 1;
963
+ if (letters[index] < 26) break;
964
+ letters[index] = 0;
965
+ index -= 1;
966
+ }
967
+ if (index < 0) letters.unshift(0);
968
+ return letters.map((n) => String.fromCharCode(97 + n)).join("");
969
+ }
970
+
971
+ export { sendDgAction, encryptFile };