badmfck-api-server 6.0.3 → 6.0.5
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/README.md +71 -14
- package/dist/apiServer/APIService.d.ts +5 -0
- package/dist/apiServer/APIService.js +20 -1
- package/dist/apiServer/deployment/BackupManager.js +6 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +67 -3
- package/dist/apiServer/deployment/ConfigService.js +5 -1
- package/dist/apiServer/deployment/DeployerService.d.ts +1 -4
- package/dist/apiServer/deployment/DeployerService.js +17 -40
- package/dist/apiServer/deployment/HashPassword.d.ts +1 -0
- package/dist/apiServer/deployment/HashPassword.js +2 -1
- package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.js +171 -0
- package/dist/apiServer/deployment/cli.js +10 -0
- package/dist/apiServer/documentation/Documentation.js +5 -2
- package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
- package/dist/apiServer/helper/IpAllowList.js +40 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +2 -0
- package/dist/apiServer/monitor/AccessStore.js +12 -2
- package/dist/apiServer/monitor/Monitor.d.ts +4 -0
- package/dist/apiServer/monitor/Monitor.js +78 -5
- package/dist/apiServer/monitor/MonitorAuth.js +3 -1
- package/dist/apiServer/monitor/index.html +112 -67
- package/dist/apiServer/review/Review.js +1 -1
- package/dist/apiServer/security/BlockedIps.d.ts +46 -0
- package/dist/apiServer/security/BlockedIps.js +196 -0
- package/monitoring.help.md +40 -2
- package/package.json +1 -1
|
@@ -0,0 +1,171 @@
|
|
|
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.ProjectConfigWizard = ProjectConfigWizard;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
10
|
+
const promises_1 = require("readline/promises");
|
|
11
|
+
const process_1 = require("process");
|
|
12
|
+
const PasswordHash_1 = require("../helper/PasswordHash");
|
|
13
|
+
const Validator_1 = require("../helper/Validator");
|
|
14
|
+
const ConfigService_1 = require("./ConfigService");
|
|
15
|
+
const HashPassword_1 = require("./HashPassword");
|
|
16
|
+
const cliCommon_1 = require("./cliCommon");
|
|
17
|
+
async function ProjectConfigWizard() {
|
|
18
|
+
const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
|
|
19
|
+
if (!process_1.stdin.isTTY) {
|
|
20
|
+
console.error(red("✗ project-config needs an interactive terminal — it asks for secrets."));
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
async function ask(question, def = "") {
|
|
24
|
+
const rl = (0, promises_1.createInterface)({ input: process_1.stdin, output: process_1.stdout });
|
|
25
|
+
try {
|
|
26
|
+
const a = (await rl.question(question + (def ? dim(` [${def}]`) : "") + ": ")).trim();
|
|
27
|
+
return a || def;
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
rl.close();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function askValid(question, def, check) {
|
|
34
|
+
for (;;) {
|
|
35
|
+
const v = await ask(question, def);
|
|
36
|
+
const problem = check(v);
|
|
37
|
+
if (!problem)
|
|
38
|
+
return v;
|
|
39
|
+
console.log(red(` ✗ ${problem}`));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function yes(question, def) {
|
|
43
|
+
const a = (await ask(question + " (y/n)", def ? "y" : "n")).toLowerCase();
|
|
44
|
+
return a.startsWith("y");
|
|
45
|
+
}
|
|
46
|
+
const list = (v, sep = ",") => v.split(sep).map(s => s.trim()).filter(Boolean);
|
|
47
|
+
const tokens = (v) => Array.from(v.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g), m => m[1] ?? m[2] ?? m[3]);
|
|
48
|
+
const section = (title) => console.log("\n" + bold(title));
|
|
49
|
+
console.log(bold("\nNew project config for the deployer") + dim(" (Enter keeps the value in brackets)"));
|
|
50
|
+
section("Project");
|
|
51
|
+
const name = await askValid("Name", "", v => /^[A-Za-z0-9._-]+$/.test(v) ? null : "letters, digits, '.', '_' and '-' only");
|
|
52
|
+
const description = await ask("Description", "");
|
|
53
|
+
const destination = await 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);
|
|
54
|
+
section("Project token");
|
|
55
|
+
let plainToken = null;
|
|
56
|
+
let tokenHash;
|
|
57
|
+
if (await yes("Generate a new random token?", true)) {
|
|
58
|
+
plainToken = crypto_1.default.randomBytes(32).toString("hex");
|
|
59
|
+
tokenHash = await PasswordHash_1.PasswordHash.hash(plainToken);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
const existing = (await (0, HashPassword_1.askHidden)("Existing token (hidden): ")).trim();
|
|
63
|
+
if (!existing) {
|
|
64
|
+
console.error(red("✗ A token is required."));
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
if (existing.length < 32)
|
|
68
|
+
console.log(yellow(` ⚠ Short token (${existing.length} chars) — a generated one is safer.`));
|
|
69
|
+
tokenHash = await PasswordHash_1.PasswordHash.hash(existing);
|
|
70
|
+
}
|
|
71
|
+
section("Deploy steps");
|
|
72
|
+
const unpack = await yes("Unpack the uploaded archive", true);
|
|
73
|
+
const install = unpack ? await yes("Install dependencies (npm ci)", true) : false;
|
|
74
|
+
const ignoreDirectoryClean = unpack ? !(await yes("Clean the destination before unpacking", true)) : false;
|
|
75
|
+
const backup = await yes("Back up the current version before each deploy", true);
|
|
76
|
+
const migrate = await yes("Run `npm run migrate` before starting", false);
|
|
77
|
+
const pm2 = await yes("Run the app with pm2", true);
|
|
78
|
+
const pm2Attributes = pm2 ? tokens(await ask(`pm2 flags (quote values with spaces: --cron-restart "10 0 * * *")`, "")) : [];
|
|
79
|
+
const chmodRaw = await askValid("chmod for deployed files (empty = leave as unpacked)", "", v => !v || /^[0-7]{3,4}$/.test(v) ? null : "octal like 750");
|
|
80
|
+
const chmod = chmodRaw ? Number(chmodRaw) : 0;
|
|
81
|
+
if (chmodRaw && Number(chmodRaw.slice(-1)) & 4)
|
|
82
|
+
console.log(yellow(` ⚠ ${chmodRaw} lets every user on the server read the files.`));
|
|
83
|
+
section("Notifications");
|
|
84
|
+
const email = list(await ask("Emails, comma-separated", ""));
|
|
85
|
+
const phone = list(await ask("Phones for SMS, comma-separated", ""));
|
|
86
|
+
const liveness = await askValid("Liveness URL checked after deploy (empty = none)", "", v => !v || /^https?:\/\/\S+$/.test(v) ? null : "must be an http(s) URL");
|
|
87
|
+
section("Config values — replace _{{key}}_ in the shipped files");
|
|
88
|
+
console.log(dim(" Values are typed hidden. Empty key finishes."));
|
|
89
|
+
const config = {};
|
|
90
|
+
for (;;) {
|
|
91
|
+
const key = await askValid(" key", "", v => !v || /^[A-Za-z0-9_]+$/.test(v) ? (v && v in config ? `"${v}" is already set` : null) : "letters, digits and '_' only");
|
|
92
|
+
if (!key)
|
|
93
|
+
break;
|
|
94
|
+
config[key] = await (0, HashPassword_1.askHidden)(` value of ${key} (hidden): `);
|
|
95
|
+
}
|
|
96
|
+
const cfg = {
|
|
97
|
+
name, destination, description, token: tokenHash,
|
|
98
|
+
unpack, ignoreDirectoryClean, backup, install, migrate, pm2,
|
|
99
|
+
...(pm2Attributes.length ? { pm2_attributes: pm2Attributes } : {}),
|
|
100
|
+
...(chmod ? { chmod } : {}),
|
|
101
|
+
...(email.length ? { email } : {}),
|
|
102
|
+
...(phone.length ? { phone } : {}),
|
|
103
|
+
...(liveness ? { liveness } : {}),
|
|
104
|
+
config,
|
|
105
|
+
};
|
|
106
|
+
section("Blue-green");
|
|
107
|
+
if (await yes("Deploy as two slots (blue/green) with zero-downtime switching?", false)) {
|
|
108
|
+
const bluePort = await askValid(" blue slot port", "", v => /^\d{2,5}$/.test(v) ? null : "a port number");
|
|
109
|
+
const greenPort = await askValid(" green slot port", "", v => !/^\d{2,5}$/.test(v) ? "a port number" : v === bluePort ? "must differ from the blue port" : null);
|
|
110
|
+
const onSwitch = tokens(await ask(" command after each switch", "/usr/sbin/nginx -s reload"));
|
|
111
|
+
if (onSwitch.length && !path_1.default.isAbsolute(onSwitch[0]))
|
|
112
|
+
console.log(yellow(" ⚠ Use an absolute path to the binary — the deployer runs it without a shell."));
|
|
113
|
+
cfg.bluegreen = { blue_config: { port: bluePort }, green_config: { port: greenPort }, ...(onSwitch.length ? { on_switch: onSwitch } : {}) };
|
|
114
|
+
}
|
|
115
|
+
section("nginx");
|
|
116
|
+
if (await yes("Let the deployer manage the nginx config of this project?", !!cfg.bluegreen)) {
|
|
117
|
+
const config_dir = await askValid(" nginx config folder (nginx includes <folder>/*.conf)", "/etc/nginx/node-projects", v => path_1.default.isAbsolute(v) ? null : "must be an absolute path");
|
|
118
|
+
const domain = await ask(" domain", "");
|
|
119
|
+
cfg.nginx = { config_dir, ...(domain ? { domain } : {}) };
|
|
120
|
+
}
|
|
121
|
+
section("Secrets file — keeps config values out of the deployed code");
|
|
122
|
+
if (Object.keys(config).length && await yes("Store config values in a secrets file outside the deploy folder?", true)) {
|
|
123
|
+
const where = await ask(" folder (empty = secrets_dir from the deployer's setup.json)", "");
|
|
124
|
+
if (where && (!path_1.default.isAbsolute(where) || path_1.default.resolve(where).startsWith(path_1.default.resolve(destination) + path_1.default.sep)))
|
|
125
|
+
console.log(yellow(" ⚠ The folder must be absolute and outside the deploy folder — the deployer will refuse this project as is."));
|
|
126
|
+
cfg.secrets = where ? { dir: where } : {};
|
|
127
|
+
if (pm2Attributes.some(a => /^--(uid|gid|user)(=|$)/.test(a)))
|
|
128
|
+
console.log(yellow(" ⚠ The pm2 flags switch the user — the app couldn't read the secrets file; the deployer will refuse this project."));
|
|
129
|
+
}
|
|
130
|
+
section("Review — deploys wait for approval");
|
|
131
|
+
if (await yes("Require reviewers to approve each deploy?", false)) {
|
|
132
|
+
const reviewers = list(await askValid(" reviewer logins from the deployer's setup.json, comma-separated", "", v => list(v).length ? null : "at least one login"));
|
|
133
|
+
const mode = (await askValid(" approval: any (one accept) / all (everyone)", "any", v => v === "any" || v === "all" ? null : "any or all"));
|
|
134
|
+
const ttlHours = Number(await askValid(" hours to decide", "24", v => /^\d+$/.test(v) && +v >= 1 && +v <= 168 ? null : "1–168"));
|
|
135
|
+
cfg.review = { reviewers, mode, ttlHours };
|
|
136
|
+
}
|
|
137
|
+
const errors = await Validator_1.Validator.validateStructure(ConfigService_1.PROJECT_CONFIG_MODEL, cfg);
|
|
138
|
+
if (errors && errors.length) {
|
|
139
|
+
console.error(red("\n✗ The config doesn't pass the deployer's validation:"));
|
|
140
|
+
for (const e of errors)
|
|
141
|
+
console.error(" " + e);
|
|
142
|
+
process.exit(1);
|
|
143
|
+
}
|
|
144
|
+
section("Deploy client (deploy.json for the project)");
|
|
145
|
+
const host = await ask(" deployer upload URL", "https://deployer.example.com/api/pckg/add");
|
|
146
|
+
const username = await ask(" deployer user login", "");
|
|
147
|
+
const projectJson = JSON.stringify(cfg, null, 4);
|
|
148
|
+
const deployJson = JSON.stringify({ name, host, token: plainToken ?? "<the existing token>", username, password: "<your deployer password>" }, null, 4);
|
|
149
|
+
console.log("");
|
|
150
|
+
const save = async (what, content, def) => {
|
|
151
|
+
const target = await ask(`Save ${what} to (empty = print here)`, def);
|
|
152
|
+
if (!target) {
|
|
153
|
+
console.log("\n" + content + "\n");
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (fs_1.default.existsSync(target) && !(await yes(` ${target} exists — overwrite?`, false))) {
|
|
157
|
+
console.log("\n" + content + "\n");
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
fs_1.default.mkdirSync(path_1.default.dirname(path_1.default.resolve(target)), { recursive: true });
|
|
161
|
+
fs_1.default.writeFileSync(target, content + "\n", { encoding: "utf-8", mode: 0o600 });
|
|
162
|
+
console.log(green(` ✓ ${path_1.default.resolve(target)}`) + dim(" (0600)"));
|
|
163
|
+
};
|
|
164
|
+
await save("the project config for the deployer", projectJson, `${name}.json`);
|
|
165
|
+
console.log(dim(` → copy it to <projects_path>/${name}.json on the deployer; it is picked up without a restart.`));
|
|
166
|
+
await save("deploy.json for the project", deployJson, "");
|
|
167
|
+
if (plainToken)
|
|
168
|
+
console.log(yellow(" The token is shown only here and in deploy.json — the deployer keeps its hash. Keep deploy.json out of git."));
|
|
169
|
+
if (cfg.review)
|
|
170
|
+
console.log(dim(" Reviewers must exist in the deployer's setup.json; it says at startup if anything is missing."));
|
|
171
|
+
}
|
|
@@ -8,6 +8,7 @@ const Backups_1 = require("./Backups");
|
|
|
8
8
|
const Restore_1 = require("./Restore");
|
|
9
9
|
const BackupManager_1 = require("./BackupManager");
|
|
10
10
|
const HashPassword_1 = require("./HashPassword");
|
|
11
|
+
const ProjectConfigWizard_1 = require("./ProjectConfigWizard");
|
|
11
12
|
function usage() {
|
|
12
13
|
console.error("Usage:");
|
|
13
14
|
console.error(" badmfck deploy [config.json] — build + upload the current project");
|
|
@@ -17,6 +18,7 @@ function usage() {
|
|
|
17
18
|
console.error(" badmfck restore [config.json] [backup] [--yes] — restore a backup (asks which, and confirms)");
|
|
18
19
|
console.error(" badmfck hash-password [--deployer] — hash a password for the monitor (or deployer setup.json)");
|
|
19
20
|
console.error(" badmfck project-token [--hash] — new project token + its hash (or hash an existing one)");
|
|
21
|
+
console.error(" badmfck project-config — build a project config for the deployer, step by step");
|
|
20
22
|
console.error("");
|
|
21
23
|
console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
|
|
22
24
|
console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
|
|
@@ -103,6 +105,14 @@ async function main() {
|
|
|
103
105
|
await (0, HashPassword_1.HashPassword)(rest.includes("--deployer") ? "deployer" : "monitor");
|
|
104
106
|
break;
|
|
105
107
|
}
|
|
108
|
+
case "project-config": {
|
|
109
|
+
if (rest.length) {
|
|
110
|
+
console.error("project-config takes no arguments — everything is asked interactively.");
|
|
111
|
+
process.exit(1);
|
|
112
|
+
}
|
|
113
|
+
await (0, ProjectConfigWizard_1.ProjectConfigWizard)();
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
106
116
|
case "project-token": {
|
|
107
117
|
const unknown = rest.filter(a => a !== "--hash");
|
|
108
118
|
if (unknown.length) {
|
|
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.Documentation = void 0;
|
|
7
|
+
const LogService_1 = require("../LogService");
|
|
7
8
|
const APIService_1 = require("../APIService");
|
|
8
9
|
const BaseEndpoint_1 = require("../BaseEndpoint");
|
|
9
10
|
const DocumentService_1 = require("../DocumentService");
|
|
@@ -88,8 +89,10 @@ class Documentation extends BaseEndpoint_1.BaseEndpoint {
|
|
|
88
89
|
}
|
|
89
90
|
async checkAuthorization(req) {
|
|
90
91
|
const users = await APIService_1.REQ_DOC_USERS.request();
|
|
91
|
-
if (!users || users.length == 0)
|
|
92
|
-
|
|
92
|
+
if (!users || users.length == 0) {
|
|
93
|
+
(0, LogService_1.logWarn)("Documentation: access refused — no documentation users are configured (access.documentation)");
|
|
94
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED };
|
|
95
|
+
}
|
|
93
96
|
let header = req.headers['authorization'];
|
|
94
97
|
if (!header)
|
|
95
98
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "No authorization header found" };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import net from "net";
|
|
2
|
+
export declare class IpAllowList {
|
|
3
|
+
static build(entries: readonly string[] | undefined | null): {
|
|
4
|
+
list: net.BlockList | null;
|
|
5
|
+
error?: string;
|
|
6
|
+
};
|
|
7
|
+
static allows(list: net.BlockList | null, ip: string | undefined | null): boolean;
|
|
8
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
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.IpAllowList = void 0;
|
|
7
|
+
const net_1 = __importDefault(require("net"));
|
|
8
|
+
class IpAllowList {
|
|
9
|
+
static build(entries) {
|
|
10
|
+
const items = (entries ?? []).map(e => String(e).trim()).filter(e => e.length > 0);
|
|
11
|
+
if (items.length === 0)
|
|
12
|
+
return { list: null };
|
|
13
|
+
const list = new net_1.default.BlockList();
|
|
14
|
+
for (const item of items) {
|
|
15
|
+
const [addr, prefix, extra] = item.split("/");
|
|
16
|
+
const family = net_1.default.isIP(addr);
|
|
17
|
+
if (!family || extra !== undefined)
|
|
18
|
+
return { list: null, error: `"${item}" is not an IP address or subnet` };
|
|
19
|
+
const type = family === 6 ? "ipv6" : "ipv4";
|
|
20
|
+
if (prefix === undefined) {
|
|
21
|
+
list.addAddress(addr, type);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const bits = Number(prefix), max = family === 6 ? 128 : 32;
|
|
25
|
+
if (!/^\d+$/.test(prefix) || bits > max)
|
|
26
|
+
return { list: null, error: `"${item}" has an invalid prefix (0–${max})` };
|
|
27
|
+
list.addSubnet(addr, bits, type);
|
|
28
|
+
}
|
|
29
|
+
return { list };
|
|
30
|
+
}
|
|
31
|
+
static allows(list, ip) {
|
|
32
|
+
if (!list)
|
|
33
|
+
return true;
|
|
34
|
+
const family = net_1.default.isIP(String(ip ?? ""));
|
|
35
|
+
if (!family)
|
|
36
|
+
return false;
|
|
37
|
+
return list.check(String(ip), family === 6 ? "ipv6" : "ipv4");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
exports.IpAllowList = IpAllowList;
|
|
@@ -2,6 +2,7 @@ import type { IMonitorUser, IDocumentationUser } from "../APIService";
|
|
|
2
2
|
export interface IAccess {
|
|
3
3
|
monitor?: IMonitorUser[];
|
|
4
4
|
documentation?: IDocumentationUser[];
|
|
5
|
+
monitorAllowedIps?: string[];
|
|
5
6
|
}
|
|
6
7
|
export declare class AccessStore {
|
|
7
8
|
private onChange?;
|
|
@@ -13,6 +14,7 @@ export declare class AccessStore {
|
|
|
13
14
|
constructor(source: IAccess | string | undefined | null, onChange?: ((prev: IAccess, next: IAccess) => void) | undefined);
|
|
14
15
|
get monitor(): IMonitorUser[];
|
|
15
16
|
get documentation(): IDocumentationUser[];
|
|
17
|
+
get monitorAllowedIps(): string[];
|
|
16
18
|
static validate(value: any): string | null;
|
|
17
19
|
private loadSync;
|
|
18
20
|
private reload;
|
|
@@ -8,6 +8,7 @@ const fs_1 = __importDefault(require("fs"));
|
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
9
|
const crypto_1 = __importDefault(require("crypto"));
|
|
10
10
|
const LogService_1 = require("../LogService");
|
|
11
|
+
const IpAllowList_1 = require("../helper/IpAllowList");
|
|
11
12
|
const ROLES = ["admin", "it", "analytic"];
|
|
12
13
|
class AccessStore {
|
|
13
14
|
onChange;
|
|
@@ -28,9 +29,17 @@ class AccessStore {
|
|
|
28
29
|
}
|
|
29
30
|
get monitor() { return this.current.monitor ?? []; }
|
|
30
31
|
get documentation() { return this.current.documentation ?? []; }
|
|
32
|
+
get monitorAllowedIps() { return this.current.monitorAllowedIps ?? []; }
|
|
31
33
|
static validate(value) {
|
|
32
34
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
33
35
|
return "root must be an object";
|
|
36
|
+
if (value.monitorAllowedIps !== undefined) {
|
|
37
|
+
if (!Array.isArray(value.monitorAllowedIps) || value.monitorAllowedIps.some((e) => typeof e !== "string"))
|
|
38
|
+
return "monitorAllowedIps must be an array of strings";
|
|
39
|
+
const ips = IpAllowList_1.IpAllowList.build(value.monitorAllowedIps);
|
|
40
|
+
if (ips.error)
|
|
41
|
+
return "monitorAllowedIps: " + ips.error;
|
|
42
|
+
}
|
|
34
43
|
for (const list of ["monitor", "documentation"]) {
|
|
35
44
|
const users = value[list];
|
|
36
45
|
if (users === undefined)
|
|
@@ -99,8 +108,9 @@ class AccessStore {
|
|
|
99
108
|
this.hash = hash;
|
|
100
109
|
this.refusedHash = "";
|
|
101
110
|
this.warnPermissions();
|
|
102
|
-
this.apply({ monitor: parsed.monitor, documentation: parsed.documentation });
|
|
103
|
-
(0, LogService_1.logInfo)(`Access ${initial ? "loaded" : "reloaded"} from ${this.file}: ${this.monitor.length} monitor, ${this.documentation.length} documentation user(s)`
|
|
111
|
+
this.apply({ monitor: parsed.monitor, documentation: parsed.documentation, monitorAllowedIps: parsed.monitorAllowedIps });
|
|
112
|
+
(0, LogService_1.logInfo)(`Access ${initial ? "loaded" : "reloaded"} from ${this.file}: ${this.monitor.length} monitor, ${this.documentation.length} documentation user(s)`
|
|
113
|
+
+ (this.monitorAllowedIps.length ? `, monitor limited to ${this.monitorAllowedIps.join(", ")}` : ""));
|
|
104
114
|
}
|
|
105
115
|
refuse(reason, initial) {
|
|
106
116
|
if (initial)
|
|
@@ -21,6 +21,7 @@ export declare class Monitor extends BaseEndpoint {
|
|
|
21
21
|
fileParsed: boolean;
|
|
22
22
|
lastTimeCacheChecked: number;
|
|
23
23
|
constructor(options: APIServiceOptions);
|
|
24
|
+
__precheck(req: HTTPRequestVO): Promise<TransferPacketVO<any> | null>;
|
|
24
25
|
loadHTMLFile(): Promise<string>;
|
|
25
26
|
html(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
26
27
|
controllers(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
@@ -39,6 +40,9 @@ export declare class Monitor extends BaseEndpoint {
|
|
|
39
40
|
inventory(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
40
41
|
metrics(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
41
42
|
threats(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
43
|
+
blocked(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
44
|
+
block(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
45
|
+
unblock(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
42
46
|
logfiles(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
43
47
|
logtail(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
44
48
|
metricsWeeks(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.Monitor = exports.S_MONITOR_RESTART_REQUESTED = exports.S_MONITOR_REGISTRATE_ACTION = void 0;
|
|
7
7
|
const badmfck_signal_1 = require("badmfck-signal");
|
|
8
8
|
const APIService_1 = require("../APIService");
|
|
9
|
+
const IpAllowList_1 = require("../helper/IpAllowList");
|
|
9
10
|
const BaseEndpoint_1 = require("../BaseEndpoint");
|
|
10
11
|
const BaseService_1 = require("../BaseService");
|
|
11
12
|
const LogService_1 = require("../LogService");
|
|
@@ -20,6 +21,7 @@ const ProcessMonitor_1 = require("./ProcessMonitor");
|
|
|
20
21
|
const LogFiles_1 = require("./LogFiles");
|
|
21
22
|
const MonitorAuth_1 = require("./MonitorAuth");
|
|
22
23
|
const ThreatMonitor_1 = require("./ThreatMonitor");
|
|
24
|
+
const BlockedIps_1 = require("../security/BlockedIps");
|
|
23
25
|
exports.S_MONITOR_REGISTRATE_ACTION = new badmfck_signal_1.Signal();
|
|
24
26
|
exports.S_MONITOR_RESTART_REQUESTED = new badmfck_signal_1.Signal();
|
|
25
27
|
const logMap = {
|
|
@@ -97,12 +99,32 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
97
99
|
range: "",
|
|
98
100
|
$__range_values: ["week", "day", "hour"]
|
|
99
101
|
} },
|
|
102
|
+
{ ignoreInterceptor: true, endpoint: "blocked", handler: this.blocked },
|
|
103
|
+
{ ignoreInterceptor: true, endpoint: "block", handler: this.block, validationModel: {
|
|
104
|
+
ip: "", reason: "", $__reason_optional: true, hours: 0, $__hours_optional: true
|
|
105
|
+
} },
|
|
106
|
+
{ ignoreInterceptor: true, endpoint: "unblock", handler: this.unblock, validationModel: { ip: "" } },
|
|
100
107
|
{ ignoreInterceptor: true, endpoint: "controllers", handler: this.controllers },
|
|
101
108
|
{ ignoreInterceptor: true, endpoint: "changeLogLevel", handler: this.changeLogLevel, validationModel: {
|
|
102
109
|
level: Object.keys(logMap).join(",")
|
|
103
110
|
} }
|
|
104
111
|
]);
|
|
105
112
|
}
|
|
113
|
+
async __precheck(req) {
|
|
114
|
+
const entries = await APIService_1.REQ_MONITOR_ALLOWED_IPS.request();
|
|
115
|
+
if (!entries || entries.length === 0)
|
|
116
|
+
return null;
|
|
117
|
+
const { list, error } = IpAllowList_1.IpAllowList.build(entries);
|
|
118
|
+
if (error) {
|
|
119
|
+
(0, LogService_1.logError)(`Monitor: monitorAllowedIps is invalid (${error}) — the monitor refuses every request until it is fixed`);
|
|
120
|
+
return { error: { ...DefaultErrors_1.default.FORBIDDEN } };
|
|
121
|
+
}
|
|
122
|
+
if (!IpAllowList_1.IpAllowList.allows(list, req.ip)) {
|
|
123
|
+
(0, LogService_1.logWarn)(`Monitor: request refused from ${req.ip ?? "unknown"} — not in monitorAllowedIps`);
|
|
124
|
+
return { error: { ...DefaultErrors_1.default.FORBIDDEN } };
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
106
128
|
async loadHTMLFile() {
|
|
107
129
|
if (!this.indexHtmlFile)
|
|
108
130
|
this.indexHtmlFile = fs_1.default.readFileSync(path_1.default.resolve(__dirname, "index.html")).toString("utf-8");
|
|
@@ -187,8 +209,10 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
187
209
|
}
|
|
188
210
|
async login(req) {
|
|
189
211
|
const users = await APIService_1.REQ_MONITOR_USERS.request();
|
|
190
|
-
if (!users || users.length === 0)
|
|
191
|
-
|
|
212
|
+
if (!users || users.length === 0) {
|
|
213
|
+
(0, LogService_1.logWarn)("Monitor: sign-in refused — no monitor users are configured (access.monitor)");
|
|
214
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED };
|
|
215
|
+
}
|
|
192
216
|
const { user, error, enrollmentRequired } = await MonitorAuth_1.MonitorAuth.authenticate(users, req.data.login, req.data.password, req.data.totp);
|
|
193
217
|
if (!user || error) {
|
|
194
218
|
(0, LogService_1.logWarn)(`Monitor login failed for "${req.data.login}" from ${req.ip ?? "unknown"}: ${error}`);
|
|
@@ -301,7 +325,56 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
301
325
|
async threats(req) {
|
|
302
326
|
await this.requireAccess(req, "logs");
|
|
303
327
|
const limit = Number(req.data.limit) || 50;
|
|
304
|
-
|
|
328
|
+
const snap = ThreatMonitor_1.ThreatMonitor.snapshot(limit);
|
|
329
|
+
return { data: { ...snap, offenders: snap.offenders.map(o => ({ ...o, blocked: BlockedIps_1.BlockedIps.isBlocked(o.ip) })) } };
|
|
330
|
+
}
|
|
331
|
+
async blocked(req) {
|
|
332
|
+
await this.requireAccess(req, "logs");
|
|
333
|
+
return { data: BlockedIps_1.BlockedIps.snapshot() };
|
|
334
|
+
}
|
|
335
|
+
async block(req) {
|
|
336
|
+
const login = await this.requireAccess(req, "admin");
|
|
337
|
+
const ip = String(req.data.ip ?? "").trim();
|
|
338
|
+
const built = IpAllowList_1.IpAllowList.build([ip]);
|
|
339
|
+
if (!ip || built.error)
|
|
340
|
+
throw { ...DefaultErrors_1.default.BAD_REQUEST, details: built.error ?? "ip is required" };
|
|
341
|
+
if (IpAllowList_1.IpAllowList.allows(built.list, "127.0.0.1") || IpAllowList_1.IpAllowList.allows(built.list, "::1"))
|
|
342
|
+
throw { ...DefaultErrors_1.default.BAD_REQUEST, details: "Loopback can't be blocked" };
|
|
343
|
+
if (req.ip && IpAllowList_1.IpAllowList.allows(built.list, req.ip))
|
|
344
|
+
throw { ...DefaultErrors_1.default.BAD_REQUEST, details: `This would block your own address (${req.ip})` };
|
|
345
|
+
const hours = Number(req.data.hours) || 0;
|
|
346
|
+
if (hours < 0 || hours > 24 * 365)
|
|
347
|
+
throw { ...DefaultErrors_1.default.BAD_REQUEST, details: "hours must be between 0 (permanent) and 8760" };
|
|
348
|
+
const entry = {
|
|
349
|
+
ip,
|
|
350
|
+
...(req.data.reason ? { reason: String(req.data.reason).slice(0, 200) } : {}),
|
|
351
|
+
until: hours ? new Date(Date.now() + hours * 3600_000).toISOString() : null,
|
|
352
|
+
by: login,
|
|
353
|
+
at: new Date().toISOString(),
|
|
354
|
+
};
|
|
355
|
+
try {
|
|
356
|
+
BlockedIps_1.BlockedIps.add(entry);
|
|
357
|
+
}
|
|
358
|
+
catch (e) {
|
|
359
|
+
throw { ...DefaultErrors_1.default.INTERNAL_SERVER_ERROR, details: e?.message ?? String(e) };
|
|
360
|
+
}
|
|
361
|
+
(0, LogService_1.logWarn)(`Monitor: "${login}" blocked ${ip}${hours ? ` for ${hours} h` : " permanently"}${entry.reason ? ` — ${entry.reason}` : ""}`);
|
|
362
|
+
return { data: BlockedIps_1.BlockedIps.snapshot() };
|
|
363
|
+
}
|
|
364
|
+
async unblock(req) {
|
|
365
|
+
const login = await this.requireAccess(req, "admin");
|
|
366
|
+
const ip = String(req.data.ip ?? "").trim();
|
|
367
|
+
let removed;
|
|
368
|
+
try {
|
|
369
|
+
removed = BlockedIps_1.BlockedIps.remove(ip);
|
|
370
|
+
}
|
|
371
|
+
catch (e) {
|
|
372
|
+
throw { ...DefaultErrors_1.default.INTERNAL_SERVER_ERROR, details: e?.message ?? String(e) };
|
|
373
|
+
}
|
|
374
|
+
if (!removed)
|
|
375
|
+
throw { ...DefaultErrors_1.default.NOT_FOUND, details: `${ip} is not in the list` };
|
|
376
|
+
(0, LogService_1.logWarn)(`Monitor: "${login}" unblocked ${ip}`);
|
|
377
|
+
return { data: BlockedIps_1.BlockedIps.snapshot() };
|
|
305
378
|
}
|
|
306
379
|
async logfiles(req) {
|
|
307
380
|
await this.requireAccess(req, "logs");
|
|
@@ -358,7 +431,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
358
431
|
async checkAuthentication(req) {
|
|
359
432
|
const users = await APIService_1.REQ_MONITOR_USERS.request();
|
|
360
433
|
if (!users || users.length == 0)
|
|
361
|
-
throw { ...DefaultErrors_1.default.UNAUTHORIZED
|
|
434
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED };
|
|
362
435
|
const header = req.headers['authorization'];
|
|
363
436
|
if (!header)
|
|
364
437
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "No authorization header found" };
|
|
@@ -367,7 +440,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
|
|
|
367
440
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Wrong authorization header" };
|
|
368
441
|
const session = MonitorAuth_1.MonitorAuth.touchSession(token);
|
|
369
442
|
if (!session)
|
|
370
|
-
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Session is invalid or expired
|
|
443
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Session is invalid or expired" };
|
|
371
444
|
return session.login;
|
|
372
445
|
}
|
|
373
446
|
}
|
|
@@ -375,8 +375,10 @@ class MonitorAuth {
|
|
|
375
375
|
if (!PasswordHash_1.PasswordHash.isHash(candidate.password)) {
|
|
376
376
|
const matches = typeof candidate.password === "string" && candidate.password.length > 0
|
|
377
377
|
&& MonitorAuth.sameSecret(candidate.password, password || "");
|
|
378
|
+
if (matches)
|
|
379
|
+
(0, LogService_1.logError)(`Monitor: "${login}" signed in with the right password, but it is stored in the config as plain text — refused; store a hash: npx badmfck hash-password`);
|
|
378
380
|
MonitorAuth.registerFailure(login);
|
|
379
|
-
return { error:
|
|
381
|
+
return { error: "Invalid user" };
|
|
380
382
|
}
|
|
381
383
|
if (!(await PasswordHash_1.PasswordHash.verify(password || "", candidate.password))) {
|
|
382
384
|
MonitorAuth.registerFailure(login);
|