@opencrvs/toolkit 2.0.1-rc.86bd821 → 2.0.1-rc.8af24af

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.
@@ -17,8 +17,142 @@ const fs = require('fs')
17
17
 
18
18
  const COUNTRYCONFIG_REPO_URL =
19
19
  'https://github.com/opencrvs/opencrvs-countryconfig.git'
20
- const INFRASTRUCTURE_REPO_URL =
21
- 'https://github.com/opencrvs/infrastructure.git'
20
+ const INFRASTRUCTURE_REPO_URL = 'https://github.com/opencrvs/infrastructure.git'
21
+
22
+ const { version } = JSON.parse(
23
+ fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8')
24
+ )
25
+
26
+ function tagExists(repoUrl, tag) {
27
+ try {
28
+ execSync(
29
+ 'git ls-remote --exit-code --tags ' + repoUrl + ' refs/tags/' + tag,
30
+ {
31
+ stdio: 'pipe'
32
+ }
33
+ )
34
+ return true
35
+ } catch (err) {
36
+ return false
37
+ }
38
+ }
39
+
40
+ function branchExists(repoUrl, branch) {
41
+ try {
42
+ execSync(
43
+ 'git ls-remote --exit-code --heads ' + repoUrl + ' refs/heads/' + branch,
44
+ {
45
+ stdio: 'pipe'
46
+ }
47
+ )
48
+ return true
49
+ } catch (err) {
50
+ return false
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Release tags (e.g. "v2.1.0"), highest first. Delegates the version-aware
56
+ * ordering to git itself rather than hand-parsing semver, then filters down
57
+ * to strict "vX.Y.Z" tags - `--sort=-version:refname` alone still leaves in
58
+ * non-release refs (e.g. "vtesting", "v2.0.0-beta") and peeled annotated-tag
59
+ * lines ("refs/tags/v2.0.0^{}").
60
+ */
61
+ function listReleaseTags(repoUrl) {
62
+ const output = execSync(
63
+ 'git ls-remote --tags --sort=-version:refname ' + repoUrl,
64
+ { encoding: 'utf-8' }
65
+ )
66
+
67
+ return output
68
+ .split('\n')
69
+ .map((line) => line.split('\t')[1])
70
+ .filter(Boolean)
71
+ .map((ref) => ref.replace('refs/tags/', ''))
72
+ .filter((tag) => /^v\d+\.\d+\.\d+$/.test(tag))
73
+ }
74
+
75
+ /**
76
+ * The highest release tag present in *both* repositories - used as the
77
+ * fallback when the version-specific tag can't be found in one or both, so
78
+ * scaffolding still lands on a real, matched release rather than develop.
79
+ */
80
+ function getLatestCommonReleaseTag() {
81
+ const infrastructureTags = new Set(listReleaseTags(INFRASTRUCTURE_REPO_URL))
82
+ return (
83
+ listReleaseTags(COUNTRYCONFIG_REPO_URL).find((tag) =>
84
+ infrastructureTags.has(tag)
85
+ ) || null
86
+ )
87
+ }
88
+
89
+ /**
90
+ * A prerelease-shaped own version (e.g. "2.1.0-rc.f5ea803", what npm resolves
91
+ * `@next` to - a build published from every push to a branch) never has a
92
+ * matching release tag, so it's resolved as a branch instead. Its base
93
+ * version (stripped of the "-rc.<sha>" suffix) tells apart two different
94
+ * situations: an RC for a version already being stabilized on its own
95
+ * "release/X.Y.Z" branch (e.g. "2.0.1-rc.*" while a patch release is in
96
+ * progress) versus an RC for a version that hasn't been branched off yet and
97
+ * only exists on develop (e.g. "2.1.0-rc.*" while that release branch hasn't
98
+ * been cut). Scaffold from the release branch when it exists in both
99
+ * repositories, otherwise fall back to develop.
100
+ *
101
+ * Otherwise, the own "X.Y.Z" version - whether resolved via npm's `latest`
102
+ * dist-tag (bare invocation) or an explicit `@X.Y.Z` pin - scaffolds from the
103
+ * matching "vX.Y.Z" tag when it exists in both repositories. If it doesn't
104
+ * (e.g. `latest` lagging behind the repos, or a pin that predates one repo's
105
+ * tagging), fall back to the highest release tag common to both, rather than
106
+ * a mismatched pairing of one tagged repo at that version and another repo
107
+ * at a different release. Exits with an error if no matching release tag
108
+ * exists in both repositories.
109
+ */
110
+ function resolveRef() {
111
+ if (version.includes('-')) {
112
+ const releaseBranch = 'release/' + version.split('-')[0]
113
+ if (
114
+ branchExists(COUNTRYCONFIG_REPO_URL, releaseBranch) &&
115
+ branchExists(INFRASTRUCTURE_REPO_URL, releaseBranch)
116
+ ) {
117
+ return releaseBranch
118
+ }
119
+ return 'develop'
120
+ }
121
+
122
+ const tag = 'v' + version
123
+ if (
124
+ tagExists(COUNTRYCONFIG_REPO_URL, tag) &&
125
+ tagExists(INFRASTRUCTURE_REPO_URL, tag)
126
+ ) {
127
+ return tag
128
+ }
129
+
130
+ const latestCommonTag = getLatestCommonReleaseTag()
131
+ if (latestCommonTag) {
132
+ console.warn(
133
+ '\nWarning: tag "' +
134
+ tag +
135
+ '" was not found in both repositories; falling back to the latest ' +
136
+ 'available release, ' +
137
+ latestCommonTag +
138
+ '.'
139
+ )
140
+ return latestCommonTag
141
+ }
142
+
143
+ console.error(
144
+ '\nError: no matching release tag was found in both the country config and ' +
145
+ 'infrastructure repositories.'
146
+ )
147
+ process.exit(1)
148
+ }
149
+
150
+ function cloneRepository(repoUrl, ref, targetDir) {
151
+ execSync(
152
+ 'git clone --depth 1 --branch ' + ref + ' ' + repoUrl + ' ' + targetDir,
153
+ { stdio: 'inherit' }
154
+ )
155
+ }
22
156
 
23
157
  const projectName = process.argv[2]
24
158
 
@@ -33,31 +167,48 @@ const countryconfigDirName = projectName + '-countryconfig'
33
167
  const infrastructureDirName = projectName + '-infrastructure'
34
168
 
35
169
  const countryconfigTargetDir = path.resolve(process.cwd(), countryconfigDirName)
36
- const infrastructureTargetDir = path.resolve(process.cwd(), infrastructureDirName)
170
+ const infrastructureTargetDir = path.resolve(
171
+ process.cwd(),
172
+ infrastructureDirName
173
+ )
37
174
 
38
175
  if (fs.existsSync(countryconfigTargetDir)) {
39
- console.error('Error: Directory "' + countryconfigDirName + '" already exists.')
176
+ console.error(
177
+ 'Error: Directory "' + countryconfigDirName + '" already exists.'
178
+ )
40
179
  process.exit(1)
41
180
  }
42
181
 
43
182
  if (fs.existsSync(infrastructureTargetDir)) {
44
- console.error('Error: Directory "' + infrastructureDirName + '" already exists.')
183
+ console.error(
184
+ 'Error: Directory "' + infrastructureDirName + '" already exists.'
185
+ )
45
186
  process.exit(1)
46
187
  }
47
188
 
48
- console.log('\nScaffolding OpenCRVS country config in ./' + countryconfigDirName + '...\n')
189
+ const ref = resolveRef()
190
+
191
+ console.log(
192
+ '\nScaffolding OpenCRVS country config in ./' + countryconfigDirName + '...\n'
193
+ )
49
194
 
50
195
  try {
51
- execSync('git clone --depth 1 ' + COUNTRYCONFIG_REPO_URL + ' ' + countryconfigDirName, { stdio: 'inherit' })
196
+ cloneRepository(COUNTRYCONFIG_REPO_URL, ref, countryconfigDirName)
52
197
  } catch (err) {
53
198
  console.error('Failed to clone the country config repository:', err.message)
54
199
  process.exit(1)
55
200
  }
56
201
 
57
202
  try {
58
- fs.rmSync(path.join(countryconfigTargetDir, '.git'), { recursive: true, force: true })
203
+ fs.rmSync(path.join(countryconfigTargetDir, '.git'), {
204
+ recursive: true,
205
+ force: true
206
+ })
59
207
  } catch (err) {
60
- console.error('Failed to remove .git directory from country config:', err.message)
208
+ console.error(
209
+ 'Failed to remove .git directory from country config:',
210
+ err.message
211
+ )
61
212
  process.exit(1)
62
213
  }
63
214
 
@@ -72,22 +223,34 @@ if (fs.existsSync(pkgPath)) {
72
223
  process.exit(1)
73
224
  }
74
225
  } else {
75
- console.warn('Warning: No package.json found in the cloned country config repository. Project name was not updated.')
226
+ console.warn(
227
+ 'Warning: No package.json found in the cloned country config repository. Project name was not updated.'
228
+ )
76
229
  }
77
230
 
78
- console.log('\nScaffolding OpenCRVS infrastructure in ./' + infrastructureDirName + '...\n')
231
+ console.log(
232
+ '\nScaffolding OpenCRVS infrastructure in ./' +
233
+ infrastructureDirName +
234
+ '...\n'
235
+ )
79
236
 
80
237
  try {
81
- execSync('git clone --depth 1 ' + INFRASTRUCTURE_REPO_URL + ' ' + infrastructureDirName, { stdio: 'inherit' })
238
+ cloneRepository(INFRASTRUCTURE_REPO_URL, ref, infrastructureDirName)
82
239
  } catch (err) {
83
240
  console.error('Failed to clone the infrastructure repository:', err.message)
84
241
  process.exit(1)
85
242
  }
86
243
 
87
244
  try {
88
- fs.rmSync(path.join(infrastructureTargetDir, '.git'), { recursive: true, force: true })
245
+ fs.rmSync(path.join(infrastructureTargetDir, '.git'), {
246
+ recursive: true,
247
+ force: true
248
+ })
89
249
  } catch (err) {
90
- console.error('Failed to remove .git directory from infrastructure:', err.message)
250
+ console.error(
251
+ 'Failed to remove .git directory from infrastructure:',
252
+ err.message
253
+ )
91
254
  process.exit(1)
92
255
  }
93
256
 
package/dist/cli.js CHANGED
@@ -3253,7 +3253,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
3253
3253
  console.warn(
3254
3254
  `
3255
3255
  WARNING: Some '${FHIR_IMPORT}' usages remain and need manual cleanup:
3256
- ` + warnings.map((line) => ` - ${line}`).join("\n")
3256
+ ` + warnings.map((line2) => ` - ${line2}`).join("\n")
3257
3257
  );
3258
3258
  }
3259
3259
  console.log(
@@ -3355,12 +3355,12 @@ function processFile11(sourceFile) {
3355
3355
  }
3356
3356
  if (inRewrittenAncestor) continue;
3357
3357
  const start = fn.getStart();
3358
- const line = sourceFile.getLineAndColumnAtPos(start).line;
3358
+ const line2 = sourceFile.getLineAndColumnAtPos(start).line;
3359
3359
  const name = describeFunction(fn);
3360
3360
  if (import_ts_morph15.Node.isFunctionDeclaration(fn) || import_ts_morph15.Node.isFunctionExpression(fn) || import_ts_morph15.Node.isMethodDeclaration(fn) || import_ts_morph15.Node.isArrowFunction(fn)) {
3361
3361
  fn.setBodyText(`return ${REPLACEMENT_IDENTIFIER}`);
3362
3362
  }
3363
- rewrittenFunctions.push({ name, line });
3363
+ rewrittenFunctions.push({ name, line: line2 });
3364
3364
  rewrittenSet.add(fn);
3365
3365
  }
3366
3366
  for (const decl of importsWithTarget) {
@@ -5145,6 +5145,282 @@ async function runUpgrade(dockerSwarm) {
5145
5145
  }
5146
5146
  }
5147
5147
 
5148
+ // src/verify/endpoints.ts
5149
+ var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
5150
+ var wrap = (code) => (text) => useColor ? `\x1B[${code}m${text}\x1B[0m` : text;
5151
+ var bold = wrap(1);
5152
+ var dim = wrap(2);
5153
+ var red = wrap(31);
5154
+ var green = wrap(32);
5155
+ var yellow = wrap(33);
5156
+ var REQUEST_TIMEOUT_MS = 15e3;
5157
+ var DEFAULT_TARGET_URL = "http://localhost:3040";
5158
+ var REQUIRED_PUBLIC_ENDPOINTS = [
5159
+ { method: "GET", path: "/client-config.js" },
5160
+ { method: "GET", path: "/login-config.js" },
5161
+ { method: "GET", path: "/handlebars.js" },
5162
+ { method: "GET", path: "/content/client" },
5163
+ { method: "GET", path: "/content/login" },
5164
+ { method: "GET", path: "/content/map.geojson" },
5165
+ { method: "GET", path: "/content/country-logo" },
5166
+ { method: "GET", path: "/config/application" },
5167
+ { method: "GET", path: "/config/workqueues" },
5168
+ { method: "GET", path: "/config/locations" },
5169
+ { method: "GET", path: "/config/roles" },
5170
+ { method: "GET", path: "/config/events" }
5171
+ ];
5172
+ var PROBE_SEGMENT = "verify-endpoints-probe";
5173
+ var SECURED_TRIGGER_USER_EVENTS = [
5174
+ "user-created",
5175
+ "user-updated",
5176
+ "username-reminder",
5177
+ "reset-password",
5178
+ "reset-password-by-admin",
5179
+ "resend-invite",
5180
+ "2fa",
5181
+ "all-user-notification",
5182
+ "change-phone-number",
5183
+ "change-email-address"
5184
+ ];
5185
+ var SECURED_ENDPOINTS = [
5186
+ ...SECURED_TRIGGER_USER_EVENTS.map(
5187
+ (event) => ({
5188
+ method: "POST",
5189
+ path: `/triggers/user/${event}`
5190
+ })
5191
+ ),
5192
+ { method: "POST", path: "/trigger/telemetry" },
5193
+ { method: "GET", path: "/triggers/system/ready" },
5194
+ {
5195
+ method: "GET",
5196
+ path: `/certificates/${PROBE_SEGMENT}`,
5197
+ label: "/certificates/{id}"
5198
+ },
5199
+ { method: "GET", path: "/certificates" },
5200
+ { method: "GET", path: "/config/users" }
5201
+ ];
5202
+ var FALLBACK_EVENT_TRIGGERS = [
5203
+ {
5204
+ method: "POST",
5205
+ path: `/trigger/events/${PROBE_SEGMENT}/actions/${PROBE_SEGMENT}`,
5206
+ label: "/trigger/events/{event}/actions/{action}"
5207
+ },
5208
+ {
5209
+ method: "POST",
5210
+ path: `/trigger/events/birth/actions/${PROBE_SEGMENT}`,
5211
+ label: "/trigger/events/birth/actions/{action}"
5212
+ },
5213
+ {
5214
+ method: "POST",
5215
+ path: `/trigger/events/death/actions/${PROBE_SEGMENT}`,
5216
+ label: "/trigger/events/death/actions/{action}"
5217
+ }
5218
+ ];
5219
+ var isSuccess = (status) => status !== "error" && status >= 200 && status < 300;
5220
+ var requiresAuthOrAbsent = (status) => status === 401 || status === 403 || status === 404;
5221
+ async function requestStatus(url, method) {
5222
+ const controller = new AbortController();
5223
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
5224
+ try {
5225
+ const response = await fetch(url, {
5226
+ method,
5227
+ signal: controller.signal,
5228
+ // Sent without an Authorization header on purpose. A secured route
5229
+ // rejects with 401/403 before ever reading the body.
5230
+ headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
5231
+ body: method === "POST" ? "{}" : void 0
5232
+ });
5233
+ return response.status;
5234
+ } catch {
5235
+ return "error";
5236
+ } finally {
5237
+ clearTimeout(timer);
5238
+ }
5239
+ }
5240
+ function toEventTriggerConfig(value) {
5241
+ if (typeof value !== "object" || value === null) {
5242
+ return null;
5243
+ }
5244
+ const record = value;
5245
+ if (typeof record.id !== "string") {
5246
+ return null;
5247
+ }
5248
+ const actions = Array.isArray(record.actions) ? Array.from(
5249
+ new Set(
5250
+ record.actions.map((action) => {
5251
+ if (typeof action !== "object" || action === null) {
5252
+ return null;
5253
+ }
5254
+ const type = action.type;
5255
+ return typeof type === "string" ? type : null;
5256
+ }).filter((type) => type !== null)
5257
+ )
5258
+ ) : [];
5259
+ return { id: record.id, actions };
5260
+ }
5261
+ async function fetchEventConfigs(baseUrl) {
5262
+ const controller = new AbortController();
5263
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
5264
+ try {
5265
+ const response = await fetch(`${baseUrl}/config/events`, {
5266
+ signal: controller.signal
5267
+ });
5268
+ if (!response.ok) {
5269
+ return null;
5270
+ }
5271
+ const body = await response.json();
5272
+ if (!Array.isArray(body)) {
5273
+ return null;
5274
+ }
5275
+ return body.map(toEventTriggerConfig).filter((config) => config !== null);
5276
+ } catch {
5277
+ return null;
5278
+ } finally {
5279
+ clearTimeout(timer);
5280
+ }
5281
+ }
5282
+ function resolveBaseUrl(input) {
5283
+ const withProtocol = /^https?:\/\//i.test(input) ? input : `https://${input}`;
5284
+ return withProtocol.replace(/\/+$/, "");
5285
+ }
5286
+ function describeStatus(status) {
5287
+ return status === "error" ? "no response" : `HTTP ${status}`;
5288
+ }
5289
+ function endpointLabel(check) {
5290
+ const shown = check.label ?? check.path;
5291
+ const suffix = check.label ? dim(` \u2192 ${check.path}`) : "";
5292
+ return `${check.method} ${shown}${suffix}`;
5293
+ }
5294
+ function line(ok, label, detail) {
5295
+ const mark = ok ? green("\u2713") : red("\u2717");
5296
+ return ` ${mark} ${label} ${dim(`(${detail})`)}`;
5297
+ }
5298
+ function securedDetail(status) {
5299
+ if (status === 401 || status === 403) {
5300
+ return `${describeStatus(status)} \u2014 auth required`;
5301
+ }
5302
+ if (status === 404) {
5303
+ return `${describeStatus(status)} \u2014 not implemented`;
5304
+ }
5305
+ if (status === "error") {
5306
+ return `${describeStatus(status)} \u2014 request failed`;
5307
+ }
5308
+ return `${describeStatus(status)} \u2014 INSECURE: processed without a token`;
5309
+ }
5310
+ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5311
+ const baseUrl = resolveBaseUrl(target);
5312
+ console.log(bold(`Verifying country config endpoints at ${baseUrl}
5313
+ `));
5314
+ let failures = 0;
5315
+ console.log(bold("Required public endpoints (must respond 2xx):"));
5316
+ for (const check of REQUIRED_PUBLIC_ENDPOINTS) {
5317
+ const status = await requestStatus(`${baseUrl}${check.path}`, check.method);
5318
+ const ok = isSuccess(status);
5319
+ if (!ok) {
5320
+ failures++;
5321
+ }
5322
+ const detail = status === 404 ? `${describeStatus(status)} \u2014 missing` : ok ? describeStatus(status) : `${describeStatus(status)} \u2014 unexpected`;
5323
+ console.log(line(ok, endpointLabel(check), detail));
5324
+ }
5325
+ {
5326
+ const path24 = `/fonts/${PROBE_SEGMENT}.ttf`;
5327
+ const status = await requestStatus(`${baseUrl}${path24}`, "GET");
5328
+ const ok = status === 200 || status === 404;
5329
+ if (!ok) {
5330
+ failures++;
5331
+ }
5332
+ let detail;
5333
+ if (status === 404) {
5334
+ detail = `${describeStatus(status)} \u2014 reachable (made-up filename)`;
5335
+ } else if (status === 200) {
5336
+ detail = describeStatus(status);
5337
+ } else if (status === 401 || status === 403) {
5338
+ detail = `${describeStatus(status)} \u2014 must be public`;
5339
+ } else {
5340
+ detail = `${describeStatus(status)} \u2014 unexpected`;
5341
+ }
5342
+ console.log(line(ok, `GET /fonts/{filename}${dim(` \u2192 ${path24}`)}`, detail));
5343
+ }
5344
+ console.log();
5345
+ console.log(bold("Secured endpoints (must be absent or require auth):"));
5346
+ for (const check of SECURED_ENDPOINTS) {
5347
+ const status = await requestStatus(`${baseUrl}${check.path}`, check.method);
5348
+ const ok = requiresAuthOrAbsent(status);
5349
+ if (!ok) {
5350
+ failures++;
5351
+ }
5352
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
5353
+ }
5354
+ console.log();
5355
+ console.log(bold("Event action triggers (must be absent or require auth):"));
5356
+ const events = await fetchEventConfigs(baseUrl);
5357
+ if (!events) {
5358
+ console.log(
5359
+ " " + yellow(
5360
+ "Could not read /config/events; falling back to route-pattern checks."
5361
+ )
5362
+ );
5363
+ for (const check of FALLBACK_EVENT_TRIGGERS) {
5364
+ const status = await requestStatus(
5365
+ `${baseUrl}${check.path}`,
5366
+ check.method
5367
+ );
5368
+ const ok = requiresAuthOrAbsent(status);
5369
+ if (!ok) {
5370
+ failures++;
5371
+ }
5372
+ console.log(line(ok, endpointLabel(check), securedDetail(status)));
5373
+ }
5374
+ } else if (events.length === 0) {
5375
+ console.log(" " + yellow("No events configured."));
5376
+ } else {
5377
+ for (const event of events) {
5378
+ const actions = event.actions.length ? event.actions : [PROBE_SEGMENT];
5379
+ const failed = [];
5380
+ for (const action of actions) {
5381
+ const status = await requestStatus(
5382
+ `${baseUrl}/trigger/events/${event.id}/actions/${action}`,
5383
+ "POST"
5384
+ );
5385
+ if (!requiresAuthOrAbsent(status)) {
5386
+ failed.push({ action, status });
5387
+ }
5388
+ }
5389
+ const pattern = `POST /trigger/events/${event.id}/actions/{action}`;
5390
+ if (failed.length === 0) {
5391
+ console.log(
5392
+ line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
5393
+ );
5394
+ } else {
5395
+ for (const failure of failed) {
5396
+ failures++;
5397
+ console.log(
5398
+ line(
5399
+ false,
5400
+ `POST /trigger/events/${event.id}/actions/${failure.action}`,
5401
+ securedDetail(failure.status)
5402
+ )
5403
+ );
5404
+ }
5405
+ const okCount = actions.length - failed.length;
5406
+ if (okCount > 0) {
5407
+ console.log(
5408
+ line(true, pattern, `${okCount} other action(s) require auth`)
5409
+ );
5410
+ }
5411
+ }
5412
+ }
5413
+ }
5414
+ console.log();
5415
+ if (failures > 0) {
5416
+ console.log(
5417
+ red(bold(`\u2717 ${failures} check(s) failed.`)) + yellow(" See the lines marked \u2717 above.")
5418
+ );
5419
+ process.exit(1);
5420
+ }
5421
+ console.log(green(bold("\u2713 All endpoint checks passed.")));
5422
+ }
5423
+
5148
5424
  // src/cli.ts
5149
5425
  var args = process.argv.slice(2);
5150
5426
  var USAGE = `
@@ -5154,9 +5430,31 @@ Commands:
5154
5430
  environment init Initialise a new environment
5155
5431
  upgrade Upgrade an existing environment
5156
5432
  check-translations Check translation files for completeness
5433
+ verify-endpoints Verify the locally-running country config exposes the
5434
+ expected endpoints and keeps secured ones locked down
5157
5435
 
5158
5436
  Run 'opencrvs <command> --help' for more information on a command.
5159
5437
  `.trim();
5438
+ var VERIFY_ENDPOINTS_USAGE = `
5439
+ Usage: opencrvs verify-endpoints [country-config-url]
5440
+
5441
+ Run this after 'opencrvs upgrade', with the upgraded country config running
5442
+ locally, to confirm it still behaves correctly. It checks over HTTP that:
5443
+ - required public endpoints exist (respond 2xx), and
5444
+ - user-notification trigger endpoints are either absent or reject
5445
+ unauthenticated requests (never processed without a token).
5446
+
5447
+ Arguments:
5448
+ [country-config-url] Optional. Domain or URL of the country config
5449
+ service. Defaults to 'http://localhost:3040', the
5450
+ port country config listens on locally. A bare
5451
+ domain is assumed to use https.
5452
+
5453
+ Options:
5454
+ -h, --help Show this message.
5455
+
5456
+ Exits with a non-zero status if any check fails.
5457
+ `.trim();
5160
5458
  var UPGRADE_USAGE = `
5161
5459
  Usage: opencrvs upgrade [options]
5162
5460
 
@@ -5183,6 +5481,8 @@ function main28() {
5183
5481
  return handleUpgrade();
5184
5482
  case "check-translations":
5185
5483
  return handleCheckTranslations();
5484
+ case "verify-endpoints":
5485
+ return handleVerifyEndpoints();
5186
5486
  default:
5187
5487
  console.error(`Unknown command: ${command}
5188
5488
  `);
@@ -5245,4 +5545,29 @@ function handleCheckTranslations() {
5245
5545
  console.warn("This command is not implemented yet!");
5246
5546
  process.exit(1);
5247
5547
  }
5548
+ async function handleVerifyEndpoints() {
5549
+ const verifyArgs = args.slice(1);
5550
+ if (verifyArgs.includes("--help") || verifyArgs.includes("-h")) {
5551
+ console.log(VERIFY_ENDPOINTS_USAGE);
5552
+ process.exit(0);
5553
+ }
5554
+ const positional = verifyArgs.filter((arg) => !arg.startsWith("-"));
5555
+ if (positional.length > 1) {
5556
+ console.error(
5557
+ `Unexpected extra argument(s): ${positional.slice(1).join(", ")}
5558
+ `
5559
+ );
5560
+ console.log(VERIFY_ENDPOINTS_USAGE);
5561
+ process.exit(1);
5562
+ }
5563
+ try {
5564
+ await runVerifyEndpoints(positional[0]);
5565
+ } catch (error) {
5566
+ console.error(
5567
+ "Endpoint verification failed:",
5568
+ error instanceof Error ? error.message : error
5569
+ );
5570
+ process.exit(1);
5571
+ }
5572
+ }
5248
5573
  main28();
@@ -184,12 +184,7 @@ export declare const TriggerPayload: {
184
184
  export type TriggerPayload = {
185
185
  [K in TriggerEvent]: z.infer<(typeof TriggerPayload)[K]>;
186
186
  };
187
- export declare function triggerUserEventNotification(args: {
188
- event: typeof TriggerEvent.ALL_USER_NOTIFICATION;
189
- payload: TriggerPayload[typeof TriggerEvent.ALL_USER_NOTIFICATION];
190
- countryConfigUrl: string;
191
- }): Promise<Response>;
192
- export declare function triggerUserEventNotification<T extends Exclude<TriggerEvent, typeof TriggerEvent.ALL_USER_NOTIFICATION>>(args: {
187
+ export declare function triggerUserEventNotification<T extends TriggerEvent>({ event, payload, countryConfigUrl, authHeader }: {
193
188
  event: T;
194
189
  payload: TriggerPayload[T];
195
190
  countryConfigUrl: string;
@@ -0,0 +1,2 @@
1
+ export declare function runVerifyEndpoints(target?: string): Promise<void>;
2
+ //# sourceMappingURL=endpoints.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoints.d.ts","sourceRoot":"","sources":["../../src/verify/endpoints.ts"],"names":[],"mappings":"AA2RA,wBAAsB,kBAAkB,CACtC,MAAM,GAAE,MAA2B,GAClC,OAAO,CAAC,IAAI,CAAC,CAkIf"}
@@ -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.86bd821",
3
+ "version": "2.0.1-rc.8af24af",
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"}