@bmfk/api 0.0.0-stage → 1.0.0

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.
Files changed (169) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1293 -2
  4. package/dist/apiServer/APIService.d.ts +125 -0
  5. package/dist/apiServer/APIService.js +769 -0
  6. package/dist/apiServer/BaseEndpoint.d.ts +90 -0
  7. package/dist/apiServer/BaseEndpoint.js +314 -0
  8. package/dist/apiServer/BaseService.d.ts +17 -0
  9. package/dist/apiServer/BaseService.js +39 -0
  10. package/dist/apiServer/DBService.d.ts +131 -0
  11. package/dist/apiServer/DBService.js +290 -0
  12. package/dist/apiServer/DocumentService.d.ts +9 -0
  13. package/dist/apiServer/DocumentService.js +65 -0
  14. package/dist/apiServer/LocalRequest.d.ts +3 -0
  15. package/dist/apiServer/LocalRequest.js +6 -0
  16. package/dist/apiServer/LogService.d.ts +78 -0
  17. package/dist/apiServer/LogService.js +349 -0
  18. package/dist/apiServer/MonitorService.d.ts +102 -0
  19. package/dist/apiServer/MonitorService.js +615 -0
  20. package/dist/apiServer/StatService.d.ts +4 -0
  21. package/dist/apiServer/StatService.js +10 -0
  22. package/dist/apiServer/TimeframeService.d.ts +28 -0
  23. package/dist/apiServer/TimeframeService.js +97 -0
  24. package/dist/apiServer/WebSocketServer.d.ts +39 -0
  25. package/dist/apiServer/WebSocketServer.js +173 -0
  26. package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
  27. package/dist/apiServer/db/IDBAdapter.js +2 -0
  28. package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
  29. package/dist/apiServer/db/MysqlAdapter.js +869 -0
  30. package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
  31. package/dist/apiServer/db/PostgresAdapter.js +73 -0
  32. package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
  33. package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
  34. package/dist/apiServer/deployment/Activate.d.ts +4 -0
  35. package/dist/apiServer/deployment/Activate.js +124 -0
  36. package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
  37. package/dist/apiServer/deployment/BackupManager.js +174 -0
  38. package/dist/apiServer/deployment/Backups.d.ts +2 -0
  39. package/dist/apiServer/deployment/Backups.js +44 -0
  40. package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
  41. package/dist/apiServer/deployment/BlueGreenState.js +150 -0
  42. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  43. package/dist/apiServer/deployment/Bundler.js +178 -0
  44. package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
  45. package/dist/apiServer/deployment/ConfigService.js +195 -0
  46. package/dist/apiServer/deployment/Deploy.d.ts +4 -0
  47. package/dist/apiServer/deployment/Deploy.js +404 -0
  48. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  49. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  50. package/dist/apiServer/deployment/Deployer.d.ts +13 -0
  51. package/dist/apiServer/deployment/Deployer.js +96 -0
  52. package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
  53. package/dist/apiServer/deployment/DeployerInit.js +214 -0
  54. package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
  55. package/dist/apiServer/deployment/DeployerService.js +1553 -0
  56. package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
  57. package/dist/apiServer/deployment/HashPassword.js +126 -0
  58. package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
  59. package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
  60. package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
  61. package/dist/apiServer/deployment/MigrateProject.js +335 -0
  62. package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
  63. package/dist/apiServer/deployment/NginxHelper.js +111 -0
  64. package/dist/apiServer/deployment/Notifier.d.ts +30 -0
  65. package/dist/apiServer/deployment/Notifier.js +82 -0
  66. package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
  67. package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
  68. package/dist/apiServer/deployment/Restore.d.ts +2 -0
  69. package/dist/apiServer/deployment/Restore.js +89 -0
  70. package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
  71. package/dist/apiServer/deployment/ReviewStore.js +186 -0
  72. package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
  73. package/dist/apiServer/deployment/SecretsInjector.js +189 -0
  74. package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
  75. package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
  76. package/dist/apiServer/deployment/Status.d.ts +2 -0
  77. package/dist/apiServer/deployment/Status.js +83 -0
  78. package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
  79. package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
  80. package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
  81. package/dist/apiServer/deployment/Watchdog.js +65 -0
  82. package/dist/apiServer/deployment/Wizards.d.ts +1 -0
  83. package/dist/apiServer/deployment/Wizards.js +83 -0
  84. package/dist/apiServer/deployment/cli.d.ts +2 -0
  85. package/dist/apiServer/deployment/cli.js +224 -0
  86. package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
  87. package/dist/apiServer/deployment/cliCommon.js +110 -0
  88. package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
  89. package/dist/apiServer/deployment/cliPrompt.js +38 -0
  90. package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
  91. package/dist/apiServer/deployment/resolveConfig.js +139 -0
  92. package/dist/apiServer/documentation/Documentation.d.ts +18 -0
  93. package/dist/apiServer/documentation/Documentation.js +143 -0
  94. package/dist/apiServer/documentation/index.html +460 -0
  95. package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
  96. package/dist/apiServer/external/MicroserviceClient.js +144 -0
  97. package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
  98. package/dist/apiServer/external/MicroserviceHost.js +183 -0
  99. package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
  100. package/dist/apiServer/external/MicroserviceHostController.js +65 -0
  101. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  102. package/dist/apiServer/helper/AppDataPath.js +81 -0
  103. package/dist/apiServer/helper/ClientIp.d.ts +3 -0
  104. package/dist/apiServer/helper/ClientIp.js +33 -0
  105. package/dist/apiServer/helper/DataProvider.d.ts +18 -0
  106. package/dist/apiServer/helper/DataProvider.js +57 -0
  107. package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
  108. package/dist/apiServer/helper/IpAllowList.js +40 -0
  109. package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
  110. package/dist/apiServer/helper/JSONStableStringify.js +15 -0
  111. package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
  112. package/dist/apiServer/helper/PasswordHash.js +52 -0
  113. package/dist/apiServer/helper/Sleep.d.ts +1 -0
  114. package/dist/apiServer/helper/Sleep.js +5 -0
  115. package/dist/apiServer/helper/Trace.d.ts +8 -0
  116. package/dist/apiServer/helper/Trace.js +30 -0
  117. package/dist/apiServer/helper/UID.d.ts +16 -0
  118. package/dist/apiServer/helper/UID.js +98 -0
  119. package/dist/apiServer/helper/Validator.d.ts +86 -0
  120. package/dist/apiServer/helper/Validator.js +560 -0
  121. package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
  122. package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
  123. package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
  124. package/dist/apiServer/helper/ZipUtils.js +28 -0
  125. package/dist/apiServer/http/Http.d.ts +183 -0
  126. package/dist/apiServer/http/Http.js +627 -0
  127. package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
  128. package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
  129. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  130. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  131. package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
  132. package/dist/apiServer/monitor/AccessStore.js +163 -0
  133. package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
  134. package/dist/apiServer/monitor/LogFiles.js +109 -0
  135. package/dist/apiServer/monitor/Monitor.d.ts +54 -0
  136. package/dist/apiServer/monitor/Monitor.js +447 -0
  137. package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
  138. package/dist/apiServer/monitor/MonitorAuth.js +474 -0
  139. package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
  140. package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
  141. package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
  142. package/dist/apiServer/monitor/SystemInfo.js +217 -0
  143. package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
  144. package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
  145. package/dist/apiServer/monitor/index.html +591 -0
  146. package/dist/apiServer/review/Review.d.ts +23 -0
  147. package/dist/apiServer/review/Review.js +149 -0
  148. package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
  149. package/dist/apiServer/review/ReviewAuth.js +147 -0
  150. package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
  151. package/dist/apiServer/review/ReviewDiff.js +175 -0
  152. package/dist/apiServer/review/index.html +501 -0
  153. package/dist/apiServer/routes/Liveness.d.ts +7 -0
  154. package/dist/apiServer/routes/Liveness.js +27 -0
  155. package/dist/apiServer/routes/Readiness.d.ts +13 -0
  156. package/dist/apiServer/routes/Readiness.js +20 -0
  157. package/dist/apiServer/security/BlockedIps.d.ts +46 -0
  158. package/dist/apiServer/security/BlockedIps.js +185 -0
  159. package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
  160. package/dist/apiServer/structures/DefaultErrors.js +52 -0
  161. package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
  162. package/dist/apiServer/structures/HTTPStatus.js +11 -0
  163. package/dist/apiServer/structures/Interfaces.d.ts +55 -0
  164. package/dist/apiServer/structures/Interfaces.js +2 -0
  165. package/dist/index.d.ts +45 -0
  166. package/dist/index.js +110 -0
  167. package/dist/signal/Signal.d.ts +23 -0
  168. package/dist/signal/Signal.js +85 -0
  169. package/package.json +88 -4
