@opencrvs/toolkit 2.0.0-rc.ba07891 → 2.0.0-rc.bb26ec5

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.
@@ -75,7 +75,10 @@ var ActionConditional = z.discriminatedUnion("type", [
75
75
  ShowConditional,
76
76
  // Action can be shown to the user in the list but as disabled
77
77
  EnableConditional
78
- ]);
78
+ ]).meta({
79
+ description: "Action conditional configuration",
80
+ id: "ActionConditional"
81
+ });
79
82
  var DisplayOnReviewConditional = z.object({
80
83
  type: z.literal(ConditionalType.DISPLAY_ON_REVIEW),
81
84
  conditional: Conditional
@@ -418,28 +421,20 @@ function schemaPriority(schema) {
418
421
  return idx === -1 ? 9999 : idx;
419
422
  }
420
423
  function safeUnion(schemas) {
424
+ const sortedSchemas = [...schemas].sort(
425
+ (a, b) => schemaPriority(a) - schemaPriority(b)
426
+ );
421
427
  return z7.any().superRefine((val, ctx) => {
422
- const successful = schemas.filter((s) => s.safeParse(val).success);
423
- if (successful.length === 1) {
424
- return;
425
- }
426
- if (successful.length === 0) {
427
- ctx.addIssue({
428
- code: "invalid_type",
429
- expected: "custom",
430
- message: "Value does not match any schema"
431
- });
432
- return;
433
- }
434
- successful.sort((a, b) => schemaPriority(a) - schemaPriority(b));
435
- const best = successful[0];
436
- if (!best.safeParse(val).success) {
437
- ctx.addIssue({
438
- expected: "custom",
439
- code: "invalid_type",
440
- message: "Value did not match the best schema"
441
- });
428
+ for (const schema of sortedSchemas) {
429
+ if (schema.safeParse(val).success) {
430
+ return;
431
+ }
442
432
  }
433
+ ctx.addIssue({
434
+ code: "invalid_type",
435
+ expected: "custom",
436
+ message: "Value does not match any schema"
437
+ });
443
438
  }).meta({
444
439
  description: "Value that matches exactly one of the possible schema types (TextValue, DateValue, DateRangeFieldValue). The best matching schema is chosen by priority."
445
440
  });
@@ -839,7 +834,9 @@ var ScopeType = z11.enum([
839
834
  var EncodedScope = z11.string().brand("EncodedScope");
840
835
  var DEFAULT_SCOPE_OPTIONS = {
841
836
  placeOfEvent: JurisdictionFilter.enum.all,
842
- accessLevel: JurisdictionFilter.enum.all
837
+ accessLevel: JurisdictionFilter.enum.all,
838
+ registeredIn: JurisdictionFilter.enum.all,
839
+ declaredIn: JurisdictionFilter.enum.all
843
840
  };
844
841
 
845
842
  // ../commons/src/authentication.ts
@@ -1085,6 +1082,9 @@ var FlagConfig = z14.object({
1085
1082
  "Indicates if this flag expects an action to be performed to be cleared."
1086
1083
  ),
1087
1084
  label: TranslationConfig.describe("Human readable label of the flag.")
1085
+ }).meta({
1086
+ description: "Flag configuration",
1087
+ id: "FlagConfig"
1088
1088
  });
1089
1089
  var ActionFlagConfig = z14.object({
1090
1090
  id: Flag,
@@ -1092,6 +1092,9 @@ var ActionFlagConfig = z14.object({
1092
1092
  conditional: Conditional.optional().describe(
1093
1093
  "When conditional is met, the operation is performed on the flag. If not provided, the operation is performed unconditionally."
1094
1094
  )
1095
+ }).meta({
1096
+ description: "Action flag configuration",
1097
+ id: "ActionFlagConfig"
1095
1098
  });
1096
1099
 
1097
1100
  // ../commons/src/events/EventMetadata.ts
@@ -1113,8 +1116,7 @@ var ActionCreationMetadata = z15.object({
1113
1116
  ),
1114
1117
  createdByUserType: z15.enum(["user", "system"]).nullish().describe("Whether the user is a normal user or a system."),
1115
1118
  acceptedAt: z15.iso.datetime().describe("Timestamp when the action request was accepted."),
1116
- createdByRole: z15.string().optional().describe("Role of the user at the time of action request creation."),
1117
- createdBySignature: z15.string().nullish().describe("Signature of the user who created the action request.")
1119
+ createdByRole: z15.string().optional().describe("Role of the user at the time of action request creation.")
1118
1120
  });
1119
1121
  var RegistrationCreationMetadata = ActionCreationMetadata.extend({
1120
1122
  registrationNumber: z15.string().describe(
@@ -1142,9 +1144,6 @@ var EventMetadata = z15.object({
1142
1144
  createdAtLocation: UUID.nullish().describe(
1143
1145
  "Location of the user who created the event."
1144
1146
  ),
1145
- createdBySignature: DocumentPath.nullish().describe(
1146
- "Signature of the user who created the event."
1147
- ),
1148
1147
  updatedAtLocation: UUID.nullish().describe(
1149
1148
  "Location of the user who last changed the status."
1150
1149
  ),
package/dist/cli.js CHANGED
@@ -1883,9 +1883,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1883
1883
  }
1884
1884
  return replacedCount;
1885
1885
  }
1886
- function resolveConfigChain(configObj, path23) {
1886
+ function resolveConfigChain(configObj, path24) {
1887
1887
  let current = configObj;
1888
- for (const key of path23) {
1888
+ for (const key of path24) {
1889
1889
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1890
1890
  const prop = current.getProperty(key);
1891
1891
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2120,6 +2120,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2120
2120
  var import_ts_morph11 = require("ts-morph");
2121
2121
  var import_path11 = __toESM(require("path"));
2122
2122
 
2123
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2124
+ var z4 = __toESM(require("zod/v4"));
2125
+ var import_lodash = require("lodash");
2126
+
2123
2127
  // ../commons/src/scopes.ts
2124
2128
  var z3 = __toESM(require("zod/v4"));
2125
2129
  var qs = __toESM(require("qs"));
@@ -2389,11 +2393,12 @@ var decodeScope = (query) => {
2389
2393
  };
2390
2394
  var DEFAULT_SCOPE_OPTIONS = {
2391
2395
  placeOfEvent: JurisdictionFilter.enum.all,
2392
- accessLevel: JurisdictionFilter.enum.all
2396
+ accessLevel: JurisdictionFilter.enum.all,
2397
+ registeredIn: JurisdictionFilter.enum.all,
2398
+ declaredIn: JurisdictionFilter.enum.all
2393
2399
  };
2394
2400
 
2395
2401
  // ../commons/src/scopes.deprecated.do-not-use.ts
2396
- var z4 = __toESM(require("zod/v4"));
2397
2402
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2398
2403
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2399
2404
  var SearchScope = z4.object({
@@ -2627,6 +2632,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2627
2632
  }
2628
2633
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2629
2634
  };
2635
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
2636
+ function isMergeableUserScopeType(type) {
2637
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
2638
+ }
2639
+ function decodeLegacyScope(legacy) {
2640
+ const encoded = legacyScopeToV2Scope(legacy);
2641
+ const scope = decodeScope(encoded);
2642
+ if (!scope) {
2643
+ throw new Error(
2644
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
2645
+ );
2646
+ }
2647
+ return { legacy, scope };
2648
+ }
2649
+ function groupByType(entries) {
2650
+ return entries.reduce(
2651
+ (groups, entry) => ({
2652
+ ...groups,
2653
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
2654
+ }),
2655
+ {}
2656
+ );
2657
+ }
2658
+ function deduplicateEntries(entries) {
2659
+ return entries.filter(
2660
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
2661
+ );
2662
+ }
2663
+ function mergeEntries(type, entries) {
2664
+ const optionsList = entries.map(
2665
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
2666
+ );
2667
+ const allKeys = optionsList.flatMap(
2668
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
2669
+ );
2670
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
2671
+ if (conflictKey) {
2672
+ const conflicting = entries.filter(
2673
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
2674
+ ).map((e) => JSON.stringify(e.legacy));
2675
+ throw new Error(
2676
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
2677
+ );
2678
+ }
2679
+ const mergedOptions = Object.assign({}, ...optionsList);
2680
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
2681
+ const parsed = Scope2.safeParse(merged);
2682
+ if (!parsed.success) {
2683
+ throw new Error(
2684
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
2685
+ );
2686
+ }
2687
+ return parsed.data;
2688
+ }
2689
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
2690
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
2691
+ return Object.entries(groups).flatMap(([type, entries]) => {
2692
+ const deduped = deduplicateEntries(entries);
2693
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
2694
+ if (!isMergeableUserScopeType(type)) {
2695
+ console.warn(
2696
+ `Multiple non-mergeable '${type}' scopes detected after dedup \u2014 kept all as-is. Legacy scopes: [${deduped.map((e) => JSON.stringify(e.legacy)).join(", ")}]. Review whether the duplication is intentional.`
2697
+ );
2698
+ return deduped.map((e) => e.scope);
2699
+ }
2700
+ return [mergeEntries(type, deduped)];
2701
+ });
2702
+ }
2630
2703
 
2631
2704
  // src/migrations/v2.0/migrate-scopes.ts
2632
2705
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2664,57 +2737,65 @@ function resolveLegacyScopeFromElement(element) {
2664
2737
  }
2665
2738
  function migrateScopesArrays(rolesFilePath, project) {
2666
2739
  const sourceFile = project.getSourceFile(rolesFilePath);
2667
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2740
+ if (!sourceFile) {
2741
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2742
+ }
2668
2743
  let migratedCount = 0;
2669
2744
  let removedCount = 0;
2745
+ let mergedCount = 0;
2670
2746
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2747
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2671
2748
  for (const scopesProp of scopesProperties) {
2672
2749
  const initializer = scopesProp.getInitializer();
2673
2750
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2674
- const elements = initializer.getElements();
2675
- for (let index = elements.length - 1; index >= 0; index--) {
2676
- const element = elements[index];
2677
- if (!import_ts_morph11.Node.isExpression(element)) continue;
2751
+ const rawTexts = [];
2752
+ const legacyStrings = [];
2753
+ let anyChange = false;
2754
+ for (const element of initializer.getElements()) {
2678
2755
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2679
2756
  if (scopeKey && !(scopeKey in SCOPES)) {
2680
2757
  console.warn(
2681
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2758
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2682
2759
  );
2683
- initializer.removeElement(index);
2684
2760
  removedCount++;
2761
+ anyChange = true;
2685
2762
  continue;
2686
2763
  }
2687
2764
  const legacyScope = resolveLegacyScopeFromElement(element);
2688
2765
  if (!legacyScope) {
2689
2766
  console.warn(
2690
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2767
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2691
2768
  );
2769
+ rawTexts.push(element.getText());
2692
2770
  continue;
2693
2771
  }
2694
- try {
2695
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2696
- const scope = decodeScope(migratedScope);
2697
- if (!scope) {
2698
- console.warn(
2699
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2700
- );
2701
- continue;
2702
- }
2703
- element.replaceWithText(JSON.stringify(scope));
2704
- migratedCount++;
2705
- } catch (error) {
2706
- console.warn(
2707
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2708
- );
2709
- }
2772
+ legacyStrings.push(legacyScope);
2773
+ anyChange = true;
2774
+ }
2775
+ if (!anyChange) continue;
2776
+ let mergedScopes;
2777
+ try {
2778
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
2779
+ } catch (error) {
2780
+ throw new Error(
2781
+ `[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`,
2782
+ { cause: error }
2783
+ );
2710
2784
  }
2785
+ migratedCount += legacyStrings.length;
2786
+ mergedCount += legacyStrings.length - mergedScopes.length;
2787
+ const outputElements = [
2788
+ ...rawTexts,
2789
+ ...mergedScopes.map((s) => JSON.stringify(s))
2790
+ ];
2791
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2711
2792
  }
2712
2793
  if (removedCount > 0) {
2713
2794
  console.log(
2714
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2795
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2715
2796
  );
2716
2797
  }
2717
- return { migratedCount, removedCount };
2798
+ return { migratedCount, removedCount, mergedCount };
2718
2799
  }
2719
2800
  function ensureScopesHelpersImport(rolesFilePath, project) {
2720
2801
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2849,7 +2930,7 @@ async function main11() {
2849
2930
  return;
2850
2931
  }
2851
2932
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2852
- const { migratedCount, removedCount } = migrateScopesArrays(
2933
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2853
2934
  rolesFilePath,
2854
2935
  project
2855
2936
  );
@@ -2868,7 +2949,7 @@ async function main11() {
2868
2949
  }
2869
2950
  await sourceFile.save();
2870
2951
  console.log(
2871
- `Done. Migrated ${migratedCount} legacy scope(s), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
2952
+ `Done. Migrated ${migratedCount} legacy scope(s), merged ${mergedCount} AND-paired scope(s) into single v2 objects (privilege-escalation fix, see issue #12489), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
2872
2953
  );
2873
2954
  }
2874
2955
 
@@ -4752,9 +4833,9 @@ var import_path24 = require("path");
4752
4833
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4753
4834
  var INFRASTRUCTURE_DIR = "infrastructure";
4754
4835
  var BASE_BRANCH = "release-v1.9";
4755
- function gitShowBytes(ref, path23) {
4836
+ function gitShowBytes(ref, path24) {
4756
4837
  try {
4757
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4838
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path24}`], {
4758
4839
  cwd: process.cwd(),
4759
4840
  stdio: ["ignore", "pipe", "pipe"]
4760
4841
  });
@@ -4930,6 +5011,94 @@ async function main26({
4930
5011
  );
4931
5012
  }
4932
5013
 
5014
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
5015
+ var import_ts_morph22 = require("ts-morph");
5016
+ var import_path26 = __toESM(require("path"));
5017
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
5018
+ var ACTION_PARAMETER_NAME = "action";
5019
+ var OLD_TYPE = "ActionInput";
5020
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
5021
+ function isAcceptRequestedRegistrationParameter(parameter) {
5022
+ const functionDeclaration = parameter.getFirstAncestorByKind(
5023
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
5024
+ );
5025
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
5026
+ return true;
5027
+ }
5028
+ const arrowFunction = parameter.getFirstAncestorByKind(
5029
+ import_ts_morph22.SyntaxKind.ArrowFunction
5030
+ );
5031
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
5032
+ import_ts_morph22.SyntaxKind.VariableDeclaration
5033
+ );
5034
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
5035
+ }
5036
+ function processFile14(filePath, project) {
5037
+ const sourceFile = project.getSourceFile(filePath);
5038
+ if (!sourceFile) return 0;
5039
+ let updatedCount = 0;
5040
+ for (const parameter of sourceFile.getDescendantsOfKind(
5041
+ import_ts_morph22.SyntaxKind.Parameter
5042
+ )) {
5043
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
5044
+ continue;
5045
+ }
5046
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
5047
+ continue;
5048
+ }
5049
+ const typeNode = parameter.getTypeNode();
5050
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
5051
+ continue;
5052
+ }
5053
+ parameter.setType(NEW_TYPE);
5054
+ updatedCount++;
5055
+ console.log(
5056
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
5057
+ );
5058
+ }
5059
+ return updatedCount;
5060
+ }
5061
+ async function main27() {
5062
+ const srcDir = import_path26.default.join(process.cwd(), "src");
5063
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
5064
+ `);
5065
+ const project = new import_ts_morph22.Project({
5066
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
5067
+ skipAddingFilesFromTsConfig: false
5068
+ });
5069
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
5070
+ const filePath = sf.getFilePath();
5071
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
5072
+ });
5073
+ let totalUpdated = 0;
5074
+ const modifiedFiles = [];
5075
+ for (const sourceFile of sourceFiles) {
5076
+ const filePath = sourceFile.getFilePath();
5077
+ const updated = processFile14(filePath, project);
5078
+ if (updated > 0) {
5079
+ totalUpdated += updated;
5080
+ modifiedFiles.push(filePath);
5081
+ }
5082
+ }
5083
+ if (modifiedFiles.length === 0) {
5084
+ console.log(
5085
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
5086
+ );
5087
+ return;
5088
+ }
5089
+ console.log(`
5090
+ Saving ${modifiedFiles.length} modified file(s)...`);
5091
+ for (const filePath of modifiedFiles) {
5092
+ const sourceFile = project.getSourceFileOrThrow(filePath);
5093
+ await sourceFile.save();
5094
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
5095
+ }
5096
+ console.log(
5097
+ `
5098
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
5099
+ );
5100
+ }
5101
+
4933
5102
  // src/migrations/v2.0/index.ts
4934
5103
  var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4935
5104
  async function runUpgrade(dockerSwarm) {
@@ -4956,6 +5125,7 @@ async function runUpgrade(dockerSwarm) {
4956
5125
  await main22();
4957
5126
  await main23();
4958
5127
  await main24();
5128
+ await main27();
4959
5129
  await main17();
4960
5130
  if (dockerSwarm) {
4961
5131
  await main25();
@@ -4990,7 +5160,7 @@ Options:
4990
5160
  'infrastructure/' directory is deleted (default).
4991
5161
  -h, --help Show this message.
4992
5162
  `.trim();
4993
- function main27() {
5163
+ function main28() {
4994
5164
  const command = args[0];
4995
5165
  if (!command || command === "--help" || command === "-h") {
4996
5166
  console.log(USAGE);
@@ -5065,4 +5235,4 @@ function handleCheckTranslations() {
5065
5235
  console.warn("This command is not implemented yet!");
5066
5236
  process.exit(1);
5067
5237
  }
5068
- main27();
5238
+ main28();