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
|
@@ -34,6 +34,8 @@ class MysqlAdapter {
|
|
|
34
34
|
statFrames = new Map();
|
|
35
35
|
constructor(options) {
|
|
36
36
|
this.options = options;
|
|
37
|
+
if ([options.host, options.user, options.database, options.password].some(v => typeof v === "string" && v.startsWith("_")))
|
|
38
|
+
(0, LogService_1.logWarn)("MysqlAdapter", "DB credentials prefixed with \"_\" are decrypted with a key built into this public package — anyone can decrypt them; this hides values, it doesn't protect them. Keep credentials in a file readable only by the service user instead.");
|
|
37
39
|
if (this.options.host.startsWith("_"))
|
|
38
40
|
this.options.host = decrypt(this.options.host.substring(1)) ?? this.options.host;
|
|
39
41
|
if (this.options.user.startsWith("_"))
|
|
@@ -136,27 +138,29 @@ class MysqlAdapter {
|
|
|
136
138
|
return;
|
|
137
139
|
}
|
|
138
140
|
this.isCleanupRunning = true;
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
141
|
+
try {
|
|
142
|
+
const now = Date.now();
|
|
143
|
+
const count = this.transactions.length;
|
|
144
|
+
const removedIDs = [];
|
|
145
|
+
for (let i of this.transactions) {
|
|
146
|
+
if (now - i.timestamp > this.maxTransactionWaitTime) {
|
|
147
|
+
(0, LogService_1.logError)("Release transaction connection due to timeout");
|
|
148
|
+
await this.rollbackTransaction(i, true);
|
|
149
|
+
removedIDs.push(i.id);
|
|
150
|
+
}
|
|
147
151
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
(
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
for (let i = 0; i < this.options.connectionLimit; i++) {
|
|
156
|
-
this.query({ query: "SELECT 1 @NOLIMIT" });
|
|
152
|
+
this.transactions = this.transactions.filter(i => !removedIDs.includes(i.id));
|
|
153
|
+
if (this.options.debug && count - this.transactions.length > 0)
|
|
154
|
+
(0, LogService_1.logDB)("Removed: ", count - this.transactions.length);
|
|
155
|
+
if (this.pool && Date.now() - this.lastSuccessQueryTime > this.pingInterval) {
|
|
156
|
+
for (let i = 0; i < this.options.connectionLimit; i++) {
|
|
157
|
+
this.query({ query: "SELECT 1 @NOLIMIT" });
|
|
158
|
+
}
|
|
157
159
|
}
|
|
158
160
|
}
|
|
159
|
-
|
|
161
|
+
finally {
|
|
162
|
+
this.isCleanupRunning = false;
|
|
163
|
+
}
|
|
160
164
|
}, 1000 * 30);
|
|
161
165
|
setInterval(() => {
|
|
162
166
|
if (!this.failReportFileStream)
|
|
@@ -550,8 +554,15 @@ class MysqlAdapter {
|
|
|
550
554
|
MonitorService_1.S_STAT_REGISTRATE_SQL_REQUEST.invoke({ success: false, query });
|
|
551
555
|
this.collectStat(query, Date.now() - executionStartTime, true);
|
|
552
556
|
}
|
|
553
|
-
|
|
554
|
-
|
|
557
|
+
const timedOut = e?.code === "TIME_OUT";
|
|
558
|
+
if (timedOut)
|
|
559
|
+
this.killQuery(conn);
|
|
560
|
+
if (!request.transactionID && doCloseConnection) {
|
|
561
|
+
if (timedOut)
|
|
562
|
+
this.destroyConnection(conn);
|
|
563
|
+
else
|
|
564
|
+
this.finalizeConnection(conn);
|
|
565
|
+
}
|
|
555
566
|
else if (request.transactionID && request.throwable) {
|
|
556
567
|
await this.rollbackTransaction(this.transactions.find(i => i.id === request.transactionID));
|
|
557
568
|
}
|
|
@@ -585,6 +596,21 @@ class MysqlAdapter {
|
|
|
585
596
|
};
|
|
586
597
|
}
|
|
587
598
|
}
|
|
599
|
+
killQuery(conn) {
|
|
600
|
+
const threadId = conn?.threadId;
|
|
601
|
+
if (!this.pool || !threadId)
|
|
602
|
+
return;
|
|
603
|
+
this.pool.query("KILL QUERY " + Number(threadId)).catch(e => (0, LogService_1.logError)("MysqlAdapter", `Can't kill timed-out query on thread ${threadId}: ${e?.message ?? e}`));
|
|
604
|
+
}
|
|
605
|
+
destroyConnection(conn) {
|
|
606
|
+
try {
|
|
607
|
+
conn.removeAllListeners();
|
|
608
|
+
conn.destroy();
|
|
609
|
+
}
|
|
610
|
+
catch (e) {
|
|
611
|
+
(0, LogService_1.logCrit)("MysqlAdapter", `Can't destroy connection: ${e}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
588
614
|
finalizeConnection(conn) {
|
|
589
615
|
try {
|
|
590
616
|
conn.removeAllListeners();
|
|
@@ -595,8 +621,10 @@ class MysqlAdapter {
|
|
|
595
621
|
}
|
|
596
622
|
}
|
|
597
623
|
prepareQuery(request) {
|
|
598
|
-
|
|
599
|
-
|
|
624
|
+
const template = request.query;
|
|
625
|
+
const fields = request.fields;
|
|
626
|
+
const values = new Map();
|
|
627
|
+
const parsedFields = [];
|
|
600
628
|
if (fields) {
|
|
601
629
|
for (let i in fields) {
|
|
602
630
|
const name = i;
|
|
@@ -618,72 +646,52 @@ class MysqlAdapter {
|
|
|
618
646
|
if (!queryField.name)
|
|
619
647
|
queryField.name = name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "");
|
|
620
648
|
fields[i] = queryField;
|
|
621
|
-
const parsed = MysqlAdapter.prepareQueryFieldValue(
|
|
622
|
-
|
|
649
|
+
const parsed = MysqlAdapter.prepareQueryFieldValue(queryField);
|
|
650
|
+
values.set(name, parsed + "");
|
|
651
|
+
if (!queryField.name.startsWith("$__"))
|
|
652
|
+
parsedFields.push(queryField);
|
|
623
653
|
}
|
|
624
654
|
}
|
|
655
|
+
const column = (f) => MysqlAdapter.quoteIdentifier(f.name ?? "");
|
|
656
|
+
const macro = (name, build) => {
|
|
657
|
+
if (!values.has(name) && template.indexOf("@" + name) !== -1)
|
|
658
|
+
values.set(name, build());
|
|
659
|
+
};
|
|
660
|
+
macro("fields", () => parsedFields.filter(f => !f.ignoreInInsert).map(column).join(","));
|
|
661
|
+
if (template.indexOf("@fields") !== -1)
|
|
662
|
+
macro("values", () => parsedFields.filter(f => !f.ignoreInInsert).map(f => f.__parsedValue).join(","));
|
|
663
|
+
macro("insert", () => {
|
|
664
|
+
const list = parsedFields.filter(f => !f.ignoreInInsert);
|
|
665
|
+
return `(${list.map(column).join(",")}) VALUES (${list.map(f => f.__parsedValue).join(",")})`;
|
|
666
|
+
});
|
|
667
|
+
macro("onupdate", () => parsedFields.filter(f => !f.ignoreInUpdate).map(f => column(f) + ' = ' + f.__parsedValue).join(" , "));
|
|
668
|
+
macro("onduplicate", () => parsedFields.filter(f => f.useInReplace).map(f => column(f) + ' = ' + f.__parsedValue).join(" , "));
|
|
669
|
+
let noLimit = false;
|
|
670
|
+
if (!values.has("NOLIMIT") && template.indexOf("@NOLIMIT") !== -1) {
|
|
671
|
+
values.set("NOLIMIT", "");
|
|
672
|
+
noLimit = true;
|
|
673
|
+
}
|
|
674
|
+
let query = MysqlAdapter.substitute(template, values);
|
|
625
675
|
const tmp = query.toLowerCase();
|
|
626
|
-
if (tmp.indexOf("select") === 0 && tmp.indexOf("limit") === -1)
|
|
676
|
+
if (tmp.indexOf("select") === 0 && !noLimit && tmp.indexOf("limit") === -1)
|
|
627
677
|
query += " LIMIT 100";
|
|
628
|
-
query = query.replaceAll("@NOLIMIT", "");
|
|
629
|
-
if (query.indexOf("@fields") !== -1) {
|
|
630
|
-
let insertFieldNames = [];
|
|
631
|
-
let insertFieldValues = [];
|
|
632
|
-
for (let i in fields) {
|
|
633
|
-
let f = fields[i];
|
|
634
|
-
if (f.name?.startsWith("$__"))
|
|
635
|
-
continue;
|
|
636
|
-
if (f.ignoreInInsert)
|
|
637
|
-
continue;
|
|
638
|
-
insertFieldNames.push('`' + f.name + '`');
|
|
639
|
-
insertFieldValues.push(f.__parsedValue);
|
|
640
|
-
}
|
|
641
|
-
query = MysqlAdapter.safeReplace(query, "@fields", insertFieldNames.join(","));
|
|
642
|
-
query = MysqlAdapter.safeReplace(query, "@values", insertFieldValues.join(","));
|
|
643
|
-
}
|
|
644
|
-
if (query.indexOf("@insert") !== -1) {
|
|
645
|
-
let oninsertNames = [];
|
|
646
|
-
let oninsertValues = [];
|
|
647
|
-
for (let i in fields) {
|
|
648
|
-
let f = fields[i];
|
|
649
|
-
if (f.name?.startsWith("$__"))
|
|
650
|
-
continue;
|
|
651
|
-
if (f.ignoreInInsert)
|
|
652
|
-
continue;
|
|
653
|
-
oninsertNames.push(f.name);
|
|
654
|
-
oninsertValues.push(f.__parsedValue);
|
|
655
|
-
}
|
|
656
|
-
query = MysqlAdapter.safeReplace(query, "@insert", `(${oninsertNames.join(",")}) VALUES (${oninsertValues.join(",")})`);
|
|
657
|
-
}
|
|
658
|
-
if (query.indexOf("@onupdate") !== -1) {
|
|
659
|
-
let onUpdate = [];
|
|
660
|
-
for (let i in fields) {
|
|
661
|
-
let f = fields[i];
|
|
662
|
-
if (f.name?.startsWith("$__"))
|
|
663
|
-
continue;
|
|
664
|
-
if (f.ignoreInUpdate)
|
|
665
|
-
continue;
|
|
666
|
-
onUpdate.push('`' + f.name + '` = ' + f.__parsedValue);
|
|
667
|
-
}
|
|
668
|
-
query = MysqlAdapter.safeReplace(query, "@onupdate", onUpdate.join(" , "));
|
|
669
|
-
}
|
|
670
|
-
if (query.indexOf('@onduplicate') !== -1) {
|
|
671
|
-
let onDuplicate = [];
|
|
672
|
-
for (let i in fields) {
|
|
673
|
-
let f = fields[i];
|
|
674
|
-
if (f.name?.startsWith("$__"))
|
|
675
|
-
continue;
|
|
676
|
-
if (!f.useInReplace)
|
|
677
|
-
continue;
|
|
678
|
-
onDuplicate.push('`' + f.name + '` = ' + f.__parsedValue);
|
|
679
|
-
}
|
|
680
|
-
query = MysqlAdapter.safeReplace(query, "@onduplicate", onDuplicate.join(" , "));
|
|
681
|
-
}
|
|
682
678
|
return query;
|
|
683
679
|
}
|
|
680
|
+
static substitute(text, values) {
|
|
681
|
+
if (values.size === 0)
|
|
682
|
+
return text;
|
|
683
|
+
const names = [...values.keys()]
|
|
684
|
+
.sort((a, b) => b.length - a.length)
|
|
685
|
+
.map(n => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
686
|
+
const regex = new RegExp("@(" + names.join("|") + ")(?=\\b|\\s|,|\\)|$)", "g");
|
|
687
|
+
return text.replace(regex, (match, name) => values.get(name) ?? match);
|
|
688
|
+
}
|
|
689
|
+
static quoteIdentifier(name) {
|
|
690
|
+
return "`" + String(name).replaceAll("`", "") + "`";
|
|
691
|
+
}
|
|
684
692
|
static safeReplace(query, key, value) {
|
|
685
|
-
const
|
|
686
|
-
return
|
|
693
|
+
const name = key.startsWith("@") ? key.substring(1) : key;
|
|
694
|
+
return MysqlAdapter.substitute(query, new Map([[name, value]]));
|
|
687
695
|
}
|
|
688
696
|
static prepareQueryFieldValue(field) {
|
|
689
697
|
let value = field.value;
|
|
@@ -713,12 +721,13 @@ class MysqlAdapter {
|
|
|
713
721
|
value = value ? 1 : 0;
|
|
714
722
|
}
|
|
715
723
|
if (field.fields && typeof field.fields === "object" && value && typeof value === "string" && value.indexOf("@") !== -1) {
|
|
724
|
+
const nested = new Map();
|
|
716
725
|
for (let key in field.fields) {
|
|
717
726
|
if (!field.fields[key])
|
|
718
727
|
continue;
|
|
719
|
-
|
|
720
|
-
value = this.safeReplace(value, "@" + key, val);
|
|
728
|
+
nested.set(key, promise_1.default.escape(field.fields[key]));
|
|
721
729
|
}
|
|
730
|
+
value = MysqlAdapter.substitute(value, nested);
|
|
722
731
|
}
|
|
723
732
|
field.__parsedValue = value;
|
|
724
733
|
if (field.__parsedValue === null || field.__parsedValue === undefined) {
|
|
@@ -817,7 +826,7 @@ class MysqlAdapter {
|
|
|
817
826
|
fatal: true,
|
|
818
827
|
sql: "no query",
|
|
819
828
|
name: "QUERY_ERR",
|
|
820
|
-
message: "Error: " + (err
|
|
829
|
+
message: "Error: " + (err instanceof Error ? err.message : String(err ?? "")),
|
|
821
830
|
isDuplicateError: false
|
|
822
831
|
};
|
|
823
832
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { Pool } from 'pg';
|
|
1
|
+
import { Pool, PoolClient } from 'pg';
|
|
2
2
|
import { DBAdapterOptions, IDBQuery, IDBResult, IDBBulkQuery, IPoolStatus, IDBStatFrame } from '../DBService';
|
|
3
|
-
import { ITransaction } from '../MysqlService';
|
|
4
3
|
import { IDBAdapter } from './IDBAdapter';
|
|
5
4
|
export declare class PostgresAdapter implements IDBAdapter {
|
|
6
5
|
options: DBAdapterOptions;
|
|
@@ -11,7 +10,15 @@ export declare class PostgresAdapter implements IDBAdapter {
|
|
|
11
10
|
timeoutID: any;
|
|
12
11
|
queries: never[];
|
|
13
12
|
static nextTransactionID: number;
|
|
14
|
-
transactions:
|
|
13
|
+
transactions: {
|
|
14
|
+
id: number;
|
|
15
|
+
timestamp: number;
|
|
16
|
+
conn: PoolClient;
|
|
17
|
+
queries: {
|
|
18
|
+
sql: string;
|
|
19
|
+
status: string;
|
|
20
|
+
}[];
|
|
21
|
+
}[];
|
|
15
22
|
maxTransactionWaitTime: number;
|
|
16
23
|
lastSuccessQueryTime: number;
|
|
17
24
|
pingInterval: number;
|
|
@@ -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 (!
|
|
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` };
|
|
@@ -24,8 +24,18 @@ export declare class MonitorAuth {
|
|
|
24
24
|
authDir?: string | null;
|
|
25
25
|
projectName?: string;
|
|
26
26
|
}): void;
|
|
27
|
+
private static storeHash;
|
|
28
|
+
private static refusedHash;
|
|
29
|
+
private static storeWatcher;
|
|
30
|
+
private static storePoll;
|
|
31
|
+
private static storeDebounce;
|
|
32
|
+
private static missingSince;
|
|
33
|
+
private static sectionOf;
|
|
27
34
|
private static loadStore;
|
|
28
|
-
private static
|
|
35
|
+
private static reloadStore;
|
|
36
|
+
private static watchStore;
|
|
37
|
+
private static stopWatchingStore;
|
|
38
|
+
private static saveEnrollment;
|
|
29
39
|
static secretFor(user: IMonitorUser): string | null;
|
|
30
40
|
static isEnrolled(user: IMonitorUser): boolean;
|
|
31
41
|
static MIN_PASSWORD_LENGTH: number;
|