@opencrvs/toolkit 2.1.0-rc.d876831 → 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 (81) hide show
  1. package/README.md +2 -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 +248 -215
  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 +1650 -100
  11. package/dist/commons/api/router.d.ts +407 -50
  12. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  13. package/dist/commons/conditionals/validate.d.ts +7 -3
  14. package/dist/commons/events/ActionDocument.d.ts +4 -4
  15. package/dist/commons/events/ActionInput.d.ts +4 -4
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -0
  17. package/dist/commons/events/EventDocument.d.ts +470 -2
  18. package/dist/commons/events/EventMetadata.d.ts +1 -11
  19. package/dist/commons/events/EventStatus.d.ts +19 -0
  20. package/dist/commons/events/FieldConfig.d.ts +24 -5
  21. package/dist/commons/events/FieldTypeMapping.d.ts +15 -15
  22. package/dist/commons/events/locations.d.ts +63 -10
  23. package/dist/commons/events/test.utils.d.ts +25 -4
  24. package/dist/commons/events/utils.d.ts +13 -2
  25. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  26. package/dist/commons/notification/dispatch.d.ts +10 -0
  27. package/dist/commons/notification/index.d.ts +1 -0
  28. package/dist/conditionals/index.js +79 -57
  29. package/dist/csv.d.ts +25 -0
  30. package/dist/csv.d.ts.map +1 -0
  31. package/dist/csv.js +120 -0
  32. package/dist/environment/logger.d.ts +3 -0
  33. package/dist/environment/logger.d.ts.map +1 -1
  34. package/dist/environment/manage-users.js +1 -1
  35. package/dist/environment/questions.d.ts.map +1 -1
  36. package/dist/environment/questions.js +20 -14
  37. package/dist/environment/setup-environment.js +26 -6
  38. package/dist/environment/templates.d.ts +0 -1
  39. package/dist/environment/templates.d.ts.map +1 -1
  40. package/dist/environment/templates.js +3 -8
  41. package/dist/events/index.js +2632 -2481
  42. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  43. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  44. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  45. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  46. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  47. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  48. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  49. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  50. package/dist/migrations/v2.1/add-translations.js +213 -0
  51. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  52. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  53. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  54. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  55. package/dist/migrations/v2.1/index.js +1058 -0
  56. package/dist/notification/index.js +1027 -1452
  57. package/dist/scopes/index.d.ts +77 -7
  58. package/dist/scopes/index.js +79 -57
  59. package/dist/telemetry/index.d.ts +45 -0
  60. package/dist/telemetry/index.d.ts.map +1 -0
  61. package/dist/telemetry/index.js +39 -0
  62. package/dist/templates/charts-values/dependencies/values.yaml +2 -0
  63. package/dist/templates/charts-values/opencrvs-services/values.yaml +1 -1
  64. package/dist/templates/charts-values/opentelemetry/values.yaml +22 -0
  65. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  66. package/dist/templates/inventory/inventory.template.yml +1 -3
  67. package/dist/translations/check.d.ts +21 -0
  68. package/dist/translations/check.d.ts.map +1 -0
  69. package/dist/translations/check.js +132 -0
  70. package/dist/verify/endpoints.d.ts +2 -0
  71. package/dist/verify/endpoints.d.ts.map +1 -0
  72. package/dist/verify/endpoints.js +345 -0
  73. package/opencrvs-toolkit-2.1.0-rc.d987aec.tgz +0 -0
  74. package/package.json +9 -4
  75. package/tsconfig.build.json +11 -0
  76. package/tsconfig.build.tsbuildinfo +1 -0
  77. package/tsconfig.json +3 -0
  78. package/dist/templates/inventory/production.example.yml +0 -77
  79. package/dist/templates/inventory/qa.example.yml +0 -48
  80. package/opencrvs-toolkit-2.1.0-rc.d876831.tgz +0 -0
  81. package/tsconfig.tsbuildinfo +0 -1
package/dist/cli.js CHANGED
@@ -32,13 +32,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
 
33
33
  // src/environment/paths.ts
