strapi-plugin-bulk-updater 1.6.11 → 1.7.1

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.
Files changed (29) hide show
  1. package/dist/_chunks/{BulkUpdater-CFStXO-q.mjs → BulkUpdater-BQnhVw0j.mjs} +75 -44
  2. package/dist/_chunks/BulkUpdater-BQnhVw0j.mjs.map +1 -0
  3. package/dist/_chunks/{BulkUpdater-BSlEEUTV.js → BulkUpdater-BrBWtCjS.js} +75 -44
  4. package/dist/_chunks/BulkUpdater-BrBWtCjS.js.map +1 -0
  5. package/dist/_chunks/{SettingsPage-BrfS4_qy.mjs → SettingsPage-DYD6M988.mjs} +2 -2
  6. package/dist/_chunks/{SettingsPage-BrfS4_qy.mjs.map → SettingsPage-DYD6M988.mjs.map} +1 -1
  7. package/dist/_chunks/{SettingsPage-BgEO2BNP.js → SettingsPage-DsKfbhNd.js} +2 -2
  8. package/dist/_chunks/{SettingsPage-BgEO2BNP.js.map → SettingsPage-DsKfbhNd.js.map} +1 -1
  9. package/dist/_chunks/{ValidationRulesTab-BslJyrBj.mjs → ValidationRulesTab-BzS4_gcN.mjs} +43 -3
  10. package/dist/_chunks/ValidationRulesTab-BzS4_gcN.mjs.map +1 -0
  11. package/dist/_chunks/{ValidationRulesTab-Cs0YDlMx.js → ValidationRulesTab-DZw6CujQ.js} +43 -3
  12. package/dist/_chunks/ValidationRulesTab-DZw6CujQ.js.map +1 -0
  13. package/dist/_chunks/{index-CjR6IZqM.js → index-BCOsNd1S.js} +16 -4
  14. package/dist/_chunks/index-BCOsNd1S.js.map +1 -0
  15. package/dist/_chunks/{index-4eNIGyGu.mjs → index-CjbxZZjb.mjs} +16 -4
  16. package/dist/_chunks/index-CjbxZZjb.mjs.map +1 -0
  17. package/dist/admin/index.js +1 -1
  18. package/dist/admin/index.mjs +1 -1
  19. package/dist/server/index.js +475 -282
  20. package/dist/server/index.js.map +1 -1
  21. package/dist/server/index.mjs +475 -282
  22. package/dist/server/index.mjs.map +1 -1
  23. package/package.json +1 -1
  24. package/dist/_chunks/BulkUpdater-BSlEEUTV.js.map +0 -1
  25. package/dist/_chunks/BulkUpdater-CFStXO-q.mjs.map +0 -1
  26. package/dist/_chunks/ValidationRulesTab-BslJyrBj.mjs.map +0 -1
  27. package/dist/_chunks/ValidationRulesTab-Cs0YDlMx.js.map +0 -1
  28. package/dist/_chunks/index-4eNIGyGu.mjs.map +0 -1
  29. package/dist/_chunks/index-CjR6IZqM.js.map +0 -1
