@bmfk/api 0.0.0-stage → 1.0.0

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.
Files changed (169) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1293 -2
  4. package/dist/apiServer/APIService.d.ts +125 -0
  5. package/dist/apiServer/APIService.js +769 -0
  6. package/dist/apiServer/BaseEndpoint.d.ts +90 -0
  7. package/dist/apiServer/BaseEndpoint.js +314 -0
  8. package/dist/apiServer/BaseService.d.ts +17 -0
  9. package/dist/apiServer/BaseService.js +39 -0
  10. package/dist/apiServer/DBService.d.ts +131 -0
  11. package/dist/apiServer/DBService.js +290 -0
  12. package/dist/apiServer/DocumentService.d.ts +9 -0
  13. package/dist/apiServer/DocumentService.js +65 -0
  14. package/dist/apiServer/LocalRequest.d.ts +3 -0
  15. package/dist/apiServer/LocalRequest.js +6 -0
  16. package/dist/apiServer/LogService.d.ts +78 -0
  17. package/dist/apiServer/LogService.js +349 -0
  18. package/dist/apiServer/MonitorService.d.ts +102 -0
  19. package/dist/apiServer/MonitorService.js +615 -0
  20. package/dist/apiServer/StatService.d.ts +4 -0
  21. package/dist/apiServer/StatService.js +10 -0
  22. package/dist/apiServer/TimeframeService.d.ts +28 -0
  23. package/dist/apiServer/TimeframeService.js +97 -0
  24. package/dist/apiServer/WebSocketServer.d.ts +39 -0
  25. package/dist/apiServer/WebSocketServer.js +173 -0
  26. package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
  27. package/dist/apiServer/db/IDBAdapter.js +2 -0
  28. package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
  29. package/dist/apiServer/db/MysqlAdapter.js +869 -0
  30. package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
  31. package/dist/apiServer/db/PostgresAdapter.js +73 -0
  32. package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
  33. package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
  34. package/dist/apiServer/deployment/Activate.d.ts +4 -0
  35. package/dist/apiServer/deployment/Activate.js +124 -0
  36. package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
  37. package/dist/apiServer/deployment/BackupManager.js +174 -0
  38. package/dist/apiServer/deployment/Backups.d.ts +2 -0
  39. package/dist/apiServer/deployment/Backups.js +44 -0
  40. package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
  41. package/dist/apiServer/deployment/BlueGreenState.js +150 -0
  42. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  43. package/dist/apiServer/deployment/Bundler.js +178 -0
  44. package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
  45. package/dist/apiServer/deployment/ConfigService.js +195 -0
  46. package/dist/apiServer/deployment/Deploy.d.ts +4 -0
  47. package/dist/apiServer/deployment/Deploy.js +404 -0
  48. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  49. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  50. package/dist/apiServer/deployment/Deployer.d.ts +13 -0
  51. package/dist/apiServer/deployment/Deployer.js +96 -0
  52. package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
  53. package/dist/apiServer/deployment/DeployerInit.js +214 -0
  54. package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
  55. package/dist/apiServer/deployment/DeployerService.js +1553 -0
  56. package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
  57. package/dist/apiServer/deployment/HashPassword.js +126 -0
  58. package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
  59. package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
  60. package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
  61. package/dist/apiServer/deployment/MigrateProject.js +335 -0
  62. package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
  63. package/dist/apiServer/deployment/NginxHelper.js +111 -0
  64. package/dist/apiServer/deployment/Notifier.d.ts +30 -0
  65. package/dist/apiServer/deployment/Notifier.js +82 -0
  66. package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
  67. package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
  68. package/dist/apiServer/deployment/Restore.d.ts +2 -0
  69. package/dist/apiServer/deployment/Restore.js +89 -0
  70. package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
  71. package/dist/apiServer/deployment/ReviewStore.js +186 -0
  72. package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
  73. package/dist/apiServer/deployment/SecretsInjector.js +189 -0
  74. package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
  75. package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
  76. package/dist/apiServer/deployment/Status.d.ts +2 -0
  77. package/dist/apiServer/deployment/Status.js +83 -0
  78. package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
  79. package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
  80. package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
  81. package/dist/apiServer/deployment/Watchdog.js +65 -0
  82. package/dist/apiServer/deployment/Wizards.d.ts +1 -0
  83. package/dist/apiServer/deployment/Wizards.js +83 -0
  84. package/dist/apiServer/deployment/cli.d.ts +2 -0
  85. package/dist/apiServer/deployment/cli.js +224 -0
  86. package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
  87. package/dist/apiServer/deployment/cliCommon.js +110 -0
  88. package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
  89. package/dist/apiServer/deployment/cliPrompt.js +38 -0
  90. package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
  91. package/dist/apiServer/deployment/resolveConfig.js +139 -0
  92. package/dist/apiServer/documentation/Documentation.d.ts +18 -0
  93. package/dist/apiServer/documentation/Documentation.js +143 -0
  94. package/dist/apiServer/documentation/index.html +460 -0
  95. package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
  96. package/dist/apiServer/external/MicroserviceClient.js +144 -0
  97. package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
  98. package/dist/apiServer/external/MicroserviceHost.js +183 -0
  99. package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
  100. package/dist/apiServer/external/MicroserviceHostController.js +65 -0
  101. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  102. package/dist/apiServer/helper/AppDataPath.js +81 -0
  103. package/dist/apiServer/helper/ClientIp.d.ts +3 -0
  104. package/dist/apiServer/helper/ClientIp.js +33 -0
  105. package/dist/apiServer/helper/DataProvider.d.ts +18 -0
  106. package/dist/apiServer/helper/DataProvider.js +57 -0
  107. package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
  108. package/dist/apiServer/helper/IpAllowList.js +40 -0
  109. package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
  110. package/dist/apiServer/helper/JSONStableStringify.js +15 -0
  111. package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
  112. package/dist/apiServer/helper/PasswordHash.js +52 -0
  113. package/dist/apiServer/helper/Sleep.d.ts +1 -0
  114. package/dist/apiServer/helper/Sleep.js +5 -0
  115. package/dist/apiServer/helper/Trace.d.ts +8 -0
  116. package/dist/apiServer/helper/Trace.js +30 -0
  117. package/dist/apiServer/helper/UID.d.ts +16 -0
  118. package/dist/apiServer/helper/UID.js +98 -0
  119. package/dist/apiServer/helper/Validator.d.ts +86 -0
  120. package/dist/apiServer/helper/Validator.js +560 -0
  121. package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
  122. package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
  123. package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
  124. package/dist/apiServer/helper/ZipUtils.js +28 -0
  125. package/dist/apiServer/http/Http.d.ts +183 -0
  126. package/dist/apiServer/http/Http.js +627 -0
  127. package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
  128. package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
  129. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  130. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  131. package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
  132. package/dist/apiServer/monitor/AccessStore.js +163 -0
  133. package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
  134. package/dist/apiServer/monitor/LogFiles.js +109 -0
  135. package/dist/apiServer/monitor/Monitor.d.ts +54 -0
  136. package/dist/apiServer/monitor/Monitor.js +447 -0
  137. package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
  138. package/dist/apiServer/monitor/MonitorAuth.js +474 -0
  139. package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
  140. package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
  141. package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
  142. package/dist/apiServer/monitor/SystemInfo.js +217 -0
  143. package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
  144. package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
  145. package/dist/apiServer/monitor/index.html +591 -0
  146. package/dist/apiServer/review/Review.d.ts +23 -0
  147. package/dist/apiServer/review/Review.js +149 -0
  148. package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
  149. package/dist/apiServer/review/ReviewAuth.js +147 -0
  150. package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
  151. package/dist/apiServer/review/ReviewDiff.js +175 -0
  152. package/dist/apiServer/review/index.html +501 -0
  153. package/dist/apiServer/routes/Liveness.d.ts +7 -0
  154. package/dist/apiServer/routes/Liveness.js +27 -0
  155. package/dist/apiServer/routes/Readiness.d.ts +13 -0
  156. package/dist/apiServer/routes/Readiness.js +20 -0
  157. package/dist/apiServer/security/BlockedIps.d.ts +46 -0
  158. package/dist/apiServer/security/BlockedIps.js +185 -0
  159. package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
  160. package/dist/apiServer/structures/DefaultErrors.js +52 -0
  161. package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
  162. package/dist/apiServer/structures/HTTPStatus.js +11 -0
  163. package/dist/apiServer/structures/Interfaces.d.ts +55 -0
  164. package/dist/apiServer/structures/Interfaces.js +2 -0
  165. package/dist/index.d.ts +45 -0
  166. package/dist/index.js +110 -0
  167. package/dist/signal/Signal.d.ts +23 -0
  168. package/dist/signal/Signal.js +85 -0
  169. package/package.json +88 -4
