badmfck-api-server 5.0.14 → 5.0.16
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/dist/apiServer/APIService.d.ts +2 -0
- package/dist/apiServer/APIService.js +23 -0
- package/dist/apiServer/MonitorService.js +11 -0
- package/dist/apiServer/deployment/Activate.js +1 -1
- package/dist/apiServer/deployment/Backups.js +1 -1
- package/dist/apiServer/deployment/Deploy.js +1 -1
- package/dist/apiServer/deployment/Deployer.js +5 -5
- package/dist/apiServer/deployment/DeployerService.d.ts +12 -0
- package/dist/apiServer/deployment/DeployerService.js +51 -21
- package/dist/apiServer/deployment/HashPassword.d.ts +1 -0
- package/dist/apiServer/deployment/HashPassword.js +91 -0
- package/dist/apiServer/deployment/Restore.js +1 -1
- package/dist/apiServer/deployment/Status.js +1 -1
- package/dist/apiServer/deployment/cli.js +11 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +1 -0
- package/dist/apiServer/deployment/cliCommon.js +4 -0
- package/dist/apiServer/helper/ClientIp.d.ts +2 -0
- package/dist/apiServer/helper/ClientIp.js +28 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/monitor/Monitor.d.ts +1 -0
- package/dist/apiServer/monitor/Monitor.js +17 -4
- package/dist/apiServer/monitor/MonitorAuth.d.ts +4 -2
- package/dist/apiServer/monitor/MonitorAuth.js +17 -7
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +65 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +153 -0
- package/dist/apiServer/monitor/index.html +115 -62
- package/dist/apiServer/structures/Interfaces.d.ts +1 -0
- package/monitoring.help.md +46 -0
- package/package.json +1 -1
|
@@ -60,6 +60,8 @@ export interface APIServiceOptions<TInterceptor = unknown> {
|
|
|
60
60
|
logFiles?: ILogFilesOptions;
|
|
61
61
|
monitorAuthDir?: string;
|
|
62
62
|
monitorAuthFile?: string;
|
|
63
|
+
threatMonitoring?: boolean;
|
|
64
|
+
trustedProxies?: string[];
|
|
63
65
|
}
|
|
64
66
|
type InferInterceptor<T> = T extends IInterceptor<infer U> ? U : unknown;
|
|
65
67
|
export declare const getDefaultOptions: <I extends IInterceptor<any> | undefined>(overrides?: Omit<Partial<APIServiceOptions<InferInterceptor<NonNullable<I>>>>, "interceptor"> & {
|
|
@@ -61,6 +61,8 @@ const Documentation_1 = require("./documentation/Documentation");
|
|
|
61
61
|
const MicroserviceHostController_1 = require("./external/MicroserviceHostController");
|
|
62
62
|
const DeployerService_1 = require("./deployment/DeployerService");
|
|
63
63
|
const BlueGreenState_1 = require("./deployment/BlueGreenState");
|
|
64
|
+
const ThreatMonitor_1 = require("./monitor/ThreatMonitor");
|
|
65
|
+
const ClientIp_1 = require("./helper/ClientIp");
|
|
64
66
|
const Deployer_1 = require("./deployment/Deployer");
|
|
65
67
|
let nextLogID = 0;
|
|
66
68
|
function defaultOptions() {
|
|
@@ -211,6 +213,26 @@ class APIService extends BaseService_1.BaseService {
|
|
|
211
213
|
return { error: DefaultErrors_1.default.UNKNOWN_REQUEST, data: null, httpStatus: 404 };
|
|
212
214
|
};
|
|
213
215
|
const app = (0, express_1.default)();
|
|
216
|
+
const trustedProxies = new Set(this.options.trustedProxies ?? ClientIp_1.DEFAULT_TRUSTED_PROXIES);
|
|
217
|
+
if (this.options.threatMonitoring !== false) {
|
|
218
|
+
app.use((req, res, next) => {
|
|
219
|
+
res.on("finish", () => {
|
|
220
|
+
try {
|
|
221
|
+
ThreatMonitor_1.ThreatMonitor.observe({
|
|
222
|
+
ip: (0, ClientIp_1.clientIp)(req, trustedProxies),
|
|
223
|
+
method: req.method,
|
|
224
|
+
url: req.originalUrl ?? req.url,
|
|
225
|
+
status: res.statusCode,
|
|
226
|
+
ua: req.get("user-agent") ?? null,
|
|
227
|
+
body: req.body,
|
|
228
|
+
contentLength: Number(req.get("content-length")) || 0,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
catch { }
|
|
232
|
+
});
|
|
233
|
+
next();
|
|
234
|
+
});
|
|
235
|
+
}
|
|
214
236
|
const server = http_1.default.createServer(app);
|
|
215
237
|
if (this.options.keepAliveTimeout !== undefined)
|
|
216
238
|
server.keepAliveTimeout = this.options.keepAliveTimeout;
|
|
@@ -351,6 +373,7 @@ class APIService extends BaseService_1.BaseService {
|
|
|
351
373
|
endpoint: ep,
|
|
352
374
|
files: req.files ?? null,
|
|
353
375
|
referer: req.get("Referer"),
|
|
376
|
+
ip: (0, ClientIp_1.clientIp)(req, trustedProxies),
|
|
354
377
|
};
|
|
355
378
|
let ignoreHttpLogging = j.ignoreHttpLogging ?? false;
|
|
356
379
|
if (!ignoreHttpLogging && typeof j.handler === "object") {
|
|
@@ -78,6 +78,17 @@ class MonitorService extends BaseService_1.BaseService {
|
|
|
78
78
|
exports.S_STAT_REGISTRATE_HTTP_RESULT.subscribe((data) => this.onHttpResultRegistrate(data));
|
|
79
79
|
exports.S_STAT_REGISTRATE_SQL_REQUEST.subscribe((data) => this.onSQLRequestRegistrate(data));
|
|
80
80
|
exports.S_STAT_REGISTRATE_REQUEST.subscribe((data) => this.onStatRegistrate(data));
|
|
81
|
+
if (!this.metricsDir) {
|
|
82
|
+
(0, LogService_1.logInfo)("Metrics persistence: OFF — history is in memory only and lost on restart. Set the APIService option metricsDir to keep it (sm/metricsWeeks).", "MonitorService");
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
this.metricsDir = path_1.default.resolve(this.metricsDir);
|
|
86
|
+
const appDir = path_1.default.resolve(process.cwd());
|
|
87
|
+
if (this.metricsDir === appDir || this.metricsDir.startsWith(appDir + path_1.default.sep))
|
|
88
|
+
(0, LogService_1.logWarn)(`Metrics persistence: metricsDir "${this.metricsDir}" is inside the application directory — a deploy that cleans it will erase the history. Use an absolute path outside the project.`);
|
|
89
|
+
else
|
|
90
|
+
(0, LogService_1.logInfo)(`Metrics persistence: ON → ${this.metricsDir}`, "MonitorService");
|
|
91
|
+
}
|
|
81
92
|
if (this.metricsDir) {
|
|
82
93
|
try {
|
|
83
94
|
await promises_1.default.mkdir(this.metricsDir, { recursive: true });
|
|
@@ -30,7 +30,7 @@ async function Activate(opt, scheme) {
|
|
|
30
30
|
console.log(`Activating${scheme ? ` slot=${scheme}` : " (auto: lastDeployed)"} for ${opt.name} at ${switchUrl}`);
|
|
31
31
|
const startedAt = Date.now();
|
|
32
32
|
const response = await __1.Http.post(switchUrl, requestBody, {
|
|
33
|
-
headers: { authorization: `Bearer ${authToken}
|
|
33
|
+
headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
|
|
34
34
|
timeoutMs: 60 * 1000,
|
|
35
35
|
retry: { enabled: false },
|
|
36
36
|
});
|
|
@@ -8,7 +8,7 @@ async function Backups(opt) {
|
|
|
8
8
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
9
9
|
const { red, yellow, blue, green, dim, bold } = (0, cliCommon_1.palette)();
|
|
10
10
|
const r = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, {
|
|
11
|
-
headers:
|
|
11
|
+
headers: (0, cliCommon_1.deployerHeaders)(opt), timeoutMs: 30000, retry: { enabled: false },
|
|
12
12
|
});
|
|
13
13
|
const err = (0, cliCommon_1.responseError)(r);
|
|
14
14
|
if (err) {
|
|
@@ -206,7 +206,7 @@ async function Deploy(opt) {
|
|
|
206
206
|
bodyTimeout: 5 * 60 * 1000,
|
|
207
207
|
});
|
|
208
208
|
const uploadResponse = await __1.Http.post(opt.host, formData, {
|
|
209
|
-
headers: { authorization: `Bearer ${authToken}
|
|
209
|
+
headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
|
|
210
210
|
dispatcher: uploadAgent,
|
|
211
211
|
timeoutMs: 5 * 60 * 1000,
|
|
212
212
|
retry: { enabled: false },
|
|
@@ -72,20 +72,20 @@ class Deployer extends BaseEndpoint_1.BaseEndpoint {
|
|
|
72
72
|
async file(req) {
|
|
73
73
|
if (!req.files)
|
|
74
74
|
throw { ...DefaultErrors_1.default.FILE_NOT_EXISTS, details: "No files were uploaded" };
|
|
75
|
-
const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization });
|
|
75
|
+
const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
76
76
|
return { data: result };
|
|
77
77
|
}
|
|
78
78
|
async switchSlot(req) {
|
|
79
|
-
return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization });
|
|
79
|
+
return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
80
80
|
}
|
|
81
81
|
async status(req) {
|
|
82
|
-
return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization });
|
|
82
|
+
return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
83
83
|
}
|
|
84
84
|
async backups(req) {
|
|
85
|
-
return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization });
|
|
85
|
+
return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
86
86
|
}
|
|
87
87
|
async restore(req) {
|
|
88
|
-
return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization });
|
|
88
|
+
return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
89
89
|
}
|
|
90
90
|
async slot(req) {
|
|
91
91
|
return await DeployerService_1.REQ_DEPLOYMENT_SLOT.request({ name: req.data.name, token: req.data.token, slot: req.data.slot });
|
|
@@ -29,6 +29,7 @@ export interface IDeployerServiceOptions {
|
|
|
29
29
|
}
|
|
30
30
|
export declare const REQ_DEPLOYMENT_PROCEED: Req<{
|
|
31
31
|
auth: string;
|
|
32
|
+
authLogin?: string;
|
|
32
33
|
name: string;
|
|
33
34
|
token: string;
|
|
34
35
|
files: {
|
|
@@ -37,12 +38,14 @@ export declare const REQ_DEPLOYMENT_PROCEED: Req<{
|
|
|
37
38
|
}, any>;
|
|
38
39
|
export declare const REQ_DEPLOYMENT_SWITCH: Req<{
|
|
39
40
|
auth?: string;
|
|
41
|
+
authLogin?: string;
|
|
40
42
|
name: string;
|
|
41
43
|
token: string;
|
|
42
44
|
scheme?: "blue" | "green";
|
|
43
45
|
}, any>;
|
|
44
46
|
export declare const REQ_DEPLOYMENT_STATUS: Req<{
|
|
45
47
|
auth?: string;
|
|
48
|
+
authLogin?: string;
|
|
46
49
|
name?: string;
|
|
47
50
|
}, any>;
|
|
48
51
|
export declare const REQ_DEPLOYMENT_SLOT: Req<{
|
|
@@ -52,10 +55,12 @@ export declare const REQ_DEPLOYMENT_SLOT: Req<{
|
|
|
52
55
|
}, any>;
|
|
53
56
|
export declare const REQ_DEPLOYMENT_BACKUPS: Req<{
|
|
54
57
|
auth?: string;
|
|
58
|
+
authLogin?: string;
|
|
55
59
|
name: string;
|
|
56
60
|
}, any>;
|
|
57
61
|
export declare const REQ_DEPLOYMENT_RESTORE: Req<{
|
|
58
62
|
auth?: string;
|
|
63
|
+
authLogin?: string;
|
|
59
64
|
name: string;
|
|
60
65
|
token: string;
|
|
61
66
|
backup: string;
|
|
@@ -76,6 +81,7 @@ export declare class DeployerService extends BaseService {
|
|
|
76
81
|
private _watchSetup;
|
|
77
82
|
proceed(data: {
|
|
78
83
|
auth?: string;
|
|
84
|
+
authLogin?: string;
|
|
79
85
|
name: string;
|
|
80
86
|
token: string;
|
|
81
87
|
files: {
|
|
@@ -101,6 +107,7 @@ export declare class DeployerService extends BaseService {
|
|
|
101
107
|
}>;
|
|
102
108
|
switchSlot(data: {
|
|
103
109
|
auth?: string;
|
|
110
|
+
authLogin?: string;
|
|
104
111
|
name: string;
|
|
105
112
|
token: string;
|
|
106
113
|
scheme?: "blue" | "green";
|
|
@@ -122,6 +129,7 @@ export declare class DeployerService extends BaseService {
|
|
|
122
129
|
}>;
|
|
123
130
|
status(data: {
|
|
124
131
|
auth?: string;
|
|
132
|
+
authLogin?: string;
|
|
125
133
|
name?: string;
|
|
126
134
|
}): Promise<{
|
|
127
135
|
data?: undefined;
|
|
@@ -142,6 +150,7 @@ export declare class DeployerService extends BaseService {
|
|
|
142
150
|
private static _backupRoot;
|
|
143
151
|
listBackups(data: {
|
|
144
152
|
auth?: string;
|
|
153
|
+
authLogin?: string;
|
|
145
154
|
name: string;
|
|
146
155
|
}): Promise<{
|
|
147
156
|
data?: undefined;
|
|
@@ -163,6 +172,7 @@ export declare class DeployerService extends BaseService {
|
|
|
163
172
|
}>;
|
|
164
173
|
restoreBackup(data: {
|
|
165
174
|
auth?: string;
|
|
175
|
+
authLogin?: string;
|
|
166
176
|
name: string;
|
|
167
177
|
token: string;
|
|
168
178
|
backup: string;
|
|
@@ -220,6 +230,8 @@ export declare class DeployerService extends BaseService {
|
|
|
220
230
|
private _statusUrl;
|
|
221
231
|
private _writeBlueGreenFiles;
|
|
222
232
|
tokensMatch(a: string | undefined, b: string | undefined): boolean;
|
|
233
|
+
private _warnPlaintextUsers;
|
|
234
|
+
static PLAINTEXT_ERROR: string;
|
|
223
235
|
private _checkUserAuth;
|
|
224
236
|
private static _extractPort;
|
|
225
237
|
private _renderNginx;
|
|
@@ -20,6 +20,7 @@ const Watchdog_1 = require("./Watchdog");
|
|
|
20
20
|
const NginxHelper_1 = require("./NginxHelper");
|
|
21
21
|
const BlueGreenState_1 = require("./BlueGreenState");
|
|
22
22
|
const BackupManager_1 = require("./BackupManager");
|
|
23
|
+
const PasswordHash_1 = require("../helper/PasswordHash");
|
|
23
24
|
const _TSetup = {
|
|
24
25
|
users: [{
|
|
25
26
|
login: "",
|
|
@@ -67,6 +68,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
67
68
|
throw new Error("Setup file missing/invalid at start — cannot start deployer");
|
|
68
69
|
}
|
|
69
70
|
this.setup = initial;
|
|
71
|
+
this._warnPlaintextUsers();
|
|
70
72
|
this._lastSetupHash = crypto_1.default.createHash("md5").update(JSON.stringify(initial)).digest("hex");
|
|
71
73
|
if (this.setup.notifier?.URL && this.setup.notifier?.KEY) {
|
|
72
74
|
this.notifier = new Notifier_1.Notifier({ URL: this.setup.notifier.URL, KEY: this.setup.notifier.KEY });
|
|
@@ -124,6 +126,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
124
126
|
return;
|
|
125
127
|
this._lastSetupHash = hash;
|
|
126
128
|
this.setup = fresh;
|
|
129
|
+
this._warnPlaintextUsers();
|
|
127
130
|
(0, LogService_1.logWarn)("Setup reloaded from disk (users list refreshed live; notifier/watchdog need service restart to change)");
|
|
128
131
|
}
|
|
129
132
|
_watchSetup() {
|
|
@@ -145,10 +148,11 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
145
148
|
setInterval(() => { this._reloadSetup(); }, 60_000).unref();
|
|
146
149
|
}
|
|
147
150
|
async proceed(data) {
|
|
148
|
-
const
|
|
151
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin);
|
|
152
|
+
const user = auth.user;
|
|
149
153
|
if (!user) {
|
|
150
154
|
(0, LogService_1.logError)("Deploy rejected: user auth failed");
|
|
151
|
-
return { error: { code: 20, message: "Unauthorized.", httpStatus: 401 } };
|
|
155
|
+
return { error: { code: 20, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
|
|
152
156
|
}
|
|
153
157
|
const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
|
|
154
158
|
let found;
|
|
@@ -369,10 +373,11 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
369
373
|
}
|
|
370
374
|
}
|
|
371
375
|
async switchSlot(data) {
|
|
372
|
-
const
|
|
376
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin);
|
|
377
|
+
const user = auth.user;
|
|
373
378
|
if (!user) {
|
|
374
379
|
(0, LogService_1.logError)("Switch rejected: user auth failed");
|
|
375
|
-
return { error: { code: 40, message: "Unauthorized.", httpStatus: 401 } };
|
|
380
|
+
return { error: { code: 40, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
|
|
376
381
|
}
|
|
377
382
|
const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
|
|
378
383
|
let found;
|
|
@@ -457,9 +462,10 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
457
462
|
}
|
|
458
463
|
}
|
|
459
464
|
async status(data) {
|
|
460
|
-
const
|
|
465
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin);
|
|
466
|
+
const user = auth.user;
|
|
461
467
|
if (!user) {
|
|
462
|
-
return { error: { code: 50, message: "Unauthorized.", httpStatus: 401 } };
|
|
468
|
+
return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
|
|
463
469
|
}
|
|
464
470
|
const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
|
|
465
471
|
const results = {};
|
|
@@ -490,9 +496,11 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
490
496
|
return DeployerService._isBlueGreen(found) ? dest : path_1.default.dirname(dest);
|
|
491
497
|
}
|
|
492
498
|
async listBackups(data) {
|
|
493
|
-
const
|
|
494
|
-
|
|
495
|
-
|
|
499
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin);
|
|
500
|
+
const user = auth.user;
|
|
501
|
+
if (!user) {
|
|
502
|
+
return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
|
|
503
|
+
}
|
|
496
504
|
const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
|
|
497
505
|
const found = Array.from(configurations.values()).find(c => c.name === data.name);
|
|
498
506
|
if (!found)
|
|
@@ -519,10 +527,11 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
519
527
|
} };
|
|
520
528
|
}
|
|
521
529
|
async restoreBackup(data) {
|
|
522
|
-
const
|
|
530
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin);
|
|
531
|
+
const user = auth.user;
|
|
523
532
|
if (!user) {
|
|
524
533
|
(0, LogService_1.logError)("Restore rejected: user auth failed");
|
|
525
|
-
return { error: { code: 50, message: "Unauthorized.", httpStatus: 401 } };
|
|
534
|
+
return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
|
|
526
535
|
}
|
|
527
536
|
const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
|
|
528
537
|
let found;
|
|
@@ -672,23 +681,44 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
672
681
|
const hb = new Uint8Array(crypto_1.default.createHash("sha256").update(String(b ?? "")).digest());
|
|
673
682
|
return crypto_1.default.timingSafeEqual(ha, hb);
|
|
674
683
|
}
|
|
675
|
-
|
|
684
|
+
_warnPlaintextUsers() {
|
|
685
|
+
const plain = (this.setup?.users ?? []).filter(u => u?.login && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
|
|
686
|
+
if (plain.length)
|
|
687
|
+
(0, LogService_1.logError)(`Deployer: password stored as plain text in setup.json for ${plain.map(l => '"' + l + '"').join(", ")} — these users are refused; store a hash instead: npx badmfck hash-password --deployer`);
|
|
688
|
+
}
|
|
689
|
+
static PLAINTEXT_ERROR = "Password is built incorrectly — setup.json must hold a hash from `npx badmfck hash-password --deployer`, not the password itself.";
|
|
690
|
+
async _checkUserAuth(authHeader, loginHeader) {
|
|
676
691
|
if (!authHeader)
|
|
677
|
-
return
|
|
692
|
+
return {};
|
|
678
693
|
if (!this.setup)
|
|
679
|
-
return
|
|
694
|
+
return {};
|
|
680
695
|
const token = authHeader.split(" ").pop() ?? "";
|
|
681
696
|
if (!token)
|
|
682
|
-
return
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
697
|
+
return {};
|
|
698
|
+
const users = this.setup.users ?? [];
|
|
699
|
+
if (users.length === 0)
|
|
700
|
+
return {};
|
|
701
|
+
const login = typeof loginHeader === "string" ? loginHeader.trim() : "";
|
|
702
|
+
if (login) {
|
|
703
|
+
const user = users.find(u => u.login === login);
|
|
704
|
+
if (user && PasswordHash_1.PasswordHash.isHash(user.password))
|
|
705
|
+
return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user } : {};
|
|
706
|
+
}
|
|
707
|
+
let plainMatch = false;
|
|
708
|
+
for (const user of users) {
|
|
709
|
+
if (PasswordHash_1.PasswordHash.isHash(user.password) || !user.password)
|
|
710
|
+
continue;
|
|
687
711
|
const expected = crypto_1.default.createHash("sha256").update(user.login + ":" + user.password).digest("hex");
|
|
688
712
|
if (this.tokensMatch(token, expected))
|
|
689
|
-
|
|
713
|
+
plainMatch = true;
|
|
714
|
+
}
|
|
715
|
+
if (plainMatch) {
|
|
716
|
+
(0, LogService_1.logError)("Deployer auth refused: user's password is stored as plain text in setup.json");
|
|
717
|
+
return { error: DeployerService.PLAINTEXT_ERROR };
|
|
690
718
|
}
|
|
691
|
-
|
|
719
|
+
if (!login)
|
|
720
|
+
(0, LogService_1.logWarn)("Deployer auth failed without X-Deployer-Login — update the badmfck CLI on the client");
|
|
721
|
+
return {};
|
|
692
722
|
}
|
|
693
723
|
static _extractPort(config) {
|
|
694
724
|
if (!config || typeof config !== "object")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function HashPassword(target: "monitor" | "deployer"): Promise<void>;
|
|
@@ -0,0 +1,91 @@
|
|
|
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.HashPassword = HashPassword;
|
|
7
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
const promises_1 = require("readline/promises");
|
|
9
|
+
const process_1 = require("process");
|
|
10
|
+
const PasswordHash_1 = require("../helper/PasswordHash");
|
|
11
|
+
const MonitorAuth_1 = require("../monitor/MonitorAuth");
|
|
12
|
+
const cliCommon_1 = require("./cliCommon");
|
|
13
|
+
function askHidden(question) {
|
|
14
|
+
return new Promise(resolve => {
|
|
15
|
+
process_1.stdout.write(question);
|
|
16
|
+
const wasRaw = !!process_1.stdin.isRaw;
|
|
17
|
+
process_1.stdin.setRawMode(true);
|
|
18
|
+
process_1.stdin.setEncoding("utf8");
|
|
19
|
+
process_1.stdin.resume();
|
|
20
|
+
let value = "";
|
|
21
|
+
const finish = () => {
|
|
22
|
+
process_1.stdin.removeListener("data", onData);
|
|
23
|
+
process_1.stdin.setRawMode(wasRaw);
|
|
24
|
+
process_1.stdin.pause();
|
|
25
|
+
process_1.stdout.write("\n");
|
|
26
|
+
};
|
|
27
|
+
const onData = (chunk) => {
|
|
28
|
+
for (const ch of chunk) {
|
|
29
|
+
if (ch === "\r" || ch === "\n" || ch === "\u0004") {
|
|
30
|
+
finish();
|
|
31
|
+
resolve(value);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (ch === "\u0003") {
|
|
35
|
+
finish();
|
|
36
|
+
process.exit(130);
|
|
37
|
+
}
|
|
38
|
+
if (ch === "\u007f" || ch === "\b") {
|
|
39
|
+
value = value.slice(0, -1);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (ch >= " ")
|
|
43
|
+
value += ch;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
process_1.stdin.on("data", onData);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async function HashPassword(target) {
|
|
50
|
+
const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
|
|
51
|
+
if (!process_1.stdin.isTTY) {
|
|
52
|
+
console.error(red("✗ hash-password needs an interactive terminal — the password is never accepted as an argument."));
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
console.log(bold(`\nHash a ${target} password`) + dim(target === "deployer" ? " (setup.json users)" : " (APIService access.monitor)"));
|
|
56
|
+
const rl = (0, promises_1.createInterface)({ input: process_1.stdin, output: process_1.stdout });
|
|
57
|
+
let login;
|
|
58
|
+
try {
|
|
59
|
+
login = (await rl.question("Login: ")).trim();
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
rl.close();
|
|
63
|
+
}
|
|
64
|
+
if (!login) {
|
|
65
|
+
console.error(red("✗ Login is required."));
|
|
66
|
+
process.exit(1);
|
|
67
|
+
}
|
|
68
|
+
{
|
|
69
|
+
const pass1 = await askHidden("Password: ");
|
|
70
|
+
const policy = MonitorAuth_1.MonitorAuth.passwordPolicyError(pass1);
|
|
71
|
+
if (policy) {
|
|
72
|
+
console.error(red(`✗ ${policy}.`));
|
|
73
|
+
process.exit(1);
|
|
74
|
+
}
|
|
75
|
+
const pass2 = await askHidden("Repeat password: ");
|
|
76
|
+
if (pass1 !== pass2) {
|
|
77
|
+
console.error(red("✗ Passwords do not match."));
|
|
78
|
+
process.exit(1);
|
|
79
|
+
}
|
|
80
|
+
const secret = target === "deployer"
|
|
81
|
+
? crypto_1.default.createHash("sha256").update(login + ":" + pass1).digest("hex")
|
|
82
|
+
: pass1;
|
|
83
|
+
const hash = await PasswordHash_1.PasswordHash.hash(secret);
|
|
84
|
+
console.log("");
|
|
85
|
+
console.log(green(bold("✓ Put this in the config instead of the plain password:")));
|
|
86
|
+
console.log(`\n { "login": ${JSON.stringify(login)}, "password": ${JSON.stringify(hash)} }\n`);
|
|
87
|
+
if (target === "deployer")
|
|
88
|
+
console.log(yellow(" Deployer users stored as a hash need an up-to-date badmfck CLI on the deploying machine."));
|
|
89
|
+
console.log(dim(" The hash is salted — running this again for the same password gives a different, equally valid hash."));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -9,7 +9,7 @@ const cliCommon_1 = require("./cliCommon");
|
|
|
9
9
|
async function Restore(opt, backupName, assumeYes = false) {
|
|
10
10
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
11
11
|
const { red, yellow, green, dim, bold } = (0, cliCommon_1.palette)();
|
|
12
|
-
const headers =
|
|
12
|
+
const headers = (0, cliCommon_1.deployerHeaders)(opt);
|
|
13
13
|
const fail = (msg) => { console.error(red(bold("✗ ")) + msg); process.exit(1); };
|
|
14
14
|
const lr = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, { headers, timeoutMs: 30000, retry: { enabled: false } });
|
|
15
15
|
const lerr = (0, cliCommon_1.responseError)(lr);
|
|
@@ -18,7 +18,7 @@ async function Status(opt) {
|
|
|
18
18
|
throw new Error(`Cannot derive status URL from host "${opt.host}" — make sure "host" ends with /add.`);
|
|
19
19
|
const authToken = crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
|
|
20
20
|
const response = await __1.Http.post(statusUrl, { name: opt.name }, {
|
|
21
|
-
headers: { authorization: `Bearer ${authToken}
|
|
21
|
+
headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
|
|
22
22
|
timeoutMs: 15 * 1000,
|
|
23
23
|
retry: { enabled: false },
|
|
24
24
|
});
|
|
@@ -7,6 +7,7 @@ const Status_1 = require("./Status");
|
|
|
7
7
|
const Backups_1 = require("./Backups");
|
|
8
8
|
const Restore_1 = require("./Restore");
|
|
9
9
|
const BackupManager_1 = require("./BackupManager");
|
|
10
|
+
const HashPassword_1 = require("./HashPassword");
|
|
10
11
|
function usage() {
|
|
11
12
|
console.error("Usage:");
|
|
12
13
|
console.error(" badmfck deploy [config.json] — build + upload the current project");
|
|
@@ -14,6 +15,7 @@ function usage() {
|
|
|
14
15
|
console.error(" badmfck status [config.json] — show active / last deployed slot");
|
|
15
16
|
console.error(" badmfck backups [config.json] — list deploy backups");
|
|
16
17
|
console.error(" badmfck restore [config.json] [backup] [--yes] — restore a backup (asks which, and confirms)");
|
|
18
|
+
console.error(" badmfck hash-password [--deployer] — hash a password for the monitor (or deployer setup.json)");
|
|
17
19
|
console.error("");
|
|
18
20
|
console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
|
|
19
21
|
console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
|
|
@@ -91,6 +93,15 @@ async function main() {
|
|
|
91
93
|
await (0, Restore_1.Restore)(config, backup, yes);
|
|
92
94
|
break;
|
|
93
95
|
}
|
|
96
|
+
case "hash-password": {
|
|
97
|
+
const unknown = rest.filter(a => a !== "--deployer");
|
|
98
|
+
if (unknown.length) {
|
|
99
|
+
console.error("hash-password takes no arguments except --deployer — the password is asked interactively.");
|
|
100
|
+
process.exit(1);
|
|
101
|
+
}
|
|
102
|
+
await (0, HashPassword_1.HashPassword)(rest.includes("--deployer") ? "deployer" : "monitor");
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
94
105
|
case "status": {
|
|
95
106
|
const { scheme, config } = parseArgs(rest);
|
|
96
107
|
if (scheme) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { IDeployerConfig } from "./resolveConfig";
|
|
2
2
|
export declare function deployerUrl(opt: IDeployerConfig, endpoint: string): string;
|
|
3
3
|
export declare function authHeader(opt: IDeployerConfig): string;
|
|
4
|
+
export declare function deployerHeaders(opt: IDeployerConfig): Record<string, string>;
|
|
4
5
|
export declare function responseError(r: any): string | null;
|
|
5
6
|
export declare function palette(): {
|
|
6
7
|
red: (t: string) => string;
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.deployerUrl = deployerUrl;
|
|
7
7
|
exports.authHeader = authHeader;
|
|
8
|
+
exports.deployerHeaders = deployerHeaders;
|
|
8
9
|
exports.responseError = responseError;
|
|
9
10
|
exports.palette = palette;
|
|
10
11
|
exports.fmtDate = fmtDate;
|
|
@@ -21,6 +22,9 @@ function deployerUrl(opt, endpoint) {
|
|
|
21
22
|
function authHeader(opt) {
|
|
22
23
|
return "Bearer " + crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
|
|
23
24
|
}
|
|
25
|
+
function deployerHeaders(opt) {
|
|
26
|
+
return { authorization: authHeader(opt), "x-deployer-login": String(opt.username) };
|
|
27
|
+
}
|
|
24
28
|
function responseError(r) {
|
|
25
29
|
const body = r?.ok ? r?.data : r?.error;
|
|
26
30
|
const e = (body && typeof body === "object")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_TRUSTED_PROXIES = void 0;
|
|
4
|
+
exports.clientIp = clientIp;
|
|
5
|
+
exports.DEFAULT_TRUSTED_PROXIES = ["127.0.0.1", "::1"];
|
|
6
|
+
const norm = (a) => {
|
|
7
|
+
let s = String(a ?? "").trim();
|
|
8
|
+
if (s.startsWith("::ffff:"))
|
|
9
|
+
s = s.slice(7);
|
|
10
|
+
return s;
|
|
11
|
+
};
|
|
12
|
+
function clientIp(req, trustedProxies = new Set(exports.DEFAULT_TRUSTED_PROXIES)) {
|
|
13
|
+
const peer = norm(req?.socket?.remoteAddress ?? req?.connection?.remoteAddress);
|
|
14
|
+
if (!peer)
|
|
15
|
+
return "unknown";
|
|
16
|
+
if (!trustedProxies.has(peer))
|
|
17
|
+
return peer;
|
|
18
|
+
const real = req?.headers?.["x-real-ip"];
|
|
19
|
+
if (typeof real === "string" && real.trim())
|
|
20
|
+
return norm(real.split(",")[0]);
|
|
21
|
+
const xff = req?.headers?.["x-forwarded-for"];
|
|
22
|
+
if (typeof xff === "string" && xff.trim()) {
|
|
23
|
+
const parts = xff.split(",").map(s => s.trim()).filter(Boolean);
|
|
24
|
+
if (parts.length)
|
|
25
|
+
return norm(parts[parts.length - 1]);
|
|
26
|
+
}
|
|
27
|
+
return peer;
|
|
28
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
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.PasswordHash = void 0;
|
|
7
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
const DEFAULTS = { N: 16384, r: 8, p: 1, keylen: 32 };
|
|
9
|
+
function scryptAsync(secret, salt, keylen, opts) {
|
|
10
|
+
return new Promise((resolve, reject) => crypto_1.default.scrypt(secret, salt, keylen, opts, (err, key) => err ? reject(err) : resolve(key)));
|
|
11
|
+
}
|
|
12
|
+
class PasswordHash {
|
|
13
|
+
static isHash(value) {
|
|
14
|
+
return typeof value === "string" && value.startsWith("scrypt$");
|
|
15
|
+
}
|
|
16
|
+
static async hash(secret) {
|
|
17
|
+
const { N, r, p, keylen } = DEFAULTS;
|
|
18
|
+
const salt = crypto_1.default.randomBytes(16);
|
|
19
|
+
const key = await scryptAsync(secret, salt, keylen, { N, r, p, maxmem: 256 * N * r });
|
|
20
|
+
return `scrypt$${N}$${r}$${p}$${salt.toString("base64")}$${key.toString("base64")}`;
|
|
21
|
+
}
|
|
22
|
+
static async verify(secret, stored) {
|
|
23
|
+
if (typeof secret !== "string" || !PasswordHash.isHash(stored))
|
|
24
|
+
return false;
|
|
25
|
+
const parts = stored.split("$");
|
|
26
|
+
if (parts.length !== 6)
|
|
27
|
+
return false;
|
|
28
|
+
const N = Number(parts[1]), r = Number(parts[2]), p = Number(parts[3]);
|
|
29
|
+
if (!Number.isInteger(N) || N < 1024 || N > 1 << 20 || (N & (N - 1)) !== 0)
|
|
30
|
+
return false;
|
|
31
|
+
if (!Number.isInteger(r) || r < 1 || r > 32 || !Number.isInteger(p) || p < 1 || p > 16)
|
|
32
|
+
return false;
|
|
33
|
+
let salt, expected;
|
|
34
|
+
try {
|
|
35
|
+
salt = Buffer.from(parts[4], "base64");
|
|
36
|
+
expected = Buffer.from(parts[5], "base64");
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
if (salt.length < 8 || expected.length < 16)
|
|
42
|
+
return false;
|
|
43
|
+
try {
|
|
44
|
+
const key = await scryptAsync(secret, salt, expected.length, { N, r, p, maxmem: 256 * N * r });
|
|
45
|
+
return crypto_1.default.timingSafeEqual(key, expected);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
exports.PasswordHash = PasswordHash;
|
|
@@ -38,6 +38,7 @@ export declare class Monitor extends BaseEndpoint {
|
|
|
38
38
|
httpstats(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
39
39
|
inventory(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
40
40
|
metrics(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
41
|
+
threats(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
41
42
|
logfiles(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
42
43
|
logtail(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
43
44
|
metricsWeeks(req: HTTPRequestVO): Promise<TransferPacketVO>;
|