badmfck-api-server 6.0.12 → 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 (60) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +207 -73
  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/Bundler.d.ts +12 -0
  10. package/dist/apiServer/deployment/Bundler.js +178 -0
  11. package/dist/apiServer/deployment/ConfigService.d.ts +6 -0
  12. package/dist/apiServer/deployment/ConfigService.js +17 -1
  13. package/dist/apiServer/deployment/Deploy.js +96 -54
  14. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +1 -0
  15. package/dist/apiServer/deployment/DeployKeyWizard.js +17 -1
  16. package/dist/apiServer/deployment/DeployerService.d.ts +4 -1
  17. package/dist/apiServer/deployment/DeployerService.js +87 -18
  18. package/dist/apiServer/deployment/HashPassword.js +2 -2
  19. package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
  20. package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
  21. package/dist/apiServer/deployment/Restore.js +5 -5
  22. package/dist/apiServer/deployment/SecretsInjector.js +2 -1
  23. package/dist/apiServer/deployment/SetupConfigWizard.js +1 -1
  24. package/dist/apiServer/deployment/Status.js +1 -1
  25. package/dist/apiServer/deployment/Watchdog.js +1 -1
  26. package/dist/apiServer/deployment/Wizards.js +11 -11
  27. package/dist/apiServer/deployment/cli.js +25 -16
  28. package/dist/apiServer/deployment/cliCommon.d.ts +12 -0
  29. package/dist/apiServer/deployment/cliCommon.js +44 -0
  30. package/dist/apiServer/deployment/resolveConfig.d.ts +2 -0
  31. package/dist/apiServer/deployment/resolveConfig.js +10 -0
  32. package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
  33. package/dist/apiServer/external/MicroserviceClient.js +90 -10
  34. package/dist/apiServer/external/MicroserviceHost.d.ts +35 -8
  35. package/dist/apiServer/external/MicroserviceHost.js +148 -55
  36. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  37. package/dist/apiServer/helper/AppDataPath.js +81 -0
  38. package/dist/apiServer/helper/ClientIp.d.ts +1 -0
  39. package/dist/apiServer/helper/ClientIp.js +5 -0
  40. package/dist/apiServer/helper/Trace.d.ts +8 -0
  41. package/dist/apiServer/helper/Trace.js +30 -0
  42. package/dist/apiServer/helper/Validator.d.ts +1 -0
  43. package/dist/apiServer/helper/Validator.js +21 -18
  44. package/dist/apiServer/http/Http.d.ts +1 -0
  45. package/dist/apiServer/http/Http.js +5 -2
  46. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +2 -1
  47. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +1 -1
  48. package/dist/apiServer/monitor/MonitorAuth.js +8 -5
  49. package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
  50. package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
  51. package/dist/apiServer/monitor/index.html +66 -66
  52. package/dist/apiServer/security/BlockedIps.js +10 -14
  53. package/dist/apiServer/structures/Interfaces.d.ts +2 -0
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.js +3 -1
  56. package/package.json +21 -6
  57. package/bluegreen.help.md +0 -392
  58. package/cocroach.help.md +0 -191
  59. package/connections.help.md +0 -0
  60. package/monitoring.help.md +0 -350
