badmfck-api-server 5.0.13 → 5.0.15
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/bluegreen.help.md +116 -1
- package/dist/apiServer/APIService.d.ts +2 -0
- package/dist/apiServer/APIService.js +24 -0
- package/dist/apiServer/LogService.js +1 -0
- package/dist/apiServer/MonitorService.js +11 -0
- package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
- package/dist/apiServer/deployment/BackupManager.js +174 -0
- package/dist/apiServer/deployment/Backups.d.ts +2 -0
- package/dist/apiServer/deployment/Backups.js +43 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +6 -1
- package/dist/apiServer/deployment/ConfigService.js +3 -1
- package/dist/apiServer/deployment/Deployer.d.ts +2 -0
- package/dist/apiServer/deployment/Deployer.js +18 -0
- package/dist/apiServer/deployment/DeployerService.d.ts +73 -1
- package/dist/apiServer/deployment/DeployerService.js +293 -18
- package/dist/apiServer/deployment/Restore.d.ts +2 -0
- package/dist/apiServer/deployment/Restore.js +88 -0
- package/dist/apiServer/deployment/cli.js +38 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +14 -0
- package/dist/apiServer/deployment/cliCommon.js +58 -0
- package/dist/apiServer/helper/ClientIp.d.ts +2 -0
- package/dist/apiServer/helper/ClientIp.js +28 -0
- package/dist/apiServer/monitor/Monitor.d.ts +1 -0
- package/dist/apiServer/monitor/Monitor.js +12 -2
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +65 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +153 -0
- package/dist/apiServer/monitor/index.html +105 -61
- package/dist/apiServer/structures/Interfaces.d.ts +1 -0
- package/monitoring.help.md +46 -0
- package/package.json +1 -1
|
@@ -50,6 +50,16 @@ export declare const REQ_DEPLOYMENT_SLOT: Req<{
|
|
|
50
50
|
token: string;
|
|
51
51
|
slot?: "blue" | "green";
|
|
52
52
|
}, any>;
|
|
53
|
+
export declare const REQ_DEPLOYMENT_BACKUPS: Req<{
|
|
54
|
+
auth?: string;
|
|
55
|
+
name: string;
|
|
56
|
+
}, any>;
|
|
57
|
+
export declare const REQ_DEPLOYMENT_RESTORE: Req<{
|
|
58
|
+
auth?: string;
|
|
59
|
+
name: string;
|
|
60
|
+
token: string;
|
|
61
|
+
backup: string;
|
|
62
|
+
}, any>;
|
|
53
63
|
export declare class DeployerService extends BaseService {
|
|
54
64
|
private static MAX_HISTORY;
|
|
55
65
|
private static _trimHistory;
|
|
@@ -128,6 +138,64 @@ export declare class DeployerService extends BaseService {
|
|
|
128
138
|
readyToSwitch: boolean;
|
|
129
139
|
}>;
|
|
130
140
|
}>;
|
|
141
|
+
private static _isBlueGreen;
|
|
142
|
+
private static _backupRoot;
|
|
143
|
+
listBackups(data: {
|
|
144
|
+
auth?: string;
|
|
145
|
+
name: string;
|
|
146
|
+
}): Promise<{
|
|
147
|
+
data?: undefined;
|
|
148
|
+
error: {
|
|
149
|
+
code: number;
|
|
150
|
+
message: string;
|
|
151
|
+
httpStatus: number;
|
|
152
|
+
};
|
|
153
|
+
} | {
|
|
154
|
+
error?: undefined;
|
|
155
|
+
data: {
|
|
156
|
+
project: string;
|
|
157
|
+
bluegreen: boolean;
|
|
158
|
+
activeSlot: string | null;
|
|
159
|
+
backupEnabled: boolean;
|
|
160
|
+
keep: number;
|
|
161
|
+
backups: import("./BackupManager").IBackupInfo[];
|
|
162
|
+
};
|
|
163
|
+
}>;
|
|
164
|
+
restoreBackup(data: {
|
|
165
|
+
auth?: string;
|
|
166
|
+
name: string;
|
|
167
|
+
token: string;
|
|
168
|
+
backup: string;
|
|
169
|
+
}): Promise<{
|
|
170
|
+
data?: undefined;
|
|
171
|
+
error: {
|
|
172
|
+
code: number;
|
|
173
|
+
message: string;
|
|
174
|
+
httpStatus: number;
|
|
175
|
+
details?: undefined;
|
|
176
|
+
};
|
|
177
|
+
} | {
|
|
178
|
+
data?: undefined;
|
|
179
|
+
error: {
|
|
180
|
+
code: number;
|
|
181
|
+
message: string;
|
|
182
|
+
details: string;
|
|
183
|
+
httpStatus: number;
|
|
184
|
+
};
|
|
185
|
+
} | {
|
|
186
|
+
error?: undefined;
|
|
187
|
+
data: {
|
|
188
|
+
project: string;
|
|
189
|
+
restored: string;
|
|
190
|
+
appVersion: string | null;
|
|
191
|
+
slot: import("./BackupManager").TBackupSlot;
|
|
192
|
+
activeSlot: "blue" | "green" | null;
|
|
193
|
+
live: boolean;
|
|
194
|
+
preRestoreBackup: string | null;
|
|
195
|
+
pm2Restarted: boolean;
|
|
196
|
+
pm2Error: string | null;
|
|
197
|
+
};
|
|
198
|
+
}>;
|
|
131
199
|
slotState(data: {
|
|
132
200
|
name: string;
|
|
133
201
|
token: string;
|
|
@@ -161,7 +229,11 @@ export declare class DeployerService extends BaseService {
|
|
|
161
229
|
private static readonly TEMPLATE_EXTENSIONS;
|
|
162
230
|
applyConfig(dir: string, config: Record<string, string>): Promise<void>;
|
|
163
231
|
processFile(filePath: string, config: Record<string, string>): Promise<void>;
|
|
164
|
-
private
|
|
232
|
+
private _destinationProblem;
|
|
233
|
+
private static _unsafeArchiveEntry;
|
|
234
|
+
private static _escapingSymlink;
|
|
235
|
+
private _runMigrate;
|
|
236
|
+
static MIGRATE_TIMEOUT_MS: number;
|
|
165
237
|
unpack(destination: string, uploadedFile: string, install?: boolean, ignoreDirectoryClean?: boolean): Promise<IError | null>;
|
|
166
238
|
upload(file: UploadedFile, uploadPath: string): Promise<IError | null>;
|
|
167
239
|
}
|
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.DeployerService = exports.REQ_DEPLOYMENT_SLOT = exports.REQ_DEPLOYMENT_STATUS = exports.REQ_DEPLOYMENT_SWITCH = exports.REQ_DEPLOYMENT_PROCEED = void 0;
|
|
6
|
+
exports.DeployerService = exports.REQ_DEPLOYMENT_RESTORE = exports.REQ_DEPLOYMENT_BACKUPS = exports.REQ_DEPLOYMENT_SLOT = exports.REQ_DEPLOYMENT_STATUS = exports.REQ_DEPLOYMENT_SWITCH = exports.REQ_DEPLOYMENT_PROCEED = void 0;
|
|
7
7
|
const badmfck_signal_1 = require("badmfck-signal");
|
|
8
8
|
const BaseService_1 = require("../BaseService");
|
|
9
9
|
const ConfigService_1 = require("./ConfigService");
|
|
@@ -12,11 +12,14 @@ const LogService_1 = require("../LogService");
|
|
|
12
12
|
const __1 = require("../..");
|
|
13
13
|
const Notifier_1 = require("./Notifier");
|
|
14
14
|
const child_process_1 = require("child_process");
|
|
15
|
+
const util_1 = require("util");
|
|
16
|
+
const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
|
|
15
17
|
const fs_1 = __importDefault(require("fs"));
|
|
16
18
|
const crypto_1 = __importDefault(require("crypto"));
|
|
17
19
|
const Watchdog_1 = require("./Watchdog");
|
|
18
20
|
const NginxHelper_1 = require("./NginxHelper");
|
|
19
21
|
const BlueGreenState_1 = require("./BlueGreenState");
|
|
22
|
+
const BackupManager_1 = require("./BackupManager");
|
|
20
23
|
const _TSetup = {
|
|
21
24
|
users: [{
|
|
22
25
|
login: "",
|
|
@@ -36,6 +39,8 @@ exports.REQ_DEPLOYMENT_PROCEED = new badmfck_signal_1.Req(undefined, "REQ_DEPLOY
|
|
|
36
39
|
exports.REQ_DEPLOYMENT_SWITCH = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SWITCH");
|
|
37
40
|
exports.REQ_DEPLOYMENT_STATUS = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_STATUS");
|
|
38
41
|
exports.REQ_DEPLOYMENT_SLOT = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SLOT");
|
|
42
|
+
exports.REQ_DEPLOYMENT_BACKUPS = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_BACKUPS");
|
|
43
|
+
exports.REQ_DEPLOYMENT_RESTORE = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_RESTORE");
|
|
39
44
|
class DeployerService extends BaseService_1.BaseService {
|
|
40
45
|
static MAX_HISTORY = 200;
|
|
41
46
|
static _trimHistory(state) {
|
|
@@ -76,6 +81,8 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
76
81
|
exports.REQ_DEPLOYMENT_SWITCH.listener = async (data) => this.switchSlot(data);
|
|
77
82
|
exports.REQ_DEPLOYMENT_STATUS.listener = async (data) => this.status(data);
|
|
78
83
|
exports.REQ_DEPLOYMENT_SLOT.listener = async (data) => this.slotState(data);
|
|
84
|
+
exports.REQ_DEPLOYMENT_BACKUPS.listener = async (data) => this.listBackups(data);
|
|
85
|
+
exports.REQ_DEPLOYMENT_RESTORE.listener = async (data) => this.restoreBackup(data);
|
|
79
86
|
}
|
|
80
87
|
async _loadSetup() {
|
|
81
88
|
const setupFile = path_1.default.resolve(this.options.setup_path, "setup.json");
|
|
@@ -161,6 +168,13 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
161
168
|
this.busy.set(realName, true);
|
|
162
169
|
try {
|
|
163
170
|
found = structuredClone(found);
|
|
171
|
+
const allConfigs = Array.from(configurations.values());
|
|
172
|
+
const isBGProject = !!(found.bluegreen && found.bluegreen.blue_config && found.bluegreen.green_config);
|
|
173
|
+
const rootProblem = this._destinationProblem(found.destination, !isBGProject && !!found.unpack && !found.ignoreDirectoryClean, allConfigs, found.destination);
|
|
174
|
+
if (rootProblem) {
|
|
175
|
+
(0, LogService_1.logError)("Deploy rejected: unsafe destination: " + rootProblem);
|
|
176
|
+
throw { code: 19, message: "Unsafe destination.", details: rootProblem, httpStatus: 400 };
|
|
177
|
+
}
|
|
164
178
|
const file = data.files.file;
|
|
165
179
|
const safeName = (path_1.default.basename(file.name || "").replace(/[^a-zA-Z0-9._-]/g, "_")) || "upload";
|
|
166
180
|
let projectState = null;
|
|
@@ -210,8 +224,33 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
210
224
|
}
|
|
211
225
|
}
|
|
212
226
|
found.name = data.name + "-" + projectState.lastDeployed;
|
|
227
|
+
const slotProblem = this._destinationProblem(found.destination, !!found.unpack && !found.ignoreDirectoryClean, allConfigs, path_1.default.dirname(path_1.default.resolve(found.destination)));
|
|
228
|
+
if (slotProblem) {
|
|
229
|
+
(0, LogService_1.logError)("Deploy rejected: unsafe slot destination: " + slotProblem);
|
|
230
|
+
throw { code: 19, message: "Unsafe destination.", details: slotProblem, httpStatus: 400 };
|
|
231
|
+
}
|
|
213
232
|
}
|
|
214
233
|
const uploadPath = path_1.default.resolve(found.destination, __1.UID.generate() + "_" + safeName);
|
|
234
|
+
if (found.backup) {
|
|
235
|
+
try {
|
|
236
|
+
const slot = projectState ? projectState.lastDeployed : null;
|
|
237
|
+
const backupName = await BackupManager_1.BackupManager.create(found.destination, realName, slot, user.login, "deploy");
|
|
238
|
+
if (backupName) {
|
|
239
|
+
(0, LogService_1.logInfo)(`Backup created: ${backupName}`);
|
|
240
|
+
const removed = await BackupManager_1.BackupManager.prune(path_1.default.dirname(path_1.default.resolve(found.destination)), realName, BackupManager_1.MAX_BACKUPS);
|
|
241
|
+
if (removed.length)
|
|
242
|
+
(0, LogService_1.logInfo)(`Old backups removed: ${removed.join(", ")}`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
(0, LogService_1.logError)("Backup failed, deploy aborted: " + (e?.message ?? e));
|
|
247
|
+
if (found.email && found.email.length > 0) {
|
|
248
|
+
for (let email of found.email)
|
|
249
|
+
this.notifier?.notifyEmailStatus(email, "error-backup", found.name, user.login);
|
|
250
|
+
}
|
|
251
|
+
throw { code: 54, message: "Backup failed, deploy aborted — nothing was changed.", details: String(e?.message ?? e), httpStatus: 500 };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
215
254
|
const result = await this.upload(file, uploadPath);
|
|
216
255
|
if (__1.ErrorUtils.isError(result)) {
|
|
217
256
|
if (found.email && found.email.length > 0) {
|
|
@@ -221,9 +260,6 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
221
260
|
}
|
|
222
261
|
throw result;
|
|
223
262
|
}
|
|
224
|
-
if (found.backup) {
|
|
225
|
-
(0, LogService_1.logInfo)("TODO: backup");
|
|
226
|
-
}
|
|
227
263
|
if (found.unpack) {
|
|
228
264
|
const unpackResult = await this.unpack(found.destination, uploadPath, found.install, found.ignoreDirectoryClean);
|
|
229
265
|
if (__1.ErrorUtils.isError(unpackResult)) {
|
|
@@ -250,6 +286,16 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
250
286
|
if (projectState && projectStatePath) {
|
|
251
287
|
this._writeBlueGreenFiles(data.name, projectState, path_1.default.dirname(found.destination));
|
|
252
288
|
}
|
|
289
|
+
if (found.migrate) {
|
|
290
|
+
const migrateErr = await this._runMigrate(found.destination);
|
|
291
|
+
if (migrateErr) {
|
|
292
|
+
if (found.email && found.email.length > 0) {
|
|
293
|
+
for (let email of found.email)
|
|
294
|
+
this.notifier?.notifyEmailStatus(email, "error-migrate", found.name, user.login);
|
|
295
|
+
}
|
|
296
|
+
throw migrateErr;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
253
299
|
if (found.pm2) {
|
|
254
300
|
const pm2Result = await this.runPM2(found, projectState);
|
|
255
301
|
if (__1.ErrorUtils.isError(pm2Result)) {
|
|
@@ -436,6 +482,133 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
436
482
|
}
|
|
437
483
|
return { data: results };
|
|
438
484
|
}
|
|
485
|
+
static _isBlueGreen(found) {
|
|
486
|
+
return !!(found.bluegreen && found.bluegreen.blue_config && found.bluegreen.green_config);
|
|
487
|
+
}
|
|
488
|
+
static _backupRoot(found) {
|
|
489
|
+
const dest = path_1.default.resolve(found.destination);
|
|
490
|
+
return DeployerService._isBlueGreen(found) ? dest : path_1.default.dirname(dest);
|
|
491
|
+
}
|
|
492
|
+
async listBackups(data) {
|
|
493
|
+
const user = this._checkUserAuth(data.auth);
|
|
494
|
+
if (!user)
|
|
495
|
+
return { error: { code: 50, message: "Unauthorized.", httpStatus: 401 } };
|
|
496
|
+
const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
|
|
497
|
+
const found = Array.from(configurations.values()).find(c => c.name === data.name);
|
|
498
|
+
if (!found)
|
|
499
|
+
return { error: { code: 58, message: "Project not found.", httpStatus: 404 } };
|
|
500
|
+
const backups = await BackupManager_1.BackupManager.list(DeployerService._backupRoot(found), found.name, true);
|
|
501
|
+
const isBG = DeployerService._isBlueGreen(found);
|
|
502
|
+
let activeSlot = null;
|
|
503
|
+
if (isBG) {
|
|
504
|
+
try {
|
|
505
|
+
const statePath = path_1.default.resolve(this.options.projects_path, found.name + "_state_.json");
|
|
506
|
+
activeSlot = JSON.parse(fs_1.default.readFileSync(statePath, "utf-8"))?.active ?? null;
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
activeSlot = null;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return { data: {
|
|
513
|
+
project: found.name,
|
|
514
|
+
bluegreen: isBG,
|
|
515
|
+
activeSlot,
|
|
516
|
+
backupEnabled: !!found.backup,
|
|
517
|
+
keep: BackupManager_1.MAX_BACKUPS,
|
|
518
|
+
backups,
|
|
519
|
+
} };
|
|
520
|
+
}
|
|
521
|
+
async restoreBackup(data) {
|
|
522
|
+
const user = this._checkUserAuth(data.auth);
|
|
523
|
+
if (!user) {
|
|
524
|
+
(0, LogService_1.logError)("Restore rejected: user auth failed");
|
|
525
|
+
return { error: { code: 50, message: "Unauthorized.", httpStatus: 401 } };
|
|
526
|
+
}
|
|
527
|
+
const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
|
|
528
|
+
let found;
|
|
529
|
+
for (const i of configurations.values()) {
|
|
530
|
+
if (i.name === data.name && this.tokensMatch(i.token, data.token)) {
|
|
531
|
+
found = i;
|
|
532
|
+
break;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (!found) {
|
|
536
|
+
(0, LogService_1.logError)("Restore rejected: wrong token and/or name");
|
|
537
|
+
return { error: { code: 41, message: "Wrong token and/or name.", httpStatus: 400 } };
|
|
538
|
+
}
|
|
539
|
+
if (this.busy.get(found.name))
|
|
540
|
+
return { error: { code: 43, message: "Deployment in progress, try again shortly.", httpStatus: 409 } };
|
|
541
|
+
const realName = found.name;
|
|
542
|
+
this.busy.set(realName, true);
|
|
543
|
+
try {
|
|
544
|
+
const root = DeployerService._backupRoot(found);
|
|
545
|
+
const backup = BackupManager_1.BackupManager.resolve(root, realName, data.backup);
|
|
546
|
+
if (!backup)
|
|
547
|
+
return { error: { code: 55, message: "Backup not found.", details: data.backup, httpStatus: 404 } };
|
|
548
|
+
const isBG = DeployerService._isBlueGreen(found);
|
|
549
|
+
const slot = backup.meta.slot;
|
|
550
|
+
if (isBG !== !!slot)
|
|
551
|
+
return { error: { code: 57, message: isBG
|
|
552
|
+
? "Backup has no slot, but the project is blue-green now."
|
|
553
|
+
: "Backup belongs to a blue-green slot, but the project is not blue-green now.", httpStatus: 400 } };
|
|
554
|
+
const target = isBG ? path_1.default.join(path_1.default.resolve(found.destination), slot) : path_1.default.resolve(found.destination);
|
|
555
|
+
const targetProblem = this._destinationProblem(target, true, Array.from(configurations.values()), isBG ? path_1.default.resolve(found.destination) : target);
|
|
556
|
+
if (targetProblem)
|
|
557
|
+
return { error: { code: 19, message: "Unsafe destination.", details: targetProblem, httpStatus: 400 } };
|
|
558
|
+
let state = null;
|
|
559
|
+
const statePath = path_1.default.resolve(this.options.projects_path, realName + "_state_.json");
|
|
560
|
+
if (isBG && fs_1.default.existsSync(statePath)) {
|
|
561
|
+
try {
|
|
562
|
+
state = JSON.parse(fs_1.default.readFileSync(statePath, "utf-8"));
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
state = null;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
const preRestore = await BackupManager_1.BackupManager.create(target, realName, slot, user.login, "pre-restore");
|
|
569
|
+
await BackupManager_1.BackupManager.restoreInto(backup.dir, target);
|
|
570
|
+
if (isBG && state)
|
|
571
|
+
this._writeBlueGreenFiles(realName, state, path_1.default.resolve(found.destination));
|
|
572
|
+
let pm2Error = null;
|
|
573
|
+
if (found.pm2) {
|
|
574
|
+
const pm2Found = { ...structuredClone(found), name: isBG ? `${realName}-${slot}` : realName, destination: target };
|
|
575
|
+
pm2Error = await this.runPM2(pm2Found, state ? { ...state, lastDeployed: slot } : null);
|
|
576
|
+
if (pm2Error)
|
|
577
|
+
(0, LogService_1.logError)(`Restore: pm2 restart failed for ${pm2Found.name}: ${pm2Error.details ?? pm2Error.message}`);
|
|
578
|
+
}
|
|
579
|
+
if (isBG && state) {
|
|
580
|
+
state.history.push({ slot: slot, action: "restore", user: user.login, at: Date.now() });
|
|
581
|
+
DeployerService._trimHistory(state);
|
|
582
|
+
const tmp = statePath + ".tmp";
|
|
583
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify(state, null, 4), "utf-8");
|
|
584
|
+
fs_1.default.renameSync(tmp, statePath);
|
|
585
|
+
}
|
|
586
|
+
await BackupManager_1.BackupManager.prune(root, realName, BackupManager_1.MAX_BACKUPS, [data.backup]);
|
|
587
|
+
(0, LogService_1.logInfo)(`Restored ${realName}${slot ? "/" + slot : ""} from ${data.backup} by ${user.login}`);
|
|
588
|
+
if (found.email && found.email.length > 0) {
|
|
589
|
+
for (let email of found.email)
|
|
590
|
+
this.notifier?.notifyEmailStatus(email, pm2Error ? "error-restore-pm2" : "restored", found.name, user.login);
|
|
591
|
+
}
|
|
592
|
+
return { data: {
|
|
593
|
+
project: realName,
|
|
594
|
+
restored: data.backup,
|
|
595
|
+
appVersion: backup.meta.appVersion,
|
|
596
|
+
slot,
|
|
597
|
+
activeSlot: state?.active ?? null,
|
|
598
|
+
live: !isBG || slot === state?.active,
|
|
599
|
+
preRestoreBackup: preRestore,
|
|
600
|
+
pm2Restarted: !!found.pm2 && !pm2Error,
|
|
601
|
+
pm2Error: pm2Error ? (pm2Error.details ?? pm2Error.message) : null,
|
|
602
|
+
} };
|
|
603
|
+
}
|
|
604
|
+
catch (e) {
|
|
605
|
+
(0, LogService_1.logError)("Restore failed: " + (e?.message ?? e));
|
|
606
|
+
return { error: { code: 56, message: "Restore failed.", details: String(e?.message ?? e), httpStatus: 500 } };
|
|
607
|
+
}
|
|
608
|
+
finally {
|
|
609
|
+
this.busy.set(realName, false);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
439
612
|
async slotState(data) {
|
|
440
613
|
const deny = { error: { code: 53, message: "Invalid project or status token.", httpStatus: 401 } };
|
|
441
614
|
if (!data || typeof data.name !== "string" || typeof data.token !== "string" || !/^[A-Za-z0-9._-]+$/.test(data.name))
|
|
@@ -671,26 +844,118 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
671
844
|
(0, LogService_1.logWarn)("Unresolved template placeholders in " + filePath + ": " + unique.join(", "));
|
|
672
845
|
}
|
|
673
846
|
}
|
|
674
|
-
|
|
847
|
+
_destinationProblem(dir, willClean, configs, ownDest) {
|
|
848
|
+
if (typeof dir !== "string" || !path_1.default.isAbsolute(dir))
|
|
849
|
+
return "destination must be an absolute path";
|
|
850
|
+
const dest = path_1.default.resolve(dir);
|
|
851
|
+
if (dest === path_1.default.parse(dest).root)
|
|
852
|
+
return "destination is the filesystem root";
|
|
853
|
+
if (dest.split(path_1.default.sep).filter(Boolean).length < 2)
|
|
854
|
+
return `destination "${dest}" is a top-level system directory`;
|
|
855
|
+
const covers = (outer, inner) => inner === outer || inner.startsWith(outer + path_1.default.sep);
|
|
856
|
+
const configsDir = path_1.default.resolve(this.options.projects_path);
|
|
857
|
+
if (covers(dest, configsDir))
|
|
858
|
+
return `destination "${dest}" contains the deployer's config folder`;
|
|
859
|
+
if (covers(dest, path_1.default.resolve(process.cwd())))
|
|
860
|
+
return `destination "${dest}" contains the deployer itself`;
|
|
861
|
+
if (willClean) {
|
|
862
|
+
const own = path_1.default.resolve(ownDest);
|
|
863
|
+
for (const c of configs) {
|
|
864
|
+
if (!c?.destination)
|
|
865
|
+
continue;
|
|
866
|
+
const other = path_1.default.resolve(c.destination);
|
|
867
|
+
if (other === own)
|
|
868
|
+
continue;
|
|
869
|
+
if (other !== dest && covers(dest, other))
|
|
870
|
+
return `destination "${dest}" contains project "${c.name}" (${other}) and would be wiped`;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
return null;
|
|
874
|
+
}
|
|
875
|
+
static _unsafeArchiveEntry(archive) {
|
|
876
|
+
let listing = "";
|
|
675
877
|
try {
|
|
676
|
-
|
|
677
|
-
const root = path_1.default.resolve(this.options.projects_path);
|
|
678
|
-
if (!path_1.default.isAbsolute(dest))
|
|
679
|
-
return false;
|
|
680
|
-
if (dest.length < 5 || dest === "/")
|
|
681
|
-
return false;
|
|
682
|
-
if (dest === root)
|
|
683
|
-
return false;
|
|
684
|
-
if (!dest.startsWith(root + path_1.default.sep))
|
|
685
|
-
return false;
|
|
686
|
-
return true;
|
|
878
|
+
listing = (0, child_process_1.execFileSync)("tar", ["-tzf", archive], { encoding: "utf-8", maxBuffer: 256 * 1024 * 1024 });
|
|
687
879
|
}
|
|
688
|
-
catch {
|
|
689
|
-
return
|
|
880
|
+
catch (e) {
|
|
881
|
+
return "archive cannot be listed: " + (e?.message ?? e);
|
|
882
|
+
}
|
|
883
|
+
for (const raw of listing.split("\n")) {
|
|
884
|
+
const name = raw.trim();
|
|
885
|
+
if (!name)
|
|
886
|
+
continue;
|
|
887
|
+
if (name.startsWith("/") || /^[A-Za-z]:[\\/]/.test(name))
|
|
888
|
+
return name;
|
|
889
|
+
if (name.split(/[\\/]/).includes(".."))
|
|
890
|
+
return name;
|
|
690
891
|
}
|
|
892
|
+
return null;
|
|
691
893
|
}
|
|
894
|
+
static _escapingSymlink(root) {
|
|
895
|
+
const base = path_1.default.resolve(root);
|
|
896
|
+
const stack = [base];
|
|
897
|
+
while (stack.length) {
|
|
898
|
+
const dir = stack.pop();
|
|
899
|
+
let entries;
|
|
900
|
+
try {
|
|
901
|
+
entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
|
|
902
|
+
}
|
|
903
|
+
catch {
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
for (const e of entries) {
|
|
907
|
+
const p = path_1.default.join(dir, e.name);
|
|
908
|
+
if (e.isSymbolicLink()) {
|
|
909
|
+
const target = fs_1.default.readlinkSync(p);
|
|
910
|
+
const resolved = path_1.default.resolve(dir, target);
|
|
911
|
+
if (path_1.default.isAbsolute(target) || (resolved !== base && !resolved.startsWith(base + path_1.default.sep)))
|
|
912
|
+
return `${path_1.default.relative(base, p)} -> ${target}`;
|
|
913
|
+
}
|
|
914
|
+
else if (e.isDirectory()) {
|
|
915
|
+
stack.push(p);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
return null;
|
|
920
|
+
}
|
|
921
|
+
async _runMigrate(dir) {
|
|
922
|
+
const tail = (t) => {
|
|
923
|
+
const s = LogService_1.LogService.sanitize(String(t ?? "").trim());
|
|
924
|
+
return s.length > 4000 ? "…" + s.slice(-4000) : s;
|
|
925
|
+
};
|
|
926
|
+
let scripts = null;
|
|
927
|
+
try {
|
|
928
|
+
scripts = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, "package.json"), "utf-8"))?.scripts;
|
|
929
|
+
}
|
|
930
|
+
catch { }
|
|
931
|
+
if (!scripts || typeof scripts.migrate !== "string")
|
|
932
|
+
return { code: 60, message: '"migrate" is enabled, but package.json has no "migrate" script.', httpStatus: 500 };
|
|
933
|
+
(0, LogService_1.logInfo)(`Running migrations: npm run migrate (${scripts.migrate})`);
|
|
934
|
+
try {
|
|
935
|
+
const { stdout, stderr } = await execFileAsync("npm", ["run", "migrate"], { cwd: dir, timeout: DeployerService.MIGRATE_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
|
|
936
|
+
(0, LogService_1.logInfo)("Migrations finished:\n" + tail(String(stdout) + String(stderr)));
|
|
937
|
+
return null;
|
|
938
|
+
}
|
|
939
|
+
catch (e) {
|
|
940
|
+
const out = tail(String(e?.stdout ?? "") + String(e?.stderr ?? ""));
|
|
941
|
+
const reason = e?.killed ? `timed out after ${DeployerService.MIGRATE_TIMEOUT_MS / 60000} min` : `exit code ${e?.code}`;
|
|
942
|
+
(0, LogService_1.logError)(`Migrations failed (${reason}):\n${out}`);
|
|
943
|
+
return { code: 60, message: `Migrations failed (${reason}), the process was not restarted.`, details: out, httpStatus: 500 };
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
static MIGRATE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
692
947
|
async unpack(destination, uploadedFile, install, ignoreDirectoryClean) {
|
|
693
948
|
return new Promise((resolve) => {
|
|
949
|
+
const unsafeEntry = DeployerService._unsafeArchiveEntry(uploadedFile);
|
|
950
|
+
if (unsafeEntry) {
|
|
951
|
+
(0, LogService_1.logError)("Refusing to unpack: archive entry escapes the destination: " + unsafeEntry);
|
|
952
|
+
try {
|
|
953
|
+
fs_1.default.rmSync(path_1.default.resolve(uploadedFile));
|
|
954
|
+
}
|
|
955
|
+
catch (e) { }
|
|
956
|
+
resolve({ code: 59, message: "Archive rejected: an entry points outside the destination.", details: unsafeEntry, httpStatus: 400 });
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
694
959
|
try {
|
|
695
960
|
const tmp = path_1.default.resolve(destination, "__tmp");
|
|
696
961
|
if (fs_1.default.existsSync(tmp))
|
|
@@ -714,6 +979,16 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
714
979
|
catch (e) {
|
|
715
980
|
(0, LogService_1.logError)("Can't remove file", e);
|
|
716
981
|
}
|
|
982
|
+
const escaping = DeployerService._escapingSymlink(path_1.default.resolve(destination, "__tmp"));
|
|
983
|
+
if (escaping) {
|
|
984
|
+
(0, LogService_1.logError)("Refusing to deploy: symlink points outside the archive: " + escaping);
|
|
985
|
+
try {
|
|
986
|
+
fs_1.default.rmSync(path_1.default.resolve(destination, "__tmp"), { recursive: true });
|
|
987
|
+
}
|
|
988
|
+
catch (e) { }
|
|
989
|
+
resolve({ code: 59, message: "Archive rejected: a symlink points outside the destination.", details: escaping, httpStatus: 400 });
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
717
992
|
if (install) {
|
|
718
993
|
try {
|
|
719
994
|
const tmpDir = path_1.default.resolve(destination, "__tmp");
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Restore = Restore;
|
|
4
|
+
const promises_1 = require("readline/promises");
|
|
5
|
+
const process_1 = require("process");
|
|
6
|
+
const __1 = require("../..");
|
|
7
|
+
const resolveConfig_1 = require("./resolveConfig");
|
|
8
|
+
const cliCommon_1 = require("./cliCommon");
|
|
9
|
+
async function Restore(opt, backupName, assumeYes = false) {
|
|
10
|
+
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
11
|
+
const { red, yellow, green, dim, bold } = (0, cliCommon_1.palette)();
|
|
12
|
+
const headers = { authorization: (0, cliCommon_1.authHeader)(opt) };
|
|
13
|
+
const fail = (msg) => { console.error(red(bold("✗ ")) + msg); process.exit(1); };
|
|
14
|
+
const lr = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, { headers, timeoutMs: 30000, retry: { enabled: false } });
|
|
15
|
+
const lerr = (0, cliCommon_1.responseError)(lr);
|
|
16
|
+
if (lerr)
|
|
17
|
+
fail("Cannot list backups: " + lerr);
|
|
18
|
+
const info = lr.data?.data ?? {};
|
|
19
|
+
const list = info.backups ?? [];
|
|
20
|
+
if (list.length === 0)
|
|
21
|
+
fail(`No backups for "${opt.name}".`);
|
|
22
|
+
const rl = process_1.stdin.isTTY ? (0, promises_1.createInterface)({ input: process_1.stdin, output: process_1.stdout }) : null;
|
|
23
|
+
let chosen;
|
|
24
|
+
try {
|
|
25
|
+
if (backupName) {
|
|
26
|
+
chosen = list.find(b => b.name === backupName);
|
|
27
|
+
if (!chosen)
|
|
28
|
+
fail(`Backup "${backupName}" not found. Run \`badmfck backups\` to see the list.`);
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
if (!rl)
|
|
32
|
+
fail("Backup name is required when not running in a terminal: badmfck restore <backup-name> --yes");
|
|
33
|
+
console.log("");
|
|
34
|
+
list.forEach((b, i) => console.log(` [${i + 1}] ${b.name} ${dim("ver")} ${b.appVersion ?? "?"} ${dim((0, cliCommon_1.fmtDate)(b.createdAt))}`));
|
|
35
|
+
while (!chosen) {
|
|
36
|
+
const a = await rl.question(`\nRestore which backup [1-${list.length}]: `);
|
|
37
|
+
const i = parseInt(a.trim(), 10) - 1;
|
|
38
|
+
if (i >= 0 && i < list.length)
|
|
39
|
+
chosen = list[i];
|
|
40
|
+
else
|
|
41
|
+
console.error(`Enter a number from 1 to ${list.length}.`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const live = !info.bluegreen || chosen.slot === info.activeSlot;
|
|
45
|
+
console.log("");
|
|
46
|
+
console.log(`${bold("Restore")} ${bold(opt.name)} ${dim("←")} ${chosen.name} ${dim("(ver " + (chosen.appVersion ?? "?") + ")")}`);
|
|
47
|
+
if (info.bluegreen)
|
|
48
|
+
console.log(` ${dim("slot:")} ${chosen.slot} ${dim("active:")} ${info.activeSlot ?? "?"}`);
|
|
49
|
+
console.log(live
|
|
50
|
+
? yellow(bold(" ⚠ LIVE: production traffic gets the restored code immediately"))
|
|
51
|
+
: dim(` not live — the slot will need: badmfck activate ${chosen.slot}`));
|
|
52
|
+
console.log(dim(" current contents are backed up first, so this can be undone"));
|
|
53
|
+
if (!assumeYes) {
|
|
54
|
+
if (!rl)
|
|
55
|
+
fail("Refusing to restore non-interactively without --yes.");
|
|
56
|
+
const a = await rl.question("\nProceed? [y/N] ");
|
|
57
|
+
if (!/^y(es)?$/i.test(a.trim())) {
|
|
58
|
+
console.log("Cancelled.");
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
rl?.close();
|
|
65
|
+
}
|
|
66
|
+
console.log(dim("\nRestoring…"));
|
|
67
|
+
const rr = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "restore"), { name: opt.name, token: opt.token, backup: chosen.name }, { headers, timeoutMs: 10 * 60 * 1000, retry: { enabled: false } });
|
|
68
|
+
const rerr = (0, cliCommon_1.responseError)(rr);
|
|
69
|
+
if (rerr)
|
|
70
|
+
fail("Restore failed: " + rerr);
|
|
71
|
+
const d = rr.data?.data ?? {};
|
|
72
|
+
const line = dim("─".repeat(60));
|
|
73
|
+
console.log("");
|
|
74
|
+
console.log(d.pm2Error ? yellow(bold("⚠ RESTORED, BUT pm2 RESTART FAILED")) : green(bold("✓ RESTORED")));
|
|
75
|
+
console.log(line);
|
|
76
|
+
console.log(` ${dim("project: ")} ${d.project}`);
|
|
77
|
+
console.log(` ${dim("backup: ")} ${d.restored} ${dim("(ver " + (d.appVersion ?? "?") + ")")}`);
|
|
78
|
+
if (d.slot)
|
|
79
|
+
console.log(` ${dim("slot: ")} ${d.slot} ${dim("active:")} ${d.activeSlot ?? "?"}`);
|
|
80
|
+
console.log(` ${dim("live: ")} ${d.live ? bold("yes") : "no"}`);
|
|
81
|
+
console.log(` ${dim("pm2: ")} ${d.pm2Error ? yellow(d.pm2Error) : d.pm2Restarted ? "restarted" : "not used"}`);
|
|
82
|
+
if (d.preRestoreBackup)
|
|
83
|
+
console.log(` ${dim("undo with: ")} badmfck restore ${d.preRestoreBackup}`);
|
|
84
|
+
if (!d.live && d.slot)
|
|
85
|
+
console.log(` ${dim("next: ")} badmfck activate ${d.slot}`);
|
|
86
|
+
console.log(line);
|
|
87
|
+
console.log("");
|
|
88
|
+
}
|
|
@@ -4,11 +4,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
4
4
|
const Deploy_1 = require("./Deploy");
|
|
5
5
|
const Activate_1 = require("./Activate");
|
|
6
6
|
const Status_1 = require("./Status");
|
|
7
|
+
const Backups_1 = require("./Backups");
|
|
8
|
+
const Restore_1 = require("./Restore");
|
|
9
|
+
const BackupManager_1 = require("./BackupManager");
|
|
7
10
|
function usage() {
|
|
8
11
|
console.error("Usage:");
|
|
9
12
|
console.error(" badmfck deploy [config.json] — build + upload the current project");
|
|
10
13
|
console.error(" badmfck activate [config.json] [blue|green] — switch blue-green slot (omit slot for lastDeployed)");
|
|
11
14
|
console.error(" badmfck status [config.json] — show active / last deployed slot");
|
|
15
|
+
console.error(" badmfck backups [config.json] — list deploy backups");
|
|
16
|
+
console.error(" badmfck restore [config.json] [backup] [--yes] — restore a backup (asks which, and confirms)");
|
|
12
17
|
console.error("");
|
|
13
18
|
console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
|
|
14
19
|
console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
|
|
@@ -53,6 +58,39 @@ async function main() {
|
|
|
53
58
|
await (0, Activate_1.Activate)(config, scheme);
|
|
54
59
|
break;
|
|
55
60
|
}
|
|
61
|
+
case "backups": {
|
|
62
|
+
const { scheme, config } = parseArgs(rest);
|
|
63
|
+
if (scheme) {
|
|
64
|
+
console.error(`"backups" does not take a slot argument ("${scheme}").`);
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
await (0, Backups_1.Backups)(config);
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
case "restore": {
|
|
71
|
+
let config, backup, yes = false;
|
|
72
|
+
for (const a of rest) {
|
|
73
|
+
if (a === "--yes" || a === "-y") {
|
|
74
|
+
yes = true;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (BackupManager_1.BackupManager.isValidName(a)) {
|
|
78
|
+
if (backup) {
|
|
79
|
+
console.error(`Backup specified twice ("${backup}" and "${a}").`);
|
|
80
|
+
process.exit(1);
|
|
81
|
+
}
|
|
82
|
+
backup = a;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (config) {
|
|
86
|
+
console.error(`Config path specified twice ("${config}" and "${a}").`);
|
|
87
|
+
process.exit(1);
|
|
88
|
+
}
|
|
89
|
+
config = a;
|
|
90
|
+
}
|
|
91
|
+
await (0, Restore_1.Restore)(config, backup, yes);
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
56
94
|
case "status": {
|
|
57
95
|
const { scheme, config } = parseArgs(rest);
|
|
58
96
|
if (scheme) {
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { IDeployerConfig } from "./resolveConfig";
|
|
2
|
+
export declare function deployerUrl(opt: IDeployerConfig, endpoint: string): string;
|
|
3
|
+
export declare function authHeader(opt: IDeployerConfig): string;
|
|
4
|
+
export declare function responseError(r: any): string | null;
|
|
5
|
+
export declare function palette(): {
|
|
6
|
+
red: (t: string) => string;
|
|
7
|
+
green: (t: string) => string;
|
|
8
|
+
yellow: (t: string) => string;
|
|
9
|
+
blue: (t: string) => string;
|
|
10
|
+
dim: (t: string) => string;
|
|
11
|
+
bold: (t: string) => string;
|
|
12
|
+
};
|
|
13
|
+
export declare function fmtDate(ms: number): string;
|
|
14
|
+
export declare function fmtSize(kb: number | null | undefined): string;
|