badmfck-api-server 6.0.9 → 6.0.10

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
@@ -604,8 +604,11 @@ getDefaultOptions({
604
604
  });
605
605
  ```
606
606
 
607
- `setup.json` lists who may deploy. Passwords are hashes: generate one with
608
- `npx badmfck hash-password --deployer`.
607
+ `setup.json` lists who may deploy. Passwords are hashes. The easiest way to manage users, reviewers and
608
+ allowed addresses is `npx badmfck setup-config <folder>`, a menu that hashes passwords for you; for a
609
+ single hash use `npx badmfck hash-password --deployer`. When sign-in fails, the deployer logs why
610
+ (unknown login, wrong password, an old CLI without `X-Deployer-Login`), while the client only gets
611
+ `Unauthorized`.
609
612
 
610
613
  ```jsonc
611
614
  {
@@ -714,6 +717,7 @@ git: it holds credentials.
714
717
  | `badmfck project-config` | build a project config for the deployer step by step (plus a `deploy.json` skeleton) |
715
718
  | `badmfck access-config [file]` | create or edit `access.json`: monitor and documentation users, roles, passwords, allowed addresses |
716
719
  | `badmfck migrate-configs [folder] [--yes]` | hash the secrets of old `setup.json`, project configs and `access.json` files in place |
720
+ | `badmfck setup-config [file\|folder]` | edit the deployer's `setup.json`: add, rename or remove users, change passwords, reviewers, allowed IPs |
717
721
 
718
722
  To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json`.
719
723
 
@@ -34,6 +34,33 @@ declare const _TSetup: {
34
34
  readonly $__secrets_dir_optional: true;
35
35
  };
36
36
  export type TDeployerSetup = ValidationModel<typeof _TSetup>;
37
+ export declare const SETUP_MODEL: {
38
+ readonly users: readonly [{
39
+ readonly login: "";
40
+ readonly password: "";
41
+ }];
42
+ readonly watchdog: true;
43
+ readonly $__watchdog_optional: true;
44
+ readonly notifier: {
45
+ readonly URL: "";
46
+ readonly KEY: "";
47
+ };
48
+ readonly $__notifier_optional: true;
49
+ readonly status_url: "";
50
+ readonly $__status_url_optional: true;
51
+ readonly allowed_ips: readonly [""];
52
+ readonly $__allowed_ips_optional: true;
53
+ readonly reviewers: readonly [{
54
+ readonly login: "";
55
+ readonly password: "";
56
+ readonly email: "";
57
+ }];
58
+ readonly $__reviewers_optional: true;
59
+ readonly review_url: "";
60
+ readonly $__review_url_optional: true;
61
+ readonly secrets_dir: "";
62
+ readonly $__secrets_dir_optional: true;
63
+ };
37
64
  export interface IDeployerServiceOptions {
38
65
  projects_path: string;
39
66
  setup_path: string;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DeployerService = exports.REQ_DEPLOYMENT_RESTORE = exports.REQ_DEPLOYMENT_BACKUPS = exports.REQ_DEPLOYMENT_SLOT = exports.REQ_DEPLOYMENT_STATUS = exports.REQ_DEPLOYMENT_SWITCH = exports.REQ_DEPLOYMENT_PROCEED = void 0;
6
+ exports.DeployerService = exports.REQ_DEPLOYMENT_RESTORE = exports.REQ_DEPLOYMENT_BACKUPS = exports.REQ_DEPLOYMENT_SLOT = exports.REQ_DEPLOYMENT_STATUS = exports.REQ_DEPLOYMENT_SWITCH = exports.REQ_DEPLOYMENT_PROCEED = exports.SETUP_MODEL = void 0;
7
7
  const badmfck_signal_1 = require("badmfck-signal");
8
8
  const BaseService_1 = require("../BaseService");
9
9
  const ConfigService_1 = require("./ConfigService");
@@ -51,6 +51,7 @@ const _TSetup = {
51
51
  secrets_dir: "",
52
52
  $__secrets_dir_optional: true
53
53
  };
54
+ exports.SETUP_MODEL = _TSetup;
54
55
  exports.REQ_DEPLOYMENT_PROCEED = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SERVICE");
55
56
  exports.REQ_DEPLOYMENT_SWITCH = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SWITCH");
56
57
  exports.REQ_DEPLOYMENT_STATUS = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_STATUS");
@@ -997,21 +998,26 @@ class DeployerService extends BaseService_1.BaseService {
997
998
  (0, LogService_1.logWarn)(`Deployer: request refused from ${ip ?? "unknown"} — not in allowed_ips`);
998
999
  return { error: "Forbidden.", status: 403 };
999
1000
  }
1001
+ const from = ip ?? "unknown";
1002
+ const shown = (v) => JSON.stringify(v.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 64));
1003
+ const refuse = (reason) => { (0, LogService_1.logWarn)(`Deployer auth failed from ${from}: ${reason}`); return {}; };
1000
1004
  if (!authHeader)
1001
- return {};
1005
+ return refuse("no Authorization header");
1002
1006
  if (!this.setup)
1003
- return {};
1007
+ return refuse("setup.json is not loaded");
1004
1008
  const token = authHeader.split(" ").pop() ?? "";
1005
1009
  if (!token)
1006
- return {};
1010
+ return refuse("empty Authorization header");
1007
1011
  const users = this.setup.users ?? [];
1008
1012
  if (users.length === 0)
1009
- return {};
1013
+ return refuse("no users in setup.json");
1010
1014
  const login = typeof loginHeader === "string" ? loginHeader.trim() : "";
1011
1015
  if (login) {
1012
1016
  const user = users.find(u => u.login === login);
1013
- if (user && PasswordHash_1.PasswordHash.isHash(user.password))
1014
- return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user } : {};
1017
+ if (!user)
1018
+ return refuse(`unknown login ${shown(login)}`);
1019
+ if (PasswordHash_1.PasswordHash.isHash(user.password))
1020
+ return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user } : refuse(`wrong password for ${shown(login)} (or the client's login/password differ from setup.json)`);
1015
1021
  }
1016
1022
  let plainMatch = null;
1017
1023
  for (const user of users) {
@@ -1026,8 +1032,8 @@ class DeployerService extends BaseService_1.BaseService {
1026
1032
  return {};
1027
1033
  }
1028
1034
  if (!login)
1029
- (0, LogService_1.logWarn)("Deployer auth failed without X-Deployer-Login — update the badmfck CLI on the client");
1030
- return {};
1035
+ return refuse("no X-Deployer-Login header — the client runs an old badmfck CLI; update it");
1036
+ return refuse(`wrong password for ${shown(login)}`);
1031
1037
  }
1032
1038
  static _extractPort(config) {
1033
1039
  if (!config || typeof config !== "object")
@@ -0,0 +1 @@
1
+ export declare function SetupConfigWizard(target?: string): Promise<void>;
@@ -0,0 +1,200 @@
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.SetupConfigWizard = SetupConfigWizard;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const process_1 = require("process");
11
+ const PasswordHash_1 = require("../helper/PasswordHash");
12
+ const IpAllowList_1 = require("../helper/IpAllowList");
13
+ const Validator_1 = require("../helper/Validator");
14
+ const MonitorAuth_1 = require("../monitor/MonitorAuth");
15
+ const DeployerService_1 = require("./DeployerService");
16
+ const HashPassword_1 = require("./HashPassword");
17
+ const cliCommon_1 = require("./cliCommon");
18
+ const cliPrompt_1 = require("./cliPrompt");
19
+ async function SetupConfigWizard(target) {
20
+ const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
21
+ if (!process_1.stdin.isTTY) {
22
+ console.error(red("✗ setup-config needs an interactive terminal — it asks for passwords."));
23
+ process.exit(1);
24
+ }
25
+ let file = target ?? (["setup.json", "projects/setup.json"].find(f => fs_1.default.existsSync(f)) ?? "");
26
+ if (target && fs_1.default.existsSync(target) && fs_1.default.statSync(target).isDirectory())
27
+ file = path_1.default.join(target, "setup.json");
28
+ console.log(bold("\nDeployer setup.json") + dim(" (the deployer re-reads it on change)"));
29
+ file = path_1.default.resolve(file || await (0, cliPrompt_1.ask)("File", "setup.json"));
30
+ let doc = { users: [] };
31
+ if (fs_1.default.existsSync(file)) {
32
+ try {
33
+ doc = JSON.parse(fs_1.default.readFileSync(file, "utf-8") || "{}");
34
+ }
35
+ catch (e) {
36
+ console.error(red(`✗ ${file} is not valid JSON (${e?.message ?? e}).`));
37
+ process.exit(1);
38
+ }
39
+ console.log(dim(` Loaded ${file}`));
40
+ }
41
+ else {
42
+ console.log(dim(` New file: ${file}`));
43
+ }
44
+ doc.users = Array.isArray(doc.users) ? doc.users : [];
45
+ for (const u of doc.users)
46
+ if (u && u.login === undefined && typeof u.username === "string") {
47
+ u.login = u.username;
48
+ delete u.username;
49
+ console.log(yellow(` ⚠ "${u.login}": old field "username" renamed to "login" — saved with the next save`));
50
+ }
51
+ let changed = false;
52
+ const clientsToUpdate = new Set();
53
+ const show = () => {
54
+ console.log("\n" + bold("Deployer users") + dim(" (in deploy.json: username + password)"));
55
+ if (!doc.users.length)
56
+ console.log(red(" none — nobody can deploy"));
57
+ for (const u of doc.users)
58
+ console.log(` ${String(u.login).padEnd(20)} ${PasswordHash_1.PasswordHash.isHash(u.password) ? dim("hashed password") : red("PLAIN-TEXT password — refused, set a new one or run migrate-configs")}`);
59
+ console.log(bold("Reviewers"));
60
+ if (!doc.reviewers?.length)
61
+ console.log(dim(" none"));
62
+ for (const r of doc.reviewers ?? [])
63
+ console.log(` ${String(r.login).padEnd(20)} ${String(r.email ?? "").padEnd(28)} ${PasswordHash_1.PasswordHash.isHash(r.password) ? dim("hashed password") : red("PLAIN-TEXT password")}`);
64
+ console.log(bold("Allowed addresses") + " " + (doc.allowed_ips?.length ? doc.allowed_ips.join(", ") : dim("any address")));
65
+ console.log(bold("Review page URL") + " " + (doc.review_url || dim("not set")));
66
+ };
67
+ const user = (login) => doc.users.find((u) => u.login === login);
68
+ const reviewer = (login) => (doc.reviewers ?? []).find((r) => r.login === login);
69
+ async function password(question) {
70
+ for (;;) {
71
+ const p1 = await (0, HashPassword_1.askHidden)(` ${question} (hidden, 12+ characters): `);
72
+ const policy = MonitorAuth_1.MonitorAuth.passwordPolicyError(p1);
73
+ if (policy) {
74
+ console.log(red(` ✗ ${policy}`));
75
+ continue;
76
+ }
77
+ const p2 = await (0, HashPassword_1.askHidden)(" repeat: ");
78
+ if (p1 !== p2) {
79
+ console.log(red(" ✗ passwords do not match"));
80
+ continue;
81
+ }
82
+ return p1;
83
+ }
84
+ }
85
+ const deployerHash = (login, pw) => PasswordHash_1.PasswordHash.hash(crypto_1.default.createHash("sha256").update(login + ":" + pw).digest("hex"));
86
+ const validLogin = (v) => /^[A-Za-z0-9._@-]+$/.test(v) ? null : "letters, digits, '.', '_', '-', '@' only";
87
+ const actions = {
88
+ "1": { title: "add a deployer user", run: async () => {
89
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => !v ? "required" : user(v) ? "already exists" : validLogin(v));
90
+ doc.users.push({ login, password: await deployerHash(login, await password(`password for ${login}`)) });
91
+ clientsToUpdate.add(login);
92
+ console.log(green(` ✓ ${login} added`));
93
+ changed = true;
94
+ } },
95
+ "2": { title: "change a deployer user's password", run: async () => {
96
+ const u = user(await (0, cliPrompt_1.askValid)(" login", "", v => user(v) ? null : "no such user"));
97
+ u.password = await deployerHash(u.login, await password(`new password for ${u.login}`));
98
+ clientsToUpdate.add(u.login);
99
+ console.log(green(` ✓ password of ${u.login} changed`));
100
+ changed = true;
101
+ } },
102
+ "3": { title: "rename a deployer user", run: async () => {
103
+ const u = user(await (0, cliPrompt_1.askValid)(" current login", "", v => user(v) ? null : "no such user"));
104
+ const login = await (0, cliPrompt_1.askValid)(" new login", "", v => !v ? "required" : user(v) ? "already exists" : validLogin(v));
105
+ u.password = await deployerHash(login, await password(`password for ${login} (the same or a new one)`));
106
+ clientsToUpdate.delete(u.login);
107
+ u.login = login;
108
+ clientsToUpdate.add(login);
109
+ console.log(green(` ✓ renamed to ${login}`));
110
+ changed = true;
111
+ } },
112
+ "4": { title: "remove a deployer user", run: async () => {
113
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => user(v) ? null : "no such user");
114
+ if (doc.users.length === 1)
115
+ console.log(yellow(" ⚠ This is the last user — nobody will be able to deploy."));
116
+ if (!(await (0, cliPrompt_1.yes)(` remove ${login}?`, false)))
117
+ return;
118
+ doc.users = doc.users.filter((u) => u.login !== login);
119
+ clientsToUpdate.delete(login);
120
+ console.log(green(` ✓ ${login} removed`));
121
+ changed = true;
122
+ } },
123
+ "5": { title: "add a reviewer", run: async () => {
124
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => !v ? "required" : reviewer(v) ? "already exists" : validLogin(v));
125
+ const email = await (0, cliPrompt_1.askValid)(" email (gets the review links)", "", v => /^[^\s@]+@[^\s@]+$/.test(v) ? null : "an email address");
126
+ doc.reviewers = [...(doc.reviewers ?? []), { login, password: await PasswordHash_1.PasswordHash.hash(await password(`password for ${login}`)), email }];
127
+ console.log(green(` ✓ reviewer ${login} added`) + dim(" — 2FA is set up at the first sign-in on the review page"));
128
+ changed = true;
129
+ } },
130
+ "6": { title: "change a reviewer's password or email", run: async () => {
131
+ const r = reviewer(await (0, cliPrompt_1.askValid)(" login", "", v => reviewer(v) ? null : "no such reviewer"));
132
+ r.email = await (0, cliPrompt_1.askValid)(" email", r.email ?? "", v => /^[^\s@]+@[^\s@]+$/.test(v) ? null : "an email address");
133
+ if (await (0, cliPrompt_1.yes)(" set a new password?", false))
134
+ r.password = await PasswordHash_1.PasswordHash.hash(await password(`new password for ${r.login}`));
135
+ console.log(green(` ✓ ${r.login} updated`));
136
+ changed = true;
137
+ } },
138
+ "7": { title: "remove a reviewer", run: async () => {
139
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => reviewer(v) ? null : "no such reviewer");
140
+ if (!(await (0, cliPrompt_1.yes)(` remove ${login}? Projects that list them can't be uploaded until their config is changed`, false)))
141
+ return;
142
+ doc.reviewers = doc.reviewers.filter((r) => r.login !== login);
143
+ if (!doc.reviewers.length)
144
+ delete doc.reviewers;
145
+ console.log(green(` ✓ ${login} removed`));
146
+ changed = true;
147
+ } },
148
+ "8": { title: "set allowed addresses", run: async () => {
149
+ const v = await (0, cliPrompt_1.askValid)(" IPs and subnets, comma-separated (empty = any address)", (doc.allowed_ips ?? []).join(", "), x => IpAllowList_1.IpAllowList.build((0, cliPrompt_1.list)(x)).error ?? null);
150
+ const ips = (0, cliPrompt_1.list)(v);
151
+ if (ips.length)
152
+ doc.allowed_ips = ips;
153
+ else
154
+ delete doc.allowed_ips;
155
+ if (ips.includes("127.0.0.1") || ips.includes("::1"))
156
+ console.log(yellow(" ⚠ Behind a proxy on this host, loopback lets every request through — use the clients' real addresses."));
157
+ changed = true;
158
+ } },
159
+ "9": { title: "set the review page URL", run: async () => {
160
+ const v = await (0, cliPrompt_1.askValid)(" URL (empty = none)", doc.review_url ?? "", x => !x || /^https?:\/\/\S+$/.test(x) ? null : "an http(s) URL");
161
+ if (v)
162
+ doc.review_url = v;
163
+ else
164
+ delete doc.review_url;
165
+ changed = true;
166
+ } },
167
+ };
168
+ for (;;) {
169
+ show();
170
+ console.log("\n" + Object.entries(actions).map(([k, a]) => ` ${k}) ${a.title}`).join("\n") + `\n s) save and exit\n q) quit without saving`);
171
+ const choice = (await (0, cliPrompt_1.ask)("Choose", "")).toLowerCase();
172
+ if (choice === "q") {
173
+ if (changed && !(await (0, cliPrompt_1.yes)("Discard the changes?", false)))
174
+ continue;
175
+ return;
176
+ }
177
+ if (choice === "s") {
178
+ const errors = await Validator_1.Validator.validateStructure(DeployerService_1.SETUP_MODEL, doc);
179
+ if (errors && errors.length) {
180
+ console.log(red(` ✗ Not saved — the deployer would refuse it: ${errors.join("; ")}`));
181
+ continue;
182
+ }
183
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
184
+ const tmp = file + ".tmp";
185
+ fs_1.default.writeFileSync(tmp, JSON.stringify(doc, null, 4) + "\n", { encoding: "utf-8", mode: 0o600 });
186
+ fs_1.default.chmodSync(tmp, 0o600);
187
+ fs_1.default.renameSync(tmp, file);
188
+ console.log(green(`✓ Saved ${file}`) + dim(" (0600) — a running deployer picks it up within a second"));
189
+ if (clientsToUpdate.size)
190
+ console.log(yellow(` Update deploy.json wherever these users deploy from (username + password): ${[...clientsToUpdate].join(", ")}`));
191
+ return;
192
+ }
193
+ const action = actions[choice];
194
+ if (!action) {
195
+ console.log(red(" ✗ choose a number, s or q"));
196
+ continue;
197
+ }
198
+ await action.run();
199
+ }
200
+ }
@@ -11,6 +11,7 @@ const HashPassword_1 = require("./HashPassword");
11
11
  const ProjectConfigWizard_1 = require("./ProjectConfigWizard");
