badmfck-api-server 5.0.15 → 5.0.17
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 +667 -0
- package/dist/apiServer/APIService.d.ts +16 -4
- package/dist/apiServer/APIService.js +92 -3
- package/dist/apiServer/WebSocketServer.d.ts +39 -0
- package/dist/apiServer/WebSocketServer.js +173 -0
- package/dist/apiServer/deployment/Activate.js +1 -1
- package/dist/apiServer/deployment/Backups.js +1 -1
- package/dist/apiServer/deployment/Deploy.js +1 -1
- package/dist/apiServer/deployment/Deployer.js +5 -5
- package/dist/apiServer/deployment/DeployerService.d.ts +12 -0
- package/dist/apiServer/deployment/DeployerService.js +51 -21
- package/dist/apiServer/deployment/HashPassword.d.ts +1 -0
- package/dist/apiServer/deployment/HashPassword.js +91 -0
- package/dist/apiServer/deployment/NginxHelper.d.ts +1 -1
- package/dist/apiServer/deployment/NginxHelper.js +3 -0
- package/dist/apiServer/deployment/Restore.js +1 -1
- package/dist/apiServer/deployment/Status.js +1 -1
- package/dist/apiServer/deployment/cli.js +11 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +1 -0
- package/dist/apiServer/deployment/cliCommon.js +4 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +24 -0
- package/dist/apiServer/monitor/AccessStore.js +146 -0
- package/dist/apiServer/monitor/Monitor.js +7 -3
- package/dist/apiServer/monitor/MonitorAuth.d.ts +4 -2
- package/dist/apiServer/monitor/MonitorAuth.js +17 -7
- package/dist/apiServer/monitor/index.html +70 -61
- package/dist/index.d.ts +11 -0
- package/dist/index.js +27 -1
- package/monitoring.help.md +1 -1
- package/package.json +1 -1
|
@@ -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;
|
|
@@ -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;
|
|
@@ -30,7 +30,7 @@ async function Activate(opt, scheme) {
|
|
|
30
30
|
console.log(`Activating${scheme ? ` slot=${scheme}` : " (auto: lastDeployed)"} for ${opt.name} at ${switchUrl}`);
|
|
31
31
|
const startedAt = Date.now();
|
|
32
32
|
const response = await __1.Http.post(switchUrl, requestBody, {
|
|
33
|
-
headers: { authorization: `Bearer ${authToken}
|
|
33
|
+
headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
|
|
34
34
|
timeoutMs: 60 * 1000,
|
|
35
35
|
retry: { enabled: false },
|
|
36
36
|
});
|
|
@@ -8,7 +8,7 @@ async function Backups(opt) {
|
|
|
8
8
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
9
9
|
const { red, yellow, blue, green, dim, bold } = (0, cliCommon_1.palette)();
|
|
10
10
|
const r = await __1.Http.post((0, cliCommon_1.deployerUrl)(opt, "backups"), { name: opt.name }, {
|
|
11
|
-
headers:
|
|
11
|
+
headers: (0, cliCommon_1.deployerHeaders)(opt), timeoutMs: 30000, retry: { enabled: false },
|
|
12
12
|
});
|
|
13
13
|
const err = (0, cliCommon_1.responseError)(r);
|
|
14
14
|
if (err) {
|
|
@@ -206,7 +206,7 @@ async function Deploy(opt) {
|
|
|
206
206
|
bodyTimeout: 5 * 60 * 1000,
|
|
207
207
|
});
|
|
208
208
|
const uploadResponse = await __1.Http.post(opt.host, formData, {
|
|
209
|
-
headers: { authorization: `Bearer ${authToken}
|
|
209
|
+
headers: { authorization: `Bearer ${authToken}`, "x-deployer-login": String(opt.username) },
|
|
210
210
|
dispatcher: uploadAgent,
|
|
211
211
|
timeoutMs: 5 * 60 * 1000,
|
|
212
212
|
retry: { enabled: false },
|
|
@@ -72,20 +72,20 @@ class Deployer extends BaseEndpoint_1.BaseEndpoint {
|
|
|
72
72
|
async file(req) {
|
|
73
73
|
if (!req.files)
|
|
74
74
|
throw { ...DefaultErrors_1.default.FILE_NOT_EXISTS, details: "No files were uploaded" };
|
|
75
|
-
const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization });
|
|
75
|
+
const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
76
76
|
return { data: result };
|
|
77
77
|
}
|
|
78
78
|
async switchSlot(req) {
|
|
79
|
-
return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization });
|
|
79
|
+
return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
80
80
|
}
|
|
81
81
|
async status(req) {
|
|
82
|
-
return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization });
|
|
82
|
+
return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
83
83
|
}
|
|
84
84
|
async backups(req) {
|
|
85
|
-
return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization });
|
|
85
|
+
return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
86
86
|
}
|
|
87
87
|
async restore(req) {
|
|
88
|
-
return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization });
|
|
88
|
+
return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"] });
|
|
89
89
|
}
|
|
90
90
|
async slot(req) {
|
|
91
91
|
return await DeployerService_1.REQ_DEPLOYMENT_SLOT.request({ name: req.data.name, token: req.data.token, slot: req.data.slot });
|
|
@@ -29,6 +29,7 @@ export interface IDeployerServiceOptions {
|
|
|
29
29
|
}
|
|
30
30
|
export declare const REQ_DEPLOYMENT_PROCEED: Req<{
|
|
31
31
|
auth: string;
|
|
32
|
+
authLogin?: string;
|
|
32
33
|
name: string;
|
|
33
34
|
token: string;
|
|
34
35
|
files: {
|
|
@@ -37,12 +38,14 @@ export declare const REQ_DEPLOYMENT_PROCEED: Req<{
|
|
|
37
38
|
}, any>;
|
|
38
39
|
export declare const REQ_DEPLOYMENT_SWITCH: Req<{
|
|
39
40
|
auth?: string;
|
|
41
|
+
authLogin?: string;
|
|
40
42
|
name: string;
|
|
41
43
|
token: string;
|
|
42
44
|
scheme?: "blue" | "green";
|
|
43
45
|
}, any>;
|
|
44
46
|
export declare const REQ_DEPLOYMENT_STATUS: Req<{
|
|
45
47
|
auth?: string;
|
|
48
|
+
authLogin?: string;
|
|
46
49
|
name?: string;
|
|
47
50
|
}, any>;
|
|
48
51
|
export declare const REQ_DEPLOYMENT_SLOT: Req<{
|
|
@@ -52,10 +55,12 @@ export declare const REQ_DEPLOYMENT_SLOT: Req<{
|
|
|
52
55
|
}, any>;
|
|
53
56
|
export declare const REQ_DEPLOYMENT_BACKUPS: Req<{
|
|
54
57
|
auth?: string;
|
|
58
|
+
authLogin?: string;
|
|
55
59
|
name: string;
|
|
56
60
|
}, any>;
|
|
57
61
|
export declare const REQ_DEPLOYMENT_RESTORE: Req<{
|
|
58
62
|
auth?: string;
|
|
63
|
+
authLogin?: string;
|
|
59
64
|
name: string;
|
|
60
65
|
token: string;
|
|
61
66
|
backup: string;
|
|
@@ -76,6 +81,7 @@ export declare class DeployerService extends BaseService {
|
|
|
76
81
|
private _watchSetup;
|
|
77
82
|
proceed(data: {
|
|
78
83
|
auth?: string;
|
|
84
|
+
authLogin?: string;
|
|
79
85
|
name: string;
|
|
80
86
|
token: string;
|
|
81
87
|
files: {
|
|
@@ -101,6 +107,7 @@ export declare class DeployerService extends BaseService {
|
|
|
101
107
|
}>;
|
|
102
108
|
switchSlot(data: {
|
|
103
109
|
auth?: string;
|
|
110
|
+
authLogin?: string;
|
|
104
111
|
name: string;
|
|
105
112
|
token: string;
|
|
106
113
|
scheme?: "blue" | "green";
|
|
@@ -122,6 +129,7 @@ export declare class DeployerService extends BaseService {
|
|
|
122
129
|
}>;
|
|
123
130
|
status(data: {
|
|
124
131
|
auth?: string;
|
|
132
|
+
authLogin?: string;
|
|
125
133
|
name?: string;
|
|
126
134
|
}): Promise<{
|
|
127
135
|
data?: undefined;
|
|
@@ -142,6 +150,7 @@ export declare class DeployerService extends BaseService {
|
|
|
142
150
|
private static _backupRoot;
|
|
143
151
|
listBackups(data: {
|
|
144
152
|
auth?: string;
|
|
153
|
+
authLogin?: string;
|
|
145
154
|
name: string;
|
|
146
155
|
}): Promise<{
|
|
147
156
|
data?: undefined;
|
|
@@ -163,6 +172,7 @@ export declare class DeployerService extends BaseService {
|
|
|
163
172
|
}>;
|
|
164
173
|
restoreBackup(data: {
|
|
165
174
|
auth?: string;
|
|
175
|
+
authLogin?: string;
|
|
166
176
|
name: string;
|
|
167
177
|
token: string;
|
|
168
178
|
backup: string;
|
|
@@ -220,6 +230,8 @@ export declare class DeployerService extends BaseService {
|
|
|
220
230
|
private _statusUrl;
|
|
221
231
|
private _writeBlueGreenFiles;
|
|
222
232
|
tokensMatch(a: string | undefined, b: string | undefined): boolean;
|
|
233
|
+
private _warnPlaintextUsers;
|
|
234
|
+
static PLAINTEXT_ERROR: string;
|
|
223
235
|
private _checkUserAuth;
|
|
224
236
|
private static _extractPort;
|
|
225
237
|
private _renderNginx;
|