@bmfk/api 0.0.0-stage → 1.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.
Files changed (169) hide show
  1. package/CHANGELOG.md +90 -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,41 @@
1
+ import { Pool, PoolClient } from 'pg';
2
+ import { DBAdapterOptions, IDBQuery, IDBResult, IDBBulkQuery, IPoolStatus, IDBStatFrame } from '../DBService';
3
+ import { IDBAdapter } from './IDBAdapter';
4
+ export declare class PostgresAdapter implements IDBAdapter {
5
+ options: DBAdapterOptions;
6
+ serviceStarted: boolean;
7
+ reconnectionTimeout: number;
8
+ reconnecting: boolean;
9
+ pool: Pool | null;
10
+ timeoutID: any;
11
+ queries: never[];
12
+ static nextTransactionID: number;
13
+ transactions: {
14
+ id: number;
15
+ timestamp: number;
16
+ conn: PoolClient;
17
+ queries: {
18
+ sql: string;
19
+ status: string;
20
+ }[];
21
+ }[];
22
+ maxTransactionWaitTime: number;
23
+ lastSuccessQueryTime: number;
24
+ pingInterval: number;
25
+ poolConnections: number;
26
+ acquiredPoolConnections: number;
27
+ statFrames: Map<number, IDBStatFrame>;
28
+ constructor(options: DBAdapterOptions);
29
+ stat(): Map<number, IDBStatFrame>;
30
+ escape(value: string): string;
31
+ tBegin?(): Promise<IDBResult>;
32
+ tCommit?(trxid: number): Promise<IDBResult>;
33
+ tRollback?(trxid: number): Promise<IDBResult>;
34
+ poolStatus(): IPoolStatus;
35
+ init(): Promise<void>;
36
+ healthcheck(): Promise<boolean>;
37
+ finish(): Promise<void>;
38
+ prepareQuery(request: IDBQuery): string;
39
+ query(request: IDBQuery): Promise<IDBResult>;
40
+ bulk(request: IDBBulkQuery): Promise<IDBResult[]>;
41
+ }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PostgresAdapter = void 0;
4
+ const pg_1 = require("pg");
5
+ const LogService_1 = require("../LogService");
6
+ class PostgresAdapter {
7
+ options;
8
+ serviceStarted = false;
9
+ reconnectionTimeout = 1000 * 3;
10
+ reconnecting = false;
11
+ pool = null;
12
+ timeoutID;
13
+ queries = [];
14
+ static nextTransactionID = 1;
15
+ transactions = [];
16
+ maxTransactionWaitTime = 1000 * 60 * 2;
17
+ lastSuccessQueryTime = 0;
18
+ pingInterval = 1000 * 60 * 5;
19
+ poolConnections = 0;
20
+ acquiredPoolConnections = 0;
21
+ statFrames = new Map();
22
+ constructor(options) {
23
+ this.options = options;
24
+ }
25
+ stat() {
26
+ return this.statFrames;
27
+ }
28
+ escape(value) {
29
+ return value;
30
+ }
31
+ tBegin() {
32
+ throw new Error('Method not implemented.');
33
+ }
34
+ tCommit(trxid) {
35
+ throw new Error('Method not implemented.');
36
+ }
37
+ tRollback(trxid) {
38
+ throw new Error('Method not implemented.');
39
+ }
40
+ poolStatus() {
41
+ throw new Error('Method not implemented.');
42
+ }
43
+ async init() {
44
+ this.pool = new pg_1.Pool({
45
+ connectionString: "postgresql://" + this.options.user + ":" + this.options.password + "@" + this.options.host + ":" + this.options.port + "/" + this.options.database + (this.options.connectionParamers ?? ""),
46
+ max: this.options.connectionLimit || 10,
47
+ idleTimeoutMillis: this.options.idleTimeoutMillis || 1000 * 60 * 5,
48
+ connectionTimeoutMillis: this.options.connectionTimeoutMillis || 1000 * 10,
49
+ keepAlive: true,
50
+ });
51
+ }
52
+ async healthcheck() {
53
+ if (!this.pool) {
54
+ (0, LogService_1.logError)("PostgreAdapter: Pool is not initialized.");
55
+ return false;
56
+ }
57
+ const { rows } = await this.pool.query('SELECT 1 AS ok');
58
+ return rows?.[0]?.ok === 1;
59
+ }
60
+ finish() {
61
+ throw new Error("Method not implemented.");
62
+ }
63
+ prepareQuery(request) {
64
+ throw new Error("Method not implemented.");
65
+ }
66
+ query(request) {
67
+ throw new Error("Method not implemented.");
68
+ }
69
+ bulk(request) {
70
+ throw new Error("Method not implemented.");
71
+ }
72
+ }
73
+ exports.PostgresAdapter = PostgresAdapter;
@@ -0,0 +1,5 @@
1
+ export declare function findAccessPaths(root: string): {
2
+ path: string;
3
+ where: string;
4
+ }[];
5
+ export declare function AccessConfigWizard(fileArg?: string): Promise<void>;
@@ -0,0 +1,254 @@
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.findAccessPaths = findAccessPaths;
7
+ exports.AccessConfigWizard = AccessConfigWizard;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const AppDataPath_1 = require("../helper/AppDataPath");
11
+ const crypto_1 = __importDefault(require("crypto"));
12
+ const process_1 = require("process");
13
+ const PasswordHash_1 = require("../helper/PasswordHash");
14
+ const IpAllowList_1 = require("../helper/IpAllowList");
15
+ const MonitorAuth_1 = require("../monitor/MonitorAuth");
16
+ const AccessStore_1 = require("../monitor/AccessStore");
17
+ const HashPassword_1 = require("./HashPassword");
18
+ const cliCommon_1 = require("./cliCommon");
19
+ const cliPrompt_1 = require("./cliPrompt");
20
+ const ROLES = {
21
+ admin: "everything, incl. restart, log level and IP blocking",
22
+ it: "dashboard and logs",
23
+ analytic: "dashboard only",
24
+ };
25
+ function findAccessPaths(root) {
26
+ const found = [];
27
+ const re = /\baccess\s*[:=]\s*(["'`])([^"'`\n]+?\.json)\1/g;
28
+ let files = 0;
29
+ const visit = (dir, depth) => {
30
+ if (depth > 8 || files > 3000)
31
+ return;
32
+ let entries;
33
+ try {
34
+ entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
35
+ }
36
+ catch {
37
+ return;
38
+ }
39
+ for (const e of entries) {
40
+ if (e.name === "node_modules" || e.name.startsWith("."))
41
+ continue;
42
+ const abs = path_1.default.join(dir, e.name);
43
+ if (e.isDirectory()) {
44
+ visit(abs, depth + 1);
45
+ continue;
46
+ }
47
+ if (!e.isFile() || !/\.(ts|js|cjs|mjs)$/.test(e.name) || e.name.endsWith(".d.ts"))
48
+ continue;
49
+ files++;
50
+ let text;
51
+ try {
52
+ if (fs_1.default.statSync(abs).size > 1024 * 1024)
53
+ continue;
54
+ text = fs_1.default.readFileSync(abs, "utf-8");
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ for (const m of text.matchAll(re)) {
60
+ if (found.some(f => f.path === m[2]))
61
+ continue;
62
+ const line = text.slice(0, m.index).split("\n").length;
63
+ found.push({ path: m[2], where: `${path_1.default.relative(root, abs)}:${line}` });
64
+ }
65
+ }
66
+ };
67
+ for (const sub of ["src", "bin", "dist"]) {
68
+ const dir = path_1.default.join(root, sub);
69
+ if (fs_1.default.existsSync(dir))
70
+ visit(dir, 0);
71
+ }
72
+ return found;
73
+ }
74
+ async function AccessConfigWizard(fileArg) {
75
+ const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
76
+ if (!process_1.stdin.isTTY) {
77
+ console.error(red("✗ access-config needs an interactive terminal — it asks for passwords."));
78
+ process.exit(1);
79
+ }
80
+ console.log(bold("\nAccess file for the monitor and the documentation") + dim(" (the service re-reads it on change)"));
81
+ let file;
82
+ if (fileArg) {
83
+ file = path_1.default.resolve(fileArg);
84
+ }
85
+ else {
86
+ const found = findAccessPaths(process.cwd());
87
+ if (found.length === 1) {
88
+ console.log(dim(` This project's access file (from ${found[0].where}): ${found[0].path}`));
89
+ file = path_1.default.resolve(await (0, cliPrompt_1.ask)("File", found[0].path));
90
+ }
91
+ else if (found.length > 1) {
92
+ found.forEach((f, i) => console.log(` ${i + 1}) ${f.path} ${dim("— " + f.where)}`));
93
+ const pick = await (0, cliPrompt_1.askValid)("File (number or path)", "1", v => /^\d+$/.test(v) && !found[+v - 1] ? "no such number" : null);
94
+ file = path_1.default.resolve(/^\d+$/.test(pick) ? found[+pick - 1].path : pick);
95
+ }
96
+ else {
97
+ const fallback = path_1.default.join(AppDataPath_1.AppData.projectDir(AppDataPath_1.AppData.project()), "access.json");
98
+ console.log(dim(` This project reads ${fallback} unless its code sets "access" to another file.`));
99
+ file = path_1.default.resolve(await (0, cliPrompt_1.ask)("File", fallback));
100
+ }
101
+ }
102
+ let doc = { monitor: [], documentation: [] };
103
+ if (fs_1.default.existsSync(file)) {
104
+ try {
105
+ doc = JSON.parse(fs_1.default.readFileSync(file, "utf-8") || "{}");
106
+ }
107
+ catch (e) {
108
+ console.error(red(`✗ ${file} is not valid JSON (${e?.message ?? e}) — fix it first or choose another file.`));
109
+ process.exit(1);
110
+ }
111
+ const problem = AccessStore_1.AccessStore.validate(doc);
112
+ if (problem)
113
+ console.log(yellow(` ⚠ The file has a problem the service would refuse: ${problem}. Fix it here before saving.`));
114
+ console.log(dim(` Loaded ${file}`));
115
+ }
116
+ else {
117
+ console.log(dim(` New file: ${file}`));
118
+ }
119
+ doc.monitor = Array.isArray(doc.monitor) ? doc.monitor : [];
120
+ doc.documentation = Array.isArray(doc.documentation) ? doc.documentation : [];
121
+ let changed = false;
122
+ const show = () => {
123
+ console.log("\n" + bold("Monitor users"));
124
+ if (!doc.monitor.length)
125
+ console.log(dim(" none — nobody can open the monitor"));
126
+ for (const u of doc.monitor) {
127
+ const state = PasswordHash_1.PasswordHash.isHash(u.password) ? dim("hashed password") : red("PLAIN-TEXT password — refused at sign-in, change it");
128
+ console.log(` ${u.login.padEnd(20)} ${String(u.role ?? "admin (default)").padEnd(16)} ${state}`);
129
+ }
130
+ console.log(bold("Documentation users"));
131
+ if (!doc.documentation.length)
132
+ console.log(dim(" none"));
133
+ for (const u of doc.documentation)
134
+ console.log(` ${u.login.padEnd(20)} ${u.endpoints?.length ? "endpoints: " + u.endpoints.join(", ") : dim("all endpoints")}`);
135
+ console.log(bold("Monitor allowed addresses"));
136
+ console.log(" " + (doc.monitorAllowedIps?.length ? doc.monitorAllowedIps.join(", ") : dim("any address")));
137
+ };
138
+ const monitorLogin = (login) => doc.monitor.find((u) => u.login === login);
139
+ const docLogin = (login) => doc.documentation.find((u) => u.login === login);
140
+ async function newMonitorPassword(login) {
141
+ for (;;) {
142
+ const p1 = await (0, HashPassword_1.askHidden)(` password for ${login} (hidden, 12+ characters): `);
143
+ const policy = MonitorAuth_1.MonitorAuth.passwordPolicyError(p1);
144
+ if (policy) {
145
+ console.log(red(` ✗ ${policy}`));
146
+ continue;
147
+ }
148
+ const p2 = await (0, HashPassword_1.askHidden)(" repeat: ");
149
+ if (p1 !== p2) {
150
+ console.log(red(" ✗ passwords do not match"));
151
+ continue;
152
+ }
153
+ return PasswordHash_1.PasswordHash.hash(p1);
154
+ }
155
+ }
156
+ const askRole = (def) => (0, cliPrompt_1.askValid)(` role: ${Object.keys(ROLES).map(r => `${r} (${ROLES[r]})`).join(" / ")}\n role`, def, v => v in ROLES ? null : "admin, it or analytic");
157
+ const actions = {
158
+ "1": { title: "add a monitor user", run: async () => {
159
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => !v ? "required" : v.includes(":") ? "no ':' in logins" : monitorLogin(v) ? "already exists — use 'change password' or 'change role'" : null);
160
+ const role = await askRole("it");
161
+ doc.monitor.push({ login, password: await newMonitorPassword(login), role });
162
+ console.log(green(` ✓ ${login} added`) + dim(" — 2FA is set up at the first sign-in"));
163
+ changed = true;
164
+ } },
165
+ "2": { title: "change a monitor password", run: async () => {
166
+ const u = monitorLogin(await (0, cliPrompt_1.askValid)(" login", "", v => monitorLogin(v) ? null : "no such monitor user"));
167
+ u.password = await newMonitorPassword(u.login);
168
+ console.log(green(` ✓ password of ${u.login} changed`) + dim(" — their open sessions end when the service picks up the file"));
169
+ changed = true;
170
+ } },
171
+ "3": { title: "change a monitor role", run: async () => {
172
+ const u = monitorLogin(await (0, cliPrompt_1.askValid)(" login", "", v => monitorLogin(v) ? null : "no such monitor user"));
173
+ u.role = await askRole(u.role ?? "admin");
174
+ console.log(green(` ✓ ${u.login} is now ${u.role}`));
175
+ changed = true;
176
+ } },
177
+ "4": { title: "remove a monitor user", run: async () => {
178
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => monitorLogin(v) ? null : "no such monitor user");
179
+ if (!(await (0, cliPrompt_1.yes)(` remove ${login}?`, false)))
180
+ return;
181
+ doc.monitor = doc.monitor.filter((u) => u.login !== login);
182
+ console.log(green(` ✓ ${login} removed`) + dim(" — their sessions end when the service picks up the file"));
183
+ changed = true;
184
+ } },
185
+ "5": { title: "add a documentation user", run: async () => {
186
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => !v ? "required" : v.includes(":") ? "no ':' in logins" : docLogin(v) ? "already exists" : null);
187
+ let password;
188
+ if (await (0, cliPrompt_1.yes)(" generate a random password?", true)) {
189
+ const plain = crypto_1.default.randomBytes(18).toString("base64url");
190
+ console.log(` password: ${bold(plain)} ${dim("— pass it on now; only its hash is stored")}`);
191
+ password = await PasswordHash_1.PasswordHash.hash(plain);
192
+ }
193
+ else {
194
+ password = await newMonitorPassword(login);
195
+ }
196
+ const endpoints = (0, cliPrompt_1.list)(await (0, cliPrompt_1.ask)(" limit to endpoints, comma-separated (empty = all)", ""));
197
+ doc.documentation.push({ login, password, ...(endpoints.length ? { endpoints } : {}) });
198
+ console.log(green(` ✓ ${login} added`) + dim(" — 2FA is set up at the first sign-in"));
199
+ changed = true;
200
+ } },
201
+ "6": { title: "remove a documentation user", run: async () => {
202
+ const login = await (0, cliPrompt_1.askValid)(" login", "", v => docLogin(v) ? null : "no such documentation user");
203
+ if (!(await (0, cliPrompt_1.yes)(` remove ${login}?`, false)))
204
+ return;
205
+ doc.documentation = doc.documentation.filter((u) => u.login !== login);
206
+ console.log(green(` ✓ ${login} removed`));
207
+ changed = true;
208
+ } },
209
+ "7": { title: "set the monitor's allowed addresses", run: async () => {
210
+ const v = await (0, cliPrompt_1.askValid)(" IPs and subnets, comma-separated (empty = any address)", (doc.monitorAllowedIps ?? []).join(", "), x => IpAllowList_1.IpAllowList.build((0, cliPrompt_1.list)(x)).error ?? null);
211
+ const ips = (0, cliPrompt_1.list)(v);
212
+ if (ips.length)
213
+ doc.monitorAllowedIps = ips;
214
+ else
215
+ delete doc.monitorAllowedIps;
216
+ if (ips.length)
217
+ console.log(dim(" Behind nginx the service must see the real address (X-Real-IP), or every request looks like 127.0.0.1."));
218
+ changed = true;
219
+ } },
220
+ };
221
+ for (;;) {
222
+ show();
223
+ console.log("\n" + Object.entries(actions).map(([k, a]) => ` ${k}) ${a.title}`).join("\n") + `\n s) save and exit\n q) quit without saving`);
224
+ const choice = (await (0, cliPrompt_1.ask)("Choose", "")).toLowerCase();
225
+ if (choice === "q") {
226
+ if (changed && !(await (0, cliPrompt_1.yes)("Discard the changes?", false)))
227
+ continue;
228
+ return;
229
+ }
230
+ if (choice === "s") {
231
+ const problem = AccessStore_1.AccessStore.validate(doc);
232
+ if (problem) {
233
+ console.log(red(` ✗ Not saved — the service would refuse it: ${problem}`));
234
+ continue;
235
+ }
236
+ if (!doc.monitor.some((u) => PasswordHash_1.PasswordHash.isHash(u.password)))
237
+ console.log(yellow(" ⚠ No monitor user can sign in — the monitor stays closed."));
238
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
239
+ const tmp = file + ".tmp";
240
+ fs_1.default.writeFileSync(tmp, JSON.stringify(doc, null, 2) + "\n", { encoding: "utf-8", mode: 0o600 });
241
+ fs_1.default.chmodSync(tmp, 0o600);
242
+ fs_1.default.renameSync(tmp, file);
243
+ console.log(green(`✓ Saved ${file}`) + dim(" (0600) — a running service picks it up within a second"));
244
+ console.log(dim(` Point the service at it: access: ${JSON.stringify(file)}`));
245
+ return;
246
+ }
247
+ const action = actions[choice];
248
+ if (!action) {
249
+ console.log(red(" ✗ choose a number, s or q"));
250
+ continue;
251
+ }
252
+ await action.run();
253
+ }
254
+ }
@@ -0,0 +1,4 @@
1
+ import { IDeployerConfig } from "./resolveConfig";
2
+ type IActivateParams = IDeployerConfig;
3
+ export declare function Activate(opt?: IActivateParams | string | null, scheme?: "blue" | "green"): Promise<string>;
4
+ export {};
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Activate = Activate;
4
+ const Http_1 = require("../http/Http");
5
+ const DefaultErrors_1 = require("../structures/DefaultErrors");
6
+ const resolveConfig_1 = require("./resolveConfig");
7
+ const cliCommon_1 = require("./cliCommon");
8
+ async function Activate(opt, scheme) {
9
+ opt = await (0, resolveConfig_1.resolveConfig)(opt);
10
+ if (scheme && scheme !== "blue" && scheme !== "green") {
11
+ throw new Error(`Invalid scheme: ${scheme}. Must be "blue" or "green" (or omitted).`);
12
+ }
13
+ let switchUrl;
14
+ if (opt.switch_host) {
15
+ switchUrl = opt.switch_host;
16
+ }
17
+ else if (/\/add\/?$/.test(opt.host)) {
18
+ switchUrl = opt.host.replace(/\/add\/?$/, "/switch");
19
+ }
20
+ else {
21
+ throw new Error(`Cannot derive switch URL from host "${opt.host}". ` +
22
+ `Either add "switch_host" to config, or make sure "host" ends with /add.`);
23
+ }
24
+ const requestBody = { name: opt.name, token: opt.token };
25
+ if (scheme)
26
+ requestBody.scheme = scheme;
27
+ console.log(`Activating${scheme ? ` slot=${scheme}` : " (auto: lastDeployed)"} for ${opt.name} at ${switchUrl}`);
28
+ const startedAt = Date.now();
29
+ const response = await Http_1.Http.post(switchUrl, requestBody, {
30
+ headers: (0, cliCommon_1.deployerHeaders)(opt, switchUrl, requestBody),
31
+ timeoutMs: 60 * 1000,
32
+ retry: { enabled: false },
33
+ });
34
+ const elapsedMs = Date.now() - startedAt;
35
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
36
+ const c = (code, t) => useColor ? `\x1b[${code}m${t}\x1b[0m` : t;
37
+ const red = (t) => c("31", t);
38
+ const green = (t) => c("32", t);
39
+ const yellow = (t) => c("33", t);
40
+ const dim = (t) => c("2", t);
41
+ const bold = (t) => c("1", t);
42
+ const line = dim("─".repeat(60));
43
+ const now = new Date();
44
+ const pad = (n) => String(n).padStart(2, "0");
45
+ const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
46
+ console.log("");
47
+ if (!response.ok) {
48
+ const statusStr = response.status !== undefined
49
+ ? `HTTP ${response.status}`
50
+ : "network error (no response)";
51
+ console.error(red(bold("✗ ACTIVATE FAILED — transport error")));
52
+ console.error(line);
53
+ console.error(` ${dim("host: ")} ${switchUrl}`);
54
+ console.error(` ${dim("status: ")} ${statusStr}`);
55
+ console.error(` ${dim("elapsed: ")} ${elapsedMs}ms`);
56
+ if (response.error !== undefined) {
57
+ const errText = typeof response.error === "string"
58
+ ? response.error
59
+ : JSON.stringify(response.error);
60
+ const clipped = errText.length > 400 ? errText.slice(0, 400) + `... (${errText.length} total)` : errText;
61
+ console.error(` ${dim("error: ")} ${clipped}`);
62
+ }
63
+ console.error(line);
64
+ process.exit(1);
65
+ }
66
+ const body = response.data;
67
+ let appError = null;
68
+ if (body && typeof body === "object") {
69
+ if (DefaultErrors_1.ErrorUtils.isError(body?.error))
70
+ appError = body.error;
71
+ else if (DefaultErrors_1.ErrorUtils.isError(body?.data?.error))
72
+ appError = body.data.error;
73
+ else if (DefaultErrors_1.ErrorUtils.isError(body?.data))
74
+ appError = body.data;
75
+ else if (DefaultErrors_1.ErrorUtils.isError(body))
76
+ appError = body;
77
+ }
78
+ if (appError) {
79
+ console.error(red(bold("✗ ACTIVATE REJECTED BY SERVER")));
80
+ console.error(line);
81
+ console.error(` ${dim("host: ")} ${switchUrl}`);
82
+ console.error(` ${dim("code: ")} ${appError.code}`);
83
+ console.error(` ${dim("message: ")} ${appError.message}`);
84
+ if (appError.httpStatus)
85
+ console.error(` ${dim("httpCode: ")} ${appError.httpStatus}`);
86
+ if (appError.details !== undefined) {
87
+ const d = typeof appError.details === "string" ? appError.details : JSON.stringify(appError.details);
88
+ const clipped = d.length > 400 ? d.slice(0, 400) + `... (${d.length} total)` : d;
89
+ console.error(` ${dim("details: ")} ${clipped}`);
90
+ }
91
+ console.error(` ${dim("elapsed: ")} ${elapsedMs}ms`);
92
+ console.error(line);
93
+ process.exit(1);
94
+ }
95
+ const info = body?.data ?? {};
96
+ const action = info.action ?? "switch";
97
+ const active = info.active ?? "?";
98
+ const previous = info.previousActive ?? "?";
99
+ const hookError = info.hookError ?? null;
100
+ if (hookError) {
101
+ console.log(yellow(bold("⚠ SLOT FLIPPED BUT nginx RELOAD FAILED")));
102
+ }
103
+ else if (action === "rollback") {
104
+ console.log(green(bold("✓ ROLLBACK SUCCESSFUL")));
105
+ }
106
+ else {
107
+ console.log(green(bold("✓ ACTIVATE SUCCESSFUL")));
108
+ }
109
+ console.log(line);
110
+ console.log(` ${dim("project: ")} ${opt.name}`);
111
+ console.log(` ${dim("action: ")} ${action}`);
112
+ console.log(` ${dim("active: ")} ${previous} ${dim("→")} ${bold(active)}`);
113
+ console.log(` ${dim("host: ")} ${switchUrl}`);
114
+ console.log(` ${dim("status: ")} HTTP ${response.status}`);
115
+ console.log(` ${dim("elapsed: ")} ${elapsedMs}ms`);
116
+ console.log(` ${dim("time: ")} ${stamp}`);
117
+ if (hookError) {
118
+ console.log(` ${dim("hookErr: ")} ${yellow(hookError)}`);
119
+ console.log(dim(` (state + symlink already committed; retry the reload manually: nginx -s reload)`));
120
+ }
121
+ console.log(line);
122
+ console.log("");
123
+ return active;
124
+ }
@@ -0,0 +1,33 @@
1
+ export declare const BACKUP_META = ".bmfk-backup.json";
2
+ export declare const MAX_BACKUPS = 10;
3
+ export type TBackupSlot = "blue" | "green" | null;
4
+ export interface IBackupMeta {
5
+ version: 1;
6
+ project: string;
7
+ slot: TBackupSlot;
8
+ createdAt: number;
9
+ user: string;
10
+ reason: "deploy" | "pre-restore";
11
+ appVersion: string | null;
12
+ }
13
+ export interface IBackupInfo extends IBackupMeta {
14
+ name: string;
15
+ sizeKb: number | null;
16
+ }
17
+ export declare class BackupManager {
18
+ static fileSafe(s: string): string;
19
+ static stamp(d?: Date): string;
20
+ static isValidName(name: string): boolean;
21
+ private static hasContent;
22
+ private static readMeta;
23
+ private static readAppVersion;
24
+ private static assertSafeRoot;
25
+ static create(target: string, project: string, slot: TBackupSlot, user: string, reason: IBackupMeta["reason"]): Promise<string | null>;
26
+ static list(root: string, project: string, withSize?: boolean): Promise<IBackupInfo[]>;
27
+ static prune(root: string, project: string, keep?: number, protect?: string[]): Promise<string[]>;
28
+ static resolve(root: string, project: string, name: string): {
29
+ dir: string;
30
+ meta: IBackupMeta;
31
+ } | null;
32
+ static restoreInto(backupDir: string, target: string): Promise<void>;
33
+ }