badmfck-api-server 5.0.15 → 5.0.17

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