@opencrvs/toolkit 2.1.0-rc.d7bd264 → 2.1.0-rc.d987aec

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 (107) hide show
  1. package/README.md +3 -12
  2. package/build.sh +9 -1
  3. package/create-countryconfig/index.js +412 -59
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +4 -1
  6. package/dist/application-config/index.js +266 -212
  7. package/dist/authentication/index.d.ts +67 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +750 -0
  10. package/dist/cli.js +1786 -120
  11. package/dist/commons/api/router.d.ts +691 -76
  12. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  13. package/dist/commons/conditionals/validate.d.ts +15 -5
  14. package/dist/commons/events/ActionConfig.d.ts +0 -21
  15. package/dist/commons/events/ActionDocument.d.ts +4 -4
  16. package/dist/commons/events/ActionInput.d.ts +4 -4
  17. package/dist/commons/events/AdvancedSearchConfig.d.ts +18 -0
  18. package/dist/commons/events/AuditLog.d.ts +147 -0
  19. package/dist/commons/events/CountryConfigQueryInput.d.ts +0 -18
  20. package/dist/commons/events/EventConfig.d.ts +3 -0
  21. package/dist/commons/events/EventDocument.d.ts +470 -2
  22. package/dist/commons/events/EventIndex.d.ts +2 -6
  23. package/dist/commons/events/EventMetadata.d.ts +1 -12
  24. package/dist/commons/events/EventStatus.d.ts +19 -0
  25. package/dist/commons/events/FieldConfig.d.ts +84 -53
  26. package/dist/commons/events/FieldTypeMapping.d.ts +15 -15
  27. package/dist/commons/events/FieldValue.d.ts +2 -2
  28. package/dist/commons/events/Flag.d.ts +0 -6
  29. package/dist/commons/events/PlainDate.d.ts +8 -0
  30. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  31. package/dist/commons/events/WorkqueueConfig.d.ts +5 -17
  32. package/dist/commons/events/event.d.ts +12 -0
  33. package/dist/commons/events/index.d.ts +1 -0
  34. package/dist/commons/events/locationPayloads.d.ts +95 -0
  35. package/dist/commons/events/locations.d.ts +169 -26
  36. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  37. package/dist/commons/events/test.utils.d.ts +25 -4
  38. package/dist/commons/events/utils.d.ts +13 -2
  39. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  40. package/dist/commons/notification/dispatch.d.ts +10 -0
  41. package/dist/commons/notification/index.d.ts +1 -0
  42. package/dist/conditionals/index.js +81 -59
  43. package/dist/csv.d.ts +25 -0
  44. package/dist/csv.d.ts.map +1 -0
  45. package/dist/csv.js +120 -0
  46. package/dist/environment/index.d.ts +1 -0
  47. package/dist/environment/index.d.ts.map +1 -1
  48. package/dist/environment/index.js +10 -0
  49. package/dist/environment/logger.d.ts +15 -3
  50. package/dist/environment/logger.d.ts.map +1 -1
  51. package/dist/environment/manage-users.js +1 -1
  52. package/dist/environment/paths.d.ts +7 -0
  53. package/dist/environment/paths.d.ts.map +1 -0
  54. package/dist/environment/paths.js +72 -0
  55. package/dist/environment/questions.d.ts.map +1 -1
  56. package/dist/environment/questions.js +20 -14
  57. package/dist/environment/setup-environment.js +28 -7
  58. package/dist/environment/templates.d.ts +0 -1
  59. package/dist/environment/templates.d.ts.map +1 -1
  60. package/dist/environment/templates.js +5 -9
  61. package/dist/environment/update-workflows.d.ts.map +1 -1
  62. package/dist/environment/update-workflows.js +17 -5
  63. package/dist/environment/upgrade.d.ts +2 -0
  64. package/dist/environment/upgrade.d.ts.map +1 -0
  65. package/dist/environment/upgrade.js +82 -0
  66. package/dist/environment/users.js +11 -13
  67. package/dist/events/index.js +2905 -2463
  68. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  69. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  70. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  71. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  72. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  73. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  74. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  75. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  76. package/dist/migrations/v2.1/add-translations.js +213 -0
  77. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  78. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  79. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  80. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  81. package/dist/migrations/v2.1/index.js +1058 -0
  82. package/dist/notification/index.js +1317 -1475
  83. package/dist/scopes/index.d.ts +104 -59
  84. package/dist/scopes/index.js +81 -59
  85. package/dist/telemetry/index.d.ts +45 -0
  86. package/dist/telemetry/index.d.ts.map +1 -0
  87. package/dist/telemetry/index.js +39 -0
  88. package/dist/templates/charts-values/dependencies/values.yaml +2 -0
  89. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  90. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  91. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  92. package/dist/templates/inventory/inventory.template.yml +1 -3
  93. package/dist/translations/check.d.ts +21 -0
  94. package/dist/translations/check.d.ts.map +1 -0
  95. package/dist/translations/check.js +132 -0
  96. package/dist/verify/endpoints.d.ts +2 -0
  97. package/dist/verify/endpoints.d.ts.map +1 -0
  98. package/dist/verify/endpoints.js +345 -0
  99. package/opencrvs-toolkit-2.1.0-rc.d987aec.tgz +0 -0
  100. package/package.json +12 -6
  101. package/tsconfig.build.json +11 -0
  102. package/tsconfig.build.tsbuildinfo +1 -0
  103. package/tsconfig.json +3 -0
  104. package/dist/templates/inventory/production.example.yml +0 -77
  105. package/dist/templates/inventory/qa.example.yml +0 -48
  106. package/opencrvs-toolkit-2.1.0-rc.d7bd264.tgz +0 -0
  107. package/tsconfig.tsbuildinfo +0 -1
package/dist/cli.js CHANGED
@@ -30,6 +30,42 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  mod
31
31
  ));
32
32
 
