@opencrvs/toolkit 2.1.0-rc.99061f0 → 2.1.0-rc.9b7a167
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.
- package/build.sh +9 -1
- package/create-countryconfig/index.js +412 -59
- package/create-countryconfig/node_modules/.bin/degit +21 -0
- package/create-countryconfig/package.json +4 -1
- package/dist/application-config/index.js +341 -274
- package/dist/authentication/index.d.ts +67 -0
- package/dist/authentication/index.d.ts.map +1 -0
- package/dist/authentication/index.js +750 -0
- package/dist/cli.js +1608 -84
- package/dist/commons/api/router.d.ts +691 -76
- package/dist/commons/conditionals/conditionals.d.ts +6 -6
- package/dist/commons/conditionals/validate.d.ts +16 -5
- package/dist/commons/events/ActionDocument.d.ts +5 -11
- package/dist/commons/events/ActionInput.d.ts +4 -4
- package/dist/commons/events/ActionStatus.d.ts +14 -0
- package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -0
- package/dist/commons/events/AuditLog.d.ts +147 -0
- package/dist/commons/events/EventConfig.d.ts +3 -0
- package/dist/commons/events/EventDocument.d.ts +470 -2
- package/dist/commons/events/EventIndex.d.ts +3 -26
- package/dist/commons/events/EventMetadata.d.ts +1 -11
- package/dist/commons/events/EventStatus.d.ts +19 -0
- package/dist/commons/events/FieldConfig.d.ts +88 -53
- package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
- package/dist/commons/events/FieldValue.d.ts +2 -2
- package/dist/commons/events/Flag.d.ts +42 -0
- package/dist/commons/events/PlainDate.d.ts +8 -0
- package/dist/commons/events/SummaryConfig.d.ts +249 -0
- package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
- package/dist/commons/events/event.d.ts +12 -0
- package/dist/commons/events/index.d.ts +1 -0
- package/dist/commons/events/locationPayloads.d.ts +95 -0
- package/dist/commons/events/locations.d.ts +165 -26
- package/dist/commons/events/mocks.test.utils.d.ts +30 -0
- package/dist/commons/events/test.utils.d.ts +8 -4
- package/dist/commons/events/utils.d.ts +2 -2
- package/dist/commons/notification/UserNotifications.d.ts +28 -13
- package/dist/commons/notification/dispatch.d.ts +10 -0
- package/dist/commons/notification/index.d.ts +1 -0
- package/dist/conditionals/index.js +328 -58
- package/dist/csv.d.ts +25 -0
- package/dist/csv.d.ts.map +1 -0
- package/dist/csv.js +120 -0
- package/dist/environment/logger.d.ts +12 -3
- package/dist/environment/logger.d.ts.map +1 -1
- package/dist/environment/questions.d.ts.map +1 -1
- package/dist/environment/questions.js +20 -14
- package/dist/environment/setup-environment.js +1 -1
- package/dist/events/index.js +3688 -3293
- package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
- package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
- package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
- package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
- package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
- package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
- package/dist/migrations/v2.1/add-translations.d.ts +9 -0
- package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
- package/dist/migrations/v2.1/add-translations.js +213 -0
- package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
- package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
- package/dist/migrations/v2.1/enable-telemetry.js +438 -0
- package/dist/migrations/v2.1/index.d.ts.map +1 -1
- package/dist/migrations/v2.1/index.js +1058 -0
- package/dist/notification/index.js +1833 -1426
- package/dist/scopes/index.d.ts +327 -32
- package/dist/scopes/index.js +329 -58
- package/dist/telemetry/index.d.ts +45 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +39 -0
- package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
- package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
- package/dist/templates/charts-values/traefik/values.yaml +23 -9
- package/dist/templates/inventory/inventory.template.yml +1 -3
- package/dist/translations/check.d.ts +19 -0
- package/dist/translations/check.d.ts.map +1 -0
- package/dist/translations/check.js +127 -0
- package/dist/verify/endpoints.d.ts +2 -0
- package/dist/verify/endpoints.d.ts.map +1 -0
- package/dist/verify/endpoints.js +345 -0
- package/opencrvs-toolkit-2.1.0-rc.9b7a167.tgz +0 -0
- package/package.json +11 -5
- package/tsconfig.build.json +11 -0
- package/tsconfig.build.tsbuildinfo +1 -0
- package/tsconfig.json +3 -0
- package/dist/templates/inventory/production.example.yml +0 -77
- package/dist/templates/inventory/qa.example.yml +0 -48
- package/opencrvs-toolkit-2.1.0-rc.99061f0.tgz +0 -0
- package/tsconfig.tsbuildinfo +0 -1
|
@@ -212,7 +212,1065 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
|
|
|
212
212
|
);
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
+
// src/migrations/v2.1/add-recovery-link-notifications.ts
|
|
216
|
+
var import_ts_morph2 = require("ts-morph");
|
|
217
|
+
var import_fs2 = require("fs");
|
|
218
|
+
var import_path2 = __toESM(require("path"));
|
|
219
|
+
|
|
220
|
+
// src/csv.ts
|
|
221
|
+
var import_fs = require("fs");
|
|
222
|
+
function parseCsvLine(line) {
|
|
223
|
+
const values = [];
|
|
224
|
+
let value = "";
|
|
225
|
+
let quoted = false;
|
|
226
|
+
for (let index = 0; index < line.length; index++) {
|
|
227
|
+
const character = line[index];
|
|
228
|
+
if (quoted) {
|
|
229
|
+
if (character !== '"') {
|
|
230
|
+
value += character;
|
|
231
|
+
} else if (line[index + 1] === '"') {
|
|
232
|
+
value += '"';
|
|
233
|
+
index++;
|
|
234
|
+
} else {
|
|
235
|
+
quoted = false;
|
|
236
|
+
}
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (character === '"') {
|
|
240
|
+
quoted = true;
|
|
241
|
+
} else if (character === ",") {
|
|
242
|
+
values.push(value);
|
|
243
|
+
value = "";
|
|
244
|
+
} else {
|
|
245
|
+
value += character;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
values.push(value);
|
|
249
|
+
return values;
|
|
250
|
+
}
|
|
251
|
+
function toCsvLine(values) {
|
|
252
|
+
return values.map(
|
|
253
|
+
(value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
|
|
254
|
+
).join(",");
|
|
255
|
+
}
|
|
256
|
+
function idOf(line) {
|
|
257
|
+
const comma = line.indexOf(",");
|
|
258
|
+
return comma === -1 ? line : line.slice(0, comma);
|
|
259
|
+
}
|
|
260
|
+
function readCsvFile(path5) {
|
|
261
|
+
if (!(0, import_fs.existsSync)(path5)) {
|
|
262
|
+
return void 0;
|
|
263
|
+
}
|
|
264
|
+
const contents = (0, import_fs.readFileSync)(path5, "utf8");
|
|
265
|
+
const newline = contents.includes("\r\n") ? "\r\n" : "\n";
|
|
266
|
+
const trailingNewline = /\r?\n$/.test(contents);
|
|
267
|
+
const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
|
|
268
|
+
const body = lines.slice(1).filter((line) => line !== "");
|
|
269
|
+
return { header: lines[0], body, newline, trailingNewline };
|
|
270
|
+
}
|
|
271
|
+
function writeCsvFile(path5, file) {
|
|
272
|
+
(0, import_fs.writeFileSync)(
|
|
273
|
+
path5,
|
|
274
|
+
[file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
function addRows(file, rows) {
|
|
278
|
+
const isSorted = file.body.every(
|
|
279
|
+
(line, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line)
|
|
280
|
+
);
|
|
281
|
+
const added = [];
|
|
282
|
+
for (const row of rows) {
|
|
283
|
+
const id = idOf(row);
|
|
284
|
+
if (file.body.some((line) => idOf(line) === id)) {
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
const insertAt = isSorted ? file.body.findIndex((line) => idOf(line) > id) : -1;
|
|
288
|
+
if (insertAt === -1) {
|
|
289
|
+
file.body.push(row);
|
|
290
|
+
} else {
|
|
291
|
+
file.body.splice(insertAt, 0, row);
|
|
292
|
+
}
|
|
293
|
+
added.push(id);
|
|
294
|
+
}
|
|
295
|
+
return added;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/migrations/v2.1/add-recovery-link-notifications.ts
|
|
299
|
+
var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
|
|
300
|
+
var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
|
|
301
|
+
var HANDLER_FILE = "src/api/notification/handler.ts";
|
|
302
|
+
var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
|
|
303
|
+
var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
|
|
304
|
+
var NOTIFICATION_CSV = "src/translations/notification.csv";
|
|
305
|
+
var LOGIN_CSV = "src/translations/login.csv";
|
|
306
|
+
var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
|
|
307
|
+
var TEMPLATES_OBJECT = "templates";
|
|
308
|
+
var OTHER_TEMPLATES_OBJECT = "otherTemplates";
|
|
309
|
+
var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
|
|
310
|
+
var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
|
|
311
|
+
var ROUTES_FUNCTION = "getUserNotificationRoutes";
|
|
312
|
+
var RECOVERY_EVENTS = [
|
|
313
|
+
{
|
|
314
|
+
id: "password-reset-link",
|
|
315
|
+
constant: "PASSWORD_RESET_LINK",
|
|
316
|
+
smsTemplate: "resetPasswordLinkNotification",
|
|
317
|
+
emailSubject: "Reset your password",
|
|
318
|
+
routeDescription: "Handles notification for password reset recovery link",
|
|
319
|
+
heading: "Reset your password",
|
|
320
|
+
reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
|
|
321
|
+
linkLabel: "Reset your password"
|
|
322
|
+
},
|
|
323
|
+
{
|
|
324
|
+
id: "username-reminder-link",
|
|
325
|
+
constant: "USERNAME_REMINDER_LINK",
|
|
326
|
+
smsTemplate: "retrieveUsernameLinkNotification",
|
|
327
|
+
emailSubject: "Retrieve your username",
|
|
328
|
+
routeDescription: "Handles notification for username reminder recovery link",
|
|
329
|
+
heading: "Retrieve your username",
|
|
330
|
+
reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
|
|
331
|
+
linkLabel: "Retrieve your username"
|
|
332
|
+
}
|
|
333
|
+
];
|
|
334
|
+
var NOTIFICATION_CSV_ROWS = [
|
|
335
|
+
`resetPasswordLinkNotification,The SMS message that is sent to a user containing a self-service password reset link,{{applicationName}}: reset your password using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9initialisez votre mot de passe \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`,
|
|
336
|
+
`retrieveUsernameLinkNotification,The SMS message that is sent to a user containing a self-service username retrieval link,{{applicationName}}: retrieve your username using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9cup\xE9rez votre nom d'utilisateur \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`
|
|
337
|
+
];
|
|
338
|
+
var LOGIN_CSV_ROWS = [
|
|
339
|
+
`buttons.backToLogin,"Label used to leave a screen that is waiting on an emailed link, where logging in is not yet possible",Back to login,Retour \xE0 la connexion`,
|
|
340
|
+
`resetCredentials.recoveryInstructionsSent.body,"Body message for the recovery instructions sent page. Must not assert delivery, since the account may not exist.","If we found an account, you'll receive instructions for {forgottenItem, select, username {retrieving your username} other {resetting your password}}. The link expires in 1 hour.","Si nous trouvons un compte correspondant, vous recevrez les instructions pour {forgottenItem, select, username {r\xE9cup\xE9rer votre nom d'utilisateur} other {r\xE9initialiser votre mot de passe}}. Le lien expire dans 1 heure."`,
|
|
341
|
+
`resetCredentials.recoveryInstructionsSent.title.email,Title for the recovery instructions sent page when notifications are delivered by email,Check your email,V\xE9rifiez votre e-mail`,
|
|
342
|
+
`resetCredentials.recoveryInstructionsSent.title.phone,Title for the recovery instructions sent page when notifications are delivered by SMS,Check your phone,V\xE9rifiez votre t\xE9l\xE9phone`,
|
|
343
|
+
`resetCredentials.recoveryLinkLanding.expired.body,"Body shown when a recovery link is invalid, expired, or already used. Must not reveal whether the underlying account exists.",This link is no longer valid. Request a new one to continue.,Ce lien n'est plus valide. Veuillez en demander un nouveau pour continuer.`,
|
|
344
|
+
`resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
|
|
345
|
+
`resetCredentials.recoveryLinkLanding.expired.title,"Title shown when a recovery link is invalid, expired, or already used",This link has expired,Ce lien a expir\xE9`
|
|
346
|
+
];
|
|
347
|
+
var skipped = [];
|
|
348
|
+
function warnSkipped(message) {
|
|
349
|
+
skipped.push(message);
|
|
350
|
+
console.warn(` \u26A0\uFE0F ${message}`);
|
|
351
|
+
}
|
|
352
|
+
function findObjectLiteral(declaration) {
|
|
353
|
+
let expression = declaration?.getInitializer();
|
|
354
|
+
while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
|
|
355
|
+
expression = expression.getExpression();
|
|
356
|
+
}
|
|
357
|
+
return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
|
|
358
|
+
}
|
|
359
|
+
function hasKeyFor(obj, key, constant) {
|
|
360
|
+
const accepted = /* @__PURE__ */ new Set([
|
|
361
|
+
`[TriggerEvent.${constant}]`,
|
|
362
|
+
`['${key}']`,
|
|
363
|
+
`["${key}"]`,
|
|
364
|
+
`'${key}'`,
|
|
365
|
+
`"${key}"`,
|
|
366
|
+
key
|
|
367
|
+
]);
|
|
368
|
+
return obj.getProperties().some(
|
|
369
|
+
(property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
function renderKey(obj, key, constant) {
|
|
373
|
+
const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
|
|
374
|
+
if (names.some((name) => name.startsWith("[TriggerEvent."))) {
|
|
375
|
+
return `[TriggerEvent.${constant}]`;
|
|
376
|
+
}
|
|
377
|
+
if (names.some((name) => name.startsWith("["))) {
|
|
378
|
+
return `['${key}']`;
|
|
379
|
+
}
|
|
380
|
+
return `'${key}'`;
|
|
381
|
+
}
|
|
382
|
+
function appendEntry(sourceFile, objectName, key, valueLines) {
|
|
383
|
+
const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
|
|
384
|
+
const properties = obj?.getProperties() ?? [];
|
|
385
|
+
const lastProperty = properties[properties.length - 1];
|
|
386
|
+
if (!lastProperty) return false;
|
|
387
|
+
const indent = lastProperty.getIndentationText();
|
|
388
|
+
const entry = valueLines.map((line, index) => `${indent}${index === 0 ? `${key}: ${line}` : line}`).join("\n");
|
|
389
|
+
sourceFile.insertText(lastProperty.getEnd(), `,
|
|
390
|
+
${entry}`);
|
|
391
|
+
return true;
|
|
392
|
+
}
|
|
393
|
+
function objectHasKeyFor(sourceFile, objectName, key, constant) {
|
|
394
|
+
const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
|
|
395
|
+
return obj ? hasKeyFor(obj, key, constant) : false;
|
|
396
|
+
}
|
|
397
|
+
function renderKeyFor(sourceFile, objectName, key, constant) {
|
|
398
|
+
const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
|
|
399
|
+
return obj ? renderKey(obj, key, constant) : `'${key}'`;
|
|
400
|
+
}
|
|
401
|
+
function updateEmailTemplates(project, cwd) {
|
|
402
|
+
const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
|
|
403
|
+
if (!sourceFile) {
|
|
404
|
+
warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
|
|
408
|
+
(objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
|
|
409
|
+
);
|
|
410
|
+
if (missingObject) {
|
|
411
|
+
warnSkipped(
|
|
412
|
+
`Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
|
|
413
|
+
);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
for (const event of RECOVERY_EVENTS) {
|
|
417
|
+
if (!objectHasKeyFor(
|
|
418
|
+
sourceFile,
|
|
419
|
+
TRIGGER_VARIABLE_OBJECT,
|
|
420
|
+
event.id,
|
|
421
|
+
event.constant
|
|
422
|
+
) && appendEntry(
|
|
423
|
+
sourceFile,
|
|
424
|
+
TRIGGER_VARIABLE_OBJECT,
|
|
425
|
+
renderKeyFor(
|
|
426
|
+
sourceFile,
|
|
427
|
+
TRIGGER_VARIABLE_OBJECT,
|
|
428
|
+
event.id,
|
|
429
|
+
event.constant
|
|
430
|
+
),
|
|
431
|
+
[
|
|
432
|
+
"z.object({",
|
|
433
|
+
" firstname: z.string(),",
|
|
434
|
+
" applicationName: z.string(),",
|
|
435
|
+
" countryLogo: z.string(),",
|
|
436
|
+
" recoveryURL: z.string()",
|
|
437
|
+
"})"
|
|
438
|
+
]
|
|
439
|
+
)) {
|
|
440
|
+
console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
|
|
441
|
+
}
|
|
442
|
+
if (!objectHasKeyFor(
|
|
443
|
+
sourceFile,
|
|
444
|
+
TEMPLATES_OBJECT,
|
|
445
|
+
event.id,
|
|
446
|
+
event.constant
|
|
447
|
+
) && appendEntry(
|
|
448
|
+
sourceFile,
|
|
449
|
+
TEMPLATES_OBJECT,
|
|
450
|
+
renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
|
|
451
|
+
[
|
|
452
|
+
"{",
|
|
453
|
+
` type: '${event.id}',`,
|
|
454
|
+
` subject: '${event.emailSubject}',`,
|
|
455
|
+
` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
|
|
456
|
+
` '${event.id}'`,
|
|
457
|
+
" )",
|
|
458
|
+
"}"
|
|
459
|
+
]
|
|
460
|
+
)) {
|
|
461
|
+
console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function updateSmsService(project, cwd) {
|
|
466
|
+
const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
|
|
467
|
+
if (!sourceFile) {
|
|
468
|
+
warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
const missingObject = [
|
|
472
|
+
OTHER_TEMPLATES_OBJECT,
|
|
473
|
+
TRIGGER_TO_SMS_TEMPLATE_OBJECT
|
|
474
|
+
].find(
|
|
475
|
+
(objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
|
|
476
|
+
);
|
|
477
|
+
if (missingObject) {
|
|
478
|
+
warnSkipped(
|
|
479
|
+
`Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
|
|
480
|
+
);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
for (const event of RECOVERY_EVENTS) {
|
|
484
|
+
if (!objectHasKeyFor(
|
|
485
|
+
sourceFile,
|
|
486
|
+
OTHER_TEMPLATES_OBJECT,
|
|
487
|
+
event.smsTemplate,
|
|
488
|
+
event.smsTemplate
|
|
489
|
+
) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
|
|
490
|
+
`'${event.smsTemplate}'`
|
|
491
|
+
])) {
|
|
492
|
+
console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
|
|
493
|
+
}
|
|
494
|
+
if (!objectHasKeyFor(
|
|
495
|
+
sourceFile,
|
|
496
|
+
TRIGGER_TO_SMS_TEMPLATE_OBJECT,
|
|
497
|
+
event.id,
|
|
498
|
+
event.constant
|
|
499
|
+
) && appendEntry(
|
|
500
|
+
sourceFile,
|
|
501
|
+
TRIGGER_TO_SMS_TEMPLATE_OBJECT,
|
|
502
|
+
renderKeyFor(
|
|
503
|
+
sourceFile,
|
|
504
|
+
TRIGGER_TO_SMS_TEMPLATE_OBJECT,
|
|
505
|
+
event.id,
|
|
506
|
+
event.constant
|
|
507
|
+
),
|
|
508
|
+
[`'${event.smsTemplate}'`]
|
|
509
|
+
)) {
|
|
510
|
+
console.log(
|
|
511
|
+
` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function updateHandler(project, cwd) {
|
|
517
|
+
const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
|
|
518
|
+
if (!sourceFile) {
|
|
519
|
+
warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
|
|
523
|
+
const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
|
|
524
|
+
if (!caseBlock) {
|
|
525
|
+
warnSkipped(
|
|
526
|
+
`Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
|
|
527
|
+
);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
const missing = RECOVERY_EVENTS.filter(
|
|
531
|
+
(event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
|
|
532
|
+
);
|
|
533
|
+
if (missing.length === 0) return;
|
|
534
|
+
const existingClauses = caseBlock.getClauses();
|
|
535
|
+
if (existingClauses.length === 0) {
|
|
536
|
+
warnSkipped(
|
|
537
|
+
`The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
|
|
538
|
+
);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
|
|
542
|
+
const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
|
|
543
|
+
const indent = anchor.getIndentationText();
|
|
544
|
+
const lines = [
|
|
545
|
+
...missing.map((event) => `case TriggerEvent.${event.constant}:`),
|
|
546
|
+
` return {`,
|
|
547
|
+
` firstname,`,
|
|
548
|
+
` applicationName: applicationConfig.APPLICATION_NAME,`,
|
|
549
|
+
` countryLogo: COUNTRY_LOGO_URL,`,
|
|
550
|
+
` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
|
|
551
|
+
` }`
|
|
552
|
+
];
|
|
553
|
+
if (defaultClause) {
|
|
554
|
+
caseBlock.insertText(
|
|
555
|
+
anchor.getStart(),
|
|
556
|
+
`${lines.map((line, index) => index === 0 ? line : `${indent}${line}`).join("\n")}
|
|
557
|
+
${indent}`
|
|
558
|
+
);
|
|
559
|
+
} else {
|
|
560
|
+
caseBlock.insertText(
|
|
561
|
+
anchor.getEnd(),
|
|
562
|
+
`
|
|
563
|
+
${lines.map((line) => `${indent}${line}`).join("\n")}`
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
for (const event of missing) {
|
|
567
|
+
console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function updateRoutes(project, cwd) {
|
|
571
|
+
const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
|
|
572
|
+
if (!sourceFile) {
|
|
573
|
+
warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
|
|
577
|
+
const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
|
|
578
|
+
if (!routesArray) {
|
|
579
|
+
warnSkipped(
|
|
580
|
+
`Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
|
|
581
|
+
);
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
for (const event of RECOVERY_EVENTS) {
|
|
585
|
+
if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
|
|
586
|
+
routesArray.addElement(`{
|
|
587
|
+
method: 'POST',
|
|
588
|
+
path: '/triggers/user/${event.id}',
|
|
589
|
+
handler: makeNotificationHandler('${event.id}'),
|
|
590
|
+
options: {
|
|
591
|
+
auth: false,
|
|
592
|
+
tags: ['api'],
|
|
593
|
+
description: '${event.routeDescription}'
|
|
594
|
+
}
|
|
595
|
+
}`);
|
|
596
|
+
console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function renderEmailTemplate(event) {
|
|
600
|
+
return `<!--
|
|
601
|
+
This Source Code Form is subject to the terms of the Mozilla Public
|
|
602
|
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
603
|
+
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
604
|
+
|
|
605
|
+
OpenCRVS is also distributed under the terms of the Civil Registration
|
|
606
|
+
& Healthcare Disclaimer located at http://opencrvs.org/license.
|
|
607
|
+
|
|
608
|
+
Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
|
|
609
|
+
-->
|
|
610
|
+
<!doctype html>
|
|
611
|
+
<html>
|
|
612
|
+
<head>
|
|
613
|
+
<link
|
|
614
|
+
href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
|
|
615
|
+
rel="stylesheet"
|
|
616
|
+
/>
|
|
617
|
+
<style type="text/css">
|
|
618
|
+
body {
|
|
619
|
+
font-family: 'Noto Sans', sans-serif;
|
|
620
|
+
color: #222;
|
|
621
|
+
padding: 16px 24px;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
h1 {
|
|
625
|
+
font-size: 21px;
|
|
626
|
+
margin-top: 32px;
|
|
627
|
+
margin-bottom: 36px;
|
|
628
|
+
font-weight: 700;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
p {
|
|
632
|
+
font-weight: 400;
|
|
633
|
+
font-size: 16px;
|
|
634
|
+
line-height: 1.8;
|
|
635
|
+
margin-bottom: 24px;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
i {
|
|
639
|
+
color: #666;
|
|
640
|
+
font-weight: 400;
|
|
641
|
+
font-size: 16px;
|
|
642
|
+
}
|
|
643
|
+
</style>
|
|
644
|
+
</head>
|
|
645
|
+
|
|
646
|
+
<body>
|
|
647
|
+
<img
|
|
648
|
+
src="{{countryLogo}}"
|
|
649
|
+
alt="country_logo"
|
|
650
|
+
style="max-height: 88px; max-width: 100%"
|
|
651
|
+
/>
|
|
652
|
+
<h1>${event.heading}</h1>
|
|
653
|
+
<p>Hello {{firstname}},</p>
|
|
654
|
+
<p>
|
|
655
|
+
${event.reason}
|
|
656
|
+
</p>
|
|
657
|
+
|
|
658
|
+
<div style="margin-top: 32px; margin-bottom: 32px">
|
|
659
|
+
<a href="{{{recoveryURL}}}">${event.linkLabel}</a>
|
|
660
|
+
</div>
|
|
661
|
+
<br />
|
|
662
|
+
<p>
|
|
663
|
+
This link expires in 1 hour and can only be used once. If you did not
|
|
664
|
+
request this, you can ignore this email.
|
|
665
|
+
</p>
|
|
666
|
+
<br />
|
|
667
|
+
<p>
|
|
668
|
+
Best regards, <br />
|
|
669
|
+
{{applicationName}} Team
|
|
670
|
+
</p>
|
|
671
|
+
</body>
|
|
672
|
+
</html>
|
|
673
|
+
`;
|
|
674
|
+
}
|
|
675
|
+
function writeEmailTemplates(cwd) {
|
|
676
|
+
const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
|
|
677
|
+
if (!(0, import_fs2.existsSync)(templateDir)) {
|
|
678
|
+
warnSkipped(
|
|
679
|
+
`${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
|
|
680
|
+
);
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
for (const event of RECOVERY_EVENTS) {
|
|
684
|
+
const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
|
|
685
|
+
if ((0, import_fs2.existsSync)(templatePath)) continue;
|
|
686
|
+
(0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
|
|
687
|
+
console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function addCsvRows(cwd, relativePath, rows) {
|
|
691
|
+
const csvPath = import_path2.default.join(cwd, relativePath);
|
|
692
|
+
const file = readCsvFile(csvPath);
|
|
693
|
+
if (!file) {
|
|
694
|
+
warnSkipped(`${relativePath} not found; translations not added`);
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
const added = addRows(file, rows);
|
|
698
|
+
if (added.length === 0) return;
|
|
699
|
+
for (const id of added) {
|
|
700
|
+
console.log(` \u2713 ${relativePath}: ${id}`);
|
|
701
|
+
}
|
|
702
|
+
writeCsvFile(csvPath, file);
|
|
703
|
+
}
|
|
704
|
+
async function main2() {
|
|
705
|
+
const cwd = process.cwd();
|
|
706
|
+
const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
|
|
707
|
+
console.log(
|
|
708
|
+
"Registering the password-reset-link and username-reminder-link notifications...\n"
|
|
709
|
+
);
|
|
710
|
+
if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
|
|
711
|
+
warnSkipped(
|
|
712
|
+
`tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
|
|
713
|
+
);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
const project = new import_ts_morph2.Project({
|
|
717
|
+
tsConfigFilePath,
|
|
718
|
+
skipAddingFilesFromTsConfig: false,
|
|
719
|
+
// ts-morph indents inserted code with four spaces by default, which every
|
|
720
|
+
// country config's prettier run would immediately undo.
|
|
721
|
+
manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
|
|
722
|
+
});
|
|
723
|
+
updateEmailTemplates(project, cwd);
|
|
724
|
+
updateSmsService(project, cwd);
|
|
725
|
+
updateHandler(project, cwd);
|
|
726
|
+
updateRoutes(project, cwd);
|
|
727
|
+
await project.save();
|
|
728
|
+
writeEmailTemplates(cwd);
|
|
729
|
+
addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
|
|
730
|
+
addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
|
|
731
|
+
if (skipped.length > 0) {
|
|
732
|
+
console.warn(
|
|
733
|
+
`
|
|
734
|
+
\u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
|
|
735
|
+
);
|
|
736
|
+
for (const message of skipped) {
|
|
737
|
+
console.warn(` - ${message}`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// src/migrations/v2.1/add-translations.ts
|
|
743
|
+
var import_path3 = __toESM(require("path"));
|
|
744
|
+
var REPOSITORY = "opencrvs/opencrvs-core";
|
|
745
|
+
var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
|
|
746
|
+
var APPLICATIONS = ["client", "login"];
|
|
747
|
+
var TARGET_VERSION = "2.1";
|
|
748
|
+
var skipped2 = [];
|
|
749
|
+
function warnSkipped2(message) {
|
|
750
|
+
skipped2.push(message);
|
|
751
|
+
console.warn(` \u26A0\uFE0F ${message}`);
|
|
752
|
+
}
|
|
753
|
+
async function matchingRefs(namespace, prefix) {
|
|
754
|
+
const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
|
|
755
|
+
const response = await fetch(url, {
|
|
756
|
+
headers: { accept: "application/vnd.github+json" }
|
|
757
|
+
});
|
|
758
|
+
if (!response.ok) {
|
|
759
|
+
throw new Error(
|
|
760
|
+
`GitHub answered ${response.status} ${response.statusText} for ${url}`
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
const refs = await response.json();
|
|
764
|
+
const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
|
|
765
|
+
return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
|
|
766
|
+
}
|
|
767
|
+
async function candidateRefs() {
|
|
768
|
+
return [
|
|
769
|
+
...await matchingRefs("heads", `release/${TARGET_VERSION}.`),
|
|
770
|
+
...await matchingRefs("tags", `v${TARGET_VERSION}.`),
|
|
771
|
+
"develop"
|
|
772
|
+
];
|
|
773
|
+
}
|
|
774
|
+
async function fetchTemplate(refs, application) {
|
|
775
|
+
for (const ref of refs) {
|
|
776
|
+
const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
|
|
777
|
+
const response = await fetch(url);
|
|
778
|
+
if (response.ok) {
|
|
779
|
+
return { ref, contents: await response.text() };
|
|
780
|
+
}
|
|
781
|
+
if (response.status !== 404) {
|
|
782
|
+
throw new Error(
|
|
783
|
+
`GitHub answered ${response.status} ${response.statusText} for ${url}`
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
warnSkipped2(
|
|
788
|
+
`No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
|
|
789
|
+
);
|
|
790
|
+
return void 0;
|
|
791
|
+
}
|
|
792
|
+
function rowsToAdd(local, template) {
|
|
793
|
+
const localColumns = parseCsvLine(local.header);
|
|
794
|
+
const templateColumns = parseCsvLine(template.header);
|
|
795
|
+
return template.body.filter((line) => line !== "").map((line) => {
|
|
796
|
+
const values = parseCsvLine(line);
|
|
797
|
+
return toCsvLine(
|
|
798
|
+
localColumns.map((column) => {
|
|
799
|
+
const index = templateColumns.indexOf(column);
|
|
800
|
+
return index === -1 ? "" : values[index] ?? "";
|
|
801
|
+
})
|
|
802
|
+
);
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
async function updateApplication(cwd, refs, application) {
|
|
806
|
+
const relativePath = `src/translations/${application}.csv`;
|
|
807
|
+
const local = readCsvFile(import_path3.default.join(cwd, relativePath));
|
|
808
|
+
if (!local) {
|
|
809
|
+
warnSkipped2(`${relativePath} not found; translations not added`);
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const fetched = await fetchTemplate(refs, application);
|
|
813
|
+
if (!fetched) {
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const template = readTemplate(fetched.contents);
|
|
817
|
+
const added = addRows(local, rowsToAdd(local, template));
|
|
818
|
+
if (added.length === 0) {
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
try {
|
|
822
|
+
writeCsvFile(import_path3.default.join(cwd, relativePath), local);
|
|
823
|
+
} catch (error) {
|
|
824
|
+
warnSkipped2(
|
|
825
|
+
`Could not write ${relativePath} (${error.message}); translations not added`
|
|
826
|
+
);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
for (const id of added) {
|
|
830
|
+
console.log(` \u2713 ${relativePath}: ${id}`);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
function readTemplate(contents) {
|
|
834
|
+
const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
|
|
835
|
+
return {
|
|
836
|
+
header: lines[0],
|
|
837
|
+
body: lines.slice(1),
|
|
838
|
+
newline: "\n",
|
|
839
|
+
trailingNewline: true
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
async function listRefs() {
|
|
843
|
+
try {
|
|
844
|
+
return await candidateRefs();
|
|
845
|
+
} catch (error) {
|
|
846
|
+
warnSkipped2(
|
|
847
|
+
`Could not list the ${TARGET_VERSION} refs on GitHub (${error.message}); translations not added`
|
|
848
|
+
);
|
|
849
|
+
return void 0;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
async function main3() {
|
|
853
|
+
const cwd = process.cwd();
|
|
854
|
+
console.log("Adding the translation keys core gained this version...\n");
|
|
855
|
+
const refs = await listRefs();
|
|
856
|
+
if (refs) {
|
|
857
|
+
for (const application of APPLICATIONS) {
|
|
858
|
+
try {
|
|
859
|
+
await updateApplication(cwd, refs, application);
|
|
860
|
+
} catch (error) {
|
|
861
|
+
warnSkipped2(
|
|
862
|
+
`Could not read ${application}.csv from the country config template on GitHub (${error.message}); ${application}.csv not updated`
|
|
863
|
+
);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
if (skipped2.length > 0) {
|
|
868
|
+
console.warn(
|
|
869
|
+
`
|
|
870
|
+
\u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
|
|
871
|
+
);
|
|
872
|
+
for (const message of skipped2) {
|
|
873
|
+
console.warn(` - ${message}`);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// src/migrations/v2.1/enable-telemetry.ts
|
|
879
|
+
var import_ts_morph3 = require("ts-morph");
|
|
880
|
+
var import_fs3 = require("fs");
|
|
881
|
+
var import_path4 = __toESM(require("path"));
|
|
882
|
+
var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
|
|
883
|
+
var ENVIRONMENT_FILE = "src/environment.ts";
|
|
884
|
+
var INDEX_FILE = "src/index.ts";
|
|
885
|
+
var HANDLER_MODULE = "./api/telemetry/handler";
|
|
886
|
+
var skipped3 = [];
|
|
887
|
+
function warnSkipped3(message) {
|
|
888
|
+
skipped3.push(message);
|
|
889
|
+
console.warn(` \u26A0\uFE0F ${message}`);
|
|
890
|
+
}
|
|
891
|
+
var TELEMETRY_HANDLER_SOURCE = `/*
|
|
892
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
893
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
894
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
895
|
+
*
|
|
896
|
+
* OpenCRVS is also distributed under the terms of the Civil Registration
|
|
897
|
+
* & Healthcare Disclaimer located at http://opencrvs.org/license.
|
|
898
|
+
*
|
|
899
|
+
* Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
|
|
900
|
+
*/
|
|
901
|
+
|
|
902
|
+
import { Request, ResponseToolkit } from '@hapi/hapi'
|
|
903
|
+
import * as Joi from 'joi'
|
|
904
|
+
import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
|
|
905
|
+
import { env } from '@countryconfig/environment'
|
|
906
|
+
import { logger } from '@countryconfig/logger'
|
|
907
|
+
import { applicationConfig } from '@countryconfig/api/application/application-config'
|
|
908
|
+
|
|
909
|
+
/** Report the events service posts to \`/trigger/telemetry\`. */
|
|
910
|
+
export const telemetrySchema = Joi.object({
|
|
911
|
+
reported_at: Joi.string().isoDate().required(),
|
|
912
|
+
app_version: Joi.string().optional(),
|
|
913
|
+
metrics: Joi.object()
|
|
914
|
+
.pattern(
|
|
915
|
+
Joi.string(),
|
|
916
|
+
Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
|
|
917
|
+
)
|
|
918
|
+
.required()
|
|
919
|
+
})
|
|
920
|
+
|
|
921
|
+
interface IncomingReport {
|
|
922
|
+
reported_at: string
|
|
923
|
+
app_version?: string
|
|
924
|
+
metrics: Record<string, number | string | boolean>
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/** Logged once at countryconfig startup while telemetry is disabled. */
|
|
928
|
+
export const TELEMETRY_DISABLED_NOTICE =
|
|
929
|
+
'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
|
|
930
|
+
'aggregate usage metrics (registration and certificate counts, active ' +
|
|
931
|
+
'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
|
|
932
|
+
'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
|
|
933
|
+
'the countryconfig service.'
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* Receives a usage report from the events service and, when telemetry is
|
|
937
|
+
* enabled for this instance, stamps the instance identity onto it and forwards
|
|
938
|
+
* it to the status service via the toolkit's \`sendTelemetry\` (which owns the
|
|
939
|
+
* endpoint and payload schema). The events service is unaware of whether
|
|
940
|
+
* telemetry is enabled or of the country code / domain / environment reported.
|
|
941
|
+
*/
|
|
942
|
+
export async function telemetryHandler(request: Request, h: ResponseToolkit) {
|
|
943
|
+
// Only accept OpenCRVS *system* tokens (the events service's service
|
|
944
|
+
// token has userType 'system'). A logged-in user's token is a 'user' token,
|
|
945
|
+
// so a user cannot submit telemetry with their own credentials \u2014 and the
|
|
946
|
+
// service-token endpoint is not reachable through the public gateway.
|
|
947
|
+
const credentials = request.auth.credentials as
|
|
948
|
+
| { userType?: string }
|
|
949
|
+
| undefined
|
|
950
|
+
if (credentials?.userType !== 'system') {
|
|
951
|
+
logger.warn('Telemetry: rejected a request that is not from a system token')
|
|
952
|
+
return h.response({ error: 'forbidden' }).code(403)
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
if (!env.TELEMETRY_ENABLED) {
|
|
956
|
+
// The encouraging notice is logged once at startup (see index.ts); keep the
|
|
957
|
+
// per-report path quiet.
|
|
958
|
+
return h.response({ status: 'skipped' }).code(200)
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
const incoming = request.payload as IncomingReport
|
|
962
|
+
|
|
963
|
+
// Only production instances report; staging, QA and local build the report
|
|
964
|
+
// but never reach the status service. (This gate used to live in the
|
|
965
|
+
// toolkit's sendTelemetry; each country config now owns it.)
|
|
966
|
+
if (!env.isProduction) {
|
|
967
|
+
logger.info(
|
|
968
|
+
\`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
|
|
969
|
+
)
|
|
970
|
+
return h.response({ status: 'skipped' }).code(200)
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
const report: TelemetryReport = {
|
|
974
|
+
reported_at: incoming.reported_at,
|
|
975
|
+
country_code: env.COUNTRY_CODE,
|
|
976
|
+
organisation: env.ORGANISATION,
|
|
977
|
+
// env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
|
|
978
|
+
// "no domain" rather than reporting a literal "*".
|
|
979
|
+
domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
|
|
980
|
+
instance: {
|
|
981
|
+
application_name: applicationConfig.APPLICATION_NAME,
|
|
982
|
+
environment: env.ENVIRONMENT_NAME,
|
|
983
|
+
app_version: incoming.app_version
|
|
984
|
+
},
|
|
985
|
+
metrics: incoming.metrics
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
let result
|
|
989
|
+
try {
|
|
990
|
+
result = await sendTelemetry(report)
|
|
991
|
+
} catch (error) {
|
|
992
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
993
|
+
logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
|
|
994
|
+
return h.response({ status: 'error' }).code(502)
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
if (result.outcome === 'rejected') {
|
|
998
|
+
logger.error(
|
|
999
|
+
\`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
|
|
1000
|
+
)
|
|
1001
|
+
return h.response({ status: 'error' }).code(502)
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
logger.info(
|
|
1005
|
+
\`Telemetry: forwarded report for \${report.reported_at} to the status service\`
|
|
1006
|
+
)
|
|
1007
|
+
return h.response({ status: 'forwarded' }).code(202)
|
|
1008
|
+
}
|
|
1009
|
+
`;
|
|
1010
|
+
var TELEMETRY_DISABLED = {
|
|
1011
|
+
enabled: false,
|
|
1012
|
+
countryCode: "",
|
|
1013
|
+
organisation: ""
|
|
1014
|
+
};
|
|
1015
|
+
async function promptTelemetryConfig() {
|
|
1016
|
+
if (!process.stdin.isTTY) {
|
|
1017
|
+
return TELEMETRY_DISABLED;
|
|
1018
|
+
}
|
|
1019
|
+
const { confirm, input } = await import("@inquirer/prompts");
|
|
1020
|
+
const enabled = await confirm({
|
|
1021
|
+
message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
|
|
1022
|
+
default: true
|
|
1023
|
+
});
|
|
1024
|
+
if (!enabled) {
|
|
1025
|
+
return TELEMETRY_DISABLED;
|
|
1026
|
+
}
|
|
1027
|
+
const countryCode = (await input({
|
|
1028
|
+
message: "Country code (ISO alpha-3, e.g. FAR):",
|
|
1029
|
+
validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
|
|
1030
|
+
})).trim().toUpperCase();
|
|
1031
|
+
const organisation = (await input({
|
|
1032
|
+
message: "Organisation running this instance:",
|
|
1033
|
+
validate: (value) => value.trim() !== "" || "Enter an organisation name."
|
|
1034
|
+
})).trim();
|
|
1035
|
+
return { enabled: true, countryCode, organisation };
|
|
1036
|
+
}
|
|
1037
|
+
function writeTelemetryHandler(cwd) {
|
|
1038
|
+
const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
|
|
1039
|
+
if ((0, import_fs3.existsSync)(handlerPath)) {
|
|
1040
|
+
console.log(` ${HANDLER_FILE2} already present; left unchanged`);
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
(0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
|
|
1044
|
+
(0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
|
|
1045
|
+
console.log(` \u2713 ${HANDLER_FILE2}`);
|
|
1046
|
+
}
|
|
1047
|
+
function appendProperty(sourceFile, object, name, valueLines) {
|
|
1048
|
+
const properties = object.getProperties();
|
|
1049
|
+
const lastProperty = properties[properties.length - 1];
|
|
1050
|
+
if (!lastProperty) return false;
|
|
1051
|
+
const indent = lastProperty.getIndentationText();
|
|
1052
|
+
const entry = valueLines.map((line, index) => `${indent}${index === 0 ? `${name}: ${line}` : line}`).join("\n");
|
|
1053
|
+
sourceFile.insertText(lastProperty.getEnd(), `,
|
|
1054
|
+
${entry}`);
|
|
1055
|
+
return true;
|
|
1056
|
+
}
|
|
1057
|
+
function ensureEnvalidNamedImports(sourceFile, names) {
|
|
1058
|
+
const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
|
|
1059
|
+
if (!importDeclaration) {
|
|
1060
|
+
warnSkipped3(
|
|
1061
|
+
`Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
|
|
1062
|
+
);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
const existing = new Set(
|
|
1066
|
+
importDeclaration.getNamedImports().map((named) => named.getName())
|
|
1067
|
+
);
|
|
1068
|
+
for (const name of names) {
|
|
1069
|
+
if (!existing.has(name)) {
|
|
1070
|
+
importDeclaration.addNamedImport(name);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
function getCleanEnvObject(sourceFile) {
|
|
1075
|
+
const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
|
|
1076
|
+
return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
|
|
1077
|
+
}
|
|
1078
|
+
function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
|
|
1079
|
+
const object = getCleanEnvObject(sourceFile);
|
|
1080
|
+
if (!object) return;
|
|
1081
|
+
const existing = object.getProperty(name);
|
|
1082
|
+
if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
|
|
1083
|
+
if (!update) return;
|
|
1084
|
+
const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
|
|
1085
|
+
if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
|
|
1086
|
+
const defaultProperty = options.getProperty("default");
|
|
1087
|
+
if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
|
|
1088
|
+
defaultProperty.setInitializer(defaultExpr);
|
|
1089
|
+
} else {
|
|
1090
|
+
options.insertPropertyAssignment(0, {
|
|
1091
|
+
name: "default",
|
|
1092
|
+
initializer: defaultExpr
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
|
|
1096
|
+
}
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
if (appendProperty(sourceFile, object, name, [
|
|
1100
|
+
`${kind}({`,
|
|
1101
|
+
` default: ${defaultExpr},`,
|
|
1102
|
+
` desc: ${JSON.stringify(desc)}`,
|
|
1103
|
+
"})"
|
|
1104
|
+
])) {
|
|
1105
|
+
console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
function addEnvironmentVariables(project, cwd, config) {
|
|
1109
|
+
const sourceFile = project.addSourceFileAtPathIfExists(
|
|
1110
|
+
import_path4.default.join(cwd, ENVIRONMENT_FILE)
|
|
1111
|
+
);
|
|
1112
|
+
if (!sourceFile) {
|
|
1113
|
+
warnSkipped3(
|
|
1114
|
+
`${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
|
|
1115
|
+
);
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
if (!getCleanEnvObject(sourceFile)) {
|
|
1119
|
+
warnSkipped3(
|
|
1120
|
+
`Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
|
|
1121
|
+
);
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
|
|
1125
|
+
upsertEnvVar(
|
|
1126
|
+
sourceFile,
|
|
1127
|
+
"TELEMETRY_ENABLED",
|
|
1128
|
+
"bool",
|
|
1129
|
+
config.enabled ? "true" : "false",
|
|
1130
|
+
"When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
|
|
1131
|
+
true
|
|
1132
|
+
);
|
|
1133
|
+
upsertEnvVar(
|
|
1134
|
+
sourceFile,
|
|
1135
|
+
"COUNTRY_CODE",
|
|
1136
|
+
"str",
|
|
1137
|
+
config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
|
|
1138
|
+
"ISO-style country code of this instance, reported with telemetry.",
|
|
1139
|
+
config.enabled
|
|
1140
|
+
);
|
|
1141
|
+
upsertEnvVar(
|
|
1142
|
+
sourceFile,
|
|
1143
|
+
"ORGANISATION",
|
|
1144
|
+
"str",
|
|
1145
|
+
config.enabled ? JSON.stringify(config.organisation) : `''`,
|
|
1146
|
+
"Organisation running this instance, reported with telemetry. Empty by default.",
|
|
1147
|
+
config.enabled
|
|
1148
|
+
);
|
|
1149
|
+
upsertEnvVar(
|
|
1150
|
+
sourceFile,
|
|
1151
|
+
"ENVIRONMENT_NAME",
|
|
1152
|
+
"str",
|
|
1153
|
+
`'development'`,
|
|
1154
|
+
'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
|
|
1155
|
+
false
|
|
1156
|
+
);
|
|
1157
|
+
}
|
|
1158
|
+
function wireIndex(project, cwd) {
|
|
1159
|
+
const sourceFile = project.addSourceFileAtPathIfExists(
|
|
1160
|
+
import_path4.default.join(cwd, INDEX_FILE)
|
|
1161
|
+
);
|
|
1162
|
+
if (!sourceFile) {
|
|
1163
|
+
warnSkipped3(
|
|
1164
|
+
`${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
|
|
1165
|
+
);
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
|
|
1169
|
+
sourceFile.addImportDeclaration({
|
|
1170
|
+
moduleSpecifier: HANDLER_MODULE,
|
|
1171
|
+
namedImports: [
|
|
1172
|
+
"telemetryHandler",
|
|
1173
|
+
"telemetrySchema",
|
|
1174
|
+
"TELEMETRY_DISABLED_NOTICE"
|
|
1175
|
+
]
|
|
1176
|
+
});
|
|
1177
|
+
console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
|
|
1178
|
+
}
|
|
1179
|
+
if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
|
|
1180
|
+
const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
|
|
1181
|
+
(call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
|
|
1182
|
+
).filter(
|
|
1183
|
+
(statement) => Boolean(statement)
|
|
1184
|
+
).pop();
|
|
1185
|
+
if (!lastRouteStatement) {
|
|
1186
|
+
warnSkipped3(
|
|
1187
|
+
`Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
|
|
1188
|
+
);
|
|
1189
|
+
} else {
|
|
1190
|
+
const indent = lastRouteStatement.getIndentationText();
|
|
1191
|
+
const route = [
|
|
1192
|
+
`server.route({`,
|
|
1193
|
+
` method: 'POST',`,
|
|
1194
|
+
` path: '/trigger/telemetry',`,
|
|
1195
|
+
` handler: telemetryHandler,`,
|
|
1196
|
+
` options: {`,
|
|
1197
|
+
` tags: ['api', 'triggers'],`,
|
|
1198
|
+
` validate: {`,
|
|
1199
|
+
` payload: telemetrySchema`,
|
|
1200
|
+
` },`,
|
|
1201
|
+
` description:`,
|
|
1202
|
+
` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
|
|
1203
|
+
` }`,
|
|
1204
|
+
`})`
|
|
1205
|
+
].map((line) => line ? `${indent}${line}` : line).join("\n");
|
|
1206
|
+
sourceFile.insertText(lastRouteStatement.getEnd(), `
|
|
1207
|
+
|
|
1208
|
+
${route}`);
|
|
1209
|
+
console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
|
|
1213
|
+
const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
|
|
1214
|
+
(statement) => statement.getText().includes("Server successfully started")
|
|
1215
|
+
);
|
|
1216
|
+
if (!startedLog) {
|
|
1217
|
+
warnSkipped3(
|
|
1218
|
+
`Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
|
|
1219
|
+
);
|
|
1220
|
+
} else {
|
|
1221
|
+
const indent = startedLog.getIndentationText();
|
|
1222
|
+
const notice = [
|
|
1223
|
+
`if (!env.TELEMETRY_ENABLED) {`,
|
|
1224
|
+
` logger.info(TELEMETRY_DISABLED_NOTICE)`,
|
|
1225
|
+
`}`
|
|
1226
|
+
].map((line) => line ? `${indent}${line}` : line).join("\n");
|
|
1227
|
+
sourceFile.insertText(startedLog.getEnd(), `
|
|
1228
|
+
|
|
1229
|
+
${notice}`);
|
|
1230
|
+
console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
|
|
1231
|
+
if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
|
|
1232
|
+
warnSkipped3(
|
|
1233
|
+
`The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
async function main4() {
|
|
1240
|
+
const cwd = process.cwd();
|
|
1241
|
+
const config = await promptTelemetryConfig();
|
|
1242
|
+
console.log(
|
|
1243
|
+
`
|
|
1244
|
+
Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
|
|
1245
|
+
`
|
|
1246
|
+
);
|
|
1247
|
+
writeTelemetryHandler(cwd);
|
|
1248
|
+
const project = new import_ts_morph3.Project({
|
|
1249
|
+
// ts-morph indents inserted code with four spaces and double-quotes strings
|
|
1250
|
+
// by default, both of which the country config's prettier run would undo.
|
|
1251
|
+
manipulationSettings: {
|
|
1252
|
+
indentationText: import_ts_morph3.IndentationText.TwoSpaces,
|
|
1253
|
+
quoteKind: import_ts_morph3.QuoteKind.Single
|
|
1254
|
+
}
|
|
1255
|
+
});
|
|
1256
|
+
addEnvironmentVariables(project, cwd, config);
|
|
1257
|
+
wireIndex(project, cwd);
|
|
1258
|
+
await project.save();
|
|
1259
|
+
if (skipped3.length > 0) {
|
|
1260
|
+
console.warn(
|
|
1261
|
+
`
|
|
1262
|
+
\u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
|
|
1263
|
+
);
|
|
1264
|
+
for (const message of skipped3) {
|
|
1265
|
+
console.warn(` - ${message}`);
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
|
|
215
1270
|
// src/migrations/v2.1/index.ts
|
|
216
1271
|
async function runUpgrade(dockerSwarm) {
|
|
217
1272
|
await main();
|
|
1273
|
+
await main2();
|
|
1274
|
+
await main3();
|
|
1275
|
+
await main4();
|
|
218
1276
|
}
|