package/CHANGELOG.md ADDED
@@ -0,0 +1,86 @@
1
+ # Changelog
2
+
3
+ ## 6.0.13 — 2026-11-19
4
+
5
+ ### Before you upgrade
6
+
7
+ These change behaviour. Check each against your project.
8
+
9
+ - **Outgoing HTTP is no longer retried by default.** `Http` used to retry failed requests on its own,
10
+ which could send a payment twice. Retries are now off unless a call asks for them:
11
+ `{ retry: { enabled: true } }`. Multipart requests are never retried.
12
+ - **Validation bounds that were ignored are now enforced.** Two bugs are fixed:
13
+ - Bounds given as separate keys — `$__limit_min: 10`, `$__limit_max: 100` — were never applied.
14
+ They now are.
15
+ - A bound of `0` was treated as "no bound": `$__n: { min: 0 }` let `-1` through. It no longer does.
16
+
17
+ Requests that passed before can now get a 400. Review every `$__*_min`, `$__*_max` and `min: 0` /
18
+ `max: 0` in your models before upgrading.
19
+ - **Every response carries a trace id**: the `X-Request-Id` header and `traceId` in the JSON envelope.
20
+ Clients that compare the whole response body need to allow the new field.
21
+ - **Data now lives in `/var/bmfk/<project>/`** (see the README, "Data folder"): metrics history,
22
+ threats, blocked IPs, monitor 2FA enrollments and deployer secrets. Create the root once on each
23
+ server: `sudo mkdir /var/bmfk && sudo chown <app user> /var/bmfk`. Without it the app falls back to
24
+ a folder beside the code and says so at startup. Explicit settings (`metricsDir`, `blockedIps.file`,
25
+ `monitorAuthDir`, `secrets_dir`) still win, and a `blocked-ips` file at the old place keeps being used.
26
+ - **The deployer renames the deployed app.** On every deploy it writes its project name into the
27
+ deployed `package.json` and `package-lock.json` `"name"`. Your repository is not changed. If your code
28
+ reads `package.json` `"name"` at runtime, it now gets the deployer's project name.
29
+ - **Project names are validated.** A project config whose `name` is not lowercase letters, digits,
30
+ `.`, `_` and `-` (starting with a letter or digit, up to 100 characters) is ignored by the deployer,
31
+ with an error in its log. Run `npx bmfk migrate-configs` to list such configs before upgrading the
32
+ deployer.
33
+ - **`bundle` needs its tools installed in the project**: `npm i -D esbuild @babel/parser`. They are no
34
+ longer dependencies of the library (see Dependencies).
35
+
36
+ ### Added
37
+
38
+ - **Signed microservice calls.** Each service has its own Ed25519 key pair (`npx bmfk ms-key`). The
39
+ caller signs every request, and the host signs every answer, bound to that request. Hosts list their
40
+ callers in `clients` with an allow-list of `requests`. An operation id (`op`) is kept across retries,
41
+ so the host runs an operation once, and reusing an `op` for a different request is refused.
42
+ `MicroserviceHost.currentCall()` tells a handler who is calling. Signed calls go over https only
43
+ (plain http only to localhost), and errors are returned without stack traces.
44
+ - **Request tracing.** Every request gets a trace id. It is in the response, in `req.traceId`, in every
45
+ log line written while handling the request, in the incoming and outgoing request logs, and in signed
46
+ microservice calls, where the host takes over the caller's id. An incoming `X-Request-Id` is accepted
47
+ only from a trusted proxy. `Trace` is exported.
48
+ - **Monitor: trace ids.** The Log, Net log and Outgoing journals have a TRACE column and search by
49
+ trace id. The detail view links to the same trace in the other journals. Monitor UI 1.0.30.
50
+ - **Metrics history survives restarts and deploys**, on by default. Only the live process writes it:
51
+ a blue-green standby and pm2 workers other than instance 0 keep counting in memory only. A slot that
52
+ becomes live first loads what the other slot wrote. `metricsDir: false` keeps metrics in memory.
53
+ - **Threats survive restarts and deploys**: `/var/bmfk/<project>/threats.json`, saved every minute and
54
+ on shutdown, by the live process only. It holds addresses, user agents and URLs, never request bodies.
55
+ - **`omitDev` in a project config**: install with `npm ci --omit=dev`, so devDependencies never reach
56
+ the server. Off by default. Check first that `npm start` and `npm run migrate` need nothing from
57
+ devDependencies.
58
+ - **`bmfk` CLI.** The command is now `bmfk`. `badmfck` still works, so existing scripts need no change.
59
+ - **Clearer deploy output**: one line per step with its duration, and the build's own output shown
60
+ only when the build fails.
61
+ - **Test suite**: `npm test` (node:test), 81 tests.
62
+
63
+ ### Changed
64
+
65
+ - `resultModel` on an endpoint is documented as what it is: documentation only. It does not validate
66
+ or filter the response.
67
+ - Deployer health checks (liveness, readiness) keep retrying explicitly, since `Http` no longer does it
68
+ by default.
69
+
70
+ ### Fixed
71
+
72
+ - Validation: `$__X_min` / `$__X_max` were never applied, and a bound of 0 was ignored (see above).
73
+ - v1 microservice calls: the payload is decrypted before the replay-cache lookup.
74
+
75
+ ### Deprecated
76
+
77
+ - Microservice `securityKey` (v1, shared AES key): still accepted while services move to signed calls.
78
+ It will be removed.
79
+ - Microservice `password`: never used. Remove it from configs.
80
+
81
+ ### Dependencies
82
+
83
+ - `npm audit`: 0 vulnerabilities. `undici` ^7.30.2.
84
+ - `esbuild` and `@babel/parser` are optional peer dependencies now, loaded only by `bundle`. Before,
85
+ every project and every server installed them, esbuild with a platform binary of about 10 MB.
86
+ - `@types/mysql` removed.
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) |
@@ -233,12 +235,65 @@ if (!res.ok) {
233
235
  }