34
34
  function getEnvironmentInventoryPath(environment) {
35
- return (0, import_path2.join)("environments", environment, INVENTORY_FILE_NAME);
35
+ return (0, import_path6.join)("environments", environment, INVENTORY_FILE_NAME);
36
36
  }
37
37
  function findOldInventoryFiles() {
38
- return glob.sync((0, import_path2.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
38
+ return glob.sync((0, import_path6.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
39
  }
40
40
  function getEnvironmentNameFromOldInventoryPath(filePath) {
41
- return (0, import_path2.basename)(filePath, ".yml");
41
+ return (0, import_path6.basename)(filePath, ".yml");
42
42
  }
43
43
  function assertNoOldInventoryLayout() {
44
44
  if (findOldInventoryFiles().length === 0) {
@@ -51,13 +51,13 @@ function assertNoOldInventoryLayout() {
51
51
  ].join(" ")
52
52
  );
53
53
  }
54
- var import_path2, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
54
+ var import_path6, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
55
  var init_paths = __esm({
56
56
  "src/environment/paths.ts"() {
57
57
  "use strict";
58
- import_path2 = require("path");
58
+ import_path6 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path2.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path6.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -507,7 +507,7 @@ function storeSecrets(environment, answers) {
507
507
  let envConfig = {};
508
508
  try {
509
509
  envConfig = import_dotenv.default.parse(
510
- (0, import_fs.readFileSync)(`${process.cwd()}/.env.${environment}`)
510
+ (0, import_fs4.readFileSync)(`${process.cwd()}/.env.${environment}`)
511
511
  );
512
512
  } catch (error3) {
513
513
  envConfig = {};
@@ -517,10 +517,10 @@ function storeSecrets(environment, answers) {
517
517
  );
518
518
  const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
519
519
  const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
520
- (0, import_fs.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
520
+ (0, import_fs4.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
521
521
  }
522
522
  function readYamlFile(filePath) {
523
- const fileContent = import_fs.default.readFileSync(filePath, "utf8");
523
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
524
524
  return yaml.load(fileContent);
525
525
  }
526
526
  function writeYamlFile(filePath, data) {
@@ -533,33 +533,30 @@ function writeYamlFile(filePath, data) {
533
533
  noRefs: true,
534
534
  sortKeys: false
535
535
  });
536
- import_fs.default.writeFileSync(filePath, yamlContent, "utf8");
536
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
537
537
  } catch (error3) {
538
538
  throw new Error(`Failed to write inventory file: ${error3}`);
539
539
  }
540
540
  }
541
- var import_fs, yaml, import_dotenv;
541
+ var import_fs4, yaml, import_dotenv;
542
542
  var init_utils = __esm({
543
543
  "src/environment/utils.ts"() {
544
544
  "use strict";
545
- import_fs = __toESM(require("fs"));
545
+ import_fs4 = __toESM(require("fs"));
546
546
  yaml = __toESM(require("js-yaml"));
547
547
  import_dotenv = __toESM(require("dotenv"));
548
548
  }
549
549
  });
550
550
 
551
551
  // src/environment/templates.ts
552
- function getUsers(data) {
553
- if (!data?.all?.vars?.users) {
554
- return { users: [] };
555
- }
556
- return data.all.vars.users;
557
- }
558
552
  function extractAndModifyUsers(data) {
559
553
  if (!data?.all?.vars?.users) {
560
554
  return { users: [] };
561
555
  }
562
556
  const users = data.all.vars.users.map((user) => {
557
+ if (user.role) {
558
+ return user;
559
+ }
563
560
  const { sudoer, ...rest } = user;
564
561
  return {
565
562
  ...rest,
@@ -595,29 +592,29 @@ function extractWorkerNodes(data) {
595
592
  return worker_hosts;
596
593
  }
597
594
  function copyChartsValues(env, values) {
598
- const srcDir = import_path3.default.resolve(__dirname, "templates", "charts-values");
599
- const destDir = import_path3.default.resolve(process.cwd(), "environments", env);
600
- import_fs2.default.mkdirSync(destDir, { recursive: true });
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 });
601
598
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
602
599
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
603
600
  values["opencrvs_environment"] = env;
604
601
  function copyRecursive(src, dest) {
605
- const stat = import_fs2.default.statSync(src);
602
+ const stat = import_fs5.default.statSync(src);
606
603
  if (stat.isDirectory()) {
607
- import_fs2.default.mkdirSync(dest, { recursive: true });
608
- for (const item of import_fs2.default.readdirSync(src)) {
609
- copyRecursive(import_path3.default.join(src, item), import_path3.default.join(dest, item));
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));
610
607
  }
611
608
  } else {
612
- const content = import_fs2.default.readFileSync(src, "utf8");
609
+ const content = import_fs5.default.readFileSync(src, "utf8");
613
610
  const template = import_handlebars.default.compile(content);
614
611
  const updated = template(values);
615
612
  const isOverridesFile = dest.endsWith("override.yaml");
616
- if (isOverridesFile && import_fs2.default.existsSync(dest)) {
613
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
617
614
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
618
615
  return;
619
616
  }
620
- import_fs2.default.writeFileSync(dest, updated, "utf8");
617
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
621
618
  log(` \u2713 Created: ${dest}`);
622
619
  }
623
620
  }
@@ -628,29 +625,29 @@ function copyChartsValues(env, values) {
628
625
  `);
629
626
  }
630
627
  function generateInventory(env, values) {
631
- const templatePath = import_path3.default.join(
628
+ const templatePath = import_path7.default.join(
632
629
  __dirname,
633
630
  "templates",
634
631
  "inventory",
635
632
  "inventory.template.yml"
636
633
  );
637
- const outputPath = import_path3.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
638
- 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");
639
636
  const template = import_handlebars.default.compile(templateFile);
640
637
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
641
638
  const updated = template(values);
642
- import_fs2.default.mkdirSync(import_path3.default.dirname(outputPath), { recursive: true });
643
- 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);
644
641
  log(`
645
642
  \u2705 Generated inventory file at ${outputPath}
646
643
  `);
647
644
  }
648
- var import_fs2, import_path3, import_handlebars;
645
+ var import_fs5, import_path7, import_handlebars;
649
646
  var init_templates = __esm({
650
647
  "src/environment/templates.ts"() {
651
648
  "use strict";
652
- import_fs2 = __toESM(require("fs"));
653
- import_path3 = __toESM(require("path"));
649
+ import_fs5 = __toESM(require("fs"));
650
+ import_path7 = __toESM(require("path"));
654
651
  init_logger();
655
652
  init_paths();
656
653
  import_handlebars = __toESM(require("handlebars"));
@@ -706,18 +703,18 @@ var init_git = __esm({
706
703
  });
707
704
 
708
705
  // src/environment/questions.ts
709
- function validateCIDR(input3) {
710
- if (!input3.trim()) {
706
+ function validateCIDR(input4) {
707
+ if (!input4.trim()) {
711
708
  return true;
712
709
  }
713
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])$/;
714
- 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)";
715
712
  }
716
- function validateCIDRs(input3) {
717
- if (!input3.trim()) {
713
+ function validateCIDRs(input4) {
714
+ if (!input4.trim()) {
718
715
  return true;
719
716
  }
720
- const cidrs = input3.split(",").map((v) => v.trim());
717
+ const cidrs = input4.split(",").map((v) => v.trim());
721
718
  for (const cidr of cidrs) {
722
719
  const result = validateCIDR(cidr);
723
720
  if (result !== true) {
@@ -860,11 +857,28 @@ var init_questions = __esm({
860
857
  scope: "ENVIRONMENT"
861
858
  },
862
859
  {
863
- name: "kubeAPIHost",
860
+ name: "kubeMasterNode",
864
861
  type: "text",
865
- message: `Kubernetes API endpoint (default: auto-detect)`,
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",
870
+ type: "text",
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)`,
866
881
  valueType: "VARIABLE",
867
- // validate: notEmpty,
868
882
  valueLabel: "KUBE_API_HOST",
869
883
  initial: process.env.KUBE_API_HOST,
870
884
  scope: "ENVIRONMENT"
@@ -878,16 +892,6 @@ var init_questions = __esm({
878
892
  valueLabel: "KUBE_API_ALLOWED_CIDRS",
879
893
  initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
880
894
  scope: "ENVIRONMENT"
881
- },
882
- {
883
- name: "kubeWorkerNodes",
884
- type: "text",
885
- message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
886
- valueType: "VARIABLE",
887
- // validate: notEmpty,
888
- valueLabel: "KUBE_WORKER_NODES",
889
- initial: process.env.KUBE_WORKER_NODES || "",
890
- scope: "ENVIRONMENT"
891
895
  }
892
896
  ];
893
897
  staticSSLCertQuestions = [
@@ -918,7 +922,6 @@ var init_questions = __esm({
918
922
  type: "text",
919
923
  message: `Please enter backup server host/IP address, (default: no backup):`,
920
924
  valueType: "VARIABLE",
921
- // validate: notEmpty,
922
925
  valueLabel: "BACKUP_HOST",
923
926
  initial: process.env.BACKUP_HOST || "",
924
927
  scope: "ENVIRONMENT"
@@ -1241,7 +1244,7 @@ function updateInventoryFile(filePath, users) {
1241
1244
  function parseInventoryFile(filePath) {
1242
1245
  try {
1243
1246
  const data = readYamlFile(filePath);
1244
- return getUsers(data);
1247
+ return extractAndModifyUsers(data);
1245
1248
  } catch {
1246
1249
  return [];
1247
1250
  }
@@ -1251,7 +1254,7 @@ function getCurrentUsername() {
1251
1254
  }
1252
1255
  function getCurrentUserSSHKeys() {
1253
1256
  const homeDir = os.homedir();
1254
- const sshDir = path3.join(homeDir, ".ssh");
1257
+ const sshDir = path7.join(homeDir, ".ssh");
1255
1258
  const keys = [];
1256
1259
  const keyFiles = [
1257
1260
  "id_rsa.pub",
@@ -1260,7 +1263,7 @@ function getCurrentUserSSHKeys() {
1260
1263
  "id_dsa.pub"
1261
1264
  ];
1262
1265
  for (const keyFile of keyFiles) {
1263
- const keyPath = path3.join(sshDir, keyFile);
1266
+ const keyPath = path7.join(sshDir, keyFile);
1264
1267
  try {
1265
1268
  if (fs3.existsSync(keyPath)) {
1266
1269
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1601,13 +1604,13 @@ async function manageUsers(inventoryPath) {
1601
1604
  }
1602
1605
  return users;
1603
1606
  }
1604
- var os, fs3, path3, input2, select2, confirm, editor, checkbox;
1607
+ var os, fs3, path7, input2, select2, confirm, editor, checkbox;
1605
1608
  var init_manage_users = __esm({
1606
1609
  "src/environment/manage-users.ts"() {
1607
1610
  "use strict";
1608
1611
  os = __toESM(require("os"));
1609
1612
  fs3 = __toESM(require("fs"));
1610
- path3 = __toESM(require("path"));
1613
+ path7 = __toESM(require("path"));
1611
1614
  init_logger();
1612
1615
  init_utils();
1613
1616
  init_templates();
@@ -1629,6 +1632,10 @@ async function select3(options) {
1629
1632
  const inquirer = await import("@inquirer/prompts");
1630
1633
  return inquirer.select(options);
1631
1634
  }
1635
+ async function input3(options) {
1636
+ const inquirer = await import("@inquirer/prompts");
1637
+ return inquirer.input(options);
1638
+ }
1632
1639
  function questionToPrompt({
1633
1640
  valueType,
1634
1641
  valueLabel,
@@ -2060,6 +2067,7 @@ var init_setup_environment = __esm({
2060
2067
  "ENVIRONMENT",
2061
2068
  existingValues
2062
2069
  )?.value;
2070
+ let restoreHost = findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2063
2071
  let restoreType = findExistingValue(
2064
2072
  "RESTORE_ENVIRONMENT_MODE",
2065
2073
  "VARIABLE",
@@ -2135,6 +2143,10 @@ var init_setup_environment = __esm({
2135
2143
  }
2136
2144
  ]
2137
2145
  });
2146
+ restoreHost = await input3({
2147
+ message: "What is the host/IP address of the restore backup server?",
2148
+ default: restoreHost
2149
+ });
2138
2150
  } else {
2139
2151
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2140
2152
  }
@@ -2469,6 +2481,22 @@ var init_setup_environment = __esm({
2469
2481
  existingValues
2470
2482
  ),
2471
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"
2472
2500
  }
2473
2501
  ];
2474
2502
  if (enableEncryption) {
@@ -2720,7 +2748,7 @@ var init_setup_environment = __esm({
2720
2748
  log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2721
2749
  generateInventory(environment, {
2722
2750
  kube_worker_nodes: kubeWorkerNodes,
2723
- kube_api_host: infrastructure.kubeAPIHost || "",
2751
+ kube_api_host: infrastructure.kubeApiHost || "",
2724
2752
  backup_host: backupHost || "",
2725
2753
  users
2726
2754
  });
@@ -2731,12 +2759,14 @@ var init_setup_environment = __esm({
2731
2759
  // Hardcode like this blocks us from being generic:
2732
2760
  // https://github.com/opencrvs/opencrvs-core/issues/11171
2733
2761
  two_fa_enabled: environment !== "production" ? false : true,
2734
- backup_enabled: configureBackup ? true : false,
2762
+ traefik_mode: traefikConfOption,
2735
2763
  restore_enabled: restoreEnvironmentName ? true : false,
2736
2764
  restore_environment_name: restoreEnvironmentName || "",
2737
2765
  restore_type: restoreType,
2738
- traefik_mode: traefikConfOption,
2739
- backup_type: backupType
2766
+ restore_host: restoreHost || "",
2767
+ backup_enabled: configureBackup ? true : false,
2768
+ backup_type: backupType,
2769
+ backup_host: backupHost || ""
2740
2770
  });
2741
2771
  let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2742
2772
 
@@ -2781,16 +2811,16 @@ var update_workflows_exports = {};
2781
2811
  __export(update_workflows_exports, {
2782
2812
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
2783
2813
  });
2784
- function isDirectory(path6) {
2814
+ function isDirectory(path10) {
2785
2815
  try {
2786
- return (0, import_fs3.statSync)(path6).isDirectory();
2816
+ return (0, import_fs6.statSync)(path10).isDirectory();
2787
2817
  } catch {
2788
2818
  return false;
2789
2819
  }
2790
2820
  }
2791
2821
  async function extractInfrastructureNames() {
2792
- const files = glob2.sync((0, import_path4.join)("environments", "*", INVENTORY_FILE_NAME));
2793
- const infraEnvironments = files.map((file) => (0, import_path4.basename)((0, import_path4.dirname)(file)));
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)));
2794
2824
  if (infraEnvironments.length === 0) {
2795
2825
  console.log(
2796
2826
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -2803,9 +2833,9 @@ async function extractInfrastructureNames() {
2803
2833
  async function extractEnvironmentNames() {
2804
2834
  const entries = await (0, import_promises.readdir)("environments");
2805
2835
  const environments = entries.filter((entry) => {
2806
- const environmentPath = (0, import_path4.join)("environments", entry);
2807
- const opencrvsServicesPath = (0, import_path4.join)(environmentPath, "opencrvs-services");
2808
- return isDirectory(environmentPath) && (0, import_fs3.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
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);
2809
2839
  });
2810
2840
  if (environments.length === 0) {
2811
2841
  console.log(
@@ -2831,7 +2861,7 @@ async function updateWorkflows(envList, config) {
2831
2861
  const { workflows } = config;
2832
2862
  for (const workflowPath of workflows) {
2833
2863
  try {
2834
- const fileContents = (0, import_fs3.readFileSync)(workflowPath, "utf8");
2864
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
2835
2865
  const workflowData = yaml2.load(fileContents);
2836
2866
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2837
2867
  throw new Error(
@@ -2839,7 +2869,7 @@ async function updateWorkflows(envList, config) {
2839
2869
  );
2840
2870
  }
2841
2871
  const updatedContent = updateOptionsInYaml(fileContents, envList);
2842
- (0, import_fs3.writeFileSync)(workflowPath, updatedContent, "utf8");
2872
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
2843
2873
  log(` \u2713 Successfully updated ${workflowPath}`);
2844
2874
  } catch (error3) {
2845
2875
  console.error(
@@ -2893,13 +2923,13 @@ async function updateWorkflowEnvironments() {
2893
2923
  process.exit(1);
2894
2924
  }
2895
2925
  }
2896
- var import_promises, import_fs3, import_path4, glob2, yaml2;
2926
+ var import_promises, import_fs6, import_path8, glob2, yaml2;
2897
2927
  var init_update_workflows = __esm({
2898
2928
  "src/environment/update-workflows.ts"() {
2899
2929
  "use strict";
2900
2930
  import_promises = require("fs/promises");
2901
- import_fs3 = require("fs");
2902
- import_path4 = require("path");
2931
+ import_fs6 = require("fs");
2932
+ import_path8 = require("path");
2903
2933
  glob2 = __toESM(require("glob"));
2904
2934
  yaml2 = __toESM(require("js-yaml"));
2905
2935
  init_logger();
@@ -2913,17 +2943,17 @@ __export(upgrade_exports, {
2913
2943
  upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2914
2944
  });
2915
2945
  function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2916
- if (!(0, import_fs4.existsSync)(sourcePath)) {
2946
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2917
2947
  return false;
2918
2948
  }
2919
- if ((0, import_fs4.existsSync)(destinationPath)) {
2949
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2920
2950
  warn(
2921
2951
  `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2922
2952
  );
2923
2953
  return false;
2924
2954
  }
2925
- (0, import_fs4.mkdirSync)((0, import_path5.dirname)(destinationPath), { recursive: true });
2926
- (0, import_fs4.renameSync)(sourcePath, destinationPath);
2955
+ (0, import_fs7.mkdirSync)((0, import_path9.dirname)(destinationPath), { recursive: true });
2956
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2927
2957
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2928
2958
  return true;
2929
2959
  }
@@ -2943,8 +2973,8 @@ function migrateInventoryFiles() {
2943
2973
  ) || didMoveInventory;
2944
2974
  }
2945
2975
  try {
2946
- if ((0, import_fs4.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs4.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2947
- (0, import_fs4.rmdirSync)(OLD_INVENTORY_DIR);
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);
2948
2978
  log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2949
2979
  }
2950
2980
  } catch {
@@ -2962,12 +2992,12 @@ async function upgradeEnvironmentLayout() {
2962
2992
  }
2963
2993
  log("\nCommit changes into git after upgrade");
2964
2994
  }
2965
- var import_fs4, import_path5, import_kleur5;
2995
+ var import_fs7, import_path9, import_kleur5;
2966
2996
  var init_upgrade = __esm({
2967
2997
  "src/environment/upgrade.ts"() {
2968
2998
  "use strict";
2969
- import_fs4 = require("fs");
2970
- import_path5 = require("path");
2999
+ import_fs7 = require("fs");
3000
+ import_path9 = require("path");
2971
3001
  import_kleur5 = __toESM(require("kleur"));
2972
3002
  init_logger();
2973
3003
  init_paths();
@@ -2993,7 +3023,7 @@ async function selectInventoryFile(dirPath = "./environments") {
2993
3023
  return null;
2994
3024
  }
2995
3025
  const environments = fs4.readdirSync(dirPath).filter((entry) => {
2996
- const filePath = path4.join(dirPath, entry);
3026
+ const filePath = path8.join(dirPath, entry);
2997
3027
  return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
2998
3028
  }).sort();
2999
3029
  if (environments.length === 0) {
@@ -3021,12 +3051,12 @@ async function manageEnvironmentUsers() {
3021
3051
  }
3022
3052
  await manageUsers(inventory_file);
3023
3053
  }
3024
- var fs4, path4, import_kleur6;
3054
+ var fs4, path8, import_kleur6;
3025
3055
  var init_users = __esm({
3026
3056
  "src/environment/users.ts"() {
3027
3057
  "use strict";
3028
3058
  fs4 = __toESM(require("fs"));
3029
- path4 = __toESM(require("path"));
3059
+ path8 = __toESM(require("path"));
3030
3060
  import_kleur6 = __toESM(require("kleur"));
3031
3061
  init_manage_users();
3032
3062
  init_logger();
@@ -3036,11 +3066,11 @@ var init_users = __esm({
3036
3066
 
3037
3067
  // src/environment/swarm-to-k8s.ts
3038
3068
  var swarm_to_k8s_exports = {};
3039
- var path5, import_kleur7, import_core2;
3069
+ var path9, import_kleur7, import_core2;
3040
3070
  var init_swarm_to_k8s = __esm({
3041
3071
  "src/environment/swarm-to-k8s.ts"() {
3042
3072
  "use strict";
3043
- path5 = __toESM(require("path"));
3073
+ path9 = __toESM(require("path"));
3044
3074
  import_kleur7 = __toESM(require("kleur"));
3045
3075
  init_logger();
3046
3076
  init_utils();
@@ -3092,7 +3122,7 @@ var init_swarm_to_k8s = __esm({
3092
3122
  );
3093
3123
  process.exit(1);
3094
3124
  }
3095
- const ansible_inventory = path5.join(old_inventory_path, environment + ".yml");
3125
+ const ansible_inventory = path9.join(old_inventory_path, environment + ".yml");
3096
3126
  const data = readYamlFile(ansible_inventory);
3097
3127
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3098
3128
  const master = dockerManagerFirst(data) || "";
@@ -3393,14 +3423,1157 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
3393
3423
  );
3394
3424
  }
3395
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
+
3396
4481
  // src/migrations/v2.1/index.ts
3397
4482
  async function runUpgrade(dockerSwarm) {
3398
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;
3399
4572
  }
3400
4573
 
3401
4574
  // src/environment/index.ts
3402
- var import_fs5 = require("fs");
3403
- var import_path6 = require("path");
4575
+ var import_fs8 = require("fs");
4576
+ var import_path10 = require("path");
3404
4577
  init_paths();
3405
4578
  var REQUIRED_REPOSITORY_DIRECTORIES = [
3406
4579
  ".github/workflows",
@@ -3411,7 +4584,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3411
4584
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3412
4585
  (directory) => {
3413
4586
  try {
3414
- return !(0, import_fs5.statSync)((0, import_path6.resolve)(repositoryRoot, directory)).isDirectory();
4587
+ return !(0, import_fs8.statSync)((0, import_path10.resolve)(repositoryRoot, directory)).isDirectory();
3415
4588
  } catch {
3416
4589
  return true;
3417
4590
  }
@@ -3448,6 +4621,278 @@ async function runEnvironmentSwarmToK8s() {
3448
4621
  await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
3449
4622
  }
3450
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
+
3451
4896
  // src/cli.ts
3452
4897
  var args = process.argv.slice(2);
3453
4898
  var USAGE = `
@@ -3457,9 +4902,31 @@ Commands:
3457
4902
  environment Manage deployment environments
3458
4903
  upgrade Upgrade an existing environment
3459
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
3460
4907
 
3461
4908
  Run 'opencrvs <command> --help' for more information on a command.
3462
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();
3463
4930
  var UPGRADE_USAGE = `
3464
4931
  Usage: opencrvs upgrade [options]
3465
4932
 
@@ -3473,7 +4940,7 @@ Options:
3473
4940
  'infrastructure/' directory is deleted (default).
3474
4941
  -h, --help Show this message.
3475
4942
  `.trim();
3476
- function main2() {
4943
+ function main5() {
3477
4944
  const command = args[0];
3478
4945
  if (!command || command === "--help" || command === "-h") {
3479
4946
  console.log(USAGE);
@@ -3486,6 +4953,8 @@ function main2() {
3486
4953
  return handleUpgrade();
3487
4954
  case "check-translations":
3488
4955
  return handleCheckTranslations();
4956
+ case "verify-endpoints":
4957
+ return handleVerifyEndpoints();
3489
4958
  default:
3490
4959
  console.error(`Unknown command: ${command}
3491
4960
  `);
@@ -3569,9 +5038,90 @@ async function handleUpgrade() {
3569
5038
  process.exit(1);
3570
5039
  }
3571
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
+ `;
3572
5052
  function handleCheckTranslations() {
3573
- console.log("Checking translations...");
3574
- console.warn("This command is not implemented yet!");
3575
- 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
+ }
3576
5126
  }
3577
- main2();
5127
+ main5();