badmfck-api-server 6.0.11 → 6.0.13

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 (64) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +247 -79
  3. package/dist/apiServer/APIService.d.ts +3 -1
  4. package/dist/apiServer/APIService.js +25 -1
  5. package/dist/apiServer/LogService.d.ts +2 -0
  6. package/dist/apiServer/LogService.js +10 -8
  7. package/dist/apiServer/MonitorService.d.ts +4 -1
  8. package/dist/apiServer/MonitorService.js +28 -5
  9. package/dist/apiServer/deployment/Activate.js +2 -6
  10. package/dist/apiServer/deployment/Backups.js +3 -2
  11. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  12. package/dist/apiServer/deployment/Bundler.js +178 -0
  13. package/dist/apiServer/deployment/ConfigService.d.ts +6 -0
  14. package/dist/apiServer/deployment/ConfigService.js +17 -1
  15. package/dist/apiServer/deployment/Deploy.js +101 -57
  16. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  17. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  18. package/dist/apiServer/deployment/Deployer.d.ts +1 -0
  19. package/dist/apiServer/deployment/Deployer.js +7 -5
  20. package/dist/apiServer/deployment/DeployerService.d.ts +27 -2
  21. package/dist/apiServer/deployment/DeployerService.js +129 -30
  22. package/dist/apiServer/deployment/HashPassword.js +2 -2
  23. package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
  24. package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
  25. package/dist/apiServer/deployment/Restore.js +9 -8
  26. package/dist/apiServer/deployment/SecretsInjector.js +2 -1
  27. package/dist/apiServer/deployment/SetupConfigWizard.js +38 -2
  28. package/dist/apiServer/deployment/Status.js +5 -8
  29. package/dist/apiServer/deployment/Watchdog.js +1 -1
  30. package/dist/apiServer/deployment/Wizards.js +16 -11
  31. package/dist/apiServer/deployment/cli.js +33 -14
  32. package/dist/apiServer/deployment/cliCommon.d.ts +13 -1
  33. package/dist/apiServer/deployment/cliCommon.js +50 -2
  34. package/dist/apiServer/deployment/resolveConfig.d.ts +4 -1
  35. package/dist/apiServer/deployment/resolveConfig.js +23 -2
  36. package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
  37. package/dist/apiServer/external/MicroserviceClient.js +90 -10
  38. package/dist/apiServer/external/MicroserviceHost.d.ts +35 -8
  39. package/dist/apiServer/external/MicroserviceHost.js +148 -55
  40. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  41. package/dist/apiServer/helper/AppDataPath.js +81 -0
  42. package/dist/apiServer/helper/ClientIp.d.ts +1 -0
  43. package/dist/apiServer/helper/ClientIp.js +5 -0
  44. package/dist/apiServer/helper/Trace.d.ts +8 -0
  45. package/dist/apiServer/helper/Trace.js +30 -0
  46. package/dist/apiServer/helper/Validator.d.ts +1 -0
  47. package/dist/apiServer/helper/Validator.js +21 -18
  48. package/dist/apiServer/http/Http.d.ts +1 -0
  49. package/dist/apiServer/http/Http.js +5 -2
  50. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  51. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  52. package/dist/apiServer/monitor/MonitorAuth.js +8 -5
  53. package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
  54. package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
  55. package/dist/apiServer/monitor/index.html +66 -66
  56. package/dist/apiServer/security/BlockedIps.js +10 -14
  57. package/dist/apiServer/structures/Interfaces.d.ts +2 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.js +5 -1
  60. package/package.json +21 -6
  61. package/bluegreen.help.md +0 -392
  62. package/cocroach.help.md +0 -191
  63. package/connections.help.md +0 -0
  64. package/monitoring.help.md +0 -350
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DeployerService = exports.REQ_DEPLOYMENT_RESTORE = 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;
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
7
  const badmfck_signal_1 = require("badmfck-signal");
8
8
  const BaseService_1 = require("../BaseService");
9
9
  const ConfigService_1 = require("./ConfigService");