@@ -0,0 +1,124 @@
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.InterceptorPayAuth = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const Validator_1 = require("../helper/Validator");
9
+ const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
10
+ const _TAuthParams = {
11
+ v: 0,
12
+ ts: "",
13
+ nonce: "",
14
+ kid: "",
15
+ alg: "",
16
+ $__alg_optional: true,
17
+ sig: ""
18
+ };
19
+ class InterceptorPayAuth {
20
+ static TS_PAST_SEC = 300;
21
+ static TS_FUTURE_SEC = 60;
22
+ static NONCE_TTL_MS = (InterceptorPayAuth.TS_PAST_SEC + InterceptorPayAuth.TS_FUTURE_SEC) * 1000;
23
+ static NONCE_MAX = 100_000;
24
+ nonceSeen = new Map();
25
+ authorizationsPreset;
26
+ constructor(authorizations) {
27
+ this.authorizationsPreset = authorizations;
28
+ }
29
+ purgeNonces(nowMs) {
30
+ for (const [nonce, expiresAt] of this.nonceSeen) {
31
+ if (expiresAt > nowMs)
32
+ break;
33
+ this.nonceSeen.delete(nonce);
34
+ }
35
+ while (this.nonceSeen.size > InterceptorPayAuth.NONCE_MAX) {
36
+ const oldest = this.nonceSeen.keys().next().value;
37
+ if (oldest === undefined)
38
+ break;
39
+ this.nonceSeen.delete(oldest);
40
+ }
41
+ }
42
+ async intercept(req, authorizations) {
43
+ const authScheme = "payauth ";
44
+ let headerData = req.headers["authorization"];
45
+ if (!headerData)
46
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "No authorization header" };
47
+ if (!headerData.toLowerCase().startsWith(authScheme))
48
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "wrong authorization scheme" };
49
+ const b64 = req.data.b64;
50
+ if (req.data.b64) {
51
+ let json = null;
52
+ try {
53
+ json = Buffer.from(req.data.b64, "base64").toString("utf-8");
54
+ json = JSON.parse(json);
55
+ }
56
+ catch (e) {
57
+ throw { ...DefaultErrors_1.default.BAD_REQUEST, details: "JSON malformed" };
58
+ }
59
+ req.data = json;
60
+ }
61
+ const params = {};
62
+ headerData.substring(authScheme.length).trim().split(",").forEach(v => {
63
+ v = v.trim();
64
+ const eq = v.indexOf("=");
65
+ if (eq > 0) {
66
+ const key = v.substring(0, eq).trim().toLowerCase();
67
+ let value = v.substring(eq + 1).trim();
68
+ if (value.length > 1 &&
69
+ ((value.startsWith("'") && value.endsWith("'")) ||
70
+ (value.startsWith('"') && value.endsWith('"')))) {
71
+ value = value.substring(1, value.length - 1);
72
+ }
73
+ params[key] = value;
74
+ }
75
+ });
76
+ const errors = await Validator_1.Validator.validateStructure(_TAuthParams, params);
77
+ if (errors)
78
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Malformed authorization header", stack: errors };
79
+ if (!/^\d{10}$/.test(params.ts) && !/^\d{13}$/.test(params.ts))
80
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "ts must be Unix epoch seconds (10 digits) or milliseconds (13 digits), UTC" };
81
+ const nowMs = Date.now();
82
+ const nowSec = Math.floor(nowMs / 1000);
83
+ const tsSec = params.ts.length === 13
84
+ ? Math.floor(parseInt(params.ts, 10) / 1000)
85
+ : parseInt(params.ts, 10);
86
+ const delta = tsSec - nowSec;
87
+ if (delta < -InterceptorPayAuth.TS_PAST_SEC || delta > InterceptorPayAuth.TS_FUTURE_SEC)
88
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: `ts out of window: off by ${delta}s (server epoch ${nowSec})` };
89
+ this.purgeNonces(nowMs);
90
+ if (this.nonceSeen.has(params.nonce))
91
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Duplicate nonce" };
92
+ if (!authorizations || authorizations.length === 0) {
93
+ if (this.authorizationsPreset && this.authorizationsPreset.length > 0)
94
+ authorizations = this.authorizationsPreset;
95
+ else
96
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "No authorizations provided" };
97
+ }
98
+ for (let i of authorizations) {
99
+ if (i.kid === params.kid) {
100
+ if (params.alg && params.alg.toLowerCase() === "hmac-sha256") {
101
+ if (b64) {
102
+ const key = Buffer.from(i.key, "hex");
103
+ const sig = crypto_1.default.createHmac("sha256", key).update(b64 + params.ts + params.nonce).digest("hex");
104
+ const got = Buffer.from(String(params.sig), "utf-8");
105
+ const want = Buffer.from(sig, "utf-8");
106
+ if (got.length === want.length && crypto_1.default.timingSafeEqual(got, want)) {
107
+ this.nonceSeen.set(params.nonce, nowMs + InterceptorPayAuth.NONCE_TTL_MS);
108
+ return i;
109
+ }
110
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Signature mismatch" };
111
+ }
112
+ else {
113
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Can't calc signature, no b64" };
114
+ }
115
+ }
116
+ else {
117
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Unsupported alg" };
118
+ }
119
+ }
120
+ }
121
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Key not found" };
122
+ }
123
+ }
124
+ exports.InterceptorPayAuth = InterceptorPayAuth;
@@ -0,0 +1,40 @@
1
+ import { IInterceptor } from "../APIService";
2
+ import { IRequest } from "../structures/Interfaces";
3
+ export interface ISignedAuthResult {
4
+ kid: string;
5
+ }
6
+ export interface ISignedAuthVerdict {
7
+ present: boolean;
8
+ kid?: string;
9
+ error?: string;
10
+ }
11
+ export declare class InterceptorSignedAuth implements IInterceptor<ISignedAuthResult> {
12
+ private resolveKey;
13
+ static TS_PAST_SEC: number;
14
+ static TS_FUTURE_SEC: number;
15
+ private static readonly NONCE_MAX;
16
+ private nonceSeen;
17
+ constructor(resolveKey: (kid: string) => Promise<string | null | undefined> | string | null | undefined);
18
+ intercept(req: IRequest): Promise<ISignedAuthResult>;
19
+ verify(req: IRequest): Promise<ISignedAuthVerdict>;
20
+ private purge;
21
+ static parseHeader(s: string): Record<string, string>;
22
+ private static hashUpload;
23
+ static pathOf(url: string): string;
24
+ static message(method: string, path: string, ts: string, nonce: string, data: unknown, files: Record<string, string>): string;
25
+ static sha256File(file: string): Promise<string>;
26
+ static generateKeyPair(): {
27
+ publicKey: string;
28
+ privateKey: string;
29
+ };
30
+ static publicKeyOf(privateKey: string): string;
31
+ static sign(o: {
32
+ privateKey: string;
33
+ kid: string;
34
+ method: string;
35
+ url: string;
36
+ data?: unknown;
37
+ files?: Record<string, string>;
38
+ nonce?: string;
39
+ }): string;
40
+ }
@@ -0,0 +1,150 @@
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.InterceptorSignedAuth = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const JSONStableStringify_1 = require("../helper/JSONStableStringify");
10
+ const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
11
+ const SCHEME = "signature ";
12
+ const VERSION = "bmfk-sig-v1";
13
+ class InterceptorSignedAuth {
14
+ resolveKey;
15
+ static TS_PAST_SEC = 300;
16
+ static TS_FUTURE_SEC = 60;
17
+ static NONCE_MAX = 100_000;
18
+ nonceSeen = new Map();
19
+ constructor(resolveKey) {
20
+ this.resolveKey = resolveKey;
21
+ }
22
+ async intercept(req) {
23
+ const v = await this.verify(req);
24
+ if (!v.kid)
25
+ throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: v.present ? "Invalid signature" : "Signature required" };
26
+ return { kid: v.kid };
27
+ }
28
+ async verify(req) {
29
+ const header = String(req.headers?.["authorization"] ?? "");
30
+ if (!header.toLowerCase().startsWith(SCHEME))
31
+ return { present: false };
32
+ const p = InterceptorSignedAuth.parseHeader(header.slice(SCHEME.length));
33
+ if (!p.kid || !p.ts || !p.nonce || !p.sig)
34
+ return { present: true, error: "malformed Signature header" };
35
+ if (!/^[A-Za-z0-9._@-]{1,128}$/.test(p.kid))
36
+ return { present: true, error: "malformed key id" };
37
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(p.nonce))
38
+ return { present: true, error: "malformed nonce" };
39
+ if (!/^\d{13}$/.test(p.ts))
40
+ return { present: true, error: "ts must be epoch milliseconds (13 digits)" };
41
+ const now = Date.now();
42
+ const delta = Math.round((Number(p.ts) - now) / 1000);
43
+ if (delta < -InterceptorSignedAuth.TS_PAST_SEC || delta > InterceptorSignedAuth.TS_FUTURE_SEC)
44
+ return { present: true, error: `ts out of window: off by ${delta}s — check the client's clock` };
45
+ this.purge(now);
46
+ const nonceKey = p.kid + ":" + p.nonce;
47
+ if (this.nonceSeen.has(nonceKey))
48
+ return { present: true, error: "nonce already used (replayed request)" };
49
+ const publicKey = await this.resolveKey(p.kid);
50
+ if (!publicKey)
51
+ return { present: true, error: `unknown key id "${p.kid}"` };
52
+ let key;
53
+ try {
54
+ key = crypto_1.default.createPublicKey({ key: Buffer.from(publicKey, "base64"), format: "der", type: "spki" });
55
+ }
56
+ catch {
57
+ return { present: true, error: `the public key of "${p.kid}" is not a valid Ed25519 key` };
58
+ }
59
+ const raw = req.raw ?? {};
60
+ const path = InterceptorSignedAuth.pathOf(raw.originalUrl ?? raw.url ?? req.endpoint ?? "");
61
+ const files = {};
62
+ for (const [field, f] of Object.entries((raw.files ?? {}))) {
63
+ const one = Array.isArray(f) ? f[0] : f;
64
+ files[field] = await InterceptorSignedAuth.hashUpload(one);
65
+ }
66
+ const data = { ...(raw.body ?? {}), ...(raw.query ?? {}) };
67
+ const message = InterceptorSignedAuth.message(String(req.method ?? raw.method ?? "").toUpperCase(), path, p.ts, p.nonce, data, files);
68
+ let ok = false;
69
+ try {
70
+ ok = crypto_1.default.verify(null, Buffer.from(message), key, Buffer.from(p.sig, "base64"));
71
+ }
72
+ catch {
73
+ ok = false;
74
+ }
75
+ if (!ok)
76
+ return { present: true, error: "signature does not match (wrong key, or the request was changed)" };
77
+ this.nonceSeen.set(nonceKey, now + (InterceptorSignedAuth.TS_PAST_SEC + InterceptorSignedAuth.TS_FUTURE_SEC) * 1000);
78
+ return { present: true, kid: p.kid };
79
+ }
80
+ purge(now) {
81
+ for (const [k, exp] of this.nonceSeen) {
82
+ if (exp > now)
83
+ break;
84
+ this.nonceSeen.delete(k);
85
+ }
86
+ while (this.nonceSeen.size > InterceptorSignedAuth.NONCE_MAX) {
87
+ const oldest = this.nonceSeen.keys().next().value;
88
+ if (oldest === undefined)
89
+ break;
90
+ this.nonceSeen.delete(oldest);
91
+ }
92
+ }
93
+ static parseHeader(s) {
94
+ const out = {};
95
+ for (const part of s.split(",")) {
96
+ const eq = part.indexOf("=");
97
+ if (eq < 1)
98
+ continue;
99
+ let v = part.slice(eq + 1).trim();
100
+ if (v.length > 1 && ((v[0] === '"' && v.endsWith('"')) || (v[0] === "'" && v.endsWith("'"))))
101
+ v = v.slice(1, -1);
102
+ out[part.slice(0, eq).trim().toLowerCase()] = v;
103
+ }
104
+ return out;
105
+ }
106
+ static async hashUpload(f) {
107
+ if (f?.tempFilePath)
108
+ return InterceptorSignedAuth.sha256File(f.tempFilePath);
109
+ return crypto_1.default.createHash("sha256").update(f?.data ?? Buffer.alloc(0)).digest("hex");
110
+ }
111
+ static pathOf(url) {
112
+ try {
113
+ return new URL(url, "http://localhost").pathname;
114
+ }
115
+ catch {
116
+ return url;
117
+ }
118
+ }
119
+ static message(method, path, ts, nonce, data, files) {
120
+ const payload = (0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ data: data ?? {}, files })));
121
+ const digest = crypto_1.default.createHash("sha256").update(payload).digest("hex");
122
+ return [VERSION, method, path, ts, nonce, digest].join("\n");
123
+ }
124
+ static sha256File(file) {
125
+ return new Promise((resolve, reject) => {
126
+ const h = crypto_1.default.createHash("sha256");
127
+ fs_1.default.createReadStream(file).on("data", d => h.update(d)).on("error", reject).on("end", () => resolve(h.digest("hex")));
128
+ });
129
+ }
130
+ static generateKeyPair() {
131
+ const { publicKey, privateKey } = crypto_1.default.generateKeyPairSync("ed25519");
132
+ return {
133
+ publicKey: publicKey.export({ format: "der", type: "spki" }).toString("base64"),
134
+ privateKey: privateKey.export({ format: "der", type: "pkcs8" }).toString("base64"),
135
+ };
136
+ }
137
+ static publicKeyOf(privateKey) {
138
+ const key = crypto_1.default.createPrivateKey({ key: Buffer.from(privateKey, "base64"), format: "der", type: "pkcs8" });
139
+ return crypto_1.default.createPublicKey(key).export({ format: "der", type: "spki" }).toString("base64");
140
+ }
141
+ static sign(o) {
142
+ const key = crypto_1.default.createPrivateKey({ key: Buffer.from(o.privateKey, "base64"), format: "der", type: "pkcs8" });
143
+ const ts = String(Date.now());
144
+ const nonce = o.nonce ?? crypto_1.default.randomBytes(18).toString("base64url");
145
+ const message = InterceptorSignedAuth.message(o.method.toUpperCase(), InterceptorSignedAuth.pathOf(o.url), ts, nonce, o.data ?? {}, o.files ?? {});
146
+ const sig = crypto_1.default.sign(null, Buffer.from(message), key).toString("base64");
147
+ return `Signature kid="${o.kid}", ts="${ts}", nonce="${nonce}", sig="${sig}"`;
148
+ }
149
+ }
150
+ exports.InterceptorSignedAuth = InterceptorSignedAuth;
@@ -0,0 +1,27 @@
1
+ import type { IMonitorUser, IDocumentationUser } from "../APIService";
2
+ export interface IAccess {
3
+ monitor?: IMonitorUser[];
4
+ documentation?: IDocumentationUser[];
5
+ monitorAllowedIps?: string[];
6
+ }
7
+ export declare class AccessStore {
8
+ private onChange?;
9
+ private optional;
10
+ private current;
11
+ private hash;
12
+ private refusedHash;
13
+ private file;
14
+ private debounce;
15
+ constructor(source: IAccess | string | undefined | null, onChange?: ((prev: IAccess, next: IAccess) => void) | undefined, optional?: boolean);
16
+ get monitor(): IMonitorUser[];
17
+ get documentation(): IDocumentationUser[];
18
+ get monitorAllowedIps(): string[];
19
+ static validate(value: any): string | null;
20
+ private loadSync;
21
+ private reload;
22
+ private accept;
23
+ private refuse;
24
+ private apply;
25
+ private warnPermissions;
26
+ private watch;
27
+ }
@@ -0,0 +1,163 @@
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 IpAllowList_1 = require("../helper/IpAllowList");
12
+ const ROLES = ["admin", "it", "analytic"];
13
+ class AccessStore {
14
+ onChange;
15
+ optional;
16
+ current = {};
17
+ hash = "";
18
+ refusedHash = "";
19
+ file = null;
20
+ debounce = null;
21
+ constructor(source, onChange, optional = false) {
22
+ this.onChange = onChange;
23
+ this.optional = optional;
24
+ if (typeof source !== "string") {
25
+ this.apply(source ?? {});
26
+ return;
27
+ }
28
+ this.file = path_1.default.resolve(source);
29
+ this.loadSync();
30
+ this.watch();
31
+ }
32
+ get monitor() { return this.current.monitor ?? []; }
33
+ get documentation() { return this.current.documentation ?? []; }
34
+ get monitorAllowedIps() { return this.current.monitorAllowedIps ?? []; }
35
+ static validate(value) {
36
+ if (!value || typeof value !== "object" || Array.isArray(value))
37
+ return "root must be an object";
38
+ if (value.monitorAllowedIps !== undefined) {
39
+ if (!Array.isArray(value.monitorAllowedIps) || value.monitorAllowedIps.some((e) => typeof e !== "string"))
40
+ return "monitorAllowedIps must be an array of strings";
41
+ const ips = IpAllowList_1.IpAllowList.build(value.monitorAllowedIps);
42
+ if (ips.error)
43
+ return "monitorAllowedIps: " + ips.error;
44
+ }
45
+ for (const list of ["monitor", "documentation"]) {
46
+ const users = value[list];
47
+ if (users === undefined)
48
+ continue;
49
+ if (!Array.isArray(users))
50
+ return `"${list}" must be an array`;
51
+ const seen = new Set();
52
+ for (const [i, u] of users.entries()) {
53
+ const at = `${list}[${i}]`;
54
+ if (!u || typeof u !== "object")
55
+ return `${at} must be an object`;
56
+ if (typeof u.login !== "string" || !u.login.trim())
57
+ return `${at}.login must be a non-empty string`;
58
+ if (u.login.includes(":"))
59
+ return `${at}.login must not contain ":"`;
60
+ if (typeof u.password !== "string")
61
+ return `${at}.password must be a string`;
62
+ if (seen.has(u.login))
63
+ return `${at}: duplicate login "${u.login}"`;
64
+ seen.add(u.login);
65
+ if (u.role !== undefined && !ROLES.includes(u.role))
66
+ return `${at}.role must be one of ${ROLES.join(", ")}`;
67
+ if (u.totpSecret !== undefined && typeof u.totpSecret !== "string")
68
+ return `${at}.totpSecret must be a string`;
69
+ if (u.endpoints !== undefined && (!Array.isArray(u.endpoints) || u.endpoints.some((e) => typeof e !== "string")))
70
+ return `${at}.endpoints must be an array of strings`;
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+ loadSync() {
76
+ try {
77
+ this.accept(fs_1.default.readFileSync(this.file, "utf-8"), true);
78
+ }
79
+ catch (e) {
80
+ if (e.code === "ENOENT" && this.optional)
81
+ (0, LogService_1.logInfo)(`Access: no ${this.file} — the monitor and the documentation are closed. Create it with: npx bmfk access-config ${this.file}`);
82
+ else
83
+ (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`);
84
+ }
85
+ }
86
+ async reload() {
87
+ let raw;
88
+ try {
89
+ raw = await fs_1.default.promises.readFile(this.file, "utf-8");
90
+ }
91
+ catch (e) {
92
+ if (e.code !== "ENOENT")
93
+ (0, LogService_1.logWarn)(`Access file ${this.file}: ${e.message} — keeping the previous access`);
94
+ return;
95
+ }
96
+ this.accept(raw, false);
97
+ }
98
+ accept(raw, initial) {
99
+ const hash = crypto_1.default.createHash("sha256").update(raw).digest("hex");
100
+ if (hash === this.hash || hash === this.refusedHash)
101
+ return;
102
+ let parsed;
103
+ try {
104
+ parsed = JSON.parse(raw);
105
+ }
106
+ catch (e) {
107
+ this.refusedHash = hash;
108
+ return this.refuse(`invalid JSON (${e.message})`, initial);
109
+ }
110
+ const problem = AccessStore.validate(parsed);
111
+ if (problem)
112
+ this.refusedHash = hash;
113
+ if (problem)
114
+ return this.refuse(problem, initial);
115
+ this.hash = hash;
116
+ this.refusedHash = "";
117
+ this.warnPermissions();
118
+ this.apply({ monitor: parsed.monitor, documentation: parsed.documentation, monitorAllowedIps: parsed.monitorAllowedIps });
119
+ (0, LogService_1.logInfo)(`Access ${initial ? "loaded" : "reloaded"} from ${this.file}: ${this.monitor.length} monitor, ${this.documentation.length} documentation user(s)`
120
+ + (this.monitorAllowedIps.length ? `, monitor limited to ${this.monitorAllowedIps.join(", ")}` : ""));
121
+ }
122
+ refuse(reason, initial) {
123
+ if (initial)
124
+ (0, LogService_1.logError)(`Access file ${this.file}: ${reason} — no one can access the monitor and documentation until it is fixed`);
125
+ else
126
+ (0, LogService_1.logError)(`Access file ${this.file}: ${reason} — change ignored, keeping the previous access`);
127
+ }
128
+ apply(next) {
129
+ const prev = this.current;
130
+ this.current = next;
131
+ try {
132
+ this.onChange?.(prev, next);
133
+ }
134
+ catch (e) {
135
+ (0, LogService_1.logError)(`Access change handler threw: ${e instanceof Error ? e.message : String(e)}`);
136
+ }
137
+ }
138
+ warnPermissions() {
139
+ try {
140
+ const mode = fs_1.default.statSync(this.file).mode;
141
+ if (mode & 0o077)
142
+ (0, LogService_1.logWarn)(`Access file ${this.file} is readable by other users (mode ${(mode & 0o777).toString(8)}) — chmod 600 it`);
143
+ }
144
+ catch { }
145
+ }
146
+ watch() {
147
+ const dir = path_1.default.dirname(this.file), name = path_1.default.basename(this.file);
148
+ try {
149
+ fs_1.default.watch(dir, (_event, filename) => {
150
+ if (filename && filename !== name)
151
+ return;
152
+ if (this.debounce)
153
+ clearTimeout(this.debounce);
154
+ this.debounce = setTimeout(() => { this.debounce = null; this.reload(); }, 200);
155
+ }).unref();
156
+ }
157
+ catch (e) {
158
+ (0, LogService_1.logWarn)(`Access file: cannot watch ${dir} (${e.message}) — changes are picked up within a minute`);
159
+ }
160
+ setInterval(() => this.reload(), 60_000).unref();
161
+ }
162
+ }
163
+ exports.AccessStore = AccessStore;
@@ -0,0 +1,34 @@
1
+ export declare const LOG_SOURCES: readonly ["process-out", "process-err", "nginx-access", "nginx-error"];
2
+ export type TLogSourceId = typeof LOG_SOURCES[number];
3
+ export interface ILogFilesOptions {
4
+ processOut?: string;
5
+ processErr?: string;
6
+ nginxAccess?: string;
7
+ nginxError?: string;
8
+ }
9
+ export interface ILogTailRequest {
10
+ lines?: number;
11
+ since?: number;
12
+ filter?: string;
13
+ }
14
+ export interface ILogTailResult {
15
+ source: TLogSourceId;
16
+ path: string;
17
+ size: number;
18
+ cursor: number;
19
+ rotated: boolean;
20
+ truncated: boolean;
21
+ lines: string[];
22
+ }
23
+ export declare function listLogSources(opts?: ILogFilesOptions): Promise<{
24
+ id: "nginx-access" | "nginx-error" | "process-err" | "process-out";
25
+ label: string;
26
+ path: string | null;
27
+ configured: boolean;
28
+ exists: boolean;
29
+ readable: boolean;
30
+ size: number | null;
31
+ modifiedAt: number | null;
32
+ reason: string | null;
33
+ }[]>;
34
+ export declare function tailLog(id: TLogSourceId, opts: ILogFilesOptions | undefined, req?: ILogTailRequest): Promise<ILogTailResult>;
@@ -0,0 +1,109 @@
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.LOG_SOURCES = void 0;
7
+ exports.listLogSources = listLogSources;
8
+ exports.tailLog = tailLog;
9
+ const promises_1 = __importDefault(require("fs/promises"));
10
+ const fs_1 = require("fs");
11
+ const LogService_1 = require("../LogService");
12
+ exports.LOG_SOURCES = ["process-out", "process-err", "nginx-access", "nginx-error"];
13
+ const LABELS = {
14
+ "process-out": "Process stdout (pm2 out log)",
15
+ "process-err": "Process stderr (pm2 error log)",
16
+ "nginx-access": "nginx access log",
17
+ "nginx-error": "nginx error log",
18
+ };
19
+ const MAX_WINDOW = 512 * 1024;
20
+ const MAX_LINE = 4000;
21
+ const MAX_LINES = 2000;
22
+ function resolvePaths(opts) {
23
+ const usable = (p) => (p && p !== "/dev/null" ? p : null);
24
+ return {
25
+ "process-out": usable(opts?.processOut) ?? usable(process.env.pm_out_log_path),
26
+ "process-err": usable(opts?.processErr) ?? usable(process.env.pm_err_log_path),
27
+ "nginx-access": usable(opts?.nginxAccess),
28
+ "nginx-error": usable(opts?.nginxError),
29
+ };
30
+ }
31
+ const ANSI = /\x1b\[[0-9;]*[A-Za-z]/g;
32
+ function cleanLine(raw) {
33
+ const line = LogService_1.LogService.sanitize(raw.replace(/\r$/, "").replace(ANSI, ""));
34
+ return line.length > MAX_LINE ? line.slice(0, MAX_LINE) + `…(${line.length} chars)` : line;
35
+ }
36
+ async function listLogSources(opts) {
37
+ const paths = resolvePaths(opts);
38
+ return Promise.all(exports.LOG_SOURCES.map(async (id) => {
39
+ const path = paths[id];
40
+ const base = { id, label: LABELS[id], path, configured: !!path, exists: false, readable: false,
41
+ size: null, modifiedAt: null, reason: null };
42
+ if (!path)
43
+ return { ...base, reason: id.startsWith("process") ? "not running under pm2 and no path configured" : "path not configured (options.logFiles)" };
44
+ try {
45
+ const st = await promises_1.default.stat(path);
46
+ base.exists = true;
47
+ base.size = st.size;
48
+ base.modifiedAt = st.mtimeMs;
49
+ await promises_1.default.access(path, fs_1.constants.R_OK);
50
+ base.readable = true;
51
+ }
52
+ catch (e) {
53
+ base.reason = e?.code === "ENOENT" ? "file not found"
54
+ : e?.code === "EACCES" ? "permission denied for the node process user"
55
+ : String(e?.message ?? e);
56
+ }
57
+ return base;
58
+ }));
59
+ }
60
+ async function tailLog(id, opts, req = {}) {
61
+ const path = resolvePaths(opts)[id];
62
+ if (!path)
63
+ throw new Error(`log source "${id}" is not configured`);
64
+ const wantLines = Math.min(MAX_LINES, Math.max(1, Math.floor(req.lines ?? 200)));
65
+ const fh = await promises_1.default.open(path, "r");
66
+ try {
67
+ const { size } = await fh.stat();
68
+ const since = typeof req.since === "number" && Number.isFinite(req.since) ? Math.floor(req.since) : undefined;
69
+ let start;
70
+ let rotated = false, truncated = false, onBoundary = false;
71
+ if (since !== undefined && since >= 0 && since <= size) {
72
+ start = since;
73
+ onBoundary = true;
74
+ if (size - start > MAX_WINDOW) {
75
+ start = size - MAX_WINDOW;
76
+ truncated = true;
77
+ onBoundary = false;
78
+ }
79
+ }
80
+ else {
81
+ rotated = since !== undefined && since > size;
82
+ start = Math.max(0, size - MAX_WINDOW);
83
+ onBoundary = start === 0;
84
+ }
85
+ const buf = Buffer.alloc(size - start);
86
+ if (buf.length > 0)
87
+ await fh.read(buf, 0, buf.length, start);
88
+ const lastNl = buf.lastIndexOf(0x0a);
89
+ const firstNl = buf.indexOf(0x0a);
90
+ let begin = onBoundary ? 0 : (firstNl >= 0 ? firstNl + 1 : buf.length);
91
+ const end = lastNl >= 0 ? lastNl + 1 : 0;
92
+ if (begin > end)
93
+ begin = end;
94
+ const text = buf.subarray(begin, end).toString("utf-8");
95
+ let lines = text.length ? text.split("\n") : [];
96
+ if (lines.length && lines[lines.length - 1] === "")
97
+ lines.pop();
98
+ lines = lines.map(cleanLine);
99
+ const filter = typeof req.filter === "string" ? req.filter.trim().toLowerCase() : "";
100
+ if (filter)
101
+ lines = lines.filter(l => l.toLowerCase().includes(filter));
102
+ if (lines.length > wantLines)
103
+ lines = lines.slice(-wantLines);
104
+ return { source: id, path, size, cursor: start + end, rotated, truncated, lines };
105
+ }
106
+ finally {
107
+ await fh.close();
108
+ }
109
+ }