@opencrvs/toolkit 2.0.0-rc.511fa6e → 2.0.0-rc.517e1aa

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