@@ -27,8 +27,13 @@ const IpAllowList_1 = require("../helper/IpAllowList");
27
27
  const _TSetup = {
28
28
  users: [{
29
29
  login: "",
30
- password: ""
30
+ password: "",
31
+ $__password_optional: true,
32
+ publicKey: "",
33
+ $__publicKey_optional: true,
31
34
  }],
35
+ require_signature: false,
36
+ $__require_signature_optional: true,
32
37
  watchdog: true,
33
38
  $__watchdog_optional: true,
34
39
  notifier: {
@@ -57,6 +62,7 @@ exports.REQ_DEPLOYMENT_SWITCH = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYE
57
62
  exports.REQ_DEPLOYMENT_STATUS = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_STATUS");
58
63
  exports.REQ_DEPLOYMENT_SLOT = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SLOT");
59
64
  exports.REQ_DEPLOYMENT_BACKUPS = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_BACKUPS");
65
+ exports.REQ_DEPLOYER_PUBLIC_KEY = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_PUBLIC_KEY");
60
66
  exports.REQ_DEPLOYMENT_RESTORE = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_RESTORE");
61
67
  class DeployerService extends BaseService_1.BaseService {
62
68
  static MAX_HISTORY = 200;
@@ -107,6 +113,7 @@ class DeployerService extends BaseService_1.BaseService {
107
113
  exports.REQ_DEPLOYMENT_SLOT.listener = async (data) => this.slotState(data);
108
114
  exports.REQ_DEPLOYMENT_BACKUPS.listener = async (data) => this.listBackups(data);
109
115
  exports.REQ_DEPLOYMENT_RESTORE.listener = async (data) => this.restoreBackup(data);
116
+ exports.REQ_DEPLOYER_PUBLIC_KEY.listener = async (login) => (this.setup?.users ?? []).find(u => u.login === login)?.publicKey || null;
110
117
  await this._checkReviewSetup();
111
118
  ConfigService_1.S_CONFIG_UPDATED.subscribe(() => { this._checkReviewSetup(); });
112
119
  }
@@ -114,7 +121,7 @@ class DeployerService extends BaseService_1.BaseService {
114
121
  try {
115
122
  const plain = (this.setup?.reviewers ?? []).filter(r => r?.login && !PasswordHash_1.PasswordHash.isHash(r.password)).map(r => r.login);
116
123
  if (plain.length)
117
- (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`);
124
+ (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`);
118
125
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
119
126
  for (const c of configurations.values()) {
120
127
  if (!c?.review)
@@ -196,7 +203,7 @@ class DeployerService extends BaseService_1.BaseService {
196
203
  setInterval(() => { this._reloadSetup(); }, 60_000).unref();
197
204
  }
198
205
  async proceed(data) {
199
- const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
206
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
200
207
  const user = auth.user;
201
208
  if (!user) {
202
209
  (0, LogService_1.logError)("Deploy rejected: user auth failed");
@@ -349,7 +356,7 @@ class DeployerService extends BaseService_1.BaseService {
349
356
  }
350
357
  }
351
358
  if (found.unpack) {
352
- const unpackResult = await this.unpack(found.destination, uploadPath, found.install, found.ignoreDirectoryClean);
359
+ const unpackResult = await this.unpack(found.destination, uploadPath, found.install, found.ignoreDirectoryClean, found.omitDev, realName);
353
360
  if (__1.ErrorUtils.isError(unpackResult)) {
354
361
  if (found.email && found.email.length > 0) {
355
362
  for (let email of found.email) {
@@ -456,7 +463,7 @@ class DeployerService extends BaseService_1.BaseService {
456
463
  const conf = found;
457
464
  const liveness = found.liveness;
458
465
  setTimeout(async () => {
459
- const result = await __1.Http.get(liveness);
466
+ const result = await __1.Http.get(liveness, { retry: { enabled: true } });
460
467
  if (!result.ok) {
461
468
  (0, LogService_1.logError)("Liveness check failed for", conf.name);
462
469
  if (conf.email && conf.email.length > 0) {
@@ -644,7 +651,7 @@ class DeployerService extends BaseService_1.BaseService {
644
651
  }
645
652
  finish("deployed", {
646
653
  message: res?.data?.bluegreen && !res.data.activeThisDeploy
647
- ? `Deployed to slot ${res.data.slot} — not live yet: run "badmfck activate" to switch traffic.`
654
+ ? `Deployed to slot ${res.data.slot} — not live yet: run "bmfk activate" to switch traffic.`
648
655
  : "Deployed and live.",
649
656
  slot: res?.data?.slot ?? null, activeThisDeploy: res?.data?.activeThisDeploy,
650
657
  });
@@ -665,7 +672,7 @@ class DeployerService extends BaseService_1.BaseService {
665
672
  }
666
673
  }
667
674
  async switchSlot(data) {
668
- const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
675
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
669
676
  const user = auth.user;
670
677
  if (!user) {
671
678
  (0, LogService_1.logError)("Switch rejected: user auth failed");
@@ -751,7 +758,7 @@ class DeployerService extends BaseService_1.BaseService {
751
758
  }
752
759
  }
753
760
  async status(data) {
754
- const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
761
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
755
762
  const user = auth.user;
756
763
  if (!user) {
757
764
  return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
@@ -785,7 +792,7 @@ class DeployerService extends BaseService_1.BaseService {
785
792
  return DeployerService._isBlueGreen(found) ? dest : path_1.default.dirname(dest);
786
793
  }
787
794
  async listBackups(data) {
788
- const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
795
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
789
796
  const user = auth.user;
790
797
  if (!user) {
791
798
  return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
@@ -816,7 +823,7 @@ class DeployerService extends BaseService_1.BaseService {
816
823
  } };
817
824
  }
818
825
  async restoreBackup(data) {
819
- const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
826
+ const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
820
827
  const user = auth.user;
821
828
  if (!user) {
822
829
  (0, LogService_1.logError)("Restore rejected: user auth failed");
@@ -969,7 +976,7 @@ class DeployerService extends BaseService_1.BaseService {
969
976
  if (PasswordHash_1.PasswordHash.isHash(config.token))
970
977
  return (await PasswordHash_1.PasswordHash.verify(token, config.token)) ? { config } : {};
971
978
  if (config.token && this.tokensMatch(config.token, token))
972
- (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 badmfck project-token --hash`);
979
+ (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`);
973
980
  return {};
974
981
  }
975
982
  tokensMatch(a, b) {
@@ -989,11 +996,20 @@ class DeployerService extends BaseService_1.BaseService {
989
996
  _warnPlaintextUsers() {
990
997
  if (!DeployerService.buildAllowList(this.setup?.allowed_ips).list)
991
998
  (0, LogService_1.logWarn)("Deployer: allowed_ips is not set in setup.json — deploys are accepted from any address");
992
- const plain = (this.setup?.users ?? []).filter(u => u?.login && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
999
+ const users = this.setup?.users ?? [];
1000
+ const plain = users.filter(u => u?.login && !u.publicKey && u.password && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
1001
+ const keyless = users.filter(u => u?.login && !u.publicKey && !u.password).map(u => u.login);
1002
+ if (keyless.length)
1003
+ (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`);
1004
+ const passwordUsers = users.filter(u => u?.login && !u.publicKey && u.password).map(u => u.login);
1005
+ if (this.setup?.require_signature && passwordUsers.length)
1006
+ (0, LogService_1.logWarn)(`Deployer: require_signature is on — password users ${passwordUsers.map(l => '"' + l + '"').join(", ")} can't sign in until they get a publicKey`);
1007
+ else if (!this.setup?.require_signature && passwordUsers.length && users.some(u => u.publicKey))
1008
+ (0, LogService_1.logInfo)(`Deployer: ${passwordUsers.length} user(s) still sign in with a password — once all have a publicKey, set "require_signature": true`);
993
1009
  if (plain.length)
994
- (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`);
1010
+ (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`);
995
1011
  }
996
- async _checkUserAuth(authHeader, loginHeader, ip) {
1012
+ async _checkUserAuth(authHeader, loginHeader, ip, sig) {
997
1013
  if (!this._ipAllowed(ip)) {
998
1014
  (0, LogService_1.logWarn)(`Deployer: request refused from ${ip ?? "unknown"} — not in allowed_ips`);
999
1015
  return { error: "Forbidden.", status: 403 };
@@ -1001,10 +1017,20 @@ class DeployerService extends BaseService_1.BaseService {
1001
1017
  const from = ip ?? "unknown";
1002
1018
  const shown = (v) => JSON.stringify(v.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 64));
1003
1019
  const refuse = (reason) => { (0, LogService_1.logWarn)(`Deployer auth failed from ${from}: ${reason}`); return {}; };
1004
- if (!authHeader)
1005
- return refuse("no Authorization header");
1006
1020
  if (!this.setup)
1007
1021
  return refuse("setup.json is not loaded");
1022
+ if (sig?.present) {
1023
+ if (sig.error || !sig.kid)
1024
+ return refuse(`signature refused — ${sig.error ?? "no key id"}`);
1025
+ const user = (this.setup.users ?? []).find(u => u.login === sig.kid);
1026
+ if (!user?.publicKey)
1027
+ return refuse(`signature by ${shown(sig.kid)}, who has no publicKey in setup.json`);
1028
+ return { user: user };
1029
+ }
1030
+ if (this.setup.require_signature)
1031
+ return refuse("unsigned request — require_signature is on in setup.json; the client needs a privateKey in deploy.json (npx bmfk deploy-key)");
1032
+ if (!authHeader)
1033
+ return refuse("no Authorization header");
1008
1034
  const token = authHeader.split(" ").pop() ?? "";
1009
1035
  if (!token)
1010
1036
  return refuse("empty Authorization header");
@@ -1016,23 +1042,27 @@ class DeployerService extends BaseService_1.BaseService {
1016
1042
  const user = users.find(u => u.login === login);
1017
1043
  if (!user)
1018
1044
  return refuse(`unknown login ${shown(login)}`);
1045
+ if (user.publicKey)
1046
+ return refuse(`${shown(login)} has a publicKey — only signed requests are accepted for them; the client needs its privateKey in deploy.json`);
1047
+ if (!user.password)
1048
+ return refuse(`${shown(login)} has neither a password nor a publicKey in setup.json`);
1019
1049
  if (PasswordHash_1.PasswordHash.isHash(user.password))
1020
- return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user } : refuse(`wrong password for ${shown(login)} (or the client's login/password differ from setup.json)`);
1050
+ 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)`);
1021
1051
  }
1022
1052
  let plainMatch = null;
1023
1053
  for (const user of users) {
1024
- if (PasswordHash_1.PasswordHash.isHash(user.password) || !user.password)
1054
+ if (user.publicKey || !user.password || PasswordHash_1.PasswordHash.isHash(user.password))
1025
1055
  continue;
1026
1056
  const expected = crypto_1.default.createHash("sha256").update(user.login + ":" + user.password).digest("hex");
1027
1057
  if (this.tokensMatch(token, expected))
1028
1058
  plainMatch = user.login;
1029
1059
  }
1030
1060
  if (plainMatch) {
1031
- (0, LogService_1.logError)(`Deployer: "${plainMatch}" sent the right credentials, but setup.json stores the password as plain text — refused; store a hash: npx badmfck hash-password --deployer`);
1061
+ (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`);
1032
1062
  return {};
1033
1063
  }
1034
1064
  if (!login)
1035
- return refuse("no X-Deployer-Login header — the client runs an old badmfck CLI; update it");
1065
+ return refuse("no X-Deployer-Login header — the client runs an old CLI; update it");
1036
1066
  return refuse(`wrong password for ${shown(login)}`);
1037
1067
  }
1038
1068
  static _extractPort(config) {
@@ -1047,6 +1077,41 @@ class DeployerService extends BaseService_1.BaseService {
1047
1077
  }
1048
1078
  return "";
1049
1079
  }
1080
+ static _mainPath(destination) {
1081
+ let main;
1082
+ try {
1083
+ main = JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(destination, "package.json"), "utf-8")).main || "index.js";
1084
+ }
1085
+ catch {
1086
+ return null;
1087
+ }
1088
+ if (main.startsWith("./"))
1089
+ main = main.substring(2);
1090
+ return destination.endsWith("/") ? destination + main : destination + "/" + main;
1091
+ }
1092
+ static _withSourceMaps(extra) {
1093
+ const FLAG = "--enable-source-maps";
1094
+ const has = (v) => v.split(/\s+/).includes(FLAG);
1095
+ const inlineIdx = extra.findIndex(a => a.startsWith("--node-args="));
1096
+ if (inlineIdx !== -1) {
1097
+ const val = extra[inlineIdx].slice("--node-args=".length);
1098
+ if (has(val))
1099
+ return extra;
1100
+ const next = [...extra];
1101
+ next[inlineIdx] = `--node-args=${(val + " " + FLAG).trim()}`;
1102
+ return next;
1103
+ }
1104
+ const splitIdx = extra.findIndex(a => a === "--node-args");
1105
+ if (splitIdx !== -1 && splitIdx + 1 < extra.length) {
1106
+ const val = extra[splitIdx + 1];
1107
+ if (has(val))
1108
+ return extra;
1109
+ const next = [...extra];
1110
+ next[splitIdx + 1] = (val + " " + FLAG).trim();
1111
+ return next;
1112
+ }
1113
+ return [...extra, `--node-args=${FLAG}`];
1114
+ }
1050
1115
  async _renderNginx(found, projectName, activePort) {
1051
1116
  if (!found.nginx?.config_dir)
1052
1117
  return null;
@@ -1101,12 +1166,16 @@ class DeployerService extends BaseService_1.BaseService {
1101
1166
  const extra = rawExtra.filter(a => !/^--no-autorestart(=.*)?$/.test(a));
1102
1167
  if (extra.length !== rawExtra.length)
1103
1168
  (0, LogService_1.logWarn)(`Ignored "--no-autorestart" in pm2 attributes for "${found.name}" — autorestart is force-kept ON so the slot self-recovers.`);
1169
+ const entryMain = DeployerService._mainPath(found.destination);
1170
+ const hasMap = !!entryMain && fs_1.default.existsSync(entryMain + ".map");
1104
1171
  const ecoJs = path_1.default.resolve(found.destination, "ecosystem.config.js");
1105
1172
  const ecoCjs = path_1.default.resolve(found.destination, "ecosystem.config.cjs");
1106
1173
  const ecosystem = fs_1.default.existsSync(ecoJs) ? ecoJs
1107
1174
  : fs_1.default.existsSync(ecoCjs) ? ecoCjs
1108
1175
  : null;
1109
1176
  if (ecosystem) {
1177
+ if (hasMap)
1178
+ (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`);
1110
1179
  (0, child_process_1.execFileSync)("pm2", ["startOrReload", ecosystem, "--update-env", ...extra]);
1111
1180
  this._verifyAutorestart(found.name);
1112
1181
  resolve(null);
@@ -1120,19 +1189,15 @@ class DeployerService extends BaseService_1.BaseService {
1120
1189
  break;
1121
1190
  }
1122
1191
  }
1123
- const packageJson = JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(found.destination, "package.json")).toString());
1124
- let main = packageJson.main || "index.js";
1125
- if (main.startsWith("./"))
1126
- main = main.substring(2);
1127
- if (!found.destination.endsWith("/"))
1128
- main = "/" + main;
1192
+ const script = entryMain ?? found.destination + "/index.js";
1129
1193
  if (running) {
1130
1194
  try {
1131
1195
  (0, child_process_1.execFileSync)("pm2", ["delete", found.name]);
1132
1196
  }
1133
1197
  catch { }
1134
1198
  }
1135
- (0, child_process_1.execFileSync)("pm2", ["start", found.destination + main, "--name", found.name, ...extra]);
1199
+ const startExtra = hasMap ? DeployerService._withSourceMaps(extra) : extra;
1200
+ (0, child_process_1.execFileSync)("pm2", ["start", script, "--name", found.name, ...startExtra]);
1136
1201
  this._verifyAutorestart(found.name);
1137
1202
  resolve(null);
1138
1203
  }
@@ -1312,7 +1377,39 @@ class DeployerService extends BaseService_1.BaseService {
1312
1377
  }
1313
1378
  }
1314
1379
  static MIGRATE_TIMEOUT_MS = 10 * 60 * 1000;
1315
- async unpack(destination, uploadedFile, install, ignoreDirectoryClean) {
1380
+ static _stampProjectName(dir, projectName) {
1381
+ const problem = (0, ConfigService_1.projectNameProblem)(projectName);
1382
+ if (problem) {
1383
+ (0, LogService_1.logWarn)(`${problem} — package.json "name" left as it is`);
1384
+ return;
1385
+ }
1386
+ for (const file of ["package.json", "package-lock.json"]) {
1387
+ const p = path_1.default.resolve(dir, file);
1388
+ if (!fs_1.default.existsSync(p))
1389
+ continue;
1390
+ try {
1391
+ const text = fs_1.default.readFileSync(p, "utf-8");
1392
+ const doc = JSON.parse(text);
1393
+ let changed = false;
1394
+ if (doc.name !== projectName) {
1395
+ doc.name = projectName;
1396
+ changed = true;
1397
+ }
1398
+ if (file === "package-lock.json" && doc.packages?.[""] && doc.packages[""].name !== projectName) {
1399
+ doc.packages[""].name = projectName;
1400
+ changed = true;
1401
+ }
1402
+ if (!changed)
1403
+ continue;
1404
+ const indent = /^\{\n(\t| +)/.exec(text)?.[1] ?? "\t";
1405
+ fs_1.default.writeFileSync(p, JSON.stringify(doc, null, indent) + "\n");
1406
+ }
1407
+ catch (e) {
1408
+ (0, LogService_1.logWarn)(`Cannot set the project name in ${file}: ${e?.message ?? e}`);
1409
+ }
1410
+ }
1411
+ }
1412
+ async unpack(destination, uploadedFile, install, ignoreDirectoryClean, omitDev, projectName) {
1316
1413
  return new Promise((resolve) => {
1317
1414
  const unsafeEntry = DeployerService._unsafeArchiveEntry(uploadedFile);
1318
1415
  if (unsafeEntry) {
@@ -1357,6 +1454,8 @@ class DeployerService extends BaseService_1.BaseService {
1357
1454
  resolve({ code: 59, message: "Archive rejected: a symlink points outside the destination.", details: escaping, httpStatus: 400 });
1358
1455
  return;
1359
1456
  }
1457
+ if (projectName)
1458
+ DeployerService._stampProjectName(path_1.default.resolve(destination, "__tmp"), projectName);
1360
1459
  if (install) {
1361
1460
  try {
1362
1461
  const tmpDir = path_1.default.resolve(destination, "__tmp");
@@ -1367,7 +1466,7 @@ class DeployerService extends BaseService_1.BaseService {
1367
1466
  "Commit and include package-lock.json for `npm ci` (deterministic + faster).");
1368
1467
  }
1369
1468
  const npmCmd = useCi ? "ci" : "i";
1370
- (0, child_process_1.execFileSync)("npm", ["--prefix", tmpDir, npmCmd, "--ignore-scripts"]);
1469
+ (0, child_process_1.execFileSync)("npm", ["--prefix", tmpDir, npmCmd, "--ignore-scripts", ...(omitDev ? ["--omit=dev"] : [])]);
1371
1470
  }
1372
1471
  catch (e) {
1373
1472
  (0, LogService_1.logError)(e);
@@ -87,7 +87,7 @@ async function HashPassword(target) {
87
87
  console.log(green(bold("✓ Put this in the config instead of the plain password:")));
88
88
  console.log(`\n { "login": ${JSON.stringify(login)}, "password": ${JSON.stringify(hash)} }\n`);
89
89
  if (target === "deployer")
90
- console.log(yellow(" Deployer users stored as a hash need an up-to-date badmfck CLI on the deploying machine."));
90
+ console.log(yellow(" Deployer users stored as a hash need an up-to-date bmfk CLI on the deploying machine."));
91
91
  console.log(dim(" The hash is salted — running this again for the same password gives a different, equally valid hash."));
92
92
  }
93
93
  }
@@ -109,7 +109,7 @@ async function ProjectToken(mode) {
109
109
  process.exit(1);
110
110
  }
111
111
  if (token.length < 32)
112
- console.log(yellow(` ⚠ This token is short (${token.length} chars). Consider generating a new one: npx badmfck project-token`));
112
+ console.log(yellow(` ⚠ This token is short (${token.length} chars). Consider generating a new one: npx bmfk project-token`));
113
113
  }
114
114
  const hash = await PasswordHash_1.PasswordHash.hash(token);
115
115
  console.log("");
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.MigrateConfigsWizard = MigrateConfigsWizard;
7
7
  const fs_1 = __importDefault(require("fs"));
8
+ const ConfigService_1 = require("./ConfigService");
8
9
  const path_1 = __importDefault(require("path"));
9
10
  const crypto_1 = __importDefault(require("crypto"));
10
11
  const process_1 = require("process");
@@ -68,9 +69,9 @@ async function MigrateConfigsWizard(folder, assumeYes = false) {
68
69
  }
69
70
  if (u && plain(u.password)) {
70
71
  if (u.password === u.login)
71
- plan.notes.push(`deployer user "${u.login}": the password is the same as the login — change it (npx badmfck hash-password --deployer, and the client's deploy.json)`);
72
+ plan.notes.push(`deployer user "${u.login}": the password is the same as the login — change it (npx bmfk hash-password --deployer, and the client's deploy.json)`);
72
73
  else if (MonitorAuth_1.MonitorAuth.passwordPolicyError(u.password))
73
- plan.notes.push(`deployer user "${u.login}": password shorter than 12 characters — change it (npx badmfck hash-password --deployer, and the client's deploy.json)`);
74
+ plan.notes.push(`deployer user "${u.login}": password shorter than 12 characters — change it (npx bmfk hash-password --deployer, and the client's deploy.json)`);
74
75
  const secret = sha256(u.login + ":" + u.password);
75
76
  plan.changes.push({ file: plan.file, label: `deployer user "${u.login}"`, secret,
76
77
  apply: (d, h) => { d.users[i].password = h; }, read: d => d.users[i].password });
@@ -107,9 +108,12 @@ async function MigrateConfigsWizard(folder, assumeYes = false) {
107
108
  if (!doc || typeof doc !== "object" || typeof doc.name !== "string" || typeof doc.token !== "string")
108
109
  continue;
109
110
  const plan = { file, doc, changes: [], notes: [] };
111
+ const nameProblem = (0, ConfigService_1.projectNameProblem)(doc.name);
112
+ if (nameProblem)
113
+ plan.notes.push(`${nameProblem} — the deployer ignores this project until it is renamed`);
110
114
  if (plain(doc.token)) {
111
115
  if (doc.token.length < 32)
112
- plan.notes.push(`project "${doc.name}": short token (${doc.token.length} chars) — consider a new one: npx badmfck project-token`);
116
+ plan.notes.push(`project "${doc.name}": short token (${doc.token.length} chars) — consider a new one: npx bmfk project-token`);
113
117
  plan.changes.push({ file, label: `project token "${doc.name}"`, secret: doc.token,
114
118
  apply: (d, h) => { d.token = h; }, read: d => d.token });
115
119
  }
@@ -124,9 +128,9 @@ async function MigrateConfigsWizard(folder, assumeYes = false) {
124
128
  (doc.monitor ?? []).forEach((u, i) => {
125
129
  if (u && plain(u.password)) {
126
130
  if (u.password === u.login)
127
- plan.notes.push(`monitor user "${u.login}": the password is the same as the login — change it later (npx badmfck access-config)`);
131
+ plan.notes.push(`monitor user "${u.login}": the password is the same as the login — change it later (npx bmfk access-config)`);
128
132
  else if (MonitorAuth_1.MonitorAuth.passwordPolicyError(u.password))
129
- plan.notes.push(`monitor user "${u.login}": password shorter than 12 characters — change it later (npx badmfck access-config)`);
133
+ plan.notes.push(`monitor user "${u.login}": password shorter than 12 characters — change it later (npx bmfk access-config)`);
130
134
  plan.changes.push({ file: plan.file, label: `monitor user "${u.login}"`, secret: u.password,
131
135
  apply: (d, h) => { d.monitor[i].password = h; }, read: d => d.monitor[i].password });
132
136
  }
@@ -23,7 +23,7 @@ async function ProjectConfigWizard() {
23
23
  const section = (title) => console.log("\n" + bold(title));
24
24
  console.log(bold("\nNew project config for the deployer") + dim(" (Enter keeps the value in brackets)"));
25
25
  section("Project");
26
- const name = await (0, cliPrompt_1.askValid)("Name", "", v => /^[A-Za-z0-9._-]+$/.test(v) ? null : "letters, digits, '.', '_' and '-' only");
26
+ const name = await (0, cliPrompt_1.askValid)("Name (e.g. api.gateway.example.com)", "", v => (0, ConfigService_1.projectNameProblem)(v));
27
27
  const description = await (0, cliPrompt_1.ask)("Description", "");
28
28
  const destination = await (0, cliPrompt_1.askValid)("Destination folder on the server", `/var/node/${name}`, v => !path_1.default.isAbsolute(v) ? "must be an absolute path" : /^\/(var|etc|home|usr|opt|srv|tmp|root)?\/?$/.test(v) ? "pick a folder of its own, not a system folder" : null);
29
29
  section("Project token");
@@ -46,6 +46,7 @@ async function ProjectConfigWizard() {
46
46
  section("Deploy steps");
47
47
  const unpack = await (0, cliPrompt_1.yes)("Unpack the uploaded archive", true);
48
48
  const install = unpack ? await (0, cliPrompt_1.yes)("Install dependencies (npm ci)", true) : false;
49
+ const omitDev = install ? await (0, cliPrompt_1.yes)("Skip devDependencies on the server (npm ci --omit=dev)", false) : false;
49
50
  const ignoreDirectoryClean = unpack ? !(await (0, cliPrompt_1.yes)("Clean the destination before unpacking", true)) : false;
50
51
  const backup = await (0, cliPrompt_1.yes)("Back up the current version before each deploy", true);
51
52
  const migrate = await (0, cliPrompt_1.yes)("Run `npm run migrate` before starting", false);
@@ -71,6 +72,7 @@ async function ProjectConfigWizard() {
71
72
  const cfg = {
72
73
  name, destination, description, token: tokenHash,
73
74
  unpack, ignoreDirectoryClean, backup, install, migrate, pm2,
75
+ ...(omitDev ? { omitDev } : {}),
74
76
  ...(pm2Attributes.length ? { pm2_attributes: pm2Attributes } : {}),
75
77
  ...(chmod ? { chmod } : {}),
76
78
  ...(email.length ? { email } : {}),
@@ -95,7 +97,7 @@ async function ProjectConfigWizard() {
95
97
  }
96
98
  section("Secrets file — keeps config values out of the deployed code");
97
99
  if (Object.keys(config).length && await (0, cliPrompt_1.yes)("Store config values in a secrets file outside the deploy folder?", true)) {
98
- const where = await (0, cliPrompt_1.ask)(" folder (empty = secrets_dir from the deployer's setup.json)", "");
100
+ const where = await (0, cliPrompt_1.ask)(" folder (empty = secrets_dir from the deployer's setup.json, else /var/bmfk/<project>)", "");
99
101
  if (where && (!path_1.default.isAbsolute(where) || path_1.default.resolve(where).startsWith(path_1.default.resolve(destination) + path_1.default.sep)))
100
102
  console.log(yellow(" ⚠ The folder must be absolute and outside the deploy folder — the deployer will refuse this project as is."));
101
103
  cfg.secrets = where ? { dir: where } : {};
@@ -9,9 +9,9 @@ const cliCommon_1 = require("./cliCommon");
9
9
  async function Restore(opt, backupName, assumeYes = false) {
10
10
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
11
11
  const { red, yellow, green, dim, bold } = (0, cliCommon_1.palette)();
12
- const headers = (0, cliCommon_1.deployerHeaders)(opt);
13
12
  const fail = (msg) => { console.error(red(bold("✗ ")) + msg); process.exit(1); };
14
- const lr = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, { headers, timeoutMs: 30000, retry: { enabled: false } });
13
+ const listUrl = (0, cliCommon_1.deployerUrl)(opt, "backups"), listBody = { name: opt.name };
14
+ const lr = await __1.Http.post(listUrl, listBody, { headers: (0, cliCommon_1.deployerHeaders)(opt, listUrl, listBody), timeoutMs: 30000, retry: { enabled: false } });
15
15
  const lerr = (0, cliCommon_1.responseError)(lr);
16
16
  if (lerr)
17
17
  fail("Cannot list backups: " + lerr);
@@ -25,11 +25,11 @@ async function Restore(opt, backupName, assumeYes = false) {
25
25
  if (backupName) {
26
26
  chosen = list.find(b => b.name === backupName);
27
27
  if (!chosen)
28
- fail(`Backup "${backupName}" not found. Run \`badmfck backups\` to see the list.`);
28
+ fail(`Backup "${backupName}" not found. Run \`bmfk backups\` to see the list.`);
29
29
  }
30
30
  else {
31
31
  if (!rl)
32
- fail("Backup name is required when not running in a terminal: badmfck restore <backup-name> --yes");
32
+ fail("Backup name is required when not running in a terminal: bmfk restore <backup-name> --yes");
33
33
  console.log("");
34
34
  list.forEach((b, i) => console.log(` [${i + 1}] ${b.name} ${dim("ver")} ${b.appVersion ?? "?"} ${dim((0, cliCommon_1.fmtDate)(b.createdAt))}`));
35
35
  while (!chosen) {
@@ -48,7 +48,7 @@ async function Restore(opt, backupName, assumeYes = false) {
48
48
  console.log(` ${dim("slot:")} ${chosen.slot} ${dim("active:")} ${info.activeSlot ?? "?"}`);
49
49
  console.log(live
50
50
  ? yellow(bold(" ⚠ LIVE: production traffic gets the restored code immediately"))
51
- : dim(` not live — the slot will need: badmfck activate ${chosen.slot}`));
51
+ : dim(` not live — the slot will need: bmfk activate ${chosen.slot}`));
52
52
  console.log(dim(" current contents are backed up first, so this can be undone"));
53
53
  if (!assumeYes) {
54
54
  if (!rl)
@@ -64,7 +64,8 @@ async function Restore(opt, backupName, assumeYes = false) {
64
64
  rl?.close();
65
65
  }
66
66
  console.log(dim("\nRestoring…"));
67
- const rr = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "restore"), { name: opt.name, token: opt.token, backup: chosen.name }, { headers, timeoutMs: 10 * 60 * 1000, retry: { enabled: false } });
67
+ const restoreUrl = (0, cliCommon_1.deployerUrl)(opt, "restore"), restoreBody = { name: opt.name, token: opt.token, backup: chosen.name };
68
+ const rr = await __1.Http.post(restoreUrl, restoreBody, { headers: (0, cliCommon_1.deployerHeaders)(opt, restoreUrl, restoreBody), timeoutMs: 10 * 60 * 1000, retry: { enabled: false } });
68
69
  const rerr = (0, cliCommon_1.responseError)(rr);
69
70
  if (rerr)
70
71
  fail("Restore failed: " + rerr);
@@ -80,9 +81,9 @@ async function Restore(opt, backupName, assumeYes = false) {
80
81
  console.log(` ${dim("live: ")} ${d.live ? bold("yes") : "no"}`);
81
82
  console.log(` ${dim("pm2: ")} ${d.pm2Error ? yellow(d.pm2Error) : d.pm2Restarted ? "restarted" : "not used"}`);
82
83
  if (d.preRestoreBackup)
83
- console.log(` ${dim("undo with: ")} badmfck restore ${d.preRestoreBackup}`);
84
+ console.log(` ${dim("undo with: ")} bmfk restore ${d.preRestoreBackup}`);
84
85
  if (!d.live && d.slot)
85
- console.log(` ${dim("next: ")} badmfck activate ${d.slot}`);
86
+ console.log(` ${dim("next: ")} bmfk activate ${d.slot}`);
86
87
  console.log(line);
87
88
  console.log("");
88
89
  }
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.SecretsInjector = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
+ const AppDataPath_1 = require("../helper/AppDataPath");
8
9
  const path_1 = __importDefault(require("path"));
9
10
  const vm_1 = __importDefault(require("vm"));
10
11
  const PLACEHOLDER = /_\{\{([A-Za-z0-9_]+)\}\}_/g;
@@ -24,7 +25,7 @@ class SecretsInjector {
24
25
  target = path_1.default.join(dir, `${project}${slot ? "-" + slot : ""}.json`);
25
26
  }
26
27
  else {
27
- return { error: "secrets is enabled, but neither secrets.dir / secrets.file nor secrets_dir in setup.json is set" };
28
+ target = path_1.default.join(AppDataPath_1.AppData.projectDir(project), `secrets${slot ? "-" + slot : ""}.json`);
28
29
  }
29
30
  target = path_1.default.resolve(target);
30
31
  const root = path_1.default.resolve(destinationRoot);
@@ -54,8 +54,15 @@ async function SetupConfigWizard(target) {
54
54
  console.log("\n" + bold("Deployer users") + dim(" (in deploy.json: username + password)"));
55
55
  if (!doc.users.length)
56
56
  console.log(red(" none — nobody can deploy"));
57
- for (const u of doc.users)
58
- console.log(` ${String(u.login).padEnd(20)} ${PasswordHash_1.PasswordHash.isHash(u.password) ? dim("hashed password") : red("PLAIN-TEXT password — refused, set a new one or run migrate-configs")}`);
57
+ for (const u of doc.users) {
58
+ const state = u.publicKey ? green("signing key")
59
+ : !u.password ? red("no password or key — can't sign in")
60
+ : doc.require_signature ? yellow("password — refused, require_signature is on")
61
+ : PasswordHash_1.PasswordHash.isHash(u.password) ? dim("hashed password")
62
+ : red("PLAIN-TEXT password — refused, set a new one or run migrate-configs");
63
+ console.log(` ${String(u.login).padEnd(20)} ${state}`);
64
+ }
65
+ console.log(bold("Signed requests only") + " " + (doc.require_signature ? green("yes") : dim("no — password users still accepted")));
59
66
  console.log(bold("Reviewers"));
60
67
  if (!doc.reviewers?.length)
61
68
  console.log(dim(" none"));
@@ -120,6 +127,35 @@ async function SetupConfigWizard(target) {
120
127
  console.log(green(` ✓ ${login} removed`));
121
128
  changed = true;
122
129
  } },
130
+ "k": { title: "set a deployer user's public key (signed deploys)", run: async () => {
131
+ const u = user(await (0, cliPrompt_1.askValid)(" login", "", v => user(v) ? null : "no such user — add the user first"));
132
+ const key = await (0, cliPrompt_1.askValid)(" public key from `npx bmfk deploy-key` (base64)", "", v => {
133
+ try {
134
+ crypto_1.default.createPublicKey({ key: Buffer.from(v, "base64"), format: "der", type: "spki" });
135
+ return /^MCowBQYDK2VwAyEA/.test(v) ? null : "not an Ed25519 public key";
136
+ }
137
+ catch {
138
+ return "not a public key (base64 SPKI)";
139
+ }
140
+ });
141
+ u.publicKey = key;
142
+ if (u.password) {
143
+ delete u.password;
144
+ console.log(dim(" password removed — the user signs in with the key only"));
145
+ }
146
+ clientsToUpdate.delete(u.login);
147
+ console.log(green(` ✓ ${u.login} signs requests with their key`));
148
+ changed = true;
149
+ } },
150
+ "r": { title: "require signed requests from everyone (on/off)", run: async () => {
151
+ const passwordUsers = doc.users.filter((x) => !x.publicKey).map((x) => x.login);
152
+ if (!doc.require_signature && passwordUsers.length)
153
+ console.log(yellow(` ⚠ ${passwordUsers.join(", ")} have no key yet — they can't deploy once this is on.`));
154
+ doc.require_signature = await (0, cliPrompt_1.yes)(" only signed requests?", !doc.require_signature);
155
+ if (!doc.require_signature)
156
+ delete doc.require_signature;
157
+ changed = true;
158
+ } },
123
159
  "5": { title: "add a reviewer", run: async () => {
124
160
  const login = await (0, cliPrompt_1.askValid)(" login", "", v => !v ? "required" : reviewer(v) ? "already exists" : validLogin(v));
125
161
  const email = await (0, cliPrompt_1.askValid)(" email (gets the review links)", "", v => /^[^\s@]+@[^\s@]+$/.test(v) ? null : "an email address");
@@ -1,12 +1,9 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.Status = Status;
7
- const crypto_1 = __importDefault(require("crypto"));
8
4
  const __1 = require("../..");
9
5
  const resolveConfig_1 = require("./resolveConfig");
6
+ const cliCommon_1 = require("./cliCommon");
10
7
  async function Status(opt) {
11
8
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
12
9
  let statusUrl;
@@ -16,9 +13,9 @@ async function Status(opt) {
16
13
  statusUrl = opt.switch_host.replace(/\/switch\/?$/, "/status");
17
14
  else
18
15
  throw new Error(`Cannot derive status URL from host "${opt.host}" — make sure "host" ends with /add.`);
19
- const authToken = crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
20
- const response = await __1.Http.post(statusUrl, { name: opt.name }, {
21
- headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
16
+ const requestBody = { name: opt.name };
17
+ const response = await __1.Http.post(statusUrl, requestBody, {
18
+ headers: (0, cliCommon_1.deployerHeaders)(opt, statusUrl, requestBody),
22
19
  timeoutMs: 15 * 1000,
23
20
  retry: { enabled: false },
24
21
  });
@@ -70,7 +67,7 @@ async function Status(opt) {
70
67
  console.log(` ${dim("active: ")} ${slotColor(state.active)}`);
71
68
  console.log(` ${dim("lastDeployed:")} ${slotColor(state.lastDeployed)}`);
72
69
  if (entry.readyToSwitch)
73
- console.log(` ${yellow("⚠ " + state.lastDeployed + " is deployed but NOT switched")} ${dim("→ badmfck activate")}`);
70
+ console.log(` ${yellow("⚠ " + state.lastDeployed + " is deployed but NOT switched")} ${dim("→ bmfk activate")}`);
74
71
  const last = Array.isArray(state.history) && state.history.length ? state.history[state.history.length - 1] : null;
75
72
  if (last) {
76
73
  const d = new Date(last.at);
@@ -29,7 +29,7 @@ class Watchdog extends BaseService_1.BaseService {
29
29
  async checkReadiness(config) {
30
30
  if (!config.readiness)
31
31
  return;
32
- const resp = await __1.Http.get(config.readiness);
32
+ const resp = await __1.Http.get(config.readiness, { retry: { enabled: true } });
33
33
  if (resp.ok) {
34
34
  this.statusPassed(config);
35
35
  }