badmfck-api-server 5.0.16 → 6.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/README.md +824 -0
- package/dist/apiServer/APIService.d.ts +16 -4
- package/dist/apiServer/APIService.js +92 -3
- package/dist/apiServer/DBService.js +1 -2
- package/dist/apiServer/WebSocketServer.d.ts +39 -0
- package/dist/apiServer/WebSocketServer.js +173 -0
- package/dist/apiServer/db/MysqlAdapter.d.ts +4 -0
- package/dist/apiServer/db/MysqlAdapter.js +93 -84
- package/dist/apiServer/db/PostgresAdapter.d.ts +10 -3
- package/dist/apiServer/deployment/NginxHelper.d.ts +1 -1
- package/dist/apiServer/deployment/NginxHelper.js +3 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +24 -0
- package/dist/apiServer/monitor/AccessStore.js +146 -0
- package/dist/apiServer/monitor/Monitor.js +5 -4
- package/dist/apiServer/monitor/MonitorAuth.d.ts +11 -1
- package/dist/apiServer/monitor/MonitorAuth.js +157 -31
- package/dist/apiServer/monitor/index.html +3 -3
- package/dist/index.d.ts +12 -2
- package/dist/index.js +27 -3
- package/monitoring.help.md +1 -1
- package/package.json +2 -2
- package/dist/apiServer/MysqlService.d.ts +0 -123
- package/dist/apiServer/MysqlService.js +0 -817
- package/dist/apiServer/WSAPITransport.d.ts +0 -0
- package/dist/apiServer/WSAPITransport.js +0 -1
- package/dist/apiServer/WebSocketHandler.d.ts +0 -0
- package/dist/apiServer/WebSocketHandler.js +0 -1
- package/dist/apiServer/WebsocketServerService.d.ts +0 -9
- package/dist/apiServer/WebsocketServerService.js +0 -18
- package/dist/apiServer/deployment/Deployment.d.ts +0 -10
- package/dist/apiServer/deployment/Deployment.js +0 -24
- package/dist/apiServer/interceptors/IntHmacSha256.d.ts +0 -5
- package/dist/apiServer/interceptors/IntHmacSha256.js +0 -22
|
@@ -7,6 +7,8 @@ import http from 'http';
|
|
|
7
7
|
import { IDeployerServiceOptions } from './deployment/DeployerService';
|
|
8
8
|
import { IBlueGreenState, IBlueGreenStateOptions } from './deployment/BlueGreenState';
|
|
9
9
|
import { ILogFilesOptions } from './monitor/LogFiles';
|
|
10
|
+
import { IAccess } from './monitor/AccessStore';
|
|
11
|
+
import { WebSocketServer, WebSocketAuthorizer } from './WebSocketServer';
|
|
10
12
|
export interface IMonitorUser {
|
|
11
13
|
totpSecret?: string;
|
|
12
14
|
role?: "admin" | "it" | "analytic";
|
|
@@ -47,10 +49,8 @@ export interface APIServiceOptions<TInterceptor = unknown> {
|
|
|
47
49
|
interceptor?: IInterceptor<TInterceptor>;
|
|
48
50
|
postproducer?: (req: HTTPRequestVO | undefined | null, res: Response, data: TransferPacketVO<any>, requestTime: number, endpoint?: string, log?: APIServiceNetworkLogItem | null) => Promise<TransferPacketVO>;
|
|
49
51
|
preproducer?: (req: HTTPRequestVO | undefined | null) => any;
|
|
50
|
-
access:
|
|
51
|
-
|
|
52
|
-
documentation?: IDocumentationUser[];
|
|
53
|
-
};
|
|
52
|
+
access: IAccess | string;
|
|
53
|
+
websocketServer?: IWebSocketServerOptions;
|
|
54
54
|
deployer?: IDeployerServiceOptions | null;
|
|
55
55
|
appVersion?: string;
|
|
56
56
|
fileTempDir: string;
|
|
@@ -73,6 +73,16 @@ export declare const REQ_HTTP_SERVER: Req<void, {
|
|
|
73
73
|
express: Application;
|
|
74
74
|
http: http.Server;
|
|
75
75
|
}>;
|
|
76
|
+
export interface IWebSocketServerOptions {
|
|
77
|
+
endpoint?: string;
|
|
78
|
+
maxPayload?: number;
|
|
79
|
+
maxMessagesPerSecond?: number;
|
|
80
|
+
maxConnections?: number;
|
|
81
|
+
maxConnectionsPerIp?: number;
|
|
82
|
+
onAuthorize?: WebSocketAuthorizer;
|
|
83
|
+
authTimeoutMs?: number;
|
|
84
|
+
}
|
|
85
|
+
export declare const REQ_WS_SERVER: Req<void, WebSocketServer | null>;
|
|
76
86
|
export declare const REQ_INTERNAL_CALL: Req<HTTPRequestVO, IError | any>;
|
|
77
87
|
export declare const REQ_MONITOR_USERS: Req<void, IMonitorUser[]>;
|
|
78
88
|
export declare const REQ_DOC_USERS: Req<void, IDocumentationUser[]>;
|
|
@@ -94,6 +104,8 @@ export declare class APIService<TInterceptorResult = any, TInternalCallParams =
|
|
|
94
104
|
constructor(options: APIServiceOptions);
|
|
95
105
|
init(): Promise<void>;
|
|
96
106
|
addNetlog(data: TransferPacketVO, req: HTTPRequestVO, created: number, time: number): void;
|
|
107
|
+
static webSocketPath(baseEndPoint: string, endpoint?: string): string;
|
|
108
|
+
private attachWebSocketServer;
|
|
97
109
|
sendResponse(ref: string, res: Response, data: TransferPacketVO<any>, requestTime: number, endpoint?: string, req?: HTTPRequestVO): Promise<void>;
|
|
98
110
|
checkDataLength(data: any, result?: any, lvl?: number): any;
|
|
99
111
|
}
|
|
@@ -36,7 +36,7 @@ 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.APIService = exports.S_APP_STARTED = exports.REQ_DOC_USERS = exports.REQ_MONITOR_USERS = exports.REQ_INTERNAL_CALL = exports.REQ_HTTP_SERVER = exports.REQ_HTTP_REQUESTS_COUNT = exports.REQ_HTTP_LOG = exports.getDefaultOptions = void 0;
|
|
39
|
+
exports.APIService = exports.S_APP_STARTED = 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
40
|
exports.Initializer = Initializer;
|
|
41
41
|
const express_1 = __importDefault(require("express"));
|
|
42
42
|
const BaseService_1 = require("./BaseService");
|
|
@@ -62,8 +62,12 @@ const MicroserviceHostController_1 = require("./external/MicroserviceHostControl
|
|
|
62
62
|
const DeployerService_1 = require("./deployment/DeployerService");
|
|
63
63
|
const BlueGreenState_1 = require("./deployment/BlueGreenState");
|
|
64
64
|
const ThreatMonitor_1 = require("./monitor/ThreatMonitor");
|
|
65
|
+
const AccessStore_1 = require("./monitor/AccessStore");
|
|
66
|
+
const MonitorAuth_1 = require("./monitor/MonitorAuth");
|
|
65
67
|
const ClientIp_1 = require("./helper/ClientIp");
|
|
66
68
|
const Deployer_1 = require("./deployment/Deployer");
|
|
69
|
+
const ws_1 = require("ws");
|
|
70
|
+
const WebSocketServer_1 = require("./WebSocketServer");
|
|
67
71
|
let nextLogID = 0;
|
|
68
72
|
function defaultOptions() {
|
|
69
73
|
return {
|
|
@@ -97,6 +101,7 @@ exports.getDefaultOptions = getDefaultOptions;
|
|
|
97
101
|
exports.REQ_HTTP_LOG = new badmfck_signal_1.Req(undefined, "REQ_HTTP_LOG");
|
|
98
102
|
exports.REQ_HTTP_REQUESTS_COUNT = new badmfck_signal_1.Req(undefined, "REQ_HTTP_REQUESTS_COUNT");
|
|
99
103
|
exports.REQ_HTTP_SERVER = new badmfck_signal_1.Req(undefined, "REQ_HTTP_SERVER");
|
|
104
|
+
exports.REQ_WS_SERVER = new badmfck_signal_1.Req(undefined, "REQ_WS_SERVER");
|
|
100
105
|
exports.REQ_INTERNAL_CALL = new badmfck_signal_1.Req(undefined, "REQ_INTERNAL_CALL");
|
|
101
106
|
exports.REQ_MONITOR_USERS = new badmfck_signal_1.Req(undefined, "REQ_MONITOR_USERS");
|
|
102
107
|
exports.REQ_DOC_USERS = new badmfck_signal_1.Req(undefined, "REQ_DOC_USERS");
|
|
@@ -166,8 +171,20 @@ class APIService extends BaseService_1.BaseService {
|
|
|
166
171
|
}
|
|
167
172
|
}
|
|
168
173
|
this.options.corsHostWhiteList = Array.from(new Set(list));
|
|
169
|
-
|
|
170
|
-
|
|
174
|
+
const access = new AccessStore_1.AccessStore(this.options.access, (prev, next) => {
|
|
175
|
+
const now = new Map((next.monitor ?? []).map(u => [u.login, u.password]));
|
|
176
|
+
for (const u of prev.monitor ?? []) {
|
|
177
|
+
if (now.get(u.login) === u.password)
|
|
178
|
+
continue;
|
|
179
|
+
MonitorAuth_1.MonitorAuth.revokeAllFor(u.login);
|
|
180
|
+
(0, LogService_1.logWarn)(`Monitor: sessions of "${u.login}" revoked (${now.has(u.login) ? "password changed" : "removed from access"})`);
|
|
181
|
+
}
|
|
182
|
+
const plain = MonitorAuth_1.MonitorAuth.plaintextLogins(next.monitor ?? []);
|
|
183
|
+
if (plain.length)
|
|
184
|
+
(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 badmfck hash-password`);
|
|
185
|
+
});
|
|
186
|
+
exports.REQ_MONITOR_USERS.listener = async () => access.monitor;
|
|
187
|
+
exports.REQ_DOC_USERS.listener = async () => access.documentation;
|
|
171
188
|
this.options.endpoints.push(new Monitor_1.Monitor(this.options));
|
|
172
189
|
this.options.endpoints.push(new Documentation_1.Documentation(this.options));
|
|
173
190
|
this.options.endpoints.push(new ExternalServiceEndpoint_1.ExternalServiceEndpoint());
|
|
@@ -239,6 +256,8 @@ class APIService extends BaseService_1.BaseService {
|
|
|
239
256
|
if (this.options.headersTimeout !== undefined)
|
|
240
257
|
server.headersTimeout = this.options.headersTimeout;
|
|
241
258
|
exports.REQ_HTTP_SERVER.listener = async (_) => { return { express: app, http: server }; };
|
|
259
|
+
const wss = this.options.websocketServer ? this.attachWebSocketServer(server, trustedProxies) : null;
|
|
260
|
+
exports.REQ_WS_SERVER.listener = async (_) => wss;
|
|
242
261
|
if (this.options.isProductionEnvironment)
|
|
243
262
|
app.set("env", 'production');
|
|
244
263
|
app.use(express_1.default.json({ limit: this.options.jsonLimit ?? '10mb' }));
|
|
@@ -534,6 +553,76 @@ class APIService extends BaseService_1.BaseService {
|
|
|
534
553
|
if (nextLogID > Number.MAX_SAFE_INTEGER - 1000)
|
|
535
554
|
nextLogID = 0;
|
|
536
555
|
}
|
|
556
|
+
static webSocketPath(baseEndPoint, endpoint) {
|
|
557
|
+
const joined = "/" + (baseEndPoint ?? "") + "/" + (endpoint || "ws");
|
|
558
|
+
return joined.replace(/\/{2,}/g, "/").replace(/\/+$/, "") || "/";
|
|
559
|
+
}
|
|
560
|
+
attachWebSocketServer(server, trustedProxies) {
|
|
561
|
+
const opt = this.options.websocketServer ?? {};
|
|
562
|
+
const wsPath = APIService.webSocketPath(this.options.baseEndPoint, opt.endpoint);
|
|
563
|
+
const maxConnections = opt.maxConnections ?? 1000;
|
|
564
|
+
const maxPerIp = opt.maxConnectionsPerIp ?? 50;
|
|
565
|
+
const allowedOrigins = new Set((this.options.corsHostWhiteList ?? []).map(x => String(x).replace(/\/$/, "")));
|
|
566
|
+
const perIp = new Map();
|
|
567
|
+
const wss = new ws_1.WebSocketServer({ noServer: true, maxPayload: opt.maxPayload ?? 256 * 1024 });
|
|
568
|
+
const gateway = new WebSocketServer_1.WebSocketServer(opt.onAuthorize ?? null, {
|
|
569
|
+
authTimeoutMs: opt.authTimeoutMs ?? 10000,
|
|
570
|
+
maxMessagesPerSecond: opt.maxMessagesPerSecond ?? 20,
|
|
571
|
+
});
|
|
572
|
+
const refuse = (socket, status, text) => {
|
|
573
|
+
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
574
|
+
socket.destroy();
|
|
575
|
+
};
|
|
576
|
+
server.on("upgrade", (req, socket, head) => {
|
|
577
|
+
socket.on("error", () => { });
|
|
578
|
+
let pathname = "";
|
|
579
|
+
try {
|
|
580
|
+
pathname = new URL(req.url ?? "", "http://localhost").pathname.replace(/\/+$/, "") || "/";
|
|
581
|
+
}
|
|
582
|
+
catch { }
|
|
583
|
+
if (pathname !== wsPath) {
|
|
584
|
+
if (server.listeners("upgrade").length === 1)
|
|
585
|
+
refuse(socket, 404, "Not Found");
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
const ip = (0, ClientIp_1.clientIp)(req, trustedProxies);
|
|
589
|
+
const origin = req.headers.origin;
|
|
590
|
+
if (origin && !this.noCors) {
|
|
591
|
+
let originNorm = "";
|
|
592
|
+
try {
|
|
593
|
+
originNorm = new URL(String(origin)).origin.replace(/\/$/, "");
|
|
594
|
+
}
|
|
595
|
+
catch { }
|
|
596
|
+
if (!allowedOrigins.has(originNorm)) {
|
|
597
|
+
(0, LogService_1.logWarn)(`WebSocket refused from ${ip}: origin not allowed (${String(origin).slice(0, 200)})`);
|
|
598
|
+
return refuse(socket, 403, "Forbidden");
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (wss.clients.size >= maxConnections) {
|
|
602
|
+
(0, LogService_1.logWarn)(`WebSocket refused from ${ip}: connection limit ${maxConnections} reached`);
|
|
603
|
+
return refuse(socket, 503, "Service Unavailable");
|
|
604
|
+
}
|
|
605
|
+
if ((perIp.get(ip) ?? 0) >= maxPerIp) {
|
|
606
|
+
(0, LogService_1.logWarn)(`WebSocket refused from ${ip}: per-IP limit ${maxPerIp} reached`);
|
|
607
|
+
return refuse(socket, 429, "Too Many Requests");
|
|
608
|
+
}
|
|
609
|
+
wss.handleUpgrade(req, socket, head, ws => {
|
|
610
|
+
perIp.set(ip, (perIp.get(ip) ?? 0) + 1);
|
|
611
|
+
ws.once("close", () => {
|
|
612
|
+
const n = (perIp.get(ip) ?? 1) - 1;
|
|
613
|
+
if (n > 0)
|
|
614
|
+
perIp.set(ip, n);
|
|
615
|
+
else
|
|
616
|
+
perIp.delete(ip);
|
|
617
|
+
});
|
|
618
|
+
gateway.accept(ws, req, ip);
|
|
619
|
+
});
|
|
620
|
+
});
|
|
621
|
+
if (!opt.onAuthorize)
|
|
622
|
+
(0, LogService_1.logWarn)(`WebSocket server at ${wsPath} has no onAuthorize — every connection is accepted without authorization`);
|
|
623
|
+
(0, LogService_1.logAPI)(`WebSocket server attached at ${wsPath}`);
|
|
624
|
+
return gateway;
|
|
625
|
+
}
|
|
537
626
|
async sendResponse(ref, res, data, requestTime, endpoint, req) {
|
|
538
627
|
const ignoreHttpLogging = data.ignoreHttpLogging ?? false;
|
|
539
628
|
delete data.ignoreHttpLogging;
|
|
@@ -187,7 +187,7 @@ class DBService extends BaseService_1.BaseService {
|
|
|
187
187
|
if (value === null || value === undefined)
|
|
188
188
|
return 'NULL';
|
|
189
189
|
const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
|
|
190
|
-
return "'" + stringValue.replace(/[\0\x08\x09\x1a\n\r"'
|
|
190
|
+
return "'" + stringValue.replace(/[\0\x08\x09\x1a\n\r"'\\]/g, (char) => {
|
|
191
191
|
switch (char) {
|
|
192
192
|
case "\0": return "\\0";
|
|
193
193
|
case "\x08": return "\\b";
|
|
@@ -198,7 +198,6 @@ class DBService extends BaseService_1.BaseService {
|
|
|
198
198
|
case "\"":
|
|
199
199
|
case "'":
|
|
200
200
|
case "\\":
|
|
201
|
-
case "%":
|
|
202
201
|
return "\\" + char;
|
|
203
202
|
default: return char;
|
|
204
203
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Signal } from "badmfck-signal";
|
|
2
|
+
import WebSocket from "ws";
|
|
3
|
+
import { IncomingMessage } from "http";
|
|
4
|
+
export declare const S_WS_ON_CONNECTED: Signal<WebSocketConnection>;
|
|
5
|
+
export declare const S_WS_ON_MESSAGE: Signal<{
|
|
6
|
+
connection: WebSocketConnection;
|
|
7
|
+
message: any;
|
|
8
|
+
}>;
|
|
9
|
+
export declare const S_WS_ON_CLOSE: Signal<WebSocketConnection>;
|
|
10
|
+
export declare const WS_CLOSE_UNAUTHORIZED = 4401;
|
|
11
|
+
export declare const WS_CLOSE_AUTH_TIMEOUT = 4408;
|
|
12
|
+
export declare const WS_CLOSE_RATE_LIMIT = 1008;
|
|
13
|
+
export declare const WS_CLOSE_INTERNAL = 1011;
|
|
14
|
+
export type WebSocketAuthorizer = (connection: WebSocketConnection, message: any) => Promise<any> | any;
|
|
15
|
+
export interface IWebSocketConnectionOptions {
|
|
16
|
+
authTimeoutMs: number;
|
|
17
|
+
maxMessagesPerSecond: number;
|
|
18
|
+
}
|
|
19
|
+
export declare class WebSocketConnection {
|
|
20
|
+
authorized: boolean;
|
|
21
|
+
auth: any;
|
|
22
|
+
ws: WebSocket;
|
|
23
|
+
id: number;
|
|
24
|
+
ip: string;
|
|
25
|
+
req: IncomingMessage;
|
|
26
|
+
connectedAt: number;
|
|
27
|
+
constructor(ws: WebSocket, req: IncomingMessage, ip: string);
|
|
28
|
+
get isOpen(): boolean;
|
|
29
|
+
send(data: any): boolean;
|
|
30
|
+
close(code?: number, reason?: string): void;
|
|
31
|
+
}
|
|
32
|
+
export declare class WebSocketServer {
|
|
33
|
+
#private;
|
|
34
|
+
connections: WebSocketConnection[];
|
|
35
|
+
constructor(onAuthorize: WebSocketAuthorizer | null, options: IWebSocketConnectionOptions);
|
|
36
|
+
accept(ws: WebSocket, req: IncomingMessage, ip: string): void;
|
|
37
|
+
broadcast(data: any, filter?: (c: WebSocketConnection) => boolean): number;
|
|
38
|
+
static parse(data: WebSocket.RawData, isBinary: boolean): any;
|
|
39
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
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.WebSocketServer = exports.WebSocketConnection = exports.WS_CLOSE_INTERNAL = exports.WS_CLOSE_RATE_LIMIT = exports.WS_CLOSE_AUTH_TIMEOUT = exports.WS_CLOSE_UNAUTHORIZED = exports.S_WS_ON_CLOSE = exports.S_WS_ON_MESSAGE = exports.S_WS_ON_CONNECTED = void 0;
|
|
7
|
+
const badmfck_signal_1 = require("badmfck-signal");
|
|
8
|
+
const ws_1 = __importDefault(require("ws"));
|
|
9
|
+
const LogService_1 = require("./LogService");
|
|
10
|
+
exports.S_WS_ON_CONNECTED = new badmfck_signal_1.Signal("S_WS_ON_CONNECTED");
|
|
11
|
+
exports.S_WS_ON_MESSAGE = new badmfck_signal_1.Signal("S_WS_ON_MESSAGE");
|
|
12
|
+
exports.S_WS_ON_CLOSE = new badmfck_signal_1.Signal("S_WS_ON_CLOSE");
|
|
13
|
+
exports.WS_CLOSE_UNAUTHORIZED = 4401;
|
|
14
|
+
exports.WS_CLOSE_AUTH_TIMEOUT = 4408;
|
|
15
|
+
exports.WS_CLOSE_RATE_LIMIT = 1008;
|
|
16
|
+
exports.WS_CLOSE_INTERNAL = 1011;
|
|
17
|
+
var WS_NEXT_ID = 1;
|
|
18
|
+
class WebSocketConnection {
|
|
19
|
+
authorized = false;
|
|
20
|
+
auth = undefined;
|
|
21
|
+
ws;
|
|
22
|
+
id;
|
|
23
|
+
ip;
|
|
24
|
+
req;
|
|
25
|
+
connectedAt = Date.now();
|
|
26
|
+
constructor(ws, req, ip) {
|
|
27
|
+
this.ws = ws;
|
|
28
|
+
this.req = req;
|
|
29
|
+
this.ip = ip;
|
|
30
|
+
this.id = WS_NEXT_ID++;
|
|
31
|
+
}
|
|
32
|
+
get isOpen() {
|
|
33
|
+
return this.ws.readyState === ws_1.default.OPEN;
|
|
34
|
+
}
|
|
35
|
+
send(data) {
|
|
36
|
+
if (!this.isOpen)
|
|
37
|
+
return false;
|
|
38
|
+
const payload = typeof data === "string" || Buffer.isBuffer(data) ? data : JSON.stringify(data);
|
|
39
|
+
this.ws.send(payload, err => { if (err)
|
|
40
|
+
(0, LogService_1.logWarn)(`WebSocket ${this.id}: send failed — ${err.message}`); });
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
close(code = 1000, reason = "") {
|
|
44
|
+
if (this.ws.readyState === ws_1.default.OPEN || this.ws.readyState === ws_1.default.CONNECTING)
|
|
45
|
+
this.ws.close(code, reason);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
exports.WebSocketConnection = WebSocketConnection;
|
|
49
|
+
class WebSocketServer {
|
|
50
|
+
#onAuthorize;
|
|
51
|
+
#options;
|
|
52
|
+
connections = [];
|
|
53
|
+
constructor(onAuthorize, options) {
|
|
54
|
+
this.#onAuthorize = onAuthorize;
|
|
55
|
+
this.#options = options;
|
|
56
|
+
}
|
|
57
|
+
accept(ws, req, ip) {
|
|
58
|
+
const connection = new WebSocketConnection(ws, req, ip);
|
|
59
|
+
ws.on("error", err => (0, LogService_1.logWarn)(`WebSocket ${connection.id} (${ip}): ${err.message}`));
|
|
60
|
+
this.#limitMessageRate(connection);
|
|
61
|
+
let stage = "waiting";
|
|
62
|
+
const timer = setTimeout(() => {
|
|
63
|
+
if (stage === "done")
|
|
64
|
+
return;
|
|
65
|
+
stage = "done";
|
|
66
|
+
(0, LogService_1.logWarn)(`WebSocket ${connection.id} (${ip}) closed: not authorized within ${this.#options.authTimeoutMs} ms`);
|
|
67
|
+
connection.close(exports.WS_CLOSE_AUTH_TIMEOUT, "Authorization timeout");
|
|
68
|
+
}, this.#options.authTimeoutMs);
|
|
69
|
+
ws.on("close", () => {
|
|
70
|
+
clearTimeout(timer);
|
|
71
|
+
stage = "done";
|
|
72
|
+
if (!connection.authorized)
|
|
73
|
+
return;
|
|
74
|
+
connection.authorized = false;
|
|
75
|
+
this.connections = this.connections.filter(c => c !== connection);
|
|
76
|
+
this.#invoke(exports.S_WS_ON_CLOSE, connection);
|
|
77
|
+
});
|
|
78
|
+
ws.on("message", async (data, isBinary) => {
|
|
79
|
+
const message = WebSocketServer.parse(data, isBinary);
|
|
80
|
+
if (connection.authorized) {
|
|
81
|
+
this.#invoke(exports.S_WS_ON_MESSAGE, { connection, message });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (stage !== "waiting")
|
|
85
|
+
return;
|
|
86
|
+
stage = "checking";
|
|
87
|
+
let result;
|
|
88
|
+
try {
|
|
89
|
+
result = this.#onAuthorize ? await this.#onAuthorize(connection, message) : true;
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
if (stage !== "checking")
|
|
93
|
+
return;
|
|
94
|
+
stage = "done";
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
(0, LogService_1.logError)(`WebSocket ${connection.id} (${ip}): onAuthorize threw — ${e instanceof Error ? e.message : String(e)}`);
|
|
97
|
+
connection.close(exports.WS_CLOSE_INTERNAL, "Authorization failed");
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (stage !== "checking" || !connection.isOpen)
|
|
101
|
+
return;
|
|
102
|
+
stage = "done";
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
if (result === false || result === null || result === undefined) {
|
|
105
|
+
(0, LogService_1.logWarn)(`WebSocket ${connection.id} (${ip}) refused: unauthorized`);
|
|
106
|
+
connection.close(exports.WS_CLOSE_UNAUTHORIZED, "Unauthorized");
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
connection.authorized = true;
|
|
110
|
+
if (result !== true)
|
|
111
|
+
connection.auth = result;
|
|
112
|
+
this.connections.push(connection);
|
|
113
|
+
this.#invoke(exports.S_WS_ON_CONNECTED, connection);
|
|
114
|
+
});
|
|
115
|
+
if (!this.#onAuthorize) {
|
|
116
|
+
stage = "done";
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
connection.authorized = true;
|
|
119
|
+
this.connections.push(connection);
|
|
120
|
+
this.#invoke(exports.S_WS_ON_CONNECTED, connection);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
broadcast(data, filter) {
|
|
124
|
+
let n = 0;
|
|
125
|
+
for (const c of this.connections)
|
|
126
|
+
if ((!filter || filter(c)) && c.send(data))
|
|
127
|
+
n++;
|
|
128
|
+
return n;
|
|
129
|
+
}
|
|
130
|
+
static parse(data, isBinary) {
|
|
131
|
+
if (isBinary)
|
|
132
|
+
return Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
133
|
+
const text = data.toString();
|
|
134
|
+
try {
|
|
135
|
+
return JSON.parse(text);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return text;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
#invoke(signal, data) {
|
|
142
|
+
try {
|
|
143
|
+
signal.invoke(data);
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
(0, LogService_1.logError)(`WebSocket signal handler threw: ${e instanceof Error ? e.message : String(e)}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
#limitMessageRate(connection) {
|
|
150
|
+
const ws = connection.ws, max = this.#options.maxMessagesPerSecond;
|
|
151
|
+
let windowStart = Date.now(), count = 0, over = false;
|
|
152
|
+
const emit = ws.emit.bind(ws);
|
|
153
|
+
ws.emit = ((event, ...args) => {
|
|
154
|
+
if (event !== "message")
|
|
155
|
+
return emit(event, ...args);
|
|
156
|
+
if (over)
|
|
157
|
+
return false;
|
|
158
|
+
const now = Date.now();
|
|
159
|
+
if (now - windowStart >= 1000) {
|
|
160
|
+
windowStart = now;
|
|
161
|
+
count = 0;
|
|
162
|
+
}
|
|
163
|
+
if (++count > max) {
|
|
164
|
+
over = true;
|
|
165
|
+
(0, LogService_1.logWarn)(`WebSocket ${connection.id} (${connection.ip}) closed: over ${max} messages/s`);
|
|
166
|
+
connection.close(exports.WS_CLOSE_RATE_LIMIT, "Rate limit exceeded");
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
return emit(event, ...args);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
exports.WebSocketServer = WebSocketServer;
|
|
@@ -53,8 +53,12 @@ export declare class MysqlAdapter implements IDBAdapter {
|
|
|
53
53
|
getConnection(transactionId?: number): Promise<mysql.PoolConnection | IDBError>;
|
|
54
54
|
withTimeout<T>(promise: Promise<T>, ms: number, query: string): Promise<T>;
|
|
55
55
|
query(request: IDBQuery, conn?: mysql.PoolConnection): Promise<IDBResult>;
|
|
56
|
+
killQuery(conn: mysql.PoolConnection): void;
|
|
57
|
+
destroyConnection(conn: mysql.PoolConnection): void;
|
|
56
58
|
finalizeConnection(conn: mysql.PoolConnection): void;
|
|
57
59
|
prepareQuery(request: IDBQuery): string;
|
|
60
|
+
static substitute(text: string, values: Map<string, string>): string;
|
|
61
|
+
static quoteIdentifier(name: string): string;
|
|
58
62
|
static safeReplace(query: string, key: string, value: string): string;
|
|
59
63
|
static prepareQueryFieldValue(field: IDBQueryField): string | number | boolean | null | undefined;
|
|
60
64
|
prepareCountQuery(query: string): string;
|