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
@@ -8,17 +8,24 @@ const child_process_1 = require("child_process");
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const fs_1 = __importDefault(require("fs"));
10
10
  const __1 = require("../..");
11
- const crypto_1 = __importDefault(require("crypto"));
12
11
  const os_1 = __importDefault(require("os"));
13
12
  const undici_1 = require("undici");
14
13
  const resolveConfig_1 = require("./resolveConfig");
14
+ const cliCommon_1 = require("./cliCommon");
15
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
16
+ const Bundler_1 = require("./Bundler");
15
17
  async function Deploy(opt) {
16
18
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
17
19
  const archiveName = __1.UID.sha256(opt.name.replaceAll(".", "_")) + ".tar.gz";
18
- 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);
19
26
  const config = path_1.default.resolve("src", "Config.ts");
20
27
  if (!fs_1.default.existsSync(config)) {
21
- console.log("Config: src/Config.ts not found — skipping scheme switch");
28
+ log.skip("config", "src/Config.ts not found — scheme switch skipped");
22
29
  }
23
30
  else {
24
31
  const configSrc = fs_1.default.readFileSync(config).toString("utf-8");
@@ -30,13 +37,13 @@ async function Deploy(opt) {
30
37
  });
31
38
  if (replaced > 0) {
32
39
  fs_1.default.writeFileSync(config, updated);
33
- console.log(`Config: switched to live (${replaced} occurrence${replaced === 1 ? "" : "s"})`);
40
+ log.ok("config", `switched to live (${replaced} occurrence${replaced === 1 ? "" : "s"})`);
34
41
  }
35
42
  else if (/\bscheme\s*:\s*Scheme\s*=\s*live\b/.test(configSrc)) {
36
- console.log("Config already in live mode — nothing to change");
43
+ log.ok("config", "already live");
37
44
  }
38
45
  else {
39
- 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 +
40
47
  " — check the file was not renamed/restructured");
41
48
  }
42
49
  }
@@ -49,21 +56,31 @@ async function Deploy(opt) {
49
56
  parts.push(0);
50
57
  parts[parts.length - 1] += 1;
51
58
  const newVersion = parts.join(".");
52
- console.log(`Bumping version: ${oldVersion} -> ${newVersion}`);
53
59
  pkg.version = newVersion;
54
60
  fs_1.default.writeFileSync(pkgPath, JSON.stringify(pkg, null, "\t") + "\n");
61
+ log.ok("version", `${oldVersion} ${dim("→")} ${bold(newVersion)}`);
55
62
  if (fs_1.default.existsSync(path_1.default.resolve(archiveName))) {
56
63
  fs_1.default.rmSync(path_1.default.resolve(archiveName));
57
- console.log("Removing old archive");
58
64
  }
59
- console.log("Build");
60
- var execResult = run("npm run build");
61
- 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);
62
78
  const items = [];
63
79
  let spaMode = false;
64
80
  const binExists = fs_1.default.existsSync("./bin");
