badmfck-api-server 6.0.4 → 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.
@@ -39,7 +39,7 @@ class Review extends BaseEndpoint_1.BaseEndpoint {
39
39
  gate(req) {
40
40
  if (!this.deployer.isIpAllowed(req.ip)) {
41
41
  (0, LogService_1.logWarn)(`Review: request refused from ${req.ip ?? "unknown"} — not in allowed_ips`);
42
- throw { ...DefaultErrors_1.default.FORBIDDEN, details: "The review page is not available from this address — connect to the VPN." };
42
+ throw { ...DefaultErrors_1.default.FORBIDDEN };
43
43
  }
44
44
  }
45
45
  session(req) {
@@ -0,0 +1,46 @@
1
+ export declare const BLOCKED_IPS_FILE = "blocked-ips.json";
2
+ export interface IBlockedIp {
3
+ ip: string;
4
+ reason?: string;
5
+ until?: string | null;
6
+ by?: string;
7
+ at?: string;
8
+ }
9
+ export declare class BlockedIps {
10
+ private static file;
11
+ private static entries;
12
+ private static list;
13
+ private static nextExpiry;
14
+ private static hash;
15
+ private static refusedHash;
16
+ private static debounce;
17
+ private static watching;
18
+ private static hits;
19
+ static configure(file?: string | null): void;
20
+ static get path(): string | null;
21
+ static defaultPath(): string;
22
+ static validate(value: any): string | null;
23
+ private static load;
24
+ private static active;
25
+ private static apply;
26
+ static isBlocked(ip: string | undefined | null): boolean;
27
+ static noteHit(ip: string): void;
28
+ static snapshot(): {
29
+ file: string | null;
30
+ entries: {
31
+ ip: string;
32
+ reason?: string;
33
+ until?: string | null;
34
+ by?: string;
35
+ at?: string;
36
+ active: boolean;
37
+ }[];
38
+ hits: {
39
+ [k: string]: number;
40
+ };
41
+ };
42
+ private static update;
43
+ static add(entry: IBlockedIp): void;
44
+ static remove(ip: string): boolean;
45
+ private static watch;
46
+ }
@@ -0,0 +1,196 @@
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.BlockedIps = exports.BLOCKED_IPS_FILE = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const IpAllowList_1 = require("../helper/IpAllowList");
11
+ const LogService_1 = require("../LogService");
12
+ exports.BLOCKED_IPS_FILE = "blocked-ips.json";
13
+ class BlockedIps {
14
+ static file = null;
15
+ static entries = [];
16
+ static list = null;
17
+ static nextExpiry = Infinity;
18
+ static hash = "";
19
+ static refusedHash = "";
20
+ static debounce = null;
21
+ static watching = false;
22
+ static hits = new Map();
23
+ static configure(file) {
24
+ BlockedIps.file = path_1.default.resolve(file || BlockedIps.defaultPath());
25
+ BlockedIps.load(true);
26
+ BlockedIps.watch();
27
+ }
28
+ static get path() { return BlockedIps.file; }
29
+ static defaultPath() {
30
+ const main = require.main?.filename ?? process.argv[1] ?? process.cwd();
31
+ let dir = path_1.default.dirname(path_1.default.resolve(main));
32
+ let packageRoot = null;
33
+ for (let i = 0; i < 12; i++) {
34
+ if (fs_1.default.existsSync(path_1.default.join(dir, ".bluegreen.json")))
35
+ return path_1.default.join(path_1.default.dirname(dir), exports.BLOCKED_IPS_FILE);
36
+ if (!packageRoot && fs_1.default.existsSync(path_1.default.join(dir, "package.json")))
37
+ packageRoot = dir;
38
+ const parent = path_1.default.dirname(dir);
39
+ if (parent === dir)
40
+ break;
41
+ dir = parent;
42
+ }
43
+ return path_1.default.join(packageRoot ?? process.cwd(), exports.BLOCKED_IPS_FILE);
44
+ }
45
+ static validate(value) {
46
+ if (!Array.isArray(value))
47
+ return "the file must hold an array of { ip, reason?, until? }";
48
+ for (const [i, e] of value.entries()) {
49
+ if (!e || typeof e !== "object" || typeof e.ip !== "string")
50
+ return `entry ${i}: "ip" is required`;
51
+ const built = IpAllowList_1.IpAllowList.build([e.ip]);
52
+ if (built.error)
53
+ return `entry ${i}: ${built.error}`;
54
+ if (e.until !== undefined && e.until !== null && Number.isNaN(Date.parse(e.until)))
55
+ return `entry ${i}: "until" is not a date`;
56
+ if (e.reason !== undefined && typeof e.reason !== "string")
57
+ return `entry ${i}: "reason" must be text`;
58
+ }
59
+ return null;
60
+ }
61
+ static load(initial = false) {
62
+ const file = BlockedIps.file;
63
+ if (!file)
64
+ return;
65
+ let raw;
66
+ try {
67
+ raw = fs_1.default.readFileSync(file, "utf-8");
68
+ }
69
+ catch (e) {
70
+ if (e?.code === "ENOENT") {
71
+ if (BlockedIps.hash !== "missing") {
72
+ BlockedIps.hash = "missing";
73
+ BlockedIps.apply([]);
74
+ }
75
+ return;
76
+ }
77
+ (0, LogService_1.logWarn)(`Blocked IPs: cannot read ${file} (${e?.message ?? e}) — keeping the current list`);
78
+ return;
79
+ }
80
+ const hash = crypto_1.default.createHash("sha256").update(raw).digest("hex");
81
+ if (hash === BlockedIps.hash || hash === BlockedIps.refusedHash)
82
+ return;
83
+ let parsed;
84
+ try {
85
+ parsed = raw.trim() ? JSON.parse(raw) : [];
86
+ }
87
+ catch (e) {
88
+ BlockedIps.refusedHash = hash;
89
+ (0, LogService_1.logError)(`Blocked IPs: ${file} is not valid JSON (${e?.message ?? e}) — change ignored, keeping the current list`);
90
+ return;
91
+ }
92
+ const problem = BlockedIps.validate(parsed);
93
+ if (problem) {
94
+ BlockedIps.refusedHash = hash;
95
+ (0, LogService_1.logError)(`Blocked IPs: ${file} — ${problem}; change ignored, keeping the current list`);
96
+ return;
97
+ }
98
+ BlockedIps.hash = hash;
99
+ BlockedIps.refusedHash = "";
100
+ BlockedIps.apply(parsed);
101
+ const active = BlockedIps.entries.filter(e => BlockedIps.active(e)).length;
102
+ (0, LogService_1.logInfo)(`Blocked IPs ${initial ? "loaded" : "reloaded"} from ${file}: ${active} active of ${parsed.length}`);
103
+ }
104
+ static active(e, now = Date.now()) {
105
+ return !e.until || Date.parse(e.until) > now;
106
+ }
107
+ static apply(entries) {
108
+ BlockedIps.entries = entries;
109
+ const now = Date.now();
110
+ const live = entries.filter(e => BlockedIps.active(e, now));
111
+ BlockedIps.list = IpAllowList_1.IpAllowList.build(live.map(e => e.ip)).list;
112
+ BlockedIps.nextExpiry = Math.min(Infinity, ...live.filter(e => e.until).map(e => Date.parse(e.until)));
113
+ }
114
+ static isBlocked(ip) {
115
+ if (!BlockedIps.list || !ip || ip === "127.0.0.1" || ip === "::1")
116
+ return false;
117
+ if (Date.now() >= BlockedIps.nextExpiry)
118
+ BlockedIps.apply(BlockedIps.entries);
119
+ return !!BlockedIps.list && IpAllowList_1.IpAllowList.allows(BlockedIps.list, ip);
120
+ }
121
+ static noteHit(ip) {
122
+ const h = BlockedIps.hits.get(ip) ?? { count: 0, lastLogged: 0 };
123
+ h.count++;
124
+ if (Date.now() - h.lastLogged > 10 * 60 * 1000) {
125
+ h.lastLogged = Date.now();
126
+ (0, LogService_1.logWarn)(`Blocked IPs: refused ${ip} (${h.count} request(s) so far)`);
127
+ }
128
+ BlockedIps.hits.set(ip, h);
129
+ if (BlockedIps.hits.size > 10000)
130
+ BlockedIps.hits.delete(BlockedIps.hits.keys().next().value);
131
+ }
132
+ static snapshot() {
133
+ const now = Date.now();
134
+ return {
135
+ file: BlockedIps.file,
136
+ entries: BlockedIps.entries.map(e => ({ ...e, active: BlockedIps.active(e, now) })),
137
+ hits: Object.fromEntries(Array.from(BlockedIps.hits.entries()).map(([ip, h]) => [ip, h.count])),
138
+ };
139
+ }
140
+ static update(change) {
141
+ const file = BlockedIps.file;
142
+ if (!file)
143
+ throw new Error("blocked IPs are not configured");
144
+ let current = [];
145
+ const raw = fs_1.default.existsSync(file) ? fs_1.default.readFileSync(file, "utf-8") : "";
146
+ if (raw.trim()) {
147
+ let parsed;
148
+ try {
149
+ parsed = JSON.parse(raw);
150
+ }
151
+ catch {
152
+ throw new Error(`${file} is not valid JSON — fix it by hand first`);
153
+ }
154
+ const problem = BlockedIps.validate(parsed);
155
+ if (problem)
156
+ throw new Error(`${file} is invalid (${problem}) — fix it by hand first`);
157
+ current = parsed;
158
+ }
159
+ const next = change(current);
160
+ const tmp = file + ".tmp";
161
+ fs_1.default.writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n", { encoding: "utf-8", mode: 0o600 });
162
+ fs_1.default.renameSync(tmp, file);
163
+ BlockedIps.load();
164
+ }
165
+ static add(entry) {
166
+ BlockedIps.update(list => [...list.filter(e => e.ip !== entry.ip), entry]);
167
+ }
168
+ static remove(ip) {
169
+ let removed = false;
170
+ BlockedIps.update(list => list.filter(e => { if (e.ip === ip) {
171
+ removed = true;
172
+ return false;
173
+ } return true; }));
174
+ return removed;
175
+ }
176
+ static watch() {
177
+ if (BlockedIps.watching || !BlockedIps.file)
178
+ return;
179
+ BlockedIps.watching = true;
180
+ const dir = path_1.default.dirname(BlockedIps.file), name = path_1.default.basename(BlockedIps.file);
181
+ try {
182
+ fs_1.default.watch(dir, (_e, filename) => {
183
+ if (filename && filename !== name)
184
+ return;
185
+ if (BlockedIps.debounce)
186
+ clearTimeout(BlockedIps.debounce);
187
+ BlockedIps.debounce = setTimeout(() => { BlockedIps.debounce = null; BlockedIps.load(); }, 200);
188
+ }).unref();
189
+ }
190
+ catch (e) {
191
+ (0, LogService_1.logWarn)(`Blocked IPs: cannot watch ${dir} (${e?.message ?? e}) — changes are picked up within a minute`);
192
+ }
193
+ setInterval(() => BlockedIps.load(), 60_000).unref();
194
+ }
195
+ }
196
+ exports.BlockedIps = BlockedIps;
@@ -64,7 +64,7 @@ Authorization: Bearer ‹token из login›
64
64
 
65
65
  - Токен держи **в памяти вкладки**, не в localStorage.
66
66
  - Повторное подключение 2FA через API **невозможно** — это защита от перепривязки чужим человеком, узнавшим пароль. Потерян телефон → администратор удаляет запись в файле 2FA на сервере.
67
- - Пароль в конфиге хранится **только как хеш** (`npx badmfck hash-password`; длину не меньше 12 символов проверяет сама команда). Если в конфиге пароль открытым текстом, вход с верным паролем вернёт `password is built incorrectly — the config must hold a hash…`, а с неверным — обычный `Invalid user`. Покажи `details` как есть: исправить это может только администратор сервера.
67
+ - Пароль в конфиге хранится **только как хеш** (`npx badmfck hash-password`; длину не меньше 12 символов проверяет сама команда). Если в конфиге пароль открытым текстом, вход отклоняется обычным `Invalid user`, как при неверном пароле. Причину видит только администратор в логе сервера.
68
68
 
69
69
  ```js
70
70
  async function sm(endpoint, body = {}, token) {
@@ -134,7 +134,10 @@ async function sm(endpoint, body = {}, token) {
134
134
  | `netlog` / `outgoingnetlog` | logs | — | входящие / исходящие запросы |
135
135
  | `logfiles` | logs | — | какие файловые логи доступны |
136
136
  | `logtail` | logs | `source`, `lines?`, `since?`, `filter?` | хвост файлового лога |
137
- | `threats` | logs | `limit?` | попытки прощупать систему: подозрительные IP и последние события |
137
+ | `threats` | logs | `limit?` | попытки прощупать систему: подозрительные IP и последние события; у каждого IP флаг `blocked` |
138
+ | `blocked` | logs | — | список заблокированных адресов и сколько запросов от них отклонено |
139
+ | `block` | admin | `ip`, `reason?`, `hours?` | заблокировать адрес или подсеть (`hours` пусто/0 — навсегда) |
140
+ | `unblock` | admin | `ip` | снять блокировку |
138
141
  | `changeLogLevel` | admin | `level` | сменить уровень логирования |
139
142
  | `restart` | admin | `confirm`, `password`, `totp?` | перезапуск процесса |
140
143
 
@@ -160,6 +163,41 @@ await sm("restart", {
160
163
 
161
164
  ---
162
165
 
166
+ ## 5.1. Блокировка адресов — `block` / `unblock` / `blocked`
167
+
168
+ Заблокированный адрес получает `403` на **любой** запрос к сервису (API, WebSocket, монитор), с текстом из настроек сервиса.
169
+
170
+ **Где показывать:** на странице угроз у каждого адреса из `offenders` есть `blocked: true|false`.
171
+ - `blocked: false` → кнопка «Заблокировать» (только для роли `admin`, см. `capabilities`);
172
+ - `blocked: true` → метка «заблокирован» и кнопка «Разблокировать».
173
+
174
+ **Диалог блокировки:** адрес (можно подсеть, `10.0.0.0/24`), причина (необязательно, видна только в мониторе), срок — «навсегда» или часы.
175
+
176
+ ```js
177
+ await sm("block", { ip: "203.0.113.7", reason: "brute force", hours: 24 }, token); // hours: 0 или нет — навсегда
178
+ await sm("unblock", { ip: "203.0.113.7" }, token);
179
+ const { entries, hits } = await sm("blocked", {}, token);
180
+ ```
181
+
182
+ `blocked` возвращает:
183
+ ```jsonc
184
+ { "file": "/var/node/app/blocked-ips.json",
185
+ "entries": [ { "ip": "203.0.113.7", "reason": "brute force", "until": "2026-11-11T10:00:00.000Z",
186
+ "by": "ops", "at": "2026-11-10T10:00:00.000Z", "active": true } ],
187
+ "hits": { "203.0.113.7": 42 } } // сколько запросов отклонено с момента старта
188
+ ```
189
+
190
+ Ответы `block` и `unblock` — тот же объект, обновлять список можно сразу из ответа.
191
+
192
+ **Ошибки (`400`, текст в `details` — показывай как есть):**
193
+ - `This would block your own address (…)` — админ пытается заблокировать себя;
194
+ - `Loopback can't be blocked`;
195
+ - неверный адрес или подсеть.
196
+
197
+ Записи с `active: false` — истёкшие блокировки (их срок прошёл); их можно показывать серым или скрывать.
198
+
199
+ ---
200
+
163
201
  ## 6. Данные: что и как рисовать
164
202
 
165
203
  ### `procinfo`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badmfck-api-server",
3
- "version": "6.0.4",
3
+ "version": "6.0.5",
4
4
  "description": "Simple API http server based on express",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",