@@ -13,9 +13,17 @@ const PERMISSIONS = {
13
13
  workspaceView: `plugin::${PLUGIN_ID}.workspace.view`,
14
14
  workspaceExecute: `plugin::${PLUGIN_ID}.workspace.execute`,
15
15
  workspacePublish: `plugin::${PLUGIN_ID}.workspace.publish`,
16
+ workspaceSubmitForChecker: `plugin::${PLUGIN_ID}.workspace.submit-for-checker`,
17
+ workspaceForceRunNow: `plugin::${PLUGIN_ID}.workspace.force-run-now`,
18
+ workspaceQueueForOffPeak: `plugin::${PLUGIN_ID}.workspace.queue-for-off-peak`,
19
+ workspaceProceedToExecute: `plugin::${PLUGIN_ID}.workspace.proceed-to-execute`,
16
20
  // CSV Management
17
21
  csvExport: `plugin::${PLUGIN_ID}.csv.export`,
18
22
  csvImport: `plugin::${PLUGIN_ID}.csv.import`,
23
+ csvSubmitForChecker: `plugin::${PLUGIN_ID}.csv.submit-for-checker`,
24
+ csvForceRunNow: `plugin::${PLUGIN_ID}.csv.force-run-now`,
25
+ csvQueueForOffPeak: `plugin::${PLUGIN_ID}.csv.queue-for-off-peak`,
26
+ csvPreFlightDryRun: `plugin::${PLUGIN_ID}.csv.pre-flight-dry-run`,
19
27
  // Audit Trail
20
28
  auditView: `plugin::${PLUGIN_ID}.audit.view`,
21
29
  auditDetails: `plugin::${PLUGIN_ID}.audit.details`,
@@ -60,6 +68,34 @@ const BULK_UPDATER_PERMISSION_ACTIONS = [
60
68
  pluginName: PLUGIN_ID,
61
69
  subCategory: "Workspace"
62
70
  },
71
+ {
72
+ section: "plugins",
73
+ displayName: "Submit For Checker",
74
+ uid: "workspace.submit-for-checker",
75
+ pluginName: PLUGIN_ID,
76
+ subCategory: "Workspace"
77
+ },
78
+ {
79
+ section: "plugins",
80
+ displayName: "Force Run Now",
81
+ uid: "workspace.force-run-now",
82
+ pluginName: PLUGIN_ID,
83
+ subCategory: "Workspace"
84
+ },
85
+ {
86
+ section: "plugins",
87
+ displayName: "Queue For Off-Peak",
88
+ uid: "workspace.queue-for-off-peak",
89
+ pluginName: PLUGIN_ID,
90
+ subCategory: "Workspace"
91
+ },
92
+ {
93
+ section: "plugins",
94
+ displayName: "Proceed to Execute",
95
+ uid: "workspace.proceed-to-execute",
96
+ pluginName: PLUGIN_ID,
97
+ subCategory: "Workspace"
98
+ },
63
99
  {
64
100
  section: "plugins",
65
101
  displayName: "Export CSV & Templates",
@@ -74,6 +110,34 @@ const BULK_UPDATER_PERMISSION_ACTIONS = [
74
110
  pluginName: PLUGIN_ID,
75
111
  subCategory: "CSV Management"
76
112
  },
113
+ {
114
+ section: "plugins",
115
+ displayName: "CSV Submit For Checker",
116
+ uid: "csv.submit-for-checker",
117
+ pluginName: PLUGIN_ID,
118
+ subCategory: "CSV Management"
119
+ },
120
+ {
121
+ section: "plugins",
122
+ displayName: "CSV Force Run Now",
123
+ uid: "csv.force-run-now",
124
+ pluginName: PLUGIN_ID,
125
+ subCategory: "CSV Management"
126
+ },
127
+ {
128
+ section: "plugins",
129
+ displayName: "CSV Queue For Off-Peak",
130
+ uid: "csv.queue-for-off-peak",
131
+ pluginName: PLUGIN_ID,
132
+ subCategory: "CSV Management"
133
+ },
134
+ {
135
+ section: "plugins",
136
+ displayName: "CSV Run Pre-Flight Dry Run",
137
+ uid: "csv.pre-flight-dry-run",
138
+ pluginName: PLUGIN_ID,
139
+ subCategory: "CSV Management"
140
+ },
77
141
  {
78
142
  section: "plugins",
79
143
  displayName: "View Audit History",
@@ -145,6 +209,151 @@ const BULK_UPDATER_PERMISSION_ACTIONS = [
145
209
  subCategory: "Settings"
146
210
  }
147
211
  ];
212
+ const BATCH_UPDATE_POLICY_CONFIG = {
213
+ actions: [
214
+ PERMISSIONS.workspaceExecute,
215
+ PERMISSIONS.workspaceSubmitForChecker,
216
+ PERMISSIONS.workspaceForceRunNow,
217
+ PERMISSIONS.workspaceQueueForOffPeak,
218
+ PERMISSIONS.workspaceProceedToExecute
219
+ ],
220
+ mode: "any",
221
+ enforceBatchUpdateExecutionMode: true
222
+ };
223
+ const CSV_SUBMIT_BATCH_POLICY_CONFIG = {
224
+ actions: [
225
+ PERMISSIONS.csvImport,
226
+ PERMISSIONS.csvSubmitForChecker,
227
+ PERMISSIONS.csvForceRunNow,
228
+ PERMISSIONS.csvQueueForOffPeak
229
+ ],
230
+ mode: "any",
231
+ enforceCsvSubmitExecutionMode: true
232
+ };
233
+ const WORKSPACE_MODE_PERMISSIONS = {
234
+ maker_checker: PERMISSIONS.workspaceSubmitForChecker,
235
+ queue_offpeak: PERMISSIONS.workspaceQueueForOffPeak,
236
+ immediate: PERMISSIONS.workspaceForceRunNow
237
+ };
238
+ const CSV_MODE_PERMISSIONS = {
239
+ maker_checker: PERMISSIONS.csvSubmitForChecker,
240
+ queue_offpeak: PERMISSIONS.csvQueueForOffPeak,
241
+ immediate: PERMISSIONS.csvForceRunNow
242
+ };
243
+ function resolveExecutionModeRequiredPermissions(body, modePermissionMap, checkPreviewOrigin) {
244
+ const rawMode = body?.executionMode;
245
+ const effectiveMode = rawMode === void 0 ? "immediate" : rawMode;
246
+ if (typeof effectiveMode !== "string" || !["maker_checker", "queue_offpeak", "immediate"].includes(effectiveMode)) {
247
+ return {
248
+ valid: false,
249
+ actions: [],
250
+ reason: `Unsupported or unauthorized execution mode "${String(rawMode)}".`
251
+ };
252
+ }
253
+ const required = [
254
+ modePermissionMap[effectiveMode]
255
+ ];
256
+ if (checkPreviewOrigin) {
257
+ const isPreviewInitiated = body?.initiatedFromPreview === true || body?.initiatedFromPreview === "true" || body?.source === "preview" || body?.executionSource === "preview";
258
+ if (isPreviewInitiated) {
259
+ required.push(PERMISSIONS.workspaceProceedToExecute);
260
+ }
261
+ }
262
+ return { valid: true, actions: required };
263
+ }
264
+ function resolveBatchUpdateRequiredPermissions(body) {
265
+ return resolveExecutionModeRequiredPermissions(body, WORKSPACE_MODE_PERMISSIONS, true);
266
+ }
267
+ function resolveCsvSubmitRequiredPermissions(body) {
268
+ return resolveExecutionModeRequiredPermissions(body, CSV_MODE_PERMISSIONS, false);
269
+ }
270
+ function setForbiddenResponse(ctx, message = "You do not have permission to perform this action.") {
271
+ if (ctx) {
272
+ ctx.status = 403;
273
+ ctx.body = {
274
+ data: null,
275
+ error: {
276
+ status: 403,
277
+ name: "ForbiddenError",
278
+ message
279
+ }
280
+ };
281
+ }
282
+ }
283
+ const hasPermissionsPolicy = (policyContext, config, { strapi } = {}) => {
284
+ const ctx = policyContext?.isSelect ? policyContext : policyContext?.context || policyContext;
285
+ let actions = [];
286
+ let mode = "all";
287
+ let enforceBatchMode = false;
288
+ let enforceCsvMode = false;
289
+ if (Array.isArray(config)) {
290
+ actions = config;
291
+ } else if (config && typeof config === "object") {
292
+ actions = Array.isArray(config.actions) ? config.actions : [];
293
+ if (config.mode === "any") {
294
+ mode = "any";
295
+ }
296
+ enforceBatchMode = Boolean(config.enforceBatchUpdateExecutionMode);
297
+ enforceCsvMode = Boolean(config.enforceCsvSubmitExecutionMode);
298
+ } else if (typeof config === "string") {
299
+ actions = [config];
300
+ }
301
+ const user = ctx?.state?.user;
302
+ const userAbility = ctx?.state?.userAbility;
303
+ const isSuperAdmin = Boolean(
304
+ user?.isSuperAdmin === true || Array.isArray(user?.roles) && user.roles.some((r) => r?.code === "strapi-super-admin" || r?.name === "Super Admin")
305
+ );
306
+ if (isSuperAdmin) {
307
+ return true;
308
+ }
309
+ let batchModeActions = null;
310
+ if (enforceBatchMode || enforceCsvMode) {
311
+ const resolved = enforceCsvMode ? resolveCsvSubmitRequiredPermissions(ctx?.request?.body) : resolveBatchUpdateRequiredPermissions(ctx?.request?.body);
312
+ if (!resolved.valid) {
313
+ setForbiddenResponse(ctx, resolved.reason || "You do not have permission to perform this action.");
314
+ return false;
315
+ }
316
+ batchModeActions = resolved.actions;
317
+ }
318
+ if ((!actions || actions.length === 0) && (!batchModeActions || batchModeActions.length === 0)) {
319
+ return true;
320
+ }
321
+ const evaluateActions = (reqActions, evalMode) => {
322
+ if (!reqActions || reqActions.length === 0) return true;
323
+ if (userAbility && typeof userAbility.can === "function") {
324
+ if (userAbility.can("manage", "all") || userAbility.can("*")) {
325
+ return true;
326
+ }
327
+ return evalMode === "any" ? reqActions.some((act) => userAbility.can(act)) : reqActions.every((act) => userAbility.can(act));
328
+ }
329
+ const permissions = Array.isArray(ctx?.state?.permissions) ? ctx.state.permissions : Array.isArray(user?.permissions) ? user.permissions.map((p) => typeof p === "string" ? p : p?.action).filter(Boolean) : [];
330
+ if (permissions.includes("*") || permissions.includes("admin::all")) {
331
+ return true;
332
+ }
333
+ return evalMode === "any" ? reqActions.some((act) => permissions.includes(act)) : reqActions.every((act) => permissions.includes(act));
334
+ };
335
+ const baseAllowed = evaluateActions(actions, mode);
336
+ if (!baseAllowed) {
337
+ setForbiddenResponse(ctx);
338
+ return false;
339
+ }
340
+ if (batchModeActions && !evaluateActions(batchModeActions, "all")) {
341
+ setForbiddenResponse(
342
+ ctx,
343
+ `You do not have permission to perform this batch update action (required: ${batchModeActions.join(", ")}).`
344
+ );
345
+ return false;
346
+ }
347
+ return true;
348
+ };
349
+ const CSV_READ_PERMISSIONS = [
350
+ PERMISSIONS.csvExport,
351
+ PERMISSIONS.csvImport,
352
+ PERMISSIONS.csvSubmitForChecker,
353
+ PERMISSIONS.csvForceRunNow,
354
+ PERMISSIONS.csvQueueForOffPeak,
355
+ PERMISSIONS.csvPreFlightDryRun
356
+ ];
148
357
  function requirePermissions(actions, mode = "all") {
149
358
  return [
150
359
  {
@@ -168,8 +377,7 @@ const routes = {
168
377
  policies: requirePermissions(
169
378
  [
170
379
  PERMISSIONS.workspaceView,
171
- PERMISSIONS.csvExport,
172
- PERMISSIONS.csvImport,
380
+ ...CSV_READ_PERMISSIONS,
173
381
  PERMISSIONS.validationView
174
382
  ],
175
383
  "any"
@@ -182,7 +390,7 @@ const routes = {
182
390
  handler: "bulkUpdater.getCollectionEntries",
183
391
  config: {
184
392
  policies: requirePermissions(
185
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
393
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
186
394
  "any"
187
395
  )
188
396
  }
@@ -193,7 +401,7 @@ const routes = {
193
401
  handler: "bulkUpdater.getRelationOptions",
194
402
  config: {
195
403
  policies: requirePermissions(
196
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
404
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
197
405
  "any"
198
406
  )
199
407
  }
@@ -204,7 +412,7 @@ const routes = {
204
412
  handler: "bulkUpdater.getMediaOptions",
205
413
  config: {
206
414
  policies: requirePermissions(
207
- [PERMISSIONS.workspaceView, PERMISSIONS.csvExport, PERMISSIONS.csvImport],
415
+ [PERMISSIONS.workspaceView, ...CSV_READ_PERMISSIONS],
208
416
  "any"
209
417
  )
210
418
  }
@@ -214,7 +422,12 @@ const routes = {
214
422
  path: "/batch-update",
215
423
  handler: "bulkUpdater.batchUpdate",
216
424
  config: {
217
- policies: requirePermissions(PERMISSIONS.workspaceExecute)
425
+ policies: [
426
+ {
427
+ name: "plugin::bulk-updater.hasPermissions",
428
+ config: BATCH_UPDATE_POLICY_CONFIG
429
+ }
430
+ ]
218
431
  }
219
432
  },
220
433
  {
@@ -286,6 +499,9 @@ const routes = {
286
499
  PERMISSIONS.workspaceView,
287
500
  PERMISSIONS.workspaceExecute,
288
501
  PERMISSIONS.csvImport,
502
+ PERMISSIONS.csvSubmitForChecker,
503
+ PERMISSIONS.csvForceRunNow,
504
+ PERMISSIONS.csvQueueForOffPeak,
289
505
  PERMISSIONS.auditView,
290
506
  PERMISSIONS.approvalView
291
507
  ],
@@ -378,7 +594,7 @@ const routes = {
378
594
  path: "/csv/template/:uid",
379
595
  handler: "csv.getTemplate",
380
596
  config: {
381
- policies: requirePermissions([PERMISSIONS.csvExport, PERMISSIONS.csvImport], "any")
597
+ policies: requirePermissions(CSV_READ_PERMISSIONS, "any")
382
598
  }
383
599
  },
384
600
  {
@@ -418,7 +634,7 @@ const routes = {
418
634
  path: "/csv/import",
419
635
  handler: "csv.importCsv",
420
636
  config: {
421
- policies: requirePermissions(PERMISSIONS.csvImport)
637
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
422
638
  }
423
639
  },
424
640
  {
@@ -426,7 +642,7 @@ const routes = {
426
642
  path: "/csv/import-chunk",
427
643
  handler: "csv.importChunk",
428
644
  config: {
429
- policies: requirePermissions(PERMISSIONS.csvImport)
645
+ policies: requirePermissions(PERMISSIONS.csvForceRunNow)
430
646
  }
431
647
  },
432
648
  {
@@ -434,7 +650,7 @@ const routes = {
434
650
  path: "/csv/validate-preflight",
435
651
  handler: "csv.validatePreflight",
436
652
  config: {
437
- policies: requirePermissions(PERMISSIONS.csvImport)
653
+ policies: requirePermissions(PERMISSIONS.csvPreFlightDryRun)
438
654
  }
439
655
  },
440
656
  {
@@ -442,81 +658,19 @@ const routes = {
442
658
  path: "/csv/submit-batch",
443
659
  handler: "csv.submitBatch",
444
660
  config: {
445
- policies: requirePermissions(PERMISSIONS.csvImport)
661
+ policies: [
662
+ {
663
+ name: "plugin::bulk-updater.hasPermissions",
664
+ config: CSV_SUBMIT_BATCH_POLICY_CONFIG
665
+ }
666
+ ]
446
667
  }
447
668
  }
448
669
  ]
449
670
  }
450
671
  };
451
- const hasPermissions = (policyContext, config, { strapi } = {}) => {
452
- const ctx = policyContext?.isSelect ? policyContext : policyContext?.context || policyContext;
453
- let actions = [];
454
- let mode = "all";
455
- if (Array.isArray(config)) {
456
- actions = config;
457
- } else if (config && typeof config === "object") {
458
- actions = Array.isArray(config.actions) ? config.actions : [];
459
- if (config.mode === "any") {
460
- mode = "any";
461
- }
462
- } else if (typeof config === "string") {
463
- actions = [config];
464
- }
465
- if (!actions || actions.length === 0) {
466
- return true;
467
- }
468
- const user = ctx?.state?.user;
469
- const userAbility = ctx?.state?.userAbility;
470
- const isSuperAdmin = Boolean(
471
- user?.isSuperAdmin === true || Array.isArray(user?.roles) && user.roles.some((r) => r?.code === "strapi-super-admin" || r?.name === "Super Admin")
472
- );
473
- if (isSuperAdmin) {
474
- return true;
475
- }
476
- if (userAbility && typeof userAbility.can === "function") {
477
- if (userAbility.can("manage", "all") || userAbility.can("*")) {
478
- return true;
479
- }
480
- const isAllowed2 = mode === "any" ? actions.some((act) => userAbility.can(act)) : actions.every((act) => userAbility.can(act));
481
- if (isAllowed2) {
482
- return true;
483
- }
484
- if (ctx) {
485
- ctx.status = 403;
486
- ctx.body = {
487
- data: null,
488
- error: {
489
- status: 403,
490
- name: "ForbiddenError",
491
- message: "You do not have permission to perform this action."
492
- }
493
- };
494
- }
495
- return false;
496
- }
497
- const permissions = Array.isArray(ctx?.state?.permissions) ? ctx.state.permissions : Array.isArray(user?.permissions) ? user.permissions.map((p) => typeof p === "string" ? p : p?.action).filter(Boolean) : [];
498
- if (permissions.includes("*") || permissions.includes("admin::all")) {
499
- return true;
500
- }
501
- const isAllowed = mode === "any" ? actions.some((act) => permissions.includes(act)) : actions.every((act) => permissions.includes(act));
502
- if (isAllowed) {
503
- return true;
504
- }
505
- if (ctx) {
506
- ctx.status = 403;
507
- ctx.body = {
508
- data: null,
509
- error: {
510
- status: 403,
511
- name: "ForbiddenError",
512
- message: "You do not have permission to perform this action."
513
- }
514
- };
515
- }
516
- return false;
517
- };
518
672
  const policies = {
519
- hasPermissions
673
+ hasPermissions: hasPermissionsPolicy
520
674
  };
521
675
  const auditLog = {
522
676
  collectionName: "bulk_updater_audit_logs",
@@ -590,7 +744,15 @@ const contentTypes = {
590
744
  schema: auditLog
591
745
  }
592
746
  };
747
+ const { AsyncLocalStorage } = require("async_hooks");
593
748
  const CRASH_GUARD_SYMBOL = Symbol.for("strapi-plugin-bulk-updater.undiciCrashGuardInstalled");
749
+ const rollbackContextStorage = new AsyncLocalStorage();
750
+ function runInRollbackContext(fn) {
751
+ return rollbackContextStorage.run(true, fn);
752
+ }
753
+ function isRollbackContext() {
754
+ return rollbackContextStorage.getStore() === true;
755
+ }
594
756
  let activeBulkOperations = 0;
595
757
  function getActiveBulkOperationCount() {
596
758
  return activeBulkOperations;
@@ -793,6 +955,12 @@ const bulkUpdaterController = ({ strapi }) => ({
793
955
  try {
794
956
  const service = strapi.plugin("bulk-updater").service("bulkUpdater");
795
957
  const currentUser = ctx.state.user;
958
+ const hasAuthContext = Boolean(
959
+ ctx?.state?.userAbility || Array.isArray(ctx?.state?.permissions) || Array.isArray(ctx?.state?.user?.permissions) || ctx?.state?.user?.isSuperAdmin !== void 0
960
+ );
961
+ if (hasAuthContext && !hasPermissionsPolicy(ctx, BATCH_UPDATE_POLICY_CONFIG, { strapi })) {
962
+ return;
963
+ }
796
964
  const result = await service.batchUpdate(ctx.request.body || {}, currentUser);
797
965
  ctx.body = result;
798
966
  } catch (err) {
@@ -1031,6 +1199,13 @@ const validationRulesController = ({ strapi }) => ({
1031
1199
  }
1032
1200
  }
1033
1201
  });
1202
+ function ensureCsvAuthorized(ctx, policyConfig, strapi) {
1203
+ const hasAuthContext = Boolean(
1204
+ ctx?.state?.userAbility || Array.isArray(ctx?.state?.permissions) || Array.isArray(ctx?.state?.user?.permissions) || ctx?.state?.user?.isSuperAdmin !== void 0
1205
+ );
1206
+ if (!hasAuthContext) return true;
1207
+ return hasPermissionsPolicy(ctx, policyConfig, { strapi });
1208
+ }
1034
1209
  const csvController = ({ strapi }) => ({
1035
1210
  async getTemplate(ctx) {
1036
1211
  try {
@@ -1139,6 +1314,9 @@ const csvController = ({ strapi }) => ({
1139
1314
  },
1140
1315
  async importCsv(ctx) {
1141
1316
  try {
1317
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1318
+ return;
1319
+ }
1142
1320
  const { uid, csvText, mode, publish, publishStrategy, unreviewedConsent } = ctx.request.body;
1143
1321
  if (!uid) {
1144
1322
  ctx.status = 400;
@@ -1168,6 +1346,9 @@ const csvController = ({ strapi }) => ({
1168
1346
  },
1169
1347
  async importChunk(ctx) {
1170
1348
  try {
1349
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvForceRunNow] }, strapi)) {
1350
+ return;
1351
+ }
1171
1352
  const { uid, rows, batchId, isFirstChunk, isLastChunk, startRowNumber, mode, publish, publishStrategy, unreviewedConsent, originalHeaders } = ctx.request.body;
1172
1353
  if (!uid) {
1173
1354
  ctx.status = 400;
@@ -1202,6 +1383,9 @@ const csvController = ({ strapi }) => ({
1202
1383
  },
1203
1384
  async validatePreflight(ctx) {
1204
1385
  try {
1386
+ if (!ensureCsvAuthorized(ctx, { actions: [PERMISSIONS.csvPreFlightDryRun] }, strapi)) {
1387
+ return;
1388
+ }
1205
1389
  const { uid, rows, mode } = ctx.request.body;
1206
1390
  if (!uid) {
1207
1391
  ctx.status = 400;
@@ -1225,6 +1409,9 @@ const csvController = ({ strapi }) => ({
1225
1409
  },
1226
1410
  async submitBatch(ctx) {
1227
1411
  try {
1412
+ if (!ensureCsvAuthorized(ctx, CSV_SUBMIT_BATCH_POLICY_CONFIG, strapi)) {
1413
+ return;
1414
+ }
1228
1415
  const { uid, rows, executionMode, makerNotes, forceImmediate, mode, publish, publishStrategy, unreviewedConsent, unreviewedCount } = ctx.request.body;
1229
1416
  if (!uid) {
1230
1417
  ctx.status = 400;
@@ -9468,236 +9655,239 @@ const auditService = ({ strapi }) => ({
9468
9655
  * Helper to revert diff items back to original values
9469
9656
  */
9470
9657
  async revertDiffItems(diffs, userId) {
9471
- let revertedCount = 0;
9472
- const rollbackDetails = [];
9473
- for (const item of diffs) {
9474
- if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9475
- try {
9476
- const ct = strapi.contentTypes[item.uid];
9477
- if (!ct) {
9478
- throw new Error(`Content type "${item.uid}" does not exist in schema.`);
9479
- }
9480
- const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
9481
- let rollbackPayload;
9482
- if (isRel) {
9483
- const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
9484
- rollbackPayload = { set: oldDocIds };
9485
- } else {
9486
- rollbackPayload = item.oldValue ?? null;
9487
- }
9488
- const parsed = parseDynamicZonePath(item.attribute);
9489
- const rootKey = parsed.rootKey;
9490
- const rootAttrDef = ct.attributes?.[rootKey];
9491
- const isComponent = rootAttrDef?.type === "component";
9492
- const isDynamicZone = rootAttrDef?.type === "dynamiczone";
9493
- const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
9494
- const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
9495
- const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9496
- const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9497
- const findOneArgs = { documentId: item.documentId };
9498
- if (populateOption) {
9499
- findOneArgs.populate = populateOption;
9500
- }
9501
- if (isLocalized) {
9502
- findOneArgs.locale = item.locale;
9503
- }
9504
- const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9505
- if (!currentDoc) {
9506
- throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9507
- }
9508
- if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
9509
- const isRootDz = isDynamicZone;
9510
- const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
9511
- let restoredRoot;
9512
- if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
9513
- const hasStructuredSegments = item.dynamicZoneDiffs.some(
9514
- (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
9515
- );
9516
- if (hasStructuredSegments) {
9517
- const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
9518
- const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
9519
- const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
9520
- return {
9521
- occurrenceKey: dzDiff.occurrenceKey,
9522
- segments: dzDiff.segments,
9523
- dynamicZoneIndex: dzDiff.index,
9524
- componentId: dzDiff.componentId,
9525
- componentUid: dzDiff.componentUid,
9526
- value: val
9527
- };
9528
- });
9529
- const reverted = await applyOccurrenceUpdatesToDocument({
9530
- strapi,
9531
- contentType: ct,
9532
- allComponents: strapi.components,
9533
- currentDoc,
9534
- attribute: item.attribute,
9535
- updates: occUpdates
9536
- });
9537
- if (reverted.errors.length > 0) {
9538
- throw new Error(reverted.errors.join("; "));
9539
- }
9540
- restoredRoot = reverted.updateData[rootKey];
9541
- } else {
9542
- let workingRoot = existingRoot;
9543
- for (const dzDiff of item.dynamicZoneDiffs) {
9544
- const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
9545
- const dzParts = parsedDz.cleanPath.split(".").slice(1);
9546
- const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
9547
- workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
9548
- targetIndexes,
9549
- targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
9550
- strapi
9658
+ return runInRollbackContext(async () => {
9659
+ const revertedEntryKeys = /* @__PURE__ */ new Set();
9660
+ const rollbackDetails = [];
9661
+ for (const item of diffs) {
9662
+ if (item.status === "updated" && item.uid && item.documentId && item.attribute) {
9663
+ try {
9664
+ const ct = strapi.contentTypes[item.uid];
9665
+ if (!ct) {
9666
+ throw new Error(`Content type "${item.uid}" does not exist in schema.`);
9667
+ }
9668
+ const isRel = item.oldValue && typeof item.oldValue === "object" && item.oldValue.isRelation;
9669
+ let rollbackPayload;
9670
+ if (isRel) {
9671
+ const oldDocIds = Array.isArray(item.oldValue.documentIds) ? item.oldValue.documentIds : [];
9672
+ rollbackPayload = { set: oldDocIds };
9673
+ } else {
9674
+ rollbackPayload = item.oldValue ?? null;
9675
+ }
9676
+ const parsed = parseDynamicZonePath(item.attribute);
9677
+ const rootKey = parsed.rootKey;
9678
+ const rootAttrDef = ct.attributes?.[rootKey];
9679
+ const isComponent = rootAttrDef?.type === "component";
9680
+ const isDynamicZone = rootAttrDef?.type === "dynamiczone";
9681
+ const isNested = item.attribute.includes(".") || item.attribute.includes("[") || isComponent || isDynamicZone || isDeepComponentField(ct, strapi.components, item.attribute);
9682
+ const isLocalized = Boolean(ct?.pluginOptions?.i18n?.localized) && item.locale && item.locale !== "null" && item.locale !== "undefined";
9683
+ const isDraftAndPublish = Boolean(ct?.options?.draftAndPublish ?? item.isDraftAndPublish);
9684
+ const populateOption = isNested ? buildDeepPopulate(ct.attributes, strapi.components) : void 0;
9685
+ const findOneArgs = { documentId: item.documentId };
9686
+ if (populateOption) {
9687
+ findOneArgs.populate = populateOption;
9688
+ }
9689
+ if (isLocalized) {
9690
+ findOneArgs.locale = item.locale;
9691
+ }
9692
+ const currentDoc = await strapi.documents(item.uid).findOne(findOneArgs);
9693
+ if (!currentDoc) {
9694
+ throw new Error(`Document "${item.documentId}" not found in collection "${item.uid}".`);
9695
+ }
9696
+ if (isNested && (isComponent || isDynamicZone || rootAttrDef)) {
9697
+ const isRootDz = isDynamicZone;
9698
+ const existingRoot = currentDoc?.[rootKey] || (isRootDz ? [] : {});
9699
+ let restoredRoot;
9700
+ if (Array.isArray(item.dynamicZoneDiffs) && item.dynamicZoneDiffs.length > 0) {
9701
+ const hasStructuredSegments = item.dynamicZoneDiffs.some(
9702
+ (dz) => Array.isArray(dz?.segments) && dz.segments.length > 0
9703
+ );
9704
+ if (hasStructuredSegments) {
9705
+ const occUpdates = item.dynamicZoneDiffs.map((dzDiff) => {
9706
+ const isRelDiff = dzDiff.oldValue && typeof dzDiff.oldValue === "object" && dzDiff.oldValue.isRelation;
9707
+ const val = isRelDiff ? { mode: "set", documentIds: Array.isArray(dzDiff.oldValue.documentIds) ? dzDiff.oldValue.documentIds : [] } : dzDiff.oldValue ?? null;
9708
+ return {
9709
+ occurrenceKey: dzDiff.occurrenceKey,
9710
+ segments: dzDiff.segments,
9711
+ dynamicZoneIndex: dzDiff.index,
9712
+ componentId: dzDiff.componentId,
9713
+ componentUid: dzDiff.componentUid,
9714
+ value: val
9715
+ };
9716
+ });
9717
+ const reverted = await applyOccurrenceUpdatesToDocument({
9718
+ strapi,
9719
+ contentType: ct,
9720
+ allComponents: strapi.components,
9721
+ currentDoc,
9722
+ attribute: item.attribute,
9723
+ updates: occUpdates
9551
9724
  });
9725
+ if (reverted.errors.length > 0) {
9726
+ throw new Error(reverted.errors.join("; "));
9727
+ }
9728
+ restoredRoot = reverted.updateData[rootKey];
9729
+ } else {
9730
+ let workingRoot = existingRoot;
9731
+ for (const dzDiff of item.dynamicZoneDiffs) {
9732
+ const parsedDz = parseDynamicZonePath(dzDiff.attribute || item.attribute);
9733
+ const dzParts = parsedDz.cleanPath.split(".").slice(1);
9734
+ const targetIndexes = dzDiff.index !== void 0 ? [dzDiff.index] : parsedDz.targetIndex !== void 0 ? [parsedDz.targetIndex] : void 0;
9735
+ workingRoot = setDeepProperty(workingRoot, dzParts, dzDiff.oldValue ?? null, {
9736
+ targetIndexes,
9737
+ targetComponentUid: dzDiff.componentUid || parsedDz.targetComponentUid,
9738
+ strapi
9739
+ });
9740
+ }
9741
+ restoredRoot = workingRoot;
9552
9742
  }
9553
- restoredRoot = workingRoot;
9743
+ } else {
9744
+ const parts = parsed.cleanPath.split(".");
9745
+ const pathParts = parts.slice(1);
9746
+ const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
9747
+ const targetComponentUid = parsed.targetComponentUid;
9748
+ restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
9749
+ targetIndexes,
9750
+ targetComponentUid,
9751
+ strapi
9752
+ });
9554
9753
  }
9555
- } else {
9556
- const parts = parsed.cleanPath.split(".");
9557
- const pathParts = parts.slice(1);
9558
- const targetIndexes = parsed.targetIndex !== void 0 ? [parsed.targetIndex] : void 0;
9559
- const targetComponentUid = parsed.targetComponentUid;
9560
- restoredRoot = setDeepProperty(existingRoot, pathParts, rollbackPayload, {
9561
- targetIndexes,
9562
- targetComponentUid,
9563
- strapi
9754
+ await strapi.documents(item.uid).update({
9755
+ documentId: item.documentId,
9756
+ ...isLocalized ? { locale: item.locale } : {},
9757
+ data: {
9758
+ [rootKey]: restoredRoot
9759
+ }
9564
9760
  });
9565
- }
9566
- await strapi.documents(item.uid).update({
9567
- documentId: item.documentId,
9568
- ...isLocalized ? { locale: item.locale } : {},
9569
- data: {
9570
- [rootKey]: restoredRoot
9571
- }
9572
- });
9573
- } else {
9574
- await strapi.documents(item.uid).update({
9575
- documentId: item.documentId,
9576
- ...isLocalized ? { locale: item.locale } : {},
9577
- data: {
9578
- [item.attribute]: rollbackPayload
9579
- }
9580
- });
9581
- }
9582
- let targetStatus = void 0;
9583
- if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9584
- targetStatus = item.previousStatus;
9585
- } else if (item.hadPublishedVersion === false) {
9586
- targetStatus = "draft";
9587
- } else if (item.hadPublishedVersion === true) {
9588
- targetStatus = "published";
9589
- }
9590
- if (isDraftAndPublish && !targetStatus) {
9591
- let publishedCounterpart = null;
9592
- try {
9593
- const docSvc = strapi.documents(item.uid);
9594
- if (typeof docSvc.findMany === "function") {
9595
- const pubs = await docSvc.findMany({
9596
- status: "published",
9597
- filters: { documentId: item.documentId },
9598
- fields: ["documentId", "publishedAt"],
9599
- limit: 1,
9600
- ...isLocalized ? { locale: item.locale } : {}
9601
- });
9602
- if (pubs && pubs.length > 0) {
9603
- publishedCounterpart = pubs[0];
9761
+ } else {
9762
+ await strapi.documents(item.uid).update({
9763
+ documentId: item.documentId,
9764
+ ...isLocalized ? { locale: item.locale } : {},
9765
+ data: {
9766
+ [item.attribute]: rollbackPayload
9604
9767
  }
9605
- }
9606
- } catch {
9768
+ });
9607
9769
  }
9608
- if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9609
- targetStatus = "published";
9610
- } else {
9770
+ let targetStatus = void 0;
9771
+ if (item.previousStatus === "published" || item.previousStatus === "modified" || item.previousStatus === "draft") {
9772
+ targetStatus = item.previousStatus;
9773
+ } else if (item.hadPublishedVersion === false) {
9611
9774
  targetStatus = "draft";
9775
+ } else if (item.hadPublishedVersion === true) {
9776
+ targetStatus = "published";
9612
9777
  }
9613
- }
9614
- if (isDraftAndPublish) {
9615
- const docSvc = strapi.documents(item.uid);
9616
- if (targetStatus === "published") {
9778
+ if (isDraftAndPublish && !targetStatus) {
9779
+ let publishedCounterpart = null;
9617
9780
  try {
9618
- if (typeof docSvc.publish === "function") {
9619
- await docSvc.publish({
9620
- documentId: item.documentId,
9781
+ const docSvc = strapi.documents(item.uid);
9782
+ if (typeof docSvc.findMany === "function") {
9783
+ const pubs = await docSvc.findMany({
9784
+ status: "published",
9785
+ filters: { documentId: item.documentId },
9786
+ fields: ["documentId", "publishedAt"],
9787
+ limit: 1,
9621
9788
  ...isLocalized ? { locale: item.locale } : {}
9622
9789
  });
9790
+ if (pubs && pubs.length > 0) {
9791
+ publishedCounterpart = pubs[0];
9792
+ }
9623
9793
  }
9624
- } catch (publishErr) {
9625
- strapi.log.warn(
9626
- `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9627
- publishErr?.message
9628
- );
9794
+ } catch {
9629
9795
  }
9630
- } else if (targetStatus === "draft") {
9631
- try {
9632
- if (typeof docSvc.unpublish === "function") {
9633
- let hasPublished = false;
9634
- if (typeof docSvc.findMany === "function") {
9635
- const pubs = await docSvc.findMany({
9636
- status: "published",
9637
- filters: { documentId: item.documentId },
9638
- fields: ["documentId", "publishedAt"],
9639
- limit: 1,
9796
+ if (publishedCounterpart?.publishedAt || currentDoc?.publishedAt) {
9797
+ targetStatus = "published";
9798
+ } else {
9799
+ targetStatus = "draft";
9800
+ }
9801
+ }
9802
+ if (isDraftAndPublish) {
9803
+ const docSvc = strapi.documents(item.uid);
9804
+ if (targetStatus === "published") {
9805
+ try {
9806
+ if (typeof docSvc.publish === "function") {
9807
+ await docSvc.publish({
9808
+ documentId: item.documentId,
9640
9809
  ...isLocalized ? { locale: item.locale } : {}
9641
9810
  });
9642
- if (pubs && pubs.length > 0) {
9811
+ }
9812
+ } catch (publishErr) {
9813
+ strapi.log.warn(
9814
+ `[bulk-updater] Failed to auto-publish rollback for ${item.uid}/${item.documentId}:`,
9815
+ publishErr?.message
9816
+ );
9817
+ }
9818
+ } else if (targetStatus === "draft") {
9819
+ try {
9820
+ if (typeof docSvc.unpublish === "function") {
9821
+ let hasPublished = false;
9822
+ if (typeof docSvc.findMany === "function") {
9823
+ const pubs = await docSvc.findMany({
9824
+ status: "published",
9825
+ filters: { documentId: item.documentId },
9826
+ fields: ["documentId", "publishedAt"],
9827
+ limit: 1,
9828
+ ...isLocalized ? { locale: item.locale } : {}
9829
+ });
9830
+ if (pubs && pubs.length > 0) {
9831
+ hasPublished = true;
9832
+ }
9833
+ } else if (currentDoc?.publishedAt) {
9643
9834
  hasPublished = true;
9644
9835
  }
9645
- } else if (currentDoc?.publishedAt) {
9646
- hasPublished = true;
9647
- }
9648
- if (hasPublished) {
9649
- await docSvc.unpublish({
9650
- documentId: item.documentId,
9651
- ...isLocalized ? { locale: item.locale } : {}
9652
- });
9836
+ if (hasPublished) {
9837
+ await docSvc.unpublish({
9838
+ documentId: item.documentId,
9839
+ ...isLocalized ? { locale: item.locale } : {}
9840
+ });
9841
+ }
9653
9842
  }
9843
+ } catch (unpubErr) {
9844
+ strapi.log.warn(
9845
+ `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9846
+ unpubErr?.message
9847
+ );
9654
9848
  }
9655
- } catch (unpubErr) {
9656
- strapi.log.warn(
9657
- `[bulk-updater] Failed to unpublish rollback for ${item.uid}/${item.documentId}:`,
9658
- unpubErr?.message
9659
- );
9660
9849
  }
9661
9850
  }
9662
- }
9663
- try {
9664
- await recordContentHistoryVersion(strapi, {
9851
+ try {
9852
+ await recordContentHistoryVersion(strapi, {
9853
+ uid: item.uid,
9854
+ documentId: item.documentId,
9855
+ userId,
9856
+ statusOverride: isDraftAndPublish ? targetStatus : "published"
9857
+ });
9858
+ } catch {
9859
+ }
9860
+ try {
9861
+ const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
9862
+ if (bulkService?.invalidateCache) {
9863
+ bulkService.invalidateCache(item.uid);
9864
+ }
9865
+ } catch {
9866
+ }
9867
+ const entryKey = `${item.uid}@@@${item.documentId}@@@${isLocalized ? item.locale : ""}`;
9868
+ revertedEntryKeys.add(entryKey);
9869
+ rollbackDetails.push({
9665
9870
  uid: item.uid,
9666
9871
  documentId: item.documentId,
9667
- userId,
9668
- statusOverride: isDraftAndPublish ? targetStatus : "published"
9872
+ label: item.label,
9873
+ attribute: item.attribute,
9874
+ revertedTo: item.oldValue,
9875
+ status: "reverted",
9876
+ restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
9877
+ });
9878
+ } catch (err) {
9879
+ rollbackDetails.push({
9880
+ uid: item.uid,
9881
+ documentId: item.documentId,
9882
+ label: item.label,
9883
+ status: "error",
9884
+ message: err.message
9669
9885
  });
9670
- } catch {
9671
- }
9672
- try {
9673
- const bulkService = strapi.plugin("bulk-updater").service("bulkUpdater");
9674
- if (bulkService?.invalidateCache) {
9675
- bulkService.invalidateCache(item.uid);
9676
- }
9677
- } catch {
9678
9886
  }
9679
- revertedCount++;
9680
- rollbackDetails.push({
9681
- uid: item.uid,
9682
- documentId: item.documentId,
9683
- label: item.label,
9684
- attribute: item.attribute,
9685
- revertedTo: item.oldValue,
9686
- status: "reverted",
9687
- restoredLifecycleStatus: isDraftAndPublish ? targetStatus : "published"
9688
- });
9689
- } catch (err) {
9690
- rollbackDetails.push({
9691
- uid: item.uid,
9692
- documentId: item.documentId,
9693
- label: item.label,
9694
- status: "error",
9695
- message: err.message
9696
- });
9697
9887
  }
9698
9888
  }
9699
- }
9700
- return { revertedCount, rollbackDetails };
9889
+ return { revertedCount: revertedEntryKeys.size, rollbackDetails };
9890
+ });
9701
9891
  },
9702
9892
  /**
9703
9893
  * Performs deterministic rollback of a batch.
@@ -12573,6 +12763,9 @@ const index = {
12573
12763
  }
12574
12764
  });
12575
12765
  strapi.documents.use(async (context, next) => {
12766
+ if (isRollbackContext()) {
12767
+ return await next();
12768
+ }
12576
12769
  if (typeof context.uid === "string" && context.uid.startsWith("plugin::bulk-updater.")) {
12577
12770
  return await next();
12578
12771
  }