@opencrvs/toolkit 2.0.1-rc.4e3cfbc → 2.0.1-rc.5248f9c

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.
@@ -0,0 +1,345 @@
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.runVerifyEndpoints = runVerifyEndpoints;
13
+ /*
14
+ * Minimal ANSI helpers, inlined rather than pulled from a colour library: the
15
+ * toolkit is published to npm and the CLI is bundled with `--packages=external`,
16
+ * so anything imported here becomes a runtime dependency country configs have
17
+ * to install. Colours are suppressed when stdout is not a TTY or NO_COLOR is
18
+ * set, so piped and CI output stays free of escape codes.
19
+ */
20
+ const useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
21
+ const wrap = (code) => (text) => useColor ? `\u001b[${code}m${text}\u001b[0m` : text;
22
+ const bold = wrap(1);
23
+ const dim = wrap(2);
24
+ const red = wrap(31);
25
+ const green = wrap(32);
26
+ const yellow = wrap(33);
27
+ const REQUEST_TIMEOUT_MS = 15000;
28
+ /**
29
+ * The country config service listens on port 3040 locally. This command is
30
+ * meant to be run against that instance right after `opencrvs upgrade`, to
31
+ * confirm the upgraded config still exposes the expected endpoints and keeps
32
+ * the secured ones locked down.
33
+ */
34
+ const DEFAULT_TARGET_URL = 'http://localhost:3040';
35
+ /**
36
+ * Publicly-served endpoints every country config must expose. The client and
37
+ * login apps, and core services, fetch these before or without user
38
+ * authentication, so they must respond with a 2xx status.
39
+ *
40
+ * `/fonts/{filename}` is handled separately: it is public but parameterised
41
+ * with a country-specific filename we cannot know, so we probe a made-up name.
42
+ */
43
+ const REQUIRED_PUBLIC_ENDPOINTS = [
44
+ { method: 'GET', path: '/client-config.js' },
45
+ { method: 'GET', path: '/login-config.js' },
46
+ { method: 'GET', path: '/handlebars.js' },
47
+ { method: 'GET', path: '/content/client' },
48
+ { method: 'GET', path: '/content/login' },
49
+ { method: 'GET', path: '/content/map.geojson' },
50
+ { method: 'GET', path: '/content/country-logo' },
51
+ { method: 'GET', path: '/config/application' },
52
+ { method: 'GET', path: '/config/workqueues' },
53
+ { method: 'GET', path: '/config/locations' },
54
+ { method: 'GET', path: '/config/roles' },
55
+ { method: 'GET', path: '/config/events' }
56
+ ];
57
+ /** Made-up path segment used to probe parameterised routes we can't enumerate. */
58
+ const PROBE_SEGMENT = 'verify-endpoints-probe';
59
+ /**
60
+ * User-notification trigger events. Core forwards an authenticated token to
61
+ * each of these, so a country config must never process them unauthenticated.
62
+ *
63
+ * Kept in sync with `TriggerEvent` in `../commons/notification` by the
64
+ * compile-time guard below.
65
+ */
66
+ const SECURED_TRIGGER_USER_EVENTS = [
67
+ 'user-created',
68
+ 'user-updated',
69
+ 'username-reminder',
70
+ 'reset-password',
71
+ 'reset-password-by-admin',
72
+ 'resend-invite',
73
+ '2fa',
74
+ 'all-user-notification',
75
+ 'change-phone-number',
76
+ 'change-email-address'
77
+ ];
78
+ /**
79
+ * Endpoints that must require authentication. Each must either be absent (404)
80
+ * or reject an unauthenticated request (401/403) — never process it. Paths
81
+ * with `{param}` segments use a throwaway concrete value; authentication is
82
+ * enforced before the handler ever inspects the parameters (so `/certificates`
83
+ * ids and the like do not need to be real).
84
+ */
85
+ const SECURED_ENDPOINTS = [
86
+ ...SECURED_TRIGGER_USER_EVENTS.map((event) => ({
87
+ method: 'POST',
88
+ path: `/triggers/user/${event}`
89
+ })),
90
+ { method: 'POST', path: '/trigger/telemetry' },
91
+ { method: 'GET', path: '/triggers/system/ready' },
92
+ {
93
+ method: 'GET',
94
+ path: `/certificates/${PROBE_SEGMENT}`,
95
+ label: '/certificates/{id}'
96
+ },
97
+ { method: 'GET', path: '/certificates' },
98
+ { method: 'GET', path: '/config/users' }
99
+ ];
100
+ /**
101
+ * Used only when `/config/events` cannot be fetched, so the event action
102
+ * triggers are still checked against their route patterns.
103
+ */
104
+ const FALLBACK_EVENT_TRIGGERS = [
105
+ {
106
+ method: 'POST',
107
+ path: `/trigger/events/${PROBE_SEGMENT}/actions/${PROBE_SEGMENT}`,
108
+ label: '/trigger/events/{event}/actions/{action}'
109
+ },
110
+ {
111
+ method: 'POST',
112
+ path: `/trigger/events/birth/actions/${PROBE_SEGMENT}`,
113
+ label: '/trigger/events/birth/actions/{action}'
114
+ },
115
+ {
116
+ method: 'POST',
117
+ path: `/trigger/events/death/actions/${PROBE_SEGMENT}`,
118
+ label: '/trigger/events/death/actions/{action}'
119
+ }
120
+ ];
121
+ const isSuccess = (status) => status !== 'error' && status >= 200 && status < 300;
122
+ const requiresAuthOrAbsent = (status) => status === 401 || status === 403 || status === 404;
123
+ /**
124
+ * Issues a single request and returns its HTTP status, or `'error'` when the
125
+ * request could not be completed (DNS failure, connection refused, timeout).
126
+ */
127
+ function requestStatus(url, method) {
128
+ return __awaiter(this, void 0, void 0, function* () {
129
+ const controller = new AbortController();
130
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
131
+ try {
132
+ const response = yield fetch(url, {
133
+ method,
134
+ signal: controller.signal,
135
+ // Sent without an Authorization header on purpose. A secured route
136
+ // rejects with 401/403 before ever reading the body.
137
+ headers: method === 'POST' ? { 'Content-Type': 'application/json' } : undefined,
138
+ body: method === 'POST' ? '{}' : undefined
139
+ });
140
+ return response.status;
141
+ }
142
+ catch (_a) {
143
+ return 'error';
144
+ }
145
+ finally {
146
+ clearTimeout(timer);
147
+ }
148
+ });
149
+ }
150
+ function toEventTriggerConfig(value) {
151
+ if (typeof value !== 'object' || value === null) {
152
+ return null;
153
+ }
154
+ const record = value;
155
+ if (typeof record.id !== 'string') {
156
+ return null;
157
+ }
158
+ const actions = Array.isArray(record.actions)
159
+ ? Array.from(new Set(record.actions
160
+ .map((action) => {
161
+ if (typeof action !== 'object' || action === null) {
162
+ return null;
163
+ }
164
+ const type = action.type;
165
+ return typeof type === 'string' ? type : null;
166
+ })
167
+ .filter((type) => type !== null)))
168
+ : [];
169
+ return { id: record.id, actions };
170
+ }
171
+ /**
172
+ * Fetches the event configuration so the event action triggers can be checked
173
+ * against the real event ids and action types. Returns `null` if the endpoint
174
+ * is unreachable or does not return the expected shape.
175
+ */
176
+ function fetchEventConfigs(baseUrl) {
177
+ return __awaiter(this, void 0, void 0, function* () {
178
+ const controller = new AbortController();
179
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
180
+ try {
181
+ const response = yield fetch(`${baseUrl}/config/events`, {
182
+ signal: controller.signal
183
+ });
184
+ if (!response.ok) {
185
+ return null;
186
+ }
187
+ const body = yield response.json();
188
+ if (!Array.isArray(body)) {
189
+ return null;
190
+ }
191
+ return body
192
+ .map(toEventTriggerConfig)
193
+ .filter((config) => config !== null);
194
+ }
195
+ catch (_a) {
196
+ return null;
197
+ }
198
+ finally {
199
+ clearTimeout(timer);
200
+ }
201
+ });
202
+ }
203
+ /**
204
+ * Normalises the CLI argument into a base URL. Accepts either a bare domain
205
+ * (`example.org`, assumed https) or a full URL, and strips any trailing slash.
206
+ */
207
+ function resolveBaseUrl(input) {
208
+ const withProtocol = /^https?:\/\//i.test(input) ? input : `https://${input}`;
209
+ return withProtocol.replace(/\/+$/, '');
210
+ }
211
+ function describeStatus(status) {
212
+ return status === 'error' ? 'no response' : `HTTP ${status}`;
213
+ }
214
+ function endpointLabel(check) {
215
+ var _a;
216
+ const shown = (_a = check.label) !== null && _a !== void 0 ? _a : check.path;
217
+ const suffix = check.label ? dim(` → ${check.path}`) : '';
218
+ return `${check.method} ${shown}${suffix}`;
219
+ }
220
+ function line(ok, label, detail) {
221
+ const mark = ok ? green('✓') : red('✗');
222
+ return ` ${mark} ${label} ${dim(`(${detail})`)}`;
223
+ }
224
+ function securedDetail(status) {
225
+ if (status === 401 || status === 403) {
226
+ return `${describeStatus(status)} — auth required`;
227
+ }
228
+ if (status === 404) {
229
+ return `${describeStatus(status)} — not implemented`;
230
+ }
231
+ if (status === 'error') {
232
+ return `${describeStatus(status)} — request failed`;
233
+ }
234
+ return `${describeStatus(status)} — INSECURE: processed without a token`;
235
+ }
236
+ function runVerifyEndpoints() {
237
+ return __awaiter(this, arguments, void 0, function* (target = DEFAULT_TARGET_URL) {
238
+ const baseUrl = resolveBaseUrl(target);
239
+ console.log(bold(`Verifying country config endpoints at ${baseUrl}\n`));
240
+ let failures = 0;
241
+ console.log(bold('Required public endpoints (must respond 2xx):'));
242
+ for (const check of REQUIRED_PUBLIC_ENDPOINTS) {
243
+ const status = yield requestStatus(`${baseUrl}${check.path}`, check.method);
244
+ const ok = isSuccess(status);
245
+ if (!ok) {
246
+ failures++;
247
+ }
248
+ const detail = status === 404
249
+ ? `${describeStatus(status)} — missing`
250
+ : ok
251
+ ? describeStatus(status)
252
+ : `${describeStatus(status)} — unexpected`;
253
+ console.log(line(ok, endpointLabel(check), detail));
254
+ }
255
+ // `/fonts/{filename}` is public but the filename is country-specific and
256
+ // cannot be automated, so we probe a made-up name. A registered public route
257
+ // returns 404 (file not found) or 200 (if the name happens to exist); either
258
+ // is acceptable. 401/403 would mean the route was wrongly put behind auth.
259
+ {
260
+ const path = `/fonts/${PROBE_SEGMENT}.ttf`;
261
+ const status = yield requestStatus(`${baseUrl}${path}`, 'GET');
262
+ const ok = status === 200 || status === 404;
263
+ if (!ok) {
264
+ failures++;
265
+ }
266
+ let detail;
267
+ if (status === 404) {
268
+ detail = `${describeStatus(status)} — reachable (made-up filename)`;
269
+ }
270
+ else if (status === 200) {
271
+ detail = describeStatus(status);
272
+ }
273
+ else if (status === 401 || status === 403) {
274
+ detail = `${describeStatus(status)} — must be public`;
275
+ }
276
+ else {
277
+ detail = `${describeStatus(status)} — unexpected`;
278
+ }
279
+ console.log(line(ok, `GET /fonts/{filename}${dim(` → ${path}`)}`, detail));
280
+ }
281
+ console.log();
282
+ console.log(bold('Secured endpoints (must be absent or require auth):'));
283
+ for (const check of SECURED_ENDPOINTS) {
284
+ const status = yield requestStatus(`${baseUrl}${check.path}`, check.method);
285
+ const ok = requiresAuthOrAbsent(status);
286
+ if (!ok) {
287
+ failures++;
288
+ }
289
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
290
+ }
291
+ console.log();
292
+ console.log(bold('Event action triggers (must be absent or require auth):'));
293
+ const events = yield fetchEventConfigs(baseUrl);
294
+ if (!events) {
295
+ console.log(' ' +
296
+ yellow('Could not read /config/events; falling back to route-pattern checks.'));
297
+ for (const check of FALLBACK_EVENT_TRIGGERS) {
298
+ const status = yield requestStatus(`${baseUrl}${check.path}`, check.method);
299
+ const ok = requiresAuthOrAbsent(status);
300
+ if (!ok) {
301
+ failures++;
302
+ }
303
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
304
+ }
305
+ }
306
+ else if (events.length === 0) {
307
+ console.log(' ' + yellow('No events configured.'));
308
+ }
309
+ else {
310
+ for (const event of events) {
311
+ // Fall back to a made-up action when an event declares none, so the
312
+ // route is still exercised.
313
+ const actions = event.actions.length ? event.actions : [PROBE_SEGMENT];
314
+ const failed = [];
315
+ for (const action of actions) {
316
+ const status = yield requestStatus(`${baseUrl}/trigger/events/${event.id}/actions/${action}`, 'POST');
317
+ if (!requiresAuthOrAbsent(status)) {
318
+ failed.push({ action, status });
319
+ }
320
+ }
321
+ const pattern = `POST /trigger/events/${event.id}/actions/{action}`;
322
+ if (failed.length === 0) {
323
+ console.log(line(true, pattern, `${actions.length} action(s) — all require auth`));
324
+ }
325
+ else {
326
+ for (const failure of failed) {
327
+ failures++;
328
+ console.log(line(false, `POST /trigger/events/${event.id}/actions/${failure.action}`, securedDetail(failure.status)));
329
+ }
330
+ const okCount = actions.length - failed.length;
331
+ if (okCount > 0) {
332
+ console.log(line(true, pattern, `${okCount} other action(s) require auth`));
333
+ }
334
+ }
335
+ }
336
+ }
337
+ console.log();
338
+ if (failures > 0) {
339
+ console.log(red(bold(`✗ ${failures} check(s) failed.`)) +
340
+ yellow(' See the lines marked ✗ above.'));
341
+ process.exit(1);
342
+ }
343
+ console.log(green(bold('✓ All endpoint checks passed.')));
344
+ });
345
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opencrvs/toolkit",
3
- "version": "2.0.1-rc.4e3cfbc",
3
+ "version": "2.0.1-rc.5248f9c",
4
4
  "description": "OpenCRVS toolkit for building country configurations",
5
5
  "license": "MPL-2.0",
6
6
  "bin": {
@@ -1 +1 @@
1
- {"root":["./src/cli.ts","./src/api/index.ts","./src/application-config/index.ts","./src/conditionals/index.ts","./src/events/deduplication.ts","./src/events/index.ts","./src/migrations/v2.0/add-birth-certificate-issuance-flag.ts","./src/migrations/v2.0/add-resend-invite-notification.ts","./src/migrations/v2.0/checkout-upstream-files.ts","./src/migrations/v2.0/convert-config-files-to-ts.ts","./src/migrations/v2.0/convert-paragraph-to-heading.ts","./src/migrations/v2.0/create-events-index.ts","./src/migrations/v2.0/delete-infrastructure-directory.ts","./src/migrations/v2.0/fix-accept-requested-registration-function-type.ts","./src/migrations/v2.0/index.ts","./src/migrations/v2.0/make-built-in-validate-actions-custom.ts","./src/migrations/v2.0/merge-infrastructure-directory.ts","./src/migrations/v2.0/migrate-application-config-url.ts","./src/migrations/v2.0/migrate-scopes.ts","./src/migrations/v2.0/migrate-validated-workqueue-status-to-flag.ts","./src/migrations/v2.0/migrate-workqueue-configs.ts","./src/migrations/v2.0/remove-delete-actions.ts","./src/migrations/v2.0/remove-demo-scope.ts","./src/migrations/v2.0/remove-deprecated-imports.ts","./src/migrations/v2.0/remove-fhir-url-helpers.ts","./src/migrations/v2.0/remove-hearth-migrations.ts","./src/migrations/v2.0/remove-old-statistics-service.ts","./src/migrations/v2.0/remove-pending-certification-flag.ts","./src/migrations/v2.0/remove-review-from-register-action.ts","./src/migrations/v2.0/remove-unused-environment-variables.ts","./src/migrations/v2.0/rename-api-paths.ts","./src/migrations/v2.0/rename-location-parent-id.ts","./src/migrations/v2.0/simplify-analytics-precalculations.ts","./src/migrations/v2.0/update-package-json.ts","./src/notification/index.ts","./src/scopes/index.ts"],"version":"5.6.3"}
1
+ {"root":["./src/cli.ts","./src/api/index.ts","./src/application-config/index.ts","./src/conditionals/index.ts","./src/events/deduplication.ts","./src/events/index.ts","./src/migrations/v2.0/add-birth-certificate-issuance-flag.ts","./src/migrations/v2.0/add-resend-invite-notification.ts","./src/migrations/v2.0/checkout-upstream-files.ts","./src/migrations/v2.0/convert-config-files-to-ts.ts","./src/migrations/v2.0/convert-paragraph-to-heading.ts","./src/migrations/v2.0/create-events-index.ts","./src/migrations/v2.0/delete-infrastructure-directory.ts","./src/migrations/v2.0/fix-accept-requested-registration-function-type.ts","./src/migrations/v2.0/index.ts","./src/migrations/v2.0/make-built-in-validate-actions-custom.ts","./src/migrations/v2.0/merge-infrastructure-directory.ts","./src/migrations/v2.0/migrate-application-config-url.ts","./src/migrations/v2.0/migrate-scopes.ts","./src/migrations/v2.0/migrate-validated-workqueue-status-to-flag.ts","./src/migrations/v2.0/migrate-workqueue-configs.ts","./src/migrations/v2.0/remove-delete-actions.ts","./src/migrations/v2.0/remove-demo-scope.ts","./src/migrations/v2.0/remove-deprecated-imports.ts","./src/migrations/v2.0/remove-fhir-url-helpers.ts","./src/migrations/v2.0/remove-hearth-migrations.ts","./src/migrations/v2.0/remove-old-statistics-service.ts","./src/migrations/v2.0/remove-pending-certification-flag.ts","./src/migrations/v2.0/remove-review-from-register-action.ts","./src/migrations/v2.0/remove-unused-environment-variables.ts","./src/migrations/v2.0/rename-api-paths.ts","./src/migrations/v2.0/rename-location-parent-id.ts","./src/migrations/v2.0/simplify-analytics-precalculations.ts","./src/migrations/v2.0/update-package-json.ts","./src/notification/index.ts","./src/scopes/index.ts","./src/verify/endpoints.ts"],"version":"5.6.3"}