234
236
  ```
235
237
 
236
- `Http` never throws for HTTP or network errors: you always get `{ ok, status, data, error }`. It uses
237
- 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),
238
246
  active connections per host and latency percentiles (p50, p95, p99) per host.
239
247
 
240
248
  ---
241
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
+
242
297
  ## Logging and redaction
243
298
 
244
299
  ```ts
@@ -261,6 +316,20 @@ The incoming and outgoing request logs shown in the monitor go through the same
261
316
  > Redaction is a safety net, not a policy. Don't log card data on purpose: masking patterns can't
262
317
  > recognize every format.
263
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
+
264
333
  ---
265
334
 
266
335
  ## Monitor console (`sm/*`)
@@ -272,8 +341,8 @@ A web console for operations: `<baseEndPoint>sm/html`, plus a JSON API used by t
272
341
  - Process: memory, event-loop delay, open file descriptors and sockets with history (to catch leaks),
273
342
  and pm2 identity.
274
343
  - System: CPU, RAM, disks, network and load.
275
- - Metrics: request rate, errors and latency, by hour, day or week. Optionally persisted to disk with
276
- 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)).
277
346
  - Outgoing HTTP: per-host p50/p95/p99 and active connections.
278
347
  - Logs: the application log, incoming and outgoing request logs, and tails of pm2 and nginx log files.
279
348
  - Threats: clients that look like they are probing (scanners, `/wp-login.php`, `../`, bursts of 404s).