65
81
  if (binExists) {
66
- items.push("./bin");
82
+ if (!opt.bundle)
83
+ items.push("./bin");
67
84
  if (fs_1.default.existsSync("package.json")) {
68
85
  items.push("package.json");
69
86
  }
@@ -73,7 +90,6 @@ async function Deploy(opt) {
73
90
  }
74
91
  else if (fs_1.default.existsSync("./dist") && fs_1.default.existsSync(path_1.default.resolve("dist", "index.html"))) {
75
92
  spaMode = true;
76
- console.log("No ./bin found — using entire ./dist contents as distribution");
77
93
  }
78
94
  const staged = [];
79
95
  if (Array.isArray(opt.includes)) {
@@ -99,9 +115,9 @@ async function Deploy(opt) {
99
115
  for (const s of staged) {
100
116
  const clash = items.some(i => i.replace(/^\.\//, "") === s.dest);
101
117
  if (clash)
102
- 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`);
103
119
  }
104
- if (items.length === 0 && !spaMode && staged.length === 0) {
120
+ if (items.length === 0 && !spaMode && staged.length === 0 && !opt.bundle) {
105
121
  throw new Error("Nothing to archive (no ./bin, no ./dist/index.html, no valid includes)");
106
122
  }
107
123
  const excludes = new Set();
@@ -112,7 +128,7 @@ async function Deploy(opt) {
112
128
  if (trimmed.length === 0 || trimmed.startsWith("#"))
113
129
  return;
114
130
  if (trimmed.startsWith("-")) {
115
- console.warn(`Skipping exclude starting with '-' from ${source}: ${trimmed}`);
131
+ log.warn("exclude", `skipped, starts with '-' (from ${source}): ${trimmed}`);
116
132
  return;
117
133
  }
118
134
  excludes.add(trimmed);
@@ -130,7 +146,22 @@ async function Deploy(opt) {
130
146
  addExclude(ex, "config.excludes");
131
147
  }
132
148
  const excludeArgs = Array.from(excludes).map(p => `--exclude=${p}`);
133
- 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];
134
165
  if (spaMode) {
135
166
  tarArgs.push("-C", "./dist", ".");
136
167
  if (items.length > 0) {
@@ -138,38 +169,40 @@ async function Deploy(opt) {
138
169
  }
139
170
  }
140
171
  else {
172
+ if (bundle) {
173
+ tarArgs.push("-C", bundle.stageDir, "bin");
174
+ if (items.length > 0)
175
+ tarArgs.push("-C", process.cwd());
176
+ }
141
177
  tarArgs.push(...items);
142
178
  }
143
179
  let stageDir = null;
180
+ const relocated = [];
144
181
  if (staged.length > 0) {
145
- 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-"));
146
183
  for (const { src, dest } of staged) {
147
184
  const target = path_1.default.join(stageDir, dest);
148
185
  fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
149
186
  fs_1.default.cpSync(path_1.default.resolve(src), target, { recursive: true });
150
- console.log(`Include: ${src} -> ${dest}`);
187
+ relocated.push(`${src} → ${dest}`);
151
188
  }
152
189
  tarArgs.push("-C", stageDir, ".");
153
190
  }
154
- if (spaMode) {
155
- console.log("Archiving: contents of ./dist (recursively, at archive root)");
156
- if (items.length > 0)
157
- console.log("Also archiving from cwd:", items.join(", "));
158
- }
159
- else {
160
- console.log("Archiving:", items.join(", "));
161
- }
162
- if (excludeArgs.length > 0)
163
- 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(", "));
164
197
  try {
165
198
  (0, child_process_1.execFileSync)("tar", tarArgs, {
166
199
  encoding: "utf-8",
167
- stdio: "inherit",
200
+ stdio: ["ignore", "pipe", "pipe"],
168
201
  env: { ...process.env, COPYFILE_DISABLE: "1" },
169
202
  });
170
203
  }
171
204
  catch (err) {
172
- console.error(`\ntar failed while creating ${archiveName}\n`);
205
+ archiveStep.fail(`tar failed while creating ${archiveName}`);
173
206
  const out = (err.stdout || "").toString().trim();
174
207
  const errOut = (err.stderr || "").toString().trim();
175
208
  if (out)
@@ -179,47 +212,54 @@ async function Deploy(opt) {
179
212
  process.exit(typeof err.status === "number" ? err.status : 1);
180
213
  }
181
214
  finally {
182
- if (stageDir) {
215
+ for (const dir of [stageDir, bundle?.stageDir]) {
216
+ if (!dir)
217
+ continue;
183
218
  try {
184
- fs_1.default.rmSync(stageDir, { recursive: true, force: true });
219
+ fs_1.default.rmSync(dir, { recursive: true, force: true });
185
220
  }
186
221
  catch (e) {
187
- console.warn(`Could not remove staging dir ${stageDir}: ${e?.message ?? e}`);
222
+ console.warn(`Could not remove staging dir ${dir}: ${e?.message ?? e}`);
188
223
  }
189
224
  }
190
225
  }
191
226
  if (!fs_1.default.existsSync(path_1.default.resolve(archiveName))) {
192
- console.error("ARCHIVE NOT CREATED!");
227
+ archiveStep.fail("archive was not created");
193
228
  return "";
194
229
  }
195
- const authToken = crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
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);
239
+ const signedFields = { token: opt.token, name: opt.name };
240
+ const uploadHeaders = (0, cliCommon_1.deployerHeaders)(opt, opt.host, signedFields, opt.privateKey ? { file: await InterceptorSignedAuth_1.InterceptorSignedAuth.sha256File(archivePath) } : undefined);
197
241
  const fileBlob = await fs_1.default.openAsBlob(archivePath);
198
242
  const formData = new FormData();
199
243
  formData.set("token", opt.token);
200
244
  formData.set("name", opt.name);
201
245
  formData.set("file", fileBlob, archiveName);
202
- console.log(`Deploying to ${opt.host} (archive: ${archiveName})`);
246
+ const uploadStep = log.start("upload", `${archiveSize} ${dim("·")} the server unpacks, installs and restarts`);
203
247
  const startedAt = Date.now();
204
248
  const uploadAgent = new undici_1.Agent({
205
249
  headersTimeout: 5 * 60 * 1000,
206
250
  bodyTimeout: 5 * 60 * 1000,
207
251
  });
208
252
  const uploadResponse = await __1.Http.post(opt.host, formData, {
209
- headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
253
+ headers: uploadHeaders,
210
254
  dispatcher: uploadAgent,
211
255
  timeoutMs: 5 * 60 * 1000,
212
256
  retry: { enabled: false },
213
257
  });
214
258
  const elapsedMs = Date.now() - startedAt;
215
- const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
216
- const c = (code, t) => useColor ? `\x1b[${code}m${t}\x1b[0m` : t;
217
- const red = (t) => c("31", t);
218
- const green = (t) => c("32", t);
219
- const yellow = (t) => c("33", t);
220
- const dim = (t) => c("2", t);
221
- const bold = (t) => c("1", t);
222
- 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");
223
263
  const deployedAt = new Date();
224
264
  const pad = (n) => String(n).padStart(2, "0");
225
265
  const stamp = `${deployedAt.getFullYear()}-${pad(deployedAt.getMonth() + 1)}-${pad(deployedAt.getDate())} ${pad(deployedAt.getHours())}:${pad(deployedAt.getMinutes())}:${pad(deployedAt.getSeconds())}`;
@@ -335,18 +375,22 @@ async function Deploy(opt) {
335
375
  console.log("");
336
376
  return archiveName;
337
377
  }
338
- 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) {
339
389
  try {
340
- 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;
341
392
  }
342
- catch (err) {
343
- console.error(`\nCommand failed: ${cmd}\n`);
344
- const out = (err.stdout || "").toString().trim();
345
- const errOut = (err.stderr || "").toString().trim();
346
- if (out)
347
- console.error(out);
348
- if (errOut)
349
- console.error(errOut);
350
- process.exit(typeof err.status === "number" ? err.status : 1);
393
+ catch {
394
+ return "?";
351
395
  }
352
396
  }
@@ -0,0 +1,2 @@
1
+ export declare function DeployKeyWizard(target?: string): Promise<void>;
2
+ export declare function MicroserviceKey(): void;
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DeployKeyWizard = DeployKeyWizard;
7
+ exports.MicroserviceKey = MicroserviceKey;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const process_1 = require("process");
11
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
12
+ const cliCommon_1 = require("./cliCommon");
13
+ const cliPrompt_1 = require("./cliPrompt");
14
+ async function DeployKeyWizard(target) {
15
+ const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
16
+ if (!process_1.stdin.isTTY) {
17
+ console.error(red("✗ deploy-key needs an interactive terminal — its output is a secret."));
18
+ process.exit(1);
19
+ }
20
+ console.log(bold("\nSigning key for deploys") + dim(" (Ed25519: the deployer keeps only the public key)"));
21
+ const candidates = target ? [target] : [
22
+ ...(fs_1.default.existsSync("deploy.json") ? ["deploy.json"] : []),
23
+ ...(fs_1.default.existsSync("deploy") && fs_1.default.statSync("deploy").isDirectory()
24
+ ? fs_1.default.readdirSync("deploy").filter(f => f.endsWith(".json")).map(f => path_1.default.join("deploy", f)) : []),
25
+ ];
26
+ let file = "";
27
+ if (candidates.length === 1)
28
+ file = await (0, cliPrompt_1.ask)("deploy.json to put the private key into (empty = only print it)", candidates[0]);
29
+ else if (candidates.length > 1) {
30
+ candidates.forEach((c, i) => console.log(` ${i + 1}) ${c}`));
31
+ const pick = await (0, cliPrompt_1.askValid)("deploy.json (number, path, or empty = only print)", "1", v => !v || !/^\d+$/.test(v) || candidates[+v - 1] ? null : "no such number");
32
+ file = /^\d+$/.test(pick) ? candidates[+pick - 1] : pick;
33
+ }
34
+ else
35
+ file = await (0, cliPrompt_1.ask)("deploy.json to put the private key into (empty = only print it)", "");
36
+ let cfg = null;
37
+ if (file) {
38
+ try {
39
+ cfg = JSON.parse(fs_1.default.readFileSync(file, "utf-8"));
40
+ }
41
+ catch (e) {
42
+ console.error(red(`✗ ${file}: ${e?.code === "ENOENT" ? "not found" : "not valid JSON"}`));
43
+ process.exit(1);
44
+ }
45
+ if (cfg.privateKey && !(await (0, cliPrompt_1.yes)(`${file} already has a privateKey — replace it?`, false)))
46
+ return;
47
+ }
48
+ const login = await (0, cliPrompt_1.askValid)("Deployer user login", cfg?.username ?? "", v => /^[A-Za-z0-9._@-]+$/.test(v) ? null : "letters, digits, '.', '_', '-', '@' only");
49
+ const { publicKey, privateKey } = InterceptorSignedAuth_1.InterceptorSignedAuth.generateKeyPair();
50
+ if (cfg) {
51
+ cfg.username = login;
52
+ cfg.privateKey = privateKey;
53
+ const hadPassword = "password" in cfg;
54
+ delete cfg.password;
55
+ const tmp = file + ".tmp";
56
+ fs_1.default.writeFileSync(tmp, JSON.stringify(cfg, null, 4) + "\n", { encoding: "utf-8", mode: 0o600 });
57
+ fs_1.default.chmodSync(tmp, 0o600);
58
+ fs_1.default.renameSync(tmp, file);
59
+ console.log(green(`\n✓ ${path_1.default.resolve(file)}`) + dim(` — privateKey written${hadPassword ? ", password removed" : ""} (0600)`));
60
+ console.log(yellow(" This file can deploy on its own: never commit or share it. In CI keep it in a secret."));
61
+ }
62
+ else {
63
+ console.log(`\nPrivate key — put it into deploy.json as "privateKey" (and keep that file out of git):\n\n ${bold(privateKey)}\n`);
64
+ }
65
+ console.log(`\nPublic key of ${bold(login)} — for the deployer's setup.json:\n\n ${bold(publicKey)}\n`);
66
+ console.log(dim(" On the deployer: npx bmfk setup-config → \"set a deployer user's public key\""));
67
+ console.log(dim(` or by hand: { "login": "${login}", "publicKey": "${publicKey}" }`));
68
+ console.log(dim(" Until the deployer has this public key, this deploy.json can't deploy."));
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
+ }
@@ -2,6 +2,7 @@ import { BaseEndpoint } from "../BaseEndpoint";
2
2
  import { HTTPRequestVO, TransferPacketVO } from "../structures/Interfaces";
3
3
  export declare class Deployer extends BaseEndpoint {
4
4
  ignoreInDocumentation: boolean;
5
+ private signed;
5
6
  constructor();
6
7
  file(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
7
8
  switchSlot(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
@@ -7,8 +7,10 @@ exports.Deployer = void 0;
7
7
  const BaseEndpoint_1 = require("../BaseEndpoint");
8
8
  const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
9
9
  const DeployerService_1 = require("./DeployerService");
10
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
10
11
  class Deployer extends BaseEndpoint_1.BaseEndpoint {
11
12
  ignoreInDocumentation = true;
13
+ signed = new InterceptorSignedAuth_1.InterceptorSignedAuth(login => DeployerService_1.REQ_DEPLOYER_PUBLIC_KEY.request(login));
12
14
  constructor() {
13
15
  super("pckg");
14
16
  this.registerEndpoints([
@@ -72,20 +74,20 @@ class Deployer extends BaseEndpoint_1.BaseEndpoint {
72
74
  async file(req) {
73
75
  if (!req.files)
74
76
  throw { ...DefaultErrors_1.default.FILE_NOT_EXISTS, details: "No files were uploaded" };
75
- const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
77
+ const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
76
78
  return { data: result };
77
79
  }
78
80
  async switchSlot(req) {
79
- return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
81
+ return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
80
82
  }
81
83
  async status(req) {
82
- return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
84
+ return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
83
85
  }
84
86
  async backups(req) {
85
- return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
87
+ return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
86
88
  }
87
89
  async restore(req) {
88
- return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
90
+ return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
89
91
  }
90
92
  async slot(req) {
91
93
  return await DeployerService_1.REQ_DEPLOYMENT_SLOT.request({ name: req.data.name, token: req.data.token, slot: req.data.slot });
@@ -6,11 +6,17 @@ import { ValidationModel } from "../..";
6
6
  import { IDeploymentNotifier } from "./Notifier";
7
7
  import { IError } from "../structures/Interfaces";
8
8
  import { IPendingReview, ReviewStore } from "./ReviewStore";
9
+ import { ISignedAuthVerdict } from "../interceptors/InterceptorSignedAuth";
9
10
  declare const _TSetup: {
10
11
  readonly users: readonly [{
11
12
  readonly login: "";
12
13
  readonly password: "";
14
+ readonly $__password_optional: true;
15
+ readonly publicKey: "";
16
+ readonly $__publicKey_optional: true;
13
17
  }];
18
+ readonly require_signature: false;
19
+ readonly $__require_signature_optional: true;
14
20
  readonly watchdog: true;
15
21
  readonly $__watchdog_optional: true;
16
22
  readonly notifier: {
@@ -38,7 +44,12 @@ export declare const SETUP_MODEL: {
38
44
  readonly users: readonly [{
39
45
  readonly login: "";
40
46
  readonly password: "";
47
+ readonly $__password_optional: true;
48
+ readonly publicKey: "";
49
+ readonly $__publicKey_optional: true;
41
50
  }];
51
+ readonly require_signature: false;
52
+ readonly $__require_signature_optional: true;
42
53
  readonly watchdog: true;
43
54
  readonly $__watchdog_optional: true;
44
55
  readonly notifier: {
@@ -71,6 +82,7 @@ export declare const REQ_DEPLOYMENT_PROCEED: Req<{
71
82
  auth: string;
72
83
  authLogin?: string;
73
84
  ip?: string;
85
+ sig?: ISignedAuthVerdict;
74
86
  name: string;
75
87
  token: string;
76
88
  files: {
@@ -81,6 +93,7 @@ export declare const REQ_DEPLOYMENT_SWITCH: Req<{
81
93
  auth?: string;
82
94
  authLogin?: string;
83
95
  ip?: string;
96
+ sig?: ISignedAuthVerdict;
84
97
  name: string;
85
98
  token: string;
86
99
  scheme?: "blue" | "green";
@@ -89,6 +102,7 @@ export declare const REQ_DEPLOYMENT_STATUS: Req<{
89
102
  auth?: string;
90
103
  authLogin?: string;
91
104
  ip?: string;
105
+ sig?: ISignedAuthVerdict;
92
106
  name?: string;
93
107
  }, any>;
94
108
  export declare const REQ_DEPLOYMENT_SLOT: Req<{
@@ -100,12 +114,15 @@ export declare const REQ_DEPLOYMENT_BACKUPS: Req<{
100
114
  auth?: string;
101
115
  authLogin?: string;
102
116
  ip?: string;
117
+ sig?: ISignedAuthVerdict;
103
118
  name: string;
104
119
  }, any>;
120
+ export declare const REQ_DEPLOYER_PUBLIC_KEY: Req<string, string | null>;
105
121
  export declare const REQ_DEPLOYMENT_RESTORE: Req<{
106
122
  auth?: string;
107
123
  authLogin?: string;
108
124
  ip?: string;
125
+ sig?: ISignedAuthVerdict;
109
126
  name: string;
110
127
  token: string;
111
128
  backup: string;
@@ -130,6 +147,7 @@ export declare class DeployerService extends BaseService {
130
147
  auth?: string;
131
148
  authLogin?: string;
132
149
  ip?: string;
150
+ sig?: ISignedAuthVerdict;
133
151
  name: string;
134
152
  token: string;
135
153
  files: {
@@ -143,6 +161,7 @@ export declare class DeployerService extends BaseService {
143
161
  };
144
162
  data?: undefined;
145
163
  } | {
164
+ error?: undefined;
146
165
  data: {
147
166
  ok: boolean;
148
167
  project: string;
@@ -151,7 +170,6 @@ export declare class DeployerService extends BaseService {
151
170
  active: "blue" | "green" | null;
152
171
  activeThisDeploy: boolean;
153
172
  };
154
- error?: undefined;
155
173
  } | {
156
174
  error?: undefined;
157
175
  data: {
@@ -178,6 +196,7 @@ export declare class DeployerService extends BaseService {
178
196
  auth?: string;
179
197
  authLogin?: string;
180
198
  ip?: string;
199
+ sig?: ISignedAuthVerdict;
181
200
  name: string;
182
201
  token: string;
183
202
  scheme?: "blue" | "green";
@@ -201,6 +220,7 @@ export declare class DeployerService extends BaseService {
201
220
  auth?: string;
202
221
  authLogin?: string;
203
222
  ip?: string;
223
+ sig?: ISignedAuthVerdict;
204
224
  name?: string;
205
225
  }): Promise<{
206
226
  data?: undefined;
@@ -223,6 +243,7 @@ export declare class DeployerService extends BaseService {
223
243
  auth?: string;
224
244
  authLogin?: string;
225
245
  ip?: string;
246
+ sig?: ISignedAuthVerdict;
226
247
  name: string;
227
248
  }): Promise<{
228
249
  data?: undefined;
@@ -246,6 +267,7 @@ export declare class DeployerService extends BaseService {
246
267
  auth?: string;
247
268
  authLogin?: string;
248
269
  ip?: string;
270
+ sig?: ISignedAuthVerdict;
249
271
  name: string;
250
272
  token: string;
251
273
  backup: string;
@@ -313,6 +335,8 @@ export declare class DeployerService extends BaseService {
313
335
  private _warnPlaintextUsers;
314
336
  private _checkUserAuth;
315
337
  private static _extractPort;
338
+ private static _mainPath;
339
+ private static _withSourceMaps;
316
340
  private _renderNginx;
317
341
  private static _pm2AttributesFor;
318
342
  runPM2(found: IConfig, projectState?: IProjectState | null): Promise<IError | null>;
@@ -332,7 +356,8 @@ export declare class DeployerService extends BaseService {
332
356
  private static _escapingSymlink;
333
357
  private _runMigrate;
334
358
  static MIGRATE_TIMEOUT_MS: number;
335
- 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>;
336
361
  upload(file: UploadedFile, uploadPath: string): Promise<IError | null>;
337
362
  }
338
363
  export {};