@opencrvs/toolkit 2.1.0-rc.99061f0 → 2.1.0-rc.9a83eed

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 (113) hide show
  1. package/README.md +2 -12
  2. package/build.sh +9 -1
  3. package/create-countryconfig/index.js +412 -59
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +4 -1
  6. package/dist/application-config/index.js +347 -281
  7. package/dist/authentication/index.d.ts +67 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +751 -0
  10. package/dist/cli.js +2077 -299
  11. package/dist/commons/api/router.d.ts +689 -110
  12. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  13. package/dist/commons/conditionals/validate.d.ts +16 -5
  14. package/dist/commons/events/ActionConfig.d.ts +4 -0
  15. package/dist/commons/events/ActionDocument.d.ts +5 -11
  16. package/dist/commons/events/ActionInput.d.ts +4 -4
  17. package/dist/commons/events/ActionStatus.d.ts +14 -0
  18. package/dist/commons/events/AdvancedSearchConfig.d.ts +36 -12
  19. package/dist/commons/events/AuditLog.d.ts +147 -0
  20. package/dist/commons/events/EventConfig.d.ts +3 -0
  21. package/dist/commons/events/EventDocument.d.ts +470 -2
  22. package/dist/commons/events/EventIndex.d.ts +3 -26
  23. package/dist/commons/events/EventMetadata.d.ts +1 -11
  24. package/dist/commons/events/EventStatus.d.ts +19 -0
  25. package/dist/commons/events/FieldConfig.d.ts +99 -63
  26. package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
  27. package/dist/commons/events/FieldValue.d.ts +2 -2
  28. package/dist/commons/events/Flag.d.ts +42 -0
  29. package/dist/commons/events/FormConfig.d.ts +6 -0
  30. package/dist/commons/events/PageConfig.d.ts +4 -0
  31. package/dist/commons/events/PlainDate.d.ts +8 -0
  32. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  33. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  34. package/dist/commons/events/event.d.ts +12 -0
  35. package/dist/commons/events/index.d.ts +1 -0
  36. package/dist/commons/events/locationPayloads.d.ts +95 -0
  37. package/dist/commons/events/locations.d.ts +169 -26
  38. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  39. package/dist/commons/events/test.utils.d.ts +25 -4
  40. package/dist/commons/events/utils.d.ts +17 -2
  41. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  42. package/dist/commons/notification/dispatch.d.ts +10 -0
  43. package/dist/commons/notification/index.d.ts +1 -0
  44. package/dist/conditionals/index.js +335 -64
  45. package/dist/csv.d.ts +25 -0
  46. package/dist/csv.d.ts.map +1 -0
  47. package/dist/csv.js +120 -0
  48. package/dist/environment/logger.d.ts +15 -3
  49. package/dist/environment/logger.d.ts.map +1 -1
  50. package/dist/environment/manage-users.js +1 -1
  51. package/dist/environment/questions.d.ts.map +1 -1
  52. package/dist/environment/questions.js +20 -14
  53. package/dist/environment/setup-environment.js +45 -27
  54. package/dist/environment/templates.d.ts +0 -1
  55. package/dist/environment/templates.d.ts.map +1 -1
  56. package/dist/environment/templates.js +3 -8
  57. package/dist/environment/update-workflows.d.ts.map +1 -1
  58. package/dist/environment/update-workflows.js +4 -0
  59. package/dist/environment/utils.d.ts +0 -12
  60. package/dist/environment/utils.d.ts.map +1 -1
  61. package/dist/environment/utils.js +1 -28
  62. package/dist/events/index.js +7660 -7156
  63. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  64. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  65. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  66. package/dist/migrations/v2.0/merge-infrastructure-directory.js +3 -3
  67. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +1 -1
  68. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +1 -1
  69. package/dist/migrations/v2.1/add-explicit-correction-flags.js +34 -6
  70. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  71. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  72. package/dist/migrations/v2.1/add-recovery-link-notifications.js +506 -0
  73. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  74. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  75. package/dist/migrations/v2.1/add-translations.js +208 -0
  76. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  77. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  78. package/dist/migrations/v2.1/enable-telemetry.js +433 -0
  79. package/dist/migrations/v2.1/index.d.ts +14 -1
  80. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  81. package/dist/migrations/v2.1/index.js +1077 -7
  82. package/dist/notification/index.js +1835 -1425
  83. package/dist/scopes/index.d.ts +435 -36
  84. package/dist/scopes/index.js +336 -64
  85. package/dist/telemetry/index.d.ts +45 -0
  86. package/dist/telemetry/index.d.ts.map +1 -0
  87. package/dist/telemetry/index.js +39 -0
  88. package/dist/templates/charts-values/dependencies/values.yaml +2 -0
  89. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  90. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  91. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  92. package/dist/templates/inventory/inventory.template.yml +1 -3
  93. package/dist/translations/check.d.ts +21 -0
  94. package/dist/translations/check.d.ts.map +1 -0
  95. package/dist/translations/check.js +132 -0
  96. package/dist/verify/endpoints.d.ts +19 -0
  97. package/dist/verify/endpoints.d.ts.map +1 -0
  98. package/dist/verify/endpoints.js +353 -0
  99. package/dist/verify/scopes.d.ts +13 -0
  100. package/dist/verify/scopes.d.ts.map +1 -0
  101. package/dist/verify/scopes.js +131 -0
  102. package/dist/verify/upgrade.d.ts +14 -0
  103. package/dist/verify/upgrade.d.ts.map +1 -0
  104. package/dist/verify/upgrade.js +111 -0
  105. package/opencrvs-toolkit-2.1.0-rc.9a83eed.tgz +0 -0
  106. package/package.json +12 -6
  107. package/tsconfig.build.json +11 -0
  108. package/tsconfig.build.tsbuildinfo +1 -0
  109. package/tsconfig.json +3 -0
  110. package/dist/templates/inventory/production.example.yml +0 -77
  111. package/dist/templates/inventory/qa.example.yml +0 -48
  112. package/opencrvs-toolkit-2.1.0-rc.99061f0.tgz +0 -0
  113. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,353 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DEFAULT_TARGET_URL = void 0;
