badmfck-api-server 5.0.12 → 5.0.14

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 CHANGED
@@ -72,6 +72,8 @@
72
72
  "destination": "/var/node/gateway",
73
73
  "token": "…",
74
74
  "unpack": true, "install": true, "pm2": true,
75
+ "backup": true, // перед каждым деплоем копировать то, что будет перезаписано (раздел 5.1)
76
+ "migrate": true, // запускать `npm run migrate` перед стартом процесса (раздел 5.2)
75
77
 
76
78
  // Общие значения для обоих слотов (БД, домены, флаги)
77
79
  "config": { "DB_HOST": "…" },
@@ -111,7 +113,9 @@
111
113
  "activate": "badmfck activate",
112
114
  "rollback:blue": "badmfck activate blue",
113
115
  "rollback:green": "badmfck activate green",
114
- "status": "badmfck status"
116
+ "status": "badmfck status",
117
+ "backups": "badmfck backups",
118
+ "restore": "badmfck restore"
115
119
  }
116
120
  ```
117
121
 
@@ -121,6 +125,8 @@
121
125
  | `npm run activate` | включить последний выложенный слот |
122
126
  | `badmfck activate blue` / `green` | включить конкретный слот (rollback) |
123
127
  | `npm run status` | какой слот активен, какой выложен последним, ждёт ли что-то переключения, кто и когда это делал |
128
+ | `npm run backups` | список бэкапов: версия, слот, кто и когда, размер на диске |
129
+ | `npm run restore` | восстановить бэкап: спросит, какой, и попросит подтверждение |
124
130
 
125
131
  **Где CLI берёт конфиг.** Сначала папка `deploy/` (если там несколько конфигов, CLI спросит, какой взять), потом файл `deploy.json`. Путь можно указать явно, но через npm нужен разделитель `--`:
126
132
 
@@ -131,6 +137,110 @@ npm run activate -- deploy/prod.json blue
131
137
 
132
138
  ---
133
139
 
140
+ ## 5.1. Бэкапы и восстановление
141
+
142
+ Работает для любых проектов, не только blue-green. Включается флагом `"backup": true` в конфиге проекта на деплоере.
143
+
144
+ ### Что происходит при деплое
145
+
146
+ Перед тем как в папку назначения что-либо попадёт, деплоер копирует **всё её содержимое** на уровень выше:
147
+
148
+ ```
149
+ обычный проект /var/node/sms → /var/node/2026-10-14_18-45-09-sms
150
+ blue-green слот /var/node/gw/blue → /var/node/gw/2026-10-14_18-45-09-gw-blue
151
+ ```
152
+
153
+ - Копия **полная, вместе с `node_modules`**, с сохранением прав и симлинков. Поэтому восстановление — обычное копирование: без сети и без `npm ci` в момент инцидента.
154
+ - Хранятся **последние 10** бэкапов проекта, более старые удаляются автоматически.
155
+ - Первый деплой в пустую папку бэкап не делает — сохранять нечего.
156
+ - **Если бэкап не удался** (кончилось место, нет прав) — **деплой прерывается, ничего не изменив**. Раз флаг включён, перезаписывать без страховочной копии нельзя.
157
+
158
+ Бэкап опознаётся по файлу метаданных внутри, а не по имени папки. Поэтому несколько проектов в одной родительской папке не путают бэкапы друг друга, даже если их имена похожи (`gateway` и `gateway-v2`).
159
+
160
+ ### Восстановление
161
+
162
+ ```bash
163
+ npm run backups # посмотреть, что есть
164
+ npm run restore # выбрать из списка, подтвердить
165
+ npm run restore -- 2026-10-13_10-00-00-gw-blue # конкретный бэкап
166
+ badmfck restore 2026-10-13_10-00-00-gw-blue --yes # без вопросов (CI, скрипты)
167
+ ```
168
+
169
+ Что делает деплоер:
170
+ 1. **Сначала бэкапит текущее состояние** — неудачное восстановление тоже можно откатить. Команда для отката печатается в конце (`undo with: …`).
171
+ 2. Готовит копию рядом и **подменяет папку переименованием**: живая папка ни в какой момент не пустая и не наполовину записанная.
172
+ 3. Перезапускает процесс в pm2, если у проекта `pm2: true` (для blue-green — именно процесс восстановленного слота).
173
+ 4. Для blue-green пишет `restore` в историю проекта.
174
+
175
+ Восстановление берёт ту же блокировку, что и деплой, поэтому одновременно с выкладкой оно не выполнится.
176
+
177
+ ### Куда уходит восстановленный код
178
+
179
+ | Проект | Результат |
180
+ |---|---|
181
+ | обычный | **сразу в проде** |
182
+ | blue-green, восстановлен **активный** слот | **сразу в проде** |
183
+ | blue-green, восстановлен **неактивный** слот | в прод не попадает; чтобы включить — `badmfck activate <слот>` |
184
+
185
+ CLI показывает это заранее и в первых двух случаях предупреждает `⚠ LIVE`. Без терминала (CI, скрипты) восстановление выполняется **только с `--yes`**.
186
+
187
+ > В blue-green деплой перезаписывает **неактивный** слот, то есть позапрошлую версию: предыдущая и так живёт во втором слоте, откат на неё — обычный `activate`. Бэкапы здесь дают историю глубже.
188
+
189
+ ### О чём помнить
190
+
191
+ - **Место на диске.** Каждый бэкап — полная копия вместе с `node_modules`, ×10 на проект. Реальный размер виден в `npm run backups`.
192
+ - **Конфиг «запечён» в бэкап.** Значения из `config` подставляются при деплое, поэтому восстановленный код несёт значения на момент **того** деплоя. Если с тех пор меняли пароль БД или другой секрет — восстановленное приложение придёт со старым.
193
+ - **Проверь флаг в существующих конфигах.** `backup` в шаблоне обязательный, поэтому у проектов, созданных через API, он, скорее всего, уже стоит `true` — до появления этой функции он просто игнорировался.
194
+
195
+ ### API
196
+
197
+ ```
198
+ POST pckg/backups {name} — список; авторизация пользователя деплоера
199
+ POST pckg/restore {name, token, backup} — восстановление; пользователь + токен проекта
200
+ ```
201
+
202
+ Ответ восстановления: `{restored, appVersion, slot, activeSlot, live, preRestoreBackup, pm2Restarted, pm2Error}`.
203
+
204
+ ---
205
+
206
+ ## 5.2. Миграции БД
207
+
208
+ Флаг `"migrate": true` в конфиге проекта на деплоере. По умолчанию выключен.
209
+
210
+ ### Когда запускается
211
+
212
+ ```
213
+ распаковка → npm ci → подстановка config → npm run migrate → запуск в pm2
214
+ ```
215
+
216
+ - **После подстановки конфига** — миграция видит настоящие доступы к БД, а не плейсхолдеры `_{{…}}_`.
217
+ - **До запуска процесса** — новый код никогда не стартует на старой схеме.
218
+ - Выполняется в папке выкладки (для blue-green — в папке слота), поэтому `.env`, загружаемый через dotenv, находится сам.
219
+ - В `package.json` проекта должен быть скрипт `migrate`. Если флаг включён, а скрипта нет — деплой падает с понятной ошибкой.
220
+ - Таймаут — 10 минут.
221
+
222
+ ### Если миграция упала
223
+
224
+ Деплой останавливается, **процесс не перезапускается**, вывод миграции возвращается в `badmfck deploy` и пишется в лог деплоера. Пароли в строках подключения (`mysql://user:***@host`) маскируются.
225
+
226
+ | Проект | Состояние после ошибки |
227
+ |---|---|
228
+ | blue-green | новый слот не запущен, **активный слот не затронут** — прод работает как раньше |
229
+ | обычный | файлы на диске **уже заменены**, но старый процесс работает со старым кодом в памяти. Если он перезапустится, поднимется новый код на непромигрированной схеме. Поэтому для таких проектов держи `"backup": true` и при ошибке делай `badmfck restore` |
230
+
231
+ ### ⚠️ Blue-green и общая база
232
+
233
+ Миграция выполняется при деплое в **неактивный** слот, то есть пока трафик ещё обслуживает **старая** версия. Схема меняется **раньше**, чем ты переключишь трафик. Отсюда два правила:
234
+
235
+ 1. **Миграции должны быть обратно совместимыми.** Старая версия обязана работать на новой схеме: добавлять колонки и таблицы можно, а удалять и переименовывать — только отдельным деплоем, когда старый код уже нигде не работает.
236
+ 2. **Откат кода не откатывает схему.** Ни `badmfck activate <старый слот>`, ни `badmfck restore` не возвращают БД назад. Если нужен откат схемы — это отдельная down-миграция.
237
+
238
+ ### Безопасность
239
+
240
+ При установке зависимостей скрипты пакетов отключены (`npm ci --ignore-scripts`). `migrate` — единственный скрипт из `package.json`, который деплоер запускает сам, и выполняется он с правами деплоера. Это тот же уровень доверия, что и к запуску самого приложения, но держи в голове: включая флаг, ты разрешаешь выкладываемому коду выполниться на сервере ещё до старта.
241
+
242
+ ---
243
+
134
244
  ## 6. Приложение: «я сейчас в проде?»
