badmfck-api-server 6.0.11 → 6.0.13

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 (64) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +247 -79
  3. package/dist/apiServer/APIService.d.ts +3 -1
  4. package/dist/apiServer/APIService.js +25 -1
  5. package/dist/apiServer/LogService.d.ts +2 -0
  6. package/dist/apiServer/LogService.js +10 -8
  7. package/dist/apiServer/MonitorService.d.ts +4 -1
  8. package/dist/apiServer/MonitorService.js +28 -5
  9. package/dist/apiServer/deployment/Activate.js +2 -6
  10. package/dist/apiServer/deployment/Backups.js +3 -2
  11. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  12. package/dist/apiServer/deployment/Bundler.js +178 -0
  13. package/dist/apiServer/deployment/ConfigService.d.ts +6 -0
  14. package/dist/apiServer/deployment/ConfigService.js +17 -1
  15. package/dist/apiServer/deployment/Deploy.js +101 -57
  16. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  17. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  18. package/dist/apiServer/deployment/Deployer.d.ts +1 -0
  19. package/dist/apiServer/deployment/Deployer.js +7 -5
  20. package/dist/apiServer/deployment/DeployerService.d.ts +27 -2
  21. package/dist/apiServer/deployment/DeployerService.js +129 -30
  22. package/dist/apiServer/deployment/HashPassword.js +2 -2
  23. package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
  24. package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
  25. package/dist/apiServer/deployment/Restore.js +9 -8
  26. package/dist/apiServer/deployment/SecretsInjector.js +2 -1
  27. package/dist/apiServer/deployment/SetupConfigWizard.js +38 -2
  28. package/dist/apiServer/deployment/Status.js +5 -8
  29. package/dist/apiServer/deployment/Watchdog.js +1 -1
  30. package/dist/apiServer/deployment/Wizards.js +16 -11
  31. package/dist/apiServer/deployment/cli.js +33 -14
  32. package/dist/apiServer/deployment/cliCommon.d.ts +13 -1
  33. package/dist/apiServer/deployment/cliCommon.js +50 -2
  34. package/dist/apiServer/deployment/resolveConfig.d.ts +4 -1
  35. package/dist/apiServer/deployment/resolveConfig.js +23 -2
  36. package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
  37. package/dist/apiServer/external/MicroserviceClient.js +90 -10
  38. package/dist/apiServer/external/MicroserviceHost.d.ts +35 -8
  39. package/dist/apiServer/external/MicroserviceHost.js +148 -55
  40. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  41. package/dist/apiServer/helper/AppDataPath.js +81 -0
  42. package/dist/apiServer/helper/ClientIp.d.ts +1 -0
  43. package/dist/apiServer/helper/ClientIp.js +5 -0
  44. package/dist/apiServer/helper/Trace.d.ts +8 -0
  45. package/dist/apiServer/helper/Trace.js +30 -0
  46. package/dist/apiServer/helper/Validator.d.ts +1 -0
  47. package/dist/apiServer/helper/Validator.js +21 -18
  48. package/dist/apiServer/http/Http.d.ts +1 -0
  49. package/dist/apiServer/http/Http.js +5 -2
  50. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  51. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  52. package/dist/apiServer/monitor/MonitorAuth.js +8 -5
  53. package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
  54. package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
  55. package/dist/apiServer/monitor/index.html +66 -66
  56. package/dist/apiServer/security/BlockedIps.js +10 -14
  57. package/dist/apiServer/structures/Interfaces.d.ts +2 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.js +5 -1
  60. package/package.json +21 -6
  61. package/bluegreen.help.md +0 -392
  62. package/cocroach.help.md +0 -191
  63. package/connections.help.md +0 -0
  64. package/monitoring.help.md +0 -350
