@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,28 @@
1
+ import { Req } from "../../signal/Signal";
2
+ import { BaseService } from "../BaseService";
3
+ import { IError } from "../structures/Interfaces";
4
+ export interface IMicroserviceClientOptions {
5
+ id: string;
6
+ host: string;
7
+ kid: string;
8
+ privateKey: string;
9
+ hostPublicKey: string;
10
+ }
11
+ export declare const REQ_MICROSERVICE_CALL: Req<{
12
+ id: string;
13
+ requestName: string;
14
+ requestData: any;
15
+ op?: string;
16
+ }, any>;
17
+ export declare class MicroserviceClient extends BaseService {
18
+ #private;
19
+ options: IMicroserviceClientOptions;
20
+ constructor(opt: IMicroserviceClientOptions);
21
+ init(): Promise<void>;
22
+ requestMicroserviceCall(req: {
23
+ id: string;
24
+ requestName: string;
25
+ requestData: any;
26
+ op?: string;
27
+ }): Promise<any | IError>;
28
+ }
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.MicroserviceClient = exports.REQ_MICROSERVICE_CALL = void 0;
40
+ const LogService_1 = require("../LogService");
41
+ const Signal_1 = require("../../signal/Signal");
42
+ const BaseService_1 = require("../BaseService");
43
+ const DefaultErrors_1 = __importStar(require("../structures/DefaultErrors"));
44
+ const Http_1 = require("../http/Http");
45
+ const crypto_1 = __importDefault(require("crypto"));
46
+ const TimeframeService_1 = require("../TimeframeService");
47
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
48
+ const MicroserviceHost_1 = require("./MicroserviceHost");
49
+ const Trace_1 = require("../helper/Trace");
50
+ exports.REQ_MICROSERVICE_CALL = new Signal_1.Req(undefined, "REQ_MICROSERVICE_CALL");
51
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
52
+ class MicroserviceClient extends BaseService_1.BaseService {
53
+ static #clients = new Map();
54
+ static #listener = false;
55
+ static #nextID = 1;
56
+ options;
57
+ constructor(opt) {
58
+ super("MicroserviceClient");
59
+ if (!opt.privateKey || !opt.kid || !opt.hostPublicKey)
60
+ throw new Error(`MicroserviceClient "${opt.id}": set all of "kid", "privateKey" and "hostPublicKey"`);
61
+ InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(opt.privateKey);
62
+ const url = new URL(opt.host);
63
+ if (url.protocol !== "https:" && !LOOPBACK.has(url.hostname))
64
+ throw new Error(`MicroserviceClient "${opt.id}": ${opt.host} — calls go over https (plain http only to localhost)`);
65
+ this.options = opt;
66
+ MicroserviceClient.#clients.set(opt.id, this);
67
+ if (!MicroserviceClient.#listener) {
68
+ exports.REQ_MICROSERVICE_CALL.listener = async (req) => {
69
+ const client = MicroserviceClient.#clients.get(req.id);
70
+ if (!client) {
71
+ return { ...DefaultErrors_1.default.BAD_REQUEST, details: "no microservice client found: " + req.id + ", requestName:" + req.requestName };
72
+ }
73
+ return await client.requestMicroserviceCall(req);
74
+ };
75
+ MicroserviceClient.#listener = true;
76
+ }
77
+ }
78
+ async init() {
79
+ super.init();
80
+ }
81
+ async requestMicroserviceCall(req) {
82
+ return this.#callSigned(req);
83
+ }
84
+ async #callSigned(req) {
85
+ const url = this.options.host + "/__ms_host_control/receiver";
86
+ const op = req.op ?? crypto_1.default.randomUUID();
87
+ const body = { v: MicroserviceHost_1.MICROSERVICE_PROTOCOL, to: this.options.id, op, trace: Trace_1.Trace.current() ?? undefined, requestName: req.requestName, requestData: req.requestData };
88
+ const where = [this.options.host, req.requestName, op];
89
+ const maxAttempts = 10;
90
+ const attemptTimeout = 1000;
91
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
92
+ const nonce = crypto_1.default.randomBytes(18).toString("base64url");
93
+ const authorization = InterceptorSignedAuth_1.InterceptorSignedAuth.sign({
94
+ privateKey: this.options.privateKey, kid: this.options.kid, method: "POST", url, data: body, nonce,
95
+ });
96
+ const resp = await Http_1.Http.post(url, body, {
97
+ headers: { "Content-Type": "application/json", "x-microservice-id": this.options.id, authorization },
98
+ retry: { enabled: false },
99
+ });
100
+ if (!resp.ok && resp.details?.network) {
101
+ if (attempt < maxAttempts) {
102
+ (0, LogService_1.logInfo)(`Retrying microservice call ${req.requestName} (op ${op})... (attempt ${attempt}/${maxAttempts})`);
103
+ await TimeframeService_1.TimeframeService.wait(attemptTimeout * attempt);
104
+ continue;
105
+ }
106
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "Network connection lost after multiple retries, attempts: " + attempt, stack: where };
107
+ }
108
+ if (!resp.ok) {
109
+ const remoteError = resp.error?.error;
110
+ (0, LogService_1.logInfo)(`Microservice call ${req.requestName} refused by ${this.options.host}: HTTP ${resp.status}`, remoteError?.details ?? resp.details);
111
+ if (DefaultErrors_1.ErrorUtils.isError(remoteError))
112
+ return remoteError;
113
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: resp.details, stack: where };
114
+ }
115
+ const a = resp.data?.data;
116
+ if (!a || a.v !== MicroserviceHost_1.MICROSERVICE_PROTOCOL || a.op !== op || typeof a.sig !== "string")
117
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "the host did not answer a signed call (is it updated?)", stack: where };
118
+ if (!this.#verifyAnswer(op, nonce, a)) {
119
+ (0, LogService_1.logError)(`Microservice ${this.options.id}: answer signature does not match — not the expected host, or changed on the way`, where);
120
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "answer signature does not match", stack: where };
121
+ }
122
+ if (a.pending === true) {
123
+ if (attempt < maxAttempts) {
124
+ await TimeframeService_1.TimeframeService.wait(attemptTimeout * attempt);
125
+ continue;
126
+ }
127
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "Microservice processing timeout, attempts: " + attempt, stack: where };
128
+ }
129
+ return a.error !== undefined ? a.error : (a.result ?? null);
130
+ }
131
+ return { ...DefaultErrors_1.default.EXTERNAL_SERVICE_ERROR, details: "Unknown polling error", stack: where };
132
+ }
133
+ #verifyAnswer(op, nonce, a) {
134
+ try {
135
+ const key = crypto_1.default.createPublicKey({ key: Buffer.from(this.options.hostPublicKey, "base64"), format: "der", type: "spki" });
136
+ const message = MicroserviceHost_1.MicroserviceHost.answerMessage(this.options.id, op, nonce, { result: a.result, error: a.error, pending: a.pending });
137
+ return crypto_1.default.verify(null, Buffer.from(message), key, Buffer.from(a.sig, "base64"));
138
+ }
139
+ catch {
140
+ return false;
141
+ }
142
+ }
143
+ }
144
+ exports.MicroserviceClient = MicroserviceClient;
@@ -0,0 +1,52 @@
1
+ import { Req } from "../../signal/Signal";
2
+ import { BaseService } from "../BaseService";
3
+ import { IRequest, IError } from "../structures/Interfaces";
4
+ export interface IMicroserviceCaller {
5
+ publicKey: string;
6
+ requests?: string[];
7
+ allowedIps?: string[];
8
+ }
9
+ export interface IMicroserviceHostOptions {
10
+ id: string;
11
+ requests: Req<any, any>[];
12
+ privateKey: string;
13
+ clients: Record<string, IMicroserviceCaller>;
14
+ jobStore?: IMicroserviceJobStore;
15
+ }
16
+ export interface IMicroserviceJob {
17
+ status: "processing" | "completed";
18
+ hash?: string;
19
+ result?: any | IError;
20
+ expires: number;
21
+ }
22
+ export interface IMicroserviceJobStore {
23
+ get(key: string): Promise<IMicroserviceJob | null> | IMicroserviceJob | null;
24
+ set(key: string, job: IMicroserviceJob): Promise<void> | void;
25
+ purge(now: number): Promise<void> | void;
26
+ }
27
+ export declare class MemoryJobStore implements IMicroserviceJobStore {
28
+ #private;
29
+ get(key: string): IMicroserviceJob | null;
30
+ set(key: string, job: IMicroserviceJob): void;
31
+ purge(now: number): void;
32
+ }
33
+ export interface IMicroserviceCall {
34
+ caller: string;
35
+ op: string;
36
+ requestName: string;
37
+ }
38
+ export declare const MICROSERVICE_PROTOCOL = 1;
39
+ export declare class MicroserviceHost extends BaseService {
40
+ #private;
41
+ options: IMicroserviceHostOptions;
42
+ constructor(opt: IMicroserviceHostOptions);
43
+ init(): Promise<void>;
44
+ static getMicroservice(id: string): MicroserviceHost | null;
45
+ static currentCall(): IMicroserviceCall | null;
46
+ static answerMessage(hostId: string, op: string, nonce: string, answer: {
47
+ result?: any;
48
+ error?: any;
49
+ pending?: boolean;
50
+ }): string;
51
+ handleIncomingRequest(req: IRequest): Promise<any | IError>;
52
+ }
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.MicroserviceHost = exports.MICROSERVICE_PROTOCOL = exports.MemoryJobStore = void 0;
40
+ const BaseService_1 = require("../BaseService");
41
+ const DefaultErrors_1 = __importStar(require("../structures/DefaultErrors"));
42
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
43
+ const JSONStableStringify_1 = require("../helper/JSONStableStringify");
44
+ const LogService_1 = require("../LogService");
45
+ const async_hooks_1 = require("async_hooks");
46
+ const Trace_1 = require("../helper/Trace");
47
+ const crypto_1 = __importDefault(require("crypto"));
48
+ const IpAllowList_1 = require("../helper/IpAllowList");
49
+ class MemoryJobStore {
50
+ #jobs = new Map();
51
+ get(key) { return this.#jobs.get(key) ?? null; }
52
+ set(key, job) { this.#jobs.set(key, job); }
53
+ purge(now) { for (const [k, j] of this.#jobs)
54
+ if (j.expires < now)
55
+ this.#jobs.delete(k); }
56
+ }
57
+ exports.MemoryJobStore = MemoryJobStore;
58
+ exports.MICROSERVICE_PROTOCOL = 1;
59
+ const ANSWER = "bmfk-ms-answer-v1";
60
+ const JOB_TTL = 1000 * 60 * 5;
61
+ class MicroserviceHost extends BaseService_1.BaseService {
62
+ static #instances = new Map();
63
+ static #context = new async_hooks_1.AsyncLocalStorage();
64
+ options;
65
+ #store;
66
+ #auth;
67
+ #allowedIps = new Map();
68
+ constructor(opt) {
69
+ super("Microservice-host-" + opt.id);
70
+ if (!opt.clients)
71
+ throw new Error(`MicroserviceHost "${opt.id}": set "clients" — the callers and their public keys`);
72
+ if (!opt.privateKey)
73
+ throw new Error(`MicroserviceHost "${opt.id}": set "privateKey" — the host signs its answers`);
74
+ InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(opt.privateKey);
75
+ this.#auth = new InterceptorSignedAuth_1.InterceptorSignedAuth(kid => opt.clients[kid]?.publicKey ?? null);
76
+ for (const [kid, c] of Object.entries(opt.clients)) {
77
+ if (c.allowedIps === undefined)
78
+ continue;
79
+ const built = IpAllowList_1.IpAllowList.build(c.allowedIps);
80
+ if (built.error)
81
+ throw new Error(`MicroserviceHost "${opt.id}": clients.${kid}.allowedIps: ${built.error}`);
82
+ if (!built.list)
83
+ throw new Error(`MicroserviceHost "${opt.id}": clients.${kid}.allowedIps is empty — list the addresses, or remove it to allow any`);
84
+ this.#allowedIps.set(kid, built.list);
85
+ }
86
+ this.options = opt;
87
+ this.#store = opt.jobStore ?? new MemoryJobStore();
88
+ MicroserviceHost.#instances.set(opt.id, this);
89
+ }
90
+ async init() {
91
+ super.init();
92
+ setInterval(() => {
93
+ Promise.resolve(this.#store.purge(Date.now())).catch(e => (0, LogService_1.logError)("MicroserviceHost job store purge failed", e));
94
+ }, 1000 * 60 * 5);
95
+ }
96
+ static getMicroservice(id) {
97
+ return MicroserviceHost.#instances.get(id) || null;
98
+ }
99
+ static currentCall() {
100
+ return MicroserviceHost.#context.getStore() ?? null;
101
+ }
102
+ static answerMessage(hostId, op, nonce, answer) {
103
+ const payload = (0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ result: answer.result, error: answer.error, pending: answer.pending })));
104
+ const digest = crypto_1.default.createHash("sha256").update(payload).digest("hex");
105
+ return [ANSWER, hostId, op, nonce, digest].join("\n");
106
+ }
107
+ async handleIncomingRequest(req) {
108
+ if (String(req.headers?.["authorization"] ?? "").toLowerCase().startsWith("signature "))
109
+ return this.#handleSigned(req);
110
+ return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "signed request required" };
111
+ }
112
+ async #handleSigned(req) {
113
+ const claimed = InterceptorSignedAuth_1.InterceptorSignedAuth.parseHeader(String(req.headers["authorization"]).slice("signature ".length)).kid;
114
+ const ips = claimed ? this.#allowedIps.get(claimed) : undefined;
115
+ if (ips && !IpAllowList_1.IpAllowList.allows(ips, req.ip)) {
116
+ (0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: rejected call — key "${claimed}" from ${req.ip ?? "unknown address"}, not in its allowedIps`);
117
+ return { ...DefaultErrors_1.default.FORBIDDEN, details: "address not allowed" };
118
+ }
119
+ const verdict = await this.#auth.verify(req);
120
+ if (!verdict.kid) {
121
+ (0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: rejected call — ${verdict.error}`);
122
+ return { ...DefaultErrors_1.default.UNAUTHORIZED, details: "invalid signature" };
123
+ }
124
+ const caller = verdict.kid;
125
+ Trace_1.Trace.adopt(req.data?.trace);
126
+ const nonce = InterceptorSignedAuth_1.InterceptorSignedAuth.parseHeader(String(req.headers["authorization"]).slice("signature ".length)).nonce;
127
+ const body = req.data ?? {};
128
+ if (body.v !== exports.MICROSERVICE_PROTOCOL || body.to !== this.options.id)
129
+ return { ...DefaultErrors_1.default.BAD_REQUEST, details: "request is not addressed to this host" };
130
+ if (typeof body.op !== "string" || !/^[A-Za-z0-9._:-]{8,128}$/.test(body.op) || typeof body.requestName !== "string")
131
+ return { ...DefaultErrors_1.default.BAD_REQUEST, details: "op and requestName required" };
132
+ const op = body.op;
133
+ const requestName = body.requestName;
134
+ const answer = (a) => this.#signAnswer(op, nonce, a);
135
+ const allowed = this.options.clients[caller]?.requests;
136
+ if (allowed && !allowed.includes(requestName)) {
137
+ (0, LogService_1.logWarn)(`MicroserviceHost ${this.options.id}: ${caller} may not call ${requestName}`);
138
+ return answer({ error: { ...DefaultErrors_1.default.FORBIDDEN, details: "request not allowed for " + caller } });
139
+ }
140
+ const jobKey = caller + "|" + op;
141
+ const hash = crypto_1.default.createHash("sha256")
142
+ .update((0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ requestName, requestData: body.requestData ?? null }))))
143
+ .digest("hex");
144
+ const job = await this.#store.get(jobKey);
145
+ if (job && job.expires >= Date.now()) {
146
+ if (job.hash && job.hash !== hash)
147
+ return answer({ error: { ...DefaultErrors_1.default.CONFLICT, details: "op was already used for another request" } });
148
+ if (job.status === "processing")
149
+ return answer({ pending: true });
150
+ return DefaultErrors_1.ErrorUtils.isError(job.result) ? answer({ error: job.result }) : answer({ result: job.result });
151
+ }
152
+ const reqCall = this.options.requests.find(r => r.name === requestName);
153
+ if (!reqCall)
154
+ return answer({ error: { ...DefaultErrors_1.default.NOT_FOUND, details: "request not registered: " + requestName } });
155
+ await this.#store.set(jobKey, { status: "processing", hash, expires: Date.now() + JOB_TTL });
156
+ let result;
157
+ try {
158
+ result = await MicroserviceHost.#context.run({ caller, op, requestName }, () => reqCall.request(body.requestData));
159
+ if (DefaultErrors_1.ErrorUtils.isError(result))
160
+ result = MicroserviceHost.#outbound(result);
161
+ }
162
+ catch (e) {
163
+ if (DefaultErrors_1.ErrorUtils.isError(e))
164
+ result = MicroserviceHost.#outbound(e);
165
+ else {
166
+ (0, LogService_1.logError)(`MicroserviceHost ${this.options.id}: ${requestName} from ${caller} threw`, e);
167
+ result = { ...DefaultErrors_1.default.INTERNAL_ERROR };
168
+ }
169
+ }
170
+ await this.#store.set(jobKey, { status: "completed", hash, result, expires: Date.now() + JOB_TTL });
171
+ return DefaultErrors_1.ErrorUtils.isError(result) ? answer({ error: result }) : answer({ result });
172
+ }
173
+ #signAnswer(op, nonce, a) {
174
+ const key = crypto_1.default.createPrivateKey({ key: Buffer.from(this.options.privateKey, "base64"), format: "der", type: "pkcs8" });
175
+ const sig = crypto_1.default.sign(null, Buffer.from(MicroserviceHost.answerMessage(this.options.id, op, nonce, a)), key).toString("base64");
176
+ return { v: exports.MICROSERVICE_PROTOCOL, op, ...a, sig };
177
+ }
178
+ static #outbound(e) {
179
+ const { stack, ...rest } = e;
180
+ return rest;
181
+ }
182
+ }
183
+ exports.MicroserviceHost = MicroserviceHost;
@@ -0,0 +1,6 @@
1
+ import { BaseEndpoint } from "../BaseEndpoint";
2
+ import { IRequest, IResponse } from "../structures/Interfaces";
3
+ export declare class MicroserviceHostController extends BaseEndpoint {
4
+ constructor();
5
+ receiver(req: IRequest): Promise<IResponse>;
6
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.MicroserviceHostController = void 0;
37
+ const BaseEndpoint_1 = require("../BaseEndpoint");
38
+ const DefaultErrors_1 = __importStar(require("../structures/DefaultErrors"));
39
+ const MicroserviceHost_1 = require("./MicroserviceHost");
40
+ class MicroserviceHostController extends BaseEndpoint_1.BaseEndpoint {
41
+ constructor() {
42
+ super("__ms_host_control");
43
+ this.ignoreInDocumentation = true;
44
+ this.ignoreHttpLogging = true;
45
+ this.registerEndpoints([{
46
+ ignoreInDocumentation: true,
47
+ endpoint: "receiver",
48
+ handler: this.receiver,
49
+ ignoreInterceptor: true,
50
+ },
51
+ ]);
52
+ }
53
+ async receiver(req) {
54
+ if (req.method.toUpperCase() !== "POST")
55
+ throw DefaultErrors_1.default.METHOD_NOT_ALLOWED;
56
+ const microserviceHost = MicroserviceHost_1.MicroserviceHost.getMicroservice(req.headers["x-microservice-id"]);
57
+ if (!microserviceHost)
58
+ throw { ...DefaultErrors_1.default.NOT_FOUND, message: "Microservice host not found with id: " + req.headers["x-microservice-id"] };
59
+ const result = await microserviceHost.handleIncomingRequest(req);
60
+ if (DefaultErrors_1.ErrorUtils.isError(result))
61
+ throw result;
62
+ return { data: result };
63
+ }
64
+ }
65
+ exports.MicroserviceHostController = MicroserviceHostController;
@@ -0,0 +1,9 @@
1
+ export declare const APP_DATA_ROOT_ENV = "BMFK_DATA_DIR";
2
+ export declare const AppData: {
3
+ project(): string;
4
+ projectDir(name: string): string;
5
+ root(): string;
6
+ dir(sub: string): string | null;
7
+ };
8
+ export declare function appDataPath(name: string, ext?: string): string;
9
+ export declare function onWriterChange(cb: (writer: boolean) => void): boolean;
@@ -0,0 +1,81 @@
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.AppData = exports.APP_DATA_ROOT_ENV = void 0;
7
+ exports.appDataPath = appDataPath;
8
+ exports.onWriterChange = onWriterChange;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const BlueGreenState_1 = require("../deployment/BlueGreenState");
12
+ exports.APP_DATA_ROOT_ENV = "BMFK_DATA_DIR";
13
+ const DEFAULT_ROOT = "/var/bmfk";
14
+ const fileSafe = (s) => s.replace(/^@[^/]+\//, "").replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^[._]+/, "").slice(0, 64);
15
+ function locate() {
16
+ const main = require.main?.filename ?? process.argv[1] ?? process.cwd();
17
+ let dir = path_1.default.dirname(path_1.default.resolve(main));
18
+ let packageRoot = null;
19
+ for (let i = 0; i < 12; i++) {
20
+ const bg = path_1.default.join(dir, ".bluegreen.json");
21
+ if (fs_1.default.existsSync(bg)) {
22
+ let project = null;
23
+ try {
24
+ project = JSON.parse(fs_1.default.readFileSync(bg, "utf-8"))?.project ?? null;
25
+ }
26
+ catch { }
27
+ return { root: path_1.default.dirname(dir), bluegreen: true, project };
28
+ }
29
+ if (!packageRoot && fs_1.default.existsSync(path_1.default.join(dir, "package.json")))
30
+ packageRoot = dir;
31
+ const parent = path_1.default.dirname(dir);
32
+ if (parent === dir)
33
+ break;
34
+ dir = parent;
35
+ }
36
+ const root = packageRoot ?? process.cwd();
37
+ let project = null;
38
+ try {
39
+ project = JSON.parse(fs_1.default.readFileSync(path_1.default.join(root, "package.json"), "utf-8"))?.name ?? null;
40
+ }
41
+ catch { }
42
+ return { root, bluegreen: false, project };
43
+ }
44
+ exports.AppData = {
45
+ project() {
46
+ const loc = locate();
47
+ return fileSafe(loc.project ?? "") || fileSafe(path_1.default.basename(loc.root)) || "app";
48
+ },
49
+ projectDir(name) {
50
+ return path_1.default.join(exports.AppData.root(), fileSafe(name) || "app");
51
+ },
52
+ root() {
53
+ const env = process.env[exports.APP_DATA_ROOT_ENV];
54
+ return path_1.default.resolve(env && env.length > 0 ? env : DEFAULT_ROOT);
55
+ },
56
+ dir(sub) {
57
+ const dir = path_1.default.join(exports.AppData.root(), exports.AppData.project(), sub);
58
+ try {
59
+ fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
60
+ fs_1.default.accessSync(dir, fs_1.default.constants.W_OK);
61
+ return dir;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ },
67
+ };
68
+ function appDataPath(name, ext = "") {
69
+ const loc = locate();
70
+ if (loc.bluegreen)
71
+ return path_1.default.join(loc.root, name + ext);
72
+ return path_1.default.join(path_1.default.dirname(loc.root), `${name}.${path_1.default.basename(loc.root)}${ext}`);
73
+ }
74
+ function onWriterChange(cb) {
75
+ const worker = process.env.NODE_APP_INSTANCE;
76
+ if (worker !== undefined && worker !== "0")
77
+ return false;
78
+ (0, BlueGreenState_1.onLiveChange)(live => cb(live));
79
+ (0, BlueGreenState_1.getBlueGreenActiveState)().catch(() => { });
80
+ return true;
81
+ }
@@ -0,0 +1,3 @@
1
+ export declare const DEFAULT_TRUSTED_PROXIES: string[];
2
+ export declare function fromTrustedProxy(req: any, trustedProxies?: Set<string>): boolean;
3
+ export declare function clientIp(req: any, trustedProxies?: Set<string>): string;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_TRUSTED_PROXIES = void 0;
4
+ exports.fromTrustedProxy = fromTrustedProxy;
5
+ exports.clientIp = clientIp;
6
+ exports.DEFAULT_TRUSTED_PROXIES = ["127.0.0.1", "::1"];
7
+ const norm = (a) => {
8
+ let s = String(a ?? "").trim();
9
+ if (s.startsWith("::ffff:"))
10
+ s = s.slice(7);
11
+ return s;
12
+ };
13
+ function fromTrustedProxy(req, trustedProxies = new Set(exports.DEFAULT_TRUSTED_PROXIES)) {
14
+ const peer = norm(req?.socket?.remoteAddress ?? req?.connection?.remoteAddress);
15
+ return !!peer && trustedProxies.has(peer);
16
+ }
17
+ function clientIp(req, trustedProxies = new Set(exports.DEFAULT_TRUSTED_PROXIES)) {
18
+ const peer = norm(req?.socket?.remoteAddress ?? req?.connection?.remoteAddress);
19
+ if (!peer)
20
+ return "unknown";
21
+ if (!trustedProxies.has(peer))
22
+ return peer;
23
+ const real = req?.headers?.["x-real-ip"];
24
+ if (typeof real === "string" && real.trim())
25
+ return norm(real.split(",")[0]);
26
+ const xff = req?.headers?.["x-forwarded-for"];
27
+ if (typeof xff === "string" && xff.trim()) {
28
+ const parts = xff.split(",").map(s => s.trim()).filter(Boolean);
29
+ if (parts.length)
30
+ return norm(parts[parts.length - 1]);
31
+ }
32
+ return peer;
33
+ }
@@ -0,0 +1,18 @@
1
+ export declare class DataProvider<T> {
2
+ private static nextID;
3
+ private name?;
4
+ private busy;
5
+ private lastRequestTime;
6
+ private cacheTime;
7
+ private data;
8
+ private callbacks;
9
+ private wasError;
10
+ private executor;
11
+ constructor(executor: () => Promise<{
12
+ data: T | null | undefined;
13
+ error?: boolean;
14
+ }>, cacheTime?: number, name?: string);
15
+ forceUpdate(): Promise<void>;
16
+ localUpdate(data: T): void;
17
+ getData(): Promise<T | null | undefined>;
18
+ }