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
@@ -1693,12 +1693,14 @@ var require_impersonation_rules = __commonJS({
1693
1693
  var IMPERSONATION_DEFAULTS = Object.freeze({ impersonationEnabled: false });
1694
1694
  var IMPERSONATION_KEYS = Object.freeze(Object.keys(IMPERSONATION_DEFAULTS));
1695
1695
  var USER_DURATIONS = Object.freeze([15, 30, 60]);
1696
+ var ADMIN_DURATIONS = Object.freeze([15, 30]);
1696
1697
  var REASON_MIN = 3;
1697
1698
  var REASON_MAX = 255;
1698
1699
  var CODE_TTL_MS = 60 * 1e3;
1699
1700
  var IMPERSONATION_HEADER = "X-Magic-Impersonation";
1700
1701
  var CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
1701
1702
  var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1703
+ var ADMIN_ID_PATTERN = /^[1-9][0-9]{0,15}$/;
1702
1704
  var LOOPBACK_HOSTS = Object.freeze(["localhost", "127.0.0.1", "[::1]"]);
1703
1705
  function normalizeImpersonationSettings(stored) {
1704
1706
  return { impersonationEnabled: stored?.impersonationEnabled === true };
@@ -1901,6 +1903,8 @@ var require_impersonation_rules = __commonJS({
1901
1903
  }
1902
1904
  }
1903
1905
  module2.exports = {
1906
+ ADMIN_DURATIONS,
1907
+ ADMIN_ID_PATTERN,
1904
1908
  CODE_PATTERN,
1905
1909
  CODE_TTL_MS,
1906
1910
  DOCUMENT_ID_PATTERN,
@@ -2735,6 +2739,17 @@ var require_register = __commonJS({
2735
2739
  uid: "impersonate.users",
2736
2740
  subCategory: "Impersonation",
2737
2741
  pluginName: "magic-sessionmanager"
2742
+ },
2743
+ // "View as admin" (4.20): a read-only preview of which content types and
2744
+ // actions another admin can use. Never a Super Admin, never oneself, and
2745
+ // for non-Super-Admins only admins whose permissions are a subset of
2746
+ // their own.
2747
+ {
2748
+ section: "plugins",
2749
+ displayName: "View as admin (read-only permission preview)",
2750
+ uid: "impersonate.admins",
2751
+ subCategory: "Impersonation",
2752
+ pluginName: "magic-sessionmanager"
2738
2753
  }
2739
2754
  ]);
2740
2755
  disableGraphqlShadowCrud(strapi2, log);
@@ -12107,6 +12122,11 @@ var require_admin = __commonJS({
12107
12122
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12108
12123
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12109
12124
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
12125
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
12126
+ var impersonationListPolicy = () => [
12127
+ ...adminPolicy(),
12128
+ "plugin::magic-sessionmanager.can-impersonate"
12129
+ ];
12110
12130
  var adminPolicy = () => [
12111
12131
  "admin::isAuthenticatedAdmin",
12112
12132
  {
@@ -12471,12 +12491,36 @@ var require_admin = __commonJS({
12471
12491
  ]
12472
12492
  }
12473
12493
  },
12494
+ {
12495
+ method: "POST",
12496
+ path: "/impersonation/admins/:adminId/preview",
12497
+ handler: "impersonation.previewAdmin",
12498
+ config: {
12499
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12500
+ // Ten previews per ten minutes per admin.
12501
+ middlewares: [
12502
+ {
12503
+ name: "plugin::magic-sessionmanager.rate-limit",
12504
+ config: { max: 10, window: 10 * 60 * 1e3 }
12505
+ }
12506
+ ]
12507
+ }
12508
+ },
12509
+ {
12510
+ method: "GET",
12511
+ path: "/impersonation/previews/:id",
12512
+ handler: "impersonation.getPreview",
12513
+ config: {
12514
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12515
+ middlewares: adminReadRateLimit()
12516
+ }
12517
+ },
12474
12518
  {
12475
12519
  method: "GET",
12476
12520
  path: "/impersonation/active",
12477
12521
  handler: "impersonation.listActive",
12478
12522
  config: {
12479
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12523
+ policies: impersonationListPolicy(),
12480
12524
  middlewares: adminReadRateLimit()
12481
12525
  }
12482
12526
  },
@@ -12485,7 +12529,7 @@ var require_admin = __commonJS({
12485
12529
  path: "/impersonation/:id/end",
12486
12530
  handler: "impersonation.end",
12487
12531
  config: {
12488
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12532
+ policies: impersonationListPolicy(),
12489
12533
  middlewares: adminSignOutRateLimit()
12490
12534
  }
12491
12535
  },
@@ -17347,6 +17391,228 @@ var require_webhooks = __commonJS({
17347
17391
  }
17348
17392
  });
17349
17393
 
17394
+ // server/src/utils/permission-subset.js
17395
+ var require_permission_subset = __commonJS({
17396
+ "server/src/utils/permission-subset.js"(exports2, module2) {
17397
+ "use strict";
17398
+ function grantsNothing(permission) {
17399
+ const fields = permission?.properties?.fields;
17400
+ return Array.isArray(fields) && fields.length === 0;
17401
+ }
17402
+ function parametersKey(value) {
17403
+ const normalize = (input) => {
17404
+ if (Array.isArray(input)) {
17405
+ return input.every((item) => typeof item === "string") ? [...new Set(input)].sort() : input.map(normalize);
17406
+ }
17407
+ if (input && typeof input === "object") {
17408
+ return Object.fromEntries(
17409
+ Object.keys(input).filter((key) => input[key] !== void 0).sort().map((key) => [key, normalize(input[key])])
17410
+ );
17411
+ }
17412
+ return input;
17413
+ };
17414
+ return JSON.stringify(normalize(value ?? {}));
17415
+ }
17416
+ function coversValue(held, property, value) {
17417
+ const allowed = held.properties?.[property];
17418
+ if (allowed === void 0 || allowed === null) return true;
17419
+ if (value === null || !Array.isArray(allowed)) return false;
17420
+ return allowed.some(
17421
+ (entry) => entry === value || property === "fields" && value.startsWith(`${entry}.`)
17422
+ );
17423
+ }
17424
+ function coversCondition(held, condition) {
17425
+ const conditions = held.conditions ?? [];
17426
+ if (conditions.length === 0) return true;
17427
+ return condition !== null && conditions.includes(condition);
17428
+ }
17429
+ function isPermissionCovered(requested, held) {
17430
+ if (grantsNothing(requested)) return true;
17431
+ const subject = requested.subject ?? null;
17432
+ const parameters = parametersKey(requested.actionParameters);
17433
+ const matching = held.filter(
17434
+ (permission) => permission.action === requested.action && (permission.subject ?? null) === subject && parametersKey(permission.actionParameters) === parameters && !grantsNothing(permission)
17435
+ );
17436
+ if (matching.length === 0) return false;
17437
+ const properties = [
17438
+ .../* @__PURE__ */ new Set([
17439
+ ...Object.keys(requested.properties ?? {}),
17440
+ ...matching.flatMap((permission) => Object.keys(permission.properties ?? {}))
17441
+ ])
17442
+ ];
17443
+ const dimensions = [];
17444
+ for (const property of properties) {
17445
+ const values = requested.properties?.[property];
17446
+ if (!Array.isArray(values)) dimensions.push({ property, values: [null] });
17447
+ else if (values.length > 0) {
17448
+ dimensions.push({ property, values: [...new Set(values.map(String))] });
17449
+ }
17450
+ }
17451
+ const conditions = (requested.conditions ?? []).length === 0 ? [null] : [...new Set(requested.conditions)];
17452
+ const walk = (index, picked, condition) => {
17453
+ if (index === dimensions.length) {
17454
+ return matching.some(
17455
+ (permission) => Object.entries(picked).every(
17456
+ ([property2, value]) => coversValue(permission, property2, value)
17457
+ ) && coversCondition(permission, condition)
17458
+ );
17459
+ }
17460
+ const { property, values } = dimensions[index];
17461
+ return values.every((value) => walk(index + 1, { ...picked, [property]: value }, condition));
17462
+ };
17463
+ return conditions.every((condition) => walk(0, {}, condition));
17464
+ }
17465
+ function uncoveredPermissions(target, actor) {
17466
+ return target.filter((permission) => !isPermissionCovered(permission, actor));
17467
+ }
17468
+ function toEnforced(permissions, context) {
17469
+ const out = [];
17470
+ for (const permission of permissions) {
17471
+ const conditions = permission.conditions ?? [];
17472
+ const registered = conditions.filter((id) => context.isConditionRegistered(id));
17473
+ if (conditions.length > 0 && registered.length === 0) continue;
17474
+ const properties = { ...permission.properties ?? {} };
17475
+ if (context.appliesLocales(permission)) {
17476
+ if (properties.locales === void 0) properties.locales = [];
17477
+ } else {
17478
+ delete properties.locales;
17479
+ }
17480
+ out.push({ ...permission, conditions: registered, properties });
17481
+ }
17482
+ return out;
17483
+ }
17484
+ module2.exports = { isPermissionCovered, toEnforced, uncoveredPermissions };
17485
+ }
17486
+ });
17487
+
17488
+ // server/src/utils/admin-preview.js
17489
+ var require_admin_preview = __commonJS({
17490
+ "server/src/utils/admin-preview.js"(exports2, module2) {
17491
+ "use strict";
17492
+ var { toEnforced, uncoveredPermissions } = require_permission_subset();
17493
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
17494
+ function isSuperAdmin(user) {
17495
+ return (user?.roles || []).some((role) => role?.code === SUPER_ADMIN_CODE);
17496
+ }
17497
+ async function loadAdmin(strapi2, id) {
17498
+ return strapi2.db.query("admin::user").findOne({
17499
+ where: { id },
17500
+ select: ["id", "firstname", "lastname", "username", "email", "isActive"],
17501
+ populate: { roles: { select: ["id", "name", "code"] } }
17502
+ });
17503
+ }
17504
+ async function effectivePermissions(strapi2, user) {
17505
+ const service = strapi2.admin.services.permission;
17506
+ const raw = await service.findUserPermissions(user);
17507
+ const appliesCache = /* @__PURE__ */ new Map();
17508
+ for (const permission of raw) {
17509
+ const key = `${permission.action}::${permission.subject}`;
17510
+ if (appliesCache.has(key)) continue;
17511
+ let applies;
17512
+ try {
17513
+ applies = Boolean(permission.subject) && service.actionProvider.has(permission.action) && await service.actionProvider.appliesToProperty(
17514
+ "locales",
17515
+ permission.action,
17516
+ permission.subject
17517
+ ) === true;
17518
+ } catch {
17519
+ applies = false;
17520
+ }
17521
+ appliesCache.set(key, applies);
17522
+ }
17523
+ return toEnforced(raw, {
17524
+ isConditionRegistered: (id) => {
17525
+ try {
17526
+ return service.conditionProvider.has(id) === true;
17527
+ } catch {
17528
+ return false;
17529
+ }
17530
+ },
17531
+ appliesLocales: (permission) => appliesCache.get(`${permission.action}::${permission.subject}`) === true
17532
+ });
17533
+ }
17534
+ async function previewRefusal(strapi2, actor, target) {
17535
+ if (String(actor.id) === String(target.id)) return { reason: "self" };
17536
+ if (isSuperAdmin(target)) return { reason: "super-admin" };
17537
+ if (isSuperAdmin(actor)) return null;
17538
+ const [held, wanted] = await Promise.all([
17539
+ effectivePermissions(strapi2, actor),
17540
+ effectivePermissions(strapi2, target)
17541
+ ]);
17542
+ const uncovered = uncoveredPermissions(wanted, held);
17543
+ return uncovered.length > 0 ? { reason: "not-subset", uncovered: uncovered.length } : null;
17544
+ }
17545
+ function contentAction(action) {
17546
+ const match = /^plugin::content-manager\.explorer\.([a-z-]+)$/.exec(action);
17547
+ return match ? match[1] : action;
17548
+ }
17549
+ async function buildPreview(strapi2, target) {
17550
+ const permissions = await effectivePermissions(strapi2, target);
17551
+ const provider = strapi2.admin.services.permission.actionProvider;
17552
+ const types = /* @__PURE__ */ new Map();
17553
+ const other = [];
17554
+ for (const permission of permissions) {
17555
+ const contentType = permission.subject ? strapi2.contentTypes?.[permission.subject] : null;
17556
+ if (contentType && permission.action.startsWith("plugin::content-manager.explorer.")) {
17557
+ const entry = types.get(permission.subject) || {
17558
+ uid: permission.subject,
17559
+ name: String(contentType.info?.displayName || permission.subject).slice(0, 120),
17560
+ kind: contentType.kind === "singleType" ? "single" : "collection",
17561
+ actions: []
17562
+ };
17563
+ const fields = permission.properties?.fields;
17564
+ const locales = permission.properties?.locales;
17565
+ entry.actions.push({
17566
+ action: contentAction(permission.action),
17567
+ fields: Array.isArray(fields) ? fields.length : null,
17568
+ locales: Array.isArray(locales) ? locales.slice(0, 20) : null,
17569
+ conditions: (permission.conditions || []).slice(0, 10)
17570
+ });
17571
+ types.set(permission.subject, entry);
17572
+ continue;
17573
+ }
17574
+ let definition;
17575
+ try {
17576
+ definition = provider.get(permission.action);
17577
+ } catch {
17578
+ definition = null;
17579
+ }
17580
+ other.push({
17581
+ action: permission.action,
17582
+ name: String(definition?.displayName || permission.action).slice(0, 160),
17583
+ section: String(definition?.section || "other"),
17584
+ scope: definition?.pluginName ? String(definition.pluginName) : null
17585
+ });
17586
+ }
17587
+ const order = ["create", "read", "update", "delete", "publish"];
17588
+ const contentTypes2 = [...types.values()].map((entry) => ({
17589
+ ...entry,
17590
+ actions: entry.actions.sort(
17591
+ (a, b) => (order.indexOf(a.action) + 1 || 99) - (order.indexOf(b.action) + 1 || 99) || a.action.localeCompare(b.action)
17592
+ )
17593
+ })).sort((a, b) => a.name.localeCompare(b.name));
17594
+ other.sort((a, b) => a.section.localeCompare(b.section) || a.name.localeCompare(b.name));
17595
+ return {
17596
+ admin: {
17597
+ id: target.id,
17598
+ name: [target.firstname, target.lastname].filter(Boolean).join(" ").trim() || target.username || "",
17599
+ active: target.isActive === true,
17600
+ roles: (target.roles || []).map((role) => ({ name: role.name }))
17601
+ },
17602
+ contentTypes: contentTypes2,
17603
+ otherPermissions: other.slice(0, 500)
17604
+ };
17605
+ }
17606
+ module2.exports = {
17607
+ buildPreview,
17608
+ effectivePermissions,
17609
+ isSuperAdmin,
17610
+ loadAdmin,
17611
+ previewRefusal
17612
+ };
17613
+ }
17614
+ });
17615
+
17350
17616
  // server/src/services/impersonation.js
17351
17617
  var require_impersonation = __commonJS({
17352
17618
  "server/src/services/impersonation.js"(exports2, module2) {
@@ -17358,7 +17624,10 @@ var require_impersonation = __commonJS({
17358
17624
  var { getPluginSettings } = require_settings_loader();
17359
17625
  var { getNativeSessionManager } = require_native_session_manager();
17360
17626
  var { REVOCATION_UID } = require_session_revocation();
17627
+ var { buildPreview, loadAdmin, previewRefusal } = require_admin_preview();
17361
17628
  var {
17629
+ ADMIN_DURATIONS,
17630
+ ADMIN_ID_PATTERN,
17362
17631
  CODE_PATTERN,
17363
17632
  CODE_TTL_MS,
17364
17633
  DOCUMENT_ID_PATTERN,
@@ -17489,6 +17758,7 @@ var require_impersonation = __commonJS({
17489
17758
  handoff: frontend ? "frontend" : "token",
17490
17759
  frontendOrigin: frontend ? frontend.origin : null,
17491
17760
  durations: [...USER_DURATIONS],
17761
+ adminDurations: [...ADMIN_DURATIONS],
17492
17762
  mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
17493
17763
  };
17494
17764
  },
@@ -17614,6 +17884,137 @@ var require_impersonation = __commonJS({
17614
17884
  handoff
17615
17885
  };
17616
17886
  },
17887
+ /**
17888
+ * Starts a read-only permission preview of another admin ("View as
17889
+ * admin"). No session or token is created; the preview can be read by
17890
+ * the admin who started it until it ends.
17891
+ *
17892
+ * @param {{actor: any, adminId: unknown, body: unknown, canReadAdmins: boolean}} input
17893
+ * Caller (with roles), target id and request body.
17894
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17895
+ * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17896
+ * or not a subset of the caller's permissions; 404 unknown admin.
17897
+ * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17898
+ */
17899
+ async previewAdmin({ actor, adminId, body, canReadAdmins }) {
17900
+ const actorId = String(actor.id);
17901
+ const refuse = (reason, status, message, extra = {}) => {
17902
+ service.recordRefused({ actorId, targetType: "admin", targetId: adminId, reason });
17903
+ return new ImpersonationError(status, message, { reason, ...extra });
17904
+ };
17905
+ if (!await service.isEnabled()) {
17906
+ throw refuse("disabled", 403, "Impersonation is turned off");
17907
+ }
17908
+ if (typeof adminId !== "string" || !ADMIN_ID_PATTERN.test(adminId)) {
17909
+ throw new ImpersonationError(404, "Admin not found");
17910
+ }
17911
+ const { value, errors: fieldErrors } = validateStartBody(body, {
17912
+ durations: ADMIN_DURATIONS,
17913
+ notify: false
17914
+ });
17915
+ if (!value) {
17916
+ throw new ImpersonationError(400, "Invalid preview request", {
17917
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
17918
+ });
17919
+ }
17920
+ const [caller, target] = await Promise.all([
17921
+ loadAdmin(strapi2, actor.id),
17922
+ loadAdmin(strapi2, Number(adminId))
17923
+ ]);
17924
+ if (!target) throw new ImpersonationError(404, "Admin not found");
17925
+ const refusal = await previewRefusal(strapi2, caller || actor, target);
17926
+ if (refusal) {
17927
+ const messages = {
17928
+ self: "You cannot view yourself as another admin",
17929
+ "super-admin": "Super Admins cannot be viewed as another admin",
17930
+ "not-subset": "This admin has permissions that you do not have"
17931
+ };
17932
+ throw refuse(
17933
+ refusal.reason,
17934
+ 403,
17935
+ messages[refusal.reason],
17936
+ refusal.uncovered ? { uncovered: refusal.uncovered } : {}
17937
+ );
17938
+ }
17939
+ await service.sweep();
17940
+ const now = /* @__PURE__ */ new Date();
17941
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
17942
+ const row = await query().create({
17943
+ data: {
17944
+ targetType: "admin",
17945
+ targetId: String(target.id),
17946
+ actorId,
17947
+ state: "active",
17948
+ reason: value.reason,
17949
+ durationMinutes: value.durationMinutes,
17950
+ handoff: "preview",
17951
+ notifyUser: false,
17952
+ startedAt: now,
17953
+ expiresAt
17954
+ }
17955
+ });
17956
+ record({
17957
+ event: EVENTS.STARTED,
17958
+ actorType: "admin",
17959
+ actorId,
17960
+ targetType: "admin",
17961
+ targetId: String(target.id),
17962
+ meta: {
17963
+ reason: value.reason,
17964
+ durationMinutes: value.durationMinutes,
17965
+ handoff: "preview"
17966
+ }
17967
+ });
17968
+ const preview = await buildPreview(strapi2, target);
17969
+ if (!canReadAdmins) preview.admin.name = "";
17970
+ return {
17971
+ impersonation: service.toDto(row, {
17972
+ admins: /* @__PURE__ */ new Map([
17973
+ [String(target.id), canReadAdmins ? target : null],
17974
+ [actorId, caller || actor]
17975
+ ]),
17976
+ viewer: actor
17977
+ }),
17978
+ preview
17979
+ };
17980
+ },
17981
+ /**
17982
+ * The preview of a running admin preview, for the admin who started it.
17983
+ * An expired one is ended and answers 404 like an unknown one.
17984
+ *
17985
+ * @param {{id: unknown, viewer: any, canReadAdmins: boolean}} input Preview id and caller.
17986
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17987
+ * @throws {ImpersonationError} 404 unknown, ended, expired or started by someone else.
17988
+ */
17989
+ async getPreview({ id, viewer, canReadAdmins }) {
17990
+ if (typeof id !== "string" || !DOCUMENT_ID_PATTERN.test(id)) {
17991
+ throw new ImpersonationError(404, "Preview not found");
17992
+ }
17993
+ const row = await query().findOne({
17994
+ where: { documentId: id, targetType: "admin", state: "active" }
17995
+ });
17996
+ if (!row || String(row.actorId) !== String(viewer.id)) {
17997
+ throw new ImpersonationError(404, "Preview not found");
17998
+ }
17999
+ if (new Date(row.expiresAt).getTime() <= Date.now()) {
18000
+ await service.end(row.documentId, { reason: "expired" });
18001
+ throw new ImpersonationError(404, "Preview not found");
18002
+ }
18003
+ const target = await loadAdmin(strapi2, Number(row.targetId));
18004
+ if (!target) {
18005
+ await service.end(row.documentId, { reason: "failed", silent: true });
18006
+ throw new ImpersonationError(404, "Preview not found");
18007
+ }
18008
+ const preview = await buildPreview(strapi2, target);
18009
+ if (!canReadAdmins) preview.admin.name = "";
18010
+ return {
18011
+ impersonation: service.toDto(row, {
18012
+ admins: /* @__PURE__ */ new Map([[String(target.id), canReadAdmins ? target : null]]),
18013
+ viewer
18014
+ }),
18015
+ preview
18016
+ };
18017
+ },
17617
18018
  /**
17618
18019
  * Mints the short-lived credential of an impersonation and links its
17619
18020
  * Magic session row.
@@ -17858,12 +18259,15 @@ var require_impersonation = __commonJS({
17858
18259
  return ended;
17859
18260
  },
17860
18261
  /**
17861
- * Active impersonations of the given target types, newest first.
18262
+ * Active impersonations of the given target types, newest first. Admin
18263
+ * names are shown only to callers who may read admin users (as in the
18264
+ * Admin panel view); the caller's own name always.
17862
18265
  *
17863
- * @param {{targetTypes: Array<'user'|'admin'>, viewer: any}} input Kinds the caller may see.
18266
+ * @param {{targetTypes: Array<'user'|'admin'>, viewer: any, canReadAdmins?: boolean}} input
18267
+ * Kinds the caller may see.
17864
18268
  * @returns {Promise<object[]>} DTOs.
17865
18269
  */
17866
- async listActive({ targetTypes, viewer }) {
18270
+ async listActive({ targetTypes, viewer, canReadAdmins = true }) {
17867
18271
  if (!targetTypes.length) return [];
17868
18272
  await service.sweep();
17869
18273
  const rows = await query().findMany({
@@ -17882,7 +18286,11 @@ var require_impersonation = __commonJS({
17882
18286
  select: ["documentId", "username", "email"]
17883
18287
  }) : [];
17884
18288
  const admins = adminIds.length ? await strapi2.db.query("admin::user").findMany({
17885
- where: { id: { $in: adminIds } },
18289
+ where: {
18290
+ id: {
18291
+ $in: canReadAdmins ? adminIds : adminIds.filter((id) => String(id) === String(viewer?.id))
18292
+ }
18293
+ },
17886
18294
  select: ["id", "firstname", "lastname", "username", "email"]
17887
18295
  }) : [];
17888
18296
  const context = {
@@ -18054,6 +18462,7 @@ var require_impersonation2 = __commonJS({
18054
18462
  var { ImpersonationError } = require_impersonation();
18055
18463
  var { sendServerError } = require_http_errors();
18056
18464
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18465
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
18057
18466
  function callerCan(ctx, action) {
18058
18467
  try {
18059
18468
  return ctx?.state?.userAbility?.can?.(action) === true;
@@ -18062,7 +18471,10 @@ var require_impersonation2 = __commonJS({
18062
18471
  }
18063
18472
  }
18064
18473
  function visibleTargetTypes(ctx) {
18065
- return callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [];
18474
+ return [
18475
+ ...callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [],
18476
+ ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) ? ["admin"] : []
18477
+ ];
18066
18478
  }
18067
18479
  var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
18068
18480
  async function respond(ctx, operation, handler) {
@@ -18135,17 +18547,19 @@ var require_impersonation2 = __commonJS({
18135
18547
  },
18136
18548
  /**
18137
18549
  * Active impersonations the caller may see: app users with
18138
- * `impersonate.users`.
18550
+ * `impersonate.users`, admin previews with `impersonate.admins`. Admin
18551
+ * names need `admin::users.read`, as in the Admin panel view.
18139
18552
  *
18140
18553
  * @route GET /magic-sessionmanager/impersonation/active
18141
- * @auth Admin JWT or admin API token; `access` + `impersonate.users`.
18554
+ * @auth Admin JWT or admin API token; `access` + one of the impersonate actions.
18142
18555
  * @returns {Promise<void>} `{ data: Impersonation[] }` (at most 100).
18143
18556
  */
18144
18557
  async listActive(ctx) {
18145
18558
  return respond(ctx, "list", async () => {
18146
18559
  const data = await service().listActive({
18147
18560
  targetTypes: visibleTargetTypes(ctx),
18148
- viewer: ctx.state.user
18561
+ viewer: ctx.state.user,
18562
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18149
18563
  });
18150
18564
  ctx.body = { data };
18151
18565
  });
@@ -18154,7 +18568,8 @@ var require_impersonation2 = __commonJS({
18154
18568
  * Ends an active impersonation now.
18155
18569
  *
18156
18570
  * @route POST /magic-sessionmanager/impersonation/:id/end
18157
- * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind.
18571
+ * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind
18572
+ * (`impersonate.users` for app users, `impersonate.admins` for admin previews).
18158
18573
  * @returns {Promise<void>} `{ data: { ended: boolean } }`.
18159
18574
  * Answers 404 for an unknown id or a kind the caller may not see.
18160
18575
  * @sideeffect Revokes the credential; logs `impersonation.ended`.
@@ -18173,6 +18588,54 @@ var require_impersonation2 = __commonJS({
18173
18588
  ctx.body = { data: { ended } };
18174
18589
  });
18175
18590
  },
18591
+ /**
18592
+ * Starts a read-only permission preview of another admin ("View as
18593
+ * admin"): which content types and actions they can use. No session or
18594
+ * token is created.
18595
+ *
18596
+ * @route POST /magic-sessionmanager/impersonation/admins/:adminId/preview
18597
+ * @auth Admin JWT only (admin API tokens are refused); `access` + `impersonate.admins`.
18598
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30 }`.
18599
+ * @returns {Promise<void>} 201 `{ data: { impersonation, preview } }`. Answers 403 with
18600
+ * `details.reason` `disabled`, `api-token`, `self`, `super-admin` or `not-subset`,
18601
+ * 400 for an invalid body and 404 for an unknown admin.
18602
+ * @sideeffect Creates a preview row; logs `impersonation.started` or `.refused`.
18603
+ */
18604
+ async previewAdmin(ctx) {
18605
+ ctx.set("Cache-Control", "no-store");
18606
+ return respond(ctx, "preview", async () => {
18607
+ const { adminId } = ctx.params;
18608
+ requirePerson(ctx, "admin", adminId);
18609
+ const result = await service().previewAdmin({
18610
+ actor: ctx.state.user,
18611
+ adminId,
18612
+ body: ctx.request.body,
18613
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18614
+ });
18615
+ ctx.status = 201;
18616
+ ctx.body = { data: result };
18617
+ });
18618
+ },
18619
+ /**
18620
+ * Reads a running admin preview; only the admin who started it.
18621
+ *
18622
+ * @route GET /magic-sessionmanager/impersonation/previews/:id
18623
+ * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
18624
+ * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
18625
+ * expired or started by someone else.
18626
+ */
18627
+ async getPreview(ctx) {
18628
+ ctx.set("Cache-Control", "no-store");
18629
+ return respond(ctx, "preview", async () => {
18630
+ ctx.body = {
18631
+ data: await service().getPreview({
18632
+ id: ctx.params.id,
18633
+ viewer: ctx.state.user,
18634
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18635
+ })
18636
+ };
18637
+ });
18638
+ },
18176
18639
  /**
18177
18640
  * Exchanges a one-time hand-off code for the impersonation credential.
18178
18641
  * Public on purpose: the code is the credential (32 random bytes, stored
@@ -18199,6 +18662,7 @@ var require_impersonation2 = __commonJS({
18199
18662
  };
18200
18663
  };
18201
18664
  module2.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
18665
+ module2.exports.IMPERSONATE_ADMINS_ACTION = IMPERSONATE_ADMINS_ACTION;
18202
18666
  }
18203
18667
  });
18204
18668
 
@@ -22682,13 +23146,33 @@ var require_session_required = __commonJS({
22682
23146
  }
22683
23147
  });
22684
23148
 
23149
+ // server/src/policies/can-impersonate.js
23150
+ var require_can_impersonate = __commonJS({
23151
+ "server/src/policies/can-impersonate.js"(exports2, module2) {
23152
+ "use strict";
23153
+ module2.exports = (policyContext) => {
23154
+ const ability = policyContext?.state?.userAbility;
23155
+ const can = (action) => {
23156
+ try {
23157
+ return ability?.can?.(action) === true;
23158
+ } catch {
23159
+ return false;
23160
+ }
23161
+ };
23162
+ return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins");
23163
+ };
23164
+ }
23165
+ });
23166
+
22685
23167
  // server/src/policies/index.js
22686
23168
  var require_policies = __commonJS({
22687
23169
  "server/src/policies/index.js"(exports2, module2) {
22688
23170
  "use strict";
22689
23171
  var sessionRequired = require_session_required();
23172
+ var canImpersonate = require_can_impersonate();
22690
23173
  module2.exports = {
22691
- "session-required": sessionRequired
23174
+ "session-required": sessionRequired,
23175
+ "can-impersonate": canImpersonate
22692
23176
  };
22693
23177
  }
22694
23178
  });