strapi-plugin-magic-sessionmanager 4.20.0 → 4.21.0

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/CHANGELOG.md +14 -0
  2. package/README.md +58 -39
  3. package/dist/admin/{Analytics-B5GnwMtH.js → Analytics-BqdZIBV4.js} +1 -1
  4. package/dist/admin/{Analytics-B-MVQ6dQ.mjs → Analytics-C-OLLzoB.mjs} +1 -1
  5. package/dist/admin/{App-DzbP5VPQ.mjs → App-BswHmNQT.mjs} +338 -4
  6. package/dist/admin/{App-xBOmg4g9.js → App-Cx9v6n_7.js} +337 -3
  7. package/dist/admin/{OnlineUsersWidget-FuPPPCCV.js → OnlineUsersWidget-BRmQPPp9.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Bf3BICmx.mjs → OnlineUsersWidget-Dusgjc1d.mjs} +1 -1
  9. package/dist/admin/{Settings-WRIXHLDa.js → Settings-DWGuf_Z3.js} +17 -9
  10. package/dist/admin/{Settings-hpkloyO6.mjs → Settings-DZyQheUS.mjs} +17 -9
  11. package/dist/admin/{de-Uqb30N5n.js → de-24TPqzG6.js} +32 -1
  12. package/dist/admin/{de-Bzd14FzX.mjs → de-DUnrmFWk.mjs} +32 -1
  13. package/dist/admin/{en-CDBcocLk.js → en-8mBSkWOF.js} +32 -1
  14. package/dist/admin/{en-DovyVwa5.mjs → en-D8J__tyF.mjs} +32 -1
  15. package/dist/admin/{es-BygJxl1J.mjs → es-BgpgWdk0.mjs} +32 -1
  16. package/dist/admin/{es-DA1X0RPv.js → es-ChUKey-Q.js} +32 -1
  17. package/dist/admin/{fr-CPPA27jW.js → fr-DE_CWmgq.js} +32 -1
  18. package/dist/admin/{fr-DONxL73-.mjs → fr-k1MHYKJo.mjs} +32 -1
  19. package/dist/admin/{index-Q_D-5LlE.js → index-Ceh3Q1Ki.js} +20 -10
  20. package/dist/admin/{index-DsaGGK7x.mjs → index-meLDPPwt.mjs} +34 -24
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +2 -2
  23. package/dist/admin/{pt-BMuwyaan.js → pt-BjqU5ioB.js} +32 -1
  24. package/dist/admin/{pt-D2yGNz2N.mjs → pt-DPO4DmDc.mjs} +32 -1
  25. package/dist/admin/{settingsTabs--7IsqMdn.mjs → settingsTabs-C1q5iMMw.mjs} +1 -1
  26. package/dist/admin/{settingsTabs-Dxlevody.js → settingsTabs-CfquZuKH.js} +1 -1
  27. package/dist/server/index.js +496 -12
  28. package/dist/server/index.mjs +496 -12
  29. package/package.json +1 -1
