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.
- package/README.md +59 -13
- package/dist/apiServer/APIService.d.ts +4 -0
- package/dist/apiServer/APIService.js +17 -0
- 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 +0 -2
- package/dist/apiServer/deployment/DeployerService.js +14 -12
- 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/monitor/Monitor.d.ts +3 -0
- package/dist/apiServer/monitor/Monitor.js +64 -7
- 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
package/README.md
CHANGED
|
@@ -23,14 +23,15 @@ Node.js 21+ is required.
|
|
|
23
23
|
6. [Outgoing HTTP client](#outgoing-http-client)
|
|
24
24
|
7. [Logging and redaction](#logging-and-redaction)
|
|
25
25
|
8. [Monitor console (`sm/*`)](#monitor-console-sm)
|
|
26
|
-
9. [
|
|
27
|
-
10. [
|
|
28
|
-
11. [
|
|
29
|
-
12. [
|
|
30
|
-
13. [
|
|
31
|
-
14. [
|
|
32
|
-
15. [
|
|
33
|
-
16. [
|
|
26
|
+
9. [IP blocking](#ip-blocking)
|
|
27
|
+
10. [Authentication](#authentication)
|
|
28
|
+
11. [WebSocket server](#websocket-server)
|
|
29
|
+
12. [Deployer and CLI](#deployer-and-cli)
|
|
30
|
+
13. [Blue-green deployments](#blue-green-deployments)
|
|
31
|
+
14. [Backups and restore](#backups-and-restore)
|
|
32
|
+
15. [Deploy review](#deploy-review)
|
|
33
|
+
16. [Options reference](#options-reference)
|
|
34
|
+
17. [Security](#security)
|
|
34
35
|
|
|
35
36
|
---
|
|
36
37
|
|
|
@@ -318,11 +319,51 @@ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
|
|
|
318
319
|
Other addresses get `403`. Changes in `access.json` apply without a restart, and an invalid entry
|
|
319
320
|
rejects the change. Behind nginx, pass `X-Real-IP` (see [`trustedProxies`](#options-reference)),
|
|
320
321
|
otherwise every request appears to come from `127.0.0.1`.
|
|
322
|
+
- **Block addresses.** Admins can block an address or a subnet from the threats page, permanently or
|
|
323
|
+
for a number of hours. See [IP blocking](#ip-blocking).
|
|
321
324
|
- **Keep `monitorAuthDir` outside the deploy folders.** Otherwise a deploy wipes the enrollments and
|
|
322
325
|
everyone has to enroll again.
|
|
323
326
|
|
|
324
327
|
---
|
|
325
328
|
|
|
329
|
+
## IP blocking
|
|
330
|
+
|
|
331
|
+
Blocked addresses get a `403` on every request, whether HTTP, WebSocket, the monitor or the
|
|
332
|
+
documentation:
|
|
333
|
+
|
|
334
|
+
```json
|
|
335
|
+
{ "error": { "code": 403, "message": "Access from your address is blocked", "httpStatus": 403 } }
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
The check runs first, before body parsing, CORS and the interceptor, so a blocked client costs almost
|
|
339
|
+
nothing. The list lives in `blocked-ips.json`, in the project folder (for blue-green, the folder above
|
|
340
|
+
the slots, shared by both). It is re-read on change:
|
|
341
|
+
|
|
342
|
+
```jsonc
|
|
343
|
+
[
|
|
344
|
+
{ "ip": "203.0.113.7", "reason": "credential stuffing", "until": "2026-12-01T00:00:00Z" },
|
|
345
|
+
{ "ip": "198.51.100.0/24", "reason": "scanner" } // no "until" → permanent
|
|
346
|
+
]
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
- **How to edit.** Edit the file by hand, or block and unblock from the monitor (`sm/block`,
|
|
350
|
+
`sm/unblock`; `admin` role). The monitor records who blocked and when. The threats page marks
|
|
351
|
+
addresses that are already blocked.
|
|
352
|
+
- **Expiry.** Entries past `until` stop applying by themselves.
|
|
353
|
+
- **Invalid edits.** An invalid file is ignored, and the previous list stays in force.
|
|
354
|
+
- **Reasons stay private.** `reason` is shown only in the monitor, never to the client.
|
|
355
|
+
- **Safety rules.** Loopback is never blocked, so a proxy without `X-Real-IP` can't take the service
|
|
356
|
+
down. An admin can't block their own address from the monitor.
|
|
357
|
+
- **Deploys and restores.** The deployer keeps the file through clean deploys and restores, because
|
|
358
|
+
it is runtime state, not part of a release.
|
|
359
|
+
- **Options.** `blockedIps: { file, message }` sets another location or the text of the error;
|
|
360
|
+
`blockedIps: false` turns blocking off.
|
|
361
|
+
|
|
362
|
+
Blocking in the service suits targeted cases: a particular attacker or a scanner subnet. To stop a
|
|
363
|
+
flood, block at nginx or with fail2ban, where requests are dropped before they reach Node.
|
|
364
|
+
|
|
365
|
+
---
|
|
366
|
+
|
|
326
367
|
## Authentication
|
|
327
368
|
|
|
328
369
|
The library protects four things, each in its own way:
|
|
@@ -362,8 +403,8 @@ Repeat password:
|
|
|
362
403
|
history or `ps`. Without a terminal (in CI, for example), the command refuses to run.
|
|
363
404
|
- **Password policy.** The minimum length is 12 characters, checked by the command.
|
|
364
405
|
- **Salting.** Every run gives a different hash for the same password. All of them are valid.
|
|
365
|
-
- **Plain text is refused.** A password stored in plain text is rejected at login with
|
|
366
|
-
|
|
406
|
+
- **Plain text is refused.** A password stored in plain text is rejected at login with the same answer
|
|
407
|
+
as a wrong password. The server log says why, and a startup error names the affected logins.
|
|
367
408
|
|
|
368
409
|
Put the result into `access.monitor` (inline or in an `access.json` file) and add a role:
|
|
369
410
|
|
|
@@ -479,8 +520,8 @@ documentation users their own passwords, never ones they use elsewhere.
|
|
|
479
520
|
- **Project token.** Deploying, switching and restoring also require the project's own `token`. The
|
|
480
521
|
project config on the server holds only its hash. Run `npx badmfck project-token`: it prints a new
|
|
481
522
|
random token for `deploy.json` and its hash for the project config. To keep an existing token, run
|
|
482
|
-
`npx badmfck project-token --hash`. A token stored in plain text is refused
|
|
483
|
-
|
|
523
|
+
`npx badmfck project-token --hash`. A token stored in plain text is refused like a wrong token. The
|
|
524
|
+
server log says why, and a startup error names the affected projects.
|
|
484
525
|
- **CLI version.** Users stored as a hash need a CLI from version 6 or later.
|
|
485
526
|
|
|
486
527
|
---
|
|
@@ -574,7 +615,10 @@ rejects the whole change, and the previous setup stays in force.
|
|
|
574
615
|
> it, every request appears to come from `127.0.0.1`. Never add `127.0.0.1` to `allowed_ips` on a
|
|
575
616
|
> deployer behind a proxy on the same host: that would let every request through.
|
|
576
617
|
|
|
577
|
-
A project config (`projects_path/<name>.json`)
|
|
618
|
+
A project config (`projects_path/<name>.json`). The easiest way to make one is `npx badmfck project-config`:
|
|
619
|
+
it asks for everything below, generates the token, takes config values as hidden input, checks the
|
|
620
|
+
result against the deployer's schema, and saves the project config and a matching `deploy.json` with
|
|
621
|
+
permissions `600`.
|
|
578
622
|
|
|
579
623
|
```jsonc
|
|
580
624
|
{
|
|
@@ -659,6 +703,7 @@ git: it holds credentials.
|
|
|
659
703
|
| `badmfck restore [config] [backup] [--yes]` | restore a backup |
|
|
660
704
|
| `badmfck hash-password [--deployer]` | hash a password for the monitor or `setup.json` |
|
|
661
705
|
| `badmfck project-token [--hash]` | generate a project token and its hash, or hash an existing token |
|
|
706
|
+
| `badmfck project-config` | build a project config for the deployer step by step (plus a `deploy.json` skeleton) |
|
|
662
707
|
|
|
663
708
|
To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json`.
|
|
664
709
|
|
|
@@ -928,6 +973,7 @@ so no restart is needed.
|
|
|
928
973
|
| `logFiles` | pm2 auto-detected | log files the monitor may tail (for example nginx) |
|
|
929
974
|
| `threatMonitoring` | `true` | probe and scan detection; observation only |
|
|
930
975
|
| `trustedProxies` | loopback | proxies whose `X-Real-IP` / `X-Forwarded-For` are trusted |
|
|
976
|
+
| `blockedIps` | `blocked-ips.json` in the project folder | `{ file, message }` for the blocked-address list; `false` turns it off |
|
|
931
977
|
| `websocketServer` | — | enables the WebSocket server, see above |
|
|
932
978
|
| `deployer` | — | turns this service into a deployer |
|
|
933
979
|
| `blueGreenWatchMs` | `5000` | how often to check the active slot; `0` disables |
|
|
@@ -62,6 +62,10 @@ export interface APIServiceOptions<TInterceptor = unknown> {
|
|
|
62
62
|
monitorAuthFile?: string;
|
|
63
63
|
threatMonitoring?: boolean;
|
|
64
64
|
trustedProxies?: string[];
|
|
65
|
+
blockedIps?: false | {
|
|
66
|
+
file?: string;
|
|
67
|
+
message?: string;
|
|
68
|
+
};
|
|
65
69
|
}
|
|
66
70
|
type InferInterceptor<T> = T extends IInterceptor<infer U> ? U : unknown;
|
|
67
71
|
export declare const getDefaultOptions: <I extends IInterceptor<any> | undefined>(overrides?: Omit<Partial<APIServiceOptions<InferInterceptor<NonNullable<I>>>>, "interceptor"> & {
|
|
@@ -63,6 +63,7 @@ const DeployerService_1 = require("./deployment/DeployerService");
|
|
|
63
63
|
const BlueGreenState_1 = require("./deployment/BlueGreenState");
|
|
64
64
|
const ThreatMonitor_1 = require("./monitor/ThreatMonitor");
|
|
65
65
|
const AccessStore_1 = require("./monitor/AccessStore");
|
|
66
|
+
const BlockedIps_1 = require("./security/BlockedIps");
|
|
66
67
|
const MonitorAuth_1 = require("./monitor/MonitorAuth");
|
|
67
68
|
const ClientIp_1 = require("./helper/ClientIp");
|
|
68
69
|
const Deployer_1 = require("./deployment/Deployer");
|
|
@@ -173,6 +174,8 @@ class APIService extends BaseService_1.BaseService {
|
|
|
173
174
|
}
|
|
174
175
|
}
|
|
175
176
|
this.options.corsHostWhiteList = Array.from(new Set(list));
|
|
177
|
+
if (this.options.blockedIps !== false)
|
|
178
|
+
BlockedIps_1.BlockedIps.configure(this.options.blockedIps?.file);
|
|
176
179
|
const access = new AccessStore_1.AccessStore(this.options.access, (prev, next) => {
|
|
177
180
|
const now = new Map((next.monitor ?? []).map(u => [u.login, u.password]));
|
|
178
181
|
for (const u of prev.monitor ?? []) {
|
|
@@ -235,6 +238,16 @@ class APIService extends BaseService_1.BaseService {
|
|
|
235
238
|
};
|
|
236
239
|
const app = (0, express_1.default)();
|
|
237
240
|
const trustedProxies = new Set(this.options.trustedProxies ?? ClientIp_1.DEFAULT_TRUSTED_PROXIES);
|
|
241
|
+
if (this.options.blockedIps !== false) {
|
|
242
|
+
const message = this.options.blockedIps?.message || "Access from your address is blocked";
|
|
243
|
+
app.use((req, res, next) => {
|
|
244
|
+
const ip = (0, ClientIp_1.clientIp)(req, trustedProxies);
|
|
245
|
+
if (!BlockedIps_1.BlockedIps.isBlocked(ip))
|
|
246
|
+
return next();
|
|
247
|
+
BlockedIps_1.BlockedIps.noteHit(ip);
|
|
248
|
+
res.status(403).json({ error: { code: 403, message, httpStatus: 403 }, data: null, httpStatus: 403, version: this.options.appVersion });
|
|
249
|
+
});
|
|
250
|
+
}
|
|
238
251
|
if (this.options.threatMonitoring !== false) {
|
|
239
252
|
app.use((req, res, next) => {
|
|
240
253
|
res.on("finish", () => {
|
|
@@ -590,6 +603,10 @@ class APIService extends BaseService_1.BaseService {
|
|
|
590
603
|
return;
|
|
591
604
|
}
|
|
592
605
|
const ip = (0, ClientIp_1.clientIp)(req, trustedProxies);
|
|
606
|
+
if (BlockedIps_1.BlockedIps.isBlocked(ip)) {
|
|
607
|
+
BlockedIps_1.BlockedIps.noteHit(ip);
|
|
608
|
+
return refuse(socket, 403, "Forbidden");
|
|
609
|
+
}
|
|
593
610
|
const origin = req.headers.origin;
|
|
594
611
|
if (origin && !this.noCors) {
|
|
595
612
|
let originNorm = "";
|
|
@@ -8,6 +8,7 @@ const fs_1 = __importDefault(require("fs"));
|
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
9
|
const child_process_1 = require("child_process");
|
|
10
10
|
const util_1 = require("util");
|
|
11
|
+
const BlockedIps_1 = require("../security/BlockedIps");
|
|
11
12
|
const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
|
|
12
13
|
exports.BACKUP_META = ".badmfck-backup.json";
|
|
13
14
|
exports.MAX_BACKUPS = 10;
|
|
@@ -157,6 +158,11 @@ class BackupManager {
|
|
|
157
158
|
await fs_1.default.promises.rm(staging, { recursive: true, force: true }).catch(() => { });
|
|
158
159
|
throw e;
|
|
159
160
|
}
|
|
161
|
+
for (const keep of [BlockedIps_1.BLOCKED_IPS_FILE]) {
|
|
162
|
+
const live = path_1.default.join(target, keep);
|
|
163
|
+
if (fs_1.default.existsSync(live))
|
|
164
|
+
await fs_1.default.promises.copyFile(live, path_1.default.join(staging, keep)).catch(() => { });
|
|
165
|
+
}
|
|
160
166
|
const hadTarget = fs_1.default.existsSync(target);
|
|
161
167
|
if (hadTarget)
|
|
162
168
|
await fs_1.default.promises.rename(target, old);
|
|
@@ -33,8 +33,11 @@ declare const _TConfig: {
|
|
|
33
33
|
readonly pm2_attributes: readonly [""];
|
|
34
34
|
readonly $__pm2_attributes_optional: true;
|
|
35
35
|
readonly chmod: 0;
|
|
36
|
+
readonly $__chmod_optional: true;
|
|
36
37
|
readonly email: readonly [""];
|
|
38
|
+
readonly $__email_optional: true;
|
|
37
39
|
readonly phone: readonly [""];
|
|
40
|
+
readonly $__phone_optional: true;
|
|
38
41
|
readonly liveness: "";
|
|
39
42
|
readonly $__liveness_optional: true;
|
|
40
43
|
readonly readiness: "";
|
|
@@ -77,6 +80,67 @@ declare const _TConfig: {
|
|
|
77
80
|
readonly $__secrets_optional: true;
|
|
78
81
|
};
|
|
79
82
|
export type IConfig = ValidationModel<typeof _TConfig>;
|
|
83
|
+
export declare const PROJECT_CONFIG_MODEL: {
|
|
84
|
+
readonly name: "";
|
|
85
|
+
readonly destination: "";
|
|
86
|
+
readonly description: "";
|
|
87
|
+
readonly token: "";
|
|
88
|
+
readonly unpack: true;
|
|
89
|
+
readonly ignoreDirectoryClean: false;
|
|
90
|
+
readonly backup: true;
|
|
91
|
+
readonly install: true;
|
|
92
|
+
readonly migrate: false;
|
|
93
|
+
readonly $__migrate_optional: true;
|
|
94
|
+
readonly pm2: true;
|
|
95
|
+
readonly pm2_attributes: readonly [""];
|
|
96
|
+
readonly $__pm2_attributes_optional: true;
|
|
97
|
+
readonly chmod: 0;
|
|
98
|
+
readonly $__chmod_optional: true;
|
|
99
|
+
readonly email: readonly [""];
|
|
100
|
+
readonly $__email_optional: true;
|
|
101
|
+
readonly phone: readonly [""];
|
|
102
|
+
readonly $__phone_optional: true;
|
|
103
|
+
readonly liveness: "";
|
|
104
|
+
readonly $__liveness_optional: true;
|
|
105
|
+
readonly readiness: "";
|
|
106
|
+
readonly $__readiness_optional: true;
|
|
107
|
+
readonly config: {};
|
|
108
|
+
readonly bluegreen: {
|
|
109
|
+
readonly blue_config: {};
|
|
110
|
+
readonly blue_pm2_attributes: readonly [""];
|
|
111
|
+
readonly $__blue_pm2_attributes_optional: true;
|
|
112
|
+
readonly green_config: {};
|
|
113
|
+
readonly green_pm2_attributes: readonly [""];
|
|
114
|
+
readonly $__green_pm2_attributes_optional: true;
|
|
115
|
+
readonly on_switch: readonly [""];
|
|
116
|
+
readonly $__on_switch_optional: true;
|
|
117
|
+
};
|
|
118
|
+
readonly $__bluegreen_optional: true;
|
|
119
|
+
readonly nginx: {
|
|
120
|
+
readonly config_dir: "";
|
|
121
|
+
readonly $__config_dir_optional: true;
|
|
122
|
+
readonly domain: "";
|
|
123
|
+
readonly $__domain_optional: true;
|
|
124
|
+
readonly upstream_name: "";
|
|
125
|
+
readonly $__upstream_name_optional: true;
|
|
126
|
+
};
|
|
127
|
+
readonly $__nginx_optional: true;
|
|
128
|
+
readonly review: {
|
|
129
|
+
readonly reviewers: readonly [""];
|
|
130
|
+
readonly mode: "";
|
|
131
|
+
readonly $__mode_values: readonly ["any", "all"];
|
|
132
|
+
readonly ttlHours: 24;
|
|
133
|
+
readonly $__ttlHours_optional: true;
|
|
134
|
+
};
|
|
135
|
+
readonly $__review_optional: true;
|
|
136
|
+
readonly secrets: {
|
|
137
|
+
readonly dir: "";
|
|
138
|
+
readonly $__dir_optional: true;
|
|
139
|
+
readonly file: "";
|
|
140
|
+
readonly $__file_optional: true;
|
|
141
|
+
};
|
|
142
|
+
readonly $__secrets_optional: true;
|
|
143
|
+
};
|
|
80
144
|
export declare const REQ_DEPLOYMENT_CONFIG: Req<void, Map<string, {
|
|
81
145
|
name: string;
|
|
82
146
|
destination: string;
|
|
@@ -89,9 +153,9 @@ export declare const REQ_DEPLOYMENT_CONFIG: Req<void, Map<string, {
|
|
|
89
153
|
migrate?: boolean | undefined;
|
|
90
154
|
pm2: boolean;
|
|
91
155
|
pm2_attributes?: string[] | undefined;
|
|
92
|
-
chmod
|
|
93
|
-
email
|
|
94
|
-
phone
|
|
156
|
+
chmod?: number | undefined;
|
|
157
|
+
email?: string[] | undefined;
|
|
158
|
+
phone?: string[] | undefined;
|
|
95
159
|
liveness?: string | undefined;
|
|
96
160
|
readiness?: string | undefined;
|
|
97
161
|
config: {};
|
|
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
36
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
37
|
};
|
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.ConfigService = exports.S_CONFIG_UPDATED = exports.REQ_DEPLOYMENT_CONFIG = void 0;
|
|
39
|
+
exports.ConfigService = exports.S_CONFIG_UPDATED = exports.REQ_DEPLOYMENT_CONFIG = exports.PROJECT_CONFIG_MODEL = void 0;
|
|
40
40
|
const fs_1 = __importDefault(require("fs"));
|
|
41
41
|
const path_1 = __importDefault(require("path"));
|
|
42
42
|
const crypto_1 = __importDefault(require("crypto"));
|
|
@@ -75,8 +75,11 @@ const _TConfig = {
|
|
|
75
75
|
pm2_attributes: [""],
|
|
76
76
|
$__pm2_attributes_optional: true,
|
|
77
77
|
chmod: 0,
|
|
78
|
+
$__chmod_optional: true,
|
|
78
79
|
email: [""],
|
|
80
|
+
$__email_optional: true,
|
|
79
81
|
phone: [""],
|
|
82
|
+
$__phone_optional: true,
|
|
80
83
|
liveness: "",
|
|
81
84
|
$__liveness_optional: true,
|
|
82
85
|
readiness: "",
|
|
@@ -118,6 +121,7 @@ const _TConfig = {
|
|
|
118
121
|
},
|
|
119
122
|
$__secrets_optional: true,
|
|
120
123
|
};
|
|
124
|
+
exports.PROJECT_CONFIG_MODEL = _TConfig;
|
|
121
125
|
exports.REQ_DEPLOYMENT_CONFIG = new badmfck_signal_1.Req();
|
|
122
126
|
exports.S_CONFIG_UPDATED = new badmfck_signal_1.default();
|
|
123
127
|
class ConfigService extends BaseService_1.BaseService {
|
|
@@ -275,7 +275,6 @@ export declare class DeployerService extends BaseService {
|
|
|
275
275
|
}>;
|
|
276
276
|
private _statusUrl;
|
|
277
277
|
private _writeBlueGreenFiles;
|
|
278
|
-
static PLAINTEXT_TOKEN_ERROR: string;
|
|
279
278
|
private _projectByToken;
|
|
280
279
|
tokensMatch(a: string | undefined, b: string | undefined): boolean;
|
|
281
280
|
static buildAllowList(entries: readonly string[] | undefined | null): {
|
|
@@ -285,7 +284,6 @@ export declare class DeployerService extends BaseService {
|
|
|
285
284
|
isIpAllowed(ip: string | undefined): boolean;
|
|
286
285
|
private _ipAllowed;
|
|
287
286
|
private _warnPlaintextUsers;
|
|
288
|
-
static PLAINTEXT_ERROR: string;
|
|
289
287
|
private _checkUserAuth;
|
|
290
288
|
private static _extractPort;
|
|
291
289
|
private _renderNginx;
|
|
@@ -24,6 +24,7 @@ const PasswordHash_1 = require("../helper/PasswordHash");
|
|
|
24
24
|
const ReviewStore_1 = require("./ReviewStore");
|
|
25
25
|
const SecretsInjector_1 = require("./SecretsInjector");
|
|
26
26
|
const IpAllowList_1 = require("../helper/IpAllowList");
|
|
27
|
+
const BlockedIps_1 = require("../security/BlockedIps");
|
|
27
28
|
const _TSetup = {
|
|
28
29
|
users: [{
|
|
29
30
|
login: "",
|
|
@@ -961,17 +962,14 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
961
962
|
}
|
|
962
963
|
}
|
|
963
964
|
}
|
|
964
|
-
static PLAINTEXT_TOKEN_ERROR = "Project token is built incorrectly — the project config must hold a hash from `npx badmfck project-token --hash`, not the token itself.";
|
|
965
965
|
async _projectByToken(configurations, name, token) {
|
|
966
966
|
const config = Array.from(configurations.values()).find(c => c.name === name);
|
|
967
967
|
if (!config || typeof token !== "string" || !token)
|
|
968
968
|
return {};
|
|
969
969
|
if (PasswordHash_1.PasswordHash.isHash(config.token))
|
|
970
970
|
return (await PasswordHash_1.PasswordHash.verify(token, config.token)) ? { config } : {};
|
|
971
|
-
if (config.token && this.tokensMatch(config.token, token))
|
|
972
|
-
(0, LogService_1.logError)(`Deployer: project "${name}" refused —
|
|
973
|
-
return { error: DeployerService.PLAINTEXT_TOKEN_ERROR };
|
|
974
|
-
}
|
|
971
|
+
if (config.token && this.tokensMatch(config.token, token))
|
|
972
|
+
(0, LogService_1.logError)(`Deployer: project "${name}" refused — the right token was sent, but the project config stores it as plain text; store a hash: npx badmfck project-token --hash`);
|
|
975
973
|
return {};
|
|
976
974
|
}
|
|
977
975
|
tokensMatch(a, b) {
|
|
@@ -995,11 +993,10 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
995
993
|
if (plain.length)
|
|
996
994
|
(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`);
|
|
997
995
|
}
|
|
998
|
-
static PLAINTEXT_ERROR = "Password is built incorrectly — setup.json must hold a hash from `npx badmfck hash-password --deployer`, not the password itself.";
|
|
999
996
|
async _checkUserAuth(authHeader, loginHeader, ip) {
|
|
1000
997
|
if (!this._ipAllowed(ip)) {
|
|
1001
998
|
(0, LogService_1.logWarn)(`Deployer: request refused from ${ip ?? "unknown"} — not in allowed_ips`);
|
|
1002
|
-
return { error: "
|
|
999
|
+
return { error: "Forbidden.", status: 403 };
|
|
1003
1000
|
}
|
|
1004
1001
|
if (!authHeader)
|
|
1005
1002
|
return {};
|
|
@@ -1017,17 +1014,17 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
1017
1014
|
if (user && PasswordHash_1.PasswordHash.isHash(user.password))
|
|
1018
1015
|
return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user } : {};
|
|
1019
1016
|
}
|
|
1020
|
-
let plainMatch =
|
|
1017
|
+
let plainMatch = null;
|
|
1021
1018
|
for (const user of users) {
|
|
1022
1019
|
if (PasswordHash_1.PasswordHash.isHash(user.password) || !user.password)
|
|
1023
1020
|
continue;
|
|
1024
1021
|
const expected = crypto_1.default.createHash("sha256").update(user.login + ":" + user.password).digest("hex");
|
|
1025
1022
|
if (this.tokensMatch(token, expected))
|
|
1026
|
-
plainMatch =
|
|
1023
|
+
plainMatch = user.login;
|
|
1027
1024
|
}
|
|
1028
1025
|
if (plainMatch) {
|
|
1029
|
-
(0, LogService_1.logError)(
|
|
1030
|
-
return {
|
|
1026
|
+
(0, LogService_1.logError)(`Deployer: "${plainMatch}" sent the right credentials, but setup.json stores the password as plain text — refused; store a hash: npx badmfck hash-password --deployer`);
|
|
1027
|
+
return {};
|
|
1031
1028
|
}
|
|
1032
1029
|
if (!login)
|
|
1033
1030
|
(0, LogService_1.logWarn)("Deployer auth failed without X-Deployer-Login — update the badmfck CLI on the client");
|
|
@@ -1376,7 +1373,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
1376
1373
|
}
|
|
1377
1374
|
if (!ignoreDirectoryClean) {
|
|
1378
1375
|
fs_1.default.readdirSync(destination).forEach((file) => {
|
|
1379
|
-
if (file === "__tmp")
|
|
1376
|
+
if (file === "__tmp" || file === BlockedIps_1.BLOCKED_IPS_FILE)
|
|
1380
1377
|
return;
|
|
1381
1378
|
try {
|
|
1382
1379
|
fs_1.default.rmSync(path_1.default.resolve(destination, file), { recursive: true });
|
|
@@ -1386,6 +1383,11 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
1386
1383
|
}
|
|
1387
1384
|
});
|
|
1388
1385
|
}
|
|
1386
|
+
if (fs_1.default.existsSync(path_1.default.resolve(destination, BlockedIps_1.BLOCKED_IPS_FILE)))
|
|
1387
|
+
try {
|
|
1388
|
+
fs_1.default.rmSync(path_1.default.resolve(destination, "__tmp", BlockedIps_1.BLOCKED_IPS_FILE), { force: true });
|
|
1389
|
+
}
|
|
1390
|
+
catch (_) { }
|
|
1389
1391
|
try {
|
|
1390
1392
|
(0, child_process_1.execFileSync)("cp", ["-RPf", path_1.default.resolve(destination, "__tmp") + "/.", destination]);
|
|
1391
1393
|
}
|
|
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.askHidden = askHidden;
|
|
6
7
|
exports.HashPassword = HashPassword;
|
|
7
8
|
exports.ProjectToken = ProjectToken;
|
|
8
9
|
const crypto_1 = __importDefault(require("crypto"));
|
|
@@ -13,9 +14,9 @@ const MonitorAuth_1 = require("../monitor/MonitorAuth");
|
|
|
13
14
|
const cliCommon_1 = require("./cliCommon");
|
|
14
15
|
function askHidden(question) {
|
|
15
16
|
return new Promise(resolve => {
|
|
16
|
-
process_1.stdout.write(question);
|
|
17
17
|
const wasRaw = !!process_1.stdin.isRaw;
|
|
18
18
|
process_1.stdin.setRawMode(true);
|
|
19
|
+
process_1.stdout.write(question);
|
|
19
20
|
process_1.stdin.setEncoding("utf8");
|
|
20
21
|
process_1.stdin.resume();
|
|
21
22
|
let value = "";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function ProjectConfigWizard(): Promise<void>;
|
|
@@ -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
|
+
}
|