@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,148 @@
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.ProjectConfigWizard = ProjectConfigWizard;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const process_1 = require("process");
11
+ const PasswordHash_1 = require("../helper/PasswordHash");
12
+ const Validator_1 = require("../helper/Validator");
13
+ const ConfigService_1 = require("./ConfigService");
14
+ const HashPassword_1 = require("./HashPassword");
15
+ const cliCommon_1 = require("./cliCommon");
16
+ const cliPrompt_1 = require("./cliPrompt");
17
+ async function ProjectConfigWizard() {
18
+ const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
19
+ if (!process_1.stdin.isTTY) {
20
+ console.error(red("✗ project-config needs an interactive terminal — it asks for secrets."));
21
+ process.exit(1);
22
+ }
23
+ const section = (title) => console.log("\n" + bold(title));
24
+ console.log(bold("\nNew project config for the deployer") + dim(" (Enter keeps the value in brackets)"));
25
+ section("Project");
26
+ const name = await (0, cliPrompt_1.askValid)("Name (e.g. api.gateway.example.com)", "", v => (0, ConfigService_1.projectNameProblem)(v));
27
+ const description = await (0, cliPrompt_1.ask)("Description", "");
28
+ const destination = await (0, cliPrompt_1.askValid)("Destination folder on the server", `/var/node/${name}`, v => !path_1.default.isAbsolute(v) ? "must be an absolute path" : /^\/(var|etc|home|usr|opt|srv|tmp|root)?\/?$/.test(v) ? "pick a folder of its own, not a system folder" : null);
29
+ section("Project token");
30
+ let plainToken = null;
31
+ let tokenHash;
32
+ if (await (0, cliPrompt_1.yes)("Generate a new random token?", true)) {
33
+ plainToken = crypto_1.default.randomBytes(32).toString("hex");
34
+ tokenHash = await PasswordHash_1.PasswordHash.hash(plainToken);
35
+ }
36
+ else {
37
+ const existing = (await (0, HashPassword_1.askHidden)("Existing token (hidden): ")).trim();
38
+ if (!existing) {
39
+ console.error(red("✗ A token is required."));
40
+ process.exit(1);
41
+ }
42
+ if (existing.length < 32)
43
+ console.log(yellow(` ⚠ Short token (${existing.length} chars) — a generated one is safer.`));
44
+ tokenHash = await PasswordHash_1.PasswordHash.hash(existing);
45
+ }
46
+ section("Deploy steps");
47
+ const unpack = await (0, cliPrompt_1.yes)("Unpack the uploaded archive", true);
48
+ const install = unpack ? await (0, cliPrompt_1.yes)("Install dependencies (npm ci)", true) : false;
49
+ const omitDev = install ? await (0, cliPrompt_1.yes)("Skip devDependencies on the server (npm ci --omit=dev)", false) : false;
50
+ const ignoreDirectoryClean = unpack ? !(await (0, cliPrompt_1.yes)("Clean the destination before unpacking", true)) : false;
51
+ const backup = await (0, cliPrompt_1.yes)("Back up the current version before each deploy", true);
52
+ const migrate = await (0, cliPrompt_1.yes)("Run `npm run migrate` before starting", false);
53
+ const pm2 = await (0, cliPrompt_1.yes)("Run the app with pm2", true);
54
+ const pm2Attributes = pm2 ? (0, cliPrompt_1.tokens)(await (0, cliPrompt_1.ask)(`pm2 flags (quote values with spaces: --cron-restart "10 0 * * *")`, "")) : [];
55
+ const chmodRaw = await (0, cliPrompt_1.askValid)("chmod for deployed files (empty = leave as unpacked)", "", v => !v || /^[0-7]{3,4}$/.test(v) ? null : "octal like 750");
56
+ const chmod = chmodRaw ? Number(chmodRaw) : 0;
57
+ if (chmodRaw && Number(chmodRaw.slice(-1)) & 4)
58
+ console.log(yellow(` ⚠ ${chmodRaw} lets every user on the server read the files.`));
59
+ section("Notifications");
60
+ const email = (0, cliPrompt_1.list)(await (0, cliPrompt_1.ask)("Emails, comma-separated", ""));
61
+ const phone = (0, cliPrompt_1.list)(await (0, cliPrompt_1.ask)("Phones for SMS, comma-separated", ""));
62
+ const liveness = await (0, cliPrompt_1.askValid)("Liveness URL checked after deploy (empty = none)", "", v => !v || /^https?:\/\/\S+$/.test(v) ? null : "must be an http(s) URL");
63
+ section("Config values — replace _{{key}}_ in the shipped files");
64
+ console.log(dim(" Values are typed hidden. Empty key finishes."));
65
+ const config = {};
66
+ for (;;) {
67
+ const key = await (0, cliPrompt_1.askValid)(" key", "", v => !v || /^[A-Za-z0-9_]+$/.test(v) ? (v && v in config ? `"${v}" is already set` : null) : "letters, digits and '_' only");
68
+ if (!key)
69
+ break;
70
+ config[key] = await (0, HashPassword_1.askHidden)(` value of ${key} (hidden): `);
71
+ }
72
+ const cfg = {
73
+ name, destination, description, token: tokenHash,
74
+ unpack, ignoreDirectoryClean, backup, install, migrate, pm2,
75
+ ...(omitDev ? { omitDev } : {}),
76
+ ...(pm2Attributes.length ? { pm2_attributes: pm2Attributes } : {}),
77
+ ...(chmod ? { chmod } : {}),
78
+ ...(email.length ? { email } : {}),
79
+ ...(phone.length ? { phone } : {}),
80
+ ...(liveness ? { liveness } : {}),
81
+ config,
82
+ };
83
+ section("Blue-green");
84
+ if (await (0, cliPrompt_1.yes)("Deploy as two slots (blue/green) with zero-downtime switching?", false)) {
85
+ const bluePort = await (0, cliPrompt_1.askValid)(" blue slot port", "", v => /^\d{2,5}$/.test(v) ? null : "a port number");
86
+ const greenPort = await (0, cliPrompt_1.askValid)(" green slot port", "", v => !/^\d{2,5}$/.test(v) ? "a port number" : v === bluePort ? "must differ from the blue port" : null);
87
+ const onSwitch = (0, cliPrompt_1.tokens)(await (0, cliPrompt_1.ask)(" command after each switch", "/usr/sbin/nginx -s reload"));
88
+ if (onSwitch.length && !path_1.default.isAbsolute(onSwitch[0]))
89
+ console.log(yellow(" ⚠ Use an absolute path to the binary — the deployer runs it without a shell."));
90
+ cfg.bluegreen = { blue_config: { port: bluePort }, green_config: { port: greenPort }, ...(onSwitch.length ? { on_switch: onSwitch } : {}) };
91
+ }
92
+ section("nginx");
93
+ if (await (0, cliPrompt_1.yes)("Let the deployer manage the nginx config of this project?", !!cfg.bluegreen)) {
94
+ const config_dir = await (0, cliPrompt_1.askValid)(" nginx config folder (nginx includes <folder>/*.conf)", "/etc/nginx/node-projects", v => path_1.default.isAbsolute(v) ? null : "must be an absolute path");
95
+ const domain = await (0, cliPrompt_1.ask)(" domain", "");
96
+ cfg.nginx = { config_dir, ...(domain ? { domain } : {}) };
97
+ }
98
+ section("Secrets file — keeps config values out of the deployed code");
99
+ if (Object.keys(config).length && await (0, cliPrompt_1.yes)("Store config values in a secrets file outside the deploy folder?", true)) {
100
+ const where = await (0, cliPrompt_1.ask)(" folder (empty = secrets_dir from the deployer's setup.json, else /var/bmfk/<project>)", "");
101
+ if (where && (!path_1.default.isAbsolute(where) || path_1.default.resolve(where).startsWith(path_1.default.resolve(destination) + path_1.default.sep)))
102
+ console.log(yellow(" ⚠ The folder must be absolute and outside the deploy folder — the deployer will refuse this project as is."));
103
+ cfg.secrets = where ? { dir: where } : {};
104
+ if (pm2Attributes.some(a => /^--(uid|gid|user)(=|$)/.test(a)))
105
+ console.log(yellow(" ⚠ The pm2 flags switch the user — the app couldn't read the secrets file; the deployer will refuse this project."));
106
+ }
107
+ section("Review — deploys wait for approval");
108
+ if (await (0, cliPrompt_1.yes)("Require reviewers to approve each deploy?", false)) {
109
+ const reviewers = (0, cliPrompt_1.list)(await (0, cliPrompt_1.askValid)(" reviewer logins from the deployer's setup.json, comma-separated", "", v => (0, cliPrompt_1.list)(v).length ? null : "at least one login"));
110
+ const mode = (await (0, cliPrompt_1.askValid)(" approval: any (one accept) / all (everyone)", "any", v => v === "any" || v === "all" ? null : "any or all"));
111
+ const ttlHours = Number(await (0, cliPrompt_1.askValid)(" hours to decide", "24", v => /^\d+$/.test(v) && +v >= 1 && +v <= 168 ? null : "1–168"));
112
+ cfg.review = { reviewers, mode, ttlHours };
113
+ }
114
+ const errors = await Validator_1.Validator.validateStructure(ConfigService_1.PROJECT_CONFIG_MODEL, cfg);
115
+ if (errors && errors.length) {
116
+ console.error(red("\n✗ The config doesn't pass the deployer's validation:"));
117
+ for (const e of errors)
118
+ console.error(" " + e);
119
+ process.exit(1);
120
+ }
121
+ section("Deploy client (deploy.json for the project)");
122
+ const host = await (0, cliPrompt_1.ask)(" deployer upload URL", "https://deployer.example.com/api/pckg/add");
123
+ const username = await (0, cliPrompt_1.ask)(" deployer user login", "");
124
+ const projectJson = JSON.stringify(cfg, null, 4);
125
+ const deployJson = JSON.stringify({ name, host, token: plainToken ?? "<the existing token>", username, password: "<your deployer password>" }, null, 4);
126
+ console.log("");
127
+ const save = async (what, content, def) => {
128
+ const target = await (0, cliPrompt_1.ask)(`Save ${what} to (empty = print here)`, def);
129
+ if (!target) {
130
+ console.log("\n" + content + "\n");
131
+ return;
132
+ }
133
+ if (fs_1.default.existsSync(target) && !(await (0, cliPrompt_1.yes)(` ${target} exists — overwrite?`, false))) {
134
+ console.log("\n" + content + "\n");
135
+ return;
136
+ }
137
+ fs_1.default.mkdirSync(path_1.default.dirname(path_1.default.resolve(target)), { recursive: true });
138
+ fs_1.default.writeFileSync(target, content + "\n", { encoding: "utf-8", mode: 0o600 });
139
+ console.log(green(` ✓ ${path_1.default.resolve(target)}`) + dim(" (0600)"));
140
+ };
141
+ await save("the project config for the deployer", projectJson, `${name}.json`);
142
+ console.log(dim(` → copy it to <projects_path>/${name}.json on the deployer; it is picked up without a restart.`));
143
+ await save("deploy.json for the project", deployJson, "");
144
+ if (plainToken)
145
+ console.log(yellow(" The token is shown only here and in deploy.json — the deployer keeps its hash. Keep deploy.json out of git."));
146
+ if (cfg.review)
147
+ console.log(dim(" Reviewers must exist in the deployer's setup.json; it says at startup if anything is missing."));
148
+ }
@@ -0,0 +1,2 @@
1
+ import { IDeployerConfig } from "./resolveConfig";
2
+ export declare function Restore(opt?: IDeployerConfig | string | null, backupName?: string, assumeYes?: boolean): Promise<void>;
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Restore = Restore;
4
+ const promises_1 = require("readline/promises");
5
+ const process_1 = require("process");
6
+ const Http_1 = require("../http/Http");
7
+ const resolveConfig_1 = require("./resolveConfig");
8
+ const cliCommon_1 = require("./cliCommon");
9
+ async function Restore(opt, backupName, assumeYes = false) {
10
+ opt = await (0, resolveConfig_1.resolveConfig)(opt);
11
+ const { red, yellow, green, dim, bold } = (0, cliCommon_1.palette)();
12
+ const fail = (msg) => { console.error(red(bold("✗ ")) + msg); process.exit(1); };
13
+ const listUrl = (0, cliCommon_1.deployerUrl)(opt, "backups"), listBody = { name: opt.name };
14
+ const lr = await Http_1.Http.post(listUrl, listBody, { headers: (0, cliCommon_1.deployerHeaders)(opt, listUrl, listBody), timeoutMs: 30000, retry: { enabled: false } });
15
+ const lerr = (0, cliCommon_1.responseError)(lr);
16
+ if (lerr)
17
+ fail("Cannot list backups: " + lerr);
18
+ const info = lr.data?.data ?? {};
19
+ const list = info.backups ?? [];
20
+ if (list.length === 0)
21
+ fail(`No backups for "${opt.name}".`);
22
+ const rl = process_1.stdin.isTTY ? (0, promises_1.createInterface)({ input: process_1.stdin, output: process_1.stdout }) : null;
23
+ let chosen;
24
+ try {
25
+ if (backupName) {
26
+ chosen = list.find(b => b.name === backupName);
27
+ if (!chosen)
28
+ fail(`Backup "${backupName}" not found. Run \`bmfk backups\` to see the list.`);
29
+ }
30
+ else {
31
+ if (!rl)
32
+ fail("Backup name is required when not running in a terminal: bmfk restore <backup-name> --yes");
33
+ console.log("");
34
+ list.forEach((b, i) => console.log(` [${i + 1}] ${b.name} ${dim("ver")} ${b.appVersion ?? "?"} ${dim((0, cliCommon_1.fmtDate)(b.createdAt))}`));
35
+ while (!chosen) {
36
+ const a = await rl.question(`\nRestore which backup [1-${list.length}]: `);
37
+ const i = parseInt(a.trim(), 10) - 1;
38
+ if (i >= 0 && i < list.length)
39
+ chosen = list[i];
40
+ else
41
+ console.error(`Enter a number from 1 to ${list.length}.`);
42
+ }
43
+ }
44
+ const live = !info.bluegreen || chosen.slot === info.activeSlot;
45
+ console.log("");
46
+ console.log(`${bold("Restore")} ${bold(opt.name)} ${dim("←")} ${chosen.name} ${dim("(ver " + (chosen.appVersion ?? "?") + ")")}`);
47
+ if (info.bluegreen)
48
+ console.log(` ${dim("slot:")} ${chosen.slot} ${dim("active:")} ${info.activeSlot ?? "?"}`);
49
+ console.log(live
50
+ ? yellow(bold(" ⚠ LIVE: production traffic gets the restored code immediately"))
51
+ : dim(` not live — the slot will need: bmfk activate ${chosen.slot}`));
52
+ console.log(dim(" current contents are backed up first, so this can be undone"));
53
+ if (!assumeYes) {
54
+ if (!rl)
55
+ fail("Refusing to restore non-interactively without --yes.");
56
+ const a = await rl.question("\nProceed? [y/N] ");
57
+ if (!/^y(es)?$/i.test(a.trim())) {
58
+ console.log("Cancelled.");
59
+ return;
60
+ }
61
+ }
62
+ }
63
+ finally {
64
+ rl?.close();
65
+ }
66
+ console.log(dim("\nRestoring…"));
67
+ const restoreUrl = (0, cliCommon_1.deployerUrl)(opt, "restore"), restoreBody = { name: opt.name, token: opt.token, backup: chosen.name };
68
+ const rr = await Http_1.Http.post(restoreUrl, restoreBody, { headers: (0, cliCommon_1.deployerHeaders)(opt, restoreUrl, restoreBody), timeoutMs: 10 * 60 * 1000, retry: { enabled: false } });
69
+ const rerr = (0, cliCommon_1.responseError)(rr);
70
+ if (rerr)
71
+ fail("Restore failed: " + rerr);
72
+ const d = rr.data?.data ?? {};
73
+ const line = dim("─".repeat(60));
74
+ console.log("");
75
+ console.log(d.pm2Error ? yellow(bold("⚠ RESTORED, BUT pm2 RESTART FAILED")) : green(bold("✓ RESTORED")));
76
+ console.log(line);
77
+ console.log(` ${dim("project: ")} ${d.project}`);
78
+ console.log(` ${dim("backup: ")} ${d.restored} ${dim("(ver " + (d.appVersion ?? "?") + ")")}`);
79
+ if (d.slot)
80
+ console.log(` ${dim("slot: ")} ${d.slot} ${dim("active:")} ${d.activeSlot ?? "?"}`);
81
+ console.log(` ${dim("live: ")} ${d.live ? bold("yes") : "no"}`);
82
+ console.log(` ${dim("pm2: ")} ${d.pm2Error ? yellow(d.pm2Error) : d.pm2Restarted ? "restarted" : "not used"}`);
83
+ if (d.preRestoreBackup)
84
+ console.log(` ${dim("undo with: ")} bmfk restore ${d.preRestoreBackup}`);
85
+ if (!d.live && d.slot)
86
+ console.log(` ${dim("next: ")} bmfk activate ${d.slot}`);
87
+ console.log(line);
88
+ console.log("");
89
+ }
@@ -0,0 +1,62 @@
1
+ import { UploadedFile } from "express-fileupload";
2
+ export interface IReviewDecision {
3
+ tokenHash: string;
4
+ decision: "accept" | "decline" | null;
5
+ at: number | null;
6
+ ip: string | null;
7
+ }
8
+ export type TReviewState = "pending" | "deploying" | "deployed" | "failed" | "declined" | "expired";
9
+ export interface IPendingReview {
10
+ project: string;
11
+ state: TReviewState;
12
+ result?: {
13
+ at: number;
14
+ message: string;
15
+ slot?: string | null;
16
+ activeThisDeploy?: boolean;
17
+ };
18
+ sha256: string;
19
+ size: number;
20
+ uploadedBy: string;
21
+ uploadedFrom: string | null;
22
+ uploadedAt: number;
23
+ expiresAt: number;
24
+ mode: "any" | "all";
25
+ reviewers: Record<string, IReviewDecision>;
26
+ }
27
+ export declare class ReviewStore {
28
+ readonly dir: string;
29
+ constructor(projectsPath: string);
30
+ static hashToken(token: string): string;
31
+ private file;
32
+ archivePath(project: string): string;
33
+ lastArchivePath(project: string): string;
34
+ private ensureDir;
35
+ private static sha256File;
36
+ private writeJson;
37
+ create(project: string, file: UploadedFile, meta: {
38
+ uploadedBy: string;
39
+ uploadedFrom: string | null;
40
+ mode: "any" | "all";
41
+ reviewers: string[];
42
+ ttlMs: number;
43
+ }): Promise<{
44
+ pending: IPendingReview;
45
+ tokens: Record<string, string>;
46
+ replaced: boolean;
47
+ }>;
48
+ get(project: string): IPendingReview | null;
49
+ save(pending: IPendingReview): void;
50
+ findByToken(token: string): {
51
+ pending: IPendingReview;
52
+ reviewer: string;
53
+ } | null;
54
+ archiveIntact(pending: IPendingReview): Promise<boolean>;
55
+ journal(project: string, event: string, details: Record<string, unknown>): void;
56
+ dropArchive(project: string): void;
57
+ sweep(): string[];
58
+ remove(project: string): void;
59
+ stageBaseline(project: string, archive: string): void;
60
+ commitBaseline(project: string): void;
61
+ dropStagedBaseline(project: string): void;
62
+ }
@@ -0,0 +1,186 @@
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.ReviewStore = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const NAME_RE = /^[A-Za-z0-9._-]+$/;
11
+ class ReviewStore {
12
+ dir;
13
+ constructor(projectsPath) {
14
+ this.dir = path_1.default.resolve(projectsPath, ".review");
15
+ }
16
+ static hashToken(token) {
17
+ return crypto_1.default.createHash("sha256").update(String(token)).digest("hex");
18
+ }
19
+ file(project, kind) {
20
+ if (!NAME_RE.test(project))
21
+ throw new Error("invalid project name");
22
+ return path_1.default.join(this.dir, `${project}.${kind}`);
23
+ }
24
+ archivePath(project) { return this.file(project, "pending.tgz"); }
25
+ lastArchivePath(project) { return this.file(project, "last.tgz"); }
26
+ ensureDir() {
27
+ fs_1.default.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
28
+ }
29
+ static sha256File(file) {
30
+ return new Promise((resolve, reject) => {
31
+ const h = crypto_1.default.createHash("sha256");
32
+ fs_1.default.createReadStream(file).on("data", d => h.update(d)).on("error", reject).on("end", () => resolve(h.digest("hex")));
33
+ });
34
+ }
35
+ writeJson(file, value) {
36
+ const tmp = file + ".tmp";
37
+ fs_1.default.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: "utf-8", mode: 0o600 });
38
+ fs_1.default.renameSync(tmp, file);
39
+ }
40
+ async create(project, file, meta) {
41
+ this.ensureDir();
42
+ const replaced = this.get(project) !== null;
43
+ this.remove(project);
44
+ const archive = this.archivePath(project);
45
+ await new Promise((resolve, reject) => file.mv(archive, (err) => err ? reject(err) : resolve()));
46
+ fs_1.default.chmodSync(archive, 0o600);
47
+ const tokens = {};
48
+ const reviewers = {};
49
+ for (const login of meta.reviewers) {
50
+ const token = crypto_1.default.randomBytes(32).toString("base64url");
51
+ tokens[login] = token;
52
+ reviewers[login] = { tokenHash: ReviewStore.hashToken(token), decision: null, at: null, ip: null };
53
+ }
54
+ const now = Date.now();
55
+ const pending = {
56
+ project,
57
+ state: "pending",
58
+ sha256: await ReviewStore.sha256File(archive),
59
+ size: fs_1.default.statSync(archive).size,
60
+ uploadedBy: meta.uploadedBy,
61
+ uploadedFrom: meta.uploadedFrom,
62
+ uploadedAt: now,
63
+ expiresAt: now + meta.ttlMs,
64
+ mode: meta.mode,
65
+ reviewers,
66
+ };
67
+ this.writeJson(this.file(project, "pending.json"), pending);
68
+ return { pending, tokens, replaced };
69
+ }
70
+ get(project) {
71
+ try {
72
+ const p = JSON.parse(fs_1.default.readFileSync(this.file(project, "pending.json"), "utf-8"));
73
+ return p && typeof p === "object" && p.project === project ? p : null;
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ }
79
+ save(pending) {
80
+ this.writeJson(this.file(pending.project, "pending.json"), pending);
81
+ }
82
+ findByToken(token) {
83
+ if (typeof token !== "string" || token.length < 20 || token.length > 200)
84
+ return null;
85
+ const hash = Buffer.from(ReviewStore.hashToken(token), "hex");
86
+ let entries;
87
+ try {
88
+ entries = fs_1.default.readdirSync(this.dir);
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ for (const f of entries) {
94
+ if (!f.endsWith(".pending.json"))
95
+ continue;
96
+ const pending = this.get(f.slice(0, -".pending.json".length));
97
+ if (!pending || pending.expiresAt < Date.now())
98
+ continue;
99
+ for (const [login, r] of Object.entries(pending.reviewers)) {
100
+ const stored = Buffer.from(String(r.tokenHash), "hex");
101
+ if (stored.length === hash.length && crypto_1.default.timingSafeEqual(stored, hash))
102
+ return { pending, reviewer: login };
103
+ }
104
+ }
105
+ return null;
106
+ }
107
+ async archiveIntact(pending) {
108
+ try {
109
+ return (await ReviewStore.sha256File(this.archivePath(pending.project))) === pending.sha256;
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ journal(project, event, details) {
116
+ try {
117
+ this.ensureDir();
118
+ const file = path_1.default.join(this.dir, `${project}.history.jsonl`);
119
+ if (!NAME_RE.test(project))
120
+ return;
121
+ try {
122
+ if (fs_1.default.statSync(file).size > 1024 * 1024)
123
+ fs_1.default.renameSync(file, file + ".1");
124
+ }
125
+ catch { }
126
+ fs_1.default.appendFileSync(file, JSON.stringify({ at: new Date().toISOString(), event, ...details }) + "\n", { encoding: "utf-8", mode: 0o600 });
127
+ }
128
+ catch { }
129
+ }
130
+ dropArchive(project) {
131
+ try {
132
+ fs_1.default.rmSync(this.archivePath(project), { force: true });
133
+ }
134
+ catch { }
135
+ }
136
+ sweep() {
137
+ const expired = [];
138
+ let entries;
139
+ try {
140
+ entries = fs_1.default.readdirSync(this.dir);
141
+ }
142
+ catch {
143
+ return expired;
144
+ }
145
+ for (const f of entries) {
146
+ if (!f.endsWith(".pending.json"))
147
+ continue;
148
+ const pending = this.get(f.slice(0, -".pending.json".length));
149
+ if (!pending || pending.state !== "pending" || pending.expiresAt >= Date.now())
150
+ continue;
151
+ pending.state = "expired";
152
+ pending.result = { at: Date.now(), message: "Nobody decided in time — upload again to restart the review." };
153
+ this.save(pending);
154
+ this.dropArchive(pending.project);
155
+ this.journal(pending.project, "expired", { sha256: pending.sha256 });
156
+ expired.push(pending.project);
157
+ }
158
+ return expired;
159
+ }
160
+ remove(project) {
161
+ for (const kind of ["pending.json", "pending.tgz"])
162
+ try {
163
+ fs_1.default.rmSync(this.file(project, kind), { force: true });
164
+ }
165
+ catch { }
166
+ }
167
+ stageBaseline(project, archive) {
168
+ this.ensureDir();
169
+ const incoming = this.file(project, "incoming.tgz");
170
+ fs_1.default.copyFileSync(archive, incoming);
171
+ fs_1.default.chmodSync(incoming, 0o600);
172
+ }
173
+ commitBaseline(project) {
174
+ try {
175
+ fs_1.default.renameSync(this.file(project, "incoming.tgz"), this.lastArchivePath(project));
176
+ }
177
+ catch { }
178
+ }
179
+ dropStagedBaseline(project) {
180
+ try {
181
+ fs_1.default.rmSync(this.file(project, "incoming.tgz"), { force: true });
182
+ }
183
+ catch { }
184
+ }
185
+ }
186
+ exports.ReviewStore = ReviewStore;
@@ -0,0 +1,21 @@
1
+ export interface ISecretsSettings {
2
+ dir?: string;
3
+ file?: string;
4
+ }
5
+ export declare class SecretsInjector {
6
+ static resolvePath(project: string, slot: string | null, settings: ISecretsSettings | undefined, defaultDir: string | undefined, destinationRoot: string): {
7
+ path?: string;
8
+ error?: string;
9
+ };
10
+ static write(file: string, values: Record<string, unknown>): void;
11
+ static verify(file: string, values: Record<string, unknown>): string | null;
12
+ static expression(file: string, key: string): string;
13
+ static transform(source: string, keys: Set<string>, file: string): {
14
+ content: string;
15
+ rewritten: number;
16
+ leftover: boolean;
17
+ };
18
+ private static endsInBlockComment;
19
+ private static rewriteLiteral;
20
+ static parses(source: string): boolean;
21
+ }