135
245
 
136
246
  ### Главное понятие — `live`
@@ -259,6 +369,11 @@ new APIService({ …, blueGreenWatchMs: 5000 }) // по умолчанию 500
259
369
 
260
370
  | Симптом | Причина | Что делать |
261
371
  |---|---|---|
372
+ | деплой падает с `Backup failed, deploy aborted` (code 54) | не удалось сделать бэкап: нет места или прав на родительскую папку | освободить место / выдать права; или временно `"backup": false` |
373
+ | деплой падает с `Migrations failed` (code 60) | ошибка в самой миграции или нет доступа к БД | смотреть вывод в ответе `badmfck deploy` или в логе деплоера; для обычного проекта при необходимости `badmfck restore` |
374
+ | `"migrate" is enabled, but package.json has no "migrate" script` | флаг включён, скрипта нет | добавить `"migrate"` в `scripts` или выключить флаг |
375
+ | `Backup not found` (code 55) при восстановлении | неверное имя или бэкап уже удалён ротацией | взять имя из `npm run backups` |
376
+ | восстановление прошло, но `pm2 RESTART FAILED` | файлы на месте, процесс не перезапустился | `pm2 restart <имя>` вручную, затем `pm2 logs` |
262
377
  | `bluegreen: false` на blue-green проекте | слот выложен **до** появления этой функции, `.bluegreen.json` нет | выполнить один деплой: файл запишется в оба слота |
