badmfck-api-server 5.0.16 → 6.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.
Files changed (33) hide show
  1. package/README.md +824 -0
  2. package/dist/apiServer/APIService.d.ts +16 -4
  3. package/dist/apiServer/APIService.js +92 -3
  4. package/dist/apiServer/DBService.js +1 -2
  5. package/dist/apiServer/WebSocketServer.d.ts +39 -0
  6. package/dist/apiServer/WebSocketServer.js +173 -0
  7. package/dist/apiServer/db/MysqlAdapter.d.ts +4 -0
  8. package/dist/apiServer/db/MysqlAdapter.js +93 -84
  9. package/dist/apiServer/db/PostgresAdapter.d.ts +10 -3
  10. package/dist/apiServer/deployment/NginxHelper.d.ts +1 -1
  11. package/dist/apiServer/deployment/NginxHelper.js +3 -0
  12. package/dist/apiServer/monitor/AccessStore.d.ts +24 -0
  13. package/dist/apiServer/monitor/AccessStore.js +146 -0
  14. package/dist/apiServer/monitor/Monitor.js +5 -4
  15. package/dist/apiServer/monitor/MonitorAuth.d.ts +11 -1
  16. package/dist/apiServer/monitor/MonitorAuth.js +157 -31
  17. package/dist/apiServer/monitor/index.html +3 -3
  18. package/dist/index.d.ts +12 -2
  19. package/dist/index.js +27 -3
  20. package/monitoring.help.md +1 -1
  21. package/package.json +2 -2
  22. package/dist/apiServer/MysqlService.d.ts +0 -123
  23. package/dist/apiServer/MysqlService.js +0 -817
  24. package/dist/apiServer/WSAPITransport.d.ts +0 -0
  25. package/dist/apiServer/WSAPITransport.js +0 -1
  26. package/dist/apiServer/WebSocketHandler.d.ts +0 -0
  27. package/dist/apiServer/WebSocketHandler.js +0 -1
  28. package/dist/apiServer/WebsocketServerService.d.ts +0 -9
  29. package/dist/apiServer/WebsocketServerService.js +0 -18
  30. package/dist/apiServer/deployment/Deployment.d.ts +0 -10
  31. package/dist/apiServer/deployment/Deployment.js +0 -24
  32. package/dist/apiServer/interceptors/IntHmacSha256.d.ts +0 -5
  33. package/dist/apiServer/interceptors/IntHmacSha256.js +0 -22