33
+ // src/environment/paths.ts
34
+ function getEnvironmentInventoryPath(environment) {
35
+ return (0, import_path6.join)("environments", environment, INVENTORY_FILE_NAME);
36
+ }
37
+ function findOldInventoryFiles() {
38
+ return glob.sync((0, import_path6.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
+ }
40
+ function getEnvironmentNameFromOldInventoryPath(filePath) {
41
+ return (0, import_path6.basename)(filePath, ".yml");
42
+ }
43
+ function assertNoOldInventoryLayout() {
44
+ if (findOldInventoryFiles().length === 0) {
45
+ return;
46
+ }
47
+ throw new Error(
48
+ [
49
+ `Old inventory layout detected at ${OLD_INVENTORY_DIR}.`,
50
+ "Please run `yarn environment:upgrade` before running `yarn environment:init`."
51
+ ].join(" ")
52
+ );
53
+ }
54
+ var import_path6, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
+ var init_paths = __esm({
56
+ "src/environment/paths.ts"() {
57
+ "use strict";
58
+ import_path6 = require("path");
59
+ glob = __toESM(require("glob"));
60
+ OLD_INVENTORY_DIR = (0, import_path6.join)(
61
+ "infrastructure",
62
+ "server-setup",
63
+ "inventory"
64
+ );
65
+ INVENTORY_FILE_NAME = "inventory.yml";
66
+ }
67
+ });
68
+
33
69
  // src/environment/logger.ts
34
70
  var import_kleur, log, warn, success, info, error;
35
71
  var init_logger = __esm({
@@ -471,9 +507,9 @@ function storeSecrets(environment, answers) {
471
507
  let envConfig = {};
472
508
  try {
473
509
  envConfig = import_dotenv.default.parse(
474
- (0, import_fs.readFileSync)(`${process.cwd()}/.env.${environment}`)
510
+ (0, import_fs4.readFileSync)(`${process.cwd()}/.env.${environment}`)
475
511
  );
476
- } catch (error4) {
512
+ } catch (error3) {
477
513
  envConfig = {};
478
514
  }
479
515
  const linesFromAnswers = answers.map(
@@ -481,10 +517,10 @@ function storeSecrets(environment, answers) {
481
517
  );
482
518
  const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
483
519
  const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
484
- (0, import_fs.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
520
+ (0, import_fs4.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
485
521
  }
486
522
  function readYamlFile(filePath) {
487
- const fileContent = import_fs.default.readFileSync(filePath, "utf8");
523
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
488
524
  return yaml.load(fileContent);
489
525
  }
490
526
  function writeYamlFile(filePath, data) {
@@ -497,33 +533,30 @@ function writeYamlFile(filePath, data) {
497
533
  noRefs: true,
498
534
  sortKeys: false
499
535
  });
500
- import_fs.default.writeFileSync(filePath, yamlContent, "utf8");
501
- } catch (error4) {
502
- throw new Error(`Failed to write inventory file: ${error4}`);
536
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
537
+ } catch (error3) {
538
+ throw new Error(`Failed to write inventory file: ${error3}`);
503
539
  }
504
540
  }
505
- var import_fs, yaml, import_dotenv;
541
+ var import_fs4, yaml, import_dotenv;
506
542
  var init_utils = __esm({
507
543
  "src/environment/utils.ts"() {
508
544
  "use strict";
509
- import_fs = __toESM(require("fs"));
545
+ import_fs4 = __toESM(require("fs"));
510
546
  yaml = __toESM(require("js-yaml"));
511
547
  import_dotenv = __toESM(require("dotenv"));
512
548
  }
513
549
  });
514
550
 
515
551
  // src/environment/templates.ts
516
- function getUsers(data) {
517
- if (!data?.all?.vars?.users) {
518
- return { users: [] };
519
- }
520
- return data.all.vars.users;
521
- }
522
552
  function extractAndModifyUsers(data) {
523
553
  if (!data?.all?.vars?.users) {
524
554
  return { users: [] };
525
555
  }
526
556
  const users = data.all.vars.users.map((user) => {
557
+ if (user.role) {
558
+ return user;
559
+ }
527
560
  const { sudoer, ...rest } = user;
528
561
  return {
529
562
  ...rest,
@@ -559,29 +592,29 @@ function extractWorkerNodes(data) {
559
592
  return worker_hosts;
560
593
  }
561
594
  function copyChartsValues(env, values) {
562
- const srcDir = import_path2.default.resolve(__dirname, "templates", "charts-values");
563
- const destDir = import_path2.default.resolve(process.cwd(), "environments", env);
564
- import_fs2.default.mkdirSync(destDir, { recursive: true });
595
+ const srcDir = import_path7.default.resolve(__dirname, "templates", "charts-values");
596
+ const destDir = import_path7.default.resolve(process.cwd(), "environments", env);
597
+ import_fs5.default.mkdirSync(destDir, { recursive: true });
565
598
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
566
599
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
567
600
  values["opencrvs_environment"] = env;
568
601
  function copyRecursive(src, dest) {
569
- const stat = import_fs2.default.statSync(src);
602
+ const stat = import_fs5.default.statSync(src);
570
603
  if (stat.isDirectory()) {
571
- import_fs2.default.mkdirSync(dest, { recursive: true });
572
- for (const item of import_fs2.default.readdirSync(src)) {
573
- copyRecursive(import_path2.default.join(src, item), import_path2.default.join(dest, item));
604
+ import_fs5.default.mkdirSync(dest, { recursive: true });
605
+ for (const item of import_fs5.default.readdirSync(src)) {
606
+ copyRecursive(import_path7.default.join(src, item), import_path7.default.join(dest, item));
574
607
  }
575
608
  } else {
576
- const content = import_fs2.default.readFileSync(src, "utf8");
609
+ const content = import_fs5.default.readFileSync(src, "utf8");
577
610
  const template = import_handlebars.default.compile(content);
578
611
  const updated = template(values);
579
612
  const isOverridesFile = dest.endsWith("override.yaml");
580
- if (isOverridesFile && import_fs2.default.existsSync(dest)) {
613
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
581
614
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
582
615
  return;
583
616
  }
584
- import_fs2.default.writeFileSync(dest, updated, "utf8");
617
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
585
618
  log(` \u2713 Created: ${dest}`);
586
619
  }
587
620
  }
@@ -592,36 +625,31 @@ function copyChartsValues(env, values) {
592
625
  `);
593
626
  }
594
627
  function generateInventory(env, values) {
595
- const templatePath = import_path2.default.join(
628
+ const templatePath = import_path7.default.join(
596
629
  __dirname,
597
630
  "templates",
598
631
  "inventory",
599
632
  "inventory.template.yml"
600
633
  );
601
- const outputPath = import_path2.default.join(
602
- process.cwd(),
603
- "infrastructure",
604
- "server-setup",
605
- "inventory",
606
- `${env}.yml`
607
- );
608
- const templateFile = import_fs2.default.readFileSync(templatePath, "utf-8");
634
+ const outputPath = import_path7.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
635
+ const templateFile = import_fs5.default.readFileSync(templatePath, "utf-8");
609
636
  const template = import_handlebars.default.compile(templateFile);
610
637
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
611
638
  const updated = template(values);
612
- import_fs2.default.mkdirSync(import_path2.default.dirname(outputPath), { recursive: true });
613
- import_fs2.default.writeFileSync(outputPath, updated);
639
+ import_fs5.default.mkdirSync(import_path7.default.dirname(outputPath), { recursive: true });
640
+ import_fs5.default.writeFileSync(outputPath, updated);
614
641
  log(`
615
642
  \u2705 Generated inventory file at ${outputPath}
616
643
  `);
617
644
  }
618
- var import_fs2, import_path2, import_handlebars;
645
+ var import_fs5, import_path7, import_handlebars;
619
646
  var init_templates = __esm({
620
647
  "src/environment/templates.ts"() {
621
648
  "use strict";
622
- import_fs2 = __toESM(require("fs"));
623
- import_path2 = __toESM(require("path"));
649
+ import_fs5 = __toESM(require("fs"));
650
+ import_path7 = __toESM(require("path"));
624
651
  init_logger();
652
+ init_paths();
625
653
  import_handlebars = __toESM(require("handlebars"));
626
654
  import_handlebars.default.registerHelper("data_label_idx", function(value) {
627
655
  return parseInt(value) + 2;
@@ -675,18 +703,18 @@ var init_git = __esm({
675
703
  });
676
704
 
677
705
  // src/environment/questions.ts
678
- function validateCIDR(input3) {
679
- if (!input3.trim()) {
706
+ function validateCIDR(input4) {
707
+ if (!input4.trim()) {
680
708
  return true;
681
709
  }
682
710
  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])$/;
683
- return cidrRegex.test(input3.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
711
+ return cidrRegex.test(input4.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
684
712
  }
685
- function validateCIDRs(input3) {
686
- if (!input3.trim()) {
713
+ function validateCIDRs(input4) {
714
+ if (!input4.trim()) {
687
715
  return true;
688
716
  }
689
- const cidrs = input3.split(",").map((v) => v.trim());
717
+ const cidrs = input4.split(",").map((v) => v.trim());
690
718
  for (const cidr of cidrs) {
691
719
  const result = validateCIDR(cidr);
692
720
  if (result !== true) {
@@ -829,11 +857,28 @@ var init_questions = __esm({
829
857
  scope: "ENVIRONMENT"
830
858
  },
831
859
  {
832
- name: "kubeAPIHost",
860
+ name: "kubeMasterNode",
861
+ type: "text",
862
+ message: `Kubernetes master node hostnames or IP (default: auto-detect)`,
863
+ valueType: "VARIABLE",
864
+ valueLabel: "KUBE_MASTER_NODE",
865
+ initial: process.env.KUBE_MASTER_NODE,
866
+ scope: "ENVIRONMENT"
867
+ },
868
+ {
869
+ name: "kubeWorkerNodes",
833
870
  type: "text",
834
- message: `Kubernetes API endpoint (default: auto-detect)`,
871
+ message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
872
+ valueType: "VARIABLE",
873
+ valueLabel: "KUBE_WORKER_NODES",
874
+ initial: process.env.KUBE_WORKER_NODES || "",
875
+ scope: "ENVIRONMENT"
876
+ },
877
+ {
878
+ name: "kubeApiHost",
879
+ type: "text",
880
+ message: `Kubernetes API endpoint IP (default: KUBE_MASTER_NODE)`,
835
881
  valueType: "VARIABLE",
836
- // validate: notEmpty,
837
882
  valueLabel: "KUBE_API_HOST",
838
883
  initial: process.env.KUBE_API_HOST,
839
884
  scope: "ENVIRONMENT"
@@ -847,16 +892,6 @@ var init_questions = __esm({
847
892
  valueLabel: "KUBE_API_ALLOWED_CIDRS",
848
893
  initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
849
894
  scope: "ENVIRONMENT"
850
- },
851
- {
852
- name: "kubeWorkerNodes",
853
- type: "text",
854
- message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
855
- valueType: "VARIABLE",
856
- // validate: notEmpty,
857
- valueLabel: "KUBE_WORKER_NODES",
858
- initial: process.env.KUBE_WORKER_NODES || "",
859
- scope: "ENVIRONMENT"
860
895
  }
861
896
  ];
862
897
  staticSSLCertQuestions = [
@@ -887,7 +922,6 @@ var init_questions = __esm({
887
922
  type: "text",
888
923
  message: `Please enter backup server host/IP address, (default: no backup):`,
889
924
  valueType: "VARIABLE",
890
- // validate: notEmpty,
891
925
  valueLabel: "BACKUP_HOST",
892
926
  initial: process.env.BACKUP_HOST || "",
893
927
  scope: "ENVIRONMENT"
@@ -1210,7 +1244,7 @@ function updateInventoryFile(filePath, users) {
1210
1244
  function parseInventoryFile(filePath) {
1211
1245
  try {
1212
1246
  const data = readYamlFile(filePath);
1213
- return getUsers(data);
1247
+ return extractAndModifyUsers(data);
1214
1248
  } catch {
1215
1249
  return [];
1216
1250
  }
@@ -1220,7 +1254,7 @@ function getCurrentUsername() {
1220
1254
  }
1221
1255
  function getCurrentUserSSHKeys() {
1222
1256
  const homeDir = os.homedir();
1223
- const sshDir = path3.join(homeDir, ".ssh");
1257
+ const sshDir = path7.join(homeDir, ".ssh");
1224
1258
  const keys = [];
1225
1259
  const keyFiles = [
1226
1260
  "id_rsa.pub",
@@ -1229,7 +1263,7 @@ function getCurrentUserSSHKeys() {
1229
1263
  "id_dsa.pub"
1230
1264
  ];
1231
1265
  for (const keyFile of keyFiles) {
1232
- const keyPath = path3.join(sshDir, keyFile);
1266
+ const keyPath = path7.join(sshDir, keyFile);
1233
1267
  try {
1234
1268
  if (fs3.existsSync(keyPath)) {
1235
1269
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1237,7 +1271,7 @@ function getCurrentUserSSHKeys() {
1237
1271
  keys.push(keyContent);
1238
1272
  }
1239
1273
  }
1240
- } catch (error4) {
1274
+ } catch (error3) {
1241
1275
  continue;
1242
1276
  }
1243
1277
  }
@@ -1570,13 +1604,13 @@ async function manageUsers(inventoryPath) {
1570
1604
  }
1571
1605
  return users;
1572
1606
  }
1573
- var os, fs3, path3, input2, select2, confirm, editor, checkbox;
1607
+ var os, fs3, path7, input2, select2, confirm, editor, checkbox;
1574
1608
  var init_manage_users = __esm({
1575
1609
  "src/environment/manage-users.ts"() {
1576
1610
  "use strict";
1577
1611
  os = __toESM(require("os"));
1578
1612
  fs3 = __toESM(require("fs"));
1579
- path3 = __toESM(require("path"));
1613
+ path7 = __toESM(require("path"));
1580
1614
  init_logger();
1581
1615
  init_utils();
1582
1616
  init_templates();
@@ -1598,6 +1632,10 @@ async function select3(options) {
1598
1632
  const inquirer = await import("@inquirer/prompts");
1599
1633
  return inquirer.select(options);
1600
1634
  }
1635
+ async function input3(options) {
1636
+ const inquirer = await import("@inquirer/prompts");
1637
+ return inquirer.input(options);
1638
+ }
1601
1639
  function questionToPrompt({
1602
1640
  valueType,
1603
1641
  valueLabel,
@@ -1773,6 +1811,7 @@ var init_setup_environment = __esm({
1773
1811
  init_editor_questions();
1774
1812
  init_questions_helper();
1775
1813
  init_manage_users();
1814
+ init_paths();
1776
1815
  ALL_QUESTIONS = [];
1777
1816
  ALL_ANSWERS = [];
1778
1817
  ALL_QUESTIONS.push(
@@ -1936,9 +1975,7 @@ var init_setup_environment = __esm({
1936
1975
  );
1937
1976
  const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1938
1977
  log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1939
- const users = await manageUsers(
1940
- `infrastructure/server-setup/inventory/${environment}.yml`
1941
- );
1978
+ const users = await manageUsers(getEnvironmentInventoryPath(environment));
1942
1979
  log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1943
1980
  const sslCertExists = findExistingValue(
1944
1981
  "SSL_CRT",
@@ -2030,6 +2067,7 @@ var init_setup_environment = __esm({
2030
2067
  "ENVIRONMENT",
2031
2068
  existingValues
2032
2069
  )?.value;
2070
+ let restoreHost = findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2033
2071
  let restoreType = findExistingValue(
2034
2072
  "RESTORE_ENVIRONMENT_MODE",
2035
2073
  "VARIABLE",
@@ -2105,6 +2143,10 @@ var init_setup_environment = __esm({
2105
2143
  }
2106
2144
  ]
2107
2145
  });
2146
+ restoreHost = await input3({
2147
+ message: "What is the host/IP address of the restore backup server?",
2148
+ default: restoreHost
2149
+ });
2108
2150
  } else {
2109
2151
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2110
2152
  }
@@ -2439,6 +2481,22 @@ var init_setup_environment = __esm({
2439
2481
  existingValues
2440
2482
  ),
2441
2483
  scope: "ENVIRONMENT"
2484
+ },
2485
+ {
2486
+ type: "VARIABLE",
2487
+ name: "RESTORE_HOST",
2488
+ value: answerOrExisting(
2489
+ restoreHost,
2490
+ findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues),
2491
+ (val) => val || ""
2492
+ ),
2493
+ didExist: findExistingValue(
2494
+ "RESTORE_HOST",
2495
+ "VARIABLE",
2496
+ "ENVIRONMENT",
2497
+ existingValues
2498
+ ),
2499
+ scope: "ENVIRONMENT"
2442
2500
  }
2443
2501
  ];
2444
2502
  if (enableEncryption) {
@@ -2690,7 +2748,7 @@ var init_setup_environment = __esm({
2690
2748
  log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2691
2749
  generateInventory(environment, {
2692
2750
  kube_worker_nodes: kubeWorkerNodes,
2693
- kube_api_host: infrastructure.kubeAPIHost || "",
2751
+ kube_api_host: infrastructure.kubeApiHost || "",
2694
2752
  backup_host: backupHost || "",
2695
2753
  users
2696
2754
  });
@@ -2701,12 +2759,14 @@ var init_setup_environment = __esm({
2701
2759
  // Hardcode like this blocks us from being generic:
2702
2760
  // https://github.com/opencrvs/opencrvs-core/issues/11171
2703
2761
  two_fa_enabled: environment !== "production" ? false : true,
2704
- backup_enabled: configureBackup ? true : false,
2762
+ traefik_mode: traefikConfOption,
2705
2763
  restore_enabled: restoreEnvironmentName ? true : false,
2706
2764
  restore_environment_name: restoreEnvironmentName || "",
2707
2765
  restore_type: restoreType,
2708
- traefik_mode: traefikConfOption,
2709
- backup_type: backupType
2766
+ restore_host: restoreHost || "",
2767
+ backup_enabled: configureBackup ? true : false,
2768
+ backup_type: backupType,
2769
+ backup_host: backupHost || ""
2710
2770
  });
2711
2771
  let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2712
2772
 
@@ -2751,12 +2811,19 @@ var update_workflows_exports = {};
2751
2811
  __export(update_workflows_exports, {
2752
2812
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
2753
2813
  });
2814
+ function isDirectory(path10) {
2815
+ try {
2816
+ return (0, import_fs6.statSync)(path10).isDirectory();
2817
+ } catch {
2818
+ return false;
2819
+ }
2820
+ }
2754
2821
  async function extractInfrastructureNames() {
2755
- const files = glob.sync("infrastructure/server-setup/inventory/*.yml");
2756
- const infraEnvironments = files.map((file) => (0, import_path3.basename)(file, ".yml"));
2822
+ const files = glob2.sync((0, import_path8.join)("environments", "*", INVENTORY_FILE_NAME));
2823
+ const infraEnvironments = files.map((file) => (0, import_path8.basename)((0, import_path8.dirname)(file)));
2757
2824
  if (infraEnvironments.length === 0) {
2758
2825
  console.log(
2759
- "\u26A0\uFE0F Warning: No environment directories found in infrastructure/server-setup/inventory/"
2826
+ `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
2760
2827
  );
2761
2828
  return [];
2762
2829
  }
@@ -2766,8 +2833,9 @@ async function extractInfrastructureNames() {
2766
2833
  async function extractEnvironmentNames() {
2767
2834
  const entries = await (0, import_promises.readdir)("environments");
2768
2835
  const environments = entries.filter((entry) => {
2769
- const fullPath = (0, import_path3.join)("environments", entry);
2770
- return (0, import_fs3.statSync)(fullPath).isDirectory();
2836
+ const environmentPath = (0, import_path8.join)("environments", entry);
2837
+ const opencrvsServicesPath = (0, import_path8.join)(environmentPath, "opencrvs-services");
2838
+ return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
2771
2839
  });
2772
2840
  if (environments.length === 0) {
2773
2841
  console.log(
@@ -2793,7 +2861,7 @@ async function updateWorkflows(envList, config) {
2793
2861
  const { workflows } = config;
2794
2862
  for (const workflowPath of workflows) {
2795
2863
  try {
2796
- const fileContents = (0, import_fs3.readFileSync)(workflowPath, "utf8");
2864
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
2797
2865
  const workflowData = yaml2.load(fileContents);
2798
2866
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2799
2867
  throw new Error(
@@ -2801,15 +2869,15 @@ async function updateWorkflows(envList, config) {
2801
2869
  );
2802
2870
  }
2803
2871
  const updatedContent = updateOptionsInYaml(fileContents, envList);
2804
- (0, import_fs3.writeFileSync)(workflowPath, updatedContent, "utf8");
2872
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
2805
2873
  log(` \u2713 Successfully updated ${workflowPath}`);
2806
- } catch (error4) {
2874
+ } catch (error3) {
2807
2875
  console.error(
2808
2876
  `
2809
2877
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
2810
2878
  );
2811
- console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2812
- throw error4;
2879
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
2880
+ throw error3;
2813
2881
  }
2814
2882
  }
2815
2883
  }
@@ -2850,21 +2918,90 @@ async function updateWorkflowEnvironments() {
2850
2918
  } else {
2851
2919
  log("\u2139\uFE0F No workflows were updated.");
2852
2920
  }
2853
- } catch (error4) {
2854
- console.error("\n\u274C Error updating workflows:", error4);
2921
+ } catch (error3) {
2922
+ console.error("\n\u274C Error updating workflows:", error3);
2855
2923
  process.exit(1);
2856
2924
  }
2857
2925
  }
2858
- var import_promises, import_fs3, import_path3, glob, yaml2;
2926
+ var import_promises, import_fs6, import_path8, glob2, yaml2;
2859
2927
  var init_update_workflows = __esm({
2860
2928
  "src/environment/update-workflows.ts"() {
2861
2929
  "use strict";
2862
2930
  import_promises = require("fs/promises");
2863
- import_fs3 = require("fs");
2864
- import_path3 = require("path");
2865
- glob = __toESM(require("glob"));
2931
+ import_fs6 = require("fs");
2932
+ import_path8 = require("path");
2933
+ glob2 = __toESM(require("glob"));
2866
2934
  yaml2 = __toESM(require("js-yaml"));
2867
2935
  init_logger();
2936
+ init_paths();
2937
+ }
2938
+ });
2939
+
2940
+ // src/environment/upgrade.ts
2941
+ var upgrade_exports = {};
2942
+ __export(upgrade_exports, {
2943
+ upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2944
+ });
2945
+ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2946
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2947
+ return false;
2948
+ }
2949
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2950
+ warn(
2951
+ `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2952
+ );
2953
+ return false;
2954
+ }
2955
+ (0, import_fs7.mkdirSync)((0, import_path9.dirname)(destinationPath), { recursive: true });
2956
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2957
+ log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2958
+ return true;
2959
+ }
2960
+ function migrateInventoryFiles() {
2961
+ const oldInventoryFiles = findOldInventoryFiles();
2962
+ if (oldInventoryFiles.length === 0) {
2963
+ log(`\u2139\uFE0F No old inventory files found at ${OLD_INVENTORY_DIR}`);
2964
+ return false;
2965
+ }
2966
+ log(import_kleur5.default.bold("\nMigrating Ansible inventory files"));
2967
+ let didMoveInventory = false;
2968
+ for (const oldInventoryFile of oldInventoryFiles) {
2969
+ const environment = getEnvironmentNameFromOldInventoryPath(oldInventoryFile);
2970
+ didMoveInventory = moveFileIfDestinationMissing(
2971
+ oldInventoryFile,
2972
+ getEnvironmentInventoryPath(environment)
2973
+ ) || didMoveInventory;
2974
+ }
2975
+ try {
2976
+ if ((0, import_fs7.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs7.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2977
+ (0, import_fs7.rmdirSync)(OLD_INVENTORY_DIR);
2978
+ log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2979
+ }
2980
+ } catch {
2981
+ warn(`\u26A0\uFE0F Could not remove ${OLD_INVENTORY_DIR}; please review it manually`);
2982
+ }
2983
+ return didMoveInventory;
2984
+ }
2985
+ async function upgradeEnvironmentLayout() {
2986
+ const didMoveInventory = migrateInventoryFiles();
2987
+ await updateWorkflowEnvironments();
2988
+ if (didMoveInventory) {
2989
+ success("\n\u2705 Environment layout upgrade completed successfully.");
2990
+ } else {
2991
+ success("\n\u2705 Environment layout already uses the current structure.");
2992
+ }
2993
+ log("\nCommit changes into git after upgrade");
2994
+ }
2995
+ var import_fs7, import_path9, import_kleur5;
2996
+ var init_upgrade = __esm({
2997
+ "src/environment/upgrade.ts"() {
2998
+ "use strict";
2999
+ import_fs7 = require("fs");
3000
+ import_path9 = require("path");
3001
+ import_kleur5 = __toESM(require("kleur"));
3002
+ init_logger();
3003
+ init_paths();
3004
+ init_update_workflows();
2868
3005
  }
2869
3006
  });
2870
3007
 
@@ -2877,7 +3014,7 @@ async function select4(options) {
2877
3014
  const inquirer = await import("@inquirer/prompts");
2878
3015
  return inquirer.select(options);
2879
3016
  }
2880
- async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
3017
+ async function selectInventoryFile(dirPath = "./environments") {
2881
3018
  if (!fs4.existsSync(dirPath)) {
2882
3019
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
2883
3020
  warn(
@@ -2885,22 +3022,20 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2885
3022
  );
2886
3023
  return null;
2887
3024
  }
2888
- const files = fs4.readdirSync(dirPath).filter((file) => {
2889
- const filePath = path4.join(dirPath, file);
2890
- const isFile = fs4.statSync(filePath).isFile();
2891
- const ext = path4.extname(file).slice(1).toLowerCase();
2892
- return isFile && (ext === "yml" || ext === "yaml");
3025
+ const environments = fs4.readdirSync(dirPath).filter((entry) => {
3026
+ const filePath = path8.join(dirPath, entry);
3027
+ return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
2893
3028
  }).sort();
2894
- if (files.length === 0) {
3029
+ if (environments.length === 0) {
2895
3030
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
2896
3031
  warn(
2897
3032
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
2898
3033
  );
2899
3034
  return null;
2900
3035
  }
2901
- const choices = files.map((file) => ({
2902
- name: path4.basename(file, path4.extname(file)),
2903
- value: path4.join(dirPath, file)
3036
+ const choices = environments.map((environment) => ({
3037
+ name: environment,
3038
+ value: getEnvironmentInventoryPath(environment)
2904
3039
  }));
2905
3040
  const selectedFile = await select4({
2906
3041
  message: "Select environment (inventory file) to load users:",
@@ -2909,33 +3044,34 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2909
3044
  return selectedFile;
2910
3045
  }
2911
3046
  async function manageEnvironmentUsers() {
2912
- console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
3047
+ console.log("\n", import_kleur6.default.bold().underline("Manage users"), "\n");
2913
3048
  const inventory_file = await selectInventoryFile();
2914
3049
  if (!inventory_file) {
2915
3050
  return;
2916
3051
  }
2917
3052
  await manageUsers(inventory_file);
2918
3053
  }
2919
- var fs4, path4, import_kleur5;
3054
+ var fs4, path8, import_kleur6;
2920
3055
  var init_users = __esm({
2921
3056
  "src/environment/users.ts"() {
2922
3057
  "use strict";
2923
3058
  fs4 = __toESM(require("fs"));
2924
- path4 = __toESM(require("path"));
2925
- import_kleur5 = __toESM(require("kleur"));
3059
+ path8 = __toESM(require("path"));
3060
+ import_kleur6 = __toESM(require("kleur"));
2926
3061
  init_manage_users();
2927
3062
  init_logger();
3063
+ init_paths();
2928
3064
  }
2929
3065
  });
2930
3066
 
2931
3067
  // src/environment/swarm-to-k8s.ts
2932
3068
  var swarm_to_k8s_exports = {};
2933
- var path5, import_kleur6, import_core2;
3069
+ var path9, import_kleur7, import_core2;
2934
3070
  var init_swarm_to_k8s = __esm({
2935
3071
  "src/environment/swarm-to-k8s.ts"() {
2936
3072
  "use strict";
2937
- path5 = __toESM(require("path"));
2938
- import_kleur6 = __toESM(require("kleur"));
3073
+ path9 = __toESM(require("path"));
3074
+ import_kleur7 = __toESM(require("kleur"));
2939
3075
  init_logger();
2940
3076
  init_utils();
2941
3077
  init_templates();
@@ -2944,7 +3080,7 @@ var init_swarm_to_k8s = __esm({
2944
3080
  init_github();
2945
3081
  (async () => {
2946
3082
  log(
2947
- import_kleur6.default.bold(
3083
+ import_kleur7.default.bold(
2948
3084
  "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2949
3085
  )
2950
3086
  );
@@ -2975,7 +3111,7 @@ var init_swarm_to_k8s = __esm({
2975
3111
  );
2976
3112
  process.exit(0);
2977
3113
  }
2978
- log(import_kleur6.default.bold().underline("Migration properties:"));
3114
+ log(import_kleur7.default.bold().underline("Migration properties:"));
2979
3115
  log(` \u2713 Environment: ${environment}`);
2980
3116
  const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
2981
3117
  if (!old_inventory_path) {
@@ -2986,7 +3122,7 @@ var init_swarm_to_k8s = __esm({
2986
3122
  );
2987
3123
  process.exit(1);
2988
3124
  }
2989
- const ansible_inventory = path5.join(old_inventory_path, environment + ".yml");
3125
+ const ansible_inventory = path9.join(old_inventory_path, environment + ".yml");
2990
3126
  const data = readYamlFile(ansible_inventory);
2991
3127
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
2992
3128
  const master = dockerManagerFirst(data) || "";
@@ -3287,14 +3423,1158 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
3287
3423
  );
3288
3424
  }
3289
3425
 
3426
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3427
+ var import_ts_morph2 = require("ts-morph");
3428
+ var import_fs2 = require("fs");
3429
+ var import_path2 = __toESM(require("path"));
3430
+
3431
+ // src/csv.ts
3432
+ var import_fs = require("fs");
3433
+ function parseCsvLine(line2) {
3434
+ const values = [];
3435
+ let value = "";
3436
+ let quoted = false;
3437
+ for (let index = 0; index < line2.length; index++) {
3438
+ const character = line2[index];
3439
+ if (quoted) {
3440
+ if (character !== '"') {
3441
+ value += character;
3442
+ } else if (line2[index + 1] === '"') {
3443
+ value += '"';
3444
+ index++;
3445
+ } else {
3446
+ quoted = false;
3447
+ }
3448
+ continue;
3449
+ }
3450
+ if (character === '"') {
3451
+ quoted = true;
3452
+ } else if (character === ",") {
3453
+ values.push(value);
3454
+ value = "";
3455
+ } else {
3456
+ value += character;
3457
+ }
3458
+ }
3459
+ values.push(value);
3460
+ return values;
3461
+ }
3462
+ function toCsvLine(values) {
3463
+ return values.map(
3464
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
3465
+ ).join(",");
3466
+ }
3467
+ function idOf(line2) {
3468
+ const comma = line2.indexOf(",");
3469
+ return comma === -1 ? line2 : line2.slice(0, comma);
3470
+ }
3471
+ function readCsvFile(path10) {
3472
+ if (!(0, import_fs.existsSync)(path10)) {
3473
+ return void 0;
3474
+ }
3475
+ const contents = (0, import_fs.readFileSync)(path10, "utf8");
3476
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3477
+ const trailingNewline = /\r?\n$/.test(contents);
3478
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3479
+ const body = lines.slice(1).filter((line2) => line2 !== "");
3480
+ return { header: lines[0], body, newline, trailingNewline };
3481
+ }
3482
+ function writeCsvFile(path10, file) {
3483
+ (0, import_fs.writeFileSync)(
3484
+ path10,
3485
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3486
+ );
3487
+ }
3488
+ function addRows(file, rows) {
3489
+ const isSorted = file.body.every(
3490
+ (line2, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line2)
3491
+ );
3492
+ const added = [];
3493
+ for (const row of rows) {
3494
+ const id = idOf(row);
3495
+ if (file.body.some((line2) => idOf(line2) === id)) {
3496
+ continue;
3497
+ }
3498
+ const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3499
+ if (insertAt === -1) {
3500
+ file.body.push(row);
3501
+ } else {
3502
+ file.body.splice(insertAt, 0, row);
3503
+ }
3504
+ added.push(id);
3505
+ }
3506
+ return added;
3507
+ }
3508
+
3509
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3510
+ var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3511
+ var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3512
+ var HANDLER_FILE = "src/api/notification/handler.ts";
3513
+ var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3514
+ var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3515
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
3516
+ var LOGIN_CSV = "src/translations/login.csv";
3517
+ var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3518
+ var TEMPLATES_OBJECT = "templates";
3519
+ var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3520
+ var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3521
+ var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3522
+ var ROUTES_FUNCTION = "getUserNotificationRoutes";
3523
+ var RECOVERY_EVENTS = [
3524
+ {
3525
+ id: "password-reset-link",
3526
+ constant: "PASSWORD_RESET_LINK",
3527
+ smsTemplate: "resetPasswordLinkNotification",
3528
+ emailSubject: "Reset your password",
3529
+ routeDescription: "Handles notification for password reset recovery link",
3530
+ heading: "Reset your password",
3531
+ reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3532
+ linkLabel: "Reset your password"
3533
+ },
3534
+ {
3535
+ id: "username-reminder-link",
3536
+ constant: "USERNAME_REMINDER_LINK",
3537
+ smsTemplate: "retrieveUsernameLinkNotification",
3538
+ emailSubject: "Retrieve your username",
3539
+ routeDescription: "Handles notification for username reminder recovery link",
3540
+ heading: "Retrieve your username",
3541
+ reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3542
+ linkLabel: "Retrieve your username"
3543
+ }
3544
+ ];
3545
+ var NOTIFICATION_CSV_ROWS = [
3546
+ `resetPasswordLinkNotification,The SMS message that is sent to a user containing a self-service password reset link,{{applicationName}}: reset your password using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9initialisez votre mot de passe \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`,
3547
+ `retrieveUsernameLinkNotification,The SMS message that is sent to a user containing a self-service username retrieval link,{{applicationName}}: retrieve your username using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9cup\xE9rez votre nom d'utilisateur \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`
3548
+ ];
3549
+ var LOGIN_CSV_ROWS = [
3550
+ `buttons.backToLogin,"Label used to leave a screen that is waiting on an emailed link, where logging in is not yet possible",Back to login,Retour \xE0 la connexion`,
3551
+ `resetCredentials.recoveryInstructionsSent.body,"Body message for the recovery instructions sent page. Must not assert delivery, since the account may not exist.","If we found an account, you'll receive instructions for {forgottenItem, select, username {retrieving your username} other {resetting your password}}. The link expires in 1 hour.","Si nous trouvons un compte correspondant, vous recevrez les instructions pour {forgottenItem, select, username {r\xE9cup\xE9rer votre nom d'utilisateur} other {r\xE9initialiser votre mot de passe}}. Le lien expire dans 1 heure."`,
3552
+ `resetCredentials.recoveryInstructionsSent.title.email,Title for the recovery instructions sent page when notifications are delivered by email,Check your email,V\xE9rifiez votre e-mail`,
3553
+ `resetCredentials.recoveryInstructionsSent.title.phone,Title for the recovery instructions sent page when notifications are delivered by SMS,Check your phone,V\xE9rifiez votre t\xE9l\xE9phone`,
3554
+ `resetCredentials.recoveryLinkLanding.expired.body,"Body shown when a recovery link is invalid, expired, or already used. Must not reveal whether the underlying account exists.",This link is no longer valid. Request a new one to continue.,Ce lien n'est plus valide. Veuillez en demander un nouveau pour continuer.`,
3555
+ `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3556
+ `resetCredentials.recoveryLinkLanding.expired.title,"Title shown when a recovery link is invalid, expired, or already used",This link has expired,Ce lien a expir\xE9`
3557
+ ];
3558
+ var skipped = [];
3559
+ function warnSkipped(message) {
3560
+ skipped.push(message);
3561
+ console.warn(` \u26A0\uFE0F ${message}`);
3562
+ }
3563
+ function findObjectLiteral(declaration) {
3564
+ let expression = declaration?.getInitializer();
3565
+ while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3566
+ expression = expression.getExpression();
3567
+ }
3568
+ return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3569
+ }
3570
+ function hasKeyFor(obj, key, constant) {
3571
+ const accepted = /* @__PURE__ */ new Set([
3572
+ `[TriggerEvent.${constant}]`,
3573
+ `['${key}']`,
3574
+ `["${key}"]`,
3575
+ `'${key}'`,
3576
+ `"${key}"`,
3577
+ key
3578
+ ]);
3579
+ return obj.getProperties().some(
3580
+ (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3581
+ );
3582
+ }
3583
+ function renderKey(obj, key, constant) {
3584
+ const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3585
+ if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3586
+ return `[TriggerEvent.${constant}]`;
3587
+ }
3588
+ if (names.some((name) => name.startsWith("["))) {
3589
+ return `['${key}']`;
3590
+ }
3591
+ return `'${key}'`;
3592
+ }
3593
+ function appendEntry(sourceFile, objectName, key, valueLines) {
3594
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3595
+ const properties = obj?.getProperties() ?? [];
3596
+ const lastProperty = properties[properties.length - 1];
3597
+ if (!lastProperty) return false;
3598
+ const indent = lastProperty.getIndentationText();
3599
+ const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${key}: ${line2}` : line2}`).join("\n");
3600
+ sourceFile.insertText(lastProperty.getEnd(), `,
3601
+ ${entry}`);
3602
+ return true;
3603
+ }
3604
+ function objectHasKeyFor(sourceFile, objectName, key, constant) {
3605
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3606
+ return obj ? hasKeyFor(obj, key, constant) : false;
3607
+ }
3608
+ function renderKeyFor(sourceFile, objectName, key, constant) {
3609
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3610
+ return obj ? renderKey(obj, key, constant) : `'${key}'`;
3611
+ }
3612
+ function updateEmailTemplates(project, cwd) {
3613
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3614
+ if (!sourceFile) {
3615
+ warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3616
+ return;
3617
+ }
3618
+ const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3619
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3620
+ );
3621
+ if (missingObject) {
3622
+ warnSkipped(
3623
+ `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3624
+ );
3625
+ return;
3626
+ }
3627
+ for (const event of RECOVERY_EVENTS) {
3628
+ if (!objectHasKeyFor(
3629
+ sourceFile,
3630
+ TRIGGER_VARIABLE_OBJECT,
3631
+ event.id,
3632
+ event.constant
3633
+ ) && appendEntry(
3634
+ sourceFile,
3635
+ TRIGGER_VARIABLE_OBJECT,
3636
+ renderKeyFor(
3637
+ sourceFile,
3638
+ TRIGGER_VARIABLE_OBJECT,
3639
+ event.id,
3640
+ event.constant
3641
+ ),
3642
+ [
3643
+ "z.object({",
3644
+ " firstname: z.string(),",
3645
+ " applicationName: z.string(),",
3646
+ " countryLogo: z.string(),",
3647
+ " recoveryURL: z.string()",
3648
+ "})"
3649
+ ]
3650
+ )) {
3651
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3652
+ }
3653
+ if (!objectHasKeyFor(
3654
+ sourceFile,
3655
+ TEMPLATES_OBJECT,
3656
+ event.id,
3657
+ event.constant
3658
+ ) && appendEntry(
3659
+ sourceFile,
3660
+ TEMPLATES_OBJECT,
3661
+ renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3662
+ [
3663
+ "{",
3664
+ ` type: '${event.id}',`,
3665
+ ` subject: '${event.emailSubject}',`,
3666
+ ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3667
+ ` '${event.id}'`,
3668
+ " )",
3669
+ "}"
3670
+ ]
3671
+ )) {
3672
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3673
+ }
3674
+ }
3675
+ }
3676
+ function updateSmsService(project, cwd) {
3677
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3678
+ if (!sourceFile) {
3679
+ warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3680
+ return;
3681
+ }
3682
+ const missingObject = [
3683
+ OTHER_TEMPLATES_OBJECT,
3684
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT
3685
+ ].find(
3686
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3687
+ );
3688
+ if (missingObject) {
3689
+ warnSkipped(
3690
+ `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3691
+ );
3692
+ return;
3693
+ }
3694
+ for (const event of RECOVERY_EVENTS) {
3695
+ if (!objectHasKeyFor(
3696
+ sourceFile,
3697
+ OTHER_TEMPLATES_OBJECT,
3698
+ event.smsTemplate,
3699
+ event.smsTemplate
3700
+ ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3701
+ `'${event.smsTemplate}'`
3702
+ ])) {
3703
+ console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3704
+ }
3705
+ if (!objectHasKeyFor(
3706
+ sourceFile,
3707
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3708
+ event.id,
3709
+ event.constant
3710
+ ) && appendEntry(
3711
+ sourceFile,
3712
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3713
+ renderKeyFor(
3714
+ sourceFile,
3715
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3716
+ event.id,
3717
+ event.constant
3718
+ ),
3719
+ [`'${event.smsTemplate}'`]
3720
+ )) {
3721
+ console.log(
3722
+ ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3723
+ );
3724
+ }
3725
+ }
3726
+ }
3727
+ function updateHandler(project, cwd) {
3728
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3729
+ if (!sourceFile) {
3730
+ warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3731
+ return;
3732
+ }
3733
+ const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3734
+ const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3735
+ if (!caseBlock) {
3736
+ warnSkipped(
3737
+ `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3738
+ );
3739
+ return;
3740
+ }
3741
+ const missing = RECOVERY_EVENTS.filter(
3742
+ (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3743
+ );
3744
+ if (missing.length === 0) return;
3745
+ const existingClauses = caseBlock.getClauses();
3746
+ if (existingClauses.length === 0) {
3747
+ warnSkipped(
3748
+ `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3749
+ );
3750
+ return;
3751
+ }
3752
+ const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3753
+ const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3754
+ const indent = anchor.getIndentationText();
3755
+ const lines = [
3756
+ ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3757
+ ` return {`,
3758
+ ` firstname,`,
3759
+ ` applicationName: applicationConfig.APPLICATION_NAME,`,
3760
+ ` countryLogo: COUNTRY_LOGO_URL,`,
3761
+ ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3762
+ ` }`
3763
+ ];
3764
+ if (defaultClause) {
3765
+ caseBlock.insertText(
3766
+ anchor.getStart(),
3767
+ `${lines.map((line2, index) => index === 0 ? line2 : `${indent}${line2}`).join("\n")}
3768
+ ${indent}`
3769
+ );
3770
+ } else {
3771
+ caseBlock.insertText(
3772
+ anchor.getEnd(),
3773
+ `
3774
+ ${lines.map((line2) => `${indent}${line2}`).join("\n")}`
3775
+ );
3776
+ }
3777
+ for (const event of missing) {
3778
+ console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3779
+ }
3780
+ }
3781
+ function updateRoutes(project, cwd) {
3782
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3783
+ if (!sourceFile) {
3784
+ warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3785
+ return;
3786
+ }
3787
+ const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3788
+ const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3789
+ if (!routesArray) {
3790
+ warnSkipped(
3791
+ `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3792
+ );
3793
+ return;
3794
+ }
3795
+ for (const event of RECOVERY_EVENTS) {
3796
+ if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
3797
+ routesArray.addElement(`{
3798
+ method: 'POST',
3799
+ path: '/triggers/user/${event.id}',
3800
+ handler: makeNotificationHandler('${event.id}'),
3801
+ options: {
3802
+ auth: false,
3803
+ tags: ['api'],
3804
+ description: '${event.routeDescription}'
3805
+ }
3806
+ }`);
3807
+ console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
3808
+ }
3809
+ }
3810
+ function renderEmailTemplate(event) {
3811
+ return `<!--
3812
+ This Source Code Form is subject to the terms of the Mozilla Public
3813
+ License, v. 2.0. If a copy of the MPL was not distributed with this
3814
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
3815
+
3816
+ OpenCRVS is also distributed under the terms of the Civil Registration
3817
+ & Healthcare Disclaimer located at http://opencrvs.org/license.
3818
+
3819
+ Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3820
+ -->
3821
+ <!doctype html>
3822
+ <html>
3823
+ <head>
3824
+ <link
3825
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3826
+ rel="stylesheet"
3827
+ />
3828
+ <style type="text/css">
3829
+ body {
3830
+ font-family: 'Noto Sans', sans-serif;
3831
+ color: #222;
3832
+ padding: 16px 24px;
3833
+ }
3834
+
3835
+ h1 {
3836
+ font-size: 21px;
3837
+ margin-top: 32px;
3838
+ margin-bottom: 36px;
3839
+ font-weight: 700;
3840
+ }
3841
+
3842
+ p {
3843
+ font-weight: 400;
3844
+ font-size: 16px;
3845
+ line-height: 1.8;
3846
+ margin-bottom: 24px;
3847
+ }
3848
+
3849
+ i {
3850
+ color: #666;
3851
+ font-weight: 400;
3852
+ font-size: 16px;
3853
+ }
3854
+ </style>
3855
+ </head>
3856
+
3857
+ <body>
3858
+ <img
3859
+ src="{{countryLogo}}"
3860
+ alt="country_logo"
3861
+ style="max-height: 88px; max-width: 100%"
3862
+ />
3863
+ <h1>${event.heading}</h1>
3864
+ <p>Hello {{firstname}},</p>
3865
+ <p>
3866
+ ${event.reason}
3867
+ </p>
3868
+
3869
+ <div style="margin-top: 32px; margin-bottom: 32px">
3870
+ <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3871
+ </div>
3872
+ <br />
3873
+ <p>
3874
+ This link expires in 1 hour and can only be used once. If you did not
3875
+ request this, you can ignore this email.
3876
+ </p>
3877
+ <br />
3878
+ <p>
3879
+ Best regards, <br />
3880
+ {{applicationName}} Team
3881
+ </p>
3882
+ </body>
3883
+ </html>
3884
+ `;
3885
+ }
3886
+ function writeEmailTemplates(cwd) {
3887
+ const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3888
+ if (!(0, import_fs2.existsSync)(templateDir)) {
3889
+ warnSkipped(
3890
+ `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3891
+ );
3892
+ return;
3893
+ }
3894
+ for (const event of RECOVERY_EVENTS) {
3895
+ const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3896
+ if ((0, import_fs2.existsSync)(templatePath)) continue;
3897
+ (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3898
+ console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3899
+ }
3900
+ }
3901
+ function addCsvRows(cwd, relativePath, rows) {
3902
+ const csvPath = import_path2.default.join(cwd, relativePath);
3903
+ const file = readCsvFile(csvPath);
3904
+ if (!file) {
3905
+ warnSkipped(`${relativePath} not found; translations not added`);
3906
+ return;
3907
+ }
3908
+ const added = addRows(file, rows);
3909
+ if (added.length === 0) return;
3910
+ for (const id of added) {
3911
+ console.log(` \u2713 ${relativePath}: ${id}`);
3912
+ }
3913
+ writeCsvFile(csvPath, file);
3914
+ }
3915
+ async function main2() {
3916
+ const cwd = process.cwd();
3917
+ const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3918
+ console.log(
3919
+ "Registering the password-reset-link and username-reminder-link notifications...\n"
3920
+ );
3921
+ if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3922
+ warnSkipped(
3923
+ `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3924
+ );
3925
+ return;
3926
+ }
3927
+ const project = new import_ts_morph2.Project({
3928
+ tsConfigFilePath,
3929
+ skipAddingFilesFromTsConfig: false,
3930
+ // ts-morph indents inserted code with four spaces by default, which every
3931
+ // country config's prettier run would immediately undo.
3932
+ manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3933
+ });
3934
+ updateEmailTemplates(project, cwd);
3935
+ updateSmsService(project, cwd);
3936
+ updateHandler(project, cwd);
3937
+ updateRoutes(project, cwd);
3938
+ await project.save();
3939
+ writeEmailTemplates(cwd);
3940
+ addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3941
+ addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3942
+ if (skipped.length > 0) {
3943
+ console.warn(
3944
+ `
3945
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3946
+ );
3947
+ for (const message of skipped) {
3948
+ console.warn(` - ${message}`);
3949
+ }
3950
+ }
3951
+ }
3952
+
3953
+ // src/migrations/v2.1/add-translations.ts
3954
+ var import_path3 = __toESM(require("path"));
3955
+ var REPOSITORY = "opencrvs/opencrvs-core";
3956
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
3957
+ var APPLICATIONS = ["client", "login"];
3958
+ var TARGET_VERSION = "2.1";
3959
+ var skipped2 = [];
3960
+ function warnSkipped2(message) {
3961
+ skipped2.push(message);
3962
+ console.warn(` \u26A0\uFE0F ${message}`);
3963
+ }
3964
+ async function matchingRefs(namespace, prefix) {
3965
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
3966
+ const response = await fetch(url, {
3967
+ headers: { accept: "application/vnd.github+json" }
3968
+ });
3969
+ if (!response.ok) {
3970
+ throw new Error(
3971
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3972
+ );
3973
+ }
3974
+ const refs = await response.json();
3975
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
3976
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
3977
+ }
3978
+ async function candidateRefs() {
3979
+ return [
3980
+ ...await matchingRefs("heads", `release/${TARGET_VERSION}.`),
3981
+ ...await matchingRefs("tags", `v${TARGET_VERSION}.`),
3982
+ "develop"
3983
+ ];
3984
+ }
3985
+ async function fetchTemplate(refs, application) {
3986
+ for (const ref of refs) {
3987
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
3988
+ const response = await fetch(url);
3989
+ if (response.ok) {
3990
+ return { ref, contents: await response.text() };
3991
+ }
3992
+ if (response.status !== 404) {
3993
+ throw new Error(
3994
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3995
+ );
3996
+ }
3997
+ }
3998
+ warnSkipped2(
3999
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
4000
+ );
4001
+ return void 0;
4002
+ }
4003
+ function rowsToAdd(local, template) {
4004
+ const localColumns = parseCsvLine(local.header);
4005
+ const templateColumns = parseCsvLine(template.header);
4006
+ return template.body.filter((line2) => line2 !== "").map((line2) => {
4007
+ const values = parseCsvLine(line2);
4008
+ return toCsvLine(
4009
+ localColumns.map((column) => {
4010
+ const index = templateColumns.indexOf(column);
4011
+ return index === -1 ? "" : values[index] ?? "";
4012
+ })
4013
+ );
4014
+ });
4015
+ }
4016
+ async function updateApplication(cwd, refs, application) {
4017
+ const relativePath = `src/translations/${application}.csv`;
4018
+ const local = readCsvFile(import_path3.default.join(cwd, relativePath));
4019
+ if (!local) {
4020
+ warnSkipped2(`${relativePath} not found; translations not added`);
4021
+ return;
4022
+ }
4023
+ const fetched = await fetchTemplate(refs, application);
4024
+ if (!fetched) {
4025
+ return;
4026
+ }
4027
+ const template = readTemplate(fetched.contents);
4028
+ const added = addRows(local, rowsToAdd(local, template));
4029
+ if (added.length === 0) {
4030
+ return;
4031
+ }
4032
+ try {
4033
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
4034
+ } catch (error3) {
4035
+ warnSkipped2(
4036
+ `Could not write ${relativePath} (${error3.message}); translations not added`
4037
+ );
4038
+ return;
4039
+ }
4040
+ for (const id of added) {
4041
+ console.log(` \u2713 ${relativePath}: ${id}`);
4042
+ }
4043
+ }
4044
+ function readTemplate(contents) {
4045
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
4046
+ return {
4047
+ header: lines[0],
4048
+ body: lines.slice(1),
4049
+ newline: "\n",
4050
+ trailingNewline: true
4051
+ };
4052
+ }
4053
+ async function listRefs() {
4054
+ try {
4055
+ return await candidateRefs();
4056
+ } catch (error3) {
4057
+ warnSkipped2(
4058
+ `Could not list the ${TARGET_VERSION} refs on GitHub (${error3.message}); translations not added`
4059
+ );
4060
+ return void 0;
4061
+ }
4062
+ }
4063
+ async function main3() {
4064
+ const cwd = process.cwd();
4065
+ console.log("Adding the translation keys core gained this version...\n");
4066
+ const refs = await listRefs();
4067
+ if (refs) {
4068
+ for (const application of APPLICATIONS) {
4069
+ try {
4070
+ await updateApplication(cwd, refs, application);
4071
+ } catch (error3) {
4072
+ warnSkipped2(
4073
+ `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
4074
+ );
4075
+ }
4076
+ }
4077
+ }
4078
+ if (skipped2.length > 0) {
4079
+ console.warn(
4080
+ `
4081
+ \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4082
+ );
4083
+ for (const message of skipped2) {
4084
+ console.warn(` - ${message}`);
4085
+ }
4086
+ }
4087
+ }
4088
+
4089
+ // src/migrations/v2.1/enable-telemetry.ts
4090
+ var import_ts_morph3 = require("ts-morph");
4091
+ var import_fs3 = require("fs");
4092
+ var import_path4 = __toESM(require("path"));
4093
+ var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
4094
+ var ENVIRONMENT_FILE = "src/environment.ts";
4095
+ var INDEX_FILE = "src/index.ts";
4096
+ var HANDLER_MODULE = "./api/telemetry/handler";
4097
+ var skipped3 = [];
4098
+ function warnSkipped3(message) {
4099
+ skipped3.push(message);
4100
+ console.warn(` \u26A0\uFE0F ${message}`);
4101
+ }
4102
+ var TELEMETRY_HANDLER_SOURCE = `/*
4103
+ * This Source Code Form is subject to the terms of the Mozilla Public
4104
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4105
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4106
+ *
4107
+ * OpenCRVS is also distributed under the terms of the Civil Registration
4108
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
4109
+ *
4110
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
4111
+ */
4112
+
4113
+ import { Request, ResponseToolkit } from '@hapi/hapi'
4114
+ import * as Joi from 'joi'
4115
+ import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
4116
+ import { env } from '@countryconfig/environment'
4117
+ import { logger } from '@countryconfig/logger'
4118
+ import { applicationConfig } from '@countryconfig/api/application/application-config'
4119
+
4120
+ /** Report the events service posts to \`/trigger/telemetry\`. */
4121
+ export const telemetrySchema = Joi.object({
4122
+ reported_at: Joi.string().isoDate().required(),
4123
+ app_version: Joi.string().optional(),
4124
+ metrics: Joi.object()
4125
+ .pattern(
4126
+ Joi.string(),
4127
+ Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
4128
+ )
4129
+ .required()
4130
+ })
4131
+
4132
+ interface IncomingReport {
4133
+ reported_at: string
4134
+ app_version?: string
4135
+ metrics: Record<string, number | string | boolean>
4136
+ }
4137
+
4138
+ /** Logged once at countryconfig startup while telemetry is disabled. */
4139
+ export const TELEMETRY_DISABLED_NOTICE =
4140
+ 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
4141
+ 'aggregate usage metrics (registration and certificate counts, active ' +
4142
+ 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
4143
+ 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
4144
+ 'the countryconfig service.'
4145
+
4146
+ /**
4147
+ * Receives a usage report from the events service and, when telemetry is
4148
+ * enabled for this instance, stamps the instance identity onto it and forwards
4149
+ * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
4150
+ * endpoint and payload schema). The events service is unaware of whether
4151
+ * telemetry is enabled or of the country code / domain / environment reported.
4152
+ */
4153
+ export async function telemetryHandler(request: Request, h: ResponseToolkit) {
4154
+ // Only accept OpenCRVS *system* tokens (the events service's service
4155
+ // token has userType 'system'). A logged-in user's token is a 'user' token,
4156
+ // so a user cannot submit telemetry with their own credentials \u2014 and the
4157
+ // service-token endpoint is not reachable through the public gateway.
4158
+ const credentials = request.auth.credentials as
4159
+ | { userType?: string }
4160
+ | undefined
4161
+ if (credentials?.userType !== 'system') {
4162
+ logger.warn('Telemetry: rejected a request that is not from a system token')
4163
+ return h.response({ error: 'forbidden' }).code(403)
4164
+ }
4165
+
4166
+ if (!env.TELEMETRY_ENABLED) {
4167
+ // The encouraging notice is logged once at startup (see index.ts); keep the
4168
+ // per-report path quiet.
4169
+ return h.response({ status: 'skipped' }).code(200)
4170
+ }
4171
+
4172
+ const incoming = request.payload as IncomingReport
4173
+
4174
+ // Only production instances report; staging, QA and local build the report
4175
+ // but never reach the status service. (This gate used to live in the
4176
+ // toolkit's sendTelemetry; each country config now owns it.)
4177
+ if (!env.isProduction) {
4178
+ logger.info(
4179
+ \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
4180
+ )
4181
+ return h.response({ status: 'skipped' }).code(200)
4182
+ }
4183
+
4184
+ const report: TelemetryReport = {
4185
+ reported_at: incoming.reported_at,
4186
+ country_code: env.COUNTRY_CODE,
4187
+ organisation: env.ORGANISATION,
4188
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
4189
+ // "no domain" rather than reporting a literal "*".
4190
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
4191
+ instance: {
4192
+ application_name: applicationConfig.APPLICATION_NAME,
4193
+ environment: env.ENVIRONMENT_NAME,
4194
+ app_version: incoming.app_version
4195
+ },
4196
+ metrics: incoming.metrics
4197
+ }
4198
+
4199
+ let result
4200
+ try {
4201
+ result = await sendTelemetry(report)
4202
+ } catch (error) {
4203
+ const message = error instanceof Error ? error.message : String(error)
4204
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
4205
+ return h.response({ status: 'error' }).code(502)
4206
+ }
4207
+
4208
+ if (result.outcome === 'rejected') {
4209
+ logger.error(
4210
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
4211
+ )
4212
+ return h.response({ status: 'error' }).code(502)
4213
+ }
4214
+
4215
+ logger.info(
4216
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
4217
+ )
4218
+ return h.response({ status: 'forwarded' }).code(202)
4219
+ }
4220
+ `;
4221
+ var TELEMETRY_DISABLED = {
4222
+ enabled: false,
4223
+ countryCode: "",
4224
+ organisation: ""
4225
+ };
4226
+ async function promptTelemetryConfig() {
4227
+ if (!process.stdin.isTTY) {
4228
+ return TELEMETRY_DISABLED;
4229
+ }
4230
+ const { confirm: confirm3, input: input4 } = await import("@inquirer/prompts");
4231
+ const enabled = await confirm3({
4232
+ message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
4233
+ default: true
4234
+ });
4235
+ if (!enabled) {
4236
+ return TELEMETRY_DISABLED;
4237
+ }
4238
+ const countryCode = (await input4({
4239
+ message: "Country code (ISO alpha-3, e.g. FAR):",
4240
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
4241
+ })).trim().toUpperCase();
4242
+ const organisation = (await input4({
4243
+ message: "Organisation running this instance:",
4244
+ validate: (value) => value.trim() !== "" || "Enter an organisation name."
4245
+ })).trim();
4246
+ return { enabled: true, countryCode, organisation };
4247
+ }
4248
+ function writeTelemetryHandler(cwd) {
4249
+ const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
4250
+ if ((0, import_fs3.existsSync)(handlerPath)) {
4251
+ console.log(` ${HANDLER_FILE2} already present; left unchanged`);
4252
+ return;
4253
+ }
4254
+ (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
4255
+ (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
4256
+ console.log(` \u2713 ${HANDLER_FILE2}`);
4257
+ }
4258
+ function appendProperty(sourceFile, object, name, valueLines) {
4259
+ const properties = object.getProperties();
4260
+ const lastProperty = properties[properties.length - 1];
4261
+ if (!lastProperty) return false;
4262
+ const indent = lastProperty.getIndentationText();
4263
+ const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${name}: ${line2}` : line2}`).join("\n");
4264
+ sourceFile.insertText(lastProperty.getEnd(), `,
4265
+ ${entry}`);
4266
+ return true;
4267
+ }
4268
+ function ensureEnvalidNamedImports(sourceFile, names) {
4269
+ const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
4270
+ if (!importDeclaration) {
4271
+ warnSkipped3(
4272
+ `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
4273
+ );
4274
+ return;
4275
+ }
4276
+ const existing = new Set(
4277
+ importDeclaration.getNamedImports().map((named) => named.getName())
4278
+ );
4279
+ for (const name of names) {
4280
+ if (!existing.has(name)) {
4281
+ importDeclaration.addNamedImport(name);
4282
+ }
4283
+ }
4284
+ }
4285
+ function getCleanEnvObject(sourceFile) {
4286
+ const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4287
+ return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
4288
+ }
4289
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
4290
+ const object = getCleanEnvObject(sourceFile);
4291
+ if (!object) return;
4292
+ const existing = object.getProperty(name);
4293
+ if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
4294
+ if (!update) return;
4295
+ const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
4296
+ if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
4297
+ const defaultProperty = options.getProperty("default");
4298
+ if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
4299
+ defaultProperty.setInitializer(defaultExpr);
4300
+ } else {
4301
+ options.insertPropertyAssignment(0, {
4302
+ name: "default",
4303
+ initializer: defaultExpr
4304
+ });
4305
+ }
4306
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
4307
+ }
4308
+ return;
4309
+ }
4310
+ if (appendProperty(sourceFile, object, name, [
4311
+ `${kind}({`,
4312
+ ` default: ${defaultExpr},`,
4313
+ ` desc: ${JSON.stringify(desc)}`,
4314
+ "})"
4315
+ ])) {
4316
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
4317
+ }
4318
+ }
4319
+ function addEnvironmentVariables(project, cwd, config) {
4320
+ const sourceFile = project.addSourceFileAtPathIfExists(
4321
+ import_path4.default.join(cwd, ENVIRONMENT_FILE)
4322
+ );
4323
+ if (!sourceFile) {
4324
+ warnSkipped3(
4325
+ `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
4326
+ );
4327
+ return;
4328
+ }
4329
+ if (!getCleanEnvObject(sourceFile)) {
4330
+ warnSkipped3(
4331
+ `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
4332
+ );
4333
+ return;
4334
+ }
4335
+ ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
4336
+ upsertEnvVar(
4337
+ sourceFile,
4338
+ "TELEMETRY_ENABLED",
4339
+ "bool",
4340
+ config.enabled ? "true" : "false",
4341
+ "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
4342
+ true
4343
+ );
4344
+ upsertEnvVar(
4345
+ sourceFile,
4346
+ "COUNTRY_CODE",
4347
+ "str",
4348
+ config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
4349
+ "ISO-style country code of this instance, reported with telemetry.",
4350
+ config.enabled
4351
+ );
4352
+ upsertEnvVar(
4353
+ sourceFile,
4354
+ "ORGANISATION",
4355
+ "str",
4356
+ config.enabled ? JSON.stringify(config.organisation) : `''`,
4357
+ "Organisation running this instance, reported with telemetry. Empty by default.",
4358
+ config.enabled
4359
+ );
4360
+ upsertEnvVar(
4361
+ sourceFile,
4362
+ "ENVIRONMENT_NAME",
4363
+ "str",
4364
+ `'development'`,
4365
+ 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
4366
+ false
4367
+ );
4368
+ }
4369
+ function wireIndex(project, cwd) {
4370
+ const sourceFile = project.addSourceFileAtPathIfExists(
4371
+ import_path4.default.join(cwd, INDEX_FILE)
4372
+ );
4373
+ if (!sourceFile) {
4374
+ warnSkipped3(
4375
+ `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
4376
+ );
4377
+ return;
4378
+ }
4379
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
4380
+ sourceFile.addImportDeclaration({
4381
+ moduleSpecifier: HANDLER_MODULE,
4382
+ namedImports: [
4383
+ "telemetryHandler",
4384
+ "telemetrySchema",
4385
+ "TELEMETRY_DISABLED_NOTICE"
4386
+ ]
4387
+ });
4388
+ console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
4389
+ }
4390
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
4391
+ const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
4392
+ (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
4393
+ ).filter(
4394
+ (statement) => Boolean(statement)
4395
+ ).pop();
4396
+ if (!lastRouteStatement) {
4397
+ warnSkipped3(
4398
+ `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
4399
+ );
4400
+ } else {
4401
+ const indent = lastRouteStatement.getIndentationText();
4402
+ const route = [
4403
+ `server.route({`,
4404
+ ` method: 'POST',`,
4405
+ ` path: '/trigger/telemetry',`,
4406
+ ` handler: telemetryHandler,`,
4407
+ ` options: {`,
4408
+ ` tags: ['api', 'triggers'],`,
4409
+ ` validate: {`,
4410
+ ` payload: telemetrySchema`,
4411
+ ` },`,
4412
+ ` description:`,
4413
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
4414
+ ` }`,
4415
+ `})`
4416
+ ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4417
+ sourceFile.insertText(lastRouteStatement.getEnd(), `
4418
+
4419
+ ${route}`);
4420
+ console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
4421
+ }
4422
+ }
4423
+ if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
4424
+ const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
4425
+ (statement) => statement.getText().includes("Server successfully started")
4426
+ );
4427
+ if (!startedLog) {
4428
+ warnSkipped3(
4429
+ `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
4430
+ );
4431
+ } else {
4432
+ const indent = startedLog.getIndentationText();
4433
+ const notice = [
4434
+ `if (!env.TELEMETRY_ENABLED) {`,
4435
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
4436
+ `}`
4437
+ ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4438
+ sourceFile.insertText(startedLog.getEnd(), `
4439
+
4440
+ ${notice}`);
4441
+ console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
4442
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
4443
+ warnSkipped3(
4444
+ `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
4445
+ );
4446
+ }
4447
+ }
4448
+ }
4449
+ }
4450
+ async function main4() {
4451
+ const cwd = process.cwd();
4452
+ const config = await promptTelemetryConfig();
4453
+ console.log(
4454
+ `
4455
+ Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
4456
+ `
4457
+ );
4458
+ writeTelemetryHandler(cwd);
4459
+ const project = new import_ts_morph3.Project({
4460
+ // ts-morph indents inserted code with four spaces and double-quotes strings
4461
+ // by default, both of which the country config's prettier run would undo.
4462
+ manipulationSettings: {
4463
+ indentationText: import_ts_morph3.IndentationText.TwoSpaces,
4464
+ quoteKind: import_ts_morph3.QuoteKind.Single
4465
+ }
4466
+ });
4467
+ addEnvironmentVariables(project, cwd, config);
4468
+ wireIndex(project, cwd);
4469
+ await project.save();
4470
+ if (skipped3.length > 0) {
4471
+ console.warn(
4472
+ `
4473
+ \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
4474
+ );
4475
+ for (const message of skipped3) {
4476
+ console.warn(` - ${message}`);
4477
+ }
4478
+ }
4479
+ }
4480
+
3290
4481
  // src/migrations/v2.1/index.ts
3291
4482
  async function runUpgrade(dockerSwarm) {
3292
4483
  await main();
4484
+ await main2();
4485
+ await main3();
4486
+ await main4();
4487
+ }
4488
+
4489
+ // src/translations/check.ts
4490
+ var import_ts_morph4 = require("ts-morph");
4491
+ var import_path5 = __toESM(require("path"));
4492
+ var TRANSLATIONS = "src/translations";
4493
+ var OWN_FILE = `${TRANSLATIONS}/countryconfig.csv`;
4494
+ var CORE_FILES = [`${TRANSLATIONS}/client.csv`, `${TRANSLATIONS}/login.csv`];
4495
+ function staticStringOf(node, name) {
4496
+ const property = node.getProperty(name);
4497
+ if (!property || !import_ts_morph4.Node.isPropertyAssignment(property)) {
4498
+ return void 0;
4499
+ }
4500
+ const initializer = property.getInitializer();
4501
+ return initializer && (import_ts_morph4.Node.isStringLiteral(initializer) || import_ts_morph4.Node.isNoSubstitutionTemplateLiteral(initializer)) ? initializer.getLiteralValue() : void 0;
4502
+ }
4503
+ function messagesDeclaredIn(cwd) {
4504
+ const project = new import_ts_morph4.Project({ skipAddingFilesFromTsConfig: true });
4505
+ project.addSourceFilesAtPaths([
4506
+ import_path5.default.join(cwd, "src/**/*.ts"),
4507
+ import_path5.default.join(cwd, "src/**/*.tsx"),
4508
+ `!${import_path5.default.join(cwd, "src/**/*.test.ts")}`,
4509
+ `!${import_path5.default.join(cwd, "src/**/*.test.tsx")}`,
4510
+ `!${import_path5.default.join(cwd, "src/**/*.stories.ts")}`,
4511
+ `!${import_path5.default.join(cwd, "src/**/*.stories.tsx")}`
4512
+ ]);
4513
+ const messages = [];
4514
+ const dynamicIds = [];
4515
+ for (const sourceFile of project.getSourceFiles()) {
4516
+ sourceFile.forEachDescendant((node) => {
4517
+ if (!import_ts_morph4.Node.isObjectLiteralExpression(node)) {
4518
+ return;
4519
+ }
4520
+ if (!(node.getProperty("id") && node.getProperty("defaultMessage"))) {
4521
+ return;
4522
+ }
4523
+ const id = staticStringOf(node, "id");
4524
+ if (id === void 0) {
4525
+ dynamicIds.push(import_path5.default.relative(cwd, sourceFile.getFilePath()));
4526
+ return;
4527
+ }
4528
+ messages.push({
4529
+ id,
4530
+ defaultMessage: staticStringOf(node, "defaultMessage") ?? "",
4531
+ description: staticStringOf(node, "description") ?? ""
4532
+ });
4533
+ });
4534
+ }
4535
+ return { messages, dynamicIds: [...new Set(dynamicIds)] };
4536
+ }
4537
+ function check(cwd) {
4538
+ const { messages, dynamicIds } = messagesDeclaredIn(cwd);
4539
+ const own = readCsvFile(import_path5.default.join(cwd, OWN_FILE));
4540
+ const covered = new Set(
4541
+ [own, ...CORE_FILES.map((file) => readCsvFile(import_path5.default.join(cwd, file)))].flatMap((csv) => csv?.body ?? []).map(idOf)
4542
+ );
4543
+ const missing = [
4544
+ ...new Map(
4545
+ messages.filter(({ id }) => !covered.has(id)).map((message) => [message.id, message])
4546
+ ).values()
4547
+ ].sort((a, b) => a.id < b.id ? -1 : 1);
4548
+ const declared = new Set(messages.map(({ id }) => id));
4549
+ const outdated = (own?.body ?? []).map(idOf).filter((id) => !declared.has(id));
4550
+ return { missing, outdated, dynamicIds };
4551
+ }
4552
+ function writeMissing(cwd, missing) {
4553
+ const file = readCsvFile(import_path5.default.join(cwd, OWN_FILE)) ?? {
4554
+ header: "id,description,en",
4555
+ body: [],
4556
+ newline: "\n",
4557
+ trailingNewline: true
4558
+ };
4559
+ const columns = file.header.split(",");
4560
+ const rows = missing.map(
4561
+ (message) => toCsvLine(
4562
+ columns.map((column) => {
4563
+ if (column === "id") return message.id;
4564
+ if (column === "description") return message.description;
4565
+ return column === "en" ? message.defaultMessage : "";
4566
+ })
4567
+ )
4568
+ );
4569
+ const added = addRows(file, rows);
4570
+ writeCsvFile(import_path5.default.join(cwd, OWN_FILE), file);
4571
+ return added;
3293
4572
  }
3294
4573
 
3295
4574
  // src/environment/index.ts
3296
- var import_fs4 = require("fs");
3297
- var import_path4 = require("path");
4575
+ var import_fs8 = require("fs");
4576
+ var import_path10 = require("path");
4577
+ init_paths();
3298
4578
  var REQUIRED_REPOSITORY_DIRECTORIES = [
3299
4579
  ".github/workflows",
3300
4580
  "environments",
@@ -3304,7 +4584,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3304
4584
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3305
4585
  (directory) => {
3306
4586
  try {
3307
- return !(0, import_fs4.statSync)((0, import_path4.resolve)(repositoryRoot, directory)).isDirectory();
4587
+ return !(0, import_fs8.statSync)((0, import_path10.resolve)(repositoryRoot, directory)).isDirectory();
3308
4588
  } catch {
3309
4589
  return true;
3310
4590
  }
@@ -3318,8 +4598,14 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3318
4598
  }
3319
4599
  async function runEnvironmentInit() {
3320
4600
  validateRepositoryStructure();
4601
+ assertNoOldInventoryLayout();
3321
4602
  await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3322
4603
  }
4604
+ async function runEnvironmentUpgrade() {
4605
+ validateRepositoryStructure();
4606
+ const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
4607
+ await upgradeEnvironmentLayout2();
4608
+ }
3323
4609
  async function runEnvironmentUpdateWorkflows() {
3324
4610
  validateRepositoryStructure();
3325
4611
  const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
@@ -3335,6 +4621,278 @@ async function runEnvironmentSwarmToK8s() {
3335
4621
  await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
3336
4622
  }
3337
4623
 
4624
+ // src/verify/endpoints.ts
4625
+ var import_colors = require("kleur/colors");
4626
+ var REQUEST_TIMEOUT_MS = 15e3;
4627
+ var DEFAULT_TARGET_URL = "http://localhost:3040";
4628
+ var REQUIRED_PUBLIC_ENDPOINTS = [
4629
+ { method: "GET", path: "/client-config.js" },
4630
+ { method: "GET", path: "/login-config.js" },
4631
+ { method: "GET", path: "/handlebars.js" },
4632
+ { method: "GET", path: "/content/client" },
4633
+ { method: "GET", path: "/content/login" },
4634
+ { method: "GET", path: "/content/map.geojson" },
4635
+ { method: "GET", path: "/content/country-logo" },
4636
+ { method: "GET", path: "/config/application" },
4637
+ { method: "GET", path: "/config/workqueues" },
4638
+ { method: "GET", path: "/config/locations" },
4639
+ { method: "GET", path: "/config/roles" },
4640
+ { method: "GET", path: "/config/events" }
4641
+ ];
4642
+ var PROBE_SEGMENT = "verify-endpoints-probe";
4643
+ var SECURED_TRIGGER_USER_EVENTS = [
4644
+ "user-created",
4645
+ "user-updated",
4646
+ "username-reminder",
4647
+ "reset-password",
4648
+ "reset-password-by-admin",
4649
+ "password-reset-link",
4650
+ "username-reminder-link",
4651
+ "resend-invite",
4652
+ "2fa",
4653
+ "all-user-notification",
4654
+ "change-phone-number",
4655
+ "change-email-address"
4656
+ ];
4657
+ var SECURED_ENDPOINTS = [
4658
+ ...SECURED_TRIGGER_USER_EVENTS.map(
4659
+ (event) => ({
4660
+ method: "POST",
4661
+ path: `/triggers/user/${event}`
4662
+ })
4663
+ ),
4664
+ { method: "POST", path: "/trigger/telemetry" },
4665
+ { method: "GET", path: "/triggers/system/ready" },
4666
+ {
4667
+ method: "GET",
4668
+ path: `/certificates/${PROBE_SEGMENT}`,
4669
+ label: "/certificates/{id}"
4670
+ },
4671
+ { method: "GET", path: "/certificates" },
4672
+ { method: "GET", path: "/config/users" }
4673
+ ];
4674
+ var FALLBACK_EVENT_TRIGGERS = [
4675
+ {
4676
+ method: "POST",
4677
+ path: `/trigger/events/${PROBE_SEGMENT}/actions/${PROBE_SEGMENT}`,
4678
+ label: "/trigger/events/{event}/actions/{action}"
4679
+ },
4680
+ {
4681
+ method: "POST",
4682
+ path: `/trigger/events/birth/actions/${PROBE_SEGMENT}`,
4683
+ label: "/trigger/events/birth/actions/{action}"
4684
+ },
4685
+ {
4686
+ method: "POST",
4687
+ path: `/trigger/events/death/actions/${PROBE_SEGMENT}`,
4688
+ label: "/trigger/events/death/actions/{action}"
4689
+ }
4690
+ ];
4691
+ var isSuccess = (status) => status !== "error" && status >= 200 && status < 300;
4692
+ var requiresAuthOrAbsent = (status) => status === 401 || status === 403 || status === 404;
4693
+ async function requestStatus(url, method) {
4694
+ const controller = new AbortController();
4695
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
4696
+ try {
4697
+ const response = await fetch(url, {
4698
+ method,
4699
+ signal: controller.signal,
4700
+ // Sent without an Authorization header on purpose. A secured route
4701
+ // rejects with 401/403 before ever reading the body.
4702
+ headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
4703
+ body: method === "POST" ? "{}" : void 0
4704
+ });
4705
+ return response.status;
4706
+ } catch {
4707
+ return "error";
4708
+ } finally {
4709
+ clearTimeout(timer);
4710
+ }
4711
+ }
4712
+ function toEventTriggerConfig(value) {
4713
+ if (typeof value !== "object" || value === null) {
4714
+ return null;
4715
+ }
4716
+ const record = value;
4717
+ if (typeof record.id !== "string") {
4718
+ return null;
4719
+ }
4720
+ const actions = Array.isArray(record.actions) ? Array.from(
4721
+ new Set(
4722
+ record.actions.map((action) => {
4723
+ if (typeof action !== "object" || action === null) {
4724
+ return null;
4725
+ }
4726
+ const type = action.type;
4727
+ return typeof type === "string" ? type : null;
4728
+ }).filter((type) => type !== null)
4729
+ )
4730
+ ) : [];
4731
+ return { id: record.id, actions };
4732
+ }
4733
+ async function fetchEventConfigs(baseUrl) {
4734
+ const controller = new AbortController();
4735
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
4736
+ try {
4737
+ const response = await fetch(`${baseUrl}/config/events`, {
4738
+ signal: controller.signal
4739
+ });
4740
+ if (!response.ok) {
4741
+ return null;
4742
+ }
4743
+ const body = await response.json();
4744
+ if (!Array.isArray(body)) {
4745
+ return null;
4746
+ }
4747
+ return body.map(toEventTriggerConfig).filter((config) => config !== null);
4748
+ } catch {
4749
+ return null;
4750
+ } finally {
4751
+ clearTimeout(timer);
4752
+ }
4753
+ }
4754
+ function resolveBaseUrl(input4) {
4755
+ const withProtocol = /^https?:\/\//i.test(input4) ? input4 : `https://${input4}`;
4756
+ return withProtocol.replace(/\/+$/, "");
4757
+ }
4758
+ function describeStatus(status) {
4759
+ return status === "error" ? "no response" : `HTTP ${status}`;
4760
+ }
4761
+ function endpointLabel(check2) {
4762
+ const shown = check2.label ?? check2.path;
4763
+ const suffix = check2.label ? (0, import_colors.dim)(` \u2192 ${check2.path}`) : "";
4764
+ return `${check2.method} ${shown}${suffix}`;
4765
+ }
4766
+ function line(ok, label, detail) {
4767
+ const mark = ok ? (0, import_colors.green)("\u2713") : (0, import_colors.red)("\u2717");
4768
+ return ` ${mark} ${label} ${(0, import_colors.dim)(`(${detail})`)}`;
4769
+ }
4770
+ function securedDetail(status) {
4771
+ if (status === 401 || status === 403) {
4772
+ return `${describeStatus(status)} \u2014 auth required`;
4773
+ }
4774
+ if (status === 404) {
4775
+ return `${describeStatus(status)} \u2014 not implemented`;
4776
+ }
4777
+ if (status === "error") {
4778
+ return `${describeStatus(status)} \u2014 request failed`;
4779
+ }
4780
+ return `${describeStatus(status)} \u2014 INSECURE: ensure this endpoint requires authentication!`;
4781
+ }
4782
+ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4783
+ const baseUrl = resolveBaseUrl(target);
4784
+ console.log((0, import_colors.bold)(`Verifying country config endpoints at ${baseUrl}
4785
+ `));
4786
+ let failures = 0;
4787
+ console.log((0, import_colors.bold)("Required public endpoints (must respond 2xx):"));
4788
+ for (const check2 of REQUIRED_PUBLIC_ENDPOINTS) {
4789
+ const status = await requestStatus(`${baseUrl}${check2.path}`, check2.method);
4790
+ const ok = isSuccess(status);
4791
+ if (!ok) {
4792
+ failures++;
4793
+ }
4794
+ const detail = status === 404 ? `${describeStatus(status)} \u2014 missing` : ok ? describeStatus(status) : `${describeStatus(status)} \u2014 unexpected`;
4795
+ console.log(line(ok, endpointLabel(check2), detail));
4796
+ }
4797
+ {
4798
+ const path10 = `/fonts/${PROBE_SEGMENT}.ttf`;
4799
+ const status = await requestStatus(`${baseUrl}${path10}`, "GET");
4800
+ const ok = status === 200 || status === 404;
4801
+ if (!ok) {
4802
+ failures++;
4803
+ }
4804
+ let detail;
4805
+ if (status === 404) {
4806
+ detail = `${describeStatus(status)} \u2014 reachable (made-up filename)`;
4807
+ } else if (status === 200) {
4808
+ detail = describeStatus(status);
4809
+ } else if (status === 401 || status === 403) {
4810
+ detail = `${describeStatus(status)} \u2014 must be public`;
4811
+ } else {
4812
+ detail = `${describeStatus(status)} \u2014 unexpected`;
4813
+ }
4814
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path10}`)}`, detail));
4815
+ }
4816
+ console.log();
4817
+ console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
4818
+ for (const check2 of SECURED_ENDPOINTS) {
4819
+ const status = await requestStatus(`${baseUrl}${check2.path}`, check2.method);
4820
+ const ok = requiresAuthOrAbsent(status);
4821
+ if (!ok) {
4822
+ failures++;
4823
+ }
4824
+ console.log(line(ok, endpointLabel(check2), securedDetail(status)));
4825
+ }
4826
+ console.log();
4827
+ console.log((0, import_colors.bold)("Event action triggers (must be absent or require auth):"));
4828
+ const events = await fetchEventConfigs(baseUrl);
4829
+ if (!events) {
4830
+ console.log(
4831
+ " " + (0, import_colors.yellow)(
4832
+ "Could not read /config/events; falling back to route-pattern checks."
4833
+ )
4834
+ );
4835
+ for (const check2 of FALLBACK_EVENT_TRIGGERS) {
4836
+ const status = await requestStatus(
4837
+ `${baseUrl}${check2.path}`,
4838
+ check2.method
4839
+ );
4840
+ const ok = requiresAuthOrAbsent(status);
4841
+ if (!ok) {
4842
+ failures++;
4843
+ }
4844
+ console.log(line(ok, endpointLabel(check2), securedDetail(status)));
4845
+ }
4846
+ } else if (events.length === 0) {
4847
+ console.log(" " + (0, import_colors.yellow)("No events configured."));
4848
+ } else {
4849
+ for (const event of events) {
4850
+ const actions = event.actions.length ? event.actions : [PROBE_SEGMENT];
4851
+ const failed = [];
4852
+ for (const action of actions) {
4853
+ const status = await requestStatus(
4854
+ `${baseUrl}/trigger/events/${event.id}/actions/${action}`,
4855
+ "POST"
4856
+ );
4857
+ if (!requiresAuthOrAbsent(status)) {
4858
+ failed.push({ action, status });
4859
+ }
4860
+ }
4861
+ const pattern = `POST /trigger/events/${event.id}/actions/{action}`;
4862
+ if (failed.length === 0) {
4863
+ console.log(
4864
+ line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4865
+ );
4866
+ } else {
4867
+ for (const failure of failed) {
4868
+ failures++;
4869
+ console.log(
4870
+ line(
4871
+ false,
4872
+ `POST /trigger/events/${event.id}/actions/${failure.action}`,
4873
+ securedDetail(failure.status)
4874
+ )
4875
+ );
4876
+ }
4877
+ const okCount = actions.length - failed.length;
4878
+ if (okCount > 0) {
4879
+ console.log(
4880
+ line(true, pattern, `${okCount} other action(s) require auth`)
4881
+ );
4882
+ }
4883
+ }
4884
+ }
4885
+ }
4886
+ console.log();
4887
+ if (failures > 0) {
4888
+ console.log(
4889
+ (0, import_colors.red)((0, import_colors.bold)(`\u2717 ${failures} check(s) failed.`)) + (0, import_colors.yellow)(" See the lines marked \u2717 above.")
4890
+ );
4891
+ process.exit(1);
4892
+ }
4893
+ console.log((0, import_colors.green)((0, import_colors.bold)("\u2713 All endpoint checks passed.")));
4894
+ }
4895
+
3338
4896
  // src/cli.ts
3339
4897
  var args = process.argv.slice(2);
3340
4898
  var USAGE = `
@@ -3344,9 +4902,31 @@ Commands:
3344
4902
  environment Manage deployment environments
3345
4903
  upgrade Upgrade an existing environment
3346
4904
  check-translations Check translation files for completeness
4905
+ verify-endpoints Verify the locally-running country config exposes the
4906
+ expected endpoints and keeps secured ones locked down
3347
4907
 
3348
4908
  Run 'opencrvs <command> --help' for more information on a command.
3349
4909
  `.trim();
4910
+ var VERIFY_ENDPOINTS_USAGE = `
4911
+ Usage: opencrvs verify-endpoints [country-config-url]
4912
+
4913
+ Run this after 'opencrvs upgrade', with the upgraded country config running
4914
+ locally, to confirm it still behaves correctly. It checks over HTTP that:
4915
+ - required public endpoints exist (respond 2xx), and
4916
+ - user-notification trigger endpoints are either absent or reject
4917
+ unauthenticated requests (never processed without a token).
4918
+
4919
+ Arguments:
4920
+ [country-config-url] Optional. Domain or URL of the country config
4921
+ service. Defaults to 'http://localhost:3040', the
4922
+ port country config listens on locally. A bare
4923
+ domain is assumed to use https.
4924
+
4925
+ Options:
4926
+ -h, --help Show this message.
4927
+
4928
+ Exits with a non-zero status if any check fails.
4929
+ `.trim();
3350
4930
  var UPGRADE_USAGE = `
3351
4931
  Usage: opencrvs upgrade [options]
3352
4932
 
@@ -3360,7 +4940,7 @@ Options:
3360
4940
  'infrastructure/' directory is deleted (default).
3361
4941
  -h, --help Show this message.
3362
4942
  `.trim();
3363
- function main2() {
4943
+ function main5() {
3364
4944
  const command = args[0];
3365
4945
  if (!command || command === "--help" || command === "-h") {
3366
4946
  console.log(USAGE);
@@ -3373,6 +4953,8 @@ function main2() {
3373
4953
  return handleUpgrade();
3374
4954
  case "check-translations":
3375
4955
  return handleCheckTranslations();
4956
+ case "verify-endpoints":
4957
+ return handleVerifyEndpoints();
3376
4958
  default:
3377
4959
  console.error(`Unknown command: ${command}
3378
4960
  `);
@@ -3389,6 +4971,7 @@ Usage: opencrvs environment <subcommand>
3389
4971
 
3390
4972
  Subcommands:
3391
4973
  init Initialise a new environment
4974
+ upgrade Upgrade existing environment configuration
3392
4975
  update-workflows Update workflow environment options
3393
4976
  users Manage environment users
3394
4977
  swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
@@ -3399,6 +4982,8 @@ Subcommands:
3399
4982
  switch (subcommand) {
3400
4983
  case "init":
3401
4984
  return runEnvironmentCommand("initialisation", runEnvironmentInit);
4985
+ case "upgrade":
4986
+ return runEnvironmentCommand("environment upgrade", runEnvironmentUpgrade);
3402
4987
  case "update-workflows":
3403
4988
  return runEnvironmentCommand(
3404
4989
  "workflow update",
@@ -3419,10 +5004,10 @@ Subcommands:
3419
5004
  async function runEnvironmentCommand(operation, command) {
3420
5005
  try {
3421
5006
  await command();
3422
- } catch (error4) {
5007
+ } catch (error3) {
3423
5008
  console.error(
3424
5009
  `Environment ${operation} failed:`,
3425
- error4 instanceof Error ? error4.message : error4
5010
+ error3 instanceof Error ? error3.message : error3
3426
5011
  );
3427
5012
  process.exit(1);
3428
5013
  }
@@ -3448,14 +5033,95 @@ async function handleUpgrade() {
3448
5033
  try {
3449
5034
  await runUpgrade(dockerSwarm);
3450
5035
  console.log("Upgrade completed successfully!");
3451
- } catch (error4) {
3452
- console.error("Upgrade failed:", error4);
5036
+ } catch (error3) {
5037
+ console.error("Upgrade failed:", error3);
3453
5038
  process.exit(1);
3454
5039
  }
3455
5040
  }
5041
+ var CHECK_TRANSLATIONS_USAGE = `
5042
+ Usage: opencrvs check-translations [options]
5043
+
5044
+ Check that every message this country config declares has a row in
5045
+ src/translations/countryconfig.csv.
5046
+
5047
+ Options:
5048
+ --write Add the missing rows, filling in English only
5049
+ --outdated List rows nothing in the source declares any more
5050
+ -h, --help Show this help
5051
+ `;
3456
5052
  function handleCheckTranslations() {
3457
- console.log("Checking translations...");
3458
- console.warn("This command is not implemented yet!");
3459
- process.exit(1);
5053
+ const checkArgs = args.slice(1);
5054
+ if (checkArgs.includes("--help") || checkArgs.includes("-h")) {
5055
+ console.log(CHECK_TRANSLATIONS_USAGE);
5056
+ return;
5057
+ }
5058
+ const unknownFlags = checkArgs.filter(
5059
+ (arg) => arg.startsWith("-") && !["--write", "--outdated"].includes(arg)
5060
+ );
5061
+ if (unknownFlags.length > 0) {
5062
+ console.error(`Unknown option: ${unknownFlags.join(", ")}
5063
+ `);
5064
+ console.log(CHECK_TRANSLATIONS_USAGE);
5065
+ process.exit(1);
5066
+ }
5067
+ const cwd = process.cwd();
5068
+ const { missing, outdated, dynamicIds } = check(cwd);
5069
+ for (const file of dynamicIds) {
5070
+ console.warn(
5071
+ `Warning: ${file} declares a message whose id is built at runtime. Ids have to be hardcoded to be checked.`
5072
+ );
5073
+ }
5074
+ if (checkArgs.includes("--outdated")) {
5075
+ console.log(
5076
+ `${outdated.length} row(s) in countryconfig.csv are not declared in src:
5077
+ `
5078
+ );
5079
+ console.log(outdated.join("\n"));
5080
+ return;
5081
+ }
5082
+ if (missing.length === 0) {
5083
+ console.log("Every message declared in src has a translation row.");
5084
+ return;
5085
+ }
5086
+ console.error(
5087
+ `${missing.length} message(s) declared in src have no row in src/translations/countryconfig.csv:
5088
+ `
5089
+ );
5090
+ console.error(missing.map(({ id }) => ` ${id}`).join("\n"));
5091
+ if (!checkArgs.includes("--write")) {
5092
+ console.error(
5093
+ "\nRun `pnpm extract:translations --write` to add them with their English copy."
5094
+ );
5095
+ process.exit(1);
5096
+ }
5097
+ const added = writeMissing(cwd, missing);
5098
+ console.log(`
5099
+ Added ${added.length} row(s) to countryconfig.csv.`);
5100
+ console.log("The languages other than English are still yours to write.");
5101
+ }
5102
+ async function handleVerifyEndpoints() {
5103
+ const verifyArgs = args.slice(1);
5104
+ if (verifyArgs.includes("--help") || verifyArgs.includes("-h")) {
5105
+ console.log(VERIFY_ENDPOINTS_USAGE);
5106
+ process.exit(0);
5107
+ }
5108
+ const positional = verifyArgs.filter((arg) => !arg.startsWith("-"));
5109
+ if (positional.length > 1) {
5110
+ console.error(
5111
+ `Unexpected extra argument(s): ${positional.slice(1).join(", ")}
5112
+ `
5113
+ );
5114
+ console.log(VERIFY_ENDPOINTS_USAGE);
5115
+ process.exit(1);
5116
+ }
5117
+ try {
5118
+ await runVerifyEndpoints(positional[0]);
5119
+ } catch (error3) {
5120
+ console.error(
5121
+ "Endpoint verification failed:",
5122
+ error3 instanceof Error ? error3.message : error3
5123
+ );
5124
+ process.exit(1);
5125
+ }
3460
5126
  }
3461
- main2();
5127
+ main5();