12
12
  const AccessConfigWizard_1 = require("./AccessConfigWizard");
13
13
  const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
14
+ const SetupConfigWizard_1 = require("./SetupConfigWizard");
14
15
  function usage() {
15
16
  console.error("Usage:");
16
17
  console.error(" badmfck deploy [config.json] — build + upload the current project");
@@ -23,6 +24,7 @@ function usage() {
23
24
  console.error(" badmfck project-config — build a project config for the deployer, step by step");
24
25
  console.error(" badmfck access-config [file] — create or edit access.json (found in the project's code if omitted)");
25
26
  console.error(" badmfck migrate-configs [folder] [--yes] — hash the secrets of old setup.json, project configs and access.json files");
27
+ console.error(" badmfck setup-config [file|folder] — edit the deployer's setup.json: users, reviewers, allowed IPs");
26
28
  console.error("");
27
29
  console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
28
30
  console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
@@ -109,6 +111,14 @@ async function main() {
109
111
  await (0, HashPassword_1.HashPassword)(rest.includes("--deployer") ? "deployer" : "monitor");
110
112
  break;
111
113
  }
114
+ case "setup-config": {
115
+ if (rest.length > 1) {
116
+ console.error("Usage: badmfck setup-config [file|folder]");
117
+ process.exit(1);
118
+ }
119
+ await (0, SetupConfigWizard_1.SetupConfigWizard)(rest[0]);
120
+ break;
121
+ }
112
122
  case "migrate-configs": {
113
123
  const assumeYes = rest.includes("--yes") || rest.includes("-y");
114
124
  const folders = rest.filter(a => a !== "--yes" && a !== "-y");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badmfck-api-server",
3
- "version": "6.0.9",
3
+ "version": "6.0.10",
4
4
  "description": "Simple API http server based on express",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",