package/README.md CHANGED
@@ -21,17 +21,18 @@ Node.js 21+ is required.
21
21
  4. [Interceptors (authentication)](#interceptors-authentication)
22
22
  5. [API documentation](#api-documentation)
23
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. [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)
24
+ 7. [Microservice calls](#microservice-calls)
25
+ 8. [Logging and redaction](#logging-and-redaction)
26
+ 9. [Monitor console (`sm/*`)](#monitor-console-sm)
27
+ 10. [IP blocking](#ip-blocking)
28
+ 11. [Authentication](#authentication)
29
+ 12. [WebSocket server](#websocket-server)
30
+ 13. [Deployer and CLI](#deployer-and-cli)
31
+ 14. [Blue-green deployments](#blue-green-deployments)
32
+ 15. [Backups and restore](#backups-and-restore)
33
+ 16. [Deploy review](#deploy-review)
34
+ 17. [Options reference](#options-reference)
35
+ 18. [Security](#security)
35
36
 
36
37
  ---
37
38
 
@@ -57,7 +58,7 @@ Every response has the same envelope:
57
58
 
58
59
  ```jsonc
59
60
  // success
60
- { "data": { … }, "responseTime": 4, "endpoint": "/api/v1/users/get", "version": "1.2.0" }
61
+ { "data": { … }, "responseTime": 4, "endpoint": "/api/v1/users/get", "version": "1.2.0", "traceId": "…" }
61
62
  // error
62
63
  { "error": { "code": 401, "message": "Unauthorized", "httpStatus": 401, "details": "…" } }
63
64
  ```
@@ -111,7 +112,8 @@ Per-endpoint flags:
111
112
  |---|---|
112
113
  | `ignoreInterceptor` | skip authentication for this endpoint |
113
114
  | `allowInterceptorError` | run the handler even if the interceptor rejected the request |
114
- | `validationModel` / `resultModel` | validate the request and/or the response |
115
+ | `validationModel` | validate the request |
116
+ | `resultModel` | describe the response in the API documentation (not checked at runtime) |
115
117
  | `asStream` | stream the response |
116
118
  | `ignoreInDocumentation` | hide from `doc/*` |
117
119
  | `ignoreHttpLogging` | keep out of the request log (polling endpoints, secrets) |
@@ -176,8 +178,25 @@ getDefaultOptions({ interceptor: new SessionInterceptor(), … });
176
178
  // handlers then read req.interceptorResult.userId
177
179
  ```
178
180
 
179
- `InterceptorPayAuth` is a ready-made interceptor for signed server-to-server requests: an HMAC-SHA256
180
- signature with a timestamp window and nonce replay protection.
181
+ Two ready-made interceptors handle signed server-to-server requests. Both use a timestamp window and
182
+ nonce replay protection:
183
+
184
+ - **`InterceptorPayAuth`** uses an HMAC-SHA256 signature with a shared key.
185
+ - **`InterceptorSignedAuth`** uses Ed25519 key pairs. The caller keeps the private key, and the
186
+ server stores only public keys, so nothing on the server can be stolen and reused. The signature
187
+ covers the method, path, timestamp, nonce, every field and the sha256 of every uploaded file.
188
+
189
+ ```ts
190
+ import { InterceptorSignedAuth } from "badmfck-api-server";
191
+
192
+ // server: public keys by key id
193
+ const interceptor = new InterceptorSignedAuth(kid => partners[kid]?.publicKey);
194
+ // handlers then read req.interceptorResult.kid
195
+
196
+ // client
197
+ const { publicKey, privateKey } = InterceptorSignedAuth.generateKeyPair();
198
+ const authorization = InterceptorSignedAuth.sign({ privateKey, kid: "partner-1", method: "POST", url, data: body });
199
+ ```
181
200
 
182
201
  ---
183
202
 
@@ -216,12 +235,65 @@ if (!res.ok) {
216
235
  }
217
236
  ```
218
237
 
219
- `Http` never throws for HTTP or network errors: you always get `{ ok, status, data, error }`. It uses
220
- connection pooling (undici), and every call is recorded for the monitor: an outgoing request log (redacted),
238
+ `Http` never throws for HTTP or network errors: you always get `{ ok, status, data, error }`.
239
+
240
+ Requests are **not retried** unless you ask for it: a `504` or a dropped connection doesn't mean the other side
241
+ did nothing, and a retried payment is a double charge. `retry: { enabled: true }` retries once on network
242
+ errors and on `429`, `502`, `503`, `504`; tune it with `maxAttempts` and `retryOnStatuses`. Multipart uploads
243
+ are never retried. The default timeout is 5 seconds.
244
+
245
+ It uses connection pooling (undici), and every call is recorded for the monitor: an outgoing request log (redacted),
221
246
  active connections per host and latency percentiles (p50, p95, p99) per host.
222
247
 
223
248
  ---
224
249
 
250
+ ## Microservice calls
251
+
252
+ One service (the host) exposes `Req` handlers; others (callers) call them by name. Every service has its own
253
+ Ed25519 key pair — `npx bmfk ms-key` prints one. There is no shared secret: the caller signs each request,
254
+ the host signs each answer, and each side holds only the other's public key.
255
+
256
+ ```ts
257
+ // host
258
+ new MicroserviceHost({
259
+ id: "crm",
260
+ requests: [REQ_FEES_ACTUAL, REQ_MERCHANT_ACTUAL],
261
+ privateKey: secrets.CRM_MS_KEY, // the host's private key: signs its answers
262
+ clients: {
263
+ gate: { publicKey: "MCowBQYDK2VwAyEA…" }, // may call everything in `requests`
264
+ reports: { publicKey: "MCowBQYDK2VwAyEA…", requests: ["REQ_FEES_ACTUAL"] },
265
+ },
266
+ });
267
+
268
+ // caller
269
+ new MicroserviceClient({
270
+ id: "crm",
271
+ host: "https://crm.example.com/api", // https; plain http only to localhost
272
+ kid: "gate", // this caller's name in the host's `clients`
273
+ privateKey: secrets.GATE_MS_KEY,
274
+ hostPublicKey: "MCowBQYDK2VwAyEA…", // every answer is checked against it
275
+ });
276
+
277
+ const fees = await REQ_MICROSERVICE_CALL.request({ id: "crm", requestName: "REQ_FEES_ACTUAL", requestData: { mid } });
278
+ ```
279
+
280
+ - **Who may call what.** The host knows each caller by its key id and refuses requests outside that caller's
281
+ `requests` list. A request can't be replayed, changed on the way, or redirected to another host.
282
+ - **Operations run once.** Each call carries an operation id (`op`) that stays the same across retries: the
283
+ host runs it once and answers repeats from its job store. Pass your own `op` (a payment or transfer id) to
284
+ make it stable beyond this process. The default store is memory, so a restart forgets it: a handler that
285
+ moves money must also record `op` in its own database, in the same transaction as the effect —
286
+ `MicroserviceHost.currentCall()` gives the handler the caller and the `op`. An `op` reused for a different
287
+ request is refused (`CONFLICT`).
288
+ - **Errors.** A handler's `IError` goes back without its `stack`; an unexpected exception is logged on the host
289
+ and the caller gets a bare `INTERNAL_ERROR`.
290
+ - **Confidentiality is TLS.** Signatures prove who sent what; they don't hide it.
291
+
292
+ The old mode with a shared `securityKey` is still accepted, so callers can move one by one. `password`
293
+ was never used: remove it from configs.
294
+
295
+ ---
296
+
225
297
  ## Logging and redaction
226
298
 
227
299
  ```ts
@@ -244,6 +316,20 @@ The incoming and outgoing request logs shown in the monitor go through the same
244
316
  > Redaction is a safety net, not a policy. Don't log card data on purpose: masking patterns can't
245
317
  > recognize every format.
246
318
 
319
+ ### Request tracing
320
+
321
+ Every request gets a trace id. It is returned in the `X-Request-Id` response header and as `traceId` in the
322
+ response body, and it follows everything the request causes:
323
+
324
+ - `req.traceId` in the handler, and `Trace.current()` anywhere in code the request runs, across `await`s;
325
+ - `traceId` on every log item written while handling it (pass it on in your `output`);
326
+ - the incoming request log and the outgoing HTTP log in the monitor;
327
+ - signed microservice calls: the host takes over the caller's id, so one operation has one id across services.
328
+
329
+ Behind nginx, `proxy_set_header X-Request-Id $request_id;` makes the service use nginx's id, so the nginx access
330
+ log and the service logs share it. The header is accepted only from `trustedProxies`; from anyone else it is
331
+ ignored, so a client can't plant an id that collides with someone else's records.
332
+
247
333
  ---
248
334
 
249
335
  ## Monitor console (`sm/*`)
@@ -255,8 +341,8 @@ A web console for operations: `<baseEndPoint>sm/html`, plus a JSON API used by t
255
341
  - Process: memory, event-loop delay, open file descriptors and sockets with history (to catch leaks),
256
342
  and pm2 identity.
257
343
  - System: CPU, RAM, disks, network and load.
258
- - Metrics: request rate, errors and latency, by hour, day or week. Optionally persisted to disk with
259
- 10 weeks of history (`metricsDir`).
344
+ - Metrics: request rate, errors and latency, by hour, day or week; 10 weeks of history kept on disk
345
+ (see [Data folder](#data-folder)).
260
346
  - Outgoing HTTP: per-host p50/p95/p99 and active connections.
261
347
  - Logs: the application log, incoming and outgoing request logs, and tails of pm2 and nginx log files.
262
348
  - Threats: clients that look like they are probing (scanners, `/wp-login.php`, `../`, bursts of 404s).
@@ -277,7 +363,7 @@ access: {
277
363
  monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
278
364
  ```
279
365
 
280
- - **Passwords must be stored as hashes.** Generate one with `npx badmfck hash-password`. The command
366
+ - **Passwords must be stored as hashes.** Generate one with `npx bmfk hash-password`. The command
281
367
  asks for the password interactively and prints the config entry. A plain-text password in the config
282
368
  is refused.
283
369
  - **2FA (TOTP) is mandatory.** At first login the console shows a QR code to scan with any
@@ -294,7 +380,7 @@ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
294
380
  - **Sessions** expire after 15 minutes idle and 8 hours at most. 10 failed logins lock the account
295
381
  for 30 minutes.
296
382
  - **Change access without a restart.** Instead of an inline object, `access` can be a path to a JSON
297
- file with the same shape: `access: "/etc/my-service/access.json"`. `npx badmfck access-config` creates
383
+ file with the same shape: `access: "/etc/my-service/access.json"`. `npx bmfk access-config` creates
298
384
  and edits this file from a menu. Run in the project folder, it finds the path the code assigns to
299
385
  `access` (a string literal in `src/` or the compiled `bin/`/`dist/`), or takes it as an argument. Passwords are typed hidden and stored as hashes, and the result is
300
386
  checked with the service's own validator. The file is watched, and changes apply
@@ -324,8 +410,8 @@ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
324
410
  otherwise every request appears to come from `127.0.0.1`.
325
411
  - **Block addresses.** Admins can block an address or a subnet from the threats page, permanently or
326
412
  for a number of hours. See [IP blocking](#ip-blocking).
327
- - **Keep `monitorAuthDir` outside the deploy folders.** Otherwise a deploy wipes the enrollments and
328
- everyone has to enroll again.
413
+ - **If you set `monitorAuthDir`, keep it outside the deploy folders.** Otherwise a deploy wipes the
414
+ enrollments and everyone has to enroll again. By default they are in `/var/bmfk/<project>/`.
329
415
 
330
416
  ---
331
417
 
@@ -339,13 +425,10 @@ documentation:
339
425
  ```
340
426
 
341
427
  The check runs first, before body parsing, CORS and the interceptor, so a blocked client costs almost
342
- nothing. The list is a JSON file one level **above** the folder with the code, so deploys and restores
343
- never touch it. It is re-read on change:
344
-
345
- | Project | Code | List |
346
- |---|---|---|
347
- | regular | `/var/node/app/…` | `/var/node/blocked-ips.app.json` (named after the project folder) |
348
- | blue-green | `/var/node/app/blue/…` | `/var/node/app/blocked-ips.json` (shared by both slots) |
428
+ nothing. The list is `/var/bmfk/<project>/blocked-ips.json` (see [Data folder](#data-folder)), outside
429
+ the code, so deploys and restores never touch it, and shared by both blue-green slots. It is re-read
430
+ on change. A list already at the old place beside the code (`/var/node/blocked-ips.app.json`, or
431
+ `/var/node/app/blocked-ips.json` for blue-green) keeps being used until you move it.
349
432
 
350
433
  The format:
351
434
 
@@ -393,7 +476,7 @@ Monitor and deployer configs store a salted scrypt hash, never the password itse
393
476
  command on any machine with the package installed:
394
477
 
395
478
  ```text
396
- $ npx badmfck hash-password
479
+ $ npx bmfk hash-password
397
480
 
398
481
  Hash a monitor password (APIService access.monitor)
399
482
  Login: ops
@@ -405,7 +488,7 @@ Repeat password:
405
488
  { "login": "ops", "password": "scrypt$16384$8$1$Rkps…$zrwU…" }
406
489
  ```
407
490
 
408
- - **Deployer users.** For a user in the deployer's `setup.json`, use `npx badmfck hash-password --deployer`.
491
+ - **Deployer users.** For a user in the deployer's `setup.json`, use `npx bmfk hash-password --deployer`.
409
492
  The hash differs from a monitor hash, so they can't be swapped.
410
493
  - **Interactive only.** The password is never accepted as an argument, so it doesn't end up in shell
411
494
  history or `ps`. Without a terminal (in CI, for example), the command refuses to run.
@@ -492,7 +575,8 @@ Authorization: Bearer <token>
492
575
  Re-enrolling through the API is impossible on purpose. Otherwise anyone who learned the password
493
576
  could attach their own authenticator. To reset:
494
577
 
495
- 1. Open `<monitorAuthDir>/monitor-2fa.<projectName>.json` on the server.
578
+ 1. Open `/var/bmfk/<project>/monitor-2fa.json` on the server (with `monitorAuthDir` set:
579
+ `<monitorAuthDir>/monitor-2fa.<projectName>.json`).
496
580
  2. Delete the user's entry under `projects.<projectName>.users.<login>`.
497
581
 
498
582
  No restart is needed. The file is watched like `access.json`: within a second the user's sessions
@@ -521,14 +605,15 @@ documentation users their own passwords, never ones they use elsewhere.
521
605
 
522
606
  - **Server.** The deployer server keeps `setup.json` users as hashes (`hash-password --deployer`).
523
607
  - **Addresses.** `allowed_ips` in `setup.json` limits which addresses can use the deployer at all.
524
- - **Client.** The deploying machine keeps the login and the plain password in `deploy.json`, which
525
- never leaves that machine and must stay out of git.
526
- - **What goes over the wire.** The CLI sends `Authorization: Bearer sha256(login:password)` and
527
- `X-Deployer-Login`.
608
+ - **Client.** The deploying machine keeps the login and either a private key (recommended) or the
609
+ password in `deploy.json`. Either way, the file can deploy on its own: never share it or commit it.
610
+ - **What goes over the wire.** With a key, `Authorization: Signature kid=…, ts=…, nonce=…, sig=…`. The
611
+ signature is good for one request and five minutes, and covers the project, the fields and the
612
+ archive. With a password, `Authorization: Bearer sha256(login:password)` and `X-Deployer-Login`.
528
613
  - **Project token.** Deploying, switching and restoring also require the project's own `token`. The
529
- project config on the server holds only its hash. Run `npx badmfck project-token`: it prints a new
614
+ project config on the server holds only its hash. Run `npx bmfk project-token`: it prints a new
530
615
  random token for `deploy.json` and its hash for the project config. To keep an existing token, run
531
- `npx badmfck project-token --hash`. A token stored in plain text is refused like a wrong token. The
616
+ `npx bmfk project-token --hash`. A token stored in plain text is refused like a wrong token. The
532
617
  server log says why, and a startup error names the affected projects.
533
618
  - **CLI version.** Users stored as a hash need a CLI from version 6 or later.
534
619
 
@@ -593,6 +678,9 @@ How connections are handled:
593
678
  The deployer is an `APIService` running on the target server with the `deployer` option. It receives a
594
679
  build, unpacks it, installs dependencies, writes the configuration and starts the process in pm2.
595
680
 
681
+ The CLI is `bmfk` (`npx bmfk <command>`). `badmfck`, its old name, still works, so existing scripts
682
+ such as `"deploy": "badmfck deploy"` need no change; switch them to `bmfk` when convenient.
683
+
596
684
  **On the server:**
597
685
 
598
686
  ```ts
@@ -604,15 +692,26 @@ getDefaultOptions({
604
692
  });
605
693
  ```
606
694
 
607
- `setup.json` lists who may deploy. Passwords are hashes. The easiest way to manage users, reviewers and
608
- allowed addresses is `npx badmfck setup-config <folder>`, a menu that hashes passwords for you; for a
609
- single hash use `npx badmfck hash-password --deployer`. When sign-in fails, the deployer logs why
695
+ `setup.json` lists who may deploy. The recommended way is a **signing key** per user. Run
696
+ `npx bmfk deploy-key` in the project: it writes an Ed25519 private key into `deploy.json` and prints the
697
+ public key to add to the user in `setup.json` (`setup-config` → "set a deployer user's public key").
698
+ Every request is then signed. A captured request can't be replayed or changed, the signature covers the
699
+ archive's sha256, and the deployer stores no secret at all. `"require_signature": true` in `setup.json`
700
+ turns passwords off for everyone once all users have keys. The project token is still required on top,
701
+ so a deploy always proves which project it is meant for. Users without a key sign in with a password,
702
+ which is stored as a hash. The easiest way to manage users, reviewers and
703
+ allowed addresses is `npx bmfk setup-config <folder>`, a menu that hashes passwords for you; for a
704
+ single hash use `npx bmfk hash-password --deployer`. When sign-in fails, the deployer logs why
610
705
  (unknown login, wrong password, an old CLI without `X-Deployer-Login`), while the client only gets
611
706
  `Unauthorized`.
612
707
 
613
708
  ```jsonc
614
709
  {
615
- "users": [ { "login": "ci", "password": "scrypt$16384$8$1$…" } ],
710
+ "users": [
711
+ { "login": "ci", "publicKey": "MCowBQYDK2VwAyEA…" }, // signs its requests
712
+ { "login": "igor", "password": "scrypt$16384$8$1$…" } // password, until moved to a key
713
+ ],
714
+ "require_signature": false,
616
715
  "allowed_ips": ["203.0.113.7", "10.8.0.0/24"] // who may deploy; IPs and CIDR subnets, IPv4/IPv6
617
716
  }
618
717
  ```
@@ -626,7 +725,7 @@ rejects the whole change, and the previous setup stays in force.
626
725
  > it, every request appears to come from `127.0.0.1`. Never add `127.0.0.1` to `allowed_ips` on a
627
726
  > deployer behind a proxy on the same host: that would let every request through.
628
727
 
629
- A project config (`projects_path/<name>.json`). The easiest way to make one is `npx badmfck project-config`:
728
+ A project config (`projects_path/<name>.json`). The easiest way to make one is `npx bmfk project-config`:
630
729
  it asks for everything below, generates the token, takes config values as hidden input, checks the
631
730
  result against the deployer's schema, and saves the project config and a matching `deploy.json` with
632
731
  permissions `600`.
@@ -635,14 +734,21 @@ permissions `600`.
635
734
  {
636
735
  "name": "my-service",
637
736
  "destination": "/var/node/my-service",
638
- "token": "scrypt$16384$8$1$…", // hash of the project token: npx badmfck project-token
737
+ "token": "scrypt$16384$8$1$…", // hash of the project token: npx bmfk project-token
639
738
  "unpack": true, "install": true, "pm2": true,
640
739
  "backup": true, // copy the current version aside before each deploy (see Backups)
641
740
  "migrate": false, // run `npm run migrate` before the process starts
741
+ "omitDev": false, // true: install without devDependencies (npm ci --omit=dev)
642
742
  "config": { "DB_HOST": "…" } // substituted into the shipped config placeholders _{{DB_HOST}}_
643
743
  }
644
744
  ```
645
745
 
746
+ The `name` becomes the deployed `package.json` name, the data folder `/var/bmfk/<name>` and part of the
747
+ state, backup and secrets file names. So it is restricted: lowercase letters, digits, `.`, `_` and `-`,
748
+ starting with a letter or digit, up to 100 characters — for example `api.gateway.example.com`. A
749
+ project config with any other name is ignored, with an error in the deployer's log;
750
+ `bmfk migrate-configs` lists such configs too.
751
+
646
752
  #### Keeping secrets out of the deployed code
647
753
 
648
754
  By default, `config` values are written into the shipped files in place of `_{{KEY}}_`. That puts
@@ -650,7 +756,7 @@ passwords into the code, into both blue-green slots and into every backup. Add `
650
756
  config to avoid this:
651
757
 
652
758
  ```jsonc
653
- "secrets": {} // uses "secrets_dir" from setup.json
759
+ "secrets": {} // "secrets_dir" from setup.json, else /var/bmfk/<project>/secrets[-<slot>].json
654
760
  "secrets": { "dir": "/etc/node-secrets" } // → /etc/node-secrets/<project>[-<slot>].json
655
761
  "secrets": { "file": "/etc/node-secrets/my.json" }
656
762
  ```
@@ -687,38 +793,66 @@ git: it holds credentials.
687
793
  {
688
794
  "name": "my-service",
689
795
  "host": "https://deployer.example.com/api/pckg/add",
690
- "token": "<project token, printed by npx badmfck project-token>",
796
+ "token": "<project token, printed by npx bmfk project-token>",
691
797
  "username": "ci",
692
- "password": "<your password>",
798
+ "privateKey": "<from npx bmfk deploy-key>", // or "password": "<your password>"
693
799
  "includes": ["certs", { "src": "assets/logo.png", "dest": "bin/logo.png" }],
694
- "excludes": ["*.map"]
800
+ "excludes": ["*.map"],
801
+ "bundle": true // optional, see below
695
802
  }
696
803
  ```
697
804
 
805
+ **`"bundle": true`** ships the app's own code as one file instead of the tsc tree in `./bin`. It needs the
806
+ bundler in the project: `npm i -D esbuild @babel/parser` (they are optional, so servers don't install them). esbuild
807
+ bundles `src/` into the file package.json `"main"` points to (the one pm2 starts, e.g. `bin/Main.js`).
808
+ Every package stays a plain `require()`, and the server still runs `npm ci` as usual. Everything else in
809
+ `./bin` (html, json, workers) ships as it is, so the slot keeps the same layout and `__dirname` in the
810
+ entry file is still `bin/`. `./bin` itself is not changed.
811
+
812
+ - The entry is derived from `"main"`: `bin/Main.js` → `src/Main.ts`. Override with
813
+ `"bundle": { "entry": "src/Main.ts" }`.
814
+ - A `bin/Main.js.map` ships alongside (line mappings only, no source code). The deployer then starts the
815
+ process with `--enable-source-maps` automatically, so stack traces point at the original `src/` lines
816
+ even when the code is one minified file. (If the project ships its own `ecosystem.config.js`, the
817
+ deployer can't edit it and instead logs a reminder to add `node_args: "--enable-source-maps"` yourself.)
818
+ Turn the map off with `"sourcemap": false`; an `excludes` pattern like `*.map` drops it too, and then
819
+ the flag isn't added.
820
+ - `"bundle": { "minify": true }` strips comments, renames local variables and collapses whitespace. It
821
+ costs nothing at runtime and makes the shipped file hard to read, so a casual `cat` over `./bin` no
822
+ longer reveals the source. It is **not** a secret-hiding measure: string literals (so any value baked
823
+ into the code) stay in clear text, and anyone running as the process user can still read them from the
824
+ runtime. The real fix for credentials in code is a [secrets file](#keeping-secrets-out-of-the-deployed-code);
825
+ protect the files themselves with `"chmod": 700` and a dedicated OS user.
826
+ - The deploy warns, but doesn't stop, about code that behaves differently once it's in one file:
827
+ `__dirname` / `__filename` outside the entry (it becomes `bin/`), a value exported by the entry (such
828
+ as `export const __root = __dirname`) read while modules load rather than inside a function (it's not
829
+ set yet), and `.js` files left in `./bin` that are not part of the bundle.
830
+
698
831
  ```json
699
832
  "scripts": {
700
- "deploy": "badmfck deploy",
701
- "activate": "badmfck activate",
702
- "status": "badmfck status",
703
- "backups": "badmfck backups",
704
- "restore": "badmfck restore"
833
+ "deploy": "bmfk deploy",
834
+ "activate": "bmfk activate",
835
+ "status": "bmfk status",
836
+ "backups": "bmfk backups",
837
+ "restore": "bmfk restore"
705
838
  }
706
839
  ```
707
840
 
708
841
  | Command | What it does |
709
842
  |---|---|
710
- | `badmfck wizards` | list every interactive wizard below with what it does, and run one |
711
- | `badmfck deploy [config]` | build and upload the project |
712
- | `badmfck activate [config] [blue\|green]` | switch traffic to a slot (blue-green) |
713
- | `badmfck status [config]` | active and last deployed slot, recent history |
714
- | `badmfck backups [config]` | list backups |
715
- | `badmfck restore [config] [backup] [--yes]` | restore a backup |
716
- | `badmfck hash-password [--deployer]` | hash a password for the monitor or `setup.json` |
717
- | `badmfck project-token [--hash]` | generate a project token and its hash, or hash an existing token |
718
- | `badmfck project-config` | build a project config for the deployer step by step (plus a `deploy.json` skeleton) |
719
- | `badmfck access-config [file]` | create or edit `access.json`: monitor and documentation users, roles, passwords, allowed addresses |
720
- | `badmfck migrate-configs [folder] [--yes]` | hash the secrets of old `setup.json`, project configs and `access.json` files in place |
721
- | `badmfck setup-config [file\|folder]` | edit the deployer's `setup.json`: add, rename or remove users, change passwords, reviewers, allowed IPs |
843
+ | `bmfk wizards` | list every interactive wizard below with what it does, and run one |
844
+ | `bmfk deploy [config]` | build and upload the project |
845
+ | `bmfk activate [config] [blue\|green]` | switch traffic to a slot (blue-green) |
846
+ | `bmfk status [config]` | active and last deployed slot, recent history |
847
+ | `bmfk backups [config]` | list backups |
848
+ | `bmfk restore [config] [backup] [--yes]` | restore a backup |
849
+ | `bmfk hash-password [--deployer]` | hash a password for the monitor or `setup.json` |
850
+ | `bmfk project-token [--hash]` | generate a project token and its hash, or hash an existing token |
851
+ | `bmfk project-config` | build a project config for the deployer step by step (plus a `deploy.json` skeleton) |
852
+ | `bmfk access-config [file]` | create or edit `access.json`: monitor and documentation users, roles, passwords, allowed addresses |
853
+ | `bmfk migrate-configs [folder] [--yes]` | hash the secrets of old `setup.json`, project configs and `access.json` files in place |
854
+ | `bmfk setup-config [file\|folder]` | edit the deployer's `setup.json`: add, rename or remove users, change passwords, reviewers, allowed IPs |
855
+ | `bmfk deploy-key [deploy.json]` | generate a signing key: private key into `deploy.json`, public key for `setup.json` |
722
856
 
723
857
  To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json`.
724
858
 
@@ -729,7 +863,9 @@ To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json
729
863
  - Unsafe destinations are refused: relative paths, the filesystem root, top-level system folders
730
864
  (`/var`, `/etc`…), the deployer's own folders, and a folder whose wipe would delete another project.
731
865
  - Dependencies are installed with `npm ci --ignore-scripts`. `migrate` is the only script the deployer
732
- runs.
866
+ runs. With `"omitDev": true` in the project config, devDependencies (TypeScript, test tools, the
867
+ bundler) are not installed on the server at all. Check first that `npm start` and `npm run migrate`
868
+ need nothing from devDependencies — `ts-node` in a migrate script, for example.
733
869
  - Every deploy, switch and restore needs a deployer user and the project token. Both are stored on
734
870
  the server only as hashes.
735
871
  - `allowed_ips` limits which addresses can reach the deployer at all.
@@ -802,7 +938,7 @@ The deployer manages two nginx files per project:
802
938
  npm run deploy # new version → inactive slot (e.g. green), production unchanged
803
939
  npm run status # "green is deployed but NOT switched"
804
940
  npm run activate # traffic → green
805
- npx badmfck activate blue # rollback → blue
941
+ npx bmfk activate blue # rollback → blue
806
942
  ```
807
943
 
808
944
  ### Is my process live? (in the application)
@@ -864,7 +1000,7 @@ With `"backup": true`, the deployer copies the destination aside before every de
864
1000
  ```bash
865
1001
  npm run backups # list: version, slot, who, when, size
866
1002
  npm run restore # pick one interactively, confirm
867
- npx badmfck restore 2026-10-13_10-00-00-my-service-blue --yes # non-interactive (CI)
1003
+ npx bmfk restore 2026-10-13_10-00-00-my-service-blue --yes # non-interactive (CI)
868
1004
  ```
869
1005
 
870
1006
  How a restore works:
@@ -888,7 +1024,7 @@ credentials alone can't change production.
888
1024
  ### Setup
889
1025
 
890
1026
  Reviewers are defined in the deployer's `setup.json`. Their passwords are hashes made with
891
- `npx badmfck hash-password`, and they set up 2FA at the first sign-in. `review_url` is the address of
1027
+ `npx bmfk hash-password`, and they set up 2FA at the first sign-in. `review_url` is the address of
892
1028
  the review page, as reviewers reach it:
893
1029
 
894
1030
  ```jsonc
@@ -918,7 +1054,7 @@ so at startup and refuses that project's uploads until it is fixed.
918
1054
 
919
1055
  ### How it works
920
1056
 
921
- 1. **`badmfck deploy`** uploads as usual. The archive goes through all the usual checks and is then
1057
+ 1. **`bmfk deploy`** uploads as usual. The archive goes through all the usual checks and is then
922
1058
  held. The CLI prints `WAITING FOR REVIEW`, and production is untouched.
923
1059
  2. **Each reviewer gets an email** with a personal link. The link alone is not enough: it opens a
924
1060
  sign-in with login, password and a 2FA code.
@@ -927,7 +1063,7 @@ so at startup and refuses that project's uploads until it is fixed.
927
1063
  line-by-line diff.
928
1064
  4. **Accept** runs the normal deploy (backup, migrations, pm2, nginx) from the stored archive, after
929
1065
  checking that its SHA-256 still matches what the reviewers saw. For blue-green, the new version
930
- lands in the inactive slot, and `badmfck activate` still switches traffic. **Decline** deletes the
1066
+ lands in the inactive slot, and `bmfk activate` still switches traffic. **Decline** deletes the
931
1067
  archive.
932
1068
  5. **A new upload** replaces the pending one. Every old link and every open review session stop
933
1069
  working, and reviewers get new links.
@@ -970,6 +1106,34 @@ so no restart is needed.
970
1106
 
971
1107
  ---
972
1108
 
1109
+
1110
+ ### Data folder
1111
+
1112
+ What has to survive restarts and deploys lives in one folder per project, outside the deployed code:
1113
+
1114
+ ```
1115
+ /var/bmfk/<project>/
1116
+ metrics/ metrics history: the current week per minute, 10 weeks in all
1117
+ threats.json what the threat monitor has seen (addresses, user agents, URLs — never bodies)
1118
+ blocked-ips.json
1119
+ monitor-2fa.json monitor 2FA enrollments
1120
+ secrets[-<slot>].json config values the deployer keeps out of the code (`"secrets": {}`)
1121
+ ```
1122
+
1123
+ - **The project name is the deployer's.** On every deploy the deployer writes its project name into
1124
+ the deployed `package.json` (and `package-lock.json`) `"name"`, and the app takes it from there. One
1125
+ source tree deployed as several projects gets a folder per project; the two blue-green slots of one
1126
+ project share theirs. Your repository's `package.json` is not changed. Off the deployer, the
1127
+ `package.json` name is used as is. (`projectName` stays what the authenticator app shows.)
1128
+ - **One writer.** Only the live process writes metrics and threats: a blue-green standby and pm2 cluster workers
1129
+ other than instance 0 count in memory only. A slot that becomes live loads what the other slot wrote,
1130
+ so charts continue across deploys.
1131
+ - **Rights.** The app creates its folder (`0700`). If it can't create `/var/bmfk` — say, the app runs as
1132
+ an unprivileged user — it says so at startup and falls back to a folder beside the code. Create the
1133
+ root once: `sudo mkdir /var/bmfk && sudo chown <app user> /var/bmfk`.
1134
+ - `BMFK_DATA_DIR` moves the root. Each file can still be set on its own: `metricsDir` (`false` keeps
1135
+ metrics in memory), `blockedIps.file`, `monitorAuthDir` / `monitorAuthFile`.
1136
+
973
1137
  ## Options reference
974
1138
 
975
1139
  | Option | Default | Description |
@@ -983,8 +1147,8 @@ so no restart is needed.
983
1147
  | `interceptor` | — | authentication for your endpoints |
984
1148
  | `preproducer` / `postproducer` | — | hooks before the handler / before the response is sent |
985
1149
  | `access` | `{}` | `{ monitor, documentation, monitorAllowedIps }`, or a path to a JSON file reloaded on change |
986
- | `monitorAuthDir` / `monitorAuthFile` | in memory | where 2FA enrollments are stored |
987
- | `metricsDir` | in memory | persist metrics; 10 weeks are kept |
1150
+ | `monitorAuthDir` / `monitorAuthFile` | `/var/bmfk/<project>/monitor-2fa.json` | where 2FA enrollments are stored |
1151
+ | `metricsDir` | `/var/bmfk/<project>/metrics` | metrics history, 10 weeks; `false` → in memory only |
988
1152
  | `logFiles` | pm2 auto-detected | log files the monitor may tail (for example nginx) |
989
1153
  | `threatMonitoring` | `true` | probe and scan detection; observation only |
990
1154
  | `trustedProxies` | loopback | proxies whose `X-Real-IP` / `X-Forwarded-For` are trusted |
@@ -1013,7 +1177,8 @@ so no restart is needed.
1013
1177
  - **Client IP.** Proxy headers are trusted only from `trustedProxies`, so clients can't spoof their
1014
1178
  address.
1015
1179
  - **Deploys.** Archives are checked for path traversal and escaping symlinks, package install scripts
1016
- are disabled, and every deploy needs a user and the project token, both stored only as hashes.
1180
+ are disabled, and every deploy needs a user and the project token. Requests are signed with Ed25519
1181
+ (the deployer keeps only public keys), so they can't be replayed or altered.
1017
1182
  - **Blue-green.** Applications get a read-only status token; deploy credentials never reach them.
1018
1183
  - **WebSocket.** Origin checks, authorization within a time limit, and limits on message size, message
1019
1184
  rate and connections. A malformed frame can't crash the process.
@@ -1022,7 +1187,7 @@ so no restart is needed.
1022
1187
  ### What you must configure before going to production
1023
1188
 
1024
1189
  1. Set `corsHostWhiteList` to your real front-end origins. Don't use `"*"` with cookies.
1025
- 2. Store all monitor and deployer passwords as hashes (`npx badmfck hash-password`).
1190
+ 2. Store all monitor and deployer passwords as hashes (`npx bmfk hash-password`).
1026
1191
  3. Point `monitorAuthDir` to a persistent directory outside the deploy folders, readable only by the
1027
1192
  service user.
1028
1193
  4. Run behind nginx (or another proxy) on loopback with TLS, and keep `trustedProxies` at its default
@@ -1049,7 +1214,7 @@ so no restart is needed.
1049
1214
  each part and convert its files right after:
1050
1215
 
1051
1216
  1. **CLI.** Update the CLI on the machines you deploy from. The new CLI also works with old deployers.
1052
- 2. **Deployer.** Upgrade the deployer, then run `npx badmfck migrate-configs <projects folder>`. It
1217
+ 2. **Deployer.** Upgrade the deployer, then run `npx bmfk migrate-configs <projects folder>`. It
1053
1218
  picks up the folder's `setup.json` and every project config at once. Add `--yes` to skip the
1054
1219
  confirmation, for example in a script. It hashes the
1055
1220
  passwords in `setup.json` and the token of every project config, and renames the old `username`
@@ -1057,14 +1222,17 @@ each part and convert its files right after:
1057
1222
  `deploy.json` unchanged.
1058
1223
  3. **Apps.** Upgrade each app, then convert its `access.json` with the same command. Monitor users
1059
1224
  keep their passwords; documentation passwords stay as they are. An app that sets `access` as an
1060
- inline object needs the passwords in that object replaced with hashes (`npx badmfck hash-password`),
1061
- or moved to a file with `npx badmfck access-config`.
1225
+ inline object needs the passwords in that object replaced with hashes (`npx bmfk hash-password`),
1226
+ or moved to a file with `npx bmfk access-config`.
1062
1227
 
1063
1228
  Before changing anything, `migrate-configs` shows what it will change and flags weak passwords (short,
1064
1229
  or the same as the login). It copies the originals into a `.pre-hash-backup-*` folder (permissions
1065
1230
  `700`) and verifies every new hash. Delete that folder once deploys and sign-ins work, because it holds
1066
1231
  the plain secrets.
1067
1232
 
1233
+ Then move deploys to signing keys, one user at a time: `npx bmfk deploy-key` in the project, and the
1234
+ public key into `setup.json`. When every user has a key, set `"require_signature": true`.
1235
+
1068
1236
  Also removed in 6.x: the old `MysqlService` (use `DBService`).
1069
1237
 
1070
1238
  ---
@@ -22,6 +22,7 @@ export interface IDeployerUser extends IMonitorUser {
22
22
  }
23
23
  export interface APIServiceNetworkLogItem {
24
24
  id: number;
25
+ traceId?: string;
25
26
  created: number;
26
27
  time: number;
27
28
  referer?: string;
@@ -55,7 +56,7 @@ export interface APIServiceOptions<TInterceptor = unknown> {
55
56
  appVersion?: string;
56
57
  fileTempDir: string;
57
58
  fileLimit: number;
58
- metricsDir?: string;
59
+ metricsDir?: string | false;
59
60
  blueGreenWatchMs?: number;
60
61
  logFiles?: ILogFilesOptions;
61
62
  monitorAuthDir?: string;
@@ -94,6 +95,7 @@ export declare const REQ_MONITOR_ALLOWED_IPS: Req<void, string[]>;
94
95
  export declare const S_APP_STARTED: Signal<void>;
95
96
  export declare function Initializer(services: IBaseService[]): Promise<void>;
96
97
  export declare class APIService<TInterceptorResult = any, TInternalCallParams = any> extends BaseService {
98
+ finishService(): Promise<void>;
97
99
  static getBlueGreenActiveState(opts?: IBlueGreenStateOptions): Promise<IBlueGreenState>;
98
100
  static get blueGreenState(): IBlueGreenState | null;
99
101
  static get isLive(): boolean | null;