badmfck-api-server 5.0.15 → 5.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +667 -0
  2. package/dist/apiServer/APIService.d.ts +16 -4
  3. package/dist/apiServer/APIService.js +92 -3
  4. package/dist/apiServer/WebSocketServer.d.ts +39 -0
  5. package/dist/apiServer/WebSocketServer.js +173 -0
  6. package/dist/apiServer/deployment/Activate.js +1 -1
  7. package/dist/apiServer/deployment/Backups.js +1 -1
  8. package/dist/apiServer/deployment/Deploy.js +1 -1
  9. package/dist/apiServer/deployment/Deployer.js +5 -5
  10. package/dist/apiServer/deployment/DeployerService.d.ts +12 -0
  11. package/dist/apiServer/deployment/DeployerService.js +51 -21
  12. package/dist/apiServer/deployment/HashPassword.d.ts +1 -0
  13. package/dist/apiServer/deployment/HashPassword.js +91 -0
  14. package/dist/apiServer/deployment/NginxHelper.d.ts +1 -1
  15. package/dist/apiServer/deployment/NginxHelper.js +3 -0
  16. package/dist/apiServer/deployment/Restore.js +1 -1
  17. package/dist/apiServer/deployment/Status.js +1 -1
  18. package/dist/apiServer/deployment/cli.js +11 -0
  19. package/dist/apiServer/deployment/cliCommon.d.ts +1 -0
  20. package/dist/apiServer/deployment/cliCommon.js +4 -0
  21. package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
  22. package/dist/apiServer/helper/PasswordHash.js +52 -0
  23. package/dist/apiServer/monitor/AccessStore.d.ts +24 -0
  24. package/dist/apiServer/monitor/AccessStore.js +146 -0
  25. package/dist/apiServer/monitor/Monitor.js +7 -3
  26. package/dist/apiServer/monitor/MonitorAuth.d.ts +4 -2
  27. package/dist/apiServer/monitor/MonitorAuth.js +17 -7
  28. package/dist/apiServer/monitor/index.html +70 -61
  29. package/dist/index.d.ts +11 -0
  30. package/dist/index.js +27 -1
  31. package/monitoring.help.md +1 -1
  32. package/package.json +1 -1
@@ -20,6 +20,7 @@ const Watchdog_1 = require("./Watchdog");
20
20
  const NginxHelper_1 = require("./NginxHelper");
21
21
  const BlueGreenState_1 = require("./BlueGreenState");
22
22
  const BackupManager_1 = require("./BackupManager");
