badmfck-api-server 6.0.11 → 6.0.13

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 (64) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +247 -79
  3. package/dist/apiServer/APIService.d.ts +3 -1
  4. package/dist/apiServer/APIService.js +25 -1
  5. package/dist/apiServer/LogService.d.ts +2 -0
  6. package/dist/apiServer/LogService.js +10 -8
  7. package/dist/apiServer/MonitorService.d.ts +4 -1
  8. package/dist/apiServer/MonitorService.js +28 -5
  9. package/dist/apiServer/deployment/Activate.js +2 -6
  10. package/dist/apiServer/deployment/Backups.js +3 -2
  11. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  12. package/dist/apiServer/deployment/Bundler.js +178 -0
  13. package/dist/apiServer/deployment/ConfigService.d.ts +6 -0
  14. package/dist/apiServer/deployment/ConfigService.js +17 -1
  15. package/dist/apiServer/deployment/Deploy.js +101 -57
  16. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  17. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  18. package/dist/apiServer/deployment/Deployer.d.ts +1 -0
  19. package/dist/apiServer/deployment/Deployer.js +7 -5
  20. package/dist/apiServer/deployment/DeployerService.d.ts +27 -2
  21. package/dist/apiServer/deployment/DeployerService.js +129 -30
  22. package/dist/apiServer/deployment/HashPassword.js +2 -2
  23. package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
  24. package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
  25. package/dist/apiServer/deployment/Restore.js +9 -8
  26. package/dist/apiServer/deployment/SecretsInjector.js +2 -1
  27. package/dist/apiServer/deployment/SetupConfigWizard.js +38 -2
  28. package/dist/apiServer/deployment/Status.js +5 -8
  29. package/dist/apiServer/deployment/Watchdog.js +1 -1
  30. package/dist/apiServer/deployment/Wizards.js +16 -11
  31. package/dist/apiServer/deployment/cli.js +33 -14
  32. package/dist/apiServer/deployment/cliCommon.d.ts +13 -1
  33. package/dist/apiServer/deployment/cliCommon.js +50 -2
  34. package/dist/apiServer/deployment/resolveConfig.d.ts +4 -1
  35. package/dist/apiServer/deployment/resolveConfig.js +23 -2
  36. package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
  37. package/dist/apiServer/external/MicroserviceClient.js +90 -10
  38. package/dist/apiServer/external/MicroserviceHost.d.ts +35 -8
  39. package/dist/apiServer/external/MicroserviceHost.js +148 -55
  40. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  41. package/dist/apiServer/helper/AppDataPath.js +81 -0
  42. package/dist/apiServer/helper/ClientIp.d.ts +1 -0
  43. package/dist/apiServer/helper/ClientIp.js +5 -0
  44. package/dist/apiServer/helper/Trace.d.ts +8 -0
  45. package/dist/apiServer/helper/Trace.js +30 -0
  46. package/dist/apiServer/helper/Validator.d.ts +1 -0
  47. package/dist/apiServer/helper/Validator.js +21 -18
  48. package/dist/apiServer/http/Http.d.ts +1 -0
  49. package/dist/apiServer/http/Http.js +5 -2
  50. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  51. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  52. package/dist/apiServer/monitor/MonitorAuth.js +8 -5
  53. package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
  54. package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
  55. package/dist/apiServer/monitor/index.html +66 -66
  56. package/dist/apiServer/security/BlockedIps.js +10 -14
  57. package/dist/apiServer/structures/Interfaces.d.ts +2 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.js +5 -1
  60. package/package.json +21 -6
  61. package/bluegreen.help.md +0 -392
  62. package/cocroach.help.md +0 -191
  63. package/connections.help.md +0 -0
  64. package/monitoring.help.md +0 -350
