badmfck-api-server 5.0.17 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,12 +23,13 @@ Node.js 21+ is required.
23
23
  6. [Outgoing HTTP client](#outgoing-http-client)
24
24
  7. [Logging and redaction](#logging-and-redaction)
25
25
  8. [Monitor console (`sm/*`)](#monitor-console-sm)
26
- 9. [WebSocket server](#websocket-server)
27
- 10. [Deployer and CLI](#deployer-and-cli)
28
- 11. [Blue-green deployments](#blue-green-deployments)
29
- 12. [Backups and restore](#backups-and-restore)
30
- 13. [Options reference](#options-reference)
31
- 14. [Security](#security)
26
+ 9. [Authentication](#authentication)
27
+ 10. [WebSocket server](#websocket-server)
28
+ 11. [Deployer and CLI](#deployer-and-cli)
29
+ 12. [Blue-green deployments](#blue-green-deployments)
30
+ 13. [Backups and restore](#backups-and-restore)
31
+ 14. [Options reference](#options-reference)
32
+ 15. [Security](#security)
32
33
 
33
34
  ---
34
35
 
@@ -310,6 +311,162 @@ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
310
311
 
311
312
  ---
312
313
 
314
+ ## Authentication
315
+
316
+ The library protects four things, each in its own way:
317
+
318
+ | What | Who uses it | How they sign in |
319
+ |---|---|---|
320
+ | Your API endpoints | your users and clients | your [interceptor](#interceptors-authentication) |
321
+ | Monitor (`sm/*`) | your operations team | password + mandatory TOTP 2FA, then a session token |
322
+ | Documentation (`doc/*`) | developers and partners | login and password (a static token) |
323
+ | Deployer (`pckg/*`) | CI and developers | deployer user + project token |
324
+
325
+ The library doesn't manage the users of your application. That's the job of your interceptor and
326
+ database. The rest of this section is about the built-in consoles.
327
+
328
+ ### 1. Generate a password hash
329
+
330
+ Monitor and deployer configs store a salted scrypt hash, never the password itself. Run the
331
+ command on any machine with the package installed:
332
+
333
+ ```text
334
+ $ npx badmfck hash-password
335
+
336
+ Hash a monitor password (APIService access.monitor)
337
+ Login: ops
338
+ Password: ← typed input is not shown
339
+ Repeat password:
340
+
341
+ ✓ Put this in the config instead of the plain password:
342
+
343
+ { "login": "ops", "password": "scrypt$16384$8$1$Rkps…$zrwU…" }
344
+ ```
345
+
346
+ - **Deployer users.** For a user in the deployer's `setup.json`, use `npx badmfck hash-password --deployer`.
347
+ The hash differs from a monitor hash, so they can't be swapped.
348
+ - **Interactive only.** The password is never accepted as an argument, so it doesn't end up in shell
349
+ history or `ps`. Without a terminal (in CI, for example), the command refuses to run.
350
+ - **Password policy.** The minimum length is 12 characters, checked by the command.
351
+ - **Salting.** Every run gives a different hash for the same password. All of them are valid.
352
+ - **Plain text is refused.** A password stored in plain text is rejected at login with "password is
353
+ built incorrectly", and a startup error names the affected logins.
354
+
355
+ Put the result into `access.monitor` (inline or in an `access.json` file) and add a role:
356
+
357
+ ```ts
358
+ access: {
359
+ monitor: [{ login: "ops", password: "scrypt$16384$8$1$…", role: "admin" }],
360
+ },
361
+ projectName: "my-service", // shown in the authenticator app
362
+ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are stored; outside deploy folders
363
+ ```
364
+
365
+ ### 2. Sign in to the monitor
366
+
367
+ Open `<baseEndPoint>sm/html` in a browser. The page runs this flow for you. The same flow over the API:
368
+
369
+ **Step 1. Log in.**
370
+
371
+ ```http
372
+ POST /api/sm/login
373
+ { "login": "ops", "password": "…" }
374
+ ```
375
+
376
+ **On the first login,** 2FA isn't set up yet, so the response contains an enrollment instead of a
377
+ session:
378
+
379
+ ```jsonc
380
+ { "data": {
381
+ "enrollmentRequired": true,
382
+ "enrollmentToken": "…", // valid for 10 minutes
383
+ "secret": "JBSWY3DPEHPK3PXP", // for manual entry
384
+ "otpauthUri": "otpauth://totp/my-service:ops?secret=…&issuer=my-service",
385
+ "expiresInMs": 600000 } }
386
+ ```
387
+
388
+ **Step 2. Enroll the authenticator (first login only).** Scan `otpauthUri` as a QR code with Google
389
+ Authenticator, 1Password, Authy or a similar app, then confirm with the current code:
390
+
391
+ ```http
392
+ POST /api/sm/enroll2fa
393
+ { "enrollmentToken": "…", "totp": "123456" }
394
+ ```
395
+
396
+ The secret is saved only after a correct code, and the response is already a session (see step 3).
397
+
398
+ **On later logins,** send the code from the app with the password:
399
+
400
+ ```http
401
+ POST /api/sm/login
402
+ { "login": "ops", "password": "…", "totp": "123456" }
403
+ ```
404
+
405
+ ```jsonc
406
+ { "data": { "token": "…", "login": "ops", "role": "admin",
407
+ "capabilities": ["dashboard", "logs", "admin"],
408
+ "idleTimeoutMs": 900000, "maxLifetimeMs": 28800000, "twoFactor": true } }
409
+ ```
410
+
411
+ **Step 3. Call the monitor with the session token.**
412
+
413
+ ```http
414
+ POST /api/sm/procinfo
415
+ Authorization: Bearer <token>
416
+ ```
417
+
418
+ **How sessions behave:**
419
+
420
+ - **Lifetime.** A session ends after 15 minutes without requests, or after 8 hours in any case.
421
+ `POST sm/logout` ends it at once.
422
+ - **Lockout.** 10 failed logins lock the account for 30 minutes.
423
+ - **Revocation.** Removing a user from `access`, or changing their password, ends their sessions
424
+ immediately.
425
+ - **Restart.** `sm/restart` asks for the password and the TOTP code again, even within a valid session.
426
+ - **Errors.** `401` means sign in again; `403` means the role doesn't allow this section.
427
+
428
+ ### 3. Reset a user's 2FA (lost phone)
429
+
430
+ Re-enrolling through the API is impossible on purpose. Otherwise anyone who learned the password
431
+ could attach their own authenticator. To reset:
432
+
433
+ 1. Open `<monitorAuthDir>/monitor-2fa.<projectName>.json` on the server.
434
+ 2. Delete the user's entry under `projects.<projectName>.users.<login>`.
435
+
436
+ No restart is needed. The file is watched like `access.json`: within a second the user's sessions
437
+ end, and their next login shows a new QR code. Deleting the whole file resets 2FA for every user of
438
+ the project in the same way. A broken file (invalid JSON) is ignored, and the current enrollments
439
+ stay in force.
440
+
441
+ > A deleted enrollment means the next person who knows the password enrolls their own
442
+ > authenticator. Reset 2FA only after confirming who is asking, and preferably change the password
443
+ > at the same time.
444
+
445
+ Alternatively, set a known base32 secret directly in the config with `totpSecret`. It takes
446
+ precedence over the stored enrollment.
447
+
448
+ ### 4. Documentation
449
+
450
+ Users in `access.documentation` sign in on `<baseEndPoint>doc/html` with a login and password. The page
451
+ then sends `Authorization: Bearer sha256(login:password)`, and API clients can do the same to fetch
452
+ `doc/json`. Use `endpoints` to limit what a user sees.
453
+
454
+ This is a **weaker level** than the monitor: there is no 2FA, the token never expires, and the
455
+ password is stored in the config in plain text. It is meant for API descriptions, not for data. Give
456
+ documentation users their own passwords, never ones they use elsewhere.
457
+
458
+ ### 5. Deployer
459
+
460
+ - **Server.** The deployer server keeps `setup.json` users as hashes (`hash-password --deployer`).
461
+ - **Client.** The deploying machine keeps the login and the plain password in `deploy.json`, which
462
+ never leaves that machine and must stay out of git.
463
+ - **What goes over the wire.** The CLI sends `Authorization: Bearer sha256(login:password)` and
464
+ `X-Deployer-Login`.
465
+ - **Project token.** Deploying, switching and restoring also require the project's own `token`.
466
+ - **CLI version.** Users stored as a hash need a CLI from version 6 or later.
467
+
468
+ ---
469
+
313
470
  ## WebSocket server
314
471
 
315
472
  The WebSocket server shares the HTTP port. It listens on `baseEndPoint + endpoint`, for example
@@ -187,7 +187,7 @@ class DBService extends BaseService_1.BaseService {
187
187
  if (value === null || value === undefined)
188
188
  return 'NULL';
189
189
  const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
190
- return "'" + stringValue.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, (char) => {
190
+ return "'" + stringValue.replace(/[\0\x08\x09\x1a\n\r"'\\]/g, (char) => {
191
191
  switch (char) {
192
192
  case "\0": return "\\0";
193
193
  case "\x08": return "\\b";
@@ -198,7 +198,6 @@ class DBService extends BaseService_1.BaseService {
198
198
  case "\"":
199
199
  case "'":
200
200
  case "\\":
201
- case "%":
202
201
  return "\\" + char;
203
202
  default: return char;
204
203
  }
@@ -53,8 +53,12 @@ export declare class MysqlAdapter implements IDBAdapter {
53
53
  getConnection(transactionId?: number): Promise<mysql.PoolConnection | IDBError>;
54
54
  withTimeout<T>(promise: Promise<T>, ms: number, query: string): Promise<T>;
55
55
  query(request: IDBQuery, conn?: mysql.PoolConnection): Promise<IDBResult>;
56
+ killQuery(conn: mysql.PoolConnection): void;
57
+ destroyConnection(conn: mysql.PoolConnection): void;
56
58
  finalizeConnection(conn: mysql.PoolConnection): void;
57
59
  prepareQuery(request: IDBQuery): string;
60
+ static substitute(text: string, values: Map<string, string>): string;
61
+ static quoteIdentifier(name: string): string;
58
62
  static safeReplace(query: string, key: string, value: string): string;
59
63
  static prepareQueryFieldValue(field: IDBQueryField): string | number | boolean | null | undefined;
60
64
  prepareCountQuery(query: string): string;
@@ -34,6 +34,8 @@ class MysqlAdapter {
34
34
  statFrames = new Map();
35
35
  constructor(options) {
36
36
  this.options = options;
37
+ if ([options.host, options.user, options.database, options.password].some(v => typeof v === "string" && v.startsWith("_")))
38
+ (0, LogService_1.logWarn)("MysqlAdapter", "DB credentials prefixed with \"_\" are decrypted with a key built into this public package — anyone can decrypt them; this hides values, it doesn't protect them. Keep credentials in a file readable only by the service user instead.");
37
39
  if (this.options.host.startsWith("_"))
38
40
  this.options.host = decrypt(this.options.host.substring(1)) ?? this.options.host;
39
41
  if (this.options.user.startsWith("_"))
@@ -136,27 +138,29 @@ class MysqlAdapter {
136
138
  return;
137
139
  }
138
140
  this.isCleanupRunning = true;
139
- const now = Date.now();
140
- const count = this.transactions.length;
141
- const removedIDs = [];
142
- for (let i of this.transactions) {
143
- if (now - i.timestamp > this.maxTransactionWaitTime) {
144
- (0, LogService_1.logError)("Release transaction connection due to timeout");
145
- await this.rollbackTransaction(i, true);
146
- removedIDs.push(i.id);
141
+ try {
142
+ const now = Date.now();
143
+ const count = this.transactions.length;
144
+ const removedIDs = [];
145
+ for (let i of this.transactions) {
146
+ if (now - i.timestamp > this.maxTransactionWaitTime) {
147
+ (0, LogService_1.logError)("Release transaction connection due to timeout");
148
+ await this.rollbackTransaction(i, true);
149
+ removedIDs.push(i.id);
150
+ }
147
151
  }
148
- }
149
- this.transactions = this.transactions.filter(i => !removedIDs.includes(i.id));
150
- if (this.options.debug && count - this.transactions.length > 0)
151
- (0, LogService_1.logDB)("Removed: ", count - this.transactions.length);
152
- if (Date.now() - this.lastSuccessQueryTime > this.pingInterval) {
153
- if (!this.pool)
154
- return;
155
- for (let i = 0; i < this.options.connectionLimit; i++) {
156
- this.query({ query: "SELECT 1 @NOLIMIT" });
152
+ this.transactions = this.transactions.filter(i => !removedIDs.includes(i.id));
153
+ if (this.options.debug && count - this.transactions.length > 0)
154
+ (0, LogService_1.logDB)("Removed: ", count - this.transactions.length);
155
+ if (this.pool && Date.now() - this.lastSuccessQueryTime > this.pingInterval) {
156
+ for (let i = 0; i < this.options.connectionLimit; i++) {
157
+ this.query({ query: "SELECT 1 @NOLIMIT" });
158
+ }
157
159
  }
158
160
  }
159
- this.isCleanupRunning = false;
161
+ finally {
162
+ this.isCleanupRunning = false;
163
+ }
160
164
  }, 1000 * 30);
161
165
  setInterval(() => {
162
166
  if (!this.failReportFileStream)
@@ -550,8 +554,15 @@ class MysqlAdapter {
550
554
  MonitorService_1.S_STAT_REGISTRATE_SQL_REQUEST.invoke({ success: false, query });
551
555
  this.collectStat(query, Date.now() - executionStartTime, true);
552
556
  }
553
- if (!request.transactionID && doCloseConnection)
554
- this.finalizeConnection(conn);
557
+ const timedOut = e?.code === "TIME_OUT";
558
+ if (timedOut)
559
+ this.killQuery(conn);
560
+ if (!request.transactionID && doCloseConnection) {
561
+ if (timedOut)
562
+ this.destroyConnection(conn);
563
+ else
564
+ this.finalizeConnection(conn);
565
+ }
555
566
  else if (request.transactionID && request.throwable) {
556
567
  await this.rollbackTransaction(this.transactions.find(i => i.id === request.transactionID));
557
568
  }
@@ -585,6 +596,21 @@ class MysqlAdapter {
585
596
  };
586
597
  }
587
598
  }
599
+ killQuery(conn) {
600
+ const threadId = conn?.threadId;
601
+ if (!this.pool || !threadId)
602
+ return;
603
+ this.pool.query("KILL QUERY " + Number(threadId)).catch(e => (0, LogService_1.logError)("MysqlAdapter", `Can't kill timed-out query on thread ${threadId}: ${e?.message ?? e}`));
604
+ }
605
+ destroyConnection(conn) {
606
+ try {
607
+ conn.removeAllListeners();
608
+ conn.destroy();
609
+ }
610
+ catch (e) {
611
+ (0, LogService_1.logCrit)("MysqlAdapter", `Can't destroy connection: ${e}`);
612
+ }
613
+ }
588
614
  finalizeConnection(conn) {
589
615
  try {
590
616
  conn.removeAllListeners();
@@ -595,8 +621,10 @@ class MysqlAdapter {
595
621
  }
596
622
  }
597
623
  prepareQuery(request) {
598
- let query = request.query;
599
- let fields = request.fields;
624
+ const template = request.query;
625
+ const fields = request.fields;
626
+ const values = new Map();
627
+ const parsedFields = [];
600
628
  if (fields) {
601
629
  for (let i in fields) {
602
630
  const name = i;
@@ -618,72 +646,52 @@ class MysqlAdapter {
618
646
  if (!queryField.name)
619
647
  queryField.name = name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "");
620
648
  fields[i] = queryField;
621
- const parsed = MysqlAdapter.prepareQueryFieldValue(fields[i]);
622
- query = MysqlAdapter.safeReplace(query, "@" + name, parsed + "");
649
+ const parsed = MysqlAdapter.prepareQueryFieldValue(queryField);
650
+ values.set(name, parsed + "");
651
+ if (!queryField.name.startsWith("$__"))
652
+ parsedFields.push(queryField);
623
653
  }
624
654
  }
655
+ const column = (f) => MysqlAdapter.quoteIdentifier(f.name ?? "");
656
+ const macro = (name, build) => {
657
+ if (!values.has(name) && template.indexOf("@" + name) !== -1)
658
+ values.set(name, build());
659
+ };
660
+ macro("fields", () => parsedFields.filter(f => !f.ignoreInInsert).map(column).join(","));
661
+ if (template.indexOf("@fields") !== -1)
662
+ macro("values", () => parsedFields.filter(f => !f.ignoreInInsert).map(f => f.__parsedValue).join(","));
663
+ macro("insert", () => {
664
+ const list = parsedFields.filter(f => !f.ignoreInInsert);
665
+ return `(${list.map(column).join(",")}) VALUES (${list.map(f => f.__parsedValue).join(",")})`;
666
+ });
667
+ macro("onupdate", () => parsedFields.filter(f => !f.ignoreInUpdate).map(f => column(f) + ' = ' + f.__parsedValue).join(" , "));
668
+ macro("onduplicate", () => parsedFields.filter(f => f.useInReplace).map(f => column(f) + ' = ' + f.__parsedValue).join(" , "));
669
+ let noLimit = false;
670
+ if (!values.has("NOLIMIT") && template.indexOf("@NOLIMIT") !== -1) {
671
+ values.set("NOLIMIT", "");
672
+ noLimit = true;
673
+ }
674
+ let query = MysqlAdapter.substitute(template, values);
625
675
  const tmp = query.toLowerCase();
626
- if (tmp.indexOf("select") === 0 && tmp.indexOf("limit") === -1)
676
+ if (tmp.indexOf("select") === 0 && !noLimit && tmp.indexOf("limit") === -1)
627
677
  query += " LIMIT 100";
628
- query = query.replaceAll("@NOLIMIT", "");
629
- if (query.indexOf("@fields") !== -1) {
630
- let insertFieldNames = [];
631
- let insertFieldValues = [];
632
- for (let i in fields) {
633
- let f = fields[i];
634
- if (f.name?.startsWith("$__"))
635
- continue;
636
- if (f.ignoreInInsert)
637
- continue;
638
- insertFieldNames.push('`' + f.name + '`');
639
- insertFieldValues.push(f.__parsedValue);
640
- }
641
- query = MysqlAdapter.safeReplace(query, "@fields", insertFieldNames.join(","));
642
- query = MysqlAdapter.safeReplace(query, "@values", insertFieldValues.join(","));
643
- }
644
- if (query.indexOf("@insert") !== -1) {
645
- let oninsertNames = [];
646
- let oninsertValues = [];
647
- for (let i in fields) {
648
- let f = fields[i];
649
- if (f.name?.startsWith("$__"))
650
- continue;
651
- if (f.ignoreInInsert)
652
- continue;
653
- oninsertNames.push(f.name);
654
- oninsertValues.push(f.__parsedValue);
655
- }
656
- query = MysqlAdapter.safeReplace(query, "@insert", `(${oninsertNames.join(",")}) VALUES (${oninsertValues.join(",")})`);
657
- }
658
- if (query.indexOf("@onupdate") !== -1) {
659
- let onUpdate = [];
660
- for (let i in fields) {
661
- let f = fields[i];
662
- if (f.name?.startsWith("$__"))
663
- continue;
664
- if (f.ignoreInUpdate)
665
- continue;
666
- onUpdate.push('`' + f.name + '` = ' + f.__parsedValue);
667
- }
668
- query = MysqlAdapter.safeReplace(query, "@onupdate", onUpdate.join(" , "));
669
- }
670
- if (query.indexOf('@onduplicate') !== -1) {
671
- let onDuplicate = [];
672
- for (let i in fields) {
673
- let f = fields[i];
674
- if (f.name?.startsWith("$__"))
675
- continue;
676
- if (!f.useInReplace)
677
- continue;
678
- onDuplicate.push('`' + f.name + '` = ' + f.__parsedValue);
679
- }
680
- query = MysqlAdapter.safeReplace(query, "@onduplicate", onDuplicate.join(" , "));
681
- }
682
678
  return query;
683
679
  }
680
+ static substitute(text, values) {
681
+ if (values.size === 0)
682
+ return text;
683
+ const names = [...values.keys()]
684
+ .sort((a, b) => b.length - a.length)
685
+ .map(n => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
686
+ const regex = new RegExp("@(" + names.join("|") + ")(?=\\b|\\s|,|\\)|$)", "g");
687
+ return text.replace(regex, (match, name) => values.get(name) ?? match);
688
+ }
689
+ static quoteIdentifier(name) {
690
+ return "`" + String(name).replaceAll("`", "") + "`";
691
+ }
684
692
  static safeReplace(query, key, value) {
685
- const regex = new RegExp(key + "(?=\\b|\\s|,|\\)|$)", "g");
686
- return query.replace(regex, value);
693
+ const name = key.startsWith("@") ? key.substring(1) : key;
694
+ return MysqlAdapter.substitute(query, new Map([[name, value]]));
687
695
  }
688
696
  static prepareQueryFieldValue(field) {
689
697
  let value = field.value;
@@ -713,12 +721,13 @@ class MysqlAdapter {
713
721
  value = value ? 1 : 0;
714
722
  }
715
723
  if (field.fields && typeof field.fields === "object" && value && typeof value === "string" && value.indexOf("@") !== -1) {
724
+ const nested = new Map();
716
725
  for (let key in field.fields) {
717
726
  if (!field.fields[key])
718
727
  continue;
719
- const val = promise_1.default.escape(field.fields[key]);
720
- value = this.safeReplace(value, "@" + key, val);
728
+ nested.set(key, promise_1.default.escape(field.fields[key]));
721
729
  }
730
+ value = MysqlAdapter.substitute(value, nested);
722
731
  }
723
732
  field.__parsedValue = value;
724
733
  if (field.__parsedValue === null || field.__parsedValue === undefined) {
@@ -817,7 +826,7 @@ class MysqlAdapter {
817
826
  fatal: true,
818
827
  sql: "no query",
819
828
  name: "QUERY_ERR",
820
- message: "Error: " + (err) ? err : "",
829
+ message: "Error: " + (err instanceof Error ? err.message : String(err ?? "")),
821
830
  isDuplicateError: false
822
831
  };
823
832
  }
@@ -1,6 +1,5 @@
1
- import { Pool } from 'pg';
1
+ import { Pool, PoolClient } from 'pg';
2
2
  import { DBAdapterOptions, IDBQuery, IDBResult, IDBBulkQuery, IPoolStatus, IDBStatFrame } from '../DBService';
3
- import { ITransaction } from '../MysqlService';
4
3
  import { IDBAdapter } from './IDBAdapter';
5
4
  export declare class PostgresAdapter implements IDBAdapter {
6
5
  options: DBAdapterOptions;
@@ -11,7 +10,15 @@ export declare class PostgresAdapter implements IDBAdapter {
11
10
  timeoutID: any;
12
11
  queries: never[];
13
12
  static nextTransactionID: number;
14
- transactions: ITransaction[];
13
+ transactions: {
14
+ id: number;
15
+ timestamp: number;
16
+ conn: PoolClient;
17
+ queries: {
18
+ sql: string;
19
+ status: string;
20
+ }[];
21
+ }[];
15
22
  maxTransactionWaitTime: number;
16
23
  lastSuccessQueryTime: number;
17
24
  pingInterval: number;
@@ -24,8 +24,18 @@ export declare class MonitorAuth {
24
24
  authDir?: string | null;
25
25
  projectName?: string;
26
26
  }): void;
27
+ private static storeHash;
28
+ private static refusedHash;
29
+ private static storeWatcher;
30
+ private static storePoll;
31
+ private static storeDebounce;
32
+ private static missingSince;
33
+ private static sectionOf;
27
34
  private static loadStore;
28
- private static saveStore;
35
+ private static reloadStore;
36
+ private static watchStore;
37
+ private static stopWatchingStore;
38
+ private static saveEnrollment;
29
39
  static secretFor(user: IMonitorUser): string | null;
30
40
  static isEnrolled(user: IMonitorUser): boolean;
31
41
  static MIN_PASSWORD_LENGTH: number;