badmfck-api-server 6.0.2 → 6.0.4

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,12 +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"));
20
19
  const Watchdog_1 = require("./Watchdog");
21
20
  const NginxHelper_1 = require("./NginxHelper");
22
21
  const BlueGreenState_1 = require("./BlueGreenState");
23
22
  const BackupManager_1 = require("./BackupManager");
24
23
  const PasswordHash_1 = require("../helper/PasswordHash");
24
+ const ReviewStore_1 = require("./ReviewStore");
25
+ const SecretsInjector_1 = require("./SecretsInjector");
26
+ const IpAllowList_1 = require("../helper/IpAllowList");
25
27
  const _TSetup = {
26
28
  users: [{
27
29
  login: "",
@@ -37,7 +39,17 @@ const _TSetup = {
37
39
  status_url: "",
38
40
  $__status_url_optional: true,
39
41
  allowed_ips: [""],
40
- $__allowed_ips_optional: true
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
41
53
  };
42
54
  exports.REQ_DEPLOYMENT_PROCEED = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SERVICE");
43
55
  exports.REQ_DEPLOYMENT_SWITCH = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SWITCH");
@@ -56,6 +68,7 @@ class DeployerService extends BaseService_1.BaseService {
56
68
  setup = null;
57
69
  notifier = null;
58
70
  busy = new Map();
71
+ reviews;
59
72
  _setupWatchDebounceTimer = null;
60
73
  _lastSetupHash = null;
61
74
  constructor(options) {
@@ -63,6 +76,11 @@ class DeployerService extends BaseService_1.BaseService {
63
76
  this.options = options;
64
77
  }
65
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();
66
84
  super.init();
67
85
  const cs = new ConfigService_1.ConfigService(this.options.projects_path);
68
86
  await cs.init();
@@ -88,6 +106,26 @@ class DeployerService extends BaseService_1.BaseService {
88
106
  exports.REQ_DEPLOYMENT_SLOT.listener = async (data) => this.slotState(data);
89
107
  exports.REQ_DEPLOYMENT_BACKUPS.listener = async (data) => this.listBackups(data);
90
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
+ }
91
129
  }
92
130
  async _loadSetup() {
93
131
  const setupFile = path_1.default.resolve(this.options.setup_path, "setup.json");
@@ -135,6 +173,7 @@ class DeployerService extends BaseService_1.BaseService {
135
173
  this._lastSetupHash = hash;
136
174
  this.setup = fresh;
137
175
  this._warnPlaintextUsers();
176
+ this._checkReviewSetup();
138
177
  (0, LogService_1.logWarn)("Setup reloaded from disk (users list refreshed live; notifier/watchdog need service restart to change)");
139
178
  }
140
179
  _watchSetup() {
@@ -171,10 +210,19 @@ class DeployerService extends BaseService_1.BaseService {
171
210
  (0, LogService_1.logError)("Deploy rejected: wrong token and/or name");
172
211
  return { error: { code: 12, message: "Wrong token and/or name.", httpStatus: 400 } };
173
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) {
174
220
  if (this.busy.get(found.name))
175
221
  return { error: { code: 13, message: "Deployment already in progress.", httpStatus: 400 } };
176
222
  const realName = found.name;
223
+ const data = { name };
177
224
  this.busy.set(realName, true);
225
+ let baselineStaged = false;
178
226
  try {
179
227
  found = structuredClone(found);
180
228
  const allConfigs = Array.from(configurations.values());
@@ -184,8 +232,8 @@ class DeployerService extends BaseService_1.BaseService {
184
232
  (0, LogService_1.logError)("Deploy rejected: unsafe destination: " + rootProblem);
185
233
  throw { code: 19, message: "Unsafe destination.", details: rootProblem, httpStatus: 400 };
186
234
  }
187
- const file = data.files.file;
188
- 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";
189
237
  let projectState = null;
190
238
  let projectStatePath = null;
191
239
  let projectStateWasCreated = false;
@@ -239,6 +287,25 @@ class DeployerService extends BaseService_1.BaseService {
239
287
  throw { code: 19, message: "Unsafe destination.", details: slotProblem, httpStatus: 400 };
240
288
  }
241
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
+ }
242
309
  const uploadPath = path_1.default.resolve(found.destination, __1.UID.generate() + "_" + safeName);
243
310
  if (found.backup) {
244
311
  try {
@@ -260,7 +327,9 @@ class DeployerService extends BaseService_1.BaseService {
260
327
  throw { code: 54, message: "Backup failed, deploy aborted — nothing was changed.", details: String(e?.message ?? e), httpStatus: 500 };
261
328
  }
262
329
  }
263
- 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);
264
333
  if (__1.ErrorUtils.isError(result)) {
265
334
  if (found.email && found.email.length > 0) {
266
335
  for (let email of found.email) {
@@ -269,6 +338,15 @@ class DeployerService extends BaseService_1.BaseService {
269
338
  }
270
339
  throw result;
271
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
+ }
272
350
  if (found.unpack) {
273
351
  const unpackResult = await this.unpack(found.destination, uploadPath, found.install, found.ignoreDirectoryClean);
274
352
  if (__1.ErrorUtils.isError(unpackResult)) {
@@ -281,6 +359,11 @@ class DeployerService extends BaseService_1.BaseService {
281
359
  }
282
360
  }
283
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"}`);
284
367
  try {
285
368
  (0, LogService_1.logInfo)("Try to execute: ", `chmod -R ${found.chmod} ${found.destination}`);
286
369
  (0, child_process_1.execFileSync)("chmod", ["-R", String(found.chmod), found.destination]);
@@ -290,7 +373,28 @@ class DeployerService extends BaseService_1.BaseService {
290
373
  }
291
374
  }
292
375
  if (found.config) {
293
- 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(", ")}`);
294
398
  }
295
399
  if (projectState && projectStatePath) {
296
400
  this._writeBlueGreenFiles(data.name, projectState, path_1.default.dirname(found.destination));
@@ -362,6 +466,10 @@ class DeployerService extends BaseService_1.BaseService {
362
466
  }
363
467
  }, 5000);
364
468
  }
469
+ if (baselineStaged) {
470
+ this.reviews.commitBaseline(realName);
471
+ baselineStaged = false;
472
+ }
365
473
  return { data: {
366
474
  ok: true,
367
475
  project: realName,
@@ -373,10 +481,188 @@ class DeployerService extends BaseService_1.BaseService {
373
481
  : true,
374
482
  } };
375
483
  }
484
+ finally {
485
+ if (baselineStaged)
486
+ this.reviews.dropStagedBaseline(realName);
487
+ this.busy.set(realName, false);
488
+ }
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
+ }
376
567
  finally {
377
568
  this.busy.set(realName, false);
378
569
  }
379
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
+ }
380
666
  async switchSlot(data) {
381
667
  const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
382
668
  const user = auth.user;
@@ -694,35 +980,13 @@ class DeployerService extends BaseService_1.BaseService {
694
980
  return crypto_1.default.timingSafeEqual(ha, hb);
695
981
  }
696
982
  static buildAllowList(entries) {
697
- const items = (entries ?? []).map(e => String(e).trim()).filter(e => e.length > 0);
698
- if (items.length === 0)
699
- return { list: null };
700
- const list = new net_1.default.BlockList();
701
- for (const item of items) {
702
- const [addr, prefix, extra] = item.split("/");
703
- const family = net_1.default.isIP(addr);
704
- if (!family || extra !== undefined)
705
- return { list: null, error: `"${item}" is not an IP address or subnet` };
706
- const type = family === 6 ? "ipv6" : "ipv4";
707
- if (prefix === undefined) {
708
- list.addAddress(addr, type);
709
- continue;
710
- }
711
- const bits = Number(prefix), max = family === 6 ? 128 : 32;
712
- if (!/^\d+$/.test(prefix) || bits > max)
713
- return { list: null, error: `"${item}" has an invalid prefix (0–${max})` };
714
- list.addSubnet(addr, bits, type);
715
- }
716
- return { list };
983
+ return IpAllowList_1.IpAllowList.build(entries);
984
+ }
985
+ isIpAllowed(ip) {
986
+ return this._ipAllowed(ip);
717
987
  }
718
988
  _ipAllowed(ip) {
719
- const { list } = DeployerService.buildAllowList(this.setup?.allowed_ips);
720
- if (!list)
721
- return true;
722
- const family = net_1.default.isIP(String(ip ?? ""));
723
- if (!family)
724
- return false;
725
- return list.check(String(ip), family === 6 ? "ipv6" : "ipv4");
989
+ return IpAllowList_1.IpAllowList.allows(IpAllowList_1.IpAllowList.build(this.setup?.allowed_ips).list, ip);
726
990
  }
727
991
  _warnPlaintextUsers() {
728
992
  if (!DeployerService.buildAllowList(this.setup?.allowed_ips).list)
@@ -818,6 +1082,11 @@ class DeployerService extends BaseService_1.BaseService {
818
1082
  return upstreamErr;
819
1083
  return null;
820
1084
  }
1085
+ static _pm2AttributesFor(found, projectState) {
1086
+ const slotAttrs = projectState?.lastDeployed === "blue" ? found.bluegreen?.blue_pm2_attributes : found.bluegreen?.green_pm2_attributes;
1087
+ const list = Array.isArray(slotAttrs) ? slotAttrs : found.pm2_attributes;
1088
+ return Array.isArray(list) ? list.filter((s) => typeof s === "string" && s.length > 0) : [];
1089
+ }
821
1090
  async runPM2(found, projectState) {
822
1091
  let pm2attrs = projectState?.lastDeployed === "blue" ? found.bluegreen?.blue_pm2_attributes : found.bluegreen?.green_pm2_attributes;
823
1092
  const pm2Attrs = Array.isArray(pm2attrs) ? pm2attrs.filter(s => typeof s === "string" && s.length > 0) : found.pm2_attributes;
@@ -884,7 +1153,7 @@ class DeployerService extends BaseService_1.BaseService {
884
1153
  }
885
1154
  static SKIP_DIRS = new Set(["node_modules", ".git", "__tmp"]);
886
1155
  static TEMPLATE_EXTENSIONS = [".js", ".ts", ".json", ".env"];
887
- async applyConfig(dir, config) {
1156
+ async applyConfig(dir, config, ctx) {
888
1157
  if (Object.keys(config).length < 1)
889
1158
  return;
890
1159
  const entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
@@ -895,23 +1164,41 @@ class DeployerService extends BaseService_1.BaseService {
895
1164
  if (DeployerService.SKIP_DIRS.has(entry.name))
896
1165
  continue;
897
1166
  const fullPath = path_1.default.join(dir, entry.name);
898
- await this.applyConfig(fullPath, config);
1167
+ await this.applyConfig(fullPath, config, ctx);
899
1168
  continue;
900
1169
  }
901
1170
  if (entry.isFile()) {
902
1171
  const fullPath = path_1.default.join(dir, entry.name);
903
1172
  const lower = fullPath.toLowerCase();
904
1173
  if (DeployerService.TEMPLATE_EXTENSIONS.some(ext => lower.endsWith(ext)))
905
- await this.processFile(fullPath, config);
1174
+ await this.processFile(fullPath, config, ctx);
906
1175
  }
907
1176
  }
908
1177
  }
909
- async processFile(filePath, config) {
1178
+ async processFile(filePath, config, ctx) {
910
1179
  let content = fs_1.default.readFileSync(filePath, "utf-8");
911
1180
  let hash = crypto_1.default.createHash("md5").update(content).digest("hex");
1181
+ const lowerPath = filePath.toLowerCase();
1182
+ if (ctx?.secretsFile && (lowerPath.endsWith(".js") || lowerPath.endsWith(".cjs")) && content.includes("_{{")) {
1183
+ const t = SecretsInjector_1.SecretsInjector.transform(content, new Set(Object.keys(config)), ctx.secretsFile);
1184
+ if (t.rewritten > 0) {
1185
+ const noShebang = (src) => src.replace(/^#!.*/, "");
1186
+ if (SecretsInjector_1.SecretsInjector.parses(noShebang(content)) && SecretsInjector_1.SecretsInjector.parses(noShebang(t.content)))
1187
+ content = t.content;
1188
+ else
1189
+ (0, LogService_1.logWarn)(`Secrets: ${filePath} can't be rewritten safely (it doesn't compile as CommonJS) — values are substituted as before`);
1190
+ }
1191
+ }
1192
+ let substituted = false;
912
1193
  for (const [key, value] of Object.entries(config)) {
913
- content = content.replaceAll(`_{{${key}}}_`, value);
1194
+ const placeholder = `_{{${key}}}_`;
1195
+ if (content.includes(placeholder)) {
1196
+ substituted = true;
1197
+ content = content.replaceAll(placeholder, () => String(value));
1198
+ }
914
1199
  }
1200
+ if (substituted && ctx?.secretsFile !== undefined && ctx.onDisk)
1201
+ ctx.onDisk.push(filePath);
915
1202
  let hash2 = crypto_1.default.createHash("md5").update(content).digest("hex");
916
1203
  if (hash !== hash2) {
917
1204
  (0, LogService_1.logInfo)("Values was changed in " + filePath);
@@ -1100,10 +1387,14 @@ class DeployerService extends BaseService_1.BaseService {
1100
1387
  });
1101
1388
  }
1102
1389
  try {
1103
- (0, child_process_1.execFileSync)("cp", ["-rf", path_1.default.resolve(destination, "__tmp") + "/.", destination]);
1390
+ (0, child_process_1.execFileSync)("cp", ["-RPf", path_1.default.resolve(destination, "__tmp") + "/.", destination]);
1104
1391
  }
1105
1392
  catch (e) {
1106
1393
  (0, LogService_1.logError)(e);
1394
+ try {
1395
+ fs_1.default.rmSync(path_1.default.resolve(destination, "__tmp"), { recursive: true, force: true });
1396
+ }
1397
+ catch (_) { }
1107
1398
  resolve({ code: 15, message: "Can't copy files", httpStatus: 500 });
1108
1399
  return;
1109
1400
  }
@@ -2,6 +2,13 @@ import { BaseService } from '../BaseService';
2
2
  export interface IDeploymentNotifier extends BaseService {
3
3
  notifyEmailStatus(email: string, status: string, project: string, user: string): Promise<void>;
4
4
  notifySMSStatus(phone: string, text: string, user: string): Promise<void>;
5
+ notifyReview(email: string, info: {
6
+ project: string;
7
+ user: string;
8
+ link: string;
9
+ expiresAt: number;
10
+ mode: "any" | "all";
11
+ }): Promise<boolean>;
5
12
  }
6
13
  export declare class Notifier extends BaseService implements IDeploymentNotifier {
7
14
  SMS_URL: string;
@@ -12,5 +19,12 @@ export declare class Notifier extends BaseService implements IDeploymentNotifier
12
19
  });
13
20
  init(): Promise<void>;
14
21
  notifyEmailStatus(email: string, status: string, project: string, user: string): Promise<void>;
22
+ notifyReview(email: string, info: {
23
+ project: string;
24
+ user: string;
25
+ link: string;
26
+ expiresAt: number;
27
+ mode: "any" | "all";
28
+ }): Promise<boolean>;
15
29
  notifySMSStatus(phone: string, text: string, user: string): Promise<void>;
16
30
  }
@@ -37,6 +37,28 @@ class Notifier extends BaseService_1.BaseService {
37
37
  (0, LogService_1.logError)(e);
38
38
  }
39
39
  }
40
+ async notifyReview(email, info) {
41
+ const esc = (v) => String(v).replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
42
+ const title = `Deploy review: ${info.project} (uploaded by ${info.user})`;
43
+ const text = `<p><b>${esc(info.user)}</b> uploaded a new version of <b>${esc(info.project)}</b>. It is not deployed until it is reviewed`
44
+ + (info.mode === "all" ? " by every reviewer" : "") + `.</p>`
45
+ + `<p><a href="${esc(info.link)}">Review the changes</a> — sign in with your reviewer login, password and 2FA code.</p>`
46
+ + `<p>The link is personal and valid until ${esc(new Date(info.expiresAt).toISOString())}, or until a newer upload replaces it. `
47
+ + `Don't forward it. If you didn't expect this, decline and tell the team.</p>`;
48
+ const token = (0, crypto_1.createHash)("sha256").update(this.SMS_KEY + email + title + text).digest("base64");
49
+ try {
50
+ const response = await __1.Http.post(this.SMS_URL + "/api/mail/send", { to: email, text: title, html: text }, {
51
+ headers: { "authorization": token, "Content-Type": "application/json" }
52
+ });
53
+ if (!response.ok)
54
+ (0, LogService_1.logError)(`Review mail to ${email} failed: HTTP ${response.status ?? "network error"}`);
55
+ return response.ok;
56
+ }
57
+ catch (e) {
58
+ (0, LogService_1.logError)(e);
59
+ return false;
60
+ }
61
+ }
40
62
  async notifySMSStatus(phone, text, user) {
41
63
  const finalText = `${text} (by ${user})`;
42
64
  const token = (0, crypto_1.createHash)("sha256").update(this.SMS_KEY + phone + finalText + "").digest("base64");
@@ -0,0 +1,62 @@
1
+ import { UploadedFile } from "express-fileupload";
2
+ export interface IReviewDecision {
3
+ tokenHash: string;
4
+ decision: "accept" | "decline" | null;
5
+ at: number | null;
6
+ ip: string | null;
7
+ }
8
+ export type TReviewState = "pending" | "deploying" | "deployed" | "failed" | "declined" | "expired";
9
+ export interface IPendingReview {
10
+ project: string;
11
+ state: TReviewState;
12
+ result?: {
13
+ at: number;
14
+ message: string;
15
+ slot?: string | null;
16
+ activeThisDeploy?: boolean;
17
+ };
18
+ sha256: string;
19
+ size: number;
20
+ uploadedBy: string;
21
+ uploadedFrom: string | null;
22
+ uploadedAt: number;
23
+ expiresAt: number;
24
+ mode: "any" | "all";
25
+ reviewers: Record<string, IReviewDecision>;
26
+ }
27
+ export declare class ReviewStore {
28
+ readonly dir: string;
29
+ constructor(projectsPath: string);
30
+ static hashToken(token: string): string;
31
+ private file;
32
+ archivePath(project: string): string;
33
+ lastArchivePath(project: string): string;
34
+ private ensureDir;
35
+ private static sha256File;
36
+ private writeJson;
37
+ create(project: string, file: UploadedFile, meta: {
38
+ uploadedBy: string;
39
+ uploadedFrom: string | null;
40
+ mode: "any" | "all";
41
+ reviewers: string[];
42
+ ttlMs: number;
43
+ }): Promise<{
44
+ pending: IPendingReview;
45
+ tokens: Record<string, string>;
46
+ replaced: boolean;
47
+ }>;
48
+ get(project: string): IPendingReview | null;
49
+ save(pending: IPendingReview): void;
50
+ findByToken(token: string): {
51
+ pending: IPendingReview;
52
+ reviewer: string;
53
+ } | null;
54
+ archiveIntact(pending: IPendingReview): Promise<boolean>;
55
+ journal(project: string, event: string, details: Record<string, unknown>): void;
56
+ dropArchive(project: string): void;
57
+ sweep(): string[];
58
+ remove(project: string): void;
59
+ stageBaseline(project: string, archive: string): void;
60
+ commitBaseline(project: string): void;
61
+ dropStagedBaseline(project: string): void;
62
+ }