@@ -1699,12 +1699,14 @@ var require_impersonation_rules = __commonJS({
1699
1699
  var IMPERSONATION_DEFAULTS = Object.freeze({ impersonationEnabled: false });
1700
1700
  var IMPERSONATION_KEYS = Object.freeze(Object.keys(IMPERSONATION_DEFAULTS));
1701
1701
  var USER_DURATIONS = Object.freeze([15, 30, 60]);
1702
+ var ADMIN_DURATIONS = Object.freeze([15, 30]);
1702
1703
  var REASON_MIN = 3;
1703
1704
  var REASON_MAX = 255;
1704
1705
  var CODE_TTL_MS = 60 * 1e3;
1705
1706
  var IMPERSONATION_HEADER = "X-Magic-Impersonation";
1706
1707
  var CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
1707
1708
  var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1709
+ var ADMIN_ID_PATTERN = /^[1-9][0-9]{0,15}$/;
1708
1710
  var LOOPBACK_HOSTS = Object.freeze(["localhost", "127.0.0.1", "[::1]"]);
1709
1711
  function normalizeImpersonationSettings(stored) {
1710
1712
  return { impersonationEnabled: stored?.impersonationEnabled === true };
@@ -1907,6 +1909,8 @@ var require_impersonation_rules = __commonJS({
1907
1909
  }
1908
1910
  }
1909
1911
  module.exports = {
1912
+ ADMIN_DURATIONS,
1913
+ ADMIN_ID_PATTERN,
1910
1914
  CODE_PATTERN,
1911
1915
  CODE_TTL_MS,
1912
1916
  DOCUMENT_ID_PATTERN,
@@ -2741,6 +2745,17 @@ var require_register = __commonJS({
2741
2745
  uid: "impersonate.users",
2742
2746
  subCategory: "Impersonation",
2743
2747
  pluginName: "magic-sessionmanager"
2748
+ },
2749
+ // "View as admin" (4.20): a read-only preview of which content types and
2750
+ // actions another admin can use. Never a Super Admin, never oneself, and
2751
+ // for non-Super-Admins only admins whose permissions are a subset of
2752
+ // their own.
2753
+ {
2754
+ section: "plugins",
2755
+ displayName: "View as admin (read-only permission preview)",
2756
+ uid: "impersonate.admins",
2757
+ subCategory: "Impersonation",
2758
+ pluginName: "magic-sessionmanager"
2744
2759
  }
2745
2760
  ]);
2746
2761
  disableGraphqlShadowCrud(strapi2, log);
@@ -12113,6 +12128,11 @@ var require_admin = __commonJS({
12113
12128
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12114
12129
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12115
12130
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
12131
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
12132
+ var impersonationListPolicy = () => [
12133
+ ...adminPolicy(),
12134
+ "plugin::magic-sessionmanager.can-impersonate"
12135
+ ];
12116
12136
  var adminPolicy = () => [
12117
12137
  "admin::isAuthenticatedAdmin",
12118
12138
  {
@@ -12477,12 +12497,36 @@ var require_admin = __commonJS({
12477
12497
  ]
12478
12498
  }
12479
12499
  },
12500
+ {
12501
+ method: "POST",
12502
+ path: "/impersonation/admins/:adminId/preview",
12503
+ handler: "impersonation.previewAdmin",
12504
+ config: {
12505
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12506
+ // Ten previews per ten minutes per admin.
12507
+ middlewares: [
12508
+ {
12509
+ name: "plugin::magic-sessionmanager.rate-limit",
12510
+ config: { max: 10, window: 10 * 60 * 1e3 }
12511
+ }
12512
+ ]
12513
+ }
12514
+ },
12515
+ {
12516
+ method: "GET",
12517
+ path: "/impersonation/previews/:id",
12518
+ handler: "impersonation.getPreview",
12519
+ config: {
12520
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12521
+ middlewares: adminReadRateLimit()
12522
+ }
12523
+ },
12480
12524
  {
12481
12525
  method: "GET",
12482
12526
  path: "/impersonation/active",
12483
12527
  handler: "impersonation.listActive",
12484
12528
  config: {
12485
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12529
+ policies: impersonationListPolicy(),
12486
12530
  middlewares: adminReadRateLimit()
12487
12531
  }
12488
12532
  },
@@ -12491,7 +12535,7 @@ var require_admin = __commonJS({
12491
12535
  path: "/impersonation/:id/end",
12492
12536
  handler: "impersonation.end",
12493
12537
  config: {
12494
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12538
+ policies: impersonationListPolicy(),
12495
12539
  middlewares: adminSignOutRateLimit()
12496
12540
  }
12497
12541
  },
@@ -17353,6 +17397,228 @@ var require_webhooks = __commonJS({
17353
17397
  }
17354
17398
  });
17355
17399
 
17400
+ // server/src/utils/permission-subset.js
17401
+ var require_permission_subset = __commonJS({
17402
+ "server/src/utils/permission-subset.js"(exports, module) {
17403
+ "use strict";
17404
+ function grantsNothing(permission) {
17405
+ const fields = permission?.properties?.fields;
17406
+ return Array.isArray(fields) && fields.length === 0;
17407
+ }
17408
+ function parametersKey(value) {
17409
+ const normalize = (input) => {
17410
+ if (Array.isArray(input)) {
17411
+ return input.every((item) => typeof item === "string") ? [...new Set(input)].sort() : input.map(normalize);
17412
+ }
17413
+ if (input && typeof input === "object") {
17414
+ return Object.fromEntries(
17415
+ Object.keys(input).filter((key) => input[key] !== void 0).sort().map((key) => [key, normalize(input[key])])
17416
+ );
17417
+ }
17418
+ return input;
17419
+ };
17420
+ return JSON.stringify(normalize(value ?? {}));
17421
+ }
17422
+ function coversValue(held, property, value) {
17423
+ const allowed = held.properties?.[property];
17424
+ if (allowed === void 0 || allowed === null) return true;
17425
+ if (value === null || !Array.isArray(allowed)) return false;
17426
+ return allowed.some(
17427
+ (entry) => entry === value || property === "fields" && value.startsWith(`${entry}.`)
17428
+ );
17429
+ }
17430
+ function coversCondition(held, condition) {
17431
+ const conditions = held.conditions ?? [];
17432
+ if (conditions.length === 0) return true;
17433
+ return condition !== null && conditions.includes(condition);
17434
+ }
17435
+ function isPermissionCovered(requested, held) {
17436
+ if (grantsNothing(requested)) return true;
17437
+ const subject = requested.subject ?? null;
17438
+ const parameters = parametersKey(requested.actionParameters);
17439
+ const matching = held.filter(
17440
+ (permission) => permission.action === requested.action && (permission.subject ?? null) === subject && parametersKey(permission.actionParameters) === parameters && !grantsNothing(permission)
17441
+ );
17442
+ if (matching.length === 0) return false;
17443
+ const properties = [
17444
+ .../* @__PURE__ */ new Set([
17445
+ ...Object.keys(requested.properties ?? {}),
17446
+ ...matching.flatMap((permission) => Object.keys(permission.properties ?? {}))
17447
+ ])
17448
+ ];
17449
+ const dimensions = [];
17450
+ for (const property of properties) {
17451
+ const values = requested.properties?.[property];
17452
+ if (!Array.isArray(values)) dimensions.push({ property, values: [null] });
17453
+ else if (values.length > 0) {
17454
+ dimensions.push({ property, values: [...new Set(values.map(String))] });
17455
+ }
17456
+ }
17457
+ const conditions = (requested.conditions ?? []).length === 0 ? [null] : [...new Set(requested.conditions)];
17458
+ const walk = (index, picked, condition) => {
17459
+ if (index === dimensions.length) {
17460
+ return matching.some(
17461
+ (permission) => Object.entries(picked).every(
17462
+ ([property2, value]) => coversValue(permission, property2, value)
17463
+ ) && coversCondition(permission, condition)
17464
+ );
17465
+ }
17466
+ const { property, values } = dimensions[index];
17467
+ return values.every((value) => walk(index + 1, { ...picked, [property]: value }, condition));
17468
+ };
17469
+ return conditions.every((condition) => walk(0, {}, condition));
17470
+ }
17471
+ function uncoveredPermissions(target, actor) {
17472
+ return target.filter((permission) => !isPermissionCovered(permission, actor));
17473
+ }
17474
+ function toEnforced(permissions, context) {
17475
+ const out = [];
17476
+ for (const permission of permissions) {
17477
+ const conditions = permission.conditions ?? [];
17478
+ const registered = conditions.filter((id) => context.isConditionRegistered(id));
17479
+ if (conditions.length > 0 && registered.length === 0) continue;
17480
+ const properties = { ...permission.properties ?? {} };
17481
+ if (context.appliesLocales(permission)) {
17482
+ if (properties.locales === void 0) properties.locales = [];
17483
+ } else {
17484
+ delete properties.locales;
17485
+ }
17486
+ out.push({ ...permission, conditions: registered, properties });
17487
+ }
17488
+ return out;
17489
+ }
17490
+ module.exports = { isPermissionCovered, toEnforced, uncoveredPermissions };
17491
+ }
17492
+ });
17493
+
17494
+ // server/src/utils/admin-preview.js
17495
+ var require_admin_preview = __commonJS({
17496
+ "server/src/utils/admin-preview.js"(exports, module) {
17497
+ "use strict";
17498
+ var { toEnforced, uncoveredPermissions } = require_permission_subset();
17499
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
17500
+ function isSuperAdmin(user) {
17501
+ return (user?.roles || []).some((role) => role?.code === SUPER_ADMIN_CODE);
17502
+ }
17503
+ async function loadAdmin(strapi2, id) {
17504
+ return strapi2.db.query("admin::user").findOne({
17505
+ where: { id },
17506
+ select: ["id", "firstname", "lastname", "username", "email", "isActive"],
17507
+ populate: { roles: { select: ["id", "name", "code"] } }
17508
+ });
17509
+ }
17510
+ async function effectivePermissions(strapi2, user) {
17511
+ const service = strapi2.admin.services.permission;
17512
+ const raw = await service.findUserPermissions(user);
17513
+ const appliesCache = /* @__PURE__ */ new Map();
17514
+ for (const permission of raw) {
17515
+ const key = `${permission.action}::${permission.subject}`;
17516
+ if (appliesCache.has(key)) continue;
17517
+ let applies;
17518
+ try {
17519
+ applies = Boolean(permission.subject) && service.actionProvider.has(permission.action) && await service.actionProvider.appliesToProperty(
17520
+ "locales",
17521
+ permission.action,
17522
+ permission.subject
17523
+ ) === true;
17524
+ } catch {
17525
+ applies = false;
17526
+ }
17527
+ appliesCache.set(key, applies);
17528
+ }
17529
+ return toEnforced(raw, {
17530
+ isConditionRegistered: (id) => {
17531
+ try {
17532
+ return service.conditionProvider.has(id) === true;
17533
+ } catch {
17534
+ return false;
17535
+ }
17536
+ },
17537
+ appliesLocales: (permission) => appliesCache.get(`${permission.action}::${permission.subject}`) === true
17538
+ });
17539
+ }
17540
+ async function previewRefusal(strapi2, actor, target) {
17541
+ if (String(actor.id) === String(target.id)) return { reason: "self" };
17542
+ if (isSuperAdmin(target)) return { reason: "super-admin" };
17543
+ if (isSuperAdmin(actor)) return null;
17544
+ const [held, wanted] = await Promise.all([
17545
+ effectivePermissions(strapi2, actor),
17546
+ effectivePermissions(strapi2, target)
17547
+ ]);
17548
+ const uncovered = uncoveredPermissions(wanted, held);
17549
+ return uncovered.length > 0 ? { reason: "not-subset", uncovered: uncovered.length } : null;
17550
+ }
17551
+ function contentAction(action) {
17552
+ const match = /^plugin::content-manager\.explorer\.([a-z-]+)$/.exec(action);
17553
+ return match ? match[1] : action;
17554
+ }
17555
+ async function buildPreview(strapi2, target) {
17556
+ const permissions = await effectivePermissions(strapi2, target);
17557
+ const provider = strapi2.admin.services.permission.actionProvider;
17558
+ const types = /* @__PURE__ */ new Map();
17559
+ const other = [];
17560
+ for (const permission of permissions) {
17561
+ const contentType = permission.subject ? strapi2.contentTypes?.[permission.subject] : null;
17562
+ if (contentType && permission.action.startsWith("plugin::content-manager.explorer.")) {
17563
+ const entry = types.get(permission.subject) || {
17564
+ uid: permission.subject,
17565
+ name: String(contentType.info?.displayName || permission.subject).slice(0, 120),
17566
+ kind: contentType.kind === "singleType" ? "single" : "collection",
17567
+ actions: []
17568
+ };
17569
+ const fields = permission.properties?.fields;
17570
+ const locales = permission.properties?.locales;
17571
+ entry.actions.push({
17572
+ action: contentAction(permission.action),
17573
+ fields: Array.isArray(fields) ? fields.length : null,
17574
+ locales: Array.isArray(locales) ? locales.slice(0, 20) : null,
17575
+ conditions: (permission.conditions || []).slice(0, 10)
17576
+ });
17577
+ types.set(permission.subject, entry);
17578
+ continue;
17579
+ }
17580
+ let definition;
17581
+ try {
17582
+ definition = provider.get(permission.action);
17583
+ } catch {
17584
+ definition = null;
17585
+ }
17586
+ other.push({
17587
+ action: permission.action,
17588
+ name: String(definition?.displayName || permission.action).slice(0, 160),
17589
+ section: String(definition?.section || "other"),
17590
+ scope: definition?.pluginName ? String(definition.pluginName) : null
17591
+ });
17592
+ }
17593
+ const order = ["create", "read", "update", "delete", "publish"];
17594
+ const contentTypes = [...types.values()].map((entry) => ({
17595
+ ...entry,
17596
+ actions: entry.actions.sort(
17597
+ (a, b) => (order.indexOf(a.action) + 1 || 99) - (order.indexOf(b.action) + 1 || 99) || a.action.localeCompare(b.action)
17598
+ )
17599
+ })).sort((a, b) => a.name.localeCompare(b.name));
17600
+ other.sort((a, b) => a.section.localeCompare(b.section) || a.name.localeCompare(b.name));
17601
+ return {
17602
+ admin: {
17603
+ id: target.id,
17604
+ name: [target.firstname, target.lastname].filter(Boolean).join(" ").trim() || target.username || "",
17605
+ active: target.isActive === true,
17606
+ roles: (target.roles || []).map((role) => ({ name: role.name }))
17607
+ },
17608
+ contentTypes,
17609
+ otherPermissions: other.slice(0, 500)
17610
+ };
17611
+ }
17612
+ module.exports = {
17613
+ buildPreview,
17614
+ effectivePermissions,
17615
+ isSuperAdmin,
17616
+ loadAdmin,
17617
+ previewRefusal
17618
+ };
17619
+ }
17620
+ });
17621
+
17356
17622
  // server/src/services/impersonation.js
17357
17623
  var require_impersonation = __commonJS({
17358
17624
  "server/src/services/impersonation.js"(exports, module) {
@@ -17364,7 +17630,10 @@ var require_impersonation = __commonJS({
17364
17630
  var { getPluginSettings } = require_settings_loader();
17365
17631
  var { getNativeSessionManager } = require_native_session_manager();
17366
17632
  var { REVOCATION_UID } = require_session_revocation();
17633
+ var { buildPreview, loadAdmin, previewRefusal } = require_admin_preview();
17367
17634
  var {
17635
+ ADMIN_DURATIONS,
17636
+ ADMIN_ID_PATTERN,
17368
17637
  CODE_PATTERN,
17369
17638
  CODE_TTL_MS,
17370
17639
  DOCUMENT_ID_PATTERN,
@@ -17495,6 +17764,7 @@ var require_impersonation = __commonJS({
17495
17764
  handoff: frontend ? "frontend" : "token",
17496
17765
  frontendOrigin: frontend ? frontend.origin : null,
17497
17766
  durations: [...USER_DURATIONS],
17767
+ adminDurations: [...ADMIN_DURATIONS],
17498
17768
  mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
17499
17769
  };
17500
17770
  },
@@ -17620,6 +17890,137 @@ var require_impersonation = __commonJS({
17620
17890
  handoff
17621
17891
  };
17622
17892
  },
17893
+ /**
17894
+ * Starts a read-only permission preview of another admin ("View as
17895
+ * admin"). No session or token is created; the preview can be read by
17896
+ * the admin who started it until it ends.
17897
+ *
17898
+ * @param {{actor: any, adminId: unknown, body: unknown, canReadAdmins: boolean}} input
17899
+ * Caller (with roles), target id and request body.
17900
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17901
+ * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17902
+ * or not a subset of the caller's permissions; 404 unknown admin.
17903
+ * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17904
+ */
17905
+ async previewAdmin({ actor, adminId, body, canReadAdmins }) {
17906
+ const actorId = String(actor.id);
17907
+ const refuse = (reason, status, message, extra = {}) => {
17908
+ service.recordRefused({ actorId, targetType: "admin", targetId: adminId, reason });
17909
+ return new ImpersonationError(status, message, { reason, ...extra });
17910
+ };
17911
+ if (!await service.isEnabled()) {
17912
+ throw refuse("disabled", 403, "Impersonation is turned off");
17913
+ }
17914
+ if (typeof adminId !== "string" || !ADMIN_ID_PATTERN.test(adminId)) {
17915
+ throw new ImpersonationError(404, "Admin not found");
17916
+ }
17917
+ const { value, errors: fieldErrors } = validateStartBody(body, {
17918
+ durations: ADMIN_DURATIONS,
17919
+ notify: false
17920
+ });
17921
+ if (!value) {
17922
+ throw new ImpersonationError(400, "Invalid preview request", {
17923
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
17924
+ });
17925
+ }
17926
+ const [caller, target] = await Promise.all([
17927
+ loadAdmin(strapi2, actor.id),
17928
+ loadAdmin(strapi2, Number(adminId))
17929
+ ]);
17930
+ if (!target) throw new ImpersonationError(404, "Admin not found");
17931
+ const refusal = await previewRefusal(strapi2, caller || actor, target);
17932
+ if (refusal) {
17933
+ const messages = {
17934
+ self: "You cannot view yourself as another admin",
17935
+ "super-admin": "Super Admins cannot be viewed as another admin",
17936
+ "not-subset": "This admin has permissions that you do not have"
17937
+ };
17938
+ throw refuse(
17939
+ refusal.reason,
17940
+ 403,
17941
+ messages[refusal.reason],
17942
+ refusal.uncovered ? { uncovered: refusal.uncovered } : {}
17943
+ );
17944
+ }
17945
+ await service.sweep();
17946
+ const now = /* @__PURE__ */ new Date();
17947
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
17948
+ const row = await query().create({
17949
+ data: {
17950
+ targetType: "admin",
17951
+ targetId: String(target.id),
17952
+ actorId,
17953
+ state: "active",
17954
+ reason: value.reason,
17955
+ durationMinutes: value.durationMinutes,
17956
+ handoff: "preview",
17957
+ notifyUser: false,
17958
+ startedAt: now,
17959
+ expiresAt
17960
+ }
17961
+ });
17962
+ record({
17963
+ event: EVENTS.STARTED,
17964
+ actorType: "admin",
17965
+ actorId,
17966
+ targetType: "admin",
17967
+ targetId: String(target.id),
17968
+ meta: {
17969
+ reason: value.reason,
17970
+ durationMinutes: value.durationMinutes,
17971
+ handoff: "preview"
17972
+ }
17973
+ });
17974
+ const preview = await buildPreview(strapi2, target);
17975
+ if (!canReadAdmins) preview.admin.name = "";
17976
+ return {
17977
+ impersonation: service.toDto(row, {
17978
+ admins: /* @__PURE__ */ new Map([
17979
+ [String(target.id), canReadAdmins ? target : null],
17980
+ [actorId, caller || actor]
17981
+ ]),
17982
+ viewer: actor
17983
+ }),
17984
+ preview
17985
+ };
17986
+ },
17987
+ /**
17988
+ * The preview of a running admin preview, for the admin who started it.
17989
+ * An expired one is ended and answers 404 like an unknown one.
17990
+ *
17991
+ * @param {{id: unknown, viewer: any, canReadAdmins: boolean}} input Preview id and caller.
17992
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17993
+ * @throws {ImpersonationError} 404 unknown, ended, expired or started by someone else.
17994
+ */
17995
+ async getPreview({ id, viewer, canReadAdmins }) {
17996
+ if (typeof id !== "string" || !DOCUMENT_ID_PATTERN.test(id)) {
17997
+ throw new ImpersonationError(404, "Preview not found");
17998
+ }
17999
+ const row = await query().findOne({
18000
+ where: { documentId: id, targetType: "admin", state: "active" }
18001
+ });
18002
+ if (!row || String(row.actorId) !== String(viewer.id)) {
18003
+ throw new ImpersonationError(404, "Preview not found");
18004
+ }
18005
+ if (new Date(row.expiresAt).getTime() <= Date.now()) {
18006
+ await service.end(row.documentId, { reason: "expired" });
18007
+ throw new ImpersonationError(404, "Preview not found");
18008
+ }
18009
+ const target = await loadAdmin(strapi2, Number(row.targetId));
18010
+ if (!target) {
18011
+ await service.end(row.documentId, { reason: "failed", silent: true });
18012
+ throw new ImpersonationError(404, "Preview not found");
18013
+ }
18014
+ const preview = await buildPreview(strapi2, target);
18015
+ if (!canReadAdmins) preview.admin.name = "";
18016
+ return {
18017
+ impersonation: service.toDto(row, {
18018
+ admins: /* @__PURE__ */ new Map([[String(target.id), canReadAdmins ? target : null]]),
18019
+ viewer
18020
+ }),
18021
+ preview
18022
+ };
18023
+ },
17623
18024
  /**
17624
18025
  * Mints the short-lived credential of an impersonation and links its
17625
18026
  * Magic session row.
@@ -17864,12 +18265,15 @@ var require_impersonation = __commonJS({
17864
18265
  return ended;
17865
18266
  },
17866
18267
  /**
17867
- * Active impersonations of the given target types, newest first.
18268
+ * Active impersonations of the given target types, newest first. Admin
18269
+ * names are shown only to callers who may read admin users (as in the
18270
+ * Admin panel view); the caller's own name always.
17868
18271
  *
17869
- * @param {{targetTypes: Array<'user'|'admin'>, viewer: any}} input Kinds the caller may see.
18272
+ * @param {{targetTypes: Array<'user'|'admin'>, viewer: any, canReadAdmins?: boolean}} input
18273
+ * Kinds the caller may see.
17870
18274
  * @returns {Promise<object[]>} DTOs.
17871
18275
  */
17872
- async listActive({ targetTypes, viewer }) {
18276
+ async listActive({ targetTypes, viewer, canReadAdmins = true }) {
17873
18277
  if (!targetTypes.length) return [];
17874
18278
  await service.sweep();
17875
18279
  const rows = await query().findMany({
@@ -17888,7 +18292,11 @@ var require_impersonation = __commonJS({
17888
18292
  select: ["documentId", "username", "email"]
17889
18293
  }) : [];
17890
18294
  const admins = adminIds.length ? await strapi2.db.query("admin::user").findMany({
17891
- where: { id: { $in: adminIds } },
18295
+ where: {
18296
+ id: {
18297
+ $in: canReadAdmins ? adminIds : adminIds.filter((id) => String(id) === String(viewer?.id))
18298
+ }
18299
+ },
17892
18300
  select: ["id", "firstname", "lastname", "username", "email"]
17893
18301
  }) : [];
17894
18302
  const context = {
@@ -18060,6 +18468,7 @@ var require_impersonation2 = __commonJS({
18060
18468
  var { ImpersonationError } = require_impersonation();
18061
18469
  var { sendServerError } = require_http_errors();
18062
18470
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18471
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
18063
18472
  function callerCan(ctx, action) {
18064
18473
  try {
18065
18474
  return ctx?.state?.userAbility?.can?.(action) === true;
@@ -18068,7 +18477,10 @@ var require_impersonation2 = __commonJS({
18068
18477
  }
18069
18478
  }
18070
18479
  function visibleTargetTypes(ctx) {
18071
- return callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [];
18480
+ return [
18481
+ ...callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [],
18482
+ ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) ? ["admin"] : []
18483
+ ];
18072
18484
  }
18073
18485
  var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
18074
18486
  async function respond(ctx, operation, handler) {
@@ -18141,17 +18553,19 @@ var require_impersonation2 = __commonJS({
18141
18553
  },
18142
18554
  /**
18143
18555
  * Active impersonations the caller may see: app users with
18144
- * `impersonate.users`.
18556
+ * `impersonate.users`, admin previews with `impersonate.admins`. Admin
18557
+ * names need `admin::users.read`, as in the Admin panel view.
18145
18558
  *
18146
18559
  * @route GET /magic-sessionmanager/impersonation/active
18147
- * @auth Admin JWT or admin API token; `access` + `impersonate.users`.
18560
+ * @auth Admin JWT or admin API token; `access` + one of the impersonate actions.
18148
18561
  * @returns {Promise<void>} `{ data: Impersonation[] }` (at most 100).
18149
18562
  */
18150
18563
  async listActive(ctx) {
18151
18564
  return respond(ctx, "list", async () => {
18152
18565
  const data = await service().listActive({
18153
18566
  targetTypes: visibleTargetTypes(ctx),
18154
- viewer: ctx.state.user
18567
+ viewer: ctx.state.user,
18568
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18155
18569
  });
18156
18570
  ctx.body = { data };
18157
18571
  });
@@ -18160,7 +18574,8 @@ var require_impersonation2 = __commonJS({
18160
18574
  * Ends an active impersonation now.
18161
18575
  *
18162
18576
  * @route POST /magic-sessionmanager/impersonation/:id/end
18163
- * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind.
18577
+ * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind
18578
+ * (`impersonate.users` for app users, `impersonate.admins` for admin previews).
18164
18579
  * @returns {Promise<void>} `{ data: { ended: boolean } }`.
18165
18580
  * Answers 404 for an unknown id or a kind the caller may not see.
18166
18581
  * @sideeffect Revokes the credential; logs `impersonation.ended`.
@@ -18179,6 +18594,54 @@ var require_impersonation2 = __commonJS({
18179
18594
  ctx.body = { data: { ended } };
18180
18595
  });
18181
18596
  },
18597
+ /**
18598
+ * Starts a read-only permission preview of another admin ("View as
18599
+ * admin"): which content types and actions they can use. No session or
18600
+ * token is created.
18601
+ *
18602
+ * @route POST /magic-sessionmanager/impersonation/admins/:adminId/preview
18603
+ * @auth Admin JWT only (admin API tokens are refused); `access` + `impersonate.admins`.
18604
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30 }`.
18605
+ * @returns {Promise<void>} 201 `{ data: { impersonation, preview } }`. Answers 403 with
18606
+ * `details.reason` `disabled`, `api-token`, `self`, `super-admin` or `not-subset`,
18607
+ * 400 for an invalid body and 404 for an unknown admin.
18608
+ * @sideeffect Creates a preview row; logs `impersonation.started` or `.refused`.
18609
+ */
18610
+ async previewAdmin(ctx) {
18611
+ ctx.set("Cache-Control", "no-store");
18612
+ return respond(ctx, "preview", async () => {
18613
+ const { adminId } = ctx.params;
18614
+ requirePerson(ctx, "admin", adminId);
18615
+ const result = await service().previewAdmin({
18616
+ actor: ctx.state.user,
18617
+ adminId,
18618
+ body: ctx.request.body,
18619
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18620
+ });
18621
+ ctx.status = 201;
18622
+ ctx.body = { data: result };
18623
+ });
18624
+ },
18625
+ /**
18626
+ * Reads a running admin preview; only the admin who started it.
18627
+ *
18628
+ * @route GET /magic-sessionmanager/impersonation/previews/:id
18629
+ * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
18630
+ * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
18631
+ * expired or started by someone else.
18632
+ */
18633
+ async getPreview(ctx) {
18634
+ ctx.set("Cache-Control", "no-store");
18635
+ return respond(ctx, "preview", async () => {
18636
+ ctx.body = {
18637
+ data: await service().getPreview({
18638
+ id: ctx.params.id,
18639
+ viewer: ctx.state.user,
18640
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18641
+ })
18642
+ };
18643
+ });
18644
+ },
18182
18645
  /**
18183
18646
  * Exchanges a one-time hand-off code for the impersonation credential.
18184
18647
  * Public on purpose: the code is the credential (32 random bytes, stored
@@ -18205,6 +18668,7 @@ var require_impersonation2 = __commonJS({
18205
18668
  };
18206
18669
  };
18207
18670
  module.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
18671
+ module.exports.IMPERSONATE_ADMINS_ACTION = IMPERSONATE_ADMINS_ACTION;
18208
18672
  }
18209
18673
  });
18210
18674
 
@@ -22688,13 +23152,33 @@ var require_session_required = __commonJS({
22688
23152
  }
22689
23153
  });
22690
23154
 
23155
+ // server/src/policies/can-impersonate.js
23156
+ var require_can_impersonate = __commonJS({
23157
+ "server/src/policies/can-impersonate.js"(exports, module) {
23158
+ "use strict";
23159
+ module.exports = (policyContext) => {
23160
+ const ability = policyContext?.state?.userAbility;
23161
+ const can = (action) => {
23162
+ try {
23163
+ return ability?.can?.(action) === true;
23164
+ } catch {
23165
+ return false;
23166
+ }
23167
+ };
23168
+ return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins");
23169
+ };
23170
+ }
23171
+ });
23172
+
22691
23173
  // server/src/policies/index.js
22692
23174
  var require_policies = __commonJS({
22693
23175
  "server/src/policies/index.js"(exports, module) {
22694
23176
  "use strict";
22695
23177
  var sessionRequired = require_session_required();
23178
+ var canImpersonate = require_can_impersonate();
22696
23179
  module.exports = {
22697
- "session-required": sessionRequired
23180
+ "session-required": sessionRequired,
23181
+ "can-impersonate": canImpersonate
22698
23182
  };
22699
23183
  }
22700
23184
  });
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.20.0",
2
+ "version": "4.21.0",
3
3
  "keywords": [
4
4
  "strapi",
5
5
  "strapi-plugin",