@opencrvs/toolkit 2.0.0-rc.fc431fe → 2.0.0-rc.fd02169

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.
@@ -2132,6 +2132,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2132
2132
  var import_ts_morph11 = require("ts-morph");
2133
2133
  var import_path11 = __toESM(require("path"));
2134
2134
 
2135
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2136
+ var z4 = __toESM(require("zod/v4"));
2137
+ var import_lodash = require("lodash");
2138
+
2135
2139
  // ../commons/src/scopes.ts
2136
2140
  var z3 = __toESM(require("zod/v4"));
2137
2141
  var qs = __toESM(require("qs"));
@@ -2405,7 +2409,6 @@ var DEFAULT_SCOPE_OPTIONS = {
2405
2409
  };
2406
2410
 
2407
2411
  // ../commons/src/scopes.deprecated.do-not-use.ts
2408
- var z4 = __toESM(require("zod/v4"));
2409
2412
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2410
2413
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2411
2414
  var SearchScope = z4.object({
@@ -2639,6 +2642,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2639
2642
  }
2640
2643
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2641
2644
  };
2645
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
2646
+ function isMergeableUserScopeType(type) {
2647
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
2648
+ }
2649
+ function decodeLegacyScope(legacy) {
2650
+ const encoded = legacyScopeToV2Scope(legacy);
2651
+ const scope = decodeScope(encoded);
2652
+ if (!scope) {
2653
+ throw new Error(
2654
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
2655
+ );
2656
+ }
2657
+ return { legacy, scope };
2658
+ }
2659
+ function groupByType(entries) {
2660
+ return entries.reduce(
2661
+ (groups, entry) => ({
2662
+ ...groups,
2663
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
2664
+ }),
2665
+ {}
2666
+ );
2667
+ }
2668
+ function deduplicateEntries(entries) {
2669
+ return entries.filter(
2670
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
2671
+ );
2672
+ }
2673
+ function mergeEntries(type, entries) {
2674
+ const optionsList = entries.map(
2675
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
2676
+ );
2677
+ const allKeys = optionsList.flatMap(
2678
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
2679
+ );
2680
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
2681
+ if (conflictKey) {
2682
+ const conflicting = entries.filter(
2683
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
2684
+ ).map((e) => JSON.stringify(e.legacy));
2685
+ throw new Error(
2686
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
2687
+ );
2688
+ }
2689
+ const mergedOptions = Object.assign({}, ...optionsList);
2690
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
2691
+ const parsed = Scope2.safeParse(merged);
2692
+ if (!parsed.success) {
2693
+ throw new Error(
2694
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
2695
+ );
2696
+ }
2697
+ return parsed.data;
2698
+ }
2699
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
2700
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
2701
+ return Object.entries(groups).flatMap(([type, entries]) => {
2702
+ const deduped = deduplicateEntries(entries);
2703
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
2704
+ if (!isMergeableUserScopeType(type)) {
2705
+ console.warn(
2706
+ `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.`
2707
+ );
2708
+ return deduped.map((e) => e.scope);
2709
+ }
2710
+ return [mergeEntries(type, deduped)];
2711
+ });
2712
+ }
2642
2713
 
2643
2714
  // src/migrations/v2.0/migrate-scopes.ts
2644
2715
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2676,57 +2747,65 @@ function resolveLegacyScopeFromElement(element) {
2676
2747
  }