@@ -0,0 +1,1553 @@
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.DeployerService = exports.REQ_DEPLOYMENT_RESTORE = exports.REQ_DEPLOYER_PUBLIC_KEY = exports.REQ_DEPLOYMENT_BACKUPS = exports.REQ_DEPLOYMENT_SLOT = exports.REQ_DEPLOYMENT_STATUS = exports.REQ_DEPLOYMENT_SWITCH = exports.REQ_DEPLOYMENT_PROCEED = exports.SETUP_MODEL = void 0;
7
+ const Signal_1 = require("../../signal/Signal");
8
+ const BaseService_1 = require("../BaseService");
9
+ const ConfigService_1 = require("./ConfigService");
10
+ const path_1 = __importDefault(require("path"));
11
+ const LogService_1 = require("../LogService");
12
+ const DefaultErrors_1 = require("../structures/DefaultErrors");
13
+ const Http_1 = require("../http/Http");
14
+ const UID_1 = require("../helper/UID");
15
+ const Validator_1 = require("../helper/Validator");
16
+ const Notifier_1 = require("./Notifier");
17
+ const TelegramNotifier_1 = require("./TelegramNotifier");
18
+ const child_process_1 = require("child_process");
19
+ const util_1 = require("util");
20
+ const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
21
+ const fs_1 = __importDefault(require("fs"));
22
+ const crypto_1 = __importDefault(require("crypto"));
23
+ const Watchdog_1 = require("./Watchdog");
24
+ const NginxHelper_1 = require("./NginxHelper");
25
+ const BlueGreenState_1 = require("./BlueGreenState");
26
+ const BackupManager_1 = require("./BackupManager");
27
+ const PasswordHash_1 = require("../helper/PasswordHash");
28
+ const ReviewStore_1 = require("./ReviewStore");
29
+ const SecretsInjector_1 = require("./SecretsInjector");
30
+ const IpAllowList_1 = require("../helper/IpAllowList");
31
+ const _TSetup = {
32
+ users: [{
33
+ login: "",
34
+ password: "",
35
+ $__password_optional: true,
36
+ publicKey: "",
37
+ $__publicKey_optional: true,
38
+ }],
39
+ require_signature: true,
40
+ $__require_signature_optional: true,
41
+ watchdog: true,
42
+ $__watchdog_optional: true,
43
+ notifier: {
44
+ URL: "",
45
+ KEY: "",
46
+ },
47
+ $__notifier_optional: true,
48
+ telegram: {
49
+ bot: "",
50
+ chat: "",
51
+ topic: 0,
52
+ $__topic_optional: true,
53
+ },
54
+ $__telegram_optional: true,
55
+ status_url: "",
56
+ $__status_url_optional: true,
57
+ allowed_ips: [""],
58
+ $__allowed_ips_optional: true,
59
+ reviewers: [{
60
+ login: "",
61
+ password: "",
62
+ email: "",
63
+ }],
64
+ $__reviewers_optional: true,
65
+ review_url: "",
66
+ $__review_url_optional: true,
67
+ secrets_dir: "",
68
+ $__secrets_dir_optional: true
69
+ };
70
+ exports.SETUP_MODEL = _TSetup;
71
+ exports.REQ_DEPLOYMENT_PROCEED = new Signal_1.Req(undefined, "REQ_DEPLOYER_SERVICE");
72
+ exports.REQ_DEPLOYMENT_SWITCH = new Signal_1.Req(undefined, "REQ_DEPLOYER_SWITCH");
73
+ exports.REQ_DEPLOYMENT_STATUS = new Signal_1.Req(undefined, "REQ_DEPLOYER_STATUS");
74
+ exports.REQ_DEPLOYMENT_SLOT = new Signal_1.Req(undefined, "REQ_DEPLOYER_SLOT");
75
+ exports.REQ_DEPLOYMENT_BACKUPS = new Signal_1.Req(undefined, "REQ_DEPLOYER_BACKUPS");
76
+ exports.REQ_DEPLOYER_PUBLIC_KEY = new Signal_1.Req(undefined, "REQ_DEPLOYER_PUBLIC_KEY");
77
+ exports.REQ_DEPLOYMENT_RESTORE = new Signal_1.Req(undefined, "REQ_DEPLOYER_RESTORE");
78
+ class DeployerService extends BaseService_1.BaseService {
79
+ static MAX_HISTORY = 200;
80
+ static _trimHistory(state) {
81
+ const h = state.history;
82
+ if (Array.isArray(h) && h.length > DeployerService.MAX_HISTORY)
83
+ h.splice(0, h.length - DeployerService.MAX_HISTORY);
84
+ }
85
+ options;
86
+ setup = null;
87
+ notifier = null;
88
+ telegram(project, status, user) {
89
+ const t = this.setup?.telegram;
90
+ if (t?.bot && t?.chat)
91
+ void (0, TelegramNotifier_1.sendTelegram)({ bot: t.bot, chat: String(t.chat), topic: t.topic || undefined }, (0, TelegramNotifier_1.telegramText)(project, status, user));
92
+ }
93
+ busy = new Map();
94
+ reviews;
95
+ _setupWatchDebounceTimer = null;
96
+ _lastSetupHash = null;
97
+ constructor(options) {
98
+ super("DeployerService");
99
+ this.options = options;
100
+ }
101
+ async init() {
102
+ this.reviews = new ReviewStore_1.ReviewStore(this.options.projects_path);
103
+ const sweep = () => { for (const p of this.reviews.sweep())
104
+ (0, LogService_1.logWarn)(`Review of "${p}" expired — the uploaded archive was removed`); };
105
+ sweep();
106
+ setInterval(sweep, 10 * 60 * 1000).unref();
107
+ super.init();
108
+ const cs = new ConfigService_1.ConfigService(this.options.projects_path);
109
+ await cs.init();
110
+ const initial = await this._loadSetup();
111
+ if (!initial) {
112
+ throw new Error("Setup file missing/invalid at start — cannot start deployer");
113
+ }
114
+ this.setup = initial;
115
+ this._warnPlaintextUsers();
116
+ this._lastSetupHash = crypto_1.default.createHash("md5").update(JSON.stringify(initial)).digest("hex");
117
+ if (this.setup.notifier?.URL && this.setup.notifier?.KEY) {
118
+ this.notifier = new Notifier_1.Notifier({ URL: this.setup.notifier.URL, KEY: this.setup.notifier.KEY });
119
+ await this.notifier.init();
120
+ }
121
+ if (this.setup.watchdog) {
122
+ const wd = new Watchdog_1.Watchdog(this.notifier, (project, status) => this.telegram(project, status, "watchdog"));
123
+ await wd.init();
124
+ }
125
+ this._watchSetup();
126
+ exports.REQ_DEPLOYMENT_PROCEED.listener = async (data) => this.proceed(data);
127
+ exports.REQ_DEPLOYMENT_SWITCH.listener = async (data) => this.switchSlot(data);
128
+ exports.REQ_DEPLOYMENT_STATUS.listener = async (data) => this.status(data);
129
+ exports.REQ_DEPLOYMENT_SLOT.listener = async (data) => this.slotState(data);
130
+ exports.REQ_DEPLOYMENT_BACKUPS.listener = async (data) => this.listBackups(data);
131
+ exports.REQ_DEPLOYMENT_RESTORE.listener = async (data) => this.restoreBackup(data);
132
+ exports.REQ_DEPLOYER_PUBLIC_KEY.listener = async (login) => (this.setup?.users ?? []).find(u => u.login === login)?.publicKey || null;
133
+ await this._checkReviewSetup();
134
+ ConfigService_1.S_CONFIG_UPDATED.subscribe(() => { this._checkReviewSetup(); });
135
+ }
136
+ async _checkReviewSetup() {
137
+ try {
138
+ const plain = (this.setup?.reviewers ?? []).filter(r => r?.login && !PasswordHash_1.PasswordHash.isHash(r.password)).map(r => r.login);
139
+ if (plain.length)
140
+ (0, LogService_1.logError)(`Deployer: reviewer password stored as plain text for ${plain.map(l => '"' + l + '"').join(", ")} — these reviewers can't sign in; store a hash: npx bmfk hash-password`);
141
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
142
+ for (const c of configurations.values()) {
143
+ if (!c?.review)
144
+ continue;
145
+ const problem = this._reviewSetup(c).error;
146
+ if (problem)
147
+ (0, LogService_1.logError)(`Deployer: review of "${c.name}" can't work — ${problem}. Uploads of this project will be refused until it is fixed.`);
148
+ }
149
+ }
150
+ catch (e) {
151
+ (0, LogService_1.logWarn)("Deployer: can't check the review setup: " + (e?.message ?? e));
152
+ }
153
+ }
154
+ async _loadSetup() {
155
+ const setupFile = path_1.default.resolve(this.options.setup_path, "setup.json");
156
+ if (!fs_1.default.existsSync(setupFile)) {
157
+ (0, LogService_1.logError)("Setup file not found: " + setupFile);
158
+ return null;
159
+ }
160
+ let raw;
161
+ try {
162
+ raw = fs_1.default.readFileSync(setupFile, "utf-8");
163
+ }
164
+ catch (e) {
165
+ (0, LogService_1.logError)("Failed to read setup file: " + e.message);
166
+ return null;
167
+ }
168
+ let parsed;
169
+ try {
170
+ parsed = JSON.parse(raw);
171
+ }
172
+ catch (e) {
173
+ (0, LogService_1.logError)("Failed to parse setup.json: " + e.message);
174
+ return null;
175
+ }
176
+ const errors = await Validator_1.Validator.validateStructure(_TSetup, parsed);
177
+ if (errors && errors.length > 0) {
178
+ (0, LogService_1.logError)("Setup validation failed: " + JSON.stringify(errors));
179
+ return null;
180
+ }
181
+ const ips = DeployerService.buildAllowList(parsed.allowed_ips);
182
+ if (ips.error) {
183
+ (0, LogService_1.logError)("Setup validation failed: allowed_ips — " + ips.error);
184
+ return null;
185
+ }
186
+ return parsed;
187
+ }
188
+ async _reloadSetup() {
189
+ const fresh = await this._loadSetup();
190
+ if (!fresh) {
191
+ (0, LogService_1.logWarn)("Setup reload failed — keeping previous good setup in memory");
192
+ return;
193
+ }
194
+ const hash = crypto_1.default.createHash("md5").update(JSON.stringify(fresh)).digest("hex");
195
+ if (hash === this._lastSetupHash)
196
+ return;
197
+ this._lastSetupHash = hash;
198
+ this.setup = fresh;
199
+ this._warnPlaintextUsers();
200
+ this._checkReviewSetup();
201
+ (0, LogService_1.logWarn)("Setup reloaded from disk (users list refreshed live; notifier/watchdog need service restart to change)");
202
+ }
203
+ _watchSetup() {
204
+ try {
205
+ fs_1.default.watch(this.options.setup_path, (_eventType, filename) => {
206
+ if (filename !== "setup.json")
207
+ return;
208
+ if (this._setupWatchDebounceTimer)
209
+ clearTimeout(this._setupWatchDebounceTimer);
210
+ this._setupWatchDebounceTimer = setTimeout(() => {
211
+ this._setupWatchDebounceTimer = null;
212
+ this._reloadSetup();
213
+ }, 200);
214
+ });
215
+ }
216
+ catch (e) {
217
+ (0, LogService_1.logError)("Failed to fs.watch setup file: " + e.message);
218
+ }
219
+ setInterval(() => { this._reloadSetup(); }, 60_000).unref();
220
+ }
221
+ async proceed(data) {
222
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
223
+ const user = auth.user;
224
+ if (!user) {
225
+ (0, LogService_1.logError)("Deploy rejected: user auth failed");
226
+ return { error: { code: 20, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
227
+ }
228
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
229
+ const project = await this._projectByToken(configurations, data.name, data.token);
230
+ if (project.error)
231
+ return { error: { code: 12, message: project.error, httpStatus: 400 } };
232
+ let found = project.config;
233
+ if (!found) {
234
+ (0, LogService_1.logError)("Deploy rejected: wrong token and/or name");
235
+ return { error: { code: 12, message: "Wrong token and/or name.", httpStatus: 400 } };
236
+ }
237
+ if (this.busy.get(found.name))
238
+ return { error: { code: 13, message: "Deployment already in progress.", httpStatus: 400 } };
239
+ if (found.review)
240
+ return await this._queueForReview(found, user, data.files.file, data.ip);
241
+ return await this._deploy(found, user, configurations, data.name, { file: data.files.file });
242
+ }
243
+ async _deploy(found, user, configurations, name, source) {
244
+ if (this.busy.get(found.name))
245
+ return { error: { code: 13, message: "Deployment already in progress.", httpStatus: 400 } };
246
+ const realName = found.name;
247
+ const data = { name };
248
+ this.busy.set(realName, true);
249
+ let baselineStaged = false;
250
+ try {
251
+ found = structuredClone(found);
252
+ const allConfigs = Array.from(configurations.values());
253
+ const isBGProject = !!(found.bluegreen && found.bluegreen.blue_config && found.bluegreen.green_config);
254
+ const rootProblem = this._destinationProblem(found.destination, !isBGProject && !!found.unpack && !found.ignoreDirectoryClean, allConfigs, found.destination);
255
+ if (rootProblem) {
256
+ (0, LogService_1.logError)("Deploy rejected: unsafe destination: " + rootProblem);
257
+ throw { code: 19, message: "Unsafe destination.", details: rootProblem, httpStatus: 400 };
258
+ }
259
+ const sourceName = source.file ? source.file.name : path_1.default.basename(source.archivePath ?? "");
260
+ const safeName = (path_1.default.basename(sourceName || "").replace(/[^a-zA-Z0-9._-]/g, "_")) || "upload";
261
+ let projectState = null;
262
+ let projectStatePath = null;
263
+ let projectStateWasCreated = false;
264
+ if (found.bluegreen && found.bluegreen.blue_config && found.bluegreen.green_config) {
265
+ projectStatePath = path_1.default.resolve(this.options.projects_path, data.name + "_state_.json");
266
+ if (fs_1.default.existsSync(projectStatePath)) {
267
+ try {
268
+ projectState = JSON.parse(fs_1.default.readFileSync(projectStatePath, "utf-8"));
269
+ }
270
+ catch (e) {
271
+ (0, LogService_1.logError)("Failed to load project state: " + e.message);
272
+ }
273
+ }
274
+ if (!projectState) {
275
+ projectState = {
276
+ active: "blue",
277
+ lastDeployed: "blue",
278
+ history: []
279
+ };
280
+ projectStateWasCreated = true;
281
+ }
282
+ else {
283
+ projectState.lastDeployed = projectState.active === "blue" ? "green" : "blue";
284
+ }
285
+ if (!projectState.statusToken)
286
+ projectState.statusToken = crypto_1.default.randomBytes(32).toString("hex");
287
+ projectState.history.push({
288
+ slot: projectState.lastDeployed,
289
+ action: "deploy",
290
+ user: user.login,
291
+ at: Date.now()
292
+ });
293
+ DeployerService._trimHistory(projectState);
294
+ const subdir = projectState.lastDeployed;
295
+ const deployPath = path_1.default.resolve(found.destination, subdir);
296
+ fs_1.default.mkdirSync(deployPath, { recursive: true });
297
+ found.destination = deployPath;
298
+ if (projectState && found.bluegreen) {
299
+ const baseConfig = found.config ?? {};
300
+ if (projectState.lastDeployed === "blue" && found.bluegreen.blue_config) {
301
+ found.config = { ...baseConfig, ...found.bluegreen.blue_config };
302
+ }
303
+ else if (projectState.lastDeployed === "green" && found.bluegreen.green_config) {
304
+ found.config = { ...baseConfig, ...found.bluegreen.green_config };
305
+ }
306
+ }
307
+ found.name = data.name + "-" + projectState.lastDeployed;
308
+ const slotProblem = this._destinationProblem(found.destination, !!found.unpack && !found.ignoreDirectoryClean, allConfigs, path_1.default.dirname(path_1.default.resolve(found.destination)));
309
+ if (slotProblem) {
310
+ (0, LogService_1.logError)("Deploy rejected: unsafe slot destination: " + slotProblem);
311
+ throw { code: 19, message: "Unsafe destination.", details: slotProblem, httpStatus: 400 };
312
+ }
313
+ }
314
+ let secretsFile = null;
315
+ if (found.secrets) {
316
+ const slotName = projectState ? projectState.lastDeployed : null;
317
+ const resolved = SecretsInjector_1.SecretsInjector.resolvePath(realName, slotName, found.secrets, this.setup?.secrets_dir, projectState ? path_1.default.dirname(path_1.default.resolve(found.destination)) : found.destination);
318
+ if (resolved.error) {
319
+ (0, LogService_1.logError)(`Deploy of "${realName}" rejected: ${resolved.error}`);
320
+ throw { code: 64, message: "Secrets are misconfigured.", details: resolved.error, httpStatus: 500 };
321
+ }
322
+ secretsFile = resolved.path;
323
+ if (found.pm2) {
324
+ const attrs = DeployerService._pm2AttributesFor(found, projectState);
325
+ const switchesUser = attrs.find(a => /^--(uid|gid|user)(=|$)/.test(a));
326
+ if (switchesUser) {
327
+ const why = `pm2 runs this project as another user (${switchesUser}), which couldn't read the secrets file`;
328
+ (0, LogService_1.logError)(`Deploy of "${realName}" rejected: ${why}`);
329
+ throw { code: 65, message: "Secrets can't be used with this pm2 setup.", details: why + " — remove \"secrets\" from the project config or the user switch from its pm2 attributes", httpStatus: 400 };
330
+ }
331
+ }
332
+ }
333
+ const uploadPath = path_1.default.resolve(found.destination, UID_1.UID.generate() + "_" + safeName);
334
+ if (found.backup) {
335
+ try {
336
+ const slot = projectState ? projectState.lastDeployed : null;
337
+ const backupName = await BackupManager_1.BackupManager.create(found.destination, realName, slot, user.login, "deploy");
338
+ if (backupName) {
339
+ (0, LogService_1.logInfo)(`Backup created: ${backupName}`);
340
+ const removed = await BackupManager_1.BackupManager.prune(path_1.default.dirname(path_1.default.resolve(found.destination)), realName, BackupManager_1.MAX_BACKUPS);
341
+ if (removed.length)
342
+ (0, LogService_1.logInfo)(`Old backups removed: ${removed.join(", ")}`);
343
+ }
344
+ }
345
+ catch (e) {
346
+ (0, LogService_1.logError)("Backup failed, deploy aborted: " + (e?.message ?? e));
347
+ this.telegram(found.name, "error-backup", user.login);
348
+ if (found.email && found.email.length > 0) {
349
+ for (let email of found.email)
350
+ this.notifier?.notifyEmailStatus(email, "error-backup", found.name, user.login);
351
+ }
352
+ throw { code: 54, message: "Backup failed, deploy aborted — nothing was changed.", details: String(e?.message ?? e), httpStatus: 500 };
353
+ }
354
+ }
355
+ const result = source.file
356
+ ? await this.upload(source.file, uploadPath)
357
+ : this._copyArchive(source.archivePath, uploadPath);
358
+ if (DefaultErrors_1.ErrorUtils.isError(result)) {
359
+ this.telegram(found.name, "error-copy", user.login);
360
+ if (found.email && found.email.length > 0) {
361
+ for (let email of found.email) {
362
+ this.notifier?.notifyEmailStatus(email, "error-copy", found.name, user.login);
363
+ }
364
+ }
365
+ throw result;
366
+ }
367
+ if (found.review) {
368
+ try {
369
+ this.reviews.stageBaseline(realName, uploadPath);
370
+ baselineStaged = true;
371
+ }
372
+ catch (e) {
373
+ (0, LogService_1.logWarn)(`Review baseline for "${realName}" not kept: ${e?.message ?? e}`);
374
+ }
375
+ }
376
+ if (found.unpack) {
377
+ const unpackResult = await this.unpack(found.destination, uploadPath, found.install, found.ignoreDirectoryClean, found.omitDev, realName);
378
+ if (DefaultErrors_1.ErrorUtils.isError(unpackResult)) {
379
+ this.telegram(found.name, "error-unpack", user.login);
380
+ if (found.email && found.email.length > 0) {
381
+ for (let email of found.email) {
382
+ this.notifier?.notifyEmailStatus(email, "error-unpack", found.name, user.login);
383
+ }
384
+ }
385
+ throw unpackResult;
386
+ }
387
+ }
388
+ if (found.chmod && found.chmod > 1) {
389
+ const others = Number(String(found.chmod).slice(-1));
390
+ if (others & 2)
391
+ (0, LogService_1.logWarn)(`"${realName}": chmod ${found.chmod} makes the deployed files WRITABLE by every user on the server — anyone can change the code that runs`);
392
+ else if (others & 4)
393
+ (0, LogService_1.logWarn)(`"${realName}": chmod ${found.chmod} makes the deployed files readable by every user on the server${found.secrets ? "" : " — including the substituted config values"}`);
394
+ try {
395
+ (0, LogService_1.logInfo)("Try to execute: ", `chmod -R ${found.chmod} ${found.destination}`);
396
+ (0, child_process_1.execFileSync)("chmod", ["-R", String(found.chmod), found.destination]);
397
+ }
398
+ catch (e) {
399
+ (0, LogService_1.logError)("Can't execute chmod", e);
400
+ }
401
+ }
402
+ if (found.config) {
403
+ let inject = secretsFile;
404
+ if (secretsFile) {
405
+ SecretsInjector_1.SecretsInjector.write(secretsFile, found.config);
406
+ const unreadable = SecretsInjector_1.SecretsInjector.verify(secretsFile, found.config);
407
+ if (unreadable) {
408
+ (0, LogService_1.logError)(`Deploy of "${found.name}" stopped: ${unreadable}`);
409
+ throw { code: 66, message: "The secrets file can't be read back — the app was not started.", details: unreadable, httpStatus: 500 };
410
+ }
411
+ (0, LogService_1.logInfo)(`Secrets of "${found.name}" written to ${secretsFile}`);
412
+ try {
413
+ const pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(found.destination, "package.json"), "utf-8"));
414
+ if (pkg?.type === "module") {
415
+ (0, LogService_1.logWarn)(`Secrets of "${found.name}": the project is an ES module ("type": "module") — values are substituted into the code as before`);
416
+ inject = null;
417
+ }
418
+ }
419
+ catch { }
420
+ }
421
+ const onDisk = [];
422
+ await this.applyConfig(found.destination, found.config, { secretsFile: inject, onDisk });
423
+ if (secretsFile && onDisk.length)
424
+ (0, LogService_1.logWarn)(`Secrets of "${found.name}" are still written into ${onDisk.length} file(s) — only quoted placeholders in .js/.cjs can read the secrets file: ${onDisk.map(f => path_1.default.relative(found.destination, f)).join(", ")}`);
425
+ }
426
+ if (projectState && projectStatePath) {
427
+ this._writeBlueGreenFiles(data.name, projectState, path_1.default.dirname(found.destination));
428
+ }
429
+ if (found.migrate) {
430
+ const migrateErr = await this._runMigrate(found.destination);
431
+ if (migrateErr) {
432
+ this.telegram(found.name, "error-migrate", user.login);
433
+ if (found.email && found.email.length > 0) {
434
+ for (let email of found.email)
435
+ this.notifier?.notifyEmailStatus(email, "error-migrate", found.name, user.login);
436
+ }
437
+ throw migrateErr;
438
+ }
439
+ }
440
+ if (found.pm2) {
441
+ const pm2Result = await this.runPM2(found, projectState);
442
+ if (DefaultErrors_1.ErrorUtils.isError(pm2Result)) {
443
+ this.telegram(found.name, "error-pm2", user.login);
444
+ if (found.email && found.email.length > 0) {
445
+ for (let email of found.email) {
446
+ this.notifier?.notifyEmailStatus(email, "error-pm2", found.name, user.login);
447
+ }
448
+ }
449
+ throw pm2Result;
450
+ }
451
+ }
452
+ if (found.nginx?.config_dir && (!projectState || projectStateWasCreated)) {
453
+ const activeCfg = (found.config ?? {});
454
+ const nginxErr = await this._renderNginx(found, data.name, DeployerService._extractPort(activeCfg));
455
+ if (nginxErr) {
456
+ this.telegram(found.name, "error-nginx", user.login);
457
+ if (found.email && found.email.length > 0) {
458
+ for (let email of found.email) {
459
+ this.notifier?.notifyEmailStatus(email, "error-nginx", found.name, user.login);
460
+ }
461
+ }
462
+ throw nginxErr;
463
+ }
464
+ const hookErr = await NginxHelper_1.NginxHelper.runHook(found.bluegreen?.on_switch);
465
+ if (hookErr) {
466
+ (0, LogService_1.logWarn)("nginx reload after initial deploy failed: " + hookErr);
467
+ }
468
+ }
469
+ if (projectState && projectStatePath) {
470
+ const tmp = projectStatePath + ".tmp";
471
+ fs_1.default.writeFileSync(tmp, JSON.stringify(projectState, null, 4), "utf-8");
472
+ fs_1.default.renameSync(tmp, projectStatePath);
473
+ }
474
+ this.telegram(found.name, "done", user.login);
475
+ if (found.email && found.email.length > 0) {
476
+ for (let email of found.email) {
477
+ this.notifier?.notifyEmailStatus(email, "done", found.name, user.login);
478
+ }
479
+ }
480
+ if (found.phone && found.phone.length > 0) {
481
+ for (let p of found.phone) {
482
+ this.notifier?.notifySMSStatus(p, found.name + " deployment done", user.login);
483
+ }
484
+ }
485
+ if (found.liveness) {
486
+ const conf = found;
487
+ const liveness = found.liveness;
488
+ setTimeout(async () => {
489
+ const result = await Http_1.Http.get(liveness, { retry: { enabled: true } });
490
+ if (!result.ok) {
491
+ (0, LogService_1.logError)("Liveness check failed for", conf.name);
492
+ this.telegram(conf.name, "error-liveness", user.login);
493
+ if (conf.email && conf.email.length > 0) {
494
+ for (let email of conf.email) {
495
+ this.notifier?.notifyEmailStatus(email, "error-liveness", conf.name, user.login);
496
+ }
497
+ }
498
+ }
499
+ }, 5000);
500
+ }
501
+ if (baselineStaged) {
502
+ this.reviews.commitBaseline(realName);
503
+ baselineStaged = false;
504
+ }
505
+ return { data: {
506
+ ok: true,
507
+ project: realName,
508
+ bluegreen: !!projectState,
509
+ slot: projectState?.lastDeployed ?? null,
510
+ active: projectState?.active ?? null,
511
+ activeThisDeploy: projectState
512
+ ? projectState.active === projectState.lastDeployed
513
+ : true,
514
+ } };
515
+ }
516
+ finally {
517
+ if (baselineStaged)
518
+ this.reviews.dropStagedBaseline(realName);
519
+ this.busy.set(realName, false);
520
+ }
521
+ }
522
+ _reviewSetup(found) {
523
+ const review = found.review;
524
+ const logins = Array.from(new Set((review?.reviewers ?? []).map(l => String(l).trim()).filter(Boolean)));
525
+ if (logins.length === 0)
526
+ return { error: "review.reviewers is empty" };
527
+ const url = String(this.setup?.review_url ?? "");
528
+ if (!/^https?:\/\/[^\s#]+$/.test(url))
529
+ return { error: "review_url is not set in setup.json" };
530
+ if (!this.notifier)
531
+ return { error: "the notifier is not configured in setup.json — reviewers can't be emailed" };
532
+ const known = new Map((this.setup?.reviewers ?? []).map(r => [r.login, r]));
533
+ const reviewers = [];
534
+ for (const login of logins) {
535
+ const r = known.get(login);
536
+ if (!r)
537
+ return { error: `reviewer "${login}" is not defined in setup.json` };
538
+ if (!PasswordHash_1.PasswordHash.isHash(r.password))
539
+ return { error: `reviewer "${login}" has no password hash in setup.json` };
540
+ if (!/^[^\s@]+@[^\s@]+$/.test(String(r.email ?? "")))
541
+ return { error: `reviewer "${login}" has no valid email` };
542
+ reviewers.push({ login, email: r.email });
543
+ }
544
+ const hours = Math.min(Math.max(Number(review?.ttlHours) || 24, 1), 168);
545
+ return { reviewers, mode: review?.mode === "all" ? "all" : "any", ttlMs: hours * 3600_000 };
546
+ }
547
+ async _queueForReview(found, user, file, ip) {
548
+ const realName = found.name;
549
+ if (!file)
550
+ return { error: { code: 14, message: "No archive uploaded.", httpStatus: 400 } };
551
+ const setup = this._reviewSetup(found);
552
+ if (setup.error) {
553
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued — review is misconfigured: ${setup.error}`);
554
+ return { error: { code: 61, message: "Review is misconfigured on the deployer.", details: setup.error, httpStatus: 500 } };
555
+ }
556
+ this.busy.set(realName, true);
557
+ try {
558
+ const { pending, tokens, replaced } = await this.reviews.create(realName, file, {
559
+ uploadedBy: user.login, uploadedFrom: ip ?? null, mode: setup.mode,
560
+ reviewers: setup.reviewers.map(r => r.login), ttlMs: setup.ttlMs,
561
+ });
562
+ const unsafe = DeployerService._unsafeArchiveEntry(this.reviews.archivePath(realName));
563
+ if (unsafe) {
564
+ this.reviews.remove(realName);
565
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued — unsafe archive entry: ${unsafe}`);
566
+ return { error: { code: 18, message: "Unsafe archive.", details: unsafe, httpStatus: 400 } };
567
+ }
568
+ const failed = [];
569
+ for (const r of setup.reviewers) {
570
+ const link = `${this.setup.review_url}#${tokens[r.login]}`;
571
+ const ok = await this.notifier.notifyReview(r.email, { project: realName, user: user.login, link, expiresAt: pending.expiresAt, mode: pending.mode });
572
+ if (!ok)
573
+ failed.push(r.login);
574
+ }
575
+ if (failed.length === setup.reviewers.length || (pending.mode === "all" && failed.length > 0)) {
576
+ this.reviews.remove(realName);
577
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued — review mail failed for ${failed.join(", ")}`);
578
+ return { error: { code: 62, message: "Review emails could not be sent — the deploy was not queued.", details: `not delivered to: ${failed.join(", ")}`, httpStatus: 502 } };
579
+ }
580
+ this.reviews.journal(realName, "uploaded", { by: user.login, ip: ip ?? null, sha256: pending.sha256, size: pending.size,
581
+ mode: pending.mode, reviewers: Object.keys(pending.reviewers), notNotified: failed, replacedPrevious: replaced });
582
+ (0, LogService_1.logInfo)(`Deploy of "${realName}" by ${user.login} is waiting for review (${pending.mode}: ${Object.keys(pending.reviewers).join(", ")})${replaced ? " — replaced the previous pending upload" : ""}`);
583
+ this.telegram(realName, `waiting for review (${Object.keys(pending.reviewers).join(", ")})`, user.login);
584
+ return { data: {
585
+ ok: true,
586
+ project: realName,
587
+ pendingReview: true,
588
+ mode: pending.mode,
589
+ reviewers: Object.keys(pending.reviewers),
590
+ notNotified: failed,
591
+ expiresAt: pending.expiresAt,
592
+ replacedPrevious: replaced,
593
+ } };
594
+ }
595
+ catch (e) {
596
+ this.reviews.remove(realName);
597
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued: ${e?.message ?? e}`);
598
+ return { error: { code: 63, message: "Can't store the archive for review.", details: String(e?.message ?? e), httpStatus: 500 } };
599
+ }
600
+ finally {
601
+ this.busy.set(realName, false);
602
+ }
603
+ }
604
+ async reviewDecide(project, sha256, reviewer, decision, ip) {
605
+ if (this.busy.get(project))
606
+ return { error: "A deploy of this project is running — try again in a moment." };
607
+ const pending = this.reviews.get(project);
608
+ if (!pending || pending.sha256 !== sha256)
609
+ return { error: "This upload was replaced or removed." };
610
+ if (pending.state !== "pending")
611
+ return { error: `This upload is already ${pending.state}.` };
612
+ if (pending.expiresAt < Date.now())
613
+ return { error: "The review time is over — upload again." };
614
+ const mine = pending.reviewers[reviewer];
615
+ if (!mine)
616
+ return { error: "You are not a reviewer of this upload." };
617
+ if (mine.decision)
618
+ return { error: `You already chose "${mine.decision}".` };
619
+ mine.decision = decision;
620
+ mine.at = Date.now();
621
+ mine.ip = ip;
622
+ this.reviews.journal(project, decision, { reviewer, ip, sha256 });
623
+ const emails = (await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request()).get(project)?.email ?? [];
624
+ if (decision === "decline") {
625
+ pending.state = "declined";
626
+ pending.result = { at: Date.now(), message: `Declined by ${reviewer}.` };
627
+ this.reviews.save(pending);
628
+ this.reviews.dropArchive(project);
629
+ (0, LogService_1.logWarn)(`Review of "${project}": declined by ${reviewer} from ${ip ?? "unknown"} — archive removed`);
630
+ for (const e of emails)
631
+ this.notifier?.notifyEmailStatus(e, `declined by ${reviewer}`, project, pending.uploadedBy);
632
+ this.telegram(project, `review declined by ${reviewer}`, pending.uploadedBy);
633
+ return { pending };
634
+ }
635
+ const accepted = Object.entries(pending.reviewers).filter(([, r]) => r.decision === "accept").map(([l]) => l);
636
+ const ready = pending.mode === "any" || accepted.length === Object.keys(pending.reviewers).length;
637
+ (0, LogService_1.logInfo)(`Review of "${project}": accepted by ${reviewer} from ${ip ?? "unknown"}${ready ? " — deploying" : ` (${accepted.length}/${Object.keys(pending.reviewers).length})`}`);
638
+ this.telegram(project, `review accepted by ${reviewer}${ready ? " — deploying" : ` (${accepted.length}/${Object.keys(pending.reviewers).length})`}`, pending.uploadedBy);
639
+ if (!ready) {
640
+ this.reviews.save(pending);
641
+ return { pending };
642
+ }
643
+ pending.state = "deploying";
644
+ this.reviews.save(pending);
645
+ this._deployApproved(project, accepted).catch(e => (0, LogService_1.logError)(`Approved deploy of "${project}" crashed: ${e?.message ?? e}`));
646
+ return { pending };
647
+ }
648
+ async _deployApproved(project, approvers) {
649
+ const finish = (state, result) => {
650
+ const p = this.reviews.get(project);
651
+ if (!p)
652
+ return;
653
+ p.state = state;
654
+ p.result = { at: Date.now(), ...result };
655
+ this.reviews.save(p);
656
+ this.reviews.dropArchive(project);
657
+ this.reviews.journal(project, state, { sha256: p.sha256, approvedBy: approvers, message: result.message });
658
+ };
659
+ const pending = this.reviews.get(project);
660
+ if (!pending)
661
+ return;
662
+ if (!(await this.reviews.archiveIntact(pending))) {
663
+ (0, LogService_1.logError)(`Approved deploy of "${project}" stopped: the stored archive no longer matches its hash`);
664
+ return finish("failed", { message: "The stored archive changed after the review — nothing was deployed." });
665
+ }
666
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
667
+ const found = configurations.get(project);
668
+ if (!found || !found.review) {
669
+ (0, LogService_1.logError)(`Approved deploy of "${project}" stopped: the project or its review setting is gone`);
670
+ return finish("failed", { message: "The project or its review setting was removed — nothing was deployed." });
671
+ }
672
+ const actor = { login: `${pending.uploadedBy} (approved by ${approvers.join(", ")})`, password: "" };
673
+ try {
674
+ const res = await this._deploy(found, actor, configurations, project, { archivePath: this.reviews.archivePath(project) });
675
+ if (res?.error) {
676
+ finish("failed", { message: res.error.message + (res.error.details ? ` (${res.error.details})` : "") });
677
+ return;
678
+ }
679
+ finish("deployed", {
680
+ message: res?.data?.bluegreen && !res.data.activeThisDeploy
681
+ ? `Deployed to slot ${res.data.slot} — not live yet: run "bmfk activate" to switch traffic.`
682
+ : "Deployed and live.",
683
+ slot: res?.data?.slot ?? null, activeThisDeploy: res?.data?.activeThisDeploy,
684
+ });
685
+ }
686
+ catch (e) {
687
+ const msg = e?.message ? e.message + (e.details ? ` (${typeof e.details === "string" ? e.details : JSON.stringify(e.details)})` : "") : String(e);
688
+ (0, LogService_1.logError)(`Approved deploy of "${project}" failed: ${msg}`);
689
+ finish("failed", { message: LogService_1.LogService.sanitize(msg) });
690
+ }
691
+ }
692
+ _copyArchive(from, to) {
693
+ try {
694
+ fs_1.default.copyFileSync(from, to);
695
+ return null;
696
+ }
697
+ catch (e) {
698
+ return { code: 13, message: "Can't copy archive", httpStatus: 500, details: String(e?.message ?? e) };
699
+ }
700
+ }
701
+ async switchSlot(data) {
702
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
703
+ const user = auth.user;
704
+ if (!user) {
705
+ (0, LogService_1.logError)("Switch rejected: user auth failed");
706
+ return { error: { code: 40, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
707
+ }
708
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
709
+ const project = await this._projectByToken(configurations, data.name, data.token);
710
+ if (project.error)
711
+ return { error: { code: 41, message: project.error, httpStatus: 400 } };
712
+ let found = project.config;
713
+ if (!found) {
714
+ (0, LogService_1.logError)("Switch rejected: wrong token and/or name");
715
+ return { error: { code: 41, message: "Wrong token and/or name.", httpStatus: 400 } };
716
+ }
717
+ if (!found.bluegreen || !found.bluegreen.blue_config || !found.bluegreen.green_config) {
718
+ return { error: { code: 42, message: "Project has no blue-green configuration.", httpStatus: 400 } };
719
+ }
720
+ if (this.busy.get(found.name)) {
721
+ return { error: { code: 43, message: "Deployment in progress, try again shortly.", httpStatus: 409 } };
722
+ }
723
+ const realName = found.name;
724
+ this.busy.set(realName, true);
725
+ try {
726
+ const projectStatePath = path_1.default.resolve(this.options.projects_path, data.name + "_state_.json");
727
+ if (!fs_1.default.existsSync(projectStatePath)) {
728
+ return { error: { code: 44, message: "Project has never been deployed.", httpStatus: 400 } };
729
+ }
730
+ let projectState;
731
+ try {
732
+ projectState = JSON.parse(fs_1.default.readFileSync(projectStatePath, "utf-8"));
733
+ }
734
+ catch (e) {
735
+ return { error: { code: 45, message: "Corrupt state file: " + e.message, httpStatus: 500 } };
736
+ }
737
+ const target = data.scheme ?? projectState.lastDeployed;
738
+ if (target !== "blue" && target !== "green") {
739
+ return { error: { code: 46, message: "Invalid target slot.", httpStatus: 400 } };
740
+ }
741
+ if (target === projectState.active) {
742
+ return { error: { code: 47, message: `Slot '${target}' is already active.`, httpStatus: 400 } };
743
+ }
744
+ const previousActive = projectState.active;
745
+ const action = target === projectState.lastDeployed ? "switch" : "rollback";
746
+ projectState.active = target;
747
+ projectState.history.push({
748
+ slot: target,
749
+ action,
750
+ user: user.login,
751
+ at: Date.now(),
752
+ });
753
+ DeployerService._trimHistory(projectState);
754
+ const tmp = projectStatePath + ".tmp";
755
+ fs_1.default.writeFileSync(tmp, JSON.stringify(projectState, null, 4), "utf-8");
756
+ fs_1.default.renameSync(tmp, projectStatePath);
757
+ let hookError = null;
758
+ if (found.nginx?.config_dir) {
759
+ const slotCfg = target === "blue" ? found.bluegreen.blue_config : found.bluegreen.green_config;
760
+ const merged = { ...(found.config ?? {}), ...(slotCfg ?? {}) };
761
+ const nginxErr = await this._renderNginx(found, data.name, DeployerService._extractPort(merged));
762
+ if (nginxErr) {
763
+ (0, LogService_1.logError)("nginx render during switch failed (state already flipped): " + nginxErr.message);
764
+ hookError = nginxErr.message;
765
+ }
766
+ }
767
+ if (!hookError) {
768
+ hookError = await NginxHelper_1.NginxHelper.runHook(found.bluegreen.on_switch);
769
+ }
770
+ const status = hookError ? "switch-hook-failed" : action === "rollback" ? `rolled-back-to-${target}` : `switched-to-${target}`;
771
+ this.telegram(found.name, status, user.login);
772
+ if (found.email && found.email.length > 0) {
773
+ for (const email of found.email) {
774
+ this.notifier?.notifyEmailStatus(email, status, found.name, user.login);
775
+ }
776
+ }
777
+ if (found.phone && found.phone.length > 0) {
778
+ for (const p of found.phone) {
779
+ this.notifier?.notifySMSStatus(p, `${found.name} ${action} to ${target}`, user.login);
780
+ }
781
+ }
782
+ return { data: { active: projectState.active, previousActive, action, hookError } };
783
+ }
784
+ finally {
785
+ this.busy.set(realName, false);
786
+ }
787
+ }
788
+ async status(data) {
789
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
790
+ const user = auth.user;
791
+ if (!user) {
792
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
793
+ }
794
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
795
+ const results = {};
796
+ for (const cfg of configurations.values()) {
797
+ if (data.name && cfg.name !== data.name)
798
+ continue;
799
+ const statePath = path_1.default.resolve(this.options.projects_path, cfg.name + "_state_.json");
800
+ let state = null;
801
+ if (fs_1.default.existsSync(statePath)) {
802
+ try {
803
+ state = JSON.parse(fs_1.default.readFileSync(statePath, "utf-8"));
804
+ }
805
+ catch { }
806
+ }
807
+ results[cfg.name] = {
808
+ hasBlueGreen: !!(cfg.bluegreen && cfg.bluegreen.blue_config && cfg.bluegreen.green_config),
809
+ state,
810
+ readyToSwitch: !!(state && state.lastDeployed !== state.active),
811
+ };
812
+ }
813
+ return { data: results };
814
+ }
815
+ static _isBlueGreen(found) {
816
+ return !!(found.bluegreen && found.bluegreen.blue_config && found.bluegreen.green_config);
817
+ }
818
+ static _backupRoot(found) {
819
+ const dest = path_1.default.resolve(found.destination);
820
+ return DeployerService._isBlueGreen(found) ? dest : path_1.default.dirname(dest);
821
+ }
822
+ async listBackups(data) {
823
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
824
+ const user = auth.user;
825
+ if (!user) {
826
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
827
+ }
828
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
829
+ const found = Array.from(configurations.values()).find(c => c.name === data.name);
830
+ if (!found)
831
+ return { error: { code: 58, message: "Project not found.", httpStatus: 404 } };
832
+ const backups = await BackupManager_1.BackupManager.list(DeployerService._backupRoot(found), found.name, true);
833
+ const isBG = DeployerService._isBlueGreen(found);
834
+ let activeSlot = null;
835
+ if (isBG) {
836
+ try {
837
+ const statePath = path_1.default.resolve(this.options.projects_path, found.name + "_state_.json");
838
+ activeSlot = JSON.parse(fs_1.default.readFileSync(statePath, "utf-8"))?.active ?? null;
839
+ }
840
+ catch {
841
+ activeSlot = null;
842
+ }
843
+ }
844
+ return { data: {
845
+ project: found.name,
846
+ bluegreen: isBG,
847
+ activeSlot,
848
+ backupEnabled: !!found.backup,
849
+ keep: BackupManager_1.MAX_BACKUPS,
850
+ backups,
851
+ } };
852
+ }
853
+ async restoreBackup(data) {
854
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
855
+ const user = auth.user;
856
+ if (!user) {
857
+ (0, LogService_1.logError)("Restore rejected: user auth failed");
858
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
859
+ }
860
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
861
+ const project = await this._projectByToken(configurations, data.name, data.token);
862
+ if (project.error)
863
+ return { error: { code: 41, message: project.error, httpStatus: 400 } };
864
+ let found = project.config;
865
+ if (!found) {
866
+ (0, LogService_1.logError)("Restore rejected: wrong token and/or name");
867
+ return { error: { code: 41, message: "Wrong token and/or name.", httpStatus: 400 } };
868
+ }
869
+ if (this.busy.get(found.name))
870
+ return { error: { code: 43, message: "Deployment in progress, try again shortly.", httpStatus: 409 } };
871
+ const realName = found.name;
872
+ this.busy.set(realName, true);
873
+ try {
874
+ const root = DeployerService._backupRoot(found);
875
+ const backup = BackupManager_1.BackupManager.resolve(root, realName, data.backup);
876
+ if (!backup)
877
+ return { error: { code: 55, message: "Backup not found.", details: data.backup, httpStatus: 404 } };
878
+ const isBG = DeployerService._isBlueGreen(found);
879
+ const slot = backup.meta.slot;
880
+ if (isBG !== !!slot)
881
+ return { error: { code: 57, message: isBG
882
+ ? "Backup has no slot, but the project is blue-green now."
883
+ : "Backup belongs to a blue-green slot, but the project is not blue-green now.", httpStatus: 400 } };
884
+ const target = isBG ? path_1.default.join(path_1.default.resolve(found.destination), slot) : path_1.default.resolve(found.destination);
885
+ const targetProblem = this._destinationProblem(target, true, Array.from(configurations.values()), isBG ? path_1.default.resolve(found.destination) : target);
886
+ if (targetProblem)
887
+ return { error: { code: 19, message: "Unsafe destination.", details: targetProblem, httpStatus: 400 } };
888
+ let state = null;
889
+ const statePath = path_1.default.resolve(this.options.projects_path, realName + "_state_.json");
890
+ if (isBG && fs_1.default.existsSync(statePath)) {
891
+ try {
892
+ state = JSON.parse(fs_1.default.readFileSync(statePath, "utf-8"));
893
+ }
894
+ catch {
895
+ state = null;
896
+ }
897
+ }
898
+ const preRestore = await BackupManager_1.BackupManager.create(target, realName, slot, user.login, "pre-restore");
899
+ await BackupManager_1.BackupManager.restoreInto(backup.dir, target);
900
+ if (isBG && state)
901
+ this._writeBlueGreenFiles(realName, state, path_1.default.resolve(found.destination));
902
+ let pm2Error = null;
903
+ if (found.pm2) {
904
+ const pm2Found = { ...structuredClone(found), name: isBG ? `${realName}-${slot}` : realName, destination: target };
905
+ pm2Error = await this.runPM2(pm2Found, state ? { ...state, lastDeployed: slot } : null);
906
+ if (pm2Error)
907
+ (0, LogService_1.logError)(`Restore: pm2 restart failed for ${pm2Found.name}: ${pm2Error.details ?? pm2Error.message}`);
908
+ }
909
+ if (isBG && state) {
910
+ state.history.push({ slot: slot, action: "restore", user: user.login, at: Date.now() });
911
+ DeployerService._trimHistory(state);
912
+ const tmp = statePath + ".tmp";
913
+ fs_1.default.writeFileSync(tmp, JSON.stringify(state, null, 4), "utf-8");
914
+ fs_1.default.renameSync(tmp, statePath);
915
+ }
916
+ await BackupManager_1.BackupManager.prune(root, realName, BackupManager_1.MAX_BACKUPS, [data.backup]);
917
+ (0, LogService_1.logInfo)(`Restored ${realName}${slot ? "/" + slot : ""} from ${data.backup} by ${user.login}`);
918
+ this.telegram(found.name, pm2Error ? "error-restore-pm2" : `restored from ${data.backup}`, user.login);
919
+ if (found.email && found.email.length > 0) {
920
+ for (let email of found.email)
921
+ this.notifier?.notifyEmailStatus(email, pm2Error ? "error-restore-pm2" : "restored", found.name, user.login);
922
+ }
923
+ return { data: {
924
+ project: realName,
925
+ restored: data.backup,
926
+ appVersion: backup.meta.appVersion,
927
+ slot,
928
+ activeSlot: state?.active ?? null,
929
+ live: !isBG || slot === state?.active,
930
+ preRestoreBackup: preRestore,
931
+ pm2Restarted: !!found.pm2 && !pm2Error,
932
+ pm2Error: pm2Error ? (pm2Error.details ?? pm2Error.message) : null,
933
+ } };
934
+ }
935
+ catch (e) {
936
+ (0, LogService_1.logError)("Restore failed: " + (e?.message ?? e));
937
+ return { error: { code: 56, message: "Restore failed.", details: String(e?.message ?? e), httpStatus: 500 } };
938
+ }
939
+ finally {
940
+ this.busy.set(realName, false);
941
+ }
942
+ }
943
+ async slotState(data) {
944
+ const deny = { error: { code: 53, message: "Invalid project or status token.", httpStatus: 401 } };
945
+ if (!data || typeof data.name !== "string" || typeof data.token !== "string" || !/^[A-Za-z0-9._-]+$/.test(data.name))
946
+ return deny;
947
+ let state = null;
948
+ try {
949
+ const statePath = path_1.default.resolve(this.options.projects_path, data.name + "_state_.json");
950
+ if (fs_1.default.existsSync(statePath))
951
+ state = JSON.parse(fs_1.default.readFileSync(statePath, "utf-8"));
952
+ }
953
+ catch {
954
+ state = null;
955
+ }
956
+ const tokenOk = this.tokensMatch(data.token, state?.statusToken || crypto_1.default.randomBytes(32).toString("hex"));
957
+ if (!state || !state.statusToken || !tokenOk)
958
+ return deny;
959
+ const slot = data.slot === "blue" || data.slot === "green" ? data.slot : null;
960
+ return { data: {
961
+ project: data.name,
962
+ active: state.active ?? null,
963
+ lastDeployed: state.lastDeployed ?? null,
964
+ readyToSwitch: !!(state.lastDeployed && state.lastDeployed !== state.active),
965
+ slot,
966
+ isActive: slot ? slot === state.active : null,
967
+ checkedAt: Date.now(),
968
+ } };
969
+ }
970
+ _statusUrl() {
971
+ const override = this.setup?.status_url;
972
+ if (typeof override === "string" && override.length > 0)
973
+ return override;
974
+ let base = this.options.selfBaseEndPoint ?? "/api/";
975
+ if (!base.startsWith("/"))
976
+ base = "/" + base;
977
+ if (!base.endsWith("/"))
978
+ base += "/";
979
+ return `http://127.0.0.1:${this.options.selfPort ?? 8080}${base}pckg/slot`;
980
+ }
981
+ _writeBlueGreenFiles(project, state, projectRoot) {
982
+ if (!state.statusToken)
983
+ return;
984
+ const statusUrl = this._statusUrl();
985
+ for (const slot of ["blue", "green"]) {
986
+ const dir = path_1.default.resolve(projectRoot, slot);
987
+ if (!fs_1.default.existsSync(dir))
988
+ continue;
989
+ const file = path_1.default.resolve(dir, BlueGreenState_1.BLUEGREEN_FILE);
990
+ const payload = { version: 1, project, slot, statusUrl, token: state.statusToken, writtenAt: Date.now() };
991
+ try {
992
+ const tmp = file + ".tmp";
993
+ fs_1.default.writeFileSync(tmp, JSON.stringify(payload, null, 2), { encoding: "utf-8", mode: 0o600 });
994
+ fs_1.default.renameSync(tmp, file);
995
+ }
996
+ catch (e) {
997
+ (0, LogService_1.logWarn)(`Cannot write ${BlueGreenState_1.BLUEGREEN_FILE} for ${project}/${slot}: ${e?.message ?? e}`);
998
+ }
999
+ }
1000
+ }
1001
+ async _projectByToken(configurations, name, token) {
1002
+ const config = Array.from(configurations.values()).find(c => c.name === name);
1003
+ if (!config || typeof token !== "string" || !token)
1004
+ return {};
1005
+ if (PasswordHash_1.PasswordHash.isHash(config.token))
1006
+ return (await PasswordHash_1.PasswordHash.verify(token, config.token)) ? { config } : {};
1007
+ if (config.token && this.tokensMatch(config.token, token))
1008
+ (0, LogService_1.logError)(`Deployer: project "${name}" refused — the right token was sent, but the project config stores it as plain text; store a hash: npx bmfk project-token --hash`);
1009
+ return {};
1010
+ }
1011
+ tokensMatch(a, b) {
1012
+ const ha = new Uint8Array(crypto_1.default.createHash("sha256").update(String(a ?? "")).digest());
1013
+ const hb = new Uint8Array(crypto_1.default.createHash("sha256").update(String(b ?? "")).digest());
1014
+ return crypto_1.default.timingSafeEqual(ha, hb);
1015
+ }
1016
+ static buildAllowList(entries) {
1017
+ return IpAllowList_1.IpAllowList.build(entries);
1018
+ }
1019
+ isIpAllowed(ip) {
1020
+ return this._ipAllowed(ip);
1021
+ }
1022
+ _ipAllowed(ip) {
1023
+ return IpAllowList_1.IpAllowList.allows(IpAllowList_1.IpAllowList.build(this.setup?.allowed_ips).list, ip);
1024
+ }
1025
+ _warnPlaintextUsers() {
1026
+ if (!DeployerService.buildAllowList(this.setup?.allowed_ips).list)
1027
+ (0, LogService_1.logWarn)("Deployer: allowed_ips is not set in setup.json — deploys are accepted from any address");
1028
+ const users = this.setup?.users ?? [];
1029
+ const plain = users.filter(u => u?.login && !u.publicKey && u.password && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
1030
+ const keyless = users.filter(u => u?.login && !u.publicKey && !u.password).map(u => u.login);
1031
+ if (keyless.length)
1032
+ (0, LogService_1.logError)(`Deployer: ${keyless.map(l => '"' + l + '"').join(", ")} in setup.json have neither a password nor a publicKey — they can't sign in`);
1033
+ const passwordUsers = users.filter(u => u?.login && !u.publicKey && u.password).map(u => u.login);
1034
+ if (this.setup?.require_signature !== false && passwordUsers.length)
1035
+ (0, LogService_1.logWarn)(`Deployer: only signed requests are accepted — password users ${passwordUsers.map(l => '"' + l + '"').join(", ")} can't sign in until they get a publicKey (npx bmfk deploy-key), or set "require_signature": false`);
1036
+ else if (this.setup?.require_signature === false && passwordUsers.length)
1037
+ (0, LogService_1.logWarn)(`Deployer: "require_signature": false — ${passwordUsers.length} user(s) sign in with a password; give them a publicKey (npx bmfk deploy-key) and remove the setting`);
1038
+ if (plain.length)
1039
+ (0, LogService_1.logError)(`Deployer: password stored as plain text in setup.json for ${plain.map(l => '"' + l + '"').join(", ")} — these users are refused; store a hash instead: npx bmfk hash-password --deployer`);
1040
+ }
1041
+ async _checkUserAuth(authHeader, loginHeader, ip, sig) {
1042
+ if (!this._ipAllowed(ip)) {
1043
+ (0, LogService_1.logWarn)(`Deployer: request refused from ${ip ?? "unknown"} — not in allowed_ips`);
1044
+ return { error: "Forbidden.", status: 403 };
1045
+ }
1046
+ const from = ip ?? "unknown";
1047
+ const shown = (v) => JSON.stringify(v.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 64));
1048
+ const refuse = (reason) => { (0, LogService_1.logWarn)(`Deployer auth failed from ${from}: ${reason}`); return {}; };
1049
+ if (!this.setup)
1050
+ return refuse("setup.json is not loaded");
1051
+ if (sig?.present) {
1052
+ if (sig.error || !sig.kid)
1053
+ return refuse(`signature refused — ${sig.error ?? "no key id"}`);
1054
+ const user = (this.setup.users ?? []).find(u => u.login === sig.kid);
1055
+ if (!user?.publicKey)
1056
+ return refuse(`signature by ${shown(sig.kid)}, who has no publicKey in setup.json`);
1057
+ return { user: user };
1058
+ }
1059
+ if (this.setup.require_signature !== false)
1060
+ return refuse("unsigned request — only signed requests are accepted; the client needs a privateKey in deploy.json (npx bmfk deploy-key)");
1061
+ if (!authHeader)
1062
+ return refuse("no Authorization header");
1063
+ const token = authHeader.split(" ").pop() ?? "";
1064
+ if (!token)
1065
+ return refuse("empty Authorization header");
1066
+ const users = this.setup.users ?? [];
1067
+ if (users.length === 0)
1068
+ return refuse("no users in setup.json");
1069
+ const login = typeof loginHeader === "string" ? loginHeader.trim() : "";
1070
+ if (login) {
1071
+ const user = users.find(u => u.login === login);
1072
+ if (!user)
1073
+ return refuse(`unknown login ${shown(login)}`);
1074
+ if (user.publicKey)
1075
+ return refuse(`${shown(login)} has a publicKey — only signed requests are accepted for them; the client needs its privateKey in deploy.json`);
1076
+ if (!user.password)
1077
+ return refuse(`${shown(login)} has neither a password nor a publicKey in setup.json`);
1078
+ if (PasswordHash_1.PasswordHash.isHash(user.password))
1079
+ return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user: user } : refuse(`wrong password for ${shown(login)} (or the client's login/password differ from setup.json)`);
1080
+ }
1081
+ let plainMatch = null;
1082
+ for (const user of users) {
1083
+ if (user.publicKey || !user.password || PasswordHash_1.PasswordHash.isHash(user.password))
1084
+ continue;
1085
+ const expected = crypto_1.default.createHash("sha256").update(user.login + ":" + user.password).digest("hex");
1086
+ if (this.tokensMatch(token, expected))
1087
+ plainMatch = user.login;
1088
+ }
1089
+ if (plainMatch) {
1090
+ (0, LogService_1.logError)(`Deployer: "${plainMatch}" sent the right credentials, but setup.json stores the password as plain text — refused; store a hash: npx bmfk hash-password --deployer`);
1091
+ return {};
1092
+ }
1093
+ if (!login)
1094
+ return refuse("no X-Deployer-Login header — the client runs an old CLI; update it");
1095
+ return refuse(`wrong password for ${shown(login)}`);
1096
+ }
1097
+ static _extractPort(config) {
1098
+ if (!config || typeof config !== "object")
1099
+ return "";
1100
+ for (const key of Object.keys(config)) {
1101
+ if (key.toLowerCase() === "port") {
1102
+ const v = config[key];
1103
+ if (v !== null && v !== undefined && String(v).length > 0)
1104
+ return String(v);
1105
+ }
1106
+ }
1107
+ return "";
1108
+ }
1109
+ static _mainPath(destination) {
1110
+ let main;
1111
+ try {
1112
+ main = JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(destination, "package.json"), "utf-8")).main || "index.js";
1113
+ }
1114
+ catch {
1115
+ return null;
1116
+ }
1117
+ if (main.startsWith("./"))
1118
+ main = main.substring(2);
1119
+ return destination.endsWith("/") ? destination + main : destination + "/" + main;
1120
+ }
1121
+ static _withSourceMaps(extra) {
1122
+ const FLAG = "--enable-source-maps";
1123
+ const has = (v) => v.split(/\s+/).includes(FLAG);
1124
+ const inlineIdx = extra.findIndex(a => a.startsWith("--node-args="));
1125
+ if (inlineIdx !== -1) {
1126
+ const val = extra[inlineIdx].slice("--node-args=".length);
1127
+ if (has(val))
1128
+ return extra;
1129
+ const next = [...extra];
1130
+ next[inlineIdx] = `--node-args=${(val + " " + FLAG).trim()}`;
1131
+ return next;
1132
+ }
1133
+ const splitIdx = extra.findIndex(a => a === "--node-args");
1134
+ if (splitIdx !== -1 && splitIdx + 1 < extra.length) {
1135
+ const val = extra[splitIdx + 1];
1136
+ if (has(val))
1137
+ return extra;
1138
+ const next = [...extra];
1139
+ next[splitIdx + 1] = (val + " " + FLAG).trim();
1140
+ return next;
1141
+ }
1142
+ return [...extra, `--node-args=${FLAG}`];
1143
+ }
1144
+ async _renderNginx(found, projectName, activePort) {
1145
+ if (!found.nginx?.config_dir)
1146
+ return null;
1147
+ if (!activePort) {
1148
+ return { code: 52, message: "Cannot render nginx: no port found in config for project " + projectName + " (expected a 'port' key in config or blue_config/green_config)", httpStatus: 500 };
1149
+ }
1150
+ const dir = found.nginx.config_dir;
1151
+ try {
1152
+ fs_1.default.mkdirSync(dir, { recursive: true });
1153
+ }
1154
+ catch (e) {
1155
+ return { code: 50, message: "Cannot create nginx config_dir: " + String(e?.message ?? e), httpStatus: 500 };
1156
+ }
1157
+ const safeName = projectName.replace(/[^a-zA-Z0-9_]/g, "_");
1158
+ const upstreamName = found.nginx.upstream_name || (safeName + "_backend");
1159
+ const upstreamPath = path_1.default.resolve(dir, projectName + ".upstream.conf");
1160
+ const serverPath = path_1.default.resolve(dir, projectName + ".server.conf");
1161
+ const domain = found.nginx.domain || projectName;
1162
+ if (!found.nginx.domain) {
1163
+ (0, LogService_1.logWarn)("nginx.domain not set for project " + projectName +
1164
+ " — seeding server.conf with server_name=" + projectName + " (edit or delete .server.conf to fix)");
1165
+ }
1166
+ const seedResult = NginxHelper_1.NginxHelper.seedServerConfig(serverPath, NginxHelper_1.DEFAULT_SERVER_TEMPLATE, {
1167
+ DOMAIN: domain,
1168
+ UPSTREAM: upstreamName,
1169
+ });
1170
+ if (seedResult.error)
1171
+ return seedResult.error;
1172
+ if (seedResult.seeded) {
1173
+ (0, LogService_1.logWarn)("Seeded nginx server config for " + projectName + " at " + serverPath +
1174
+ " — run `certbot --nginx -d " + domain + "` to add SSL");
1175
+ }
1176
+ const upstreamErr = NginxHelper_1.NginxHelper.writeUpstream(upstreamPath, upstreamName, activePort);
1177
+ if (upstreamErr)
1178
+ return upstreamErr;
1179
+ return null;
1180
+ }
1181
+ static _pm2AttributesFor(found, projectState) {
1182
+ const slotAttrs = projectState?.lastDeployed === "blue" ? found.bluegreen?.blue_pm2_attributes : found.bluegreen?.green_pm2_attributes;
1183
+ const list = Array.isArray(slotAttrs) ? slotAttrs : found.pm2_attributes;
1184
+ return Array.isArray(list) ? list.filter((s) => typeof s === "string" && s.length > 0) : [];
1185
+ }
1186
+ async runPM2(found, projectState) {
1187
+ let pm2attrs = projectState?.lastDeployed === "blue" ? found.bluegreen?.blue_pm2_attributes : found.bluegreen?.green_pm2_attributes;
1188
+ const pm2Attrs = Array.isArray(pm2attrs) ? pm2attrs.filter(s => typeof s === "string" && s.length > 0) : found.pm2_attributes;
1189
+ return new Promise((resolve) => {
1190
+ try {
1191
+ (0, child_process_1.execFileSync)("pm2", ["--version"]);
1192
+ const rawExtra = Array.isArray(pm2Attrs)
1193
+ ? pm2Attrs.filter(s => typeof s === "string" && s.length > 0)
1194
+ : [];
1195
+ const extra = rawExtra.filter(a => !/^--no-autorestart(=.*)?$/.test(a));
1196
+ if (extra.length !== rawExtra.length)
1197
+ (0, LogService_1.logWarn)(`Ignored "--no-autorestart" in pm2 attributes for "${found.name}" — autorestart is force-kept ON so the slot self-recovers.`);
1198
+ const entryMain = DeployerService._mainPath(found.destination);
1199
+ const hasMap = !!entryMain && fs_1.default.existsSync(entryMain + ".map");
1200
+ const ecoJs = path_1.default.resolve(found.destination, "ecosystem.config.js");
1201
+ const ecoCjs = path_1.default.resolve(found.destination, "ecosystem.config.cjs");
1202
+ const ecosystem = fs_1.default.existsSync(ecoJs) ? ecoJs
1203
+ : fs_1.default.existsSync(ecoCjs) ? ecoCjs
1204
+ : null;
1205
+ if (ecosystem) {
1206
+ if (hasMap)
1207
+ (0, LogService_1.logInfo)(`"${found.name}": a sourcemap ships next to the entry — add node_args:"--enable-source-maps" to ${path_1.default.basename(ecosystem)} for src-mapped stack traces`);
1208
+ (0, child_process_1.execFileSync)("pm2", ["startOrReload", ecosystem, "--update-env", ...extra]);
1209
+ this._verifyAutorestart(found.name);
1210
+ resolve(null);
1211
+ return;
1212
+ }
1213
+ const list = (0, child_process_1.execFileSync)("pm2", ["list"]).toString();
1214
+ let running = false;
1215
+ for (let l of list.split("\n")) {
1216
+ if (l.indexOf(found.name) !== -1) {
1217
+ running = true;
1218
+ break;
1219
+ }
1220
+ }
1221
+ const script = entryMain ?? found.destination + "/index.js";
1222
+ if (running) {
1223
+ try {
1224
+ (0, child_process_1.execFileSync)("pm2", ["delete", found.name]);
1225
+ }
1226
+ catch { }
1227
+ }
1228
+ const startExtra = hasMap ? DeployerService._withSourceMaps(extra) : extra;
1229
+ (0, child_process_1.execFileSync)("pm2", ["start", script, "--name", found.name, ...startExtra]);
1230
+ this._verifyAutorestart(found.name);
1231
+ resolve(null);
1232
+ }
1233
+ catch (e) {
1234
+ resolve({ code: 18, message: "Can't run pm2", details: "" + e, httpStatus: 500 });
1235
+ }
1236
+ });
1237
+ }
1238
+ _verifyAutorestart(name) {
1239
+ try {
1240
+ const list = JSON.parse((0, child_process_1.execFileSync)("pm2", ["jlist"]).toString());
1241
+ const proc = Array.isArray(list) ? list.find((p) => p?.name === name) : null;
1242
+ if (proc?.pm2_env && proc.pm2_env.autorestart === false) {
1243
+ (0, LogService_1.logWarn)(`pm2 autorestart is DISABLED for "${name}" — the slot will NOT respawn after a restart/exit. Check the project's ecosystem.config (autorestart:false).`);
1244
+ }
1245
+ }
1246
+ catch (e) {
1247
+ (0, LogService_1.logWarn)(`Could not verify pm2 autorestart for "${name}": ${e?.message ?? e}`);
1248
+ }
1249
+ }
1250
+ static SKIP_DIRS = new Set(["node_modules", ".git", "__tmp"]);
1251
+ static TEMPLATE_EXTENSIONS = [".js", ".ts", ".json", ".env"];
1252
+ async applyConfig(dir, config, ctx) {
1253
+ if (Object.keys(config).length < 1)
1254
+ return;
1255
+ const entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
1256
+ for (const entry of entries) {
1257
+ if (entry.isSymbolicLink())
1258
+ continue;
1259
+ if (entry.isDirectory()) {
1260
+ if (DeployerService.SKIP_DIRS.has(entry.name))
1261
+ continue;
1262
+ const fullPath = path_1.default.join(dir, entry.name);
1263
+ await this.applyConfig(fullPath, config, ctx);
1264
+ continue;
1265
+ }
1266
+ if (entry.isFile()) {
1267
+ const fullPath = path_1.default.join(dir, entry.name);
1268
+ const lower = fullPath.toLowerCase();
1269
+ if (DeployerService.TEMPLATE_EXTENSIONS.some(ext => lower.endsWith(ext)))
1270
+ await this.processFile(fullPath, config, ctx);
1271
+ }
1272
+ }
1273
+ }
1274
+ async processFile(filePath, config, ctx) {
1275
+ let content = fs_1.default.readFileSync(filePath, "utf-8");
1276
+ let hash = crypto_1.default.createHash("md5").update(content).digest("hex");
1277
+ const lowerPath = filePath.toLowerCase();
1278
+ if (ctx?.secretsFile && (lowerPath.endsWith(".js") || lowerPath.endsWith(".cjs")) && content.includes("_{{")) {
1279
+ const t = SecretsInjector_1.SecretsInjector.transform(content, new Set(Object.keys(config)), ctx.secretsFile);
1280
+ if (t.rewritten > 0) {
1281
+ const noShebang = (src) => src.replace(/^#!.*/, "");
1282
+ if (SecretsInjector_1.SecretsInjector.parses(noShebang(content)) && SecretsInjector_1.SecretsInjector.parses(noShebang(t.content)))
1283
+ content = t.content;
1284
+ else
1285
+ (0, LogService_1.logWarn)(`Secrets: ${filePath} can't be rewritten safely (it doesn't compile as CommonJS) — values are substituted as before`);
1286
+ }
1287
+ }
1288
+ let substituted = false;
1289
+ for (const [key, value] of Object.entries(config)) {
1290
+ const placeholder = `_{{${key}}}_`;
1291
+ if (content.includes(placeholder)) {
1292
+ substituted = true;
1293
+ content = content.replaceAll(placeholder, () => String(value));
1294
+ }
1295
+ }
1296
+ if (substituted && ctx?.secretsFile !== undefined && ctx.onDisk)
1297
+ ctx.onDisk.push(filePath);
1298
+ let hash2 = crypto_1.default.createHash("md5").update(content).digest("hex");
1299
+ if (hash !== hash2) {
1300
+ (0, LogService_1.logInfo)("Values was changed in " + filePath);
1301
+ fs_1.default.writeFileSync(filePath, content, "utf-8");
1302
+ }
1303
+ const leftover = content.match(/_\{\{[A-Za-z0-9_]+\}\}_/g);
1304
+ if (leftover && leftover.length > 0) {
1305
+ const unique = [...new Set(leftover)];
1306
+ (0, LogService_1.logWarn)("Unresolved template placeholders in " + filePath + ": " + unique.join(", "));
1307
+ }
1308
+ }
1309
+ _destinationProblem(dir, willClean, configs, ownDest) {
1310
+ if (typeof dir !== "string" || !path_1.default.isAbsolute(dir))
1311
+ return "destination must be an absolute path";
1312
+ const dest = path_1.default.resolve(dir);
1313
+ if (dest === path_1.default.parse(dest).root)
1314
+ return "destination is the filesystem root";
1315
+ if (dest.split(path_1.default.sep).filter(Boolean).length < 2)
1316
+ return `destination "${dest}" is a top-level system directory`;
1317
+ const covers = (outer, inner) => inner === outer || inner.startsWith(outer + path_1.default.sep);
1318
+ const configsDir = path_1.default.resolve(this.options.projects_path);
1319
+ if (covers(dest, configsDir))
1320
+ return `destination "${dest}" contains the deployer's config folder`;
1321
+ if (covers(dest, path_1.default.resolve(process.cwd())))
1322
+ return `destination "${dest}" contains the deployer itself`;
1323
+ if (willClean) {
1324
+ const own = path_1.default.resolve(ownDest);
1325
+ for (const c of configs) {
1326
+ if (!c?.destination)
1327
+ continue;
1328
+ const other = path_1.default.resolve(c.destination);
1329
+ if (other === own)
1330
+ continue;
1331
+ if (other !== dest && covers(dest, other))
1332
+ return `destination "${dest}" contains project "${c.name}" (${other}) and would be wiped`;
1333
+ }
1334
+ }
1335
+ return null;
1336
+ }
1337
+ static _unsafeArchiveEntry(archive) {
1338
+ let listing = "";
1339
+ try {
1340
+ listing = (0, child_process_1.execFileSync)("tar", ["-tzf", archive], { encoding: "utf-8", maxBuffer: 256 * 1024 * 1024 });
1341
+ }
1342
+ catch (e) {
1343
+ return "archive cannot be listed: " + (e?.message ?? e);
1344
+ }
1345
+ for (const raw of listing.split("\n")) {
1346
+ const name = raw.trim();
1347
+ if (!name)
1348
+ continue;
1349
+ if (name.startsWith("/") || /^[A-Za-z]:[\\/]/.test(name))
1350
+ return name;
1351
+ if (name.split(/[\\/]/).includes(".."))
1352
+ return name;
1353
+ }
1354
+ return null;
1355
+ }
1356
+ static _escapingSymlink(root) {
1357
+ const base = path_1.default.resolve(root);
1358
+ const stack = [base];
1359
+ while (stack.length) {
1360
+ const dir = stack.pop();
1361
+ let entries;
1362
+ try {
1363
+ entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
1364
+ }
1365
+ catch {
1366
+ continue;
1367
+ }
1368
+ for (const e of entries) {
1369
+ const p = path_1.default.join(dir, e.name);
1370
+ if (e.isSymbolicLink()) {
1371
+ const target = fs_1.default.readlinkSync(p);
1372
+ const resolved = path_1.default.resolve(dir, target);
1373
+ if (path_1.default.isAbsolute(target) || (resolved !== base && !resolved.startsWith(base + path_1.default.sep)))
1374
+ return `${path_1.default.relative(base, p)} -> ${target}`;
1375
+ }
1376
+ else if (e.isDirectory()) {
1377
+ stack.push(p);
1378
+ }
1379
+ }
1380
+ }
1381
+ return null;
1382
+ }
1383
+ async _runMigrate(dir) {
1384
+ const tail = (t) => {
1385
+ const s = LogService_1.LogService.sanitize(String(t ?? "").trim());
1386
+ return s.length > 4000 ? "…" + s.slice(-4000) : s;
1387
+ };
1388
+ let scripts = null;
1389
+ try {
1390
+ scripts = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, "package.json"), "utf-8"))?.scripts;
1391
+ }
1392
+ catch { }
1393
+ if (!scripts || typeof scripts.migrate !== "string")
1394
+ return { code: 60, message: '"migrate" is enabled, but package.json has no "migrate" script.', httpStatus: 500 };
1395
+ (0, LogService_1.logInfo)(`Running migrations: npm run migrate (${scripts.migrate})`);
1396
+ try {
1397
+ const { stdout, stderr } = await execFileAsync("npm", ["run", "migrate"], { cwd: dir, timeout: DeployerService.MIGRATE_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
1398
+ (0, LogService_1.logInfo)("Migrations finished:\n" + tail(String(stdout) + String(stderr)));
1399
+ return null;
1400
+ }
1401
+ catch (e) {
1402
+ const out = tail(String(e?.stdout ?? "") + String(e?.stderr ?? ""));
1403
+ const reason = e?.killed ? `timed out after ${DeployerService.MIGRATE_TIMEOUT_MS / 60000} min` : `exit code ${e?.code}`;
1404
+ (0, LogService_1.logError)(`Migrations failed (${reason}):\n${out}`);
1405
+ return { code: 60, message: `Migrations failed (${reason}), the process was not restarted.`, details: out, httpStatus: 500 };
1406
+ }
1407
+ }
1408
+ static MIGRATE_TIMEOUT_MS = 10 * 60 * 1000;
1409
+ static _stampProjectName(dir, projectName) {
1410
+ const problem = (0, ConfigService_1.projectNameProblem)(projectName);
1411
+ if (problem) {
1412
+ (0, LogService_1.logWarn)(`${problem} — package.json "name" left as it is`);
1413
+ return;
1414
+ }
1415
+ for (const file of ["package.json", "package-lock.json"]) {
1416
+ const p = path_1.default.resolve(dir, file);
1417
+ if (!fs_1.default.existsSync(p))
1418
+ continue;
1419
+ try {
1420
+ const text = fs_1.default.readFileSync(p, "utf-8");
1421
+ const doc = JSON.parse(text);
1422
+ let changed = false;
1423
+ if (doc.name !== projectName) {
1424
+ doc.name = projectName;
1425
+ changed = true;
1426
+ }
1427
+ if (file === "package-lock.json" && doc.packages?.[""] && doc.packages[""].name !== projectName) {
1428
+ doc.packages[""].name = projectName;
1429
+ changed = true;
1430
+ }
1431
+ if (!changed)
1432
+ continue;
1433
+ const indent = /^\{\n(\t| +)/.exec(text)?.[1] ?? "\t";
1434
+ fs_1.default.writeFileSync(p, JSON.stringify(doc, null, indent) + "\n");
1435
+ }
1436
+ catch (e) {
1437
+ (0, LogService_1.logWarn)(`Cannot set the project name in ${file}: ${e?.message ?? e}`);
1438
+ }
1439
+ }
1440
+ }
1441
+ async unpack(destination, uploadedFile, install, ignoreDirectoryClean, omitDev, projectName) {
1442
+ return new Promise((resolve) => {
1443
+ const unsafeEntry = DeployerService._unsafeArchiveEntry(uploadedFile);
1444
+ if (unsafeEntry) {
1445
+ (0, LogService_1.logError)("Refusing to unpack: archive entry escapes the destination: " + unsafeEntry);
1446
+ try {
1447
+ fs_1.default.rmSync(path_1.default.resolve(uploadedFile));
1448
+ }
1449
+ catch (e) { }
1450
+ resolve({ code: 59, message: "Archive rejected: an entry points outside the destination.", details: unsafeEntry, httpStatus: 400 });
1451
+ return;
1452
+ }
1453
+ try {
1454
+ const tmp = path_1.default.resolve(destination, "__tmp");
1455
+ if (fs_1.default.existsSync(tmp))
1456
+ fs_1.default.rmSync(tmp, { recursive: true });
1457
+ if (!fs_1.default.existsSync(tmp))
1458
+ fs_1.default.mkdirSync(tmp, { recursive: true });
1459
+ (0, child_process_1.execFileSync)("tar", ["-xzf", uploadedFile, "-C", tmp]);
1460
+ }
1461
+ catch (e) {
1462
+ (0, LogService_1.logError)(e);
1463
+ try {
1464
+ fs_1.default.rmSync(path_1.default.resolve(uploadedFile));
1465
+ }
1466
+ catch (e) { }
1467
+ resolve({ code: 14, message: "Can't unpack file", httpStatus: 500 });
1468
+ return;
1469
+ }
1470
+ try {
1471
+ fs_1.default.rmSync(path_1.default.resolve(uploadedFile));
1472
+ }
1473
+ catch (e) {
1474
+ (0, LogService_1.logError)("Can't remove file", e);
1475
+ }
1476
+ const escaping = DeployerService._escapingSymlink(path_1.default.resolve(destination, "__tmp"));
1477
+ if (escaping) {
1478
+ (0, LogService_1.logError)("Refusing to deploy: symlink points outside the archive: " + escaping);
1479
+ try {
1480
+ fs_1.default.rmSync(path_1.default.resolve(destination, "__tmp"), { recursive: true });
1481
+ }
1482
+ catch (e) { }
1483
+ resolve({ code: 59, message: "Archive rejected: a symlink points outside the destination.", details: escaping, httpStatus: 400 });
1484
+ return;
1485
+ }
1486
+ if (projectName)
1487
+ DeployerService._stampProjectName(path_1.default.resolve(destination, "__tmp"), projectName);
1488
+ if (install) {
1489
+ try {
1490
+ const tmpDir = path_1.default.resolve(destination, "__tmp");
1491
+ const useCi = fs_1.default.existsSync(path_1.default.resolve(tmpDir, "package-lock.json"));
1492
+ if (!useCi) {
1493
+ (0, LogService_1.logWarn)("No package-lock.json in uploaded tarball — falling back to `npm i`. " +
1494
+ "This is non-deterministic and vulnerable to supply-chain attacks. " +
1495
+ "Commit and include package-lock.json for `npm ci` (deterministic + faster).");
1496
+ }
1497
+ const npmCmd = useCi ? "ci" : "i";
1498
+ (0, child_process_1.execFileSync)("npm", ["--prefix", tmpDir, npmCmd, "--ignore-scripts", ...(omitDev ? ["--omit=dev"] : [])]);
1499
+ }
1500
+ catch (e) {
1501
+ (0, LogService_1.logError)(e);
1502
+ (0, LogService_1.logError)(e);
1503
+ resolve({ code: 17, message: "Can't install", httpStatus: 500 });
1504
+ return;
1505
+ }
1506
+ }
1507
+ if (!ignoreDirectoryClean) {
1508
+ fs_1.default.readdirSync(destination).forEach((file) => {
1509
+ if (file === "__tmp")
1510
+ return;
1511
+ try {
1512
+ fs_1.default.rmSync(path_1.default.resolve(destination, file), { recursive: true });
1513
+ }
1514
+ catch (e) {
1515
+ (0, LogService_1.logError)(e);
1516
+ }
1517
+ });
1518
+ }
1519
+ try {
1520
+ (0, child_process_1.execFileSync)("cp", ["-RPf", path_1.default.resolve(destination, "__tmp") + "/.", destination]);
1521
+ }
1522
+ catch (e) {
1523
+ (0, LogService_1.logError)(e);
1524
+ try {
1525
+ fs_1.default.rmSync(path_1.default.resolve(destination, "__tmp"), { recursive: true, force: true });
1526
+ }
1527
+ catch (_) { }
1528
+ resolve({ code: 15, message: "Can't copy files", httpStatus: 500 });
1529
+ return;
1530
+ }
1531
+ try {
1532
+ fs_1.default.rmSync(path_1.default.resolve(destination, "__tmp"), { recursive: true });
1533
+ }
1534
+ catch (e) {
1535
+ (0, LogService_1.logError)(e);
1536
+ resolve({ code: 16, message: "Can't remove tmp", httpStatus: 500 });
1537
+ }
1538
+ resolve(null);
1539
+ });
1540
+ }
1541
+ async upload(file, uploadPath) {
1542
+ return new Promise((resolve) => {
1543
+ file.mv(uploadPath, (err) => {
1544
+ if (err) {
1545
+ resolve({ code: 13, message: "Can't upload file", httpStatus: 500, details: err });
1546
+ return;
1547
+ }
1548
+ resolve(null);
1549
+ });
1550
+ });
1551
+ }
1552
+ }
1553
+ exports.DeployerService = DeployerService;