@opencrvs/toolkit 2.0.0-rc.06690b2 → 2.0.0-rc.068feb5

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 (108) hide show
  1. package/README.md +14 -0
  2. package/build.sh +1 -0
  3. package/create-countryconfig/index.js +50 -20
  4. package/create-countryconfig/package.json +12 -2
  5. package/dist/application-config/index.js +271 -119
  6. package/dist/cli.js +3407 -74
  7. package/dist/commons/api/router.d.ts +3357 -217
  8. package/dist/commons/application-config/index.d.ts +1 -0
  9. package/dist/commons/conditionals/conditionals.d.ts +354 -4
  10. package/dist/commons/conditionals/validate.d.ts +52 -2
  11. package/dist/commons/events/ActionConfig.d.ts +28 -2
  12. package/dist/commons/events/ActionDocument.d.ts +6 -0
  13. package/dist/commons/events/ActionInput.d.ts +114 -0
  14. package/dist/commons/events/AdvancedSearchConfig.d.ts +342 -0
  15. package/dist/commons/events/Draft.d.ts +4 -2
  16. package/dist/commons/events/EventDocument.d.ts +3 -0
  17. package/dist/commons/events/EventIndex.d.ts +0 -3
  18. package/dist/commons/events/EventMetadata.d.ts +0 -7
  19. package/dist/commons/events/FieldConfig.d.ts +378 -50
  20. package/dist/commons/events/FieldType.d.ts +1 -0
  21. package/dist/commons/events/FieldTypeMapping.d.ts +1 -1
  22. package/dist/commons/events/FieldValue.d.ts +6 -0
  23. package/dist/commons/events/WorkqueueConfig.d.ts +150 -150
  24. package/dist/commons/events/field.d.ts +53 -1
  25. package/dist/commons/events/index.d.ts +2 -0
  26. package/dist/commons/events/state/flags.d.ts +16 -0
  27. package/dist/commons/events/state/index.d.ts +0 -4
  28. package/dist/commons/events/state/utils.d.ts +12 -289
  29. package/dist/commons/events/utils.d.ts +13 -2
  30. package/dist/conditionals/index.js +55 -2
  31. package/dist/environment/custom-types.d.ts +33 -0
  32. package/dist/environment/custom-types.d.ts.map +1 -0
  33. package/dist/environment/custom-types.js +12 -0
  34. package/dist/environment/derived-variables.d.ts +134 -0
  35. package/dist/environment/derived-variables.d.ts.map +1 -0
  36. package/dist/environment/derived-variables.js +169 -0
  37. package/dist/environment/editor-questions.d.ts +5 -0
  38. package/dist/environment/editor-questions.d.ts.map +1 -0
  39. package/dist/environment/editor-questions.js +66 -0
  40. package/dist/environment/git.d.ts +5 -0
  41. package/dist/environment/git.d.ts.map +1 -0
  42. package/dist/environment/git.js +38 -0
  43. package/dist/environment/github.d.ts +26 -0
  44. package/dist/environment/github.d.ts.map +1 -0
  45. package/dist/environment/github.js +244 -0
  46. package/dist/environment/index.d.ts +6 -0
  47. package/dist/environment/index.d.ts.map +1 -0
  48. package/dist/environment/index.js +71 -0
  49. package/dist/environment/logger.d.ts +15 -0
  50. package/dist/environment/logger.d.ts.map +1 -0
  51. package/dist/environment/logger.js +25 -0
  52. package/dist/environment/manage-users.d.ts +11 -0
  53. package/dist/environment/manage-users.d.ts.map +1 -0
  54. package/dist/environment/manage-users.js +494 -0
  55. package/dist/environment/questions-helper.d.ts +15 -0
  56. package/dist/environment/questions-helper.d.ts.map +1 -0
  57. package/dist/environment/questions-helper.js +70 -0
  58. package/dist/environment/questions.d.ts +222 -0
  59. package/dist/environment/questions.d.ts.map +1 -0
  60. package/dist/environment/questions.js +465 -0
  61. package/dist/environment/setup-environment.d.ts +2 -0
  62. package/dist/environment/setup-environment.d.ts.map +1 -0
  63. package/dist/environment/setup-environment.js +773 -0
  64. package/dist/environment/ssh-keygen.d.ts +5 -0
  65. package/dist/environment/ssh-keygen.d.ts.map +1 -0
  66. package/dist/environment/ssh-keygen.js +18 -0
  67. package/dist/environment/swarm-to-k8s.d.ts +2 -0
  68. package/dist/environment/swarm-to-k8s.d.ts.map +1 -0
  69. package/dist/environment/swarm-to-k8s.js +172 -0
  70. package/dist/environment/templates/charts-values/dependencies/values.override.yaml +4 -0
  71. package/dist/environment/templates/charts-values/dependencies/values.yaml +82 -0
  72. package/dist/environment/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  73. package/dist/environment/templates/charts-values/opencrvs-services/values.yaml +79 -0
  74. package/dist/environment/templates/charts-values/traefik/values.override.yaml +4 -0
  75. package/dist/environment/templates/charts-values/traefik/values.yaml +116 -0
  76. package/dist/environment/templates/inventory/inventory.template.yml +100 -0
  77. package/dist/environment/templates/inventory/production.example.yml +77 -0
  78. package/dist/environment/templates/inventory/qa.example.yml +48 -0
  79. package/dist/environment/templates.d.ts +27 -0
  80. package/dist/environment/templates.d.ts.map +1 -0
  81. package/dist/environment/templates.js +159 -0
  82. package/dist/environment/update-workflows.d.ts +2 -0
  83. package/dist/environment/update-workflows.d.ts.map +1 -0
  84. package/dist/environment/update-workflows.js +168 -0
  85. package/dist/environment/users.d.ts +2 -0
  86. package/dist/environment/users.d.ts.map +1 -0
  87. package/dist/environment/users.js +102 -0
  88. package/dist/environment/utils.d.ts +18 -0
  89. package/dist/environment/utils.d.ts.map +1 -0
  90. package/dist/environment/utils.js +100 -0
  91. package/dist/events/index.js +1075 -284
  92. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  93. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  94. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -1
  95. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  96. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  97. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  98. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  99. package/dist/migrations/v2.0/index.js +214 -38
  100. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  101. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  102. package/dist/notification/index.js +899 -155
  103. package/dist/scopes/index.d.ts +4 -6
  104. package/dist/scopes/index.js +12 -4
  105. package/opencrvs-toolkit-2.0.0-rc.068feb5.tgz +0 -0
  106. package/package.json +20 -2
  107. package/tsconfig.tsbuildinfo +1 -1
  108. package/opencrvs-toolkit-2.0.0-rc.06690b2.tgz +0 -0
