badmfck-api-server 5.0.15 → 5.0.16

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.
@@ -30,7 +30,7 @@ async function Activate(opt, scheme) {
30
30
  console.log(`Activating${scheme ? ` slot=${scheme}` : " (auto: lastDeployed)"} for ${opt.name} at ${switchUrl}`);
31
31
  const startedAt = Date.now();
32
32
  const response = await __1.Http.post(switchUrl, requestBody, {
33
- headers: { authorization: `Bearer ${authToken}` },
33
+ headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
34
34
  timeoutMs: 60 * 1000,
35
35
  retry: { enabled: false },
36
36
  });
@@ -8,7 +8,7 @@ async function Backups(opt) {
8
8
  opt = await (0, resolveConfig_1.resolveConfig)(opt);
9
9
  const { red, yellow, blue, green, dim, bold } = (0, cliCommon_1.palette)();
10
10
  const r = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, {
11
- headers: { authorization: (0, cliCommon_1.authHeader)(opt) }, timeoutMs: 30000, retry: { enabled: false },
11
+ headers: (0, cliCommon_1.deployerHeaders)(opt), timeoutMs: 30000, retry: { enabled: false },
12
12
  });
13
13
  const err = (0, cliCommon_1.responseError)(r);
14
14
  if (err) {
@@ -206,7 +206,7 @@ async function Deploy(opt) {
206
206
  bodyTimeout: 5 * 60 * 1000,
207
207
  });
208
208
  const uploadResponse = await __1.Http.post(opt.host, formData, {
209
- headers: { authorization: `Bearer ${authToken}` },
209
+ headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
210
210
  dispatcher: uploadAgent,
211
211
  timeoutMs: 5 * 60 * 1000,
212
212
  retry: { enabled: false },
@@ -72,20 +72,20 @@ class Deployer extends BaseEndpoint_1.BaseEndpoint {
72
72
  async file(req) {
73
73
  if (!req.files)
74
74
  throw { ...DefaultErrors_1.default.FILE_NOT_EXISTS, details: "No files were uploaded" };
75
- const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization });
75
+ const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
76
76
  return { data: result };
77
77
  }
78
78
  async switchSlot(req) {
79
- return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization });
79
+ return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
80
80
  }
81
81
  async status(req) {
82
- return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization });
82
+ return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
83
83
  }
84
84
  async backups(req) {
85
- return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization });
85
+ return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
86
86
  }
87
87
  async restore(req) {
88
- return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization });
88
+ return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
89
89
  }
