@opscompass/opscompass-cli 1.3.5 → 1.3.7
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/lib/cliHelpers.js +10 -6
- package/lib/dataGathering/sendDg.js +171 -1
- package/lib/homeInteraction.js +276 -68
- package/lib/utils.js +22 -0
- package/modules/data-gathering-scripts.js +191 -54
- package/modules/data-gathering.js +45 -1
- package/modules/license-manager/microsoft.js +31 -5
- package/modules/license-manager/oracle.js +513 -0
- package/modules/license-manager.js +57 -6
- package/package.json +7 -6
package/lib/cliHelpers.js
CHANGED
|
@@ -158,17 +158,21 @@ async function downloadFile(downloadUrl, downloadFilePath, downloadName) {
|
|
|
158
158
|
}
|
|
159
159
|
|
|
160
160
|
/**
|
|
161
|
-
* Unzips a file
|
|
162
|
-
* containing the
|
|
163
|
-
* @param {string}
|
|
164
|
-
* @param {string}
|
|
161
|
+
* Unzips a file to the requested extraction directory.
|
|
162
|
+
* @param {string} unzipFileLocation directory containing the zip archive
|
|
163
|
+
* @param {string} unzipFileName archive file name
|
|
164
|
+
* @param {string} extractionDestination directory receiving extracted contents
|
|
165
165
|
*/
|
|
166
|
-
async function unzipFile(
|
|
166
|
+
async function unzipFile(
|
|
167
|
+
unzipFileLocation,
|
|
168
|
+
unzipFileName,
|
|
169
|
+
extractionDestination = unzipFileLocation,
|
|
170
|
+
) {
|
|
167
171
|
const zipFileLocation = path.join(unzipFileLocation, unzipFileName);
|
|
168
172
|
try {
|
|
169
173
|
const zip = new AdmZip(zipFileLocation);
|
|
170
174
|
// Overwrite and keepOriginalPermissions
|
|
171
|
-
zip.extractAllTo(
|
|
175
|
+
zip.extractAllTo(extractionDestination, true, true);
|
|
172
176
|
} catch (err) {
|
|
173
177
|
deleteFile(zipFileLocation);
|
|
174
178
|
throw "Something went wrong during unzipping.\nIf you specified a script version, confirm it is correct.\nIf the error continues, contact your OpsCompass rep.";
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
2
|
import os from "os";
|
|
3
3
|
import path from "path";
|
|
4
|
-
import
|
|
4
|
+
import crypto from "crypto";
|
|
5
|
+
import * as tarModule from "tar";
|
|
6
|
+
const tar = tarModule.create ? tarModule : tarModule.default;
|
|
5
7
|
import * as openpgp from "openpgp";
|
|
6
8
|
|
|
7
9
|
import { getOpsCompassClient } from "../../opscompass.js";
|
|
@@ -690,6 +692,104 @@ function isArchiveFile(filePath) {
|
|
|
690
692
|
return lower.endsWith(".tgz") || lower.endsWith(".tar.gz");
|
|
691
693
|
}
|
|
692
694
|
|
|
695
|
+
function canonicalizeEncryptedArchiveForUpload(filePath) {
|
|
696
|
+
if (!filePath.toLowerCase().endsWith(".tar.gz.gpg")) {
|
|
697
|
+
return { filePath };
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "opscompass-send-dg-upload-"));
|
|
701
|
+
const uploadPath = path.join(
|
|
702
|
+
tempDir,
|
|
703
|
+
`${path.basename(filePath).slice(0, -".tar.gz.gpg".length)}.tgz.gpg`,
|
|
704
|
+
);
|
|
705
|
+
fs.copyFileSync(filePath, uploadPath);
|
|
706
|
+
return { filePath: uploadPath, tempDir };
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function logCheckpointKey(company, account, logDirectory) {
|
|
710
|
+
return `${company}\u0000${account || ""}\u0000${path.resolve(logDirectory)}`;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function collectEligibleLogs(logDirectory, checkpointMs, startedAtMs) {
|
|
714
|
+
if (!fs.existsSync(logDirectory)) return { files: [], reason: "directory-missing" };
|
|
715
|
+
const stat = fs.statSync(logDirectory);
|
|
716
|
+
if (!stat.isDirectory()) return { files: [], reason: "not-a-directory" };
|
|
717
|
+
const files = fs.readdirSync(logDirectory, { withFileTypes: true })
|
|
718
|
+
.filter((entry) => entry.isFile() && !entry.isSymbolicLink())
|
|
719
|
+
.map((entry) => path.join(logDirectory, entry.name))
|
|
720
|
+
.filter((filePath) => {
|
|
721
|
+
try {
|
|
722
|
+
const mtimeMs = fs.statSync(filePath).mtimeMs;
|
|
723
|
+
return mtimeMs > checkpointMs && mtimeMs <= startedAtMs;
|
|
724
|
+
} catch (error) {
|
|
725
|
+
if (error?.code === "ENOENT") return false;
|
|
726
|
+
throw error;
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
return { files };
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
async function createLogsArchive(logDirectory, checkpointMs, startedAtMs) {
|
|
733
|
+
const eligible = collectEligibleLogs(logDirectory, checkpointMs, startedAtMs);
|
|
734
|
+
if (eligible.reason || eligible.files.length === 0) return eligible;
|
|
735
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "opscompass-send-dg-logs-"));
|
|
736
|
+
const archivePath = path.join(
|
|
737
|
+
tempDir,
|
|
738
|
+
`opscompass-dg-logs_${toTimestamp()}_${crypto.randomUUID()}.tgz`,
|
|
739
|
+
);
|
|
740
|
+
try {
|
|
741
|
+
await tar.create({
|
|
742
|
+
file: archivePath,
|
|
743
|
+
gzip: true,
|
|
744
|
+
cwd: logDirectory,
|
|
745
|
+
}, eligible.files.map((filePath) => path.basename(filePath)));
|
|
746
|
+
} catch (error) {
|
|
747
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
748
|
+
throw error;
|
|
749
|
+
}
|
|
750
|
+
return { files: eligible.files, archivePath, tempDir };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
async function augmentArchiveWithLogs(archivePath, logsArchivePath, encrypted, account) {
|
|
754
|
+
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "opscompass-send-dg-repack-"));
|
|
755
|
+
const inputArchive = path.join(tempRoot, "input.tgz");
|
|
756
|
+
const outputArchive = path.join(tempRoot, "output.tgz");
|
|
757
|
+
try {
|
|
758
|
+
if (encrypted) {
|
|
759
|
+
const encryptedBytes = fs.readFileSync(archivePath);
|
|
760
|
+
const message = await openpgp.readMessage({ binaryMessage: encryptedBytes });
|
|
761
|
+
const { data } = await openpgp.decrypt({
|
|
762
|
+
message,
|
|
763
|
+
passwords: [`${utilsModule.hobKey}${account}`],
|
|
764
|
+
format: "binary",
|
|
765
|
+
});
|
|
766
|
+
fs.writeFileSync(inputArchive, Buffer.from(data));
|
|
767
|
+
} else {
|
|
768
|
+
fs.copyFileSync(archivePath, inputArchive);
|
|
769
|
+
}
|
|
770
|
+
const extractedDir = path.join(tempRoot, "extracted");
|
|
771
|
+
fs.mkdirSync(extractedDir);
|
|
772
|
+
await tar.extract({ file: inputArchive, cwd: extractedDir });
|
|
773
|
+
fs.copyFileSync(logsArchivePath, path.join(extractedDir, path.basename(logsArchivePath)));
|
|
774
|
+
const entries = fs.readdirSync(extractedDir);
|
|
775
|
+
await tar.create({ file: outputArchive, gzip: true, cwd: extractedDir }, entries);
|
|
776
|
+
if (!encrypted) {
|
|
777
|
+
fs.copyFileSync(outputArchive, archivePath);
|
|
778
|
+
return { filePath: archivePath };
|
|
779
|
+
}
|
|
780
|
+
const encryptedOutput = await encryptFile(outputArchive, account);
|
|
781
|
+
const stableOutputDir = fs.mkdtempSync(path.join(os.tmpdir(), "opscompass-send-dg-log-upload-"));
|
|
782
|
+
const stableOutput = path.join(
|
|
783
|
+
stableOutputDir,
|
|
784
|
+
`${path.basename(archivePath).replace(/\.gpg$/i, "")}.gpg`,
|
|
785
|
+
);
|
|
786
|
+
fs.copyFileSync(encryptedOutput, stableOutput);
|
|
787
|
+
return { filePath: stableOutput, tempDir: stableOutputDir };
|
|
788
|
+
} finally {
|
|
789
|
+
fs.rmSync(tempRoot, { recursive: true, force: true });
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
693
793
|
async function sendDgAction(args = [], logger = { emit: () => {} }) {
|
|
694
794
|
const params = {
|
|
695
795
|
metadataType: undefined,
|
|
@@ -699,6 +799,7 @@ async function sendDgAction(args = [], logger = { emit: () => {} }) {
|
|
|
699
799
|
company: undefined,
|
|
700
800
|
account: undefined,
|
|
701
801
|
directory: process.cwd(),
|
|
802
|
+
logDirectory: path.join(utilsModule.opscompassHome, "log"),
|
|
702
803
|
};
|
|
703
804
|
|
|
704
805
|
function readFlagValue(arr, idx, flag) {
|
|
@@ -740,6 +841,10 @@ async function sendDgAction(args = [], logger = { emit: () => {} }) {
|
|
|
740
841
|
params.directory = readFlagValue(args, i, arg);
|
|
741
842
|
i += 1;
|
|
742
843
|
break;
|
|
844
|
+
case "--log-directory":
|
|
845
|
+
params.logDirectory = readFlagValue(args, i, arg);
|
|
846
|
+
i += 1;
|
|
847
|
+
break;
|
|
743
848
|
default:
|
|
744
849
|
if (arg.startsWith("--")) {
|
|
745
850
|
throw new DataGatheringError(`Unknown flag: ${arg}`, {
|
|
@@ -857,6 +962,52 @@ async function sendDgAction(args = [], logger = { emit: () => {} }) {
|
|
|
857
962
|
seq = nextSeq(archiveSeq);
|
|
858
963
|
}
|
|
859
964
|
}
|
|
965
|
+
const startedAtMs = Date.now();
|
|
966
|
+
const checkpointKey = logCheckpointKey(params.company, params.account, params.logDirectory);
|
|
967
|
+
const previousCheckpoint = Number(state.logCheckpoints?.[checkpointKey]?.successfulAtMs || 0);
|
|
968
|
+
let logArchivePath;
|
|
969
|
+
let logArchiveTempDir;
|
|
970
|
+
const stableOutputTempDirs = new Set();
|
|
971
|
+
let logFiles = [];
|
|
972
|
+
let logSendItem;
|
|
973
|
+
let logSendSucceeded = false;
|
|
974
|
+
try {
|
|
975
|
+
const logResult = await createLogsArchive(path.resolve(params.logDirectory), previousCheckpoint, startedAtMs);
|
|
976
|
+
logArchiveTempDir = logResult.tempDir;
|
|
977
|
+
if (logResult.reason || !logResult.archivePath) {
|
|
978
|
+
logger.emit("send-dg.logs-skipped", { directory: params.logDirectory, reason: logResult.reason || "no-eligible-files" });
|
|
979
|
+
} else {
|
|
980
|
+
logArchivePath = logResult.archivePath;
|
|
981
|
+
logFiles = logResult.files;
|
|
982
|
+
const target = toSend.find((item) => isArchiveFile(item.filePath) || isEncryptedFile(item.filePath));
|
|
983
|
+
if (target) {
|
|
984
|
+
const originalPath = target.filePath;
|
|
985
|
+
const augmented = await augmentArchiveWithLogs(
|
|
986
|
+
originalPath,
|
|
987
|
+
logArchivePath,
|
|
988
|
+
isEncryptedFile(originalPath),
|
|
989
|
+
params.account,
|
|
990
|
+
);
|
|
991
|
+
target.filePath = augmented.filePath;
|
|
992
|
+
if (augmented.tempDir) stableOutputTempDirs.add(augmented.tempDir);
|
|
993
|
+
logSendItem = target;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
} catch (error) {
|
|
997
|
+
logFiles = [];
|
|
998
|
+
logArchivePath = undefined;
|
|
999
|
+
logger.emit("send-dg.logs-skipped", {
|
|
1000
|
+
directory: params.logDirectory,
|
|
1001
|
+
reason: "archive-failed",
|
|
1002
|
+
message: error?.message || String(error),
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
if (logArchiveTempDir) {
|
|
1006
|
+
fs.rmSync(logArchiveTempDir, { recursive: true, force: true });
|
|
1007
|
+
logArchiveTempDir = undefined;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
try {
|
|
860
1011
|
|
|
861
1012
|
for (const sendItem of toSend) {
|
|
862
1013
|
const filePath = sendItem.filePath;
|
|
@@ -877,6 +1028,9 @@ async function sendDgAction(args = [], logger = { emit: () => {} }) {
|
|
|
877
1028
|
if (!isEncryptedFile(filePath)) {
|
|
878
1029
|
encrypted = await encryptFile(filePath, params.account);
|
|
879
1030
|
}
|
|
1031
|
+
const uploadArchive = canonicalizeEncryptedArchiveForUpload(encrypted);
|
|
1032
|
+
encrypted = uploadArchive.filePath;
|
|
1033
|
+
if (uploadArchive.tempDir) stableOutputTempDirs.add(uploadArchive.tempDir);
|
|
880
1034
|
|
|
881
1035
|
const response = await sendToOc(client, params.metadataType, params.fileType, encrypted, params.company);
|
|
882
1036
|
if (!transferSucceeded(response)) {
|
|
@@ -935,6 +1089,9 @@ async function sendDgAction(args = [], logger = { emit: () => {} }) {
|
|
|
935
1089
|
);
|
|
936
1090
|
}
|
|
937
1091
|
logger.emit("send-dg.sent", { file: path.basename(encrypted), logicalName });
|
|
1092
|
+
if (sendItem === logSendItem) {
|
|
1093
|
+
logSendSucceeded = true;
|
|
1094
|
+
}
|
|
938
1095
|
|
|
939
1096
|
try {
|
|
940
1097
|
if (!isEncryptedFile(filePath) && generatedArchives.has(filePath) && fs.existsSync(filePath)) {
|
|
@@ -952,7 +1109,20 @@ async function sendDgAction(args = [], logger = { emit: () => {} }) {
|
|
|
952
1109
|
}
|
|
953
1110
|
}
|
|
954
1111
|
|
|
1112
|
+
if (logSendSucceeded && logFiles.length > 0) {
|
|
1113
|
+
await withStateLock(async () => {
|
|
1114
|
+
const currentState = loadState();
|
|
1115
|
+
currentState.logCheckpoints = currentState.logCheckpoints || {};
|
|
1116
|
+
currentState.logCheckpoints[checkpointKey] = { successfulAtMs: startedAtMs };
|
|
1117
|
+
saveState(currentState);
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
955
1120
|
return { exitCode: DATA_GATHERING_EXIT_CODES.success };
|
|
1121
|
+
} finally {
|
|
1122
|
+
for (const tempDir of stableOutputTempDirs) {
|
|
1123
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
956
1126
|
}
|
|
957
1127
|
|
|
958
1128
|
function nextSeq(value) {
|
package/lib/homeInteraction.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from "fs-extra";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
2
3
|
import path from "path";
|
|
3
4
|
import {
|
|
4
5
|
Verify,
|
|
@@ -12,11 +13,9 @@ import {
|
|
|
12
13
|
} from "../environment/current.js";
|
|
13
14
|
import {
|
|
14
15
|
findOrCreateFolder,
|
|
15
|
-
deleteDirectory,
|
|
16
16
|
downloadFile,
|
|
17
17
|
unzipFile,
|
|
18
18
|
deleteFile,
|
|
19
|
-
moveFolder,
|
|
20
19
|
writeFile,
|
|
21
20
|
canReadFile,
|
|
22
21
|
getAllFilesInFolder,
|
|
@@ -111,13 +110,148 @@ async function getScriptMetadata(scriptType) {
|
|
|
111
110
|
}
|
|
112
111
|
}
|
|
113
112
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
113
|
+
function assertDirectChildSemver(version, description) {
|
|
114
|
+
if (
|
|
115
|
+
typeof version !== "string" ||
|
|
116
|
+
path.posix.basename(version) !== version ||
|
|
117
|
+
path.win32.basename(version) !== version ||
|
|
118
|
+
!semver.valid(version)
|
|
119
|
+
) {
|
|
120
|
+
throw new Error(`${description} must be a direct-child semantic version.`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return version;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function versionFromArchiveName(fileName) {
|
|
127
|
+
if (
|
|
128
|
+
typeof fileName !== "string" ||
|
|
129
|
+
path.posix.basename(fileName) !== fileName ||
|
|
130
|
+
path.win32.basename(fileName) !== fileName ||
|
|
131
|
+
!fileName.endsWith(".zip")
|
|
132
|
+
) {
|
|
133
|
+
throw new Error("Script archive name must be a direct-child .zip file.");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return fileName.slice(0, -".zip".length);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function validateInstalledMetadata(scriptType, scriptTypePath, srcPath) {
|
|
140
|
+
const metadataPath = path.join(scriptTypePath, METADATA_FILE_NAME);
|
|
141
|
+
if (!fs.existsSync(metadataPath)) {
|
|
142
|
+
if (fs.existsSync(srcPath)) {
|
|
143
|
+
throw new Error(
|
|
144
|
+
`Cannot replace ${scriptType} scripts because ${METADATA_FILE_NAME} does not contain the installed version.`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
const scriptMetadata = await getScriptMetadata(scriptType);
|
|
152
|
+
assertDirectChildSemver(
|
|
153
|
+
scriptMetadata?.version,
|
|
154
|
+
`Installed ${METADATA_FILE_NAME} version`,
|
|
155
|
+
);
|
|
156
|
+
} catch (err) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`Cannot replace ${scriptType} scripts because ${METADATA_FILE_NAME} is unreadable or lacks a valid direct-child semantic version.`,
|
|
159
|
+
{ cause: err },
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function normalizeScriptPermissions(destinationPath) {
|
|
165
|
+
const allFilePaths = getAllFilesInFolder(destinationPath);
|
|
166
|
+
allFilePaths.forEach(function (filePath) {
|
|
167
|
+
// Skip files we don't care about ({hidden}, bat, txt, ...)
|
|
168
|
+
if (path.basename(filePath).match(/^\./)) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const fileExtension = path.extname(filePath);
|
|
173
|
+
if (fileExtension.match(/bat|txt|pl/)) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const fileStat = fs.lstatSync(filePath);
|
|
178
|
+
if (fileStat.mode & 0o007) {
|
|
179
|
+
fs.chmodSync(filePath, fileStat.mode & 0o770);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function removeInstallArtifact(artifactPath, output, description) {
|
|
185
|
+
try {
|
|
186
|
+
await fs.rm(artifactPath, { recursive: true, force: true });
|
|
187
|
+
} catch (err) {
|
|
188
|
+
output.warn?.(`Unable to remove ${description} ${artifactPath}: ${err}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function cleanupOldBackups(backupRoot, keepBackupPath, output) {
|
|
193
|
+
if (!fs.existsSync(backupRoot)) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
let entries;
|
|
198
|
+
try {
|
|
199
|
+
entries = await fs.readdir(backupRoot, { withFileTypes: true });
|
|
200
|
+
} catch (err) {
|
|
201
|
+
output.warn?.(`Unable to inspect script backups ${backupRoot}: ${err}`);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const backupEntries = entries.filter((entry) =>
|
|
206
|
+
entry.name.startsWith("backup-"),
|
|
207
|
+
);
|
|
208
|
+
if (!keepBackupPath && backupEntries.length > 0) {
|
|
209
|
+
let newestModifiedTime = -Infinity;
|
|
210
|
+
try {
|
|
211
|
+
for (const entry of backupEntries) {
|
|
212
|
+
const backupPath = path.join(backupRoot, entry.name);
|
|
213
|
+
const modifiedTime = (await fs.stat(backupPath)).mtimeMs;
|
|
214
|
+
if (modifiedTime >= newestModifiedTime) {
|
|
215
|
+
newestModifiedTime = modifiedTime;
|
|
216
|
+
keepBackupPath = backupPath;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
} catch (err) {
|
|
220
|
+
output.warn?.(`Unable to inspect script backups ${backupRoot}: ${err}`);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
for (const entry of backupEntries) {
|
|
226
|
+
const backupPath = path.join(backupRoot, entry.name);
|
|
227
|
+
if (backupPath === keepBackupPath) {
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
await removeInstallArtifact(backupPath, output, "old script backup");
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function restorePreviousSource({
|
|
235
|
+
srcPath,
|
|
236
|
+
stagedPayloadPath,
|
|
237
|
+
backupPath,
|
|
238
|
+
previousSourceBackedUp,
|
|
239
|
+
payloadPromoted,
|
|
240
|
+
installError,
|
|
241
|
+
}) {
|
|
242
|
+
try {
|
|
243
|
+
if (payloadPromoted) {
|
|
244
|
+
await fs.rename(srcPath, stagedPayloadPath);
|
|
245
|
+
}
|
|
246
|
+
if (previousSourceBackedUp) {
|
|
247
|
+
await fs.rename(backupPath, srcPath);
|
|
248
|
+
}
|
|
249
|
+
} catch (rollbackError) {
|
|
250
|
+
throw new Error(
|
|
251
|
+
`Script install failed (${installError}); rollback also failed (${rollbackError}). Live source: ${srcPath}. Previous source backup: ${backupPath || "none"}. Staged payload: ${stagedPayloadPath}.`,
|
|
252
|
+
{ cause: installError },
|
|
253
|
+
);
|
|
254
|
+
}
|
|
121
255
|
}
|
|
122
256
|
|
|
123
257
|
/**
|
|
@@ -199,7 +333,7 @@ async function downloadScriptsToHome(
|
|
|
199
333
|
);
|
|
200
334
|
const scriptTypePath = findOrCreateScriptTypeFolder(scriptType);
|
|
201
335
|
const fileName = scriptDownloadInfo.fileName;
|
|
202
|
-
scriptVersion = fileName
|
|
336
|
+
scriptVersion = versionFromArchiveName(fileName);
|
|
203
337
|
|
|
204
338
|
await downloadFile(
|
|
205
339
|
scriptDownloadInfo.downloadUrl,
|
|
@@ -208,68 +342,132 @@ async function downloadScriptsToHome(
|
|
|
208
342
|
);
|
|
209
343
|
|
|
210
344
|
scriptDownloadInfo.filePath = path.join(scriptTypePath, fileName);
|
|
211
|
-
|
|
212
|
-
|
|
345
|
+
let stagingDirectory;
|
|
346
|
+
let stagedPayloadPath;
|
|
347
|
+
let backupArtifactPath;
|
|
348
|
+
let backupPath;
|
|
349
|
+
let preserveDiagnosticPaths = false;
|
|
213
350
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
throw new Error(
|
|
218
|
-
`Script bundle verification failed for ${scriptType}: ${verification.reason || "invalid signature"}`,
|
|
219
|
-
);
|
|
220
|
-
}
|
|
351
|
+
try {
|
|
352
|
+
const verification =
|
|
353
|
+
(await Verify(scriptDownloadInfo, output)) || SCRIPT_VERIFICATION_FALLBACK;
|
|
221
354
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
355
|
+
// Signature present but invalid must fail closed and not install.
|
|
356
|
+
if (verification.status === SCRIPT_BUNDLE_VERIFICATION_STATUS.invalid) {
|
|
357
|
+
throw new Error(
|
|
358
|
+
`Script bundle verification failed for ${scriptType}: ${verification.reason || "invalid signature"}`,
|
|
359
|
+
);
|
|
360
|
+
}
|
|
229
361
|
|
|
230
|
-
|
|
362
|
+
if (verification.status !== SCRIPT_BUNDLE_VERIFICATION_STATUS.verified) {
|
|
363
|
+
output.warn?.(
|
|
364
|
+
"Downloaded %s bundle is unverified (%s)",
|
|
365
|
+
scriptType,
|
|
366
|
+
verification.reason || "unknown",
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
assertDirectChildSemver(scriptVersion, "Script archive version");
|
|
231
370
|
|
|
232
|
-
|
|
371
|
+
const stagingRoot = path.join(scriptTypePath, ".src-staging");
|
|
372
|
+
await fs.ensureDir(stagingRoot);
|
|
373
|
+
stagingDirectory = await fs.mkdtemp(path.join(stagingRoot, "install-"));
|
|
374
|
+
await unzipFile(scriptTypePath, fileName, stagingDirectory);
|
|
233
375
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
376
|
+
stagedPayloadPath = path.join(stagingDirectory, scriptVersion);
|
|
377
|
+
let stagedPayloadStat;
|
|
378
|
+
try {
|
|
379
|
+
stagedPayloadStat = await fs.lstat(stagedPayloadPath);
|
|
380
|
+
} catch (err) {
|
|
381
|
+
throw new Error(
|
|
382
|
+
`Script archive does not contain the expected ${scriptVersion} directory.`,
|
|
383
|
+
{ cause: err },
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
if (!stagedPayloadStat.isDirectory()) {
|
|
387
|
+
throw new Error(
|
|
388
|
+
`Script archive does not contain the expected ${scriptVersion} directory.`,
|
|
389
|
+
);
|
|
390
|
+
}
|
|
240
391
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
392
|
+
normalizeScriptPermissions(stagedPayloadPath);
|
|
393
|
+
|
|
394
|
+
const srcPath = path.join(scriptTypePath, SRC_FOLDER_NAME);
|
|
395
|
+
await validateInstalledMetadata(scriptType, scriptTypePath, srcPath);
|
|
396
|
+
|
|
397
|
+
let previousSourceBackedUp = false;
|
|
398
|
+
let payloadPromoted = false;
|
|
399
|
+
|
|
400
|
+
// WHY: NFS clients can keep live script files open, so recursive replacement is not a safe cutover.
|
|
401
|
+
// DECISION: validate installed metadata before any live rename so an unsafe recovery state fails while src is untouched; use only native same-filesystem renames for the live transition.
|
|
402
|
+
// DECISION: Leave legacy direct-child semver folders untouched because an interrupted older installer may have left its only recoverable payload there.
|
|
403
|
+
// TRADEOFF: Keep the newest hidden backup with its validated metadata beside src after a successful cutover, accepting its disk-space cost for a self-describing recovery point.
|
|
404
|
+
try {
|
|
405
|
+
if (fs.existsSync(srcPath)) {
|
|
406
|
+
const backupRoot = path.join(scriptTypePath, ".src-backups");
|
|
407
|
+
await fs.ensureDir(backupRoot);
|
|
408
|
+
backupArtifactPath = await fs.mkdtemp(
|
|
409
|
+
path.join(backupRoot, "backup-"),
|
|
410
|
+
);
|
|
411
|
+
backupPath = path.join(backupArtifactPath, SRC_FOLDER_NAME);
|
|
412
|
+
await fs.copy(
|
|
413
|
+
path.join(scriptTypePath, METADATA_FILE_NAME),
|
|
414
|
+
path.join(backupArtifactPath, METADATA_FILE_NAME),
|
|
415
|
+
);
|
|
416
|
+
await fs.rename(srcPath, backupPath);
|
|
417
|
+
previousSourceBackedUp = true;
|
|
252
418
|
}
|
|
253
|
-
}
|
|
254
419
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
420
|
+
await fs.rename(stagedPayloadPath, srcPath);
|
|
421
|
+
payloadPromoted = true;
|
|
422
|
+
|
|
423
|
+
await setScriptMetadata(scriptTypePath, scriptVersion, verification);
|
|
424
|
+
} catch (installError) {
|
|
425
|
+
try {
|
|
426
|
+
await restorePreviousSource({
|
|
427
|
+
srcPath,
|
|
428
|
+
stagedPayloadPath,
|
|
429
|
+
backupPath,
|
|
430
|
+
previousSourceBackedUp,
|
|
431
|
+
payloadPromoted,
|
|
432
|
+
installError,
|
|
433
|
+
});
|
|
434
|
+
} catch (rollbackError) {
|
|
435
|
+
preserveDiagnosticPaths = true;
|
|
436
|
+
throw rollbackError;
|
|
437
|
+
}
|
|
438
|
+
throw installError;
|
|
263
439
|
}
|
|
264
|
-
});
|
|
265
440
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
441
|
+
await cleanupOldBackups(
|
|
442
|
+
path.join(scriptTypePath, ".src-backups"),
|
|
443
|
+
backupArtifactPath,
|
|
444
|
+
output,
|
|
445
|
+
);
|
|
270
446
|
|
|
271
|
-
|
|
272
|
-
|
|
447
|
+
return scriptVersion;
|
|
448
|
+
} finally {
|
|
449
|
+
if (fs.existsSync(scriptDownloadInfo.filePath)) {
|
|
450
|
+
deleteFile(scriptDownloadInfo.filePath);
|
|
451
|
+
}
|
|
452
|
+
if (stagingDirectory && !preserveDiagnosticPaths) {
|
|
453
|
+
await removeInstallArtifact(
|
|
454
|
+
stagingDirectory,
|
|
455
|
+
output,
|
|
456
|
+
"script staging directory",
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
if (
|
|
460
|
+
backupArtifactPath &&
|
|
461
|
+
!preserveDiagnosticPaths &&
|
|
462
|
+
!fs.existsSync(backupPath)
|
|
463
|
+
) {
|
|
464
|
+
await removeInstallArtifact(
|
|
465
|
+
backupArtifactPath,
|
|
466
|
+
output,
|
|
467
|
+
"empty script backup",
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
273
471
|
}
|
|
274
472
|
|
|
275
473
|
/**
|
|
@@ -287,7 +485,7 @@ function previousScriptsDownloaded(scriptType) {
|
|
|
287
485
|
}
|
|
288
486
|
|
|
289
487
|
/**
|
|
290
|
-
*
|
|
488
|
+
* Atomically creates or updates a script's metadata.
|
|
291
489
|
* @param {string} scriptFolderPath path to the script folder
|
|
292
490
|
* @param {string} scriptVersion the version of the downloaded script
|
|
293
491
|
*/
|
|
@@ -296,6 +494,7 @@ async function setScriptMetadata(
|
|
|
296
494
|
scriptVersion,
|
|
297
495
|
verification = SCRIPT_VERIFICATION_FALLBACK,
|
|
298
496
|
) {
|
|
497
|
+
assertDirectChildSemver(scriptVersion, "Installed metadata version");
|
|
299
498
|
const scriptMetadata = {
|
|
300
499
|
version: scriptVersion,
|
|
301
500
|
verification: {
|
|
@@ -309,13 +508,23 @@ async function setScriptMetadata(
|
|
|
309
508
|
};
|
|
310
509
|
|
|
311
510
|
const metadataFilePath = path.join(scriptFolderPath, METADATA_FILE_NAME);
|
|
511
|
+
const pendingMetadataPath = path.join(
|
|
512
|
+
scriptFolderPath,
|
|
513
|
+
`.metadata-${randomUUID()}.tmp`,
|
|
514
|
+
);
|
|
312
515
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
516
|
+
try {
|
|
517
|
+
await writeFile(pendingMetadataPath, scriptMetadata);
|
|
518
|
+
await fs.rename(pendingMetadataPath, metadataFilePath);
|
|
519
|
+
} finally {
|
|
520
|
+
if (fs.existsSync(pendingMetadataPath)) {
|
|
521
|
+
try {
|
|
522
|
+
await fs.rm(pendingMetadataPath, { force: true });
|
|
523
|
+
} catch {
|
|
524
|
+
// The original write/rename failure is more useful than temp cleanup.
|
|
525
|
+
}
|
|
526
|
+
}
|
|
316
527
|
}
|
|
317
|
-
|
|
318
|
-
await writeFile(metadataFilePath, scriptMetadata);
|
|
319
528
|
}
|
|
320
529
|
|
|
321
530
|
async function getScriptVerificationState(scriptType) {
|
|
@@ -355,7 +564,6 @@ export {
|
|
|
355
564
|
getInstalledScriptVersion,
|
|
356
565
|
getScriptVerificationState,
|
|
357
566
|
assertScriptBundleVerified,
|
|
358
|
-
removeCurrentlyInstalledScript,
|
|
359
567
|
downloadScriptsToHome,
|
|
360
568
|
previousScriptsDownloaded,
|
|
361
569
|
};
|