@bmfk/api 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/LICENSE +21 -0
- package/README.md +1293 -2
- package/dist/apiServer/APIService.d.ts +125 -0
- package/dist/apiServer/APIService.js +769 -0
- package/dist/apiServer/BaseEndpoint.d.ts +90 -0
- package/dist/apiServer/BaseEndpoint.js +314 -0
- package/dist/apiServer/BaseService.d.ts +17 -0
- package/dist/apiServer/BaseService.js +39 -0
- package/dist/apiServer/DBService.d.ts +131 -0
- package/dist/apiServer/DBService.js +290 -0
- package/dist/apiServer/DocumentService.d.ts +9 -0
- package/dist/apiServer/DocumentService.js +65 -0
- package/dist/apiServer/LocalRequest.d.ts +3 -0
- package/dist/apiServer/LocalRequest.js +6 -0
- package/dist/apiServer/LogService.d.ts +78 -0
- package/dist/apiServer/LogService.js +349 -0
- package/dist/apiServer/MonitorService.d.ts +102 -0
- package/dist/apiServer/MonitorService.js +615 -0
- package/dist/apiServer/StatService.d.ts +4 -0
- package/dist/apiServer/StatService.js +10 -0
- package/dist/apiServer/TimeframeService.d.ts +28 -0
- package/dist/apiServer/TimeframeService.js +97 -0
- package/dist/apiServer/WebSocketServer.d.ts +39 -0
- package/dist/apiServer/WebSocketServer.js +173 -0
- package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
- package/dist/apiServer/db/IDBAdapter.js +2 -0
- package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
- package/dist/apiServer/db/MysqlAdapter.js +869 -0
- package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
- package/dist/apiServer/db/PostgresAdapter.js +73 -0
- package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
- package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
- package/dist/apiServer/deployment/Activate.d.ts +4 -0
- package/dist/apiServer/deployment/Activate.js +124 -0
- package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
- package/dist/apiServer/deployment/BackupManager.js +174 -0
- package/dist/apiServer/deployment/Backups.d.ts +2 -0
- package/dist/apiServer/deployment/Backups.js +44 -0
- package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
- package/dist/apiServer/deployment/BlueGreenState.js +150 -0
- package/dist/apiServer/deployment/Bundler.d.ts +12 -0
- package/dist/apiServer/deployment/Bundler.js +178 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
- package/dist/apiServer/deployment/ConfigService.js +195 -0
- package/dist/apiServer/deployment/Deploy.d.ts +4 -0
- package/dist/apiServer/deployment/Deploy.js +404 -0
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
- package/dist/apiServer/deployment/Deployer.d.ts +13 -0
- package/dist/apiServer/deployment/Deployer.js +96 -0
- package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
- package/dist/apiServer/deployment/DeployerInit.js +214 -0
- package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
- package/dist/apiServer/deployment/DeployerService.js +1553 -0
- package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
- package/dist/apiServer/deployment/HashPassword.js +126 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
- package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
- package/dist/apiServer/deployment/MigrateProject.js +335 -0
- package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
- package/dist/apiServer/deployment/NginxHelper.js +111 -0
- package/dist/apiServer/deployment/Notifier.d.ts +30 -0
- package/dist/apiServer/deployment/Notifier.js +82 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
- package/dist/apiServer/deployment/Restore.d.ts +2 -0
- package/dist/apiServer/deployment/Restore.js +89 -0
- package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
- package/dist/apiServer/deployment/ReviewStore.js +186 -0
- package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
- package/dist/apiServer/deployment/SecretsInjector.js +189 -0
- package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
- package/dist/apiServer/deployment/Status.d.ts +2 -0
- package/dist/apiServer/deployment/Status.js +83 -0
- package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
- package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
- package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
- package/dist/apiServer/deployment/Watchdog.js +65 -0
- package/dist/apiServer/deployment/Wizards.d.ts +1 -0
- package/dist/apiServer/deployment/Wizards.js +83 -0
- package/dist/apiServer/deployment/cli.d.ts +2 -0
- package/dist/apiServer/deployment/cli.js +224 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
- package/dist/apiServer/deployment/cliCommon.js +110 -0
- package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
- package/dist/apiServer/deployment/cliPrompt.js +38 -0
- package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
- package/dist/apiServer/deployment/resolveConfig.js +139 -0
- package/dist/apiServer/documentation/Documentation.d.ts +18 -0
- package/dist/apiServer/documentation/Documentation.js +143 -0
- package/dist/apiServer/documentation/index.html +460 -0
- package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
- package/dist/apiServer/external/MicroserviceClient.js +144 -0
- package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
- package/dist/apiServer/external/MicroserviceHost.js +183 -0
- package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
- package/dist/apiServer/external/MicroserviceHostController.js +65 -0
- package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
- package/dist/apiServer/helper/AppDataPath.js +81 -0
- package/dist/apiServer/helper/ClientIp.d.ts +3 -0
- package/dist/apiServer/helper/ClientIp.js +33 -0
- package/dist/apiServer/helper/DataProvider.d.ts +18 -0
- package/dist/apiServer/helper/DataProvider.js +57 -0
- package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
- package/dist/apiServer/helper/IpAllowList.js +40 -0
- package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
- package/dist/apiServer/helper/JSONStableStringify.js +15 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/helper/Sleep.d.ts +1 -0
- package/dist/apiServer/helper/Sleep.js +5 -0
- package/dist/apiServer/helper/Trace.d.ts +8 -0
- package/dist/apiServer/helper/Trace.js +30 -0
- package/dist/apiServer/helper/UID.d.ts +16 -0
- package/dist/apiServer/helper/UID.js +98 -0
- package/dist/apiServer/helper/Validator.d.ts +86 -0
- package/dist/apiServer/helper/Validator.js +560 -0
- package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
- package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
- package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
- package/dist/apiServer/helper/ZipUtils.js +28 -0
- package/dist/apiServer/http/Http.d.ts +183 -0
- package/dist/apiServer/http/Http.js +627 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
- package/dist/apiServer/monitor/AccessStore.js +163 -0
- package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
- package/dist/apiServer/monitor/LogFiles.js +109 -0
- package/dist/apiServer/monitor/Monitor.d.ts +54 -0
- package/dist/apiServer/monitor/Monitor.js +447 -0
- package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
- package/dist/apiServer/monitor/MonitorAuth.js +474 -0
- package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
- package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
- package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
- package/dist/apiServer/monitor/SystemInfo.js +217 -0
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
- package/dist/apiServer/monitor/index.html +591 -0
- package/dist/apiServer/review/Review.d.ts +23 -0
- package/dist/apiServer/review/Review.js +149 -0
- package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
- package/dist/apiServer/review/ReviewAuth.js +147 -0
- package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
- package/dist/apiServer/review/ReviewDiff.js +175 -0
- package/dist/apiServer/review/index.html +501 -0
- package/dist/apiServer/routes/Liveness.d.ts +7 -0
- package/dist/apiServer/routes/Liveness.js +27 -0
- package/dist/apiServer/routes/Readiness.d.ts +13 -0
- package/dist/apiServer/routes/Readiness.js +20 -0
- package/dist/apiServer/security/BlockedIps.d.ts +46 -0
- package/dist/apiServer/security/BlockedIps.js +185 -0
- package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
- package/dist/apiServer/structures/DefaultErrors.js +52 -0
- package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
- package/dist/apiServer/structures/HTTPStatus.js +11 -0
- package/dist/apiServer/structures/Interfaces.d.ts +55 -0
- package/dist/apiServer/structures/Interfaces.js +2 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +110 -0
- package/dist/signal/Signal.d.ts +23 -0
- package/dist/signal/Signal.js +85 -0
- package/package.json +88 -4
package/README.md
CHANGED
|
@@ -1,3 +1,1294 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bmfk/api
|
|
2
2
|
|
|
3
|
-
|
|
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 @bmfk/api
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Node.js 24+ is required (the supported LTS lines). Everything is imported from `@bmfk/api` itself; the
|
|
13
|
+
package has no other entry points.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Contents
|
|
18
|
+
|
|
19
|
+
1. [Quick start](#quick-start)
|
|
20
|
+
2. [Endpoints](#endpoints)
|
|
21
|
+
3. [Validation models](#validation-models)
|
|
22
|
+
4. [Interceptors (authentication)](#interceptors-authentication)
|
|
23
|
+
5. [API documentation](#api-documentation)
|
|
24
|
+
6. [Outgoing HTTP client](#outgoing-http-client)
|
|
25
|
+
7. [Microservice calls](#microservice-calls)
|
|
26
|
+
8. [Logging and redaction](#logging-and-redaction)
|
|
27
|
+
9. [Signals and requests between services](#signals-and-requests-between-services)
|
|
28
|
+
10. [Monitor console (`sm/*`)](#monitor-console-sm)
|
|
29
|
+
11. [IP blocking](#ip-blocking)
|
|
30
|
+
12. [Authentication](#authentication)
|
|
31
|
+
13. [WebSocket server](#websocket-server)
|
|
32
|
+
14. [Deployer and CLI](#deployer-and-cli)
|
|
33
|
+
15. [Blue-green deployments](#blue-green-deployments)
|
|
34
|
+
16. [Backups and restore](#backups-and-restore)
|
|
35
|
+
17. [Deploy review](#deploy-review)
|
|
36
|
+
18. [Options reference](#options-reference)
|
|
37
|
+
19. [Security](#security)
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { APIService, Initializer, getDefaultOptions } from "@bmfk/api";
|
|
45
|
+
import { Users } from "./endpoints/Users";
|
|
46
|
+
|
|
47
|
+
const api = new APIService(getDefaultOptions({
|
|
48
|
+
port: 8080,
|
|
49
|
+
baseEndPoint: "/api/v1/",
|
|
50
|
+
projectName: "my-service",
|
|
51
|
+
isProductionEnvironment: true,
|
|
52
|
+
corsHostWhiteList: ["https://app.example.com"],
|
|
53
|
+
endpoints: [new Users()],
|
|
54
|
+
}));
|
|
55
|
+
|
|
56
|
+
Initializer([api]);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Every response has the same envelope:
|
|
60
|
+
|
|
61
|
+
```jsonc
|
|
62
|
+
// success
|
|
63
|
+
{ "data": { … }, "responseTime": 4, "endpoint": "/api/v1/users/get", "version": "1.2.0", "traceId": "…" }
|
|
64
|
+
// error
|
|
65
|
+
{ "error": { "code": 401, "message": "Unauthorized", "httpStatus": 401, "details": "…" } }
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Built-in routes: `liveness` and `readiness` (for load balancers and orchestrators), `doc/*` (API documentation),
|
|
69
|
+
`sm/*` (monitor console) and, if configured, `pckg/*` (deployer).
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Endpoints
|
|
74
|
+
|
|
75
|
+
An endpoint class groups handlers under one path segment:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { BaseEndpoint, IRequest, IResponse } from "@bmfk/api";
|
|
79
|
+
|
|
80
|
+
export class Users extends BaseEndpoint {
|
|
81
|
+
constructor() {
|
|
82
|
+
super("users"); // → /api/v1/users/…
|
|
83
|
+
this.registerEndpoints([
|
|
84
|
+
{
|
|
85
|
+
endpoint: "get", // → /api/v1/users/get
|
|
86
|
+
handler: this.get,
|
|
87
|
+
title: "Get a user",
|
|
88
|
+
description: "Returns one user by id",
|
|
89
|
+
validationModel: { id: 0 },
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
endpoint: "profile",
|
|
93
|
+
handler: { // different handlers per HTTP method
|
|
94
|
+
GET: this.profile,
|
|
95
|
+
POST: { controller: this.updateProfile, validationModel: { name: "" } },
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
]);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async get(req: IRequest): Promise<IResponse> {
|
|
102
|
+
return { data: { id: req.data.id } };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`req.data` merges the JSON body, form body and query string. Other useful fields: `req.headers`,
|
|
108
|
+
`req.params`, `req.files` (uploads), `req.ip` (the real client address, see
|
|
109
|
+
[`trustedProxies`](#options-reference)) and `req.interceptorResult` (whatever your interceptor returned).
|
|
110
|
+
|
|
111
|
+
Per-endpoint flags:
|
|
112
|
+
|
|
113
|
+
| Flag | Effect |
|
|
114
|
+
|---|---|
|
|
115
|
+
| `ignoreInterceptor` | skip authentication for this endpoint |
|
|
116
|
+
| `allowInterceptorError` | run the handler even if the interceptor rejected the request |
|
|
117
|
+
| `validationModel` | validate the request |
|
|
118
|
+
| `resultModel` | describe the response in the API documentation (not checked at runtime) |
|
|
119
|
+
| `asStream` | stream the response |
|
|
120
|
+
| `ignoreInDocumentation` | hide from `doc/*` |
|
|
121
|
+
| `ignoreHttpLogging` | keep out of the request log (polling endpoints, secrets) |
|
|
122
|
+
| `independed` | register the path as is, without `baseEndPoint` |
|
|
123
|
+
|
|
124
|
+
A handler can return an error with `throw { ...DefaultErrors.NOT_FOUND, details: "…" }` or
|
|
125
|
+
`return { error: { code, message, httpStatus } }`.
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## Validation models
|
|
130
|
+
|
|
131
|
+
A validation model is a sample object. The type of each value is the type of the field:
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
validationModel: {
|
|
135
|
+
email: "", // string, required
|
|
136
|
+
age: 0, // number
|
|
137
|
+
agree: false, // boolean
|
|
138
|
+
tags: [""], // array of strings
|
|
139
|
+
address: { city: "", zip: "" }, // nested object
|
|
140
|
+
|
|
141
|
+
status: "",
|
|
142
|
+
$__status_values: ["new", "paid", "refunded"], // allowed values (shown in documentation too)
|
|
143
|
+
|
|
144
|
+
comment: "",
|
|
145
|
+
$__comment_optional: true,
|
|
146
|
+
|
|
147
|
+
amount: 0,
|
|
148
|
+
$__amount: { min: 1, max: 100000, details: "Amount in cents" },
|
|
149
|
+
|
|
150
|
+
phone: "",
|
|
151
|
+
$__phone: { regex: "^\\+[0-9]{8,15}$" },
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
A sample value is only the type: `amount: 100` means "a number", not "at most 100". Limits are always
|
|
156
|
+
written as `min` / `max`.
|
|
157
|
+
|
|
158
|
+
For a field `X`, options live in `$__X` (an object, or a string used as the description) or in
|
|
159
|
+
`$__X_optional`, `$__X_values`, `$__X_ignore_in_documentation` and similar keys. Supported options:
|
|
160
|
+
`optional`, `default`, `values`, `min`, `max`, `regex`, `type` (`email`, `phone`, `date`…) and `details`.
|
|
161
|
+
|
|
162
|
+
The `ValidationModel<typeof model>` type turns a model into a TypeScript type, optional and enum fields
|
|
163
|
+
included. `Validator.validateStructure(model, object)` can be used on its own, outside endpoints.
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## Interceptors (authentication)
|
|
168
|
+
|
|
169
|
+
An interceptor runs before every endpoint that doesn't set `ignoreInterceptor`. It returns the caller's
|
|
170
|
+
identity, or an error:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import { IInterceptor, DefaultErrors } from "@bmfk/api";
|
|
174
|
+
|
|
175
|
+
class SessionInterceptor implements IInterceptor<{ userId: number }> {
|
|
176
|
+
async intercept(req) {
|
|
177
|
+
const user = await sessions.find(req.headers.authorization);
|
|
178
|
+
return user ?? { ...DefaultErrors.UNAUTHORIZED };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
getDefaultOptions({ interceptor: new SessionInterceptor(), … });
|
|
183
|
+
// handlers then read req.interceptorResult.userId
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Two ready-made interceptors handle signed server-to-server requests. Both use a timestamp window and
|
|
187
|
+
nonce replay protection:
|
|
188
|
+
|
|
189
|
+
- **`InterceptorPayAuth`** uses an HMAC-SHA256 signature with a shared key.
|
|
190
|
+
- **`InterceptorSignedAuth`** uses Ed25519 key pairs. The caller keeps the private key, and the
|
|
191
|
+
server stores only public keys, so nothing on the server can be stolen and reused. The signature
|
|
192
|
+
covers the method, path, timestamp, nonce, every field and the sha256 of every uploaded file.
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
import { InterceptorSignedAuth } from "@bmfk/api";
|
|
196
|
+
|
|
197
|
+
// server: public keys by key id
|
|
198
|
+
const interceptor = new InterceptorSignedAuth(kid => partners[kid]?.publicKey);
|
|
199
|
+
// handlers then read req.interceptorResult.kid
|
|
200
|
+
|
|
201
|
+
// client
|
|
202
|
+
const { publicKey, privateKey } = InterceptorSignedAuth.generateKeyPair();
|
|
203
|
+
const authorization = InterceptorSignedAuth.sign({ privateKey, kid: "partner-1", method: "POST", url, data: body });
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## API documentation
|
|
209
|
+
|
|
210
|
+
`GET <baseEndPoint>doc/html` is an interactive page, and `<baseEndPoint>doc/json` is the same data as JSON.
|
|
211
|
+
Both are built from your endpoints: titles, descriptions, request models, allowed `values` and result models.
|
|
212
|
+
|
|
213
|
+
Access is restricted to users listed in `access.documentation`. A user can be limited to some endpoints:
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
access: {
|
|
217
|
+
documentation: [{ login: "partner", password: "…", endpoints: ["/api/v1/orders"] }],
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Hide an endpoint with `ignoreInDocumentation`. The built-in `sm/*` and `pckg/*` endpoints are always hidden.
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
## Outgoing HTTP client
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
import { Http } from "@bmfk/api";
|
|
229
|
+
|
|
230
|
+
const res = await Http.post("https://api.example.com/charge", { amount: 100 }, {
|
|
231
|
+
headers: { authorization: `Bearer ${token}` },
|
|
232
|
+
timeoutMs: 15_000,
|
|
233
|
+
retry: { enabled: true },
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
if (!res.ok) {
|
|
237
|
+
// res.status is undefined on network errors; res.error holds the details
|
|
238
|
+
} else {
|
|
239
|
+
use(res.data);
|
|
240
|
+
}
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`Http` never throws for HTTP or network errors: you always get `{ ok, status, data, error }`.
|
|
244
|
+
|
|
245
|
+
Requests are **not retried** unless you ask for it: a `504` or a dropped connection doesn't mean the other side
|
|
246
|
+
did nothing, and a retried payment is a double charge. `retry: { enabled: true }` retries once on network
|
|
247
|
+
errors and on `429`, `502`, `503`, `504`; tune it with `maxAttempts` and `retryOnStatuses`. Multipart uploads
|
|
248
|
+
are never retried. The default timeout is 5 seconds.
|
|
249
|
+
|
|
250
|
+
It uses connection pooling (undici), and every call is recorded for the monitor: an outgoing request log (redacted),
|
|
251
|
+
active connections per host and latency percentiles (p50, p95, p99) per host.
|
|
252
|
+
|
|
253
|
+
A URL that carries a secret (a bot token in the path, a key the provider wants in the query) is recorded
|
|
254
|
+
only as its origin with `skipLogging: true`: the call is still in the outgoing log, the slowest calls and
|
|
255
|
+
the stats — so you see that it was made, when, how long it took and its status — but as
|
|
256
|
+
`https://api.telegram.org`, marked `skipLogging` (“not logged” in the monitor), without path, query, bodies
|
|
257
|
+
or error text.
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
await Http.post(`https://api.telegram.org/bot${token}/sendMessage`, body, { skipLogging: true });
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
---
|
|
264
|
+
|
|
265
|
+
## Microservice calls
|
|
266
|
+
|
|
267
|
+
One service (the host) exposes `Req` handlers; others (callers) call them by name. Every service has its own
|
|
268
|
+
Ed25519 key pair — `npx bmfk ms-key` prints one. There is no shared secret: the caller signs each request,
|
|
269
|
+
the host signs each answer, and each side holds only the other's public key.
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
// host
|
|
273
|
+
new MicroserviceHost({
|
|
274
|
+
id: "crm",
|
|
275
|
+
requests: [REQ_FEES_ACTUAL, REQ_MERCHANT_ACTUAL],
|
|
276
|
+
privateKey: secrets.CRM_MS_KEY, // the host's private key: signs its answers
|
|
277
|
+
clients: {
|
|
278
|
+
shop: { publicKey: "MCowBQYDK2VwAyEA…", allowedIps: ["127.0.0.1", "::1"] }, // everything in `requests`, from this server only
|
|
279
|
+
reports: { publicKey: "MCowBQYDK2VwAyEA…", requests: ["REQ_FEES_ACTUAL"], allowedIps: ["10.8.0.0/24"] },
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// caller
|
|
284
|
+
new MicroserviceClient({
|
|
285
|
+
id: "crm",
|
|
286
|
+
host: "https://crm.example.com/api", // https; plain http only to localhost
|
|
287
|
+
kid: "shop", // this caller's name in the host's `clients`
|
|
288
|
+
privateKey: secrets.GATE_MS_KEY,
|
|
289
|
+
hostPublicKey: "MCowBQYDK2VwAyEA…", // every answer is checked against it
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
const fees = await REQ_MICROSERVICE_CALL.request({ id: "crm", requestName: "REQ_FEES_ACTUAL", requestData: { mid } });
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
- **Who may call what.** The host knows each caller by its key id and refuses requests outside that caller's
|
|
296
|
+
`requests` list. A request can't be replayed, changed on the way, or redirected to another host.
|
|
297
|
+
- **From where.** `allowedIps` (IPs and subnets, IPv4/IPv6) limits where a caller's key works, so a leaked key
|
|
298
|
+
is useless anywhere else. A call from another address gets `403` before its signature is even checked, and
|
|
299
|
+
the host logs the key id and address. The address is the real client's: behind nginx it is `X-Real-IP`
|
|
300
|
+
(`proxy_set_header X-Real-IP $remote_addr;`), believed only from `trustedProxies` (loopback by default);
|
|
301
|
+
otherwise the TCP peer. List both `127.0.0.1` and `::1` for a caller on the same server — `localhost` can
|
|
302
|
+
resolve to either. Without `allowedIps` any address is accepted; a malformed or empty list stops the host.
|
|
303
|
+
- **Operations run once.** Each call carries an operation id (`op`) that stays the same across retries: the
|
|
304
|
+
host runs it once and answers repeats from its job store. Pass your own `op` (a payment or transfer id) to
|
|
305
|
+
make it stable beyond this process. The default store is memory, so a restart forgets it: a handler that
|
|
306
|
+
moves money must also record `op` in its own database, in the same transaction as the effect —
|
|
307
|
+
`MicroserviceHost.currentCall()` gives the handler the caller and the `op`. An `op` reused for a different
|
|
308
|
+
request is refused (`CONFLICT`).
|
|
309
|
+
- **Errors.** A handler's `IError` goes back without its `stack`; an unexpected exception is logged on the host
|
|
310
|
+
and the caller gets a bare `INTERNAL_ERROR`.
|
|
311
|
+
- **Confidentiality is TLS.** Signatures prove who sent what; they don't hide it.
|
|
312
|
+
|
|
313
|
+
---
|
|
314
|
+
|
|
315
|
+
## Logging and redaction
|
|
316
|
+
|
|
317
|
+
```ts
|
|
318
|
+
import { logInfo, logWarn, logError, logCrit } from "@bmfk/api";
|
|
319
|
+
|
|
320
|
+
logInfo("Order created", { orderId, amount });
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
Every message is **redacted when it is written**. The objects you pass are never modified. What gets masked:
|
|
324
|
+
|
|
325
|
+
- **Card data.** PANs in any text are masked to the last 4 digits, checked with Luhn and known card
|
|
326
|
+
prefixes. The same applies to fields such as `pan`, `cardNumber`, `primaryAccountNumber` (DPAN) and
|
|
327
|
+
`track2`. CVV/CVC, PIN, expiry and cardholder-name fields are replaced with `<REDACTED>`.
|
|
328
|
+
- **Secrets.** Fields such as `password`, `token`, `authorization`, `cookie`, `apiKey` and `clientSecret`,
|
|
329
|
+
secrets in query strings (`?token=…`), and passwords inside connection strings (`mysql://user:***@host`).
|
|
330
|
+
|
|
331
|
+
The incoming and outgoing request logs shown in the monitor go through the same redaction.
|
|
332
|
+
`LogService.sanitize(text)` and `LogService.sanitizeDeep(value)` are available for your own output.
|
|
333
|
+
|
|
334
|
+
> Redaction is a safety net, not a policy. Don't log card data on purpose: masking patterns can't
|
|
335
|
+
> recognize every format.
|
|
336
|
+
|
|
337
|
+
### Request tracing
|
|
338
|
+
|
|
339
|
+
Every request gets a trace id. It is returned in the `X-Request-Id` response header and as `traceId` in the
|
|
340
|
+
response body, and it follows everything the request causes:
|
|
341
|
+
|
|
342
|
+
- `req.traceId` in the handler, and `Trace.current()` anywhere in code the request runs, across `await`s;
|
|
343
|
+
- `traceId` on every log item written while handling it (pass it on in your `output`);
|
|
344
|
+
- the incoming request log and the outgoing HTTP log in the monitor;
|
|
345
|
+
- signed microservice calls: the host takes over the caller's id, so one operation has one id across services.
|
|
346
|
+
|
|
347
|
+
Behind nginx, `proxy_set_header X-Request-Id $request_id;` makes the service use nginx's id, so the nginx access
|
|
348
|
+
log and the service logs share it. The header is accepted only from `trustedProxies`; from anyone else it is
|
|
349
|
+
ignored, so a client can't plant an id that collides with someone else's records.
|
|
350
|
+
|
|
351
|
+
---
|
|
352
|
+
|
|
353
|
+
## Signals and requests between services
|
|
354
|
+
|
|
355
|
+
Services talk to each other through signals and requests instead of importing each other.
|
|
356
|
+
|
|
357
|
+
```ts
|
|
358
|
+
import { Signal, Req } from "@bmfk/api";
|
|
359
|
+
|
|
360
|
+
export const S_ORDER_PAID = new Signal<Order>("S_ORDER_PAID"); // one-to-many notification
|
|
361
|
+
export const REQ_RATE = new Req<string, number>(undefined, "REQ_RATE"); // one worker answers
|
|
362
|
+
|
|
363
|
+
S_ORDER_PAID.subscribe(order => notify(order)); // returns an id for unsubscribe(id)
|
|
364
|
+
REQ_RATE.listener = async currency => rates.get(currency);
|
|
365
|
+
|
|
366
|
+
S_ORDER_PAID.invoke(order);
|
|
367
|
+
const rate = await REQ_RATE.request("EUR");
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
- **Order.** Subscribers run synchronously, in the order they subscribed. An `invoke` from inside a
|
|
371
|
+
subscriber runs after the current one.
|
|
372
|
+
- **Errors.** A subscriber that throws does not stop the others or break the signal; the error goes to
|
|
373
|
+
`Signal.onError` (stderr by default).
|
|
374
|
+
- **Changes while running** apply from the next `invoke`: a new subscriber is not called in the current
|
|
375
|
+
one, a removed one still is.
|
|
376
|
+
- **Requests.** `request()` returns a promise that rejects when the worker throws or no worker is set.
|
|
377
|
+
The library's own requests (`REQ_DB`, `REQ_MICROSERVICE_CALL`, `REQ_HTTP_SERVER`, …) work the same way.
|
|
378
|
+
|
|
379
|
+
---
|
|
380
|
+
|
|
381
|
+
## Monitor console (`sm/*`)
|
|
382
|
+
|
|
383
|
+
A web console for operations: `<baseEndPoint>sm/html`, plus a JSON API used by the page.
|
|
384
|
+
|
|
385
|
+
**What it shows:**
|
|
386
|
+
|
|
387
|
+
- Process: memory, event-loop delay, open file descriptors and sockets with history (to catch leaks),
|
|
388
|
+
and pm2 identity.
|
|
389
|
+
- System: CPU, RAM, disks, network and load.
|
|
390
|
+
- Metrics: request rate, errors and latency, by hour, day or week; 10 weeks of history kept on disk
|
|
391
|
+
(see [Data folder](#data-folder)).
|
|
392
|
+
- Outgoing HTTP: per-host p50/p95/p99 and active connections.
|
|
393
|
+
- Logs: the application log, incoming and outgoing request logs, and tails of pm2 and nginx log files.
|
|
394
|
+
- Threats: clients that look like they are probing (scanners, `/wp-login.php`, `../`, bursts of 404s).
|
|
395
|
+
This is observation only; nothing is ever blocked.
|
|
396
|
+
- Actions: change the log level, or restart the process via pm2 (the password and 2FA code are asked
|
|
397
|
+
again).
|
|
398
|
+
|
|
399
|
+
**Access** is configured in `access.monitor`:
|
|
400
|
+
|
|
401
|
+
```ts
|
|
402
|
+
access: {
|
|
403
|
+
monitor: [
|
|
404
|
+
{ login: "ops", password: "scrypt$16384$8$1$…", role: "admin" },
|
|
405
|
+
{ login: "support", password: "scrypt$16384$8$1$…", role: "it" },
|
|
406
|
+
{ login: "finance", password: "scrypt$16384$8$1$…", role: "analytic" },
|
|
407
|
+
],
|
|
408
|
+
},
|
|
409
|
+
monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
- **Passwords must be stored as hashes.** Generate one with `npx bmfk hash-password`. The command
|
|
413
|
+
asks for the password interactively and prints the config entry. A plain-text password in the config
|
|
414
|
+
is refused.
|
|
415
|
+
- **2FA (TOTP) is mandatory.** At first login the console shows a QR code to scan with any
|
|
416
|
+
authenticator app. Re-enrolling through the API is deliberately impossible: to reset 2FA, remove
|
|
417
|
+
the user's record from the 2FA file on the server.
|
|
418
|
+
- **Roles:**
|
|
419
|
+
|
|
420
|
+
| Role | Can do |
|
|
421
|
+
|---|---|
|
|
422
|
+
| `admin` | everything |
|
|
423
|
+
| `it` | dashboard and logs |
|
|
424
|
+
| `analytic` | dashboard only |
|
|
425
|
+
|
|
426
|
+
- **Sessions** expire after 15 minutes idle and 8 hours at most. 10 failed logins lock the account
|
|
427
|
+
for 30 minutes.
|
|
428
|
+
- **Change access without a restart.** By default (`access: ""`) the service reads
|
|
429
|
+
`/var/bmfk/<project>/access.json`; while the file doesn't exist, the monitor and the documentation are
|
|
430
|
+
closed. `access` can also be another path (`access: "/etc/my-service/access.json"`) or an inline object
|
|
431
|
+
of the same shape. `npx bmfk access-config` creates and edits the file from a menu. Run in the project
|
|
432
|
+
folder, it finds the path the code assigns to `access` (a string literal in `src/` or the compiled
|
|
433
|
+
`bin/`/`dist/`), proposes the data-folder file otherwise, or takes the path as an argument. Passwords are typed hidden and stored as hashes, and the result is
|
|
434
|
+
checked with the service's own validator. The file is watched, and changes apply
|
|
435
|
+
within a second, without a restart or a redeploy:
|
|
436
|
+
|
|
437
|
+
```jsonc
|
|
438
|
+
{ "monitor": [ { "login": "ops", "password": "scrypt$…", "role": "admin" } ],
|
|
439
|
+
"documentation": [ { "login": "partner", "password": "…" } ] }
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
- **Revocation.** Removing a user or changing their password ends their open sessions immediately.
|
|
443
|
+
A role change applies to the next request.
|
|
444
|
+
- **Bad edits are ignored.** If the file is invalid (broken JSON, unknown role, duplicate login), the
|
|
445
|
+
change is ignored and the previous access stays in force. The reason is logged.
|
|
446
|
+
- **Location and permissions.** Keep the file outside the deploy folders and `chmod 600` it. A warning
|
|
447
|
+
is logged if other users can read it.
|
|
448
|
+
- **Restrict by address.** `monitorAllowedIps` in `access` (inline or in `access.json`) limits every
|
|
449
|
+
`sm/*` request to the given IPs and CIDR subnets, the page and sign-in included. A session token
|
|
450
|
+
taken elsewhere is therefore useless outside those addresses too:
|
|
451
|
+
|
|
452
|
+
```jsonc
|
|
453
|
+
{ "monitor": [ … ], "monitorAllowedIps": ["10.8.0.0/24", "203.0.113.7"] }
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
Other addresses get `403`. Changes in `access.json` apply without a restart, and an invalid entry
|
|
457
|
+
rejects the change. Behind nginx, pass `X-Real-IP` (see [`trustedProxies`](#options-reference)),
|
|
458
|
+
otherwise every request appears to come from `127.0.0.1`.
|
|
459
|
+
- **Block addresses.** Admins can block an address or a subnet from the threats page, permanently or
|
|
460
|
+
for a number of hours. See [IP blocking](#ip-blocking).
|
|
461
|
+
- **If you set `monitorAuthDir`, keep it outside the deploy folders.** Otherwise a deploy wipes the
|
|
462
|
+
enrollments and everyone has to enroll again. By default they are in `/var/bmfk/<project>/`.
|
|
463
|
+
|
|
464
|
+
---
|
|
465
|
+
|
|
466
|
+
## IP blocking
|
|
467
|
+
|
|
468
|
+
Blocked addresses get a `403` on every request, whether HTTP, WebSocket, the monitor or the
|
|
469
|
+
documentation:
|
|
470
|
+
|
|
471
|
+
```json
|
|
472
|
+
{ "error": { "code": 403, "message": "Access from your address is blocked", "httpStatus": 403 } }
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
The check runs first, before body parsing, CORS and the interceptor, so a blocked client costs almost
|
|
476
|
+
nothing. The list is `/var/bmfk/<project>/blocked-ips.json` (see [Data folder](#data-folder)), outside
|
|
477
|
+
the code, so deploys and restores never touch it, and shared by both blue-green slots. It is re-read
|
|
478
|
+
on change.
|
|
479
|
+
|
|
480
|
+
The format:
|
|
481
|
+
|
|
482
|
+
```jsonc
|
|
483
|
+
[
|
|
484
|
+
{ "ip": "203.0.113.7", "reason": "credential stuffing", "until": "2026-12-01T00:00:00Z" },
|
|
485
|
+
{ "ip": "198.51.100.0/24", "reason": "scanner" } // no "until" → permanent
|
|
486
|
+
]
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
- **How to edit.** Edit the file by hand, or block and unblock from the monitor (`sm/block`,
|
|
490
|
+
`sm/unblock`; `admin` role). The monitor records who blocked and when. The threats page marks
|
|
491
|
+
addresses that are already blocked.
|
|
492
|
+
- **Expiry.** Entries past `until` stop applying by themselves.
|
|
493
|
+
- **Invalid edits.** An invalid file is ignored, and the previous list stays in force.
|
|
494
|
+
- **Reasons stay private.** `reason` is shown only in the monitor, never to the client.
|
|
495
|
+
- **Safety rules.** Loopback is never blocked, so a proxy without `X-Real-IP` can't take the service
|
|
496
|
+
down. An admin can't block their own address from the monitor.
|
|
497
|
+
- **Options.** `blockedIps: { file, message }` sets another location or the text of the error;
|
|
498
|
+
`blockedIps: false` turns blocking off.
|
|
499
|
+
|
|
500
|
+
Blocking in the service suits targeted cases: a particular attacker or a scanner subnet. To stop a
|
|
501
|
+
flood, block at nginx or with fail2ban, where requests are dropped before they reach Node.
|
|
502
|
+
|
|
503
|
+
---
|
|
504
|
+
|
|
505
|
+
## Authentication
|
|
506
|
+
|
|
507
|
+
The library protects four things, each in its own way:
|
|
508
|
+
|
|
509
|
+
| What | Who uses it | How they sign in |
|
|
510
|
+
|---|---|---|
|
|
511
|
+
| Your API endpoints | your users and clients | your [interceptor](#interceptors-authentication) |
|
|
512
|
+
| Monitor (`sm/*`) | your operations team | password + mandatory TOTP 2FA, then a session token |
|
|
513
|
+
| Documentation (`doc/*`) | developers and partners | login and password (a static token) |
|
|
514
|
+
| Deployer (`pckg/*`) | CI and developers | deployer user + project token |
|
|
515
|
+
| Deploy review (`review/*`) | reviewers | personal emailed link + login, password and TOTP 2FA |
|
|
516
|
+
|
|
517
|
+
The library doesn't manage the users of your application. That's the job of your interceptor and
|
|
518
|
+
database. The rest of this section is about the built-in consoles.
|
|
519
|
+
|
|
520
|
+
### 1. Generate a password hash
|
|
521
|
+
|
|
522
|
+
Monitor and deployer configs store a salted scrypt hash, never the password itself. Run the
|
|
523
|
+
command on any machine with the package installed:
|
|
524
|
+
|
|
525
|
+
```text
|
|
526
|
+
$ npx bmfk hash-password
|
|
527
|
+
|
|
528
|
+
Hash a monitor password (APIService access.monitor)
|
|
529
|
+
Login: ops
|
|
530
|
+
Password: ← typed input is not shown
|
|
531
|
+
Repeat password:
|
|
532
|
+
|
|
533
|
+
✓ Put this in the config instead of the plain password:
|
|
534
|
+
|
|
535
|
+
{ "login": "ops", "password": "scrypt$16384$8$1$Rkps…$zrwU…" }
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
- **Deployer users.** For a user in the deployer's `setup.json`, use `npx bmfk hash-password --deployer`.
|
|
539
|
+
The hash differs from a monitor hash, so they can't be swapped.
|
|
540
|
+
- **Interactive only.** The password is never accepted as an argument, so it doesn't end up in shell
|
|
541
|
+
history or `ps`. Without a terminal (in CI, for example), the command refuses to run.
|
|
542
|
+
- **Password policy.** The minimum length is 12 characters, checked by the command.
|
|
543
|
+
- **Salting.** Every run gives a different hash for the same password. All of them are valid.
|
|
544
|
+
- **Plain text is refused.** A password stored in plain text is rejected at login with the same answer
|
|
545
|
+
as a wrong password. The server log says why, and a startup error names the affected logins.
|
|
546
|
+
|
|
547
|
+
Put the result into `access.monitor` (inline or in an `access.json` file) and add a role:
|
|
548
|
+
|
|
549
|
+
```ts
|
|
550
|
+
access: {
|
|
551
|
+
monitor: [{ login: "ops", password: "scrypt$16384$8$1$…", role: "admin" }],
|
|
552
|
+
},
|
|
553
|
+
projectName: "my-service", // shown in the authenticator app
|
|
554
|
+
monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are stored; outside deploy folders
|
|
555
|
+
```
|
|
556
|
+
|
|
557
|
+
### 2. Sign in to the monitor
|
|
558
|
+
|
|
559
|
+
Open `<baseEndPoint>sm/html` in a browser. The page runs this flow for you. The same flow over the API:
|
|
560
|
+
|
|
561
|
+
**Step 1. Log in.**
|
|
562
|
+
|
|
563
|
+
```http
|
|
564
|
+
POST /api/sm/login
|
|
565
|
+
{ "login": "ops", "password": "…" }
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
**On the first login,** 2FA isn't set up yet, so the response contains an enrollment instead of a
|
|
569
|
+
session:
|
|
570
|
+
|
|
571
|
+
```jsonc
|
|
572
|
+
{ "data": {
|
|
573
|
+
"enrollmentRequired": true,
|
|
574
|
+
"enrollmentToken": "…", // valid for 10 minutes
|
|
575
|
+
"secret": "JBSWY3DPEHPK3PXP", // for manual entry
|
|
576
|
+
"otpauthUri": "otpauth://totp/my-service:ops?secret=…&issuer=my-service",
|
|
577
|
+
"expiresInMs": 600000 } }
|
|
578
|
+
```
|
|
579
|
+
|
|
580
|
+
**Step 2. Enroll the authenticator (first login only).** Scan `otpauthUri` as a QR code with Google
|
|
581
|
+
Authenticator, 1Password, Authy or a similar app, then confirm with the current code:
|
|
582
|
+
|
|
583
|
+
```http
|
|
584
|
+
POST /api/sm/enroll2fa
|
|
585
|
+
{ "enrollmentToken": "…", "totp": "123456" }
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
The secret is saved only after a correct code, and the response is already a session (see step 3).
|
|
589
|
+
|
|
590
|
+
**On later logins,** send the code from the app with the password:
|
|
591
|
+
|
|
592
|
+
```http
|
|
593
|
+
POST /api/sm/login
|
|
594
|
+
{ "login": "ops", "password": "…", "totp": "123456" }
|
|
595
|
+
```
|
|
596
|
+
|
|
597
|
+
```jsonc
|
|
598
|
+
{ "data": { "token": "…", "login": "ops", "role": "admin",
|
|
599
|
+
"capabilities": ["dashboard", "logs", "admin"],
|
|
600
|
+
"idleTimeoutMs": 900000, "maxLifetimeMs": 28800000, "twoFactor": true } }
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
**Step 3. Call the monitor with the session token.**
|
|
604
|
+
|
|
605
|
+
```http
|
|
606
|
+
POST /api/sm/procinfo
|
|
607
|
+
Authorization: Bearer <token>
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
**How sessions behave:**
|
|
611
|
+
|
|
612
|
+
- **Lifetime.** A session ends after 15 minutes without requests, or after 8 hours in any case.
|
|
613
|
+
`POST sm/logout` ends it at once.
|
|
614
|
+
- **Lockout.** 10 failed logins lock the account for 30 minutes.
|
|
615
|
+
- **Revocation.** Removing a user from `access`, or changing their password, ends their sessions
|
|
616
|
+
immediately.
|
|
617
|
+
- **Restart.** `sm/restart` asks for the password and the TOTP code again, even within a valid session.
|
|
618
|
+
- **Errors.** `401` means sign in again; `403` means the role doesn't allow this section.
|
|
619
|
+
|
|
620
|
+
### 3. Reset a user's 2FA (lost phone)
|
|
621
|
+
|
|
622
|
+
Re-enrolling through the API is impossible on purpose. Otherwise anyone who learned the password
|
|
623
|
+
could attach their own authenticator. To reset:
|
|
624
|
+
|
|
625
|
+
1. Open `/var/bmfk/<project>/monitor-2fa.json` on the server (with `monitorAuthDir` set:
|
|
626
|
+
`<monitorAuthDir>/monitor-2fa.<projectName>.json`).
|
|
627
|
+
2. Delete the user's entry under `projects.<projectName>.users.<login>`.
|
|
628
|
+
|
|
629
|
+
No restart is needed. The file is watched like `access.json`: within a second the user's sessions
|
|
630
|
+
end, and their next login shows a new QR code. Deleting the whole file resets 2FA for every user of
|
|
631
|
+
the project in the same way. A broken file (invalid JSON) is ignored, and the current enrollments
|
|
632
|
+
stay in force.
|
|
633
|
+
|
|
634
|
+
> A deleted enrollment means the next person who knows the password enrolls their own
|
|
635
|
+
> authenticator. Reset 2FA only after confirming who is asking, and preferably change the password
|
|
636
|
+
> at the same time.
|
|
637
|
+
|
|
638
|
+
Alternatively, set a known base32 secret directly in the config with `totpSecret`. It takes
|
|
639
|
+
precedence over the stored enrollment.
|
|
640
|
+
|
|
641
|
+
### 4. Documentation
|
|
642
|
+
|
|
643
|
+
Users in `access.documentation` sign in on `<baseEndPoint>doc/html` the way monitor users do: the
|
|
644
|
+
password is stored as a hash (`npx bmfk access-config` or `hash-password`), a second factor is set up at
|
|
645
|
+
the first sign-in, a session ends after 15 minutes idle and 8 hours at most, and 10 failed sign-ins lock
|
|
646
|
+
the account for 30 minutes. `doc/json` answers only with a session token (`Authorization: Bearer
|
|
647
|
+
<token>` from `doc/login`). Use `endpoints` to limit what a user sees.
|
|
648
|
+
|
|
649
|
+
Documentation sessions and monitor sessions are separate: one never opens the other. 2FA enrollments of
|
|
650
|
+
documentation users are kept in the same file as the monitor's, under `doc:<login>` — to reset a
|
|
651
|
+
partner's 2FA, remove `doc:<login>` from it (see above).
|
|
652
|
+
|
|
653
|
+
### 5. Deployer
|
|
654
|
+
|
|
655
|
+
- **Server.** The deployer server keeps `setup.json` users as hashes (`hash-password --deployer`).
|
|
656
|
+
- **Addresses.** `allowed_ips` in `setup.json` limits which addresses can use the deployer at all.
|
|
657
|
+
- **Client.** The deploying machine keeps the login and either a private key (recommended) or the
|
|
658
|
+
password in `deploy.json`. Either way, the file can deploy on its own: never share it or commit it.
|
|
659
|
+
- **What goes over the wire.** With a key, `Authorization: Signature kid=…, ts=…, nonce=…, sig=…`. The
|
|
660
|
+
signature is good for one request and five minutes, and covers the project, the fields and the
|
|
661
|
+
archive. With a password, `Authorization: Bearer sha256(login:password)` and `X-Deployer-Login`.
|
|
662
|
+
- **Project token.** Deploying, switching and restoring also require the project's own `token`. The
|
|
663
|
+
project config on the server holds only its hash. Run `npx bmfk project-token`: it prints a new
|
|
664
|
+
random token for `deploy.json` and its hash for the project config. To keep an existing token, run
|
|
665
|
+
`npx bmfk project-token --hash`. A token stored in plain text is refused like a wrong token. The
|
|
666
|
+
server log says why, and a startup error names the affected projects.
|
|
667
|
+
|
|
668
|
+
---
|
|
669
|
+
|
|
670
|
+
## WebSocket server
|
|
671
|
+
|
|
672
|
+
The WebSocket server shares the HTTP port. It listens on `baseEndPoint + endpoint`, for example
|
|
673
|
+
`wss://api.example.com/api/v1/ws`:
|
|
674
|
+
|
|
675
|
+
```ts
|
|
676
|
+
getDefaultOptions({
|
|
677
|
+
websocketServer: {
|
|
678
|
+
endpoint: "ws", // default "ws"
|
|
679
|
+
authTimeoutMs: 10_000, // the client must authorize within this time
|
|
680
|
+
onAuthorize: async (connection, message) => {
|
|
681
|
+
// `message` is the client's FIRST message, parsed JSON
|
|
682
|
+
const user = await sessions.find(message?.token);
|
|
683
|
+
return user ?? false; // false / null → close 4401; an object → connection.auth
|
|
684
|
+
},
|
|
685
|
+
maxPayload: 256 * 1024, // bytes per message → close 1009
|
|
686
|
+
maxMessagesPerSecond: 20, // per connection → close 1008
|
|
687
|
+
maxConnections: 1000, // total → HTTP 503
|
|
688
|
+
maxConnectionsPerIp: 50, // per client IP → HTTP 429
|
|
689
|
+
},
|
|
690
|
+
});
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
```ts
|
|
694
|
+
import { S_WS_ON_CONNECTED, S_WS_ON_MESSAGE, S_WS_ON_CLOSE, REQ_WS_SERVER } from "@bmfk/api";
|
|
695
|
+
|
|
696
|
+
S_WS_ON_CONNECTED.subscribe(conn => conn.send({ hello: conn.auth.name }));
|
|
697
|
+
S_WS_ON_MESSAGE.subscribe(({ connection, message }) => { /* … */ });
|
|
698
|
+
S_WS_ON_CLOSE.subscribe(conn => { /* … */ });
|
|
699
|
+
|
|
700
|
+
const ws = await REQ_WS_SERVER.request();
|
|
701
|
+
ws?.broadcast({ event: "price" }, c => c.auth.plan === "pro");
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
The client sends credentials as its **first message**, not in the URL, so tokens don't end up in proxy
|
|
705
|
+
access logs:
|
|
706
|
+
|
|
707
|
+
```js
|
|
708
|
+
const socket = new WebSocket("wss://api.example.com/api/v1/ws");
|
|
709
|
+
socket.onopen = () => socket.send(JSON.stringify({ token }));
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
How connections are handled:
|
|
713
|
+
|
|
714
|
+
- **Authorization.** Messages sent while authorization is being checked are dropped. A connection that
|
|
715
|
+
doesn't authorize within `authTimeoutMs` is closed with code 4408. This also applies when
|
|
716
|
+
`onAuthorize` itself is too slow.
|
|
717
|
+
- **Origin check.** The browser `Origin` is checked as for HTTP (same-origin or `corsHostWhiteList`). This
|
|
718
|
+
prevents cross-site WebSocket hijacking.
|
|
719
|
+
- **`onAuthorize` is required.** A server without it does not start, unless `public: true` says on purpose
|
|
720
|
+
that every connection is accepted (a warning is logged at startup).
|
|
721
|
+
|
|
722
|
+
---
|
|
723
|
+
|
|
724
|
+
## Deployer and CLI
|
|
725
|
+
|
|
726
|
+
The deployer is an `APIService` running on the target server with the `deployer` option. It receives a
|
|
727
|
+
build, unpacks it, installs dependencies, writes the configuration and starts the process in pm2.
|
|
728
|
+
|
|
729
|
+
The CLI is `bmfk` (`npx bmfk <command>`).
|
|
730
|
+
|
|
731
|
+
**On the server**, the quickest start is the wizard — in an empty folder, as the user that will own the
|
|
732
|
+
deployed projects (not root):
|
|
733
|
+
|
|
734
|
+
```bash
|
|
735
|
+
npm init -y && npm i @bmfk/api
|
|
736
|
+
npx bmfk deployer-init
|
|
737
|
+
```
|
|
738
|
+
|
|
739
|
+
It checks Node, pm2 and `/var/bmfk`, asks for the port, the folders, the first deploy users' public keys
|
|
740
|
+
(`npx bmfk deploy-key` prints them on the machine you deploy from), the addresses allowed to deploy and an
|
|
741
|
+
optional Telegram chat. It writes `bin/Main.js`, `ecosystem.config.cjs` for pm2 and `setup.json`
|
|
742
|
+
(mode `600`), and prints the nginx block (with `client_max_body_size` matching the archive limit) and the
|
|
743
|
+
next commands. It asks before replacing anything. What it writes is an ordinary service:
|
|
744
|
+
|
|
745
|
+
```ts
|
|
746
|
+
getDefaultOptions({
|
|
747
|
+
port: 9915,
|
|
748
|
+
fileLimit: 100 * 1024 * 1024, // the largest deploy archive
|
|
749
|
+
deployer: {
|
|
750
|
+
projects_path: "/var/bmfk/bmfk-deployer/projects", // one JSON config per project
|
|
751
|
+
setup_path: "/var/bmfk/bmfk-deployer/setup", // the folder that holds setup.json
|
|
752
|
+
},
|
|
753
|
+
});
|
|
754
|
+
```
|
|
755
|
+
|
|
756
|
+
`setup.json` lists who may deploy. The recommended way is a **signing key** per user. Run
|
|
757
|
+
`npx bmfk deploy-key` in the project: it writes an Ed25519 private key into `deploy.json` and prints the
|
|
758
|
+
public key to add to the user in `setup.json` (`setup-config` → "set a deployer user's public key").
|
|
759
|
+
Every request is then signed. A captured request can't be replayed or changed, the signature covers the
|
|
760
|
+
archive's sha256, and the deployer stores no secret at all. Only signed requests are accepted by default;
|
|
761
|
+
`"require_signature": false` in `setup.json` also lets users with a password (stored as a hash) in, for
|
|
762
|
+
example while they get their keys. The project token is still required on top, so a deploy always proves
|
|
763
|
+
which project it is meant for. The easiest way to manage users, reviewers and
|
|
764
|
+
allowed addresses is `npx bmfk setup-config <folder>`, a menu that hashes passwords for you; for a
|
|
765
|
+
single hash use `npx bmfk hash-password --deployer`. When sign-in fails, the deployer logs why
|
|
766
|
+
(unknown login, wrong password, unsigned request, no `X-Deployer-Login`), while the client only gets
|
|
767
|
+
`Unauthorized`.
|
|
768
|
+
|
|
769
|
+
```jsonc
|
|
770
|
+
{
|
|
771
|
+
"users": [
|
|
772
|
+
{ "login": "ci", "publicKey": "MCowBQYDK2VwAyEA…" }, // signs its requests
|
|
773
|
+
{ "login": "igor", "password": "scrypt$16384$8$1$…" } // password: only with require_signature false
|
|
774
|
+
],
|
|
775
|
+
"require_signature": false, // omit it (default): signed requests only
|
|
776
|
+
"allowed_ips": ["203.0.113.7", "10.8.0.0/24"] // who may deploy; IPs and CIDR subnets, IPv4/IPv6
|
|
777
|
+
}
|
|
778
|
+
```
|
|
779
|
+
|
|
780
|
+
`allowed_ips` is checked before the credentials, for deploy, activate, status, backups and restore.
|
|
781
|
+
|
|
782
|
+
**Telegram.** With `telegram` in `setup.json` the deployer posts one message per event to a chat: deploy
|
|
783
|
+
done, a failed step (backup, unpack, migrate, pm2, nginx, liveness), switch and rollback, restore, a deploy
|
|
784
|
+
waiting for review and the review's outcome, readiness lost and back. The message names the project, the
|
|
785
|
+
status, the user and the server — never a review link (those are personal) and never config values.
|
|
786
|
+
|
|
787
|
+
```jsonc
|
|
788
|
+
"telegram": { "bot": "<token from @BotFather>", "chat": "-100…", "topic": 12 } // topic: optional, a forum topic
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
The bot must be a member of the chat. The token is a secret: keep `setup.json` at `600`, and if the token
|
|
792
|
+
leaks, revoke it in @BotFather. It is sent only to `api.telegram.org` and never written to logs or the
|
|
793
|
+
monitor's journal. Changes apply without a restart; a failed send is logged and never stops a deploy.
|
|
794
|
+
|
|
795
|
+
Other addresses get `403`. Without the list the deployer accepts any address, and a warning is logged.
|
|
796
|
+
`setup.json` is reloaded on change, so the list can be edited without a restart. An invalid entry
|
|
797
|
+
rejects the whole change, and the previous setup stays in force.
|
|
798
|
+
|
|
799
|
+
> **Behind nginx,** pass the real client address: `proxy_set_header X-Real-IP $remote_addr;`. Without
|
|
800
|
+
> it, every request appears to come from `127.0.0.1`. Never add `127.0.0.1` to `allowed_ips` on a
|
|
801
|
+
> deployer behind a proxy on the same host: that would let every request through.
|
|
802
|
+
|
|
803
|
+
A project config (`projects_path/<name>.json`). The easiest way to make one is `npx bmfk project-config`:
|
|
804
|
+
it asks for everything below, generates the token, takes config values as hidden input, checks the
|
|
805
|
+
result against the deployer's schema, and saves the project config and a matching `deploy.json` with
|
|
806
|
+
permissions `600`.
|
|
807
|
+
|
|
808
|
+
```jsonc
|
|
809
|
+
{
|
|
810
|
+
"name": "my-service",
|
|
811
|
+
"destination": "/var/node/my-service",
|
|
812
|
+
"token": "scrypt$16384$8$1$…", // hash of the project token: npx bmfk project-token
|
|
813
|
+
"unpack": true, "install": true, "pm2": true,
|
|
814
|
+
"backup": true, // copy the current version aside before each deploy (see Backups)
|
|
815
|
+
"migrate": false, // run `npm run migrate` before the process starts
|
|
816
|
+
"omitDev": false, // true: install without devDependencies (npm ci --omit=dev)
|
|
817
|
+
"config": { "DB_HOST": "…" } // substituted into the shipped config placeholders _{{DB_HOST}}_
|
|
818
|
+
}
|
|
819
|
+
```
|
|
820
|
+
|
|
821
|
+
The `name` becomes the deployed `package.json` name, the data folder `/var/bmfk/<name>` and part of the
|
|
822
|
+
state, backup and secrets file names. So it is restricted: lowercase letters, digits, `.`, `_` and `-`,
|
|
823
|
+
starting with a letter or digit, up to 100 characters — for example `api.gateway.example.com`. A
|
|
824
|
+
project config with any other name is ignored, with an error in the deployer's log;
|
|
825
|
+
`bmfk migrate-configs` lists such configs too.
|
|
826
|
+
|
|
827
|
+
#### Keeping secrets out of the deployed code
|
|
828
|
+
|
|
829
|
+
By default, `config` values are written into the shipped files in place of `_{{KEY}}_`. That puts
|
|
830
|
+
passwords into the code, into both blue-green slots and into every backup. Add `secrets` to the project
|
|
831
|
+
config to avoid this:
|
|
832
|
+
|
|
833
|
+
```jsonc
|
|
834
|
+
"secrets": {} // "secrets_dir" from setup.json, else /var/bmfk/<project>/secrets[-<slot>].json
|
|
835
|
+
"secrets": { "dir": "/etc/node-secrets" } // → /etc/node-secrets/<project>[-<slot>].json
|
|
836
|
+
"secrets": { "file": "/etc/node-secrets/my.json" }
|
|
837
|
+
```
|
|
838
|
+
|
|
839
|
+
The deployer writes the values (merged for the slot) into that file, with permissions `600` and
|
|
840
|
+
outside the deploy folder, and rewrites each quoted placeholder in `.js` files as a read of the file:
|
|
841
|
+
|
|
842
|
+
```js
|
|
843
|
+
DB_PASSWORD: "_{{db_password}}_" // in the archive
|
|
844
|
+
DB_PASSWORD: (function(k){ … reads /etc/node-secrets/my-blue.json … })("db_password") // on the server
|
|
845
|
+
```
|
|
846
|
+
|
|
847
|
+
- **No code changes.** The application gets exactly the strings it got before, so `parseInt("_{{port}}_")`
|
|
848
|
+
still works. The file is read once per process.
|
|
849
|
+
- **Restarts.** pm2 restarts, `migrate` and cluster workers keep working, because the file stays in place.
|
|
850
|
+
- **Backups and restore.** Backups and archives contain only the file path. A restored version reads
|
|
851
|
+
the current values instead of the ones from its deploy.
|
|
852
|
+
- **Missing key.** If a key is missing from the file, the start fails with a clear error instead of
|
|
853
|
+
running with a placeholder.
|
|
854
|
+
- **Same user.** The secrets file belongs to the deployer's user and is readable only by it. pm2,
|
|
855
|
+
started by the deployer, runs the app as that same user. A project whose pm2 attributes switch the
|
|
856
|
+
user (`--uid`, `--gid`) is refused before anything changes, since the app couldn't read the file.
|
|
857
|
+
The file is also read back before the app is started.
|
|
858
|
+
- **Start with a blue-green project.** If the new version fails to start, the inactive slot fails and
|
|
859
|
+
traffic stays on the old one until you `activate`.
|
|
860
|
+
- **Fallback to plain substitution.** Values are still written into the file for `.json`, `.env`,
|
|
861
|
+
unquoted placeholders, templates with `${…}`, ES-module projects, and any file that wouldn't compile
|
|
862
|
+
after the rewrite. Each deploy logs which files still hold values.
|
|
863
|
+
|
|
864
|
+
**In your project**, create `deploy.json` or a `deploy/` folder with one or more configs. Keep it out of
|
|
865
|
+
git: it holds credentials.
|
|
866
|
+
|
|
867
|
+
```jsonc
|
|
868
|
+
{
|
|
869
|
+
"name": "my-service",
|
|
870
|
+
"host": "https://deployer.example.com/api/pckg/add",
|
|
871
|
+
"token": "<project token, printed by npx bmfk project-token>",
|
|
872
|
+
"username": "ci",
|
|
873
|
+
"privateKey": "<from npx bmfk deploy-key>", // or "password": "<your password>"
|
|
874
|
+
"includes": ["certs", { "src": "assets/logo.png", "dest": "bin/logo.png" }],
|
|
875
|
+
"excludes": ["*.map"],
|
|
876
|
+
"bundle": true, // optional, see below
|
|
877
|
+
"versionBump": false // optional: keep package.json "version" (default: patch + 1 on every deploy)
|
|
878
|
+
}
|
|
879
|
+
```
|
|
880
|
+
|
|
881
|
+
**`"bundle": true`** ships the app's own code as one file instead of the tsc tree in `./bin`. It needs the
|
|
882
|
+
bundler in the project: `npm i -D esbuild @babel/parser` (they are optional, so servers don't install them). esbuild
|
|
883
|
+
bundles `src/` into the file package.json `"main"` points to (the one pm2 starts, e.g. `bin/Main.js`).
|
|
884
|
+
Every package stays a plain `require()`, and the server still runs `npm ci` as usual. Everything else in
|
|
885
|
+
`./bin` (html, json, workers) ships as it is, so the slot keeps the same layout and `__dirname` in the
|
|
886
|
+
entry file is still `bin/`. `./bin` itself is not changed.
|
|
887
|
+
|
|
888
|
+
- The entry is derived from `"main"`: `bin/Main.js` → `src/Main.ts`. Override with
|
|
889
|
+
`"bundle": { "entry": "src/Main.ts" }`.
|
|
890
|
+
- A `bin/Main.js.map` ships alongside (line mappings only, no source code). The deployer then starts the
|
|
891
|
+
process with `--enable-source-maps` automatically, so stack traces point at the original `src/` lines
|
|
892
|
+
even when the code is one minified file. (If the project ships its own `ecosystem.config.js`, the
|
|
893
|
+
deployer can't edit it and instead logs a reminder to add `node_args: "--enable-source-maps"` yourself.)
|
|
894
|
+
Turn the map off with `"sourcemap": false`; an `excludes` pattern like `*.map` drops it too, and then
|
|
895
|
+
the flag isn't added.
|
|
896
|
+
- `"bundle": { "minify": true }` strips comments, renames local variables and collapses whitespace. It
|
|
897
|
+
costs nothing at runtime and makes the shipped file hard to read, so a casual `cat` over `./bin` no
|
|
898
|
+
longer reveals the source. It is **not** a secret-hiding measure: string literals (so any value baked
|
|
899
|
+
into the code) stay in clear text, and anyone running as the process user can still read them from the
|
|
900
|
+
runtime. The real fix for credentials in code is a [secrets file](#keeping-secrets-out-of-the-deployed-code);
|
|
901
|
+
protect the files themselves with `"chmod": 700` and a dedicated OS user.
|
|
902
|
+
- The deploy warns, but doesn't stop, about code that behaves differently once it's in one file:
|
|
903
|
+
`__dirname` / `__filename` outside the entry (it becomes `bin/`), a value exported by the entry (such
|
|
904
|
+
as `export const __root = __dirname`) read while modules load rather than inside a function (it's not
|
|
905
|
+
set yet), and `.js` files left in `./bin` that are not part of the bundle.
|
|
906
|
+
|
|
907
|
+
```json
|
|
908
|
+
"scripts": {
|
|
909
|
+
"deploy": "bmfk deploy",
|
|
910
|
+
"activate": "bmfk activate",
|
|
911
|
+
"status": "bmfk status",
|
|
912
|
+
"backups": "bmfk backups",
|
|
913
|
+
"restore": "bmfk restore"
|
|
914
|
+
}
|
|
915
|
+
```
|
|
916
|
+
|
|
917
|
+
| Command | What it does |
|
|
918
|
+
|---|---|
|
|
919
|
+
| `bmfk wizards` | list every interactive wizard below with what it does, and run one |
|
|
920
|
+
| `bmfk deployer-init [folder]` | set up a deployer on this server: service, pm2 file, `setup.json`, nginx block |
|
|
921
|
+
| `bmfk deploy [config]` | build and upload the project |
|
|
922
|
+
| `bmfk activate [config] [blue\|green]` | switch traffic to a slot (blue-green) |
|
|
923
|
+
| `bmfk status [config]` | active and last deployed slot, recent history |
|
|
924
|
+
| `bmfk backups [config]` | list backups |
|
|
925
|
+
| `bmfk restore [config] [backup] [--yes]` | restore a backup |
|
|
926
|
+
| `bmfk hash-password [--deployer]` | hash a password for the monitor or `setup.json` |
|
|
927
|
+
| `bmfk project-token [--hash]` | generate a project token and its hash, or hash an existing token |
|
|
928
|
+
| `bmfk project-config` | build a project config for the deployer step by step (plus a `deploy.json` skeleton) |
|
|
929
|
+
| `bmfk access-config [file]` | create or edit `access.json`: monitor and documentation users, roles, passwords, allowed addresses |
|
|
930
|
+
| `bmfk migrate-configs [folder] [--yes]` | hash the secrets of old `setup.json`, project configs and `access.json` files in place |
|
|
931
|
+
| `bmfk setup-config [file\|folder]` | edit the deployer's `setup.json`: add, rename or remove users, change passwords, reviewers, allowed IPs |
|
|
932
|
+
| `bmfk deploy-key [deploy.json]` | generate a signing key: private key into `deploy.json`, public key for `setup.json` |
|
|
933
|
+
|
|
934
|
+
To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json`.
|
|
935
|
+
|
|
936
|
+
**Safety of the deploy pipeline:**
|
|
937
|
+
|
|
938
|
+
- Archives are checked before unpacking: absolute paths, `..`, and symlinks that point outside the
|
|
939
|
+
destination are rejected.
|
|
940
|
+
- Unsafe destinations are refused: relative paths, the filesystem root, top-level system folders
|
|
941
|
+
(`/var`, `/etc`…), the deployer's own folders, and a folder whose wipe would delete another project.
|
|
942
|
+
- Dependencies are installed with `npm ci --ignore-scripts`. `migrate` is the only script the deployer
|
|
943
|
+
runs. With `"omitDev": true` in the project config, devDependencies (TypeScript, test tools, the
|
|
944
|
+
bundler) are not installed on the server at all. Check first that `npm start` and `npm run migrate`
|
|
945
|
+
need nothing from devDependencies — `ts-node` in a migrate script, for example.
|
|
946
|
+
- Every deploy, switch and restore needs a deployer user and the project token. Both are stored on
|
|
947
|
+
the server only as hashes.
|
|
948
|
+
- `allowed_ips` limits which addresses can reach the deployer at all.
|
|
949
|
+
- With [deploy review](#deploy-review), uploads wait for approval by reviewers who sign in with a
|
|
950
|
+
password and 2FA.
|
|
951
|
+
|
|
952
|
+
---
|
|
953
|
+
|
|
954
|
+
## Blue-green deployments
|
|
955
|
+
|
|
956
|
+
Blue-green gives you releases without downtime and rollbacks in seconds.
|
|
957
|
+
|
|
958
|
+
### The idea
|
|
959
|
+
|
|
960
|
+
A project has **two slots**, `blue` and `green`. Each slot is its own folder and its own pm2 process on its
|
|
961
|
+
own port. nginx sends traffic to **one** slot at a time.
|
|
962
|
+
|
|
963
|
+
```
|
|
964
|
+
┌──────────── nginx ────────────┐
|
|
965
|
+
clients ───▶ │ upstream → active slot port │
|
|
966
|
+
└───────┬───────────────┬───────┘
|
|
967
|
+
▼ ┆ (no traffic)
|
|
968
|
+
my-service-blue my-service-green
|
|
969
|
+
:8055 (live) :8056 (standby)
|
|
970
|
+
```
|
|
971
|
+
|
|
972
|
+
1. **`deploy`** puts the new version into the **inactive** slot and starts it. Production is not touched,
|
|
973
|
+
and you can test the new slot directly on its port.
|
|
974
|
+
2. **`activate`** points nginx to that slot and reloads nginx. The switch is instant.
|
|
975
|
+
3. **Rollback** is `activate` back to the other slot. The previous version is still running, so a
|
|
976
|
+
rollback takes seconds.
|
|
977
|
+
|
|
978
|
+
The very first deploy creates `blue` and makes it active right away.
|
|
979
|
+
|
|
980
|
+
### Configuring a project
|
|
981
|
+
|
|
982
|
+
Add `bluegreen` and `nginx` blocks to the project config on the deployer:
|
|
983
|
+
|
|
984
|
+
```jsonc
|
|
985
|
+
{
|
|
986
|
+
"name": "my-service",
|
|
987
|
+
"destination": "/var/node/my-service", // slots go to …/blue and …/green
|
|
988
|
+
"token": "scrypt$…", "unpack": true, "install": true, "pm2": true, "backup": true,
|
|
989
|
+
|
|
990
|
+
"config": { "DB_HOST": "…" }, // shared by both slots
|
|
991
|
+
|
|
992
|
+
"bluegreen": {
|
|
993
|
+
"blue_config": { "port": "8055" }, // per-slot values; the ports must differ
|
|
994
|
+
"green_config": { "port": "8056" },
|
|
995
|
+
"on_switch": ["/usr/sbin/nginx", "-s", "reload"] // runs after each switch (absolute path)
|
|
996
|
+
},
|
|
997
|
+
|
|
998
|
+
"nginx": {
|
|
999
|
+
"config_dir": "/etc/nginx/node-projects", // nginx must include <config_dir>/*.conf
|
|
1000
|
+
"domain": "api.example.com"
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
```
|
|
1004
|
+
|
|
1005
|
+
The deployer manages two nginx files per project:
|
|
1006
|
+
|
|
1007
|
+
- **`<name>.upstream.conf`** holds only the active port. The deployer rewrites it on every switch.
|
|
1008
|
+
- **`<name>.server.conf`** is the server block. The deployer creates it once, and after that it belongs
|
|
1009
|
+
to you: add SSL with `certbot --nginx -d <domain>`, extra locations and so on. The deployer never
|
|
1010
|
+
overwrites it. The generated block already passes `X-Real-IP` and the WebSocket upgrade headers.
|
|
1011
|
+
|
|
1012
|
+
### Workflow
|
|
1013
|
+
|
|
1014
|
+
```bash
|
|
1015
|
+
npm run deploy # new version → inactive slot (e.g. green), production unchanged
|
|
1016
|
+
npm run status # "green is deployed but NOT switched"
|
|
1017
|
+
npm run activate # traffic → green
|
|
1018
|
+
npx bmfk activate blue # rollback → blue
|
|
1019
|
+
```
|
|
1020
|
+
|
|
1021
|
+
### Is my process live? (in the application)
|
|
1022
|
+
|
|
1023
|
+
Both slots run at the same time. Work that must happen once, such as cron jobs, queue consumers and
|
|
1024
|
+
mailings, should run **only in the live slot**:
|
|
1025
|
+
|
|
1026
|
+
```ts
|
|
1027
|
+
APIService.onLiveChange(live => {
|
|
1028
|
+
if (live) startCrons();
|
|
1029
|
+
else stopCrons(); // this slot was switched to standby
|
|
1030
|
+
});
|
|
1031
|
+
|
|
1032
|
+
if (APIService.isLive) { … } // synchronous: true / false / null (not known yet)
|
|
1033
|
+
```
|
|
1034
|
+
|
|
1035
|
+
| Situation | `live` |
|
|
1036
|
+
|---|---|
|
|
1037
|
+
| Project not on blue-green | `true`, always |
|
|
1038
|
+
| Blue-green, my slot is active | `true` |
|
|
1039
|
+
| Blue-green, my slot is standby | `false` |
|
|
1040
|
+
| Not known yet | `null`; the callback isn't called until the answer is known |
|
|
1041
|
+
|
|
1042
|
+
The same code works before and after a project moves to blue-green. Without blue-green, the callback is
|
|
1043
|
+
called once with `true`.
|
|
1044
|
+
|
|
1045
|
+
**How it works.** On deploy, each slot gets a `.bluegreen.json` file (mode `600`) with the project name,
|
|
1046
|
+
the slot and a **read-only status token**. The app asks the deployer over loopback every
|
|
1047
|
+
`blueGreenWatchMs` (default 5 s) which slot is active, so a switch is seen within seconds without a
|
|
1048
|
+
restart.
|
|
1049
|
+
|
|
1050
|
+
**If the deployer is unreachable,** the last known value is kept (`stale: true`), and the app is never
|
|
1051
|
+
switched to standby because of an error. The status token only allows reading the active slot. Deploy
|
|
1052
|
+
credentials never reach the application.
|
|
1053
|
+
|
|
1054
|
+
### Two things to keep in mind
|
|
1055
|
+
|
|
1056
|
+
- **The database is shared by both slots.** The new version starts before the switch, and after a
|
|
1057
|
+
rollback the old version works with the database again. Schema migrations must be
|
|
1058
|
+
**backward-compatible**: add first, remove in a later release. Neither `activate` nor `restore` rolls
|
|
1059
|
+
back the schema.
|
|
1060
|
+
- **Moving an existing project to blue-green.** Use ports different from the current one. After the
|
|
1061
|
+
first blue-green deploy, stop the old process (`pm2 delete <name>`, then `pm2 save`). The old process
|
|
1062
|
+
has no `.bluegreen.json`, so it would consider itself live, and singleton work would run twice.
|
|
1063
|
+
|
|
1064
|
+
---
|
|
1065
|
+
|
|
1066
|
+
## Backups and restore
|
|
1067
|
+
|
|
1068
|
+
With `"backup": true`, the deployer copies the destination aside before every deploy, for example to
|
|
1069
|
+
`/var/node/my-service/2026-10-14_18-45-09-my-service-blue`. It works for blue-green and regular projects.
|
|
1070
|
+
|
|
1071
|
+
- **Complete copies.** A backup includes `node_modules`, permissions and symlinks, so a restore needs no
|
|
1072
|
+
network and no `npm ci`.
|
|
1073
|
+
- **Retention.** The last 10 backups per project are kept.
|
|
1074
|
+
- **Fail-closed.** If the backup fails (disk full, no permissions), the deploy stops without changing
|
|
1075
|
+
anything.
|
|
1076
|
+
|
|
1077
|
+
```bash
|
|
1078
|
+
npm run backups # list: version, slot, who, when, size
|
|
1079
|
+
npm run restore # pick one interactively, confirm
|
|
1080
|
+
npx bmfk restore 2026-10-13_10-00-00-my-service-blue --yes # non-interactive (CI)
|
|
1081
|
+
```
|
|
1082
|
+
|
|
1083
|
+
How a restore works:
|
|
1084
|
+
|
|
1085
|
+
- It first backs up the current state, so a bad restore can be undone.
|
|
1086
|
+
- It swaps the folders atomically and restarts the pm2 process.
|
|
1087
|
+
- Restoring the active slot (or a regular project) goes live immediately, and the CLI warns about it.
|
|
1088
|
+
Restoring a standby slot changes nothing until you `activate` it.
|
|
1089
|
+
|
|
1090
|
+
Configuration values are baked in at deploy time. A restored version comes back with the secrets it was
|
|
1091
|
+
deployed with, unless the project uses a [secrets file](#keeping-secrets-out-of-the-deployed-code).
|
|
1092
|
+
|
|
1093
|
+
---
|
|
1094
|
+
|
|
1095
|
+
## Deploy review
|
|
1096
|
+
|
|
1097
|
+
A project can require approval before anything reaches the server. The upload is held, each reviewer
|
|
1098
|
+
gets a personal link by email, and the deploy runs only after approval. That way stolen deploy
|
|
1099
|
+
credentials alone can't change production.
|
|
1100
|
+
|
|
1101
|
+
### Setup
|
|
1102
|
+
|
|
1103
|
+
Reviewers are defined in the deployer's `setup.json`. Their passwords are hashes made with
|
|
1104
|
+
`npx bmfk hash-password`, and they set up 2FA at the first sign-in. `review_url` is the address of
|
|
1105
|
+
the review page, as reviewers reach it:
|
|
1106
|
+
|
|
1107
|
+
```jsonc
|
|
1108
|
+
{
|
|
1109
|
+
"reviewers": [
|
|
1110
|
+
{ "login": "lead", "password": "scrypt$16384$8$1$…", "email": "lead@example.com" },
|
|
1111
|
+
{ "login": "cto", "password": "scrypt$16384$8$1$…", "email": "cto@example.com" }
|
|
1112
|
+
],
|
|
1113
|
+
"review_url": "https://deployer.example.com/api/review/html",
|
|
1114
|
+
"notifier": { "URL": "…", "KEY": "…" }, // sends the emails
|
|
1115
|
+
"allowed_ips": ["10.8.0.0/24"] // the review page is behind it too, e.g. the VPN range
|
|
1116
|
+
}
|
|
1117
|
+
```
|
|
1118
|
+
|
|
1119
|
+
A project opts in from its config:
|
|
1120
|
+
|
|
1121
|
+
```jsonc
|
|
1122
|
+
"review": { "reviewers": ["lead", "cto"], "mode": "all", "ttlHours": 24 }
|
|
1123
|
+
```
|
|
1124
|
+
|
|
1125
|
+
- **`mode`.** With `"any"`, one accept is enough; with `"all"`, every reviewer must accept. Either
|
|
1126
|
+
way, a single decline rejects the upload.
|
|
1127
|
+
- **`ttlHours`.** How long the links stay valid: 1 to 168 hours, 24 by default.
|
|
1128
|
+
|
|
1129
|
+
If a project's review can't work (an unknown reviewer, no `review_url`, no notifier), the deployer says
|
|
1130
|
+
so at startup and refuses that project's uploads until it is fixed.
|
|
1131
|
+
|
|
1132
|
+
### How it works
|
|
1133
|
+
|
|
1134
|
+
1. **`bmfk deploy`** uploads as usual. The archive goes through all the usual checks and is then
|
|
1135
|
+
held. The CLI prints `WAITING FOR REVIEW`, and production is untouched.
|
|
1136
|
+
2. **Each reviewer gets an email** with a personal link. The link alone is not enough: it opens a
|
|
1137
|
+
sign-in with login, password and a 2FA code.
|
|
1138
|
+
3. **The page shows the changes** compared with the last deployed version: version before and
|
|
1139
|
+
after, dependency changes in `package.json`, and added, removed and changed files with a
|
|
1140
|
+
line-by-line diff.
|
|
1141
|
+
4. **Accept** runs the normal deploy (backup, migrations, pm2, nginx) from the stored archive, after
|
|
1142
|
+
checking that its SHA-256 still matches what the reviewers saw. For blue-green, the new version
|
|
1143
|
+
lands in the inactive slot, and `bmfk activate` still switches traffic. **Decline** deletes the
|
|
1144
|
+
archive.
|
|
1145
|
+
5. **A new upload** replaces the pending one. Every old link and every open review session stop
|
|
1146
|
+
working, and reviewers get new links.
|
|
1147
|
+
|
|
1148
|
+
Undecided uploads expire after `ttlHours`, and their archive is removed.
|
|
1149
|
+
|
|
1150
|
+
### What the diff shows and hides
|
|
1151
|
+
|
|
1152
|
+
The comparison uses the **raw archives**: the stored archive of the last successful deploy and the
|
|
1153
|
+
new one. Deployed folders are never read, because config values (passwords) are substituted there.
|
|
1154
|
+
Files such as `.env*`, `*.pem` and `*.key` are listed, but their content is never shown. Binary and
|
|
1155
|
+
very large files are listed with their sizes. The first reviewed deploy of a project has nothing to
|
|
1156
|
+
compare with, so every file is shown as added.
|
|
1157
|
+
|
|
1158
|
+
### Security notes
|
|
1159
|
+
|
|
1160
|
+
- **Personal links.** A link works only for the reviewer it was sent to. The token is in the URL
|
|
1161
|
+
fragment (`#…`), which never reaches the server logs, and the page removes it from the address bar.
|
|
1162
|
+
- **Sessions.** A session lasts 15 minutes without activity and 1 hour at most. It is bound to one
|
|
1163
|
+
upload: a new upload ends it.
|
|
1164
|
+
- **Lockout.** 10 failed sign-ins lock the reviewer for 30 minutes.
|
|
1165
|
+
- **Mail scanners.** Opening the link changes nothing. Accept and decline need a signed-in click, so
|
|
1166
|
+
a mail scanner that "visits" links can't approve anything.
|
|
1167
|
+
- **Separation of duties.** Give the review to someone other than the person who deploys. That's
|
|
1168
|
+
what change control (for example PCI DSS 6.5) expects.
|
|
1169
|
+
|
|
1170
|
+
### Audit trail and maintenance
|
|
1171
|
+
|
|
1172
|
+
All review data lives in `<projects_path>/.review/`, with permissions `600`:
|
|
1173
|
+
|
|
1174
|
+
| File | Content |
|
|
1175
|
+
|---|---|
|
|
1176
|
+
| `<project>.history.jsonl` | every upload, decision and result, with IP addresses and the archive SHA-256 |
|
|
1177
|
+
| `<project>.pending.*` | the archive waiting for review and its state |
|
|
1178
|
+
| `<project>.last.tgz` | the raw archive of the last successful deploy, the "before" of the next diff |
|
|
1179
|
+
| `reviewers-2fa.json` | reviewers' 2FA enrollments |
|
|
1180
|
+
|
|
1181
|
+
To reset a reviewer's 2FA, delete their entry from `reviewers-2fa.json`. It is read at every sign-in,
|
|
1182
|
+
so no restart is needed.
|
|
1183
|
+
|
|
1184
|
+
---
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
### Data folder
|
|
1188
|
+
|
|
1189
|
+
What has to survive restarts and deploys lives in one folder per project, outside the deployed code:
|
|
1190
|
+
|
|
1191
|
+
```
|
|
1192
|
+
/var/bmfk/<project>/
|
|
1193
|
+
metrics/ metrics history: the current week per minute, 10 weeks in all
|
|
1194
|
+
threats.json what the threat monitor has seen (addresses, user agents, URLs — never bodies)
|
|
1195
|
+
blocked-ips.json
|
|
1196
|
+
access.json monitor and documentation users (option `access: ""`, the default)
|
|
1197
|
+
monitor-2fa.json monitor 2FA enrollments
|
|
1198
|
+
uploads/ uploaded files while their request runs
|
|
1199
|
+
secrets[-<slot>].json config values the deployer keeps out of the code (`"secrets": {}`)
|
|
1200
|
+
```
|
|
1201
|
+
|
|
1202
|
+
- **The project name is the deployer's.** On every deploy the deployer writes its project name into
|
|
1203
|
+
the deployed `package.json` (and `package-lock.json`) `"name"`, and the app takes it from there. One
|
|
1204
|
+
source tree deployed as several projects gets a folder per project; the two blue-green slots of one
|
|
1205
|
+
project share theirs. Your repository's `package.json` is not changed. Off the deployer, the
|
|
1206
|
+
`package.json` name is used as is. (`projectName` stays what the authenticator app shows.)
|
|
1207
|
+
- **One writer.** Only the live process writes metrics and threats: a blue-green standby and pm2 cluster workers
|
|
1208
|
+
other than instance 0 count in memory only. A slot that becomes live loads what the other slot wrote,
|
|
1209
|
+
so charts continue across deploys.
|
|
1210
|
+
- **Rights.** The app creates its folder (`0700`). If it can't create `/var/bmfk` — say, the app runs as
|
|
1211
|
+
an unprivileged user — it says so at startup and falls back to a folder beside the code. Create the
|
|
1212
|
+
root once: `sudo mkdir /var/bmfk && sudo chown <app user> /var/bmfk`.
|
|
1213
|
+
- `BMFK_DATA_DIR` moves the root. Each file can still be set on its own: `metricsDir` (`false` keeps
|
|
1214
|
+
metrics in memory), `blockedIps.file`, `monitorAuthDir` / `monitorAuthFile`.
|
|
1215
|
+
|
|
1216
|
+
## Options reference
|
|
1217
|
+
|
|
1218
|
+
| Option | Default | Description |
|
|
1219
|
+
|---|---|---|
|
|
1220
|
+
| `port` | `8080` | HTTP port |
|
|
1221
|
+
| `baseEndPoint` | `"/api/"` | prefix for all endpoints |
|
|
1222
|
+
| `projectName` | `"Application project"` | shown in the monitor and as the 2FA issuer, so set it |
|
|
1223
|
+
| `endpoints` | `[]` | your `BaseEndpoint` instances |
|
|
1224
|
+
| `corsHostWhiteList` | `[]` | browser origins allowed besides the API's own; `"*"` allows any, without credentials |
|
|
1225
|
+
| `isProductionEnvironment` | `true` unless `NODE_ENV=development` | production mode |
|
|
1226
|
+
| `interceptor` | — | authentication for your endpoints |
|
|
1227
|
+
| `preproducer` / `postproducer` | — | hooks before the handler / before the response is sent |
|
|
1228
|
+
| `access` | `""` → `/var/bmfk/<project>/access.json` | a path to a JSON file reloaded on change, or `{ monitor, documentation, monitorAllowedIps }` |
|
|
1229
|
+
| `monitorAuthDir` / `monitorAuthFile` | `/var/bmfk/<project>/monitor-2fa.json` | where 2FA enrollments are stored |
|
|
1230
|
+
| `metricsDir` | `/var/bmfk/<project>/metrics` | metrics history, 10 weeks; `false` → in memory only |
|
|
1231
|
+
| `logFiles` | pm2 auto-detected | log files the monitor may tail (for example nginx) |
|
|
1232
|
+
| `threatMonitoring` | `true` | probe and scan detection; observation only |
|
|
1233
|
+
| `trustedProxies` | loopback | proxies whose `X-Real-IP` / `X-Forwarded-For` are trusted |
|
|
1234
|
+
| `blockedIps` | `/var/bmfk/<project>/blocked-ips.json` | `{ file, message }` for the blocked-address list; `false` turns it off |
|
|
1235
|
+
| `websocketServer` | — | enables the WebSocket server, see above |
|
|
1236
|
+
| `deployer` | — | turns this service into a deployer |
|
|
1237
|
+
| `blueGreenWatchMs` | `5000` | how often to check the active slot; `0` disables |
|
|
1238
|
+
| `jsonLimit` | `"10mb"` | maximum JSON / form body |
|
|
1239
|
+
| `fileTempDir` / `fileLimit` | `<data folder>/uploads` (mode 700) / 10 MB | uploads |
|
|
1240
|
+
| `keepAliveTimeout` / `headersTimeout` | 25 s / 26 s | HTTP server timeouts |
|
|
1241
|
+
| `appVersion` | — | returned in every response as `version` |
|
|
1242
|
+
|
|
1243
|
+
---
|
|
1244
|
+
|
|
1245
|
+
## Security
|
|
1246
|
+
|
|
1247
|
+
### What you get by default
|
|
1248
|
+
|
|
1249
|
+
- **Credentials.** Monitor and deployer passwords are stored as salted scrypt hashes, and plain text in
|
|
1250
|
+
configs is refused. Comparisons run in constant time. Verifying a deployer request costs at most one
|
|
1251
|
+
scrypt computation, so the deployer can't be used to burn CPU.
|
|
1252
|
+
- **Monitor access.** Mandatory TOTP 2FA, short-lived sessions, account lockout, roles, and the password
|
|
1253
|
+
asked again before a restart.
|
|
1254
|
+
- **Data in logs.** Card data and secrets are redacted when logs are written and when they are viewed
|
|
1255
|
+
through the monitor. Logged objects are never modified.
|
|
1256
|
+
- **Client IP.** Proxy headers are trusted only from `trustedProxies`, so clients can't spoof their
|
|
1257
|
+
address.
|
|
1258
|
+
- **Deploys.** Archives are checked for path traversal and escaping symlinks, package install scripts
|
|
1259
|
+
are disabled, and every deploy needs a user and the project token. Requests are signed with Ed25519
|
|
1260
|
+
(the deployer keeps only public keys), so they can't be replayed or altered.
|
|
1261
|
+
- **Blue-green.** Applications get a read-only status token; deploy credentials never reach them.
|
|
1262
|
+
- **WebSocket.** Origin checks, authorization within a time limit, and limits on message size, message
|
|
1263
|
+
rate and connections. A malformed frame can't crash the process.
|
|
1264
|
+
- **Built-in endpoints.** The monitor and deployer endpoints are hidden from the API documentation.
|
|
1265
|
+
|
|
1266
|
+
### What you must configure before going to production
|
|
1267
|
+
|
|
1268
|
+
1. List your other front-end origins in `corsHostWhiteList` (the API's own origin is always allowed;
|
|
1269
|
+
behind nginx pass the host: `proxy_set_header Host $host;`).
|
|
1270
|
+
2. Store all monitor and deployer passwords as hashes (`npx bmfk hash-password`).
|
|
1271
|
+
3. Point `monitorAuthDir` to a persistent directory outside the deploy folders, readable only by the
|
|
1272
|
+
service user.
|
|
1273
|
+
4. Run behind nginx (or another proxy) on loopback with TLS, and keep `trustedProxies` at its default
|
|
1274
|
+
unless the proxy runs on another host.
|
|
1275
|
+
5. If you use WebSockets, set `onAuthorize` (required unless `public: true`).
|
|
1276
|
+
6. Keep `deploy.json` / `deploy/` out of version control, and restrict permissions on `setup.json` and
|
|
1277
|
+
the project configs on the server.
|
|
1278
|
+
7. Set a meaningful `projectName`, which is shown in authenticator apps.
|
|
1279
|
+
|
|
1280
|
+
### What this library does not do
|
|
1281
|
+
|
|
1282
|
+
- **It is not a WAF.** Threat monitoring records suspicious clients but never blocks them. Use nginx
|
|
1283
|
+
rate limiting, fail2ban or a WAF for blocking.
|
|
1284
|
+
- **It doesn't make your system PCI DSS compliant on its own.** It helps with some requirements
|
|
1285
|
+
(redaction, MFA, access roles, audit logs), but compliance is assessed for your whole environment.
|
|
1286
|
+
- **Redaction is pattern-based.** Treat it as a safety net, not a substitute for not logging sensitive
|
|
1287
|
+
data.
|
|
1288
|
+
|
|
1289
|
+
---
|
|
1290
|
+
---
|
|
1291
|
+
|
|
1292
|
+
## License
|
|
1293
|
+
|
|
1294
|
+
MIT
|