badmfck-api-server 6.0.12 → 6.0.14

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 (60) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/README.md +213 -73
  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/Bundler.d.ts +12 -0
  10. package/dist/apiServer/deployment/Bundler.js +178 -0
  11. package/dist/apiServer/deployment/ConfigService.d.ts +7 -0
  12. package/dist/apiServer/deployment/ConfigService.js +24 -1
  13. package/dist/apiServer/deployment/Deploy.js +96 -54
  14. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +1 -0
  15. package/dist/apiServer/deployment/DeployKeyWizard.js +17 -1
  16. package/dist/apiServer/deployment/DeployerService.d.ts +4 -1
  17. package/dist/apiServer/deployment/DeployerService.js +87 -18
  18. package/dist/apiServer/deployment/HashPassword.js +2 -2
  19. package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
  20. package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
  21. package/dist/apiServer/deployment/Restore.js +5 -5
  22. package/dist/apiServer/deployment/SecretsInjector.js +2 -1
  23. package/dist/apiServer/deployment/SetupConfigWizard.js +1 -1
  24. package/dist/apiServer/deployment/Status.js +1 -1
  25. package/dist/apiServer/deployment/Watchdog.js +1 -1
  26. package/dist/apiServer/deployment/Wizards.js +11 -11
  27. package/dist/apiServer/deployment/cli.js +25 -16
  28. package/dist/apiServer/deployment/cliCommon.d.ts +12 -0
  29. package/dist/apiServer/deployment/cliCommon.js +44 -0
  30. package/dist/apiServer/deployment/resolveConfig.d.ts +2 -0
  31. package/dist/apiServer/deployment/resolveConfig.js +10 -0
  32. package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
  33. package/dist/apiServer/external/MicroserviceClient.js +90 -10
  34. package/dist/apiServer/external/MicroserviceHost.d.ts +36 -8
  35. package/dist/apiServer/external/MicroserviceHost.js +166 -55
  36. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  37. package/dist/apiServer/helper/AppDataPath.js +81 -0
  38. package/dist/apiServer/helper/ClientIp.d.ts +1 -0
  39. package/dist/apiServer/helper/ClientIp.js +5 -0
  40. package/dist/apiServer/helper/Trace.d.ts +8 -0
  41. package/dist/apiServer/helper/Trace.js +30 -0
  42. package/dist/apiServer/helper/Validator.d.ts +1 -0
  43. package/dist/apiServer/helper/Validator.js +21 -18
  44. package/dist/apiServer/http/Http.d.ts +1 -0
  45. package/dist/apiServer/http/Http.js +5 -2
  46. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +2 -1
  47. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +1 -1
  48. package/dist/apiServer/monitor/MonitorAuth.js +8 -5
  49. package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
  50. package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
  51. package/dist/apiServer/monitor/index.html +66 -66
  52. package/dist/apiServer/security/BlockedIps.js +10 -14
  53. package/dist/apiServer/structures/Interfaces.d.ts +2 -0
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.js +3 -1
  56. package/package.json +21 -6
  57. package/bluegreen.help.md +0 -392
  58. package/cocroach.help.md +0 -191
  59. package/connections.help.md +0 -0
  60. package/monitoring.help.md +0 -350
@@ -36,68 +36,167 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.MicroserviceHost = void 0;
39
+ exports.MicroserviceHost = exports.MemoryJobStore = void 0;
40
40
  const BaseService_1 = require("../BaseService");
41
41
  const DefaultErrors_1 = __importStar(require("../structures/DefaultErrors"));
42
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
43
+ const JSONStableStringify_1 = require("../helper/JSONStableStringify");
44
+ const LogService_1 = require("../LogService");
45
+ const async_hooks_1 = require("async_hooks");
46
+ const Trace_1 = require("../helper/Trace");
42
47
  const crypto_1 = __importDefault(require("crypto"));
