@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,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Wizards = Wizards;
4
+ const process_1 = require("process");
5
+ const cliCommon_1 = require("./cliCommon");
6
+ const cliPrompt_1 = require("./cliPrompt");
7
+ const HashPassword_1 = require("./HashPassword");
8
+ const ProjectConfigWizard_1 = require("./ProjectConfigWizard");
9
+ const AccessConfigWizard_1 = require("./AccessConfigWizard");
10
+ const SetupConfigWizard_1 = require("./SetupConfigWizard");
11
+ const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
12
+ const DeployKeyWizard_1 = require("./DeployKeyWizard");
13
+ const DeployerInit_1 = require("./DeployerInit");
14
+ const WIZARDS = [
15
+ { command: "bmfk deployer-init [folder]", title: "New deployer on this server",
16
+ what: "Checks Node, pm2 and /var/bmfk, asks for port, folders, the first deploy users' public keys, allowed addresses and Telegram, then writes the service, its pm2 file and setup.json, and prints the nginx block and the next steps.",
17
+ where: "on the server, in an empty folder with @bmfk/api installed",
18
+ run: () => (0, DeployerInit_1.DeployerInit)([]) },
19
+ { command: "bmfk project-config", title: "New project config for the deployer",
20
+ what: "Asks for everything a project needs (folder, token, deploy steps, config values, blue-green, nginx, secrets file, review) and writes the deployer's project config plus a matching deploy.json.",
21
+ where: "anywhere; copy the config to the deployer's projects folder",
22
+ run: () => (0, ProjectConfigWizard_1.ProjectConfigWizard)() },
23
+ { command: "bmfk setup-config [file|folder]", title: "Deployer users, reviewers and allowed IPs",
24
+ what: "Edits the deployer's setup.json from a menu: add, rename or remove deployer users, change passwords or set their public signing keys, require signed requests, manage reviewers, allowed addresses and the review page URL.",
25
+ where: "on the deployer server",
26
+ run: () => (0, SetupConfigWizard_1.SetupConfigWizard)() },
27
+ { command: "bmfk deploy-key [deploy.json]", title: "Signing key for deploys",
28
+ what: "Generates an Ed25519 key pair: writes the private key into deploy.json (instead of the password) and prints the public key for the deployer's setup.json. Signed requests can't be replayed or altered.",
29
+ where: "in the project folder you deploy from",
30
+ run: () => (0, DeployKeyWizard_1.DeployKeyWizard)() },
31
+ { command: "bmfk access-config [file]", title: "Monitor and documentation access",
32
+ what: "Creates or edits an app's access.json: monitor users with roles and passwords, documentation users, the monitor's allowed addresses. Finds the file named in the project's code.",
33
+ where: "on the app server, or in the project folder",
34
+ run: () => (0, AccessConfigWizard_1.AccessConfigWizard)() },
35
+ { command: "bmfk migrate-configs [folder] [--yes]", title: "Upgrade old configs to hashed secrets",
36
+ what: "Hashes the plain passwords and tokens in old setup.json, project configs and access.json files, computing each hash from the value already there; clients keep their deploy.json.",
37
+ where: "on the servers, right after upgrading to 6.x",
38
+ run: () => (0, MigrateConfigsWizard_1.MigrateConfigsWizard)() },
39
+ { command: "bmfk project-token", title: "New project token",
40
+ what: "Generates a random project token: the token itself for deploy.json and its hash for the project config.",
41
+ where: "anywhere",
42
+ run: () => (0, HashPassword_1.ProjectToken)("generate") },
43
+ { command: "bmfk project-token --hash", title: "Hash an existing project token",
44
+ what: "Asks for a token you already use and prints its hash for the project config.",
45
+ where: "anywhere",
46
+ run: () => (0, HashPassword_1.ProjectToken)("hash") },
47
+ { command: "bmfk hash-password", title: "Hash a monitor password",
48
+ what: "Prints a monitor user entry with a hashed password, to paste into access.json or the access option.",
49
+ where: "anywhere",
50
+ run: () => (0, HashPassword_1.HashPassword)("monitor") },
51
+ { command: "bmfk hash-password --deployer", title: "Hash a deployer password",
52
+ what: "Prints a deployer user entry with a hashed password, to paste into setup.json.",
53
+ where: "anywhere",
54
+ run: () => (0, HashPassword_1.HashPassword)("deployer") },
55
+ ];
56
+ async function Wizards() {
57
+ const { red, dim, bold, green } = (0, cliCommon_1.palette)();
58
+ if (!process_1.stdin.isTTY) {
59
+ console.error(red("✗ wizards is interactive — run it in a terminal. To script, call a command directly (see `bmfk` for the list)."));
60
+ process.exit(1);
61
+ }
62
+ for (;;) {
63
+ console.log(bold("\nbmfk wizards\n"));
64
+ WIZARDS.forEach((w, i) => {
65
+ console.log(` ${bold(String(i + 1).padStart(2) + ")")} ${bold(w.title)}`);
66
+ console.log(` ${w.what}`);
67
+ console.log(dim(` where: ${w.where} · directly: npx ${w.command}`));
68
+ });
69
+ console.log(`\n ${bold("q)")} quit`);
70
+ const choice = (await (0, cliPrompt_1.ask)("\nChoose", "")).toLowerCase();
71
+ if (choice === "q" || choice === "")
72
+ return;
73
+ const w = WIZARDS[Number(choice) - 1];
74
+ if (!/^\d+$/.test(choice) || !w) {
75
+ console.log(red(" ✗ choose a number or q"));
76
+ continue;
77
+ }
78
+ console.log(green(`\n→ ${w.title}`) + dim(` (next time: npx ${w.command})`));
79
+ await w.run();
80
+ if (!(await (0, cliPrompt_1.yes)("\nBack to the list of wizards?", false)))
81
+ return;
82
+ }
83
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const Deploy_1 = require("./Deploy");
5
+ const Activate_1 = require("./Activate");
6
+ const Status_1 = require("./Status");
7
+ const Backups_1 = require("./Backups");
8
+ const Restore_1 = require("./Restore");
9
+ const BackupManager_1 = require("./BackupManager");
10
+ const HashPassword_1 = require("./HashPassword");
11
+ const ProjectConfigWizard_1 = require("./ProjectConfigWizard");
12
+ const AccessConfigWizard_1 = require("./AccessConfigWizard");
13
+ const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
14
+ const SetupConfigWizard_1 = require("./SetupConfigWizard");
15
+ const Wizards_1 = require("./Wizards");
16
+ const DeployKeyWizard_1 = require("./DeployKeyWizard");
17
+ const MigrateProject_1 = require("./MigrateProject");
18
+ const DeployerInit_1 = require("./DeployerInit");
19
+ function usage() {
20
+ console.error("Usage:");
21
+ console.error(" bmfk wizards — list every interactive wizard and run one");
22
+ console.error(" bmfk deploy [config.json] — build + upload the current project");
23
+ console.error(" bmfk activate [config.json] [blue|green] — switch blue-green slot (omit slot for lastDeployed)");
24
+ console.error(" bmfk status [config.json] — show active / last deployed slot");
25
+ console.error(" bmfk backups [config.json] — list deploy backups");
26
+ console.error(" bmfk restore [config.json] [backup] [--yes] — restore a backup (asks which, and confirms)");
27
+ console.error(" bmfk hash-password [--deployer] — hash a password for the monitor (or deployer setup.json)");
28
+ console.error(" bmfk project-token [--hash] — new project token + its hash (or hash an existing one)");
29
+ console.error(" bmfk project-config — build a project config for the deployer, step by step");
30
+ console.error(" bmfk access-config [file] — create or edit access.json (found in the project's code if omitted)");
31
+ console.error(" bmfk migrate-configs [folder] [--yes] — hash the secrets of old setup.json, project configs and access.json files");
32
+ console.error(" bmfk setup-config [file|folder] — edit the deployer's setup.json: users, reviewers, allowed IPs");
33
+ console.error(" bmfk deploy-key [deploy.json] — a signing key pair: private key into deploy.json, public key for setup.json");
34
+ console.error(" bmfk ms-key — a signing key pair for a microservice host or caller");
35
+ console.error(" bmfk migrate [folder] [--write] — move a project from the legacy server 6.x (shows the plan; --write applies it)");
36
+ console.error(" bmfk deployer-init [folder] — set up a deployer on this server: service, pm2, setup.json, nginx");
37
+ console.error("");
38
+ console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
39
+ console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
40
+ process.exit(1);
41
+ }
42
+ function parseArgs(args) {
43
+ let scheme;
44
+ let config;
45
+ for (const a of args) {
46
+ if (a === "blue" || a === "green") {
47
+ if (scheme) {
48
+ console.error(`Slot specified twice ("${scheme}" and "${a}").`);
49
+ process.exit(1);
50
+ }
51
+ scheme = a;
52
+ }
53
+ else {
54
+ if (config) {
55
+ console.error(`Config path specified twice ("${config}" and "${a}").`);
56
+ process.exit(1);
57
+ }
58
+ config = a;
59
+ }
60
+ }
61
+ return { scheme, config };
62
+ }
63
+ async function main() {
64
+ const command = process.argv[2];
65
+ const rest = process.argv.slice(3);
66
+ switch (command) {
67
+ case "deploy": {
68
+ const { scheme, config } = parseArgs(rest);
69
+ if (scheme) {
70
+ console.error(`"deploy" does not take a slot argument ("${scheme}").`);
71
+ process.exit(1);
72
+ }
73
+ await (0, Deploy_1.Deploy)(config);
74
+ break;
75
+ }
76
+ case "activate": {
77
+ const { scheme, config } = parseArgs(rest);
78
+ await (0, Activate_1.Activate)(config, scheme);
79
+ break;
80
+ }
81
+ case "backups": {
82
+ const { scheme, config } = parseArgs(rest);
83
+ if (scheme) {
84
+ console.error(`"backups" does not take a slot argument ("${scheme}").`);
85
+ process.exit(1);
86
+ }
87
+ await (0, Backups_1.Backups)(config);
88
+ break;
89
+ }
90
+ case "restore": {
91
+ let config, backup, yes = false;
92
+ for (const a of rest) {
93
+ if (a === "--yes" || a === "-y") {
94
+ yes = true;
95
+ continue;
96
+ }
97
+ if (BackupManager_1.BackupManager.isValidName(a)) {
98
+ if (backup) {
99
+ console.error(`Backup specified twice ("${backup}" and "${a}").`);
100
+ process.exit(1);
101
+ }
102
+ backup = a;
103
+ continue;
104
+ }
105
+ if (config) {
106
+ console.error(`Config path specified twice ("${config}" and "${a}").`);
107
+ process.exit(1);
108
+ }
109
+ config = a;
110
+ }
111
+ await (0, Restore_1.Restore)(config, backup, yes);
112
+ break;
113
+ }
114
+ case "hash-password": {
115
+ const unknown = rest.filter(a => a !== "--deployer");
116
+ if (unknown.length) {
117
+ console.error("hash-password takes no arguments except --deployer — the password is asked interactively.");
118
+ process.exit(1);
119
+ }
120
+ await (0, HashPassword_1.HashPassword)(rest.includes("--deployer") ? "deployer" : "monitor");
121
+ break;
122
+ }
123
+ case "wizards": {
124
+ if (rest.length) {
125
+ console.error("wizards takes no arguments.");
126
+ process.exit(1);
127
+ }
128
+ await (0, Wizards_1.Wizards)();
129
+ break;
130
+ }
131
+ case "deploy-key": {
132
+ if (rest.length > 1) {
133
+ console.error("Usage: bmfk deploy-key [deploy.json]");
134
+ process.exit(1);
135
+ }
136
+ await (0, DeployKeyWizard_1.DeployKeyWizard)(rest[0]);
137
+ break;
138
+ }
139
+ case "ms-key": {
140
+ if (rest.length > 0) {
141
+ console.error("Usage: bmfk ms-key");
142
+ process.exit(1);
143
+ }
144
+ (0, DeployKeyWizard_1.MicroserviceKey)();
145
+ break;
146
+ }
147
+ case "setup-config": {
148
+ if (rest.length > 1) {
149
+ console.error("Usage: bmfk setup-config [file|folder]");
150
+ process.exit(1);
151
+ }
152
+ await (0, SetupConfigWizard_1.SetupConfigWizard)(rest[0]);
153
+ break;
154
+ }
155
+ case "deployer-init": {
156
+ if (rest.length > 1 || rest.some(a => a.startsWith("-"))) {
157
+ console.error("Usage: bmfk deployer-init [folder]");
158
+ process.exit(1);
159
+ }
160
+ await (0, DeployerInit_1.DeployerInit)(rest);
161
+ break;
162
+ }
163
+ case "migrate": {
164
+ if (rest.some(a => a.startsWith("-") && a !== "--write")) {
165
+ console.error("Usage: bmfk migrate [folder] [--write]");
166
+ process.exit(1);
167
+ }
168
+ await (0, MigrateProject_1.MigrateProject)(rest);
169
+ break;
170
+ }
171
+ case "migrate-configs": {
172
+ const assumeYes = rest.includes("--yes") || rest.includes("-y");
173
+ const folders = rest.filter(a => a !== "--yes" && a !== "-y");
174
+ if (folders.length > 1 || folders.some(a => a.startsWith("-"))) {
175
+ console.error("Usage: bmfk migrate-configs [folder] [--yes]");
176
+ process.exit(1);
177
+ }
178
+ await (0, MigrateConfigsWizard_1.MigrateConfigsWizard)(folders[0], assumeYes);
179
+ break;
180
+ }
181
+ case "access-config": {
182
+ if (rest.length > 1) {
183
+ console.error("access-config takes at most one argument: the path to the access file.");
184
+ process.exit(1);
185
+ }
186
+ await (0, AccessConfigWizard_1.AccessConfigWizard)(rest[0]);
187
+ break;
188
+ }
189
+ case "project-config": {
190
+ if (rest.length) {
191
+ console.error("project-config takes no arguments — everything is asked interactively.");
192
+ process.exit(1);
193
+ }
194
+ await (0, ProjectConfigWizard_1.ProjectConfigWizard)();
195
+ break;
196
+ }
197
+ case "project-token": {
198
+ const unknown = rest.filter(a => a !== "--hash");
199
+ if (unknown.length) {
200
+ console.error("project-token takes no arguments except --hash — an existing token is asked interactively.");
201
+ process.exit(1);
202
+ }
203
+ await (0, HashPassword_1.ProjectToken)(rest.includes("--hash") ? "hash" : "generate");
204
+ break;
205
+ }
206
+ case "status": {
207
+ const { scheme, config } = parseArgs(rest);
208
+ if (scheme) {
209
+ console.error(`"status" does not take a slot argument ("${scheme}").`);
210
+ process.exit(1);
211
+ }
212
+ await (0, Status_1.Status)(config);
213
+ break;
214
+ }
215
+ default:
216
+ if (command)
217
+ console.error(`Unknown command: ${command}\n`);
218
+ usage();
219
+ }
220
+ }
221
+ main().catch((err) => {
222
+ console.error("\n" + (err instanceof Error ? err.message : String(err)));
223
+ process.exit(1);
224
+ });
@@ -0,0 +1,27 @@
1
+ import { IDeployerConfig } from "./resolveConfig";
2
+ export declare function deployerUrl(opt: IDeployerConfig, endpoint: string): string;
3
+ export declare function authHeader(opt: IDeployerConfig): string;
4
+ export declare function deployerHeaders(opt: IDeployerConfig, url: string, data: unknown, files?: Record<string, string>): Record<string, string>;
5
+ export declare function responseError(r: any): string | null;
6
+ export declare function palette(): {
7
+ red: (t: string) => string;
8
+ green: (t: string) => string;
9
+ yellow: (t: string) => string;
10
+ blue: (t: string) => string;
11
+ dim: (t: string) => string;
12
+ bold: (t: string) => string;
13
+ };
14
+ export declare function fmtDate(ms: number): string;
15
+ export declare function fmtSize(kb: number | null | undefined): string;
16
+ export declare function fmtMs(ms: number): string;
17
+ export declare function stepLog(): {
18
+ ok: (name: string, text: string, ms?: number) => void;
19
+ skip: (name: string, text: string) => void;
20
+ warn: (name: string, text: string) => void;
21
+ fail: (name: string, text: string, ms?: number) => void;
22
+ note: (text: string) => void;
23
+ start(name: string, text: string): {
24
+ ok: (done?: string) => void;
25
+ fail: (done?: string) => void;
26
+ };
27
+ };
@@ -0,0 +1,110 @@
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.deployerUrl = deployerUrl;
7
+ exports.authHeader = authHeader;
8
+ exports.deployerHeaders = deployerHeaders;
9
+ exports.responseError = responseError;
10
+ exports.palette = palette;
11
+ exports.fmtDate = fmtDate;
12
+ exports.fmtSize = fmtSize;
13
+ exports.fmtMs = fmtMs;
14
+ exports.stepLog = stepLog;
15
+ const crypto_1 = __importDefault(require("crypto"));
16
+ const DefaultErrors_1 = require("../structures/DefaultErrors");
17
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
18
+ function deployerUrl(opt, endpoint) {
19
+ if (/\/add\/?$/.test(opt.host))
20
+ return opt.host.replace(/\/add\/?$/, "/" + endpoint);
21
+ if (opt.switch_host && /\/switch\/?$/.test(opt.switch_host))
22
+ return opt.switch_host.replace(/\/switch\/?$/, "/" + endpoint);
23
+ throw new Error(`Cannot derive the ${endpoint} URL from host "${opt.host}" — make sure "host" ends with /add.`);
24
+ }
25
+ function authHeader(opt) {
26
+ return "Bearer " + crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
27
+ }
28
+ function deployerHeaders(opt, url, data, files) {
29
+ const authorization = opt.privateKey
30
+ ? InterceptorSignedAuth_1.InterceptorSignedAuth.sign({ privateKey: opt.privateKey, kid: String(opt.username), method: "POST", url, data, files })
31
+ : authHeader(opt);
32
+ return { authorization, "x-deployer-login": String(opt.username) };
33
+ }
34
+ function responseError(r) {
35
+ const body = r?.ok ? r?.data : r?.error;
36
+ const e = (body && typeof body === "object")
37
+ ? (body.error ?? (DefaultErrors_1.ErrorUtils.isError(body.data) ? body.data : null) ?? (DefaultErrors_1.ErrorUtils.isError(body) ? body : null))
38
+ : null;
39
+ if (e && (e.message || e.details)) {
40
+ const text = [e.message, e.details].filter(Boolean).join(" — ");
41
+ return e.code !== undefined ? `${text} (code ${e.code})` : text;
42
+ }
43
+ if (!r?.ok) {
44
+ if (r?.status !== undefined)
45
+ return `HTTP ${r.status}`;
46
+ const raw = typeof r?.error === "string" ? r.error : JSON.stringify(r?.error);
47
+ return "network error: " + raw;
48
+ }
49
+ return null;
50
+ }
51
+ function palette() {
52
+ const on = !!process.stdout.isTTY && !process.env.NO_COLOR;
53
+ const c = (code) => (t) => on ? `\x1b[${code}m${t}\x1b[0m` : t;
54
+ return { red: c("31"), green: c("32"), yellow: c("33"), blue: c("34"), dim: c("2"), bold: c("1") };
55
+ }
56
+ function fmtDate(ms) {
57
+ const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
58
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
59
+ }
60
+ function fmtSize(kb) {
61
+ if (kb === null || kb === undefined)
62
+ return "—";
63
+ if (kb < 1024)
64
+ return `${kb} KB`;
65
+ if (kb < 1024 * 1024)
66
+ return `${(kb / 1024).toFixed(1)} MB`;
67
+ return `${(kb / 1024 / 1024).toFixed(2)} GB`;
68
+ }
69
+ function fmtMs(ms) {
70
+ if (ms < 1000)
71
+ return `${Math.round(ms)}ms`;
72
+ if (ms < 60_000)
73
+ return `${(ms / 1000).toFixed(1)}s`;
74
+ return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;
75
+ }
76
+ function stepLog() {
77
+ const p = palette();
78
+ const tty = !!process.stdout.isTTY;
79
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
80
+ const row = (mark, name, text, ms) => ` ${mark} ${name.padEnd(8)} ${text}` + (ms !== undefined ? " " + p.dim(fmtMs(ms)) : "");
81
+ const log = {
82
+ ok: (name, text, ms) => console.log(row(p.green("✓"), name, text, ms)),
83
+ skip: (name, text) => console.log(row(p.dim("–"), name, p.dim(text))),
84
+ warn: (name, text) => console.log(row(p.yellow("⚠"), name, p.yellow(text))),
85
+ fail: (name, text, ms) => console.log(row(p.red("✗"), name, p.red(text), ms)),
86
+ note: (text) => console.log(" ".repeat(13) + p.dim(text)),
87
+ start(name, text) {
88
+ const startedAt = Date.now();
89
+ let frame = 0;
90
+ const draw = () => {
91
+ const plain = ` ${frames[frame++ % frames.length]} ${name.padEnd(8)} ${text} ${fmtMs(Date.now() - startedAt)}`;
92
+ process.stdout.write("\r\x1b[2K" + plain.slice(0, Math.max(20, (process.stdout.columns || 80) - 1)));
93
+ };
94
+ const timer = tty ? setInterval(draw, 80) : null;
95
+ if (tty)
96
+ draw();
97
+ const stop = () => {
98
+ if (!timer)
99
+ return;
100
+ clearInterval(timer);
101
+ process.stdout.write("\r\x1b[2K");
102
+ };
103
+ return {
104
+ ok: (done) => { stop(); log.ok(name, done ?? text, Date.now() - startedAt); },
105
+ fail: (done) => { stop(); log.fail(name, done ?? text, Date.now() - startedAt); },
106
+ };
107
+ },
108
+ };
109
+ return log;
110
+ }
@@ -0,0 +1,5 @@
1
+ export declare function ask(question: string, def?: string): Promise<string>;
2
+ export declare function askValid(question: string, def: string, check: (v: string) => string | null): Promise<string>;
3
+ export declare function yes(question: string, def: boolean): Promise<boolean>;
4
+ export declare const list: (v: string, sep?: string) => string[];
5
+ export declare const tokens: (v: string) => string[];
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tokens = exports.list = void 0;
4
+ exports.ask = ask;
5
+ exports.askValid = askValid;
6
+ exports.yes = yes;
7
+ const promises_1 = require("readline/promises");
8
+ const process_1 = require("process");
9
+ const cliCommon_1 = require("./cliCommon");
10
+ async function ask(question, def = "") {
11
+ const { dim } = (0, cliCommon_1.palette)();
12
+ const rl = (0, promises_1.createInterface)({ input: process_1.stdin, output: process_1.stdout });
13
+ try {
14
+ const a = (await rl.question(question + (def ? dim(` [${def}]`) : "") + ": ")).trim();
15
+ return a || def;
16
+ }
17
+ finally {
18
+ rl.close();
19
+ }
20
+ }
21
+ async function askValid(question, def, check) {
22
+ const { red } = (0, cliCommon_1.palette)();
23
+ for (;;) {
24
+ const v = await ask(question, def);
25
+ const problem = check(v);
26
+ if (!problem)
27
+ return v;
28
+ console.log(red(` ✗ ${problem}`));
29
+ }
30
+ }
31
+ async function yes(question, def) {
32
+ const a = (await ask(question + " (y/n)", def ? "y" : "n")).toLowerCase();
33
+ return a.startsWith("y");
34
+ }
35
+ const list = (v, sep = ",") => v.split(sep).map(s => s.trim()).filter(Boolean);
36
+ exports.list = list;
37
+ const tokens = (v) => Array.from(v.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g), m => m[1] ?? m[2] ?? m[3]);
38
+ exports.tokens = tokens;
@@ -0,0 +1,19 @@
1
+ import type { IBundleOptions } from "./Bundler";
2
+ export interface IDeployerConfig {
3
+ name: string;
4
+ token: string;
5
+ host: string;
6
+ username: string;
7
+ password?: string;
8
+ privateKey?: string;
9
+ includes?: (string | {
10
+ src: string;
11
+ dest?: string;
12
+ })[];
13
+ excludes?: string[];
14
+ bundle?: boolean | IBundleOptions;
15
+ versionBump?: boolean;
16
+ switch_host?: string;
17
+ }
18
+ export declare function validateConfig(cfg: any): string | null;
19
+ export declare function resolveConfig(opt?: IDeployerConfig | string | null): Promise<IDeployerConfig>;
@@ -0,0 +1,139 @@
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.validateConfig = validateConfig;
7
+ exports.resolveConfig = resolveConfig;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const promises_1 = require("readline/promises");
11
+ const process_1 = require("process");
12
+ const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
13
+ function validateConfig(cfg) {
14
+ if (!cfg || typeof cfg !== "object")
15
+ return "not an object";
16
+ if (!cfg.name || !cfg.token || !cfg.host || !cfg.username)
17
+ return "missing one of: name, token, host, username";
18
+ if (!cfg.password && !cfg.privateKey)
19
+ return "missing credentials: privateKey (signed requests) or password";
20
+ if (cfg.privateKey) {
21
+ try {
22
+ InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(cfg.privateKey);
23
+ }
24
+ catch {
25
+ return "privateKey is not a valid Ed25519 key (base64 PKCS#8)";
26
+ }
27
+ }
28
+ if (cfg.includes) {
29
+ if (!Array.isArray(cfg.includes))
30
+ return "includes must be an array";
31
+ for (const inc of cfg.includes) {
32
+ if (typeof inc === "string")
33
+ continue;
34
+ if (!inc || typeof inc !== "object")
35
+ return "includes entries must be a string or { src, dest? }";
36
+ if (typeof inc.src !== "string" || inc.src.length === 0)
37
+ return "includes entry is missing a non-empty 'src'";
38
+ if (inc.dest !== undefined && (typeof inc.dest !== "string" || inc.dest.length === 0))
39
+ return `includes entry "${inc.src}" has an invalid 'dest'`;
40
+ }
41
+ }
42
+ if (cfg.excludes && !Array.isArray(cfg.excludes))
43
+ return "excludes must be an array";
44
+ if (cfg.versionBump !== undefined && typeof cfg.versionBump !== "boolean")
45
+ return "versionBump must be true or false";
46
+ if (cfg.bundle !== undefined && typeof cfg.bundle !== "boolean") {
47
+ if (!cfg.bundle || typeof cfg.bundle !== "object" || Array.isArray(cfg.bundle))
48
+ return "bundle must be true/false or { entry?, sourcemap? }";
49
+ if (cfg.bundle.entry !== undefined && (typeof cfg.bundle.entry !== "string" || cfg.bundle.entry.length === 0))
50
+ return "bundle.entry must be a non-empty path";
51
+ if (cfg.bundle.sourcemap !== undefined && typeof cfg.bundle.sourcemap !== "boolean")
52
+ return "bundle.sourcemap must be true or false";
53
+ if (cfg.bundle.minify !== undefined && typeof cfg.bundle.minify !== "boolean")
54
+ return "bundle.minify must be true or false";
55
+ }
56
+ if (cfg.switch_host && typeof cfg.switch_host !== "string")
57
+ return "switch_host must be a string";
58
+ return null;
59
+ }
60
+ async function selectConfig(configs) {
61
+ if (configs.length === 0) {
62
+ throw new Error("No valid deploy configs found");
63
+ }
64
+ if (configs.length === 1) {
65
+ console.log(`Using deploy config: ${configs[0].name}`);
66
+ return configs[0];
67
+ }
68
+ if (!process_1.stdin.isTTY) {
69
+ throw new Error(`Found ${configs.length} deploy configs (${configs.map(c => c.name).join(", ")}) but stdin is not a TTY — ` +
70
+ `cannot prompt for a choice. Pass a specific config explicitly, e.g. "deploy/<name>.json".`);
71
+ }
72
+ console.log("\nAvailable deploy configs:\n");
73
+ configs.forEach((config, index) => {
74
+ console.log(`[${index + 1}] ${config.name ?? "bad-config-file"}`);
75
+ });
76
+ const rl = (0, promises_1.createInterface)({ input: process_1.stdin, output: process_1.stdout });
77
+ try {
78
+ while (true) {
79
+ const answer = await rl.question(`\nChoose config [1-${configs.length}]: `);
80
+ const selectedIndex = Number.parseInt(answer.trim(), 10) - 1;
81
+ if (Number.isInteger(selectedIndex) && selectedIndex >= 0 && selectedIndex < configs.length) {
82
+ return configs[selectedIndex];
83
+ }
84
+ console.error(`Invalid selection. Enter a number from 1 to ${configs.length}.`);
85
+ }
86
+ }
87
+ finally {
88
+ rl.close();
89
+ }
90
+ }
91
+ async function resolveConfig(opt) {
92
+ if (!opt) {
93
+ const dir = path_1.default.resolve("deploy");
94
+ const single = path_1.default.resolve("deploy.json");
95
+ if (fs_1.default.existsSync(dir) && fs_1.default.statSync(dir).isDirectory()) {
96
+ const files = fs_1.default.readdirSync(dir).filter(f => f.endsWith(".json"));
97
+ if (files.length === 0)
98
+ throw new Error(`No .json configs found in ${dir}`);
99
+ const configs = [];
100
+ for (const f of files) {
101
+ const filePath = path_1.default.resolve(dir, f);
102
+ let parsed;
103
+ try {
104
+ parsed = JSON.parse(fs_1.default.readFileSync(filePath).toString("utf-8"));
105
+ }
106
+ catch (e) {
107
+ console.error(`Skipping ${f}: failed to parse JSON:`, e.message);
108
+ continue;
109
+ }
110
+ const reason = validateConfig(parsed);
111
+ if (reason) {
112
+ console.error(`Skipping ${f}: ${reason}`);
113
+ continue;
114
+ }
115
+ configs.push(parsed);
116
+ }
117
+ if (configs.length === 0)
118
+ throw new Error(`No valid deploy configs in ${dir} (all ${files.length} were skipped)`);
119
+ opt = await selectConfig(configs);
120
+ }
121
+ else if (fs_1.default.existsSync(single)) {
122
+ opt = single;
123
+ }
124
+ else {
125
+ throw new Error(`No deploy config found: neither ${dir}/ nor ${single} exists`);
126
+ }
127
+ }
128
+ if (typeof opt === "string") {
129
+ if (!fs_1.default.existsSync(opt)) {
130
+ throw new Error(`Config file not found: ${opt}`);
131
+ }
132
+ opt = JSON.parse(fs_1.default.readFileSync(opt).toString("utf-8"));
133
+ }
134
+ const invalidReason = validateConfig(opt);
135
+ if (invalidReason) {
136
+ throw new Error(`Invalid deploy config: ${invalidReason}`);
137
+ }
138
+ return opt;
139
+ }