badmfck-api-server 5.0.16 → 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.
@@ -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
- monitor?: IMonitorUser[];
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
- exports.REQ_MONITOR_USERS.listener = async () => this.options.access.monitor ?? [];
170
- exports.REQ_DOC_USERS.listener = async () => this.options.access.documentation ?? [];
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;
@@ -1,5 +1,5 @@
1
1
  import { IError } from "../structures/Interfaces";
2
- export declare const DEFAULT_SERVER_TEMPLATE = "# Seeded by deployer for _{{DOMAIN}}_. SAFE TO EDIT.\n# Deployer NEVER overwrites this file after the initial seed.\n# Add SSL by running: certbot --nginx -d _{{DOMAIN}}_\n\nserver {\n server_name _{{DOMAIN}}_;\n listen 80;\n\n location / {\n proxy_pass http://_{{UPSTREAM}}_;\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 60s;\n }\n}\n";
2
+ export declare const DEFAULT_SERVER_TEMPLATE = "# Seeded by deployer for _{{DOMAIN}}_. SAFE TO EDIT.\n# Deployer NEVER overwrites this file after the initial seed.\n# Add SSL by running: certbot --nginx -d _{{DOMAIN}}_\n\nserver {\n server_name _{{DOMAIN}}_;\n listen 80;\n\n location / {\n proxy_pass http://_{{UPSTREAM}}_;\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n # WebSocket: pass the upgrade handshake through to the app.\n proxy_set_header Upgrade $http_upgrade;\n proxy_set_header Connection \"upgrade\";\n proxy_read_timeout 60s;\n }\n}\n";
3
3
  export declare class NginxHelper {
4
4
  static writeUpstream(filePath: string, upstreamName: string, port: string): IError | null;
5
5
  static seedServerConfig(filePath: string, template: string, values: Record<string, string>): {
@@ -25,6 +25,9 @@ server {
25
25
  proxy_set_header X-Real-IP $remote_addr;
26
26
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
27
27
  proxy_set_header X-Forwarded-Proto $scheme;
28
+ # WebSocket: pass the upgrade handshake through to the app.
29
+ proxy_set_header Upgrade $http_upgrade;
30
+ proxy_set_header Connection "upgrade";
28
31
  proxy_read_timeout 60s;
29
32
  }
30
33
  }
@@ -0,0 +1,24 @@
1
+ import type { IMonitorUser, IDocumentationUser } from "../APIService";
2
+ export interface IAccess {
3
+ monitor?: IMonitorUser[];
4
+ documentation?: IDocumentationUser[];
5
+ }
6
+ export declare class AccessStore {
7
+ private onChange?;
8
+ private current;
9
+ private hash;
10
+ private refusedHash;
11
+ private file;
12
+ private debounce;
13
+ constructor(source: IAccess | string | undefined | null, onChange?: ((prev: IAccess, next: IAccess) => void) | undefined);
14
+ get monitor(): IMonitorUser[];
15
+ get documentation(): IDocumentationUser[];
16
+ static validate(value: any): string | null;
17
+ private loadSync;
18
+ private reload;
19
+ private accept;
20
+ private refuse;
21
+ private apply;
22
+ private warnPermissions;
23
+ private watch;
24
+ }
@@ -0,0 +1,146 @@
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.AccessStore = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const LogService_1 = require("../LogService");
11
+ const ROLES = ["admin", "it", "analytic"];
12
+ class AccessStore {
13
+ onChange;
14
+ current = {};
15
+ hash = "";
16
+ refusedHash = "";
17
+ file = null;
18
+ debounce = null;
19
+ constructor(source, onChange) {
20
+ this.onChange = onChange;
21
+ if (typeof source !== "string") {
22
+ this.apply(source ?? {});
23
+ return;
24
+ }
25
+ this.file = path_1.default.resolve(source);
26
+ this.loadSync();
27
+ this.watch();
28
+ }
29
+ get monitor() { return this.current.monitor ?? []; }
30
+ get documentation() { return this.current.documentation ?? []; }
31
+ static validate(value) {
32
+ if (!value || typeof value !== "object" || Array.isArray(value))
33
+ return "root must be an object";
34
+ for (const list of ["monitor", "documentation"]) {
35
+ const users = value[list];
36
+ if (users === undefined)
37
+ continue;
38
+ if (!Array.isArray(users))
39
+ return `"${list}" must be an array`;
40
+ const seen = new Set();
41
+ for (const [i, u] of users.entries()) {
42
+ const at = `${list}[${i}]`;
43
+ if (!u || typeof u !== "object")
44
+ return `${at} must be an object`;
45
+ if (typeof u.login !== "string" || !u.login.trim())
46
+ return `${at}.login must be a non-empty string`;
47
+ if (typeof u.password !== "string")
48
+ return `${at}.password must be a string`;
49
+ if (seen.has(u.login))
50
+ return `${at}: duplicate login "${u.login}"`;
51
+ seen.add(u.login);
52
+ if (u.role !== undefined && !ROLES.includes(u.role))
53
+ return `${at}.role must be one of ${ROLES.join(", ")}`;
54
+ if (u.totpSecret !== undefined && typeof u.totpSecret !== "string")
55
+ return `${at}.totpSecret must be a string`;
56
+ if (u.endpoints !== undefined && (!Array.isArray(u.endpoints) || u.endpoints.some((e) => typeof e !== "string")))
57
+ return `${at}.endpoints must be an array of strings`;
58
+ }
59
+ }
60
+ return null;
61
+ }
62
+ loadSync() {
63
+ try {
64
+ this.accept(fs_1.default.readFileSync(this.file, "utf-8"), true);
65
+ }
66
+ catch (e) {
67
+ (0, LogService_1.logError)(`Access file ${this.file}: ${e.code === "ENOENT" ? "not found" : e.message} — no one can access the monitor and documentation until it is fixed`);
68
+ }
69
+ }
70
+ async reload() {
71
+ let raw;
72
+ try {
73
+ raw = await fs_1.default.promises.readFile(this.file, "utf-8");
74
+ }
75
+ catch (e) {
76
+ if (e.code !== "ENOENT")
77
+ (0, LogService_1.logWarn)(`Access file ${this.file}: ${e.message} — keeping the previous access`);
78
+ return;
79
+ }
80
+ this.accept(raw, false);
81
+ }
82
+ accept(raw, initial) {
83
+ const hash = crypto_1.default.createHash("sha256").update(raw).digest("hex");
84
+ if (hash === this.hash || hash === this.refusedHash)
85
+ return;
86
+ let parsed;
87
+ try {
88
+ parsed = JSON.parse(raw);
89
+ }
90
+ catch (e) {
91
+ this.refusedHash = hash;
92
+ return this.refuse(`invalid JSON (${e.message})`, initial);
93
+ }
94
+ const problem = AccessStore.validate(parsed);
95
+ if (problem)
96
+ this.refusedHash = hash;
97
+ if (problem)
98
+ return this.refuse(problem, initial);
99
+ this.hash = hash;
100
+ this.refusedHash = "";
101
+ this.warnPermissions();
102
+ this.apply({ monitor: parsed.monitor, documentation: parsed.documentation });
103
+ (0, LogService_1.logInfo)(`Access ${initial ? "loaded" : "reloaded"} from ${this.file}: ${this.monitor.length} monitor, ${this.documentation.length} documentation user(s)`);
104
+ }
105
+ refuse(reason, initial) {
106
+ if (initial)
107
+ (0, LogService_1.logError)(`Access file ${this.file}: ${reason} — no one can access the monitor and documentation until it is fixed`);
108
+ else
109
+ (0, LogService_1.logError)(`Access file ${this.file}: ${reason} — change ignored, keeping the previous access`);
110
+ }
111
+ apply(next) {
112
+ const prev = this.current;
113
+ this.current = next;
114
+ try {
115
+ this.onChange?.(prev, next);
116
+ }
117
+ catch (e) {
118
+ (0, LogService_1.logError)(`Access change handler threw: ${e instanceof Error ? e.message : String(e)}`);
119
+ }
120
+ }
121
+ warnPermissions() {
122
+ try {
123
+ const mode = fs_1.default.statSync(this.file).mode;
124
+ if (mode & 0o077)
125
+ (0, LogService_1.logWarn)(`Access file ${this.file} is readable by other users (mode ${(mode & 0o777).toString(8)}) — chmod 600 it`);
126
+ }
127
+ catch { }
128
+ }
129
+ watch() {
130
+ const dir = path_1.default.dirname(this.file), name = path_1.default.basename(this.file);
131
+ try {
132
+ fs_1.default.watch(dir, (_event, filename) => {
133
+ if (filename && filename !== name)
134
+ return;
135
+ if (this.debounce)
136
+ clearTimeout(this.debounce);
137
+ this.debounce = setTimeout(() => { this.debounce = null; this.reload(); }, 200);
138
+ }).unref();
139
+ }
140
+ catch (e) {
141
+ (0, LogService_1.logWarn)(`Access file: cannot watch ${dir} (${e.message}) — changes are picked up within a minute`);
142
+ }
143
+ setInterval(() => this.reload(), 60_000).unref();
144
+ }
145
+ }
146
+ exports.AccessStore = AccessStore;
@@ -42,9 +42,6 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
42
42
  super("sm");
43
43
  this.apiServiceOptions = options;
44
44
  MonitorAuth_1.MonitorAuth.configure({ authFile: options.monitorAuthFile, authDir: options.monitorAuthDir, projectName: options.projectName });
45
- const plain = MonitorAuth_1.MonitorAuth.plaintextLogins(options.access?.monitor ?? []);
46
- if (plain.length)
47
- (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`);
48
45
  this.registerEndpoints([
49
46
  { ignoreInterceptor: true, endpoint: "html", handler: this.html },
50
47
  { ignoreInterceptor: true, endpoint: "log", handler: this.logs },
@@ -347,7 +344,11 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
347
344
  const login = await this.checkAuthentication(req);
348
345
  const users = await APIService_1.REQ_MONITOR_USERS.request();
349
346
  const user = users?.find(u => u?.login === login);
350
- if (!MonitorAuth_1.MonitorAuth.roleAllows(user?.role, capability)) {
347
+ if (!user) {
348
+ MonitorAuth_1.MonitorAuth.revokeAllFor(login);
349
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "User no longer has monitor access" };
350
+ }
351
+ if (!MonitorAuth_1.MonitorAuth.roleAllows(user.role, capability)) {
351
352
  const { role } = MonitorAuth_1.MonitorAuth.describeRole(user?.role);
352
353
  (0, LogService_1.logWarn)(`Monitor access denied: "${login}" (role ${role}) tried a "${capability}" endpoint`);
353
354
  throw { ...DefaultErrors_1.default.FORBIDDEN, details: `Role "${role}" is not allowed to access ${capability} endpoints` };
@@ -1,8 +1,8 @@
1
1
  <!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
- <!-- Build: 2026-10-28T15:37:14.586Z | Version: 1.0.26 -->
5
- <script>var __ver = "1.0.26";</script>
4
+ <!-- Build: 2026-11-03T16:43:22.836Z | Version: 1.0.27 -->
5
+ <script>var __ver = "1.0.27";</script>
6
6
  <meta charset="UTF-8" />
7
7
  <link rel="icon" type="image/svg+xml" href="/vite.svg" />
8
8
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
@@ -528,4 +528,4 @@ const z2={background:"#a7a7a7",backgroundSelected:"#66bb6a",toggle:"#FFFFFF"},U2
528
528
  <body>
529
529
  <div id="root"></div>
530
530
  </body>
531
- </html>
531
+ </html>
package/dist/index.d.ts CHANGED
@@ -23,3 +23,14 @@ import { InterceptorPayAuth } from "./apiServer/interceptors/InterceptorPayAuth"
23
23
  export { MicroserviceHost, MicroserviceClient, Http, ZipUtils, UID, YYYYMMDDHH, JSONStableStringify, APIService, Initializer, LocalRequest, ValidationModel, MysqlService, TimeframeService, Validator, LogService, DataProvider, ErrorUtils, ExternalService, DBService, Deploy, Activate, InterceptorPayAuth, S_MONITOR_REGISTRATE_ACTION, S_MONITOR_RESTART_REQUESTED, ProcessMonitor };
24
24
  export type { IBlueGreenState, IBlueGreenStateOptions } from "./apiServer/deployment/BlueGreenState";
25
25
  export { S_BLUEGREEN_STATE_CHANGED } from "./apiServer/deployment/BlueGreenState";
26
+ export { REQ_WS_SERVER } from "./apiServer/APIService";
27
+ export type { IWebSocketServerOptions } from "./apiServer/APIService";
28
+ export { WebSocketServer, WebSocketConnection, S_WS_ON_CONNECTED, S_WS_ON_MESSAGE, S_WS_ON_CLOSE, WS_CLOSE_UNAUTHORIZED, WS_CLOSE_AUTH_TIMEOUT, WS_CLOSE_RATE_LIMIT, WS_CLOSE_INTERNAL } from "./apiServer/WebSocketServer";
29
+ export type { WebSocketAuthorizer } from "./apiServer/WebSocketServer";
30
+ export { getDefaultOptions } from "./apiServer/APIService";
31
+ export type { APIServiceOptions, IInterceptor, IMonitorUser, IDocumentationUser } from "./apiServer/APIService";
32
+ export { BaseEndpoint } from "./apiServer/BaseEndpoint";
33
+ export { default as DefaultErrors } from "./apiServer/structures/DefaultErrors";
34
+ export type { HTTPRequestVO, TransferPacketVO, IError } from "./apiServer/structures/Interfaces";
35
+ export { logInfo, logWarn, logError, logCrit } from "./apiServer/LogService";
36
+ export type { IAccess } from "./apiServer/monitor/AccessStore";