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.
- package/CHANGELOG.md +103 -0
- package/README.md +213 -73
- package/dist/apiServer/APIService.d.ts +3 -1
- package/dist/apiServer/APIService.js +25 -1
- package/dist/apiServer/LogService.d.ts +2 -0
- package/dist/apiServer/LogService.js +10 -8
- package/dist/apiServer/MonitorService.d.ts +4 -1
- package/dist/apiServer/MonitorService.js +28 -5
- package/dist/apiServer/deployment/Bundler.d.ts +12 -0
- package/dist/apiServer/deployment/Bundler.js +178 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +7 -0
- package/dist/apiServer/deployment/ConfigService.js +24 -1
- package/dist/apiServer/deployment/Deploy.js +96 -54
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +1 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +17 -1
- package/dist/apiServer/deployment/DeployerService.d.ts +4 -1
- package/dist/apiServer/deployment/DeployerService.js +87 -18
- package/dist/apiServer/deployment/HashPassword.js +2 -2
- package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
- package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
- package/dist/apiServer/deployment/Restore.js +5 -5
- package/dist/apiServer/deployment/SecretsInjector.js +2 -1
- package/dist/apiServer/deployment/SetupConfigWizard.js +1 -1
- package/dist/apiServer/deployment/Status.js +1 -1
- package/dist/apiServer/deployment/Watchdog.js +1 -1
- package/dist/apiServer/deployment/Wizards.js +11 -11
- package/dist/apiServer/deployment/cli.js +25 -16
- package/dist/apiServer/deployment/cliCommon.d.ts +12 -0
- package/dist/apiServer/deployment/cliCommon.js +44 -0
- package/dist/apiServer/deployment/resolveConfig.d.ts +2 -0
- package/dist/apiServer/deployment/resolveConfig.js +10 -0
- package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
- package/dist/apiServer/external/MicroserviceClient.js +90 -10
- package/dist/apiServer/external/MicroserviceHost.d.ts +36 -8
- package/dist/apiServer/external/MicroserviceHost.js +166 -55
- package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
- package/dist/apiServer/helper/AppDataPath.js +81 -0
- package/dist/apiServer/helper/ClientIp.d.ts +1 -0
- package/dist/apiServer/helper/ClientIp.js +5 -0
- package/dist/apiServer/helper/Trace.d.ts +8 -0
- package/dist/apiServer/helper/Trace.js +30 -0
- package/dist/apiServer/helper/Validator.d.ts +1 -0
- package/dist/apiServer/helper/Validator.js +21 -18
- package/dist/apiServer/http/Http.d.ts +1 -0
- package/dist/apiServer/http/Http.js +5 -2
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +2 -1
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +1 -1
- package/dist/apiServer/monitor/MonitorAuth.js +8 -5
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
- package/dist/apiServer/monitor/index.html +66 -66
- package/dist/apiServer/security/BlockedIps.js +10 -14
- package/dist/apiServer/structures/Interfaces.d.ts +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -1
- package/package.json +21 -6
- package/bluegreen.help.md +0 -392
- package/cocroach.help.md +0 -191
- package/connections.help.md +0 -0
- package/monitoring.help.md +0 -350
|
@@ -23,7 +23,7 @@ async function ProjectConfigWizard() {
|
|
|
23
23
|
const section = (title) => console.log("\n" + bold(title));
|
|
24
24
|
console.log(bold("\nNew project config for the deployer") + dim(" (Enter keeps the value in brackets)"));
|
|
25
25
|
section("Project");
|
|
26
|
-
const name = await (0, cliPrompt_1.askValid)("Name", "", v =>
|
|
26
|
+
const name = await (0, cliPrompt_1.askValid)("Name (e.g. api.gateway.example.com)", "", v => (0, ConfigService_1.projectNameProblem)(v));
|
|
27
27
|
const description = await (0, cliPrompt_1.ask)("Description", "");
|
|
28
28
|
const destination = await (0, cliPrompt_1.askValid)("Destination folder on the server", `/var/node/${name}`, v => !path_1.default.isAbsolute(v) ? "must be an absolute path" : /^\/(var|etc|home|usr|opt|srv|tmp|root)?\/?$/.test(v) ? "pick a folder of its own, not a system folder" : null);
|
|
29
29
|
section("Project token");
|
|
@@ -46,6 +46,7 @@ async function ProjectConfigWizard() {
|
|
|
46
46
|
section("Deploy steps");
|
|
47
47
|
const unpack = await (0, cliPrompt_1.yes)("Unpack the uploaded archive", true);
|
|
48
48
|
const install = unpack ? await (0, cliPrompt_1.yes)("Install dependencies (npm ci)", true) : false;
|
|
49
|
+
const omitDev = install ? await (0, cliPrompt_1.yes)("Skip devDependencies on the server (npm ci --omit=dev)", false) : false;
|
|
49
50
|
const ignoreDirectoryClean = unpack ? !(await (0, cliPrompt_1.yes)("Clean the destination before unpacking", true)) : false;
|
|
50
51
|
const backup = await (0, cliPrompt_1.yes)("Back up the current version before each deploy", true);
|
|
51
52
|
const migrate = await (0, cliPrompt_1.yes)("Run `npm run migrate` before starting", false);
|
|
@@ -71,6 +72,7 @@ async function ProjectConfigWizard() {
|
|
|
71
72
|
const cfg = {
|
|
72
73
|
name, destination, description, token: tokenHash,
|
|
73
74
|
unpack, ignoreDirectoryClean, backup, install, migrate, pm2,
|
|
75
|
+
...(omitDev ? { omitDev } : {}),
|
|
74
76
|
...(pm2Attributes.length ? { pm2_attributes: pm2Attributes } : {}),
|
|
75
77
|
...(chmod ? { chmod } : {}),
|
|
76
78
|
...(email.length ? { email } : {}),
|
|
@@ -95,7 +97,7 @@ async function ProjectConfigWizard() {
|
|
|
95
97
|
}
|
|
96
98
|
section("Secrets file — keeps config values out of the deployed code");
|
|
97
99
|
if (Object.keys(config).length && await (0, cliPrompt_1.yes)("Store config values in a secrets file outside the deploy folder?", true)) {
|
|
98
|
-
const where = await (0, cliPrompt_1.ask)(" folder (empty = secrets_dir from the deployer's setup.json)", "");
|
|
100
|
+
const where = await (0, cliPrompt_1.ask)(" folder (empty = secrets_dir from the deployer's setup.json, else /var/bmfk/<project>)", "");
|
|
99
101
|
if (where && (!path_1.default.isAbsolute(where) || path_1.default.resolve(where).startsWith(path_1.default.resolve(destination) + path_1.default.sep)))
|
|
100
102
|
console.log(yellow(" ⚠ The folder must be absolute and outside the deploy folder — the deployer will refuse this project as is."));
|
|
101
103
|
cfg.secrets = where ? { dir: where } : {};
|
|
@@ -25,11 +25,11 @@ async function Restore(opt, backupName, assumeYes = false) {
|
|
|
25
25
|
if (backupName) {
|
|
26
26
|
chosen = list.find(b => b.name === backupName);
|
|
27
27
|
if (!chosen)
|
|
28
|
-
fail(`Backup "${backupName}" not found. Run \`
|
|
28
|
+
fail(`Backup "${backupName}" not found. Run \`bmfk backups\` to see the list.`);
|
|
29
29
|
}
|
|
30
30
|
else {
|
|
31
31
|
if (!rl)
|
|
32
|
-
fail("Backup name is required when not running in a terminal:
|
|
32
|
+
fail("Backup name is required when not running in a terminal: bmfk restore <backup-name> --yes");
|
|
33
33
|
console.log("");
|
|
34
34
|
list.forEach((b, i) => console.log(` [${i + 1}] ${b.name} ${dim("ver")} ${b.appVersion ?? "?"} ${dim((0, cliCommon_1.fmtDate)(b.createdAt))}`));
|
|
35
35
|
while (!chosen) {
|
|
@@ -48,7 +48,7 @@ async function Restore(opt, backupName, assumeYes = false) {
|
|
|
48
48
|
console.log(` ${dim("slot:")} ${chosen.slot} ${dim("active:")} ${info.activeSlot ?? "?"}`);
|
|
49
49
|
console.log(live
|
|
50
50
|
? yellow(bold(" ⚠ LIVE: production traffic gets the restored code immediately"))
|
|
51
|
-
: dim(` not live — the slot will need:
|
|
51
|
+
: dim(` not live — the slot will need: bmfk activate ${chosen.slot}`));
|
|
52
52
|
console.log(dim(" current contents are backed up first, so this can be undone"));
|
|
53
53
|
if (!assumeYes) {
|
|
54
54
|
if (!rl)
|
|
@@ -81,9 +81,9 @@ async function Restore(opt, backupName, assumeYes = false) {
|
|
|
81
81
|
console.log(` ${dim("live: ")} ${d.live ? bold("yes") : "no"}`);
|
|
82
82
|
console.log(` ${dim("pm2: ")} ${d.pm2Error ? yellow(d.pm2Error) : d.pm2Restarted ? "restarted" : "not used"}`);
|
|
83
83
|
if (d.preRestoreBackup)
|
|
84
|
-
console.log(` ${dim("undo with: ")}
|
|
84
|
+
console.log(` ${dim("undo with: ")} bmfk restore ${d.preRestoreBackup}`);
|
|
85
85
|
if (!d.live && d.slot)
|
|
86
|
-
console.log(` ${dim("next: ")}
|
|
86
|
+
console.log(` ${dim("next: ")} bmfk activate ${d.slot}`);
|
|
87
87
|
console.log(line);
|
|
88
88
|
console.log("");
|
|
89
89
|
}
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.SecretsInjector = void 0;
|
|
7
7
|
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const AppDataPath_1 = require("../helper/AppDataPath");
|
|
8
9
|
const path_1 = __importDefault(require("path"));
|
|
9
10
|
const vm_1 = __importDefault(require("vm"));
|
|
10
11
|
const PLACEHOLDER = /_\{\{([A-Za-z0-9_]+)\}\}_/g;
|
|
@@ -24,7 +25,7 @@ class SecretsInjector {
|
|
|
24
25
|
target = path_1.default.join(dir, `${project}${slot ? "-" + slot : ""}.json`);
|
|
25
26
|
}
|
|
26
27
|
else {
|
|
27
|
-
|
|
28
|
+
target = path_1.default.join(AppDataPath_1.AppData.projectDir(project), `secrets${slot ? "-" + slot : ""}.json`);
|
|
28
29
|
}
|
|
29
30
|
target = path_1.default.resolve(target);
|
|
30
31
|
const root = path_1.default.resolve(destinationRoot);
|
|
@@ -129,7 +129,7 @@ async function SetupConfigWizard(target) {
|
|
|
129
129
|
} },
|
|
130
130
|
"k": { title: "set a deployer user's public key (signed deploys)", run: async () => {
|
|
131
131
|
const u = user(await (0, cliPrompt_1.askValid)(" login", "", v => user(v) ? null : "no such user — add the user first"));
|
|
132
|
-
const key = await (0, cliPrompt_1.askValid)(" public key from `npx
|
|
132
|
+
const key = await (0, cliPrompt_1.askValid)(" public key from `npx bmfk deploy-key` (base64)", "", v => {
|
|
133
133
|
try {
|
|
134
134
|
crypto_1.default.createPublicKey({ key: Buffer.from(v, "base64"), format: "der", type: "spki" });
|
|
135
135
|
return /^MCowBQYDK2VwAyEA/.test(v) ? null : "not an Ed25519 public key";
|
|
@@ -67,7 +67,7 @@ async function Status(opt) {
|
|
|
67
67
|
console.log(` ${dim("active: ")} ${slotColor(state.active)}`);
|
|
68
68
|
console.log(` ${dim("lastDeployed:")} ${slotColor(state.lastDeployed)}`);
|
|
69
69
|
if (entry.readyToSwitch)
|
|
70
|
-
console.log(` ${yellow("⚠ " + state.lastDeployed + " is deployed but NOT switched")} ${dim("→
|
|
70
|
+
console.log(` ${yellow("⚠ " + state.lastDeployed + " is deployed but NOT switched")} ${dim("→ bmfk activate")}`);
|
|
71
71
|
const last = Array.isArray(state.history) && state.history.length ? state.history[state.history.length - 1] : null;
|
|
72
72
|
if (last) {
|
|
73
73
|
const d = new Date(last.at);
|
|
@@ -29,7 +29,7 @@ class Watchdog extends BaseService_1.BaseService {
|
|
|
29
29
|
async checkReadiness(config) {
|
|
30
30
|
if (!config.readiness)
|
|
31
31
|
return;
|
|
32
|
-
const resp = await __1.Http.get(config.readiness);
|
|
32
|
+
const resp = await __1.Http.get(config.readiness, { retry: { enabled: true } });
|
|
33
33
|
if (resp.ok) {
|
|
34
34
|
this.statusPassed(config);
|
|
35
35
|
}
|
|
@@ -11,39 +11,39 @@ const SetupConfigWizard_1 = require("./SetupConfigWizard");
|
|
|
11
11
|
const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
|
|
12
12
|
const DeployKeyWizard_1 = require("./DeployKeyWizard");
|
|
13
13
|
const WIZARDS = [
|
|
14
|
-
{ command: "
|
|
14
|
+
{ command: "bmfk project-config", title: "New project config for the deployer",
|
|
15
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.",
|
|
16
16
|
where: "anywhere; copy the config to the deployer's projects folder",
|
|
17
17
|
run: () => (0, ProjectConfigWizard_1.ProjectConfigWizard)() },
|
|
18
|
-
{ command: "
|
|
18
|
+
{ command: "bmfk setup-config [file|folder]", title: "Deployer users, reviewers and allowed IPs",
|
|
19
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.",
|
|
20
20
|
where: "on the deployer server",
|
|
21
21
|
run: () => (0, SetupConfigWizard_1.SetupConfigWizard)() },
|
|
22
|
-
{ command: "
|
|
22
|
+
{ command: "bmfk deploy-key [deploy.json]", title: "Signing key for deploys",
|
|
23
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
24
|
where: "in the project folder you deploy from",
|
|
25
25
|
run: () => (0, DeployKeyWizard_1.DeployKeyWizard)() },
|
|
26
|
-
{ command: "
|
|
26
|
+
{ command: "bmfk access-config [file]", title: "Monitor and documentation access",
|
|
27
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.",
|
|
28
28
|
where: "on the app server, or in the project folder",
|
|
29
29
|
run: () => (0, AccessConfigWizard_1.AccessConfigWizard)() },
|
|
30
|
-
{ command: "
|
|
30
|
+
{ command: "bmfk migrate-configs [folder] [--yes]", title: "Upgrade old configs to hashed secrets",
|
|
31
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.",
|
|
32
32
|
where: "on the servers, right after upgrading to 6.x",
|
|
33
33
|
run: () => (0, MigrateConfigsWizard_1.MigrateConfigsWizard)() },
|
|
34
|
-
{ command: "
|
|
34
|
+
{ command: "bmfk project-token", title: "New project token",
|
|
35
35
|
what: "Generates a random project token: the token itself for deploy.json and its hash for the project config.",
|
|
36
36
|
where: "anywhere",
|
|
37
37
|
run: () => (0, HashPassword_1.ProjectToken)("generate") },
|
|
38
|
-
{ command: "
|
|
38
|
+
{ command: "bmfk project-token --hash", title: "Hash an existing project token",
|
|
39
39
|
what: "Asks for a token you already use and prints its hash for the project config.",
|
|
40
40
|
where: "anywhere",
|
|
41
41
|
run: () => (0, HashPassword_1.ProjectToken)("hash") },
|
|
42
|
-
{ command: "
|
|
42
|
+
{ command: "bmfk hash-password", title: "Hash a monitor password",
|
|
43
43
|
what: "Prints a monitor user entry with a hashed password, to paste into access.json or the access option.",
|
|
44
44
|
where: "anywhere",
|
|
45
45
|
run: () => (0, HashPassword_1.HashPassword)("monitor") },
|
|
46
|
-
{ command: "
|
|
46
|
+
{ command: "bmfk hash-password --deployer", title: "Hash a deployer password",
|
|
47
47
|
what: "Prints a deployer user entry with a hashed password, to paste into setup.json.",
|
|
48
48
|
where: "anywhere",
|
|
49
49
|
run: () => (0, HashPassword_1.HashPassword)("deployer") },
|
|
@@ -51,11 +51,11 @@ const WIZARDS = [
|
|
|
51
51
|
async function Wizards() {
|
|
52
52
|
const { red, dim, bold, green } = (0, cliCommon_1.palette)();
|
|
53
53
|
if (!process_1.stdin.isTTY) {
|
|
54
|
-
console.error(red("✗ wizards is interactive — run it in a terminal. To script, call a command directly (see `
|
|
54
|
+
console.error(red("✗ wizards is interactive — run it in a terminal. To script, call a command directly (see `bmfk` for the list)."));
|
|
55
55
|
process.exit(1);
|
|
56
56
|
}
|
|
57
57
|
for (;;) {
|
|
58
|
-
console.log(bold("\
|
|
58
|
+
console.log(bold("\nbmfk wizards\n"));
|
|
59
59
|
WIZARDS.forEach((w, i) => {
|
|
60
60
|
console.log(` ${bold(String(i + 1).padStart(2) + ")")} ${bold(w.title)}`);
|
|
61
61
|
console.log(` ${w.what}`);
|
|
@@ -16,19 +16,20 @@ const Wizards_1 = require("./Wizards");
|
|
|
16
16
|
const DeployKeyWizard_1 = require("./DeployKeyWizard");
|
|
17
17
|
function usage() {
|
|
18
18
|
console.error("Usage:");
|
|
19
|
-
console.error("
|
|
20
|
-
console.error("
|
|
21
|
-
console.error("
|
|
22
|
-
console.error("
|
|
23
|
-
console.error("
|
|
24
|
-
console.error("
|
|
25
|
-
console.error("
|
|
26
|
-
console.error("
|
|
27
|
-
console.error("
|
|
28
|
-
console.error("
|
|
29
|
-
console.error("
|
|
30
|
-
console.error("
|
|
31
|
-
console.error("
|
|
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");
|
|
32
33
|
console.error("");
|
|
33
34
|
console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
|
|
34
35
|
console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
|
|
@@ -125,15 +126,23 @@ async function main() {
|
|
|
125
126
|
}
|
|
126
127
|
case "deploy-key": {
|
|
127
128
|
if (rest.length > 1) {
|
|
128
|
-
console.error("Usage:
|
|
129
|
+
console.error("Usage: bmfk deploy-key [deploy.json]");
|
|
129
130
|
process.exit(1);
|
|
130
131
|
}
|
|
131
132
|
await (0, DeployKeyWizard_1.DeployKeyWizard)(rest[0]);
|
|
132
133
|
break;
|
|
133
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
|
+
}
|
|
134
143
|
case "setup-config": {
|
|
135
144
|
if (rest.length > 1) {
|
|
136
|
-
console.error("Usage:
|
|
145
|
+
console.error("Usage: bmfk setup-config [file|folder]");
|
|
137
146
|
process.exit(1);
|
|
138
147
|
}
|
|
139
148
|
await (0, SetupConfigWizard_1.SetupConfigWizard)(rest[0]);
|
|
@@ -143,7 +152,7 @@ async function main() {
|
|
|
143
152
|
const assumeYes = rest.includes("--yes") || rest.includes("-y");
|
|
144
153
|
const folders = rest.filter(a => a !== "--yes" && a !== "-y");
|
|
145
154
|
if (folders.length > 1 || folders.some(a => a.startsWith("-"))) {
|
|
146
|
-
console.error("Usage:
|
|
155
|
+
console.error("Usage: bmfk migrate-configs [folder] [--yes]");
|
|
147
156
|
process.exit(1);
|
|
148
157
|
}
|
|
149
158
|
await (0, MigrateConfigsWizard_1.MigrateConfigsWizard)(folders[0], assumeYes);
|
|
@@ -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,6 +10,8 @@ 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("../..");
|
|
15
17
|
const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
|
|
@@ -64,3 +66,45 @@ function fmtSize(kb) {
|
|
|
64
66
|
return `${(kb / 1024).toFixed(1)} MB`;
|
|
65
67
|
return `${(kb / 1024 / 1024).toFixed(2)} GB`;
|
|
66
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,3 +1,4 @@
|
|
|
1
|
+
import type { IBundleOptions } from "./Bundler";
|
|
1
2
|
export interface IDeployerConfig {
|
|
2
3
|
name: string;
|
|
3
4
|
token: string;
|
|
@@ -10,6 +11,7 @@ export interface IDeployerConfig {
|
|
|
10
11
|
dest?: string;
|
|
11
12
|
})[];
|
|
12
13
|
excludes?: string[];
|
|
14
|
+
bundle?: boolean | IBundleOptions;
|
|
13
15
|
switch_host?: string;
|
|
14
16
|
}
|
|
15
17
|
export declare function validateConfig(cfg: any): string | null;
|
|
@@ -41,6 +41,16 @@ function validateConfig(cfg) {
|
|
|
41
41
|
}
|
|
42
42
|
if (cfg.excludes && !Array.isArray(cfg.excludes))
|
|
43
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
|
+
}
|
|
44
54
|
if (cfg.switch_host && typeof cfg.switch_host !== "string")
|
|
45
55
|
return "switch_host must be a string";
|
|
46
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
|
-
|
|
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 (
|
|
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(
|
|
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(
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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,53 @@
|
|
|
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
|
+
allowedIps?: string[];
|
|
8
|
+
}
|
|
4
9
|
export interface IMicroserviceHostOptions {
|
|
5
10
|
id: string;
|
|
6
|
-
securityKey: string;
|
|
7
|
-
password: string;
|
|
8
11
|
requests: Req<any, any>[];
|
|
12
|
+
privateKey?: string;
|
|
13
|
+
clients?: Record<string, IMicroserviceCaller>;
|
|
14
|
+
jobStore?: IMicroserviceJobStore;
|
|
15
|
+
securityKey?: string;
|
|
16
|
+
password?: string;
|
|
9
17
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
18
|
+
export interface IMicroserviceJob {
|
|
19
|
+
status: "processing" | "completed";
|
|
20
|
+
hash?: string;
|
|
13
21
|
result?: any | IError;
|
|
14
22
|
expires: number;
|
|
15
|
-
}
|
|
23
|
+
}
|
|
24
|
+
export interface IMicroserviceJobStore {
|
|
25
|
+
get(key: string): Promise<IMicroserviceJob | null> | IMicroserviceJob | null;
|
|
26
|
+
set(key: string, job: IMicroserviceJob): Promise<void> | void;
|
|
27
|
+
purge(now: number): Promise<void> | void;
|
|
28
|
+
}
|
|
29
|
+
export declare class MemoryJobStore implements IMicroserviceJobStore {
|
|
30
|
+
#private;
|
|
31
|
+
get(key: string): IMicroserviceJob | null;
|
|
32
|
+
set(key: string, job: IMicroserviceJob): void;
|
|
33
|
+
purge(now: number): void;
|
|
34
|
+
}
|
|
35
|
+
export interface IMicroserviceCall {
|
|
36
|
+
caller: string;
|
|
37
|
+
op: string;
|
|
38
|
+
requestName: string;
|
|
39
|
+
}
|
|
16
40
|
export declare class MicroserviceHost extends BaseService {
|
|
17
41
|
#private;
|
|
18
42
|
options: IMicroserviceHostOptions;
|
|
19
|
-
jobs: Map<string, TJob>;
|
|
20
43
|
constructor(opt: IMicroserviceHostOptions);
|
|
21
44
|
init(): Promise<void>;
|
|
22
45
|
static getMicroservice(id: string): MicroserviceHost | null;
|
|
46
|
+
static currentCall(): IMicroserviceCall | null;
|
|
47
|
+
static answerMessage(hostId: string, op: string, nonce: string, answer: {
|
|
48
|
+
result?: any;
|
|
49
|
+
error?: any;
|
|
50
|
+
pending?: boolean;
|
|
51
|
+
}): string;
|
|
23
52
|
handleIncomingRequest(req: HTTPRequestVO): Promise<any | IError>;
|
|
24
53
|
}
|
|
25
|
-
export {};
|