badmfck-api-server 6.0.12 → 6.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/README.md +213 -73
  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/Bundler.d.ts +12 -0
  10. package/dist/apiServer/deployment/Bundler.js +178 -0
  11. package/dist/apiServer/deployment/ConfigService.d.ts +7 -0
  12. package/dist/apiServer/deployment/ConfigService.js +24 -1
  13. package/dist/apiServer/deployment/Deploy.js +96 -54
  14. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +1 -0
  15. package/dist/apiServer/deployment/DeployKeyWizard.js +17 -1
  16. package/dist/apiServer/deployment/DeployerService.d.ts +4 -1
  17. package/dist/apiServer/deployment/DeployerService.js +87 -18
  18. package/dist/apiServer/deployment/HashPassword.js +2 -2
  19. package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
  20. package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
  21. package/dist/apiServer/deployment/Restore.js +5 -5
  22. package/dist/apiServer/deployment/SecretsInjector.js +2 -1
  23. package/dist/apiServer/deployment/SetupConfigWizard.js +1 -1
  24. package/dist/apiServer/deployment/Status.js +1 -1
  25. package/dist/apiServer/deployment/Watchdog.js +1 -1
  26. package/dist/apiServer/deployment/Wizards.js +11 -11
  27. package/dist/apiServer/deployment/cli.js +25 -16
  28. package/dist/apiServer/deployment/cliCommon.d.ts +12 -0
  29. package/dist/apiServer/deployment/cliCommon.js +44 -0
  30. package/dist/apiServer/deployment/resolveConfig.d.ts +2 -0
  31. package/dist/apiServer/deployment/resolveConfig.js +10 -0
  32. package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
  33. package/dist/apiServer/external/MicroserviceClient.js +90 -10
  34. package/dist/apiServer/external/MicroserviceHost.d.ts +36 -8
  35. package/dist/apiServer/external/MicroserviceHost.js +166 -55
  36. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  37. package/dist/apiServer/helper/AppDataPath.js +81 -0
  38. package/dist/apiServer/helper/ClientIp.d.ts +1 -0
  39. package/dist/apiServer/helper/ClientIp.js +5 -0
  40. package/dist/apiServer/helper/Trace.d.ts +8 -0
  41. package/dist/apiServer/helper/Trace.js +30 -0
  42. package/dist/apiServer/helper/Validator.d.ts +1 -0
  43. package/dist/apiServer/helper/Validator.js +21 -18
  44. package/dist/apiServer/http/Http.d.ts +1 -0
  45. package/dist/apiServer/http/Http.js +5 -2
  46. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +2 -1
  47. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +1 -1
  48. package/dist/apiServer/monitor/MonitorAuth.js +8 -5
  49. package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
  50. package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
  51. package/dist/apiServer/monitor/index.html +66 -66
  52. package/dist/apiServer/security/BlockedIps.js +10 -14
  53. package/dist/apiServer/structures/Interfaces.d.ts +2 -0
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.js +3 -1
  56. package/package.json +21 -6
  57. package/bluegreen.help.md +0 -392
  58. package/cocroach.help.md +0 -191
  59. package/connections.help.md +0 -0
  60. package/monitoring.help.md +0 -350
@@ -13,13 +13,19 @@ const undici_1 = require("undici");
13
13
  const resolveConfig_1 = require("./resolveConfig");
14
14
  const cliCommon_1 = require("./cliCommon");
15
15
  const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