@@ -0,0 +1,150 @@
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.InterceptorSignedAuth = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const JSONStableStringify_1 = require("../helper/JSONStableStringify");
10
+ const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
11
+ const SCHEME = "signature ";
12
+ const VERSION = "badmfck-sig-v1";
13
+ class InterceptorSignedAuth {
14
+ resolveKey;
15
+ static TS_PAST_SEC = 300;
16
+ static TS_FUTURE_SEC = 60;
17
+ static NONCE_MAX = 100_000;
18
+ nonceSeen = new Map();
19
+ constructor(resolveKey) {
20
+ this.resolveKey = resolveKey;
21
+ }
22
+ async intercept(req) {
23
+ const v = await this.verify(req);
24
+ if (!v.kid)
25
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: v.present ? "Invalid signature" : "Signature required" };
26
+ return { kid: v.kid };
27
+ }
28
+ async verify(req) {
29
+ const header = String(req.headers?.["authorization"] ?? "");
30
+ if (!header.toLowerCase().startsWith(SCHEME))
31
+ return { present: false };
32
+ const p = InterceptorSignedAuth.parseHeader(header.slice(SCHEME.length));
33
+ if (!p.kid || !p.ts || !p.nonce || !p.sig)
34
+ return { present: true, error: "malformed Signature header" };
35
+ if (!/^[A-Za-z0-9._@-]{1,128}$/.test(p.kid))
36
+ return { present: true, error: "malformed key id" };
37
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(p.nonce))
38
+ return { present: true, error: "malformed nonce" };
39
+ if (!/^\d{13}$/.test(p.ts))
40
+ return { present: true, error: "ts must be epoch milliseconds (13 digits)" };
41
+ const now = Date.now();
42
+ const delta = Math.round((Number(p.ts) - now) / 1000);
43
+ if (delta < -InterceptorSignedAuth.TS_PAST_SEC || delta > InterceptorSignedAuth.TS_FUTURE_SEC)
44
+ return { present: true, error: `ts out of window: off by ${delta}s — check the client's clock` };
45
+ this.purge(now);
46
+ const nonceKey = p.kid + ":" + p.nonce;
47
+ if (this.nonceSeen.has(nonceKey))
48
+ return { present: true, error: "nonce already used (replayed request)" };
49
+ const publicKey = await this.resolveKey(p.kid);
50
+ if (!publicKey)
51
+ return { present: true, error: `unknown key id "${p.kid}"` };
52
+ let key;
53
+ try {
54
+ key = crypto_1.default.createPublicKey({ key: Buffer.from(publicKey, "base64"), format: "der", type: "spki" });
55
+ }
56
+ catch {
57
+ return { present: true, error: `the public key of "${p.kid}" is not a valid Ed25519 key` };
58
+ }
59
+ const raw = req.raw ?? {};
60
+ const path = InterceptorSignedAuth.pathOf(raw.originalUrl ?? raw.url ?? req.endpoint ?? "");
61
+ const files = {};
62
+ for (const [field, f] of Object.entries((raw.files ?? {}))) {
63
+ const one = Array.isArray(f) ? f[0] : f;
64
+ files[field] = await InterceptorSignedAuth.hashUpload(one);
65
+ }
66
+ const data = { ...(raw.body ?? {}), ...(raw.query ?? {}) };
67
+ const message = InterceptorSignedAuth.message(String(req.method ?? raw.method ?? "").toUpperCase(), path, p.ts, p.nonce, data, files);
68
+ let ok = false;
69
+ try {
70
+ ok = crypto_1.default.verify(null, Buffer.from(message), key, Buffer.from(p.sig, "base64"));
71
+ }
72
+ catch {
73
+ ok = false;
74
+ }
75
+ if (!ok)
76
+ return { present: true, error: "signature does not match (wrong key, or the request was changed)" };
77
+ this.nonceSeen.set(nonceKey, now + (InterceptorSignedAuth.TS_PAST_SEC + InterceptorSignedAuth.TS_FUTURE_SEC) * 1000);
78
+ return { present: true, kid: p.kid };
79
+ }
80
+ purge(now) {
81
+ for (const [k, exp] of this.nonceSeen) {
82
+ if (exp > now)
83
+ break;
84
+ this.nonceSeen.delete(k);
85
+ }
86
+ while (this.nonceSeen.size > InterceptorSignedAuth.NONCE_MAX) {
87
+ const oldest = this.nonceSeen.keys().next().value;
88
+ if (oldest === undefined)
89
+ break;
90
+ this.nonceSeen.delete(oldest);
91
+ }
92
+ }
93
+ static parseHeader(s) {
94
+ const out = {};
95
+ for (const part of s.split(",")) {
96
+ const eq = part.indexOf("=");
97
+ if (eq < 1)
98
+ continue;
99
+ let v = part.slice(eq + 1).trim();
100
+ if (v.length > 1 && ((v[0] === '"' && v.endsWith('"')) || (v[0] === "'" && v.endsWith("'"))))
101
+ v = v.slice(1, -1);
102
+ out[part.slice(0, eq).trim().toLowerCase()] = v;
103
+ }
104
+ return out;
105
+ }
106
+ static async hashUpload(f) {
107
+ if (f?.tempFilePath)
108
+ return InterceptorSignedAuth.sha256File(f.tempFilePath);
109
+ return crypto_1.default.createHash("sha256").update(f?.data ?? Buffer.alloc(0)).digest("hex");
110
+ }
111
+ static pathOf(url) {
112
+ try {
113
+ return new URL(url, "http://localhost").pathname;
114
+ }
115
+ catch {
116
+ return url;
117
+ }
118
+ }
119
+ static message(method, path, ts, nonce, data, files) {
120
+ const payload = (0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ data: data ?? {}, files })));
121
+ const digest = crypto_1.default.createHash("sha256").update(payload).digest("hex");
122
+ return [VERSION, method, path, ts, nonce, digest].join("\n");
123
+ }
124
+ static sha256File(file) {
125
+ return new Promise((resolve, reject) => {
126
+ const h = crypto_1.default.createHash("sha256");
127
+ fs_1.default.createReadStream(file).on("data", d => h.update(d)).on("error", reject).on("end", () => resolve(h.digest("hex")));
128
+ });
129
+ }
130
+ static generateKeyPair() {
131
+ const { publicKey, privateKey } = crypto_1.default.generateKeyPairSync("ed25519");
132
+ return {
133
+ publicKey: publicKey.export({ format: "der", type: "spki" }).toString("base64"),
134
+ privateKey: privateKey.export({ format: "der", type: "pkcs8" }).toString("base64"),
135
+ };
136
+ }
137
+ static publicKeyOf(privateKey) {
138
+ const key = crypto_1.default.createPrivateKey({ key: Buffer.from(privateKey, "base64"), format: "der", type: "pkcs8" });
139
+ return crypto_1.default.createPublicKey(key).export({ format: "der", type: "spki" }).toString("base64");
140
+ }
141
+ static sign(o) {
142
+ const key = crypto_1.default.createPrivateKey({ key: Buffer.from(o.privateKey, "base64"), format: "der", type: "pkcs8" });
143
+ const ts = String(Date.now());
144
+ const nonce = o.nonce ?? crypto_1.default.randomBytes(18).toString("base64url");
145
+ const message = InterceptorSignedAuth.message(o.method.toUpperCase(), InterceptorSignedAuth.pathOf(o.url), ts, nonce, o.data ?? {}, o.files ?? {});
146
+ const sig = crypto_1.default.sign(null, Buffer.from(message), key).toString("base64");
147
+ return `Signature kid="${o.kid}", ts="${ts}", nonce="${nonce}", sig="${sig}"`;
148
+ }
149
+ }
150
+ exports.InterceptorSignedAuth = InterceptorSignedAuth;
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.MonitorAuth = void 0;
7
7
  const crypto_1 = __importDefault(require("crypto"));
