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.
- package/CHANGELOG.md +86 -0
- package/README.md +247 -79
- package/dist/apiServer/APIService.d.ts +3 -1
- package/dist/apiServer/APIService.js +25 -1
- package/dist/apiServer/LogService.d.ts +2 -0
- package/dist/apiServer/LogService.js +10 -8
- package/dist/apiServer/MonitorService.d.ts +4 -1
- package/dist/apiServer/MonitorService.js +28 -5
- package/dist/apiServer/deployment/Activate.js +2 -6
- package/dist/apiServer/deployment/Backups.js +3 -2
- package/dist/apiServer/deployment/Bundler.d.ts +12 -0
- package/dist/apiServer/deployment/Bundler.js +178 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +6 -0
- package/dist/apiServer/deployment/ConfigService.js +17 -1
- package/dist/apiServer/deployment/Deploy.js +101 -57
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
- package/dist/apiServer/deployment/Deployer.d.ts +1 -0
- package/dist/apiServer/deployment/Deployer.js +7 -5
- package/dist/apiServer/deployment/DeployerService.d.ts +27 -2
- package/dist/apiServer/deployment/DeployerService.js +129 -30
- package/dist/apiServer/deployment/HashPassword.js +2 -2
- package/dist/apiServer/deployment/MigrateConfigsWizard.js +9 -5
- package/dist/apiServer/deployment/ProjectConfigWizard.js +4 -2
- package/dist/apiServer/deployment/Restore.js +9 -8
- package/dist/apiServer/deployment/SecretsInjector.js +2 -1
- package/dist/apiServer/deployment/SetupConfigWizard.js +38 -2
- package/dist/apiServer/deployment/Status.js +5 -8
- package/dist/apiServer/deployment/Watchdog.js +1 -1
- package/dist/apiServer/deployment/Wizards.js +16 -11
- package/dist/apiServer/deployment/cli.js +33 -14
- package/dist/apiServer/deployment/cliCommon.d.ts +13 -1
- package/dist/apiServer/deployment/cliCommon.js +50 -2
- package/dist/apiServer/deployment/resolveConfig.d.ts +4 -1
- package/dist/apiServer/deployment/resolveConfig.js +23 -2
- package/dist/apiServer/external/MicroserviceClient.d.ts +7 -2
- package/dist/apiServer/external/MicroserviceClient.js +90 -10
- package/dist/apiServer/external/MicroserviceHost.d.ts +35 -8
- package/dist/apiServer/external/MicroserviceHost.js +148 -55
- package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
- package/dist/apiServer/helper/AppDataPath.js +81 -0
- package/dist/apiServer/helper/ClientIp.d.ts +1 -0
- package/dist/apiServer/helper/ClientIp.js +5 -0
- package/dist/apiServer/helper/Trace.d.ts +8 -0
- package/dist/apiServer/helper/Trace.js +30 -0
- package/dist/apiServer/helper/Validator.d.ts +1 -0
- package/dist/apiServer/helper/Validator.js +21 -18
- package/dist/apiServer/http/Http.d.ts +1 -0
- package/dist/apiServer/http/Http.js +5 -2
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
- package/dist/apiServer/monitor/MonitorAuth.js +8 -5
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +8 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +87 -1
- package/dist/apiServer/monitor/index.html +66 -66
- package/dist/apiServer/security/BlockedIps.js +10 -14
- package/dist/apiServer/structures/Interfaces.d.ts +2 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +5 -1
- package/package.json +21 -6
- package/bluegreen.help.md +0 -392
- package/cocroach.help.md +0 -191
- package/connections.help.md +0 -0
- package/monitoring.help.md +0 -350
|
@@ -36,68 +36,149 @@ 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
|
+
class MemoryJobStore {
|
|
49
|
+
#jobs = new Map();
|
|
50
|
+
get(key) { return this.#jobs.get(key) ?? null; }
|
|
51
|
+
set(key, job) { this.#jobs.set(key, job); }
|
|
52
|
+
purge(now) { for (const [k, j] of this.#jobs)
|
|
53
|
+
if (j.expires < now)
|
|
54
|
+
this.#jobs.delete(k); }
|
|
55
|
+
}
|
|
56
|
+
exports.MemoryJobStore = MemoryJobStore;
|
|
57
|
+
const VERSION = 2;
|
|
58
|
+
const ANSWER = "badmfck-ms-v2-answer";
|
|
59
|
+
const JOB_TTL = 1000 * 60 * 5;
|
|
43
60
|
class MicroserviceHost extends BaseService_1.BaseService {
|
|
44
61
|
static #calls = new Set();
|
|
45
62
|
static #instances = new Map();
|
|
63
|
+
static #context = new async_hooks_1.AsyncLocalStorage();
|
|
46
64
|
options;
|
|
47
|
-
|
|
65
|
+
#store;
|
|
66
|
+
#auth = null;
|
|
48
67
|
constructor(opt) {
|
|
49
68
|
super("Microservice-host-" + opt.id);
|
|
69
|
+
if (!opt.clients && !opt.securityKey)
|
|
70
|
+
throw new Error(`MicroserviceHost "${opt.id}": set "clients" (and "privateKey") for signed calls`);
|
|
71
|
+
if (opt.clients) {
|
|
72
|
+
if (!opt.privateKey)
|
|
73
|
+
throw new Error(`MicroserviceHost "${opt.id}": "clients" needs "privateKey" — the host signs its answers`);
|
|
74
|
+
InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(opt.privateKey);
|
|
75
|
+
this.#auth = new InterceptorSignedAuth_1.InterceptorSignedAuth(kid => opt.clients?.[kid]?.publicKey ?? null);
|
|
76
|
+
}
|
|
50
77
|
this.options = opt;
|
|
78
|
+
this.#store = opt.jobStore ?? new MemoryJobStore();
|
|
51
79
|
MicroserviceHost.#instances.set(opt.id, this);
|
|
52
80
|
}
|
|
53
81
|
async init() {
|
|
54
82
|
super.init();
|
|
55
83
|
setInterval(() => {
|
|
56
|
-
|
|
57
|
-
for (const [key, job] of this.jobs) {
|
|
58
|
-
if (job.expires < now)
|
|
59
|
-
this.jobs.delete(key);
|
|
60
|
-
}
|
|
84
|
+
Promise.resolve(this.#store.purge(Date.now())).catch(e => (0, LogService_1.logError)("MicroserviceHost job store purge failed", e));
|
|
61
85
|
}, 1000 * 60 * 5);
|
|
62
86
|
}
|
|
63
87
|
static getMicroservice(id) {
|
|
64
88
|
return MicroserviceHost.#instances.get(id) || null;
|
|
65
89
|
}
|
|
90
|
+
static currentCall() {
|
|
91
|
+
return MicroserviceHost.#context.getStore() ?? null;
|
|
92
|
+
}
|
|
93
|
+
static answerMessage(hostId, op, nonce, answer) {
|
|
94
|
+
const payload = (0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ result: answer.result, error: answer.error, pending: answer.pending })));
|
|
95
|
+
const digest = crypto_1.default.createHash("sha256").update(payload).digest("hex");
|
|
96
|
+
return [ANSWER, hostId, op, nonce, digest].join("\n");
|
|
97
|
+
}
|
|
66
98
|
async handleIncomingRequest(req) {
|
|
99
|
+
if (String(req.headers?.["authorization"] ?? "").toLowerCase().startsWith("signature "))
|
|
100
|
+
return this.#handleSigned(req);
|
|
101
|
+
if (this.options.securityKey)
|
|
102
|
+
return this.#handleV1(req);
|
|
103
|
+
return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "signed request required" };
|
|
104
|
+
}
|
|
105
|
+
async #handleSigned(req) {
|
|
106
|
+
if (!this.#auth)
|
|
107
|
+
return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "this host takes no signed calls" };
|
|
108
|
+
const verdict = await this.#auth.verify(req);
|
|
109
|
+
if (!verdict.kid) {
|
|
110
|
+
(0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: rejected call — ${verdict.error}`);
|
|
111
|
+
return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "invalid signature" };
|
|
112
|
+
}
|
|
113
|
+
const caller = verdict.kid;
|
|
114
|
+
Trace_1.Trace.adopt(req.data?.trace);
|
|
115
|
+
const nonce = InterceptorSignedAuth_1.InterceptorSignedAuth.parseHeader(String(req.headers["authorization"]).slice("signature ".length)).nonce;
|
|
116
|
+
const body = req.data ?? {};
|
|
117
|
+
if (body.v !== VERSION || body.to !== this.options.id)
|
|
118
|
+
return { ...DefaultErrors_1.default.BAD_REQUEST, details: "request is not addressed to this host" };
|
|
119
|
+
if (typeof body.op !== "string" || !/^[A-Za-z0-9._:-]{8,128}$/.test(body.op) || typeof body.requestName !== "string")
|
|
120
|
+
return { ...DefaultErrors_1.default.BAD_REQUEST, details: "op and requestName required" };
|
|
121
|
+
const op = body.op;
|
|
122
|
+
const requestName = body.requestName;
|
|
123
|
+
const answer = (a) => this.#signAnswer(op, nonce, a);
|
|
124
|
+
const allowed = this.options.clients?.[caller]?.requests;
|
|
125
|
+
if (allowed && !allowed.includes(requestName)) {
|
|
126
|
+
(0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: ${caller} may not call ${requestName}`);
|
|
127
|
+
return answer({ error: { ...DefaultErrors_1.default.FORBIDDEN, details: "request not allowed for " + caller } });
|
|
128
|
+
}
|
|
129
|
+
const jobKey = caller + "|" + op;
|
|
130
|
+
const hash = crypto_1.default.createHash("sha256")
|
|
131
|
+
.update((0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ requestName, requestData: body.requestData ?? null }))))
|
|
132
|
+
.digest("hex");
|
|
133
|
+
const job = await this.#store.get(jobKey);
|
|
134
|
+
if (job && job.expires >= Date.now()) {
|
|
135
|
+
if (job.hash && job.hash !== hash)
|
|
136
|
+
return answer({ error: { ...DefaultErrors_1.default.CONFLICT, details: "op was already used for another request" } });
|
|
137
|
+
if (job.status === "processing")
|
|
138
|
+
return answer({ pending: true });
|
|
139
|
+
return DefaultErrors_1.ErrorUtils.isError(job.result) ? answer({ error: job.result }) : answer({ result: job.result });
|
|
140
|
+
}
|
|
141
|
+
const reqCall = this.options.requests.find(r => r.name === requestName);
|
|
142
|
+
if (!reqCall)
|
|
143
|
+
return answer({ error: { ...DefaultErrors_1.default.NOT_FOUND, details: "request not registered: " + requestName } });
|
|
144
|
+
await this.#store.set(jobKey, { status: "processing", hash, expires: Date.now() + JOB_TTL });
|
|
145
|
+
let result;
|
|
146
|
+
try {
|
|
147
|
+
result = await MicroserviceHost.#context.run({ caller, op, requestName }, () => reqCall.request(body.requestData));
|
|
148
|
+
if (DefaultErrors_1.ErrorUtils.isError(result))
|
|
149
|
+
result = MicroserviceHost.#outbound(result);
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
if (DefaultErrors_1.ErrorUtils.isError(e))
|
|
153
|
+
result = MicroserviceHost.#outbound(e);
|
|
154
|
+
else {
|
|
155
|
+
(0, LogService_1.logError)(`MicroserviceHost ${this.options.id}: ${requestName} from ${caller} threw`, e);
|
|
156
|
+
result = { ...DefaultErrors_1.default.INTERNAL_ERROR };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
await this.#store.set(jobKey, { status: "completed", hash, result, expires: Date.now() + JOB_TTL });
|
|
160
|
+
return DefaultErrors_1.ErrorUtils.isError(result) ? answer({ error: result }) : answer({ result });
|
|
161
|
+
}
|
|
162
|
+
#signAnswer(op, nonce, a) {
|
|
163
|
+
const key = crypto_1.default.createPrivateKey({ key: Buffer.from(this.options.privateKey, "base64"), format: "der", type: "pkcs8" });
|
|
164
|
+
const sig = crypto_1.default.sign(null, Buffer.from(MicroserviceHost.answerMessage(this.options.id, op, nonce, a)), key).toString("base64");
|
|
165
|
+
return { v: VERSION, op, ...a, sig };
|
|
166
|
+
}
|
|
167
|
+
static #outbound(e) {
|
|
168
|
+
const { stack, ...rest } = e;
|
|
169
|
+
return rest;
|
|
170
|
+
}
|
|
171
|
+
async #handleV1(req) {
|
|
67
172
|
const nonce = req.headers["x-microservice-nonce"];
|
|
68
173
|
const ts = req.headers["x-microservice-ts"];
|
|
69
174
|
if (!nonce || !ts)
|
|
70
175
|
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
176
|
const requestTime = parseInt(ts);
|
|
84
177
|
const now = Date.now();
|
|
85
178
|
if (isNaN(requestTime) || Math.abs(now - requestTime) > 1000 * 60 * 2) {
|
|
86
179
|
return { ...DefaultErrors_1.default.BAD_REQUEST, details: "timestamp out of range" };
|
|
87
180
|
}
|
|
88
|
-
|
|
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
|
-
}
|
|
181
|
+
let request;
|
|
101
182
|
try {
|
|
102
183
|
const rawSecret = Buffer.from(this.options.securityKey, "base64");
|
|
103
184
|
const key = crypto_1.default.createHash("sha256").update(rawSecret).digest();
|
|
@@ -110,33 +191,45 @@ class MicroserviceHost extends BaseService_1.BaseService {
|
|
|
110
191
|
decipher.setAAD(aad);
|
|
111
192
|
decipher.setAuthTag(tag);
|
|
112
193
|
const decrypted = Buffer.concat([decipher.update(enc), decipher.final()]);
|
|
113
|
-
|
|
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
|
-
}
|
|
194
|
+
request = JSON.parse(decrypted.toString("utf8"));
|
|
136
195
|
}
|
|
137
196
|
catch (e) {
|
|
138
197
|
return { ...DefaultErrors_1.default.BAD_REQUEST, details: "decryption error" };
|
|
139
198
|
}
|
|
199
|
+
const jobKey = `${nonce}|${ts}`;
|
|
200
|
+
const job = await this.#store.get(jobKey);
|
|
201
|
+
if (job && job.expires >= Date.now()) {
|
|
202
|
+
if (job.status === "processing")
|
|
203
|
+
return { ...DefaultErrors_1.default.ACCEPTED, details: "request is being processed" };
|
|
204
|
+
return job.result;
|
|
205
|
+
}
|
|
206
|
+
if (MicroserviceHost.#calls.has(jobKey)) {
|
|
207
|
+
return { ...DefaultErrors_1.default.BAD_REQUEST, details: "replay attack detected" };
|
|
208
|
+
}
|
|
209
|
+
MicroserviceHost.#calls.add(jobKey);
|
|
210
|
+
if (MicroserviceHost.#calls.size > 5000) {
|
|
211
|
+
const iterator = MicroserviceHost.#calls.values();
|
|
212
|
+
for (let i = 0; i < 100; i++) {
|
|
213
|
+
const val = iterator.next().value;
|
|
214
|
+
if (val)
|
|
215
|
+
MicroserviceHost.#calls.delete(val);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const reqCall = this.options.requests.find(r => r.name === request?.requestName);
|
|
219
|
+
if (!reqCall)
|
|
220
|
+
return { ...DefaultErrors_1.default.NOT_FOUND, details: "request not registered: " + request?.requestName };
|
|
221
|
+
await this.#store.set(jobKey, { status: "processing", expires: Date.now() + JOB_TTL });
|
|
222
|
+
let result;
|
|
223
|
+
try {
|
|
224
|
+
result = await reqCall.request(request.requestData);
|
|
225
|
+
}
|
|
226
|
+
catch (e) {
|
|
227
|
+
const errText = e instanceof Error ? e.message : "unknown error: " + e;
|
|
228
|
+
const errStack = e instanceof Error && e.stack ? e.stack : "";
|
|
229
|
+
result = DefaultErrors_1.ErrorUtils.isError(e) ? e : { ...DefaultErrors_1.default.INTERNAL_ERROR, details: errText, stack: errStack };
|
|
230
|
+
}
|
|
231
|
+
await this.#store.set(jobKey, { status: "completed", result, expires: Date.now() + JOB_TTL });
|
|
232
|
+
return result;
|
|
140
233
|
}
|
|
141
234
|
}
|
|
142
235
|
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,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,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
|
-
|
|
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
|
-
|
|
71
|
-
|
|
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;
|
|
@@ -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:
|
|
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 ??
|
|
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,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { IInterceptor } from "../APIService";
|
|
2
|
+
import { HTTPRequestVO } from "../structures/Interfaces";
|
|
3
|
+
export interface ISignedAuthResult {
|
|
4
|
+
kid: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ISignedAuthVerdict {
|
|
7
|
+
present: boolean;
|
|
8
|
+
kid?: string;
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare class InterceptorSignedAuth implements IInterceptor<ISignedAuthResult> {
|
|
12
|
+
private resolveKey;
|
|
13
|
+
static TS_PAST_SEC: number;
|
|
14
|
+
static TS_FUTURE_SEC: number;
|
|
15
|
+
private static readonly NONCE_MAX;
|
|
16
|
+
private nonceSeen;
|
|
17
|
+
constructor(resolveKey: (kid: string) => Promise<string | null | undefined> | string | null | undefined);
|
|
18
|
+
intercept(req: HTTPRequestVO): Promise<ISignedAuthResult>;
|
|
19
|
+
verify(req: HTTPRequestVO): Promise<ISignedAuthVerdict>;
|
|
20
|
+
private purge;
|
|
21
|
+
static parseHeader(s: string): Record<string, string>;
|
|
22
|
+
private static hashUpload;
|
|
23
|
+
static pathOf(url: string): string;
|
|
24
|
+
static message(method: string, path: string, ts: string, nonce: string, data: unknown, files: Record<string, string>): string;
|
|
25
|
+
static sha256File(file: string): Promise<string>;
|
|
26
|
+
static generateKeyPair(): {
|
|
27
|
+
publicKey: string;
|
|
28
|
+
privateKey: string;
|
|
29
|
+
};
|
|
30
|
+
static publicKeyOf(privateKey: string): string;
|
|
31
|
+
static sign(o: {
|
|
32
|
+
privateKey: string;
|
|
33
|
+
kid: string;
|
|
34
|
+
method: string;
|
|
35
|
+
url: string;
|
|
36
|
+
data?: unknown;
|
|
37
|
+
files?: Record<string, string>;
|
|
38
|
+
nonce?: string;
|
|
39
|
+
}): string;
|
|
40
|
+
}
|