48
+ const IpAllowList_1 = require("../helper/IpAllowList");
49
+ class MemoryJobStore {
50
+ #jobs = new Map();
51
+ get(key) { return this.#jobs.get(key) ?? null; }
52
+ set(key, job) { this.#jobs.set(key, job); }
53
+ purge(now) { for (const [k, j] of this.#jobs)
54
+ if (j.expires < now)
55
+ this.#jobs.delete(k); }
56
+ }
57
+ exports.MemoryJobStore = MemoryJobStore;
58
+ const VERSION = 2;
59
+ const ANSWER = "badmfck-ms-v2-answer";
60
+ const JOB_TTL = 1000 * 60 * 5;
43
61
  class MicroserviceHost extends BaseService_1.BaseService {
44
62
  static #calls = new Set();
45
63
  static #instances = new Map();
64
+ static #context = new async_hooks_1.AsyncLocalStorage();
46
65
  options;
47
- jobs = new Map();
66
+ #store;
67
+ #auth = null;
68
+ #allowedIps = new Map();
48
69
  constructor(opt) {
49
70
  super("Microservice-host-" + opt.id);
71
+ if (!opt.clients && !opt.securityKey)
72
+ throw new Error(`MicroserviceHost "${opt.id}": set "clients" (and "privateKey") for signed calls`);
73
+ if (opt.clients) {
74
+ if (!opt.privateKey)
75
+ throw new Error(`MicroserviceHost "${opt.id}": "clients" needs "privateKey" — the host signs its answers`);
76
+ InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(opt.privateKey);
77
+ this.#auth = new InterceptorSignedAuth_1.InterceptorSignedAuth(kid => opt.clients?.[kid]?.publicKey ?? null);
78
+ for (const [kid, c] of Object.entries(opt.clients)) {
79
+ if (c.allowedIps === undefined)
80
+ continue;
81
+ const built = IpAllowList_1.IpAllowList.build(c.allowedIps);
82
+ if (built.error)
83
+ throw new Error(`MicroserviceHost "${opt.id}": clients.${kid}.allowedIps: ${built.error}`);
84
+ if (!built.list)
85
+ throw new Error(`MicroserviceHost "${opt.id}": clients.${kid}.allowedIps is empty — list the addresses, or remove it to allow any`);
86
+ this.#allowedIps.set(kid, built.list);
87
+ }
88
+ }
50
89
  this.options = opt;
90
+ this.#store = opt.jobStore ?? new MemoryJobStore();
51
91
  MicroserviceHost.#instances.set(opt.id, this);
52
92
  }
53
93
  async init() {
54
94
  super.init();
55
95
  setInterval(() => {
56
- const now = Date.now();
57
- for (const [key, job] of this.jobs) {
58
- if (job.expires < now)
59
- this.jobs.delete(key);
60
- }
96
+ Promise.resolve(this.#store.purge(Date.now())).catch(e => (0, LogService_1.logError)("MicroserviceHost job store purge failed", e));
61
97
  }, 1000 * 60 * 5);
62
98
  }
63
99
  static getMicroservice(id) {
64
100
  return MicroserviceHost.#instances.get(id) || null;
65
101
  }
102
+ static currentCall() {
103
+ return MicroserviceHost.#context.getStore() ?? null;
104
+ }
105
+ static answerMessage(hostId, op, nonce, answer) {
106
+ const payload = (0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ result: answer.result, error: answer.error, pending: answer.pending })));
107
+ const digest = crypto_1.default.createHash("sha256").update(payload).digest("hex");
108
+ return [ANSWER, hostId, op, nonce, digest].join("\n");
109
+ }
66
110
  async handleIncomingRequest(req) {
111
+ if (String(req.headers?.["authorization"] ?? "").toLowerCase().startsWith("signature "))
112
+ return this.#handleSigned(req);
113
+ if (this.options.securityKey)
114
+ return this.#handleV1(req);
115
+ return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "signed request required" };
116
+ }
117
+ async #handleSigned(req) {
118
+ if (!this.#auth)
119
+ return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "this host takes no signed calls" };
120
+ const claimed = InterceptorSignedAuth_1.InterceptorSignedAuth.parseHeader(String(req.headers["authorization"]).slice("signature ".length)).kid;
121
+ const ips = claimed ? this.#allowedIps.get(claimed) : undefined;
122
+ if (ips && !IpAllowList_1.IpAllowList.allows(ips, req.ip)) {
123
+ (0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: rejected call — key "${claimed}" from ${req.ip ?? "unknown address"}, not in its allowedIps`);
124
+ return { ...DefaultErrors_1.default.FORBIDDEN, details: "address not allowed" };
125
+ }
126
+ const verdict = await this.#auth.verify(req);
127
+ if (!verdict.kid) {
128
+ (0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: rejected call — ${verdict.error}`);
129
+ return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "invalid signature" };
130
+ }
131
+ const caller = verdict.kid;
132
+ Trace_1.Trace.adopt(req.data?.trace);
133
+ const nonce = InterceptorSignedAuth_1.InterceptorSignedAuth.parseHeader(String(req.headers["authorization"]).slice("signature ".length)).nonce;
134
+ const body = req.data ?? {};
135
+ if (body.v !== VERSION || body.to !== this.options.id)
136
+ return { ...DefaultErrors_1.default.BAD_REQUEST, details: "request is not addressed to this host" };
137
+ if (typeof body.op !== "string" || !/^[A-Za-z0-9._:-]{8,128}$/.test(body.op) || typeof body.requestName !== "string")
138
+ return { ...DefaultErrors_1.default.BAD_REQUEST, details: "op and requestName required" };
139
+ const op = body.op;
140
+ const requestName = body.requestName;
141
+ const answer = (a) => this.#signAnswer(op, nonce, a);
142
+ const allowed = this.options.clients?.[caller]?.requests;
143
+ if (allowed && !allowed.includes(requestName)) {
144
+ (0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: ${caller} may not call ${requestName}`);
145
+ return answer({ error: { ...DefaultErrors_1.default.FORBIDDEN, details: "request not allowed for " + caller } });
146
+ }
147
+ const jobKey = caller + "|" + op;
148
+ const hash = crypto_1.default.createHash("sha256")
149
+ .update((0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ requestName, requestData: body.requestData ?? null }))))
150
+ .digest("hex");
151
+ const job = await this.#store.get(jobKey);
152
+ if (job && job.expires >= Date.now()) {
153
+ if (job.hash && job.hash !== hash)
154
+ return answer({ error: { ...DefaultErrors_1.default.CONFLICT, details: "op was already used for another request" } });
155
+ if (job.status === "processing")
156
+ return answer({ pending: true });
157
+ return DefaultErrors_1.ErrorUtils.isError(job.result) ? answer({ error: job.result }) : answer({ result: job.result });
158
+ }
159
+ const reqCall = this.options.requests.find(r => r.name === requestName);
160
+ if (!reqCall)
161
+ return answer({ error: { ...DefaultErrors_1.default.NOT_FOUND, details: "request not registered: " + requestName } });
162
+ await this.#store.set(jobKey, { status: "processing", hash, expires: Date.now() + JOB_TTL });
163
+ let result;
164
+ try {
165
+ result = await MicroserviceHost.#context.run({ caller, op, requestName }, () => reqCall.request(body.requestData));
166
+ if (DefaultErrors_1.ErrorUtils.isError(result))
167
+ result = MicroserviceHost.#outbound(result);
168
+ }
169
+ catch (e) {
170
+ if (DefaultErrors_1.ErrorUtils.isError(e))
171
+ result = MicroserviceHost.#outbound(e);
172
+ else {
173
+ (0, LogService_1.logError)(`MicroserviceHost ${this.options.id}: ${requestName} from ${caller} threw`, e);
174
+ result = { ...DefaultErrors_1.default.INTERNAL_ERROR };
175
+ }
176
+ }
177
+ await this.#store.set(jobKey, { status: "completed", hash, result, expires: Date.now() + JOB_TTL });
178
+ return DefaultErrors_1.ErrorUtils.isError(result) ? answer({ error: result }) : answer({ result });
179
+ }
180
+ #signAnswer(op, nonce, a) {
181
+ const key = crypto_1.default.createPrivateKey({ key: Buffer.from(this.options.privateKey, "base64"), format: "der", type: "pkcs8" });
182
+ const sig = crypto_1.default.sign(null, Buffer.from(MicroserviceHost.answerMessage(this.options.id, op, nonce, a)), key).toString("base64");
183
+ return { v: VERSION, op, ...a, sig };
184
+ }
185
+ static #outbound(e) {
186
+ const { stack, ...rest } = e;
187
+ return rest;
188
+ }
189
+ async #handleV1(req) {
67
190
  const nonce = req.headers["x-microservice-nonce"];
68
191
  const ts = req.headers["x-microservice-ts"];
69
192
  if (!nonce || !ts)
70
193
  return { ...DefaultErrors_1.default.BAD_REQUEST, details: "missing headers" };
71
- const jobKey = `${nonce}|${ts}`;
72
- const job = this.jobs.get(jobKey);
73
- if (job) {
74
- if (job.expires < Date.now()) {
75
- this.jobs.delete(jobKey);
76
- }
77
- else {
78
- if (job.status === "processing")
79
- return { ...DefaultErrors_1.default.ACCEPTED, details: "request is being processed" };
80
- return job.result;
81
- }
82
- }
83
194
  const requestTime = parseInt(ts);
84
195
  const now = Date.now();
85
196
  if (isNaN(requestTime) || Math.abs(now - requestTime) > 1000 * 60 * 2) {
86
197
  return { ...DefaultErrors_1.default.BAD_REQUEST, details: "timestamp out of range" };
87
198
  }
88
- const callKey = `${nonce}|${ts}`;
89
- if (MicroserviceHost.#calls.has(callKey)) {
90
- return { ...DefaultErrors_1.default.BAD_REQUEST, details: "replay attack detected" };
91
- }
92
- MicroserviceHost.#calls.add(callKey);
93
- if (MicroserviceHost.#calls.size > 5000) {
94
- const iterator = MicroserviceHost.#calls.values();
95
- for (let i = 0; i < 100; i++) {
96
- const val = iterator.next().value;
97
- if (val)
98
- MicroserviceHost.#calls.delete(val);
99
- }
100
- }
199
+ let request;
101
200
  try {
102
201
  const rawSecret = Buffer.from(this.options.securityKey, "base64");
103
202
  const key = crypto_1.default.createHash("sha256").update(rawSecret).digest();
@@ -110,33 +209,45 @@ class MicroserviceHost extends BaseService_1.BaseService {
110
209
  decipher.setAAD(aad);
111
210
  decipher.setAuthTag(tag);
112
211
  const decrypted = Buffer.concat([decipher.update(enc), decipher.final()]);
113
- const request = JSON.parse(decrypted.toString("utf8"));
114
- const reqCall = this.options.requests.find(r => r.name === request?.requestName);
115
- if (!reqCall)
116
- return { ...DefaultErrors_1.default.NOT_FOUND, details: "request not registered: " + request?.requestName };
117
- const job = {
118
- status: "processing",
119
- expires: Date.now() + 1000 * 60 * 5
120
- };
121
- this.jobs.set(jobKey, job);
122
- try {
123
- const result = await reqCall.request(request.requestData);
124
- job.status = "completed";
125
- job.result = result;
126
- return result;
127
- }
128
- catch (e) {
129
- const errText = e instanceof Error ? e.message : "unknown error: " + e;
130
- const errStack = e instanceof Error && e.stack ? e.stack : "";
131
- const err = DefaultErrors_1.ErrorUtils.isError(e) ? e : { ...DefaultErrors_1.default.INTERNAL_ERROR, details: errText, stack: errStack };
132
- job.status = "completed";
133
- job.result = err;
134
- return job.result;
135
- }
212
+ request = JSON.parse(decrypted.toString("utf8"));
136
213
  }
137
214
  catch (e) {
138
215
  return { ...DefaultErrors_1.default.BAD_REQUEST, details: "decryption error" };
139
216
  }
217
+ const jobKey = `${nonce}|${ts}`;
218
+ const job = await this.#store.get(jobKey);
219
+ if (job && job.expires >= Date.now()) {
220
+ if (job.status === "processing")
221
+ return { ...DefaultErrors_1.default.ACCEPTED, details: "request is being processed" };
222
+ return job.result;
223
+ }
224
+ if (MicroserviceHost.#calls.has(jobKey)) {
225
+ return { ...DefaultErrors_1.default.BAD_REQUEST, details: "replay attack detected" };
226
+ }
227
+ MicroserviceHost.#calls.add(jobKey);
228
+ if (MicroserviceHost.#calls.size > 5000) {
229
+ const iterator = MicroserviceHost.#calls.values();
230
+ for (let i = 0; i < 100; i++) {
231
+ const val = iterator.next().value;
232
+ if (val)
233
+ MicroserviceHost.#calls.delete(val);
234
+ }
235
+ }
236
+ const reqCall = this.options.requests.find(r => r.name === request?.requestName);
237
+ if (!reqCall)
238
+ return { ...DefaultErrors_1.default.NOT_FOUND, details: "request not registered: " + request?.requestName };
239
+ await this.#store.set(jobKey, { status: "processing", expires: Date.now() + JOB_TTL });
240
+ let result;
241
+ try {
242
+ result = await reqCall.request(request.requestData);
243
+ }
244
+ catch (e) {
245
+ const errText = e instanceof Error ? e.message : "unknown error: " + e;
246
+ const errStack = e instanceof Error && e.stack ? e.stack : "";
247
+ result = DefaultErrors_1.ErrorUtils.isError(e) ? e : { ...DefaultErrors_1.default.INTERNAL_ERROR, details: errText, stack: errStack };
248
+ }
249
+ await this.#store.set(jobKey, { status: "completed", result, expires: Date.now() + JOB_TTL });
250
+ return result;
140
251
  }
141
252
  }
142
253
  exports.MicroserviceHost = MicroserviceHost;
@@ -0,0 +1,9 @@
1
+ export declare const APP_DATA_ROOT_ENV = "BMFK_DATA_DIR";
2
+ export declare const AppData: {
3
+ project(): string;
4
+ projectDir(name: string): string;
5
+ root(): string;
6
+ dir(sub: string): string | null;
7
+ };
8
+ export declare function appDataPath(name: string, ext?: string): string;
9
+ export declare function onWriterChange(cb: (writer: boolean) => void): boolean;
@@ -0,0 +1,81 @@
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.AppData = exports.APP_DATA_ROOT_ENV = void 0;
7
+ exports.appDataPath = appDataPath;
8
+ exports.onWriterChange = onWriterChange;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const BlueGreenState_1 = require("../deployment/BlueGreenState");
12
+ exports.APP_DATA_ROOT_ENV = "BMFK_DATA_DIR";
13
+ const DEFAULT_ROOT = "/var/bmfk";
14
+ const fileSafe = (s) => s.replace(/^@[^/]+\//, "").replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^[._]+/, "").slice(0, 64);
15
+ function locate() {
16
+ const main = require.main?.filename ?? process.argv[1] ?? process.cwd();
17
+ let dir = path_1.default.dirname(path_1.default.resolve(main));
18
+ let packageRoot = null;
19
+ for (let i = 0; i < 12; i++) {
20
+ const bg = path_1.default.join(dir, ".bluegreen.json");
21
+ if (fs_1.default.existsSync(bg)) {
22
+ let project = null;
23
+ try {
24
+ project = JSON.parse(fs_1.default.readFileSync(bg, "utf-8"))?.project ?? null;
25
+ }
26
+ catch { }
27
+ return { root: path_1.default.dirname(dir), bluegreen: true, project };
28
+ }
29
+ if (!packageRoot && fs_1.default.existsSync(path_1.default.join(dir, "package.json")))
30
+ packageRoot = dir;
31
+ const parent = path_1.default.dirname(dir);
32
+ if (parent === dir)
33
+ break;
34
+ dir = parent;
35
+ }
36
+ const root = packageRoot ?? process.cwd();
37
+ let project = null;
38
+ try {
39
+ project = JSON.parse(fs_1.default.readFileSync(path_1.default.join(root, "package.json"), "utf-8"))?.name ?? null;
40
+ }
41
+ catch { }
42
+ return { root, bluegreen: false, project };
43
+ }
44
+ exports.AppData = {
45
+ project() {
46
+ const loc = locate();
47
+ return fileSafe(loc.project ?? "") || fileSafe(path_1.default.basename(loc.root)) || "app";
48
+ },
49
+ projectDir(name) {
50
+ return path_1.default.join(exports.AppData.root(), fileSafe(name) || "app");
51
+ },
52
+ root() {
53
+ const env = process.env[exports.APP_DATA_ROOT_ENV];
54
+ return path_1.default.resolve(env && env.length > 0 ? env : DEFAULT_ROOT);
55
+ },
56
+ dir(sub) {
57
+ const dir = path_1.default.join(exports.AppData.root(), exports.AppData.project(), sub);
58
+ try {
59
+ fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
60
+ fs_1.default.accessSync(dir, fs_1.default.constants.W_OK);
61
+ return dir;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ },
67
+ };
68
+ function appDataPath(name, ext = "") {
69
+ const loc = locate();
70
+ if (loc.bluegreen)
71
+ return path_1.default.join(loc.root, name + ext);
72
+ return path_1.default.join(path_1.default.dirname(loc.root), `${name}.${path_1.default.basename(loc.root)}${ext}`);
73
+ }
74
+ function onWriterChange(cb) {
75
+ const worker = process.env.NODE_APP_INSTANCE;
76
+ if (worker !== undefined && worker !== "0")
77
+ return false;
78
+ (0, BlueGreenState_1.onLiveChange)(live => cb(live));
79
+ (0, BlueGreenState_1.getBlueGreenActiveState)().catch(() => { });
80
+ return true;
81
+ }
@@ -1,2 +1,3 @@
1
1
  export declare const DEFAULT_TRUSTED_PROXIES: string[];
2
+ export declare function fromTrustedProxy(req: any, trustedProxies?: Set<string>): boolean;
2
3
  export declare function clientIp(req: any, trustedProxies?: Set<string>): string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEFAULT_TRUSTED_PROXIES = void 0;
4
+ exports.fromTrustedProxy = fromTrustedProxy;
4
5
  exports.clientIp = clientIp;
5
6
  exports.DEFAULT_TRUSTED_PROXIES = ["127.0.0.1", "::1"];
6
7
  const norm = (a) => {
@@ -9,6 +10,10 @@ const norm = (a) => {
9
10
  s = s.slice(7);
10
11
  return s;
11
12
  };
13
+ function fromTrustedProxy(req, trustedProxies = new Set(exports.DEFAULT_TRUSTED_PROXIES)) {
14
+ const peer = norm(req?.socket?.remoteAddress ?? req?.connection?.remoteAddress);
15
+ return !!peer && trustedProxies.has(peer);
16
+ }
12
17
  function clientIp(req, trustedProxies = new Set(exports.DEFAULT_TRUSTED_PROXIES)) {
13
18
  const peer = norm(req?.socket?.remoteAddress ?? req?.connection?.remoteAddress);
14
19
  if (!peer)
@@ -0,0 +1,8 @@
1
+ export declare const TRACE_HEADER = "x-request-id";
2
+ export declare const Trace: {
3
+ newId(): string;
4
+ isValid(id: unknown): id is string;
5
+ current(): string | null;
6
+ run<T>(traceId: string, fn: () => T): T;
7
+ adopt(traceId: unknown): void;
8
+ };
@@ -0,0 +1,30 @@
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.Trace = exports.TRACE_HEADER = void 0;
7
+ const async_hooks_1 = require("async_hooks");
8
+ const crypto_1 = __importDefault(require("crypto"));
9
+ exports.TRACE_HEADER = "x-request-id";
10
+ const VALID = /^[A-Za-z0-9._:-]{8,128}$/;
11
+ const storage = new async_hooks_1.AsyncLocalStorage();
12
+ exports.Trace = {
13
+ newId() {
14
+ return crypto_1.default.randomUUID();
15
+ },
16
+ isValid(id) {
17
+ return typeof id === "string" && VALID.test(id);
18
+ },
19
+ current() {
20
+ return storage.getStore()?.traceId ?? null;
21
+ },
22
+ run(traceId, fn) {
23
+ return storage.run({ traceId }, fn);
24
+ },
25
+ adopt(traceId) {
26
+ const ctx = storage.getStore();
27
+ if (ctx && exports.Trace.isValid(traceId))
28
+ ctx.traceId = traceId;
29
+ },
30
+ };
@@ -72,6 +72,7 @@ export type ValidationModel<T> = DeepMutable<{
72
72
  export declare class Validator {
73
73
  static validateObject(fields: string[], object: any): boolean;
74
74
  static documentStructure(structure: any): Record<string, any> | undefined;
75
+ static boundFromKey(structure: Record<string, any>, name: string): number | undefined;
75
76
  static parseStructureOptions(key: string, structure: Record<string, any>): IStructureOptions;
76
77
  static validateStructure(structure: any, object: any, level?: number, parentPath?: string): Promise<string[] | undefined>;
77
78
  static filterStructure(structure: any, object: any): void;
@@ -46,6 +46,13 @@ class Validator {
46
46
  }
47
47
  return params;
48
48
  }
49
+ static boundFromKey(structure, name) {
50
+ const v = structure[name];
51
+ if (v === undefined || v === null || v === "" || typeof v === "boolean")
52
+ return undefined;
53
+ const n = Number(v);
54
+ return isNaN(n) ? undefined : n;
55
+ }
49
56
  static parseStructureOptions(key, structure) {
50
57
  let k = '$__' + key;
51
58
  let s_options = structure[k];
@@ -54,23 +61,19 @@ class Validator {
54
61
  if (typeof s_options === "string")
55
62
  s_options = { details: s_options };
56
63
  k = k + "_";
57
- if (s_options.min == undefined || isNaN(s_options.min)) {
58
- if (structure[key + "min"] && !isNaN(structure[key + "min"]))
59
- s_options.min = parseInt(structure[key + "min"]);
60
- }
64
+ if (s_options.min == undefined || isNaN(s_options.min))
65
+ s_options.min = Validator.boundFromKey(structure, k + "min") ?? s_options.min;
61
66
  if (s_options.ignore_in_documentation === undefined && structure[k + "ignore_in_documentation"] !== undefined)
62
67
  s_options.ignore_in_documentation = structure[k + "ignore_in_documentation"];
63
68
  if (s_options.values === undefined && structure[k + "values"] !== undefined)
64
69
  s_options.values = structure[k + "values"];
65
70
  if (s_options.values === undefined && typeof structure[key] === "string" && structure[key].includes(","))
66
71
  s_options.values = structure[key].split(",").map((v) => v.trim()).filter((v) => v.length > 0);
67
- if (s_options.min && isNaN(s_options.min))
72
+ if (s_options.min !== undefined && isNaN(s_options.min))
68
73
  s_options.min = undefined;
69
- if (s_options.max == undefined || isNaN(s_options.max)) {
70
- if (structure[key + "max"] && !isNaN(structure[key + "max"]))
71
- s_options.max = parseInt(structure[key + "max"]);
72
- }
73
- if (s_options.max && isNaN(s_options.max))
74
+ if (s_options.max == undefined || isNaN(s_options.max))
75
+ s_options.max = Validator.boundFromKey(structure, k + "max") ?? s_options.max;
76
+ if (s_options.max !== undefined && isNaN(s_options.max))
74
77
  s_options.max = undefined;
75
78
  if (s_options && !s_options.type) {
76
79
  let type = typeof structure[key];
@@ -310,11 +313,11 @@ class Validator {
310
313
  }
311
314
  }
312
315
  }
313
- if (typeof structure[i] === "number" && structureOptions.min && !isNaN(structureOptions.min)) {
316
+ if (typeof structure[i] === "number" && structureOptions.min !== undefined && !isNaN(structureOptions.min)) {
314
317
  if (object[i] < structureOptions.min)
315
318
  errors.push("value for field '" + parentPath + i + "' is too small, expected more than " + structureOptions.min + " got: " + object[i]);
316
319
  }
317
- if (typeof structure[i] === "number" && structureOptions.max && !isNaN(structureOptions.max)) {
320
+ if (typeof structure[i] === "number" && structureOptions.max !== undefined && !isNaN(structureOptions.max)) {
318
321
  if (object[i] > structureOptions.max)
319
322
  errors.push("value for field '" + parentPath + i + "' is too big, expected less than " + structureOptions.max + " got: " + object[i]);
320
323
  }
@@ -325,11 +328,11 @@ class Validator {
325
328
  if (object[i].toString().trim().length < min)
326
329
  errors.push("empty value for field '" + parentPath + i + "'");
327
330
  }
328
- if (typeof object[i] === "string" && structureOptions.min && !isNaN(structureOptions.min)) {
331
+ if (typeof object[i] === "string" && structureOptions.min !== undefined && !isNaN(structureOptions.min)) {
329
332
  if (object[i].length < structureOptions.min)
330
333
  errors.push("value length for field '" + parentPath + i + "' is too small, expected more than " + structureOptions.min + " got: " + object[i].length);
331
334
  }
332
- if (typeof object[i] === "string" && structureOptions.max && !isNaN(structureOptions.max)) {
335
+ if (typeof object[i] === "string" && structureOptions.max !== undefined && !isNaN(structureOptions.max)) {
333
336
  if (object[i].length > structureOptions.max)
334
337
  errors.push("value length for field '" + parentPath + i + "' is too big, expected less than " + structureOptions.max + " got: " + object[i].length);
335
338
  }
@@ -521,17 +524,17 @@ class Validator {
521
524
  if (opt.type === "number") {
522
525
  if (typeof value !== "number")
523
526
  return ValidationReport.TYPE_MISSMATCH;
524
- if (opt.max && value > opt.max)
527
+ if (opt.max !== undefined && value > opt.max)
525
528
  return ValidationReport.VALUE_TOO_BIG;
526
- if (opt.min && value < opt.min)
529
+ if (opt.min !== undefined && value < opt.min)
527
530
  return ValidationReport.VALUE_TOO_SHORT;
528
531
  return ValidationReport.OK;
529
532
  }
530
533
  if (typeof value !== "string")
531
534
  return ValidationReport.TYPE_MISSMATCH;
532
- if (opt.max && value.length > opt.max)
535
+ if (opt.max !== undefined && value.length > opt.max)
533
536
  return ValidationReport.VALUE_TOO_BIG;
534
- if (opt.min && value.length < opt.min)
537
+ if (opt.min !== undefined && value.length < opt.min)
535
538
  return ValidationReport.VALUE_TOO_SHORT;
536
539
  if (opt.type === "email" && !opt.regex) {
537
540
  opt.regex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,6}$/g;
@@ -15,6 +15,7 @@ export type THttpErr<E = any> = {
15
15
  export type THttpResult<T, E = any> = THttpOk<T> | THttpErr<E>;
16
16
  export type THttpOutgoingLogItem = {
17
17
  id: number;
18
+ traceId?: string;
18
19
  created: number;
19
20
  time: number;
20
21
  method: HttpMethod;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Http = void 0;
7
7
  const undici_1 = require("undici");
8
8
  const node_diagnostics_channel_1 = __importDefault(require("node:diagnostics_channel"));
9
+ const Trace_1 = require("../helper/Trace");
9
10
  const MonitorService_1 = require("../MonitorService");
10
11
  const LogService_1 = require("../LogService");
11
12
  function sleep(ms) {
@@ -99,7 +100,7 @@ class Http {
99
100
  accept: "application/json",
100
101
  },
101
102
  retry: {
102
- enabled: true,
103
+ enabled: false,
103
104
  maxAttempts: 2,
104
105
  baseDelayMs: 200,
105
106
  maxDelayMs: 1500,
@@ -466,7 +467,7 @@ class Http {
466
467
  const overallStarted = Date.now();
467
468
  const cfg = this.config;
468
469
  const retryCfg = {
469
- enabled: opts.retry?.enabled ?? cfg.retry?.enabled ?? true,
470
+ enabled: opts.retry?.enabled ?? cfg.retry?.enabled ?? false,
470
471
  maxAttempts: opts.retry?.maxAttempts ?? cfg.retry?.maxAttempts ?? 2,
471
472
  baseDelayMs: opts.retry?.baseDelayMs ?? cfg.retry?.baseDelayMs ?? 200,
472
473
  maxDelayMs: opts.retry?.maxDelayMs ?? cfg.retry?.maxDelayMs ?? 1500,
@@ -510,10 +511,12 @@ class Http {
510
511
  const throwOnJsonParseError = opts.throwOnJsonParseError ?? false;
511
512
  let attemptsMade = 0;
512
513
  const host = Http._hostFromUrl(url);
514
+ const traceId = Trace_1.Trace.current() ?? undefined;
513
515
  Http._incInFlight(host);
514
516
  const finish = (result, networkErr) => {
515
517
  Http._decInFlight(host);
516
518
  const entry = Http._pushOutgoingLog({
519
+ traceId,
517
520
  created: overallStarted,
518
521
  time: Date.now() - overallStarted,
519
522
  method: opts.method,
@@ -18,7 +18,7 @@ export declare class InterceptorSignedAuth implements IInterceptor<ISignedAuthRe
18
18
  intercept(req: HTTPRequestVO): Promise<ISignedAuthResult>;
19
19
  verify(req: HTTPRequestVO): Promise<ISignedAuthVerdict>;
20
20
  private purge;
21
- private static parseHeader;
21
+ static parseHeader(s: string): Record<string, string>;
22
22
  private static hashUpload;
23
23
  static pathOf(url: string): string;
24
24
  static message(method: string, path: string, ts: string, nonce: string, data: unknown, files: Record<string, string>): string;
@@ -35,5 +35,6 @@ export declare class InterceptorSignedAuth implements IInterceptor<ISignedAuthRe
35
35
  url: string;
36
36
  data?: unknown;
37
37
  files?: Record<string, string>;
38
+ nonce?: string;
38
39
  }): string;
39
40
  }
@@ -141,7 +141,7 @@ class InterceptorSignedAuth {
141
141
  static sign(o) {
142
142
  const key = crypto_1.default.createPrivateKey({ key: Buffer.from(o.privateKey, "base64"), format: "der", type: "pkcs8" });
143
143
  const ts = String(Date.now());
144
- const nonce = crypto_1.default.randomBytes(18).toString("base64url");
144
+ const nonce = o.nonce ?? crypto_1.default.randomBytes(18).toString("base64url");
145
145
  const message = InterceptorSignedAuth.message(o.method.toUpperCase(), InterceptorSignedAuth.pathOf(o.url), ts, nonce, o.data ?? {}, o.files ?? {});
146
146
  const sig = crypto_1.default.sign(null, Buffer.from(message), key).toString("base64");
147
147
  return `Signature kid="${o.kid}", ts="${ts}", nonce="${nonce}", sig="${sig}"`;
@@ -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
  }