8
+ const AppDataPath_1 = require("../helper/AppDataPath");
8
9
  const fs_1 = __importDefault(require("fs"));
9
10
  const path_1 = __importDefault(require("path"));
10
11
  const LogService_1 = require("../LogService");
@@ -40,8 +41,10 @@ class MonitorAuth {
40
41
  MonitorAuth.authFile = authFile;
41
42
  else if (authDir && authDir.length > 0)
42
43
  MonitorAuth.authFile = path_1.default.join(authDir, `monitor-2fa.${MonitorAuth.fileSafe(project ?? "")}.json`);
43
- else
44
- MonitorAuth.authFile = null;
44
+ else {
45
+ const dir = AppDataPath_1.AppData.dir("");
46
+ MonitorAuth.authFile = dir ? path_1.default.join(dir, "monitor-2fa.json") : null;
47
+ }
45
48
  MonitorAuth.projectKey = (project && project.length > 0 ? project : "default");
46
49
  MonitorAuth.stopWatchingStore();
47
50
  MonitorAuth.enrolled.clear();
@@ -51,7 +54,7 @@ class MonitorAuth {
51
54
  MonitorAuth.storeLoaded = false;
52
55
  MonitorAuth.loadStore();
53
56
  if (!MonitorAuth.authFile)
54
- (0, LogService_1.logWarn)("Monitor 2FA: neither monitorAuthFile nor monitorAuthDir is set — enrollments live in memory only and are LOST on restart");
57
+ (0, LogService_1.logWarn)(`Monitor 2FA: no monitorAuthFile / monitorAuthDir and ${AppDataPath_1.AppData.root()} can't be created — enrollments live in memory only and are LOST on restart`);
55
58
  }
56
59
  static storeHash = "";
57
60
  static refusedHash = "";
@@ -262,7 +265,7 @@ class MonitorAuth {
262
265
  }
263
266
  return out;
264
267
  }