package/dist/cli.js CHANGED
@@ -6,22 +6,3114 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
  var __copyProps = (to, from, except, desc) => {
10
17
  if (from && typeof from === "object" || typeof from === "function") {
11
18
  for (let key of __getOwnPropNames(from))
12
19
  if (!__hasOwnProp.call(to, key) && key !== except)
13
20
  __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
21
  }
15
- return to;
16
- };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
- // If the importer is in node compatibility mode or this is not an ESM
19
- // file that has been converted to a CommonJS file using a Babel-
20
- // compatible transform (i.e. "__esModule" has not been set), then set
21
- // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
24
- ));
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/environment/logger.ts
34
+ var import_kleur, log, warn, success, info, error;
35
+ var init_logger = __esm({
36
+ "src/environment/logger.ts"() {
37
+ "use strict";
38
+ import_kleur = __toESM(require("kleur"));
39
+ log = console.log;
40
+ warn = console.warn;
41
+ success = (...args2) => console.log(import_kleur.default.green(args2.join(" ")));
42
+ info = console.info;
43
+ error = (...args2) => console.log(import_kleur.default.red(args2.join(" ")));
44
+ }
45
+ });
46
+
47
+ // src/environment/github.ts
48
+ async function createEnvironmentVariable(octokit, repositoryId, environment, name, value) {
49
+ await octokit.request(
50
+ `POST /repositories/${repositoryId}/environments/${environment}/variables`,
51
+ {
52
+ repository_id: repositoryId,
53
+ environment_name: environment,
54
+ name,
55
+ value,
56
+ headers: {
57
+ "X-GitHub-Api-Version": "2022-11-28"
58
+ }
59
+ }
60
+ );
61
+ }
62
+ async function updateEnvironmentVariable(octokit, repositoryId, environment, name, value) {
63
+ await octokit.request(
64
+ `PATCH /repositories/${repositoryId}/environments/${environment}/variables/${name}`,
65
+ {
66
+ repository_id: repositoryId,
67
+ environment_name: environment,
68
+ name,
69
+ value,
70
+ headers: {
71
+ "X-GitHub-Api-Version": "2022-11-28"
72
+ }
73
+ }
74
+ );
75
+ }
76
+ async function createRepositoryVariable(octokit, repositoryId, name, value) {
77
+ await octokit.request(
78
+ `POST /repositories/${repositoryId}/actions/variables`,
79
+ {
80
+ repository_id: repositoryId,
81
+ name,
82
+ value,
83
+ headers: {
84
+ "X-GitHub-Api-Version": "2022-11-28"
85
+ }
86
+ }
87
+ );
88
+ }
89
+ async function updateRepositoryVariable(octokit, repositoryId, name, value) {
90
+ await octokit.request(
91
+ `PATCH /repositories/${repositoryId}/actions/variables/${name}`,
92
+ {
93
+ repository_id: repositoryId,
94
+ name,
95
+ value,
96
+ headers: {
97
+ "X-GitHub-Api-Version": "2022-11-28"
98
+ }
99
+ }
100
+ );
101
+ }
102
+ async function getRepositoryId(octokit, owner, repo) {
103
+ const response = await octokit.request("GET /repos/{owner}/{repo}", {
104
+ owner,
105
+ repo
106
+ });
107
+ return response.data.id;
108
+ }
109
+ async function getRepositoryPublicKey(octokit, owner, repo) {
110
+ const res = await octokit.request(
111
+ "GET /repos/{owner}/{repo}/actions/secrets/public-key",
112
+ {
113
+ owner,
114
+ repo
115
+ }
116
+ );
117
+ return res.data;
118
+ }
119
+ async function getPublicKey(octokit, environment, ORGANISATION, REPOSITORY_NAME) {
120
+ const repositoryId = await getRepositoryId(
121
+ octokit,
122
+ ORGANISATION,
123
+ REPOSITORY_NAME
124
+ );
125
+ await octokit.request(
126
+ `PUT /repos/${ORGANISATION}/${REPOSITORY_NAME}/environments/${environment}`,
127
+ {
128
+ headers: {
129
+ "X-GitHub-Api-Version": "2022-11-28"
130
+ }
131
+ }
132
+ );
133
+ const res = await octokit.request(
134
+ `GET /repositories/${repositoryId}/environments/${environment}/secrets/public-key`,
135
+ {
136
+ owner: ORGANISATION,
137
+ repo: REPOSITORY_NAME,
138
+ headers: {
139
+ "X-GitHub-Api-Version": "2022-11-28"
140
+ }
141
+ }
142
+ );
143
+ return res.data;
144
+ }
145
+ async function createEnvironmentSecret(octokit, repositoryId, environment, name, secret, organisationName, repositoryName) {
146
+ await sodium.ready;
147
+ const { key, key_id } = await getPublicKey(
148
+ octokit,
149
+ environment,
150
+ organisationName,
151
+ repositoryName
152
+ );
153
+ const binkey = sodium.from_base64(key, sodium.base64_variants.ORIGINAL);
154
+ const binsec = sodium.from_string(secret);
155
+ const encBytes = sodium.crypto_box_seal(binsec, binkey);
156
+ const encryptedValue = sodium.to_base64(
157
+ encBytes,
158
+ sodium.base64_variants.ORIGINAL
159
+ );
160
+ await octokit.request(
161
+ `PUT /repositories/${repositoryId}/environments/${environment}/secrets/${name}`,
162
+ {
163
+ repository_id: repositoryId,
164
+ environment_name: environment,
165
+ secret_name: name,
166
+ encrypted_value: encryptedValue,
167
+ key_id,
168
+ headers: {
169
+ "X-GitHub-Api-Version": "2022-11-28"
170
+ }
171
+ }
172
+ );
173
+ }
174
+ async function createRepositorySecret(octokit, repositoryId, name, secret, organisationName, repositoryName) {
175
+ await sodium.ready;
176
+ const { key, key_id } = await getRepositoryPublicKey(
177
+ octokit,
178
+ organisationName,
179
+ repositoryName
180
+ );
181
+ const binkey = sodium.from_base64(key, sodium.base64_variants.ORIGINAL);
182
+ const binsec = sodium.from_string(secret);
183
+ const encBytes = sodium.crypto_box_seal(binsec, binkey);
184
+ const encryptedValue = sodium.to_base64(
185
+ encBytes,
186
+ sodium.base64_variants.ORIGINAL
187
+ );
188
+ await octokit.request(
189
+ `PUT /repositories/${repositoryId}/actions/secrets/${name}`,
190
+ {
191
+ encrypted_value: encryptedValue,
192
+ key_id,
193
+ headers: {
194
+ "X-GitHub-Api-Version": "2022-11-28"
195
+ }
196
+ }
197
+ );
198
+ }
199
+ async function getRepositoryEnvironments(octokit, githubOrganisation, repository) {
200
+ const response = await octokit.request("GET /repos/{githubOrganisation}/{repository}/environments", {
201
+ githubOrganisation,
202
+ repository
203
+ });
204
+ const environments = (response.data.environments ?? []).map(
205
+ (env) => env.name
206
+ );
207
+ return environments;
208
+ }
209
+ async function createEnvironment(octokit, environment, ORGANISATION, REPOSITORY_NAME) {
210
+ try {
211
+ await octokit.request(
212
+ `PUT /repos/${ORGANISATION}/${REPOSITORY_NAME}/environments/${environment}`,
213
+ {
214
+ headers: {
215
+ "X-GitHub-Api-Version": "2022-11-28"
216
+ }
217
+ }
218
+ );
219
+ return true;
220
+ } catch (err) {
221
+ error(
222
+ `Cannot create environment: [${err.status}] ${err.response?.data?.message}`
223
+ );
224
+ throw new Error(
225
+ `Cannot create environment: [${err.status}] ${err.response?.data?.message}`
226
+ );
227
+ }
228
+ }
229
+ async function listEnvironmentSecrets(octokit, owner, repositoryId, environmentName) {
230
+ const response = await octokit.request(
231
+ "GET /repositories/{repository_id}/environments/{environment_name}/secrets",
232
+ {
233
+ owner,
234
+ repository_id: repositoryId,
235
+ environment_name: environmentName,
236
+ per_page: 100
237
+ }
238
+ );
239
+ return response.data.secrets.map((secret) => ({
240
+ ...secret,
241
+ type: "SECRET",
242
+ scope: "ENVIRONMENT"
243
+ }));
244
+ }
245
+ async function listRepositorySecrets(octokit, owner, repositoryName) {
246
+ const response = await octokit.request(
247
+ "GET /repos/{owner}/{repo}/actions/secrets",
248
+ {
249
+ owner,
250
+ repo: repositoryName,
251
+ per_page: 100
252
+ }
253
+ );
254
+ return response.data.secrets.map((secret) => ({
255
+ ...secret,
256
+ type: "SECRET",
257
+ scope: "REPOSITORY"
258
+ }));
259
+ }
260
+ async function listEnvironmentVariables(octokit, repositoryId, environmentName) {
261
+ const response = await octokit.request(
262
+ "GET /repositories/{repository_id}/environments/{environment_name}/variables",
263
+ {
264
+ repository_id: repositoryId,
265
+ environment_name: environmentName,
266
+ per_page: 100,
267
+ headers: {
268
+ "X-GitHub-Api-Version": "2022-11-28"
269
+ }
270
+ }
271
+ );
272
+ return response.data.variables.map((variable) => ({
273
+ ...variable,
274
+ type: "VARIABLE",
275
+ scope: "ENVIRONMENT"
276
+ })).filter((variable) => variable.name !== "ACTIONS_RUNNER_DEBUG");
277
+ }
278
+ async function listRepositoryVariables(octokit, owner, repositoryName) {
279
+ const response = await octokit.request(
280
+ "GET /repos/{owner}/{repo}/actions/variables",
281
+ {
282
+ owner,
283
+ repo: repositoryName,
284
+ per_page: 100
285
+ }
286
+ );
287
+ return response.data.variables.map((variable) => ({
288
+ ...variable,
289
+ type: "VARIABLE",
290
+ scope: "REPOSITORY"
291
+ }));
292
+ }
293
+ var sodium;
294
+ var init_github = __esm({
295
+ "src/environment/github.ts"() {
296
+ "use strict";
297
+ init_logger();
298
+ sodium = require("libsodium-wrappers");
299
+ }
300
+ });
301
+
302
+ // src/environment/derived-variables.ts
303
+ var derivedVariables;
304
+ var init_derived_variables = __esm({
305
+ "src/environment/derived-variables.ts"() {
306
+ "use strict";
307
+ derivedVariables = [
308
+ {
309
+ name: "ACTIVATE_USERS",
310
+ valueLabel: "ACTIVATE_USERS",
311
+ valueType: "VARIABLE",
312
+ type: "disabled",
313
+ scope: "ENVIRONMENT"
314
+ },
315
+ {
316
+ name: "COUNTRY_CONFIG_HOST",
317
+ valueLabel: "COUNTRY_CONFIG_HOST",
318
+ valueType: "VARIABLE",
319
+ type: "disabled",
320
+ scope: "ENVIRONMENT"
321
+ },
322
+ {
323
+ name: "GATEWAY_HOST",
324
+ valueLabel: "GATEWAY_HOST",
325
+ valueType: "VARIABLE",
326
+ type: "disabled",
327
+ scope: "ENVIRONMENT"
328
+ },
329
+ {
330
+ name: "CONTENT_SECURITY_POLICY_WILDCARD",
331
+ valueLabel: "CONTENT_SECURITY_POLICY_WILDCARD",
332
+ valueType: "VARIABLE",
333
+ type: "disabled",
334
+ scope: "ENVIRONMENT"
335
+ },
336
+ {
337
+ name: "CLIENT_APP_URL",
338
+ valueLabel: "CLIENT_APP_URL",
339
+ valueType: "VARIABLE",
340
+ type: "disabled",
341
+ scope: "ENVIRONMENT"
342
+ },
343
+ {
344
+ name: "LOGIN_URL",
345
+ valueLabel: "LOGIN_URL",
346
+ valueType: "VARIABLE",
347
+ type: "disabled",
348
+ scope: "ENVIRONMENT"
349
+ },
350
+ {
351
+ name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
352
+ valueLabel: "ELASTICSEARCH_SUPERUSER_PASSWORD",
353
+ valueType: "SECRET",
354
+ type: "disabled",
355
+ scope: "ENVIRONMENT"
356
+ },
357
+ {
358
+ name: "KIBANA_SYSTEM_PASSWORD",
359
+ valueLabel: "KIBANA_SYSTEM_PASSWORD",
360
+ valueType: "SECRET",
361
+ type: "disabled",
362
+ scope: "ENVIRONMENT"
363
+ },
364
+ {
365
+ name: "MINIO_ROOT_USER",
366
+ valueLabel: "MINIO_ROOT_USER",
367
+ valueType: "SECRET",
368
+ type: "disabled",
369
+ scope: "ENVIRONMENT"
370
+ },
371
+ {
372
+ name: "MINIO_ROOT_PASSWORD",
373
+ valueLabel: "MINIO_ROOT_PASSWORD",
374
+ valueType: "SECRET",
375
+ type: "disabled",
376
+ scope: "ENVIRONMENT"
377
+ },
378
+ {
379
+ name: "MONGODB_ADMIN_USER",
380
+ valueLabel: "MONGODB_ADMIN_USER",
381
+ valueType: "SECRET",
382
+ type: "disabled",
383
+ scope: "ENVIRONMENT"
384
+ },
385
+ {
386
+ name: "MONGODB_ADMIN_PASSWORD",
387
+ valueLabel: "MONGODB_ADMIN_PASSWORD",
388
+ valueType: "SECRET",
389
+ type: "disabled",
390
+ scope: "ENVIRONMENT"
391
+ },
392
+ {
393
+ name: "POSTGRES_USER",
394
+ valueLabel: "POSTGRES_USER",
395
+ valueType: "SECRET",
396
+ type: "disabled",
397
+ scope: "ENVIRONMENT"
398
+ },
399
+ {
400
+ name: "POSTGRES_PASSWORD",
401
+ valueLabel: "POSTGRES_PASSWORD",
402
+ valueType: "SECRET",
403
+ type: "disabled",
404
+ scope: "ENVIRONMENT"
405
+ },
406
+ {
407
+ name: "SUPER_USER_PASSWORD",
408
+ valueLabel: "SUPER_USER_PASSWORD",
409
+ valueType: "SECRET",
410
+ type: "disabled",
411
+ scope: "ENVIRONMENT"
412
+ },
413
+ {
414
+ name: "ENCRYPTION_KEY",
415
+ valueLabel: "ENCRYPTION_KEY",
416
+ valueType: "SECRET",
417
+ type: "disabled",
418
+ scope: "ENVIRONMENT"
419
+ },
420
+ {
421
+ name: "GH_ENCRYPTION_PASSWORD",
422
+ valueLabel: "GH_ENCRYPTION_PASSWORD",
423
+ valueType: "SECRET",
424
+ type: "disabled",
425
+ scope: "REPOSITORY"
426
+ },
427
+ {
428
+ name: "BACKUP_ENCRYPTION_PASSPHRASE",
429
+ valueLabel: "BACKUP_ENCRYPTION_PASSPHRASE",
430
+ valueType: "SECRET",
431
+ type: "disabled",
432
+ scope: "ENVIRONMENT"
433
+ },
434
+ {
435
+ name: "BACKUP_HOST_PRIVATE_KEY",
436
+ valueLabel: "BACKUP_HOST_PRIVATE_KEY",
437
+ valueType: "SECRET",
438
+ type: "disabled",
439
+ scope: "ENVIRONMENT"
440
+ },
441
+ {
442
+ name: "BACKUP_HOST_PUBLIC_KEY",
443
+ valueLabel: "BACKUP_HOST_PUBLIC_KEY",
444
+ valueType: "SECRET",
445
+ type: "disabled",
446
+ scope: "ENVIRONMENT"
447
+ },
448
+ {
449
+ name: "RESTORE_ENVIRONMENT_NAME",
450
+ valueLabel: "RESTORE_ENVIRONMENT_NAME",
451
+ valueType: "VARIABLE",
452
+ type: "disabled",
453
+ scope: "ENVIRONMENT"
454
+ },
455
+ {
456
+ name: "NOTIFICATION_TRANSPORT",
457
+ valueLabel: "NOTIFICATION_TRANSPORT",
458
+ valueType: "VARIABLE",
459
+ type: "disabled",
460
+ scope: "ENVIRONMENT"
461
+ }
462
+ ];
463
+ }
464
+ });
465
+
466
+ // src/environment/utils.ts
467
+ function generateLongPassword() {
468
+ const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
469
+ let result = "";
470
+ for (let i = 16; i > 0; --i)
471
+ result += chars[Math.floor(Math.random() * chars.length)];
472
+ return result;
473
+ }
474
+ function findExistingValue(name, type, scope, existingValues) {
475
+ return existingValues.find(
476
+ (value) => value.name === name && value.type === type && value.scope === scope
477
+ );
478
+ }
479
+ function storeSecrets(environment, answers) {
480
+ let envConfig = {};
481
+ try {
482
+ envConfig = import_dotenv.default.parse(
483
+ (0, import_fs7.readFileSync)(`${process.cwd()}/.env.${environment}`)
484
+ );
485
+ } catch (error4) {
486
+ envConfig = {};
487
+ }
488
+ const linesFromAnswers = answers.map(
489
+ (update) => `${update.name}="${update.value}"`
490
+ );
491
+ const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
492
+ const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
493
+ (0, import_fs7.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
494
+ }
495
+ function readYamlFile(filePath) {
496
+ const fileContent = import_fs7.default.readFileSync(filePath, "utf8");
497
+ return yaml.load(fileContent);
498
+ }
499
+ function writeYamlFile(filePath, data) {
500
+ try {
501
+ const yamlContent = yaml.dump(data, {
502
+ indent: 2,
503
+ lineWidth: -1,
504
+ flowLevel: -1,
505
+ // Prevent flow style for arrays/objects
506
+ noRefs: true,
507
+ sortKeys: false
508
+ });
509
+ import_fs7.default.writeFileSync(filePath, yamlContent, "utf8");
510
+ } catch (error4) {
511
+ throw new Error(`Failed to write inventory file: ${error4}`);
512
+ }
513
+ }
514
+ var import_fs7, yaml, import_dotenv;
515
+ var init_utils = __esm({
516
+ "src/environment/utils.ts"() {
517
+ "use strict";
518
+ import_fs7 = __toESM(require("fs"));
519
+ yaml = __toESM(require("js-yaml"));
520
+ import_dotenv = __toESM(require("dotenv"));
521
+ }
522
+ });
523
+
524
+ // src/environment/templates.ts
525
+ function getUsers(data) {
526
+ if (!data?.all?.vars?.users) {
527
+ return { users: [] };
528
+ }
529
+ return data.all.vars.users;
530
+ }
531
+ function extractAndModifyUsers(data) {
532
+ if (!data?.all?.vars?.users) {
533
+ return { users: [] };
534
+ }
535
+ const users = data.all.vars.users.map((user) => {
536
+ const { sudoer, ...rest } = user;
537
+ return {
538
+ ...rest,
539
+ role: sudoer ? "admin" : "operator"
540
+ };
541
+ });
542
+ return users;
543
+ }
544
+ function dockerManagerFirst(data) {
545
+ if (!data?.["docker-manager-first"]?.hosts) {
546
+ throw new Error("Invalid YAML structure: missing docker-manager-first.hosts");
547
+ }
548
+ const hosts = data["docker-manager-first"].hosts;
549
+ const dockerManagerFirst2 = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
550
+ return dockerManagerFirst2.length === 1 ? dockerManagerFirst2[0] : "";
551
+ }
552
+ function extractBackupNode(data) {
553
+ if (!data?.["backups"]?.hosts) {
554
+ return "";
555
+ }
556
+ const hosts = data["backups"].hosts;
557
+ const backupHostEntry = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
558
+ return backupHostEntry.length === 1 ? backupHostEntry[0] : "";
559
+ }
560
+ function extractWorkerNodes(data) {
561
+ if (!data?.["docker-workers"]?.hosts) {
562
+ return [];
563
+ }
564
+ const hosts = data["docker-workers"].hosts;
565
+ const worker_hosts = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
566
+ return worker_hosts;
567
+ }
568
+ function copyChartsValues(env, values) {
569
+ const srcDir = import_path27.default.resolve(__dirname, "templates", "charts-values");
570
+ const destDir = import_path27.default.resolve(process.cwd(), "environments", env);
571
+ import_fs8.default.mkdirSync(destDir, { recursive: true });
572
+ values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
573
+ values["static_ssl"] = values["traefik_mode"] === "static_ssl";
574
+ function copyRecursive(src, dest) {
575
+ const stat = import_fs8.default.statSync(src);
576
+ if (stat.isDirectory()) {
577
+ import_fs8.default.mkdirSync(dest, { recursive: true });
578
+ for (const item of import_fs8.default.readdirSync(src)) {
579
+ copyRecursive(import_path27.default.join(src, item), import_path27.default.join(dest, item));
580
+ }
581
+ } else {
582
+ const content = import_fs8.default.readFileSync(src, "utf8");
583
+ const template = import_handlebars.default.compile(content);
584
+ const updated = template(values);
585
+ const isOverridesFile = dest.endsWith("override.yaml");
586
+ if (isOverridesFile && import_fs8.default.existsSync(dest)) {
587
+ log(` \u21B7 Skipped existing overrides file: ${dest}`);
588
+ return;
589
+ }
590
+ import_fs8.default.writeFileSync(dest, updated, "utf8");
591
+ log(` \u2713 Created: ${dest}`);
592
+ }
593
+ }
594
+ log(`
595
+ \u{1F4CB} Copying charts-values templates to ${destDir}:`);
596
+ copyRecursive(srcDir, destDir);
597
+ success(`\u2705 Completed copying charts-values.
598
+ `);
599
+ }
600
+ function generateInventory(env, values) {
601
+ const templatePath = import_path27.default.join(__dirname, "templates", "inventory", "inventory.template.yml");
602
+ const outputPath = import_path27.default.join(process.cwd(), "infrastructure", "server-setup", "inventory", `${env}.yml`);
603
+ const templateFile = import_fs8.default.readFileSync(templatePath, "utf-8");
604
+ const template = import_handlebars.default.compile(templateFile);
605
+ values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
606
+ const updated = template(values);
607
+ import_fs8.default.mkdirSync(import_path27.default.dirname(outputPath), { recursive: true });
608
+ import_fs8.default.writeFileSync(outputPath, updated);
609
+ log(`
610
+ \u2705 Generated inventory file at ${outputPath}
611
+ `);
612
+ }
613
+ var import_fs8, import_path27, import_handlebars;
614
+ var init_templates = __esm({
615
+ "src/environment/templates.ts"() {
616
+ "use strict";
617
+ import_fs8 = __toESM(require("fs"));
618
+ import_path27 = __toESM(require("path"));
619
+ init_logger();
620
+ import_handlebars = __toESM(require("handlebars"));
621
+ import_handlebars.default.registerHelper("data_label_idx", function(value) {
622
+ return parseInt(value) + 2;
623
+ });
624
+ }
625
+ });
626
+
627
+ // src/environment/ssh-keygen.ts
628
+ function generateSSHKeyPair() {
629
+ let keys = import_ssh2.utils.generateKeyPairSync("ed25519");
630
+ return { publicKey: keys.public.toString(), privateKey: keys.private.toString() };
631
+ }
632
+ var import_ssh2;
633
+ var init_ssh_keygen = __esm({
634
+ "src/environment/ssh-keygen.ts"() {
635
+ "use strict";
636
+ import_ssh2 = require("ssh2");
637
+ }
638
+ });
639
+
640
+ // src/environment/git.ts
641
+ function getRepoInfo() {
642
+ try {
643
+ const remoteUrl = (0, import_child_process3.execSync)("git config --get remote.origin.url", {
644
+ stdio: ["ignore", "pipe", "ignore"]
645
+ }).toString().trim();
646
+ const match = remoteUrl.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
647
+ if (!match) {
648
+ return { organization: "", repository: "" };
649
+ }
650
+ return {
651
+ organization: match[1],
652
+ repository: match[2]
653
+ };
654
+ } catch {
655
+ return {
656
+ organization: "",
657
+ repository: ""
658
+ };
659
+ }
660
+ }
661
+ var import_child_process3;
662
+ var init_git = __esm({
663
+ "src/environment/git.ts"() {
664
+ "use strict";
665
+ import_child_process3 = require("child_process");
666
+ }
667
+ });
668
+
669
+ // src/environment/questions.ts
670
+ function validateCIDR(input3) {
671
+ if (!input3.trim()) {
672
+ return true;
673
+ }
674
+ 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])$/;
675
+ return cidrRegex.test(input3.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
676
+ }
677
+ function validateCIDRs(input3) {
678
+ if (!input3.trim()) {
679
+ return true;
680
+ }
681
+ const cidrs = input3.split(",").map((v) => v.trim());
682
+ for (const cidr of cidrs) {
683
+ const result = validateCIDR(cidr);
684
+ if (result !== true) {
685
+ return `Invalid CIDR: ${cidr}`;
686
+ }
687
+ }
688
+ return true;
689
+ }
690
+ var import_kleur2, notEmpty, dockerhubQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, notificationTransportQuestions, smsQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
691
+ var init_questions = __esm({
692
+ "src/environment/questions.ts"() {
693
+ "use strict";
694
+ import_kleur2 = __toESM(require("kleur"));
695
+ init_utils();
696
+ init_git();
697
+ notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
698
+ dockerhubQuestions = [
699
+ {
700
+ name: "dockerhubOrganisation",
701
+ type: "text",
702
+ message: "What is the name of your Docker Hub organisation?",
703
+ valueType: "SECRET",
704
+ valueLabel: "DOCKERHUB_ACCOUNT",
705
+ validate: notEmpty,
706
+ initial: process.env.DOCKER_ORGANISATION,
707
+ scope: "REPOSITORY"
708
+ },
709
+ {
710
+ name: "dockerhubRepository",
711
+ type: "text",
712
+ message: "What is the name of your private Docker Hub repository?",
713
+ valueType: "SECRET",
714
+ valueLabel: "DOCKERHUB_REPO",
715
+ validate: notEmpty,
716
+ initial: process.env.DOCKER_REPO,
717
+ scope: "REPOSITORY"
718
+ },
719
+ {
720
+ name: "dockerhubUsername",
721
+ type: "text",
722
+ message: "What is the Docker Hub username the the target server should be using?",
723
+ valueType: "SECRET",
724
+ valueLabel: "DOCKER_USERNAME",
725
+ validate: notEmpty,
726
+ initial: process.env.DOCKER_USERNAME,
727
+ scope: "REPOSITORY"
728
+ },
729
+ {
730
+ name: "dockerhubToken",
731
+ type: "text",
732
+ message: "What is the token of this Docker Hub account?",
733
+ valueType: "SECRET",
734
+ valueLabel: "DOCKER_TOKEN",
735
+ validate: notEmpty,
736
+ initial: process.env.DOCKER_TOKEN,
737
+ scope: "REPOSITORY"
738
+ }
739
+ ];
740
+ githubQuestions = [
741
+ {
742
+ name: "githubOrganisation",
743
+ type: "text",
744
+ message: "What is the name of your Github organisation?",
745
+ validate: notEmpty,
746
+ initial: process.env.GITHUB_ORGANISATION || getRepoInfo().organization,
747
+ scope: "REPOSITORY"
748
+ },
749
+ {
750
+ name: "githubRepository",
751
+ type: "text",
752
+ message: "What is your Github infrastructure repository?",
753
+ validate: notEmpty,
754
+ initial: process.env.GITHUB_REPOSITORY || getRepoInfo().repository,
755
+ scope: "REPOSITORY"
756
+ }
757
+ ];
758
+ githubOtherQuestions = [
759
+ {
760
+ name: "githubApprovers",
761
+ type: "text",
762
+ message: "Please provide/update list of production approvers?",
763
+ initial: process.env.GH_APPROVERS,
764
+ valueType: "VARIABLE",
765
+ valueLabel: "GH_APPROVERS",
766
+ scope: "REPOSITORY"
767
+ },
768
+ {
769
+ name: "approvalRequired",
770
+ type: "select",
771
+ message: "Would you like to enable approvals process for GitHub action workflows?",
772
+ choices: [
773
+ {
774
+ title: "True",
775
+ value: "true"
776
+ },
777
+ {
778
+ title: "False",
779
+ value: "false"
780
+ }
781
+ ],
782
+ valueType: "VARIABLE",
783
+ validate: notEmpty,
784
+ valueLabel: "APPROVAL_REQUIRED",
785
+ initial: process.env.APPROVAL_REQUIRED,
786
+ scope: "ENVIRONMENT"
787
+ }
788
+ ];
789
+ githubTokenQuestion = [
790
+ {
791
+ name: "githubToken",
792
+ type: "text",
793
+ message: "What is your Github token?",
794
+ validate: notEmpty,
795
+ initial: process.env.GITHUB_TOKEN,
796
+ valueType: "SECRET",
797
+ scope: "REPOSITORY",
798
+ valueLabel: "GH_TOKEN"
799
+ }
800
+ ];
801
+ countryQuestions = [
802
+ {
803
+ name: "country",
804
+ type: "text",
805
+ message: 'What is the ISO 3166-1 alpha-3 country-code? (e.g. "NZL" for New Zealand) Reference: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3',
806
+ valueType: "VARIABLE",
807
+ valueLabel: "COUNTRY",
808
+ initial: process.env.COUNTRY,
809
+ scope: "REPOSITORY"
810
+ }
811
+ ];
812
+ infrastructureQuestions = [
813
+ {
814
+ name: "domain",
815
+ type: "text",
816
+ message: "What is the web domain applied after all subdomains in URLs?",
817
+ valueType: "VARIABLE",
818
+ validate: notEmpty,
819
+ valueLabel: "DOMAIN",
820
+ initial: process.env.DOMAIN,
821
+ scope: "ENVIRONMENT"
822
+ },
823
+ {
824
+ name: "kubeAPIHost",
825
+ type: "text",
826
+ message: `Kubernetes API endpoint (default: auto-detect)`,
827
+ valueType: "VARIABLE",
828
+ // validate: notEmpty,
829
+ valueLabel: "KUBE_API_HOST",
830
+ initial: process.env.KUBE_API_HOST,
831
+ scope: "ENVIRONMENT"
832
+ },
833
+ {
834
+ name: "kubeApiAllowedCidrs",
835
+ type: "text",
836
+ message: `Allowed CIDRs for Kubernetes API access (default: KUBE_API_HOST)`,
837
+ valueType: "VARIABLE",
838
+ validate: validateCIDRs,
839
+ valueLabel: "KUBE_API_ALLOWED_CIDRS",
840
+ initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
841
+ scope: "ENVIRONMENT"
842
+ },
843
+ {
844
+ name: "kubeWorkerNodes",
845
+ type: "text",
846
+ message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
847
+ valueType: "VARIABLE",
848
+ // validate: notEmpty,
849
+ valueLabel: "KUBE_WORKER_NODES",
850
+ initial: process.env.KUBE_WORKER_NODES || "",
851
+ scope: "ENVIRONMENT"
852
+ }
853
+ ];
854
+ staticSSLCertQuestions = [
855
+ {
856
+ name: "sslCrt",
857
+ type: "text",
858
+ message: "Provide SSL Certificate or Certificate chain:",
859
+ valueType: "SECRET",
860
+ validate: notEmpty,
861
+ valueLabel: "SSL_CRT",
862
+ initial: process.env.SSL_CRT,
863
+ scope: "ENVIRONMENT"
864
+ },
865
+ {
866
+ name: "sslKey",
867
+ type: "text",
868
+ message: "Provide SSL Certificate key",
869
+ valueType: "SECRET",
870
+ validate: notEmpty,
871
+ valueLabel: "SSL_KEY",
872
+ initial: process.env.SSL_KEY,
873
+ scope: "ENVIRONMENT"
874
+ }
875
+ ];
876
+ backupQuestions = [
877
+ {
878
+ name: "backupHost",
879
+ type: "text",
880
+ message: `Please enter backup server host/IP address, (default: no backup):`,
881
+ valueType: "VARIABLE",
882
+ // validate: notEmpty,
883
+ valueLabel: "BACKUP_HOST",
884
+ initial: process.env.BACKUP_HOST || "",
885
+ scope: "ENVIRONMENT"
886
+ },
887
+ {
888
+ name: "backupUser",
889
+ type: "text",
890
+ message: `Please enter backup server user name:`,
891
+ valueType: "SECRET",
892
+ validate: notEmpty,
893
+ valueLabel: "BACKUP_SERVER_USER",
894
+ initial: process.env.BACKUP_SERVER_USER || "backup",
895
+ scope: "ENVIRONMENT"
896
+ },
897
+ {
898
+ name: "backupType",
899
+ type: "select",
900
+ message: "Select environment backup mode",
901
+ choices: [
902
+ {
903
+ title: "Full dump (daily full database backup)",
904
+ value: "dump"
905
+ },
906
+ {
907
+ title: "Differential (weekly full, daily diff backup)",
908
+ value: "differential"
909
+ }
910
+ ],
911
+ valueType: "VARIABLE",
912
+ validate: notEmpty,
913
+ valueLabel: "BACKUP_ENVIRONMENT_MODE",
914
+ initial: process.env.BACKUP_ENVIRONMENT_MODE,
915
+ scope: "ENVIRONMENT"
916
+ }
917
+ ];
918
+ diskQuestions = [
919
+ {
920
+ name: "diskSpace",
921
+ type: "text",
922
+ message: `What is the amount of diskspace that should be dedicated to OpenCRVS data and will become the size of an encrypted cryptfs data directory.
923
+
924
+ ${import_kleur2.default.red("DO NOT USE ALL DISKSPACE FOR OPENCRVS!")}
925
+
926
+ Leave at least 50g available for OS use.`,
927
+ valueType: "VARIABLE",
928
+ validate: notEmpty,
929
+ valueLabel: "DISK_SPACE",
930
+ initial: process.env.DISK_SPACE || "200g",
931
+ scope: "ENVIRONMENT"
932
+ }
933
+ ];
934
+ databaseAndMonitoringQuestions = [
935
+ {
936
+ name: "kibanaUsername",
937
+ type: "text",
938
+ message: "Input the username for logging in to Kibana",
939
+ valueType: "SECRET",
940
+ validate: notEmpty,
941
+ valueLabel: "KIBANA_USERNAME",
942
+ initial: process.env.KIBANA_USERNAME || "opencrvs-admin",
943
+ scope: "ENVIRONMENT"
944
+ },
945
+ {
946
+ name: "kibanaPassword",
947
+ type: "text",
948
+ message: "Input the password for logging in to Kibana",
949
+ valueType: "SECRET",
950
+ validate: notEmpty,
951
+ valueLabel: "KIBANA_PASSWORD",
952
+ initial: process.env.KIBANA_PASSWORD || generateLongPassword(),
953
+ scope: "ENVIRONMENT"
954
+ }
955
+ ];
956
+ notificationTransportQuestions = [
957
+ {
958
+ name: "notificationTransport",
959
+ type: "select",
960
+ message: "Notification transport for 2FA, informant and user messaging",
961
+ choices: [
962
+ {
963
+ title: "Email (with SMTP details)",
964
+ value: "email"
965
+ },
966
+ {
967
+ title: "SMS (Infobip)",
968
+ value: "sms"
969
+ }
970
+ ],
971
+ valueLabel: "NOTIFICATION_TRANSPORT",
972
+ valueType: "VARIABLE",
973
+ scope: "ENVIRONMENT",
974
+ initial: process.env.NOTIFICATION_TRANSPORT
975
+ }
976
+ ];
977
+ smsQuestions = [
978
+ {
979
+ name: "infobipApiKey",
980
+ type: "text",
981
+ message: "What is your Infobip API key?",
982
+ valueType: "SECRET",
983
+ validate: notEmpty,
984
+ valueLabel: "INFOBIP_API_KEY",
985
+ initial: process.env.INFOBIP_API_KEY,
986
+ scope: "ENVIRONMENT"
987
+ },
988
+ {
989
+ name: "infobipGatewayEndpoint",
990
+ type: "text",
991
+ message: "What is your Infobip gateway endpoint?",
992
+ valueType: "SECRET",
993
+ validate: notEmpty,
994
+ valueLabel: "INFOBIP_GATEWAY_ENDPOINT",
995
+ initial: process.env.INFOBIP_GATEWAY_ENDPOINT,
996
+ scope: "ENVIRONMENT"
997
+ },
998
+ {
999
+ name: "infobipSenderId",
1000
+ type: "text",
1001
+ message: "What is your Infobip sender ID?",
1002
+ valueType: "SECRET",
1003
+ validate: notEmpty,
1004
+ valueLabel: "INFOBIP_SENDER_ID",
1005
+ initial: process.env.INFOBIP_SENDER_ID,
1006
+ scope: "ENVIRONMENT"
1007
+ }
1008
+ ];
1009
+ emailQuestions = [
1010
+ {
1011
+ name: "smtpHost",
1012
+ type: "text",
1013
+ message: "What is your SMTP host?",
1014
+ valueType: "SECRET",
1015
+ validate: notEmpty,
1016
+ valueLabel: "SMTP_HOST",
1017
+ initial: process.env.SMTP_HOST,
1018
+ scope: "ENVIRONMENT"
1019
+ },
1020
+ {
1021
+ name: "smtpUsername",
1022
+ type: "text",
1023
+ message: "What is your SMTP username?",
1024
+ valueType: "SECRET",
1025
+ validate: notEmpty,
1026
+ valueLabel: "SMTP_USERNAME",
1027
+ initial: process.env.SMTP_USERNAME,
1028
+ scope: "ENVIRONMENT"
1029
+ },
1030
+ {
1031
+ name: "smtpPassword",
1032
+ type: "text",
1033
+ message: "What is your SMTP password?",
1034
+ valueType: "SECRET",
1035
+ validate: notEmpty,
1036
+ valueLabel: "SMTP_PASSWORD",
1037
+ initial: process.env.SMTP_PASSWORD,
1038
+ scope: "ENVIRONMENT"
1039
+ },
1040
+ {
1041
+ name: "smtpPort",
1042
+ type: "text",
1043
+ message: "What is your SMTP port?",
1044
+ valueType: "SECRET",
1045
+ validate: notEmpty,
1046
+ valueLabel: "SMTP_PORT",
1047
+ initial: process.env.SMTP_PORT,
1048
+ scope: "ENVIRONMENT"
1049
+ },
1050
+ {
1051
+ name: "smtpSecure",
1052
+ type: "select",
1053
+ message: "Is the SMTP connection made securely using TLS?",
1054
+ choices: [
1055
+ {
1056
+ title: "True",
1057
+ value: "true"
1058
+ },
1059
+ {
1060
+ title: "False",
1061
+ value: "false"
1062
+ }
1063
+ ],
1064
+ valueType: "SECRET",
1065
+ validate: notEmpty,
1066
+ valueLabel: "SMTP_SECURE",
1067
+ initial: process.env.SMTP_SECURE,
1068
+ scope: "ENVIRONMENT"
1069
+ },
1070
+ {
1071
+ name: "senderEmailAddress",
1072
+ type: "text",
1073
+ message: "What is your sender email address?",
1074
+ valueType: "SECRET",
1075
+ validate: notEmpty,
1076
+ valueLabel: "SENDER_EMAIL_ADDRESS",
1077
+ initial: process.env.SENDER_EMAIL_ADDRESS,
1078
+ scope: "ENVIRONMENT"
1079
+ },
1080
+ {
1081
+ name: "alertEmail",
1082
+ type: "text",
1083
+ message: "What is the email address to receive alert emails or a Slack channel email link?",
1084
+ valueType: "SECRET",
1085
+ validate: notEmpty,
1086
+ valueLabel: "ALERT_EMAIL",
1087
+ initial: process.env.ALERT_EMAIL,
1088
+ scope: "ENVIRONMENT"
1089
+ }
1090
+ ];
1091
+ sentryQuestions = [
1092
+ {
1093
+ name: "sentryDsn",
1094
+ type: "text",
1095
+ message: "What is your Sentry DSN?",
1096
+ valueType: "SECRET",
1097
+ validate: notEmpty,
1098
+ valueLabel: "SENTRY_DSN",
1099
+ initial: process.env.SENTRY_DSN,
1100
+ scope: "ENVIRONMENT"
1101
+ }
1102
+ ];
1103
+ metabaseAdminQuestions = [
1104
+ {
1105
+ valueType: "SECRET",
1106
+ name: "OPENCRVS_METABASE_ADMIN_EMAIL",
1107
+ type: "text",
1108
+ message: "Email for Metabase super admin. Used as a username when logging in to the dashboard",
1109
+ valueLabel: "OPENCRVS_METABASE_ADMIN_EMAIL",
1110
+ scope: "ENVIRONMENT",
1111
+ initial: "user@opencrvs.org"
1112
+ },
1113
+ {
1114
+ valueType: "SECRET",
1115
+ name: "OPENCRVS_METABASE_ADMIN_PASSWORD",
1116
+ type: "text",
1117
+ message: "Password for Metabase super admin.",
1118
+ valueLabel: "OPENCRVS_METABASE_ADMIN_PASSWORD",
1119
+ scope: "ENVIRONMENT",
1120
+ initial: generateLongPassword()
1121
+ }
1122
+ ];
1123
+ }
1124
+ });
1125
+
1126
+ // src/environment/editor-questions.ts
1127
+ function editorQuestion(question) {
1128
+ return import("@inquirer/prompts").then(
1129
+ ({ editor: editor2 }) => editor2({ message: question })
1130
+ );
1131
+ }
1132
+ async function askQuestionWithEditor(questions, existingValues) {
1133
+ let answers = [];
1134
+ for (const question of questions) {
1135
+ const questionWithVariableLabel = {
1136
+ ...question,
1137
+ message: `${import_kleur3.default.cyan(question.valueLabel || "")}: ${question.message}`
1138
+ };
1139
+ if (!questionWithVariableLabel.valueLabel) {
1140
+ throw Error("Undefined Label");
1141
+ }
1142
+ const existingSecret = findExistingValue(
1143
+ questionWithVariableLabel.valueLabel,
1144
+ "SECRET",
1145
+ questionWithVariableLabel.scope,
1146
+ existingValues
1147
+ );
1148
+ let updateSecret = true;
1149
+ if (existingSecret) {
1150
+ updateSecret = (await (0, import_prompts.default)([{
1151
+ name: "overWrite",
1152
+ type: "confirm",
1153
+ message: `${import_kleur3.default.yellow(
1154
+ `${existingSecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur3.default.cyan(
1155
+ existingSecret.name
1156
+ )} already exists in Github. Do you want to update it?`
1157
+ )}`
1158
+ }])).overWrite;
1159
+ }
1160
+ if (!existingSecret || updateSecret === true) {
1161
+ const question_answer = await editorQuestion(questionWithVariableLabel.message);
1162
+ const answer = {
1163
+ type: "SECRET",
1164
+ scope: "ENVIRONMENT",
1165
+ name: questionWithVariableLabel.valueLabel,
1166
+ value: question_answer,
1167
+ didExist: existingSecret
1168
+ };
1169
+ answers.push(answer);
1170
+ }
1171
+ }
1172
+ return answers;
1173
+ }
1174
+ var import_kleur3, import_prompts;
1175
+ var init_editor_questions = __esm({
1176
+ "src/environment/editor-questions.ts"() {
1177
+ "use strict";
1178
+ init_utils();
1179
+ import_kleur3 = __toESM(require("kleur"));
1180
+ import_prompts = __toESM(require("prompts"));
1181
+ }
1182
+ });
1183
+
1184
+ // src/environment/questions-helper.ts
1185
+ async function input(options) {
1186
+ const inquirer = await import("@inquirer/prompts");
1187
+ return inquirer.input(options);
1188
+ }
1189
+ async function select(options) {
1190
+ const inquirer = await import("@inquirer/prompts");
1191
+ return inquirer.select(options);
1192
+ }
1193
+ function getIndexFromChoices(choices, value) {
1194
+ let idx = 0;
1195
+ for (const choice of choices) {
1196
+ if (choice.value === value) {
1197
+ return idx;
1198
+ }
1199
+ idx++;
1200
+ }
1201
+ return 0;
1202
+ }
1203
+ async function selectWithCustom(config) {
1204
+ const {
1205
+ message,
1206
+ choices,
1207
+ initial = void 0,
1208
+ customLabel = "Other...",
1209
+ customInputMessage = "Enter custom value:"
1210
+ } = config;
1211
+ const CUSTOM = "__custom__";
1212
+ const selected = await select({
1213
+ message,
1214
+ choices: [
1215
+ ...choices,
1216
+ {
1217
+ value: CUSTOM,
1218
+ name: customLabel
1219
+ }
1220
+ ],
1221
+ default: initial
1222
+ });
1223
+ if (selected === CUSTOM) {
1224
+ const customValue = await input({
1225
+ message: customInputMessage,
1226
+ validate: (value) => value.trim().length > 0 ? true : "Value cannot be empty"
1227
+ });
1228
+ return customValue;
1229
+ }
1230
+ return selected;
1231
+ }
1232
+ var init_questions_helper = __esm({
1233
+ "src/environment/questions-helper.ts"() {
1234
+ "use strict";
1235
+ }
1236
+ });
1237
+
1238
+ // src/environment/manage-users.ts
1239
+ async function inquirerPrompt(name, options) {
1240
+ const inquirer = await import("@inquirer/prompts");
1241
+ return inquirer[name](options);
1242
+ }
1243
+ function updateInventoryFile(filePath, users) {
1244
+ const data = readYamlFile(filePath);
1245
+ if (!data?.all?.vars?.users) {
1246
+ throw Error(`'users' section not found within inventory file: ${filePath}`);
1247
+ }
1248
+ data.all.vars.users = users;
1249
+ writeYamlFile(filePath, data);
1250
+ }
1251
+ function parseInventoryFile(filePath) {
1252
+ try {
1253
+ const data = readYamlFile(filePath);
1254
+ return getUsers(data);
1255
+ } catch {
1256
+ return [];
1257
+ }
1258
+ }
1259
+ function getCurrentUsername() {
1260
+ return os.userInfo().username;
1261
+ }
1262
+ function getCurrentUserSSHKeys() {
1263
+ const homeDir = os.homedir();
1264
+ const sshDir = path25.join(homeDir, ".ssh");
1265
+ const keys = [];
1266
+ const keyFiles = [
1267
+ "id_rsa.pub",
1268
+ "id_ecdsa.pub",
1269
+ "id_ed25519.pub",
1270
+ "id_dsa.pub"
1271
+ ];
1272
+ for (const keyFile of keyFiles) {
1273
+ const keyPath = path25.join(sshDir, keyFile);
1274
+ try {
1275
+ if (fs7.existsSync(keyPath)) {
1276
+ const keyContent = fs7.readFileSync(keyPath, "utf8").trim();
1277
+ if (keyContent) {
1278
+ keys.push(keyContent);
1279
+ }
1280
+ }
1281
+ } catch (error4) {
1282
+ continue;
1283
+ }
1284
+ }
1285
+ return keys;
1286
+ }
1287
+ async function selectRole() {
1288
+ return await select2({
1289
+ message: "Select user role:",
1290
+ choices: [
1291
+ { name: "Admin (full access to OS and Kubernetes)", value: "admin" },
1292
+ { name: "Operator (read-only OS, full Kubernetes)", value: "operator" }
1293
+ ]
1294
+ });
1295
+ }
1296
+ async function selectState() {
1297
+ return await select2({
1298
+ message: "Select user state:",
1299
+ choices: [
1300
+ { name: "Present (user is allowed to login)", value: "present" },
1301
+ { name: "Absent (user account is disabled)", value: "absent" }
1302
+ ]
1303
+ });
1304
+ }
1305
+ async function askToAddCurrentUser(existingUsers) {
1306
+ const currentUsername = getCurrentUsername();
1307
+ const currentKeys = getCurrentUserSSHKeys();
1308
+ if (existingUsers.find((u) => u.name === currentUsername)) {
1309
+ info(`\u2139\uFE0F User "${currentUsername}" already exists in inventory.`);
1310
+ return null;
1311
+ }
1312
+ if (currentKeys.length === 0) {
1313
+ return null;
1314
+ }
1315
+ const addCurrentUser = await confirm({
1316
+ message: `Add current user "${currentUsername}" with ${currentKeys.length} SSH key(s)?`,
1317
+ default: true
1318
+ });
1319
+ if (!addCurrentUser) {
1320
+ return null;
1321
+ }
1322
+ const role = await selectRole();
1323
+ return {
1324
+ name: currentUsername,
1325
+ ssh_keys: currentKeys,
1326
+ state: "present",
1327
+ role
1328
+ };
1329
+ }
1330
+ async function addNewUser(existingUsers) {
1331
+ const name = await input2({
1332
+ message: "Enter username:",
1333
+ validate: (value) => {
1334
+ if (!value.trim()) {
1335
+ return "Username required";
1336
+ }
1337
+ if (existingUsers.find((u) => u.name === value.trim())) {
1338
+ return `User "${value}" already exists`;
1339
+ }
1340
+ if (!/^[a-z_][a-z0-9_-]*[$]?$/.test(value.trim())) {
1341
+ return "Invalid username format (use lowercase, numbers, underscore, hyphen)";
1342
+ }
1343
+ return true;
1344
+ }
1345
+ });
1346
+ const keysInput = await editor({
1347
+ message: "Paste SSH public key(s) (one per line):",
1348
+ default: ""
1349
+ });
1350
+ const ssh_keys = keysInput.split("\n").map((key) => key.trim()).filter((key) => key && !key.startsWith("#"));
1351
+ if (ssh_keys.length === 0) {
1352
+ warn("\u26A0\uFE0F Warning: No SSH keys provided. User will not be able to login remotely.");
1353
+ }
1354
+ const role = await selectRole();
1355
+ const state = "present";
1356
+ return {
1357
+ name: name.trim(),
1358
+ ssh_keys,
1359
+ state,
1360
+ role
1361
+ };
1362
+ }
1363
+ function displayUserSummary(users) {
1364
+ if (users.length === 0) {
1365
+ console.log("\n\u{1F4CB} No users configured.\n");
1366
+ return;
1367
+ }
1368
+ console.log("\n" + "=".repeat(70));
1369
+ console.log(`\u{1F4CB} User Configuration Summary - Total users: ${users.length}`);
1370
+ console.log("=".repeat(70));
1371
+ users.forEach((user, index) => {
1372
+ const stateIcon = user.state === "present" ? "\u2705" : "\u274C";
1373
+ const roleIcon = user.role === "admin" ? "\u{1F451}" : "\u{1F464}";
1374
+ console.log(
1375
+ `${index + 1}. ${stateIcon} ${roleIcon} ${user.name.padEnd(20)} Role: ${user.role.padEnd(10)} State: ${user.state.padEnd(10)} SSH Keys: ${user.ssh_keys.length}`
1376
+ );
1377
+ });
1378
+ console.log("=".repeat(70) + "\n");
1379
+ }
1380
+ async function editUser(user) {
1381
+ const updatedUser = { ...user };
1382
+ let continueEditing = true;
1383
+ const clearScreen = () => {
1384
+ process.stdout.write("\x1Bc");
1385
+ };
1386
+ const displayUserState = () => {
1387
+ clearScreen();
1388
+ console.log("\u2500".repeat(70));
1389
+ console.log(`\u{1F4DD} Editing user: ${updatedUser.name}`);
1390
+ console.log("\u2500".repeat(70));
1391
+ console.log(`Current Role: ${updatedUser.role === "admin" ? "\u{1F451} admin" : "\u{1F464} operator"}`);
1392
+ console.log(`Current State: ${updatedUser.state === "present" ? "\u2705 present" : "\u274C absent"}`);
1393
+ console.log(`Current SSH Keys: ${updatedUser.ssh_keys.length} key(s)`);
1394
+ if (updatedUser.ssh_keys.length > 0) {
1395
+ updatedUser.ssh_keys.forEach((key, idx) => {
1396
+ const keyPreview = key.length > 50 ? key.substring(0, 47) + "..." : key;
1397
+ console.log(` ${idx + 1}. ${keyPreview}`);
1398
+ });
1399
+ }
1400
+ console.log("\u2500".repeat(70));
1401
+ console.log("");
1402
+ };
1403
+ while (continueEditing) {
1404
+ displayUserState();
1405
+ const action = await select2({
1406
+ message: "What would you like to modify?",
1407
+ choices: [
1408
+ {
1409
+ name: `Change role (current: ${updatedUser.role})`,
1410
+ value: "role"
1411
+ },
1412
+ {
1413
+ name: `Change state (current: ${updatedUser.state})`,
1414
+ value: "state"
1415
+ },
1416
+ {
1417
+ name: `Update SSH keys (current: ${updatedUser.ssh_keys.length} key(s))`,
1418
+ value: "keys"
1419
+ },
1420
+ {
1421
+ name: "\u{1F4BE} Save changes and return",
1422
+ value: "save"
1423
+ },
1424
+ {
1425
+ name: "\u{1F6AB} Cancel and discard changes",
1426
+ value: "cancel"
1427
+ }
1428
+ ]
1429
+ });
1430
+ switch (action) {
1431
+ case "role":
1432
+ const newRole = await selectRole();
1433
+ if (newRole !== updatedUser.role) {
1434
+ updatedUser.role = newRole;
1435
+ }
1436
+ break;
1437
+ case "state":
1438
+ const newState = await selectState();
1439
+ if (newState !== updatedUser.state) {
1440
+ updatedUser.state = newState;
1441
+ }
1442
+ break;
1443
+ case "keys":
1444
+ const keysInput = await editor({
1445
+ message: "Update SSH public key(s) (one per line):",
1446
+ default: updatedUser.ssh_keys.join("\n")
1447
+ });
1448
+ const newKeys = keysInput.split("\n").map((key) => key.trim()).filter((key) => key && !key.startsWith("#"));
1449
+ if (newKeys.length === 0) {
1450
+ clearScreen();
1451
+ displayUserState();
1452
+ const confirmRemoveKeys = await confirm({
1453
+ message: "\u26A0\uFE0F Warning: All SSH keys will be removed. Continue with no SSH keys?",
1454
+ default: false
1455
+ });
1456
+ if (confirmRemoveKeys) {
1457
+ updatedUser.ssh_keys = [];
1458
+ }
1459
+ } else {
1460
+ updatedUser.ssh_keys = newKeys;
1461
+ }
1462
+ break;
1463
+ case "save":
1464
+ const hasChanges = updatedUser.role !== user.role || updatedUser.state !== user.state || JSON.stringify(updatedUser.ssh_keys) !== JSON.stringify(user.ssh_keys);
1465
+ clearScreen();
1466
+ if (hasChanges) {
1467
+ console.log("\n\u2705 Changes saved for user:", updatedUser.name, "\n");
1468
+ } else {
1469
+ console.log("\n\u2139\uFE0F No changes made\n");
1470
+ }
1471
+ continueEditing = false;
1472
+ break;
1473
+ case "cancel":
1474
+ clearScreen();
1475
+ const confirmCancel = await confirm({
1476
+ message: "Discard all changes?",
1477
+ default: false
1478
+ });
1479
+ if (confirmCancel) {
1480
+ console.log("\n\u{1F6AB} Changes discarded\n");
1481
+ return user;
1482
+ }
1483
+ break;
1484
+ }
1485
+ }
1486
+ return updatedUser;
1487
+ }
1488
+ async function manageUsers(inventoryPath) {
1489
+ let users = fs7.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1490
+ if (users.length > 0) {
1491
+ displayUserSummary(users);
1492
+ }
1493
+ let continueManaging = true;
1494
+ while (continueManaging) {
1495
+ const action = await select2({
1496
+ message: "What would you like to do?",
1497
+ choices: [
1498
+ { name: "\u2795 Add new user", value: "add" },
1499
+ { name: "\u270F\uFE0F Edit existing user", value: "edit" },
1500
+ { name: "\u{1F5D1}\uFE0F Remove user", value: "remove" },
1501
+ { name: "\u{1F464} Add current system user", value: "add-current" },
1502
+ { name: "\u{1F4CB} View all users", value: "view" },
1503
+ { name: "\u{1F4BE} Save and exit", value: "save" },
1504
+ { name: "\u{1F6AA} Exit without saving", value: "exit" }
1505
+ ]
1506
+ });
1507
+ switch (action) {
1508
+ case "add":
1509
+ const newUser = await addNewUser(users);
1510
+ if (newUser) {
1511
+ users.push(newUser);
1512
+ console.log(`\u2705 User "${newUser.name}" added.
1513
+ `);
1514
+ }
1515
+ break;
1516
+ case "add-current":
1517
+ const currentUser = await askToAddCurrentUser(users);
1518
+ if (currentUser) {
1519
+ users.push(currentUser);
1520
+ console.log(`\u2705 Current user "${currentUser.name}" added.
1521
+ `);
1522
+ }
1523
+ break;
1524
+ case "edit":
1525
+ if (users.length === 0) {
1526
+ console.log("\u26A0\uFE0F No users to edit.\n");
1527
+ break;
1528
+ }
1529
+ const userToEdit = await select2({
1530
+ message: "Select user to edit:",
1531
+ choices: users.map((u) => ({
1532
+ name: `${u.name} (${u.role}, ${u.state})`,
1533
+ value: u.name
1534
+ }))
1535
+ });
1536
+ const userIndex = users.findIndex((u) => u.name === userToEdit);
1537
+ if (userIndex !== -1) {
1538
+ users[userIndex] = await editUser(users[userIndex]);
1539
+ console.log(`\u2705 User "${userToEdit}" updated.
1540
+ `);
1541
+ }
1542
+ break;
1543
+ case "remove":
1544
+ if (users.length === 0) {
1545
+ console.log("\u26A0\uFE0F No users to remove.\n");
1546
+ break;
1547
+ }
1548
+ const usersToRemove = await checkbox({
1549
+ message: "Select user(s) to remove:",
1550
+ choices: users.map((u) => ({
1551
+ name: `${u.name} (${u.role}, ${u.state})`,
1552
+ value: u.name
1553
+ }))
1554
+ });
1555
+ if (usersToRemove.length > 0) {
1556
+ const confirmRemove = await confirm({
1557
+ message: `Remove ${usersToRemove.length} user(s)?`,
1558
+ default: false
1559
+ });
1560
+ if (confirmRemove) {
1561
+ users = users.filter((u) => !usersToRemove.includes(u.name));
1562
+ console.log(`\u2705 Removed ${usersToRemove.length} user(s).
1563
+ `);
1564
+ }
1565
+ }
1566
+ break;
1567
+ case "view":
1568
+ displayUserSummary(users);
1569
+ break;
1570
+ case "save":
1571
+ if (users.length === 0) {
1572
+ info("\n\u{1F4CB} No users configured.\n");
1573
+ continueManaging = false;
1574
+ break;
1575
+ }
1576
+ displayUserSummary(users);
1577
+ const confirmSave = await confirm({
1578
+ message: "Save changes end exit?",
1579
+ default: true
1580
+ });
1581
+ if (confirmSave && fs7.existsSync(inventoryPath)) {
1582
+ updateInventoryFile(inventoryPath, users);
1583
+ console.log(`
1584
+ \u2705 Changes saved to ${inventoryPath}
1585
+ `);
1586
+ }
1587
+ continueManaging = false;
1588
+ break;
1589
+ case "exit":
1590
+ if (users.length === 0) {
1591
+ info("\n\u{1F4CB} No users configured.\n");
1592
+ continueManaging = false;
1593
+ break;
1594
+ }
1595
+ const confirmExit = await confirm({
1596
+ message: "Exit without saving changes?",
1597
+ default: false
1598
+ });
1599
+ if (confirmExit) {
1600
+ console.log("\u{1F44B} Exited without saving.\n");
1601
+ continueManaging = false;
1602
+ }
1603
+ break;
1604
+ }
1605
+ }
1606
+ return users;
1607
+ }
1608
+ var os, fs7, path25, input2, select2, confirm, editor, checkbox;
1609
+ var init_manage_users = __esm({
1610
+ "src/environment/manage-users.ts"() {
1611
+ "use strict";
1612
+ os = __toESM(require("os"));
1613
+ fs7 = __toESM(require("fs"));
1614
+ path25 = __toESM(require("path"));
1615
+ init_logger();
1616
+ init_utils();
1617
+ init_templates();
1618
+ input2 = (options) => inquirerPrompt("input", options);
1619
+ select2 = (options) => inquirerPrompt("select", options);
1620
+ confirm = (options) => inquirerPrompt("confirm", options);
1621
+ editor = (options) => inquirerPrompt("editor", options);
1622
+ checkbox = (options) => inquirerPrompt("checkbox", options);
1623
+ }
1624
+ });
1625
+
1626
+ // src/environment/setup-environment.ts
1627
+ var setup_environment_exports = {};
1628
+ async function confirm2(options) {
1629
+ const inquirer = await import("@inquirer/prompts");
1630
+ return inquirer.confirm(options);
1631
+ }
1632
+ async function select3(options) {
1633
+ const inquirer = await import("@inquirer/prompts");
1634
+ return inquirer.select(options);
1635
+ }
1636
+ function questionToPrompt({
1637
+ // eslint-disable-next-line no-unused-vars
1638
+ valueType,
1639
+ // eslint-disable-next-line no-unused-vars
1640
+ valueLabel,
1641
+ // eslint-disable-next-line no-unused-vars
1642
+ scope,
1643
+ ...promptOptions
1644
+ }) {
1645
+ return promptOptions;
1646
+ }
1647
+ function getAnswers(existingValues) {
1648
+ return ALL_ANSWERS.flatMap((answerObject) => {
1649
+ const questionsThatAreSecretsOrVariables = Object.entries(
1650
+ answerObject
1651
+ ).filter(([key, value]) => {
1652
+ if (value === "") {
1653
+ return false;
1654
+ }
1655
+ const existingQuestion = ALL_QUESTIONS.find(
1656
+ (question) => question.name === key
1657
+ );
1658
+ const valueType = existingQuestion?.valueType;
1659
+ return valueType === "VARIABLE" || valueType === "SECRET";
1660
+ });
1661
+ return questionsThatAreSecretsOrVariables.map(([key, value]) => {
1662
+ const existingQuestion = ALL_QUESTIONS.find(
1663
+ (question) => question.name === key
1664
+ );
1665
+ const valueType = existingQuestion.valueType;
1666
+ if (valueType === "SECRET") {
1667
+ const existingSecret = findExistingValue(
1668
+ existingQuestion.valueLabel,
1669
+ "SECRET",
1670
+ existingQuestion?.scope,
1671
+ existingValues
1672
+ );
1673
+ return {
1674
+ type: valueType,
1675
+ name: existingQuestion?.valueLabel,
1676
+ value: value.toString(),
1677
+ didExist: existingSecret,
1678
+ scope: existingQuestion.scope
1679
+ };
1680
+ }
1681
+ const existingVariable = findExistingValue(
1682
+ existingQuestion?.valueLabel,
1683
+ valueType,
1684
+ existingQuestion?.scope,
1685
+ existingValues
1686
+ );
1687
+ return {
1688
+ type: valueType,
1689
+ name: existingQuestion?.valueLabel,
1690
+ didExist: findExistingValue(
1691
+ existingQuestion?.valueLabel,
1692
+ valueType,
1693
+ existingQuestion?.scope,
1694
+ existingValues
1695
+ ),
1696
+ value: value.toString() || existingVariable?.value || "",
1697
+ scope: existingQuestion.scope
1698
+ };
1699
+ });
1700
+ });
1701
+ }
1702
+ async function promptAndStoreAnswer(environment, questions, existingValues) {
1703
+ log("");
1704
+ const processedQuestions = questions.flatMap((question) => {
1705
+ const questionWithVariableLabel = {
1706
+ ...question,
1707
+ message: `${import_kleur4.default.cyan(question.valueLabel || "")}: ${question.message}`
1708
+ };
1709
+ if (!questionWithVariableLabel.valueLabel) {
1710
+ return questionWithVariableLabel;
1711
+ }
1712
+ if (questionWithVariableLabel.valueType === "VARIABLE") {
1713
+ const existingVariable = findExistingValue(
1714
+ questionWithVariableLabel.valueLabel,
1715
+ "VARIABLE",
1716
+ questionWithVariableLabel.scope,
1717
+ existingValues
1718
+ );
1719
+ if (existingVariable) {
1720
+ let initial_value = existingVariable.value;
1721
+ if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1722
+ initial_value = getIndexFromChoices(questionWithVariableLabel.choices, existingVariable.value);
1723
+ }
1724
+ return [
1725
+ {
1726
+ name: "overWrite" + questionWithVariableLabel.name,
1727
+ type: "confirm",
1728
+ scope: questionWithVariableLabel.scope,
1729
+ message: `${import_kleur4.default.yellow(
1730
+ `Variable ${import_kleur4.default.cyan(
1731
+ existingVariable.name
1732
+ )} already exists in Github. Do you want to update it?`
1733
+ )}`
1734
+ },
1735
+ {
1736
+ ...questionWithVariableLabel,
1737
+ type: (prev) => prev ? questionWithVariableLabel.type : null,
1738
+ initial: initial_value
1739
+ }
1740
+ ];
1741
+ }
1742
+ }
1743
+ if (questionWithVariableLabel.valueType === "SECRET") {
1744
+ const existingSecret = findExistingValue(
1745
+ questionWithVariableLabel.valueLabel,
1746
+ "SECRET",
1747
+ questionWithVariableLabel.scope,
1748
+ existingValues
1749
+ );
1750
+ if (existingSecret) {
1751
+ return [
1752
+ {
1753
+ name: "overWrite" + questionWithVariableLabel.name,
1754
+ type: "confirm",
1755
+ scope: questionWithVariableLabel.scope,
1756
+ message: `${import_kleur4.default.yellow(
1757
+ `${existingSecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur4.default.cyan(
1758
+ existingSecret.name
1759
+ )} already exists in Github. Do you want to update it?`
1760
+ )}`
1761
+ },
1762
+ {
1763
+ ...questionWithVariableLabel,
1764
+ type: (prev) => prev ? questionWithVariableLabel.type : null
1765
+ }
1766
+ ];
1767
+ }
1768
+ }
1769
+ return questionWithVariableLabel;
1770
+ });
1771
+ const promptQuestions = processedQuestions.map(questionToPrompt);
1772
+ const result = await (0, import_prompts2.default)(promptQuestions, {
1773
+ onCancel: () => {
1774
+ process.exit(1);
1775
+ }
1776
+ });
1777
+ ALL_ANSWERS.push(result);
1778
+ storeSecrets(environment, getAnswers(existingValues));
1779
+ const existingValuesForQuestions = questions.filter((question) => question.valueType === "VARIABLE").map((question) => [
1780
+ question.name,
1781
+ findExistingValue(
1782
+ question.valueLabel,
1783
+ "VARIABLE",
1784
+ question.scope,
1785
+ existingValues
1786
+ )?.value
1787
+ ]);
1788
+ return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1789
+ }
1790
+ var import_core, import_dotenv2, import_kleur4, import_prompts2, ALL_QUESTIONS, ALL_ANSWERS;
1791
+ var init_setup_environment = __esm({
1792
+ "src/environment/setup-environment.ts"() {
1793
+ "use strict";
1794
+ import_core = require("@octokit/core");
1795
+ import_dotenv2 = __toESM(require("dotenv"));
1796
+ import_kleur4 = __toESM(require("kleur"));
1797
+ import_prompts2 = __toESM(require("prompts"));
1798
+ init_github();
1799
+ init_derived_variables();
1800
+ init_utils();
1801
+ init_logger();
1802
+ init_templates();
1803
+ init_ssh_keygen();
1804
+ init_questions();
1805
+ init_editor_questions();
1806
+ init_questions_helper();
1807
+ init_manage_users();
1808
+ ALL_QUESTIONS = [];
1809
+ ALL_ANSWERS = [];
1810
+ ALL_QUESTIONS.push(
1811
+ ...githubTokenQuestion,
1812
+ ...githubOtherQuestions,
1813
+ ...dockerhubQuestions,
1814
+ ...diskQuestions,
1815
+ ...infrastructureQuestions,
1816
+ ...backupQuestions,
1817
+ ...countryQuestions,
1818
+ ...databaseAndMonitoringQuestions,
1819
+ ...emailQuestions,
1820
+ ...sentryQuestions,
1821
+ ...derivedVariables,
1822
+ ...metabaseAdminQuestions
1823
+ );
1824
+ (async () => {
1825
+ log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1826
+ const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
1827
+ githubQuestions.map(questionToPrompt),
1828
+ {
1829
+ onCancel: () => {
1830
+ process.exit(1);
1831
+ }
1832
+ }
1833
+ );
1834
+ const { githubToken } = await promptAndStoreAnswer(
1835
+ "",
1836
+ githubTokenQuestion,
1837
+ []
1838
+ );
1839
+ const octokit = new import_core.Octokit({
1840
+ auth: githubToken
1841
+ });
1842
+ log(import_kleur4.default.green("\nSuccessfully logged in to Github\n"));
1843
+ let existingEnvironments = await getRepositoryEnvironments(octokit, githubOrganisation, githubRepository);
1844
+ let defaultChoices = [
1845
+ { name: "Development", value: "development" },
1846
+ { name: "Quality assurance (no PII data)", value: "qa" },
1847
+ {
1848
+ name: "Staging (hosts PII data, no backups)",
1849
+ value: "staging"
1850
+ },
1851
+ {
1852
+ name: "Production (hosts PII data, requires frequent backups)",
1853
+ value: "production"
1854
+ }
1855
+ ];
1856
+ const choices = [
1857
+ ...defaultChoices,
1858
+ ...existingEnvironments.filter(
1859
+ (env) => !defaultChoices.some((choice) => choice.value === env)
1860
+ ).map((env) => ({
1861
+ name: env,
1862
+ value: env
1863
+ }))
1864
+ ];
1865
+ const environment = await selectWithCustom(
1866
+ {
1867
+ message: "Choose a name and purpose for the environment?",
1868
+ choices
1869
+ }
1870
+ );
1871
+ let environment_type = "non-production";
1872
+ if (["development", "qa"].includes(environment)) {
1873
+ environment_type = "non-production";
1874
+ } else if (["staging", "production"].includes(environment)) {
1875
+ environment_type = "production";
1876
+ } else {
1877
+ environment_type = await select3(
1878
+ {
1879
+ message: "Purpose for the environment?",
1880
+ choices: [
1881
+ { name: "Development/Quality assurance/Testing (no PII data)", value: "non-production" },
1882
+ { name: "Staging/Production (hosts PII data, requires frequent backups)", value: "production" }
1883
+ ]
1884
+ }
1885
+ );
1886
+ }
1887
+ const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
1888
+ if (!environment) {
1889
+ process.exit(1);
1890
+ }
1891
+ import_dotenv2.default.config({
1892
+ path: `${process.cwd()}/.env.${environment}`
1893
+ });
1894
+ await createEnvironment(
1895
+ octokit,
1896
+ environment,
1897
+ githubOrganisation,
1898
+ githubRepository
1899
+ );
1900
+ const repositoryId = await getRepositoryId(
1901
+ octokit,
1902
+ githubOrganisation,
1903
+ githubRepository
1904
+ );
1905
+ const existingRepositorySecrets = await listRepositorySecrets(
1906
+ octokit,
1907
+ githubOrganisation,
1908
+ githubRepository
1909
+ );
1910
+ const existingRepositoryVariables = await listRepositoryVariables(
1911
+ octokit,
1912
+ githubOrganisation,
1913
+ githubRepository
1914
+ );
1915
+ const existingEnvironmentVariables = await listEnvironmentVariables(
1916
+ octokit,
1917
+ repositoryId,
1918
+ environment
1919
+ );
1920
+ const existingEnvironmentSecrets = await listEnvironmentSecrets(
1921
+ octokit,
1922
+ githubOrganisation,
1923
+ repositoryId,
1924
+ environment
1925
+ );
1926
+ const existingValues = [
1927
+ ...existingEnvironmentVariables,
1928
+ ...existingRepositoryVariables,
1929
+ ...existingRepositorySecrets,
1930
+ ...existingEnvironmentSecrets
1931
+ ];
1932
+ if (existingEnvironmentVariables.length > 0 || existingEnvironmentSecrets.length > 0) {
1933
+ log(
1934
+ "\nEnvironment with the name",
1935
+ environment,
1936
+ "already exists in Github.",
1937
+ "\nFound",
1938
+ existingEnvironmentVariables.length,
1939
+ "existing variables and",
1940
+ existingEnvironmentSecrets.length,
1941
+ "secrets"
1942
+ );
1943
+ }
1944
+ if (environment_type === "production") {
1945
+ log("\n", import_kleur4.default.yellow().bold(
1946
+ "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
1947
+ ));
1948
+ await promptAndStoreAnswer(environment, githubOtherQuestions, existingValues);
1949
+ }
1950
+ log("\n", import_kleur4.default.bold().underline("Docker Hub"));
1951
+ await promptAndStoreAnswer(environment, dockerhubQuestions, existingValues);
1952
+ log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
1953
+ const infrastructure = await promptAndStoreAnswer(
1954
+ environment,
1955
+ infrastructureQuestions,
1956
+ existingValues
1957
+ );
1958
+ const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1959
+ log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1960
+ const users = await manageUsers(`infrastructure/server-setup/inventory/${environment}.yml`);
1961
+ log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1962
+ const sslCertExists = findExistingValue(
1963
+ "SSL_CRT",
1964
+ "SECRET",
1965
+ "ENVIRONMENT",
1966
+ existingValues
1967
+ );
1968
+ let ssl_answers = [];
1969
+ const traefikConfOption = (await (0, import_prompts2.default)(
1970
+ [
1971
+ {
1972
+ name: "traefikConfOption",
1973
+ type: "select",
1974
+ message: "Choose option to configure Traefik SSL Certificate",
1975
+ choices: [
1976
+ { title: "Let's Encrypt certificate", value: "lets_encrypt" },
1977
+ { title: "Static SSL certificate", value: "static_ssl" },
1978
+ { title: "Custom configuration", value: "custom" }
1979
+ ],
1980
+ initial: sslCertExists ? 1 : 0
1981
+ }
1982
+ ]
1983
+ )).traefikConfOption;
1984
+ if (traefikConfOption === "static_ssl") {
1985
+ ssl_answers = await askQuestionWithEditor(staticSSLCertQuestions, existingEnvironmentSecrets);
1986
+ }
1987
+ log("\n", import_kleur4.default.bold().underline("Storage"), "\n");
1988
+ let enableEncryption = false;
1989
+ const encryption_key_defined = findExistingValue(
1990
+ "ENCRYPTION_KEY",
1991
+ "SECRET",
1992
+ "ENVIRONMENT",
1993
+ existingValues
1994
+ );
1995
+ if (!encryption_key_defined && !environment_exists) {
1996
+ const answers_enable_encryption = await (0, import_prompts2.default)(
1997
+ [
1998
+ {
1999
+ name: "enableEncryption",
2000
+ type: "confirm",
2001
+ message: "Do you want to enable disk encryption?",
2002
+ scope: "ENVIRONMENT",
2003
+ initial: Boolean(process.env.ENABLE_ENCRYPTION)
2004
+ }
2005
+ ].map(questionToPrompt)
2006
+ );
2007
+ enableEncryption = answers_enable_encryption.enableEncryption;
2008
+ }
2009
+ if (enableEncryption && !encryption_key_defined && !environment_exists) {
2010
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow(" Disk encryption is enabled"));
2011
+ await promptAndStoreAnswer(environment, diskQuestions, existingValues);
2012
+ } else {
2013
+ if (!enableEncryption && !encryption_key_defined && environment_exists) {
2014
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().grey(`Environment ${environment} is already configured, skipping disk encryption question`));
2015
+ }
2016
+ const DISK_SPACE = findExistingValue(
2017
+ "DISK_SPACE",
2018
+ "VARIABLE",
2019
+ "ENVIRONMENT",
2020
+ existingValues
2021
+ );
2022
+ if (!DISK_SPACE) {
2023
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().grey("All available disk space at /data will be used"));
2024
+ } else {
2025
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Variable DISK_SPACE is read-only, allocated space:"), DISK_SPACE?.value);
2026
+ }
2027
+ }
2028
+ let backupHost = findExistingValue(
2029
+ "BACKUP_HOST",
2030
+ "VARIABLE",
2031
+ "ENVIRONMENT",
2032
+ existingValues
2033
+ )?.value || "";
2034
+ let backupType = "";
2035
+ let restoreEnvironmentName = findExistingValue(
2036
+ "RESTORE_ENVIRONMENT_NAME",
2037
+ "VARIABLE",
2038
+ "ENVIRONMENT",
2039
+ existingValues
2040
+ )?.value;
2041
+ let restoreType = findExistingValue(
2042
+ "RESTORE_ENVIRONMENT_MODE",
2043
+ "VARIABLE",
2044
+ "ENVIRONMENT",
2045
+ existingValues
2046
+ )?.value || process.env.RESTORE_ENVIRONMENT_MODE || "dump";
2047
+ log("\n", import_kleur4.default.bold().underline("Backup"));
2048
+ let configureBackup = backupHost ? true : false;
2049
+ if (!configureBackup && !restoreEnvironmentName) {
2050
+ configureBackup = await confirm2({
2051
+ message: "Do you want to configure backup?",
2052
+ default: Boolean(process.env.CONFIGURE_BACKUP)
2053
+ });
2054
+ }
2055
+ let backupHostPrivateKey = "";
2056
+ let backupHostPublicKey = "";
2057
+ if (configureBackup) {
2058
+ const backupAnswers = await promptAndStoreAnswer(
2059
+ environment,
2060
+ backupQuestions,
2061
+ existingValues
2062
+ );
2063
+ let backupHostPrivateKeyExists = findExistingValue(
2064
+ "BACKUP_HOST_PRIVATE_KEY",
2065
+ "SECRET",
2066
+ "ENVIRONMENT",
2067
+ existingValues
2068
+ );
2069
+ backupType = backupAnswers.backupType;
2070
+ backupHost = backupAnswers.backupHost || backupHost;
2071
+ if (!backupHostPrivateKeyExists) {
2072
+ const { publicKey, privateKey } = generateSSHKeyPair();
2073
+ backupHostPublicKey = publicKey;
2074
+ backupHostPrivateKey = privateKey;
2075
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow(`Generated new SSH key pair for backup host: ${backupHost}`));
2076
+ }
2077
+ } else {
2078
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Backup is disabled"));
2079
+ }
2080
+ log("\n", import_kleur4.default.bold().underline("Restore"));
2081
+ let configureRestore = restoreEnvironmentName ? true : false;
2082
+ if (!restoreEnvironmentName && !configureBackup) {
2083
+ configureRestore = await confirm2({
2084
+ message: "Do you want to configure restore?",
2085
+ default: Boolean(process.env.CONFIGURE_RESTORE)
2086
+ });
2087
+ }
2088
+ if (configureRestore) {
2089
+ const env_list_filtered = existingEnvironments.filter((env) => env !== environment);
2090
+ restoreEnvironmentName = await selectWithCustom(
2091
+ {
2092
+ message: "What is the name of your environment to restore?",
2093
+ choices: env_list_filtered.map((env) => ({
2094
+ name: env,
2095
+ value: env
2096
+ })),
2097
+ initial: restoreEnvironmentName
2098
+ }
2099
+ );
2100
+ restoreType = await select3(
2101
+ {
2102
+ message: `Select ${import_kleur4.default.yellow().bold(restoreEnvironmentName)} environment backup mode`,
2103
+ choices: [
2104
+ {
2105
+ name: "Full dump (daily full database backup)",
2106
+ value: "dump"
2107
+ },
2108
+ {
2109
+ name: "Differential (weekly full, daily diff backup)",
2110
+ value: "differential"
2111
+ }
2112
+ ]
2113
+ }
2114
+ );
2115
+ } else {
2116
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2117
+ }
2118
+ log("\n", import_kleur4.default.bold().underline("Monitoring"));
2119
+ await promptAndStoreAnswer(
2120
+ environment,
2121
+ databaseAndMonitoringQuestions,
2122
+ existingValues
2123
+ );
2124
+ const sentryDSNExists = findExistingValue(
2125
+ "SENTRY_DSN",
2126
+ "SECRET",
2127
+ "ENVIRONMENT",
2128
+ existingValues
2129
+ );
2130
+ log("\n", import_kleur4.default.bold().underline("Sentry"));
2131
+ if (sentryDSNExists) {
2132
+ await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2133
+ } else {
2134
+ const { useSentry } = await (0, import_prompts2.default)(
2135
+ [
2136
+ {
2137
+ name: "useSentry",
2138
+ type: "confirm",
2139
+ message: "Do you want to use Sentry?",
2140
+ initial: Boolean(process.env.SENTRY_DNS)
2141
+ }
2142
+ ]
2143
+ );
2144
+ if (useSentry) {
2145
+ await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2146
+ }
2147
+ }
2148
+ log("\n", import_kleur4.default.bold().underline("METABASE ADMIN"));
2149
+ await promptAndStoreAnswer(
2150
+ environment,
2151
+ metabaseAdminQuestions,
2152
+ existingValues
2153
+ );
2154
+ log("\n", import_kleur4.default.bold().underline("SMTP"));
2155
+ await promptAndStoreAnswer(environment, emailQuestions, existingValues);
2156
+ const allAnswers = ALL_ANSWERS.reduce((acc, answer) => {
2157
+ return { ...acc, ...answer };
2158
+ });
2159
+ const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2160
+ function findExistingOrDefine(name, type, scope, newValue) {
2161
+ return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2162
+ }
2163
+ const derivedUpdates = [
2164
+ {
2165
+ name: "GH_ENCRYPTION_PASSWORD",
2166
+ type: "SECRET",
2167
+ didExist: findExistingValue(
2168
+ "GH_ENCRYPTION_PASSWORD",
2169
+ "SECRET",
2170
+ "REPOSITORY",
2171
+ existingValues
2172
+ ),
2173
+ value: findExistingOrDefine(
2174
+ "GH_ENCRYPTION_PASSWORD",
2175
+ "SECRET",
2176
+ "REPOSITORY",
2177
+ generateLongPassword()
2178
+ ),
2179
+ scope: "REPOSITORY"
2180
+ }
2181
+ ];
2182
+ derivedUpdates.push({
2183
+ name: "NOTIFICATION_TRANSPORT",
2184
+ type: "VARIABLE",
2185
+ didExist: findExistingValue(
2186
+ "NOTIFICATION_TRANSPORT",
2187
+ "VARIABLE",
2188
+ "ENVIRONMENT",
2189
+ existingValues
2190
+ ),
2191
+ value: findExistingOrDefine(
2192
+ "NOTIFICATION_TRANSPORT",
2193
+ "VARIABLE",
2194
+ "ENVIRONMENT",
2195
+ "email"
2196
+ ),
2197
+ scope: "ENVIRONMENT"
2198
+ });
2199
+ derivedUpdates.push(...ssl_answers);
2200
+ if (configureBackup) {
2201
+ derivedUpdates.push({
2202
+ name: "BACKUP_ENCRYPTION_PASSPHRASE",
2203
+ type: "SECRET",
2204
+ didExist: findExistingValue(
2205
+ "BACKUP_ENCRYPTION_PASSPHRASE",
2206
+ "SECRET",
2207
+ "ENVIRONMENT",
2208
+ existingValues
2209
+ ),
2210
+ value: findExistingOrDefine(
2211
+ "BACKUP_ENCRYPTION_PASSPHRASE",
2212
+ "SECRET",
2213
+ "ENVIRONMENT",
2214
+ generateLongPassword()
2215
+ ),
2216
+ scope: "ENVIRONMENT"
2217
+ });
2218
+ }
2219
+ const applicationServerUpdates = [
2220
+ {
2221
+ name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
2222
+ type: "SECRET",
2223
+ didExist: findExistingValue(
2224
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2225
+ "SECRET",
2226
+ "ENVIRONMENT",
2227
+ existingValues
2228
+ ),
2229
+ value: findExistingOrDefine(
2230
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2231
+ "SECRET",
2232
+ "ENVIRONMENT",
2233
+ generateLongPassword()
2234
+ ),
2235
+ scope: "ENVIRONMENT"
2236
+ },
2237
+ {
2238
+ name: "KIBANA_SYSTEM_PASSWORD",
2239
+ type: "SECRET",
2240
+ didExist: findExistingValue(
2241
+ "KIBANA_SYSTEM_PASSWORD",
2242
+ "SECRET",
2243
+ "ENVIRONMENT",
2244
+ existingValues
2245
+ ),
2246
+ value: findExistingOrDefine(
2247
+ "KIBANA_SYSTEM_PASSWORD",
2248
+ "SECRET",
2249
+ "ENVIRONMENT",
2250
+ generateLongPassword()
2251
+ ),
2252
+ scope: "ENVIRONMENT"
2253
+ },
2254
+ {
2255
+ name: "MINIO_ROOT_USER",
2256
+ type: "SECRET",
2257
+ didExist: findExistingValue(
2258
+ "MINIO_ROOT_USER",
2259
+ "SECRET",
2260
+ "ENVIRONMENT",
2261
+ existingValues
2262
+ ),
2263
+ value: findExistingOrDefine(
2264
+ "MINIO_ROOT_USER",
2265
+ "SECRET",
2266
+ "ENVIRONMENT",
2267
+ generateLongPassword()
2268
+ ),
2269
+ scope: "ENVIRONMENT"
2270
+ },
2271
+ {
2272
+ name: "MINIO_ROOT_PASSWORD",
2273
+ type: "SECRET",
2274
+ didExist: findExistingValue(
2275
+ "MINIO_ROOT_PASSWORD",
2276
+ "SECRET",
2277
+ "ENVIRONMENT",
2278
+ existingValues
2279
+ ),
2280
+ value: findExistingOrDefine(
2281
+ "MINIO_ROOT_PASSWORD",
2282
+ "SECRET",
2283
+ "ENVIRONMENT",
2284
+ generateLongPassword()
2285
+ ),
2286
+ scope: "ENVIRONMENT"
2287
+ },
2288
+ {
2289
+ name: "MONGODB_ADMIN_USER",
2290
+ type: "SECRET",
2291
+ didExist: findExistingValue(
2292
+ "MONGODB_ADMIN_USER",
2293
+ "SECRET",
2294
+ "ENVIRONMENT",
2295
+ existingValues
2296
+ ),
2297
+ value: findExistingOrDefine(
2298
+ "MONGODB_ADMIN_USER",
2299
+ "SECRET",
2300
+ "ENVIRONMENT",
2301
+ generateLongPassword()
2302
+ ),
2303
+ scope: "ENVIRONMENT"
2304
+ },
2305
+ {
2306
+ name: "MONGODB_ADMIN_PASSWORD",
2307
+ type: "SECRET",
2308
+ didExist: findExistingValue(
2309
+ "MONGODB_ADMIN_PASSWORD",
2310
+ "SECRET",
2311
+ "ENVIRONMENT",
2312
+ existingValues
2313
+ ),
2314
+ value: findExistingOrDefine(
2315
+ "MONGODB_ADMIN_PASSWORD",
2316
+ "SECRET",
2317
+ "ENVIRONMENT",
2318
+ generateLongPassword()
2319
+ ),
2320
+ scope: "ENVIRONMENT"
2321
+ },
2322
+ {
2323
+ name: "POSTGRES_USER",
2324
+ type: "SECRET",
2325
+ didExist: findExistingValue(
2326
+ "POSTGRES_USER",
2327
+ "SECRET",
2328
+ "ENVIRONMENT",
2329
+ existingValues
2330
+ ),
2331
+ value: findExistingOrDefine(
2332
+ "POSTGRES_USER",
2333
+ "SECRET",
2334
+ "ENVIRONMENT",
2335
+ generateLongPassword()
2336
+ ),
2337
+ scope: "ENVIRONMENT"
2338
+ },
2339
+ {
2340
+ name: "POSTGRES_PASSWORD",
2341
+ type: "SECRET",
2342
+ didExist: findExistingValue(
2343
+ "POSTGRES_PASSWORD",
2344
+ "SECRET",
2345
+ "ENVIRONMENT",
2346
+ existingValues
2347
+ ),
2348
+ value: findExistingOrDefine(
2349
+ "POSTGRES_PASSWORD",
2350
+ "SECRET",
2351
+ "ENVIRONMENT",
2352
+ generateLongPassword()
2353
+ ),
2354
+ scope: "ENVIRONMENT"
2355
+ },
2356
+ {
2357
+ name: "SUPER_USER_PASSWORD",
2358
+ type: "SECRET",
2359
+ didExist: findExistingValue(
2360
+ "SUPER_USER_PASSWORD",
2361
+ "SECRET",
2362
+ "ENVIRONMENT",
2363
+ existingValues
2364
+ ),
2365
+ value: findExistingOrDefine(
2366
+ "SUPER_USER_PASSWORD",
2367
+ "SECRET",
2368
+ "ENVIRONMENT",
2369
+ generateLongPassword()
2370
+ ),
2371
+ scope: "ENVIRONMENT"
2372
+ },
2373
+ {
2374
+ type: "VARIABLE",
2375
+ name: "ACTIVATE_USERS",
2376
+ value: "production" === environment_type ? "false" : "true",
2377
+ didExist: findExistingValue(
2378
+ "ACTIVATE_USERS",
2379
+ "VARIABLE",
2380
+ "ENVIRONMENT",
2381
+ existingValues
2382
+ ),
2383
+ scope: "ENVIRONMENT"
2384
+ },
2385
+ {
2386
+ type: "VARIABLE",
2387
+ name: "COUNTRY_CONFIG_HOST",
2388
+ value: answerOrExisting(
2389
+ allAnswers.domain,
2390
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2391
+ (val) => `https://countryconfig.${val}`
2392
+ ),
2393
+ didExist: findExistingValue(
2394
+ "COUNTRY_CONFIG_HOST",
2395
+ "VARIABLE",
2396
+ "ENVIRONMENT",
2397
+ existingValues
2398
+ ),
2399
+ scope: "ENVIRONMENT"
2400
+ },
2401
+ {
2402
+ type: "VARIABLE",
2403
+ name: "GATEWAY_HOST",
2404
+ value: answerOrExisting(
2405
+ allAnswers.domain,
2406
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2407
+ (val) => `https://gateway.${val}`
2408
+ ),
2409
+ didExist: findExistingValue(
2410
+ "GATEWAY_HOST",
2411
+ "VARIABLE",
2412
+ "ENVIRONMENT",
2413
+ existingValues
2414
+ ),
2415
+ scope: "ENVIRONMENT"
2416
+ },
2417
+ {
2418
+ type: "VARIABLE",
2419
+ name: "CONTENT_SECURITY_POLICY_WILDCARD",
2420
+ value: answerOrExisting(
2421
+ allAnswers.domain,
2422
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2423
+ (val) => `*.${val}`
2424
+ ),
2425
+ didExist: findExistingValue(
2426
+ "CONTENT_SECURITY_POLICY_WILDCARD",
2427
+ "VARIABLE",
2428
+ "ENVIRONMENT",
2429
+ existingValues
2430
+ ),
2431
+ scope: "ENVIRONMENT"
2432
+ },
2433
+ {
2434
+ type: "VARIABLE",
2435
+ name: "CLIENT_APP_URL",
2436
+ value: answerOrExisting(
2437
+ allAnswers.domain,
2438
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2439
+ (val) => `https://register.${val}`
2440
+ ),
2441
+ didExist: findExistingValue(
2442
+ "CLIENT_APP_URL",
2443
+ "VARIABLE",
2444
+ "ENVIRONMENT",
2445
+ existingValues
2446
+ ),
2447
+ scope: "ENVIRONMENT"
2448
+ },
2449
+ {
2450
+ type: "VARIABLE",
2451
+ name: "LOGIN_URL",
2452
+ value: answerOrExisting(
2453
+ allAnswers.domain,
2454
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2455
+ (val) => `https://login.${val}`
2456
+ ),
2457
+ didExist: findExistingValue(
2458
+ "LOGIN_URL",
2459
+ "VARIABLE",
2460
+ "ENVIRONMENT",
2461
+ existingValues
2462
+ ),
2463
+ scope: "ENVIRONMENT"
2464
+ },
2465
+ {
2466
+ type: "VARIABLE",
2467
+ name: "RESTORE_ENVIRONMENT_NAME",
2468
+ value: answerOrExisting(restoreEnvironmentName, findExistingValue(
2469
+ "RESTORE_ENVIRONMENT_NAME",
2470
+ "VARIABLE",
2471
+ "ENVIRONMENT",
2472
+ existingValues
2473
+ ), (val) => val || ""),
2474
+ didExist: findExistingValue(
2475
+ "RESTORE_ENVIRONMENT_NAME",
2476
+ "VARIABLE",
2477
+ "ENVIRONMENT",
2478
+ existingValues
2479
+ ),
2480
+ scope: "ENVIRONMENT"
2481
+ }
2482
+ ];
2483
+ if (enableEncryption) {
2484
+ applicationServerUpdates.push({
2485
+ name: "ENCRYPTION_KEY",
2486
+ type: "SECRET",
2487
+ didExist: findExistingValue(
2488
+ "ENCRYPTION_KEY",
2489
+ "SECRET",
2490
+ "ENVIRONMENT",
2491
+ existingValues
2492
+ ),
2493
+ value: findExistingOrDefine(
2494
+ "ENCRYPTION_KEY",
2495
+ "SECRET",
2496
+ "ENVIRONMENT",
2497
+ generateLongPassword()
2498
+ ),
2499
+ scope: "ENVIRONMENT"
2500
+ });
2501
+ }
2502
+ if (configureBackup && backupHostPrivateKey && backupHostPublicKey) {
2503
+ applicationServerUpdates.push({
2504
+ name: "BACKUP_HOST_PRIVATE_KEY",
2505
+ type: "SECRET",
2506
+ didExist: void 0,
2507
+ value: backupHostPrivateKey,
2508
+ scope: "ENVIRONMENT"
2509
+ });
2510
+ applicationServerUpdates.push({
2511
+ name: "BACKUP_HOST_PUBLIC_KEY",
2512
+ type: "SECRET",
2513
+ didExist: void 0,
2514
+ value: backupHostPublicKey,
2515
+ scope: "ENVIRONMENT"
2516
+ });
2517
+ }
2518
+ derivedUpdates.push(...applicationServerUpdates);
2519
+ const updates = getAnswers(existingValues).concat(
2520
+ ...derivedUpdates.filter(
2521
+ (update) => update.value !== null
2522
+ )
2523
+ ).filter(
2524
+ (variable) => Boolean(variable.value) && // Only update values that changed
2525
+ (variable.type !== "VARIABLE" || variable.value !== variable.didExist?.value)
2526
+ );
2527
+ storeSecrets(environment, updates);
2528
+ const newSecrets = updates.filter(
2529
+ (update) => update.type === "SECRET" && !update.didExist
2530
+ );
2531
+ const updatedSecrets = updates.filter(
2532
+ (update) => update.type === "SECRET" && Boolean(update.didExist)
2533
+ );
2534
+ const newVariables = updates.filter(
2535
+ (update) => update.type === "VARIABLE" && !update.didExist
2536
+ );
2537
+ const updatedVariables = updates.filter(
2538
+ (update) => update.type === "VARIABLE" && Boolean(update.didExist)
2539
+ );
2540
+ const unknownVariables = existingValues.filter((value) => {
2541
+ return !ALL_QUESTIONS.find(
2542
+ (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2543
+ );
2544
+ });
2545
+ log("");
2546
+ if (newSecrets.length > 0) {
2547
+ log(
2548
+ import_kleur4.default.yellow(
2549
+ `The following secrets will be added to Github for environment ${environment}:`
2550
+ )
2551
+ );
2552
+ newSecrets.filter(({ scope }) => scope === "ENVIRONMENT").forEach((secret) => {
2553
+ log(secret.name, "=", secret.value);
2554
+ });
2555
+ log("");
2556
+ log(
2557
+ import_kleur4.default.yellow(`The following secrets will be added to Github repository:`)
2558
+ );
2559
+ newSecrets.filter(({ scope }) => scope === "REPOSITORY").forEach((secret) => {
2560
+ log(secret.name, "=", secret.value);
2561
+ });
2562
+ log("");
2563
+ }
2564
+ if (updatedSecrets.length > 0) {
2565
+ log(
2566
+ import_kleur4.default.yellow(
2567
+ `The following secrets will be updated in Github for environment ${environment}:`
2568
+ )
2569
+ );
2570
+ updatedSecrets.forEach((secret) => {
2571
+ log(secret.name, "=", secret.value);
2572
+ });
2573
+ log("");
2574
+ }
2575
+ if (newVariables.length > 0) {
2576
+ log(
2577
+ import_kleur4.default.yellow(
2578
+ `The following variables will be added to Github for environment ${environment}:`
2579
+ )
2580
+ );
2581
+ newVariables.forEach((variable) => {
2582
+ log(variable.name, "=", variable.value);
2583
+ });
2584
+ log("");
2585
+ }
2586
+ if (updatedVariables.length > 0) {
2587
+ log(
2588
+ import_kleur4.default.yellow(
2589
+ `The following variables will be updated in Github for environment ${environment}:`
2590
+ )
2591
+ );
2592
+ updatedVariables.forEach((variable) => {
2593
+ log(
2594
+ variable.name,
2595
+ "=",
2596
+ variable.value,
2597
+ `(was ${variable.didExist?.value})`
2598
+ );
2599
+ });
2600
+ log("");
2601
+ }
2602
+ if (unknownVariables.length > 0) {
2603
+ log(
2604
+ import_kleur4.default.yellow(
2605
+ `The following unknown variables/secrets were stored in Github are not managed by this script:`
2606
+ )
2607
+ );
2608
+ log("");
2609
+ log(import_kleur4.default.blue(`Repository:`));
2610
+ unknownVariables.filter(({ scope }) => scope === "REPOSITORY").forEach((variable) => {
2611
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2612
+ });
2613
+ log("");
2614
+ log(import_kleur4.default.blue(`Environment:`));
2615
+ unknownVariables.filter(({ scope }) => scope === "ENVIRONMENT").forEach((variable) => {
2616
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2617
+ });
2618
+ log("");
2619
+ log(
2620
+ import_kleur4.default.yellow(
2621
+ `These variables will not be updated by this script. If you want to update them, you will need to do so manually.`
2622
+ )
2623
+ );
2624
+ log("");
2625
+ }
2626
+ if ([].concat(newSecrets).concat(updatedSecrets).concat(newVariables).concat(updatedVariables).length === 0) {
2627
+ process.exit(0);
2628
+ }
2629
+ const saveChanges = await confirm2({
2630
+ message: "Do you want to continue?",
2631
+ default: true
2632
+ });
2633
+ if (!saveChanges) {
2634
+ process.exit(0);
2635
+ }
2636
+ for (const newSecret of newSecrets) {
2637
+ log(`Creating secret ${newSecret.name} with value ${newSecret.value}`);
2638
+ if (newSecret.scope === "ENVIRONMENT") {
2639
+ await createEnvironmentSecret(
2640
+ octokit,
2641
+ repositoryId,
2642
+ environment,
2643
+ newSecret.name,
2644
+ newSecret.value,
2645
+ githubOrganisation,
2646
+ githubRepository
2647
+ );
2648
+ } else {
2649
+ await createRepositorySecret(
2650
+ octokit,
2651
+ repositoryId,
2652
+ newSecret.name,
2653
+ newSecret.value,
2654
+ githubOrganisation,
2655
+ githubRepository
2656
+ );
2657
+ }
2658
+ }
2659
+ for (const updatedSecret of updatedSecrets) {
2660
+ log(
2661
+ `Updating secret ${updatedSecret.name} with value ${updatedSecret.value}`
2662
+ );
2663
+ if (updatedSecret.scope === "ENVIRONMENT") {
2664
+ await createEnvironmentSecret(
2665
+ octokit,
2666
+ repositoryId,
2667
+ environment,
2668
+ updatedSecret.name,
2669
+ updatedSecret.value,
2670
+ githubOrganisation,
2671
+ githubRepository
2672
+ );
2673
+ } else {
2674
+ await createRepositorySecret(
2675
+ octokit,
2676
+ repositoryId,
2677
+ updatedSecret.name,
2678
+ updatedSecret.value,
2679
+ githubOrganisation,
2680
+ githubRepository
2681
+ );
2682
+ }
2683
+ }
2684
+ for (const newVariable of newVariables) {
2685
+ log(`Creating variable ${newVariable.name} with value ${newVariable.value}`);
2686
+ if (newVariable.scope === "ENVIRONMENT") {
2687
+ await createEnvironmentVariable(
2688
+ octokit,
2689
+ repositoryId,
2690
+ environment,
2691
+ newVariable.name,
2692
+ newVariable.value
2693
+ );
2694
+ } else {
2695
+ await createRepositoryVariable(
2696
+ octokit,
2697
+ repositoryId,
2698
+ newVariable.name,
2699
+ newVariable.value
2700
+ );
2701
+ }
2702
+ }
2703
+ for (const updatedVariable of updatedVariables) {
2704
+ log(
2705
+ `Updating variable ${updatedVariable.name} with value ${updatedVariable.value}`
2706
+ );
2707
+ if (updatedVariable.scope === "ENVIRONMENT") {
2708
+ await updateEnvironmentVariable(
2709
+ octokit,
2710
+ repositoryId,
2711
+ environment,
2712
+ updatedVariable.name,
2713
+ updatedVariable.value
2714
+ );
2715
+ } else {
2716
+ await updateRepositoryVariable(
2717
+ octokit,
2718
+ repositoryId,
2719
+ updatedVariable.name,
2720
+ updatedVariable.value
2721
+ );
2722
+ }
2723
+ }
2724
+ log(
2725
+ import_kleur4.default.green(
2726
+ `Successfully updated Github secrets and variables for environment ${environment}`
2727
+ )
2728
+ );
2729
+ log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2730
+ generateInventory(
2731
+ environment,
2732
+ {
2733
+ kube_worker_nodes: kubeWorkerNodes,
2734
+ kube_api_host: infrastructure.kubeAPIHost || "",
2735
+ backup_host: backupHost || "",
2736
+ users
2737
+ }
2738
+ );
2739
+ copyChartsValues(
2740
+ environment,
2741
+ {
2742
+ env: environment,
2743
+ environment_type,
2744
+ // FIXME: In general that should be environment_type,
2745
+ // Hardcode like this blocks us from being generic:
2746
+ // https://github.com/opencrvs/opencrvs-core/issues/11171
2747
+ two_fa_enabled: environment !== "production" ? false : true,
2748
+ backup_enabled: configureBackup ? true : false,
2749
+ restore_enabled: restoreEnvironmentName ? true : false,
2750
+ restore_environment_name: restoreEnvironmentName || "",
2751
+ restore_type: restoreType,
2752
+ traefik_mode: traefikConfOption,
2753
+ backup_type: backupType
2754
+ }
2755
+ );
2756
+ let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2757
+
2758
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("COPY the SSH public key from the master VM to your clipboard")}
2759
+ --------------------------------------------------------------------------------------------
2760
+ ` : "";
2761
+ addon_message += kubeWorkerNodes.length > 0 ? `\u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes worker VM to create provision user and setup SSH key:")}
2762
+
2763
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2764
+ bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"
2765
+ ` : "";
2766
+ addon_message += configureBackup ? `
2767
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on backup server to create provision user and setup SSH key:")}
2768
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2769
+ bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"` : "";
2770
+ log(`
2771
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2772
+ Follow the steps below to complete the setup of your environment:
2773
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2774
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes master VM to bootstrap self-hosted runner:")}
2775
+
2776
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2777
+ bash opencrvs-bootstrap.sh --owner ${githubOrganisation} \\
2778
+ --repo ${githubRepository} \\
2779
+ --env ${environment} \\
2780
+ --token ${githubToken} \\
2781
+ --enable-runner
2782
+
2783
+ ${addon_message}
2784
+
2785
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2786
+ ${import_kleur4.default.yellow("Please KINDLY read hints above")}
2787
+ `);
2788
+ log("\nAll variables stored in", import_kleur4.default.cyan(`.env.${environment}`));
2789
+ log(import_kleur4.default.bold().yellow("DO NOT COMMIT THIS FILE TO GIT!"));
2790
+ })();
2791
+ }
2792
+ });
2793
+
2794
+ // src/environment/update-workflows.ts
2795
+ var update_workflows_exports = {};
2796
+ __export(update_workflows_exports, {
2797
+ updateWorkflowEnvironments: () => updateWorkflowEnvironments
2798
+ });
2799
+ async function extractInfrastructureNames() {
2800
+ const files = glob.sync("infrastructure/server-setup/inventory/*.yml");
2801
+ const infraEnvironments = files.map((file) => (0, import_path28.basename)(file, ".yml"));
2802
+ if (infraEnvironments.length === 0) {
2803
+ console.log("\u26A0\uFE0F Warning: No environment directories found in infrastructure/server-setup/inventory/");
2804
+ return [];
2805
+ }
2806
+ log("\u{1F50D} Found infrastructure configurations:", infraEnvironments.join(", "));
2807
+ return infraEnvironments;
2808
+ }
2809
+ async function extractEnvironmentNames() {
2810
+ const entries = await (0, import_promises.readdir)("environments");
2811
+ const environments = entries.filter((entry) => {
2812
+ const fullPath = (0, import_path28.join)("environments", entry);
2813
+ return (0, import_fs9.statSync)(fullPath).isDirectory();
2814
+ });
2815
+ if (environments.length === 0) {
2816
+ console.log("\u26A0\uFE0F Warning: No environment directories found in environments/");
2817
+ return [];
2818
+ }
2819
+ log("\u{1F50D} Found OpenCRVS configurations:", environments.join(", "));
2820
+ return environments;
2821
+ }
2822
+ function updateOptionsInYaml(content, envList) {
2823
+ const optionsRegex = /([ ]*options:[ ]*\n)((?:[ ]*-[^\n]*\n)+)/;
2824
+ const match = content.match(optionsRegex);
2825
+ if (!match) {
2826
+ throw new Error("Could not find options array in workflow file");
2827
+ }
2828
+ const firstItemMatch = match[2].match(/^([ ]*)-/);
2829
+ const itemIndent = firstItemMatch ? firstItemMatch[1] : " ";
2830
+ const newOptions = match[1] + envList.map((env) => `${itemIndent}- ${env}`).join("\n") + "\n";
2831
+ return content.replace(optionsRegex, newOptions);
2832
+ }
2833
+ async function updateWorkflows(envList, config) {
2834
+ const { workflows } = config;
2835
+ for (const workflowPath of workflows) {
2836
+ try {
2837
+ const fileContents = (0, import_fs9.readFileSync)(workflowPath, "utf8");
2838
+ const workflowData = yaml2.load(fileContents);
2839
+ if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2840
+ throw new Error("Workflow does not have the expected structure: on.workflow_dispatch.inputs.environment.options");
2841
+ }
2842
+ const updatedContent = updateOptionsInYaml(fileContents, envList);
2843
+ (0, import_fs9.writeFileSync)(workflowPath, updatedContent, "utf8");
2844
+ log(` \u2713 Successfully updated ${workflowPath}`);
2845
+ } catch (error4) {
2846
+ console.error(`
2847
+ \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`);
2848
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2849
+ throw error4;
2850
+ }
2851
+ }
2852
+ }
2853
+ async function updateWorkflowEnvironments() {
2854
+ try {
2855
+ let didUpdateWorkflows = false;
2856
+ const infraEnvironments = await extractInfrastructureNames();
2857
+ if (infraEnvironments.length > 0) {
2858
+ console.log("\u{1F504} Updating infrastructure workflows:");
2859
+ await updateWorkflows(infraEnvironments, {
2860
+ workflows: [
2861
+ ".github/workflows/provision.yml",
2862
+ ".github/workflows/reset-2fa.yml"
2863
+ ],
2864
+ path: "on.workflow_dispatch.inputs.environment.options"
2865
+ });
2866
+ didUpdateWorkflows = true;
2867
+ }
2868
+ const environments = await extractEnvironmentNames();
2869
+ if (environments.length > 0) {
2870
+ const workflows = [
2871
+ ".github/workflows/deploy-dependencies.yml",
2872
+ ".github/workflows/deploy-opencrvs.yml",
2873
+ ".github/workflows/clear-all-data.yml",
2874
+ ".github/workflows/seed-data.yml",
2875
+ ".github/workflows/reindex.yml",
2876
+ ".github/workflows/github-to-k8s-sync-env.yml"
2877
+ ];
2878
+ log("\u{1F4CB} Updating OpenCRVS application workflows:");
2879
+ await updateWorkflows(environments, {
2880
+ workflows,
2881
+ path: "on.workflow_dispatch.inputs.environment.options"
2882
+ });
2883
+ didUpdateWorkflows = true;
2884
+ }
2885
+ if (didUpdateWorkflows) {
2886
+ success("\u2705 Workflow updates completed successfully!");
2887
+ } else {
2888
+ log("\u2139\uFE0F No workflows were updated.");
2889
+ }
2890
+ } catch (error4) {
2891
+ console.error("\n\u274C Error updating workflows:", error4);
2892
+ process.exit(1);
2893
+ }
2894
+ }
2895
+ var import_promises, import_fs9, import_path28, glob, yaml2;
2896
+ var init_update_workflows = __esm({
2897
+ "src/environment/update-workflows.ts"() {
2898
+ "use strict";
2899
+ import_promises = require("fs/promises");
2900
+ import_fs9 = require("fs");
2901
+ import_path28 = require("path");
2902
+ glob = __toESM(require("glob"));
2903
+ yaml2 = __toESM(require("js-yaml"));
2904
+ init_logger();
2905
+ }
2906
+ });
2907
+
2908
+ // src/environment/users.ts
2909
+ var users_exports = {};
2910
+ async function select4(options) {
2911
+ const inquirer = await import("@inquirer/prompts");
2912
+ return inquirer.select(options);
2913
+ }
2914
+ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
2915
+ if (!fs8.existsSync(dirPath)) {
2916
+ throw Error(`Directory ${dirPath} doesn't exist`);
2917
+ }
2918
+ const files = fs8.readdirSync(dirPath).filter((file) => {
2919
+ const filePath = path26.join(dirPath, file);
2920
+ const isFile = fs8.statSync(filePath).isFile();
2921
+ const ext = path26.extname(file).slice(1).toLowerCase();
2922
+ return isFile && (ext === "yml" || ext === "yaml");
2923
+ }).sort();
2924
+ if (files.length === 0) {
2925
+ throw Error(`No environment configuration files found at ${dirPath}`);
2926
+ }
2927
+ const choices = files.map((file) => ({
2928
+ name: path26.basename(file, path26.extname(file)),
2929
+ value: path26.join(dirPath, file)
2930
+ }));
2931
+ const selectedFile = await select4({
2932
+ message: "Select environment (inventory file) to load users:",
2933
+ choices
2934
+ });
2935
+ return selectedFile;
2936
+ }
2937
+ async function manageUsersStandalone() {
2938
+ console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
2939
+ const inventory_file = await selectInventoryFile();
2940
+ manageUsers(inventory_file);
2941
+ }
2942
+ var fs8, path26, import_kleur5;
2943
+ var init_users = __esm({
2944
+ "src/environment/users.ts"() {
2945
+ "use strict";
2946
+ fs8 = __toESM(require("fs"));
2947
+ path26 = __toESM(require("path"));
2948
+ import_kleur5 = __toESM(require("kleur"));
2949
+ init_manage_users();
2950
+ manageUsersStandalone();
2951
+ }
2952
+ });
2953
+
2954
+ // src/environment/swarm-to-k8s.ts
2955
+ var swarm_to_k8s_exports = {};
2956
+ var path27, import_kleur6, import_core2;
2957
+ var init_swarm_to_k8s = __esm({
2958
+ "src/environment/swarm-to-k8s.ts"() {
2959
+ "use strict";
2960
+ path27 = __toESM(require("path"));
2961
+ import_kleur6 = __toESM(require("kleur"));
2962
+ init_logger();
2963
+ init_utils();
2964
+ init_templates();
2965
+ import_core2 = require("@octokit/core");
2966
+ init_ssh_keygen();
2967
+ init_github();
2968
+ (async () => {
2969
+ log(import_kleur6.default.bold(
2970
+ "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2971
+ ));
2972
+ const environment_type = process.env.ENVIRONMENT_TYPE || "production";
2973
+ const environment = process.env.ENVIRONMENT || "";
2974
+ const githubToken = process.env.INFRA_TOKEN || "";
2975
+ const githubOrganisation = process.env.INFRA_ORGANISATION || "";
2976
+ const githubRepository = process.env.INFRA_REPOSITORY || "";
2977
+ if (!environment) {
2978
+ error("\n", "Environment variable ENVIRONMENT is not set. Exiting.");
2979
+ process.exit(1);
2980
+ }
2981
+ if (!githubToken) {
2982
+ error("\n", "Environment variable GITHUB_TOKEN is not set. Exiting.");
2983
+ process.exit(1);
2984
+ }
2985
+ if (!githubOrganisation) {
2986
+ error("\n", "Environment variable INFRA_ORGANISATION is not set. Exiting.");
2987
+ process.exit(1);
2988
+ }
2989
+ if (!githubRepository) {
2990
+ error("\n", "Environment variable INFRA_REPOSITORY is not set. Exiting.");
2991
+ process.exit(1);
2992
+ }
2993
+ if (["backup", "jumpbox"].includes(environment)) {
2994
+ info(` > ${environment} environment will not be migrated, see migration notes`);
2995
+ process.exit(0);
2996
+ }
2997
+ log(import_kleur6.default.bold().underline("Migration properties:"));
2998
+ log(` \u2713 Environment: ${environment}`);
2999
+ const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
3000
+ if (!old_inventory_path) {
3001
+ error("\n", "Environment variable OLD_INVENTORY_PATH is not set. Exiting.");
3002
+ log("\n", "Old inventory path is required to read existing Swarm configurations.");
3003
+ process.exit(1);
3004
+ }
3005
+ const ansible_inventory = path27.join(old_inventory_path, environment + ".yml");
3006
+ const data = readYamlFile(ansible_inventory);
3007
+ log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3008
+ const master = dockerManagerFirst(data) || "";
3009
+ log(` \u2713 Kubernetes API Host (Docker Manager): ${master}`);
3010
+ const users = extractAndModifyUsers(data);
3011
+ const kube_worker_nodes = extractWorkerNodes(data);
3012
+ log(` \u2713 Worker nodes: ${kube_worker_nodes.join(", ")}`);
3013
+ const backup_host = extractBackupNode(data);
3014
+ log(` \u2713 Backup host: ${backup_host}`);
3015
+ generateInventory(
3016
+ environment,
3017
+ {
3018
+ kube_worker_nodes,
3019
+ users,
3020
+ backup_host: environment === "production" ? backup_host : "",
3021
+ kube_api_host: master
3022
+ }
3023
+ );
3024
+ copyChartsValues(
3025
+ environment,
3026
+ {
3027
+ env: environment,
3028
+ environment_type,
3029
+ // FIXME: In general that should be environment_type,
3030
+ // Hardcode like this blocks us from being generic:
3031
+ // https://github.com/opencrvs/opencrvs-core/issues/11171
3032
+ two_fa_enabled: environment !== "production" ? false : true,
3033
+ backup_enabled: environment === "production" ? "true" : "false",
3034
+ restore_enabled: environment === "staging" ? "true" : "false",
3035
+ restore_environment_name: environment === "staging" ? "production" : "",
3036
+ restore_type: "dump",
3037
+ traefik_mode: "static_ssl",
3038
+ backup_type: "dump"
3039
+ }
3040
+ );
3041
+ if (environment === "staging") {
3042
+ const octokit = new import_core2.Octokit({
3043
+ auth: githubToken
3044
+ });
3045
+ const repositoryId = await getRepositoryId(
3046
+ octokit,
3047
+ githubOrganisation,
3048
+ githubRepository
3049
+ );
3050
+ try {
3051
+ await createEnvironmentVariable(
3052
+ octokit,
3053
+ repositoryId,
3054
+ environment,
3055
+ "RESTORE_ENVIRONMENT_NAME",
3056
+ "production"
3057
+ );
3058
+ } catch (err) {
3059
+ error(`Failed to create variable RESTORE_ENVIRONMENT_NAME for environment ${environment}:`, err);
3060
+ }
3061
+ }
3062
+ if (environment === "production") {
3063
+ const octokit = new import_core2.Octokit({
3064
+ auth: githubToken
3065
+ });
3066
+ console.log("Fetching repository ID for:", githubOrganisation, githubRepository);
3067
+ const repositoryId = await getRepositoryId(
3068
+ octokit,
3069
+ githubOrganisation,
3070
+ githubRepository
3071
+ );
3072
+ console.log("Repository ID:", repositoryId);
3073
+ const { publicKey, privateKey } = generateSSHKeyPair();
3074
+ const secretsToCreate = {
3075
+ BACKUP_HOST_PRIVATE_KEY: privateKey,
3076
+ BACKUP_HOST_PUBLIC_KEY: publicKey,
3077
+ BACKUP_SERVER_USER: "backup"
3078
+ };
3079
+ const variablesToCreate = {
3080
+ BACKUP_HOST: backup_host,
3081
+ KUBE_WORKER_NODES: kube_worker_nodes.join(",")
3082
+ };
3083
+ for (const [secretName, secretValue] of Object.entries(secretsToCreate)) {
3084
+ try {
3085
+ await createEnvironmentSecret(
3086
+ octokit,
3087
+ repositoryId,
3088
+ environment,
3089
+ secretName,
3090
+ secretValue,
3091
+ githubOrganisation,
3092
+ githubRepository
3093
+ );
3094
+ log(` \u2713 Created secret ${secretName} for environment ${environment}`);
3095
+ } catch (err) {
3096
+ error(`Failed to create secret ${secretName} for environment ${environment}:`, err);
3097
+ }
3098
+ }
3099
+ for (const [variableName, variableValue] of Object.entries(variablesToCreate)) {
3100
+ try {
3101
+ await createEnvironmentVariable(
3102
+ octokit,
3103
+ repositoryId,
3104
+ environment,
3105
+ variableName,
3106
+ variableValue
3107
+ );
3108
+ log(` \u2713 Created variable ${variableName} for environment ${environment}`);
3109
+ } catch (err) {
3110
+ error(`Failed to create variable ${variableName} for environment ${environment}:`, err);
3111
+ }
3112
+ }
3113
+ }
3114
+ })();
3115
+ }
3116
+ });
25
3117
 