263
378
  | `live: null`, в `error` «malformed» | `.bluegreen.json` повреждён | передеплоить слот |
264
379
  | `live: null`, `error` «deployer unreachable» | деплоер недоступен, а прошлого значения ещё нет | проверить деплоер; если он не слушает loopback — задать `status_url` в его `setup.json` |
@@ -190,6 +190,7 @@ class APIService extends BaseService_1.BaseService {
190
190
  exports.REQ_HTTP_REQUESTS_COUNT.listener = async () => this.requestsCount;
191
191
  }
192
192
  async init() {
193
+ super.init();
193
194
  exports.REQ_HTTP_LOG.listener = async (_) => this.netLog;
194
195
  exports.REQ_INTERNAL_CALL.listener = async (req) => {
195
196
  for (let i of this.options.endpoints) {
@@ -261,6 +261,7 @@ class LogService extends BaseService_1.BaseService {
261
261
  [/-----BEGIN [A-Z0-9 ]+-----[\s\S]+?-----END [A-Z0-9 ]+-----/g, "<REDACTED PEM>"],
262
262
  [/eyJ[A-Za-z0-9_-]{5,}\.eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]+/g, "<REDACTED JWT>"],
263
263
  [/(Bearer|Basic|Digest)\s+[A-Za-z0-9\-._~+\/=]+/gi, "$1 <REDACTED>"],
264
+ [/\b([a-z][a-z0-9+.-]*:\/\/[^\s:\/@]+:)[^\s@\/]+@/gi, "$1<REDACTED>@"],
264
265
  [/%B\d{13,19}\^[^?]{2,50}\^\d{4,}[^?]*\?/g, "<REDACTED TRACK1>"],
265
266
  [/;\d{13,19}=\d{4,}[^?]*\?/g, "<REDACTED TRACK2>"],
266
267
  [/("(?:password|passwd|pwd|secret|api[_-]?key|api[_-]?secret|client[_-]?secret|access[_-]?key|private[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|token|authorization|cookie|set[_-]?cookie|session[_-]?id|sess[_-]?id|sid|cvv2?|cvc2?|cvn|cav2?|cid|security[_-]?code|card[_-]?verification[_-]?(?:value|code)?|pin|pin[_-]?block|encrypted[_-]?pin|iso[_-]?9564|exp|expiry|expiration|expiration[_-]?date|exp[_-]?date|exp[_-]?month|exp[_-]?year|cardholder[_-]?name|holder[_-]?name|card[_-]?holder|pan|dpan|primary[_-]?account[_-]?number|application[_-]?primary[_-]?account[_-]?number|card[_-]?number|card[_-]?no|account[_-]?number|application[_-]?expiration[_-]?date|online[_-]?payment[_-]?cryptogram|cryptogram|emv[_-]?data|track[12]?[_-]?data)"\s*:\s*)"[^"]*"/gi, '$1"<REDACTED>"'],
@@ -0,0 +1,33 @@
1
+ export declare const BACKUP_META = ".badmfck-backup.json";
2
+ export declare const MAX_BACKUPS = 10;
3
+ export type TBackupSlot = "blue" | "green" | null;
4
+ export interface IBackupMeta {
5
+ version: 1;
6
+ project: string;
7
+ slot: TBackupSlot;
8
+ createdAt: number;
9
+ user: string;
10
+ reason: "deploy" | "pre-restore";
11
+ appVersion: string | null;
12
+ }
13
+ export interface IBackupInfo extends IBackupMeta {
14
+ name: string;
15
+ sizeKb: number | null;
16
+ }
17
+ export declare class BackupManager {
18
+ static fileSafe(s: string): string;
19
+ static stamp(d?: Date): string;
20
+ static isValidName(name: string): boolean;
21
+ private static hasContent;
22
+ private static readMeta;
23
+ private static readAppVersion;
24
+ private static assertSafeRoot;
25
+ static create(target: string, project: string, slot: TBackupSlot, user: string, reason: IBackupMeta["reason"]): Promise<string | null>;
26
+ static list(root: string, project: string, withSize?: boolean): Promise<IBackupInfo[]>;
27
+ static prune(root: string, project: string, keep?: number, protect?: string[]): Promise<string[]>;
28
+ static resolve(root: string, project: string, name: string): {
29
+ dir: string;
30
+ meta: IBackupMeta;
31
+ } | null;
32
+ static restoreInto(backupDir: string, target: string): Promise<void>;
33
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BackupManager = exports.MAX_BACKUPS = exports.BACKUP_META = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const child_process_1 = require("child_process");
10
+ const util_1 = require("util");
11
+ const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
12
+ exports.BACKUP_META = ".badmfck-backup.json";
13
+ exports.MAX_BACKUPS = 10;
14
+ const NAME_RE = /^(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:_(\d+))?-([A-Za-z0-9._-]+)$/;
15
+ const PARTIAL_PREFIX = ".partial-";
16
+ class BackupManager {
17
+ static fileSafe(s) {
18
+ const v = String(s || "").replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
19
+ return v.length > 0 ? v.slice(0, 80) : "project";
20
+ }
21
+ static stamp(d = new Date()) {
22
+ const p = (n) => String(n).padStart(2, "0");
23
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}_${p(d.getHours())}-${p(d.getMinutes())}-${p(d.getSeconds())}`;
24
+ }
25
+ static isValidName(name) {
26
+ return typeof name === "string" && NAME_RE.test(name);
27
+ }
28
+ static hasContent(dir) {
29
+ try {
30
+ return fs_1.default.readdirSync(dir).some(f => f !== "__tmp");
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ static readMeta(dir) {
37
+ try {
38
+ const m = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, exports.BACKUP_META), "utf-8"));
39
+ return m && typeof m.project === "string" ? m : null;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ static readAppVersion(dir) {
46
+ try {
47
+ const v = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, "package.json"), "utf-8"))?.version;
48
+ return typeof v === "string" ? v : null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ static assertSafeRoot(root) {
55
+ const r = path_1.default.resolve(root);
56
+ if (r === path_1.default.parse(r).root || r.length < 5)
57
+ throw new Error(`refusing to keep backups in "${r}"`);
58
+ }
59
+ static async create(target, project, slot, user, reason) {
60
+ target = path_1.default.resolve(target);
61
+ if (!fs_1.default.existsSync(target) || !BackupManager.hasContent(target))
62
+ return null;
63
+ const root = path_1.default.dirname(target);
64
+ BackupManager.assertSafeRoot(root);
65
+ const label = BackupManager.fileSafe(slot ? `${project}-${slot}` : project);
66
+ const st = BackupManager.stamp();
67
+ let name = `${st}-${label}`;
68
+ for (let n = 2; fs_1.default.existsSync(path_1.default.join(root, name)); n++)
69
+ name = `${st}_${n}-${label}`;
70
+ const finalDir = path_1.default.join(root, name);
71
+ const partial = path_1.default.join(root, PARTIAL_PREFIX + name);
72
+ try {
73
+ await fs_1.default.promises.mkdir(partial, { recursive: true });
74
+ await execFileAsync("cp", ["-a", target + "/.", partial + "/"]);
75
+ await fs_1.default.promises.rm(path_1.default.join(partial, "__tmp"), { recursive: true, force: true });
76
+ const meta = {
77
+ version: 1, project, slot, createdAt: Date.now(), user, reason,
78
+ appVersion: BackupManager.readAppVersion(target),
79
+ };
80
+ await fs_1.default.promises.writeFile(path_1.default.join(partial, exports.BACKUP_META), JSON.stringify(meta, null, 2), "utf-8");
81
+ await fs_1.default.promises.rename(partial, finalDir);
82
+ }
83
+ catch (e) {
84
+ await fs_1.default.promises.rm(partial, { recursive: true, force: true }).catch(() => { });
85
+ throw e;
86
+ }
87
+ return name;
88
+ }
89
+ static async list(root, project, withSize = false) {
90
+ root = path_1.default.resolve(root);
91
+ if (!fs_1.default.existsSync(root))
92
+ return [];
93
+ const out = [];
94
+ for (const e of fs_1.default.readdirSync(root, { withFileTypes: true })) {
95
+ if (!e.isDirectory() || !NAME_RE.test(e.name))
96
+ continue;
97
+ const meta = BackupManager.readMeta(path_1.default.join(root, e.name));
98
+ if (!meta || meta.project !== project)
99
+ continue;
100
+ out.push({ ...meta, name: e.name, sizeKb: null });
101
+ }
102
+ out.sort((a, b) => b.createdAt - a.createdAt);
103
+ if (withSize && out.length > 0) {
104
+ try {
105
+ const { stdout } = await execFileAsync("du", ["-sk", ...out.map(b => path_1.default.join(root, b.name))], { timeout: 20000 });
106
+ for (const line of String(stdout).split("\n")) {
107
+ const m = line.match(/^(\d+)\s+(.+)$/);
108
+ if (!m)
109
+ continue;
110
+ const item = out.find(b => path_1.default.join(root, b.name) === m[2].trim());
111
+ if (item)
112
+ item.sizeKb = parseInt(m[1], 10);
113
+ }
114
+ }
115
+ catch { }
116
+ }
117
+ return out;
118
+ }
119
+ static async prune(root, project, keep = exports.MAX_BACKUPS, protect = []) {
120
+ const all = await BackupManager.list(root, project);
121
+ const removed = [];
122
+ let kept = 0;
123
+ for (const b of all) {
124
+ if (kept < keep || protect.includes(b.name)) {
125
+ kept++;
126
+ continue;
127
+ }
128
+ await fs_1.default.promises.rm(path_1.default.join(path_1.default.resolve(root), b.name), { recursive: true, force: true });
129
+ removed.push(b.name);
130
+ }
131
+ return removed;
132
+ }
133
+ static resolve(root, project, name) {
134
+ if (!BackupManager.isValidName(name))
135
+ return null;
136
+ const r = path_1.default.resolve(root);
137
+ const dir = path_1.default.resolve(r, name);
138
+ if (path_1.default.dirname(dir) !== r)
139
+ return null;
140
+ const meta = BackupManager.readMeta(dir);
141
+ if (!meta || meta.project !== project)
142
+ return null;
143
+ return { dir, meta };
144
+ }
145
+ static async restoreInto(backupDir, target) {
146
+ target = path_1.default.resolve(target);
147
+ const staging = target + ".restore-tmp";
148
+ const old = target + ".restore-old";
149
+ await fs_1.default.promises.rm(staging, { recursive: true, force: true });
150
+ await fs_1.default.promises.rm(old, { recursive: true, force: true });
151
+ await fs_1.default.promises.mkdir(staging, { recursive: true });
152
+ try {
153
+ await execFileAsync("cp", ["-a", backupDir + "/.", staging + "/"]);
154
+ await fs_1.default.promises.rm(path_1.default.join(staging, exports.BACKUP_META), { force: true });
155
+ }
156
+ catch (e) {
157
+ await fs_1.default.promises.rm(staging, { recursive: true, force: true }).catch(() => { });
158
+ throw e;
159
+ }
160
+ const hadTarget = fs_1.default.existsSync(target);
161
+ if (hadTarget)
162
+ await fs_1.default.promises.rename(target, old);
163
+ try {
164
+ await fs_1.default.promises.rename(staging, target);
165
+ }
166
+ catch (e) {
167
+ if (hadTarget)
168
+ await fs_1.default.promises.rename(old, target).catch(() => { });
169
+ throw e;
170
+ }
171
+ await fs_1.default.promises.rm(old, { recursive: true, force: true }).catch(() => { });
172
+ }
173
+ }
174
+ exports.BackupManager = BackupManager;
@@ -0,0 +1,2 @@
1
+ import { IDeployerConfig } from "./resolveConfig";
2
+ export declare function Backups(opt?: IDeployerConfig | string | null): Promise<any[]>;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Backups = Backups;
4
+ const __1 = require("../..");
5
+ const resolveConfig_1 = require("./resolveConfig");
6
+ const cliCommon_1 = require("./cliCommon");
7
+ async function Backups(opt) {
8
+ opt = await (0, resolveConfig_1.resolveConfig)(opt);
9
+ const { red, yellow, blue, green, dim, bold } = (0, cliCommon_1.palette)();
10
+ const r = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, {
11
+ headers: { authorization: (0, cliCommon_1.authHeader)(opt) }, timeoutMs: 30000, retry: { enabled: false },
12
+ });
13
+ const err = (0, cliCommon_1.responseError)(r);
14
+ if (err) {
15
+ console.error(red(bold("✗ Cannot list backups: ")) + err);
16
+ process.exit(1);
17
+ }
18
+ const info = r.data?.data ?? {};
19
+ const list = info.backups ?? [];
20
+ const slotColor = (s) => s === "blue" ? blue(s) : s === "green" ? green(s) : dim("—");
21
+ const line = dim("─".repeat(72));
22
+ console.log("");
23
+ console.log(`${bold("●")} ${bold(info.project ?? opt.name)} ${dim("backups:")} ${list.length}/${info.keep ?? "?"}` +
24
+ (info.bluegreen ? ` ${dim("active:")} ${slotColor(info.activeSlot)}` : ""));
25
+ if (!info.backupEnabled)
26
+ console.log(yellow(" ⚠ backup is disabled for this project — new deploys are not backed up"));
27
+ console.log(line);
28
+ if (list.length === 0) {
29
+ console.log(dim(" no backups yet"));
30
+ }
31
+ else {
32
+ for (const b of list) {
33
+ const reason = b.reason === "pre-restore" ? yellow("pre-restore") : dim("deploy ");
34
+ console.log(` ${bold(b.name)}`);
35
+ console.log(` ${dim("ver")} ${String(b.appVersion ?? "?").padEnd(12)}` +
36
+ (info.bluegreen ? `${dim("slot")} ${slotColor(b.slot).padEnd(15)}` : "") +
37
+ `${reason} ${dim("by")} ${b.user} ${dim((0, cliCommon_1.fmtDate)(b.createdAt))} ${dim((0, cliCommon_1.fmtSize)(b.sizeKb))}`);
38
+ }
39
+ }
40
+ console.log(line);
41
+ console.log("");
42
+ return list;
43
+ }
@@ -11,7 +11,7 @@ declare const _ProjectState: {
11
11
  readonly slot: "";
12
12
  readonly $__slot_values: readonly ["blue", "green"];
13
13
  readonly action: "";
14
- readonly $__action_values: readonly ["deploy", "switch", "rollback"];
14
+ readonly $__action_values: readonly ["deploy", "switch", "rollback", "restore"];
15
15
  readonly user: "";
16
16
  readonly at: 0;
17
17
  }];
@@ -28,6 +28,8 @@ declare const _TConfig: {
28
28
  readonly ignoreDirectoryClean: false;
29
29
  readonly backup: true;
30
30
  readonly install: true;
31
+ readonly migrate: false;
32
+ readonly $__migrate_optional: true;
31
33
  readonly pm2: true;
32
34
  readonly pm2_attributes: readonly [""];
33
35
  readonly $__pm2_attributes_optional: true;
@@ -70,6 +72,7 @@ export declare const REQ_DEPLOYMENT_CONFIG: Req<void, Map<string, {
70
72
  ignoreDirectoryClean: boolean;
71
73
  backup: boolean;
72
74
  install: boolean;
75
+ migrate?: boolean | undefined;
73
76
  pm2: boolean;
74
77
  pm2_attributes?: string[] | undefined;
75
78
  chmod: number;
@@ -100,6 +103,7 @@ export declare const REQ_DEPLOYMENT_CONFIG_ADD: Req<{
100
103
  ignoreDirectoryClean: boolean;
101
104
  backup: boolean;
102
105
  install: boolean;
106
+ migrate?: boolean | undefined;
103
107
  pm2: boolean;
104
108
  pm2_attributes?: string[] | undefined;
105
109
  chmod: number;
@@ -129,6 +133,7 @@ export declare const REQ_DEPLOYMENT_CONFIG_ADD: Req<{
129
133
  ignoreDirectoryClean: boolean;
130
134
  backup: boolean;
131
135
  install: boolean;
136
+ migrate?: boolean | undefined;
132
137
  pm2: boolean;
133
138
  pm2_attributes?: string[] | undefined;
134
139
  chmod: number;
@@ -54,7 +54,7 @@ const _ProjectState = {
54
54
  slot: "",
55
55
  $__slot_values: ["blue", "green"],
56
56
  action: "",
57
- $__action_values: ["deploy", "switch", "rollback"],
57
+ $__action_values: ["deploy", "switch", "rollback", "restore"],
58
58
  user: "",
59
59
  at: 0,
60
60
  }],
@@ -70,6 +70,8 @@ const _TConfig = {
70
70
  ignoreDirectoryClean: false,
71
71
  backup: true,
72
72
  install: true,
73
+ migrate: false,
74
+ $__migrate_optional: true,
73
75
  pm2: true,
74
76
  pm2_attributes: [""],
75
77
  $__pm2_attributes_optional: true,
@@ -6,5 +6,7 @@ export declare class Deployer extends BaseEndpoint {
6
6
  file(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
7
7
  switchSlot(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
8
8
  status(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
9
+ backups(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
10
+ restore(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
9
11
  slot(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
10
12
  }
@@ -54,6 +54,18 @@ class Deployer extends BaseEndpoint_1.BaseEndpoint {
54
54
  $__slot_values: ["blue", "green"],
55
55
  $__slot_optional: true
56
56
  }
57
+ },
58
+ {
59
+ ignoreInterceptor: true,
60
+ endpoint: "backups",
61
+ handler: this.backups,
62
+ validationModel: { name: "" }
63
+ },
64
+ {
65
+ ignoreInterceptor: true,
66
+ endpoint: "restore",
67
+ handler: this.restore,
68
+ validationModel: { name: "", token: "", backup: "" }
57
69
  }
58
70
  ]);
59
71
  }
@@ -69,6 +81,12 @@ class Deployer extends BaseEndpoint_1.BaseEndpoint {
69
81
  async status(req) {
70
82
  return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization });
71
83
  }
84
+ async backups(req) {
85
+ return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization });
86
+ }
87
+ async restore(req) {
88
+ return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization });
89
+ }
72
90
  async slot(req) {
73
91
  return await DeployerService_1.REQ_DEPLOYMENT_SLOT.request({ name: req.data.name, token: req.data.token, slot: req.data.slot });
74
92
  }
@@ -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 _isDestinationSafe;
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
- _isDestinationSafe(destination) {
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
- const dest = path_1.default.resolve(destination);
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 false;
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,2 @@
1
+ import { IDeployerConfig } from "./resolveConfig";
2
+ export declare function Restore(opt?: IDeployerConfig | string | null, backupName?: string, assumeYes?: boolean): Promise<void>;
@@ -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;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.deployerUrl = deployerUrl;
7
+ exports.authHeader = authHeader;
8
+ exports.responseError = responseError;
9
+ exports.palette = palette;
10
+ exports.fmtDate = fmtDate;
11
+ exports.fmtSize = fmtSize;
12
+ const crypto_1 = __importDefault(require("crypto"));
13
+ const __1 = require("../..");
14
+ function deployerUrl(opt, endpoint) {
15
+ if (/\/add\/?$/.test(opt.host))
16
+ return opt.host.replace(/\/add\/?$/, "/" + endpoint);
17
+ if (opt.switch_host && /\/switch\/?$/.test(opt.switch_host))
18
+ return opt.switch_host.replace(/\/switch\/?$/, "/" + endpoint);
19
+ throw new Error(`Cannot derive the ${endpoint} URL from host "${opt.host}" — make sure "host" ends with /add.`);
20
+ }
21
+ function authHeader(opt) {
22
+ return "Bearer " + crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
23
+ }
24
+ function responseError(r) {
25
+ const body = r?.ok ? r?.data : r?.error;
26
+ const e = (body && typeof body === "object")
27
+ ? (body.error ?? (__1.ErrorUtils.isError(body.data) ? body.data : null) ?? (__1.ErrorUtils.isError(body) ? body : null))
28
+ : null;
29
+ if (e && (e.message || e.details)) {
30
+ const text = [e.message, e.details].filter(Boolean).join(" — ");
31
+ return e.code !== undefined ? `${text} (code ${e.code})` : text;
32
+ }
33
+ if (!r?.ok) {
34
+ if (r?.status !== undefined)
35
+ return `HTTP ${r.status}`;
36
+ const raw = typeof r?.error === "string" ? r.error : JSON.stringify(r?.error);
37
+ return "network error: " + raw;
38
+ }
39
+ return null;
40
+ }
41
+ function palette() {
42
+ const on = !!process.stdout.isTTY && !process.env.NO_COLOR;
43
+ const c = (code) => (t) => on ? `\x1b[${code}m${t}\x1b[0m` : t;
44
+ return { red: c("31"), green: c("32"), yellow: c("33"), blue: c("34"), dim: c("2"), bold: c("1") };
45
+ }
46
+ function fmtDate(ms) {
47
+ const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
48
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
49
+ }
50
+ function fmtSize(kb) {
51
+ if (kb === null || kb === undefined)
52
+ return "—";
53
+ if (kb < 1024)
54
+ return `${kb} KB`;
55
+ if (kb < 1024 * 1024)
56
+ return `${(kb / 1024).toFixed(1)} MB`;
57
+ return `${(kb / 1024 / 1024).toFixed(2)} GB`;
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badmfck-api-server",
3
- "version": "5.0.12",
3
+ "version": "5.0.14",
4
4
  "description": "Simple API http server based on express",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",