@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,214 @@
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.publicKeyProblem = publicKeyProblem;
7
+ exports.normalizeBase = normalizeBase;
8
+ exports.deployerInitFiles = deployerInitFiles;
9
+ exports.nginxSnippet = nginxSnippet;
10
+ exports.DeployerInit = DeployerInit;
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const net_1 = __importDefault(require("net"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const crypto_1 = __importDefault(require("crypto"));
15
+ const child_process_1 = require("child_process");
16
+ const process_1 = require("process");
17
+ const AppDataPath_1 = require("../helper/AppDataPath");
18
+ const IpAllowList_1 = require("../helper/IpAllowList");
19
+ const ConfigService_1 = require("./ConfigService");
20
+ const HashPassword_1 = require("./HashPassword");
21
+ const cliCommon_1 = require("./cliCommon");
22
+ const cliPrompt_1 = require("./cliPrompt");
23
+ const DEFAULT_PORT = 9915;
24
+ function publicKeyProblem(key) {
25
+ try {
26
+ const k = crypto_1.default.createPublicKey({ key: Buffer.from(key, "base64"), format: "der", type: "spki" });
27
+ return k.asymmetricKeyType === "ed25519" ? null : `an ${k.asymmetricKeyType} key — deploy keys are Ed25519`;
28
+ }
29
+ catch {
30
+ return "not a public key — paste what `npx bmfk deploy-key` printed";
31
+ }
32
+ }
33
+ function normalizeBase(base) {
34
+ let b = base.trim() || "/";
35
+ if (!b.startsWith("/"))
36
+ b = "/" + b;
37
+ if (!b.endsWith("/"))
38
+ b += "/";
39
+ return b;
40
+ }
41
+ function deployerInitFiles(a, packageJson) {
42
+ const main = `"use strict";
43
+ // The deployer — written by \`bmfk deployer-init\`. It runs under pm2 (ecosystem.config.cjs) as the user
44
+ // that owns the deployed projects. Who may deploy: ${path_1.default.join(a.setupPath, "setup.json")}
45
+ // (npx bmfk setup-config ${a.setupPath}); project configs: ${a.projectsPath} (npx bmfk project-config).
46
+ const { APIService, Initializer, LogService, getDefaultOptions, getDefaultLogOptions, LOG_LEVEL } = require("@bmfk/api");
47
+
48
+ const logOptions = getDefaultLogOptions();
49
+ logOptions.output = item => console.log(\`\${item.date} \${LOG_LEVEL[item.level]} \${item.text}\`);
50
+
51
+ Initializer([
52
+ new LogService(logOptions),
53
+ new APIService(getDefaultOptions({
54
+ port: ${a.port},
55
+ baseEndPoint: ${JSON.stringify(a.baseEndPoint)},
56
+ projectName: ${JSON.stringify(a.name)},
57
+ fileLimit: ${a.maxArchiveMb} * 1024 * 1024, // the largest deploy archive accepted
58
+ deployer: {
59
+ projects_path: ${JSON.stringify(a.projectsPath)},
60
+ setup_path: ${JSON.stringify(a.setupPath)},
61
+ },
62
+ })),
63
+ ]);
64
+ `;
65
+ const ecosystem = `// pm2 process of the deployer — written by \`bmfk deployer-init\`.
66
+ // pm2 start ecosystem.config.cjs && pm2 save
67
+ module.exports = {
68
+ apps: [{
69
+ name: ${JSON.stringify(a.name)},
70
+ script: "bin/Main.js",
71
+ cwd: __dirname,
72
+ autorestart: true,
73
+ env: { NODE_ENV: "production" },
74
+ }],
75
+ };
76
+ `;
77
+ let pkg = {};
78
+ let indent = 2;
79
+ if (packageJson) {
80
+ pkg = JSON.parse(packageJson);
81
+ indent = packageJson.match(/^[ \t]+(?=")/m)?.[0] ?? 2;
82
+ }
83
+ pkg.name = a.name;
84
+ pkg.private = true;
85
+ pkg.main = "bin/Main.js";
86
+ pkg.scripts = { ...(pkg.scripts ?? {}), start: "node bin/Main.js" };
87
+ delete pkg.scripts.test;
88
+ const setup = { users: a.users };
89
+ if (a.allowedIps.length)
90
+ setup.allowed_ips = a.allowedIps;
91
+ if (a.telegram)
92
+ setup.telegram = a.telegram;
93
+ return {
94
+ "bin/Main.js": { content: main },
95
+ "ecosystem.config.cjs": { content: ecosystem },
96
+ "package.json": { content: JSON.stringify(pkg, null, indent) + "\n" },
97
+ [path_1.default.join(a.setupPath, "setup.json")]: { content: JSON.stringify(setup, null, 4) + "\n", mode: 0o600 },
98
+ };
99
+ }
100
+ function nginxSnippet(a) {
101
+ return `location ${a.baseEndPoint}pckg/ {
102
+ proxy_pass http://127.0.0.1:${a.port};
103
+ proxy_set_header Host $host;
104
+ proxy_set_header X-Real-IP $remote_addr;
105
+ client_max_body_size ${a.maxArchiveMb}m;
106
+ proxy_read_timeout 600s; # npm ci and the build of a deploy take a while
107
+ }`;
108
+ }
109
+ const portFree = (port) => new Promise(resolve => {
110
+ const s = net_1.default.createServer().once("error", () => resolve(false)).once("listening", () => s.close(() => resolve(true)));
111
+ s.listen(port, "127.0.0.1");
112
+ });
113
+ function pm2Version() {
114
+ try {
115
+ return (0, child_process_1.execFileSync)("pm2", ["-v"], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();
116
+ }
117
+ catch {
118
+ return null;
119
+ }
120
+ }
121
+ async function DeployerInit(args) {
122
+ const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
123
+ if (!process_1.stdin.isTTY) {
124
+ console.error(red("✗ deployer-init is interactive — run it in a terminal on the server."));
125
+ process.exit(1);
126
+ }
127
+ const dir = path_1.default.resolve(args[0] ?? ".");
128
+ console.log(bold(`\nbmfk deployer-init — ${dir}\n`));
129
+ if (process.getuid?.() === 0) {
130
+ console.error(red("✗ running as root. The deployer must run as the user that owns the deployed projects (and pm2) — switch to it."));
131
+ process.exit(1);
132
+ }
133
+ if (!fs_1.default.existsSync(path_1.default.join(dir, "node_modules", "@bmfk", "api"))) {
134
+ console.error(red(`✗ @bmfk/api is not installed in ${dir}. First: npm init -y && npm i @bmfk/api`));
135
+ process.exit(1);
136
+ }
137
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
138
+ console.log(` ${nodeMajor >= 24 ? green("✓") : red("✗")} Node.js ${process.versions.node}${nodeMajor >= 24 ? "" : " — @bmfk/api needs 24 or later"}`);
139
+ const pm2 = pm2Version();
140
+ console.log(` ${pm2 ? green("✓") : yellow("!")} pm2 ${pm2 ?? "not found — install it: npm i -g pm2"}`);
141
+ const root = AppDataPath_1.AppData.root();
142
+ let rootOk = true;
143
+ try {
144
+ fs_1.default.accessSync(root, fs_1.default.constants.W_OK);
145
+ }
146
+ catch {
147
+ rootOk = false;
148
+ }
149
+ console.log(` ${rootOk ? green("✓") : yellow("!")} ${root} ${rootOk ? "writable" : `missing or not writable — create it once: sudo mkdir -p ${root} && sudo chown ${process.env.USER ?? "<this user>"} ${root}`}`);
150
+ if (!rootOk && !(await (0, cliPrompt_1.yes)(" continue anyway (folders are asked next)?", false)))
151
+ return;
152
+ console.log(bold("\nThe service"));
153
+ const name = await (0, cliPrompt_1.askValid)(" name (pm2 process, data folder)", "bmfk-deployer", v => (0, ConfigService_1.projectNameProblem)(v));
154
+ let port = 0;
155
+ for (;;) {
156
+ port = Number(await (0, cliPrompt_1.askValid)(" port (local; nginx proxies to it)", String(DEFAULT_PORT), v => /^\d+$/.test(v) && +v > 0 && +v < 65536 ? null : "a port number"));
157
+ if (await portFree(port))
158
+ break;
159
+ console.log(red(` ✗ port ${port} is in use`));
160
+ }
161
+ const baseEndPoint = normalizeBase(await (0, cliPrompt_1.ask)(" base path (deploys go to <domain><base>pckg/add)", "/api/"));
162
+ const maxArchiveMb = Number(await (0, cliPrompt_1.askValid)(" largest deploy archive, MB", "100", v => /^\d+$/.test(v) && +v > 0 ? null : "a number"));
163
+ const dataDir = path_1.default.join(root, name);
164
+ const projectsPath = path_1.default.resolve(await (0, cliPrompt_1.ask)(" project configs folder", path_1.default.join(dataDir, "projects")));
165
+ const setupPath = path_1.default.resolve(await (0, cliPrompt_1.ask)(" setup.json folder", path_1.default.join(dataDir, "setup")));
166
+ console.log(bold("\nWho may deploy") + dim(" (signed requests only; more users later: npx bmfk setup-config " + setupPath + ")"));
167
+ console.log(dim(" On the machine you deploy from, in the project: npx bmfk deploy-key — it prints the public key."));
168
+ const users = [];
169
+ while (users.length === 0 || await (0, cliPrompt_1.yes)(" add another user?", false)) {
170
+ const login = await (0, cliPrompt_1.askValid)(" login", users.length ? "" : "ci", v => !v ? "required" : v.includes(":") ? "no ':' in logins" : users.some(u => u.login === v) ? "already added" : null);
171
+ const publicKey = await (0, cliPrompt_1.askValid)(" public key", "", v => publicKeyProblem(v));
172
+ users.push({ login, publicKey });
173
+ }
174
+ const allowedIps = (0, cliPrompt_1.list)(await (0, cliPrompt_1.askValid)(" addresses allowed to deploy (IPs / subnets, comma-separated; empty = any)", "", v => !v.trim() ? null : IpAllowList_1.IpAllowList.build((0, cliPrompt_1.list)(v)).error ?? null));
175
+ let telegram;
176
+ if (await (0, cliPrompt_1.yes)("\nPost deploy events to a Telegram chat?", false)) {
177
+ const bot = (await (0, HashPassword_1.askHidden)(" bot token (hidden): ")).trim();
178
+ const chat = await (0, cliPrompt_1.askValid)(" chat id (a group starts with -100)", "", v => /^-?\d+$/.test(v) ? null : "a number");
179
+ if (bot)
180
+ telegram = { bot, chat };
181
+ }
182
+ const answers = { name, port, baseEndPoint, maxArchiveMb, projectsPath, setupPath, users, allowedIps, telegram };
183
+ const pkgFile = path_1.default.join(dir, "package.json");
184
+ const files = deployerInitFiles(answers, fs_1.default.existsSync(pkgFile) ? fs_1.default.readFileSync(pkgFile, "utf-8") : null);
185
+ console.log(bold("\nFiles"));
186
+ for (const [rel, f] of Object.entries(files)) {
187
+ const target = path_1.default.resolve(dir, rel);
188
+ if (fs_1.default.existsSync(target) && rel !== "package.json") {
189
+ if (fs_1.default.readFileSync(target, "utf-8") === f.content) {
190
+ console.log(dim(` = ${target} (unchanged)`));
191
+ continue;
192
+ }
193
+ if (!(await (0, cliPrompt_1.yes)(` ${target} exists — replace it?`, false))) {
194
+ console.log(yellow(` ! kept ${target}`));
195
+ continue;
196
+ }
197
+ }
198
+ fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true, mode: 0o700 });
199
+ fs_1.default.writeFileSync(target, f.content, { encoding: "utf-8", mode: f.mode ?? 0o644 });
200
+ if (f.mode)
201
+ fs_1.default.chmodSync(target, f.mode);
202
+ console.log(green(` ✓ ${target}`));
203
+ }
204
+ fs_1.default.mkdirSync(projectsPath, { recursive: true, mode: 0o700 });
205
+ console.log(green(` ✓ ${projectsPath}/`));
206
+ console.log(bold("\nNext"));
207
+ console.log(` 1. Start it: ${bold("pm2 start ecosystem.config.cjs && pm2 save")}`);
208
+ console.log(` ${dim("once per server, to start pm2 at boot: pm2 startup (run the command it prints)")}`);
209
+ console.log(` 2. Check it: curl -s http://127.0.0.1:${port}${baseEndPoint}liveness`);
210
+ console.log(` 3. nginx (TLS site):\n${nginxSnippet(answers).split("\n").map(l => " " + l).join("\n")}`);
211
+ console.log(` 4. Each project: npx bmfk project-config → put the config into ${projectsPath}`);
212
+ console.log(` and in its deploy.json: "host": "https://<this server's domain>${baseEndPoint}pckg/add", "username": "${users[0].login}"`);
213
+ console.log("");
214
+ }
@@ -0,0 +1,378 @@
1
+ import { Req } from "../../signal/Signal";
2
+ import { BaseService } from "../BaseService";
3
+ import { IConfig, IProjectState } from "./ConfigService";
4
+ import { UploadedFile } from "express-fileupload";
5
+ import { ValidationModel } from "../helper/Validator";
6
+ import { IDeploymentNotifier } from "./Notifier";
7
+ import { IError } from "../structures/Interfaces";
8
+ import { IPendingReview, ReviewStore } from "./ReviewStore";
9
+ import { ISignedAuthVerdict } from "../interceptors/InterceptorSignedAuth";
10
+ declare const _TSetup: {
11
+ readonly users: readonly [{
12
+ readonly login: "";
13
+ readonly password: "";
14
+ readonly $__password_optional: true;
15
+ readonly publicKey: "";
16
+ readonly $__publicKey_optional: true;
17
+ }];
18
+ readonly require_signature: true;
19
+ readonly $__require_signature_optional: true;
20
+ readonly watchdog: true;
21
+ readonly $__watchdog_optional: true;
22
+ readonly notifier: {
23
+ readonly URL: "";
24
+ readonly KEY: "";
25
+ };
26
+ readonly $__notifier_optional: true;
27
+ readonly telegram: {
28
+ readonly bot: "";
29
+ readonly chat: "";
30
+ readonly topic: 0;
31
+ readonly $__topic_optional: true;
32
+ };
33
+ readonly $__telegram_optional: true;
34
+ readonly status_url: "";
35
+ readonly $__status_url_optional: true;
36
+ readonly allowed_ips: readonly [""];
37
+ readonly $__allowed_ips_optional: true;
38
+ readonly reviewers: readonly [{
39
+ readonly login: "";
40
+ readonly password: "";
41
+ readonly email: "";
42
+ }];
43
+ readonly $__reviewers_optional: true;
44
+ readonly review_url: "";
45
+ readonly $__review_url_optional: true;
46
+ readonly secrets_dir: "";
47
+ readonly $__secrets_dir_optional: true;
48
+ };
49
+ export type TDeployerSetup = ValidationModel<typeof _TSetup>;
50
+ export declare const SETUP_MODEL: {
51
+ readonly users: readonly [{
52
+ readonly login: "";
53
+ readonly password: "";
54
+ readonly $__password_optional: true;
55
+ readonly publicKey: "";
56
+ readonly $__publicKey_optional: true;
57
+ }];
58
+ readonly require_signature: true;
59
+ readonly $__require_signature_optional: true;
60
+ readonly watchdog: true;
61
+ readonly $__watchdog_optional: true;
62
+ readonly notifier: {
63
+ readonly URL: "";
64
+ readonly KEY: "";
65
+ };
66
+ readonly $__notifier_optional: true;
67
+ readonly telegram: {
68
+ readonly bot: "";
69
+ readonly chat: "";
70
+ readonly topic: 0;
71
+ readonly $__topic_optional: true;
72
+ };
73
+ readonly $__telegram_optional: true;
74
+ readonly status_url: "";
75
+ readonly $__status_url_optional: true;
76
+ readonly allowed_ips: readonly [""];
77
+ readonly $__allowed_ips_optional: true;
78
+ readonly reviewers: readonly [{
79
+ readonly login: "";
80
+ readonly password: "";
81
+ readonly email: "";
82
+ }];
83
+ readonly $__reviewers_optional: true;
84
+ readonly review_url: "";
85
+ readonly $__review_url_optional: true;
86
+ readonly secrets_dir: "";
87
+ readonly $__secrets_dir_optional: true;
88
+ };
89
+ export interface IDeployerServiceOptions {
90
+ projects_path: string;
91
+ setup_path: string;
92
+ selfPort?: number;
93
+ selfBaseEndPoint?: string;
94
+ }
95
+ export declare const REQ_DEPLOYMENT_PROCEED: Req<{
96
+ auth: string;
97
+ authLogin?: string;
98
+ ip?: string;
99
+ sig?: ISignedAuthVerdict;
100
+ name: string;
101
+ token: string;
102
+ files: {
103
+ file: UploadedFile;
104
+ };
105
+ }, any>;
106
+ export declare const REQ_DEPLOYMENT_SWITCH: Req<{
107
+ auth?: string;
108
+ authLogin?: string;
109
+ ip?: string;
110
+ sig?: ISignedAuthVerdict;
111
+ name: string;
112
+ token: string;
113
+ scheme?: "blue" | "green";
114
+ }, any>;
115
+ export declare const REQ_DEPLOYMENT_STATUS: Req<{
116
+ auth?: string;
117
+ authLogin?: string;
118
+ ip?: string;
119
+ sig?: ISignedAuthVerdict;
120
+ name?: string;
121
+ }, any>;
122
+ export declare const REQ_DEPLOYMENT_SLOT: Req<{
123
+ name: string;
124
+ token: string;
125
+ slot?: "blue" | "green";
126
+ }, any>;
127
+ export declare const REQ_DEPLOYMENT_BACKUPS: Req<{
128
+ auth?: string;
129
+ authLogin?: string;
130
+ ip?: string;
131
+ sig?: ISignedAuthVerdict;
132
+ name: string;
133
+ }, any>;
134
+ export declare const REQ_DEPLOYER_PUBLIC_KEY: Req<string, string | null>;
135
+ export declare const REQ_DEPLOYMENT_RESTORE: Req<{
136
+ auth?: string;
137
+ authLogin?: string;
138
+ ip?: string;
139
+ sig?: ISignedAuthVerdict;
140
+ name: string;
141
+ token: string;
142
+ backup: string;
143
+ }, any>;
144
+ export declare class DeployerService extends BaseService {
145
+ private static MAX_HISTORY;
146
+ private static _trimHistory;
147
+ options: IDeployerServiceOptions;
148
+ setup: TDeployerSetup | null;
149
+ notifier: IDeploymentNotifier | null;
150
+ private telegram;
151
+ busy: Map<string, boolean>;
152
+ reviews: ReviewStore;
153
+ private _setupWatchDebounceTimer;
154
+ private _lastSetupHash;
155
+ constructor(options: IDeployerServiceOptions);
156
+ init(): Promise<void>;
157
+ private _checkReviewSetup;
158
+ private _loadSetup;
159
+ private _reloadSetup;
160
+ private _watchSetup;
161
+ proceed(data: {
162
+ auth?: string;
163
+ authLogin?: string;
164
+ ip?: string;
165
+ sig?: ISignedAuthVerdict;
166
+ name: string;
167
+ token: string;
168
+ files: {
169
+ file: UploadedFile;
170
+ };
171
+ }): Promise<{
172
+ error: {
173
+ code: number;
174
+ message: string;
175
+ httpStatus: number;
176
+ };
177
+ data?: undefined;
178
+ } | {
179
+ data: {
180
+ ok: boolean;
181
+ project: string;
182
+ bluegreen: boolean;
183
+ slot: "blue" | "green" | null;
184
+ active: "blue" | "green" | null;
185
+ activeThisDeploy: boolean;
186
+ };
187
+ error?: undefined;
188
+ } | {
189
+ error?: undefined;
190
+ data: {
191
+ ok: boolean;
192
+ project: string;
193
+ pendingReview: boolean;
194
+ mode: "all" | "any";
195
+ reviewers: string[];
196
+ notNotified: string[];
197
+ expiresAt: number;
198
+ replacedPrevious: boolean;
199
+ };
200
+ }>;
201
+ private _deploy;
202
+ private _reviewSetup;
203
+ private _queueForReview;
204
+ reviewDecide(project: string, sha256: string, reviewer: string, decision: "accept" | "decline", ip: string | null): Promise<{
205
+ pending?: IPendingReview;
206
+ error?: string;
207
+ }>;
208
+ private _deployApproved;
209
+ private _copyArchive;
210
+ switchSlot(data: {
211
+ auth?: string;
212
+ authLogin?: string;
213
+ ip?: string;
214
+ sig?: ISignedAuthVerdict;
215
+ name: string;
216
+ token: string;
217
+ scheme?: "blue" | "green";
218
+ }): Promise<{
219
+ data?: undefined;
220
+ error: {
221
+ code: number;
222
+ message: string;
223
+ httpStatus: number;
224
+ };
225
+ } | {
226
+ error?: undefined;
227
+ data: {
228
+ active: "blue" | "green";
229
+ previousActive: "blue" | "green";
230
+ action: "rollback" | "switch";
231
+ hookError: string | null;
232
+ };
233
+ }>;
234
+ status(data: {
235
+ auth?: string;
236
+ authLogin?: string;
237
+ ip?: string;
238
+ sig?: ISignedAuthVerdict;
239
+ name?: string;
240
+ }): Promise<{
241
+ data?: undefined;
242
+ error: {
243
+ code: number;
244
+ message: string;
245
+ httpStatus: number;
246
+ };
247
+ } | {
248
+ error?: undefined;
249
+ data: Record<string, {
250
+ hasBlueGreen: boolean;
251
+ state: IProjectState | null;
252
+ readyToSwitch: boolean;
253
+ }>;
254
+ }>;
255
+ private static _isBlueGreen;
256
+ private static _backupRoot;
257
+ listBackups(data: {
258
+ auth?: string;
259
+ authLogin?: string;
260
+ ip?: string;
261
+ sig?: ISignedAuthVerdict;
262
+ name: string;
263
+ }): Promise<{
264
+ data?: undefined;
265
+ error: {
266
+ code: number;
267
+ message: string;
268
+ httpStatus: number;
269
+ };
270
+ } | {
271
+ error?: undefined;
272
+ data: {
273
+ project: string;
274
+ bluegreen: boolean;
275
+ activeSlot: string | null;
276
+ backupEnabled: boolean;
277
+ keep: number;
278
+ backups: import("./BackupManager").IBackupInfo[];
279
+ };
280
+ }>;
281
+ restoreBackup(data: {
282
+ auth?: string;
283
+ authLogin?: string;
284
+ ip?: string;
285
+ sig?: ISignedAuthVerdict;
286
+ name: string;
287
+ token: string;
288
+ backup: string;
289
+ }): Promise<{
290
+ data?: undefined;
291
+ error: {
292
+ details?: undefined;
293
+ code: number;
294
+ message: string;
295
+ httpStatus: number;
296
+ };
297
+ } | {
298
+ data?: undefined;
299
+ error: {
300
+ code: number;
301
+ message: string;
302
+ details: string;
303
+ httpStatus: number;
304
+ };
305
+ } | {
306
+ error?: undefined;
307
+ data: {
308
+ project: string;
309
+ restored: string;
310
+ appVersion: string | null;
311
+ slot: import("./BackupManager").TBackupSlot;
312
+ activeSlot: "blue" | "green" | null;
313
+ live: boolean;
314
+ preRestoreBackup: string | null;
315
+ pm2Restarted: boolean;
316
+ pm2Error: string | null;
317
+ };
318
+ }>;
319
+ slotState(data: {
320
+ name: string;
321
+ token: string;
322
+ slot?: "blue" | "green";
323
+ }): Promise<{
324
+ error: {
325
+ code: number;
326
+ message: string;
327
+ httpStatus: number;
328
+ };
329
+ } | {
330
+ data: {
331
+ project: string;
332
+ active: "blue" | "green";
333
+ lastDeployed: "blue" | "green";
334
+ readyToSwitch: boolean;
335
+ slot: "blue" | "green" | null;
336
+ isActive: boolean | null;
337
+ checkedAt: number;
338
+ };
339
+ }>;
340
+ private _statusUrl;
341
+ private _writeBlueGreenFiles;
342
+ private _projectByToken;
343
+ tokensMatch(a: string | undefined, b: string | undefined): boolean;
344
+ static buildAllowList(entries: readonly string[] | undefined | null): {
345
+ list: import("node:net").BlockList | null;
346
+ error?: string;
347
+ };
348
+ isIpAllowed(ip: string | undefined): boolean;
349
+ private _ipAllowed;
350
+ private _warnPlaintextUsers;
351
+ private _checkUserAuth;
352
+ private static _extractPort;
353
+ private static _mainPath;
354
+ private static _withSourceMaps;
355
+ private _renderNginx;
356
+ private static _pm2AttributesFor;
357
+ runPM2(found: IConfig, projectState?: IProjectState | null): Promise<IError | null>;
358
+ private _verifyAutorestart;
359
+ private static readonly SKIP_DIRS;
360
+ private static readonly TEMPLATE_EXTENSIONS;
361
+ applyConfig(dir: string, config: Record<string, string>, ctx?: {
362
+ secretsFile: string | null;
363
+ onDisk: string[];
364
+ }): Promise<void>;
365
+ processFile(filePath: string, config: Record<string, string>, ctx?: {
366
+ secretsFile: string | null;
367
+ onDisk: string[];
368
+ }): Promise<void>;
369
+ private _destinationProblem;
370
+ private static _unsafeArchiveEntry;
371
+ private static _escapingSymlink;
372
+ private _runMigrate;
373
+ static MIGRATE_TIMEOUT_MS: number;
374
+ static _stampProjectName(dir: string, projectName: string): void;
375
+ unpack(destination: string, uploadedFile: string, install?: boolean, ignoreDirectoryClean?: boolean, omitDev?: boolean, projectName?: string): Promise<IError | null>;
376
+ upload(file: UploadedFile, uploadPath: string): Promise<IError | null>;
377
+ }
378
+ export {};