23
+ const PasswordHash_1 = require("../helper/PasswordHash");
23
24
  const _TSetup = {
24
25
  users: [{
25
26
  login: "",
@@ -67,6 +68,7 @@ class DeployerService extends BaseService_1.BaseService {
67
68
  throw new Error("Setup file missing/invalid at start — cannot start deployer");
68
69
  }
69
70
  this.setup = initial;
71
+ this._warnPlaintextUsers();
70
72
  this._lastSetupHash = crypto_1.default.createHash("md5").update(JSON.stringify(initial)).digest("hex");
71
73
  if (this.setup.notifier?.URL && this.setup.notifier?.KEY) {
72
74
  this.notifier = new Notifier_1.Notifier({ URL: this.setup.notifier.URL, KEY: this.setup.notifier.KEY });
@@ -124,6 +126,7 @@ class DeployerService extends BaseService_1.BaseService {
124
126
  return;
125
127
  this._lastSetupHash = hash;
126
128
  this.setup = fresh;
129
+ this._warnPlaintextUsers();
127
130
  (0, LogService_1.logWarn)("Setup reloaded from disk (users list refreshed live; notifier/watchdog need service restart to change)");
128
131
  }
129
132
  _watchSetup() {
@@ -145,10 +148,11 @@ class DeployerService extends BaseService_1.BaseService {
145
148
  setInterval(() => { this._reloadSetup(); }, 60_000).unref();
146
149
  }
147
150
  async proceed(data) {
148
- const user = this._checkUserAuth(data.auth);
151
+ const auth = await this._checkUserAuth(data.auth, data.authLogin);
152
+ const user = auth.user;
149
153
  if (!user) {
150
154
  (0, LogService_1.logError)("Deploy rejected: user auth failed");
151
- return { error: { code: 20, message: "Unauthorized.", httpStatus: 401 } };
155
+ return { error: { code: 20, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
152
156
  }
153
157
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
154
158
  let found;
@@ -369,10 +373,11 @@ class DeployerService extends BaseService_1.BaseService {
369
373
  }
370
374
  }
371
375
  async switchSlot(data) {
372
- const user = this._checkUserAuth(data.auth);
376
+ const auth = await this._checkUserAuth(data.auth, data.authLogin);
377
+ const user = auth.user;
373
378
  if (!user) {
374
379
  (0, LogService_1.logError)("Switch rejected: user auth failed");
375
- return { error: { code: 40, message: "Unauthorized.", httpStatus: 401 } };
380
+ return { error: { code: 40, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
376
381
  }
377
382
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
378
383
  let found;
@@ -457,9 +462,10 @@ class DeployerService extends BaseService_1.BaseService {
457
462
  }
458
463
  }
459
464
  async status(data) {
460
- const user = this._checkUserAuth(data.auth);
465
+ const auth = await this._checkUserAuth(data.auth, data.authLogin);
466
+ const user = auth.user;
461
467
  if (!user) {
462
- return { error: { code: 50, message: "Unauthorized.", httpStatus: 401 } };
468
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
463
469
  }
464
470
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
465
471
  const results = {};
@@ -490,9 +496,11 @@ class DeployerService extends BaseService_1.BaseService {
490
496
  return DeployerService._isBlueGreen(found) ? dest : path_1.default.dirname(dest);
491
497
  }
492
498
  async listBackups(data) {
493
- const user = this._checkUserAuth(data.auth);
494
- if (!user)
495
- return { error: { code: 50, message: "Unauthorized.", httpStatus: 401 } };
499
+ const auth = await this._checkUserAuth(data.auth, data.authLogin);
500
+ const user = auth.user;
501
+ if (!user) {
502
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
503
+ }
496
504
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
497
505
  const found = Array.from(configurations.values()).find(c => c.name === data.name);
498
506
  if (!found)
@@ -519,10 +527,11 @@ class DeployerService extends BaseService_1.BaseService {
519
527
  } };
520
528
  }
521
529
  async restoreBackup(data) {
522
- const user = this._checkUserAuth(data.auth);
530
+ const auth = await this._checkUserAuth(data.auth, data.authLogin);
531
+ const user = auth.user;
523
532
  if (!user) {
524
533
  (0, LogService_1.logError)("Restore rejected: user auth failed");
525
- return { error: { code: 50, message: "Unauthorized.", httpStatus: 401 } };
534
+ return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: 401 } };
526
535
  }
527
536
  const configurations = await ConfigService_1.REQ_DEPLOYMENT_CONFIG.request();
528
537
  let found;
@@ -672,23 +681,44 @@ class DeployerService extends BaseService_1.BaseService {
672
681
  const hb = new Uint8Array(crypto_1.default.createHash("sha256").update(String(b ?? "")).digest());
673
682
  return crypto_1.default.timingSafeEqual(ha, hb);
674
683
  }
675
- _checkUserAuth(authHeader) {
684
+ _warnPlaintextUsers() {
685
+ const plain = (this.setup?.users ?? []).filter(u => u?.login && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
686
+ if (plain.length)
687
+ (0, LogService_1.logError)(`Deployer: password stored as plain text in setup.json for ${plain.map(l => '"' + l + '"').join(", ")} — these users are refused; store a hash instead: npx badmfck hash-password --deployer`);
688
+ }
689
+ static PLAINTEXT_ERROR = "Password is built incorrectly — setup.json must hold a hash from `npx badmfck hash-password --deployer`, not the password itself.";
690
+ async _checkUserAuth(authHeader, loginHeader) {
676
691
  if (!authHeader)
677
- return null;
692
+ return {};
678
693
  if (!this.setup)
679
- return null;
694
+ return {};
680
695
  const token = authHeader.split(" ").pop() ?? "";
681
696
  if (!token)
682
- return null;
683
- if (!this.setup.users || this.setup.users.length === 0)
684
- return null;
685
- let matched = null;
686
- for (const user of this.setup.users) {
697
+ return {};
698
+ const users = this.setup.users ?? [];
699
+ if (users.length === 0)
700
+ return {};
701
+ const login = typeof loginHeader === "string" ? loginHeader.trim() : "";
702
+ if (login) {
703
+ const user = users.find(u => u.login === login);
704
+ if (user && PasswordHash_1.PasswordHash.isHash(user.password))
705
+ return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user } : {};
706
+ }
707
+ let plainMatch = false;
708
+ for (const user of users) {
709
+ if (PasswordHash_1.PasswordHash.isHash(user.password) || !user.password)
710
+ continue;
687
711
  const expected = crypto_1.default.createHash("sha256").update(user.login + ":" + user.password).digest("hex");
688
712
  if (this.tokensMatch(token, expected))
689
- matched = user;
713
+ plainMatch = true;
714
+ }
715
+ if (plainMatch) {
716
+ (0, LogService_1.logError)("Deployer auth refused: user's password is stored as plain text in setup.json");
717
+ return { error: DeployerService.PLAINTEXT_ERROR };
690
718
  }
691
- return matched;
719
+ if (!login)
720
+ (0, LogService_1.logWarn)("Deployer auth failed without X-Deployer-Login — update the badmfck CLI on the client");
721
+ return {};
692
722
  }
693
723
  static _extractPort(config) {
694
724
  if (!config || typeof config !== "object")
@@ -0,0 +1 @@
1
+ export declare function HashPassword(target: "monitor" | "deployer"): Promise<void>;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.HashPassword = HashPassword;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const promises_1 = require("readline/promises");
9
+ const process_1 = require("process");
10
+ const PasswordHash_1 = require("../helper/PasswordHash");
11
+ const MonitorAuth_1 = require("../monitor/MonitorAuth");
12
+ const cliCommon_1 = require("./cliCommon");
13
+ function askHidden(question) {
14
+ return new Promise(resolve => {
15
+ process_1.stdout.write(question);
16
+ const wasRaw = !!process_1.stdin.isRaw;
17
+ process_1.stdin.setRawMode(true);
18
+ process_1.stdin.setEncoding("utf8");
19
+ process_1.stdin.resume();
20
+ let value = "";
21
+ const finish = () => {
22
+ process_1.stdin.removeListener("data", onData);
23
+ process_1.stdin.setRawMode(wasRaw);
24
+ process_1.stdin.pause();
25
+ process_1.stdout.write("\n");
26
+ };
27
+ const onData = (chunk) => {
28
+ for (const ch of chunk) {
29
+ if (ch === "\r" || ch === "\n" || ch === "\u0004") {
30
+ finish();
31
+ resolve(value);
32
+ return;
33
+ }
34
+ if (ch === "\u0003") {
35
+ finish();
36
+ process.exit(130);
37
+ }
38
+ if (ch === "\u007f" || ch === "\b") {
39
+ value = value.slice(0, -1);
40
+ continue;
41
+ }
42
+ if (ch >= " ")
43
+ value += ch;
44
+ }
45
+ };
46
+ process_1.stdin.on("data", onData);
47
+ });
48
+ }
49
+ async function HashPassword(target) {
50
+ const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
51
+ if (!process_1.stdin.isTTY) {
52
+ console.error(red("✗ hash-password needs an interactive terminal — the password is never accepted as an argument."));
53
+ process.exit(1);
54
+ }
55
+ console.log(bold(`\nHash a ${target} password`) + dim(target === "deployer" ? " (setup.json users)" : " (APIService access.monitor)"));
56
+ const rl = (0, promises_1.createInterface)({ input: process_1.stdin, output: process_1.stdout });
57
+ let login;
58
+ try {
59
+ login = (await rl.question("Login: ")).trim();
60
+ }
61
+ finally {
62
+ rl.close();
63
+ }
64
+ if (!login) {
65
+ console.error(red("✗ Login is required."));
66
+ process.exit(1);
67
+ }
68
+ {
69
+ const pass1 = await askHidden("Password: ");
70
+ const policy = MonitorAuth_1.MonitorAuth.passwordPolicyError(pass1);
71
+ if (policy) {
72
+ console.error(red(`✗ ${policy}.`));
73
+ process.exit(1);
74
+ }
75
+ const pass2 = await askHidden("Repeat password: ");
76
+ if (pass1 !== pass2) {
77
+ console.error(red("✗ Passwords do not match."));
78
+ process.exit(1);
79
+ }
80
+ const secret = target === "deployer"
81
+ ? crypto_1.default.createHash("sha256").update(login + ":" + pass1).digest("hex")
82
+ : pass1;
83
+ const hash = await PasswordHash_1.PasswordHash.hash(secret);
84
+ console.log("");
85
+ console.log(green(bold("✓ Put this in the config instead of the plain password:")));
86
+ console.log(`\n { "login": ${JSON.stringify(login)}, "password": ${JSON.stringify(hash)} }\n`);
87
+ if (target === "deployer")
88
+ console.log(yellow(" Deployer users stored as a hash need an up-to-date badmfck CLI on the deploying machine."));
89
+ console.log(dim(" The hash is salted — running this again for the same password gives a different, equally valid hash."));
90
+ }
91
+ }
@@ -1,5 +1,5 @@
1
1
  import { IError } from "../structures/Interfaces";
2
- export declare const DEFAULT_SERVER_TEMPLATE = "# Seeded by deployer for _{{DOMAIN}}_. SAFE TO EDIT.\n# Deployer NEVER overwrites this file after the initial seed.\n# Add SSL by running: certbot --nginx -d _{{DOMAIN}}_\n\nserver {\n server_name _{{DOMAIN}}_;\n listen 80;\n\n location / {\n proxy_pass http://_{{UPSTREAM}}_;\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 60s;\n }\n}\n";
2
+ export declare const DEFAULT_SERVER_TEMPLATE = "# Seeded by deployer for _{{DOMAIN}}_. SAFE TO EDIT.\n# Deployer NEVER overwrites this file after the initial seed.\n# Add SSL by running: certbot --nginx -d _{{DOMAIN}}_\n\nserver {\n server_name _{{DOMAIN}}_;\n listen 80;\n\n location / {\n proxy_pass http://_{{UPSTREAM}}_;\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n # WebSocket: pass the upgrade handshake through to the app.\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_read_timeout 60s;\n }\n}\n";
3
3
  export declare class NginxHelper {
4
4
  static writeUpstream(filePath: string, upstreamName: string, port: string): IError | null;
5
5
  static seedServerConfig(filePath: string, template: string, values: Record<string, string>): {
@@ -25,6 +25,9 @@ server {
25
25
  proxy_set_header X-Real-IP $remote_addr;
26
26
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
27
27
  proxy_set_header X-Forwarded-Proto $scheme;
28
+ # WebSocket: pass the upgrade handshake through to the app.
29
+ proxy_set_header Upgrade $http_upgrade;
30
+ proxy_set_header Connection "upgrade";
28
31
  proxy_read_timeout 60s;
29
32
  }
30
33
  }
@@ -9,7 +9,7 @@ const cliCommon_1 = require("./cliCommon");
9
9
  async function Restore(opt, backupName, assumeYes = false) {
10
10
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
11
11
  const { red, yellow, green, dim, bold } = (0, cliCommon_1.palette)();
12
- const headers = { authorization: (0, cliCommon_1.authHeader)(opt) };
12
+ const headers = (0, cliCommon_1.deployerHeaders)(opt);
13
13
  const fail = (msg) => { console.error(red(bold("✗ ")) + msg); process.exit(1); };
14
14
  const lr = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, { headers, timeoutMs: 30000, retry: { enabled: false } });
15
15
  const lerr = (0, cliCommon_1.responseError)(lr);
@@ -18,7 +18,7 @@ async function Status(opt) {
18
18
  throw new Error(`Cannot derive status URL from host "${opt.host}" — make sure "host" ends with /add.`);
19
19
  const authToken = crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
20
20
  const response = await __1.Http.post(statusUrl, { name: opt.name }, {
21
- headers: { authorization: `Bearer ${authToken}` },
21
+ headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
22
22
  timeoutMs: 15 * 1000,
23
23
  retry: { enabled: false },
24
24
  });
@@ -7,6 +7,7 @@ const Status_1 = require("./Status");
7
7
  const Backups_1 = require("./Backups");
8
8
  const Restore_1 = require("./Restore");
9
9
  const BackupManager_1 = require("./BackupManager");
10
+ const HashPassword_1 = require("./HashPassword");
10
11
  function usage() {
11
12
  console.error("Usage:");
12
13
  console.error(" badmfck deploy [config.json] — build + upload the current project");
@@ -14,6 +15,7 @@ function usage() {
14
15
  console.error(" badmfck status [config.json] — show active / last deployed slot");
15
16
  console.error(" badmfck backups [config.json] — list deploy backups");
16
17
  console.error(" badmfck restore [config.json] [backup] [--yes] — restore a backup (asks which, and confirms)");
18
+ console.error(" badmfck hash-password [--deployer] — hash a password for the monitor (or deployer setup.json)");
17
19
  console.error("");
18
20
  console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
19
21
  console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
@@ -91,6 +93,15 @@ async function main() {
91
93
  await (0, Restore_1.Restore)(config, backup, yes);
92
94
  break;
93
95
  }
96
+ case "hash-password": {
97
+ const unknown = rest.filter(a => a !== "--deployer");
98
+ if (unknown.length) {
99
+ console.error("hash-password takes no arguments except --deployer — the password is asked interactively.");
100
+ process.exit(1);
101
+ }
102
+ await (0, HashPassword_1.HashPassword)(rest.includes("--deployer") ? "deployer" : "monitor");
103
+ break;
104
+ }
94
105
  case "status": {
95
106
  const { scheme, config } = parseArgs(rest);
96
107
  if (scheme) {
@@ -1,6 +1,7 @@
1
1
  import { IDeployerConfig } from "./resolveConfig";
2
2
  export declare function deployerUrl(opt: IDeployerConfig, endpoint: string): string;
3
3
  export declare function authHeader(opt: IDeployerConfig): string;
4
+ export declare function deployerHeaders(opt: IDeployerConfig): Record<string, string>;
4
5
  export declare function responseError(r: any): string | null;
5
6
  export declare function palette(): {
6
7
  red: (t: string) => string;
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.deployerUrl = deployerUrl;
7
7
  exports.authHeader = authHeader;
8
+ exports.deployerHeaders = deployerHeaders;
8
9
  exports.responseError = responseError;
9
10
  exports.palette = palette;
10
11
  exports.fmtDate = fmtDate;
@@ -21,6 +22,9 @@ function deployerUrl(opt, endpoint) {
21
22
  function authHeader(opt) {
22
23
  return "Bearer " + crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
23
24
  }
25
+ function deployerHeaders(opt) {
26
+ return { authorization: authHeader(opt), "x-deployer-login": String(opt.username) };
27
+ }
24
28
  function responseError(r) {
25
29
  const body = r?.ok ? r?.data : r?.error;
26
30
  const e = (body && typeof body === "object")
@@ -0,0 +1,5 @@
1
+ export declare class PasswordHash {
2
+ static isHash(value: unknown): boolean;
3
+ static hash(secret: string): Promise<string>;
4
+ static verify(secret: string, stored: string): Promise<boolean>;
5
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PasswordHash = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const DEFAULTS = { N: 16384, r: 8, p: 1, keylen: 32 };
9
+ function scryptAsync(secret, salt, keylen, opts) {
10
+ return new Promise((resolve, reject) => crypto_1.default.scrypt(secret, salt, keylen, opts, (err, key) => err ? reject(err) : resolve(key)));
11
+ }
12
+ class PasswordHash {
13
+ static isHash(value) {
14
+ return typeof value === "string" && value.startsWith("scrypt$");
15
+ }
16
+ static async hash(secret) {
17
+ const { N, r, p, keylen } = DEFAULTS;
18
+ const salt = crypto_1.default.randomBytes(16);
19
+ const key = await scryptAsync(secret, salt, keylen, { N, r, p, maxmem: 256 * N * r });
20
+ return `scrypt$${N}$${r}$${p}$${salt.toString("base64")}$${key.toString("base64")}`;
21
+ }
22
+ static async verify(secret, stored) {
23
+ if (typeof secret !== "string" || !PasswordHash.isHash(stored))
24
+ return false;
25
+ const parts = stored.split("$");
26
+ if (parts.length !== 6)
27
+ return false;
28
+ const N = Number(parts[1]), r = Number(parts[2]), p = Number(parts[3]);
29
+ if (!Number.isInteger(N) || N < 1024 || N > 1 << 20 || (N & (N - 1)) !== 0)
30
+ return false;
31
+ if (!Number.isInteger(r) || r < 1 || r > 32 || !Number.isInteger(p) || p < 1 || p > 16)
32
+ return false;
33
+ let salt, expected;
34
+ try {
35
+ salt = Buffer.from(parts[4], "base64");
36
+ expected = Buffer.from(parts[5], "base64");
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ if (salt.length < 8 || expected.length < 16)
42
+ return false;
43
+ try {
44
+ const key = await scryptAsync(secret, salt, expected.length, { N, r, p, maxmem: 256 * N * r });
45
+ return crypto_1.default.timingSafeEqual(key, expected);
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ }
52
+ exports.PasswordHash = PasswordHash;
@@ -0,0 +1,24 @@
1
+ import type { IMonitorUser, IDocumentationUser } from "../APIService";
2
+ export interface IAccess {
3
+ monitor?: IMonitorUser[];
4
+ documentation?: IDocumentationUser[];
5
+ }
6
+ export declare class AccessStore {
7
+ private onChange?;
8
+ private current;
9
+ private hash;
10
+ private refusedHash;
11
+ private file;
12
+ private debounce;
13
+ constructor(source: IAccess | string | undefined | null, onChange?: ((prev: IAccess, next: IAccess) => void) | undefined);
14
+ get monitor(): IMonitorUser[];
15
+ get documentation(): IDocumentationUser[];
16
+ static validate(value: any): string | null;
17
+ private loadSync;
18
+ private reload;
19
+ private accept;
20
+ private refuse;
21
+ private apply;
22
+ private warnPermissions;
23
+ private watch;
24
+ }
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AccessStore = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const LogService_1 = require("../LogService");
11
+ const ROLES = ["admin", "it", "analytic"];
12
+ class AccessStore {
13
+ onChange;
14
+ current = {};
15
+ hash = "";
16
+ refusedHash = "";
17
+ file = null;
18
+ debounce = null;
19
+ constructor(source, onChange) {
20
+ this.onChange = onChange;
21
+ if (typeof source !== "string") {
22
+ this.apply(source ?? {});
23
+ return;
24
+ }
25
+ this.file = path_1.default.resolve(source);
26
+ this.loadSync();
27
+ this.watch();
28
+ }
29
+ get monitor() { return this.current.monitor ?? []; }
30
+ get documentation() { return this.current.documentation ?? []; }
31
+ static validate(value) {
32
+ if (!value || typeof value !== "object" || Array.isArray(value))
33
+ return "root must be an object";
34
+ for (const list of ["monitor", "documentation"]) {
35
+ const users = value[list];
36
+ if (users === undefined)
37
+ continue;
38
+ if (!Array.isArray(users))
39
+ return `"${list}" must be an array`;
40
+ const seen = new Set();
41
+ for (const [i, u] of users.entries()) {
42
+ const at = `${list}[${i}]`;
43
+ if (!u || typeof u !== "object")
44
+ return `${at} must be an object`;
45
+ if (typeof u.login !== "string" || !u.login.trim())
46
+ return `${at}.login must be a non-empty string`;
47
+ if (typeof u.password !== "string")
48
+ return `${at}.password must be a string`;
49
+ if (seen.has(u.login))
50
+ return `${at}: duplicate login "${u.login}"`;
51
+ seen.add(u.login);
52
+ if (u.role !== undefined && !ROLES.includes(u.role))
53
+ return `${at}.role must be one of ${ROLES.join(", ")}`;
54
+ if (u.totpSecret !== undefined && typeof u.totpSecret !== "string")
55
+ return `${at}.totpSecret must be a string`;
56
+ if (u.endpoints !== undefined && (!Array.isArray(u.endpoints) || u.endpoints.some((e) => typeof e !== "string")))
57
+ return `${at}.endpoints must be an array of strings`;
58
+ }
59
+ }
60
+ return null;
61
+ }
62
+ loadSync() {
63
+ try {
64
+ this.accept(fs_1.default.readFileSync(this.file, "utf-8"), true);
65
+ }
66
+ catch (e) {
67
+ (0, LogService_1.logError)(`Access file ${this.file}: ${e.code === "ENOENT" ? "not found" : e.message} — no one can access the monitor and documentation until it is fixed`);
68
+ }
69
+ }
70
+ async reload() {
71
+ let raw;
72
+ try {
73
+ raw = await fs_1.default.promises.readFile(this.file, "utf-8");
74
+ }
75
+ catch (e) {
76
+ if (e.code !== "ENOENT")
77
+ (0, LogService_1.logWarn)(`Access file ${this.file}: ${e.message} — keeping the previous access`);
78
+ return;
79
+ }
80
+ this.accept(raw, false);
81
+ }
82
+ accept(raw, initial) {
83
+ const hash = crypto_1.default.createHash("sha256").update(raw).digest("hex");
84
+ if (hash === this.hash || hash === this.refusedHash)
85
+ return;
86
+ let parsed;
87
+ try {
88
+ parsed = JSON.parse(raw);
89
+ }
90
+ catch (e) {
91
+ this.refusedHash = hash;
92
+ return this.refuse(`invalid JSON (${e.message})`, initial);
93
+ }
94
+ const problem = AccessStore.validate(parsed);
95
+ if (problem)
96
+ this.refusedHash = hash;
97
+ if (problem)
98
+ return this.refuse(problem, initial);
99
+ this.hash = hash;
100
+ this.refusedHash = "";
101
+ this.warnPermissions();
102
+ this.apply({ monitor: parsed.monitor, documentation: parsed.documentation });
103
+ (0, LogService_1.logInfo)(`Access ${initial ? "loaded" : "reloaded"} from ${this.file}: ${this.monitor.length} monitor, ${this.documentation.length} documentation user(s)`);
104
+ }
105
+ refuse(reason, initial) {
106
+ if (initial)
107
+ (0, LogService_1.logError)(`Access file ${this.file}: ${reason} — no one can access the monitor and documentation until it is fixed`);
108
+ else
109
+ (0, LogService_1.logError)(`Access file ${this.file}: ${reason} — change ignored, keeping the previous access`);
110
+ }
111
+ apply(next) {
112
+ const prev = this.current;
113
+ this.current = next;
114
+ try {
115
+ this.onChange?.(prev, next);
116
+ }
117
+ catch (e) {
118
+ (0, LogService_1.logError)(`Access change handler threw: ${e instanceof Error ? e.message : String(e)}`);
119
+ }
120
+ }
121
+ warnPermissions() {
122
+ try {
123
+ const mode = fs_1.default.statSync(this.file).mode;
124
+ if (mode & 0o077)
125
+ (0, LogService_1.logWarn)(`Access file ${this.file} is readable by other users (mode ${(mode & 0o777).toString(8)}) — chmod 600 it`);
126
+ }
127
+ catch { }
128
+ }
129
+ watch() {
130
+ const dir = path_1.default.dirname(this.file), name = path_1.default.basename(this.file);
131
+ try {
132
+ fs_1.default.watch(dir, (_event, filename) => {
133
+ if (filename && filename !== name)
134
+ return;
135
+ if (this.debounce)
136
+ clearTimeout(this.debounce);
137
+ this.debounce = setTimeout(() => { this.debounce = null; this.reload(); }, 200);
138
+ }).unref();
139
+ }
140
+ catch (e) {
141
+ (0, LogService_1.logWarn)(`Access file: cannot watch ${dir} (${e.message}) — changes are picked up within a minute`);
142
+ }
143
+ setInterval(() => this.reload(), 60_000).unref();
144
+ }
145
+ }
146
+ exports.AccessStore = AccessStore;
@@ -189,7 +189,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
189
189
  const users = await APIService_1.REQ_MONITOR_USERS.request();
190
190
  if (!users || users.length === 0)
191
191
  throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "No users found for monitor access, please set up users first." };
192
- const { user, error, enrollmentRequired } = MonitorAuth_1.MonitorAuth.authenticate(users, req.data.login, req.data.password, req.data.totp);
192
+ const { user, error, enrollmentRequired } = await MonitorAuth_1.MonitorAuth.authenticate(users, req.data.login, req.data.password, req.data.totp);
193
193
  if (!user || error) {
194
194
  (0, LogService_1.logWarn)(`Monitor login failed for "${req.data.login}" from ${req.ip ?? "unknown"}: ${error}`);
195
195
  throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: error ?? "Invalid user" };
@@ -243,7 +243,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
243
243
  async restart(req) {
244
244
  const login = await this.requireAccess(req, "admin");
245
245
  const users = await APIService_1.REQ_MONITOR_USERS.request();
246
- const stepUp = MonitorAuth_1.MonitorAuth.authenticate(users ?? [], login, req.data.password, req.data.totp);
246
+ const stepUp = await MonitorAuth_1.MonitorAuth.authenticate(users ?? [], login, req.data.password, req.data.totp);
247
247
  if (!stepUp.user) {
248
248
  (0, LogService_1.logWarn)(`Monitor restart re-auth failed for "${login}": ${stepUp.error}`);
249
249
  throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Re-authentication required: " + (stepUp.error ?? "invalid credentials") };
@@ -344,7 +344,11 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
344
344
  const login = await this.checkAuthentication(req);
345
345
  const users = await APIService_1.REQ_MONITOR_USERS.request();
346
346
  const user = users?.find(u => u?.login === login);
347
- if (!MonitorAuth_1.MonitorAuth.roleAllows(user?.role, capability)) {
347
+ if (!user) {
348
+ MonitorAuth_1.MonitorAuth.revokeAllFor(login);
349
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "User no longer has monitor access" };
350
+ }
351
+ if (!MonitorAuth_1.MonitorAuth.roleAllows(user.role, capability)) {
348
352
  const { role } = MonitorAuth_1.MonitorAuth.describeRole(user?.role);
349
353
  (0, LogService_1.logWarn)(`Monitor access denied: "${login}" (role ${role}) tried a "${capability}" endpoint`);
350
354
  throw { ...DefaultErrors_1.default.FORBIDDEN, details: `Role "${role}" is not allowed to access ${capability} endpoints` };
@@ -39,6 +39,8 @@ export declare class MonitorAuth {
39
39
  static passwordPolicyError(password: string | undefined | null): string | null;
40
40
  static compliantUsers(users: IMonitorUser[]): IMonitorUser[];
41
41
  static policyReportFor(users: IMonitorUser[]): string[];
42
+ static PLAINTEXT_ERROR: string;
43
+ static plaintextLogins(users: IMonitorUser[]): string[];
42
44
  private static base32Decode;
43
45
  private static hotp;
44
46
  static verifyTotp(login: string, secretBase32: string, code: string): string | null;
@@ -51,11 +53,11 @@ export declare class MonitorAuth {
51
53
  private static registerFailure;
52
54
  private static clearFailures;
53
55
  private static sameSecret;
54
- static authenticate(users: IMonitorUser[], login: string, password: string, totp?: string): {
56
+ static authenticate(users: IMonitorUser[], login: string, password: string, totp?: string): Promise<{
55
57
  user?: IMonitorUser;
56
58
  error?: string;
57
59
  enrollmentRequired?: boolean;
58
- };
60
+ }>;
59
61
  private static pendingEnrollments;
60
62
  static ENROLLMENT_TTL_MS: number;
61
63
  static beginEnrollment(login: string, issuer?: string): {