26
3118
  // src/migrations/v2.0/remove-review-from-register-action.ts
27
3119
  var import_ts_morph = require("ts-morph");
@@ -1883,9 +4975,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1883
4975
  }
1884
4976
  return replacedCount;
1885
4977
  }
1886
- function resolveConfigChain(configObj, path23) {
4978
+ function resolveConfigChain(configObj, path28) {
1887
4979
  let current = configObj;
1888
- for (const key of path23) {
4980
+ for (const key of path28) {
1889
4981
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1890
4982
  const prop = current.getProperty(key);
1891
4983
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2120,6 +5212,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2120
5212
  var import_ts_morph11 = require("ts-morph");
2121
5213
  var import_path11 = __toESM(require("path"));
2122
5214
 
5215
+ // ../commons/src/scopes.deprecated.do-not-use.ts
5216
+ var z4 = __toESM(require("zod/v4"));
5217
+ var import_lodash = require("lodash");
5218
+
2123
5219
  // ../commons/src/scopes.ts
2124
5220
  var z3 = __toESM(require("zod/v4"));
2125
5221
  var qs = __toESM(require("qs"));
@@ -2364,8 +5460,8 @@ var flattenScope = (scope) => ({
2364
5460
  type: scope.type,
2365
5461
  ..."options" in scope ? scope.options : {}
2366
5462
  });
2367
- var unflattenScope = (input) => {
2368
- const { type, ...options } = input;
5463
+ var unflattenScope = (input3) => {
5464
+ const { type, ...options } = input3;
2369
5465
  return { type, options };
2370
5466
  };
2371
5467
  var EncodedScope2 = z3.string().brand("EncodedScope");
@@ -2378,22 +5474,29 @@ var encodeScope = (scope) => {
2378
5474
  encode: false
2379
5475
  });
2380
5476
  };
2381
- var decodeScope = (query) => {
2382
- const scope = qs.parse(query, {
5477
+ var decodedScopeCache = /* @__PURE__ */ new Map();
5478
+ var decodeScope = (encodedScope) => {
5479
+ if (decodedScopeCache.has(encodedScope)) {
5480
+ return decodedScopeCache.get(encodedScope);
5481
+ }
5482
+ const scope = qs.parse(encodedScope, {
2383
5483
  ignoreQueryPrefix: true,
2384
5484
  comma: true,
2385
5485
  allowDots: true
2386
5486
  });
2387
5487
  const unflattenedScope = unflattenScope(scope);
2388
- return Scope2.safeParse(unflattenedScope)?.data;
5488
+ const result = Scope2.safeParse(unflattenedScope)?.data;
5489
+ decodedScopeCache.set(encodedScope, result);
5490
+ return result;
2389
5491
  };
2390
5492
  var DEFAULT_SCOPE_OPTIONS = {
2391
5493
  placeOfEvent: JurisdictionFilter.enum.all,
2392
- accessLevel: JurisdictionFilter.enum.all
5494
+ accessLevel: JurisdictionFilter.enum.all,
5495
+ registeredIn: JurisdictionFilter.enum.all,
5496
+ declaredIn: JurisdictionFilter.enum.all
2393
5497
  };
2394
5498
 
2395
5499
  // ../commons/src/scopes.deprecated.do-not-use.ts
2396
- var z4 = __toESM(require("zod/v4"));
2397
5500
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2398
5501
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2399
5502
  var SearchScope = z4.object({
@@ -2627,6 +5730,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2627
5730
  }
2628
5731
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2629
5732
  };
5733
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
5734
+ function isMergeableUserScopeType(type) {
5735
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
5736
+ }
5737
+ function decodeLegacyScope(legacy) {
5738
+ const encoded = legacyScopeToV2Scope(legacy);
5739
+ const scope = decodeScope(encoded);
5740
+ if (!scope) {
5741
+ throw new Error(
5742
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
5743
+ );
5744
+ }
5745
+ return { legacy, scope };
5746
+ }
5747
+ function groupByType(entries) {
5748
+ return entries.reduce(
5749
+ (groups, entry) => ({
5750
+ ...groups,
5751
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
5752
+ }),
5753
+ {}
5754
+ );
5755
+ }
5756
+ function deduplicateEntries(entries) {
5757
+ return entries.filter(
5758
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
5759
+ );
5760
+ }
5761
+ function mergeEntries(type, entries) {
5762
+ const optionsList = entries.map(
5763
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
5764
+ );
5765
+ const allKeys = optionsList.flatMap(
5766
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
5767
+ );
5768
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
5769
+ if (conflictKey) {
5770
+ const conflicting = entries.filter(
5771
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
5772
+ ).map((e) => JSON.stringify(e.legacy));
5773
+ throw new Error(
5774
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
5775
+ );
5776
+ }
5777
+ const mergedOptions = Object.assign({}, ...optionsList);
5778
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
5779
+ const parsed = Scope2.safeParse(merged);
5780
+ if (!parsed.success) {
5781
+ throw new Error(
5782
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
5783
+ );
5784
+ }
5785
+ return parsed.data;
5786
+ }
5787
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
5788
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
5789
+ return Object.entries(groups).flatMap(([type, entries]) => {
5790
+ const deduped = deduplicateEntries(entries);
5791
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
5792
+ if (!isMergeableUserScopeType(type)) {
5793
+ console.warn(
5794
+ `Multiple non-mergeable '${type}' scopes detected after dedup \u2014 kept all as-is. Legacy scopes: [${deduped.map((e) => JSON.stringify(e.legacy)).join(", ")}]. Review whether the duplication is intentional.`
5795
+ );
5796
+ return deduped.map((e) => e.scope);
5797
+ }
5798
+ return [mergeEntries(type, deduped)];
5799
+ });
5800
+ }
2630
5801
 
2631
5802
  // src/migrations/v2.0/migrate-scopes.ts
2632
5803
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2664,57 +5835,65 @@ function resolveLegacyScopeFromElement(element) {
2664
5835
  }
2665
5836
  function migrateScopesArrays(rolesFilePath, project) {
2666
5837
  const sourceFile = project.getSourceFile(rolesFilePath);
2667
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
5838
+ if (!sourceFile) {
5839
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
5840
+ }
2668
5841
  let migratedCount = 0;
2669
5842
  let removedCount = 0;
5843
+ let mergedCount = 0;
2670
5844
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
5845
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2671
5846
  for (const scopesProp of scopesProperties) {
2672
5847
  const initializer = scopesProp.getInitializer();
2673
5848
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2674
- const elements = initializer.getElements();
2675
- for (let index = elements.length - 1; index >= 0; index--) {
2676
- const element = elements[index];
2677
- if (!import_ts_morph11.Node.isExpression(element)) continue;
5849
+ const rawTexts = [];
5850
+ const legacyStrings = [];
5851
+ let anyChange = false;
5852
+ for (const element of initializer.getElements()) {
2678
5853
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2679
5854
  if (scopeKey && !(scopeKey in SCOPES)) {
2680
5855
  console.warn(
2681
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
5856
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2682
5857
  );
2683
- initializer.removeElement(index);
2684
5858
  removedCount++;
5859
+ anyChange = true;
2685
5860
  continue;
2686
5861
  }
2687
5862
  const legacyScope = resolveLegacyScopeFromElement(element);
2688
5863
  if (!legacyScope) {
2689
5864
  console.warn(
2690
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
5865
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2691
5866
  );
5867
+ rawTexts.push(element.getText());
2692
5868
  continue;
2693
5869
  }
2694
- try {
2695
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2696
- const scope = decodeScope(migratedScope);
2697
- if (!scope) {
2698
- console.warn(
2699
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2700
- );
2701
- continue;
2702
- }
2703
- element.replaceWithText(JSON.stringify(scope));
2704
- migratedCount++;
2705
- } catch (error) {
2706
- console.warn(
2707
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2708
- );
2709
- }
5870
+ legacyStrings.push(legacyScope);
5871
+ anyChange = true;
5872
+ }
5873
+ if (!anyChange) continue;
5874
+ let mergedScopes;
5875
+ try {
5876
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
5877
+ } catch (error4) {
5878
+ throw new Error(
5879
+ `[${relPath}] Failed to migrate scopes for role: ${error4 instanceof Error ? error4.message : String(error4)}`,
5880
+ { cause: error4 }
5881
+ );
2710
5882
  }
5883
+ migratedCount += legacyStrings.length;
5884
+ mergedCount += legacyStrings.length - mergedScopes.length;
5885
+ const outputElements = [
5886
+ ...rawTexts,
5887
+ ...mergedScopes.map((s) => JSON.stringify(s))
5888
+ ];
5889
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2711
5890
  }
2712
5891
  if (removedCount > 0) {
2713
5892
  console.log(
2714
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
5893
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2715
5894
  );
2716
5895
  }
2717
- return { migratedCount, removedCount };
5896
+ return { migratedCount, removedCount, mergedCount };
2718
5897
  }
2719
5898
  function ensureScopesHelpersImport(rolesFilePath, project) {
2720
5899
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2849,7 +6028,7 @@ async function main11() {
2849
6028
  return;
2850
6029
  }
2851
6030
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2852
- const { migratedCount, removedCount } = migrateScopesArrays(
6031
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2853
6032
  rolesFilePath,
2854
6033
  project
2855
6034
  );
@@ -2868,7 +6047,7 @@ async function main11() {
2868
6047
  }
2869
6048
  await sourceFile.save();
2870
6049
  console.log(
2871
- `Done. Migrated ${migratedCount} legacy scope(s), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
6050
+ `Done. Migrated ${migratedCount} legacy scope(s), merged ${mergedCount} AND-paired scope(s) into single v2 objects (privilege-escalation fix, see issue #12489), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
2872
6051
  );
2873
6052
  }
2874
6053
 
@@ -3616,9 +6795,9 @@ async function main17() {
3616
6795
  let parsed;
3617
6796
  try {
3618
6797
  parsed = JSON.parse(raw);
3619
- } catch (error) {
6798
+ } catch (error4) {
3620
6799
  console.warn(
3621
- ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error.message}`
6800
+ ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error4.message}`
3622
6801
  );
3623
6802
  return;
3624
6803
  }
@@ -4213,7 +7392,7 @@ Saved ${handlerRelPath}.`);
4213
7392
  // src/migrations/v2.0/checkout-upstream-files.ts
4214
7393
  var import_child_process = require("child_process");
4215
7394
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4216
- var UPSTREAM_BRANCH = "release-v2.0.0";
7395
+ var UPSTREAM_BRANCH = "release/2.0.0";
4217
7396
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4218
7397
  var FILES_TO_CHECKOUT = [
4219
7398
  "src/analytics/analytics.ts",
@@ -4645,7 +7824,7 @@ var FUNCTION_NAME = "precalculateAdditionalAnalytics";
4645
7824
  var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
4646
7825
  var RETURN_EXPRESSION_TEXT = "declaration";
4647
7826
  function removeTargetedNamedImports(sourceFile) {
4648
- const log = [];
7827
+ const log2 = [];
4649
7828
  for (const importDecl of [...sourceFile.getImportDeclarations()]) {
4650
7829
  const namedImports = importDecl.getNamedImports();
4651
7830
  if (namedImports.length === 0) continue;
@@ -4655,13 +7834,13 @@ function removeTargetedNamedImports(sourceFile) {
4655
7834
  if (matched.length === 0) continue;
4656
7835
  const removedNames = matched.map((ni) => ni.getName());
4657
7836
  for (const ni of matched) ni.remove();
4658
- log.push(
7837
+ log2.push(
4659
7838
  `removed import(s) ${removedNames.join(", ")} from '${importDecl.getModuleSpecifierValue()}'`
4660
7839
  );
4661
7840
  const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
4662
7841
  if (!stillUsed) importDecl.remove();
4663
7842
  }
4664
- return log;
7843
+ return log2;
4665
7844
  }
4666
7845
  function findPrecalculateFunction(sourceFile) {
4667
7846
  for (const fn of sourceFile.getFunctions()) {
@@ -4684,16 +7863,16 @@ function getFunctionBodyBlock(fn) {
4684
7863
  return initializer.getBody();
4685
7864
  }
4686
7865
  function simplifyPrecalculateFunction(sourceFile) {
4687
- const log = [];
7866
+ const log2 = [];
4688
7867
  const fn = findPrecalculateFunction(sourceFile);
4689
- if (!fn) return log;
7868
+ if (!fn) return log2;
4690
7869
  const body = getFunctionBodyBlock(fn);
4691
- if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
7870
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log2;
4692
7871
  for (const statement of [...body.getStatements()]) {
4693
7872
  const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4694
7873
  if (references) {
4695
7874
  statement.remove();
4696
- log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
7875
+ log2.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
4697
7876
  }
4698
7877
  }
4699
7878
  const remaining = body.getStatements();
@@ -4701,11 +7880,11 @@ function simplifyPrecalculateFunction(sourceFile) {
4701
7880
  const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4702
7881
  if (!alreadyCorrect) {
4703
7882
  body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
4704
- log.push(
7883
+ log2.push(
4705
7884
  `ensured '${FUNCTION_NAME}' ends with 'return ${RETURN_EXPRESSION_TEXT}'`
4706
7885
  );
4707
7886
  }
4708
- return log;
7887
+ return log2;
4709
7888
  }
4710
7889
  async function main24() {
4711
7890
  const cwd = process.cwd();
@@ -4736,8 +7915,8 @@ async function main24() {
4736
7915
  console.log(`[${ANALYTICS_FILE_REL}] already clean \u2014 nothing to do.`);
4737
7916
  return;
4738
7917
  }
4739
- for (const log of allLogs) {
4740
- console.log(` [${ANALYTICS_FILE_REL}] ${log}`);
7918
+ for (const log2 of allLogs) {
7919
+ console.log(` [${ANALYTICS_FILE_REL}] ${log2}`);
4741
7920
  }
4742
7921
  await sourceFile.save();
4743
7922
  console.log(`
@@ -4752,9 +7931,9 @@ var import_path24 = require("path");
4752
7931
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4753
7932
  var INFRASTRUCTURE_DIR = "infrastructure";
4754
7933
  var BASE_BRANCH = "release-v1.9";
4755
- function gitShowBytes(ref, path23) {
7934
+ function gitShowBytes(ref, path28) {
4756
7935
  try {
4757
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
7936
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path28}`], {
4758
7937
  cwd: process.cwd(),
4759
7938
  stdio: ["ignore", "pipe", "pipe"]
4760
7939
  });
@@ -4930,6 +8109,94 @@ async function main26({
4930
8109
  );
4931
8110
  }
4932
8111
 
8112
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
8113
+ var import_ts_morph22 = require("ts-morph");
8114
+ var import_path26 = __toESM(require("path"));
8115
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
8116
+ var ACTION_PARAMETER_NAME = "action";
8117
+ var OLD_TYPE = "ActionInput";
8118
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
8119
+ function isAcceptRequestedRegistrationParameter(parameter) {
8120
+ const functionDeclaration = parameter.getFirstAncestorByKind(
8121
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
8122
+ );
8123
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
8124
+ return true;
8125
+ }
8126
+ const arrowFunction = parameter.getFirstAncestorByKind(
8127
+ import_ts_morph22.SyntaxKind.ArrowFunction
8128
+ );
8129
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
8130
+ import_ts_morph22.SyntaxKind.VariableDeclaration
8131
+ );
8132
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
8133
+ }
8134
+ function processFile14(filePath, project) {
8135
+ const sourceFile = project.getSourceFile(filePath);
8136
+ if (!sourceFile) return 0;
8137
+ let updatedCount = 0;
8138
+ for (const parameter of sourceFile.getDescendantsOfKind(
8139
+ import_ts_morph22.SyntaxKind.Parameter
8140
+ )) {
8141
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
8142
+ continue;
8143
+ }
8144
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
8145
+ continue;
8146
+ }
8147
+ const typeNode = parameter.getTypeNode();
8148
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
8149
+ continue;
8150
+ }
8151
+ parameter.setType(NEW_TYPE);
8152
+ updatedCount++;
8153
+ console.log(
8154
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
8155
+ );
8156
+ }
8157
+ return updatedCount;
8158
+ }
8159
+ async function main27() {
8160
+ const srcDir = import_path26.default.join(process.cwd(), "src");
8161
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
8162
+ `);
8163
+ const project = new import_ts_morph22.Project({
8164
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
8165
+ skipAddingFilesFromTsConfig: false
8166
+ });
8167
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
8168
+ const filePath = sf.getFilePath();
8169
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
8170
+ });
8171
+ let totalUpdated = 0;
8172
+ const modifiedFiles = [];
8173
+ for (const sourceFile of sourceFiles) {
8174
+ const filePath = sourceFile.getFilePath();
8175
+ const updated = processFile14(filePath, project);
8176
+ if (updated > 0) {
8177
+ totalUpdated += updated;
8178
+ modifiedFiles.push(filePath);
8179
+ }
8180
+ }
8181
+ if (modifiedFiles.length === 0) {
8182
+ console.log(
8183
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
8184
+ );
8185
+ return;
8186
+ }
8187
+ console.log(`
8188
+ Saving ${modifiedFiles.length} modified file(s)...`);
8189
+ for (const filePath of modifiedFiles) {
8190
+ const sourceFile = project.getSourceFileOrThrow(filePath);
8191
+ await sourceFile.save();
8192
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
8193
+ }
8194
+ console.log(
8195
+ `
8196
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
8197
+ );
8198
+ }
8199
+
4933
8200
  // src/migrations/v2.0/index.ts
4934
8201
  var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4935
8202
  async function runUpgrade(dockerSwarm) {
@@ -4956,6 +8223,7 @@ async function runUpgrade(dockerSwarm) {
4956
8223
  await main22();
4957
8224
  await main23();
4958
8225
  await main24();
8226
+ await main27();
4959
8227
  await main17();
4960
8228
  if (dockerSwarm) {
4961
8229
  await main25();
@@ -4965,13 +8233,55 @@ async function runUpgrade(dockerSwarm) {
4965
8233
  }
4966
8234
  }
4967
8235
 
8236
+ // src/environment/index.ts
8237
+ var import_fs10 = require("fs");
8238
+ var import_path29 = require("path");
8239
+ var REQUIRED_REPOSITORY_DIRECTORIES = [
8240
+ ".github/workflows",
8241
+ "environments",
8242
+ "infrastructure"
8243
+ ];
8244
+ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
8245
+ const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
8246
+ (directory) => {
8247
+ try {
8248
+ return !(0, import_fs10.statSync)((0, import_path29.resolve)(repositoryRoot, directory)).isDirectory();
8249
+ } catch {
8250
+ return true;
8251
+ }
8252
+ }
8253
+ );
8254
+ if (missingDirectories.length > 0) {
8255
+ throw new Error(
8256
+ `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
8257
+ );
8258
+ }
8259
+ }
8260
+ async function runEnvironmentInit() {
8261
+ validateRepositoryStructure();
8262
+ await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
8263
+ }
8264
+ async function runEnvironmentUpdateWorkflows() {
8265
+ validateRepositoryStructure();
8266
+ const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
8267
+ await updateWorkflowEnvironments2();
8268
+ }
8269
+ async function runEnvironmentUsers() {
8270
+ validateRepositoryStructure();
8271
+ await Promise.resolve().then(() => (init_users(), users_exports));
8272
+ }
8273
+ async function runEnvironmentSwarmToK8s() {
8274
+ validateRepositoryStructure();
8275
+ await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
8276
+ }
8277
+
4968
8278
  // src/cli.ts
4969
8279
  var args = process.argv.slice(2);
4970
8280
  var USAGE = `
4971
8281
  Usage: opencrvs <command>
4972
8282
 
4973
8283
  Commands:
4974
- environment init Initialise a new environment
8284
+ environment Manage deployment environments
4975
8285
  upgrade Upgrade an existing environment
4976
8286
  check-translations Check translation files for completeness
4977
8287
 
@@ -4990,7 +8300,7 @@ Options:
4990
8300
  'infrastructure/' directory is deleted (default).
4991
8301
  -h, --help Show this message.
4992
8302
  `.trim();
4993
- function main27() {
8303
+ function main28() {
4994
8304
  const command = args[0];
4995
8305
  if (!command || command === "--help" || command === "-h") {
4996
8306
  console.log(USAGE);
@@ -5010,7 +8320,7 @@ function main27() {
5010
8320
  process.exit(1);
5011
8321
  }
5012
8322
  }
5013
- function handleEnvironment() {
8323
+ async function handleEnvironment() {
5014
8324
  const subcommand = args[1];
5015
8325
  if (!subcommand || subcommand === "--help" || subcommand === "-h") {
5016
8326
  console.log(
@@ -5018,22 +8328,45 @@ function handleEnvironment() {
5018
8328
  Usage: opencrvs environment <subcommand>
5019
8329
 
5020
8330
  Subcommands:
5021
- init Initialise a new environment
8331
+ init Initialise a new environment
8332
+ update-workflows Update workflow environment options
8333
+ users Manage environment users
8334
+ swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
5022
8335
  `.trim()
5023
8336
  );
5024
8337
  process.exit(0);
5025
8338
  }
5026
8339
  switch (subcommand) {
5027
8340
  case "init":
5028
- console.log("Initialising environment...");
5029
- console.warn("This command is not implemented yet!");
5030
- process.exit(1);
5031
- break;
8341
+ return runEnvironmentCommand("initialisation", runEnvironmentInit);
8342
+ case "update-workflows":
8343
+ return runEnvironmentCommand(
8344
+ "workflow update",
8345
+ runEnvironmentUpdateWorkflows
8346
+ );
8347
+ case "users":
8348
+ return runEnvironmentCommand("user management", runEnvironmentUsers);
8349
+ case "swarm-to-k8s":
8350
+ return runEnvironmentCommand(
8351
+ "Swarm to Kubernetes migration",
8352
+ runEnvironmentSwarmToK8s
8353
+ );
5032
8354
  default:
5033
8355
  console.error(`Unknown subcommand: environment ${subcommand}`);
5034
8356
  process.exit(1);
5035
8357
  }
5036
8358
  }
8359
+ async function runEnvironmentCommand(operation, command) {
8360
+ try {
8361
+ await command();
8362
+ } catch (error4) {
8363
+ console.error(
8364
+ `Environment ${operation} failed:`,
8365
+ error4 instanceof Error ? error4.message : error4
8366
+ );
8367
+ process.exit(1);
8368
+ }
8369
+ }
5037
8370
  async function handleUpgrade() {
5038
8371
  const upgradeArgs = args.slice(1);
5039
8372
  if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
@@ -5055,8 +8388,8 @@ async function handleUpgrade() {
5055
8388
  try {
5056
8389
  await runUpgrade(dockerSwarm);
5057
8390
  console.log("Upgrade completed successfully!");
5058
- } catch (error) {
5059
- console.error("Upgrade failed:", error);
8391
+ } catch (error4) {
8392
+ console.error("Upgrade failed:", error4);
5060
8393
  process.exit(1);
5061
8394
  }
5062
8395
  }
@@ -5065,4 +8398,4 @@ function handleCheckTranslations() {
5065
8398
  console.warn("This command is not implemented yet!");
5066
8399
  process.exit(1);
5067
8400
  }
5068
- main27();
8401
+ main28();