package/README.md ADDED
@@ -0,0 +1,824 @@
1
+ # badmfck-api-server
2
+
3
+ A batteries-included TypeScript framework for HTTP API services on Node.js: endpoints with validation, an
4
+ operations console (metrics, logs, restart) behind 2FA, a deployer with zero-downtime blue-green releases and
5
+ backups, an outgoing HTTP client with latency metrics, log redaction for payment data, and a WebSocket server
6
+ on the same port.
7
+
8
+ ```bash
9
+ npm install badmfck-api-server
10
+ ```
11
+
12
+ Node.js 21+ is required.
13
+
14
+ ---
15
+
16
+ ## Contents
17
+
18
+ 1. [Quick start](#quick-start)
19
+ 2. [Endpoints](#endpoints)
20
+ 3. [Validation models](#validation-models)
21
+ 4. [Interceptors (authentication)](#interceptors-authentication)
22
+ 5. [API documentation](#api-documentation)
23
+ 6. [Outgoing HTTP client](#outgoing-http-client)
24
+ 7. [Logging and redaction](#logging-and-redaction)
25
+ 8. [Monitor console (`sm/*`)](#monitor-console-sm)
26
+ 9. [Authentication](#authentication)
27
+ 10. [WebSocket server](#websocket-server)
28
+ 11. [Deployer and CLI](#deployer-and-cli)
29
+ 12. [Blue-green deployments](#blue-green-deployments)
30
+ 13. [Backups and restore](#backups-and-restore)
31
+ 14. [Options reference](#options-reference)
32
+ 15. [Security](#security)
33
+
34
+ ---
35
+
36
+ ## Quick start
37
+
38
+ ```ts
39
+ import { APIService, Initializer, getDefaultOptions } from "badmfck-api-server";
40
+ import { Users } from "./endpoints/Users";
41
+
42
+ const api = new APIService(getDefaultOptions({
43
+ port: 8080,
44
+ baseEndPoint: "/api/v1/",
45
+ projectName: "my-service",
46
+ isProductionEnvironment: true,
47
+ corsHostWhiteList: ["https://app.example.com"],
48
+ endpoints: [new Users()],
49
+ }));
50
+
51
+ Initializer([api]);
52
+ ```
53
+
54
+ Every response has the same envelope:
55
+
56
+ ```jsonc
57
+ // success
58
+ { "data": { … }, "responseTime": 4, "endpoint": "/api/v1/users/get", "version": "1.2.0" }
59
+ // error
60
+ { "error": { "code": 401, "message": "Unauthorized", "httpStatus": 401, "details": "…" } }
61
+ ```
62
+
63
+ Built-in routes: `liveness` and `readiness` (for load balancers and orchestrators), `doc/*` (API documentation),
64
+ `sm/*` (monitor console) and, if configured, `pckg/*` (deployer).
65
+
66
+ ---
67
+
68
+ ## Endpoints
69
+
70
+ An endpoint class groups handlers under one path segment:
71
+
72
+ ```ts
73
+ import { BaseEndpoint, HTTPRequestVO, TransferPacketVO } from "badmfck-api-server";
74
+
75
+ export class Users extends BaseEndpoint {
76
+ constructor() {
77
+ super("users"); // → /api/v1/users/…
78
+ this.registerEndpoints([
79
+ {
80
+ endpoint: "get", // → /api/v1/users/get
81
+ handler: this.get,
82
+ title: "Get a user",
83
+ description: "Returns one user by id",
84
+ validationModel: { id: 0 },
85
+ },
86
+ {
87
+ endpoint: "profile",
88
+ handler: { // different handlers per HTTP method
89
+ GET: this.profile,
90
+ POST: { controller: this.updateProfile, validationModel: { name: "" } },
91
+ },
92
+ },
93
+ ]);
94
+ }
95
+
96
+ async get(req: HTTPRequestVO): Promise<TransferPacketVO> {
97
+ return { data: { id: req.data.id } };
98
+ }
99
+ }
100
+ ```
101
+
102
+ `req.data` merges the JSON body, form body and query string. Other useful fields: `req.headers`,
103
+ `req.params`, `req.files` (uploads), `req.ip` (the real client address, see
104
+ [`trustedProxies`](#options-reference)) and `req.interceptorResult` (whatever your interceptor returned).
105
+
106
+ Per-endpoint flags:
107
+
108
+ | Flag | Effect |
109
+ |---|---|
110
+ | `ignoreInterceptor` | skip authentication for this endpoint |
111
+ | `allowInterceptorError` | run the handler even if the interceptor rejected the request |
112
+ | `validationModel` / `resultModel` | validate the request and/or the response |
113
+ | `asStream` | stream the response |
114
+ | `ignoreInDocumentation` | hide from `doc/*` |
115
+ | `ignoreHttpLogging` | keep out of the request log (polling endpoints, secrets) |
116
+ | `independed` | register the path as is, without `baseEndPoint` |
117
+
118
+ A handler can return an error with `throw { ...DefaultErrors.NOT_FOUND, details: "…" }` or
119
+ `return { error: { code, message, httpStatus } }`.
120
+
121
+ ---
122
+
123
+ ## Validation models
124
+
125
+ A validation model is a sample object. The type of each value is the type of the field:
126
+
127
+ ```ts
128
+ validationModel: {
129
+ email: "", // string, required
130
+ age: 0, // number
131
+ agree: false, // boolean
132
+ tags: [""], // array of strings
133
+ address: { city: "", zip: "" }, // nested object
134
+
135
+ status: "",
136
+ $__status_values: ["new", "paid", "refunded"], // allowed values (shown in documentation too)
137
+
138
+ comment: "",
139
+ $__comment_optional: true,
140
+
141
+ amount: 0,
142
+ $__amount: { min: 1, max: 100000, details: "Amount in cents" },
143
+
144
+ phone: "",
145
+ $__phone: { regex: "^\\+[0-9]{8,15}$" },
146
+ }
147
+ ```
148
+
149
+ For a field `X`, options live in `$__X` (an object, or a string used as the description) or in
150
+ `$__X_optional`, `$__X_values`, `$__X_ignore_in_documentation` and similar keys. Supported options:
151
+ `optional`, `default`, `values`, `min`, `max`, `regex`, `type` (`email`, `phone`, `date`…) and `details`.
152
+
153
+ The `ValidationModel<typeof model>` type turns a model into a TypeScript type, optional and enum fields
154
+ included. `Validator.validateStructure(model, object)` can be used on its own, outside endpoints.
155
+
156
+ ---
157
+
158
+ ## Interceptors (authentication)
159
+
160
+ An interceptor runs before every endpoint that doesn't set `ignoreInterceptor`. It returns the caller's
161
+ identity, or an error:
162
+
163
+ ```ts
164
+ import { IInterceptor, DefaultErrors } from "badmfck-api-server";
165
+
166
+ class SessionInterceptor implements IInterceptor<{ userId: number }> {
167
+ async intercept(req) {
168
+ const user = await sessions.find(req.headers.authorization);
169
+ return user ?? { ...DefaultErrors.UNAUTHORIZED };
170
+ }
171
+ }
172
+
173
+ getDefaultOptions({ interceptor: new SessionInterceptor(), … });
174
+ // handlers then read req.interceptorResult.userId
175
+ ```
176
+
177
+ `InterceptorPayAuth` is a ready-made interceptor for signed server-to-server requests: an HMAC-SHA256
178
+ signature with a timestamp window and nonce replay protection.
179
+
180
+ ---
181
+
182
+ ## API documentation
183
+
184
+ `GET <baseEndPoint>doc/html` is an interactive page, and `<baseEndPoint>doc/json` is the same data as JSON.
185
+ Both are built from your endpoints: titles, descriptions, request models, allowed `values` and result models.
186
+
187
+ Access is restricted to users listed in `access.documentation`. A user can be limited to some endpoints:
188
+
189
+ ```ts
190
+ access: {
191
+ documentation: [{ login: "partner", password: "…", endpoints: ["/api/v1/orders"] }],
192
+ }
193
+ ```
194
+
195
+ Hide an endpoint with `ignoreInDocumentation`. The built-in `sm/*` and `pckg/*` endpoints are always hidden.
196
+
197
+ ---
198
+
199
+ ## Outgoing HTTP client
200
+
201
+ ```ts
202
+ import { Http } from "badmfck-api-server";
203
+
204
+ const res = await Http.post("https://api.example.com/charge", { amount: 100 }, {
205
+ headers: { authorization: `Bearer ${token}` },
206
+ timeoutMs: 15_000,
207
+ retry: { enabled: true },
208
+ });
209
+
210
+ if (!res.ok) {
211
+ // res.status is undefined on network errors; res.error holds the details
212
+ } else {
213
+ use(res.data);
214
+ }
215
+ ```
216
+
217
+ `Http` never throws for HTTP or network errors: you always get `{ ok, status, data, error }`. It uses
218
+ connection pooling (undici), and every call is recorded for the monitor: an outgoing request log (redacted),
219
+ active connections per host and latency percentiles (p50, p95, p99) per host.
220
+
221
+ ---
222
+
223
+ ## Logging and redaction
224
+
225
+ ```ts
226
+ import { logInfo, logWarn, logError, logCrit } from "badmfck-api-server";
227
+
228
+ logInfo("Order created", { orderId, amount });
229
+ ```
230
+
231
+ Every message is **redacted when it is written**. The objects you pass are never modified. What gets masked:
232
+
233
+ - **Card data.** PANs in any text are masked to the last 4 digits, checked with Luhn and known card
234
+ prefixes. The same applies to fields such as `pan`, `cardNumber`, `primaryAccountNumber` (DPAN) and
235
+ `track2`. CVV/CVC, PIN, expiry and cardholder-name fields are replaced with `<REDACTED>`.
236
+ - **Secrets.** Fields such as `password`, `token`, `authorization`, `cookie`, `apiKey` and `clientSecret`,
237
+ secrets in query strings (`?token=…`), and passwords inside connection strings (`mysql://user:***@host`).
238
+
239
+ The incoming and outgoing request logs shown in the monitor go through the same redaction.
240
+ `LogService.sanitize(text)` and `LogService.sanitizeDeep(value)` are available for your own output.
241
+
242
+ > Redaction is a safety net, not a policy. Don't log card data on purpose: masking patterns can't
243
+ > recognize every format.
244
+
245
+ ---
246
+
247
+ ## Monitor console (`sm/*`)
248
+
249
+ A web console for operations: `<baseEndPoint>sm/html`, plus a JSON API used by the page.
250
+
251
+ **What it shows:**
252
+
253
+ - Process: memory, event-loop delay, open file descriptors and sockets with history (to catch leaks),
254
+ and pm2 identity.
255
+ - System: CPU, RAM, disks, network and load.
256
+ - Metrics: request rate, errors and latency, by hour, day or week. Optionally persisted to disk with
257
+ 10 weeks of history (`metricsDir`).
258
+ - Outgoing HTTP: per-host p50/p95/p99 and active connections.
259
+ - Logs: the application log, incoming and outgoing request logs, and tails of pm2 and nginx log files.
260
+ - Threats: clients that look like they are probing (scanners, `/wp-login.php`, `../`, bursts of 404s).
261
+ This is observation only; nothing is ever blocked.
262
+ - Actions: change the log level, or restart the process via pm2 (the password and 2FA code are asked
263
+ again).
264
+
265
+ **Access** is configured in `access.monitor`:
266
+
267
+ ```ts
268
+ access: {
269
+ monitor: [
270
+ { login: "ops", password: "scrypt$16384$8$1$…", role: "admin" },
271
+ { login: "support", password: "scrypt$16384$8$1$…", role: "it" },
272
+ { login: "finance", password: "scrypt$16384$8$1$…", role: "analytic" },
273
+ ],
274
+ },
275
+ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
276
+ ```
277
+
278
+ - **Passwords must be stored as hashes.** Generate one with `npx badmfck hash-password`. The command
279
+ asks for the password interactively and prints the config entry. A plain-text password in the config
280
+ is refused.
281
+ - **2FA (TOTP) is mandatory.** At first login the console shows a QR code to scan with any
282
+ authenticator app. Re-enrolling through the API is deliberately impossible: to reset 2FA, remove
283
+ the user's record from the 2FA file on the server.
284
+ - **Roles:**
285
+
286
+ | Role | Can do |
287
+ |---|---|
288
+ | `admin` | everything |
289
+ | `it` | dashboard and logs |
290
+ | `analytic` | dashboard only |
291
+
292
+ - **Sessions** expire after 15 minutes idle and 8 hours at most. 10 failed logins lock the account
293
+ for 30 minutes.
294
+ - **Change access without a restart.** Instead of an inline object, `access` can be a path to a JSON
295
+ file with the same shape: `access: "/etc/my-service/access.json"`. The file is watched, and changes apply
296
+ within a second, without a restart or a redeploy:
297
+
298
+ ```jsonc
299
+ { "monitor": [ { "login": "ops", "password": "scrypt$…", "role": "admin" } ],
300
+ "documentation": [ { "login": "partner", "password": "…" } ] }
301
+ ```
302
+
303
+ - **Revocation.** Removing a user or changing their password ends their open sessions immediately.
304
+ A role change applies to the next request.
305
+ - **Bad edits are ignored.** If the file is invalid (broken JSON, unknown role, duplicate login), the
306
+ change is ignored and the previous access stays in force. The reason is logged.
307
+ - **Location and permissions.** Keep the file outside the deploy folders and `chmod 600` it. A warning
308
+ is logged if other users can read it.
309
+ - **Keep `monitorAuthDir` outside the deploy folders.** Otherwise a deploy wipes the enrollments and
310
+ everyone has to enroll again.
311
+
312
+ ---
313
+
314
+ ## Authentication
315
+
316
+ The library protects four things, each in its own way:
317
+
318
+ | What | Who uses it | How they sign in |
319
+ |---|---|---|
320
+ | Your API endpoints | your users and clients | your [interceptor](#interceptors-authentication) |
321
+ | Monitor (`sm/*`) | your operations team | password + mandatory TOTP 2FA, then a session token |
322
+ | Documentation (`doc/*`) | developers and partners | login and password (a static token) |
323
+ | Deployer (`pckg/*`) | CI and developers | deployer user + project token |
324
+
325
+ The library doesn't manage the users of your application. That's the job of your interceptor and
326
+ database. The rest of this section is about the built-in consoles.
327
+
328
+ ### 1. Generate a password hash
329
+
330
+ Monitor and deployer configs store a salted scrypt hash, never the password itself. Run the
331
+ command on any machine with the package installed:
332
+
333
+ ```text
334
+ $ npx badmfck hash-password
335
+
336
+ Hash a monitor password (APIService access.monitor)
337
+ Login: ops
338
+ Password: ← typed input is not shown
339
+ Repeat password:
340
+
341
+ ✓ Put this in the config instead of the plain password:
342
+
343
+ { "login": "ops", "password": "scrypt$16384$8$1$Rkps…$zrwU…" }
344
+ ```
345
+
346
+ - **Deployer users.** For a user in the deployer's `setup.json`, use `npx badmfck hash-password --deployer`.
347
+ The hash differs from a monitor hash, so they can't be swapped.
348
+ - **Interactive only.** The password is never accepted as an argument, so it doesn't end up in shell
349
+ history or `ps`. Without a terminal (in CI, for example), the command refuses to run.
350
+ - **Password policy.** The minimum length is 12 characters, checked by the command.
351
+ - **Salting.** Every run gives a different hash for the same password. All of them are valid.
352
+ - **Plain text is refused.** A password stored in plain text is rejected at login with "password is
353
+ built incorrectly", and a startup error names the affected logins.
354
+
355
+ Put the result into `access.monitor` (inline or in an `access.json` file) and add a role:
356
+
357
+ ```ts
358
+ access: {
359
+ monitor: [{ login: "ops", password: "scrypt$16384$8$1$…", role: "admin" }],
360
+ },
361
+ projectName: "my-service", // shown in the authenticator app
362
+ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are stored; outside deploy folders
363
+ ```
364
+
365
+ ### 2. Sign in to the monitor
366
+
367
+ Open `<baseEndPoint>sm/html` in a browser. The page runs this flow for you. The same flow over the API:
368
+
369
+ **Step 1. Log in.**
370
+
371
+ ```http
372
+ POST /api/sm/login
373
+ { "login": "ops", "password": "…" }
374
+ ```
375
+
376
+ **On the first login,** 2FA isn't set up yet, so the response contains an enrollment instead of a
377
+ session:
378
+
379
+ ```jsonc
380
+ { "data": {
381
+ "enrollmentRequired": true,
382
+ "enrollmentToken": "…", // valid for 10 minutes
383
+ "secret": "JBSWY3DPEHPK3PXP", // for manual entry
384
+ "otpauthUri": "otpauth://totp/my-service:ops?secret=…&issuer=my-service",
385
+ "expiresInMs": 600000 } }
386
+ ```
387
+
388
+ **Step 2. Enroll the authenticator (first login only).** Scan `otpauthUri` as a QR code with Google
389
+ Authenticator, 1Password, Authy or a similar app, then confirm with the current code:
390
+
391
+ ```http
392
+ POST /api/sm/enroll2fa
393
+ { "enrollmentToken": "…", "totp": "123456" }
394
+ ```
395
+
396
+ The secret is saved only after a correct code, and the response is already a session (see step 3).
397
+
398
+ **On later logins,** send the code from the app with the password:
399
+
400
+ ```http
401
+ POST /api/sm/login
402
+ { "login": "ops", "password": "…", "totp": "123456" }
403
+ ```
404
+
405
+ ```jsonc
406
+ { "data": { "token": "…", "login": "ops", "role": "admin",
407
+ "capabilities": ["dashboard", "logs", "admin"],
408
+ "idleTimeoutMs": 900000, "maxLifetimeMs": 28800000, "twoFactor": true } }
409
+ ```
410
+
411
+ **Step 3. Call the monitor with the session token.**
412
+
413
+ ```http
414
+ POST /api/sm/procinfo
415
+ Authorization: Bearer <token>
416
+ ```
417
+
418
+ **How sessions behave:**
419
+
420
+ - **Lifetime.** A session ends after 15 minutes without requests, or after 8 hours in any case.
421
+ `POST sm/logout` ends it at once.
422
+ - **Lockout.** 10 failed logins lock the account for 30 minutes.
423
+ - **Revocation.** Removing a user from `access`, or changing their password, ends their sessions
424
+ immediately.
425
+ - **Restart.** `sm/restart` asks for the password and the TOTP code again, even within a valid session.
426
+ - **Errors.** `401` means sign in again; `403` means the role doesn't allow this section.
427
+
428
+ ### 3. Reset a user's 2FA (lost phone)
429
+
430
+ Re-enrolling through the API is impossible on purpose. Otherwise anyone who learned the password
431
+ could attach their own authenticator. To reset:
432
+
433
+ 1. Open `<monitorAuthDir>/monitor-2fa.<projectName>.json` on the server.
434
+ 2. Delete the user's entry under `projects.<projectName>.users.<login>`.
435
+
436
+ No restart is needed. The file is watched like `access.json`: within a second the user's sessions
437
+ end, and their next login shows a new QR code. Deleting the whole file resets 2FA for every user of
438
+ the project in the same way. A broken file (invalid JSON) is ignored, and the current enrollments
439
+ stay in force.
440
+
441
+ > A deleted enrollment means the next person who knows the password enrolls their own
442
+ > authenticator. Reset 2FA only after confirming who is asking, and preferably change the password
443
+ > at the same time.
444
+
445
+ Alternatively, set a known base32 secret directly in the config with `totpSecret`. It takes
446
+ precedence over the stored enrollment.
447
+
448
+ ### 4. Documentation
449
+
450
+ Users in `access.documentation` sign in on `<baseEndPoint>doc/html` with a login and password. The page
451
+ then sends `Authorization: Bearer sha256(login:password)`, and API clients can do the same to fetch
452
+ `doc/json`. Use `endpoints` to limit what a user sees.
453
+
454
+ This is a **weaker level** than the monitor: there is no 2FA, the token never expires, and the
455
+ password is stored in the config in plain text. It is meant for API descriptions, not for data. Give
456
+ documentation users their own passwords, never ones they use elsewhere.
457
+
458
+ ### 5. Deployer
459
+
460
+ - **Server.** The deployer server keeps `setup.json` users as hashes (`hash-password --deployer`).
461
+ - **Client.** The deploying machine keeps the login and the plain password in `deploy.json`, which
462
+ never leaves that machine and must stay out of git.
463
+ - **What goes over the wire.** The CLI sends `Authorization: Bearer sha256(login:password)` and
464
+ `X-Deployer-Login`.
465
+ - **Project token.** Deploying, switching and restoring also require the project's own `token`.
466
+ - **CLI version.** Users stored as a hash need a CLI from version 6 or later.
467
+
468
+ ---
469
+
470
+ ## WebSocket server
471
+
472
+ The WebSocket server shares the HTTP port. It listens on `baseEndPoint + endpoint`, for example
473
+ `wss://api.example.com/api/v1/ws`:
474
+
475
+ ```ts
476
+ getDefaultOptions({
477
+ websocketServer: {
478
+ endpoint: "ws", // default "ws"
479
+ authTimeoutMs: 10_000, // the client must authorize within this time
480
+ onAuthorize: async (connection, message) => {
481
+ // `message` is the client's FIRST message, parsed JSON
482
+ const user = await sessions.find(message?.token);
483
+ return user ?? false; // false / null → close 4401; an object → connection.auth
484
+ },
485
+ maxPayload: 256 * 1024, // bytes per message → close 1009
486
+ maxMessagesPerSecond: 20, // per connection → close 1008
487
+ maxConnections: 1000, // total → HTTP 503
488
+ maxConnectionsPerIp: 50, // per client IP → HTTP 429
489
+ },
490
+ });
491
+ ```
492
+
493
+ ```ts
494
+ import { S_WS_ON_CONNECTED, S_WS_ON_MESSAGE, S_WS_ON_CLOSE, REQ_WS_SERVER } from "badmfck-api-server";
495
+
496
+ S_WS_ON_CONNECTED.subscribe(conn => conn.send({ hello: conn.auth.name }));
497
+ S_WS_ON_MESSAGE.subscribe(({ connection, message }) => { /* … */ });
498
+ S_WS_ON_CLOSE.subscribe(conn => { /* … */ });
499
+
500
+ const ws = await REQ_WS_SERVER.request();
501
+ ws?.broadcast({ event: "price" }, c => c.auth.plan === "pro");
502
+ ```
503
+
504
+ The client sends credentials as its **first message**, not in the URL, so tokens don't end up in proxy
505
+ access logs:
506
+
507
+ ```js
508
+ const socket = new WebSocket("wss://api.example.com/api/v1/ws");
509
+ socket.onopen = () => socket.send(JSON.stringify({ token }));
510
+ ```
511
+
512
+ How connections are handled:
513
+
514
+ - **Authorization.** Messages sent while authorization is being checked are dropped. A connection that
515
+ doesn't authorize within `authTimeoutMs` is closed with code 4408. This also applies when
516
+ `onAuthorize` itself is too slow.
517
+ - **Origin check.** The browser `Origin` is checked against `corsHostWhiteList`, as for HTTP. This
518
+ prevents cross-site WebSocket hijacking.
519
+ - **Without `onAuthorize`.** The socket is public: every connection is accepted, and a warning is logged
520
+ at startup.
521
+
522
+ ---
523
+
524
+ ## Deployer and CLI
525
+
526
+ The deployer is an `APIService` running on the target server with the `deployer` option. It receives a
527
+ build, unpacks it, installs dependencies, writes the configuration and starts the process in pm2.
528
+
529
+ **On the server:**
530
+
531
+ ```ts
532
+ getDefaultOptions({
533
+ deployer: {
534
+ projects_path: "/etc/deployer/projects", // one JSON config per project
535
+ setup_path: "/etc/deployer/setup.json",
536
+ },
537
+ });
538
+ ```
539
+
540
+ `setup.json` lists who may deploy. Passwords are hashes: generate one with
541
+ `npx badmfck hash-password --deployer`.
542
+
543
+ ```jsonc
544
+ { "users": [ { "login": "ci", "password": "scrypt$16384$8$1$…" } ] }
545
+ ```
546
+
547
+ A project config (`projects_path/<name>.json`):
548
+
549
+ ```jsonc
550
+ {
551
+ "name": "my-service",
552
+ "destination": "/var/node/my-service",
553
+ "token": "<per-project deploy token>",
554
+ "unpack": true, "install": true, "pm2": true,
555
+ "backup": true, // copy the current version aside before each deploy (see Backups)
556
+ "migrate": false, // run `npm run migrate` before the process starts
557
+ "config": { "DB_HOST": "…" } // substituted into the shipped config placeholders _{{DB_HOST}}_
558
+ }
559
+ ```
560
+
561
+ **In your project**, create `deploy.json` or a `deploy/` folder with one or more configs. Keep it out of
562
+ git: it holds credentials.
563
+
564
+ ```jsonc
565
+ {
566
+ "name": "my-service",
567
+ "host": "https://deployer.example.com/api/pckg/add",
568
+ "token": "<per-project deploy token>",
569
+ "username": "ci",
570
+ "password": "<your password>",
571
+ "includes": ["certs", { "src": "assets/logo.png", "dest": "bin/logo.png" }],
572
+ "excludes": ["*.map"]
573
+ }
574
+ ```
575
+
576
+ ```json
577
+ "scripts": {
578
+ "deploy": "badmfck deploy",
579
+ "activate": "badmfck activate",
580
+ "status": "badmfck status",
581
+ "backups": "badmfck backups",
582
+ "restore": "badmfck restore"
583
+ }
584
+ ```
585
+
586
+ | Command | What it does |
587
+ |---|---|
588
+ | `badmfck deploy [config]` | build and upload the project |
589
+ | `badmfck activate [config] [blue\|green]` | switch traffic to a slot (blue-green) |
590
+ | `badmfck status [config]` | active and last deployed slot, recent history |
591
+ | `badmfck backups [config]` | list backups |
592
+ | `badmfck restore [config] [backup] [--yes]` | restore a backup |
593
+ | `badmfck hash-password [--deployer]` | hash a password for the monitor or `setup.json` |
594
+
595
+ To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json`.
596
+
597
+ **Safety of the deploy pipeline:**
598
+
599
+ - Archives are checked before unpacking: absolute paths, `..`, and symlinks that point outside the
600
+ destination are rejected.
601
+ - Unsafe destinations are refused: relative paths, the filesystem root, top-level system folders
602
+ (`/var`, `/etc`…), the deployer's own folders, and a folder whose wipe would delete another project.
603
+ - Dependencies are installed with `npm ci --ignore-scripts`. `migrate` is the only script the deployer
604
+ runs.
605
+ - Every deploy, switch and restore needs a deployer user and the project token.
606
+
607
+ ---
608
+
609
+ ## Blue-green deployments
610
+
611
+ Blue-green gives you releases without downtime and rollbacks in seconds.
612
+
613
+ ### The idea
614
+
615
+ A project has **two slots**, `blue` and `green`. Each slot is its own folder and its own pm2 process on its
616
+ own port. nginx sends traffic to **one** slot at a time.
617
+
618
+ ```
619
+ ┌──────────── nginx ────────────┐
620
+ clients ───▶ │ upstream → active slot port │
621
+ └───────┬───────────────┬───────┘
622
+ ▼ ┆ (no traffic)
623
+ my-service-blue my-service-green
624
+ :8055 (live) :8056 (standby)
625
+ ```
626
+
627
+ 1. **`deploy`** puts the new version into the **inactive** slot and starts it. Production is not touched,
628
+ and you can test the new slot directly on its port.
629
+ 2. **`activate`** points nginx to that slot and reloads nginx. The switch is instant.
630
+ 3. **Rollback** is `activate` back to the other slot. The previous version is still running, so a
631
+ rollback takes seconds.
632
+
633
+ The very first deploy creates `blue` and makes it active right away.
634
+
635
+ ### Configuring a project
636
+
637
+ Add `bluegreen` and `nginx` blocks to the project config on the deployer:
638
+
639
+ ```jsonc
640
+ {
641
+ "name": "my-service",
642
+ "destination": "/var/node/my-service", // slots go to …/blue and …/green
643
+ "token": "…", "unpack": true, "install": true, "pm2": true, "backup": true,
644
+
645
+ "config": { "DB_HOST": "…" }, // shared by both slots
646
+
647
+ "bluegreen": {
648
+ "blue_config": { "port": "8055" }, // per-slot values; the ports must differ
649
+ "green_config": { "port": "8056" },
650
+ "on_switch": ["/usr/sbin/nginx", "-s", "reload"] // runs after each switch (absolute path)
651
+ },
652
+
653
+ "nginx": {
654
+ "config_dir": "/etc/nginx/node-projects", // nginx must include <config_dir>/*.conf
655
+ "domain": "api.example.com"
656
+ }
657
+ }
658
+ ```
659
+
660
+ The deployer manages two nginx files per project:
661
+
662
+ - **`<name>.upstream.conf`** holds only the active port. The deployer rewrites it on every switch.
663
+ - **`<name>.server.conf`** is the server block. The deployer creates it once, and after that it belongs
664
+ to you: add SSL with `certbot --nginx -d <domain>`, extra locations and so on. The deployer never
665
+ overwrites it. The generated block already passes `X-Real-IP` and the WebSocket upgrade headers.
666
+
667
+ ### Workflow
668
+
669
+ ```bash
670
+ npm run deploy # new version → inactive slot (e.g. green), production unchanged
671
+ npm run status # "green is deployed but NOT switched"
672
+ npm run activate # traffic → green
673
+ npx badmfck activate blue # rollback → blue
674
+ ```
675
+
676
+ ### Is my process live? (in the application)
677
+
678
+ Both slots run at the same time. Work that must happen once, such as cron jobs, queue consumers and
679
+ mailings, should run **only in the live slot**:
680
+
681
+ ```ts
682
+ APIService.onLiveChange(live => {
683
+ if (live) startCrons();
684
+ else stopCrons(); // this slot was switched to standby
685
+ });
686
+
687
+ if (APIService.isLive) { … } // synchronous: true / false / null (not known yet)
688
+ ```
689
+
690
+ | Situation | `live` |
691
+ |---|---|
692
+ | Project not on blue-green | `true`, always |
693
+ | Blue-green, my slot is active | `true` |
694
+ | Blue-green, my slot is standby | `false` |
695
+ | Not known yet | `null`; the callback isn't called until the answer is known |
696
+
697
+ The same code works before and after a project moves to blue-green. Without blue-green, the callback is
698
+ called once with `true`.
699
+
700
+ **How it works.** On deploy, each slot gets a `.bluegreen.json` file (mode `600`) with the project name,
701
+ the slot and a **read-only status token**. The app asks the deployer over loopback every
702
+ `blueGreenWatchMs` (default 5 s) which slot is active, so a switch is seen within seconds without a
703
+ restart.
704
+
705
+ **If the deployer is unreachable,** the last known value is kept (`stale: true`), and the app is never
706
+ switched to standby because of an error. The status token only allows reading the active slot. Deploy
707
+ credentials never reach the application.
708
+
709
+ ### Two things to keep in mind
710
+
711
+ - **The database is shared by both slots.** The new version starts before the switch, and after a
712
+ rollback the old version works with the database again. Schema migrations must be
713
+ **backward-compatible**: add first, remove in a later release. Neither `activate` nor `restore` rolls
714
+ back the schema.
715
+ - **Moving an existing project to blue-green.** Use ports different from the current one. After the
716
+ first blue-green deploy, stop the old process (`pm2 delete <name>`, then `pm2 save`). The old process
717
+ has no `.bluegreen.json`, so it would consider itself live, and singleton work would run twice.
718
+
719
+ ---
720
+
721
+ ## Backups and restore
722
+
723
+ With `"backup": true`, the deployer copies the destination aside before every deploy, for example to
724
+ `/var/node/my-service/2026-10-14_18-45-09-my-service-blue`. It works for blue-green and regular projects.
725
+
726
+ - **Complete copies.** A backup includes `node_modules`, permissions and symlinks, so a restore needs no
727
+ network and no `npm ci`.
728
+ - **Retention.** The last 10 backups per project are kept.
729
+ - **Fail-closed.** If the backup fails (disk full, no permissions), the deploy stops without changing
730
+ anything.
731
+
732
+ ```bash
733
+ npm run backups # list: version, slot, who, when, size
734
+ npm run restore # pick one interactively, confirm
735
+ npx badmfck restore 2026-10-13_10-00-00-my-service-blue --yes # non-interactive (CI)
736
+ ```
737
+
738
+ How a restore works:
739
+
740
+ - It first backs up the current state, so a bad restore can be undone.
741
+ - It swaps the folders atomically and restarts the pm2 process.
742
+ - Restoring the active slot (or a regular project) goes live immediately, and the CLI warns about it.
743
+ Restoring a standby slot changes nothing until you `activate` it.
744
+
745
+ Configuration values are baked in at deploy time. A restored version comes back with the secrets it was
746
+ deployed with.
747
+
748
+ ---
749
+
750
+ ## Options reference
751
+
752
+ | Option | Default | Description |
753
+ |---|---|---|
754
+ | `port` | `8080` | HTTP port |
755
+ | `baseEndPoint` | `"/api/"` | prefix for all endpoints |
756
+ | `projectName` | `"Application project"` | shown in the monitor and as the 2FA issuer, so set it |
757
+ | `endpoints` | `[]` | your `BaseEndpoint` instances |
758
+ | `corsHostWhiteList` | `["http://localhost:3000"]` | allowed browser origins; `"*"` allows any |
759
+ | `isProductionEnvironment` | `false` | production mode |
760
+ | `interceptor` | — | authentication for your endpoints |
761
+ | `preproducer` / `postproducer` | — | hooks before the handler / before the response is sent |
762
+ | `access` | `{}` | `{ monitor, documentation }` users, or a path to a JSON file reloaded on change |
763
+ | `monitorAuthDir` / `monitorAuthFile` | in memory | where 2FA enrollments are stored |
764
+ | `metricsDir` | in memory | persist metrics; 10 weeks are kept |
765
+ | `logFiles` | pm2 auto-detected | log files the monitor may tail (for example nginx) |
766
+ | `threatMonitoring` | `true` | probe and scan detection; observation only |
767
+ | `trustedProxies` | loopback | proxies whose `X-Real-IP` / `X-Forwarded-For` are trusted |
768
+ | `websocketServer` | — | enables the WebSocket server, see above |
769
+ | `deployer` | — | turns this service into a deployer |
770
+ | `blueGreenWatchMs` | `5000` | how often to check the active slot; `0` disables |
771
+ | `jsonLimit` | `"10mb"` | maximum JSON / form body |
772
+ | `fileTempDir` / `fileLimit` | `"/tmp"` / 10 MB | uploads |
773
+ | `keepAliveTimeout` / `headersTimeout` | 25 s / 26 s | HTTP server timeouts |
774
+ | `appVersion` | — | returned in every response as `version` |
775
+
776
+ ---
777
+
778
+ ## Security
779
+
780
+ ### What you get by default
781
+
782
+ - **Credentials.** Monitor and deployer passwords are stored as salted scrypt hashes, and plain text in
783
+ configs is refused. Comparisons run in constant time. Verifying a deployer request costs at most one
784
+ scrypt computation, so the deployer can't be used to burn CPU.
785
+ - **Monitor access.** Mandatory TOTP 2FA, short-lived sessions, account lockout, roles, and the password
786
+ asked again before a restart.
787
+ - **Data in logs.** Card data and secrets are redacted when logs are written and when they are viewed
788
+ through the monitor. Logged objects are never modified.
789
+ - **Client IP.** Proxy headers are trusted only from `trustedProxies`, so clients can't spoof their
790
+ address.
791
+ - **Deploys.** Archives are checked for path traversal and escaping symlinks, package install scripts
792
+ are disabled, and every deploy needs a user and the project token.
793
+ - **Blue-green.** Applications get a read-only status token; deploy credentials never reach them.
794
+ - **WebSocket.** Origin checks, authorization within a time limit, and limits on message size, message
795
+ rate and connections. A malformed frame can't crash the process.
796
+ - **Built-in endpoints.** The monitor and deployer endpoints are hidden from the API documentation.
797
+
798
+ ### What you must configure before going to production
799
+
800
+ 1. Set `corsHostWhiteList` to your real front-end origins. Don't use `"*"` with cookies.
801
+ 2. Store all monitor and deployer passwords as hashes (`npx badmfck hash-password`).
802
+ 3. Point `monitorAuthDir` to a persistent directory outside the deploy folders, readable only by the
803
+ service user.
804
+ 4. Run behind nginx (or another proxy) on loopback with TLS, and keep `trustedProxies` at its default
805
+ unless the proxy runs on another host.
806
+ 5. If you use WebSockets, set `onAuthorize`.
807
+ 6. Keep `deploy.json` / `deploy/` out of version control, and restrict permissions on `setup.json` and
808
+ the project configs on the server.
809
+ 7. Set a meaningful `projectName`, which is shown in authenticator apps.
810
+
811
+ ### What this library does not do
812
+
813
+ - **It is not a WAF.** Threat monitoring records suspicious clients but never blocks them. Use nginx
814
+ rate limiting, fail2ban or a WAF for blocking.
815
+ - **It doesn't make your system PCI DSS compliant on its own.** It helps with some requirements
816
+ (redaction, MFA, access roles, audit logs), but compliance is assessed for your whole environment.
817
+ - **Redaction is pattern-based.** Treat it as a safety net, not a substitute for not logging sensitive
818
+ data.
819
+
820
+ ---
821
+
822
+ ## License
823
+
824
+ MIT