@@ -294,7 +363,7 @@ access: {
294
363
  monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
295
364
  ```
296
365
 
297
- - **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
298
367
  asks for the password interactively and prints the config entry. A plain-text password in the config
299
368
  is refused.
300
369
  - **2FA (TOTP) is mandatory.** At first login the console shows a QR code to scan with any
@@ -311,7 +380,7 @@ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
311
380
  - **Sessions** expire after 15 minutes idle and 8 hours at most. 10 failed logins lock the account
312
381
  for 30 minutes.
313
382
  - **Change access without a restart.** Instead of an inline object, `access` can be a path to a JSON
314
- 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
315
384
  and edits this file from a menu. Run in the project folder, it finds the path the code assigns to
316
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
317
386
  checked with the service's own validator. The file is watched, and changes apply
@@ -341,8 +410,8 @@ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
341
410
  otherwise every request appears to come from `127.0.0.1`.
342
411
  - **Block addresses.** Admins can block an address or a subnet from the threats page, permanently or
343
412
  for a number of hours. See [IP blocking](#ip-blocking).
344
- - **Keep `monitorAuthDir` outside the deploy folders.** Otherwise a deploy wipes the enrollments and
345
- 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>/`.
346
415
 
347
416
  ---
348
417
 
@@ -356,13 +425,10 @@ documentation:
356
425
  ```
357
426
 
358
427
  The check runs first, before body parsing, CORS and the interceptor, so a blocked client costs almost
359
- nothing. The list is a JSON file one level **above** the folder with the code, so deploys and restores
360
- never touch it. It is re-read on change:
361
-
362
- | Project | Code | List |
363
- |---|---|---|
364
- | regular | `/var/node/app/…` | `/var/node/blocked-ips.app.json` (named after the project folder) |
365
- | 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.
366
432
 
367
433
  The format:
368
434
 
@@ -410,7 +476,7 @@ Monitor and deployer configs store a salted scrypt hash, never the password itse
410
476
  command on any machine with the package installed:
411
477
 
412
478
  ```text
413
- $ npx badmfck hash-password
479
+ $ npx bmfk hash-password
414
480
 
415
481
  Hash a monitor password (APIService access.monitor)
416
482
  Login: ops
@@ -422,7 +488,7 @@ Repeat password:
422
488
  { "login": "ops", "password": "scrypt$16384$8$1$Rkps…$zrwU…" }
423
489
  ```
424
490
 
425
- - **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`.
426
492
  The hash differs from a monitor hash, so they can't be swapped.
427
493
  - **Interactive only.** The password is never accepted as an argument, so it doesn't end up in shell
428
494
  history or `ps`. Without a terminal (in CI, for example), the command refuses to run.
@@ -509,7 +575,8 @@ Authorization: Bearer <token>
509
575
  Re-enrolling through the API is impossible on purpose. Otherwise anyone who learned the password
510
576
  could attach their own authenticator. To reset:
511
577
 
512
- 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`).
513
580
  2. Delete the user's entry under `projects.<projectName>.users.<login>`.
514
581
 
515
582
  No restart is needed. The file is watched like `access.json`: within a second the user's sessions
@@ -544,9 +611,9 @@ documentation users their own passwords, never ones they use elsewhere.
544
611
  signature is good for one request and five minutes, and covers the project, the fields and the
545
612
  archive. With a password, `Authorization: Bearer sha256(login:password)` and `X-Deployer-Login`.
546
613
  - **Project token.** Deploying, switching and restoring also require the project's own `token`. The
547
- 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
548
615
  random token for `deploy.json` and its hash for the project config. To keep an existing token, run
549
- `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
550
617
  server log says why, and a startup error names the affected projects.
551
618
  - **CLI version.** Users stored as a hash need a CLI from version 6 or later.
552
619
 
@@ -611,6 +678,9 @@ How connections are handled:
611
678
  The deployer is an `APIService` running on the target server with the `deployer` option. It receives a
612
679
  build, unpacks it, installs dependencies, writes the configuration and starts the process in pm2.
613
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
+
614
684
  **On the server:**
615
685
 
616
686
  ```ts
@@ -623,15 +693,15 @@ getDefaultOptions({
623
693
  ```
624
694
 
625
695
  `setup.json` lists who may deploy. The recommended way is a **signing key** per user. Run
626
- `npx badmfck deploy-key` in the project: it writes an Ed25519 private key into `deploy.json` and prints the
696
+ `npx bmfk deploy-key` in the project: it writes an Ed25519 private key into `deploy.json` and prints the
627
697
  public key to add to the user in `setup.json` (`setup-config` → "set a deployer user's public key").
628
698
  Every request is then signed. A captured request can't be replayed or changed, the signature covers the
629
699
  archive's sha256, and the deployer stores no secret at all. `"require_signature": true` in `setup.json`
630
700
  turns passwords off for everyone once all users have keys. The project token is still required on top,
631
701
  so a deploy always proves which project it is meant for. Users without a key sign in with a password,
632
702
  which is stored as a hash. The easiest way to manage users, reviewers and
633
- allowed addresses is `npx badmfck setup-config <folder>`, a menu that hashes passwords for you; for a
634
- single hash use `npx badmfck hash-password --deployer`. When sign-in fails, the deployer logs why
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
635
705
  (unknown login, wrong password, an old CLI without `X-Deployer-Login`), while the client only gets
636
706
  `Unauthorized`.
637
707
 
@@ -655,7 +725,7 @@ rejects the whole change, and the previous setup stays in force.
655
725
  > it, every request appears to come from `127.0.0.1`. Never add `127.0.0.1` to `allowed_ips` on a
656
726
  > deployer behind a proxy on the same host: that would let every request through.
657
727
 
658
- 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`:
659
729
  it asks for everything below, generates the token, takes config values as hidden input, checks the
660
730
  result against the deployer's schema, and saves the project config and a matching `deploy.json` with
661
731
  permissions `600`.
@@ -664,14 +734,21 @@ permissions `600`.
664
734
  {
665
735
  "name": "my-service",
666
736
  "destination": "/var/node/my-service",
667
- "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
668
738
  "unpack": true, "install": true, "pm2": true,
669
739
  "backup": true, // copy the current version aside before each deploy (see Backups)
670
740
  "migrate": false, // run `npm run migrate` before the process starts
741
+ "omitDev": false, // true: install without devDependencies (npm ci --omit=dev)
671
742
  "config": { "DB_HOST": "…" } // substituted into the shipped config placeholders _{{DB_HOST}}_
672
743
  }
673
744
  ```
674
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
+
675
752
  #### Keeping secrets out of the deployed code
676
753
 
677
754
  By default, `config` values are written into the shipped files in place of `_{{KEY}}_`. That puts
@@ -679,7 +756,7 @@ passwords into the code, into both blue-green slots and into every backup. Add `
679
756
  config to avoid this:
680
757
 
681
758
  ```jsonc
682
- "secrets": {} // uses "secrets_dir" from setup.json
759
+ "secrets": {} // "secrets_dir" from setup.json, else /var/bmfk/<project>/secrets[-<slot>].json
683
760
  "secrets": { "dir": "/etc/node-secrets" } // → /etc/node-secrets/<project>[-<slot>].json
684
761
  "secrets": { "file": "/etc/node-secrets/my.json" }
685
762
  ```
@@ -716,39 +793,66 @@ git: it holds credentials.
716
793
  {
717
794
  "name": "my-service",
718
795
  "host": "https://deployer.example.com/api/pckg/add",
719
- "token": "<project token, printed by npx badmfck project-token>",
796
+ "token": "<project token, printed by npx bmfk project-token>",
720
797
  "username": "ci",
721
- "privateKey": "<from npx badmfck deploy-key>", // or "password": "<your password>"
798
+ "privateKey": "<from npx bmfk deploy-key>", // or "password": "<your password>"
722
799
  "includes": ["certs", { "src": "assets/logo.png", "dest": "bin/logo.png" }],
723
- "excludes": ["*.map"]
800
+ "excludes": ["*.map"],
801
+ "bundle": true // optional, see below
724
802
  }
725
803
  ```
726
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
+
727
831
  ```json
728
832
  "scripts": {
729
- "deploy": "badmfck deploy",
730
- "activate": "badmfck activate",
731
- "status": "badmfck status",
732
- "backups": "badmfck backups",
733
- "restore": "badmfck restore"
833
+ "deploy": "bmfk deploy",
834
+ "activate": "bmfk activate",
835
+ "status": "bmfk status",
836
+ "backups": "bmfk backups",
837
+ "restore": "bmfk restore"
734
838
  }
735
839
  ```
736
840
 
737
841
  | Command | What it does |
738
842
  |---|---|
739
- | `badmfck wizards` | list every interactive wizard below with what it does, and run one |
740
- | `badmfck deploy [config]` | build and upload the project |
741
- | `badmfck activate [config] [blue\|green]` | switch traffic to a slot (blue-green) |
742
- | `badmfck status [config]` | active and last deployed slot, recent history |
743
- | `badmfck backups [config]` | list backups |
744
- | `badmfck restore [config] [backup] [--yes]` | restore a backup |
745
- | `badmfck hash-password [--deployer]` | hash a password for the monitor or `setup.json` |
746
- | `badmfck project-token [--hash]` | generate a project token and its hash, or hash an existing token |
747
- | `badmfck project-config` | build a project config for the deployer step by step (plus a `deploy.json` skeleton) |
748
- | `badmfck access-config [file]` | create or edit `access.json`: monitor and documentation users, roles, passwords, allowed addresses |
749
- | `badmfck migrate-configs [folder] [--yes]` | hash the secrets of old `setup.json`, project configs and `access.json` files in place |
750
- | `badmfck setup-config [file\|folder]` | edit the deployer's `setup.json`: add, rename or remove users, change passwords, reviewers, allowed IPs |
751
- | `badmfck deploy-key [deploy.json]` | generate a signing key: private key into `deploy.json`, public key for `setup.json` |
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` |
752
856
 
753
857
  To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json`.
754
858
 
@@ -759,7 +863,9 @@ To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json
759
863
  - Unsafe destinations are refused: relative paths, the filesystem root, top-level system folders
760
864
  (`/var`, `/etc`…), the deployer's own folders, and a folder whose wipe would delete another project.
761
865
  - Dependencies are installed with `npm ci --ignore-scripts`. `migrate` is the only script the deployer
762
- 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.
763
869
  - Every deploy, switch and restore needs a deployer user and the project token. Both are stored on
764
870
  the server only as hashes.
765
871
  - `allowed_ips` limits which addresses can reach the deployer at all.
@@ -832,7 +938,7 @@ The deployer manages two nginx files per project:
832
938
  npm run deploy # new version → inactive slot (e.g. green), production unchanged
833
939
  npm run status # "green is deployed but NOT switched"
834
940
  npm run activate # traffic → green
835
- npx badmfck activate blue # rollback → blue
941
+ npx bmfk activate blue # rollback → blue
836
942
  ```
837
943
 
838
944
  ### Is my process live? (in the application)
@@ -894,7 +1000,7 @@ With `"backup": true`, the deployer copies the destination aside before every de
894
1000
  ```bash
895
1001
  npm run backups # list: version, slot, who, when, size
896
1002
  npm run restore # pick one interactively, confirm
897
- 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)
898
1004
  ```
899
1005
 
900
1006
  How a restore works:
@@ -918,7 +1024,7 @@ credentials alone can't change production.
918
1024
  ### Setup
919
1025
 
920
1026
  Reviewers are defined in the deployer's `setup.json`. Their passwords are hashes made with
921
- `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
922
1028
  the review page, as reviewers reach it:
