@opencrvs/toolkit 2.0.0-rc.be6338d → 2.0.0-rc.bee0e60

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