@opencrvs/toolkit 2.1.0-rc.ffe0b7f → 2.2.0-rc.ab91cce

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 (246) hide show
  1. package/README.md +2 -12
  2. package/build.sh +23 -5
  3. package/create-countryconfig/index.js +441 -59
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +5 -2
  6. package/dist/application-config/index.js +362 -284
  7. package/dist/authentication/index.d.ts +66 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +765 -0
  10. package/dist/cli.js +2041 -1311
  11. package/dist/commons/api/router.d.ts +940 -363
  12. package/dist/commons/application-config/index.d.ts +0 -2
  13. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  14. package/dist/commons/conditionals/validate.d.ts +34 -8
  15. package/dist/commons/events/ActionConfig.d.ts +77 -7
  16. package/dist/commons/events/ActionDocument.d.ts +35 -15
  17. package/dist/commons/events/ActionInput.d.ts +4 -4
  18. package/dist/commons/events/ActionStatus.d.ts +14 -0
  19. package/dist/commons/events/AdvancedSearchConfig.d.ts +48 -12
  20. package/dist/commons/events/AuditLog.d.ts +148 -0
  21. package/dist/commons/events/Draft.d.ts +1 -21
  22. package/dist/commons/events/EventConfig.d.ts +29 -6
  23. package/dist/commons/events/EventDocument.d.ts +472 -4
  24. package/dist/commons/events/EventIndex.d.ts +3 -26
  25. package/dist/commons/events/EventMetadata.d.ts +1 -11
  26. package/dist/commons/events/EventStatus.d.ts +19 -0
  27. package/dist/commons/events/FieldConfig.d.ts +109 -63
  28. package/dist/commons/events/FieldTypeMapping.d.ts +17 -17
  29. package/dist/commons/events/FieldValue.d.ts +3 -2
  30. package/dist/commons/events/Flag.d.ts +42 -0
  31. package/dist/commons/events/FormConfig.d.ts +6 -0
  32. package/dist/commons/events/PageConfig.d.ts +4 -0
  33. package/dist/commons/events/PlainDate.d.ts +8 -0
  34. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  35. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  36. package/dist/commons/events/event.d.ts +12 -0
  37. package/dist/commons/events/eventConfigValidation.d.ts +17 -1
  38. package/dist/commons/events/index.d.ts +1 -0
  39. package/dist/commons/events/locationPayloads.d.ts +95 -0
  40. package/dist/commons/events/locations.d.ts +169 -26
  41. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  42. package/dist/commons/events/scopes.d.ts +21 -1
  43. package/dist/commons/events/test.utils.d.ts +83 -25
  44. package/dist/commons/events/utils.d.ts +52 -17
  45. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  46. package/dist/commons/notification/dispatch.d.ts +10 -0
  47. package/dist/commons/notification/index.d.ts +1 -0
  48. package/dist/conditionals/index.js +349 -65
  49. package/dist/csv.d.ts +25 -0
  50. package/dist/csv.d.ts.map +1 -0
  51. package/dist/csv.js +120 -0
  52. package/dist/environment/derived-variables.d.ts +18 -0
  53. package/dist/environment/derived-variables.d.ts.map +1 -1
  54. package/dist/environment/derived-variables.js +22 -1
  55. package/dist/environment/index.d.ts.map +1 -1
  56. package/dist/environment/index.js +2 -1
  57. package/dist/environment/logger.d.ts +15 -3
  58. package/dist/environment/logger.d.ts.map +1 -1
  59. package/dist/environment/manage-users.js +1 -1
  60. package/dist/environment/questions.d.ts.map +1 -1
  61. package/dist/environment/questions.js +20 -14
  62. package/dist/environment/setup-environment.d.ts +1 -1
  63. package/dist/environment/setup-environment.d.ts.map +1 -1
  64. package/dist/environment/setup-environment.js +610 -560
  65. package/dist/environment/swarm-to-k8s.js +3 -4
  66. package/dist/environment/templates.d.ts +0 -1
  67. package/dist/environment/templates.d.ts.map +1 -1
  68. package/dist/environment/templates.js +3 -8
  69. package/dist/environment/update-workflows.d.ts.map +1 -1
  70. package/dist/environment/update-workflows.js +4 -0
  71. package/dist/environment/utils.d.ts +0 -12
  72. package/dist/environment/utils.d.ts.map +1 -1
  73. package/dist/environment/utils.js +1 -28
  74. package/dist/events/index.js +6115 -5378
  75. package/dist/migrations/add-translations.d.ts +15 -0
  76. package/dist/migrations/add-translations.d.ts.map +1 -0
  77. package/dist/migrations/add-translations.js +151 -0
  78. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  79. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  80. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  81. package/dist/migrations/{v2.0/rename-api-paths.d.ts → v2.1/enable-telemetry.d.ts} +1 -1
  82. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  83. package/dist/migrations/v2.1/enable-telemetry.js +455 -0
  84. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  85. package/dist/migrations/v2.1/index.js +47 -215
  86. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +17 -0
  87. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -0
  88. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +348 -0
  89. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +2 -0
  90. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +1 -0
  91. package/dist/migrations/v2.1/remove-metabase-package-installs.js +161 -0
  92. package/dist/migrations/{v2.0/migrate-scopes.d.ts → v2.1/remove-sentry.d.ts} +1 -1
  93. package/dist/migrations/v2.1/remove-sentry.d.ts.map +1 -0
  94. package/dist/migrations/v2.1/remove-sentry.js +354 -0
  95. package/dist/migrations/{v2.0/create-events-index.d.ts → v2.1/rename-trigger-paths.d.ts} +1 -1
  96. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  97. package/dist/migrations/{v2.0/rename-api-paths.js → v2.1/rename-trigger-paths.js} +69 -40
  98. package/dist/migrations/v2.1/template-files.d.ts +8 -0
  99. package/dist/migrations/v2.1/template-files.d.ts.map +1 -0
  100. package/dist/migrations/v2.1/template-files.js +49 -0
  101. package/dist/migrations/v2.1/upgrade-tilt.d.ts +11 -0
  102. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -0
  103. package/dist/migrations/v2.1/upgrade-tilt.js +139 -0
  104. package/dist/migrations/v2.2/index.d.ts +6 -0
  105. package/dist/migrations/v2.2/index.d.ts.map +1 -0
  106. package/dist/migrations/v2.2/index.js +456 -0
  107. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts +39 -0
  108. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts.map +1 -0
  109. package/dist/migrations/v2.2/read-declaration-through-helper.js +257 -0
  110. package/dist/notification/index.js +2012 -1455
  111. package/dist/scopes/index.d.ts +614 -36
  112. package/dist/scopes/index.js +351 -65
  113. package/dist/telemetry/index.d.ts +45 -0
  114. package/dist/telemetry/index.d.ts.map +1 -0
  115. package/dist/telemetry/index.js +43 -0
  116. package/dist/templates/charts-values/dependencies/values.yaml +8 -0
  117. package/dist/templates/charts-values/opencrvs-services/values.yaml +10 -3
  118. package/dist/templates/charts-values/opentelemetry/values.yaml +102 -0
  119. package/dist/templates/charts-values/traefik/values.yaml +25 -12
  120. package/dist/templates/countryconfig-template/.tiltignore +1 -0
  121. package/dist/templates/countryconfig-template/Dockerfile.assets +7 -0
  122. package/dist/templates/countryconfig-template/Tiltfile +112 -0
  123. package/dist/templates/countryconfig-template/assets/README.md +1 -0
  124. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +61 -0
  125. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +455 -0
  126. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +168 -0
  127. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +67 -0
  128. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +168 -0
  129. package/dist/templates/countryconfig-template/assets/metabase/README.md +34 -0
  130. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +36 -0
  131. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +46 -0
  132. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +27737 -0
  133. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +21 -0
  134. package/dist/templates/countryconfig-template/assets/metabase/package.json +13 -0
  135. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +108 -0
  136. package/dist/templates/countryconfig-template/assets/metabase/run.sh +120 -0
  137. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +40 -0
  138. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +135 -0
  139. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +108 -0
  140. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +50 -0
  141. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +35 -0
  142. package/dist/templates/countryconfig-template/tilt/common.tilt +145 -0
  143. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +15 -0
  144. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +56 -0
  145. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +21 -0
  146. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +38 -0
  147. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +17 -0
  148. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +16 -0
  149. package/dist/templates/countryconfig-template/tilt/lib.tilt +95 -0
  150. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +136 -0
  151. package/dist/templates/inventory/inventory.template.yml +1 -3
  152. package/dist/translations/template.d.ts +11 -0
  153. package/dist/translations/template.d.ts.map +1 -0
  154. package/dist/translations/template.js +100 -0
  155. package/dist/verify/endpoints.d.ts +2 -0
  156. package/dist/verify/endpoints.d.ts.map +1 -0
  157. package/dist/verify/endpoints.js +510 -0
  158. package/opencrvs-toolkit-2.2.0-rc.ab91cce.tgz +0 -0
  159. package/package.json +13 -7
  160. package/tsconfig.build.json +11 -0
  161. package/tsconfig.build.tsbuildinfo +1 -0
  162. package/tsconfig.json +3 -0
  163. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +0 -3
  164. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +0 -1
  165. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +0 -429
  166. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +0 -3
  167. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +0 -1
  168. package/dist/migrations/v2.0/add-resend-invite-notification.js +0 -373
  169. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +0 -22
  170. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +0 -1
  171. package/dist/migrations/v2.0/checkout-upstream-files.js +0 -146
  172. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +0 -2
  173. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +0 -1
  174. package/dist/migrations/v2.0/convert-config-files-to-ts.js +0 -838
  175. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +0 -3
  176. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +0 -1
  177. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +0 -158
  178. package/dist/migrations/v2.0/create-events-index.d.ts.map +0 -1
  179. package/dist/migrations/v2.0/create-events-index.js +0 -325
  180. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +0 -11
  181. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +0 -1
  182. package/dist/migrations/v2.0/delete-infrastructure-directory.js +0 -123
  183. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +0 -3
  184. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +0 -1
  185. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +0 -110
  186. package/dist/migrations/v2.0/index.d.ts +0 -13
  187. package/dist/migrations/v2.0/index.d.ts.map +0 -1
  188. package/dist/migrations/v2.0/index.js +0 -103
  189. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +0 -3
  190. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +0 -1
  191. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +0 -432
  192. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +0 -13
  193. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +0 -1
  194. package/dist/migrations/v2.0/merge-infrastructure-directory.js +0 -222
  195. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +0 -3
  196. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +0 -1
  197. package/dist/migrations/v2.0/migrate-application-config-url.js +0 -343
  198. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +0 -1
  199. package/dist/migrations/v2.0/migrate-scopes.js +0 -305
  200. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +0 -3
  201. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +0 -1
  202. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +0 -267
  203. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +0 -3
  204. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +0 -1
  205. package/dist/migrations/v2.0/migrate-workqueue-configs.js +0 -317
  206. package/dist/migrations/v2.0/remove-delete-actions.d.ts +0 -3
  207. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +0 -1
  208. package/dist/migrations/v2.0/remove-delete-actions.js +0 -156
  209. package/dist/migrations/v2.0/remove-demo-scope.d.ts +0 -3
  210. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +0 -1
  211. package/dist/migrations/v2.0/remove-demo-scope.js +0 -74
  212. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +0 -3
  213. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +0 -1
  214. package/dist/migrations/v2.0/remove-deprecated-imports.js +0 -96
  215. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +0 -3
  216. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +0 -1
  217. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +0 -163
  218. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +0 -3
  219. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +0 -1
  220. package/dist/migrations/v2.0/remove-hearth-migrations.js +0 -87
  221. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +0 -3
  222. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +0 -1
  223. package/dist/migrations/v2.0/remove-old-statistics-service.js +0 -356
  224. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +0 -3
  225. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +0 -1
  226. package/dist/migrations/v2.0/remove-pending-certification-flag.js +0 -109
  227. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +0 -3
  228. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +0 -1
  229. package/dist/migrations/v2.0/remove-review-from-register-action.js +0 -163
  230. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +0 -3
  231. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +0 -1
  232. package/dist/migrations/v2.0/remove-unused-environment-variables.js +0 -186
  233. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +0 -1
  234. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +0 -3
  235. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +0 -1
  236. package/dist/migrations/v2.0/rename-location-parent-id.js +0 -180
  237. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +0 -3
  238. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +0 -1
  239. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +0 -195
  240. package/dist/migrations/v2.0/update-package-json.d.ts +0 -3
  241. package/dist/migrations/v2.0/update-package-json.d.ts.map +0 -1
  242. package/dist/migrations/v2.0/update-package-json.js +0 -105
  243. package/dist/templates/inventory/production.example.yml +0 -77
  244. package/dist/templates/inventory/qa.example.yml +0 -48
  245. package/opencrvs-toolkit-2.1.0-rc.ffe0b7f.tgz +0 -0
  246. package/tsconfig.tsbuildinfo +0 -1
package/dist/cli.js CHANGED
@@ -32,13 +32,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
 
33
33
  // src/environment/paths.ts
34
34
  function getEnvironmentInventoryPath(environment) {
35
- return (0, import_path2.join)("environments", environment, INVENTORY_FILE_NAME);
35
+ return (0, import_path3.join)("environments", environment, INVENTORY_FILE_NAME);
36
36
  }
