@bmfk/api 0.0.0-stage → 1.0.1
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 +90 -0
- package/LICENSE +21 -0
- package/README.md +1293 -2
- package/dist/apiServer/APIService.d.ts +125 -0
- package/dist/apiServer/APIService.js +769 -0
- package/dist/apiServer/BaseEndpoint.d.ts +90 -0
- package/dist/apiServer/BaseEndpoint.js +314 -0
- package/dist/apiServer/BaseService.d.ts +17 -0
- package/dist/apiServer/BaseService.js +39 -0
- package/dist/apiServer/DBService.d.ts +131 -0
- package/dist/apiServer/DBService.js +290 -0
- package/dist/apiServer/DocumentService.d.ts +9 -0
- package/dist/apiServer/DocumentService.js +65 -0
- package/dist/apiServer/LocalRequest.d.ts +3 -0
- package/dist/apiServer/LocalRequest.js +6 -0
- package/dist/apiServer/LogService.d.ts +78 -0
- package/dist/apiServer/LogService.js +349 -0
- package/dist/apiServer/MonitorService.d.ts +102 -0
- package/dist/apiServer/MonitorService.js +615 -0
- package/dist/apiServer/StatService.d.ts +4 -0
- package/dist/apiServer/StatService.js +10 -0
- package/dist/apiServer/TimeframeService.d.ts +28 -0
- package/dist/apiServer/TimeframeService.js +97 -0
- package/dist/apiServer/WebSocketServer.d.ts +39 -0
- package/dist/apiServer/WebSocketServer.js +173 -0
- package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
- package/dist/apiServer/db/IDBAdapter.js +2 -0
- package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
- package/dist/apiServer/db/MysqlAdapter.js +869 -0
- package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
- package/dist/apiServer/db/PostgresAdapter.js +73 -0
- package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
- package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
- package/dist/apiServer/deployment/Activate.d.ts +4 -0
- package/dist/apiServer/deployment/Activate.js +124 -0
- package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
- package/dist/apiServer/deployment/BackupManager.js +174 -0
- package/dist/apiServer/deployment/Backups.d.ts +2 -0
- package/dist/apiServer/deployment/Backups.js +44 -0
- package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
- package/dist/apiServer/deployment/BlueGreenState.js +150 -0
- package/dist/apiServer/deployment/Bundler.d.ts +12 -0
- package/dist/apiServer/deployment/Bundler.js +178 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
- package/dist/apiServer/deployment/ConfigService.js +195 -0
- package/dist/apiServer/deployment/Deploy.d.ts +4 -0
- package/dist/apiServer/deployment/Deploy.js +404 -0
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
- package/dist/apiServer/deployment/Deployer.d.ts +13 -0
- package/dist/apiServer/deployment/Deployer.js +96 -0
- package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
- package/dist/apiServer/deployment/DeployerInit.js +214 -0
- package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
- package/dist/apiServer/deployment/DeployerService.js +1553 -0
- package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
- package/dist/apiServer/deployment/HashPassword.js +126 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
- package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
- package/dist/apiServer/deployment/MigrateProject.js +335 -0
- package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
- package/dist/apiServer/deployment/NginxHelper.js +111 -0
- package/dist/apiServer/deployment/Notifier.d.ts +30 -0
- package/dist/apiServer/deployment/Notifier.js +82 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
- package/dist/apiServer/deployment/Restore.d.ts +2 -0
- package/dist/apiServer/deployment/Restore.js +89 -0
- package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
- package/dist/apiServer/deployment/ReviewStore.js +186 -0
- package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
- package/dist/apiServer/deployment/SecretsInjector.js +189 -0
- package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
- package/dist/apiServer/deployment/Status.d.ts +2 -0
- package/dist/apiServer/deployment/Status.js +83 -0
- package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
- package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
- package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
- package/dist/apiServer/deployment/Watchdog.js +65 -0
- package/dist/apiServer/deployment/Wizards.d.ts +1 -0
- package/dist/apiServer/deployment/Wizards.js +83 -0
- package/dist/apiServer/deployment/cli.d.ts +2 -0
- package/dist/apiServer/deployment/cli.js +224 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
- package/dist/apiServer/deployment/cliCommon.js +110 -0
- package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
- package/dist/apiServer/deployment/cliPrompt.js +38 -0
- package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
- package/dist/apiServer/deployment/resolveConfig.js +139 -0
- package/dist/apiServer/documentation/Documentation.d.ts +18 -0
- package/dist/apiServer/documentation/Documentation.js +143 -0
- package/dist/apiServer/documentation/index.html +460 -0
- package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
- package/dist/apiServer/external/MicroserviceClient.js +144 -0
- package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
- package/dist/apiServer/external/MicroserviceHost.js +183 -0
- package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
- package/dist/apiServer/external/MicroserviceHostController.js +65 -0
- package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
- package/dist/apiServer/helper/AppDataPath.js +81 -0
- package/dist/apiServer/helper/ClientIp.d.ts +3 -0
- package/dist/apiServer/helper/ClientIp.js +33 -0
- package/dist/apiServer/helper/DataProvider.d.ts +18 -0
- package/dist/apiServer/helper/DataProvider.js +57 -0
- package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
- package/dist/apiServer/helper/IpAllowList.js +40 -0
- package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
- package/dist/apiServer/helper/JSONStableStringify.js +15 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/helper/Sleep.d.ts +1 -0
- package/dist/apiServer/helper/Sleep.js +5 -0
- package/dist/apiServer/helper/Trace.d.ts +8 -0
- package/dist/apiServer/helper/Trace.js +30 -0
- package/dist/apiServer/helper/UID.d.ts +16 -0
- package/dist/apiServer/helper/UID.js +98 -0
- package/dist/apiServer/helper/Validator.d.ts +86 -0
- package/dist/apiServer/helper/Validator.js +560 -0
- package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
- package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
- package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
- package/dist/apiServer/helper/ZipUtils.js +28 -0
- package/dist/apiServer/http/Http.d.ts +183 -0
- package/dist/apiServer/http/Http.js +627 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
- package/dist/apiServer/monitor/AccessStore.js +163 -0
- package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
- package/dist/apiServer/monitor/LogFiles.js +109 -0
- package/dist/apiServer/monitor/Monitor.d.ts +54 -0
- package/dist/apiServer/monitor/Monitor.js +447 -0
- package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
- package/dist/apiServer/monitor/MonitorAuth.js +474 -0
- package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
- package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
- package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
- package/dist/apiServer/monitor/SystemInfo.js +217 -0
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
- package/dist/apiServer/monitor/index.html +591 -0
- package/dist/apiServer/review/Review.d.ts +23 -0
- package/dist/apiServer/review/Review.js +149 -0
- package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
- package/dist/apiServer/review/ReviewAuth.js +147 -0
- package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
- package/dist/apiServer/review/ReviewDiff.js +175 -0
- package/dist/apiServer/review/index.html +501 -0
- package/dist/apiServer/routes/Liveness.d.ts +7 -0
- package/dist/apiServer/routes/Liveness.js +27 -0
- package/dist/apiServer/routes/Readiness.d.ts +13 -0
- package/dist/apiServer/routes/Readiness.js +20 -0
- package/dist/apiServer/security/BlockedIps.d.ts +46 -0
- package/dist/apiServer/security/BlockedIps.js +185 -0
- package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
- package/dist/apiServer/structures/DefaultErrors.js +52 -0
- package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
- package/dist/apiServer/structures/HTTPStatus.js +11 -0
- package/dist/apiServer/structures/Interfaces.d.ts +55 -0
- package/dist/apiServer/structures/Interfaces.js +2 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +110 -0
- package/dist/signal/Signal.d.ts +23 -0
- package/dist/signal/Signal.js +85 -0
- package/package.json +88 -4
|
@@ -0,0 +1,217 @@
|
|
|
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.collectSystemInfo = collectSystemInfo;
|
|
7
|
+
const os_1 = __importDefault(require("os"));
|
|
8
|
+
const child_process_1 = require("child_process");
|
|
9
|
+
const util_1 = require("util");
|
|
10
|
+
const promises_1 = __importDefault(require("fs/promises"));
|
|
11
|
+
const execP = (0, util_1.promisify)(child_process_1.exec);
|
|
12
|
+
async function safeExec(cmd, timeoutMs = 3000) {
|
|
13
|
+
try {
|
|
14
|
+
const { stdout, stderr } = await execP(cmd, {
|
|
15
|
+
timeout: timeoutMs,
|
|
16
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
17
|
+
shell: "/bin/sh",
|
|
18
|
+
});
|
|
19
|
+
return { ok: true, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), code: 0 };
|
|
20
|
+
}
|
|
21
|
+
catch (e) {
|
|
22
|
+
return {
|
|
23
|
+
ok: false,
|
|
24
|
+
stdout: e?.stdout != null ? String(e.stdout) : "",
|
|
25
|
+
stderr: e?.stderr != null ? String(e.stderr) : String(e?.message ?? e),
|
|
26
|
+
code: typeof e?.code === "number" ? e.code : -1,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function commandExists(cmd) {
|
|
31
|
+
const r = await safeExec(`command -v ${cmd}`, 1000);
|
|
32
|
+
return r.ok && r.stdout.trim().length > 0;
|
|
33
|
+
}
|
|
34
|
+
function cpuStatic() {
|
|
35
|
+
const cpus = os_1.default.cpus();
|
|
36
|
+
const models = {};
|
|
37
|
+
for (const c of cpus)
|
|
38
|
+
models[c.model] = (models[c.model] ?? 0) + 1;
|
|
39
|
+
return {
|
|
40
|
+
count: cpus.length,
|
|
41
|
+
models,
|
|
42
|
+
loadAvg: os_1.default.loadavg(),
|
|
43
|
+
platform: process.platform,
|
|
44
|
+
arch: process.arch,
|
|
45
|
+
uptimeSec: os_1.default.uptime(),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
async function cpuUsage(sampleMs = 200) {
|
|
49
|
+
if (process.platform !== "linux")
|
|
50
|
+
return null;
|
|
51
|
+
const read = async () => {
|
|
52
|
+
try {
|
|
53
|
+
const txt = await promises_1.default.readFile("/proc/stat", "utf-8");
|
|
54
|
+
const line = txt.split("\n", 1)[0];
|
|
55
|
+
const parts = line.split(/\s+/).slice(1).map(s => parseInt(s, 10) || 0);
|
|
56
|
+
return {
|
|
57
|
+
user: parts[0] ?? 0,
|
|
58
|
+
nice: parts[1] ?? 0,
|
|
59
|
+
system: parts[2] ?? 0,
|
|
60
|
+
idle: parts[3] ?? 0,
|
|
61
|
+
iowait: parts[4] ?? 0,
|
|
62
|
+
irq: parts[5] ?? 0,
|
|
63
|
+
softirq: parts[6] ?? 0,
|
|
64
|
+
steal: parts[7] ?? 0,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
const a = await read();
|
|
72
|
+
if (!a)
|
|
73
|
+
return null;
|
|
74
|
+
await new Promise(r => setTimeout(r, sampleMs));
|
|
75
|
+
const b = await read();
|
|
76
|
+
if (!b)
|
|
77
|
+
return null;
|
|
78
|
+
const sum = (x) => x.user + x.nice + x.system + x.idle + x.iowait + x.irq + x.softirq + x.steal;
|
|
79
|
+
const total = sum(b) - sum(a);
|
|
80
|
+
if (total <= 0)
|
|
81
|
+
return null;
|
|
82
|
+
const pct = (delta) => Math.round((delta / total) * 1000) / 10;
|
|
83
|
+
return {
|
|
84
|
+
userPct: pct(b.user + b.nice - a.user - a.nice),
|
|
85
|
+
systemPct: pct(b.system - a.system),
|
|
86
|
+
idlePct: pct(b.idle - a.idle),
|
|
87
|
+
iowaitPct: pct(b.iowait - a.iowait),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function memory() {
|
|
91
|
+
const total = os_1.default.totalmem();
|
|
92
|
+
const free = os_1.default.freemem();
|
|
93
|
+
return {
|
|
94
|
+
total,
|
|
95
|
+
free,
|
|
96
|
+
used: total - free,
|
|
97
|
+
usedPct: Math.round(((total - free) / total) * 1000) / 10,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
async function disk() {
|
|
101
|
+
const r = await safeExec("df -kP");
|
|
102
|
+
if (!r.ok)
|
|
103
|
+
return null;
|
|
104
|
+
const lines = r.stdout.split("\n").slice(1).filter(l => l.trim().length > 0);
|
|
105
|
+
return lines
|
|
106
|
+
.map(line => {
|
|
107
|
+
const parts = line.trim().split(/\s+/);
|
|
108
|
+
if (parts.length < 6)
|
|
109
|
+
return null;
|
|
110
|
+
const sizeKB = parseInt(parts[1], 10) || 0;
|
|
111
|
+
const usedKB = parseInt(parts[2], 10) || 0;
|
|
112
|
+
const availKB = parseInt(parts[3], 10) || 0;
|
|
113
|
+
return {
|
|
114
|
+
filesystem: parts[0],
|
|
115
|
+
size: sizeKB * 1024,
|
|
116
|
+
used: usedKB * 1024,
|
|
117
|
+
available: availKB * 1024,
|
|
118
|
+
usePct: parts[4],
|
|
119
|
+
mount: parts.slice(5).join(" "),
|
|
120
|
+
};
|
|
121
|
+
})
|
|
122
|
+
.filter((d) => d !== null)
|
|
123
|
+
.filter(d => !/^(tmpfs|devtmpfs|squashfs|overlay|udev|none|run)/.test(d.filesystem));
|
|
124
|
+
}
|
|
125
|
+
async function httpConnections(ports = [80, 443]) {
|
|
126
|
+
const portList = ports.join("|");
|
|
127
|
+
const ssCmd = `ss -tnH 2>/dev/null | awk '$1=="ESTAB" && $4 ~ /:(${portList})$/ {print $4, $5}'`;
|
|
128
|
+
let r = await safeExec(ssCmd);
|
|
129
|
+
if (!r.ok || r.stdout.trim().length === 0) {
|
|
130
|
+
const nsCmd = `netstat -tn 2>/dev/null | awk '$6=="ESTABLISHED" && $4 ~ /:(${portList})$/ {print $4, $5}'`;
|
|
131
|
+
r = await safeExec(nsCmd);
|
|
132
|
+
if (!r.ok)
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const lines = r.stdout.split("\n").filter(l => l.trim().length > 0);
|
|
136
|
+
const byRemote = {};
|
|
137
|
+
for (const line of lines) {
|
|
138
|
+
const parts = line.split(/\s+/);
|
|
139
|
+
const remote = parts[1] ?? "";
|
|
140
|
+
const ipMatch = remote.match(/^\[?([^\]]+)\]?:\d+$/);
|
|
141
|
+
const ip = ipMatch ? ipMatch[1] : remote;
|
|
142
|
+
byRemote[ip] = (byRemote[ip] ?? 0) + 1;
|
|
143
|
+
}
|
|
144
|
+
const topRemote = Object.entries(byRemote)
|
|
145
|
+
.sort(([, a], [, b]) => b - a)
|
|
146
|
+
.slice(0, 20)
|
|
147
|
+
.map(([ip, count]) => ({ ip, count }));
|
|
148
|
+
return { ports, total: lines.length, topRemote };
|
|
149
|
+
}
|
|
150
|
+
async function nginx() {
|
|
151
|
+
const installed = await commandExists("nginx");
|
|
152
|
+
if (!installed)
|
|
153
|
+
return { installed: false };
|
|
154
|
+
const [version, status, listening, workers] = await Promise.all([
|
|
155
|
+
safeExec("nginx -v 2>&1", 1000),
|
|
156
|
+
safeExec("systemctl is-active nginx 2>/dev/null", 1000),
|
|
157
|
+
safeExec("ss -tlnH 2>/dev/null | awk '{print $4}'", 1000),
|
|
158
|
+
safeExec("pgrep -c nginx 2>/dev/null", 1000),
|
|
159
|
+
]);
|
|
160
|
+
return {
|
|
161
|
+
installed: true,
|
|
162
|
+
version: (version.stdout || version.stderr).trim(),
|
|
163
|
+
status: status.stdout.trim() || "unknown",
|
|
164
|
+
listening: listening.stdout.split("\n").filter(l => l.trim().length > 0),
|
|
165
|
+
workerCount: parseInt(workers.stdout.trim(), 10) || 0,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
async function pm2() {
|
|
169
|
+
const installed = await commandExists("pm2");
|
|
170
|
+
if (!installed)
|
|
171
|
+
return { installed: false };
|
|
172
|
+
const r = await safeExec("pm2 jlist 2>/dev/null", 3000);
|
|
173
|
+
if (!r.ok)
|
|
174
|
+
return { installed: true, error: r.stderr.slice(0, 500) };
|
|
175
|
+
const text = r.stdout;
|
|
176
|
+
const start = text.indexOf("[");
|
|
177
|
+
const end = text.lastIndexOf("]");
|
|
178
|
+
if (start === -1 || end === -1)
|
|
179
|
+
return { installed: true, error: "no JSON in pm2 jlist output" };
|
|
180
|
+
try {
|
|
181
|
+
const arr = JSON.parse(text.slice(start, end + 1));
|
|
182
|
+
const processes = arr.map((p) => ({
|
|
183
|
+
name: p.name,
|
|
184
|
+
pid: p.pid,
|
|
185
|
+
pm_id: p.pm_id,
|
|
186
|
+
status: p.pm2_env?.status,
|
|
187
|
+
uptime: p.pm2_env?.pm_uptime,
|
|
188
|
+
restarts: p.pm2_env?.restart_time,
|
|
189
|
+
cpu: p.monit?.cpu,
|
|
190
|
+
memory: p.monit?.memory,
|
|
191
|
+
exec_mode: p.pm2_env?.exec_mode,
|
|
192
|
+
instances: p.pm2_env?.instances,
|
|
193
|
+
node_version: p.pm2_env?.node_version,
|
|
194
|
+
}));
|
|
195
|
+
return { installed: true, processes };
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
return { installed: true, error: "Failed to parse pm2 jlist output" };
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
async function collectSystemInfo() {
|
|
202
|
+
const [cpuUsageData, diskData, connectionsData, nginxData, pm2Data] = await Promise.all([
|
|
203
|
+
cpuUsage().catch(() => null),
|
|
204
|
+
disk().catch(() => null),
|
|
205
|
+
httpConnections().catch(() => null),
|
|
206
|
+
nginx().catch(() => ({ installed: false, error: "probe failed" })),
|
|
207
|
+
pm2().catch(() => ({ installed: false, error: "probe failed" })),
|
|
208
|
+
]);
|
|
209
|
+
return {
|
|
210
|
+
cpu: { ...cpuStatic(), usage: cpuUsageData },
|
|
211
|
+
memory: memory(),
|
|
212
|
+
disk: diskData,
|
|
213
|
+
connections: connectionsData,
|
|
214
|
+
nginx: nginxData,
|
|
215
|
+
pm2: pm2Data,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
export type TThreatCategory = "scanner" | "injection" | "enumeration" | "auth" | "method" | "not-found";
|
|
2
|
+
export type TThreatLevel = "none" | "suspicious" | "high";
|
|
3
|
+
interface ISample {
|
|
4
|
+
ts: number;
|
|
5
|
+
method: string;
|
|
6
|
+
url: string;
|
|
7
|
+
status: number;
|
|
8
|
+
categories: TThreatCategory[];
|
|
9
|
+
}
|
|
10
|
+
export interface IThreatObservation {
|
|
11
|
+
ip: string;
|
|
12
|
+
method: string;
|
|
13
|
+
url: string;
|
|
14
|
+
status: number;
|
|
15
|
+
ua?: string | null;
|
|
16
|
+
body?: unknown;
|
|
17
|
+
contentLength?: number;
|
|
18
|
+
}
|
|
19
|
+
export declare class ThreatMonitor {
|
|
20
|
+
static HALF_LIFE_MS: number;
|
|
21
|
+
static LEVEL_SUSPICIOUS: number;
|
|
22
|
+
static LEVEL_HIGH: number;
|
|
23
|
+
static ENUM_WINDOW_MS: number;
|
|
24
|
+
static ENUM_DISTINCT_PATHS: number;
|
|
25
|
+
static MAX_IPS: number;
|
|
26
|
+
static MAX_EVENTS: number;
|
|
27
|
+
static MAX_BODY_SCAN: number;
|
|
28
|
+
private static records;
|
|
29
|
+
private static events;
|
|
30
|
+
static SAVE_EVERY_MS: number;
|
|
31
|
+
private static file;
|
|
32
|
+
private static writer;
|
|
33
|
+
private static dirty;
|
|
34
|
+
private static timer;
|
|
35
|
+
static configure(file: string | null): void;
|
|
36
|
+
static save(): boolean;
|
|
37
|
+
private static load;
|
|
38
|
+
private static decayed;
|
|
39
|
+
static levelOf(score: number): TThreatLevel;
|
|
40
|
+
private static rank;
|
|
41
|
+
static classify(o: IThreatObservation): TThreatCategory[];
|
|
42
|
+
static observe(o: IThreatObservation): void;
|
|
43
|
+
static snapshot(limit?: number): {
|
|
44
|
+
generatedAt: number;
|
|
45
|
+
settings: {
|
|
46
|
+
halfLifeMinutes: number;
|
|
47
|
+
suspiciousAt: number;
|
|
48
|
+
highAt: number;
|
|
49
|
+
};
|
|
50
|
+
totals: {
|
|
51
|
+
tracked: number;
|
|
52
|
+
suspicious: number;
|
|
53
|
+
high: number;
|
|
54
|
+
};
|
|
55
|
+
offenders: {
|
|
56
|
+
ip: string;
|
|
57
|
+
score: number;
|
|
58
|
+
level: TThreatLevel;
|
|
59
|
+
firstSeen: number;
|
|
60
|
+
lastSeen: number;
|
|
61
|
+
hits: number;
|
|
62
|
+
categories: Partial<Record<TThreatCategory, number>>;
|
|
63
|
+
userAgent: string | null;
|
|
64
|
+
samples: ISample[];
|
|
65
|
+
}[];
|
|
66
|
+
recent: (ISample & {
|
|
67
|
+
ip: string;
|
|
68
|
+
score: number;
|
|
69
|
+
})[];
|
|
70
|
+
};
|
|
71
|
+
static reset(): void;
|
|
72
|
+
}
|
|
73
|
+
export {};
|
|
@@ -0,0 +1,239 @@
|
|
|
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.ThreatMonitor = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const LogService_1 = require("../LogService");
|
|
10
|
+
const AppDataPath_1 = require("../helper/AppDataPath");
|
|
11
|
+
const SCANNER_PATHS = [
|
|
12
|
+
/\/\.(?:env|git|svn|hg|aws|ssh|DS_Store|htaccess|htpasswd|npmrc|dockerenv)(?:[\/.]|$)/i,
|
|
13
|
+
/\/wp-(?:login|admin|content|includes|config|json)/i,
|
|
14
|
+
/\/(?:xmlrpc|phpinfo|phpmyadmin|adminer)\b/i,
|
|
15
|
+
/\/(?:cgi-bin|actuator|server-status|server-info|jmx-console|manager\/html)(?:\/|$)/i,
|
|
16
|
+
/\.(?:php\d?|aspx?|jsp|cgi|pl|cfm)(?:$|\?|\/)/i,
|
|
17
|
+
/(?:etc\/passwd|win\.ini|boot\.ini|id_rsa)/i,
|
|
18
|
+
];
|
|
19
|
+
const INJECTION = [
|
|
20
|
+
/\.\.(?:\/|\\|%2f|%5c)|%2e%2e(?:\/|%2f|%5c)/i,
|
|
21
|
+
/\bunion\b[\s\S]{0,40}\bselect\b|\bor\b\s+['"]?\d+['"]?\s*=\s*['"]?\d+|'\s*(?:or|and)\s+'|;\s*(?:drop|truncate)\s+table/i,
|
|
22
|
+
/<\s*script\b|javascript:|\bon(?:error|load)\s*=/i,
|
|
23
|
+
/\$\{\s*(?:jndi|env|sys|java):/i,
|
|
24
|
+
/(?:;|\|\||&&|\|)\s*(?:cat|wget|curl|bash|nc|whoami)\b|\$\((?:cat|id|whoami|curl|wget)\b/i,
|
|
25
|
+
];
|
|
26
|
+
const ODD_METHODS = new Set(["TRACE", "TRACK", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", "CONNECT", "DEBUG", "SEARCH"]);
|
|
27
|
+
const WEIGHT = {
|
|
28
|
+
scanner: 10, injection: 8, enumeration: 10, method: 5, auth: 2, "not-found": 1,
|
|
29
|
+
};
|
|
30
|
+
class ThreatMonitor {
|
|
31
|
+
static HALF_LIFE_MS = 30 * 60 * 1000;
|
|
32
|
+
static LEVEL_SUSPICIOUS = 10;
|
|
33
|
+
static LEVEL_HIGH = 30;
|
|
34
|
+
static ENUM_WINDOW_MS = 5 * 60 * 1000;
|
|
35
|
+
static ENUM_DISTINCT_PATHS = 10;
|
|
36
|
+
static MAX_IPS = 5000;
|
|
37
|
+
static MAX_EVENTS = 500;
|
|
38
|
+
static MAX_BODY_SCAN = 8 * 1024;
|
|
39
|
+
static records = new Map();
|
|
40
|
+
static events = [];
|
|
41
|
+
static SAVE_EVERY_MS = 60_000;
|
|
42
|
+
static file = null;
|
|
43
|
+
static writer = false;
|
|
44
|
+
static dirty = false;
|
|
45
|
+
static timer = null;
|
|
46
|
+
static configure(file) {
|
|
47
|
+
ThreatMonitor.file = file;
|
|
48
|
+
if (!file)
|
|
49
|
+
return;
|
|
50
|
+
ThreatMonitor.load();
|
|
51
|
+
(0, AppDataPath_1.onWriterChange)(writer => {
|
|
52
|
+
ThreatMonitor.writer = writer;
|
|
53
|
+
if (writer)
|
|
54
|
+
ThreatMonitor.load();
|
|
55
|
+
});
|
|
56
|
+
if (!ThreatMonitor.timer) {
|
|
57
|
+
ThreatMonitor.timer = setInterval(() => ThreatMonitor.save(), ThreatMonitor.SAVE_EVERY_MS);
|
|
58
|
+
ThreatMonitor.timer.unref?.();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
static save() {
|
|
62
|
+
const file = ThreatMonitor.file;
|
|
63
|
+
if (!file || !ThreatMonitor.writer || !ThreatMonitor.dirty)
|
|
64
|
+
return false;
|
|
65
|
+
try {
|
|
66
|
+
const doc = {
|
|
67
|
+
version: 1,
|
|
68
|
+
savedAt: Date.now(),
|
|
69
|
+
records: Array.from(ThreatMonitor.records.values()).map(r => ({ ...r, notFound: Array.from(r.notFound.entries()) })),
|
|
70
|
+
events: ThreatMonitor.events,
|
|
71
|
+
};
|
|
72
|
+
fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true, mode: 0o700 });
|
|
73
|
+
const tmp = file + ".tmp";
|
|
74
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify(doc), { mode: 0o600 });
|
|
75
|
+
fs_1.default.renameSync(tmp, file);
|
|
76
|
+
ThreatMonitor.dirty = false;
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
(0, LogService_1.logWarn)("threats: cannot save " + file + ": " + (e?.message ?? e));
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
static load() {
|
|
85
|
+
const file = ThreatMonitor.file;
|
|
86
|
+
if (!file || !fs_1.default.existsSync(file))
|
|
87
|
+
return;
|
|
88
|
+
let doc;
|
|
89
|
+
try {
|
|
90
|
+
doc = JSON.parse(fs_1.default.readFileSync(file, "utf-8"));
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
(0, LogService_1.logWarn)("threats: cannot read " + file + ": " + (e?.message ?? e));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
97
|
+
for (const raw of Array.isArray(doc?.records) ? doc.records : []) {
|
|
98
|
+
if (!raw || typeof raw.ip !== "string")
|
|
99
|
+
continue;
|
|
100
|
+
const mine = ThreatMonitor.records.get(raw.ip);
|
|
101
|
+
if (mine && mine.lastSeen >= num(raw.lastSeen))
|
|
102
|
+
continue;
|
|
103
|
+
ThreatMonitor.records.set(raw.ip, {
|
|
104
|
+
ip: raw.ip, score: num(raw.score), scoreAt: num(raw.scoreAt),
|
|
105
|
+
firstSeen: num(raw.firstSeen), lastSeen: num(raw.lastSeen), hits: num(raw.hits),
|
|
106
|
+
categories: raw.categories && typeof raw.categories === "object" ? raw.categories : {},
|
|
107
|
+
ua: typeof raw.ua === "string" ? raw.ua : null,
|
|
108
|
+
samples: Array.isArray(raw.samples) ? raw.samples.slice(-10) : [],
|
|
109
|
+
notFound: new Map(Array.isArray(raw.notFound) ? raw.notFound : []),
|
|
110
|
+
enumFlaggedAt: num(raw.enumFlaggedAt),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
const sorted = Array.from(ThreatMonitor.records.values()).sort((a, b) => a.lastSeen - b.lastSeen);
|
|
114
|
+
ThreatMonitor.records = new Map(sorted.slice(-ThreatMonitor.MAX_IPS).map(r => [r.ip, r]));
|
|
115
|
+
const seen = new Set(ThreatMonitor.events.map(e => `${e.ts}|${e.ip}|${e.url}`));
|
|
116
|
+
const incoming = (Array.isArray(doc?.events) ? doc.events : [])
|
|
117
|
+
.filter((e) => e && typeof e.ip === "string" && typeof e.ts === "number" && !seen.has(`${e.ts}|${e.ip}|${e.url}`));
|
|
118
|
+
ThreatMonitor.events = ThreatMonitor.events.concat(incoming).sort((a, b) => a.ts - b.ts).slice(-ThreatMonitor.MAX_EVENTS);
|
|
119
|
+
}
|
|
120
|
+
static decayed(r, now) {
|
|
121
|
+
return r.score * Math.pow(0.5, (now - r.scoreAt) / ThreatMonitor.HALF_LIFE_MS);
|
|
122
|
+
}
|
|
123
|
+
static levelOf(score) {
|
|
124
|
+
return score >= ThreatMonitor.LEVEL_HIGH ? "high" : score >= ThreatMonitor.LEVEL_SUSPICIOUS ? "suspicious" : "none";
|
|
125
|
+
}
|
|
126
|
+
static rank(l) { return l === "high" ? 2 : l === "suspicious" ? 1 : 0; }
|
|
127
|
+
static classify(o) {
|
|
128
|
+
const cats = new Set();
|
|
129
|
+
let target = String(o.url ?? "");
|
|
130
|
+
try {
|
|
131
|
+
target = decodeURIComponent(target);
|
|
132
|
+
}
|
|
133
|
+
catch { }
|
|
134
|
+
if (SCANNER_PATHS.some(r => r.test(target)))
|
|
135
|
+
cats.add("scanner");
|
|
136
|
+
if (INJECTION.some(r => r.test(target)))
|
|
137
|
+
cats.add("injection");
|
|
138
|
+
if (o.status >= 400 && !cats.has("injection") && o.body !== undefined && o.body !== null
|
|
139
|
+
&& !(o.contentLength && o.contentLength > 64 * 1024)) {
|
|
140
|
+
let text = "";
|
|
141
|
+
try {
|
|
142
|
+
text = typeof o.body === "string" ? o.body : JSON.stringify(o.body);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
text = "";
|
|
146
|
+
}
|
|
147
|
+
if (text && INJECTION.some(r => r.test(text.slice(0, ThreatMonitor.MAX_BODY_SCAN))))
|
|
148
|
+
cats.add("injection");
|
|
149
|
+
}
|
|
150
|
+
if (ODD_METHODS.has(String(o.method).toUpperCase()))
|
|
151
|
+
cats.add("method");
|
|
152
|
+
if (o.status === 401 || o.status === 403)
|
|
153
|
+
cats.add("auth");
|
|
154
|
+
if (o.status === 404)
|
|
155
|
+
cats.add("not-found");
|
|
156
|
+
return Array.from(cats);
|
|
157
|
+
}
|
|
158
|
+
static observe(o) {
|
|
159
|
+
if (!o || !o.ip)
|
|
160
|
+
return;
|
|
161
|
+
const cats = ThreatMonitor.classify(o);
|
|
162
|
+
if (cats.length === 0)
|
|
163
|
+
return;
|
|
164
|
+
const now = Date.now();
|
|
165
|
+
let r = ThreatMonitor.records.get(o.ip);
|
|
166
|
+
if (r)
|
|
167
|
+
ThreatMonitor.records.delete(o.ip);
|
|
168
|
+
else
|
|
169
|
+
r = { ip: o.ip, score: 0, scoreAt: now, firstSeen: now, lastSeen: now, hits: 0,
|
|
170
|
+
categories: {}, ua: null, samples: [], notFound: new Map(), enumFlaggedAt: 0 };
|
|
171
|
+
const path = String(o.url ?? "").split("?")[0];
|
|
172
|
+
if (cats.includes("not-found")) {
|
|
173
|
+
r.notFound.set(path, now);
|
|
174
|
+
for (const [p, ts] of r.notFound)
|
|
175
|
+
if (now - ts > ThreatMonitor.ENUM_WINDOW_MS)
|
|
176
|
+
r.notFound.delete(p);
|
|
177
|
+
while (r.notFound.size > 50)
|
|
178
|
+
r.notFound.delete(r.notFound.keys().next().value);
|
|
179
|
+
if (r.notFound.size >= ThreatMonitor.ENUM_DISTINCT_PATHS && now - r.enumFlaggedAt > ThreatMonitor.ENUM_WINDOW_MS) {
|
|
180
|
+
cats.push("enumeration");
|
|
181
|
+
r.enumFlaggedAt = now;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const before = ThreatMonitor.decayed(r, now);
|
|
185
|
+
const add = cats.reduce((sum, c) => sum + WEIGHT[c], 0);
|
|
186
|
+
r.score = before + add;
|
|
187
|
+
r.scoreAt = now;
|
|
188
|
+
r.lastSeen = now;
|
|
189
|
+
r.hits++;
|
|
190
|
+
if (o.ua)
|
|
191
|
+
r.ua = String(o.ua).slice(0, 200);
|
|
192
|
+
for (const c of cats)
|
|
193
|
+
r.categories[c] = (r.categories[c] ?? 0) + 1;
|
|
194
|
+
const sample = { ts: now, method: String(o.method), url: LogService_1.LogService.sanitize(String(o.url ?? "")).slice(0, 200),
|
|
195
|
+
status: o.status, categories: cats };
|
|
196
|
+
r.samples.push(sample);
|
|
197
|
+
if (r.samples.length > 10)
|
|
198
|
+
r.samples.shift();
|
|
199
|
+
ThreatMonitor.records.set(o.ip, r);
|
|
200
|
+
ThreatMonitor.dirty = true;
|
|
201
|
+
while (ThreatMonitor.records.size > ThreatMonitor.MAX_IPS)
|
|
202
|
+
ThreatMonitor.records.delete(ThreatMonitor.records.keys().next().value);
|
|
203
|
+
if (add >= WEIGHT.auth) {
|
|
204
|
+
ThreatMonitor.events.push({ ...sample, ip: o.ip, score: Math.round(r.score) });
|
|
205
|
+
if (ThreatMonitor.events.length > ThreatMonitor.MAX_EVENTS)
|
|
206
|
+
ThreatMonitor.events.shift();
|
|
207
|
+
}
|
|
208
|
+
const prev = ThreatMonitor.levelOf(before), next = ThreatMonitor.levelOf(r.score);
|
|
209
|
+
if (ThreatMonitor.rank(next) > ThreatMonitor.rank(prev)) {
|
|
210
|
+
const allCats = Object.keys(r.categories).join(",");
|
|
211
|
+
(0, LogService_1.logWarn)(`THREAT ip=${o.ip} level=${next} score=${Math.round(r.score)} categories=${allCats} last=${o.method} ${sample.url}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
static snapshot(limit = 50) {
|
|
215
|
+
const now = Date.now();
|
|
216
|
+
const offenders = Array.from(ThreatMonitor.records.values())
|
|
217
|
+
.map(r => {
|
|
218
|
+
const score = ThreatMonitor.decayed(r, now);
|
|
219
|
+
return { ip: r.ip, score: Math.round(score * 10) / 10, level: ThreatMonitor.levelOf(score),
|
|
220
|
+
firstSeen: r.firstSeen, lastSeen: r.lastSeen, hits: r.hits,
|
|
221
|
+
categories: r.categories, userAgent: r.ua, samples: r.samples.slice().reverse() };
|
|
222
|
+
})
|
|
223
|
+
.filter(o => o.score >= 1)
|
|
224
|
+
.sort((a, b) => b.score - a.score);
|
|
225
|
+
return {
|
|
226
|
+
generatedAt: now,
|
|
227
|
+
settings: { halfLifeMinutes: ThreatMonitor.HALF_LIFE_MS / 60000, suspiciousAt: ThreatMonitor.LEVEL_SUSPICIOUS, highAt: ThreatMonitor.LEVEL_HIGH },
|
|
228
|
+
totals: {
|
|
229
|
+
tracked: offenders.length,
|
|
230
|
+
suspicious: offenders.filter(o => o.level === "suspicious").length,
|
|
231
|
+
high: offenders.filter(o => o.level === "high").length,
|
|
232
|
+
},
|
|
233
|
+
offenders: offenders.slice(0, Math.max(1, Math.min(limit, 500))),
|
|
234
|
+
recent: ThreatMonitor.events.slice(-Math.max(1, Math.min(limit, 500))).reverse(),
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
static reset() { ThreatMonitor.records.clear(); ThreatMonitor.events = []; ThreatMonitor.dirty = true; }
|
|
238
|
+
}
|
|
239
|
+
exports.ThreatMonitor = ThreatMonitor;
|