90
90
  async slot(req) {
91
91
  return await DeployerService_1.REQ_DEPLOYMENT_SLOT.request({ name: req.data.name, token: req.data.token, slot: req.data.slot });
@@ -29,6 +29,7 @@ export interface IDeployerServiceOptions {
29
29
  }
30
30
  export declare const REQ_DEPLOYMENT_PROCEED: Req<{
31
31
  auth: string;
32
+ authLogin?: string;
32
33
  name: string;
33
34
  token: string;
34
35
  files: {
@@ -37,12 +38,14 @@ export declare const REQ_DEPLOYMENT_PROCEED: Req<{
37
38
  }, any>;
38
39
  export declare const REQ_DEPLOYMENT_SWITCH: Req<{
39
40
  auth?: string;
41
+ authLogin?: string;
40
42
  name: string;
41
43
  token: string;
42
44
  scheme?: "blue" | "green";
43
45
  }, any>;
44
46
  export declare const REQ_DEPLOYMENT_STATUS: Req<{
45
47
  auth?: string;
48
+ authLogin?: string;
46
49
  name?: string;
47
50
  }, any>;
48
51
  export declare const REQ_DEPLOYMENT_SLOT: Req<{
@@ -52,10 +55,12 @@ export declare const REQ_DEPLOYMENT_SLOT: Req<{
52
55
  }, any>;
53
56
  export declare const REQ_DEPLOYMENT_BACKUPS: Req<{
54
57
  auth?: string;
58
+ authLogin?: string;
55
59
  name: string;
56
60
  }, any>;
57
61
  export declare const REQ_DEPLOYMENT_RESTORE: Req<{
58
62
  auth?: string;
63
+ authLogin?: string;
59
64
  name: string;
60
65
  token: string;
61
66
  backup: string;
@@ -76,6 +81,7 @@ export declare class DeployerService extends BaseService {
76
81
  private _watchSetup;
77
82
  proceed(data: {
78
83
  auth?: string;
84
+ authLogin?: string;
79
85
  name: string;
80
86
  token: string;
81
87
  files: {
@@ -101,6 +107,7 @@ export declare class DeployerService extends BaseService {
101
107
  }>;
102
108
  switchSlot(data: {
103
109
  auth?: string;
110
+ authLogin?: string;
104
111
  name: string;
105
112
  token: string;
106
113
  scheme?: "blue" | "green";
@@ -122,6 +129,7 @@ export declare class DeployerService extends BaseService {
122
129
  }>;
123
130
  status(data: {
124
131
  auth?: string;
132
+ authLogin?: string;
125
133
  name?: string;
126
134
  }): Promise<{
127
135
  data?: undefined;
@@ -142,6 +150,7 @@ export declare class DeployerService extends BaseService {
142
150
  private static _backupRoot;
143
151
  listBackups(data: {
144
152
  auth?: string;
153
+ authLogin?: string;
145
154
  name: string;
146
155
  }): Promise<{
147
156
  data?: undefined;
@@ -163,6 +172,7 @@ export declare class DeployerService extends BaseService {
163
172
  }>;
164
173
  restoreBackup(data: {
165
174
  auth?: string;
175
+ authLogin?: string;
166
176
  name: string;
167
177
  token: string;
168
178
  backup: string;
@@ -220,6 +230,8 @@ export declare class DeployerService extends BaseService {
220
230
  private _statusUrl;
221
231
  private _writeBlueGreenFiles;
222
232
  tokensMatch(a: string | undefined, b: string | undefined): boolean;
233
+ private _warnPlaintextUsers;
234
+ static PLAINTEXT_ERROR: string;
223
235
  private _checkUserAuth;
224
236
  private static _extractPort;
225
237
  private _renderNginx;
@@ -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
+ }
@@ -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;
@@ -42,6 +42,9 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
42
42
  super("sm");
43
43
  this.apiServiceOptions = options;
44
44
  MonitorAuth_1.MonitorAuth.configure({ authFile: options.monitorAuthFile, authDir: options.monitorAuthDir, projectName: options.projectName });
45
+ const plain = MonitorAuth_1.MonitorAuth.plaintextLogins(options.access?.monitor ?? []);
46
+ if (plain.length)
47
+ (0, LogService_1.logError)(`Monitor: password stored as plain text for ${plain.map(l => '"' + l + '"').join(", ")} — these logins are refused; store a hash instead: npx badmfck hash-password`);
45
48
  this.registerEndpoints([
46
49
  { ignoreInterceptor: true, endpoint: "html", handler: this.html },
47
50
  { ignoreInterceptor: true, endpoint: "log", handler: this.logs },
@@ -189,7 +192,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
189
192
  const users = await APIService_1.REQ_MONITOR_USERS.request();
190
193
  if (!users || users.length === 0)
191
194
  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);
195
+ const { user, error, enrollmentRequired } = await MonitorAuth_1.MonitorAuth.authenticate(users, req.data.login, req.data.password, req.data.totp);
193
196
  if (!user || error) {
194
197
  (0, LogService_1.logWarn)(`Monitor login failed for "${req.data.login}" from ${req.ip ?? "unknown"}: ${error}`);
195
198
  throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: error ?? "Invalid user" };
@@ -243,7 +246,7 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
243
246
  async restart(req) {
244
247
  const login = await this.requireAccess(req, "admin");
245
248
  const users = await APIService_1.REQ_MONITOR_USERS.request();
246
- const stepUp = MonitorAuth_1.MonitorAuth.authenticate(users ?? [], login, req.data.password, req.data.totp);
249
+ const stepUp = await MonitorAuth_1.MonitorAuth.authenticate(users ?? [], login, req.data.password, req.data.totp);
247
250
  if (!stepUp.user) {
248
251
  (0, LogService_1.logWarn)(`Monitor restart re-auth failed for "${login}": ${stepUp.error}`);
249
252
  throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Re-authentication required: " + (stepUp.error ?? "invalid credentials") };
@@ -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): {
@@ -8,6 +8,7 @@ const crypto_1 = __importDefault(require("crypto"));
8
8
  const fs_1 = __importDefault(require("fs"));
9
9
  const path_1 = __importDefault(require("path"));
10
10
  const LogService_1 = require("../LogService");
11
+ const PasswordHash_1 = require("../helper/PasswordHash");
11
12
  class MonitorAuth {
12
13
  static ROLE_CAPS = {
13
14
  admin: ["dashboard", "logs", "admin"],
@@ -128,17 +129,23 @@ class MonitorAuth {
128
129
  }
129
130
  static compliantUsers(users) {
130
131
  return users.filter(u => u && typeof u.login === "string" && u.login.length > 0
131
- && MonitorAuth.passwordPolicyError(u.password) === null);
132
+ && PasswordHash_1.PasswordHash.isHash(u.password));
132
133
  }
133
134
  static policyReportFor(users) {
134
135
  const out = [];
135
136
  for (const u of users || []) {
136
- const reason = !u?.login ? "login is empty" : MonitorAuth.passwordPolicyError(u.password);
137
+ const reason = !u?.login ? "login is empty"
138
+ : PasswordHash_1.PasswordHash.isHash(u.password) ? null
139
+ : MonitorAuth.PLAINTEXT_ERROR;
137
140
  if (reason)
138
141
  out.push(`${u?.login || "<no login>"}: ${reason}`);
139
142
  }
140
143
  return out;
141
144
  }
145
+ static PLAINTEXT_ERROR = "password is built incorrectly — the config must hold a hash from `npx badmfck hash-password`, not the password itself";
146
+ static plaintextLogins(users) {
147
+ return (users || []).filter(u => u?.login && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
148
+ }
142
149
  static base32Decode(input) {
143
150
  const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
144
151
  let bits = 0, value = 0;
@@ -235,7 +242,7 @@ class MonitorAuth {
235
242
  const x = Buffer.from(String(a), "utf-8"), y = Buffer.from(String(b), "utf-8");
236
243
  return x.length === y.length && crypto_1.default.timingSafeEqual(x, y);
237
244
  }
238
- static authenticate(users, login, password, totp) {
245
+ static async authenticate(users, login, password, totp) {
239
246
  const locked = MonitorAuth.lockoutRemainingMs(login);
240
247
  if (locked > 0)
241
248
  return { error: `account locked, try again in ${Math.ceil(locked / 60000)} min` };
@@ -245,10 +252,13 @@ class MonitorAuth {
245
252
  MonitorAuth.registerFailure(login);
246
253
  return { error: "Invalid user" };
247
254
  }
248
- const policy = MonitorAuth.passwordPolicyError(candidate.password);
249
- if (policy)
250
- return { error: `password policy violation for this account (${policy})` };
251
- if (!MonitorAuth.sameSecret(candidate.password, password || "")) {
255
+ if (!PasswordHash_1.PasswordHash.isHash(candidate.password)) {
256
+ const matches = typeof candidate.password === "string" && candidate.password.length > 0
257
+ && MonitorAuth.sameSecret(candidate.password, password || "");
258
+ MonitorAuth.registerFailure(login);
259
+ return { error: matches ? MonitorAuth.PLAINTEXT_ERROR : "Invalid user" };
260
+ }
261
+ if (!(await PasswordHash_1.PasswordHash.verify(password || "", candidate.password))) {
252
262
  MonitorAuth.registerFailure(login);
253
263
  return { error: "Invalid user" };
254
264
  }