265
- static PLAINTEXT_ERROR = "password is built incorrectly — the config must hold a hash from `npx badmfck hash-password`, not the password itself";
268
+ static PLAINTEXT_ERROR = "password is built incorrectly — the config must hold a hash from `npx bmfk hash-password`, not the password itself";
266
269
  static plaintextLogins(users) {
267
270
  return (users || []).filter(u => u?.login && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
268
271
  }
@@ -376,7 +379,7 @@ class MonitorAuth {
376
379
  const matches = typeof candidate.password === "string" && candidate.password.length > 0
377
380
  && MonitorAuth.sameSecret(candidate.password, password || "");
378
381
  if (matches)
379
- (0, LogService_1.logError)(`Monitor: "${login}" signed in with the right password, but it is stored in the config as plain text — refused; store a hash: npx badmfck hash-password`);
382
+ (0, LogService_1.logError)(`Monitor: "${login}" signed in with the right password, but it is stored in the config as plain text — refused; store a hash: npx bmfk hash-password`);
380
383
  MonitorAuth.registerFailure(login);
381
384
  return { error: "Invalid user" };
382
385
  }
@@ -27,6 +27,14 @@ export declare class ThreatMonitor {
27
27
  static MAX_BODY_SCAN: number;
28
28
  private static records;
29
29
  private static events;
30
+ static SAVE_EVERY_MS: number;
31
+ private static file;
32
+ private static writer;
33
+ private static dirty;
34
+ private static timer;
35
+ static configure(file: string | null): void;
36
+ static save(): boolean;
37
+ private static load;
30
38
  private static decayed;
31
39
  static levelOf(score: number): TThreatLevel;
32
40
  private static rank;
@@ -1,7 +1,13 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.ThreatMonitor = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
4
9
  const LogService_1 = require("../LogService");
10
+ const AppDataPath_1 = require("../helper/AppDataPath");
5
11
  const SCANNER_PATHS = [
6
12
  /\/\.(?:env|git|svn|hg|aws|ssh|DS_Store|htaccess|htpasswd|npmrc|dockerenv)(?:[\/.]|$)/i,
7
13
  /\/wp-(?:login|admin|content|includes|config|json)/i,
@@ -32,6 +38,85 @@ class ThreatMonitor {
32
38
  static MAX_BODY_SCAN = 8 * 1024;
33
39
  static records = new Map();
34
40
  static events = [];
41
+ static SAVE_EVERY_MS = 60_000;
42
+ static file = null;
43
+ static writer = false;
44
+ static dirty = false;
45
+ static timer = null;
46
+ static configure(file) {
47
+ ThreatMonitor.file = file;
48
+ if (!file)
49
+ return;
50
+ ThreatMonitor.load();
51
+ (0, AppDataPath_1.onWriterChange)(writer => {
52
+ ThreatMonitor.writer = writer;
53
+ if (writer)
54
+ ThreatMonitor.load();
55
+ });
56
+ if (!ThreatMonitor.timer) {
57
+ ThreatMonitor.timer = setInterval(() => ThreatMonitor.save(), ThreatMonitor.SAVE_EVERY_MS);
58
+ ThreatMonitor.timer.unref?.();
59
+ }
60
+ }
61
+ static save() {
62
+ const file = ThreatMonitor.file;
63
+ if (!file || !ThreatMonitor.writer || !ThreatMonitor.dirty)
64
+ return false;
65
+ try {
66
+ const doc = {
67
+ version: 1,
68
+ savedAt: Date.now(),
69
+ records: Array.from(ThreatMonitor.records.values()).map(r => ({ ...r, notFound: Array.from(r.notFound.entries()) })),
70
+ events: ThreatMonitor.events,
71
+ };
72
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true, mode: 0o700 });
73
+ const tmp = file + ".tmp";
74
+ fs_1.default.writeFileSync(tmp, JSON.stringify(doc), { mode: 0o600 });
75
+ fs_1.default.renameSync(tmp, file);
76
+ ThreatMonitor.dirty = false;
77
+ return true;
78
+ }
79
+ catch (e) {
80
+ (0, LogService_1.logWarn)("threats: cannot save " + file + ": " + (e?.message ?? e));
81
+ return false;
82
+ }
83
+ }
84
+ static load() {
85
+ const file = ThreatMonitor.file;
86
+ if (!file || !fs_1.default.existsSync(file))
87
+ return;
88
+ let doc;
89
+ try {
90
+ doc = JSON.parse(fs_1.default.readFileSync(file, "utf-8"));
91
+ }
92
+ catch (e) {
93
+ (0, LogService_1.logWarn)("threats: cannot read " + file + ": " + (e?.message ?? e));
94
+ return;
95
+ }
96
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
97
+ for (const raw of Array.isArray(doc?.records) ? doc.records : []) {
98
+ if (!raw || typeof raw.ip !== "string")
99
+ continue;
100
+ const mine = ThreatMonitor.records.get(raw.ip);
101
+ if (mine && mine.lastSeen >= num(raw.lastSeen))
102
+ continue;
103
+ ThreatMonitor.records.set(raw.ip, {
104
+ ip: raw.ip, score: num(raw.score), scoreAt: num(raw.scoreAt),
105
+ firstSeen: num(raw.firstSeen), lastSeen: num(raw.lastSeen), hits: num(raw.hits),
106
+ categories: raw.categories && typeof raw.categories === "object" ? raw.categories : {},
107
+ ua: typeof raw.ua === "string" ? raw.ua : null,
108
+ samples: Array.isArray(raw.samples) ? raw.samples.slice(-10) : [],
109
+ notFound: new Map(Array.isArray(raw.notFound) ? raw.notFound : []),
110
+ enumFlaggedAt: num(raw.enumFlaggedAt),
111
+ });
112
+ }
113
+ const sorted = Array.from(ThreatMonitor.records.values()).sort((a, b) => a.lastSeen - b.lastSeen);
114
+ ThreatMonitor.records = new Map(sorted.slice(-ThreatMonitor.MAX_IPS).map(r => [r.ip, r]));
115
+ const seen = new Set(ThreatMonitor.events.map(e => `${e.ts}|${e.ip}|${e.url}`));
116
+ const incoming = (Array.isArray(doc?.events) ? doc.events : [])
117
+ .filter((e) => e && typeof e.ip === "string" && typeof e.ts === "number" && !seen.has(`${e.ts}|${e.ip}|${e.url}`));
118
+ ThreatMonitor.events = ThreatMonitor.events.concat(incoming).sort((a, b) => a.ts - b.ts).slice(-ThreatMonitor.MAX_EVENTS);
119
+ }
35
120
  static decayed(r, now) {
36
121
  return r.score * Math.pow(0.5, (now - r.scoreAt) / ThreatMonitor.HALF_LIFE_MS);
37
122
  }
@@ -112,6 +197,7 @@ class ThreatMonitor {
112
197
  if (r.samples.length > 10)
113
198
  r.samples.shift();
114
199
  ThreatMonitor.records.set(o.ip, r);
200
+ ThreatMonitor.dirty = true;
115
201
  while (ThreatMonitor.records.size > ThreatMonitor.MAX_IPS)
116
202
  ThreatMonitor.records.delete(ThreatMonitor.records.keys().next().value);
117
203
  if (add >= WEIGHT.auth) {
@@ -148,6 +234,6 @@ class ThreatMonitor {
148
234
  recent: ThreatMonitor.events.slice(-Math.max(1, Math.min(limit, 500))).reverse(),
149
235
  };
150
236
  }
151
- static reset() { ThreatMonitor.records.clear(); ThreatMonitor.events = []; }
237
+ static reset() { ThreatMonitor.records.clear(); ThreatMonitor.events = []; ThreatMonitor.dirty = true; }
152
238
  }
153
239
  exports.ThreatMonitor = ThreatMonitor;