13
+ exports.resolveBaseUrl = resolveBaseUrl;
14
+ exports.line = line;
15
+ exports.runVerifyEndpoints = runVerifyEndpoints;
16
+ /*
17
+ * This Source Code Form is subject to the terms of the Mozilla Public
18
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
19
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
20
+ *
21
+ * OpenCRVS is also distributed under the terms of the Civil Registration
22
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
23
+ *
24
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
25
+ */
26
+ /* eslint-disable no-console */
27
+ const colors_1 = require("kleur/colors");
28
+ const REQUEST_TIMEOUT_MS = 15000;
29
+ /**
30
+ * The country config service listens on port 3040 locally. This command is
31
+ * meant to be run against that instance right after `opencrvs upgrade`, to
32
+ * confirm the upgraded config still exposes the expected endpoints and keeps
33
+ * the secured ones locked down.
34
+ */
35
+ exports.DEFAULT_TARGET_URL = 'http://localhost:3040';
36
+ /**
37
+ * Publicly-served endpoints every country config must expose. The client and
38
+ * login apps, and core services, fetch these before or without user
39
+ * authentication, so they must respond with a 2xx status.
40
+ *
41
+ * `/fonts/{filename}` is handled separately: it is public but parameterised
42
+ * with a country-specific filename we cannot know, so we probe a made-up name.
43
+ */
44
+ const REQUIRED_PUBLIC_ENDPOINTS = [
45
+ { method: 'GET', path: '/client-config.js' },
46
+ { method: 'GET', path: '/login-config.js' },
47
+ { method: 'GET', path: '/handlebars.js' },
48
+ { method: 'GET', path: '/content/client' },
49
+ { method: 'GET', path: '/content/login' },
50
+ { method: 'GET', path: '/content/map.geojson' },
51
+ { method: 'GET', path: '/content/country-logo' },
52
+ { method: 'GET', path: '/config/application' },
53
+ { method: 'GET', path: '/config/workqueues' },
54
+ { method: 'GET', path: '/config/locations' },
55
+ { method: 'GET', path: '/config/roles' },
56
+ { method: 'GET', path: '/config/events' }
57
+ ];
58
+ /** Made-up path segment used to probe parameterised routes we can't enumerate. */
59
+ const PROBE_SEGMENT = 'verify-endpoints-probe';
60
+ /**
61
+ * User-notification trigger events. Core forwards an authenticated token to
62
+ * each of these, so a country config must never process them unauthenticated.
63
+ *
64
+ * Kept in sync with `TriggerEvent` in `../commons/notification` by the
65
+ * compile-time guard below.
66
+ */
67
+ const SECURED_TRIGGER_USER_EVENTS = [
68
+ 'user-created',
69
+ 'user-updated',
70
+ 'username-reminder',
71
+ 'reset-password',
72
+ 'reset-password-by-admin',
73
+ 'password-reset-link',
74
+ 'username-reminder-link',
75
+ 'resend-invite',
76
+ '2fa',
77
+ 'all-user-notification',
78
+ 'change-phone-number',
79
+ 'change-email-address'
80
+ ];
81
+ /**
82
+ * Endpoints that must require authentication. Each must either be absent (404)
83
+ * or reject an unauthenticated request (401/403) — never process it. Paths
84
+ * with `{param}` segments use a throwaway concrete value; authentication is
85
+ * enforced before the handler ever inspects the parameters (so `/certificates`
86
+ * ids and the like do not need to be real).
87
+ */
88
+ const SECURED_ENDPOINTS = [
89
+ ...SECURED_TRIGGER_USER_EVENTS.map((event) => ({
90
+ method: 'POST',
91
+ path: `/triggers/user/${event}`
92
+ })),
93
+ { method: 'POST', path: '/trigger/telemetry' },
94
+ { method: 'GET', path: '/triggers/system/ready' },
95
+ {
96
+ method: 'GET',
97
+ path: `/certificates/${PROBE_SEGMENT}`,
98
+ label: '/certificates/{id}'
99
+ },
100
+ { method: 'GET', path: '/certificates' },
101
+ { method: 'GET', path: '/config/users' }
102
+ ];
103
+ /**
104
+ * Used only when `/config/events` cannot be fetched, so the event action
105
+ * triggers are still checked against their route patterns.
106
+ */
107
+ const FALLBACK_EVENT_TRIGGERS = [
108
+ {
109
+ method: 'POST',
110
+ path: `/trigger/events/${PROBE_SEGMENT}/actions/${PROBE_SEGMENT}`,
111
+ label: '/trigger/events/{event}/actions/{action}'
112
+ },
113
+ {
114
+ method: 'POST',
115
+ path: `/trigger/events/birth/actions/${PROBE_SEGMENT}`,
116
+ label: '/trigger/events/birth/actions/{action}'
117
+ },
118
+ {
119
+ method: 'POST',
120
+ path: `/trigger/events/death/actions/${PROBE_SEGMENT}`,
121
+ label: '/trigger/events/death/actions/{action}'
122
+ }
123
+ ];
124
+ const isSuccess = (status) => status !== 'error' && status >= 200 && status < 300;
125
+ const requiresAuthOrAbsent = (status) => status === 401 || status === 403 || status === 404;
126
+ /**
127
+ * Issues a single request and returns its HTTP status, or `'error'` when the
128
+ * request could not be completed (DNS failure, connection refused, timeout).
129
+ */
130
+ function requestStatus(url, method) {
131
+ return __awaiter(this, void 0, void 0, function* () {
132
+ const controller = new AbortController();
133
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
134
+ try {
135
+ const response = yield fetch(url, {
136
+ method,
137
+ signal: controller.signal,
138
+ // Sent without an Authorization header on purpose. A secured route
139
+ // rejects with 401/403 before ever reading the body.
140
+ headers: method === 'POST' ? { 'Content-Type': 'application/json' } : undefined,
141
+ body: method === 'POST' ? '{}' : undefined
142
+ });
143
+ return response.status;
144
+ }
145
+ catch (_a) {
146
+ return 'error';
147
+ }
148
+ finally {
149
+ clearTimeout(timer);
150
+ }
151
+ });
152
+ }
153
+ function toEventTriggerConfig(value) {
154
+ if (typeof value !== 'object' || value === null) {
155
+ return null;
156
+ }
157
+ const record = value;
158
+ if (typeof record.id !== 'string') {
159
+ return null;
160
+ }
161
+ const actions = Array.isArray(record.actions)
162
+ ? Array.from(new Set(record.actions
163
+ .map((action) => {
164
+ if (typeof action !== 'object' || action === null) {
165
+ return null;
166
+ }
167
+ const type = action.type;
168
+ return typeof type === 'string' ? type : null;
169
+ })
170
+ .filter((type) => type !== null)))
171
+ : [];
172
+ return { id: record.id, actions };
173
+ }
174
+ /**
175
+ * Fetches the event configuration so the event action triggers can be checked
176
+ * against the real event ids and action types. Returns `null` if the endpoint
177
+ * is unreachable or does not return the expected shape.
178
+ */
179
+ function fetchEventConfigs(baseUrl) {
180
+ return __awaiter(this, void 0, void 0, function* () {
181
+ const controller = new AbortController();
182
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
183
+ try {
184
+ const response = yield fetch(`${baseUrl}/config/events`, {
185
+ signal: controller.signal
186
+ });
187
+ if (!response.ok) {
188
+ return null;
189
+ }
190
+ const body = yield response.json();
191
+ if (!Array.isArray(body)) {
192
+ return null;
193
+ }
194
+ return body
195
+ .map(toEventTriggerConfig)
196
+ .filter((config) => config !== null);
197
+ }
198
+ catch (_a) {
199
+ return null;
200
+ }
201
+ finally {
202
+ clearTimeout(timer);
203
+ }
204
+ });
205
+ }
206
+ /**
207
+ * Normalises the CLI argument into a base URL. Accepts either a bare domain
208
+ * (`example.org`, assumed https) or a full URL, and strips any trailing slash.
209
+ */
210
+ function resolveBaseUrl(input) {
211
+ const withProtocol = /^https?:\/\//i.test(input) ? input : `https://${input}`;
212
+ return withProtocol.replace(/\/+$/, '');
213
+ }
214
+ function describeStatus(status) {
215
+ return status === 'error' ? 'no response' : `HTTP ${status}`;
216
+ }
217
+ function endpointLabel(check) {
218
+ var _a;
219
+ const shown = (_a = check.label) !== null && _a !== void 0 ? _a : check.path;
220
+ const suffix = check.label ? (0, colors_1.dim)(` → ${check.path}`) : '';
221
+ return `${check.method} ${shown}${suffix}`;
222
+ }
223
+ function line(ok, label, detail) {
224
+ const mark = ok ? (0, colors_1.green)('✓') : (0, colors_1.red)('✗');
225
+ return ` ${mark} ${label} ${(0, colors_1.dim)(`(${detail})`)}`;
226
+ }
227
+ function securedDetail(status) {
228
+ if (status === 401 || status === 403) {
229
+ return `${describeStatus(status)} — auth required`;
230
+ }
231
+ if (status === 404) {
232
+ return `${describeStatus(status)} — not implemented`;
233
+ }
234
+ if (status === 'error') {
235
+ return `${describeStatus(status)} — request failed`;
236
+ }
237
+ return `${describeStatus(status)} — INSECURE: ensure this endpoint requires authentication!`;
238
+ }
239
+ /**
240
+ * @returns the number of failed checks, so a caller that runs several
241
+ * verifications can report them together. Exiting is the CLI's decision.
242
+ */
243
+ function runVerifyEndpoints() {
244
+ return __awaiter(this, arguments, void 0, function* (target = exports.DEFAULT_TARGET_URL) {
245
+ const baseUrl = resolveBaseUrl(target);
246
+ console.log((0, colors_1.bold)(`Verifying country config endpoints at ${baseUrl}\n`));
247
+ let failures = 0;
248
+ console.log((0, colors_1.bold)('Required public endpoints (must respond 2xx):'));
249
+ for (const check of REQUIRED_PUBLIC_ENDPOINTS) {
250
+ const status = yield requestStatus(`${baseUrl}${check.path}`, check.method);
251
+ const ok = isSuccess(status);
252
+ if (!ok) {
253
+ failures++;
254
+ }
255
+ const detail = status === 404
256
+ ? `${describeStatus(status)} — missing`
257
+ : ok
258
+ ? describeStatus(status)
259
+ : `${describeStatus(status)} — unexpected`;
260
+ console.log(line(ok, endpointLabel(check), detail));
261
+ }
262
+ // `/fonts/{filename}` is public but the filename is country-specific and
263
+ // cannot be automated, so we probe a made-up name. A registered public route
264
+ // returns 404 (file not found) or 200 (if the name happens to exist); either
265
+ // is acceptable. 401/403 would mean the route was wrongly put behind auth.
266
+ {
267
+ const path = `/fonts/${PROBE_SEGMENT}.ttf`;
268
+ const status = yield requestStatus(`${baseUrl}${path}`, 'GET');
269
+ const ok = status === 200 || status === 404;
270
+ if (!ok) {
271
+ failures++;
272
+ }
273
+ let detail;
274
+ if (status === 404) {
275
+ detail = `${describeStatus(status)} — reachable (made-up filename)`;
276
+ }
277
+ else if (status === 200) {
278
+ detail = describeStatus(status);
279
+ }
280
+ else if (status === 401 || status === 403) {
281
+ detail = `${describeStatus(status)} — must be public`;
282
+ }
283
+ else {
284
+ detail = `${describeStatus(status)} — unexpected`;
285
+ }
286
+ console.log(line(ok, `GET /fonts/{filename}${(0, colors_1.dim)(` → ${path}`)}`, detail));
287
+ }
288
+ console.log();
289
+ console.log((0, colors_1.bold)('Secured endpoints (must be absent or require auth):'));
290
+ for (const check of SECURED_ENDPOINTS) {
291
+ const status = yield requestStatus(`${baseUrl}${check.path}`, check.method);
292
+ const ok = requiresAuthOrAbsent(status);
293
+ if (!ok) {
294
+ failures++;
295
+ }
296
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
297
+ }
298
+ console.log();
299
+ console.log((0, colors_1.bold)('Event action triggers (must be absent or require auth):'));
300
+ const events = yield fetchEventConfigs(baseUrl);
301
+ if (!events) {
302
+ console.log(' ' +
303
+ (0, colors_1.yellow)('Could not read /config/events; falling back to route-pattern checks.'));
304
+ for (const check of FALLBACK_EVENT_TRIGGERS) {
305
+ const status = yield requestStatus(`${baseUrl}${check.path}`, check.method);
306
+ const ok = requiresAuthOrAbsent(status);
307
+ if (!ok) {
308
+ failures++;
309
+ }
310
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
311
+ }
312
+ }
313
+ else if (events.length === 0) {
314
+ console.log(' ' + (0, colors_1.yellow)('No events configured.'));
315
+ }
316
+ else {
317
+ for (const event of events) {
318
+ // Fall back to a made-up action when an event declares none, so the
319
+ // route is still exercised.
320
+ const actions = event.actions.length ? event.actions : [PROBE_SEGMENT];
321
+ const failed = [];
322
+ for (const action of actions) {
323
+ const status = yield requestStatus(`${baseUrl}/trigger/events/${event.id}/actions/${action}`, 'POST');
324
+ if (!requiresAuthOrAbsent(status)) {
325
+ failed.push({ action, status });
326
+ }
327
+ }
328
+ const pattern = `POST /trigger/events/${event.id}/actions/{action}`;
329
+ if (failed.length === 0) {
330
+ console.log(line(true, pattern, `${actions.length} action(s) — all require auth`));
331
+ }
332
+ else {
333
+ for (const failure of failed) {
334
+ failures++;
335
+ console.log(line(false, `POST /trigger/events/${event.id}/actions/${failure.action}`, securedDetail(failure.status)));
336
+ }
337
+ const okCount = actions.length - failed.length;
338
+ if (okCount > 0) {
339
+ console.log(line(true, pattern, `${okCount} other action(s) require auth`));
340
+ }
341
+ }
342
+ }
343
+ }
344
+ console.log();
345
+ if (failures > 0) {
346
+ console.log((0, colors_1.red)((0, colors_1.bold)(`✗ ${failures} check(s) failed.`)) +
347
+ (0, colors_1.yellow)(' See the lines marked ✗ above.'));
348
+ return failures;
349
+ }
350
+ console.log((0, colors_1.green)((0, colors_1.bold)('✓ All endpoint checks passed.')));
351
+ return 0;
352
+ });
353
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Checks the country config assigns the scopes this release added to at least
3
+ * one role.
4
+ *
5
+ * Deliberately "at least one role" and not more: which roles should hold a
6
+ * scope is the country's own policy, and this cannot know it. Assigning a scope
7
+ * to nobody, on the other hand, is almost always an upgrade that was missed
8
+ * rather than a decision.
9
+ *
10
+ * @returns the number of failed checks.
11
+ */
12
+ export declare function runVerifyScopes(target?: string): Promise<number>;
13
+ //# sourceMappingURL=scopes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../../src/verify/scopes.ts"],"names":[],"mappings":"AAgGA;;;;;;;;;;GAUG;AACH,wBAAsB,eAAe,CACnC,MAAM,GAAE,MAA2B,GAClC,OAAO,CAAC,MAAM,CAAC,CA+CjB"}
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.runVerifyScopes = runVerifyScopes;
13
+ /*
14
+ * This Source Code Form is subject to the terms of the Mozilla Public
15
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
16
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
17
+ *
18
+ * OpenCRVS is also distributed under the terms of the Civil Registration
19
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
20
+ *
21
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
22
+ */
23
+ /* eslint-disable no-console */
24
+ const colors_1 = require("kleur/colors");
25
+ const endpoints_1 = require("./endpoints");
26
+ const REQUEST_TIMEOUT_MS = 15000;
27
+ /**
28
+ * Scopes this release added, which guard features that ship whether or not a
29
+ * country config assigns them.
30
+ *
31
+ * A missing scope is the quietest kind of upgrade miss: the country config
32
+ * compiles, the deployment comes up healthy, and the feature is simply absent
33
+ * from every role — there is no error anywhere to notice. Adding a scope here
34
+ * whenever a release introduces one is what makes it noticeable.
35
+ */
36
+ const SCOPES_ADDED_THIS_RELEASE = [
37
+ {
38
+ scope: 'record.unarchive',
39
+ guards: 'the new UNARCHIVE action. Without it no role can restore an archived record, including roles that hold record.archive.'
40
+ },
41
+ {
42
+ scope: 'location.edit',
43
+ guards: 'the location and administrative area write API (create, update, withdrawVersion).'
44
+ },
45
+ {
46
+ scope: 'integration.audit.read',
47
+ guards: "reading a system client's audit log via the integrations.audit endpoint."
48
+ }
49
+ ];
50
+ /**
51
+ * The scope type out of one encoded scope.
52
+ *
53
+ * Scopes arrive from `/config/roles` in the query-string form `encodeScope`
54
+ * produces — `type=record.unarchive`, or `type=record.read&event[]=birth` once
55
+ * options are involved — so the type has to be read out of the `type` pair
56
+ * rather than matched against the whole string.
57
+ */
58
+ function scopeType(encoded) {
59
+ for (const pair of encoded.split('&')) {
60
+ const [key, value] = pair.split('=');
61
+ if (key === 'type') {
62
+ return value;
63
+ }
64
+ }
65
+ return undefined;
66
+ }
67
+ function fetchRoles(baseUrl) {
68
+ return __awaiter(this, void 0, void 0, function* () {
69
+ try {
70
+ const response = yield fetch(`${baseUrl}/config/roles`, {
71
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
72
+ });
73
+ if (!response.ok) {
74
+ return undefined;
75
+ }
76
+ const body = yield response.json();
77
+ if (!Array.isArray(body)) {
78
+ return undefined;
79
+ }
80
+ return body.filter((role) => typeof role === 'object' &&
81
+ role !== null &&
82
+ Array.isArray(role.scopes));
83
+ }
84
+ catch (_a) {
85
+ return undefined;
86
+ }
87
+ });
88
+ }
89
+ /**
90
+ * Checks the country config assigns the scopes this release added to at least
91
+ * one role.
92
+ *
93
+ * Deliberately "at least one role" and not more: which roles should hold a
94
+ * scope is the country's own policy, and this cannot know it. Assigning a scope
95
+ * to nobody, on the other hand, is almost always an upgrade that was missed
96
+ * rather than a decision.
97
+ *
98
+ * @returns the number of failed checks.
99
+ */
100
+ function runVerifyScopes() {
101
+ return __awaiter(this, arguments, void 0, function* (target = endpoints_1.DEFAULT_TARGET_URL) {
102
+ const baseUrl = (0, endpoints_1.resolveBaseUrl)(target);
103
+ console.log((0, colors_1.bold)(`Scopes added in this release, at ${baseUrl}\n`));
104
+ const roles = yield fetchRoles(baseUrl);
105
+ if (!roles) {
106
+ console.log(' ' +
107
+ (0, colors_1.yellow)('Could not read /config/roles, so the new scopes could not be checked.'));
108
+ return 1;
109
+ }
110
+ let failures = 0;
111
+ for (const { scope, guards } of SCOPES_ADDED_THIS_RELEASE) {
112
+ const holders = roles.filter((role) => role.scopes.some((encoded) => scopeType(encoded) === scope));
113
+ if (holders.length === 0) {
114
+ failures++;
115
+ console.log((0, endpoints_1.line)(false, scope, `held by no role — guards ${guards}`));
116
+ continue;
117
+ }
118
+ const named = holders
119
+ .map((role) => role.id)
120
+ .slice(0, 3)
121
+ .join(', ');
122
+ const more = holders.length > 3 ? `, +${holders.length - 3} more` : '';
123
+ console.log((0, endpoints_1.line)(true, scope, `${holders.length} role(s)${(0, colors_1.dim)(`: ${named}${more}`)}`));
124
+ }
125
+ console.log();
126
+ if (failures === 0) {
127
+ console.log((0, colors_1.green)((0, colors_1.bold)('✓ Every scope added this release is assigned.')));
128
+ }
129
+ return failures;
130
+ });
131
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Runs every post-upgrade check there is and reports them together.
3
+ *
4
+ * The point of gathering them behind one command is that an upgrade is only
5
+ * finished when all of them pass, and an operator should not have to know which
6
+ * individual commands exist — or remember to run them — to find that out.
7
+ *
8
+ * Expects to run in the country config directory, with the upgraded country
9
+ * config running (locally by default, see `target`).
10
+ *
11
+ * @returns the total number of failed checks.
12
+ */
13
+ export declare function runVerifyUpgrade(target?: string, cwd?: string): Promise<number>;
14
+ //# sourceMappingURL=upgrade.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade.d.ts","sourceRoot":"","sources":["../../src/verify/upgrade.ts"],"names":[],"mappings":"AAuEA;;;;;;;;;;;GAWG;AACH,wBAAsB,gBAAgB,CACpC,MAAM,GAAE,MAA2B,EACnC,GAAG,GAAE,MAAsB,GAC1B,OAAO,CAAC,MAAM,CAAC,CAiDjB"}
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.runVerifyUpgrade = runVerifyUpgrade;
13
+ /*
14
+ * This Source Code Form is subject to the terms of the Mozilla Public
15
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
16
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
17
+ *
18
+ * OpenCRVS is also distributed under the terms of the Civil Registration
19
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
20
+ *
21
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
22
+ */
23
+ /* eslint-disable no-console */
24
+ const colors_1 = require("kleur/colors");
25
+ const check_1 = require("../translations/check");
26
+ const endpoints_1 = require("./endpoints");
27
+ const scopes_1 = require("./scopes");
28
+ /**
29
+ * Every message the country config declares must have a translation row, or the
30
+ * UI falls back to the English `defaultMessage`. Static, so this needs no
31
+ * running service — unlike the other two sections.
32
+ */
33
+ function verifyTranslations(cwd) {
34
+ console.log((0, colors_1.bold)('Translations\n'));
35
+ const { missing, dynamicIds } = (0, check_1.check)(cwd);
36
+ for (const file of dynamicIds) {
37
+ console.log(' ' +
38
+ (0, colors_1.yellow)(`${file} declares a message whose id is built at runtime; ids have to be hardcoded to be checked.`));
39
+ }
40
+ if (missing.length === 0) {
41
+ console.log(' ' +
42
+ (0, colors_1.green)('✓') +
43
+ ' Every message declared in src has a translation row.');
44
+ }
45
+ else {
46
+ console.log(' ' +
47
+ (0, colors_1.red)('✗') +
48
+ ` ${missing.length} message(s) declared in src have no row in src/translations/countryconfig.csv.`);
49
+ for (const { id } of missing.slice(0, 10)) {
50
+ console.log(` ${id}`);
51
+ }
52
+ if (missing.length > 10) {
53
+ console.log(` +${missing.length - 10} more`);
54
+ }
55
+ }
56
+ console.log();
57
+ return {
58
+ name: 'Translations',
59
+ failures: missing.length === 0 ? 0 : 1,
60
+ remedy: 'Run `opencrvs check-translations --write` to add the missing rows.'
61
+ };
62
+ }
63
+ /**
64
+ * Runs every post-upgrade check there is and reports them together.
65
+ *
66
+ * The point of gathering them behind one command is that an upgrade is only
67
+ * finished when all of them pass, and an operator should not have to know which
68
+ * individual commands exist — or remember to run them — to find that out.
69
+ *
70
+ * Expects to run in the country config directory, with the upgraded country
71
+ * config running (locally by default, see `target`).
72
+ *
73
+ * @returns the total number of failed checks.
74
+ */
75
+ function runVerifyUpgrade() {
76
+ return __awaiter(this, arguments, void 0, function* (target = endpoints_1.DEFAULT_TARGET_URL, cwd = process.cwd()) {
77
+ const sections = [];
78
+ sections.push(verifyTranslations(cwd));
79
+ sections.push({
80
+ name: 'Scopes added this release',
81
+ failures: yield (0, scopes_1.runVerifyScopes)(target),
82
+ remedy: 'Assign each unheld scope to the role(s) that should have it in src/data-seeding/roles/roles.ts.'
83
+ });
84
+ console.log();
85
+ sections.push({
86
+ name: 'Endpoints',
87
+ failures: yield (0, endpoints_1.runVerifyEndpoints)(target),
88
+ remedy: 'See the lines marked ✗ above. A missing public endpoint or a secured one that answers without a token both need fixing before deploying.'
89
+ });
90
+ const total = sections.reduce((sum, section) => sum + section.failures, 0);
91
+ console.log();
92
+ console.log((0, colors_1.bold)('Upgrade verification summary'));
93
+ console.log();
94
+ for (const section of sections) {
95
+ const mark = section.failures === 0 ? (0, colors_1.green)('✓') : (0, colors_1.red)('✗');
96
+ const detail = section.failures === 0 ? 'passed' : `${section.failures} problem(s)`;
97
+ console.log(` ${mark} ${section.name}: ${detail}`);
98
+ }
99
+ console.log();
100
+ if (total === 0) {
101
+ console.log((0, colors_1.green)((0, colors_1.bold)('✓ This country config looks ready to deploy.')));
102
+ return 0;
103
+ }
104
+ console.log((0, colors_1.red)((0, colors_1.bold)(`✗ ${total} problem(s) to fix before deploying:`)));
105
+ console.log();
106
+ for (const section of sections.filter((s) => s.failures > 0)) {
107
+ console.log(` ${(0, colors_1.bold)(section.name)}: ${section.remedy}`);
108
+ }
109
+ return total;
110
+ });
111
+ }