16
+ const Bundler_1 = require("./Bundler");
16
17
  async function Deploy(opt) {
17
18
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
18
19
  const archiveName = __1.UID.sha256(opt.name.replaceAll(".", "_")) + ".tar.gz";
19
- console.log("Changing Config to live");
20
+ const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
21
+ const line = dim("─".repeat(60));
22
+ const log = (0, cliCommon_1.stepLog)();
23
+ console.log("");
24
+ console.log(`${bold("▸ DEPLOY")} ${bold(opt.name)} ${dim("→")} ${opt.host}`);
25
+ console.log(line);
20
26
  const config = path_1.default.resolve("src", "Config.ts");
21
27
  if (!fs_1.default.existsSync(config)) {
22
- console.log("Config: src/Config.ts not found — skipping scheme switch");
28
+ log.skip("config", "src/Config.ts not found — scheme switch skipped");
23
29
  }
24
30
  else {
25
31
  const configSrc = fs_1.default.readFileSync(config).toString("utf-8");
@@ -31,13 +37,13 @@ async function Deploy(opt) {
31
37
  });
32
38
  if (replaced > 0) {
33
39
  fs_1.default.writeFileSync(config, updated);
34
- console.log(`Config: switched to live (${replaced} occurrence${replaced === 1 ? "" : "s"})`);
40
+ log.ok("config", `switched to live (${replaced} occurrence${replaced === 1 ? "" : "s"})`);
35
41
  }
36
42
  else if (/\bscheme\s*:\s*Scheme\s*=\s*live\b/.test(configSrc)) {
37
- console.log("Config already in live mode — nothing to change");
43
+ log.ok("config", "already live");
38
44
  }
39
45
  else {
40
- console.warn("Config: no 'scheme: Scheme = local|live' pattern found in " + config +
46
+ log.warn("config", "no 'scheme: Scheme = local|live' pattern found in " + config +
41
47
  " — check the file was not renamed/restructured");
42
48
  }
43
49
  }
@@ -50,21 +56,31 @@ async function Deploy(opt) {
50
56
  parts.push(0);
51
57
  parts[parts.length - 1] += 1;
52
58
  const newVersion = parts.join(".");
53
- console.log(`Bumping version: ${oldVersion} -> ${newVersion}`);
54
59
  pkg.version = newVersion;
55
60
  fs_1.default.writeFileSync(pkgPath, JSON.stringify(pkg, null, "\t") + "\n");
61
+ log.ok("version", `${oldVersion} ${dim("→")} ${bold(newVersion)}`);
56
62
  if (fs_1.default.existsSync(path_1.default.resolve(archiveName))) {
57
63
  fs_1.default.rmSync(path_1.default.resolve(archiveName));
58
- console.log("Removing old archive");
59
64
  }
60
- console.log("Build");
61
- var execResult = run("npm run build");
62
- console.log(execResult);
65
+ const buildStep = log.start("build", "npm run build");
66
+ const build = await exec("npm run build");
67
+ if (build.code !== 0) {
68
+ buildStep.fail(`npm run build failed (exit code ${build.code})`);
69
+ const out = (build.stdout.trim() + "\n" + build.stderr.trim()).trim();
70
+ if (out)
71
+ console.error("\n" + out + "\n");
72
+ process.exit(build.code);
73
+ }
74
+ buildStep.ok();
75
+ for (const l of build.stderr.split(/\r?\n/))
76
+ if (l.trim())
77
+ log.note(l);
63
78
  const items = [];
64
79
  let spaMode = false;
65
80
  const binExists = fs_1.default.existsSync("./bin");
66
81
  if (binExists) {
67
- items.push("./bin");
82
+ if (!opt.bundle)
83
+ items.push("./bin");
68
84
  if (fs_1.default.existsSync("package.json")) {
69
85
  items.push("package.json");
70
86
  }
@@ -74,7 +90,6 @@ async function Deploy(opt) {
74
90
  }
75
91
  else if (fs_1.default.existsSync("./dist") && fs_1.default.existsSync(path_1.default.resolve("dist", "index.html"))) {
76
92
  spaMode = true;
77
- console.log("No ./bin found — using entire ./dist contents as distribution");
78
93
  }
79
94
  const staged = [];
80
95
  if (Array.isArray(opt.includes)) {
@@ -100,9 +115,9 @@ async function Deploy(opt) {
100
115
  for (const s of staged) {
101
116
  const clash = items.some(i => i.replace(/^\.\//, "") === s.dest);
102
117
  if (clash)
103
- console.warn(`Include dest "${s.dest}" collides with an already-archived path — the later entry wins on extraction`);
118
+ log.warn("include", `dest "${s.dest}" collides with an already-archived path — the later entry wins on extraction`);
104
119
  }
105
- if (items.length === 0 && !spaMode && staged.length === 0) {
120
+ if (items.length === 0 && !spaMode && staged.length === 0 && !opt.bundle) {
106
121
  throw new Error("Nothing to archive (no ./bin, no ./dist/index.html, no valid includes)");
107
122
  }
108
123
  const excludes = new Set();
@@ -113,7 +128,7 @@ async function Deploy(opt) {
113
128
  if (trimmed.length === 0 || trimmed.startsWith("#"))
114
129
  return;
115
130
  if (trimmed.startsWith("-")) {
116
- console.warn(`Skipping exclude starting with '-' from ${source}: ${trimmed}`);
131
+ log.warn("exclude", `skipped, starts with '-' (from ${source}): ${trimmed}`);
117
132
  return;
118
133
  }
119
134
  excludes.add(trimmed);
@@ -131,7 +146,22 @@ async function Deploy(opt) {
131
146
  addExclude(ex, "config.excludes");
132
147
  }
133
148
  const excludeArgs = Array.from(excludes).map(p => `--exclude=${p}`);
134
- const tarArgs = ["-czvf", archiveName, ...excludeArgs];
149
+ let bundle = null;
150
+ if (opt.bundle) {
151
+ const minified = typeof opt.bundle === "object" && opt.bundle.minify === true;
152
+ const bundleStep = log.start("bundle", "bundling the project's code into one file");
153
+ try {
154
+ bundle = await (0, Bundler_1.Bundle)(opt.bundle, pkg);
155
+ }
156
+ catch (e) {
157
+ bundleStep.fail();
158
+ throw e;
159
+ }
160
+ bundleStep.ok(`${bundle.outFile} ${dim("·")} ${bundle.modules} source files` + (minified ? ` ${dim("·")} minified` : ""));
161
+ for (const w of bundle.warnings)
162
+ log.note(yellow("⚠ " + w));
163
+ }
164
+ const tarArgs = ["-czf", archiveName, ...excludeArgs];
135
165
  if (spaMode) {
136
166
  tarArgs.push("-C", "./dist", ".");
137
167
  if (items.length > 0) {
@@ -139,38 +169,40 @@ async function Deploy(opt) {
139
169
  }
140
170
  }
141
171
  else {
172
+ if (bundle) {
173
+ tarArgs.push("-C", bundle.stageDir, "bin");
174
+ if (items.length > 0)
175
+ tarArgs.push("-C", process.cwd());
176
+ }
142
177
  tarArgs.push(...items);
143
178
  }
144
179
  let stageDir = null;
180
+ const relocated = [];
145
181
  if (staged.length > 0) {
146
- stageDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "badmfck-deploy-"));
182
+ stageDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "bmfk-deploy-"));
147
183
  for (const { src, dest } of staged) {
148
184
  const target = path_1.default.join(stageDir, dest);
149
185
  fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
150
186
  fs_1.default.cpSync(path_1.default.resolve(src), target, { recursive: true });
151
- console.log(`Include: ${src} -> ${dest}`);
187
+ relocated.push(`${src} → ${dest}`);
152
188
  }
153
189
  tarArgs.push("-C", stageDir, ".");
154
190
  }
155
- if (spaMode) {
156
- console.log("Archiving: contents of ./dist (recursively, at archive root)");
157
- if (items.length > 0)
158
- console.log("Also archiving from cwd:", items.join(", "));
159
- }
160
- else {
161
- console.log("Archiving:", items.join(", "));
162
- }
163
- if (excludeArgs.length > 0)
164
- console.log("Excluding:", Array.from(excludes).join(", "));
191
+ const archived = [
192
+ ...(spaMode ? ["contents of ./dist (at archive root)"] : []),
193
+ ...(bundle ? ["bin (bundle)"] : []),
194
+ ...items.map(i => i.replace(/^\.\//, "")),
195
+ ];
196
+ const archiveStep = log.start("archive", archived.join(", "));
165
197
  try {
166
198
  (0, child_process_1.execFileSync)("tar", tarArgs, {
167
199
  encoding: "utf-8",
168
- stdio: "inherit",
200
+ stdio: ["ignore", "pipe", "pipe"],
169
201
  env: { ...process.env, COPYFILE_DISABLE: "1" },
170
202
  });
171
203
  }
172
204
  catch (err) {
173
- console.error(`\ntar failed while creating ${archiveName}\n`);
205
+ archiveStep.fail(`tar failed while creating ${archiveName}`);
174
206
  const out = (err.stdout || "").toString().trim();
175
207
  const errOut = (err.stderr || "").toString().trim();
176
208
  if (out)
@@ -180,19 +212,29 @@ async function Deploy(opt) {
180
212
  process.exit(typeof err.status === "number" ? err.status : 1);
181
213
  }
182
214
  finally {
183
- if (stageDir) {
215
+ for (const dir of [stageDir, bundle?.stageDir]) {
216
+ if (!dir)
217
+ continue;
184
218
  try {
185
- fs_1.default.rmSync(stageDir, { recursive: true, force: true });
219
+ fs_1.default.rmSync(dir, { recursive: true, force: true });
186
220
  }
187
221
  catch (e) {
188
- console.warn(`Could not remove staging dir ${stageDir}: ${e?.message ?? e}`);
222
+ console.warn(`Could not remove staging dir ${dir}: ${e?.message ?? e}`);
189
223
  }
190
224
  }
191
225
  }
192
226
  if (!fs_1.default.existsSync(path_1.default.resolve(archiveName))) {
193
- console.error("ARCHIVE NOT CREATED!");
227
+ archiveStep.fail("archive was not created");
194
228
  return "";
195
229
  }
230
+ const archiveSize = (0, cliCommon_1.fmtSize)(Math.max(1, Math.round(fs_1.default.statSync(path_1.default.resolve(archiveName)).size / 1024)));
231
+ archiveStep.ok(`${countFiles(archiveName)} files ${dim("·")} ${archiveSize}`);
232
+ log.note(archived.join(", "));
233
+ for (const r of relocated)
234
+ log.note("include: " + r);
235
+ const ownExcludes = Array.from(excludes).filter(e => e !== "._*" && e !== ".DS_Store");
236
+ if (ownExcludes.length > 0)
237
+ log.note("excluded: " + ownExcludes.join(", "));
196
238
  const archivePath = path_1.default.resolve(archiveName);
197
239
  const signedFields = { token: opt.token, name: opt.name };
198
240
  const uploadHeaders = (0, cliCommon_1.deployerHeaders)(opt, opt.host, signedFields, opt.privateKey ? { file: await InterceptorSignedAuth_1.InterceptorSignedAuth.sha256File(archivePath) } : undefined);
@@ -201,7 +243,7 @@ async function Deploy(opt) {
201
243
  formData.set("token", opt.token);
202
244
  formData.set("name", opt.name);
203
245
  formData.set("file", fileBlob, archiveName);
204
- console.log(`Deploying to ${opt.host} (archive: ${archiveName})`);
246
+ const uploadStep = log.start("upload", `${archiveSize} ${dim("·")} the server unpacks, installs and restarts`);
205
247
  const startedAt = Date.now();
206
248
  const uploadAgent = new undici_1.Agent({
207
249
  headersTimeout: 5 * 60 * 1000,
@@ -214,14 +256,10 @@ async function Deploy(opt) {
214
256
  retry: { enabled: false },
215
257
  });
216
258
  const elapsedMs = Date.now() - startedAt;
217
- const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
218
- const c = (code, t) => useColor ? `\x1b[${code}m${t}\x1b[0m` : t;
219
- const red = (t) => c("31", t);
220
- const green = (t) => c("32", t);
221
- const yellow = (t) => c("33", t);
222
- const dim = (t) => c("2", t);
223
- const bold = (t) => c("1", t);
224
- const line = dim("─".repeat(60));
259
+ if (uploadResponse.ok)
260
+ uploadStep.ok(`${archiveSize} sent, server answered`);
261
+ else
262
+ uploadStep.fail("no successful answer from the server");
225
263
  const deployedAt = new Date();
226
264
  const pad = (n) => String(n).padStart(2, "0");
227
265
  const stamp = `${deployedAt.getFullYear()}-${pad(deployedAt.getMonth() + 1)}-${pad(deployedAt.getDate())} ${pad(deployedAt.getHours())}:${pad(deployedAt.getMinutes())}:${pad(deployedAt.getSeconds())}`;
@@ -337,18 +375,22 @@ async function Deploy(opt) {
337
375
  console.log("");
338
376
  return archiveName;
339
377
  }
340
- function run(cmd) {
378
+ function exec(cmd) {
379
+ return new Promise(resolve => {
380
+ const child = (0, child_process_1.spawn)(cmd, { shell: true });
381
+ let stdout = "", stderr = "";
382
+ child.stdout.on("data", d => stdout += d);
383
+ child.stderr.on("data", d => stderr += d);
384
+ child.on("error", e => resolve({ code: 1, stdout, stderr: stderr + String(e?.message ?? e) }));
385
+ child.on("close", code => resolve({ code: code ?? 1, stdout, stderr }));
386
+ });
387
+ }
388
+ function countFiles(archive) {
341
389
  try {
342
- return (0, child_process_1.execSync)(cmd, { encoding: "utf-8" });
390
+ return (0, child_process_1.execFileSync)("tar", ["-tzf", archive], { encoding: "utf-8", maxBuffer: 256 * 1024 * 1024 })
391
+ .split("\n").filter(l => l.length > 0 && !l.endsWith("/")).length;
343
392
  }
344
- catch (err) {
345
- console.error(`\nCommand failed: ${cmd}\n`);
346
- const out = (err.stdout || "").toString().trim();
347
- const errOut = (err.stderr || "").toString().trim();
348
- if (out)
349
- console.error(out);
350
- if (errOut)
351
- console.error(errOut);
352
- process.exit(typeof err.status === "number" ? err.status : 1);
393
+ catch {
394
+ return "?";
353
395
  }
354
396
  }
@@ -1 +1,2 @@
1
1
  export declare function DeployKeyWizard(target?: string): Promise<void>;
2
+ export declare function MicroserviceKey(): void;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DeployKeyWizard = DeployKeyWizard;
7
+ exports.MicroserviceKey = MicroserviceKey;
7
8
  const fs_1 = __importDefault(require("fs"));
8
9
  const path_1 = __importDefault(require("path"));
9
10
  const process_1 = require("process");
@@ -62,7 +63,22 @@ async function DeployKeyWizard(target) {
62
63
  console.log(`\nPrivate key — put it into deploy.json as "privateKey" (and keep that file out of git):\n\n ${bold(privateKey)}\n`);
63
64
  }
64
65
  console.log(`\nPublic key of ${bold(login)} — for the deployer's setup.json:\n\n ${bold(publicKey)}\n`);
65
- console.log(dim(" On the deployer: npx badmfck setup-config → \"set a deployer user's public key\""));
66
+ console.log(dim(" On the deployer: npx bmfk setup-config → \"set a deployer user's public key\""));
66
67
  console.log(dim(` or by hand: { "login": "${login}", "publicKey": "${publicKey}" }`));
67
68
  console.log(dim(" Until the deployer has this public key, this deploy.json can't deploy."));
68
69
  }
70
+ function MicroserviceKey() {
71
+ const { red, yellow, dim, bold } = (0, cliCommon_1.palette)();
72
+ if (!process_1.stdin.isTTY) {
73
+ console.error(red("✗ ms-key needs an interactive terminal — its output is a secret."));
74
+ process.exit(1);
75
+ }
76
+ const { publicKey, privateKey } = InterceptorSignedAuth_1.InterceptorSignedAuth.generateKeyPair();
77
+ console.log(bold("\nMicroservice signing key") + dim(" (Ed25519)"));
78
+ console.log(`\nPrivate key — "privateKey" of this service (host or caller). A secret: keep it out of git.\n\n ${bold(privateKey)}\n`);
79
+ console.log(`Public key — not a secret:`);
80
+ console.log(dim(` a caller's → the host's clients: { "<kid>": { publicKey: "…" } }`));
81
+ console.log(dim(` a host's → each caller's hostPublicKey`));
82
+ console.log(`\n ${bold(publicKey)}\n`);
83
+ console.log(yellow("A new pair for every service — never reuse one key on two services."));
84
+ }
@@ -335,6 +335,8 @@ export declare class DeployerService extends BaseService {
335
335
  private _warnPlaintextUsers;
336
336
  private _checkUserAuth;
337
337
  private static _extractPort;
338
+ private static _mainPath;
339
+ private static _withSourceMaps;
338
340
  private _renderNginx;
339
341
  private static _pm2AttributesFor;
340
342
  runPM2(found: IConfig, projectState?: IProjectState | null): Promise<IError | null>;
@@ -354,7 +356,8 @@ export declare class DeployerService extends BaseService {
354
356
  private static _escapingSymlink;
355
357
  private _runMigrate;
356
358
  static MIGRATE_TIMEOUT_MS: number;
357
- unpack(destination: string, uploadedFile: string, install?: boolean, ignoreDirectoryClean?: boolean): Promise<IError | null>;
359
+ static _stampProjectName(dir: string, projectName: string): void;
360
+ unpack(destination: string, uploadedFile: string, install?: boolean, ignoreDirectoryClean?: boolean, omitDev?: boolean, projectName?: string): Promise<IError | null>;
358
361
  upload(file: UploadedFile, uploadPath: string): Promise<IError | null>;
359
362
  }
360
363
  export {};
@@ -121,7 +121,7 @@ class DeployerService extends BaseService_1.BaseService {
121
121
  try {
122
122
  const plain = (this.setup?.reviewers ?? []).filter(r => r?.login && !PasswordHash_1.PasswordHash.isHash(r.password)).map(r => r.login);
123
123
  if (plain.length)
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 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`);
125
125
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
126
126
  for (const c of configurations.values()) {
127
127
  if (!c?.review)
@@ -356,7 +356,7 @@ class DeployerService extends BaseService_1.BaseService {
356
356
  }
357
357
  }
358
358
  if (found.unpack) {
359
- 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);
360
360
  if (__1.ErrorUtils.isError(unpackResult)) {
361
361
  if (found.email && found.email.length > 0) {
362
362
  for (let email of found.email) {
@@ -463,7 +463,7 @@ class DeployerService extends BaseService_1.BaseService {
463
463
  const conf = found;
464
464
  const liveness = found.liveness;
465
465
  setTimeout(async () => {
466
- const result = await __1.Http.get(liveness);
466
+ const result = await __1.Http.get(liveness, { retry: { enabled: true } });
467
467
  if (!result.ok) {
468
468
  (0, LogService_1.logError)("Liveness check failed for", conf.name);
469
469
  if (conf.email && conf.email.length > 0) {
@@ -651,7 +651,7 @@ class DeployerService extends BaseService_1.BaseService {
651
651
  }
652
652
  finish("deployed", {
653
653
  message: res?.data?.bluegreen && !res.data.activeThisDeploy
654
- ? `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.`
655
655
  : "Deployed and live.",
656
656
  slot: res?.data?.slot ?? null, activeThisDeploy: res?.data?.activeThisDeploy,
657
657
  });
@@ -976,7 +976,7 @@ class DeployerService extends BaseService_1.BaseService {
976
976
  if (PasswordHash_1.PasswordHash.isHash(config.token))
977
977
  return (await PasswordHash_1.PasswordHash.verify(token, config.token)) ? { config } : {};
978
978
  if (config.token && this.tokensMatch(config.token, token))
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 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`);
980
980
  return {};
981
981
  }
982
982
  tokensMatch(a, b) {
@@ -1007,7 +1007,7 @@ class DeployerService extends BaseService_1.BaseService {
1007
1007
  else if (!this.setup?.require_signature && passwordUsers.length && users.some(u => u.publicKey))
1008
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`);
1009
1009
  if (plain.length)
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 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`);
1011
1011
  }
1012
1012
  async _checkUserAuth(authHeader, loginHeader, ip, sig) {
1013
1013
  if (!this._ipAllowed(ip)) {
@@ -1028,7 +1028,7 @@ class DeployerService extends BaseService_1.BaseService {
1028
1028
  return { user: user };
1029
1029
  }
1030
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 badmfck deploy-key)");
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
1032
  if (!authHeader)
1033
1033
  return refuse("no Authorization header");
1034
1034
  const token = authHeader.split(" ").pop() ?? "";
@@ -1058,11 +1058,11 @@ class DeployerService extends BaseService_1.BaseService {
1058
1058
  plainMatch = user.login;
1059
1059
  }
1060
1060
  if (plainMatch) {
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 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`);
1062
1062
  return {};
1063
1063
  }
1064
1064
  if (!login)
1065
- 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");
1066
1066
  return refuse(`wrong password for ${shown(login)}`);
1067
1067
  }
1068
1068
  static _extractPort(config) {
@@ -1077,6 +1077,41 @@ class DeployerService extends BaseService_1.BaseService {
1077
1077
  }
1078
1078
  return "";
1079
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
+ }
1080
1115
  async _renderNginx(found, projectName, activePort) {
1081
1116
  if (!found.nginx?.config_dir)
1082
1117
  return null;
@@ -1131,12 +1166,16 @@ class DeployerService extends BaseService_1.BaseService {
1131
1166
  const extra = rawExtra.filter(a => !/^--no-autorestart(=.*)?$/.test(a));
1132
1167
  if (extra.length !== rawExtra.length)
1133
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");
1134
1171
  const ecoJs = path_1.default.resolve(found.destination, "ecosystem.config.js");
1135
1172
  const ecoCjs = path_1.default.resolve(found.destination, "ecosystem.config.cjs");
1136
1173
  const ecosystem = fs_1.default.existsSync(ecoJs) ? ecoJs
1137
1174
  : fs_1.default.existsSync(ecoCjs) ? ecoCjs
1138
1175
  : null;
1139
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`);
1140
1179
  (0, child_process_1.execFileSync)("pm2", ["startOrReload", ecosystem, "--update-env", ...extra]);
1141
1180
  this._verifyAutorestart(found.name);
1142
1181
  resolve(null);
@@ -1150,19 +1189,15 @@ class DeployerService extends BaseService_1.BaseService {
1150
1189
  break;
1151
1190
  }
1152
1191
  }
1153
- const packageJson = JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(found.destination, "package.json")).toString());
1154
- let main = packageJson.main || "index.js";
1155
- if (main.startsWith("./"))
1156
- main = main.substring(2);
1157
- if (!found.destination.endsWith("/"))
1158
- main = "/" + main;
1192
+ const script = entryMain ?? found.destination + "/index.js";
1159
1193
  if (running) {
1160
1194
  try {
1161
1195
  (0, child_process_1.execFileSync)("pm2", ["delete", found.name]);
1162
1196
  }
1163
1197
  catch { }
1164
1198
  }
1165
- (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]);
1166
1201
  this._verifyAutorestart(found.name);
1167
1202
  resolve(null);
1168
1203
  }
@@ -1342,7 +1377,39 @@ class DeployerService extends BaseService_1.BaseService {
1342
1377
  }
1343
1378
  }
1344
1379
  static MIGRATE_TIMEOUT_MS = 10 * 60 * 1000;
1345
- 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) {
1346
1413
  return new Promise((resolve) => {
1347
1414
  const unsafeEntry = DeployerService._unsafeArchiveEntry(uploadedFile);
1348
1415
  if (unsafeEntry) {
@@ -1387,6 +1454,8 @@ class DeployerService extends BaseService_1.BaseService {
1387
1454
  resolve({ code: 59, message: "Archive rejected: a symlink points outside the destination.", details: escaping, httpStatus: 400 });
1388
1455
  return;
1389
1456
  }
1457
+ if (projectName)
1458
+ DeployerService._stampProjectName(path_1.default.resolve(destination, "__tmp"), projectName);
1390
1459
  if (install) {
1391
1460
  try {
1392
1461
  const tmpDir = path_1.default.resolve(destination, "__tmp");
@@ -1397,7 +1466,7 @@ class DeployerService extends BaseService_1.BaseService {
1397
1466
  "Commit and include package-lock.json for `npm ci` (deterministic + faster).");
1398
1467
  }
1399
1468
  const npmCmd = useCi ? "ci" : "i";
1400
- (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"] : [])]);
1401
1470
  }
1402
1471
  catch (e) {
1403
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
  }