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
@@ -9,36 +9,41 @@ const ProjectConfigWizard_1 = require("./ProjectConfigWizard");
9
9
  const AccessConfigWizard_1 = require("./AccessConfigWizard");
10
10
  const SetupConfigWizard_1 = require("./SetupConfigWizard");
11
11
  const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
12
+ const DeployKeyWizard_1 = require("./DeployKeyWizard");
12
13
  const WIZARDS = [
13
- { command: "badmfck project-config", title: "New project config for the deployer",
14
+ { command: "bmfk project-config", title: "New project config for the deployer",
14
15
  what: "Asks for everything a project needs (folder, token, deploy steps, config values, blue-green, nginx, secrets file, review) and writes the deployer's project config plus a matching deploy.json.",
15
16
  where: "anywhere; copy the config to the deployer's projects folder",
16
17
  run: () => (0, ProjectConfigWizard_1.ProjectConfigWizard)() },
17
- { command: "badmfck setup-config [file|folder]", title: "Deployer users, reviewers and allowed IPs",
18
- what: "Edits the deployer's setup.json from a menu: add, rename or remove deployer users, change passwords, manage reviewers, allowed addresses and the review page URL.",
18
+ { command: "bmfk setup-config [file|folder]", title: "Deployer users, reviewers and allowed IPs",
19
+ what: "Edits the deployer's setup.json from a menu: add, rename or remove deployer users, change passwords or set their public signing keys, require signed requests, manage reviewers, allowed addresses and the review page URL.",
19
20
  where: "on the deployer server",
20
21
  run: () => (0, SetupConfigWizard_1.SetupConfigWizard)() },
21
- { command: "badmfck access-config [file]", title: "Monitor and documentation access",
22
+ { command: "bmfk deploy-key [deploy.json]", title: "Signing key for deploys",
23
+ what: "Generates an Ed25519 key pair: writes the private key into deploy.json (instead of the password) and prints the public key for the deployer's setup.json. Signed requests can't be replayed or altered.",
24
+ where: "in the project folder you deploy from",
25
+ run: () => (0, DeployKeyWizard_1.DeployKeyWizard)() },
26
+ { command: "bmfk access-config [file]", title: "Monitor and documentation access",
22
27
  what: "Creates or edits an app's access.json: monitor users with roles and passwords, documentation users, the monitor's allowed addresses. Finds the file named in the project's code.",
23
28
  where: "on the app server, or in the project folder",
24
29
  run: () => (0, AccessConfigWizard_1.AccessConfigWizard)() },
25
- { command: "badmfck migrate-configs [folder] [--yes]", title: "Upgrade old configs to hashed secrets",
30
+ { command: "bmfk migrate-configs [folder] [--yes]", title: "Upgrade old configs to hashed secrets",
26
31
  what: "Hashes the plain passwords and tokens in old setup.json, project configs and access.json files, computing each hash from the value already there; clients keep their deploy.json.",
27
32
  where: "on the servers, right after upgrading to 6.x",
28
33
  run: () => (0, MigrateConfigsWizard_1.MigrateConfigsWizard)() },
29
- { command: "badmfck project-token", title: "New project token",
34
+ { command: "bmfk project-token", title: "New project token",
30
35
  what: "Generates a random project token: the token itself for deploy.json and its hash for the project config.",
31
36
  where: "anywhere",
32
37
  run: () => (0, HashPassword_1.ProjectToken)("generate") },
33
- { command: "badmfck project-token --hash", title: "Hash an existing project token",
38
+ { command: "bmfk project-token --hash", title: "Hash an existing project token",
34
39
  what: "Asks for a token you already use and prints its hash for the project config.",
35
40
  where: "anywhere",
36
41
  run: () => (0, HashPassword_1.ProjectToken)("hash") },
37
- { command: "badmfck hash-password", title: "Hash a monitor password",
42
+ { command: "bmfk hash-password", title: "Hash a monitor password",
38
43
  what: "Prints a monitor user entry with a hashed password, to paste into access.json or the access option.",
39
44
  where: "anywhere",
40
45
  run: () => (0, HashPassword_1.HashPassword)("monitor") },
41
- { command: "badmfck hash-password --deployer", title: "Hash a deployer password",
46
+ { command: "bmfk hash-password --deployer", title: "Hash a deployer password",
42
47
  what: "Prints a deployer user entry with a hashed password, to paste into setup.json.",
43
48
  where: "anywhere",
44
49
  run: () => (0, HashPassword_1.HashPassword)("deployer") },
@@ -46,11 +51,11 @@ const WIZARDS = [
46
51
  async function Wizards() {
47
52
  const { red, dim, bold, green } = (0, cliCommon_1.palette)();
48
53
  if (!process_1.stdin.isTTY) {
49
- console.error(red("✗ wizards is interactive — run it in a terminal. To script, call a command directly (see `badmfck` for the list)."));
54
+ console.error(red("✗ wizards is interactive — run it in a terminal. To script, call a command directly (see `bmfk` for the list)."));
50
55
  process.exit(1);
51
56
  }
52
57
  for (;;) {
53
- console.log(bold("\nbadmfck wizards\n"));
58
+ console.log(bold("\nbmfk wizards\n"));
54
59
  WIZARDS.forEach((w, i) => {
55
60
  console.log(` ${bold(String(i + 1).padStart(2) + ")")} ${bold(w.title)}`);
56
61
  console.log(` ${w.what}`);
@@ -13,20 +13,23 @@ const AccessConfigWizard_1 = require("./AccessConfigWizard");
13
13
  const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
14
14
  const SetupConfigWizard_1 = require("./SetupConfigWizard");
15
15
  const Wizards_1 = require("./Wizards");
16
+ const DeployKeyWizard_1 = require("./DeployKeyWizard");
16
17
  function usage() {
17
18
  console.error("Usage:");
18
- console.error(" badmfck wizards — list every interactive wizard and run one");
19
- console.error(" badmfck deploy [config.json] — build + upload the current project");
20
- console.error(" badmfck activate [config.json] [blue|green] — switch blue-green slot (omit slot for lastDeployed)");
21
- console.error(" badmfck status [config.json] — show active / last deployed slot");
22
- console.error(" badmfck backups [config.json] — list deploy backups");
23
- console.error(" badmfck restore [config.json] [backup] [--yes] — restore a backup (asks which, and confirms)");
24
- console.error(" badmfck hash-password [--deployer] — hash a password for the monitor (or deployer setup.json)");
25
- console.error(" badmfck project-token [--hash] — new project token + its hash (or hash an existing one)");
26
- console.error(" badmfck project-config — build a project config for the deployer, step by step");
27
- console.error(" badmfck access-config [file] — create or edit access.json (found in the project's code if omitted)");
28
- console.error(" badmfck migrate-configs [folder] [--yes] — hash the secrets of old setup.json, project configs and access.json files");
29
- console.error(" badmfck setup-config [file|folder] — edit the deployer's setup.json: users, reviewers, allowed IPs");
19
+ console.error(" bmfk wizards — list every interactive wizard and run one");
20
+ console.error(" bmfk deploy [config.json] — build + upload the current project");
21
+ console.error(" bmfk activate [config.json] [blue|green] — switch blue-green slot (omit slot for lastDeployed)");
22
+ console.error(" bmfk status [config.json] — show active / last deployed slot");
23
+ console.error(" bmfk backups [config.json] — list deploy backups");
24
+ console.error(" bmfk restore [config.json] [backup] [--yes] — restore a backup (asks which, and confirms)");
25
+ console.error(" bmfk hash-password [--deployer] — hash a password for the monitor (or deployer setup.json)");
26
+ console.error(" bmfk project-token [--hash] — new project token + its hash (or hash an existing one)");
27
+ console.error(" bmfk project-config — build a project config for the deployer, step by step");
28
+ console.error(" bmfk access-config [file] — create or edit access.json (found in the project's code if omitted)");
29
+ console.error(" bmfk migrate-configs [folder] [--yes] — hash the secrets of old setup.json, project configs and access.json files");
30
+ console.error(" bmfk setup-config [file|folder] — edit the deployer's setup.json: users, reviewers, allowed IPs");
31
+ console.error(" bmfk deploy-key [deploy.json] — a signing key pair: private key into deploy.json, public key for setup.json");
32
+ console.error(" bmfk ms-key — a signing key pair for a microservice host or caller");
30
33
  console.error("");
31
34
  console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
32
35
  console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
@@ -121,9 +124,25 @@ async function main() {
121
124
  await (0, Wizards_1.Wizards)();
122
125
  break;
123
126
  }
127
+ case "deploy-key": {
128
+ if (rest.length > 1) {
129
+ console.error("Usage: bmfk deploy-key [deploy.json]");
130
+ process.exit(1);
131
+ }
132
+ await (0, DeployKeyWizard_1.DeployKeyWizard)(rest[0]);
133
+ break;
134
+ }
135
+ case "ms-key": {
136
+ if (rest.length > 0) {
137
+ console.error("Usage: bmfk ms-key");
138
+ process.exit(1);
139
+ }
140
+ (0, DeployKeyWizard_1.MicroserviceKey)();
141
+ break;
142
+ }
124
143
  case "setup-config": {
125
144
  if (rest.length > 1) {
126
- console.error("Usage: badmfck setup-config [file|folder]");
145
+ console.error("Usage: bmfk setup-config [file|folder]");
127
146
  process.exit(1);
128
147
  }
129
148
  await (0, SetupConfigWizard_1.SetupConfigWizard)(rest[0]);
@@ -133,7 +152,7 @@ async function main() {
133
152
  const assumeYes = rest.includes("--yes") || rest.includes("-y");
134
153
  const folders = rest.filter(a => a !== "--yes" && a !== "-y");
135
154
  if (folders.length > 1 || folders.some(a => a.startsWith("-"))) {
136
- console.error("Usage: badmfck migrate-configs [folder] [--yes]");
155
+ console.error("Usage: bmfk migrate-configs [folder] [--yes]");
137
156
  process.exit(1);
138
157
  }
139
158
  await (0, MigrateConfigsWizard_1.MigrateConfigsWizard)(folders[0], assumeYes);
@@ -1,7 +1,7 @@
1
1
  import { IDeployerConfig } from "./resolveConfig";
2
2
  export declare function deployerUrl(opt: IDeployerConfig, endpoint: string): string;
3
3
  export declare function authHeader(opt: IDeployerConfig): string;
4
- export declare function deployerHeaders(opt: IDeployerConfig): Record<string, string>;
4
+ export declare function deployerHeaders(opt: IDeployerConfig, url: string, data: unknown, files?: Record<string, string>): Record<string, string>;
5
5
  export declare function responseError(r: any): string | null;
6
6
  export declare function palette(): {
7
7
  red: (t: string) => string;
@@ -13,3 +13,15 @@ export declare function palette(): {
13
13
  };
14
14
  export declare function fmtDate(ms: number): string;
15
15
  export declare function fmtSize(kb: number | null | undefined): string;
16
+ export declare function fmtMs(ms: number): string;
17
+ export declare function stepLog(): {
18
+ ok: (name: string, text: string, ms?: number) => void;
19
+ skip: (name: string, text: string) => void;
20
+ warn: (name: string, text: string) => void;
21
+ fail: (name: string, text: string, ms?: number) => void;
22
+ note: (text: string) => void;
23
+ start(name: string, text: string): {
24
+ ok: (done?: string) => void;
25
+ fail: (done?: string) => void;
26
+ };
27
+ };
@@ -10,8 +10,11 @@ exports.responseError = responseError;
10
10
  exports.palette = palette;
11
11
  exports.fmtDate = fmtDate;
12
12
  exports.fmtSize = fmtSize;
13
+ exports.fmtMs = fmtMs;
14
+ exports.stepLog = stepLog;
13
15
  const crypto_1 = __importDefault(require("crypto"));
14
16
  const __1 = require("../..");
17
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
15
18
  function deployerUrl(opt, endpoint) {
16
19
  if (/\/add\/?$/.test(opt.host))
17
20
  return opt.host.replace(/\/add\/?$/, "/" + endpoint);
@@ -22,8 +25,11 @@ function deployerUrl(opt, endpoint) {
22
25
  function authHeader(opt) {
23
26
  return "Bearer " + crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
24
27
  }
25
- function deployerHeaders(opt) {
26
- return { authorization: authHeader(opt), "x-deployer-login": String(opt.username) };
28
+ function deployerHeaders(opt, url, data, files) {
29
+ const authorization = opt.privateKey
30
+ ? InterceptorSignedAuth_1.InterceptorSignedAuth.sign({ privateKey: opt.privateKey, kid: String(opt.username), method: "POST", url, data, files })
31
+ : authHeader(opt);
32
+ return { authorization, "x-deployer-login": String(opt.username) };
27
33
  }
28
34
  function responseError(r) {
29
35
  const body = r?.ok ? r?.data : r?.error;
@@ -60,3 +66,45 @@ function fmtSize(kb) {
60
66
  return `${(kb / 1024).toFixed(1)} MB`;
61
67
  return `${(kb / 1024 / 1024).toFixed(2)} GB`;
62
68
  }
69
+ function fmtMs(ms) {
70
+ if (ms < 1000)
71
+ return `${Math.round(ms)}ms`;
72
+ if (ms < 60_000)
73
+ return `${(ms / 1000).toFixed(1)}s`;
74
+ return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;
75
+ }
76
+ function stepLog() {
77
+ const p = palette();
78
+ const tty = !!process.stdout.isTTY;
79
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
80
+ const row = (mark, name, text, ms) => ` ${mark} ${name.padEnd(8)} ${text}` + (ms !== undefined ? " " + p.dim(fmtMs(ms)) : "");
81
+ const log = {
82
+ ok: (name, text, ms) => console.log(row(p.green("✓"), name, text, ms)),
83
+ skip: (name, text) => console.log(row(p.dim("–"), name, p.dim(text))),
84
+ warn: (name, text) => console.log(row(p.yellow("⚠"), name, p.yellow(text))),
85
+ fail: (name, text, ms) => console.log(row(p.red("✗"), name, p.red(text), ms)),
86
+ note: (text) => console.log(" ".repeat(13) + p.dim(text)),
87
+ start(name, text) {
88
+ const startedAt = Date.now();
89
+ let frame = 0;
90
+ const draw = () => {
91
+ const plain = ` ${frames[frame++ % frames.length]} ${name.padEnd(8)} ${text} ${fmtMs(Date.now() - startedAt)}`;
92
+ process.stdout.write("\r\x1b[2K" + plain.slice(0, Math.max(20, (process.stdout.columns || 80) - 1)));
93
+ };
94
+ const timer = tty ? setInterval(draw, 80) : null;
95
+ if (tty)
96
+ draw();
97
+ const stop = () => {
98
+ if (!timer)
99
+ return;
100
+ clearInterval(timer);
101
+ process.stdout.write("\r\x1b[2K");
102
+ };
103
+ return {
104
+ ok: (done) => { stop(); log.ok(name, done ?? text, Date.now() - startedAt); },
105
+ fail: (done) => { stop(); log.fail(name, done ?? text, Date.now() - startedAt); },
106
+ };
107
+ },
108
+ };
109
+ return log;
110
+ }
@@ -1,14 +1,17 @@
1
+ import type { IBundleOptions } from "./Bundler";
1
2
  export interface IDeployerConfig {
2
3
  name: string;
3
4
  token: string;
4
5
  host: string;
5
6
  username: string;
6
- password: string;
7
+ password?: string;
8
+ privateKey?: string;
7
9
  includes?: (string | {
8
10
  src: string;
9
11
  dest?: string;
10
12
  })[];
11
13
  excludes?: string[];
14
+ bundle?: boolean | IBundleOptions;
12
15
  switch_host?: string;
13
16
  }
14
17
  export declare function validateConfig(cfg: any): string | null;
@@ -9,11 +9,22 @@ const fs_1 = __importDefault(require("fs"));
9
9
  const path_1 = __importDefault(require("path"));
10
10
  const promises_1 = require("readline/promises");
11
11
  const process_1 = require("process");
12
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
12
13
  function validateConfig(cfg) {
13
14
  if (!cfg || typeof cfg !== "object")
14
15
  return "not an object";
15
- if (!cfg.name || !cfg.token || !cfg.host || !cfg.username || !cfg.password)
16
- return "missing one of: name, token, host, username, password";
16
+ if (!cfg.name || !cfg.token || !cfg.host || !cfg.username)
17
+ return "missing one of: name, token, host, username";
18
+ if (!cfg.password && !cfg.privateKey)
19
+ return "missing credentials: privateKey (signed requests) or password";
20
+ if (cfg.privateKey) {
21
+ try {
22
+ InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(cfg.privateKey);
23
+ }
24
+ catch {
25
+ return "privateKey is not a valid Ed25519 key (base64 PKCS#8)";
26
+ }
27
+ }
17
28
  if (cfg.includes) {
18
29
  if (!Array.isArray(cfg.includes))
19
30
  return "includes must be an array";
@@ -30,6 +41,16 @@ function validateConfig(cfg) {
30
41
  }
31
42
  if (cfg.excludes && !Array.isArray(cfg.excludes))
32
43
  return "excludes must be an array";
44
+ if (cfg.bundle !== undefined && typeof cfg.bundle !== "boolean") {
45
+ if (!cfg.bundle || typeof cfg.bundle !== "object" || Array.isArray(cfg.bundle))
46
+ return "bundle must be true/false or { entry?, sourcemap? }";
47
+ if (cfg.bundle.entry !== undefined && (typeof cfg.bundle.entry !== "string" || cfg.bundle.entry.length === 0))
48
+ return "bundle.entry must be a non-empty path";
49
+ if (cfg.bundle.sourcemap !== undefined && typeof cfg.bundle.sourcemap !== "boolean")
50
+ return "bundle.sourcemap must be true or false";
51
+ if (cfg.bundle.minify !== undefined && typeof cfg.bundle.minify !== "boolean")
52
+ return "bundle.minify must be true or false";
53
+ }
33
54
  if (cfg.switch_host && typeof cfg.switch_host !== "string")
34
55
  return "switch_host must be a string";
35
56
  return null;
@@ -3,14 +3,18 @@ import { BaseService } from "../BaseService";
3
3
  import { IError } from "../structures/Interfaces";
4
4
  export interface IMicroserviceClientOptions {
5
5
  id: string;
6
- securityKey: string;
7
6
  host: string;
8
- password: string;
7
+ kid?: string;
8
+ privateKey?: string;
9
+ hostPublicKey?: string;
10
+ securityKey?: string;
11
+ password?: string;
9
12
  }
10
13
  export declare const REQ_MICROSERVICE_CALL: Req<{
11
14
  id: string;
12
15
  requestName: string;
13
16
  requestData: any;
17
+ op?: string;
14
18
  }, any>;
15
19
  export declare class MicroserviceClient extends BaseService {
16
20
  #private;
@@ -21,5 +25,6 @@ export declare class MicroserviceClient extends BaseService {
21
25
  id: string;
22
26
  requestName: string;
23
27
  requestData: any;
28
+ op?: string;
24
29
  }): Promise<any | IError>;
25
30
  }
@@ -44,23 +44,39 @@ const DefaultErrors_1 = __importStar(require("../structures/DefaultErrors"));
44
44
  const Http_1 = require("../http/Http");
45
45
  const crypto_1 = __importDefault(require("crypto"));
46
46
  const TimeframeService_1 = require("../TimeframeService");
47
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
48
+ const MicroserviceHost_1 = require("./MicroserviceHost");
49
+ const Trace_1 = require("../helper/Trace");
47
50
  exports.REQ_MICROSERVICE_CALL = new badmfck_signal_1.Req(undefined, "REQ_MICROSERVICE_CALL");
51
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
48
52
  class MicroserviceClient extends BaseService_1.BaseService {
49
53
  static #clients = new Map();
50
54
  static #listener = false;
51
55
  static #nextID = 1;
52
56
  options;
57
+ #signed;
53
58
  constructor(opt) {
54
59
  super("MicroserviceClient");
60
+ this.#signed = !!(opt.privateKey || opt.kid || opt.hostPublicKey);
61
+ if (this.#signed) {
62
+ if (!opt.privateKey || !opt.kid || !opt.hostPublicKey)
63
+ throw new Error(`MicroserviceClient "${opt.id}": signed calls need all of "kid", "privateKey" and "hostPublicKey"`);
64
+ InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(opt.privateKey);
65
+ const url = new URL(opt.host);
66
+ if (url.protocol !== "https:" && !LOOPBACK.has(url.hostname))
67
+ throw new Error(`MicroserviceClient "${opt.id}": ${opt.host} — signed calls go over https (plain http only to localhost)`);
68
+ }
69
+ else if (!opt.securityKey)
70
+ throw new Error(`MicroserviceClient "${opt.id}": set "kid", "privateKey" and "hostPublicKey" for signed calls`);
55
71
  this.options = opt;
56
72
  MicroserviceClient.#clients.set(opt.id, this);
57
73
  if (!MicroserviceClient.#listener) {
58
- exports.REQ_MICROSERVICE_CALL.listener = async ({ id, requestName, requestData }) => {
59
- const client = MicroserviceClient.#clients.get(id);
74
+ exports.REQ_MICROSERVICE_CALL.listener = async (req) => {
75
+ const client = MicroserviceClient.#clients.get(req.id);
60
76
  if (!client) {
61
- return { ...DefaultErrors_1.default.BAD_REQUEST, details: "no microservice client found: " + id + ", requestName:" + requestName };
77
+ return { ...DefaultErrors_1.default.BAD_REQUEST, details: "no microservice client found: " + req.id + ", requestName:" + req.requestName };
62
78
  }
63
- return await client.requestMicroserviceCall({ id, requestName, requestData });
79
+ return await client.requestMicroserviceCall(req);
64
80
  };
65
81
  MicroserviceClient.#listener = true;
66
82
  }
@@ -69,7 +85,71 @@ class MicroserviceClient extends BaseService_1.BaseService {
69
85
  super.init();
70
86
  }
71
87
  async requestMicroserviceCall(req) {
88
+ return this.#signed ? this.#callSigned(req) : this.#callV1(req);
89
+ }
90
+ async #callSigned(req) {
91
+ const url = this.options.host + "/__ms_host_control/receiver";
92
+ const op = req.op ?? crypto_1.default.randomUUID();
93
+ const body = { v: 2, to: this.options.id, op, trace: Trace_1.Trace.current() ?? undefined, requestName: req.requestName, requestData: req.requestData };
94
+ const where = [this.options.host, req.requestName, op];
95
+ const maxAttempts = 10;
96
+ const attemptTimeout = 1000;
97
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
98
+ const nonce = crypto_1.default.randomBytes(18).toString("base64url");
99
+ const authorization = InterceptorSignedAuth_1.InterceptorSignedAuth.sign({
100
+ privateKey: this.options.privateKey, kid: this.options.kid, method: "POST", url, data: body, nonce,
101
+ });
102
+ const resp = await Http_1.Http.post(url, body, {
103
+ headers: { "Content-Type": "application/json", "x-microservice-id": this.options.id, authorization },
104
+ retry: { enabled: false },
105
+ });
106
+ if (!resp.ok && resp.details?.network) {
107
+ if (attempt < maxAttempts) {
108
+ (0, LogService_1.logInfo)(`Retrying microservice call ${req.requestName} (op ${op})... (attempt ${attempt}/${maxAttempts})`);
109
+ await TimeframeService_1.TimeframeService.wait(attemptTimeout * attempt);
110
+ continue;
111
+ }
112
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "Network connection lost after multiple retries, attempts: " + attempt, stack: where };
113
+ }
114
+ if (!resp.ok) {
115
+ const remoteError = resp.error?.error;
116
+ (0, LogService_1.logInfo)(`Microservice call ${req.requestName} refused by ${this.options.host}: HTTP ${resp.status}`, remoteError?.details ?? resp.details);
117
+ if (DefaultErrors_1.ErrorUtils.isError(remoteError))
118
+ return remoteError;
119
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: resp.details, stack: where };
120
+ }
121
+ const a = resp.data?.data;
122
+ if (!a || a.v !== 2 || a.op !== op || typeof a.sig !== "string")
123
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "the host did not answer a signed call (is it updated?)", stack: where };
124
+ if (!this.#verifyAnswer(op, nonce, a)) {
125
+ (0, LogService_1.logError)(`Microservice ${this.options.id}: answer signature does not match — not the expected host, or changed on the way`, where);
126
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "answer signature does not match", stack: where };
127
+ }
128
+ if (a.pending === true) {
129
+ if (attempt < maxAttempts) {
130
+ await TimeframeService_1.TimeframeService.wait(attemptTimeout * attempt);
131
+ continue;
132
+ }
133
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "Microservice processing timeout, attempts: " + attempt, stack: where };
134
+ }
135
+ return a.error !== undefined ? a.error : (a.result ?? null);
136
+ }
137
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "Unknown polling error", stack: where };
138
+ }
139
+ #verifyAnswer(op, nonce, a) {
140
+ try {
141
+ const key = crypto_1.default.createPublicKey({ key: Buffer.from(this.options.hostPublicKey, "base64"), format: "der", type: "spki" });
142
+ const message = MicroserviceHost_1.MicroserviceHost.answerMessage(this.options.id, op, nonce, { result: a.result, error: a.error, pending: a.pending });
143
+ return crypto_1.default.verify(null, Buffer.from(message), key, Buffer.from(a.sig, "base64"));
144
+ }
145
+ catch {
146
+ return false;
147
+ }
148
+ }
149
+ async #callV1(req) {
72
150
  const url = this.options.host + "/__ms_host_control/receiver";
151
+ const where = [this.options.host, req.requestName];
152
+ const payload = { id: req.id, requestName: req.requestName, requestData: req.requestData };
73
153
  const ts = Date.now().toString();
74
154
  const nonce = crypto_1.default.randomBytes(12).toString("hex");
75
155
  const maxAttempts = 10;
@@ -80,7 +160,7 @@ class MicroserviceClient extends BaseService_1.BaseService {
80
160
  const hash = crypto_1.default.createHash("sha256").update(nonce + ts + this.options.securityKey).digest();
81
161
  const iv = hash.subarray(0, 12);
82
162
  const aad = Buffer.from(`${ts}.${nonce}.${this.options.id}`, "utf8");
83
- const data = Buffer.from(JSON.stringify(req), "utf8");
163
+ const data = Buffer.from(JSON.stringify(payload), "utf8");
84
164
  const cipher = crypto_1.default.createCipheriv("aes-256-gcm", key, iv);
85
165
  cipher.setAAD(aad);
86
166
  const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
@@ -101,14 +181,14 @@ class MicroserviceClient extends BaseService_1.BaseService {
101
181
  await TimeframeService_1.TimeframeService.wait(attemptTimeout * attempt);
102
182
  continue;
103
183
  }
104
- return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, stack: [this.options.host, req], details: "Network connection lost after multiple retries, attempts: " + attempt };
184
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, stack: where, details: "Network connection lost after multiple retries, attempts: " + attempt };
105
185
  }
106
186
  if (!resp.ok) {
107
- (0, LogService_1.logInfo)(`Microservice call error response:`, resp);
108
187
  const remoteError = resp.error?.error;
188
+ (0, LogService_1.logInfo)(`Microservice call ${req.requestName} error response: HTTP ${resp.status}`, remoteError?.details ?? resp.details);
109
189
  if (DefaultErrors_1.ErrorUtils.isError(remoteError))
110
190
  return remoteError;
111
- return { ...DefaultErrors_1.default.BAD_REQUEST, stack: [this.options.host, req, resp.error], details: resp.details };
191
+ return { ...DefaultErrors_1.default.BAD_REQUEST, stack: where, details: resp.details };
112
192
  }
113
193
  const body = resp.data;
114
194
  const isAccepted = body?.error?.code === DefaultErrors_1.default.ACCEPTED.code || body?.code === DefaultErrors_1.default.ACCEPTED.code;
@@ -117,14 +197,14 @@ class MicroserviceClient extends BaseService_1.BaseService {
117
197
  await TimeframeService_1.TimeframeService.wait(attemptTimeout * attempt);
118
198
  continue;
119
199
  }
120
- return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, stack: [this.options.host, req], details: "Microservice processing timeout, attempts: " + attempt };
200
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, stack: where, details: "Microservice processing timeout, attempts: " + attempt };
121
201
  }
122
202
  if (body && typeof body === "object") {
123
203
  return "error" in body ? body.error : (body.data ?? null);
124
204
  }
125
205
  return body ?? null;
126
206
  }
127
- return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, stack: [this.options.host, req], details: "Unknown polling error" };
207
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, stack: where, details: "Unknown polling error" };
128
208
  }
129
209
  }
130
210
  exports.MicroserviceClient = MicroserviceClient;
@@ -1,25 +1,52 @@
1
1
  import { Req } from "badmfck-signal";
2
2
  import { BaseService } from "../BaseService";
3
3
  import { HTTPRequestVO, IError } from "../structures/Interfaces";
4
+ export interface IMicroserviceCaller {
5
+ publicKey: string;
6
+ requests?: string[];
7
+ }
4
8
  export interface IMicroserviceHostOptions {
5
9
  id: string;
6
- securityKey: string;
7
- password: string;
8
10
  requests: Req<any, any>[];
11
+ privateKey?: string;
12
+ clients?: Record<string, IMicroserviceCaller>;
13
+ jobStore?: IMicroserviceJobStore;
14
+ securityKey?: string;
15
+ password?: string;
9
16
  }
10
- type TJobStatus = "processing" | "completed";
11
- type TJob = {
12
- status: TJobStatus;
17
+ export interface IMicroserviceJob {
18
+ status: "processing" | "completed";
19
+ hash?: string;
13
20
  result?: any | IError;
14
21
  expires: number;
15
- };
22
+ }
23
+ export interface IMicroserviceJobStore {
24
+ get(key: string): Promise<IMicroserviceJob | null> | IMicroserviceJob | null;
25
+ set(key: string, job: IMicroserviceJob): Promise<void> | void;
26
+ purge(now: number): Promise<void> | void;
27
+ }
28
+ export declare class MemoryJobStore implements IMicroserviceJobStore {
29
+ #private;
30
+ get(key: string): IMicroserviceJob | null;
31
+ set(key: string, job: IMicroserviceJob): void;
32
+ purge(now: number): void;
33
+ }
34
+ export interface IMicroserviceCall {
35
+ caller: string;
36
+ op: string;
37
+ requestName: string;
38
+ }
16
39
  export declare class MicroserviceHost extends BaseService {
17
40
  #private;
18
41
  options: IMicroserviceHostOptions;
19
- jobs: Map<string, TJob>;
20
42
  constructor(opt: IMicroserviceHostOptions);
21
43
  init(): Promise<void>;
22
44
  static getMicroservice(id: string): MicroserviceHost | null;
45
+ static currentCall(): IMicroserviceCall | null;
46
+ static answerMessage(hostId: string, op: string, nonce: string, answer: {
47
+ result?: any;
48
+ error?: any;
49
+ pending?: boolean;
50
+ }): string;
23
51
  handleIncomingRequest(req: HTTPRequestVO): Promise<any | IError>;
24
52
  }
25
- export {};