2677
2748
  function migrateScopesArrays(rolesFilePath, project) {
2678
2749
  const sourceFile = project.getSourceFile(rolesFilePath);
2679
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2750
+ if (!sourceFile) {
2751
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2752
+ }
2680
2753
  let migratedCount = 0;
2681
2754
  let removedCount = 0;
2755
+ let mergedCount = 0;
2682
2756
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2757
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2683
2758
  for (const scopesProp of scopesProperties) {
2684
2759
  const initializer = scopesProp.getInitializer();
2685
2760
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2686
- const elements = initializer.getElements();
2687
- for (let index = elements.length - 1; index >= 0; index--) {
2688
- const element = elements[index];
2689
- if (!import_ts_morph11.Node.isExpression(element)) continue;
2761
+ const rawTexts = [];
2762
+ const legacyStrings = [];
2763
+ let anyChange = false;
2764
+ for (const element of initializer.getElements()) {
2690
2765
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2691
2766
  if (scopeKey && !(scopeKey in SCOPES)) {
2692
2767
  console.warn(
2693
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2768
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2694
2769
  );
2695
- initializer.removeElement(index);
2696
2770
  removedCount++;
2771
+ anyChange = true;
2697
2772
  continue;
2698
2773
  }
2699
2774
  const legacyScope = resolveLegacyScopeFromElement(element);
2700
2775
  if (!legacyScope) {
2701
2776
  console.warn(
2702
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2777
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2703
2778
  );
2779
+ rawTexts.push(element.getText());
2704
2780
  continue;
2705
2781
  }
2706
- try {
2707
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2708
- const scope = decodeScope(migratedScope);
2709
- if (!scope) {
2710
- console.warn(
2711
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2712
- );
2713
- continue;
2714
- }
2715
- element.replaceWithText(JSON.stringify(scope));
2716
- migratedCount++;
2717
- } catch (error) {
2718
- console.warn(
2719
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2720
- );
2721
- }
2782
+ legacyStrings.push(legacyScope);
2783
+ anyChange = true;
2784
+ }
2785
+ if (!anyChange) continue;
2786
+ let mergedScopes;
2787
+ try {
2788
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
2789
+ } catch (error) {
2790
+ throw new Error(
2791
+ `[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`,
2792
+ { cause: error }
2793
+ );
2722
2794
  }
2795
+ migratedCount += legacyStrings.length;
2796
+ mergedCount += legacyStrings.length - mergedScopes.length;
2797
+ const outputElements = [
2798
+ ...rawTexts,
2799
+ ...mergedScopes.map((s) => JSON.stringify(s))
2800
+ ];
2801
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2723
2802
  }
2724
2803
  if (removedCount > 0) {
2725
2804
  console.log(
2726
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2805
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2727
2806
  );
2728
2807
  }
2729
- return { migratedCount, removedCount };
2808
+ return { migratedCount, removedCount, mergedCount };
2730
2809
  }
2731
2810
  function ensureScopesHelpersImport(rolesFilePath, project) {
2732
2811
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2861,7 +2940,7 @@ async function main11() {
2861
2940
  return;
2862
2941
  }
2863
2942
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2864
- const { migratedCount, removedCount } = migrateScopesArrays(
2943
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2865
2944
  rolesFilePath,
2866
2945
  project
2867
2946
  );
@@ -2880,7 +2959,7 @@ async function main11() {
2880
2959
  }
2881
2960
  await sourceFile.save();
2882
2961
  console.log(
2883
- `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." : "."}`
2962
+ `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." : "."}`
2884
2963
  );
2885
2964
  }
2886
2965
 
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-scopes.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/migrate-scopes.ts"],"names":[],"mappings":"AAyVA,iBAAe,IAAI,kBAmDlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
1
+ {"version":3,"file":"migrate-scopes.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/migrate-scopes.ts"],"names":[],"mappings":"AAoXA,iBAAe,IAAI,kBAmDlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -25,7 +25,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
25
25
  exports.main = main;
26
26
  const ts_morph_1 = require("ts-morph");
27
27
  const path_1 = __importDefault(require("path"));
28
- const scopes_1 = require("../commons/scopes");
29
28
  const scopes_deprecated_do_not_use_1 = require("../commons/scopes.deprecated.do-not-use");
30
29
  const ROLES_FILE_RELATIVE_PATH = 'src/data-seeding/roles/roles.ts';
31
30
  const SCOPES_PROPERTY_NAME = 'scopes';
@@ -65,60 +64,85 @@ function resolveLegacyScopeFromElement(element) {
65
64
  }
66
65
  return null;
67
66
  }
