badmfck-api-server 6.0.1 → 6.0.3

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.
@@ -16,11 +16,14 @@ const util_1 = require("util");
16
16
  const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
17
17
  const fs_1 = __importDefault(require("fs"));
18
18
  const crypto_1 = __importDefault(require("crypto"));
19
+ const net_1 = __importDefault(require("net"));
19
20
  const Watchdog_1 = require("./Watchdog");
20
21
  const NginxHelper_1 = require("./NginxHelper");
21
22
  const BlueGreenState_1 = require("./BlueGreenState");
22
23
  const BackupManager_1 = require("./BackupManager");
23
24
  const PasswordHash_1 = require("../helper/PasswordHash");
25
+ const ReviewStore_1 = require("./ReviewStore");
26
+ const SecretsInjector_1 = require("./SecretsInjector");
24
27
  const _TSetup = {
25
28
  users: [{
26
29
  login: "",
@@ -34,7 +37,19 @@ const _TSetup = {
34
37
  },
35
38
  $__notifier_optional: true,
36
39
  status_url: "",
37
- $__status_url_optional: true
40
+ $__status_url_optional: true,
41
+ allowed_ips: [""],
42
+ $__allowed_ips_optional: true,
43
+ reviewers: [{
44
+ login: "",
45
+ password: "",
46
+ email: "",
47
+ }],
48
+ $__reviewers_optional: true,
49
+ review_url: "",
50
+ $__review_url_optional: true,
51
+ secrets_dir: "",
52
+ $__secrets_dir_optional: true
38
53
  };
39
54
  exports.REQ_DEPLOYMENT_PROCEED = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SERVICE");
40
55
  exports.REQ_DEPLOYMENT_SWITCH = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SWITCH");
@@ -53,6 +68,7 @@ class DeployerService extends BaseService_1.BaseService {
53
68
  setup = null;
54
69
  notifier = null;
55
70
  busy = new Map();
71
+ reviews;
56
72
  _setupWatchDebounceTimer = null;
57
73
  _lastSetupHash = null;
58
74
  constructor(options) {
@@ -60,6 +76,11 @@ class DeployerService extends BaseService_1.BaseService {
60
76
  this.options = options;
61
77
  }
62
78
  async init() {
79
+ this.reviews = new ReviewStore_1.ReviewStore(this.options.projects_path);
80
+ const sweep = () => { for (const p of this.reviews.sweep())
81
+ (0, LogService_1.logWarn)(`Review of "${p}" expired — the uploaded archive was removed`); };
82
+ sweep();
83
+ setInterval(sweep, 10 * 60 * 1000).unref();
63
84
  super.init();
64
85
  const cs = new ConfigService_1.ConfigService(this.options.projects_path);
65
86
  await cs.init();
@@ -85,6 +106,26 @@ class DeployerService extends BaseService_1.BaseService {
85
106
  exports.REQ_DEPLOYMENT_SLOT.listener = async (data) => this.slotState(data);
86
107
  exports.REQ_DEPLOYMENT_BACKUPS.listener = async (data) => this.listBackups(data);
87
108
  exports.REQ_DEPLOYMENT_RESTORE.listener = async (data) => this.restoreBackup(data);
109
+ await this._checkReviewSetup();
110
+ ConfigService_1.S_CONFIG_UPDATED.subscribe(() => { this._checkReviewSetup(); });
111
+ }
112
+ async _checkReviewSetup() {
113
+ try {
114
+ const plain = (this.setup?.reviewers ?? []).filter(r => r?.login && !PasswordHash_1.PasswordHash.isHash(r.password)).map(r => r.login);
115
+ if (plain.length)
116
+ (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 badmfck hash-password`);
117
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
118
+ for (const c of configurations.values()) {
119
+ if (!c?.review)
120
+ continue;
121
+ const problem = this._reviewSetup(c).error;
122
+ if (problem)
123
+ (0, LogService_1.logError)(`Deployer: review of "${c.name}" can't work — ${problem}. Uploads of this project will be refused until it is fixed.`);
124
+ }
125
+ }
126
+ catch (e) {
127
+ (0, LogService_1.logWarn)("Deployer: can't check the review setup: " + (e?.message ?? e));
128
+ }
88
129
  }
89
130
  async _loadSetup() {
90
131
  const setupFile = path_1.default.resolve(this.options.setup_path, "setup.json");
@@ -113,6 +154,11 @@ class DeployerService extends BaseService_1.BaseService {
113
154
  (0, LogService_1.logError)("Setup validation failed: " + JSON.stringify(errors));
114
155
  return null;
115
156
  }
157
+ const ips = DeployerService.buildAllowList(parsed.allowed_ips);
158
+ if (ips.error) {
159
+ (0, LogService_1.logError)("Setup validation failed: allowed_ips — " + ips.error);
160
+ return null;
161
+ }
116
162
  return parsed;
117
163
  }
118
164
  async _reloadSetup() {
@@ -127,6 +173,7 @@ class DeployerService extends BaseService_1.BaseService {
127
173
  this._lastSetupHash = hash;
128
174
  this.setup = fresh;
129
175
  this._warnPlaintextUsers();
176
+ this._checkReviewSetup();
130
177
  (0, LogService_1.logWarn)("Setup reloaded from disk (users list refreshed live; notifier/watchdog need service restart to change)");
131
178
  }
132
179
  _watchSetup() {
@@ -148,28 +195,34 @@ class DeployerService extends BaseService_1.BaseService {
148
195
  setInterval(() => { this._reloadSetup(); }, 60_000).unref();
149
196
  }
150
197
  async proceed(data) {
151
- const auth = await this._checkUserAuth(data.auth, data.authLogin);
198
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
152
199
  const user = auth.user;
153
200
  if (!user) {
154
201
  (0, LogService_1.logError)("Deploy rejected: user auth failed");
155
- return { error: { code: 20, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
202
+ return { error: { code: 20, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
156
203
  }
157
204
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
158
- let found;
159
- for (let i of configurations.values()) {
160
- if (i.name === data.name && this.tokensMatch(i.token, data.token)) {
161
- found = i;
162
- break;
163
- }
164
- }
205
+ const project = await this._projectByToken(configurations, data.name, data.token);
206
+ if (project.error)
207
+ return { error: { code: 12, message: project.error, httpStatus: 400 } };
208
+ let found = project.config;
165
209
  if (!found) {
166
210
  (0, LogService_1.logError)("Deploy rejected: wrong token and/or name");
167
211
  return { error: { code: 12, message: "Wrong token and/or name.", httpStatus: 400 } };
168
212
  }
213
+ if (this.busy.get(found.name))
214
+ return { error: { code: 13, message: "Deployment already in progress.", httpStatus: 400 } };
215
+ if (found.review)
216
+ return await this._queueForReview(found, user, data.files.file, data.ip);
217
+ return await this._deploy(found, user, configurations, data.name, { file: data.files.file });
218
+ }
219
+ async _deploy(found, user, configurations, name, source) {
169
220
  if (this.busy.get(found.name))
170
221
  return { error: { code: 13, message: "Deployment already in progress.", httpStatus: 400 } };
171
222
  const realName = found.name;
223
+ const data = { name };
172
224
  this.busy.set(realName, true);
225
+ let baselineStaged = false;
173
226
  try {
174
227
  found = structuredClone(found);
175
228
  const allConfigs = Array.from(configurations.values());
@@ -179,8 +232,8 @@ class DeployerService extends BaseService_1.BaseService {
179
232
  (0, LogService_1.logError)("Deploy rejected: unsafe destination: " + rootProblem);
180
233
  throw { code: 19, message: "Unsafe destination.", details: rootProblem, httpStatus: 400 };
181
234
  }
182
- const file = data.files.file;
183
- const safeName = (path_1.default.basename(file.name || "").replace(/[^a-zA-Z0-9._-]/g, "_")) || "upload";
235
+ const sourceName = source.file ? source.file.name : path_1.default.basename(source.archivePath ?? "");
236
+ const safeName = (path_1.default.basename(sourceName || "").replace(/[^a-zA-Z0-9._-]/g, "_")) || "upload";
184
237
  let projectState = null;
185
238
  let projectStatePath = null;
186
239
  let projectStateWasCreated = false;
@@ -234,6 +287,25 @@ class DeployerService extends BaseService_1.BaseService {
234
287
  throw { code: 19, message: "Unsafe destination.", details: slotProblem, httpStatus: 400 };
235
288
  }
236
289
  }
290
+ let secretsFile = null;
291
+ if (found.secrets) {
292
+ const slotName = projectState ? projectState.lastDeployed : null;
293
+ 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);
294
+ if (resolved.error) {
295
+ (0, LogService_1.logError)(`Deploy of "${realName}" rejected: ${resolved.error}`);
296
+ throw { code: 64, message: "Secrets are misconfigured.", details: resolved.error, httpStatus: 500 };
297
+ }
298
+ secretsFile = resolved.path;
299
+ if (found.pm2) {
300
+ const attrs = DeployerService._pm2AttributesFor(found, projectState);
301
+ const switchesUser = attrs.find(a => /^--(uid|gid|user)(=|$)/.test(a));
302
+ if (switchesUser) {
303
+ const why = `pm2 runs this project as another user (${switchesUser}), which couldn't read the secrets file`;
304
+ (0, LogService_1.logError)(`Deploy of "${realName}" rejected: ${why}`);
305
+ 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 };
306
+ }
307
+ }
308
+ }
237
309
  const uploadPath = path_1.default.resolve(found.destination, __1.UID.generate() + "_" + safeName);
238
310
  if (found.backup) {
239
311
  try {
@@ -255,7 +327,9 @@ class DeployerService extends BaseService_1.BaseService {
255
327
  throw { code: 54, message: "Backup failed, deploy aborted — nothing was changed.", details: String(e?.message ?? e), httpStatus: 500 };
256
328
  }
257
329
  }
258
- const result = await this.upload(file, uploadPath);
330
+ const result = source.file
331
+ ? await this.upload(source.file, uploadPath)
332
+ : this._copyArchive(source.archivePath, uploadPath);
259
333
  if (__1.ErrorUtils.isError(result)) {
260
334
  if (found.email && found.email.length > 0) {
261
335
  for (let email of found.email) {
@@ -264,6 +338,15 @@ class DeployerService extends BaseService_1.BaseService {
264
338
  }
265
339
  throw result;
266
340
  }
341
+ if (found.review) {
342
+ try {
343
+ this.reviews.stageBaseline(realName, uploadPath);
344
+ baselineStaged = true;
345
+ }
346
+ catch (e) {
347
+ (0, LogService_1.logWarn)(`Review baseline for "${realName}" not kept: ${e?.message ?? e}`);
348
+ }
349
+ }
267
350
  if (found.unpack) {
268
351
  const unpackResult = await this.unpack(found.destination, uploadPath, found.install, found.ignoreDirectoryClean);
269
352
  if (__1.ErrorUtils.isError(unpackResult)) {
@@ -276,6 +359,11 @@ class DeployerService extends BaseService_1.BaseService {
276
359
  }
277
360
  }
278
361
  if (found.chmod && found.chmod > 1) {
362
+ const others = Number(String(found.chmod).slice(-1));
363
+ if (others & 2)
364
+ (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`);
365
+ else if (others & 4)
366
+ (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"}`);
279
367
  try {
280
368
  (0, LogService_1.logInfo)("Try to execute: ", `chmod -R ${found.chmod} ${found.destination}`);
281
369
  (0, child_process_1.execFileSync)("chmod", ["-R", String(found.chmod), found.destination]);
@@ -285,7 +373,28 @@ class DeployerService extends BaseService_1.BaseService {
285
373
  }
286
374
  }
287
375
  if (found.config) {
288
- await this.applyConfig(found.destination, found.config);
376
+ let inject = secretsFile;
377
+ if (secretsFile) {
378
+ SecretsInjector_1.SecretsInjector.write(secretsFile, found.config);
379
+ const unreadable = SecretsInjector_1.SecretsInjector.verify(secretsFile, found.config);
380
+ if (unreadable) {
381
+ (0, LogService_1.logError)(`Deploy of "${found.name}" stopped: ${unreadable}`);
382
+ throw { code: 66, message: "The secrets file can't be read back — the app was not started.", details: unreadable, httpStatus: 500 };
383
+ }
384
+ (0, LogService_1.logInfo)(`Secrets of "${found.name}" written to ${secretsFile}`);
385
+ try {
386
+ const pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(found.destination, "package.json"), "utf-8"));
387
+ if (pkg?.type === "module") {
388
+ (0, LogService_1.logWarn)(`Secrets of "${found.name}": the project is an ES module ("type": "module") — values are substituted into the code as before`);
389
+ inject = null;
390
+ }
391
+ }
392
+ catch { }
393
+ }
394
+ const onDisk = [];
395
+ await this.applyConfig(found.destination, found.config, { secretsFile: inject, onDisk });
396
+ if (secretsFile && onDisk.length)
397
+ (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(", ")}`);
289
398
  }
290
399
  if (projectState && projectStatePath) {
291
400
  this._writeBlueGreenFiles(data.name, projectState, path_1.default.dirname(found.destination));
@@ -357,6 +466,10 @@ class DeployerService extends BaseService_1.BaseService {
357
466
  }
358
467
  }, 5000);
359
468
  }
469
+ if (baselineStaged) {
470
+ this.reviews.commitBaseline(realName);
471
+ baselineStaged = false;
472
+ }
360
473
  return { data: {
361
474
  ok: true,
362
475
  project: realName,
@@ -369,24 +482,199 @@ class DeployerService extends BaseService_1.BaseService {
369
482
  } };
370
483
  }
371
484
  finally {
485
+ if (baselineStaged)
486
+ this.reviews.dropStagedBaseline(realName);
372
487
  this.busy.set(realName, false);
373
488
  }
374
489
  }
490
+ _reviewSetup(found) {
491
+ const review = found.review;
492
+ const logins = Array.from(new Set((review?.reviewers ?? []).map(l => String(l).trim()).filter(Boolean)));
493
+ if (logins.length === 0)
494
+ return { error: "review.reviewers is empty" };
495
+ const url = String(this.setup?.review_url ?? "");
496
+ if (!/^https?:\/\/[^\s#]+$/.test(url))
497
+ return { error: "review_url is not set in setup.json" };
498
+ if (!this.notifier)
499
+ return { error: "the notifier is not configured in setup.json — reviewers can't be emailed" };
500
+ const known = new Map((this.setup?.reviewers ?? []).map(r => [r.login, r]));
501
+ const reviewers = [];
502
+ for (const login of logins) {
503
+ const r = known.get(login);
504
+ if (!r)
505
+ return { error: `reviewer "${login}" is not defined in setup.json` };
506
+ if (!PasswordHash_1.PasswordHash.isHash(r.password))
507
+ return { error: `reviewer "${login}" has no password hash in setup.json` };
508
+ if (!/^[^\s@]+@[^\s@]+$/.test(String(r.email ?? "")))
509
+ return { error: `reviewer "${login}" has no valid email` };
510
+ reviewers.push({ login, email: r.email });
511
+ }
512
+ const hours = Math.min(Math.max(Number(review?.ttlHours) || 24, 1), 168);
513
+ return { reviewers, mode: review?.mode === "all" ? "all" : "any", ttlMs: hours * 3600_000 };
514
+ }
515
+ async _queueForReview(found, user, file, ip) {
516
+ const realName = found.name;
517
+ if (!file)
518
+ return { error: { code: 14, message: "No archive uploaded.", httpStatus: 400 } };
519
+ const setup = this._reviewSetup(found);
520
+ if (setup.error) {
521
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued — review is misconfigured: ${setup.error}`);
522
+ return { error: { code: 61, message: "Review is misconfigured on the deployer.", details: setup.error, httpStatus: 500 } };
523
+ }
524
+ this.busy.set(realName, true);
525
+ try {
526
+ const { pending, tokens, replaced } = await this.reviews.create(realName, file, {
527
+ uploadedBy: user.login, uploadedFrom: ip ?? null, mode: setup.mode,
528
+ reviewers: setup.reviewers.map(r => r.login), ttlMs: setup.ttlMs,
529
+ });
530
+ const unsafe = DeployerService._unsafeArchiveEntry(this.reviews.archivePath(realName));
531
+ if (unsafe) {
532
+ this.reviews.remove(realName);
533
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued — unsafe archive entry: ${unsafe}`);
534
+ return { error: { code: 18, message: "Unsafe archive.", details: unsafe, httpStatus: 400 } };
535
+ }
536
+ const failed = [];
537
+ for (const r of setup.reviewers) {
538
+ const link = `${this.setup.review_url}#${tokens[r.login]}`;
539
+ const ok = await this.notifier.notifyReview(r.email, { project: realName, user: user.login, link, expiresAt: pending.expiresAt, mode: pending.mode });
540
+ if (!ok)
541
+ failed.push(r.login);
542
+ }
543
+ if (failed.length === setup.reviewers.length || (pending.mode === "all" && failed.length > 0)) {
544
+ this.reviews.remove(realName);
545
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued — review mail failed for ${failed.join(", ")}`);
546
+ return { error: { code: 62, message: "Review emails could not be sent — the deploy was not queued.", details: `not delivered to: ${failed.join(", ")}`, httpStatus: 502 } };
547
+ }
548
+ this.reviews.journal(realName, "uploaded", { by: user.login, ip: ip ?? null, sha256: pending.sha256, size: pending.size,
549
+ mode: pending.mode, reviewers: Object.keys(pending.reviewers), notNotified: failed, replacedPrevious: replaced });
550
+ (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" : ""}`);
551
+ return { data: {
552
+ ok: true,
553
+ project: realName,
554
+ pendingReview: true,
555
+ mode: pending.mode,
556
+ reviewers: Object.keys(pending.reviewers),
557
+ notNotified: failed,
558
+ expiresAt: pending.expiresAt,
559
+ replacedPrevious: replaced,
560
+ } };
561
+ }
562
+ catch (e) {
563
+ this.reviews.remove(realName);
564
+ (0, LogService_1.logError)(`Deploy of "${realName}" not queued: ${e?.message ?? e}`);
565
+ return { error: { code: 63, message: "Can't store the archive for review.", details: String(e?.message ?? e), httpStatus: 500 } };
566
+ }
567
+ finally {
568
+ this.busy.set(realName, false);
569
+ }
570
+ }
571
+ async reviewDecide(project, sha256, reviewer, decision, ip) {
572
+ if (this.busy.get(project))
573
+ return { error: "A deploy of this project is running — try again in a moment." };
574
+ const pending = this.reviews.get(project);
575
+ if (!pending || pending.sha256 !== sha256)
576
+ return { error: "This upload was replaced or removed." };
577
+ if (pending.state !== "pending")
578
+ return { error: `This upload is already ${pending.state}.` };
579
+ if (pending.expiresAt < Date.now())
580
+ return { error: "The review time is over — upload again." };
581
+ const mine = pending.reviewers[reviewer];
582
+ if (!mine)
583
+ return { error: "You are not a reviewer of this upload." };
584
+ if (mine.decision)
585
+ return { error: `You already chose "${mine.decision}".` };
586
+ mine.decision = decision;
587
+ mine.at = Date.now();
588
+ mine.ip = ip;
589
+ this.reviews.journal(project, decision, { reviewer, ip, sha256 });
590
+ const emails = (await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request()).get(project)?.email ?? [];
591
+ if (decision === "decline") {
592
+ pending.state = "declined";
593
+ pending.result = { at: Date.now(), message: `Declined by ${reviewer}.` };
594
+ this.reviews.save(pending);
595
+ this.reviews.dropArchive(project);
596
+ (0, LogService_1.logWarn)(`Review of "${project}": declined by ${reviewer} from ${ip ?? "unknown"} — archive removed`);
597
+ for (const e of emails)
598
+ this.notifier?.notifyEmailStatus(e, `declined by ${reviewer}`, project, pending.uploadedBy);
599
+ return { pending };
600
+ }
601
+ const accepted = Object.entries(pending.reviewers).filter(([, r]) => r.decision === "accept").map(([l]) => l);
602
+ const ready = pending.mode === "any" || accepted.length === Object.keys(pending.reviewers).length;
603
+ (0, LogService_1.logInfo)(`Review of "${project}": accepted by ${reviewer} from ${ip ?? "unknown"}${ready ? " — deploying" : ` (${accepted.length}/${Object.keys(pending.reviewers).length})`}`);
604
+ if (!ready) {
605
+ this.reviews.save(pending);
606
+ return { pending };
607
+ }
608
+ pending.state = "deploying";
609
+ this.reviews.save(pending);
610
+ this._deployApproved(project, accepted).catch(e => (0, LogService_1.logError)(`Approved deploy of "${project}" crashed: ${e?.message ?? e}`));
611
+ return { pending };
612
+ }
613
+ async _deployApproved(project, approvers) {
614
+ const finish = (state, result) => {
615
+ const p = this.reviews.get(project);
616
+ if (!p)
617
+ return;
618
+ p.state = state;
619
+ p.result = { at: Date.now(), ...result };
620
+ this.reviews.save(p);
621
+ this.reviews.dropArchive(project);
622
+ this.reviews.journal(project, state, { sha256: p.sha256, approvedBy: approvers, message: result.message });
623
+ };
624
+ const pending = this.reviews.get(project);
625
+ if (!pending)
626
+ return;
627
+ if (!(await this.reviews.archiveIntact(pending))) {
628
+ (0, LogService_1.logError)(`Approved deploy of "${project}" stopped: the stored archive no longer matches its hash`);
629
+ return finish("failed", { message: "The stored archive changed after the review — nothing was deployed." });
630
+ }
631
+ const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
632
+ const found = configurations.get(project);
633
+ if (!found || !found.review) {
634
+ (0, LogService_1.logError)(`Approved deploy of "${project}" stopped: the project or its review setting is gone`);
635
+ return finish("failed", { message: "The project or its review setting was removed — nothing was deployed." });
636
+ }
637
+ const actor = { login: `${pending.uploadedBy} (approved by ${approvers.join(", ")})`, password: "" };
638
+ try {
639
+ const res = await this._deploy(found, actor, configurations, project, { archivePath: this.reviews.archivePath(project) });
640
+ if (res?.error) {
641
+ finish("failed", { message: res.error.message + (res.error.details ? ` (${res.error.details})` : "") });
642
+ return;
643
+ }
644
+ finish("deployed", {
645
+ message: res?.data?.bluegreen && !res.data.activeThisDeploy
646
+ ? `Deployed to slot ${res.data.slot} — not live yet: run "badmfck activate" to switch traffic.`
647
+ : "Deployed and live.",
648
+ slot: res?.data?.slot ?? null, activeThisDeploy: res?.data?.activeThisDeploy,
649
+ });
650
+ }
651
+ catch (e) {
652
+ const msg = e?.message ? e.message + (e.details ? ` (${typeof e.details === "string" ? e.details : JSON.stringify(e.details)})` : "") : String(e);
653
+ (0, LogService_1.logError)(`Approved deploy of "${project}" failed: ${msg}`);
654
+ finish("failed", { message: LogService_1.LogService.sanitize(msg) });
655
+ }
656
+ }
657
+ _copyArchive(from, to) {
658
+ try {
659
+ fs_1.default.copyFileSync(from, to);
660
+ return null;
661
+ }
662
+ catch (e) {
663
+ return { code: 13, message: "Can't copy archive", httpStatus: 500, details: String(e?.message ?? e) };
664
+ }
665
+ }
375
666
  async switchSlot(data) {
376
- const auth = await this._checkUserAuth(data.auth, data.authLogin);
667
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
377
668
  const user = auth.user;
378
669
  if (!user) {
379
670
  (0, LogService_1.logError)("Switch rejected: user auth failed");
380
- return { error: { code: 40, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
671
+ return { error: { code: 40, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
381
672
  }
382
673
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
383
- let found;
384
- for (const i of configurations.values()) {
385
- if (i.name === data.name && this.tokensMatch(i.token, data.token)) {
386
- found = i;
387
- break;
388
- }
389
- }
674
+ const project = await this._projectByToken(configurations, data.name, data.token);
675
+ if (project.error)
676
+ return { error: { code: 41, message: project.error, httpStatus: 400 } };
677
+ let found = project.config;
390
678
  if (!found) {
391
679
  (0, LogService_1.logError)("Switch rejected: wrong token and/or name");
392
680
  return { error: { code: 41, message: "Wrong token and/or name.", httpStatus: 400 } };
@@ -462,10 +750,10 @@ class DeployerService extends BaseService_1.BaseService {
462
750
  }
463
751
  }
464
752
  async status(data) {
465
- const auth = await this._checkUserAuth(data.auth, data.authLogin);
753
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
466
754
  const user = auth.user;
467
755
  if (!user) {
468
- return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
756
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
469
757
  }
470
758
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
471
759
  const results = {};
@@ -496,10 +784,10 @@ class DeployerService extends BaseService_1.BaseService {
496
784
  return DeployerService._isBlueGreen(found) ? dest : path_1.default.dirname(dest);
497
785
  }
498
786
  async listBackups(data) {
499
- const auth = await this._checkUserAuth(data.auth, data.authLogin);
787
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
500
788
  const user = auth.user;
501
789
  if (!user) {
502
- return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
790
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
503
791
  }
504
792
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
505
793
  const found = Array.from(configurations.values()).find(c => c.name === data.name);
@@ -527,20 +815,17 @@ class DeployerService extends BaseService_1.BaseService {
527
815
  } };
528
816
  }
529
817
  async restoreBackup(data) {
530
- const auth = await this._checkUserAuth(data.auth, data.authLogin);
818
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
531
819
  const user = auth.user;
532
820
  if (!user) {
533
821
  (0, LogService_1.logError)("Restore rejected: user auth failed");
534
- return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
822
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
535
823
  }
536
824
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
537
- let found;
538
- for (const i of configurations.values()) {
539
- if (i.name === data.name && this.tokensMatch(i.token, data.token)) {
540
- found = i;
541
- break;
542
- }
543
- }
825
+ const project = await this._projectByToken(configurations, data.name, data.token);
826
+ if (project.error)
827
+ return { error: { code: 41, message: project.error, httpStatus: 400 } };
828
+ let found = project.config;
544
829
  if (!found) {
545
830
  (0, LogService_1.logError)("Restore rejected: wrong token and/or name");
546
831
  return { error: { code: 41, message: "Wrong token and/or name.", httpStatus: 400 } };
@@ -676,18 +961,71 @@ class DeployerService extends BaseService_1.BaseService {
676
961
  }
677
962
  }
678
963
  }
964
+ static PLAINTEXT_TOKEN_ERROR = "Project token is built incorrectly — the project config must hold a hash from `npx badmfck project-token --hash`, not the token itself.";
965
+ async _projectByToken(configurations, name, token) {
966
+ const config = Array.from(configurations.values()).find(c => c.name === name);
967
+ if (!config || typeof token !== "string" || !token)
968
+ return {};
969
+ if (PasswordHash_1.PasswordHash.isHash(config.token))
970
+ return (await PasswordHash_1.PasswordHash.verify(token, config.token)) ? { config } : {};
971
+ if (config.token && this.tokensMatch(config.token, token)) {
972
+ (0, LogService_1.logError)(`Deployer: project "${name}" refused — its token is stored as plain text`);
973
+ return { error: DeployerService.PLAINTEXT_TOKEN_ERROR };
974
+ }
975
+ return {};
976
+ }
679
977
  tokensMatch(a, b) {
680
978
  const ha = new Uint8Array(crypto_1.default.createHash("sha256").update(String(a ?? "")).digest());
681
979
  const hb = new Uint8Array(crypto_1.default.createHash("sha256").update(String(b ?? "")).digest());
682
980
  return crypto_1.default.timingSafeEqual(ha, hb);
683
981
  }
982
+ static buildAllowList(entries) {
983
+ const items = (entries ?? []).map(e => String(e).trim()).filter(e => e.length > 0);
984
+ if (items.length === 0)
985
+ return { list: null };
986
+ const list = new net_1.default.BlockList();
987
+ for (const item of items) {
988
+ const [addr, prefix, extra] = item.split("/");
989
+ const family = net_1.default.isIP(addr);
990
+ if (!family || extra !== undefined)
991
+ return { list: null, error: `"${item}" is not an IP address or subnet` };
992
+ const type = family === 6 ? "ipv6" : "ipv4";
993
+ if (prefix === undefined) {
994
+ list.addAddress(addr, type);
995
+ continue;
996
+ }
997
+ const bits = Number(prefix), max = family === 6 ? 128 : 32;
998
+ if (!/^\d+$/.test(prefix) || bits > max)
999
+ return { list: null, error: `"${item}" has an invalid prefix (0–${max})` };
1000
+ list.addSubnet(addr, bits, type);
1001
+ }
1002
+ return { list };
1003
+ }
1004
+ isIpAllowed(ip) {
1005
+ return this._ipAllowed(ip);
1006
+ }
1007
+ _ipAllowed(ip) {
1008
+ const { list } = DeployerService.buildAllowList(this.setup?.allowed_ips);
1009
+ if (!list)
1010
+ return true;
1011
+ const family = net_1.default.isIP(String(ip ?? ""));
1012
+ if (!family)
1013
+ return false;
1014
+ return list.check(String(ip), family === 6 ? "ipv6" : "ipv4");
1015
+ }
684
1016
  _warnPlaintextUsers() {
1017
+ if (!DeployerService.buildAllowList(this.setup?.allowed_ips).list)
1018
+ (0, LogService_1.logWarn)("Deployer: allowed_ips is not set in setup.json — deploys are accepted from any address");
685
1019
  const plain = (this.setup?.users ?? []).filter(u => u?.login && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
686
1020
  if (plain.length)
687
1021
  (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 badmfck hash-password --deployer`);
688
1022
  }
689
1023
  static PLAINTEXT_ERROR = "Password is built incorrectly — setup.json must hold a hash from `npx badmfck hash-password --deployer`, not the password itself.";
690
- async _checkUserAuth(authHeader, loginHeader) {
1024
+ async _checkUserAuth(authHeader, loginHeader, ip) {
1025
+ if (!this._ipAllowed(ip)) {
1026
+ (0, LogService_1.logWarn)(`Deployer: request refused from ${ip ?? "unknown"} — not in allowed_ips`);
1027
+ return { error: "Deployer access is not allowed from this address.", status: 403 };
1028
+ }
691
1029
  if (!authHeader)
692
1030
  return {};
693
1031
  if (!this.setup)
@@ -769,6 +1107,11 @@ class DeployerService extends BaseService_1.BaseService {
769
1107
  return upstreamErr;
770
1108
  return null;
771
1109
  }
1110
+ static _pm2AttributesFor(found, projectState) {
1111
+ const slotAttrs = projectState?.lastDeployed === "blue" ? found.bluegreen?.blue_pm2_attributes : found.bluegreen?.green_pm2_attributes;
1112
+ const list = Array.isArray(slotAttrs) ? slotAttrs : found.pm2_attributes;
1113
+ return Array.isArray(list) ? list.filter((s) => typeof s === "string" && s.length > 0) : [];
1114
+ }
772
1115
  async runPM2(found, projectState) {
773
1116
  let pm2attrs = projectState?.lastDeployed === "blue" ? found.bluegreen?.blue_pm2_attributes : found.bluegreen?.green_pm2_attributes;
774
1117
  const pm2Attrs = Array.isArray(pm2attrs) ? pm2attrs.filter(s => typeof s === "string" && s.length > 0) : found.pm2_attributes;
@@ -835,7 +1178,7 @@ class DeployerService extends BaseService_1.BaseService {
835
1178
  }
836
1179
  static SKIP_DIRS = new Set(["node_modules", ".git", "__tmp"]);
837
1180
  static TEMPLATE_EXTENSIONS = [".js", ".ts", ".json", ".env"];
838
- async applyConfig(dir, config) {
1181
+ async applyConfig(dir, config, ctx) {
839
1182
  if (Object.keys(config).length < 1)
840
1183
  return;
841
1184
  const entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
@@ -846,23 +1189,41 @@ class DeployerService extends BaseService_1.BaseService {
846
1189
  if (DeployerService.SKIP_DIRS.has(entry.name))
847
1190
  continue;
848
1191
  const fullPath = path_1.default.join(dir, entry.name);
849
- await this.applyConfig(fullPath, config);
1192
+ await this.applyConfig(fullPath, config, ctx);
850
1193
  continue;
851
1194
  }
852
1195
  if (entry.isFile()) {
853
1196
  const fullPath = path_1.default.join(dir, entry.name);
854
1197
  const lower = fullPath.toLowerCase();
855
1198
  if (DeployerService.TEMPLATE_EXTENSIONS.some(ext => lower.endsWith(ext)))
856
- await this.processFile(fullPath, config);
1199
+ await this.processFile(fullPath, config, ctx);
857
1200
  }
858
1201
  }
859
1202
  }
860
- async processFile(filePath, config) {
1203
+ async processFile(filePath, config, ctx) {
861
1204
  let content = fs_1.default.readFileSync(filePath, "utf-8");
862
1205
  let hash = crypto_1.default.createHash("md5").update(content).digest("hex");
1206
+ const lowerPath = filePath.toLowerCase();
1207
+ if (ctx?.secretsFile && (lowerPath.endsWith(".js") || lowerPath.endsWith(".cjs")) && content.includes("_{{")) {
1208
+ const t = SecretsInjector_1.SecretsInjector.transform(content, new Set(Object.keys(config)), ctx.secretsFile);
1209
+ if (t.rewritten > 0) {
1210
+ const noShebang = (src) => src.replace(/^#!.*/, "");
1211
+ if (SecretsInjector_1.SecretsInjector.parses(noShebang(content)) && SecretsInjector_1.SecretsInjector.parses(noShebang(t.content)))
1212
+ content = t.content;
1213
+ else
1214
+ (0, LogService_1.logWarn)(`Secrets: ${filePath} can't be rewritten safely (it doesn't compile as CommonJS) — values are substituted as before`);
1215
+ }
1216
+ }
1217
+ let substituted = false;
863
1218
  for (const [key, value] of Object.entries(config)) {
864
- content = content.replaceAll(`_{{${key}}}_`, value);
1219
+ const placeholder = `_{{${key}}}_`;
1220
+ if (content.includes(placeholder)) {
1221
+ substituted = true;
1222
+ content = content.replaceAll(placeholder, () => String(value));
1223
+ }
865
1224
  }
1225
+ if (substituted && ctx?.secretsFile !== undefined && ctx.onDisk)
1226
+ ctx.onDisk.push(filePath);
866
1227
  let hash2 = crypto_1.default.createHash("md5").update(content).digest("hex");
867
1228
  if (hash !== hash2) {
868
1229
  (0, LogService_1.logInfo)("Values was changed in " + filePath);
@@ -1051,10 +1412,14 @@ class DeployerService extends BaseService_1.BaseService {
1051
1412
  });
1052
1413
  }
1053
1414
  try {
1054
- (0, child_process_1.execFileSync)("cp", ["-rf", path_1.default.resolve(destination, "__tmp") + "/.", destination]);
1415
+ (0, child_process_1.execFileSync)("cp", ["-RPf", path_1.default.resolve(destination, "__tmp") + "/.", destination]);
1055
1416
  }
1056
1417
  catch (e) {
1057
1418
  (0, LogService_1.logError)(e);
1419
+ try {
1420
+ fs_1.default.rmSync(path_1.default.resolve(destination, "__tmp"), { recursive: true, force: true });
1421
+ }
1422
+ catch (_) { }
1058
1423
  resolve({ code: 15, message: "Can't copy files", httpStatus: 500 });
1059
1424
  return;
1060
1425
  }