@bmfk/api 0.0.0-stage → 1.0.1
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 +90 -0
- package/LICENSE +21 -0
- package/README.md +1293 -2
- package/dist/apiServer/APIService.d.ts +125 -0
- package/dist/apiServer/APIService.js +769 -0
- package/dist/apiServer/BaseEndpoint.d.ts +90 -0
- package/dist/apiServer/BaseEndpoint.js +314 -0
- package/dist/apiServer/BaseService.d.ts +17 -0
- package/dist/apiServer/BaseService.js +39 -0
- package/dist/apiServer/DBService.d.ts +131 -0
- package/dist/apiServer/DBService.js +290 -0
- package/dist/apiServer/DocumentService.d.ts +9 -0
- package/dist/apiServer/DocumentService.js +65 -0
- package/dist/apiServer/LocalRequest.d.ts +3 -0
- package/dist/apiServer/LocalRequest.js +6 -0
- package/dist/apiServer/LogService.d.ts +78 -0
- package/dist/apiServer/LogService.js +349 -0
- package/dist/apiServer/MonitorService.d.ts +102 -0
- package/dist/apiServer/MonitorService.js +615 -0
- package/dist/apiServer/StatService.d.ts +4 -0
- package/dist/apiServer/StatService.js +10 -0
- package/dist/apiServer/TimeframeService.d.ts +28 -0
- package/dist/apiServer/TimeframeService.js +97 -0
- package/dist/apiServer/WebSocketServer.d.ts +39 -0
- package/dist/apiServer/WebSocketServer.js +173 -0
- package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
- package/dist/apiServer/db/IDBAdapter.js +2 -0
- package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
- package/dist/apiServer/db/MysqlAdapter.js +869 -0
- package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
- package/dist/apiServer/db/PostgresAdapter.js +73 -0
- package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
- package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
- package/dist/apiServer/deployment/Activate.d.ts +4 -0
- package/dist/apiServer/deployment/Activate.js +124 -0
- package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
- package/dist/apiServer/deployment/BackupManager.js +174 -0
- package/dist/apiServer/deployment/Backups.d.ts +2 -0
- package/dist/apiServer/deployment/Backups.js +44 -0
- package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
- package/dist/apiServer/deployment/BlueGreenState.js +150 -0
- package/dist/apiServer/deployment/Bundler.d.ts +12 -0
- package/dist/apiServer/deployment/Bundler.js +178 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
- package/dist/apiServer/deployment/ConfigService.js +195 -0
- package/dist/apiServer/deployment/Deploy.d.ts +4 -0
- package/dist/apiServer/deployment/Deploy.js +404 -0
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
- package/dist/apiServer/deployment/Deployer.d.ts +13 -0
- package/dist/apiServer/deployment/Deployer.js +96 -0
- package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
- package/dist/apiServer/deployment/DeployerInit.js +214 -0
- package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
- package/dist/apiServer/deployment/DeployerService.js +1553 -0
- package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
- package/dist/apiServer/deployment/HashPassword.js +126 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
- package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
- package/dist/apiServer/deployment/MigrateProject.js +335 -0
- package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
- package/dist/apiServer/deployment/NginxHelper.js +111 -0
- package/dist/apiServer/deployment/Notifier.d.ts +30 -0
- package/dist/apiServer/deployment/Notifier.js +82 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
- package/dist/apiServer/deployment/Restore.d.ts +2 -0
- package/dist/apiServer/deployment/Restore.js +89 -0
- package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
- package/dist/apiServer/deployment/ReviewStore.js +186 -0
- package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
- package/dist/apiServer/deployment/SecretsInjector.js +189 -0
- package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
- package/dist/apiServer/deployment/Status.d.ts +2 -0
- package/dist/apiServer/deployment/Status.js +83 -0
- package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
- package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
- package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
- package/dist/apiServer/deployment/Watchdog.js +65 -0
- package/dist/apiServer/deployment/Wizards.d.ts +1 -0
- package/dist/apiServer/deployment/Wizards.js +83 -0
- package/dist/apiServer/deployment/cli.d.ts +2 -0
- package/dist/apiServer/deployment/cli.js +224 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
- package/dist/apiServer/deployment/cliCommon.js +110 -0
- package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
- package/dist/apiServer/deployment/cliPrompt.js +38 -0
- package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
- package/dist/apiServer/deployment/resolveConfig.js +139 -0
- package/dist/apiServer/documentation/Documentation.d.ts +18 -0
- package/dist/apiServer/documentation/Documentation.js +143 -0
- package/dist/apiServer/documentation/index.html +460 -0
- package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
- package/dist/apiServer/external/MicroserviceClient.js +144 -0
- package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
- package/dist/apiServer/external/MicroserviceHost.js +183 -0
- package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
- package/dist/apiServer/external/MicroserviceHostController.js +65 -0
- package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
- package/dist/apiServer/helper/AppDataPath.js +81 -0
- package/dist/apiServer/helper/ClientIp.d.ts +3 -0
- package/dist/apiServer/helper/ClientIp.js +33 -0
- package/dist/apiServer/helper/DataProvider.d.ts +18 -0
- package/dist/apiServer/helper/DataProvider.js +57 -0
- package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
- package/dist/apiServer/helper/IpAllowList.js +40 -0
- package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
- package/dist/apiServer/helper/JSONStableStringify.js +15 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/helper/Sleep.d.ts +1 -0
- package/dist/apiServer/helper/Sleep.js +5 -0
- package/dist/apiServer/helper/Trace.d.ts +8 -0
- package/dist/apiServer/helper/Trace.js +30 -0
- package/dist/apiServer/helper/UID.d.ts +16 -0
- package/dist/apiServer/helper/UID.js +98 -0
- package/dist/apiServer/helper/Validator.d.ts +86 -0
- package/dist/apiServer/helper/Validator.js +560 -0
- package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
- package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
- package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
- package/dist/apiServer/helper/ZipUtils.js +28 -0
- package/dist/apiServer/http/Http.d.ts +183 -0
- package/dist/apiServer/http/Http.js +627 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
- package/dist/apiServer/monitor/AccessStore.js +163 -0
- package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
- package/dist/apiServer/monitor/LogFiles.js +109 -0
- package/dist/apiServer/monitor/Monitor.d.ts +54 -0
- package/dist/apiServer/monitor/Monitor.js +447 -0
- package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
- package/dist/apiServer/monitor/MonitorAuth.js +474 -0
- package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
- package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
- package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
- package/dist/apiServer/monitor/SystemInfo.js +217 -0
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
- package/dist/apiServer/monitor/index.html +591 -0
- package/dist/apiServer/review/Review.d.ts +23 -0
- package/dist/apiServer/review/Review.js +149 -0
- package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
- package/dist/apiServer/review/ReviewAuth.js +147 -0
- package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
- package/dist/apiServer/review/ReviewDiff.js +175 -0
- package/dist/apiServer/review/index.html +501 -0
- package/dist/apiServer/routes/Liveness.d.ts +7 -0
- package/dist/apiServer/routes/Liveness.js +27 -0
- package/dist/apiServer/routes/Readiness.d.ts +13 -0
- package/dist/apiServer/routes/Readiness.js +20 -0
- package/dist/apiServer/security/BlockedIps.d.ts +46 -0
- package/dist/apiServer/security/BlockedIps.js +185 -0
- package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
- package/dist/apiServer/structures/DefaultErrors.js +52 -0
- package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
- package/dist/apiServer/structures/HTTPStatus.js +11 -0
- package/dist/apiServer/structures/Interfaces.d.ts +55 -0
- package/dist/apiServer/structures/Interfaces.js +2 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +110 -0
- package/dist/signal/Signal.d.ts +23 -0
- package/dist/signal/Signal.js +85 -0
- package/package.json +88 -4
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.APIService = exports.S_APP_STARTED = exports.REQ_MONITOR_ALLOWED_IPS = exports.REQ_DOC_USERS = exports.REQ_MONITOR_USERS = exports.REQ_INTERNAL_CALL = exports.REQ_WS_SERVER = exports.REQ_HTTP_SERVER = exports.REQ_HTTP_REQUESTS_COUNT = exports.REQ_HTTP_LOG = exports.getDefaultOptions = void 0;
|
|
40
|
+
exports.Initializer = Initializer;
|
|
41
|
+
const express_1 = __importDefault(require("express"));
|
|
42
|
+
const BaseService_1 = require("./BaseService");
|
|
43
|
+
const cors_1 = __importDefault(require("cors"));
|
|
44
|
+
const BaseEndpoint_1 = require("./BaseEndpoint");
|
|
45
|
+
const DefaultErrors_1 = __importStar(require("./structures/DefaultErrors"));
|
|
46
|
+
const Signal_1 = require("../signal/Signal");
|
|
47
|
+
const LogService_1 = require("./LogService");
|
|
48
|
+
const Monitor_1 = require("./monitor/Monitor");
|
|
49
|
+
const express_fileupload_1 = __importDefault(require("express-fileupload"));
|
|
50
|
+
const Liveness_1 = require("./routes/Liveness");
|
|
51
|
+
const Readiness_1 = require("./routes/Readiness");
|
|
52
|
+
const http_1 = __importDefault(require("http"));
|
|
53
|
+
const path_1 = __importDefault(require("path"));
|
|
54
|
+
const fs_1 = __importDefault(require("fs"));
|
|
55
|
+
const os_1 = __importDefault(require("os"));
|
|
56
|
+
const StatService_1 = require("./StatService");
|
|
57
|
+
const MonitorService_1 = require("./MonitorService");
|
|
58
|
+
const MysqlAdapter_1 = require("./db/MysqlAdapter");
|
|
59
|
+
const DocumentService_1 = require("./DocumentService");
|
|
60
|
+
const Documentation_1 = require("./documentation/Documentation");
|
|
61
|
+
const MicroserviceHostController_1 = require("./external/MicroserviceHostController");
|
|
62
|
+
const DeployerService_1 = require("./deployment/DeployerService");
|
|
63
|
+
const AppDataPath_1 = require("./helper/AppDataPath");
|
|
64
|
+
const BlueGreenState_1 = require("./deployment/BlueGreenState");
|
|
65
|
+
const ThreatMonitor_1 = require("./monitor/ThreatMonitor");
|
|
66
|
+
const AccessStore_1 = require("./monitor/AccessStore");
|
|
67
|
+
const BlockedIps_1 = require("./security/BlockedIps");
|
|
68
|
+
const MonitorAuth_1 = require("./monitor/MonitorAuth");
|
|
69
|
+
const ClientIp_1 = require("./helper/ClientIp");
|
|
70
|
+
const Trace_1 = require("./helper/Trace");
|
|
71
|
+
const Deployer_1 = require("./deployment/Deployer");
|
|
72
|
+
const Review_1 = require("./review/Review");
|
|
73
|
+
const ws_1 = require("ws");
|
|
74
|
+
const WebSocketServer_1 = require("./WebSocketServer");
|
|
75
|
+
let nextLogID = 0;
|
|
76
|
+
function defaultOptions() {
|
|
77
|
+
return {
|
|
78
|
+
port: 8080,
|
|
79
|
+
baseEndPoint: "/api/",
|
|
80
|
+
corsHostWhiteList: [],
|
|
81
|
+
endpoints: [],
|
|
82
|
+
jsonLimit: "10mb",
|
|
83
|
+
projectName: "Application project",
|
|
84
|
+
isProductionEnvironment: process.env.NODE_ENV !== "development",
|
|
85
|
+
interceptor: undefined,
|
|
86
|
+
postproducer: undefined,
|
|
87
|
+
preproducer: undefined,
|
|
88
|
+
access: "",
|
|
89
|
+
appVersion: undefined,
|
|
90
|
+
metricsDir: undefined,
|
|
91
|
+
fileTempDir: "",
|
|
92
|
+
fileLimit: 10_000_000,
|
|
93
|
+
keepAliveTimeout: 25 * 1000,
|
|
94
|
+
headersTimeout: 26 * 1000,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const getDefaultOptions = (overrides) => {
|
|
98
|
+
const base = defaultOptions();
|
|
99
|
+
return { ...base, ...overrides };
|
|
100
|
+
};
|
|
101
|
+
exports.getDefaultOptions = getDefaultOptions;
|
|
102
|
+
exports.REQ_HTTP_LOG = new Signal_1.Req(undefined, "REQ_HTTP_LOG");
|
|
103
|
+
exports.REQ_HTTP_REQUESTS_COUNT = new Signal_1.Req(undefined, "REQ_HTTP_REQUESTS_COUNT");
|
|
104
|
+
exports.REQ_HTTP_SERVER = new Signal_1.Req(undefined, "REQ_HTTP_SERVER");
|
|
105
|
+
exports.REQ_WS_SERVER = new Signal_1.Req(undefined, "REQ_WS_SERVER");
|
|
106
|
+
exports.REQ_INTERNAL_CALL = new Signal_1.Req(undefined, "REQ_INTERNAL_CALL");
|
|
107
|
+
exports.REQ_MONITOR_USERS = new Signal_1.Req(undefined, "REQ_MONITOR_USERS");
|
|
108
|
+
exports.REQ_DOC_USERS = new Signal_1.Req(undefined, "REQ_DOC_USERS");
|
|
109
|
+
exports.REQ_MONITOR_ALLOWED_IPS = new Signal_1.Req(undefined, "REQ_MONITOR_ALLOWED_IPS");
|
|
110
|
+
exports.S_APP_STARTED = new Signal_1.Signal("S_APP_STARTED");
|
|
111
|
+
const activeServices = [];
|
|
112
|
+
const PACKAGE_VERSION = (() => {
|
|
113
|
+
try {
|
|
114
|
+
return JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(__dirname, "../../package.json"), "utf-8")).version ?? "unknown";
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return "unknown";
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
async function Initializer(services) {
|
|
121
|
+
services.push(new StatService_1.StatService());
|
|
122
|
+
for (let i of services) {
|
|
123
|
+
await i.init();
|
|
124
|
+
activeServices.push(i.getName());
|
|
125
|
+
MonitorService_1.S_STAT_REGISTRATE_SERVICE.invoke(i.getName());
|
|
126
|
+
}
|
|
127
|
+
exports.S_APP_STARTED.invoke();
|
|
128
|
+
for (let i of services) {
|
|
129
|
+
i.applicationReady();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
class APIService extends BaseService_1.BaseService {
|
|
133
|
+
async finishService() {
|
|
134
|
+
await super.finishService();
|
|
135
|
+
ThreatMonitor_1.ThreatMonitor.save();
|
|
136
|
+
}
|
|
137
|
+
static getBlueGreenActiveState(opts) {
|
|
138
|
+
return (0, BlueGreenState_1.getBlueGreenActiveState)(opts);
|
|
139
|
+
}
|
|
140
|
+
static get blueGreenState() {
|
|
141
|
+
return (0, BlueGreenState_1.getBlueGreenStateSync)();
|
|
142
|
+
}
|
|
143
|
+
static get isLive() {
|
|
144
|
+
return (0, BlueGreenState_1.getBlueGreenStateSync)()?.live ?? null;
|
|
145
|
+
}
|
|
146
|
+
static onLiveChange(cb) {
|
|
147
|
+
return (0, BlueGreenState_1.onLiveChange)(cb);
|
|
148
|
+
}
|
|
149
|
+
version = PACKAGE_VERSION;
|
|
150
|
+
options;
|
|
151
|
+
monitor = null;
|
|
152
|
+
deployer = null;
|
|
153
|
+
started = new Date();
|
|
154
|
+
requestsCount = 0;
|
|
155
|
+
anyOrigin = false;
|
|
156
|
+
netLog = [];
|
|
157
|
+
failure(e) {
|
|
158
|
+
if (DefaultErrors_1.ErrorUtils.isError(e))
|
|
159
|
+
return { error: e };
|
|
160
|
+
const dev = !this.options.isProductionEnvironment;
|
|
161
|
+
if ((0, MysqlAdapter_1.isError)(e))
|
|
162
|
+
return { error: { ...DefaultErrors_1.default.DB_ERROR, ...(dev ? { details: e.message } : {}) } };
|
|
163
|
+
return { error: { ...DefaultErrors_1.default.INTERNAL_SERVER_ERROR, ...(dev ? { details: String(e) } : {}) }, httpStatus: 500 };
|
|
164
|
+
}
|
|
165
|
+
static defaultAccessFile() {
|
|
166
|
+
const dir = AppDataPath_1.AppData.dir("");
|
|
167
|
+
return dir ? path_1.default.join(dir, "access.json") : (0, AppDataPath_1.appDataPath)("access", ".json");
|
|
168
|
+
}
|
|
169
|
+
static withoutStack(data) {
|
|
170
|
+
if (!data.error || data.error.stack === undefined)
|
|
171
|
+
return data;
|
|
172
|
+
const { stack, ...error } = data.error;
|
|
173
|
+
return { ...data, error };
|
|
174
|
+
}
|
|
175
|
+
uploadDir() {
|
|
176
|
+
if (this.options.fileTempDir)
|
|
177
|
+
return this.options.fileTempDir;
|
|
178
|
+
const dir = AppDataPath_1.AppData.dir("uploads");
|
|
179
|
+
if (dir)
|
|
180
|
+
return dir;
|
|
181
|
+
const fallback = path_1.default.join(os_1.default.tmpdir(), `bmfk-uploads-${process.getuid?.() ?? "u"}`);
|
|
182
|
+
fs_1.default.mkdirSync(fallback, { recursive: true, mode: 0o700 });
|
|
183
|
+
if (process.getuid && fs_1.default.statSync(fallback).uid !== process.getuid())
|
|
184
|
+
throw new Error(`Uploads: ${fallback} belongs to another user — set fileTempDir`);
|
|
185
|
+
fs_1.default.chmodSync(fallback, 0o700);
|
|
186
|
+
(0, LogService_1.logWarn)(`Uploads: no data folder — using ${fallback}`);
|
|
187
|
+
return fallback;
|
|
188
|
+
}
|
|
189
|
+
static originVerdict(origin, host, listed, any) {
|
|
190
|
+
let o;
|
|
191
|
+
try {
|
|
192
|
+
o = new URL(origin);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return "denied";
|
|
196
|
+
}
|
|
197
|
+
if (host && o.host.toLowerCase() === host.toLowerCase())
|
|
198
|
+
return "same";
|
|
199
|
+
if (listed.has(o.origin))
|
|
200
|
+
return "listed";
|
|
201
|
+
return any ? "any" : "denied";
|
|
202
|
+
}
|
|
203
|
+
constructor(options) {
|
|
204
|
+
super('HTTP Service');
|
|
205
|
+
this.options = options;
|
|
206
|
+
if (!this.options.corsHostWhiteList)
|
|
207
|
+
this.options.corsHostWhiteList = [];
|
|
208
|
+
if (this.options.corsHostWhiteList.find(x => x === "*"))
|
|
209
|
+
this.anyOrigin = true;
|
|
210
|
+
const list = [];
|
|
211
|
+
for (let h of this.options.corsHostWhiteList) {
|
|
212
|
+
if (h === "*")
|
|
213
|
+
continue;
|
|
214
|
+
h = h.replace(/\/$/, "");
|
|
215
|
+
if (!/^https?:\/\//i.test(h)) {
|
|
216
|
+
list.push(`http://${h}`, `https://${h}`);
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
list.push(h);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
this.options.corsHostWhiteList = Array.from(new Set(list.map(h => { try {
|
|
223
|
+
return new URL(h).origin;
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return h;
|
|
227
|
+
} })));
|
|
228
|
+
if (this.options.blockedIps !== false)
|
|
229
|
+
BlockedIps_1.BlockedIps.configure(this.options.blockedIps?.file);
|
|
230
|
+
const accessDefault = this.options.access === "";
|
|
231
|
+
const accessSource = accessDefault ? APIService.defaultAccessFile() : this.options.access;
|
|
232
|
+
const access = new AccessStore_1.AccessStore(accessSource, (prev, next) => {
|
|
233
|
+
const now = new Map((next.monitor ?? []).map(u => [u.login, u.password]));
|
|
234
|
+
for (const u of prev.monitor ?? []) {
|
|
235
|
+
if (now.get(u.login) === u.password)
|
|
236
|
+
continue;
|
|
237
|
+
MonitorAuth_1.MonitorAuth.revokeAllFor(u.login);
|
|
238
|
+
(0, LogService_1.logWarn)(`Monitor: sessions of "${u.login}" revoked (${now.has(u.login) ? "password changed" : "removed from access"})`);
|
|
239
|
+
}
|
|
240
|
+
const plain = MonitorAuth_1.MonitorAuth.plaintextLogins(next.monitor ?? []);
|
|
241
|
+
if (plain.length)
|
|
242
|
+
(0, LogService_1.logError)(`Monitor: password stored as plain text for ${plain.map(l => '"' + l + '"').join(", ")} — these logins are refused; store a hash instead: npx bmfk hash-password`);
|
|
243
|
+
const nowDoc = new Map((next.documentation ?? []).map(u => [u.login, u.password]));
|
|
244
|
+
for (const u of prev.documentation ?? []) {
|
|
245
|
+
if (nowDoc.get(u.login) === u.password)
|
|
246
|
+
continue;
|
|
247
|
+
MonitorAuth_1.MonitorAuth.revokeAllFor("doc:" + u.login);
|
|
248
|
+
(0, LogService_1.logWarn)(`Documentation: sessions of "${u.login}" revoked (${nowDoc.has(u.login) ? "password changed" : "removed from access"})`);
|
|
249
|
+
}
|
|
250
|
+
const plainDoc = MonitorAuth_1.MonitorAuth.plaintextLogins(next.documentation ?? []);
|
|
251
|
+
if (plainDoc.length)
|
|
252
|
+
(0, LogService_1.logError)(`Documentation: password stored as plain text for ${plainDoc.map(l => '"' + l + '"').join(", ")} — these logins are refused; store a hash instead: npx bmfk hash-password`);
|
|
253
|
+
}, accessDefault);
|
|
254
|
+
exports.REQ_MONITOR_USERS.listener = async () => access.monitor;
|
|
255
|
+
exports.REQ_DOC_USERS.listener = async () => access.documentation;
|
|
256
|
+
exports.REQ_MONITOR_ALLOWED_IPS.listener = async () => access.monitorAllowedIps;
|
|
257
|
+
this.options.endpoints.push(new Monitor_1.Monitor(this.options));
|
|
258
|
+
this.options.endpoints.push(new Documentation_1.Documentation(this.options));
|
|
259
|
+
this.options.endpoints.push(new MicroserviceHostController_1.MicroserviceHostController());
|
|
260
|
+
if (this.options.deployer && this.options.deployer.projects_path && this.options.deployer.setup_path) {
|
|
261
|
+
this.deployer = new DeployerService_1.DeployerService({
|
|
262
|
+
...this.options.deployer,
|
|
263
|
+
selfPort: this.options.port,
|
|
264
|
+
selfBaseEndPoint: this.options.baseEndPoint,
|
|
265
|
+
});
|
|
266
|
+
this.deployer.init();
|
|
267
|
+
this.options.endpoints = [
|
|
268
|
+
new Deployer_1.Deployer(),
|
|
269
|
+
new Review_1.Review(this.deployer, this.options),
|
|
270
|
+
new Documentation_1.Documentation(this.options),
|
|
271
|
+
new Monitor_1.Monitor(this.options),
|
|
272
|
+
];
|
|
273
|
+
}
|
|
274
|
+
this.monitor = new MonitorService_1.MonitorService(this.options.metricsDir);
|
|
275
|
+
this.monitor.init();
|
|
276
|
+
new DocumentService_1.DocumentGenerator(this.options.endpoints);
|
|
277
|
+
this.options.endpoints.push(new Liveness_1.Liveness(this.started), new Readiness_1.Readiness(this.started));
|
|
278
|
+
exports.REQ_HTTP_REQUESTS_COUNT.listener = async () => this.requestsCount;
|
|
279
|
+
}
|
|
280
|
+
async init() {
|
|
281
|
+
super.init();
|
|
282
|
+
exports.REQ_HTTP_LOG.listener = async (_) => this.netLog;
|
|
283
|
+
exports.REQ_INTERNAL_CALL.listener = async (req) => {
|
|
284
|
+
for (let i of this.options.endpoints) {
|
|
285
|
+
if (!i || !i.endpoints)
|
|
286
|
+
continue;
|
|
287
|
+
for (let j of i.endpoints) {
|
|
288
|
+
let ep = BaseEndpoint_1.BaseEndpoint.getEntryPoint() + j.endpoint;
|
|
289
|
+
ep = ep.replaceAll("//", "/");
|
|
290
|
+
if (ep === req.endpoint) {
|
|
291
|
+
req.internalCall = true;
|
|
292
|
+
const response = await i.__execute(req);
|
|
293
|
+
if (response.error)
|
|
294
|
+
return response.error;
|
|
295
|
+
return response.data;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return { error: DefaultErrors_1.default.UNKNOWN_REQUEST, data: null, httpStatus: 404 };
|
|
300
|
+
};
|
|
301
|
+
const app = (0, express_1.default)();
|
|
302
|
+
const trustedProxies = new Set(this.options.trustedProxies ?? ClientIp_1.DEFAULT_TRUSTED_PROXIES);
|
|
303
|
+
app.use((req, res, next) => {
|
|
304
|
+
const incoming = req.get(Trace_1.TRACE_HEADER);
|
|
305
|
+
const traceId = Trace_1.Trace.isValid(incoming) && (0, ClientIp_1.fromTrustedProxy)(req, trustedProxies) ? incoming : Trace_1.Trace.newId();
|
|
306
|
+
res.setHeader("X-Request-Id", traceId);
|
|
307
|
+
Trace_1.Trace.run(traceId, next);
|
|
308
|
+
});
|
|
309
|
+
if (this.options.blockedIps !== false) {
|
|
310
|
+
const message = this.options.blockedIps?.message || "Access from your address is blocked";
|
|
311
|
+
app.use((req, res, next) => {
|
|
312
|
+
const ip = (0, ClientIp_1.clientIp)(req, trustedProxies);
|
|
313
|
+
if (!BlockedIps_1.BlockedIps.isBlocked(ip))
|
|
314
|
+
return next();
|
|
315
|
+
BlockedIps_1.BlockedIps.noteHit(ip);
|
|
316
|
+
res.status(403).json({ error: { code: 403, message, httpStatus: 403 }, data: null, httpStatus: 403, version: this.options.appVersion });
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
if (this.options.threatMonitoring !== false) {
|
|
320
|
+
const dataDir = AppDataPath_1.AppData.dir("");
|
|
321
|
+
ThreatMonitor_1.ThreatMonitor.configure(dataDir ? path_1.default.join(dataDir, "threats.json") : (0, AppDataPath_1.appDataPath)("threats", ".json"));
|
|
322
|
+
app.use((req, res, next) => {
|
|
323
|
+
res.on("finish", () => {
|
|
324
|
+
try {
|
|
325
|
+
ThreatMonitor_1.ThreatMonitor.observe({
|
|
326
|
+
ip: (0, ClientIp_1.clientIp)(req, trustedProxies),
|
|
327
|
+
method: req.method,
|
|
328
|
+
url: req.originalUrl ?? req.url,
|
|
329
|
+
status: res.statusCode,
|
|
330
|
+
ua: req.get("user-agent") ?? null,
|
|
331
|
+
body: req.body,
|
|
332
|
+
contentLength: Number(req.get("content-length")) || 0,
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
catch { }
|
|
336
|
+
});
|
|
337
|
+
next();
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
const server = http_1.default.createServer(app);
|
|
341
|
+
if (this.options.keepAliveTimeout !== undefined)
|
|
342
|
+
server.keepAliveTimeout = this.options.keepAliveTimeout;
|
|
343
|
+
if (this.options.headersTimeout !== undefined)
|
|
344
|
+
server.headersTimeout = this.options.headersTimeout;
|
|
345
|
+
exports.REQ_HTTP_SERVER.listener = async (_) => { return { express: app, http: server }; };
|
|
346
|
+
const wss = this.options.websocketServer ? this.attachWebSocketServer(server, trustedProxies) : null;
|
|
347
|
+
exports.REQ_WS_SERVER.listener = async (_) => wss;
|
|
348
|
+
if (this.options.isProductionEnvironment)
|
|
349
|
+
app.set("env", 'production');
|
|
350
|
+
app.use(express_1.default.json({ limit: this.options.jsonLimit ?? '10mb' }));
|
|
351
|
+
app.use(express_1.default.urlencoded({ limit: this.options.jsonLimit ?? '10mb', extended: true }));
|
|
352
|
+
app.use((0, express_fileupload_1.default)({
|
|
353
|
+
limitHandler: (req, res, next) => {
|
|
354
|
+
this.sendResponse(req.get("Referer") ?? "", res, {
|
|
355
|
+
error: DefaultErrors_1.default.FILE_TOO_LARGE,
|
|
356
|
+
data: null,
|
|
357
|
+
httpStatus: 413,
|
|
358
|
+
}, +new Date(), req.path, {
|
|
359
|
+
endpoint: req.path,
|
|
360
|
+
headers: req.headers,
|
|
361
|
+
method: req.method,
|
|
362
|
+
data: req.body,
|
|
363
|
+
params: req.params,
|
|
364
|
+
interceptorResult: null,
|
|
365
|
+
raw: req,
|
|
366
|
+
response: undefined,
|
|
367
|
+
files: undefined
|
|
368
|
+
});
|
|
369
|
+
return;
|
|
370
|
+
},
|
|
371
|
+
limits: { fileSize: this.options.fileLimit },
|
|
372
|
+
useTempFiles: true,
|
|
373
|
+
uriDecodeFileNames: true,
|
|
374
|
+
tempFileDir: this.uploadDir(),
|
|
375
|
+
abortOnLimit: true
|
|
376
|
+
}));
|
|
377
|
+
app.use((err, req, resp, next) => {
|
|
378
|
+
if (!err) {
|
|
379
|
+
next();
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const tme = +new Date();
|
|
383
|
+
let responseError = DefaultErrors_1.default.UNKNOWN_REQUEST;
|
|
384
|
+
if (typeof err === "object" && err.status === 400 && 'body' in err && err.type === 'entity.parse.failed') {
|
|
385
|
+
responseError = DefaultErrors_1.default.JSON_MALFORMED;
|
|
386
|
+
}
|
|
387
|
+
this.sendResponse(req.get("Referer") ?? "", resp, {
|
|
388
|
+
error: responseError,
|
|
389
|
+
data: null,
|
|
390
|
+
httpStatus: 400
|
|
391
|
+
}, tme, "", {
|
|
392
|
+
endpoint: "",
|
|
393
|
+
headers: req.headers,
|
|
394
|
+
method: req.method,
|
|
395
|
+
data: req.body,
|
|
396
|
+
params: req.params,
|
|
397
|
+
interceptorResult: null,
|
|
398
|
+
raw: req,
|
|
399
|
+
response: undefined,
|
|
400
|
+
files: undefined
|
|
401
|
+
});
|
|
402
|
+
return;
|
|
403
|
+
});
|
|
404
|
+
const corsSet = new Set(this.options.corsHostWhiteList);
|
|
405
|
+
app.use((0, cors_1.default)((req, callback) => {
|
|
406
|
+
const origin = req.headers.origin;
|
|
407
|
+
if (!origin)
|
|
408
|
+
return callback(null, { origin: false });
|
|
409
|
+
const verdict = APIService.originVerdict(origin, req.headers.host, corsSet, this.anyOrigin);
|
|
410
|
+
if (verdict === "any")
|
|
411
|
+
return callback(null, { origin: "*", credentials: false });
|
|
412
|
+
return callback(null, { origin: verdict !== "denied", credentials: true });
|
|
413
|
+
}));
|
|
414
|
+
app.use((req, res, next) => {
|
|
415
|
+
const origin = req.headers.origin;
|
|
416
|
+
if (!origin)
|
|
417
|
+
return next();
|
|
418
|
+
if (APIService.originVerdict(origin, req.headers.host, corsSet, this.anyOrigin) !== "denied")
|
|
419
|
+
return next();
|
|
420
|
+
let shown = String(origin).slice(0, 200);
|
|
421
|
+
try {
|
|
422
|
+
shown = new URL(String(origin)).origin;
|
|
423
|
+
}
|
|
424
|
+
catch { }
|
|
425
|
+
res.status(403).send({
|
|
426
|
+
error: { ...DefaultErrors_1.default.FORBIDDEN, details: `Origin not allowed: ${shown}` },
|
|
427
|
+
data: null,
|
|
428
|
+
httpStatus: 403,
|
|
429
|
+
version: this.options.appVersion
|
|
430
|
+
});
|
|
431
|
+
});
|
|
432
|
+
BaseEndpoint_1.BaseEndpoint.setEntryPoint(this.options.baseEndPoint);
|
|
433
|
+
for (let i of this.options.endpoints) {
|
|
434
|
+
await i.init();
|
|
435
|
+
if (!i.endpoints)
|
|
436
|
+
continue;
|
|
437
|
+
for (let j of i.endpoints) {
|
|
438
|
+
let ep = BaseEndpoint_1.BaseEndpoint.getEntryPoint() + j.endpoint;
|
|
439
|
+
ep = ep.replaceAll("//", "/");
|
|
440
|
+
app.all(ep, async (req, res) => {
|
|
441
|
+
this.requestsCount++;
|
|
442
|
+
const tme = +new Date();
|
|
443
|
+
const execute = async () => {
|
|
444
|
+
const body = { ...(req.body ?? {}) };
|
|
445
|
+
if (req.query && typeof req.query === "object") {
|
|
446
|
+
const keys = Object.keys(req.query);
|
|
447
|
+
for (let k of keys)
|
|
448
|
+
body[k] = req.query[k];
|
|
449
|
+
}
|
|
450
|
+
let httpRequest = {
|
|
451
|
+
raw: req,
|
|
452
|
+
response: res,
|
|
453
|
+
method: req.method,
|
|
454
|
+
data: body,
|
|
455
|
+
params: req.params,
|
|
456
|
+
headers: req.headers,
|
|
457
|
+
endpoint: ep,
|
|
458
|
+
files: req.files ?? null,
|
|
459
|
+
referer: req.get("Referer"),
|
|
460
|
+
ip: (0, ClientIp_1.clientIp)(req, trustedProxies),
|
|
461
|
+
traceId: Trace_1.Trace.current() ?? undefined,
|
|
462
|
+
};
|
|
463
|
+
let ignoreHttpLogging = j.ignoreHttpLogging ?? false;
|
|
464
|
+
if (!ignoreHttpLogging && typeof j.handler === "object") {
|
|
465
|
+
const handler = j.handler[httpRequest.method.toUpperCase()];
|
|
466
|
+
if (typeof handler === "object")
|
|
467
|
+
ignoreHttpLogging = handler.ignoreHttpLogging ?? false;
|
|
468
|
+
}
|
|
469
|
+
if (!ignoreHttpLogging)
|
|
470
|
+
ignoreHttpLogging = i.ignoreHttpLogging ?? false;
|
|
471
|
+
const respond = (data) => {
|
|
472
|
+
data.ignoreHttpLogging = ignoreHttpLogging || data.ignoreHttpLogging || false;
|
|
473
|
+
return this.sendResponse(req.get("Referer") ?? "", res, data, tme, ep, httpRequest);
|
|
474
|
+
};
|
|
475
|
+
if (this.options.preproducer && ep !== "--sys-monitor") {
|
|
476
|
+
try {
|
|
477
|
+
const preproducerResult = await this.options.preproducer(httpRequest);
|
|
478
|
+
if (preproducerResult)
|
|
479
|
+
httpRequest.preproducerResult = preproducerResult;
|
|
480
|
+
}
|
|
481
|
+
catch (e) {
|
|
482
|
+
(0, LogService_1.logError)(e);
|
|
483
|
+
respond(this.failure(e));
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
let result;
|
|
488
|
+
try {
|
|
489
|
+
let ignoreInterceptor = false;
|
|
490
|
+
let allowInterceptorError = false;
|
|
491
|
+
if (j.ignoreInterceptor)
|
|
492
|
+
ignoreInterceptor = true;
|
|
493
|
+
if (j.allowInterceptorError)
|
|
494
|
+
allowInterceptorError = true;
|
|
495
|
+
if (typeof j.handler === "object") {
|
|
496
|
+
const handler = j.handler[httpRequest.method.toUpperCase()];
|
|
497
|
+
if (typeof handler === "object") {
|
|
498
|
+
if (handler.ignoreInterceptor)
|
|
499
|
+
ignoreInterceptor = true;
|
|
500
|
+
if (handler.allowInterceptorError)
|
|
501
|
+
allowInterceptorError = true;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (!ignoreInterceptor) {
|
|
505
|
+
let interceptorResult;
|
|
506
|
+
if (this.options.interceptor) {
|
|
507
|
+
interceptorResult = await this.options.interceptor.intercept(httpRequest, j.internalCallParams);
|
|
508
|
+
if (DefaultErrors_1.ErrorUtils.isError(interceptorResult) && !allowInterceptorError) {
|
|
509
|
+
respond(interceptorResult);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
httpRequest.interceptorResult = interceptorResult;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
const precheck = await i.__precheck(httpRequest);
|
|
516
|
+
if (precheck && precheck.error) {
|
|
517
|
+
respond(precheck);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
httpRequest.precheck = precheck;
|
|
521
|
+
result = await i.__execute(httpRequest);
|
|
522
|
+
}
|
|
523
|
+
catch (e) {
|
|
524
|
+
if (DefaultErrors_1.ErrorUtils.isError(e)) {
|
|
525
|
+
if (!e.httpStatus || e.httpStatus >= 500)
|
|
526
|
+
(0, LogService_1.logError)(`${ep} failed`, e);
|
|
527
|
+
}
|
|
528
|
+
else
|
|
529
|
+
(0, LogService_1.logCrit)(`${ep} threw`, e);
|
|
530
|
+
respond(this.failure(e));
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
respond(result);
|
|
534
|
+
};
|
|
535
|
+
return execute();
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
app.use((req, res, next) => {
|
|
540
|
+
const tme = +new Date();
|
|
541
|
+
this.sendResponse(req.get("Referer") ?? "", res, {
|
|
542
|
+
error: DefaultErrors_1.default.UNKNOWN_REQUEST,
|
|
543
|
+
data: null,
|
|
544
|
+
httpStatus: 404
|
|
545
|
+
}, tme, req.path, {
|
|
546
|
+
endpoint: req.path,
|
|
547
|
+
headers: req.headers,
|
|
548
|
+
method: req.method,
|
|
549
|
+
data: req.body,
|
|
550
|
+
params: req.params,
|
|
551
|
+
interceptorResult: null,
|
|
552
|
+
raw: req,
|
|
553
|
+
response: undefined,
|
|
554
|
+
files: undefined
|
|
555
|
+
});
|
|
556
|
+
});
|
|
557
|
+
server.listen(this.options.port, () => {
|
|
558
|
+
(0, LogService_1.logAPI)('${APIService.js}', 'API Service started at: ' + this.options.port + ", with base endpoint:" + this.options.baseEndPoint + ", ver.: " + this.version);
|
|
559
|
+
(0, BlueGreenState_1.startBlueGreenWatcher)(this.options.blueGreenWatchMs ?? 5000);
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
addNetlog(data, req, created, time) {
|
|
563
|
+
if (time === 0)
|
|
564
|
+
time = +new Date() - created;
|
|
565
|
+
const logItem = {
|
|
566
|
+
id: nextLogID++,
|
|
567
|
+
traceId: req?.traceId,
|
|
568
|
+
created: created,
|
|
569
|
+
time: time,
|
|
570
|
+
request: {
|
|
571
|
+
endpoint: req?.endpoint,
|
|
572
|
+
headers: LogService_1.LogService.sanitizeDeep(req?.headers),
|
|
573
|
+
method: req?.method,
|
|
574
|
+
data: this.checkDataLength(req?.data),
|
|
575
|
+
params: LogService_1.LogService.sanitizeDeep(req?.params),
|
|
576
|
+
interceptorResult: LogService_1.LogService.sanitizeDeep(req?.interceptorResult)
|
|
577
|
+
},
|
|
578
|
+
response: this.checkDataLength(data),
|
|
579
|
+
};
|
|
580
|
+
this.netLog.push(logItem);
|
|
581
|
+
if (this.netLog.length > 100)
|
|
582
|
+
this.netLog.shift();
|
|
583
|
+
if (nextLogID > Number.MAX_SAFE_INTEGER - 1000)
|
|
584
|
+
nextLogID = 0;
|
|
585
|
+
}
|
|
586
|
+
static webSocketPath(baseEndPoint, endpoint) {
|
|
587
|
+
const joined = "/" + (baseEndPoint ?? "") + "/" + (endpoint || "ws");
|
|
588
|
+
return joined.replace(/\/{2,}/g, "/").replace(/\/+$/, "") || "/";
|
|
589
|
+
}
|
|
590
|
+
attachWebSocketServer(server, trustedProxies) {
|
|
591
|
+
const opt = this.options.websocketServer ?? {};
|
|
592
|
+
const wsPath = APIService.webSocketPath(this.options.baseEndPoint, opt.endpoint);
|
|
593
|
+
if (!opt.onAuthorize && opt.public !== true)
|
|
594
|
+
throw new Error(`WebSocket server at ${wsPath}: set onAuthorize, or public: true to accept every connection without authorization`);
|
|
595
|
+
const maxConnections = opt.maxConnections ?? 1000;
|
|
596
|
+
const maxPerIp = opt.maxConnectionsPerIp ?? 50;
|
|
597
|
+
const allowedOrigins = new Set(this.options.corsHostWhiteList ?? []);
|
|
598
|
+
const perIp = new Map();
|
|
599
|
+
const wss = new ws_1.WebSocketServer({ noServer: true, maxPayload: opt.maxPayload ?? 256 * 1024 });
|
|
600
|
+
const gateway = new WebSocketServer_1.WebSocketServer(opt.onAuthorize ?? null, {
|
|
601
|
+
authTimeoutMs: opt.authTimeoutMs ?? 10000,
|
|
602
|
+
maxMessagesPerSecond: opt.maxMessagesPerSecond ?? 20,
|
|
603
|
+
});
|
|
604
|
+
const refuse = (socket, status, text) => {
|
|
605
|
+
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
606
|
+
socket.destroy();
|
|
607
|
+
};
|
|
608
|
+
server.on("upgrade", (req, socket, head) => {
|
|
609
|
+
socket.on("error", () => { });
|
|
610
|
+
let pathname = "";
|
|
611
|
+
try {
|
|
612
|
+
pathname = new URL(req.url ?? "", "http://localhost").pathname.replace(/\/+$/, "") || "/";
|
|
613
|
+
}
|
|
614
|
+
catch { }
|
|
615
|
+
if (pathname !== wsPath) {
|
|
616
|
+
if (server.listeners("upgrade").length === 1)
|
|
617
|
+
refuse(socket, 404, "Not Found");
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const ip = (0, ClientIp_1.clientIp)(req, trustedProxies);
|
|
621
|
+
if (BlockedIps_1.BlockedIps.isBlocked(ip)) {
|
|
622
|
+
BlockedIps_1.BlockedIps.noteHit(ip);
|
|
623
|
+
return refuse(socket, 403, "Forbidden");
|
|
624
|
+
}
|
|
625
|
+
const origin = req.headers.origin;
|
|
626
|
+
if (origin) {
|
|
627
|
+
if (APIService.originVerdict(origin, req.headers.host, allowedOrigins, this.anyOrigin) === "denied") {
|
|
628
|
+
(0, LogService_1.logWarn)(`WebSocket refused from ${ip}: origin not allowed (${String(origin).slice(0, 200)})`);
|
|
629
|
+
return refuse(socket, 403, "Forbidden");
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (wss.clients.size >= maxConnections) {
|
|
633
|
+
(0, LogService_1.logWarn)(`WebSocket refused from ${ip}: connection limit ${maxConnections} reached`);
|
|
634
|
+
return refuse(socket, 503, "Service Unavailable");
|
|
635
|
+
}
|
|
636
|
+
if ((perIp.get(ip) ?? 0) >= maxPerIp) {
|
|
637
|
+
(0, LogService_1.logWarn)(`WebSocket refused from ${ip}: per-IP limit ${maxPerIp} reached`);
|
|
638
|
+
return refuse(socket, 429, "Too Many Requests");
|
|
639
|
+
}
|
|
640
|
+
wss.handleUpgrade(req, socket, head, ws => {
|
|
641
|
+
perIp.set(ip, (perIp.get(ip) ?? 0) + 1);
|
|
642
|
+
ws.once("close", () => {
|
|
643
|
+
const n = (perIp.get(ip) ?? 1) - 1;
|
|
644
|
+
if (n > 0)
|
|
645
|
+
perIp.set(ip, n);
|
|
646
|
+
else
|
|
647
|
+
perIp.delete(ip);
|
|
648
|
+
});
|
|
649
|
+
gateway.accept(ws, req, ip);
|
|
650
|
+
});
|
|
651
|
+
});
|
|
652
|
+
if (!opt.onAuthorize)
|
|
653
|
+
(0, LogService_1.logWarn)(`WebSocket server at ${wsPath} is public (public: true) — every connection is accepted without authorization`);
|
|
654
|
+
(0, LogService_1.logAPI)(`WebSocket server attached at ${wsPath}`);
|
|
655
|
+
return gateway;
|
|
656
|
+
}
|
|
657
|
+
async sendResponse(ref, res, data, requestTime, endpoint, req) {
|
|
658
|
+
const ignoreHttpLogging = data.ignoreHttpLogging ?? false;
|
|
659
|
+
delete data.ignoreHttpLogging;
|
|
660
|
+
if (data.blockResponse) {
|
|
661
|
+
if (!ignoreHttpLogging)
|
|
662
|
+
(0, LogService_1.logAPI)("Response blocked");
|
|
663
|
+
if (req && !ignoreHttpLogging)
|
|
664
|
+
this.addNetlog(data, req, requestTime, 0);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
if (!ignoreHttpLogging)
|
|
668
|
+
MonitorService_1.S_STAT_REGISTRATE_REQUEST.invoke({ ...data, endpoint: data.endpoint ?? endpoint });
|
|
669
|
+
if (this.options.postproducer) {
|
|
670
|
+
try {
|
|
671
|
+
data = await this.options.postproducer(req, res, data, requestTime, endpoint);
|
|
672
|
+
}
|
|
673
|
+
catch (e) {
|
|
674
|
+
(0, LogService_1.logError)("Postproducer error", e);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
if (DefaultErrors_1.ErrorUtils.isError(data))
|
|
678
|
+
data = { error: data, data: null };
|
|
679
|
+
data.responseTime = (+new Date()) - requestTime;
|
|
680
|
+
const traceId = Trace_1.Trace.current() ?? req?.traceId;
|
|
681
|
+
if (traceId) {
|
|
682
|
+
data.traceId = traceId;
|
|
683
|
+
if (req)
|
|
684
|
+
req.traceId = traceId;
|
|
685
|
+
if (!res.headersSent)
|
|
686
|
+
res.setHeader("X-Request-Id", traceId);
|
|
687
|
+
}
|
|
688
|
+
data.core = this.version;
|
|
689
|
+
data.endpoint = endpoint ?? "no_endpoint";
|
|
690
|
+
if (this.options.appVersion)
|
|
691
|
+
data.version = this.options.appVersion;
|
|
692
|
+
if (res.socket?.destroyed || res.writableEnded || res.headersSent || (res.destroyed !== undefined && res.destroyed)) {
|
|
693
|
+
if (!ignoreHttpLogging)
|
|
694
|
+
(0, LogService_1.logAPI)("Connection already closed, can't send response for: " + data.endpoint);
|
|
695
|
+
}
|
|
696
|
+
else {
|
|
697
|
+
try {
|
|
698
|
+
if (data.file) {
|
|
699
|
+
const normalizedFile = process.platform === "win32" ? data.file : data.file.replaceAll("\\", "/");
|
|
700
|
+
const filePath = path_1.default.isAbsolute(normalizedFile) ? normalizedFile : path_1.default.resolve(normalizedFile);
|
|
701
|
+
const onSendFileError = (err) => {
|
|
702
|
+
if (!ignoreHttpLogging)
|
|
703
|
+
(0, LogService_1.logError)("Can't send file: " + filePath);
|
|
704
|
+
if (!res.headersSent && !res.writableEnded) {
|
|
705
|
+
res.status(500).send({ error: DefaultErrors_1.default.CANT_SEND_FILE, data: null });
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
else {
|
|
709
|
+
try {
|
|
710
|
+
res.destroy?.(err);
|
|
711
|
+
}
|
|
712
|
+
catch { }
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
};
|
|
716
|
+
try {
|
|
717
|
+
res.sendFile(filePath, err => {
|
|
718
|
+
if (err) {
|
|
719
|
+
onSendFileError(err);
|
|
720
|
+
}
|
|
721
|
+
else {
|
|
722
|
+
if (req && !data.ignoreHttpLogging)
|
|
723
|
+
this.addNetlog(data, req, requestTime, 0);
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
catch (e) {
|
|
728
|
+
onSendFileError(e);
|
|
729
|
+
}
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
if (data.redirect) {
|
|
733
|
+
res.redirect(data.redirect);
|
|
734
|
+
if (!data.ignoreHttpLogging)
|
|
735
|
+
(0, LogService_1.logAPI)("redirect: " + data.redirect);
|
|
736
|
+
}
|
|
737
|
+
else {
|
|
738
|
+
if (data.headers) {
|
|
739
|
+
for (let i in data.headers)
|
|
740
|
+
res.setHeader(i, data.headers[i]);
|
|
741
|
+
}
|
|
742
|
+
if (data.error && data.error.httpStatus && data.error.httpStatus > 99)
|
|
743
|
+
res.statusCode = data.error.httpStatus;
|
|
744
|
+
else
|
|
745
|
+
res.statusCode = data.httpStatus ?? 200;
|
|
746
|
+
if (data.rawResponse) {
|
|
747
|
+
res.send(data.data);
|
|
748
|
+
if (!ignoreHttpLogging)
|
|
749
|
+
(0, LogService_1.logAPI)(this.checkDataLength(data));
|
|
750
|
+
}
|
|
751
|
+
else {
|
|
752
|
+
res.send(this.options.isProductionEnvironment ? APIService.withoutStack(data) : data);
|
|
753
|
+
if (!ignoreHttpLogging)
|
|
754
|
+
(0, LogService_1.logAPI)(this.checkDataLength(data));
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
catch (e) {
|
|
759
|
+
(0, LogService_1.logError)(e);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (req && !ignoreHttpLogging)
|
|
763
|
+
this.addNetlog(data, req, requestTime, 0);
|
|
764
|
+
}
|
|
765
|
+
checkDataLength(data, result, lvl) {
|
|
766
|
+
return LogService_1.LogService.snapshot(data) ?? "";
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
exports.APIService = APIService;
|