923
1029
 
924
1030
  ```jsonc
@@ -948,7 +1054,7 @@ so at startup and refuses that project's uploads until it is fixed.
948
1054
 
949
1055
  ### How it works
950
1056
 
951
- 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
952
1058
  held. The CLI prints `WAITING FOR REVIEW`, and production is untouched.
953
1059
  2. **Each reviewer gets an email** with a personal link. The link alone is not enough: it opens a
954
1060
  sign-in with login, password and a 2FA code.
@@ -957,7 +1063,7 @@ so at startup and refuses that project's uploads until it is fixed.
957
1063
  line-by-line diff.
958
1064
  4. **Accept** runs the normal deploy (backup, migrations, pm2, nginx) from the stored archive, after
959
1065
  checking that its SHA-256 still matches what the reviewers saw. For blue-green, the new version
960
- 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
961
1067
  archive.
962
1068
  5. **A new upload** replaces the pending one. Every old link and every open review session stop
963
1069
  working, and reviewers get new links.
@@ -1000,6 +1106,34 @@ so no restart is needed.
1000
1106
 
1001
1107
  ---
1002
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
+
1003
1137
  ## Options reference
1004
1138
 
1005
1139
  | Option | Default | Description |
@@ -1013,8 +1147,8 @@ so no restart is needed.
1013
1147
  | `interceptor` | — | authentication for your endpoints |
1014
1148
  | `preproducer` / `postproducer` | — | hooks before the handler / before the response is sent |
1015
1149
  | `access` | `{}` | `{ monitor, documentation, monitorAllowedIps }`, or a path to a JSON file reloaded on change |
1016
- | `monitorAuthDir` / `monitorAuthFile` | in memory | where 2FA enrollments are stored |
1017
- | `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 |
1018
1152
  | `logFiles` | pm2 auto-detected | log files the monitor may tail (for example nginx) |