67
+ /**
68
+ * Walks each `scopes: [...]` array in the roles file, classifies elements,
69
+ * and rewrites the whole array using `migrateLegacyScopesArrayToV2Scopes`
70
+ * (which preserves v1.9 AND semantics by merging pairs of legacy scopes
71
+ * that targeted the same v2 type). See issue #12489.
72
+ *
73
+ * Elements are partitioned into three kinds:
74
+ * - drop: `SCOPES.X` references where X is not in the SCOPES map (warned
75
+ * and removed, matching pre-refactor behavior).
76
+ * - raw: non-literal expressions we cannot statically resolve (e.g.
77
+ * `...sharedScopes` spreads). Preserved verbatim in output so authoring
78
+ * intent isn't lost.
79
+ * - legacy: literal strings or resolvable `SCOPES.X` references.
80
+ * Collected and passed as a batch to the merge function.
81
+ *
82
+ * The output array text is `[...rawTexts, ...mergedScopesAsJson]`. Order of
83
+ * legacy entries relative to raw expressions is not preserved — scopes in a
84
+ * v2 array compose with OR, so position is semantically irrelevant.
85
+ */
68
86
  function migrateScopesArrays(rolesFilePath, project) {
69
87
  const sourceFile = project.getSourceFile(rolesFilePath);
70
- if (!sourceFile)
71
- return { migratedCount: 0, removedCount: 0 };
88
+ if (!sourceFile) {
89
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
90
+ }
72
91
  let migratedCount = 0;
73
92
  let removedCount = 0;
93
+ let mergedCount = 0;
74
94
  const scopesProperties = sourceFile
75
95
  .getDescendantsOfKind(ts_morph_1.SyntaxKind.PropertyAssignment)
76
96
  .filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
97
+ const relPath = path_1.default.relative(process.cwd(), rolesFilePath);
77
98
  for (const scopesProp of scopesProperties) {
78
99
  const initializer = scopesProp.getInitializer();
79
100
  if (!initializer || !ts_morph_1.Node.isArrayLiteralExpression(initializer))
80
101
  continue;
81
- const elements = initializer.getElements();
82
- for (let index = elements.length - 1; index >= 0; index--) {
83
- const element = elements[index];
84
- if (!ts_morph_1.Node.isExpression(element))
85
- continue;
102
+ const rawTexts = [];
103
+ const legacyStrings = [];
104
+ let anyChange = false;
105
+ for (const element of initializer.getElements()) {
86
106
  const scopeKey = resolveScopeKeyFromElementAccess(element);
87
107
  if (scopeKey && !(scopeKey in scopes_deprecated_do_not_use_1.SCOPES)) {
88
108
  // eslint-disable-next-line no-console
89
- console.warn(` [${path_1.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`);
90
- initializer.removeElement(index);
109
+ console.warn(` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`);
91
110
  removedCount++;
111
+ anyChange = true;
92
112
  continue;
93
113
  }
94
114
  const legacyScope = resolveLegacyScopeFromElement(element);
95
115
  if (!legacyScope) {
96
116
  // eslint-disable-next-line no-console
97
- console.warn(` [${path_1.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`);
117
+ console.warn(` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`);
118
+ rawTexts.push(element.getText());
98
119
  continue;
99
120
  }
100
- try {
101
- const migratedScope = (0, scopes_deprecated_do_not_use_1.legacyScopeToV2Scope)(legacyScope);
102
- const scope = (0, scopes_1.decodeScope)(migratedScope);
103
- if (!scope) {
104
- // eslint-disable-next-line no-console
105
- console.warn(` [${path_1.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`);
106
- continue;
107
- }
108
- element.replaceWithText(JSON.stringify(scope));
109
- migratedCount++;
110
- }
111
- catch (error) {
112
- // eslint-disable-next-line no-console
113
- console.warn(` [${path_1.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`);
114
- }
121
+ legacyStrings.push(legacyScope);
122
+ anyChange = true;
123
+ }
124
+ if (!anyChange)
125
+ continue;
126
+ let mergedScopes;
127
+ try {
128
+ mergedScopes = (0, scopes_deprecated_do_not_use_1.migrateLegacyScopesArrayToV2Scopes)(legacyStrings);
129
+ }
130
+ catch (error) {
131
+ throw new Error(`[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
115
132
  }
133
+ migratedCount += legacyStrings.length;
134
+ mergedCount += legacyStrings.length - mergedScopes.length;
135
+ const outputElements = [
136
+ ...rawTexts,
137
+ ...mergedScopes.map((s) => JSON.stringify(s))
138
+ ];
139
+ scopesProp.setInitializer(`[${outputElements.join(', ')}]`);
116
140
  }
117
141
  if (removedCount > 0) {
118
142
  // eslint-disable-next-line no-console
119
- console.log(` Removed ${removedCount} unknown SCOPES reference(s) from '${path_1.default.relative(process.cwd(), rolesFilePath)}'.`);
143
+ console.log(` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`);
120
144
  }
121
- return { migratedCount, removedCount };
145
+ return { migratedCount, removedCount, mergedCount };
122
146
  }
123
147
  function ensureScopesHelpersImport(rolesFilePath, project) {
124
148
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -262,7 +286,7 @@ function main() {
262
286
  return;
263
287
  }
264
288
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
265
- const { migratedCount, removedCount } = migrateScopesArrays(rolesFilePath, project);
289
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(rolesFilePath, project);
266
290
  const wrappedScopesCount = wrapScopesArraysWithDefineScopes(rolesFilePath, project);
267
291
  const wrappedRoles = wrapRolesWithDefineRoles(rolesFilePath, project);
268
292
  const removedRoleType = removeRoleTypeDefinitionAndUnusedImports(rolesFilePath, project);
@@ -276,6 +300,6 @@ function main() {
276
300
  return;
277
301
  }
278
302
  yield sourceFile.save();
279
- console.log(`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.' : '.'}`);
303
+ console.log(`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.' : '.'}`);
280
304
  });
281
305
  }
@@ -980,28 +980,20 @@ function schemaPriority(schema) {
980
980
  return idx === -1 ? 9999 : idx;
981
981
  }
982
982
  function safeUnion(schemas) {
983
+ const sortedSchemas = [...schemas].sort(
984
+ (a, b) => schemaPriority(a) - schemaPriority(b)
985
+ );
983
986
  return z12.any().superRefine((val, ctx) => {
984
- const successful = schemas.filter((s) => s.safeParse(val).success);
985
- if (successful.length === 1) {
986
- return;
987
- }
988
- if (successful.length === 0) {
989
- ctx.addIssue({
990
- code: "invalid_type",
991
- expected: "custom",
992
- message: "Value does not match any schema"
993
- });
994
- return;
995
- }
996
- successful.sort((a, b) => schemaPriority(a) - schemaPriority(b));
997
- const best = successful[0];
998
- if (!best.safeParse(val).success) {
999
- ctx.addIssue({
1000
- expected: "custom",
1001
- code: "invalid_type",
1002
- message: "Value did not match the best schema"
1003
- });
987
+ for (const schema of sortedSchemas) {
988
+ if (schema.safeParse(val).success) {
989
+ return;
990
+ }
1004
991
  }
992
+ ctx.addIssue({
993
+ code: "invalid_type",
994
+ expected: "custom",
995
+ message: "Value does not match any schema"
996
+ });
1005
997
  }).meta({
1006
998
  description: "Value that matches exactly one of the possible schema types (TextValue, DateValue, DateRangeFieldValue). The best matching schema is chosen by priority."
1007
999
  });
@@ -4180,6 +4172,9 @@ var BaseActionInput = z38.object({
4180
4172
  originalActionId: UUID.optional(),
4181
4173
  // should not be part of base action.
4182
4174
  keepAssignment: z38.boolean().optional(),
4175
+ keepAssignmentIfAccepted: z38.boolean().optional(),
4176
+ keepAssignmentIfRejected: z38.boolean().optional(),
4177
+ waitFor: z38.boolean().optional(),
4183
4178
  // For normal users, the createdAtLocation is resolved on the backend from the user's primaryOfficeId.
4184
4179
  // @TODO: createdAtLocation should be limited to actions that system users can perform. For normal users, it should not be part of the base action.
4185
4180
  createdAtLocation: UUID.nullish().describe(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opencrvs/toolkit",
3
- "version": "2.0.0-rc.fc431fe",
3
+ "version": "2.0.0-rc.fd02169",
4
4
  "description": "OpenCRVS toolkit for building country configurations",
5
5
  "license": "MPL-2.0",
6
6
  "bin": {