37
37
  function findOldInventoryFiles() {
38
- return glob.sync((0, import_path2.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
38
+ return glob.sync((0, import_path3.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
39
  }
40
40
  function getEnvironmentNameFromOldInventoryPath(filePath) {
41
- return (0, import_path2.basename)(filePath, ".yml");
41
+ return (0, import_path3.basename)(filePath, ".yml");
42
42
  }
43
43
  function assertNoOldInventoryLayout() {
44
44
  if (findOldInventoryFiles().length === 0) {
@@ -51,13 +51,13 @@ function assertNoOldInventoryLayout() {
51
51
  ].join(" ")
52
52
  );
53
53
  }
54
- var import_path2, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
54
+ var import_path3, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
55
  var init_paths = __esm({
56
56
  "src/environment/paths.ts"() {
57
57
  "use strict";
58
- import_path2 = require("path");
58
+ import_path3 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path2.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path3.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -479,12 +479,33 @@ var init_derived_variables = __esm({
479
479
  type: "disabled",
480
480
  scope: "ENVIRONMENT"
481
481
  },
482
+ {
483
+ name: "RESTORE_ENVIRONMENT_MODE",
484
+ valueLabel: "RESTORE_ENVIRONMENT_MODE",
485
+ valueType: "VARIABLE",
486
+ type: "disabled",
487
+ scope: "ENVIRONMENT"
488
+ },
489
+ {
490
+ name: "RESTORE_HOST",
491
+ valueLabel: "RESTORE_HOST",
492
+ valueType: "VARIABLE",
493
+ type: "disabled",
494
+ scope: "ENVIRONMENT"
495
+ },
482
496
  {
483
497
  name: "NOTIFICATION_TRANSPORT",
484
498
  valueLabel: "NOTIFICATION_TRANSPORT",
485
499
  valueType: "VARIABLE",
486
500
  type: "disabled",
487
501
  scope: "ENVIRONMENT"
502
+ },
503
+ {
504
+ name: "TWO_FA_ENABLED",
505
+ valueLabel: "TWO_FA_ENABLED",
506
+ valueType: "VARIABLE",
507
+ type: "disabled",
508
+ scope: "ENVIRONMENT"
488
509
  }
489
510
  ];
490
511
  }
@@ -503,24 +524,8 @@ function findExistingValue(name, type, scope, existingValues) {
503
524
  (value) => value.name === name && value.type === type && value.scope === scope
504
525
  );
505
526
  }
506
- function storeSecrets(environment, answers) {
507
- let envConfig = {};
508
- try {
509
- envConfig = import_dotenv.default.parse(
510
- (0, import_fs.readFileSync)(`${process.cwd()}/.env.${environment}`)
511
- );
512
- } catch (error3) {
513
- envConfig = {};
514
- }
515
- const linesFromAnswers = answers.map(
516
- (update) => `${update.name}="${update.value}"`
517
- );
518
- const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
519
- const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
520
- (0, import_fs.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
521
- }
522
527
  function readYamlFile(filePath) {
523
- const fileContent = import_fs.default.readFileSync(filePath, "utf8");
528
+ const fileContent = import_fs2.default.readFileSync(filePath, "utf8");
524
529
  return yaml.load(fileContent);
525
530
  }
526
531
  function writeYamlFile(filePath, data) {
@@ -533,33 +538,29 @@ function writeYamlFile(filePath, data) {
533
538
  noRefs: true,
534
539
  sortKeys: false
535
540
  });
536
- import_fs.default.writeFileSync(filePath, yamlContent, "utf8");
541
+ import_fs2.default.writeFileSync(filePath, yamlContent, "utf8");
537
542
  } catch (error3) {
538
543
  throw new Error(`Failed to write inventory file: ${error3}`);
539
544
  }
540
545
  }
541
- var import_fs, yaml, import_dotenv;
546
+ var import_fs2, yaml;
542
547
  var init_utils = __esm({
543
548
  "src/environment/utils.ts"() {
544
549
  "use strict";
545
- import_fs = __toESM(require("fs"));
550
+ import_fs2 = __toESM(require("fs"));
546
551
  yaml = __toESM(require("js-yaml"));
547
- import_dotenv = __toESM(require("dotenv"));
548
552
  }
549
553
  });
550
554
 
551
555
  // src/environment/templates.ts
552
- function getUsers(data) {
553
- if (!data?.all?.vars?.users) {
554
- return { users: [] };
555
- }
556
- return data.all.vars.users;
557
- }
558
556
  function extractAndModifyUsers(data) {
559
557
  if (!data?.all?.vars?.users) {
560
558
  return { users: [] };
561
559
  }
562
560
  const users = data.all.vars.users.map((user) => {
561
+ if (user.role) {
562
+ return user;
563
+ }
563
564
  const { sudoer, ...rest } = user;
564
565
  return {
565
566
  ...rest,
@@ -595,29 +596,29 @@ function extractWorkerNodes(data) {
595
596
  return worker_hosts;
596
597
  }
597
598
  function copyChartsValues(env, values) {
598
- const srcDir = import_path3.default.resolve(__dirname, "templates", "charts-values");
599
- const destDir = import_path3.default.resolve(process.cwd(), "environments", env);
600
- import_fs2.default.mkdirSync(destDir, { recursive: true });
599
+ const srcDir = import_path4.default.resolve(__dirname, "templates", "charts-values");
600
+ const destDir = import_path4.default.resolve(process.cwd(), "environments", env);
601
+ import_fs3.default.mkdirSync(destDir, { recursive: true });
601
602
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
602
603
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
603
604
  values["opencrvs_environment"] = env;
604
605
  function copyRecursive(src, dest) {
605
- const stat = import_fs2.default.statSync(src);
606
+ const stat = import_fs3.default.statSync(src);
606
607
  if (stat.isDirectory()) {
607
- import_fs2.default.mkdirSync(dest, { recursive: true });
608
- for (const item of import_fs2.default.readdirSync(src)) {
609
- copyRecursive(import_path3.default.join(src, item), import_path3.default.join(dest, item));
608
+ import_fs3.default.mkdirSync(dest, { recursive: true });
609
+ for (const item of import_fs3.default.readdirSync(src)) {
610
+ copyRecursive(import_path4.default.join(src, item), import_path4.default.join(dest, item));
610
611
  }
611
612
  } else {
612
- const content = import_fs2.default.readFileSync(src, "utf8");
613
+ const content = import_fs3.default.readFileSync(src, "utf8");
613
614
  const template = import_handlebars.default.compile(content);
614
615
  const updated = template(values);
615
616
  const isOverridesFile = dest.endsWith("override.yaml");
616
- if (isOverridesFile && import_fs2.default.existsSync(dest)) {
617
+ if (isOverridesFile && import_fs3.default.existsSync(dest)) {
617
618
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
618
619
  return;
619
620
  }
620
- import_fs2.default.writeFileSync(dest, updated, "utf8");
621
+ import_fs3.default.writeFileSync(dest, updated, "utf8");
621
622
  log(` \u2713 Created: ${dest}`);
622
623
  }
623
624
  }
@@ -628,29 +629,29 @@ function copyChartsValues(env, values) {
628
629
  `);
629
630
  }
630
631
  function generateInventory(env, values) {
631
- const templatePath = import_path3.default.join(
632
+ const templatePath = import_path4.default.join(
632
633
  __dirname,
633
634
  "templates",
634
635
  "inventory",
635
636
  "inventory.template.yml"
636
637
  );
637
- const outputPath = import_path3.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
638
- const templateFile = import_fs2.default.readFileSync(templatePath, "utf-8");
638
+ const outputPath = import_path4.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
639
+ const templateFile = import_fs3.default.readFileSync(templatePath, "utf-8");
639
640
  const template = import_handlebars.default.compile(templateFile);
640
641
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
641
642
  const updated = template(values);
642
- import_fs2.default.mkdirSync(import_path3.default.dirname(outputPath), { recursive: true });
643
- import_fs2.default.writeFileSync(outputPath, updated);
643
+ import_fs3.default.mkdirSync(import_path4.default.dirname(outputPath), { recursive: true });
644
+ import_fs3.default.writeFileSync(outputPath, updated);
644
645
  log(`
645
646
  \u2705 Generated inventory file at ${outputPath}
646
647
  `);
647
648
  }
648
- var import_fs2, import_path3, import_handlebars;
649
+ var import_fs3, import_path4, import_handlebars;
649
650
  var init_templates = __esm({
650
651
  "src/environment/templates.ts"() {
651
652
  "use strict";
652
- import_fs2 = __toESM(require("fs"));
653
- import_path3 = __toESM(require("path"));
653
+ import_fs3 = __toESM(require("fs"));
654
+ import_path4 = __toESM(require("path"));
654
655
  init_logger();
655
656
  init_paths();
656
657
  import_handlebars = __toESM(require("handlebars"));
@@ -676,6 +677,141 @@ var init_ssh_keygen = __esm({
676
677
  }
677
678
  });
678
679
 
680
+ // src/environment/update-workflows.ts
681
+ var update_workflows_exports = {};
682
+ __export(update_workflows_exports, {
683
+ updateWorkflowEnvironments: () => updateWorkflowEnvironments
684
+ });
685
+ function isDirectory(path7) {
686
+ try {
687
+ return (0, import_fs4.statSync)(path7).isDirectory();
688
+ } catch {
689
+ return false;
690
+ }
691
+ }
692
+ async function extractInfrastructureNames() {
693
+ const files = glob2.sync((0, import_path5.join)("environments", "*", INVENTORY_FILE_NAME));
694
+ const infraEnvironments = files.map((file) => (0, import_path5.basename)((0, import_path5.dirname)(file)));
695
+ if (infraEnvironments.length === 0) {
696
+ console.log(
697
+ `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
698
+ );
699
+ return [];
700
+ }
701
+ log("\u{1F50D} Found infrastructure configurations:", infraEnvironments.join(", "));
702
+ return infraEnvironments;
703
+ }
704
+ async function extractEnvironmentNames() {
705
+ const entries = await (0, import_promises.readdir)("environments");
706
+ const environments = entries.filter((entry) => {
707
+ const environmentPath = (0, import_path5.join)("environments", entry);
708
+ const opencrvsServicesPath = (0, import_path5.join)(environmentPath, "opencrvs-services");
709
+ return isDirectory(environmentPath) && (0, import_fs4.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
710
+ });
711
+ if (environments.length === 0) {
712
+ console.log(
713
+ "\u26A0\uFE0F Warning: No environment directories found in environments/"
714
+ );
715
+ return [];
716
+ }
717
+ log("\u{1F50D} Found OpenCRVS configurations:", environments.join(", "));
718
+ return environments;
719
+ }
720
+ function updateOptionsInYaml(content, envList) {
721
+ const optionsRegex = /([ ]*options:[ ]*\n)((?:[ ]*-[^\n]*\n)+)/;
722
+ const match = content.match(optionsRegex);
723
+ if (!match) {
724
+ throw new Error("Could not find options array in workflow file");
725
+ }
726
+ const firstItemMatch = match[2].match(/^([ ]*)-/);
727
+ const itemIndent = firstItemMatch ? firstItemMatch[1] : " ";
728
+ const newOptions = match[1] + envList.map((env) => `${itemIndent}- ${env}`).join("\n") + "\n";
729
+ return content.replace(optionsRegex, newOptions);
730
+ }
731
+ async function updateWorkflows(envList, config) {
732
+ const { workflows } = config;
733
+ for (const workflowPath of workflows) {
734
+ if (!(0, import_fs4.existsSync)(workflowPath)) {
735
+ log(` \u21B7 Skipped ${workflowPath} (not found in this repository)`);
736
+ continue;
737
+ }
738
+ try {
739
+ const fileContents = (0, import_fs4.readFileSync)(workflowPath, "utf8");
740
+ const workflowData = yaml2.load(fileContents);
741
+ if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
742
+ throw new Error(
743
+ "Workflow does not have the expected structure: on.workflow_dispatch.inputs.environment.options"
744
+ );
745
+ }
746
+ const updatedContent = updateOptionsInYaml(fileContents, envList);
747
+ (0, import_fs4.writeFileSync)(workflowPath, updatedContent, "utf8");
748
+ log(` \u2713 Successfully updated ${workflowPath}`);
749
+ } catch (error3) {
750
+ console.error(
751
+ `
752
+ \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
753
+ );
754
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
755
+ throw error3;
756
+ }
757
+ }
758
+ }
759
+ async function updateWorkflowEnvironments() {
760
+ try {
761
+ let didUpdateWorkflows = false;
762
+ const infraEnvironments = await extractInfrastructureNames();
763
+ if (infraEnvironments.length > 0) {
764
+ console.log("\u{1F504} Updating infrastructure workflows:");
765
+ await updateWorkflows(infraEnvironments, {
766
+ workflows: [
767
+ ".github/workflows/provision.yml",
768
+ ".github/workflows/reset-2fa.yml"
769
+ ],
770
+ path: "on.workflow_dispatch.inputs.environment.options"
771
+ });
772
+ didUpdateWorkflows = true;
773
+ }
774
+ const environments = await extractEnvironmentNames();
775
+ if (environments.length > 0) {
776
+ const workflows = [
777
+ ".github/workflows/deploy-dependencies.yml",
778
+ ".github/workflows/deploy-opencrvs.yml",
779
+ ".github/workflows/clear-all-data.yml",
780
+ ".github/workflows/seed-data.yml",
781
+ ".github/workflows/reindex.yml",
782
+ ".github/workflows/github-to-k8s-sync-env.yml"
783
+ ];
784
+ log("\u{1F4CB} Updating OpenCRVS application workflows:");
785
+ await updateWorkflows(environments, {
786
+ workflows,
787
+ path: "on.workflow_dispatch.inputs.environment.options"
788
+ });
789
+ didUpdateWorkflows = true;
790
+ }
791
+ if (didUpdateWorkflows) {
792
+ success("\u2705 Workflow updates completed successfully!");
793
+ } else {
794
+ log("\u2139\uFE0F No workflows were updated.");
795
+ }
796
+ } catch (error3) {
797
+ console.error("\n\u274C Error updating workflows:", error3);
798
+ process.exit(1);
799
+ }
800
+ }
801
+ var import_promises, import_fs4, import_path5, glob2, yaml2;
802
+ var init_update_workflows = __esm({
803
+ "src/environment/update-workflows.ts"() {
804
+ "use strict";
805
+ import_promises = require("fs/promises");
806
+ import_fs4 = require("fs");
807
+ import_path5 = require("path");
808
+ glob2 = __toESM(require("glob"));
809
+ yaml2 = __toESM(require("js-yaml"));
810
+ init_logger();
811
+ init_paths();
812
+ }
813
+ });
814
+
679
815
  // src/environment/git.ts
680
816
  function getRepoInfo() {
681
817
  try {
@@ -706,18 +842,18 @@ var init_git = __esm({
706
842
  });
707
843
 
708
844
  // src/environment/questions.ts
709
- function validateCIDR(input3) {
710
- if (!input3.trim()) {
845
+ function validateCIDR(input4) {
846
+ if (!input4.trim()) {
711
847
  return true;
712
848
  }
713
849
  const cidrRegex = /^((25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\/([0-9]|[12][0-9]|3[0-2])$/;
714
- return cidrRegex.test(input3.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
850
+ return cidrRegex.test(input4.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
715
851
  }
716
- function validateCIDRs(input3) {
717
- if (!input3.trim()) {
852
+ function validateCIDRs(input4) {
853
+ if (!input4.trim()) {
718
854
  return true;
719
855
  }
720
- const cidrs = input3.split(",").map((v) => v.trim());
856
+ const cidrs = input4.split(",").map((v) => v.trim());
721
857
  for (const cidr of cidrs) {
722
858
  const result = validateCIDR(cidr);
723
859
  if (result !== true) {
@@ -860,11 +996,28 @@ var init_questions = __esm({
860
996
  scope: "ENVIRONMENT"
861
997
  },
862
998
  {
863
- name: "kubeAPIHost",
999
+ name: "kubeMasterNode",
1000
+ type: "text",
1001
+ message: `Kubernetes master node hostnames or IP (default: auto-detect)`,
1002
+ valueType: "VARIABLE",
1003
+ valueLabel: "KUBE_MASTER_NODE",
1004
+ initial: process.env.KUBE_MASTER_NODE,
1005
+ scope: "ENVIRONMENT"
1006
+ },
1007
+ {
1008
+ name: "kubeWorkerNodes",
1009
+ type: "text",
1010
+ message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
1011
+ valueType: "VARIABLE",
1012
+ valueLabel: "KUBE_WORKER_NODES",
1013
+ initial: process.env.KUBE_WORKER_NODES || "",
1014
+ scope: "ENVIRONMENT"
1015
+ },
1016
+ {
1017
+ name: "kubeApiHost",
864
1018
  type: "text",
865
- message: `Kubernetes API endpoint (default: auto-detect)`,
1019
+ message: `Kubernetes API endpoint IP (default: KUBE_MASTER_NODE)`,
866
1020
  valueType: "VARIABLE",
867
- // validate: notEmpty,
868
1021
  valueLabel: "KUBE_API_HOST",
869
1022
  initial: process.env.KUBE_API_HOST,
870
1023
  scope: "ENVIRONMENT"
@@ -878,16 +1031,6 @@ var init_questions = __esm({
878
1031
  valueLabel: "KUBE_API_ALLOWED_CIDRS",
879
1032
  initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
880
1033
  scope: "ENVIRONMENT"
881
- },
882
- {
883
- name: "kubeWorkerNodes",
884
- type: "text",
885
- message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
886
- valueType: "VARIABLE",
887
- // validate: notEmpty,
888
- valueLabel: "KUBE_WORKER_NODES",
889
- initial: process.env.KUBE_WORKER_NODES || "",
890
- scope: "ENVIRONMENT"
891
1034
  }
892
1035
  ];
893
1036
  staticSSLCertQuestions = [
@@ -918,7 +1061,6 @@ var init_questions = __esm({
918
1061
  type: "text",
919
1062
  message: `Please enter backup server host/IP address, (default: no backup):`,
920
1063
  valueType: "VARIABLE",
921
- // validate: notEmpty,
922
1064
  valueLabel: "BACKUP_HOST",
923
1065
  initial: process.env.BACKUP_HOST || "",
924
1066
  scope: "ENVIRONMENT"
@@ -1241,7 +1383,7 @@ function updateInventoryFile(filePath, users) {
1241
1383
  function parseInventoryFile(filePath) {
1242
1384
  try {
1243
1385
  const data = readYamlFile(filePath);
1244
- return getUsers(data);
1386
+ return extractAndModifyUsers(data);
1245
1387
  } catch {
1246
1388
  return [];
1247
1389
  }
@@ -1251,7 +1393,7 @@ function getCurrentUsername() {
1251
1393
  }
1252
1394
  function getCurrentUserSSHKeys() {
1253
1395
  const homeDir = os.homedir();
1254
- const sshDir = path3.join(homeDir, ".ssh");
1396
+ const sshDir = path4.join(homeDir, ".ssh");
1255
1397
  const keys = [];
1256
1398
  const keyFiles = [
1257
1399
  "id_rsa.pub",
@@ -1260,7 +1402,7 @@ function getCurrentUserSSHKeys() {
1260
1402
  "id_dsa.pub"
1261
1403
  ];
1262
1404
  for (const keyFile of keyFiles) {
1263
- const keyPath = path3.join(sshDir, keyFile);
1405
+ const keyPath = path4.join(sshDir, keyFile);
1264
1406
  try {
1265
1407
  if (fs3.existsSync(keyPath)) {
1266
1408
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1601,13 +1743,13 @@ async function manageUsers(inventoryPath) {
1601
1743
  }
1602
1744
  return users;
1603
1745
  }
1604
- var os, fs3, path3, input2, select2, confirm, editor, checkbox;
1746
+ var os, fs3, path4, input2, select2, confirm, editor, checkbox;
1605
1747
  var init_manage_users = __esm({
1606
1748
  "src/environment/manage-users.ts"() {
1607
1749
  "use strict";
1608
1750
  os = __toESM(require("os"));
1609
1751
  fs3 = __toESM(require("fs"));
1610
- path3 = __toESM(require("path"));
1752
+ path4 = __toESM(require("path"));
1611
1753
  init_logger();
1612
1754
  init_utils();
1613
1755
  init_templates();
@@ -1621,6 +1763,9 @@ var init_manage_users = __esm({
1621
1763
 
1622
1764
  // src/environment/setup-environment.ts
1623
1765
  var setup_environment_exports = {};
1766
+ __export(setup_environment_exports, {
1767
+ runSetupEnvironment: () => runSetupEnvironment
1768
+ });
1624
1769
  async function confirm2(options) {
1625
1770
  const inquirer = await import("@inquirer/prompts");
1626
1771
  return inquirer.confirm(options);
@@ -1629,6 +1774,10 @@ async function select3(options) {
1629
1774
  const inquirer = await import("@inquirer/prompts");
1630
1775
  return inquirer.select(options);
1631
1776
  }
1777
+ async function input3(options) {
1778
+ const inquirer = await import("@inquirer/prompts");
1779
+ return inquirer.input(options);
1780
+ }
1632
1781
  function questionToPrompt({
1633
1782
  valueType,
1634
1783
  valueLabel,
@@ -1695,7 +1844,7 @@ function getAnswers(existingValues) {
1695
1844
  });
1696
1845
  });
1697
1846
  }
1698
- async function promptAndStoreAnswer(environment, questions, existingValues) {
1847
+ async function promptAndStoreAnswer(questions, existingValues) {
1699
1848
  log("");
1700
1849
  const processedQuestions = questions.flatMap((question) => {
1701
1850
  const questionWithVariableLabel = {
@@ -1774,7 +1923,6 @@ async function promptAndStoreAnswer(environment, questions, existingValues) {
1774
1923
  }
1775
1924
  });
1776
1925
  ALL_ANSWERS.push(result);
1777
- storeSecrets(environment, getAnswers(existingValues));
1778
1926
  const existingValuesForQuestions = questions.filter((question) => question.valueType === "VARIABLE").map((question) => [
1779
1927
  question.name,
1780
1928
  findExistingValue(
@@ -1786,973 +1934,988 @@ async function promptAndStoreAnswer(environment, questions, existingValues) {
1786
1934
  ]);
1787
1935
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1788
1936
  }
1789
- var import_core, import_dotenv2, import_kleur4, import_prompts2, ALL_QUESTIONS, ALL_ANSWERS;
1790
- var init_setup_environment = __esm({
1791
- "src/environment/setup-environment.ts"() {
1792
- "use strict";
1793
- import_core = require("@octokit/core");
1794
- import_dotenv2 = __toESM(require("dotenv"));
1795
- import_kleur4 = __toESM(require("kleur"));
1796
- import_prompts2 = __toESM(require("prompts"));
1797
- init_github();
1798
- init_derived_variables();
1799
- init_utils();
1800
- init_logger();
1801
- init_templates();
1802
- init_ssh_keygen();
1803
- init_questions();
1804
- init_editor_questions();
1805
- init_questions_helper();
1806
- init_manage_users();
1807
- init_paths();
1808
- ALL_QUESTIONS = [];
1809
- ALL_ANSWERS = [];
1810
- ALL_QUESTIONS.push(
1811
- ...githubTokenQuestion,
1812
- ...githubOtherQuestions,
1813
- ...dockerhubQuestions,
1814
- ...diskQuestions,
1815
- ...infrastructureQuestions,
1816
- ...backupQuestions,
1817
- ...countryQuestions,
1818
- ...databaseAndMonitoringQuestions,
1819
- ...emailQuestions,
1820
- ...sentryQuestions,
1821
- ...derivedVariables,
1822
- ...metabaseAdminQuestions
1823
- );
1824
- (async () => {
1825
- log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1826
- const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
1827
- githubQuestions.map(questionToPrompt),
1828
- {
1829
- onCancel: () => {
1830
- process.exit(1);
1831
- }
1832
- }
1833
- );
1834
- const { githubToken } = await promptAndStoreAnswer(
1835
- "",
1836
- githubTokenQuestion,
1837
- []
1838
- );
1839
- const octokit = new import_core.Octokit({
1840
- auth: githubToken
1841
- });
1842
- log(import_kleur4.default.green("\nSuccessfully logged in to Github\n"));
1843
- const existingEnvironments = await getRepositoryEnvironments(
1844
- octokit,
1845
- githubOrganisation,
1846
- githubRepository
1847
- );
1848
- const defaultChoices = [
1849
- { name: "Development", value: "development" },
1850
- { name: "Quality assurance (no PII data)", value: "qa" },
1937
+ async function runSetupEnvironment() {
1938
+ log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1939
+ const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
1940
+ githubQuestions.map(questionToPrompt),
1941
+ {
1942
+ onCancel: () => {
1943
+ process.exit(1);
1944
+ }
1945
+ }
1946
+ );
1947
+ const { githubToken } = await promptAndStoreAnswer(githubTokenQuestion, []);
1948
+ const octokit = new import_core.Octokit({
1949
+ auth: githubToken
1950
+ });
1951
+ log(import_kleur4.default.green("\nSuccessfully logged in to Github\n"));
1952
+ const existingEnvironments = await getRepositoryEnvironments(
1953
+ octokit,
1954
+ githubOrganisation,
1955
+ githubRepository
1956
+ );
1957
+ const defaultChoices = [
1958
+ { name: "Development", value: "development" },
1959
+ { name: "Quality assurance (no PII data)", value: "qa" },
1960
+ {
1961
+ name: "Staging (hosts PII data, no backups)",
1962
+ value: "staging"
1963
+ },
1964
+ {
1965
+ name: "Production (hosts PII data, requires frequent backups)",
1966
+ value: "production"
1967
+ }
1968
+ ];
1969
+ const choices = [
1970
+ ...defaultChoices,
1971
+ ...existingEnvironments.filter((env) => !defaultChoices.some((choice) => choice.value === env)).map((env) => ({
1972
+ name: env,
1973
+ value: env
1974
+ }))
1975
+ ];
1976
+ const environment = await selectWithCustom({
1977
+ message: "Choose a name and purpose for the environment?",
1978
+ choices
1979
+ });
1980
+ let environment_type = "non-production";
1981
+ if (["development", "qa"].includes(environment)) {
1982
+ environment_type = "non-production";
1983
+ } else if (["staging", "production"].includes(environment)) {
1984
+ environment_type = "production";
1985
+ } else {
1986
+ environment_type = await select3({
1987
+ message: "Purpose for the environment?",
1988
+ choices: [
1851
1989
  {
1852
- name: "Staging (hosts PII data, no backups)",
1853
- value: "staging"
1990
+ name: "Development/Quality assurance/Testing (no PII data)",
1991
+ value: "non-production"
1854
1992
  },
1855
1993
  {
1856
- name: "Production (hosts PII data, requires frequent backups)",
1994
+ name: "Staging/Production (hosts PII data, requires frequent backups)",
1857
1995
  value: "production"
1858
1996
  }
1859
- ];
1860
- const choices = [
1861
- ...defaultChoices,
1862
- ...existingEnvironments.filter((env) => !defaultChoices.some((choice) => choice.value === env)).map((env) => ({
1863
- name: env,
1864
- value: env
1865
- }))
1866
- ];
1867
- const environment = await selectWithCustom({
1868
- message: "Choose a name and purpose for the environment?",
1869
- choices
1870
- });
1871
- let environment_type = "non-production";
1872
- if (["development", "qa"].includes(environment)) {
1873
- environment_type = "non-production";
1874
- } else if (["staging", "production"].includes(environment)) {
1875
- environment_type = "production";
1876
- } else {
1877
- environment_type = await select3({
1878
- message: "Purpose for the environment?",
1879
- choices: [
1880
- {
1881
- name: "Development/Quality assurance/Testing (no PII data)",
1882
- value: "non-production"
1883
- },
1884
- {
1885
- name: "Staging/Production (hosts PII data, requires frequent backups)",
1886
- value: "production"
1887
- }
1888
- ]
1889
- });
1890
- }
1891
- const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
1892
- if (!environment) {
1893
- process.exit(1);
1894
- }
1895
- import_dotenv2.default.config({
1896
- path: `${process.cwd()}/.env.${environment}`
1897
- });
1898
- await createEnvironment(
1899
- octokit,
1900
- environment,
1901
- githubOrganisation,
1902
- githubRepository
1903
- );
1904
- const repositoryId = await getRepositoryId(
1905
- octokit,
1906
- githubOrganisation,
1907
- githubRepository
1908
- );
1909
- const existingRepositorySecrets = await listRepositorySecrets(
1910
- octokit,
1911
- githubOrganisation,
1912
- githubRepository
1997
+ ]
1998
+ });
1999
+ }
2000
+ const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
2001
+ if (!environment) {
2002
+ process.exit(1);
2003
+ }
2004
+ await createEnvironment(
2005
+ octokit,
2006
+ environment,
2007
+ githubOrganisation,
2008
+ githubRepository
2009
+ );
2010
+ const repositoryId = await getRepositoryId(
2011
+ octokit,
2012
+ githubOrganisation,
2013
+ githubRepository
2014
+ );
2015
+ const existingRepositorySecrets = await listRepositorySecrets(
2016
+ octokit,
2017
+ githubOrganisation,
2018
+ githubRepository
2019
+ );
2020
+ const existingRepositoryVariables = await listRepositoryVariables(
2021
+ octokit,
2022
+ githubOrganisation,
2023
+ githubRepository
2024
+ );
2025
+ const existingEnvironmentVariables = await listEnvironmentVariables(
2026
+ octokit,
2027
+ repositoryId,
2028
+ environment
2029
+ );
2030
+ const existingEnvironmentSecrets = await listEnvironmentSecrets(
2031
+ octokit,
2032
+ githubOrganisation,
2033
+ repositoryId,
2034
+ environment
2035
+ );
2036
+ const existingValues = [
2037
+ ...existingEnvironmentVariables,
2038
+ ...existingRepositoryVariables,
2039
+ ...existingRepositorySecrets,
2040
+ ...existingEnvironmentSecrets
2041
+ ];
2042
+ if (existingEnvironmentVariables.length > 0 || existingEnvironmentSecrets.length > 0) {
2043
+ log(
2044
+ "\nEnvironment with the name",
2045
+ environment,
2046
+ "already exists in Github.",
2047
+ "\nFound",
2048
+ existingEnvironmentVariables.length,
2049
+ "existing variables and",
2050
+ existingEnvironmentSecrets.length,
2051
+ "secrets"
2052
+ );
2053
+ }
2054
+ if (environment_type === "production") {
2055
+ log(
2056
+ "\n",
2057
+ import_kleur4.default.yellow().bold(
2058
+ "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
2059
+ )
2060
+ );
2061
+ await promptAndStoreAnswer(githubOtherQuestions, existingValues);
2062
+ }
2063
+ log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2064
+ const existingTwoFaEnabled = findExistingValue(
2065
+ "TWO_FA_ENABLED",
2066
+ "VARIABLE",
2067
+ "ENVIRONMENT",
2068
+ existingValues
2069
+ );
2070
+ const twoFaDefault = process.env.TWO_FA_ENABLED || existingTwoFaEnabled?.value;
2071
+ const two_fa_enabled = await confirm2({
2072
+ message: "Enable two-factor authentication (2FA)? This should be enabled for any environment that hosts PII data.",
2073
+ default: twoFaDefault ? twoFaDefault === "true" : environment_type === "production"
2074
+ });
2075
+ if (!two_fa_enabled && ["production", "staging"].includes(environment_type)) {
2076
+ warn(
2077
+ "2FA is disabled on a production-like environment. Logins will accept the fixed test code 000000, exposing real citizen data. Only do this if you know what you are doing."
2078
+ );
2079
+ }
2080
+ log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2081
+ await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2082
+ log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2083
+ const infrastructure = await promptAndStoreAnswer(
2084
+ infrastructureQuestions,
2085
+ existingValues
2086
+ );
2087
+ const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
2088
+ log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
2089
+ const users = await manageUsers(getEnvironmentInventoryPath(environment));
2090
+ log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
2091
+ const sslCertExists = findExistingValue(
2092
+ "SSL_CRT",
2093
+ "SECRET",
2094
+ "ENVIRONMENT",
2095
+ existingValues
2096
+ );
2097
+ let ssl_answers = [];
2098
+ const traefikConfOption = (await (0, import_prompts2.default)([
2099
+ {
2100
+ name: "traefikConfOption",
2101
+ type: "select",
2102
+ message: "Choose option to configure Traefik SSL Certificate",
2103
+ choices: [
2104
+ { title: "Let's Encrypt certificate", value: "lets_encrypt" },
2105
+ { title: "Static SSL certificate", value: "static_ssl" },
2106
+ { title: "Custom configuration", value: "custom" }
2107
+ ],
2108
+ initial: sslCertExists ? 1 : 0
2109
+ }
2110
+ ])).traefikConfOption;
2111
+ if (traefikConfOption === "static_ssl") {
2112
+ ssl_answers = await askQuestionWithEditor(
2113
+ staticSSLCertQuestions,
2114
+ existingEnvironmentSecrets
2115
+ );
2116
+ }
2117
+ log("\n", import_kleur4.default.bold().underline("Storage"), "\n");
2118
+ let enableEncryption = false;
2119
+ const encryption_key_defined = findExistingValue(
2120
+ "ENCRYPTION_KEY",
2121
+ "SECRET",
2122
+ "ENVIRONMENT",
2123
+ existingValues
2124
+ );
2125
+ if (!encryption_key_defined && !environment_exists) {
2126
+ const answers_enable_encryption = await (0, import_prompts2.default)(
2127
+ [
2128
+ {
2129
+ name: "enableEncryption",
2130
+ type: "confirm",
2131
+ message: "Do you want to enable disk encryption?",
2132
+ scope: "ENVIRONMENT",
2133
+ initial: Boolean(process.env.ENABLE_ENCRYPTION)
2134
+ }
2135
+ ].map(questionToPrompt)
2136
+ );
2137
+ enableEncryption = answers_enable_encryption.enableEncryption;
2138
+ }
2139
+ if (enableEncryption && !encryption_key_defined && !environment_exists) {
2140
+ log(
2141
+ import_kleur4.default.bold().green("\u2714"),
2142
+ import_kleur4.default.bold().yellow(" Disk encryption is enabled")
2143
+ );
2144
+ await promptAndStoreAnswer(diskQuestions, existingValues);
2145
+ } else {
2146
+ if (!enableEncryption && !encryption_key_defined && environment_exists) {
2147
+ log(
2148
+ import_kleur4.default.bold().green("\u2714"),
2149
+ import_kleur4.default.bold().grey(
2150
+ `Environment ${environment} is already configured, skipping disk encryption question`
2151
+ )
1913
2152
  );
1914
- const existingRepositoryVariables = await listRepositoryVariables(
1915
- octokit,
1916
- githubOrganisation,
1917
- githubRepository
2153
+ }
2154
+ const DISK_SPACE = findExistingValue(
2155
+ "DISK_SPACE",
2156
+ "VARIABLE",
2157
+ "ENVIRONMENT",
2158
+ existingValues
2159
+ );
2160
+ if (!DISK_SPACE) {
2161
+ log(
2162
+ import_kleur4.default.bold().green("\u2714"),
2163
+ import_kleur4.default.bold().grey("All available disk space at /data will be used")
1918
2164
  );
1919
- const existingEnvironmentVariables = await listEnvironmentVariables(
1920
- octokit,
1921
- repositoryId,
1922
- environment
2165
+ } else {
2166
+ log(
2167
+ import_kleur4.default.bold().green("\u2714"),
2168
+ import_kleur4.default.bold().yellow("Variable DISK_SPACE is read-only, allocated space:"),
2169
+ DISK_SPACE?.value
1923
2170
  );
1924
- const existingEnvironmentSecrets = await listEnvironmentSecrets(
1925
- octokit,
1926
- githubOrganisation,
1927
- repositoryId,
1928
- environment
2171
+ }
2172
+ }
2173
+ let backupHost = findExistingValue("BACKUP_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2174
+ let backupType = "";
2175
+ let restoreEnvironmentName = findExistingValue(
2176
+ "RESTORE_ENVIRONMENT_NAME",
2177
+ "VARIABLE",
2178
+ "ENVIRONMENT",
2179
+ existingValues
2180
+ )?.value;
2181
+ let restoreHost = findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2182
+ let restoreType = findExistingValue(
2183
+ "RESTORE_ENVIRONMENT_MODE",
2184
+ "VARIABLE",
2185
+ "ENVIRONMENT",
2186
+ existingValues
2187
+ )?.value || process.env.RESTORE_ENVIRONMENT_MODE || "dump";
2188
+ log("\n", import_kleur4.default.bold().underline("Backup"));
2189
+ let configureBackup = backupHost ? true : false;
2190
+ if (!configureBackup && !restoreEnvironmentName) {
2191
+ configureBackup = await confirm2({
2192
+ message: "Do you want to configure backup?",
2193
+ default: Boolean(process.env.CONFIGURE_BACKUP)
2194
+ });
2195
+ }
2196
+ let backupHostPrivateKey = "";
2197
+ let backupHostPublicKey = "";
2198
+ if (configureBackup) {
2199
+ const backupAnswers = await promptAndStoreAnswer(
2200
+ backupQuestions,
2201
+ existingValues
2202
+ );
2203
+ const backupHostPrivateKeyExists = findExistingValue(
2204
+ "BACKUP_HOST_PRIVATE_KEY",
2205
+ "SECRET",
2206
+ "ENVIRONMENT",
2207
+ existingValues
2208
+ );
2209
+ backupType = backupAnswers.backupType;
2210
+ backupHost = backupAnswers.backupHost || backupHost;
2211
+ if (!backupHostPrivateKeyExists) {
2212
+ const { publicKey, privateKey } = generateSSHKeyPair();
2213
+ backupHostPublicKey = publicKey;
2214
+ backupHostPrivateKey = privateKey;
2215
+ log(
2216
+ import_kleur4.default.bold().green("\u2714"),
2217
+ import_kleur4.default.bold().yellow(`Generated new SSH key pair for backup host: ${backupHost}`)
1929
2218
  );
1930
- const existingValues = [
1931
- ...existingEnvironmentVariables,
1932
- ...existingRepositoryVariables,
1933
- ...existingRepositorySecrets,
1934
- ...existingEnvironmentSecrets
1935
- ];
1936
- if (existingEnvironmentVariables.length > 0 || existingEnvironmentSecrets.length > 0) {
1937
- log(
1938
- "\nEnvironment with the name",
1939
- environment,
1940
- "already exists in Github.",
1941
- "\nFound",
1942
- existingEnvironmentVariables.length,
1943
- "existing variables and",
1944
- existingEnvironmentSecrets.length,
1945
- "secrets"
1946
- );
1947
- }
1948
- if (environment_type === "production") {
1949
- log(
1950
- "\n",
1951
- import_kleur4.default.yellow().bold(
1952
- "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
1953
- )
1954
- );
1955
- await promptAndStoreAnswer(
1956
- environment,
1957
- githubOtherQuestions,
1958
- existingValues
1959
- );
2219
+ }
2220
+ } else {
2221
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Backup is disabled"));
2222
+ }
2223
+ log("\n", import_kleur4.default.bold().underline("Restore"));
2224
+ let configureRestore = restoreEnvironmentName ? true : false;
2225
+ if (!restoreEnvironmentName && !configureBackup) {
2226
+ configureRestore = await confirm2({
2227
+ message: "Do you want to configure restore?",
2228
+ default: Boolean(process.env.CONFIGURE_RESTORE)
2229
+ });
2230
+ }
2231
+ if (configureRestore) {
2232
+ const env_list_filtered = existingEnvironments.filter(
2233
+ (env) => env !== environment
2234
+ );
2235
+ restoreEnvironmentName = await selectWithCustom({
2236
+ message: "What is the name of your environment to restore?",
2237
+ choices: env_list_filtered.map((env) => ({
2238
+ name: env,
2239
+ value: env
2240
+ })),
2241
+ initial: restoreEnvironmentName
2242
+ });
2243
+ restoreType = await select3({
2244
+ message: `Select ${import_kleur4.default.yellow().bold(restoreEnvironmentName)} environment backup mode`,
2245
+ default: restoreType,
2246
+ choices: [
2247
+ {
2248
+ name: "Full dump (daily full database backup)",
2249
+ value: "dump"
2250
+ },
2251
+ {
2252
+ name: "Differential (weekly full, daily diff backup)",
2253
+ value: "differential"
2254
+ }
2255
+ ]
2256
+ });
2257
+ restoreHost = await input3({
2258
+ message: "What is the host/IP address of the restore backup server?",
2259
+ default: restoreHost
2260
+ });
2261
+ } else {
2262
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2263
+ }
2264
+ log("\n", import_kleur4.default.bold().underline("Monitoring"));
2265
+ await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2266
+ const sentryDSNExists = findExistingValue(
2267
+ "SENTRY_DSN",
2268
+ "SECRET",
2269
+ "ENVIRONMENT",
2270
+ existingValues
2271
+ );
2272
+ log("\n", import_kleur4.default.bold().underline("Sentry"));
2273
+ if (sentryDSNExists) {
2274
+ await promptAndStoreAnswer(sentryQuestions, existingValues);
2275
+ } else {
2276
+ const { useSentry } = await (0, import_prompts2.default)([
2277
+ {
2278
+ name: "useSentry",
2279
+ type: "confirm",
2280
+ message: "Do you want to use Sentry?",
2281
+ initial: Boolean(process.env.SENTRY_DNS)
1960
2282
  }
1961
- log("\n", import_kleur4.default.bold().underline("Docker Hub"));
1962
- await promptAndStoreAnswer(environment, dockerhubQuestions, existingValues);
1963
- log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
1964
- const infrastructure = await promptAndStoreAnswer(
1965
- environment,
1966
- infrastructureQuestions,
2283
+ ]);
2284
+ if (useSentry) {
2285
+ await promptAndStoreAnswer(sentryQuestions, existingValues);
2286
+ }
2287
+ }
2288
+ log("\n", import_kleur4.default.bold().underline("METABASE ADMIN"));
2289
+ await promptAndStoreAnswer(metabaseAdminQuestions, existingValues);
2290
+ log("\n", import_kleur4.default.bold().underline("SMTP"));
2291
+ await promptAndStoreAnswer(emailQuestions, existingValues);
2292
+ const allAnswers = ALL_ANSWERS.reduce((acc, answer) => {
2293
+ return { ...acc, ...answer };
2294
+ });
2295
+ const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2296
+ function findExistingOrDefine(name, type, scope, newValue) {
2297
+ return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2298
+ }
2299
+ const derivedUpdates = [
2300
+ {
2301
+ name: "GH_ENCRYPTION_PASSWORD",
2302
+ type: "SECRET",
2303
+ didExist: findExistingValue(
2304
+ "GH_ENCRYPTION_PASSWORD",
2305
+ "SECRET",
2306
+ "REPOSITORY",
1967
2307
  existingValues
1968
- );
1969
- const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1970
- log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1971
- const users = await manageUsers(getEnvironmentInventoryPath(environment));
1972
- log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1973
- const sslCertExists = findExistingValue(
1974
- "SSL_CRT",
2308
+ ),
2309
+ value: findExistingOrDefine(
2310
+ "GH_ENCRYPTION_PASSWORD",
2311
+ "SECRET",
2312
+ "REPOSITORY",
2313
+ generateLongPassword()
2314
+ ),
2315
+ scope: "REPOSITORY"
2316
+ }
2317
+ ];
2318
+ derivedUpdates.push({
2319
+ name: "NOTIFICATION_TRANSPORT",
2320
+ type: "VARIABLE",
2321
+ didExist: findExistingValue(
2322
+ "NOTIFICATION_TRANSPORT",
2323
+ "VARIABLE",
2324
+ "ENVIRONMENT",
2325
+ existingValues
2326
+ ),
2327
+ value: findExistingOrDefine(
2328
+ "NOTIFICATION_TRANSPORT",
2329
+ "VARIABLE",
2330
+ "ENVIRONMENT",
2331
+ "email"
2332
+ ),
2333
+ scope: "ENVIRONMENT"
2334
+ });
2335
+ derivedUpdates.push({
2336
+ name: "TWO_FA_ENABLED",
2337
+ type: "VARIABLE",
2338
+ didExist: existingTwoFaEnabled,
2339
+ // Always stored, so the next run defaults to the current answer
2340
+ value: two_fa_enabled ? "true" : "false",
2341
+ scope: "ENVIRONMENT"
2342
+ });
2343
+ derivedUpdates.push(...ssl_answers);
2344
+ if (configureBackup) {
2345
+ derivedUpdates.push({
2346
+ name: "BACKUP_ENCRYPTION_PASSPHRASE",
2347
+ type: "SECRET",
2348
+ didExist: findExistingValue(
2349
+ "BACKUP_ENCRYPTION_PASSPHRASE",
1975
2350
  "SECRET",
1976
2351
  "ENVIRONMENT",
1977
2352
  existingValues
1978
- );
1979
- let ssl_answers = [];
1980
- const traefikConfOption = (await (0, import_prompts2.default)([
1981
- {
1982
- name: "traefikConfOption",
1983
- type: "select",
1984
- message: "Choose option to configure Traefik SSL Certificate",
1985
- choices: [
1986
- { title: "Let's Encrypt certificate", value: "lets_encrypt" },
1987
- { title: "Static SSL certificate", value: "static_ssl" },
1988
- { title: "Custom configuration", value: "custom" }
1989
- ],
1990
- initial: sslCertExists ? 1 : 0
1991
- }
1992
- ])).traefikConfOption;
1993
- if (traefikConfOption === "static_ssl") {
1994
- ssl_answers = await askQuestionWithEditor(
1995
- staticSSLCertQuestions,
1996
- existingEnvironmentSecrets
1997
- );
1998
- }
1999
- log("\n", import_kleur4.default.bold().underline("Storage"), "\n");
2000
- let enableEncryption = false;
2001
- const encryption_key_defined = findExistingValue(
2002
- "ENCRYPTION_KEY",
2353
+ ),
2354
+ value: findExistingOrDefine(
2355
+ "BACKUP_ENCRYPTION_PASSPHRASE",
2356
+ "SECRET",
2357
+ "ENVIRONMENT",
2358
+ generateLongPassword()
2359
+ ),
2360
+ scope: "ENVIRONMENT"
2361
+ });
2362
+ }
2363
+ const applicationServerUpdates = [
2364
+ {
2365
+ name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
2366
+ type: "SECRET",
2367
+ didExist: findExistingValue(
2368
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2003
2369
  "SECRET",
2004
2370
  "ENVIRONMENT",
2005
2371
  existingValues
2006
- );
2007
- if (!encryption_key_defined && !environment_exists) {
2008
- const answers_enable_encryption = await (0, import_prompts2.default)(
2009
- [
2010
- {
2011
- name: "enableEncryption",
2012
- type: "confirm",
2013
- message: "Do you want to enable disk encryption?",
2014
- scope: "ENVIRONMENT",
2015
- initial: Boolean(process.env.ENABLE_ENCRYPTION)
2016
- }
2017
- ].map(questionToPrompt)
2018
- );
2019
- enableEncryption = answers_enable_encryption.enableEncryption;
2020
- }
2021
- if (enableEncryption && !encryption_key_defined && !environment_exists) {
2022
- log(
2023
- import_kleur4.default.bold().green("\u2714"),
2024
- import_kleur4.default.bold().yellow(" Disk encryption is enabled")
2025
- );
2026
- await promptAndStoreAnswer(environment, diskQuestions, existingValues);
2027
- } else {
2028
- if (!enableEncryption && !encryption_key_defined && environment_exists) {
2029
- log(
2030
- import_kleur4.default.bold().green("\u2714"),
2031
- import_kleur4.default.bold().grey(
2032
- `Environment ${environment} is already configured, skipping disk encryption question`
2033
- )
2034
- );
2035
- }
2036
- const DISK_SPACE = findExistingValue(
2037
- "DISK_SPACE",
2038
- "VARIABLE",
2039
- "ENVIRONMENT",
2040
- existingValues
2041
- );
2042
- if (!DISK_SPACE) {
2043
- log(
2044
- import_kleur4.default.bold().green("\u2714"),
2045
- import_kleur4.default.bold().grey("All available disk space at /data will be used")
2046
- );
2047
- } else {
2048
- log(
2049
- import_kleur4.default.bold().green("\u2714"),
2050
- import_kleur4.default.bold().yellow("Variable DISK_SPACE is read-only, allocated space:"),
2051
- DISK_SPACE?.value
2052
- );
2053
- }
2054
- }
2055
- let backupHost = findExistingValue("BACKUP_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2056
- let backupType = "";
2057
- let restoreEnvironmentName = findExistingValue(
2058
- "RESTORE_ENVIRONMENT_NAME",
2372
+ ),
2373
+ value: findExistingOrDefine(
2374
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2375
+ "SECRET",
2376
+ "ENVIRONMENT",
2377
+ generateLongPassword()
2378
+ ),
2379
+ scope: "ENVIRONMENT"
2380
+ },
2381
+ {
2382
+ name: "KIBANA_SYSTEM_PASSWORD",
2383
+ type: "SECRET",
2384
+ didExist: findExistingValue(
2385
+ "KIBANA_SYSTEM_PASSWORD",
2386
+ "SECRET",
2387
+ "ENVIRONMENT",
2388
+ existingValues
2389
+ ),
2390
+ value: findExistingOrDefine(
2391
+ "KIBANA_SYSTEM_PASSWORD",
2392
+ "SECRET",
2393
+ "ENVIRONMENT",
2394
+ generateLongPassword()
2395
+ ),
2396
+ scope: "ENVIRONMENT"
2397
+ },
2398
+ {
2399
+ name: "MINIO_ROOT_USER",
2400
+ type: "SECRET",
2401
+ didExist: findExistingValue(
2402
+ "MINIO_ROOT_USER",
2403
+ "SECRET",
2404
+ "ENVIRONMENT",
2405
+ existingValues
2406
+ ),
2407
+ value: findExistingOrDefine(
2408
+ "MINIO_ROOT_USER",
2409
+ "SECRET",
2410
+ "ENVIRONMENT",
2411
+ generateLongPassword()
2412
+ ),
2413
+ scope: "ENVIRONMENT"
2414
+ },
2415
+ {
2416
+ name: "MINIO_ROOT_PASSWORD",
2417
+ type: "SECRET",
2418
+ didExist: findExistingValue(
2419
+ "MINIO_ROOT_PASSWORD",
2420
+ "SECRET",
2421
+ "ENVIRONMENT",
2422
+ existingValues
2423
+ ),
2424
+ value: findExistingOrDefine(
2425
+ "MINIO_ROOT_PASSWORD",
2426
+ "SECRET",
2427
+ "ENVIRONMENT",
2428
+ generateLongPassword()
2429
+ ),
2430
+ scope: "ENVIRONMENT"
2431
+ },
2432
+ {
2433
+ name: "POSTGRES_USER",
2434
+ type: "SECRET",
2435
+ didExist: findExistingValue(
2436
+ "POSTGRES_USER",
2437
+ "SECRET",
2438
+ "ENVIRONMENT",
2439
+ existingValues
2440
+ ),
2441
+ value: findExistingOrDefine(
2442
+ "POSTGRES_USER",
2443
+ "SECRET",
2444
+ "ENVIRONMENT",
2445
+ generateLongPassword()
2446
+ ),
2447
+ scope: "ENVIRONMENT"
2448
+ },
2449
+ {
2450
+ name: "POSTGRES_PASSWORD",
2451
+ type: "SECRET",
2452
+ didExist: findExistingValue(
2453
+ "POSTGRES_PASSWORD",
2454
+ "SECRET",
2455
+ "ENVIRONMENT",
2456
+ existingValues
2457
+ ),
2458
+ value: findExistingOrDefine(
2459
+ "POSTGRES_PASSWORD",
2460
+ "SECRET",
2461
+ "ENVIRONMENT",
2462
+ generateLongPassword()
2463
+ ),
2464
+ scope: "ENVIRONMENT"
2465
+ },
2466
+ {
2467
+ name: "SUPER_USER_PASSWORD",
2468
+ type: "SECRET",
2469
+ didExist: findExistingValue(
2470
+ "SUPER_USER_PASSWORD",
2471
+ "SECRET",
2472
+ "ENVIRONMENT",
2473
+ existingValues
2474
+ ),
2475
+ value: findExistingOrDefine(
2476
+ "SUPER_USER_PASSWORD",
2477
+ "SECRET",
2478
+ "ENVIRONMENT",
2479
+ generateLongPassword()
2480
+ ),
2481
+ scope: "ENVIRONMENT"
2482
+ },
2483
+ {
2484
+ type: "VARIABLE",
2485
+ name: "ACTIVATE_USERS",
2486
+ value: "production" === environment_type ? "false" : "true",
2487
+ didExist: findExistingValue(
2488
+ "ACTIVATE_USERS",
2059
2489
  "VARIABLE",
2060
2490
  "ENVIRONMENT",
2061
2491
  existingValues
2062
- )?.value;
2063
- let restoreType = findExistingValue(
2064
- "RESTORE_ENVIRONMENT_MODE",
2492
+ ),
2493
+ scope: "ENVIRONMENT"
2494
+ },
2495
+ {
2496
+ type: "VARIABLE",
2497
+ name: "COUNTRY_CONFIG_HOST",
2498
+ value: answerOrExisting(
2499
+ allAnswers.domain,
2500
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2501
+ (val) => `https://countryconfig.${val}`
2502
+ ),
2503
+ didExist: findExistingValue(
2504
+ "COUNTRY_CONFIG_HOST",
2065
2505
  "VARIABLE",
2066
2506
  "ENVIRONMENT",
2067
2507
  existingValues
2068
- )?.value || process.env.RESTORE_ENVIRONMENT_MODE || "dump";
2069
- log("\n", import_kleur4.default.bold().underline("Backup"));
2070
- let configureBackup = backupHost ? true : false;
2071
- if (!configureBackup && !restoreEnvironmentName) {
2072
- configureBackup = await confirm2({
2073
- message: "Do you want to configure backup?",
2074
- default: Boolean(process.env.CONFIGURE_BACKUP)
2075
- });
2076
- }
2077
- let backupHostPrivateKey = "";
2078
- let backupHostPublicKey = "";
2079
- if (configureBackup) {
2080
- const backupAnswers = await promptAndStoreAnswer(
2081
- environment,
2082
- backupQuestions,
2083
- existingValues
2084
- );
2085
- const backupHostPrivateKeyExists = findExistingValue(
2086
- "BACKUP_HOST_PRIVATE_KEY",
2087
- "SECRET",
2088
- "ENVIRONMENT",
2089
- existingValues
2090
- );
2091
- backupType = backupAnswers.backupType;
2092
- backupHost = backupAnswers.backupHost || backupHost;
2093
- if (!backupHostPrivateKeyExists) {
2094
- const { publicKey, privateKey } = generateSSHKeyPair();
2095
- backupHostPublicKey = publicKey;
2096
- backupHostPrivateKey = privateKey;
2097
- log(
2098
- import_kleur4.default.bold().green("\u2714"),
2099
- import_kleur4.default.bold().yellow(`Generated new SSH key pair for backup host: ${backupHost}`)
2100
- );
2101
- }
2102
- } else {
2103
- log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Backup is disabled"));
2104
- }
2105
- log("\n", import_kleur4.default.bold().underline("Restore"));
2106
- let configureRestore = restoreEnvironmentName ? true : false;
2107
- if (!restoreEnvironmentName && !configureBackup) {
2108
- configureRestore = await confirm2({
2109
- message: "Do you want to configure restore?",
2110
- default: Boolean(process.env.CONFIGURE_RESTORE)
2111
- });
2112
- }
2113
- if (configureRestore) {
2114
- const env_list_filtered = existingEnvironments.filter(
2115
- (env) => env !== environment
2116
- );
2117
- restoreEnvironmentName = await selectWithCustom({
2118
- message: "What is the name of your environment to restore?",
2119
- choices: env_list_filtered.map((env) => ({
2120
- name: env,
2121
- value: env
2122
- })),
2123
- initial: restoreEnvironmentName
2124
- });
2125
- restoreType = await select3({
2126
- message: `Select ${import_kleur4.default.yellow().bold(restoreEnvironmentName)} environment backup mode`,
2127
- choices: [
2128
- {
2129
- name: "Full dump (daily full database backup)",
2130
- value: "dump"
2131
- },
2132
- {
2133
- name: "Differential (weekly full, daily diff backup)",
2134
- value: "differential"
2135
- }
2136
- ]
2137
- });
2138
- } else {
2139
- log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2140
- }
2141
- log("\n", import_kleur4.default.bold().underline("Monitoring"));
2142
- await promptAndStoreAnswer(
2143
- environment,
2144
- databaseAndMonitoringQuestions,
2508
+ ),
2509
+ scope: "ENVIRONMENT"
2510
+ },
2511
+ {
2512
+ type: "VARIABLE",
2513
+ name: "GATEWAY_HOST",
2514
+ value: answerOrExisting(
2515
+ allAnswers.domain,
2516
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2517
+ (val) => `https://gateway.${val}`
2518
+ ),
2519
+ didExist: findExistingValue(
2520
+ "GATEWAY_HOST",
2521
+ "VARIABLE",
2522
+ "ENVIRONMENT",
2145
2523
  existingValues
2146
- );
2147
- const sentryDSNExists = findExistingValue(
2148
- "SENTRY_DSN",
2149
- "SECRET",
2524
+ ),
2525
+ scope: "ENVIRONMENT"
2526
+ },
2527
+ {
2528
+ type: "VARIABLE",
2529
+ name: "CONTENT_SECURITY_POLICY_WILDCARD",
2530
+ value: answerOrExisting(
2531
+ allAnswers.domain,
2532
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2533
+ (val) => `*.${val}`
2534
+ ),
2535
+ didExist: findExistingValue(
2536
+ "CONTENT_SECURITY_POLICY_WILDCARD",
2537
+ "VARIABLE",
2150
2538
  "ENVIRONMENT",
2151
2539
  existingValues
2152
- );
2153
- log("\n", import_kleur4.default.bold().underline("Sentry"));
2154
- if (sentryDSNExists) {
2155
- await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2156
- } else {
2157
- const { useSentry } = await (0, import_prompts2.default)([
2158
- {
2159
- name: "useSentry",
2160
- type: "confirm",
2161
- message: "Do you want to use Sentry?",
2162
- initial: Boolean(process.env.SENTRY_DNS)
2163
- }
2164
- ]);
2165
- if (useSentry) {
2166
- await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2167
- }
2168
- }
2169
- log("\n", import_kleur4.default.bold().underline("METABASE ADMIN"));
2170
- await promptAndStoreAnswer(
2171
- environment,
2172
- metabaseAdminQuestions,
2540
+ ),
2541
+ scope: "ENVIRONMENT"
2542
+ },
2543
+ {
2544
+ type: "VARIABLE",
2545
+ name: "CLIENT_APP_URL",
2546
+ value: answerOrExisting(
2547
+ allAnswers.domain,
2548
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2549
+ (val) => `https://register.${val}`
2550
+ ),
2551
+ didExist: findExistingValue(
2552
+ "CLIENT_APP_URL",
2553
+ "VARIABLE",
2554
+ "ENVIRONMENT",
2173
2555
  existingValues
2174
- );
2175
- log("\n", import_kleur4.default.bold().underline("SMTP"));
2176
- await promptAndStoreAnswer(environment, emailQuestions, existingValues);
2177
- const allAnswers = ALL_ANSWERS.reduce((acc, answer) => {
2178
- return { ...acc, ...answer };
2179
- });
2180
- const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2181
- function findExistingOrDefine(name, type, scope, newValue) {
2182
- return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2183
- }
2184
- const derivedUpdates = [
2185
- {
2186
- name: "GH_ENCRYPTION_PASSWORD",
2187
- type: "SECRET",
2188
- didExist: findExistingValue(
2189
- "GH_ENCRYPTION_PASSWORD",
2190
- "SECRET",
2191
- "REPOSITORY",
2192
- existingValues
2193
- ),
2194
- value: findExistingOrDefine(
2195
- "GH_ENCRYPTION_PASSWORD",
2196
- "SECRET",
2197
- "REPOSITORY",
2198
- generateLongPassword()
2199
- ),
2200
- scope: "REPOSITORY"
2201
- }
2202
- ];
2203
- derivedUpdates.push({
2204
- name: "NOTIFICATION_TRANSPORT",
2205
- type: "VARIABLE",
2206
- didExist: findExistingValue(
2207
- "NOTIFICATION_TRANSPORT",
2556
+ ),
2557
+ scope: "ENVIRONMENT"
2558
+ },
2559
+ {
2560
+ type: "VARIABLE",
2561
+ name: "LOGIN_URL",
2562
+ value: answerOrExisting(
2563
+ allAnswers.domain,
2564
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2565
+ (val) => `https://login.${val}`
2566
+ ),
2567
+ didExist: findExistingValue(
2568
+ "LOGIN_URL",
2569
+ "VARIABLE",
2570
+ "ENVIRONMENT",
2571
+ existingValues
2572
+ ),
2573
+ scope: "ENVIRONMENT"
2574
+ },
2575
+ {
2576
+ type: "VARIABLE",
2577
+ name: "RESTORE_ENVIRONMENT_NAME",
2578
+ value: answerOrExisting(
2579
+ restoreEnvironmentName,
2580
+ findExistingValue(
2581
+ "RESTORE_ENVIRONMENT_NAME",
2208
2582
  "VARIABLE",
2209
2583
  "ENVIRONMENT",
2210
2584
  existingValues
2211
2585
  ),
2212
- value: findExistingOrDefine(
2213
- "NOTIFICATION_TRANSPORT",
2586
+ (val) => val || ""
2587
+ ),
2588
+ didExist: findExistingValue(
2589
+ "RESTORE_ENVIRONMENT_NAME",
2590
+ "VARIABLE",
2591
+ "ENVIRONMENT",
2592
+ existingValues
2593
+ ),
2594
+ scope: "ENVIRONMENT"
2595
+ },
2596
+ {
2597
+ type: "VARIABLE",
2598
+ name: "RESTORE_HOST",
2599
+ value: answerOrExisting(
2600
+ restoreHost,
2601
+ findExistingValue(
2602
+ "RESTORE_HOST",
2214
2603
  "VARIABLE",
2215
2604
  "ENVIRONMENT",
2216
- "email"
2605
+ existingValues
2217
2606
  ),
2218
- scope: "ENVIRONMENT"
2219
- });
2220
- derivedUpdates.push(...ssl_answers);
2221
- if (configureBackup) {
2222
- derivedUpdates.push({
2223
- name: "BACKUP_ENCRYPTION_PASSPHRASE",
2224
- type: "SECRET",
2225
- didExist: findExistingValue(
2226
- "BACKUP_ENCRYPTION_PASSPHRASE",
2227
- "SECRET",
2228
- "ENVIRONMENT",
2229
- existingValues
2230
- ),
2231
- value: findExistingOrDefine(
2232
- "BACKUP_ENCRYPTION_PASSPHRASE",
2233
- "SECRET",
2234
- "ENVIRONMENT",
2235
- generateLongPassword()
2236
- ),
2237
- scope: "ENVIRONMENT"
2238
- });
2239
- }
2240
- const applicationServerUpdates = [
2241
- {
2242
- name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
2243
- type: "SECRET",
2244
- didExist: findExistingValue(
2245
- "ELASTICSEARCH_SUPERUSER_PASSWORD",
2246
- "SECRET",
2247
- "ENVIRONMENT",
2248
- existingValues
2249
- ),
2250
- value: findExistingOrDefine(
2251
- "ELASTICSEARCH_SUPERUSER_PASSWORD",
2252
- "SECRET",
2253
- "ENVIRONMENT",
2254
- generateLongPassword()
2255
- ),
2256
- scope: "ENVIRONMENT"
2257
- },
2258
- {
2259
- name: "KIBANA_SYSTEM_PASSWORD",
2260
- type: "SECRET",
2261
- didExist: findExistingValue(
2262
- "KIBANA_SYSTEM_PASSWORD",
2263
- "SECRET",
2264
- "ENVIRONMENT",
2265
- existingValues
2266
- ),
2267
- value: findExistingOrDefine(
2268
- "KIBANA_SYSTEM_PASSWORD",
2269
- "SECRET",
2270
- "ENVIRONMENT",
2271
- generateLongPassword()
2272
- ),
2273
- scope: "ENVIRONMENT"
2274
- },
2275
- {
2276
- name: "MINIO_ROOT_USER",
2277
- type: "SECRET",
2278
- didExist: findExistingValue(
2279
- "MINIO_ROOT_USER",
2280
- "SECRET",
2281
- "ENVIRONMENT",
2282
- existingValues
2283
- ),
2284
- value: findExistingOrDefine(
2285
- "MINIO_ROOT_USER",
2286
- "SECRET",
2287
- "ENVIRONMENT",
2288
- generateLongPassword()
2289
- ),
2290
- scope: "ENVIRONMENT"
2291
- },
2292
- {
2293
- name: "MINIO_ROOT_PASSWORD",
2294
- type: "SECRET",
2295
- didExist: findExistingValue(
2296
- "MINIO_ROOT_PASSWORD",
2297
- "SECRET",
2298
- "ENVIRONMENT",
2299
- existingValues
2300
- ),
2301
- value: findExistingOrDefine(
2302
- "MINIO_ROOT_PASSWORD",
2303
- "SECRET",
2304
- "ENVIRONMENT",
2305
- generateLongPassword()
2306
- ),
2307
- scope: "ENVIRONMENT"
2308
- },
2309
- {
2310
- name: "POSTGRES_USER",
2311
- type: "SECRET",
2312
- didExist: findExistingValue(
2313
- "POSTGRES_USER",
2314
- "SECRET",
2315
- "ENVIRONMENT",
2316
- existingValues
2317
- ),
2318
- value: findExistingOrDefine(
2319
- "POSTGRES_USER",
2320
- "SECRET",
2321
- "ENVIRONMENT",
2322
- generateLongPassword()
2323
- ),
2324
- scope: "ENVIRONMENT"
2325
- },
2326
- {
2327
- name: "POSTGRES_PASSWORD",
2328
- type: "SECRET",
2329
- didExist: findExistingValue(
2330
- "POSTGRES_PASSWORD",
2331
- "SECRET",
2332
- "ENVIRONMENT",
2333
- existingValues
2334
- ),
2335
- value: findExistingOrDefine(
2336
- "POSTGRES_PASSWORD",
2337
- "SECRET",
2338
- "ENVIRONMENT",
2339
- generateLongPassword()
2340
- ),
2341
- scope: "ENVIRONMENT"
2342
- },
2343
- {
2344
- name: "SUPER_USER_PASSWORD",
2345
- type: "SECRET",
2346
- didExist: findExistingValue(
2347
- "SUPER_USER_PASSWORD",
2348
- "SECRET",
2349
- "ENVIRONMENT",
2350
- existingValues
2351
- ),
2352
- value: findExistingOrDefine(
2353
- "SUPER_USER_PASSWORD",
2354
- "SECRET",
2355
- "ENVIRONMENT",
2356
- generateLongPassword()
2357
- ),
2358
- scope: "ENVIRONMENT"
2359
- },
2360
- {
2361
- type: "VARIABLE",
2362
- name: "ACTIVATE_USERS",
2363
- value: "production" === environment_type ? "false" : "true",
2364
- didExist: findExistingValue(
2365
- "ACTIVATE_USERS",
2366
- "VARIABLE",
2367
- "ENVIRONMENT",
2368
- existingValues
2369
- ),
2370
- scope: "ENVIRONMENT"
2371
- },
2372
- {
2373
- type: "VARIABLE",
2374
- name: "COUNTRY_CONFIG_HOST",
2375
- value: answerOrExisting(
2376
- allAnswers.domain,
2377
- findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2378
- (val) => `https://countryconfig.${val}`
2379
- ),
2380
- didExist: findExistingValue(
2381
- "COUNTRY_CONFIG_HOST",
2382
- "VARIABLE",
2383
- "ENVIRONMENT",
2384
- existingValues
2385
- ),
2386
- scope: "ENVIRONMENT"
2387
- },
2388
- {
2389
- type: "VARIABLE",
2390
- name: "GATEWAY_HOST",
2391
- value: answerOrExisting(
2392
- allAnswers.domain,
2393
- findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2394
- (val) => `https://gateway.${val}`
2395
- ),
2396
- didExist: findExistingValue(
2397
- "GATEWAY_HOST",
2398
- "VARIABLE",
2399
- "ENVIRONMENT",
2400
- existingValues
2401
- ),
2402
- scope: "ENVIRONMENT"
2403
- },
2404
- {
2405
- type: "VARIABLE",
2406
- name: "CONTENT_SECURITY_POLICY_WILDCARD",
2407
- value: answerOrExisting(
2408
- allAnswers.domain,
2409
- findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2410
- (val) => `*.${val}`
2411
- ),
2412
- didExist: findExistingValue(
2413
- "CONTENT_SECURITY_POLICY_WILDCARD",
2414
- "VARIABLE",
2415
- "ENVIRONMENT",
2416
- existingValues
2417
- ),
2418
- scope: "ENVIRONMENT"
2419
- },
2420
- {
2421
- type: "VARIABLE",
2422
- name: "CLIENT_APP_URL",
2423
- value: answerOrExisting(
2424
- allAnswers.domain,
2425
- findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2426
- (val) => `https://register.${val}`
2427
- ),
2428
- didExist: findExistingValue(
2429
- "CLIENT_APP_URL",
2430
- "VARIABLE",
2431
- "ENVIRONMENT",
2432
- existingValues
2433
- ),
2434
- scope: "ENVIRONMENT"
2435
- },
2436
- {
2437
- type: "VARIABLE",
2438
- name: "LOGIN_URL",
2439
- value: answerOrExisting(
2440
- allAnswers.domain,
2441
- findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2442
- (val) => `https://login.${val}`
2443
- ),
2444
- didExist: findExistingValue(
2445
- "LOGIN_URL",
2446
- "VARIABLE",
2447
- "ENVIRONMENT",
2448
- existingValues
2449
- ),
2450
- scope: "ENVIRONMENT"
2451
- },
2452
- {
2453
- type: "VARIABLE",
2454
- name: "RESTORE_ENVIRONMENT_NAME",
2455
- value: answerOrExisting(
2456
- restoreEnvironmentName,
2457
- findExistingValue(
2458
- "RESTORE_ENVIRONMENT_NAME",
2459
- "VARIABLE",
2460
- "ENVIRONMENT",
2461
- existingValues
2462
- ),
2463
- (val) => val || ""
2464
- ),
2465
- didExist: findExistingValue(
2466
- "RESTORE_ENVIRONMENT_NAME",
2467
- "VARIABLE",
2468
- "ENVIRONMENT",
2469
- existingValues
2470
- ),
2471
- scope: "ENVIRONMENT"
2472
- }
2473
- ];
2474
- if (enableEncryption) {
2475
- applicationServerUpdates.push({
2476
- name: "ENCRYPTION_KEY",
2477
- type: "SECRET",
2478
- didExist: findExistingValue(
2479
- "ENCRYPTION_KEY",
2480
- "SECRET",
2481
- "ENVIRONMENT",
2482
- existingValues
2483
- ),
2484
- value: findExistingOrDefine(
2485
- "ENCRYPTION_KEY",
2486
- "SECRET",
2487
- "ENVIRONMENT",
2488
- generateLongPassword()
2489
- ),
2490
- scope: "ENVIRONMENT"
2491
- });
2492
- }
2493
- if (configureBackup && backupHostPrivateKey && backupHostPublicKey) {
2494
- applicationServerUpdates.push({
2495
- name: "BACKUP_HOST_PRIVATE_KEY",
2496
- type: "SECRET",
2497
- didExist: void 0,
2498
- value: backupHostPrivateKey,
2499
- scope: "ENVIRONMENT"
2500
- });
2501
- applicationServerUpdates.push({
2502
- name: "BACKUP_HOST_PUBLIC_KEY",
2503
- type: "SECRET",
2504
- didExist: void 0,
2505
- value: backupHostPublicKey,
2506
- scope: "ENVIRONMENT"
2507
- });
2508
- }
2509
- derivedUpdates.push(...applicationServerUpdates);
2510
- const updates = getAnswers(existingValues).concat(
2511
- ...derivedUpdates.filter(
2512
- (update) => update.value !== null
2513
- )
2514
- ).filter(
2515
- (variable) => Boolean(variable.value) && // Only update values that changed
2516
- (variable.type !== "VARIABLE" || variable.value !== variable.didExist?.value)
2517
- );
2518
- storeSecrets(environment, updates);
2519
- const newSecrets = updates.filter(
2520
- (update) => update.type === "SECRET" && !update.didExist
2521
- );
2522
- const updatedSecrets = updates.filter(
2523
- (update) => update.type === "SECRET" && Boolean(update.didExist)
2524
- );
2525
- const newVariables = updates.filter(
2526
- (update) => update.type === "VARIABLE" && !update.didExist
2527
- );
2528
- const updatedVariables = updates.filter(
2529
- (update) => update.type === "VARIABLE" && Boolean(update.didExist)
2530
- );
2531
- const unknownVariables = existingValues.filter((value) => {
2532
- return !ALL_QUESTIONS.find(
2533
- (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2534
- );
2535
- });
2536
- log("");
2537
- if (newSecrets.length > 0) {
2538
- log(
2539
- import_kleur4.default.yellow(
2540
- `The following secrets will be added to Github for environment ${environment}:`
2541
- )
2542
- );
2543
- newSecrets.filter(({ scope }) => scope === "ENVIRONMENT").forEach((secret) => {
2544
- log(secret.name, "=", secret.value);
2545
- });
2546
- log("");
2547
- log(
2548
- import_kleur4.default.yellow(`The following secrets will be added to Github repository:`)
2549
- );
2550
- newSecrets.filter(({ scope }) => scope === "REPOSITORY").forEach((secret) => {
2551
- log(secret.name, "=", secret.value);
2552
- });
2553
- log("");
2554
- }
2555
- if (updatedSecrets.length > 0) {
2556
- log(
2557
- import_kleur4.default.yellow(
2558
- `The following secrets will be updated in Github for environment ${environment}:`
2559
- )
2560
- );
2561
- updatedSecrets.forEach((secret) => {
2562
- log(secret.name, "=", secret.value);
2563
- });
2564
- log("");
2565
- }
2566
- if (newVariables.length > 0) {
2567
- log(
2568
- import_kleur4.default.yellow(
2569
- `The following variables will be added to Github for environment ${environment}:`
2570
- )
2571
- );
2572
- newVariables.forEach((variable) => {
2573
- log(variable.name, "=", variable.value);
2574
- });
2575
- log("");
2576
- }
2577
- if (updatedVariables.length > 0) {
2578
- log(
2579
- import_kleur4.default.yellow(
2580
- `The following variables will be updated in Github for environment ${environment}:`
2581
- )
2582
- );
2583
- updatedVariables.forEach((variable) => {
2584
- log(
2585
- variable.name,
2586
- "=",
2587
- variable.value,
2588
- `(was ${variable.didExist?.value})`
2589
- );
2590
- });
2591
- log("");
2592
- }
2593
- if (unknownVariables.length > 0) {
2594
- log(
2595
- import_kleur4.default.yellow(
2596
- `The following unknown variables/secrets were stored in Github are not managed by this script:`
2597
- )
2598
- );
2599
- log("");
2600
- log(import_kleur4.default.blue(`Repository:`));
2601
- unknownVariables.filter(({ scope }) => scope === "REPOSITORY").forEach((variable) => {
2602
- log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2603
- });
2604
- log("");
2605
- log(import_kleur4.default.blue(`Environment:`));
2606
- unknownVariables.filter(({ scope }) => scope === "ENVIRONMENT").forEach((variable) => {
2607
- log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2608
- });
2609
- log("");
2610
- log(
2611
- import_kleur4.default.yellow(
2612
- `These variables will not be updated by this script. If you want to update them, you will need to do so manually.`
2613
- )
2614
- );
2615
- log("");
2616
- }
2617
- if ([].concat(newSecrets).concat(updatedSecrets).concat(newVariables).concat(updatedVariables).length === 0) {
2618
- process.exit(0);
2619
- }
2620
- const saveChanges = await confirm2({
2621
- message: "Do you want to continue?",
2622
- default: true
2623
- });
2624
- if (!saveChanges) {
2625
- process.exit(0);
2626
- }
2627
- for (const newSecret of newSecrets) {
2628
- log(`Creating secret ${newSecret.name} with value ${newSecret.value}`);
2629
- if (newSecret.scope === "ENVIRONMENT") {
2630
- await createEnvironmentSecret(
2631
- octokit,
2632
- repositoryId,
2633
- environment,
2634
- newSecret.name,
2635
- newSecret.value,
2636
- githubOrganisation,
2637
- githubRepository
2638
- );
2639
- } else {
2640
- await createRepositorySecret(
2641
- octokit,
2642
- repositoryId,
2643
- newSecret.name,
2644
- newSecret.value,
2645
- githubOrganisation,
2646
- githubRepository
2647
- );
2648
- }
2649
- }
2650
- for (const updatedSecret of updatedSecrets) {
2651
- log(
2652
- `Updating secret ${updatedSecret.name} with value ${updatedSecret.value}`
2653
- );
2654
- if (updatedSecret.scope === "ENVIRONMENT") {
2655
- await createEnvironmentSecret(
2656
- octokit,
2657
- repositoryId,
2658
- environment,
2659
- updatedSecret.name,
2660
- updatedSecret.value,
2661
- githubOrganisation,
2662
- githubRepository
2663
- );
2664
- } else {
2665
- await createRepositorySecret(
2666
- octokit,
2667
- repositoryId,
2668
- updatedSecret.name,
2669
- updatedSecret.value,
2670
- githubOrganisation,
2671
- githubRepository
2672
- );
2673
- }
2674
- }
2675
- for (const newVariable of newVariables) {
2676
- log(`Creating variable ${newVariable.name} with value ${newVariable.value}`);
2677
- if (newVariable.scope === "ENVIRONMENT") {
2678
- await createEnvironmentVariable(
2679
- octokit,
2680
- repositoryId,
2681
- environment,
2682
- newVariable.name,
2683
- newVariable.value
2684
- );
2685
- } else {
2686
- await createRepositoryVariable(
2687
- octokit,
2688
- repositoryId,
2689
- newVariable.name,
2690
- newVariable.value
2691
- );
2692
- }
2693
- }
2694
- for (const updatedVariable of updatedVariables) {
2695
- log(
2696
- `Updating variable ${updatedVariable.name} with value ${updatedVariable.value}`
2697
- );
2698
- if (updatedVariable.scope === "ENVIRONMENT") {
2699
- await updateEnvironmentVariable(
2700
- octokit,
2701
- repositoryId,
2702
- environment,
2703
- updatedVariable.name,
2704
- updatedVariable.value
2705
- );
2706
- } else {
2707
- await updateRepositoryVariable(
2708
- octokit,
2709
- repositoryId,
2710
- updatedVariable.name,
2711
- updatedVariable.value
2712
- );
2713
- }
2714
- }
2607
+ (val) => val || ""
2608
+ ),
2609
+ didExist: findExistingValue(
2610
+ "RESTORE_HOST",
2611
+ "VARIABLE",
2612
+ "ENVIRONMENT",
2613
+ existingValues
2614
+ ),
2615
+ scope: "ENVIRONMENT"
2616
+ },
2617
+ {
2618
+ type: "VARIABLE",
2619
+ name: "RESTORE_ENVIRONMENT_MODE",
2620
+ // Only persist the mode when restore is configured
2621
+ value: restoreEnvironmentName ? restoreType : "",
2622
+ didExist: findExistingValue(
2623
+ "RESTORE_ENVIRONMENT_MODE",
2624
+ "VARIABLE",
2625
+ "ENVIRONMENT",
2626
+ existingValues
2627
+ ),
2628
+ scope: "ENVIRONMENT"
2629
+ }
2630
+ ];
2631
+ if (enableEncryption) {
2632
+ applicationServerUpdates.push({
2633
+ name: "ENCRYPTION_KEY",
2634
+ type: "SECRET",
2635
+ didExist: findExistingValue(
2636
+ "ENCRYPTION_KEY",
2637
+ "SECRET",
2638
+ "ENVIRONMENT",
2639
+ existingValues
2640
+ ),
2641
+ value: findExistingOrDefine(
2642
+ "ENCRYPTION_KEY",
2643
+ "SECRET",
2644
+ "ENVIRONMENT",
2645
+ generateLongPassword()
2646
+ ),
2647
+ scope: "ENVIRONMENT"
2648
+ });
2649
+ }
2650
+ if (configureBackup && backupHostPrivateKey && backupHostPublicKey) {
2651
+ applicationServerUpdates.push({
2652
+ name: "BACKUP_HOST_PRIVATE_KEY",
2653
+ type: "SECRET",
2654
+ didExist: void 0,
2655
+ value: backupHostPrivateKey,
2656
+ scope: "ENVIRONMENT"
2657
+ });
2658
+ applicationServerUpdates.push({
2659
+ name: "BACKUP_HOST_PUBLIC_KEY",
2660
+ type: "SECRET",
2661
+ didExist: void 0,
2662
+ value: backupHostPublicKey,
2663
+ scope: "ENVIRONMENT"
2664
+ });
2665
+ }
2666
+ derivedUpdates.push(...applicationServerUpdates);
2667
+ const updates = getAnswers(existingValues).concat(
2668
+ ...derivedUpdates.filter(
2669
+ (update) => update.value !== null
2670
+ )
2671
+ ).filter(
2672
+ (variable) => Boolean(variable.value) && // Only update values that changed
2673
+ (variable.type !== "VARIABLE" || variable.value !== variable.didExist?.value)
2674
+ );
2675
+ const newSecrets = updates.filter(
2676
+ (update) => update.type === "SECRET" && !update.didExist
2677
+ );
2678
+ const updatedSecrets = updates.filter(
2679
+ (update) => update.type === "SECRET" && Boolean(update.didExist)
2680
+ );
2681
+ const newVariables = updates.filter(
2682
+ (update) => update.type === "VARIABLE" && !update.didExist
2683
+ );
2684
+ const updatedVariables = updates.filter(
2685
+ (update) => update.type === "VARIABLE" && Boolean(update.didExist)
2686
+ );
2687
+ const unknownVariables = existingValues.filter((value) => {
2688
+ return !ALL_QUESTIONS.find(
2689
+ (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2690
+ );
2691
+ });
2692
+ log("");
2693
+ if (newSecrets.length > 0) {
2694
+ log(
2695
+ import_kleur4.default.yellow(
2696
+ `The following secrets will be added to Github for environment ${environment}:`
2697
+ )
2698
+ );
2699
+ newSecrets.filter(({ scope }) => scope === "ENVIRONMENT").forEach((secret) => {
2700
+ log(secret.name, "=", secret.value);
2701
+ });
2702
+ log("");
2703
+ log(
2704
+ import_kleur4.default.yellow(`The following secrets will be added to Github repository:`)
2705
+ );
2706
+ newSecrets.filter(({ scope }) => scope === "REPOSITORY").forEach((secret) => {
2707
+ log(secret.name, "=", secret.value);
2708
+ });
2709
+ log("");
2710
+ }
2711
+ if (updatedSecrets.length > 0) {
2712
+ log(
2713
+ import_kleur4.default.yellow(
2714
+ `The following secrets will be updated in Github for environment ${environment}:`
2715
+ )
2716
+ );
2717
+ updatedSecrets.forEach((secret) => {
2718
+ log(secret.name, "=", secret.value);
2719
+ });
2720
+ log("");
2721
+ }
2722
+ if (newVariables.length > 0) {
2723
+ log(
2724
+ import_kleur4.default.yellow(
2725
+ `The following variables will be added to Github for environment ${environment}:`
2726
+ )
2727
+ );
2728
+ newVariables.forEach((variable) => {
2729
+ log(variable.name, "=", variable.value);
2730
+ });
2731
+ log("");
2732
+ }
2733
+ if (updatedVariables.length > 0) {
2734
+ log(
2735
+ import_kleur4.default.yellow(
2736
+ `The following variables will be updated in Github for environment ${environment}:`
2737
+ )
2738
+ );
2739
+ updatedVariables.forEach((variable) => {
2715
2740
  log(
2716
- import_kleur4.default.green(
2717
- `Successfully updated Github secrets and variables for environment ${environment}`
2718
- )
2741
+ variable.name,
2742
+ "=",
2743
+ variable.value,
2744
+ `(was ${variable.didExist?.value})`
2719
2745
  );
2720
- log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2721
- generateInventory(environment, {
2722
- kube_worker_nodes: kubeWorkerNodes,
2723
- kube_api_host: infrastructure.kubeAPIHost || "",
2724
- backup_host: backupHost || "",
2725
- users
2726
- });
2727
- copyChartsValues(environment, {
2728
- env: environment,
2729
- environment_type,
2730
- // FIXME: In general that should be environment_type,
2731
- // Hardcode like this blocks us from being generic:
2732
- // https://github.com/opencrvs/opencrvs-core/issues/11171
2733
- two_fa_enabled: environment !== "production" ? false : true,
2734
- backup_enabled: configureBackup ? true : false,
2735
- restore_enabled: restoreEnvironmentName ? true : false,
2736
- restore_environment_name: restoreEnvironmentName || "",
2737
- restore_type: restoreType,
2738
- traefik_mode: traefikConfOption,
2739
- backup_type: backupType
2740
- });
2741
- let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2746
+ });
2747
+ log("");
2748
+ }
2749
+ if (unknownVariables.length > 0) {
2750
+ log(
2751
+ import_kleur4.default.yellow(
2752
+ `The following unknown variables/secrets were stored in Github are not managed by this script:`
2753
+ )
2754
+ );
2755
+ log("");
2756
+ log(import_kleur4.default.blue(`Repository:`));
2757
+ unknownVariables.filter(({ scope }) => scope === "REPOSITORY").forEach((variable) => {
2758
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2759
+ });
2760
+ log("");
2761
+ log(import_kleur4.default.blue(`Environment:`));
2762
+ unknownVariables.filter(({ scope }) => scope === "ENVIRONMENT").forEach((variable) => {
2763
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2764
+ });
2765
+ log("");
2766
+ log(
2767
+ import_kleur4.default.yellow(
2768
+ `These variables will not be updated by this script. If you want to update them, you will need to do so manually.`
2769
+ )
2770
+ );
2771
+ log("");
2772
+ }
2773
+ if ([].concat(newSecrets).concat(updatedSecrets).concat(newVariables).concat(updatedVariables).length === 0) {
2774
+ process.exit(0);
2775
+ }
2776
+ log(
2777
+ import_kleur4.default.bold().red(
2778
+ "\u26A0\uFE0F COPY THESE NOW INTO A PASSWORD MANAGER \u2014 YOU WON'T SEE THEM AGAIN"
2779
+ )
2780
+ );
2781
+ log("");
2782
+ const saveChanges = await confirm2({
2783
+ message: "Do you want to continue?",
2784
+ default: true
2785
+ });
2786
+ if (!saveChanges) {
2787
+ process.exit(0);
2788
+ }
2789
+ for (const newSecret of newSecrets) {
2790
+ log(`Creating secret ${newSecret.name} with value ${newSecret.value}`);
2791
+ if (newSecret.scope === "ENVIRONMENT") {
2792
+ await createEnvironmentSecret(
2793
+ octokit,
2794
+ repositoryId,
2795
+ environment,
2796
+ newSecret.name,
2797
+ newSecret.value,
2798
+ githubOrganisation,
2799
+ githubRepository
2800
+ );
2801
+ } else {
2802
+ await createRepositorySecret(
2803
+ octokit,
2804
+ repositoryId,
2805
+ newSecret.name,
2806
+ newSecret.value,
2807
+ githubOrganisation,
2808
+ githubRepository
2809
+ );
2810
+ }
2811
+ }
2812
+ for (const updatedSecret of updatedSecrets) {
2813
+ log(
2814
+ `Updating secret ${updatedSecret.name} with value ${updatedSecret.value}`
2815
+ );
2816
+ if (updatedSecret.scope === "ENVIRONMENT") {
2817
+ await createEnvironmentSecret(
2818
+ octokit,
2819
+ repositoryId,
2820
+ environment,
2821
+ updatedSecret.name,
2822
+ updatedSecret.value,
2823
+ githubOrganisation,
2824
+ githubRepository
2825
+ );
2826
+ } else {
2827
+ await createRepositorySecret(
2828
+ octokit,
2829
+ repositoryId,
2830
+ updatedSecret.name,
2831
+ updatedSecret.value,
2832
+ githubOrganisation,
2833
+ githubRepository
2834
+ );
2835
+ }
2836
+ }
2837
+ for (const newVariable of newVariables) {
2838
+ log(`Creating variable ${newVariable.name} with value ${newVariable.value}`);
2839
+ if (newVariable.scope === "ENVIRONMENT") {
2840
+ await createEnvironmentVariable(
2841
+ octokit,
2842
+ repositoryId,
2843
+ environment,
2844
+ newVariable.name,
2845
+ newVariable.value
2846
+ );
2847
+ } else {
2848
+ await createRepositoryVariable(
2849
+ octokit,
2850
+ repositoryId,
2851
+ newVariable.name,
2852
+ newVariable.value
2853
+ );
2854
+ }
2855
+ }
2856
+ for (const updatedVariable of updatedVariables) {
2857
+ log(
2858
+ `Updating variable ${updatedVariable.name} with value ${updatedVariable.value}`
2859
+ );
2860
+ if (updatedVariable.scope === "ENVIRONMENT") {
2861
+ await updateEnvironmentVariable(
2862
+ octokit,
2863
+ repositoryId,
2864
+ environment,
2865
+ updatedVariable.name,
2866
+ updatedVariable.value
2867
+ );
2868
+ } else {
2869
+ await updateRepositoryVariable(
2870
+ octokit,
2871
+ repositoryId,
2872
+ updatedVariable.name,
2873
+ updatedVariable.value
2874
+ );
2875
+ }
2876
+ }
2877
+ log(
2878
+ import_kleur4.default.green(
2879
+ `Successfully updated Github secrets and variables for environment ${environment}`
2880
+ )
2881
+ );
2882
+ log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2883
+ generateInventory(environment, {
2884
+ kube_worker_nodes: kubeWorkerNodes,
2885
+ kube_api_host: infrastructure.kubeApiHost || "",
2886
+ backup_host: backupHost || "",
2887
+ users
2888
+ });
2889
+ copyChartsValues(environment, {
2890
+ env: environment,
2891
+ environment_type,
2892
+ two_fa_enabled,
2893
+ traefik_mode: traefikConfOption,
2894
+ restore_enabled: restoreEnvironmentName ? true : false,
2895
+ restore_environment_name: restoreEnvironmentName || "",
2896
+ restore_type: restoreType,
2897
+ restore_host: restoreHost || "",
2898
+ backup_enabled: configureBackup ? true : false,
2899
+ backup_type: backupType,
2900
+ backup_host: backupHost || ""
2901
+ });
2902
+ log("\n", import_kleur4.default.bold().underline("Updating workflow files"));
2903
+ await updateWorkflowEnvironments();
2904
+ let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2742
2905
 
2743
2906
  \u27A1\uFE0F ${import_kleur4.default.bold().yellow("COPY the SSH public key from the master VM to your clipboard")}
2744
2907
  --------------------------------------------------------------------------------------------
2745
2908
  ` : "";
2746
- addon_message += kubeWorkerNodes.length > 0 ? `\u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes worker VM to create provision user and setup SSH key:")}
2909
+ addon_message += kubeWorkerNodes.length > 0 ? `\u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes worker VM to create provision user and setup SSH key:")}
2747
2910
 
2748
2911
  curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2749
2912
  bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"
2750
2913
  ` : "";
2751
- addon_message += configureBackup ? `
2914
+ addon_message += configureBackup ? `
2752
2915
  \u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on backup server to create provision user and setup SSH key:")}
2753
2916
  curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2754
2917
  bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"` : "";
2755
- log(`
2918
+ log(`
2756
2919
  ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2757
2920
  Follow the steps below to complete the setup of your environment:
2758
2921
  ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
@@ -2770,140 +2933,46 @@ ${addon_message}
2770
2933
  ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2771
2934
  ${import_kleur4.default.yellow("Please KINDLY read hints above")}
2772
2935
  `);
2773
- log("\nAll variables stored in", import_kleur4.default.cyan(`.env.${environment}`));
2774
- log(import_kleur4.default.bold().yellow("DO NOT COMMIT THIS FILE TO GIT!"));
2775
- })();
2776
- }
2777
- });
2778
-
2779
- // src/environment/update-workflows.ts
2780
- var update_workflows_exports = {};
2781
- __export(update_workflows_exports, {
2782
- updateWorkflowEnvironments: () => updateWorkflowEnvironments
2783
- });
2784
- function isDirectory(path6) {
2785
- try {
2786
- return (0, import_fs3.statSync)(path6).isDirectory();
2787
- } catch {
2788
- return false;
2789
- }
2790
- }
2791
- async function extractInfrastructureNames() {
2792
- const files = glob2.sync((0, import_path4.join)("environments", "*", INVENTORY_FILE_NAME));
2793
- const infraEnvironments = files.map((file) => (0, import_path4.basename)((0, import_path4.dirname)(file)));
2794
- if (infraEnvironments.length === 0) {
2795
- console.log(
2796
- `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
2797
- );
2798
- return [];
2799
- }
2800
- log("\u{1F50D} Found infrastructure configurations:", infraEnvironments.join(", "));
2801
- return infraEnvironments;
2802
- }
2803
- async function extractEnvironmentNames() {
2804
- const entries = await (0, import_promises.readdir)("environments");
2805
- const environments = entries.filter((entry) => {
2806
- const environmentPath = (0, import_path4.join)("environments", entry);
2807
- const opencrvsServicesPath = (0, import_path4.join)(environmentPath, "opencrvs-services");
2808
- return isDirectory(environmentPath) && (0, import_fs3.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
2809
- });
2810
- if (environments.length === 0) {
2811
- console.log(
2812
- "\u26A0\uFE0F Warning: No environment directories found in environments/"
2813
- );
2814
- return [];
2815
- }
2816
- log("\u{1F50D} Found OpenCRVS configurations:", environments.join(", "));
2817
- return environments;
2818
- }
2819
- function updateOptionsInYaml(content, envList) {
2820
- const optionsRegex = /([ ]*options:[ ]*\n)((?:[ ]*-[^\n]*\n)+)/;
2821
- const match = content.match(optionsRegex);
2822
- if (!match) {
2823
- throw new Error("Could not find options array in workflow file");
2824
- }
2825
- const firstItemMatch = match[2].match(/^([ ]*)-/);
2826
- const itemIndent = firstItemMatch ? firstItemMatch[1] : " ";
2827
- const newOptions = match[1] + envList.map((env) => `${itemIndent}- ${env}`).join("\n") + "\n";
2828
- return content.replace(optionsRegex, newOptions);
2829
- }
2830
- async function updateWorkflows(envList, config) {
2831
- const { workflows } = config;
2832
- for (const workflowPath of workflows) {
2833
- try {
2834
- const fileContents = (0, import_fs3.readFileSync)(workflowPath, "utf8");
2835
- const workflowData = yaml2.load(fileContents);
2836
- if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2837
- throw new Error(
2838
- "Workflow does not have the expected structure: on.workflow_dispatch.inputs.environment.options"
2839
- );
2840
- }
2841
- const updatedContent = updateOptionsInYaml(fileContents, envList);
2842
- (0, import_fs3.writeFileSync)(workflowPath, updatedContent, "utf8");
2843
- log(` \u2713 Successfully updated ${workflowPath}`);
2844
- } catch (error3) {
2845
- console.error(
2846
- `
2847
- \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
2848
- );
2849
- console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
2850
- throw error3;
2851
- }
2852
- }
2853
- }
2854
- async function updateWorkflowEnvironments() {
2855
- try {
2856
- let didUpdateWorkflows = false;
2857
- const infraEnvironments = await extractInfrastructureNames();
2858
- if (infraEnvironments.length > 0) {
2859
- console.log("\u{1F504} Updating infrastructure workflows:");
2860
- await updateWorkflows(infraEnvironments, {
2861
- workflows: [
2862
- ".github/workflows/provision.yml",
2863
- ".github/workflows/reset-2fa.yml"
2864
- ],
2865
- path: "on.workflow_dispatch.inputs.environment.options"
2866
- });
2867
- didUpdateWorkflows = true;
2868
- }
2869
- const environments = await extractEnvironmentNames();
2870
- if (environments.length > 0) {
2871
- const workflows = [
2872
- ".github/workflows/deploy-dependencies.yml",
2873
- ".github/workflows/deploy-opencrvs.yml",
2874
- ".github/workflows/clear-all-data.yml",
2875
- ".github/workflows/seed-data.yml",
2876
- ".github/workflows/reindex.yml",
2877
- ".github/workflows/github-to-k8s-sync-env.yml"
2878
- ];
2879
- log("\u{1F4CB} Updating OpenCRVS application workflows:");
2880
- await updateWorkflows(environments, {
2881
- workflows,
2882
- path: "on.workflow_dispatch.inputs.environment.options"
2883
- });
2884
- didUpdateWorkflows = true;
2885
- }
2886
- if (didUpdateWorkflows) {
2887
- success("\u2705 Workflow updates completed successfully!");
2888
- } else {
2889
- log("\u2139\uFE0F No workflows were updated.");
2890
- }
2891
- } catch (error3) {
2892
- console.error("\n\u274C Error updating workflows:", error3);
2893
- process.exit(1);
2894
- }
2936
+ log(
2937
+ "\nAll secrets and variables were printed above.",
2938
+ import_kleur4.default.bold().yellow("Store them in a password manager \u2014 they are not saved to disk.")
2939
+ );
2895
2940
  }
2896
- var import_promises, import_fs3, import_path4, glob2, yaml2;
2897
- var init_update_workflows = __esm({
2898
- "src/environment/update-workflows.ts"() {
2941
+ var import_core, import_kleur4, import_prompts2, ALL_QUESTIONS, ALL_ANSWERS;
2942
+ var init_setup_environment = __esm({
2943
+ "src/environment/setup-environment.ts"() {
2899
2944
  "use strict";
2900
- import_promises = require("fs/promises");
2901
- import_fs3 = require("fs");
2902
- import_path4 = require("path");
2903
- glob2 = __toESM(require("glob"));
2904
- yaml2 = __toESM(require("js-yaml"));
2945
+ import_core = require("@octokit/core");
2946
+ import_kleur4 = __toESM(require("kleur"));
2947
+ import_prompts2 = __toESM(require("prompts"));
2948
+ init_github();
2949
+ init_derived_variables();
2950
+ init_utils();
2905
2951
  init_logger();
2952
+ init_templates();
2953
+ init_ssh_keygen();
2954
+ init_update_workflows();
2955
+ init_questions();
2956
+ init_editor_questions();
2957
+ init_questions_helper();
2958
+ init_manage_users();
2906
2959
  init_paths();
2960
+ ALL_QUESTIONS = [];
2961
+ ALL_ANSWERS = [];
2962
+ ALL_QUESTIONS.push(
2963
+ ...githubTokenQuestion,
2964
+ ...githubOtherQuestions,
2965
+ ...dockerhubQuestions,
2966
+ ...diskQuestions,
2967
+ ...infrastructureQuestions,
2968
+ ...backupQuestions,
2969
+ ...countryQuestions,
2970
+ ...databaseAndMonitoringQuestions,
2971
+ ...emailQuestions,
2972
+ ...sentryQuestions,
2973
+ ...derivedVariables,
2974
+ ...metabaseAdminQuestions
2975
+ );
2907
2976
  }
2908
2977
  });
2909
2978
 
@@ -2913,17 +2982,17 @@ __export(upgrade_exports, {
2913
2982
  upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2914
2983
  });
2915
2984
  function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2916
- if (!(0, import_fs4.existsSync)(sourcePath)) {
2985
+ if (!(0, import_fs5.existsSync)(sourcePath)) {
2917
2986
  return false;
2918
2987
  }
2919
- if ((0, import_fs4.existsSync)(destinationPath)) {
2988
+ if ((0, import_fs5.existsSync)(destinationPath)) {
2920
2989
  warn(
2921
2990
  `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2922
2991
  );
2923
2992
  return false;
2924
2993
  }
2925
- (0, import_fs4.mkdirSync)((0, import_path5.dirname)(destinationPath), { recursive: true });
2926
- (0, import_fs4.renameSync)(sourcePath, destinationPath);
2994
+ (0, import_fs5.mkdirSync)((0, import_path6.dirname)(destinationPath), { recursive: true });
2995
+ (0, import_fs5.renameSync)(sourcePath, destinationPath);
2927
2996
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2928
2997
  return true;
2929
2998
  }
@@ -2943,8 +3012,8 @@ function migrateInventoryFiles() {
2943
3012
  ) || didMoveInventory;
2944
3013
  }
2945
3014
  try {
2946
- if ((0, import_fs4.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs4.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2947
- (0, import_fs4.rmdirSync)(OLD_INVENTORY_DIR);
3015
+ if ((0, import_fs5.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs5.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3016
+ (0, import_fs5.rmdirSync)(OLD_INVENTORY_DIR);
2948
3017
  log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2949
3018
  }
2950
3019
  } catch {
@@ -2962,12 +3031,12 @@ async function upgradeEnvironmentLayout() {
2962
3031
  }
2963
3032
  log("\nCommit changes into git after upgrade");
2964
3033
  }
2965
- var import_fs4, import_path5, import_kleur5;
3034
+ var import_fs5, import_path6, import_kleur5;
2966
3035
  var init_upgrade = __esm({
2967
3036
  "src/environment/upgrade.ts"() {
2968
3037
  "use strict";
2969
- import_fs4 = require("fs");
2970
- import_path5 = require("path");
3038
+ import_fs5 = require("fs");
3039
+ import_path6 = require("path");
2971
3040
  import_kleur5 = __toESM(require("kleur"));
2972
3041
  init_logger();
2973
3042
  init_paths();
@@ -2993,7 +3062,7 @@ async function selectInventoryFile(dirPath = "./environments") {
2993
3062
  return null;
2994
3063
  }
2995
3064
  const environments = fs4.readdirSync(dirPath).filter((entry) => {
2996
- const filePath = path4.join(dirPath, entry);
3065
+ const filePath = path5.join(dirPath, entry);
2997
3066
  return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
2998
3067
  }).sort();
2999
3068
  if (environments.length === 0) {
@@ -3021,12 +3090,12 @@ async function manageEnvironmentUsers() {
3021
3090
  }
3022
3091
  await manageUsers(inventory_file);
3023
3092
  }
3024
- var fs4, path4, import_kleur6;
3093
+ var fs4, path5, import_kleur6;
3025
3094
  var init_users = __esm({
3026
3095
  "src/environment/users.ts"() {
3027
3096
  "use strict";
3028
3097
  fs4 = __toESM(require("fs"));
3029
- path4 = __toESM(require("path"));
3098
+ path5 = __toESM(require("path"));
3030
3099
  import_kleur6 = __toESM(require("kleur"));
3031
3100
  init_manage_users();
3032
3101
  init_logger();
@@ -3036,11 +3105,11 @@ var init_users = __esm({
3036
3105
 
3037
3106
  // src/environment/swarm-to-k8s.ts
3038
3107
  var swarm_to_k8s_exports = {};
3039
- var path5, import_kleur7, import_core2;
3108
+ var path6, import_kleur7, import_core2;
3040
3109
  var init_swarm_to_k8s = __esm({
3041
3110
  "src/environment/swarm-to-k8s.ts"() {
3042
3111
  "use strict";
3043
- path5 = __toESM(require("path"));
3112
+ path6 = __toESM(require("path"));
3044
3113
  import_kleur7 = __toESM(require("kleur"));
3045
3114
  init_logger();
3046
3115
  init_utils();
@@ -3092,7 +3161,7 @@ var init_swarm_to_k8s = __esm({
3092
3161
  );
3093
3162
  process.exit(1);
3094
3163
  }
3095
- const ansible_inventory = path5.join(old_inventory_path, environment + ".yml");
3164
+ const ansible_inventory = path6.join(old_inventory_path, environment + ".yml");
3096
3165
  const data = readYamlFile(ansible_inventory);
3097
3166
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3098
3167
  const master = dockerManagerFirst(data) || "";
@@ -3111,10 +3180,7 @@ var init_swarm_to_k8s = __esm({
3111
3180
  copyChartsValues(environment, {
3112
3181
  env: environment,
3113
3182
  environment_type,
3114
- // FIXME: In general that should be environment_type,
3115
- // Hardcode like this blocks us from being generic:
3116
- // https://github.com/opencrvs/opencrvs-core/issues/11171
3117
- two_fa_enabled: environment !== "production" ? false : true,
3183
+ two_fa_enabled: process.env.TWO_FA_ENABLED ? process.env.TWO_FA_ENABLED === "true" : environment_type === "production",
3118
3184
  backup_enabled: environment === "production" ? "true" : "false",
3119
3185
  restore_enabled: environment === "staging" ? "true" : "false",
3120
3186
  restore_environment_name: environment === "staging" ? "production" : "",
@@ -3212,150 +3278,385 @@ var init_swarm_to_k8s = __esm({
3212
3278
  }
3213
3279
  }
3214
3280
  }
3215
- })();
3281
+ })();
3282
+ }
3283
+ });
3284
+
3285
+ // src/migrations/add-translations.ts
3286
+ var import_path = __toESM(require("path"));
3287
+
3288
+ // src/csv.ts
3289
+ var import_fs = require("fs");
3290
+ function parseCsvLine(line2) {
3291
+ const values = [];
3292
+ let value = "";
3293
+ let quoted = false;
3294
+ for (let index = 0; index < line2.length; index++) {
3295
+ const character = line2[index];
3296
+ if (quoted) {
3297
+ if (character !== '"') {
3298
+ value += character;
3299
+ } else if (line2[index + 1] === '"') {
3300
+ value += '"';
3301
+ index++;
3302
+ } else {
3303
+ quoted = false;
3304
+ }
3305
+ continue;
3306
+ }
3307
+ if (character === '"') {
3308
+ quoted = true;
3309
+ } else if (character === ",") {
3310
+ values.push(value);
3311
+ value = "";
3312
+ } else {
3313
+ value += character;
3314
+ }
3315
+ }
3316
+ values.push(value);
3317
+ return values;
3318
+ }
3319
+ function toCsvLine(values) {
3320
+ return values.map(
3321
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
3322
+ ).join(",");
3323
+ }
3324
+ function idOf(line2) {
3325
+ const comma = line2.indexOf(",");
3326
+ return comma === -1 ? line2 : line2.slice(0, comma);
3327
+ }
3328
+ function readCsvFile(path7) {
3329
+ if (!(0, import_fs.existsSync)(path7)) {
3330
+ return void 0;
3331
+ }
3332
+ const contents = (0, import_fs.readFileSync)(path7, "utf8");
3333
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3334
+ const trailingNewline = /\r?\n$/.test(contents);
3335
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3336
+ const body = lines.slice(1).filter((line2) => line2 !== "");
3337
+ return { header: lines[0], body, newline, trailingNewline };
3338
+ }
3339
+ function writeCsvFile(path7, file) {
3340
+ (0, import_fs.writeFileSync)(
3341
+ path7,
3342
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3343
+ );
3344
+ }
3345
+ function addRows(file, rows) {
3346
+ const isSorted = file.body.every(
3347
+ (line2, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line2)
3348
+ );
3349
+ const added = [];
3350
+ for (const row of rows) {
3351
+ const id = idOf(row);
3352
+ if (file.body.some((line2) => idOf(line2) === id)) {
3353
+ continue;
3354
+ }
3355
+ const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3356
+ if (insertAt === -1) {
3357
+ file.body.push(row);
3358
+ } else {
3359
+ file.body.splice(insertAt, 0, row);
3360
+ }
3361
+ added.push(id);
3362
+ }
3363
+ return added;
3364
+ }
3365
+
3366
+ // src/translations/template.ts
3367
+ var REPOSITORY = "opencrvs/opencrvs-core";
3368
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
3369
+ async function matchingRefs(namespace, prefix) {
3370
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
3371
+ const response = await fetch(url, {
3372
+ headers: { accept: "application/vnd.github+json" }
3373
+ });
3374
+ if (!response.ok) {
3375
+ throw new Error(
3376
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3377
+ );
3378
+ }
3379
+ const refs = await response.json();
3380
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
3381
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
3382
+ }
3383
+ async function candidateRefs(version) {
3384
+ return [
3385
+ ...await matchingRefs("heads", `release/${version}.`),
3386
+ ...await matchingRefs("tags", `v${version}.`),
3387
+ "develop"
3388
+ ];
3389
+ }
3390
+ async function fetchTemplate(refs, application) {
3391
+ for (const ref of refs) {
3392
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
3393
+ const response = await fetch(url);
3394
+ if (response.ok) {
3395
+ return { ref, contents: await response.text() };
3396
+ }
3397
+ if (response.status !== 404) {
3398
+ throw new Error(
3399
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3400
+ );
3401
+ }
3402
+ }
3403
+ return void 0;
3404
+ }
3405
+
3406
+ // src/migrations/add-translations.ts
3407
+ var APPLICATIONS = ["client", "login"];
3408
+ var skipped = [];
3409
+ function warnSkipped(message) {
3410
+ skipped.push(message);
3411
+ console.warn(` \u26A0\uFE0F ${message}`);
3412
+ }
3413
+ function rowsToAdd(local, template) {
3414
+ const localColumns = parseCsvLine(local.header);
3415
+ const templateColumns = parseCsvLine(template.header);
3416
+ return template.body.filter((line2) => line2 !== "").map((line2) => {
3417
+ const values = parseCsvLine(line2);
3418
+ return toCsvLine(
3419
+ localColumns.map((column) => {
3420
+ const index = templateColumns.indexOf(column);
3421
+ return index === -1 ? "" : values[index] ?? "";
3422
+ })
3423
+ );
3424
+ });
3425
+ }
3426
+ async function updateApplication(cwd, targetVersion, refs, application) {
3427
+ const relativePath = `src/translations/${application}.csv`;
3428
+ const local = readCsvFile(import_path.default.join(cwd, relativePath));
3429
+ if (!local) {
3430
+ warnSkipped(`${relativePath} not found; translations not added`);
3431
+ return;
3432
+ }
3433
+ const fetched = await fetchTemplate(refs, application);
3434
+ if (!fetched) {
3435
+ warnSkipped(
3436
+ `No ${application}.csv found in the ${targetVersion} country config template on GitHub; ${application}.csv not updated`
3437
+ );
3438
+ return;
3439
+ }
3440
+ const template = readTemplate(fetched.contents);
3441
+ const added = addRows(local, rowsToAdd(local, template));
3442
+ if (added.length === 0) {
3443
+ return;
3444
+ }
3445
+ try {
3446
+ writeCsvFile(import_path.default.join(cwd, relativePath), local);
3447
+ } catch (error3) {
3448
+ warnSkipped(
3449
+ `Could not write ${relativePath} (${error3.message}); translations not added`
3450
+ );
3451
+ return;
3452
+ }
3453
+ for (const id of added) {
3454
+ console.log(` \u2713 ${relativePath}: ${id}`);
3455
+ }
3456
+ }
3457
+ function readTemplate(contents) {
3458
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3459
+ return {
3460
+ header: lines[0],
3461
+ body: lines.slice(1),
3462
+ newline: "\n",
3463
+ trailingNewline: true
3464
+ };
3465
+ }
3466
+ async function listRefs(targetVersion) {
3467
+ try {
3468
+ return await candidateRefs(targetVersion);
3469
+ } catch (error3) {
3470
+ warnSkipped(
3471
+ `Could not list the ${targetVersion} refs on GitHub (${error3.message}); translations not added`
3472
+ );
3473
+ return void 0;
3474
+ }
3475
+ }
3476
+ async function main(targetVersion) {
3477
+ const cwd = process.cwd();
3478
+ console.log("Adding the translation keys core gained this version...\n");
3479
+ const refs = await listRefs(targetVersion);
3480
+ if (refs) {
3481
+ for (const application of APPLICATIONS) {
3482
+ try {
3483
+ await updateApplication(cwd, targetVersion, refs, application);
3484
+ } catch (error3) {
3485
+ warnSkipped(
3486
+ `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
3487
+ );
3488
+ }
3489
+ }
3216
3490
  }
3217
- });
3491
+ if (skipped.length > 0) {
3492
+ console.warn(
3493
+ `
3494
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
3495
+ );
3496
+ for (const message of skipped) {
3497
+ console.warn(` - ${message}`);
3498
+ }
3499
+ }
3500
+ }
3218
3501
 
3219
- // src/migrations/v2.1/add-explicit-correction-flags.ts
3502
+ // src/migrations/v2.2/read-declaration-through-helper.ts
3220
3503
  var import_ts_morph = require("ts-morph");
3221
- var import_path = __toESM(require("path"));
3222
- var DEFINE_CONFIG_NAME = "defineConfig";
3223
- var ACTIONS_PROPERTY_NAME = "actions";
3224
- var TYPE_PROPERTY_NAME = "type";
3225
- var FLAGS_PROPERTY_NAME = "flags";
3226
- var CONDITIONALS_PROPERTY_NAME = "conditionals";
3227
- var ACTION_TYPE_ENUM_NAME = "ActionType";
3228
- var REQUEST_CORRECTION_TYPE = "REQUEST_CORRECTION";
3229
- var CORRECTION_ACTIONS_TO_ADD = [
3230
- {
3231
- actionType: "APPROVE_CORRECTION",
3232
- labelId: "v2.events.correction.approve.label",
3233
- defaultMessage: "Approve correction",
3234
- description: "Label for the approve correction action"
3235
- },
3236
- {
3237
- actionType: "REJECT_CORRECTION",
3238
- labelId: "v2.events.correction.reject.label",
3239
- defaultMessage: "Reject correction",
3240
- description: "Label for the reject correction action"
3504
+ var import_path2 = __toESM(require("path"));
3505
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
3506
+ var DECLARATION_PROPERTY_NAME = "declaration";
3507
+ var GET_DECLARATION_NAME = "getDeclaration";
3508
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3509
+ function isToolkitEventConfig(type) {
3510
+ const nonNullableType = type.getNonNullableType();
3511
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
3512
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
3513
+ return false;
3241
3514
  }
3242
- ];
3243
- function isActionOfType(obj, typeName) {
3244
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3245
- if (!typeProperty || !import_ts_morph.Node.isPropertyAssignment(typeProperty)) return false;
3246
- const typeInit = typeProperty.getInitializer();
3247
- if (!typeInit) return false;
3248
- if (import_ts_morph.Node.isPropertyAccessExpression(typeInit)) {
3249
- return typeInit.getExpression().getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === typeName;
3250
- }
3251
- if (import_ts_morph.Node.isStringLiteral(typeInit)) {
3252
- return typeInit.getLiteralValue() === typeName;
3253
- }
3254
- return false;
3255
- }
3256
- function getTypeInitializerStyle(obj) {
3257
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3258
- if (typeProperty && import_ts_morph.Node.isPropertyAssignment(typeProperty)) {
3259
- const typeInit = typeProperty.getInitializer();
3260
- if (typeInit && import_ts_morph.Node.isPropertyAccessExpression(typeInit)) return "enum";
3261
- }
3262
- return "string";
3263
- }
3264
- function getNonEmptyArrayPropertyText(obj, propName) {
3265
- const prop = obj.getProperty(propName);
3266
- if (!prop || !import_ts_morph.Node.isPropertyAssignment(prop)) return void 0;
3267
- const init = prop.getInitializer();
3268
- if (!init || !import_ts_morph.Node.isArrayLiteralExpression(init)) return void 0;
3269
- if (init.getElements().length === 0) return void 0;
3270
- return init.getText();
3271
- }
3272
- function buildCorrectionActionText(spec, typeStyle, flagsText, conditionalsText) {
3273
- const typeText = typeStyle === "enum" ? `${ACTION_TYPE_ENUM_NAME}.${spec.actionType}` : `'${spec.actionType}'`;
3274
- const lines = [
3275
- `type: ${typeText}`,
3276
- `label: {
3277
- id: '${spec.labelId}',
3278
- defaultMessage: '${spec.defaultMessage}',
3279
- description: '${spec.description}'
3280
- }`
3281
- ];
3282
- if (flagsText) {
3283
- lines.push(`${FLAGS_PROPERTY_NAME}: ${flagsText}`);
3284
- }
3285
- if (conditionalsText) {
3286
- lines.push(`${CONDITIONALS_PROPERTY_NAME}: ${conditionalsText}`);
3287
- }
3288
- return `{
3289
- ${lines.join(",\n ")}
3290
- }`;
3291
- }
3292
- function processFile(filePath, project) {
3293
- const sourceFile = project.getSourceFile(filePath);
3294
- if (!sourceFile) return 0;
3295
- let changes = 0;
3296
- const relPath = import_path.default.relative(process.cwd(), filePath);
3297
- const callExpressions = sourceFile.getDescendantsOfKind(
3298
- import_ts_morph.SyntaxKind.CallExpression
3515
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
3516
+ }
3517
+ function isDeclarationReadOnEventConfig(node) {
3518
+ return node.getName() === DECLARATION_PROPERTY_NAME && isToolkitEventConfig(node.getExpression().getType());
3519
+ }
3520
+ function isAssignmentOperator(kind) {
3521
+ return kind >= import_ts_morph.SyntaxKind.FirstAssignment && kind <= import_ts_morph.SyntaxKind.LastAssignment;
3522
+ }
3523
+ function isWriteTarget(node) {
3524
+ const parent = node.getParent();
3525
+ if (import_ts_morph.Node.isDeleteExpression(parent)) {
3526
+ return true;
3527
+ }
3528
+ return import_ts_morph.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
3529
+ }
3530
+ function location(node) {
3531
+ const relPath = import_path2.default.relative(
3532
+ process.cwd(),
3533
+ node.getSourceFile().getFilePath()
3299
3534
  );
3300
- for (const call of callExpressions) {
3301
- const expression = call.getExpression();
3302
- if (!import_ts_morph.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME) {
3303
- continue;
3304
- }
3305
- const args2 = call.getArguments();
3306
- if (args2.length === 0) continue;
3307
- const configArg = args2[0];
3308
- if (!import_ts_morph.Node.isObjectLiteralExpression(configArg)) continue;
3309
- const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME);
3310
- if (!actionsProperty || !import_ts_morph.Node.isPropertyAssignment(actionsProperty))
3311
- continue;
3312
- const actionsInitializer = actionsProperty.getInitializer();
3313
- if (!actionsInitializer || !import_ts_morph.Node.isArrayLiteralExpression(actionsInitializer))
3314
- continue;
3315
- const elements = actionsInitializer.getElements();
3316
- const requestCorrectionIndex = elements.findIndex(
3317
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, REQUEST_CORRECTION_TYPE)
3535
+ return `${relPath}:${node.getStartLineNumber()}`;
3536
+ }
3537
+ function warnDestructuredDeclarations(sourceFile) {
3538
+ for (const pattern of sourceFile.getDescendantsOfKind(
3539
+ import_ts_morph.SyntaxKind.ObjectBindingPattern
3540
+ )) {
3541
+ const destructuresDeclaration = pattern.getElements().some(
3542
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME
3318
3543
  );
3319
- if (requestCorrectionIndex === -1) continue;
3320
- const requestCorrection = elements[requestCorrectionIndex];
3321
- const flagsText = getNonEmptyArrayPropertyText(
3322
- requestCorrection,
3323
- FLAGS_PROPERTY_NAME
3544
+ if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3545
+ console.warn(
3546
+ ` [${location(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3547
+ );
3548
+ }
3549
+ }
3550
+ }
3551
+ function warnSpreadDeclarations(sourceFile) {
3552
+ for (const literal of sourceFile.getDescendantsOfKind(
3553
+ import_ts_morph.SyntaxKind.ObjectLiteralExpression
3554
+ )) {
3555
+ const properties = literal.getProperties();
3556
+ const spreadsEventConfig = properties.some(
3557
+ (property) => import_ts_morph.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
3324
3558
  );
3325
- const conditionalsText = getNonEmptyArrayPropertyText(
3326
- requestCorrection,
3327
- CONDITIONALS_PROPERTY_NAME
3559
+ const setsDeclaration = properties.some(
3560
+ (property) => (import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME
3328
3561
  );
3329
- if (!flagsText && !conditionalsText) continue;
3330
- const typeStyle = getTypeInitializerStyle(requestCorrection);
3331
- let insertAt = requestCorrectionIndex + 1;
3332
- for (const spec of CORRECTION_ACTIONS_TO_ADD) {
3333
- const alreadyPresent = actionsInitializer.getElements().some(
3334
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, spec.actionType)
3562
+ if (spreadsEventConfig && setsDeclaration) {
3563
+ console.warn(
3564
+ ` [${location(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME}\` on its DECLARE action, so replace that one by hand.`
3335
3565
  );
3336
- if (alreadyPresent) continue;
3337
- const text = buildCorrectionActionText(
3338
- spec,
3339
- typeStyle,
3340
- flagsText,
3341
- conditionalsText
3566
+ }
3567
+ }
3568
+ }
3569
+ function findToolkitImport(sourceFile) {
3570
+ return sourceFile.getImportDeclaration(
3571
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3572
+ );
3573
+ }
3574
+ function findGetDeclarationName(sourceFile) {
3575
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3576
+ if (imported) {
3577
+ return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
3578
+ }
3579
+ if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
3580
+ return void 0;
3581
+ }
3582
+ return GET_DECLARATION_NAME;
3583
+ }
3584
+ function addGetDeclarationImport(sourceFile) {
3585
+ const toolkitImport = findToolkitImport(sourceFile);
3586
+ if (!toolkitImport) {
3587
+ const imports = sourceFile.getImportDeclarations();
3588
+ const lastImport = imports[imports.length - 1];
3589
+ sourceFile.insertStatements(
3590
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3591
+ `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
3592
+ );
3593
+ return;
3594
+ }
3595
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3596
+ if (alreadyImported) {
3597
+ return;
3598
+ }
3599
+ const namedImports = toolkitImport.getNamedImports();
3600
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3601
+ toolkitImport.addNamedImport(GET_DECLARATION_NAME);
3602
+ return;
3603
+ }
3604
+ const names = [
3605
+ ...namedImports.map((namedImport) => namedImport.getText()),
3606
+ GET_DECLARATION_NAME
3607
+ ];
3608
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
3609
+ ${names.join(",\n ")}
3610
+ }` : `{ ${names.join(", ")} }`;
3611
+ toolkitImport.replaceWithText(
3612
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
3613
+ );
3614
+ }
3615
+ function rewriteDeclarationReads(sourceFile) {
3616
+ warnDestructuredDeclarations(sourceFile);
3617
+ warnSpreadDeclarations(sourceFile);
3618
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
3619
+ if (node.hasQuestionDotToken()) {
3620
+ console.warn(
3621
+ ` [${location(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
3342
3622
  );
3343
- actionsInitializer.insertElement(insertAt, text);
3344
- insertAt++;
3345
- changes++;
3346
- console.log(
3347
- ` [${relPath}] Added ${spec.actionType} action carrying over REQUEST_CORRECTION's flags/conditionals`
3623
+ return false;
3624
+ }
3625
+ if (isWriteTarget(node)) {
3626
+ console.warn(
3627
+ ` [${location(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME}\` on the DECLARE action instead.`
3348
3628
  );
3629
+ return false;
3349
3630
  }
3631
+ return true;
3632
+ }).sort((a, b) => b.getStart() - a.getStart());
3633
+ if (reads.length === 0) {
3634
+ return 0;
3635
+ }
3636
+ const getDeclarationName = findGetDeclarationName(sourceFile);
3637
+ if (!getDeclarationName) {
3638
+ console.warn(
3639
+ ` [${location(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
3640
+ );
3641
+ return 0;
3642
+ }
3643
+ for (const read of reads) {
3644
+ console.log(
3645
+ ` [${location(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
3646
+ );
3647
+ read.replaceWithText(
3648
+ `${getDeclarationName}(${read.getExpression().getText()})`
3649
+ );
3350
3650
  }
3351
- return changes;
3651
+ addGetDeclarationImport(sourceFile);
3652
+ return reads.length;
3352
3653
  }
3353
- async function main() {
3354
- const srcDir = import_path.default.join(process.cwd(), "src");
3355
- console.log(`Scanning for defineConfig calls in: ${srcDir}
3654
+ async function main2() {
3655
+ const srcDir = import_path2.default.join(process.cwd(), "src");
3656
+ console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
3356
3657
  `);
3357
3658
  const project = new import_ts_morph.Project({
3358
- tsConfigFilePath: import_path.default.resolve(srcDir, "../tsconfig.json"),
3659
+ tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
3359
3660
  skipAddingFilesFromTsConfig: false
3360
3661
  });
3361
3662
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -3367,40 +3668,39 @@ async function main() {
3367
3668
  let totalChanges = 0;
3368
3669
  const modifiedFiles = [];
3369
3670
  for (const sourceFile of sourceFiles) {
3370
- const filePath = sourceFile.getFilePath();
3371
- const changes = processFile(filePath, project);
3671
+ const changes = rewriteDeclarationReads(sourceFile);
3372
3672
  if (changes > 0) {
3373
3673
  totalChanges += changes;
3374
- modifiedFiles.push(filePath);
3674
+ modifiedFiles.push(sourceFile);
3375
3675
  }
3376
3676
  }
3377
3677
  if (modifiedFiles.length === 0) {
3378
- console.log(
3379
- "No REQUEST_CORRECTION actions with flags/conditionals found. Nothing to do."
3380
- );
3678
+ console.log("No EventConfig declaration reads found. Nothing to do.");
3381
3679
  return;
3382
3680
  }
3383
3681
  console.log(`
3384
3682
  Saving ${modifiedFiles.length} modified file(s)...`);
3385
- for (const filePath of modifiedFiles) {
3386
- const sourceFile = project.getSourceFileOrThrow(filePath);
3683
+ for (const sourceFile of modifiedFiles) {
3387
3684
  await sourceFile.save();
3388
- console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
3685
+ console.log(
3686
+ ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
3687
+ );
3389
3688
  }
3390
3689
  console.log(
3391
3690
  `
3392
- Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.length} file(s).`
3691
+ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
3393
3692
  );
3394
3693
  }
3395
3694
 
3396
- // src/migrations/v2.1/index.ts
3397
- async function runUpgrade(dockerSwarm) {
3398
- await main();
3695
+ // src/migrations/v2.2/index.ts
3696
+ async function runUpgrade() {
3697
+ await main2();
3698
+ await main("2.2");
3399
3699
  }
3400
3700
 
3401
3701
  // src/environment/index.ts
3402
- var import_fs5 = require("fs");
3403
- var import_path6 = require("path");
3702
+ var import_fs6 = require("fs");
3703
+ var import_path7 = require("path");
3404
3704
  init_paths();
3405
3705
  var REQUIRED_REPOSITORY_DIRECTORIES = [
3406
3706
  ".github/workflows",
@@ -3411,7 +3711,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3411
3711
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3412
3712
  (directory) => {
3413
3713
  try {
3414
- return !(0, import_fs5.statSync)((0, import_path6.resolve)(repositoryRoot, directory)).isDirectory();
3714
+ return !(0, import_fs6.statSync)((0, import_path7.resolve)(repositoryRoot, directory)).isDirectory();
3415
3715
  } catch {
3416
3716
  return true;
3417
3717
  }
@@ -3426,7 +3726,8 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3426
3726
  async function runEnvironmentInit() {
3427
3727
  validateRepositoryStructure();
3428
3728
  assertNoOldInventoryLayout();
3429
- await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3729
+ const { runSetupEnvironment: runSetupEnvironment2 } = await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3730
+ await runSetupEnvironment2();
3430
3731
  }
3431
3732
  async function runEnvironmentUpgrade() {
3432
3733
  validateRepositoryStructure();
@@ -3448,6 +3749,396 @@ async function runEnvironmentSwarmToK8s() {
3448
3749
  await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
3449
3750
  }
3450
3751
 
3752
+ // src/verify/endpoints.ts
3753
+ var import_colors = require("kleur/colors");
3754
+ var z = __toESM(require("zod/v4"));
3755
+ var REQUEST_TIMEOUT_MS = 15e3;
3756
+ var DEFAULT_TARGET_URL = "http://localhost:3040";
3757
+ var REQUIRED_PUBLIC_ENDPOINTS = [
3758
+ { method: "GET", path: "/client-config.js" },
3759
+ { method: "GET", path: "/login-config.js" },
3760
+ { method: "GET", path: "/handlebars.js" },
3761
+ { method: "GET", path: "/content/client" },
3762
+ { method: "GET", path: "/content/login" },
3763
+ { method: "GET", path: "/content/map.geojson" },
3764
+ { method: "GET", path: "/content/country-logo" },
3765
+ { method: "GET", path: "/config/application" },
3766
+ { method: "GET", path: "/config/workqueues" },
3767
+ { method: "GET", path: "/config/locations" },
3768
+ { method: "GET", path: "/config/roles" },
3769
+ { method: "GET", path: "/config/events" }
3770
+ ];
3771
+ var PROBE_SEGMENT = "verify-endpoints-probe";
3772
+ var SECURED_TRIGGER_USER_EVENTS = [
3773
+ "user-created",
3774
+ "user-updated",
3775
+ "username-reminder",
3776
+ "reset-password",
3777
+ "reset-password-by-admin",
3778
+ "password-reset-link",
3779
+ "username-reminder-link",
3780
+ "resend-invite",
3781
+ "2fa",
3782
+ "all-user-notification",
3783
+ "change-phone-number",
3784
+ "change-email-address"
3785
+ ];
3786
+ var SECURED_ENDPOINTS = [
3787
+ ...SECURED_TRIGGER_USER_EVENTS.map(
3788
+ (event) => ({
3789
+ method: "POST",
3790
+ path: `/trigger/user/${event}`
3791
+ })
3792
+ ),
3793
+ { method: "POST", path: "/trigger/telemetry" },
3794
+ { method: "GET", path: "/trigger/system/ready" },
3795
+ {
3796
+ method: "GET",
3797
+ path: `/certificates/${PROBE_SEGMENT}`,
3798
+ label: "/certificates/{id}"
3799
+ },
3800
+ { method: "GET", path: "/certificates" },
3801
+ { method: "GET", path: "/config/users" }
3802
+ ];
3803
+ var FALLBACK_EVENT_TRIGGERS = [
3804
+ {
3805
+ method: "POST",
3806
+ path: `/trigger/events/${PROBE_SEGMENT}/actions/${PROBE_SEGMENT}`,
3807
+ label: "/trigger/events/{event}/actions/{action}"
3808
+ },
3809
+ {
3810
+ method: "POST",
3811
+ path: `/trigger/events/birth/actions/${PROBE_SEGMENT}`,
3812
+ label: "/trigger/events/birth/actions/{action}"
3813
+ },
3814
+ {
3815
+ method: "POST",
3816
+ path: `/trigger/events/death/actions/${PROBE_SEGMENT}`,
3817
+ label: "/trigger/events/death/actions/{action}"
3818
+ }
3819
+ ];
3820
+ var isSuccess = (status) => status !== "error" && status >= 200 && status < 300;
3821
+ var requiresAuthOrAbsent = (status) => status === 401 || status === 403 || status === 404;
3822
+ async function requestStatus(url, method) {
3823
+ try {
3824
+ const response = await fetch(url, {
3825
+ method,
3826
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
3827
+ // Sent without an Authorization header on purpose. A secured route
3828
+ // rejects with 401/403 before ever reading the body.
3829
+ headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
3830
+ body: method === "POST" ? "{}" : void 0
3831
+ });
3832
+ return response.status;
3833
+ } catch {
3834
+ return "error";
3835
+ }
3836
+ }
3837
+ function toEventTriggerConfig(value) {
3838
+ if (typeof value !== "object" || value === null) {
3839
+ return null;
3840
+ }
3841
+ const record2 = value;
3842
+ if (typeof record2.id !== "string") {
3843
+ return null;
3844
+ }
3845
+ const actions = Array.isArray(record2.actions) ? Array.from(
3846
+ new Set(
3847
+ record2.actions.map((action) => {
3848
+ if (typeof action !== "object" || action === null) {
3849
+ return null;
3850
+ }
3851
+ const type = action.type;
3852
+ return typeof type === "string" ? type : null;
3853
+ }).filter((type) => type !== null)
3854
+ )
3855
+ ) : [];
3856
+ return { id: record2.id, actions };
3857
+ }
3858
+ async function fetchEventConfigs(baseUrl) {
3859
+ try {
3860
+ const response = await fetch(`${baseUrl}/config/events`, {
3861
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
3862
+ });
3863
+ if (!response.ok) {
3864
+ return null;
3865
+ }
3866
+ const body = await response.json();
3867
+ if (!Array.isArray(body)) {
3868
+ return null;
3869
+ }
3870
+ return body.map(toEventTriggerConfig).filter((config) => config !== null);
3871
+ } catch {
3872
+ return null;
3873
+ }
3874
+ }
3875
+ function resolveBaseUrl(input4) {
3876
+ const withProtocol = /^https?:\/\//i.test(input4) ? input4 : `https://${input4}`;
3877
+ return withProtocol.replace(/\/+$/, "");
3878
+ }
3879
+ function describeStatus(status) {
3880
+ return status === "error" ? "no response" : `HTTP ${status}`;
3881
+ }
3882
+ function endpointLabel(check) {
3883
+ const shown = check.label ?? check.path;
3884
+ const suffix = check.label ? (0, import_colors.dim)(` \u2192 ${check.path}`) : "";
3885
+ return `${check.method} ${shown}${suffix}`;
3886
+ }
3887
+ function line(ok, label, detail) {
3888
+ const mark = ok ? (0, import_colors.green)("\u2713") : (0, import_colors.red)("\u2717");
3889
+ return ` ${mark} ${label} ${(0, import_colors.dim)(`(${detail})`)}`;
3890
+ }
3891
+ function securedDetail(status) {
3892
+ if (status === 401 || status === 403) {
3893
+ return `${describeStatus(status)} \u2014 auth required`;
3894
+ }
3895
+ if (status === 404) {
3896
+ return `${describeStatus(status)} \u2014 not implemented`;
3897
+ }
3898
+ if (status === "error") {
3899
+ return `${describeStatus(status)} \u2014 request failed`;
3900
+ }
3901
+ return `${describeStatus(status)} \u2014 INSECURE: ensure this endpoint requires authentication!`;
3902
+ }
3903
+ var TEMPLATE_VERSION = "2.1";
3904
+ var TRANSLATED_APPLICATIONS = ["client", "login"];
3905
+ function readTemplateTranslations(contents) {
3906
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3907
+ return {
3908
+ ids: lines.slice(1).filter((line2) => line2 !== "").map(idOf),
3909
+ languages: parseCsvLine(lines[0]).filter(
3910
+ (column) => column !== "id" && column !== "description"
3911
+ )
3912
+ };
3913
+ }
3914
+ var ServedTranslations = z.object({
3915
+ languages: z.array(
3916
+ z.object({
3917
+ lang: z.string(),
3918
+ messages: z.record(z.string(), z.string())
3919
+ })
3920
+ )
3921
+ });
3922
+ async function fetchServedTranslations(baseUrl, application) {
3923
+ try {
3924
+ const response = await fetch(`${baseUrl}/content/${application}`, {
3925
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
3926
+ });
3927
+ if (!response.ok) {
3928
+ return null;
3929
+ }
3930
+ const parsed = ServedTranslations.safeParse(await response.json());
3931
+ return parsed.success ? parsed.data.languages : null;
3932
+ } catch {
3933
+ return null;
3934
+ }
3935
+ }
3936
+ var MISSING_IDS_SHOWN = 10;
3937
+ async function verifyTranslations(baseUrl) {
3938
+ let refs;
3939
+ try {
3940
+ refs = await candidateRefs(TEMPLATE_VERSION);
3941
+ } catch (error3) {
3942
+ console.log(
3943
+ " " + (0, import_colors.yellow)(
3944
+ `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error3.message}); translations not checked.`
3945
+ )
3946
+ );
3947
+ return 0;
3948
+ }
3949
+ let failures = 0;
3950
+ for (const application of TRANSLATED_APPLICATIONS) {
3951
+ const endpoint = `GET /content/${application}`;
3952
+ let fetched;
3953
+ try {
3954
+ fetched = await fetchTemplate(refs, application);
3955
+ } catch (error3) {
3956
+ console.log(
3957
+ " " + (0, import_colors.yellow)(
3958
+ `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${endpoint} not checked.`
3959
+ )
3960
+ );
3961
+ continue;
3962
+ }
3963
+ if (!fetched) {
3964
+ console.log(
3965
+ " " + (0, import_colors.yellow)(
3966
+ `No ${application}.csv in the ${TEMPLATE_VERSION} country config template on GitHub; ${endpoint} not checked.`
3967
+ )
3968
+ );
3969
+ continue;
3970
+ }
3971
+ const template = readTemplateTranslations(fetched.contents);
3972
+ const served = await fetchServedTranslations(baseUrl, application);
3973
+ if (!served) {
3974
+ console.log(
3975
+ " " + (0, import_colors.yellow)(`Could not read ${endpoint}; translations not checked.`)
3976
+ );
3977
+ continue;
3978
+ }
3979
+ const servedIds = new Set(
3980
+ served.flatMap(({ messages }) => Object.keys(messages))
3981
+ );
3982
+ const missing = template.ids.filter((id) => !servedIds.has(id));
3983
+ const servedLanguages = new Set(served.map(({ lang }) => lang));
3984
+ const absentLanguages = template.languages.filter(
3985
+ (lang) => !servedLanguages.has(lang)
3986
+ );
3987
+ if (missing.length === 0) {
3988
+ console.log(
3989
+ line(
3990
+ true,
3991
+ endpoint,
3992
+ `all ${template.ids.length} id(s) from the ${fetched.ref} template served`
3993
+ )
3994
+ );
3995
+ } else {
3996
+ failures++;
3997
+ console.log(
3998
+ line(
3999
+ false,
4000
+ endpoint,
4001
+ `${missing.length} of ${template.ids.length} id(s) from the ${fetched.ref} template not served`
4002
+ )
4003
+ );
4004
+ for (const id of missing.slice(0, MISSING_IDS_SHOWN)) {
4005
+ console.log(` ${(0, import_colors.dim)(id)}`);
4006
+ }
4007
+ if (missing.length > MISSING_IDS_SHOWN) {
4008
+ console.log(
4009
+ ` ${(0, import_colors.dim)(`\u2026 and ${missing.length - MISSING_IDS_SHOWN} more`)}`
4010
+ );
4011
+ }
4012
+ }
4013
+ if (absentLanguages.length > 0) {
4014
+ console.log(
4015
+ " " + (0, import_colors.yellow)(
4016
+ `${application}: the template carries ${absentLanguages.join(
4017
+ ", "
4018
+ )}, which this country config does not serve.`
4019
+ )
4020
+ );
4021
+ }
4022
+ }
4023
+ return failures;
4024
+ }
4025
+ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4026
+ const baseUrl = resolveBaseUrl(target);
4027
+ console.log((0, import_colors.bold)(`Verifying country config endpoints at ${baseUrl}
4028
+ `));
4029
+ let failures = 0;
4030
+ console.log((0, import_colors.bold)("Required public endpoints (must respond 2xx):"));
4031
+ for (const check of REQUIRED_PUBLIC_ENDPOINTS) {
4032
+ const status = await requestStatus(`${baseUrl}${check.path}`, check.method);
4033
+ const ok = isSuccess(status);
4034
+ if (!ok) {
4035
+ failures++;
4036
+ }
4037
+ const detail = status === 404 ? `${describeStatus(status)} \u2014 missing` : ok ? describeStatus(status) : `${describeStatus(status)} \u2014 unexpected`;
4038
+ console.log(line(ok, endpointLabel(check), detail));
4039
+ }
4040
+ {
4041
+ const path7 = `/fonts/${PROBE_SEGMENT}.ttf`;
4042
+ const status = await requestStatus(`${baseUrl}${path7}`, "GET");
4043
+ const ok = status === 200 || status === 404;
4044
+ if (!ok) {
4045
+ failures++;
4046
+ }
4047
+ let detail;
4048
+ if (status === 404) {
4049
+ detail = `${describeStatus(status)} \u2014 reachable (made-up filename)`;
4050
+ } else if (status === 200) {
4051
+ detail = describeStatus(status);
4052
+ } else if (status === 401 || status === 403) {
4053
+ detail = `${describeStatus(status)} \u2014 must be public`;
4054
+ } else {
4055
+ detail = `${describeStatus(status)} \u2014 unexpected`;
4056
+ }
4057
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path7}`)}`, detail));
4058
+ }
4059
+ console.log();
4060
+ console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
4061
+ for (const check of SECURED_ENDPOINTS) {
4062
+ const status = await requestStatus(`${baseUrl}${check.path}`, check.method);
4063
+ const ok = requiresAuthOrAbsent(status);
4064
+ if (!ok) {
4065
+ failures++;
4066
+ }
4067
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
4068
+ }
4069
+ console.log();
4070
+ console.log((0, import_colors.bold)("Event action triggers (must be absent or require auth):"));
4071
+ const events = await fetchEventConfigs(baseUrl);
4072
+ if (!events) {
4073
+ console.log(
4074
+ " " + (0, import_colors.yellow)(
4075
+ "Could not read /config/events; falling back to route-pattern checks."
4076
+ )
4077
+ );
4078
+ for (const check of FALLBACK_EVENT_TRIGGERS) {
4079
+ const status = await requestStatus(
4080
+ `${baseUrl}${check.path}`,
4081
+ check.method
4082
+ );
4083
+ const ok = requiresAuthOrAbsent(status);
4084
+ if (!ok) {
4085
+ failures++;
4086
+ }
4087
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
4088
+ }
4089
+ } else if (events.length === 0) {
4090
+ console.log(" " + (0, import_colors.yellow)("No events configured."));
4091
+ } else {
4092
+ for (const event of events) {
4093
+ const actions = event.actions.length ? event.actions : [PROBE_SEGMENT];
4094
+ const failed = [];
4095
+ for (const action of actions) {
4096
+ const status = await requestStatus(
4097
+ `${baseUrl}/trigger/events/${event.id}/actions/${action}`,
4098
+ "POST"
4099
+ );
4100
+ if (!requiresAuthOrAbsent(status)) {
4101
+ failed.push({ action, status });
4102
+ }
4103
+ }
4104
+ const pattern = `POST /trigger/events/${event.id}/actions/{action}`;
4105
+ if (failed.length === 0) {
4106
+ console.log(
4107
+ line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4108
+ );
4109
+ } else {
4110
+ for (const failure of failed) {
4111
+ failures++;
4112
+ console.log(
4113
+ line(
4114
+ false,
4115
+ `POST /trigger/events/${event.id}/actions/${failure.action}`,
4116
+ securedDetail(failure.status)
4117
+ )
4118
+ );
4119
+ }
4120
+ const okCount = actions.length - failed.length;
4121
+ if (okCount > 0) {
4122
+ console.log(
4123
+ line(true, pattern, `${okCount} other action(s) require auth`)
4124
+ );
4125
+ }
4126
+ }
4127
+ }
4128
+ }
4129
+ console.log();
4130
+ console.log((0, import_colors.bold)("Translations served (must cover the copy core requires):"));
4131
+ failures += await verifyTranslations(baseUrl);
4132
+ console.log();
4133
+ if (failures > 0) {
4134
+ console.log(
4135
+ (0, import_colors.red)((0, import_colors.bold)(`\u2717 ${failures} check(s) failed.`)) + (0, import_colors.yellow)(" See the lines marked \u2717 above.")
4136
+ );
4137
+ process.exit(1);
4138
+ }
4139
+ console.log((0, import_colors.green)((0, import_colors.bold)("\u2713 All endpoint checks passed.")));
4140
+ }
4141
+
3451
4142
  // src/cli.ts
3452
4143
  var args = process.argv.slice(2);
3453
4144
  var USAGE = `
@@ -3456,10 +4147,37 @@ Usage: opencrvs <command>
3456
4147
  Commands:
3457
4148
  environment Manage deployment environments
3458
4149
  upgrade Upgrade an existing environment
3459
- check-translations Check translation files for completeness
4150
+ verify-endpoints Verify the locally-running country config exposes the
4151
+ expected endpoints, keeps secured ones locked down and
4152
+ serves the translations core requires
3460
4153
 
3461
4154
  Run 'opencrvs <command> --help' for more information on a command.
3462
4155
  `.trim();
4156
+ var VERIFY_ENDPOINTS_USAGE = `
4157
+ Usage: opencrvs verify-endpoints [country-config-url]
4158
+
4159
+ Run this after 'opencrvs upgrade', with the upgraded country config running
4160
+ locally, to confirm it still behaves correctly. It checks over HTTP that:
4161
+ - required public endpoints exist (respond 2xx),
4162
+ - user-notification trigger endpoints are either absent or reject
4163
+ unauthenticated requests (never processed without a token), and
4164
+ - '/content/client' and '/content/login' serve every message id the country
4165
+ config template of this version carries.
4166
+
4167
+ Checking the translations reads the template off GitHub. When GitHub cannot be
4168
+ reached the other checks still run and that one is skipped with a warning.
4169
+
4170
+ Arguments:
4171
+ [country-config-url] Optional. Domain or URL of the country config
4172
+ service. Defaults to 'http://localhost:3040', the
4173
+ port country config listens on locally. A bare
4174
+ domain is assumed to use https.
4175
+
4176
+ Options:
4177
+ -h, --help Show this message.
4178
+
4179
+ Exits with a non-zero status if any check fails.
4180
+ `.trim();
3463
4181
  var UPGRADE_USAGE = `
3464
4182
  Usage: opencrvs upgrade [options]
3465
4183
 
@@ -3467,13 +4185,9 @@ Upgrade the country config in the current working directory to the next
3467
4185
  major version of OpenCRVS.
3468
4186
 
3469
4187
  Options:
3470
- --docker-swarm Keep and merge the 'infrastructure/' directory with
3471
- upstream changes. Use this if your country deploys
3472
- OpenCRVS via Docker Swarm. When omitted, the
3473
- 'infrastructure/' directory is deleted (default).
3474
4188
  -h, --help Show this message.
3475
4189
  `.trim();
3476
- function main2() {
4190
+ function main3() {
3477
4191
  const command = args[0];
3478
4192
  if (!command || command === "--help" || command === "-h") {
3479
4193
  console.log(USAGE);
@@ -3484,8 +4198,8 @@ function main2() {
3484
4198
  return handleEnvironment();
3485
4199
  case "upgrade":
3486
4200
  return handleUpgrade();
3487
- case "check-translations":
3488
- return handleCheckTranslations();
4201
+ case "verify-endpoints":
4202
+ return handleVerifyEndpoints();
3489
4203
  default:
3490
4204
  console.error(`Unknown command: ${command}
3491
4205
  `);
@@ -3549,29 +4263,45 @@ async function handleUpgrade() {
3549
4263
  console.log(UPGRADE_USAGE);
3550
4264
  process.exit(0);
3551
4265
  }
3552
- const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--docker-swarm"]);
3553
- const unknownFlags = upgradeArgs.filter(
3554
- (arg) => arg.startsWith("-") && !KNOWN_FLAGS.has(arg)
3555
- );
4266
+ const unknownFlags = upgradeArgs.filter((arg) => arg.startsWith("-"));
3556
4267
  if (unknownFlags.length > 0) {
3557
4268
  console.error(`Unknown option(s): ${unknownFlags.join(", ")}
3558
4269
  `);
3559
4270
  console.log(UPGRADE_USAGE);
3560
4271
  process.exit(1);
3561
4272
  }
3562
- const dockerSwarm = upgradeArgs.includes("--docker-swarm");
3563
4273
  console.log("Initiating upgrade...");
3564
4274
  try {
3565
- await runUpgrade(dockerSwarm);
4275
+ await runUpgrade();
3566
4276
  console.log("Upgrade completed successfully!");
3567
4277
  } catch (error3) {
3568
4278
  console.error("Upgrade failed:", error3);
3569
4279
  process.exit(1);
3570
4280
  }
3571
4281
  }
3572
- function handleCheckTranslations() {
3573
- console.log("Checking translations...");
3574
- console.warn("This command is not implemented yet!");
3575
- process.exit(1);
4282
+ async function handleVerifyEndpoints() {
4283
+ const verifyArgs = args.slice(1);
4284
+ if (verifyArgs.includes("--help") || verifyArgs.includes("-h")) {
4285
+ console.log(VERIFY_ENDPOINTS_USAGE);
4286
+ process.exit(0);
4287
+ }
4288
+ const positional = verifyArgs.filter((arg) => !arg.startsWith("-"));
4289
+ if (positional.length > 1) {
4290
+ console.error(
4291
+ `Unexpected extra argument(s): ${positional.slice(1).join(", ")}
4292
+ `
4293
+ );
4294
+ console.log(VERIFY_ENDPOINTS_USAGE);
4295
+ process.exit(1);
4296
+ }
4297
+ try {
4298
+ await runVerifyEndpoints(positional[0]);
4299
+ } catch (error3) {
4300
+ console.error(
4301
+ "Endpoint verification failed:",
4302
+ error3 instanceof Error ? error3.message : error3
4303
+ );
4304
+ process.exit(1);
4305
+ }
3576
4306
  }
3577
- main2();
4307
+ main3();