1019
1153
  | `threatMonitoring` | `true` | probe and scan detection; observation only |
1020
1154
  | `trustedProxies` | loopback | proxies whose `X-Real-IP` / `X-Forwarded-For` are trusted |
@@ -1053,7 +1187,7 @@ so no restart is needed.
1053
1187
  ### What you must configure before going to production
1054
1188
 
1055
1189
  1. Set `corsHostWhiteList` to your real front-end origins. Don't use `"*"` with cookies.
1056
- 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`).
1057
1191
  3. Point `monitorAuthDir` to a persistent directory outside the deploy folders, readable only by the
1058
1192
  service user.
1059
1193
  4. Run behind nginx (or another proxy) on loopback with TLS, and keep `trustedProxies` at its default
@@ -1080,7 +1214,7 @@ so no restart is needed.
1080
1214
  each part and convert its files right after:
1081
1215
 
1082
1216
  1. **CLI.** Update the CLI on the machines you deploy from. The new CLI also works with old deployers.
1083
- 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
1084
1218
  picks up the folder's `setup.json` and every project config at once. Add `--yes` to skip the
1085
1219
  confirmation, for example in a script. It hashes the
1086
1220
  passwords in `setup.json` and the token of every project config, and renames the old `username`
@@ -1088,15 +1222,15 @@ each part and convert its files right after:
1088
1222
  `deploy.json` unchanged.
1089
1223
  3. **Apps.** Upgrade each app, then convert its `access.json` with the same command. Monitor users
1090
1224
  keep their passwords; documentation passwords stay as they are. An app that sets `access` as an
1091
- inline object needs the passwords in that object replaced with hashes (`npx badmfck hash-password`),
1092
- 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`.
1093
1227
 
1094
1228
  Before changing anything, `migrate-configs` shows what it will change and flags weak passwords (short,
1095
1229
  or the same as the login). It copies the originals into a `.pre-hash-backup-*` folder (permissions
1096
1230
  `700`) and verifies every new hash. Delete that folder once deploys and sign-ins work, because it holds
1097
1231
  the plain secrets.
1098
1232
 
1099
- Then move deploys to signing keys, one user at a time: `npx badmfck deploy-key` in the project, and the
1233
+ Then move deploys to signing keys, one user at a time: `npx bmfk deploy-key` in the project, and the
1100
1234
  public key into `setup.json`. When every user has a key, set `"require_signature": true`.
1101
1235
 
1102
1236
  Also removed in 6.x: the old `MysqlService` (use `DBService`).
@@ -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;