strapi-plugin-magic-mark 3.4.0 → 4.0.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 (48) hide show
  1. package/CHANGELOG.md +366 -0
  2. package/README.md +390 -619
  3. package/dist/admin/App-C9PsvW9C.mjs +580 -0
  4. package/dist/admin/App-KJvUCwN1.js +580 -0
  5. package/dist/admin/PinnedBookmarksWidget-ClskVR1i.mjs +55 -0
  6. package/dist/admin/PinnedBookmarksWidget-DlD8lDhq.js +55 -0
  7. package/dist/admin/de-BF0nCjGF.mjs +183 -0
  8. package/dist/admin/de-Cn90CcnC.js +183 -0
  9. package/dist/admin/en-D-EGHodf.mjs +183 -0
  10. package/dist/admin/en-GDfO_EfL.js +183 -0
  11. package/dist/admin/es-6o-_RABX.js +183 -0
  12. package/dist/admin/es-C33BufuB.mjs +183 -0
  13. package/dist/admin/fr-BOZS5mJT.js +183 -0
  14. package/dist/admin/fr-DJHTjkmb.mjs +183 -0
  15. package/dist/admin/index-CLjQOzqv.js +1770 -0
  16. package/dist/admin/index-X8I03cOT.mjs +1769 -0
  17. package/dist/admin/index.js +4 -2
  18. package/dist/admin/index.mjs +2 -1
  19. package/dist/admin/pt-D13SxuK2.js +183 -0
  20. package/dist/admin/pt-yoB1jrsq.mjs +183 -0
  21. package/dist/server/index.js +1129 -1542
  22. package/dist/server/index.mjs +1126 -1539
  23. package/package.json +90 -54
  24. package/strapi-admin.js +5 -0
  25. package/strapi-server.js +2 -1
  26. package/COPYRIGHT_NOTICE.txt +0 -20
  27. package/dist/_chunks/App-DNyxeldt.js +0 -1451
  28. package/dist/_chunks/App-D_Vllkur.mjs +0 -1449
  29. package/dist/_chunks/UpgradePage-DuyIskve.mjs +0 -351
  30. package/dist/_chunks/UpgradePage-SzlmS6po.js +0 -353
  31. package/dist/_chunks/de-Cs9dd3Mr.js +0 -138
  32. package/dist/_chunks/de-DOVki5VS.mjs +0 -138
  33. package/dist/_chunks/en-CE3r46Y2.js +0 -138
  34. package/dist/_chunks/en-Cf5-O03L.mjs +0 -138
  35. package/dist/_chunks/es-Ba6JcPIm.mjs +0 -138
  36. package/dist/_chunks/es-D4AOyJYJ.js +0 -138
  37. package/dist/_chunks/fr-CWSfoA8i.js +0 -138
  38. package/dist/_chunks/fr-CrMBXR3c.mjs +0 -138
  39. package/dist/_chunks/index-CBwb0AEf.js +0 -3618
  40. package/dist/_chunks/index-JirQF8zE.mjs +0 -328
  41. package/dist/_chunks/index-QkINaIgJ.mjs +0 -3614
  42. package/dist/_chunks/index-uUErgmi9.js +0 -330
  43. package/dist/_chunks/pt-BXxZ1Zym.mjs +0 -138
  44. package/dist/_chunks/pt-DW_6r_mP.js +0 -138
  45. package/pics/advancedFilters.png +0 -0
  46. package/pics/dashboard.png +0 -0
  47. package/pics/quickaccesinContentmanager.png +0 -0
  48. package/pics/saveAsMagicMark.png +0 -0
@@ -1,160 +1,101 @@
1
1
  "use strict";
2
- const crypto = require("crypto");
3
- const os = require("os");
4
- const fs = require("fs");
5
- const path = require("path");
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const utils = require("@strapi/utils");
4
+ const qs = require("qs");
5
+ const zod = require("zod");
6
6
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
7
- const crypto__default = /* @__PURE__ */ _interopDefault(crypto);
8
- const os__default = /* @__PURE__ */ _interopDefault(os);
9
- const PLUGIN_NAME = "magic-mark";
10
- const PREFIX = "[Magic-Mark]";
11
- function formatMessage(prefix, args) {
12
- if (args.length === 0) return prefix;
13
- const parts = args.map(
14
- (arg) => typeof arg === "string" ? arg : JSON.stringify(arg)
15
- );
16
- return `${prefix} ${parts.join(" ")}`;
17
- }
18
- function createLogger(strapi) {
19
- const getDebugMode = () => {
20
- try {
21
- const config2 = strapi.config.get(`plugin::${PLUGIN_NAME}`) || {};
22
- return config2.debug === true;
23
- } catch {
24
- return false;
25
- }
26
- };
27
- return {
28
- /**
29
- * Log info - only when debug: true
30
- */
31
- info: (...args) => {
32
- if (getDebugMode()) {
33
- strapi.log.info(formatMessage(PREFIX, args));
34
- }
35
- },
36
- /**
37
- * Log debug - only when debug: true
38
- */
39
- debug: (...args) => {
40
- if (getDebugMode()) {
41
- strapi.log.debug(formatMessage(PREFIX, args));
42
- }
43
- },
44
- /**
45
- * Log warning - only when debug: true
46
- */
47
- warn: (...args) => {
48
- if (getDebugMode()) {
49
- strapi.log.warn(formatMessage(PREFIX, args));
50
- }
51
- },
52
- /**
53
- * Log error - only when debug: true
54
- */
55
- error: (...args) => {
56
- if (getDebugMode()) {
57
- strapi.log.error(formatMessage(PREFIX, args));
58
- }
59
- },
60
- /**
61
- * Force log - always logged (for critical errors only)
62
- */
63
- forceError: (...args) => {
64
- strapi.log.error(formatMessage(PREFIX, args));
65
- }
66
- };
67
- }
68
- const magicMarkActions = {
69
- actions: [
70
- {
71
- section: "plugins",
72
- displayName: "Read",
73
- uid: "settings.read",
74
- subCategory: "Settings",
75
- pluginName: "magic-mark"
76
- },
77
- {
78
- section: "plugins",
79
- displayName: "Edit",
80
- uid: "settings.update",
81
- subCategory: "Settings",
82
- pluginName: "magic-mark"
83
- }
84
- ]
7
+ const qs__default = /* @__PURE__ */ _interopDefault(qs);
8
+ const PLUGIN_ID = "magic-mark";
9
+ const BOOKMARK_UID = "plugin::magic-mark.bookmark";
10
+ const SHARE_UID = "plugin::magic-mark.bookmark-share";
11
+ const PREFERENCE_UID = "plugin::magic-mark.bookmark-preference";
12
+ const ADMIN_USER_UID = "admin::user";
13
+ const ADMIN_ROLE_UID = "admin::role";
14
+ const ADMIN_PERMISSION_UID = "admin::permission";
15
+ const SUPER_ADMIN_CODE = "strapi-super-admin";
16
+ const ACTION_UIDS = {
17
+ read: "bookmarks.read",
18
+ create: "bookmarks.create",
19
+ update: "bookmarks.update",
20
+ delete: "bookmarks.delete",
21
+ share: "bookmarks.share",
22
+ manage: "bookmarks.manage"
85
23
  };
86
- const register = async ({ strapi }) => {
87
- const log = createLogger(strapi);
88
- await strapi.admin.services.permission.actionProvider.registerMany(
89
- magicMarkActions.actions
90
- );
91
- log.info("Plugin registered successfully");
24
+ const actionId = (key) => `plugin::${PLUGIN_ID}.${ACTION_UIDS[key]}`;
25
+ const LEGACY_ACTION_MAP = {
26
+ [`plugin::${PLUGIN_ID}.settings.read`]: ["read"],
27
+ [`plugin::${PLUGIN_ID}.settings.update`]: ["read", "create", "update", "delete", "share"]
28
+ };
29
+ const LEGACY_STORE_KEYS = ["licenseKey", "lastValidated"];
30
+ const LIMITS = {
31
+ pageSizeMax: 100,
32
+ shareTargetsMax: 200,
33
+ userSearchPageSize: 20,
34
+ migrationBatch: 200
92
35
  };
93
- const bootstrap = ({ strapi }) => {
94
- const log = createLogger(strapi);
95
- log.info("Plugin bootstrapping...");
36
+ const STATE_KEY = "magicMarkDeletedIds";
37
+ let unsubscribe = null;
38
+ const detachLifecycles = () => {
39
+ unsubscribe?.();
40
+ unsubscribe = null;
41
+ };
42
+ const bootstrap = async ({ strapi }) => {
43
+ const maintenance = strapi.plugin(PLUGIN_ID).service("maintenance");
96
44
  try {
97
- const licenseGuardService2 = strapi.plugin("magic-mark").service("license-guard");
98
- setTimeout(async () => {
99
- const licenseStatus = await licenseGuardService2.initialize();
100
- if (!licenseStatus.valid) {
101
- log.error("╔════════════════════════════════════════════════════════════════╗");
102
- log.error("║ [ERROR] MAGICMARK PLUGIN - NO VALID LICENSE ║");
103
- log.error("║ ║");
104
- log.error("║ This plugin requires a valid license to operate. ║");
105
- log.error("║ Please activate your license via Admin UI: ║");
106
- log.error("║ Go to Settings → MagicMark → License ║");
107
- log.error("║ ║");
108
- log.error("║ The plugin will run with limited functionality until ║");
109
- log.error("║ a valid license is activated. ║");
110
- log.error("╚════════════════════════════════════════════════════════════════╝");
111
- } else if (licenseStatus.valid) {
112
- const pluginStore = strapi.store({
113
- type: "plugin",
114
- name: "magic-mark"
115
- });
116
- const storedKey = await pluginStore.get({ key: "licenseKey" });
117
- log.info("╔════════════════════════════════════════════════════════════════╗");
118
- log.info("║ [SUCCESS] MAGICMARK PLUGIN LICENSE ACTIVE ║");
119
- log.info("║ ║");
120
- if (licenseStatus.data) {
121
- log.info(`║ License: ${licenseStatus.data.licenseKey} ║`);
122
- log.info(`║ User: ${licenseStatus.data.firstName} ${licenseStatus.data.lastName}`.padEnd(66) + "║");
123
- log.info(`║ Email: ${licenseStatus.data.email}`.padEnd(66) + "║");
124
- } else if (storedKey) {
125
- log.info(`║ License: ${storedKey} (Offline Mode) ║`);
126
- log.info(`║ Status: Grace Period Active ║`);
127
- }
128
- log.info("║ ║");
129
- log.info("║ [PING] Auto-pinging every 15 minutes ║");
130
- log.info("╚════════════════════════════════════════════════════════════════╝");
131
- }
132
- }, 3e3);
45
+ await maintenance.removeLegacyLicenseKeys();
133
46
  } catch (error) {
134
- log.error("[ERROR] Error initializing License Guard:", error);
47
+ strapi.log.error("[magic-mark] Removing legacy license keys failed", {
48
+ name: error?.name
49
+ });
135
50
  }
136
- log.info("Plugin bootstrapped successfully");
137
- };
138
- const destroy = ({ strapi }) => {
139
- const log = createLogger(strapi);
140
51
  try {
141
- const licenseGuardService2 = strapi.plugin("magic-mark")?.service("license-guard");
142
- if (licenseGuardService2) {
143
- licenseGuardService2.cleanup();
144
- log.info("[SUCCESS] License Guard cleanup completed");
145
- }
52
+ await maintenance.migrateLegacyBookmarks();
146
53
  } catch (error) {
147
- log.error("[ERROR] Error during License Guard cleanup:", error);
54
+ strapi.log.error("[magic-mark] Bookmark migration failed", { name: error?.name });
148
55
  }
56
+ try {
57
+ await maintenance.removeDuplicatePermissions();
58
+ } catch (error) {
59
+ strapi.log.error("[magic-mark] Removing duplicate permissions failed", {
60
+ name: error?.name
61
+ });
62
+ }
63
+ const captureIds = async (event) => {
64
+ const rows = await strapi.db.query(event.model.uid).findMany({
65
+ where: event.params.where ?? {},
66
+ select: ["documentId"]
67
+ });
68
+ event.state[STATE_KEY] = rows.map((row) => row.documentId);
69
+ };
70
+ const cleanup = async (event) => {
71
+ const ids = event.state[STATE_KEY] ?? [];
72
+ try {
73
+ if (event.model.uid === ADMIN_USER_UID) await maintenance.cleanupDeletedUsers(ids);
74
+ if (event.model.uid === ADMIN_ROLE_UID) await maintenance.cleanupDeletedRoles(ids);
75
+ } catch (error) {
76
+ strapi.log.error("[magic-mark] Cleanup after deletion failed", {
77
+ name: error?.name
78
+ });
79
+ }
80
+ };
81
+ detachLifecycles();
82
+ unsubscribe = strapi.db.lifecycles.subscribe({
83
+ models: [ADMIN_USER_UID, ADMIN_ROLE_UID],
84
+ beforeDelete: captureIds,
85
+ beforeDeleteMany: captureIds,
86
+ afterDelete: cleanup,
87
+ afterDeleteMany: cleanup
88
+ });
149
89
  };
150
90
  const config = {
151
- default: {
152
- // Enable debug logging (set to true to see all plugin logs)
153
- debug: false
154
- },
91
+ default: {},
155
92
  validator: () => {
156
93
  }
157
94
  };
95
+ const internal = {
96
+ "content-manager": { visible: false },
97
+ "content-type-builder": { visible: false }
98
+ };
158
99
  const contentTypes = {
159
100
  bookmark: {
160
101
  schema: {
@@ -163,1513 +104,1161 @@ const contentTypes = {
163
104
  info: {
164
105
  singularName: "bookmark",
165
106
  pluralName: "bookmarks",
166
- displayName: "Magic Bookmark",
167
- description: "Saved filter views for quick access with path and query parameters"
107
+ displayName: "Magic Mark bookmark"
168
108
  },
169
- options: {
170
- draftAndPublish: false,
171
- comment: "Magic Bookmarks - Saved Views with Filters"
172
- },
173
- pluginOptions: {
174
- "content-manager": { visible: false },
175
- "content-type-builder": { visible: false }
109
+ options: { draftAndPublish: false },
110
+ pluginOptions: internal,
111
+ attributes: {
112
+ name: { type: "string", required: true, maxLength: 100, configurable: false },
113
+ description: { type: "text", maxLength: 500, configurable: false },
114
+ // Router path of the list view, e.g. /content-manager/collection-types/api::article.article
115
+ path: { type: "string", required: true, maxLength: 255, configurable: false },
116
+ // Content-type uid derived from `path`; used to list the bookmarks of one list view.
117
+ contentType: { type: "string", maxLength: 255, configurable: false },
118
+ // Query string without the leading "?" (filters, sort, pageSize, plugins).
119
+ query: { type: "text", configurable: false },
120
+ // Icon key (see server/src/validation.ts ICON_KEYS). The column keeps its 3.x name.
121
+ emoji: { type: "string", default: "bookmark", maxLength: 50, configurable: false },
122
+ creatorId: { type: "string", configurable: false },
123
+ updaterId: { type: "string", configurable: false },
124
+ isPublic: { type: "boolean", default: false, configurable: false },
125
+ // 3.x fields. Migrated on bootstrap into bookmark-share and bookmark-preference rows
126
+ // and then cleared; kept in the schema so the migration can still read old rows.
127
+ sharedWithRoles: { type: "json", configurable: false },
128
+ sharedWithUsers: { type: "json", configurable: false },
129
+ isPinned: { type: "boolean", default: false, configurable: false },
130
+ order: { type: "integer", default: 0, configurable: false }
131
+ }
132
+ }
133
+ },
134
+ "bookmark-share": {
135
+ schema: {
136
+ kind: "collectionType",
137
+ collectionName: "magic_bookmark_shares",
138
+ info: {
139
+ singularName: "bookmark-share",
140
+ pluralName: "bookmark-shares",
141
+ displayName: "Magic Mark bookmark share"
176
142
  },
143
+ options: { draftAndPublish: false },
144
+ pluginOptions: internal,
177
145
  attributes: {
178
- name: {
179
- type: "string",
146
+ bookmarkDocumentId: { type: "string", required: true, configurable: false },
147
+ targetType: {
148
+ type: "enumeration",
149
+ enum: ["user", "role"],
180
150
  required: true,
181
- maxLength: 100,
182
151
  configurable: false
183
152
  },
184
- // Path: /content-manager/collection-types/api::article.article
185
- path: {
186
- type: "string",
187
- required: true,
188
- configurable: false,
189
- description: "Content Manager path (e.g., /content-manager/collection-types/api::article.article)"
190
- },
191
- // Query: filters[status][$eq]=published&sort=createdAt:DESC
192
- query: {
193
- type: "text",
194
- configurable: false,
195
- description: "URL query parameters (e.g., filters[status][$eq]=published&sort=createdAt:DESC)"
196
- },
197
- emoji: {
198
- type: "string",
199
- default: "bookmark",
200
- configurable: false,
201
- maxLength: 50
202
- },
203
- isPinned: {
204
- type: "boolean",
205
- default: false,
206
- configurable: false
207
- },
208
- order: {
209
- type: "integer",
210
- default: 0,
211
- configurable: false
212
- },
213
- description: {
214
- type: "text",
215
- configurable: false
216
- },
217
- // Creator's documentId (stored as string, not relation)
218
- // We store documentId instead of relation to avoid admin::user permission issues
219
- creatorId: {
220
- type: "string",
221
- configurable: false,
222
- description: "documentId of the admin user who created this bookmark"
223
- },
224
- // Last updater's documentId
225
- updaterId: {
226
- type: "string",
227
- configurable: false,
228
- description: "documentId of the admin user who last updated this bookmark"
229
- },
230
- // Array of role documentIds that have access to this bookmark
231
- sharedWithRoles: {
232
- type: "json",
233
- configurable: false,
234
- description: "Array of role documentIds that have access to this bookmark"
235
- },
236
- // Array of user documentIds that have direct access to this bookmark
237
- sharedWithUsers: {
238
- type: "json",
239
- configurable: false,
240
- description: "Array of user documentIds that have direct access to this bookmark"
241
- },
242
- // Whether this bookmark is public to all admin users
243
- isPublic: {
244
- type: "boolean",
245
- default: false,
246
- configurable: false,
247
- description: "If true, all admin users can see this bookmark"
248
- }
249
- }
250
- }
251
- }
252
- };
253
- const ADMIN_ROLE_UID = "admin::role";
254
- const ADMIN_USER_UID$1 = "admin::user";
255
- const bookmarkController = ({ strapi }) => ({
256
- /**
257
- * Get all bookmarks for current user
258
- * GET /magic-mark/bookmarks
259
- */
260
- async getAll(ctx) {
261
- try {
262
- const user = ctx.state.user;
263
- if (!user) {
264
- return ctx.throw(401, "User not authenticated");
265
- }
266
- const userId = user.documentId || String(user.id);
267
- const bookmarks = await strapi.plugin("magic-mark").service("bookmarks").findAll(userId);
268
- ctx.body = {
269
- data: bookmarks,
270
- meta: {
271
- count: bookmarks.length
272
- }
273
- };
274
- } catch (error) {
275
- ctx.throw(500, `Error fetching bookmarks: ${error}`);
276
- }
277
- },
278
- /**
279
- * Create a new bookmark
280
- * POST /magic-mark/bookmarks
281
- */
282
- async create(ctx) {
283
- try {
284
- const user = ctx.state.user;
285
- if (!user) {
286
- return ctx.throw(401, "User not authenticated");
287
- }
288
- const { name, path: path2, query, emoji, description, sharedWithRoles, sharedWithUsers, isPublic } = ctx.request.body;
289
- if (!name || name.trim().length === 0) {
290
- return ctx.throw(400, "Name is required");
291
- }
292
- if (!path2 || path2.trim().length === 0) {
293
- return ctx.throw(400, "Path is required");
294
- }
295
- const userId = user.documentId || String(user.id);
296
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
297
- const limitCheck = await licenseGuard.canCreateBookmark(userId);
298
- if (!limitCheck.canCreate) {
299
- return ctx.throw(403, {
300
- error: "BOOKMARK_LIMIT_REACHED",
301
- message: limitCheck.message || `Bookmark limit reached (${limitCheck.current}/${limitCheck.max}). Upgrade to Premium or Advanced to create more bookmarks.`,
302
- current: limitCheck.current,
303
- max: limitCheck.max,
304
- upgradeUrl: "/admin/settings/magic-mark/upgrade"
305
- });
306
- }
307
- const service = strapi.plugin("magic-mark").service("bookmarks");
308
- const bookmark = await service.create(name, path2, query, emoji, description, userId, sharedWithRoles, sharedWithUsers, isPublic);
309
- ctx.body = {
310
- data: bookmark
311
- };
312
- } catch (error) {
313
- ctx.throw(500, `Error creating bookmark: ${error}`);
314
- }
315
- },
316
- /**
317
- * Update an existing bookmark
318
- * PUT /magic-mark/bookmarks/:id
319
- */
320
- async update(ctx) {
321
- try {
322
- const user = ctx.state.user;
323
- if (!user) {
324
- return ctx.throw(401, "User not authenticated");
325
- }
326
- const { id } = ctx.params;
327
- const { name, path: path2, query, emoji, description, isPinned, order, sharedWithRoles, sharedWithUsers, isPublic } = ctx.request.body;
328
- if (!name || name.trim().length === 0) {
329
- return ctx.throw(400, "Name is required");
330
- }
331
- if (!path2 || path2.trim().length === 0) {
332
- return ctx.throw(400, "Path is required");
333
- }
334
- const userId = user.documentId || String(user.id);
335
- const bookmark = await strapi.plugin("magic-mark").service("bookmarks").update(id, { name, path: path2, query, emoji, description, isPinned, order, sharedWithRoles, sharedWithUsers, isPublic }, userId);
336
- ctx.body = {
337
- data: bookmark
338
- };
339
- } catch (error) {
340
- ctx.throw(500, `Error updating bookmark: ${error}`);
341
- }
342
- },
343
- /**
344
- * Delete a bookmark
345
- * DELETE /magic-mark/bookmarks/:id
346
- */
347
- async delete(ctx) {
348
- try {
349
- const user = ctx.state.user;
350
- if (!user) {
351
- return ctx.throw(401, "User not authenticated");
153
+ targetId: { type: "string", required: true, configurable: false }
352
154
  }
353
- const { id } = ctx.params;
354
- await strapi.plugin("magic-mark").service("bookmarks").delete(id);
355
- ctx.body = {
356
- data: { success: true }
357
- };
358
- } catch (error) {
359
- ctx.throw(500, `Error deleting bookmark: ${error}`);
360
155
  }
361
156
  },
362
- /**
363
- * Pin or unpin a bookmark
364
- * PUT /magic-mark/bookmarks/:id/pin
365
- */
366
- async pin(ctx) {
367
- try {
368
- const user = ctx.state.user;
369
- if (!user) {
370
- return ctx.throw(401, "User not authenticated");
371
- }
372
- const { id } = ctx.params;
373
- const { isPinned } = ctx.request.body;
374
- const userId = user.documentId || String(user.id);
375
- const bookmark = await strapi.plugin("magic-mark").service("bookmarks").pin(id, isPinned, userId);
376
- ctx.body = {
377
- data: bookmark
378
- };
379
- } catch (error) {
380
- ctx.throw(500, `Error pinning bookmark: ${error}`);
381
- }
382
- },
383
- /**
384
- * Reorder bookmarks
385
- * PUT /magic-mark/bookmarks/reorder
386
- */
387
- async reorder(ctx) {
388
- try {
389
- const user = ctx.state.user;
390
- if (!user) {
391
- return ctx.throw(401, "User not authenticated");
392
- }
393
- const { bookmarkIds } = ctx.request.body;
394
- if (!bookmarkIds || !Array.isArray(bookmarkIds)) {
395
- return ctx.throw(400, "Bookmark IDs array is required");
396
- }
397
- const userId = user.documentId || String(user.id);
398
- const bookmarks = await strapi.plugin("magic-mark").service("bookmarks").reorder(bookmarkIds, userId);
399
- ctx.body = {
400
- data: bookmarks
401
- };
402
- } catch (error) {
403
- ctx.throw(500, `Error reordering bookmarks: ${error}`);
404
- }
405
- },
406
- /**
407
- * Get all admin roles for sharing
408
- * GET /magic-mark/roles
409
- */
410
- async getRoles(ctx) {
411
- try {
412
- const user = ctx.state.user;
413
- if (!user) {
414
- return ctx.throw(401, "User not authenticated");
157
+ "bookmark-preference": {
158
+ schema: {
159
+ kind: "collectionType",
160
+ collectionName: "magic_bookmark_preferences",
161
+ info: {
162
+ singularName: "bookmark-preference",
163
+ pluralName: "bookmark-preferences",
164
+ displayName: "Magic Mark bookmark preference"
165
+ },
166
+ options: { draftAndPublish: false },
167
+ pluginOptions: internal,
168
+ attributes: {
169
+ userId: { type: "string", required: true, configurable: false },
170
+ bookmarkDocumentId: { type: "string", required: true, configurable: false },
171
+ isPinned: { type: "boolean", default: false, configurable: false }
415
172
  }
416
- const roles = await strapi.documents(ADMIN_ROLE_UID).findMany({
417
- fields: ["name", "code", "description", "createdAt", "updatedAt"],
418
- sort: { name: "asc" },
419
- populate: ["users"]
420
- });
421
- const rolesWithDetails = roles?.map((role) => ({
422
- id: role.documentId,
423
- name: role.name,
424
- code: role.code,
425
- description: role.description,
426
- userCount: role.users?.length || 0,
427
- isCustom: !["super_admin", "editor", "author"].includes(role.code)
428
- })) || [];
429
- ctx.body = {
430
- data: {
431
- data: rolesWithDetails
432
- }
433
- };
434
- } catch (error) {
435
- ctx.throw(500, `Error fetching roles: ${error}`);
436
173
  }
437
- },
438
- /**
439
- * Get all admin users for sharing
440
- * GET /magic-mark/users
441
- */
442
- async getUsers(ctx) {
443
- try {
444
- const user = ctx.state.user;
445
- if (!user) {
446
- return ctx.throw(401, "User not authenticated");
447
- }
448
- let users = [];
449
- try {
450
- const adminUserService = strapi.admin?.services?.user || strapi.service("admin::user");
451
- if (adminUserService?.findPage) {
452
- const results = await adminUserService.findPage({
453
- pagination: {
454
- page: 1,
455
- pageSize: 100
456
- }
457
- });
458
- users = results.results || [];
459
- } else if (adminUserService?.find) {
460
- users = await adminUserService.find();
461
- }
462
- } catch (err) {
463
- strapi.log.debug("[magic-mark] Admin service not available, trying Document Service");
464
- }
465
- if (!users || users.length === 0) {
466
- try {
467
- users = await strapi.documents(ADMIN_USER_UID$1).findMany({
468
- limit: 100
469
- });
470
- } catch (err) {
471
- strapi.log.debug("[magic-mark] Document Service error for admin::user");
472
- }
473
- }
474
- if (!users || users.length === 0) {
475
- try {
476
- users = await strapi.entityService.findMany(ADMIN_USER_UID$1, {
477
- limit: 100
478
- });
479
- } catch (err) {
480
- strapi.log.warn("[magic-mark] entityService fallback also failed");
481
- }
482
- }
483
- const currentUserId = user.documentId || String(user.id);
484
- const filteredUsers = users.filter((u) => {
485
- const uId = u.documentId || String(u.id);
486
- return uId !== currentUserId;
487
- });
488
- strapi.log.debug(`[magic-mark] Total admin users found: ${users.length}`);
489
- ctx.body = {
490
- data: {
491
- data: filteredUsers.map((u) => ({
492
- id: u.documentId || u.id,
493
- firstname: u.firstname || "",
494
- lastname: u.lastname || "",
495
- email: u.email,
496
- username: u.username || u.email
497
- }))
498
- }
499
- };
500
- } catch (error) {
501
- ctx.throw(500, `Error fetching users: ${error}`);
174
+ }
175
+ };
176
+ const ICON_KEYS = [
177
+ "bookmark",
178
+ "book",
179
+ "star",
180
+ "heart",
181
+ "bolt",
182
+ "rocket",
183
+ "pencil",
184
+ "link",
185
+ "sparkles",
186
+ "briefcase",
187
+ "photo",
188
+ "document",
189
+ "bell",
190
+ "check",
191
+ "gift",
192
+ "user",
193
+ "users",
194
+ "mail",
195
+ "calendar",
196
+ "clock",
197
+ "folder",
198
+ "search",
199
+ "filter",
200
+ "globe",
201
+ "tag",
202
+ "flag",
203
+ "fire",
204
+ "cube",
205
+ "home",
206
+ "cog",
207
+ "wrench",
208
+ "terminal",
209
+ "chart"
210
+ ];
211
+ const VISIBILITIES = ["private", "shared", "public"];
212
+ const LIST_VIEW_PATH = /^\/content-manager\/(collection-types|single-types)\/((?:api|plugin)::[a-z0-9_-]{1,80}\.[a-z0-9_-]{1,80})$/;
213
+ const DOCUMENT_ID = /^[a-z0-9]{1,64}$/;
214
+ const FIELD_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,99}$/;
215
+ const OPERATOR_KEY = /^\$[A-Za-z]{1,20}$/;
216
+ const SORT_VALUE = /^[A-Za-z_][A-Za-z0-9_.]{0,99}:(ASC|DESC|asc|desc)$/;
217
+ const LOCALE = /^[A-Za-z0-9-]{1,20}$/;
218
+ const MAX_QUERY_LENGTH = 8192;
219
+ const MAX_FILTER_VALUE_LENGTH = 1e3;
220
+ const MAX_FILTER_DEPTH = 8;
221
+ const documentId = zod.z.string().regex(DOCUMENT_ID);
222
+ const fail = (error) => {
223
+ throw new utils.errors.ValidationError("Validation failed", zod.z.flattenError(error));
224
+ };
225
+ const parse = (schema, input) => {
226
+ const result = schema.safeParse(input ?? {});
227
+ if (!result.success) fail(result.error);
228
+ return result.data;
229
+ };
230
+ const normalizeListViewPath = (path) => {
231
+ if (typeof path !== "string") return null;
232
+ const trimmed = path.trim();
233
+ const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
234
+ const match = LIST_VIEW_PATH.exec(withSlash);
235
+ if (!match) return null;
236
+ return { path: withSlash, contentType: match[2] };
237
+ };
238
+ const isSafeFilterTree = (node, depth = 0) => {
239
+ if (depth > MAX_FILTER_DEPTH) return false;
240
+ if (typeof node === "string") return node.length <= MAX_FILTER_VALUE_LENGTH;
241
+ if (Array.isArray(node)) {
242
+ return node.length <= 100 && node.every((item) => isSafeFilterTree(item, depth + 1));
243
+ }
244
+ if (node && typeof node === "object") {
245
+ const entries = Object.entries(node);
246
+ if (entries.length > 100) return false;
247
+ return entries.every(
248
+ ([key, value]) => (FIELD_KEY.test(key) || OPERATOR_KEY.test(key) || /^\d{1,3}$/.test(key)) && key !== "__proto__" && key !== "constructor" && key !== "prototype" && isSafeFilterTree(value, depth + 1)
249
+ );
250
+ }
251
+ return false;
252
+ };
253
+ const normalizeListViewQuery = (query) => {
254
+ if (query === void 0 || query === null || query === "") return "";
255
+ if (typeof query !== "string") return null;
256
+ const raw = query.startsWith("?") ? query.slice(1) : query;
257
+ if (raw.length > MAX_QUERY_LENGTH || raw.includes("#") || raw.includes("\\")) return null;
258
+ if (/[\u0000-\u001f\u007f]/.test(raw)) return null;
259
+ const parsed = qs__default.default.parse(raw, {
260
+ depth: MAX_FILTER_DEPTH,
261
+ allowPrototypes: false,
262
+ plainObjects: true,
263
+ parameterLimit: 500,
264
+ arrayLimit: 100
265
+ });
266
+ const out = {};
267
+ if (parsed.filters !== void 0) {
268
+ if (!parsed.filters || typeof parsed.filters !== "object" || Array.isArray(parsed.filters)) {
269
+ return null;
502
270
  }
271
+ if (!isSafeFilterTree(parsed.filters)) return null;
272
+ out.filters = parsed.filters;
273
+ }
274
+ if (parsed.sort !== void 0) {
275
+ if (typeof parsed.sort !== "string" || !SORT_VALUE.test(parsed.sort)) return null;
276
+ out.sort = parsed.sort;
277
+ }
278
+ if (parsed.pageSize !== void 0) {
279
+ const size = Number(parsed.pageSize);
280
+ if (!Number.isInteger(size) || size < 1 || size > 100) return null;
281
+ out.pageSize = String(size);
503
282
  }
283
+ if (parsed._q !== void 0) {
284
+ if (typeof parsed._q !== "string" || parsed._q.length > MAX_FILTER_VALUE_LENGTH) return null;
285
+ if (parsed._q) out._q = parsed._q;
286
+ }
287
+ const locale = parsed.plugins?.i18n?.locale;
288
+ if (locale !== void 0) {
289
+ if (typeof locale !== "string" || !LOCALE.test(locale)) return null;
290
+ out.plugins = { i18n: { locale } };
291
+ }
292
+ return qs__default.default.stringify(out, { encodeValuesOnly: true });
293
+ };
294
+ const name = zod.z.string().trim().min(1).max(100);
295
+ const description = zod.z.string().trim().max(500);
296
+ const shareTargets = zod.z.array(documentId).max(LIMITS.shareTargetsMax).transform((ids) => [...new Set(ids)]);
297
+ const listViewPath = zod.z.string().max(255).transform((value, ctx) => {
298
+ const normalized = normalizeListViewPath(value);
299
+ if (!normalized) {
300
+ ctx.addIssue({ code: "custom", message: "Must be a Content Manager list view path" });
301
+ return zod.z.NEVER;
302
+ }
303
+ return normalized;
504
304
  });
505
- const license = ({ strapi }) => ({
506
- /**
507
- * Auto-create license with logged-in admin user data
508
- */
509
- async autoCreate(ctx) {
510
- try {
511
- const adminUser = ctx.state.user;
512
- if (!adminUser) {
513
- return ctx.unauthorized("No admin user logged in");
514
- }
515
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
516
- const license2 = await licenseGuard.createLicense({
517
- email: adminUser.email,
518
- firstName: adminUser.firstname || "Admin",
519
- lastName: adminUser.lastname || "User"
520
- });
521
- if (!license2) {
522
- return ctx.badRequest("Failed to create license");
523
- }
524
- await licenseGuard.storeLicenseKey(license2.licenseKey);
525
- const pingInterval = licenseGuard.startPinging(license2.licenseKey, 15);
526
- strapi.licenseGuard = {
527
- licenseKey: license2.licenseKey,
528
- pingInterval,
529
- data: license2
530
- };
531
- return ctx.send({
532
- success: true,
533
- message: "License automatically created and activated",
534
- data: license2
535
- });
536
- } catch (error) {
537
- strapi.log.error("Error auto-creating license:", error);
538
- return ctx.badRequest("Error creating license");
539
- }
540
- },
541
- /**
542
- * Get current license status
543
- */
544
- async getStatus(ctx) {
545
- try {
546
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
547
- const pluginStore = strapi.store({
548
- type: "plugin",
549
- name: "magic-mark"
550
- });
551
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
552
- if (!licenseKey) {
553
- return ctx.send({
554
- success: false,
555
- demo: true,
556
- valid: false,
557
- message: "No license found. Running in demo mode."
558
- });
559
- }
560
- const verification = await licenseGuard.verifyLicense(licenseKey);
561
- const license2 = await licenseGuard.getLicenseByKey(licenseKey);
562
- return ctx.send({
563
- success: true,
564
- valid: verification.valid,
565
- demo: false,
566
- data: {
567
- licenseKey,
568
- email: license2?.email || null,
569
- firstName: license2?.firstName || null,
570
- lastName: license2?.lastName || null,
571
- isActive: license2?.isActive || false,
572
- isExpired: license2?.isExpired || false,
573
- isOnline: license2?.isOnline || false,
574
- expiresAt: license2?.expiresAt,
575
- lastPingAt: license2?.lastPingAt,
576
- deviceName: license2?.deviceName,
577
- deviceId: license2?.deviceId,
578
- ipAddress: license2?.ipAddress,
579
- features: {
580
- premium: license2?.featurePremium || false,
581
- advanced: license2?.featureAdvanced || false,
582
- enterprise: license2?.featureEnterprise || false,
583
- custom: license2?.featureCustom || false
584
- },
585
- maxDevices: license2?.maxDevices || 1,
586
- currentDevices: license2?.currentDevices || 0
587
- }
588
- });
589
- } catch (error) {
590
- strapi.log.error("Error getting license status:", error);
591
- return ctx.badRequest("Error getting license status");
592
- }
593
- },
594
- /**
595
- * Create and activate a new license
596
- */
597
- async createAndActivate(ctx) {
598
- try {
599
- const { email, firstName, lastName } = ctx.request.body;
600
- if (!email || !firstName || !lastName) {
601
- return ctx.badRequest("Email, firstName, and lastName are required");
602
- }
603
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
604
- const license2 = await licenseGuard.createLicense({ email, firstName, lastName });
605
- if (!license2) {
606
- return ctx.badRequest("Failed to create license");
607
- }
608
- await licenseGuard.storeLicenseKey(license2.licenseKey);
609
- const pingInterval = licenseGuard.startPinging(license2.licenseKey, 15);
610
- strapi.licenseGuard = {
611
- licenseKey: license2.licenseKey,
612
- pingInterval,
613
- data: license2
614
- };
615
- return ctx.send({
616
- success: true,
617
- message: "License created and activated successfully",
618
- data: license2
619
- });
620
- } catch (error) {
621
- strapi.log.error("Error creating license:", error);
622
- return ctx.badRequest("Error creating license");
623
- }
624
- },
625
- /**
626
- * Manually ping the current license
627
- */
628
- async ping(ctx) {
629
- try {
630
- const pluginStore = strapi.store({
631
- type: "plugin",
632
- name: "magic-mark"
633
- });
634
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
635
- if (!licenseKey) {
636
- return ctx.badRequest("No license key found");
637
- }
638
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
639
- const pingResult = await licenseGuard.pingLicense(licenseKey);
640
- if (!pingResult) {
641
- return ctx.badRequest("Ping failed");
642
- }
643
- return ctx.send({
644
- success: true,
645
- message: "License pinged successfully",
646
- data: pingResult
647
- });
648
- } catch (error) {
649
- strapi.log.error("Error pinging license:", error);
650
- return ctx.badRequest("Error pinging license");
651
- }
652
- },
653
- /**
654
- * Store and validate an existing license key
655
- */
656
- async storeKey(ctx) {
657
- try {
658
- const { licenseKey, email } = ctx.request.body;
659
- if (!licenseKey || !licenseKey.trim()) {
660
- return ctx.badRequest("License key is required");
661
- }
662
- if (!email || !email.trim()) {
663
- return ctx.badRequest("Email address is required");
664
- }
665
- const trimmedKey = licenseKey.trim();
666
- const trimmedEmail = email.trim().toLowerCase();
667
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
668
- const verification = await licenseGuard.verifyLicense(trimmedKey);
669
- if (!verification.valid) {
670
- strapi.log.warn(`[WARN] Invalid license key attempted: ${trimmedKey.substring(0, 8)}...`);
671
- return ctx.badRequest("Invalid or expired license key");
672
- }
673
- const license2 = await licenseGuard.getLicenseByKey(trimmedKey);
674
- if (!license2) {
675
- strapi.log.warn(`[WARN] License not found in database: ${trimmedKey.substring(0, 8)}...`);
676
- return ctx.badRequest("License not found");
677
- }
678
- if (license2.email.toLowerCase() !== trimmedEmail) {
679
- strapi.log.warn(`[WARN] Email mismatch for license key: ${trimmedKey.substring(0, 8)}... (Attempted: ${trimmedEmail})`);
680
- return ctx.badRequest("Email address does not match this license key");
681
- }
682
- await licenseGuard.storeLicenseKey(trimmedKey);
683
- const pingInterval = licenseGuard.startPinging(trimmedKey, 15);
684
- strapi.licenseGuard = {
685
- licenseKey: trimmedKey,
686
- pingInterval,
687
- data: verification.data
688
- };
689
- strapi.log.info(`[SUCCESS] Existing license key validated and stored: ${trimmedKey.substring(0, 8)}... (Email: ${trimmedEmail})`);
690
- return ctx.send({
691
- success: true,
692
- message: "License key validated and activated successfully",
693
- data: verification.data
694
- });
695
- } catch (error) {
696
- strapi.log.error("Error storing license key:", error);
697
- return ctx.badRequest("Error validating license key");
698
- }
699
- },
700
- /**
701
- * Get license limits and feature flags for current user
702
- */
703
- async getLimits(ctx) {
704
- try {
705
- const user = ctx.state.user;
706
- if (!user) {
707
- return ctx.unauthorized("User not authenticated");
708
- }
709
- const userId = user.documentId || String(user.id);
710
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
711
- const limits = await licenseGuard.getLicenseLimits(userId);
712
- return ctx.send({
713
- success: true,
714
- data: limits
715
- });
716
- } catch (error) {
717
- strapi.log.error("Error getting license limits:", error);
718
- return ctx.badRequest("Error getting license limits");
719
- }
305
+ const listViewQuery = zod.z.string().max(MAX_QUERY_LENGTH).transform((value, ctx) => {
306
+ const normalized = normalizeListViewQuery(value);
307
+ if (normalized === null) {
308
+ ctx.addIssue({ code: "custom", message: "Unsupported list view query" });
309
+ return zod.z.NEVER;
720
310
  }
311
+ return normalized;
721
312
  });
722
- const controllers = {
723
- bookmarks: bookmarkController,
724
- license
313
+ const sharing = {
314
+ visibility: zod.z.enum(VISIBILITIES).optional(),
315
+ roles: shareTargets.optional(),
316
+ users: shareTargets.optional()
725
317
  };
726
- const admin = {
727
- type: "admin",
728
- routes: [
729
- // Get available roles for sharing
730
- {
731
- method: "GET",
732
- path: "/roles",
733
- handler: "bookmarks.getRoles",
734
- config: {
735
- policies: []
736
- }
737
- },
738
- // Get available users for sharing
739
- {
740
- method: "GET",
741
- path: "/users",
742
- handler: "bookmarks.getUsers",
743
- config: {
744
- policies: []
745
- }
746
- },
747
- // Get all bookmarks
748
- {
749
- method: "GET",
750
- path: "/bookmarks",
751
- handler: "bookmarks.getAll",
752
- config: {
753
- policies: []
754
- }
755
- },
756
- // Reorder bookmarks (SPECIFIC - must come before :id routes)
757
- {
758
- method: "POST",
759
- path: "/bookmarks/reorder",
760
- handler: "bookmarks.reorder",
761
- config: {
762
- policies: []
763
- }
764
- },
765
- // Pin/Unpin bookmark (SPECIFIC - must come before generic :id)
766
- {
767
- method: "POST",
768
- path: "/bookmarks/:id/pin",
769
- handler: "bookmarks.pin",
770
- config: {
771
- policies: []
772
- }
318
+ const createBookmarkSchema = zod.z.strictObject({
319
+ name,
320
+ description: description.optional(),
321
+ icon: zod.z.enum(ICON_KEYS).optional(),
322
+ path: listViewPath,
323
+ query: listViewQuery.optional(),
324
+ ...sharing
325
+ });
326
+ const updateBookmarkSchema = zod.z.strictObject({
327
+ name: name.optional(),
328
+ description: description.optional(),
329
+ icon: zod.z.enum(ICON_KEYS).optional(),
330
+ ...sharing
331
+ });
332
+ const updateViewSchema = zod.z.strictObject({
333
+ query: listViewQuery
334
+ });
335
+ const pinSchema = zod.z.strictObject({
336
+ pinned: zod.z.boolean()
337
+ });
338
+ const duplicateSchema = zod.z.strictObject({
339
+ name: name.optional()
340
+ });
341
+ const SCOPES = ["all", "mine", "shared", "pinned", "managed"];
342
+ const SORTS = ["name:asc", "name:desc", "updatedAt:desc", "updatedAt:asc"];
343
+ const intFromQuery = (min, max) => zod.z.coerce.number().int().min(min).max(max).optional();
344
+ const listQuerySchema = zod.z.strictObject({
345
+ page: intFromQuery(1, 1e5),
346
+ pageSize: intFromQuery(1, LIMITS.pageSizeMax),
347
+ q: zod.z.string().trim().max(100).optional(),
348
+ scope: zod.z.enum(SCOPES).optional(),
349
+ sort: zod.z.enum(SORTS).optional(),
350
+ contentType: zod.z.string().max(170).regex(/^(?:api|plugin)::[a-z0-9_-]{1,80}\.[a-z0-9_-]{1,80}$/).optional()
351
+ });
352
+ const userSearchSchema = zod.z.strictObject({
353
+ q: zod.z.string().trim().max(100).optional(),
354
+ page: intFromQuery(1, 1e3)
355
+ });
356
+ const idParamSchema = zod.z.strictObject({ id: documentId });
357
+ const getViewer = async (strapi, ctx) => {
358
+ const user = ctx.state.user;
359
+ if (!user) throw new utils.errors.UnauthorizedError("Authentication required");
360
+ let userId = user.documentId;
361
+ let roles = user.roles;
362
+ if (!userId || !roles || roles.some((role) => !role.documentId)) {
363
+ const row = await strapi.db.query("admin::user").findOne({
364
+ where: { id: user.id },
365
+ select: ["documentId"],
366
+ populate: { roles: { select: ["documentId"] } }
367
+ });
368
+ if (!row) throw new utils.errors.UnauthorizedError("Authentication required");
369
+ userId = row.documentId;
370
+ roles = row.roles;
371
+ }
372
+ const can = (action) => ctx.state.userAbility?.can(action) === true;
373
+ return {
374
+ userId,
375
+ roleIds: (roles ?? []).map((role) => role.documentId).filter(Boolean),
376
+ canShare: can(actionId("share")),
377
+ canManage: can(actionId("manage")),
378
+ canReadUsers: can("admin::users.read")
379
+ };
380
+ };
381
+ const controller = ({ strapi }) => {
382
+ const service = () => strapi.plugin(PLUGIN_ID).service("bookmarks");
383
+ return {
384
+ /**
385
+ * @route GET /magic-mark/bookmarks
386
+ * @access bookmarks.read
387
+ * Query: page, pageSize (<=100), q, scope (all|mine|shared|pinned), sort, contentType.
388
+ */
389
+ async find(ctx) {
390
+ const params = parse(listQuerySchema, ctx.query);
391
+ const viewer = await getViewer(strapi, ctx);
392
+ const { results, pagination } = await service().list(viewer, params);
393
+ ctx.body = {
394
+ data: results,
395
+ meta: {
396
+ pagination,
397
+ permissions: { canShare: viewer.canShare, canManage: viewer.canManage }
398
+ }
399
+ };
773
400
  },
774
- // Create bookmark
775
- {
776
- method: "POST",
777
- path: "/bookmarks",
778
- handler: "bookmarks.create",
779
- config: {
780
- policies: []
781
- }
401
+ /**
402
+ * @route GET /magic-mark/bookmarks/:id
403
+ * @access bookmarks.read; 404 when not visible. Sharing lists only for owner/manager.
404
+ */
405
+ async findOne(ctx) {
406
+ const { id } = parse(idParamSchema, { id: ctx.params.id });
407
+ ctx.body = { data: await service().findOne(await getViewer(strapi, ctx), id) };
782
408
  },
783
- // Update bookmark
784
- {
785
- method: "PUT",
786
- path: "/bookmarks/:id",
787
- handler: "bookmarks.update",
788
- config: {
789
- policies: []
790
- }
409
+ /**
410
+ * @route POST /magic-mark/bookmarks
411
+ * @access bookmarks.read + bookmarks.create; sharing also needs bookmarks.share.
412
+ * @sideeffect Creates a bookmark owned by the caller.
413
+ */
414
+ async create(ctx) {
415
+ const input = parse(createBookmarkSchema, ctx.request.body);
416
+ ctx.body = { data: await service().create(await getViewer(strapi, ctx), input) };
791
417
  },
792
- // Delete bookmark
793
- {
794
- method: "DELETE",
795
- path: "/bookmarks/:id",
796
- handler: "bookmarks.delete",
797
- config: {
798
- policies: []
799
- }
418
+ /**
419
+ * @route PUT /magic-mark/bookmarks/:id
420
+ * @access bookmarks.read + bookmarks.update, owner or bookmarks.manage.
421
+ */
422
+ async update(ctx) {
423
+ const { id } = parse(idParamSchema, { id: ctx.params.id });
424
+ const input = parse(updateBookmarkSchema, ctx.request.body);
425
+ ctx.body = { data: await service().update(await getViewer(strapi, ctx), id, input) };
800
426
  },
801
- // License Management
802
- {
803
- method: "GET",
804
- path: "/license/status",
805
- handler: "license.getStatus",
806
- config: {
807
- policies: []
808
- }
427
+ /**
428
+ * @route PUT /magic-mark/bookmarks/:id/view
429
+ * @access bookmarks.read + bookmarks.update, owner or bookmarks.manage.
430
+ */
431
+ async updateView(ctx) {
432
+ const { id } = parse(idParamSchema, { id: ctx.params.id });
433
+ const { query } = parse(updateViewSchema, ctx.request.body);
434
+ ctx.body = { data: await service().updateView(await getViewer(strapi, ctx), id, query) };
809
435
  },
810
- {
811
- method: "POST",
812
- path: "/license/auto-create",
813
- handler: "license.autoCreate",
814
- config: {
815
- policies: []
816
- }
436
+ /**
437
+ * @route POST /magic-mark/bookmarks/:id/duplicate
438
+ * @access bookmarks.read + bookmarks.create; the copy is private and owned by the caller.
439
+ */
440
+ async duplicate(ctx) {
441
+ const { id } = parse(idParamSchema, { id: ctx.params.id });
442
+ const { name: name2 } = parse(duplicateSchema, ctx.request.body);
443
+ ctx.body = { data: await service().duplicate(await getViewer(strapi, ctx), id, name2) };
817
444
  },
818
- {
819
- method: "POST",
820
- path: "/license/create",
821
- handler: "license.createAndActivate",
822
- config: {
823
- policies: []
824
- }
445
+ /**
446
+ * @route PUT /magic-mark/bookmarks/:id/pin
447
+ * @access bookmarks.read; pins only for the caller.
448
+ */
449
+ async pin(ctx) {
450
+ const { id } = parse(idParamSchema, { id: ctx.params.id });
451
+ const { pinned } = parse(pinSchema, ctx.request.body);
452
+ ctx.body = { data: await service().setPinned(await getViewer(strapi, ctx), id, pinned) };
825
453
  },
826
- {
827
- method: "POST",
828
- path: "/license/ping",
829
- handler: "license.ping",
830
- config: {
831
- policies: []
832
- }
454
+ /**
455
+ * @route DELETE /magic-mark/bookmarks/:id
456
+ * @access bookmarks.read + bookmarks.delete, owner or bookmarks.manage.
457
+ */
458
+ async delete(ctx) {
459
+ const { id } = parse(idParamSchema, { id: ctx.params.id });
460
+ ctx.body = { data: await service().delete(await getViewer(strapi, ctx), id) };
833
461
  },
834
- {
835
- method: "POST",
836
- path: "/license/store-key",
837
- handler: "license.storeKey",
838
- config: {
839
- policies: []
840
- }
462
+ /**
463
+ * @route GET /magic-mark/sharing/roles
464
+ * @access bookmarks.share
465
+ */
466
+ async roles(ctx) {
467
+ parse(userSearchSchema.pick({}), ctx.query);
468
+ ctx.body = { data: await service().listRoles() };
841
469
  },
842
- {
843
- method: "GET",
844
- path: "/license/limits",
845
- handler: "license.getLimits",
846
- config: {
847
- policies: []
848
- }
470
+ /**
471
+ * @route GET /magic-mark/sharing/users?q=&page=
472
+ * @access bookmarks.share; email only with admin::users.read.
473
+ */
474
+ async users(ctx) {
475
+ const params = parse(userSearchSchema, ctx.query);
476
+ const { results, pagination } = await service().searchUsers(
477
+ await getViewer(strapi, ctx),
478
+ params
479
+ );
480
+ ctx.body = { data: results, meta: { pagination } };
849
481
  }
850
- ]
482
+ };
851
483
  };
852
- const contentApi = {
853
- type: "content-api",
854
- routes: []
484
+ const controllers = {
485
+ bookmarks: controller
855
486
  };
856
- const routes = {
857
- admin,
858
- "content-api": contentApi
487
+ const destroy = () => {
488
+ detachLifecycles();
859
489
  };
860
- const licenseCheck$1 = (config2, { strapi }) => {
861
- return async (ctx, next) => {
862
- if (ctx.request.url.includes("/magic-mark/license/")) {
863
- return await next();
864
- }
865
- if (ctx.request.url.includes("/admin/login")) {
866
- return await next();
867
- }
490
+ const PERMISSION_ACTIONS = [
491
+ { uid: ACTION_UIDS.read, displayName: "Read bookmarks" },
492
+ { uid: ACTION_UIDS.create, displayName: "Create bookmarks" },
493
+ { uid: ACTION_UIDS.update, displayName: "Edit own bookmarks" },
494
+ { uid: ACTION_UIDS.delete, displayName: "Delete own bookmarks" },
495
+ { uid: ACTION_UIDS.share, displayName: "Share bookmarks" },
496
+ { uid: ACTION_UIDS.manage, displayName: "Manage shared bookmarks of others" }
497
+ ].map((action) => ({
498
+ section: "plugins",
499
+ pluginName: PLUGIN_ID,
500
+ subCategory: "Bookmarks",
501
+ ...action
502
+ }));
503
+ const register = async ({ strapi }) => {
504
+ await strapi.admin.services.permission.actionProvider.registerMany(PERMISSION_ACTIONS);
505
+ strapi.hook("strapi::content-types.afterSync").register(async () => {
868
506
  try {
869
- const licenseGuard = strapi.plugin("magic-mark")?.service("license-guard");
870
- if (!licenseGuard) {
871
- return await next();
872
- }
873
- const pluginStore = strapi.store({
874
- type: "plugin",
875
- name: "magic-mark"
507
+ await strapi.plugin(PLUGIN_ID).service("maintenance").migrateLegacyPermissions();
508
+ } catch (error) {
509
+ strapi.log.error("[magic-mark] Permission migration failed", {
510
+ name: error?.name
876
511
  });
877
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
878
- if (!licenseKey) {
879
- strapi.log.warn("[WARN] MagicMark: No license key found");
880
- return await next();
881
- }
882
- const verification = await licenseGuard.verifyLicense(licenseKey, true);
883
- if (!verification.valid && !verification.gracePeriod) {
884
- strapi.log.warn("[WARN] MagicMark: Invalid license detected");
885
- }
886
- return await next();
512
+ }
513
+ try {
514
+ await strapi.plugin(PLUGIN_ID).service("maintenance").grantSuperAdminActions();
887
515
  } catch (error) {
888
- strapi.log.error("Error in license check middleware:", error);
889
- return await next();
516
+ strapi.log.error("[magic-mark] Granting super admin actions failed", {
517
+ name: error?.name
518
+ });
890
519
  }
891
- };
892
- };
893
- const middlewares = {
894
- "license-check": licenseCheck$1
520
+ });
895
521
  };
896
- const licenseCheck = async (policyContext, config2, { strapi }) => {
897
- try {
898
- const licenseGuard = strapi.plugin("magic-mark").service("license-guard");
899
- const pluginStore = strapi.store({ type: "plugin", name: "magic-mark" });
900
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
901
- if (!licenseKey) {
902
- strapi.log.warn("[WARN] API access denied: No license key found");
903
- return policyContext.unauthorized("No license found. Please activate the plugin first.");
904
- }
905
- const verification = await licenseGuard.verifyLicense(licenseKey);
906
- if (!verification.valid) {
907
- strapi.log.warn("[WARN] API access denied: Invalid license");
908
- return policyContext.unauthorized("Invalid or expired license. Please check your license status.");
909
- }
910
- const license2 = await licenseGuard.getLicenseByKey(licenseKey);
911
- if (!license2) {
912
- strapi.log.warn("[WARN] API access denied: License not found in database");
913
- return policyContext.unauthorized("License not found. Please contact support.");
914
- }
915
- if (!license2.isActive) {
916
- strapi.log.warn("[WARN] API access denied: License is inactive");
917
- return policyContext.unauthorized("License is inactive. Please activate your license.");
918
- }
919
- if (license2.isExpired) {
920
- strapi.log.warn("[WARN] API access denied: License has expired");
921
- return policyContext.unauthorized("License has expired. Please renew your license.");
922
- }
923
- return true;
924
- } catch (error) {
925
- strapi.log.error("Error checking license:", error);
926
- return policyContext.unauthorized("Error verifying license. Please try again.");
522
+ const route = (method, path, handler, actions) => ({
523
+ method,
524
+ path,
525
+ handler,
526
+ config: {
527
+ policies: [
528
+ "admin::isAuthenticatedAdmin",
529
+ { name: "admin::hasPermissions", config: { actions: actions.map(actionId) } }
530
+ ]
927
531
  }
532
+ });
533
+ const routes$1 = [
534
+ route("GET", "/bookmarks", "bookmarks.find", ["read"]),
535
+ route("POST", "/bookmarks", "bookmarks.create", ["read", "create"]),
536
+ route("GET", "/bookmarks/:id", "bookmarks.findOne", ["read"]),
537
+ route("PUT", "/bookmarks/:id", "bookmarks.update", ["read", "update"]),
538
+ route("DELETE", "/bookmarks/:id", "bookmarks.delete", ["read", "delete"]),
539
+ route("PUT", "/bookmarks/:id/view", "bookmarks.updateView", ["read", "update"]),
540
+ route("POST", "/bookmarks/:id/duplicate", "bookmarks.duplicate", ["read", "create"]),
541
+ route("PUT", "/bookmarks/:id/pin", "bookmarks.pin", ["read"]),
542
+ route("GET", "/sharing/roles", "bookmarks.roles", ["share"]),
543
+ route("GET", "/sharing/users", "bookmarks.users", ["share"])
544
+ ];
545
+ const admin = {
546
+ type: "admin",
547
+ routes: routes$1
928
548
  };
929
- const policies = {
930
- "license-check": licenseCheck
549
+ const routes = {
550
+ admin
931
551
  };
932
- const BOOKMARK_UID = "plugin::magic-mark.bookmark";
933
- const ADMIN_USER_UID = "admin::user";
934
- const bookmarkService = ({ strapi }) => ({
935
- /**
936
- * Find all bookmarks accessible to a user
937
- * @param userId - The admin user's documentId
938
- * @returns Array of accessible bookmarks with createdBy info
939
- */
940
- async findAll(userId) {
941
- try {
942
- const user = await strapi.documents(ADMIN_USER_UID).findOne({
943
- documentId: userId,
944
- populate: ["roles"]
945
- });
946
- const userRoleIds = user?.roles?.map((role) => role.documentId || role.id) || [];
947
- const allBookmarks = await strapi.documents(BOOKMARK_UID).findMany({
948
- sort: [
949
- { isPinned: "desc" },
950
- { order: "asc" }
951
- ]
952
- });
953
- const accessibleBookmarks = allBookmarks?.filter((bookmark) => {
954
- if (bookmark.creatorId === userId) {
955
- return true;
956
- }
957
- if (bookmark.isPublic) {
958
- return true;
959
- }
960
- if (bookmark.sharedWithUsers && Array.isArray(bookmark.sharedWithUsers)) {
961
- if (bookmark.sharedWithUsers.includes(userId)) {
962
- return true;
963
- }
964
- }
965
- if (bookmark.sharedWithRoles && Array.isArray(bookmark.sharedWithRoles)) {
966
- return bookmark.sharedWithRoles.some(
967
- (roleId) => userRoleIds.includes(roleId)
968
- );
969
- }
970
- return false;
971
- }) || [];
972
- const creatorIds = [...new Set(accessibleBookmarks.map((b) => b.creatorId).filter(Boolean))];
973
- const creatorsMap = /* @__PURE__ */ new Map();
974
- for (const creatorId of creatorIds) {
975
- try {
976
- const creator = await strapi.documents(ADMIN_USER_UID).findOne({
977
- documentId: creatorId,
978
- fields: ["firstname", "lastname", "email"]
979
- });
980
- if (creator) {
981
- creatorsMap.set(creatorId, {
982
- id: creatorId,
983
- documentId: creatorId,
984
- firstname: creator.firstname,
985
- lastname: creator.lastname,
986
- email: creator.email
987
- });
988
- }
989
- } catch (err) {
990
- strapi.log.debug(`[magic-mark] Could not fetch creator ${creatorId}`);
991
- }
992
- }
993
- const enrichedBookmarks = accessibleBookmarks.map((bookmark) => ({
994
- ...bookmark,
995
- createdBy: creatorsMap.get(bookmark.creatorId) || null
996
- }));
997
- return enrichedBookmarks;
998
- } catch (error) {
999
- strapi.log.error("[magic-mark] Error finding bookmarks:", error);
1000
- throw error;
1001
- }
1002
- },
1003
- /**
1004
- * Create a new bookmark
1005
- * @param name - Bookmark name
1006
- * @param path - URL path
1007
- * @param query - Query string
1008
- * @param emoji - Emoji icon
1009
- * @param description - Description
1010
- * @param userId - Creator's documentId
1011
- * @param sharedWithRoles - Array of role documentIds
1012
- * @param sharedWithUsers - Array of user documentIds
1013
- * @param isPublic - Public visibility
1014
- * @returns Created bookmark
1015
- */
1016
- async create(name, path2, query, emoji, description, userId, sharedWithRoles, sharedWithUsers, isPublic) {
1017
- try {
1018
- const bookmarks = await strapi.documents(BOOKMARK_UID).findMany({
1019
- sort: [{ order: "desc" }],
1020
- limit: 1
1021
- });
1022
- const maxOrder = bookmarks && bookmarks.length > 0 ? bookmarks[0].order : 0;
1023
- const bookmark = await strapi.documents(BOOKMARK_UID).create({
1024
- data: {
1025
- name,
1026
- path: path2,
1027
- query: query || "",
1028
- emoji: emoji || "bookmark",
1029
- description,
1030
- isPinned: false,
1031
- order: (maxOrder || 0) + 1,
1032
- creatorId: userId,
1033
- // Store as string field, not relation
1034
- updaterId: userId,
1035
- sharedWithRoles: sharedWithRoles || [],
1036
- sharedWithUsers: sharedWithUsers || [],
1037
- isPublic: isPublic || false
1038
- }
1039
- });
1040
- return bookmark;
1041
- } catch (error) {
1042
- strapi.log.error("[magic-mark] Error creating bookmark:", error);
1043
- throw error;
552
+ const BOOKMARK_FIELDS = [
553
+ "name",
554
+ "description",
555
+ "path",
556
+ "contentType",
557
+ "query",
558
+ "emoji",
559
+ "creatorId",
560
+ "isPublic",
561
+ "createdAt",
562
+ "updatedAt"
563
+ ];
564
+ const SORT_MAP = {
565
+ "name:asc": [{ name: "asc" }, { id: "asc" }],
566
+ "name:desc": [{ name: "desc" }, { id: "desc" }],
567
+ "updatedAt:desc": [{ updatedAt: "desc" }, { id: "desc" }],
568
+ "updatedAt:asc": [{ updatedAt: "asc" }, { id: "asc" }]
569
+ };
570
+ const displayName = (user) => {
571
+ if (!user) return null;
572
+ const full = [user.firstname, user.lastname].filter(Boolean).join(" ").trim();
573
+ return full || user.username || null;
574
+ };
575
+ const notFound = () => new utils.errors.NotFoundError("Bookmark not found");
576
+ const bookmarkService = ({ strapi }) => {
577
+ const db = strapi.db;
578
+ const documents = () => strapi.documents(BOOKMARK_UID);
579
+ const sharedBookmarkIds = async (viewer) => {
580
+ const or = [{ targetType: "user", targetId: viewer.userId }];
581
+ if (viewer.roleIds.length) {
582
+ or.push({ targetType: "role", targetId: { $in: viewer.roleIds } });
1044
583
  }
1045
- },
1046
- /**
1047
- * Update an existing bookmark
1048
- * @param documentId - Bookmark's documentId
1049
- * @param data - Update data
1050
- * @param userId - Editor's documentId
1051
- * @returns Updated bookmark
1052
- */
1053
- async update(documentId, data, userId) {
1054
- try {
1055
- const existingBookmark = await strapi.documents(BOOKMARK_UID).findOne({
1056
- documentId
584
+ const rows = await db.query(SHARE_UID).findMany({
585
+ where: { $or: or },
586
+ select: ["bookmarkDocumentId"]
587
+ });
588
+ return [...new Set(rows.map((row) => row.bookmarkDocumentId))];
589
+ };
590
+ const accessFilter = async (viewer) => {
591
+ const shared = await sharedBookmarkIds(viewer);
592
+ const or = [{ creatorId: viewer.userId }, { isPublic: true }];
593
+ if (shared.length) or.push({ documentId: { $in: shared } });
594
+ return { $or: or };
595
+ };
596
+ const managedFilter = async (viewer) => {
597
+ const rows = await db.query(SHARE_UID).findMany({ select: ["bookmarkDocumentId"] });
598
+ const shared = [
599
+ ...new Set(rows.map((row) => row.bookmarkDocumentId))
600
+ ];
601
+ const or = [
602
+ { creatorId: viewer.userId },
603
+ { isPublic: true },
604
+ { creatorId: { $null: true } }
605
+ ];
606
+ if (shared.length) or.push({ documentId: { $in: shared } });
607
+ return { $or: or };
608
+ };
609
+ const pinnedIds = async (userId, ids) => {
610
+ const where = { userId, isPinned: true };
611
+ if (ids) where.bookmarkDocumentId = { $in: ids };
612
+ const rows = await db.query(PREFERENCE_UID).findMany({
613
+ where,
614
+ select: ["bookmarkDocumentId"]
615
+ });
616
+ return new Set(rows.map((row) => row.bookmarkDocumentId));
617
+ };
618
+ const usersById = async (ids, withEmail = false) => {
619
+ const unique = [...new Set(ids.filter(Boolean))];
620
+ if (!unique.length) return /* @__PURE__ */ new Map();
621
+ const select = ["documentId", "firstname", "lastname", "username"];
622
+ if (withEmail) select.push("email");
623
+ const rows = await db.query(ADMIN_USER_UID).findMany({
624
+ where: { documentId: { $in: unique } },
625
+ select
626
+ });
627
+ return new Map(rows.map((row) => [row.documentId, row]));
628
+ };
629
+ const toDtos = async (rows, viewer) => {
630
+ const ids = rows.map((row) => row.documentId);
631
+ const [owners, pins, shareRows] = await Promise.all([
632
+ usersById(rows.map((row) => row.creatorId)),
633
+ ids.length ? pinnedIds(viewer.userId, ids) : Promise.resolve(/* @__PURE__ */ new Set()),
634
+ ids.length ? db.query(SHARE_UID).findMany({
635
+ where: { bookmarkDocumentId: { $in: ids } },
636
+ select: ["bookmarkDocumentId"]
637
+ }) : Promise.resolve([])
638
+ ]);
639
+ const sharedSet = new Set(
640
+ shareRows.map((row) => row.bookmarkDocumentId)
641
+ );
642
+ return rows.map((row) => {
643
+ const normalized = normalizeListViewPath(row.path);
644
+ const isOwner = !!row.creatorId && row.creatorId === viewer.userId;
645
+ const visibility = row.isPublic ? "public" : sharedSet.has(row.documentId) ? "shared" : "private";
646
+ const icon = ICON_KEYS.includes(row.emoji ?? "") ? row.emoji : "bookmark";
647
+ return {
648
+ documentId: row.documentId,
649
+ name: row.name,
650
+ description: row.description ?? "",
651
+ icon,
652
+ path: normalized?.path ?? null,
653
+ contentType: normalized?.contentType ?? row.contentType ?? null,
654
+ query: row.query ?? "",
655
+ visibility,
656
+ owner: row.creatorId ? { name: displayName(owners.get(row.creatorId)), isDeleted: !owners.has(row.creatorId) } : null,
657
+ isOwner,
658
+ isPinned: pins.has(row.documentId),
659
+ canEdit: isOwner || viewer.canManage,
660
+ createdAt: row.createdAt,
661
+ updatedAt: row.updatedAt
662
+ };
663
+ });
664
+ };
665
+ const findVisible = async (viewer, documentId2) => {
666
+ const access = await accessFilter(viewer);
667
+ const row = await documents().findFirst({
668
+ filters: { $and: [{ documentId: documentId2 }, access] },
669
+ fields: BOOKMARK_FIELDS
670
+ });
671
+ if (row) return row;
672
+ if (viewer.canManage) {
673
+ const candidate = await documents().findFirst({
674
+ filters: { documentId: documentId2 },
675
+ fields: BOOKMARK_FIELDS
1057
676
  });
1058
- if (!existingBookmark || existingBookmark.creatorId !== userId) {
1059
- throw new Error("Unauthorized: You can only edit your own bookmarks");
677
+ if (candidate) {
678
+ if (candidate.isPublic || !candidate.creatorId) return candidate;
679
+ const shares = await db.query(SHARE_UID).count({
680
+ where: { bookmarkDocumentId: documentId2 }
681
+ });
682
+ if (shares > 0) return candidate;
1060
683
  }
1061
- const bookmark = await strapi.documents(BOOKMARK_UID).update({
1062
- documentId,
1063
- data: {
1064
- name: data.name,
1065
- path: data.path,
1066
- query: data.query || "",
1067
- emoji: data.emoji || "bookmark",
1068
- description: data.description,
1069
- isPinned: data.isPinned,
1070
- order: data.order,
1071
- sharedWithRoles: data.sharedWithRoles,
1072
- sharedWithUsers: data.sharedWithUsers,
1073
- isPublic: data.isPublic,
1074
- updaterId: userId
1075
- // Store as string field
1076
- }
1077
- });
1078
- return bookmark;
1079
- } catch (error) {
1080
- strapi.log.error("[magic-mark] Error updating bookmark:", error);
1081
- throw error;
1082
684
  }
1083
- },
1084
- /**
1085
- * Delete a bookmark
1086
- * @param documentId - Bookmark's documentId
1087
- * @returns Deleted bookmark
1088
- */
1089
- async delete(documentId) {
1090
- try {
1091
- return await strapi.documents(BOOKMARK_UID).delete({
1092
- documentId
1093
- });
1094
- } catch (error) {
1095
- strapi.log.error("[magic-mark] Error deleting bookmark:", error);
1096
- throw error;
685
+ throw notFound();
686
+ };
687
+ const findEditable = async (viewer, documentId2) => {
688
+ const row = await findVisible(viewer, documentId2);
689
+ if (row.creatorId !== viewer.userId && !viewer.canManage) {
690
+ throw new utils.errors.ForbiddenError("Only the owner can change this bookmark");
1097
691
  }
1098
- },
1099
- /**
1100
- * Pin or unpin a bookmark
1101
- * @param documentId - Bookmark's documentId
1102
- * @param isPinned - Pin status
1103
- * @param userId - Editor's documentId
1104
- * @returns Updated bookmark
1105
- */
1106
- async pin(documentId, isPinned, userId) {
1107
- try {
1108
- const bookmark = await strapi.documents(BOOKMARK_UID).update({
1109
- documentId,
1110
- data: {
1111
- isPinned,
1112
- updaterId: userId
1113
- }
1114
- });
1115
- return bookmark;
1116
- } catch (error) {
1117
- strapi.log.error("[magic-mark] Error pinning bookmark:", error);
1118
- throw error;
692
+ return row;
693
+ };
694
+ const assertTargetsExist = async (roles, users) => {
695
+ const [roleCount, userCount] = await Promise.all([
696
+ roles.length ? db.query(ADMIN_ROLE_UID).count({ where: { documentId: { $in: roles } } }) : 0,
697
+ users.length ? db.query(ADMIN_USER_UID).count({
698
+ where: { documentId: { $in: users }, isActive: true }
699
+ }) : 0
700
+ ]);
701
+ const details = {};
702
+ if (roleCount !== roles.length) details.roles = ["Unknown role"];
703
+ if (userCount !== users.length) details.users = ["Unknown or inactive user"];
704
+ if (Object.keys(details).length) {
705
+ throw new utils.errors.ValidationError("Validation failed", { fieldErrors: details });
1119
706
  }
1120
- },
1121
- /**
1122
- * Reorder bookmarks
1123
- * @param bookmarkIds - Array of bookmark documentIds in new order
1124
- * @param userId - Editor's documentId
1125
- * @returns Updated bookmarks
1126
- */
1127
- async reorder(bookmarkIds, userId) {
1128
- try {
1129
- const updates = bookmarkIds.map(
1130
- (documentId, index2) => strapi.documents(BOOKMARK_UID).update({
1131
- documentId,
1132
- data: {
1133
- order: index2,
1134
- updaterId: userId
1135
- }
1136
- })
1137
- );
1138
- return Promise.all(updates);
1139
- } catch (error) {
1140
- strapi.log.error("[magic-mark] Error reordering bookmarks:", error);
1141
- throw error;
707
+ };
708
+ const resolveSharing = async (viewer, input) => {
709
+ if (input.visibility === void 0 && !input.roles && !input.users) return void 0;
710
+ const visibility = input.visibility ?? "shared";
711
+ const roles = visibility === "shared" ? input.roles ?? [] : [];
712
+ const users = (visibility === "shared" ? input.users ?? [] : []).filter(
713
+ (id) => id !== viewer.userId
714
+ );
715
+ if (visibility !== "private" && !viewer.canShare) {
716
+ throw new utils.errors.ForbiddenError("Sharing needs the share permission");
1142
717
  }
1143
- },
1144
- /**
1145
- * Validate URL format
1146
- * @param url - URL to validate
1147
- * @returns True if valid
1148
- */
1149
- validateUrl(url) {
1150
- try {
1151
- new URL(url);
1152
- return true;
1153
- } catch {
1154
- return false;
718
+ if (visibility === "shared" && roles.length + users.length === 0) {
719
+ throw new utils.errors.ValidationError("Validation failed", {
720
+ fieldErrors: { roles: ["Choose at least one role or user"] }
721
+ });
1155
722
  }
1156
- }
1157
- });
1158
- let pluginVersion = "2.0.0";
1159
- try {
1160
- const pkgPath = path.join(__dirname, "../../../package.json");
1161
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
1162
- pluginVersion = pkg.version || "2.0.0";
1163
- } catch (e) {
1164
- }
1165
- const LICENSE_SERVER_URL = "https://magicapi.fitlex.me";
1166
- const licenseGuardService = ({ strapi }) => {
1167
- const log = createLogger(strapi);
723
+ await assertTargetsExist(roles, users);
724
+ return { isPublic: visibility === "public", roles, users };
725
+ };
726
+ const lockBookmark = async (trx, documentId2) => {
727
+ const row = await db.queryBuilder(BOOKMARK_UID).select(["id"]).where({ documentId: documentId2 }).first().transacting(trx).forUpdate().execute();
728
+ if (!row) throw notFound();
729
+ };
730
+ const replaceShares = async (bookmarkDocumentId, roles, users) => {
731
+ await db.query(SHARE_UID).deleteMany({ where: { bookmarkDocumentId } });
732
+ const data = [
733
+ ...roles.map((targetId) => ({ bookmarkDocumentId, targetType: "role", targetId })),
734
+ ...users.map((targetId) => ({ bookmarkDocumentId, targetType: "user", targetId }))
735
+ ];
736
+ if (data.length) await db.query(SHARE_UID).createMany({ data });
737
+ };
1168
738
  return {
1169
739
  /**
1170
- * Get license server URL (hardcoded and immutable for security)
1171
- * @returns The fixed license server URL - cannot be overridden
1172
- */
1173
- getLicenseServerUrl() {
1174
- return LICENSE_SERVER_URL;
1175
- },
1176
- /**
1177
- * Generate a unique device ID based on machine identifiers
740
+ * Lists the bookmarks the viewer can see, filtered, sorted and paginated in the database.
741
+ * @param viewer - Current viewer.
742
+ * @param params - Validated list params.
743
+ * @returns `{ results, pagination }`.
1178
744
  */
1179
- generateDeviceId() {
1180
- try {
1181
- const networkInterfaces = os__default.default.networkInterfaces();
1182
- const macAddresses = [];
1183
- Object.values(networkInterfaces).forEach((interfaces) => {
1184
- interfaces?.forEach((iface) => {
1185
- if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
1186
- macAddresses.push(iface.mac);
1187
- }
1188
- });
1189
- });
1190
- const identifier = `${macAddresses.join("-")}-${os__default.default.hostname()}`;
1191
- return crypto__default.default.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
1192
- } catch (error) {
1193
- log.error("Error generating device ID:", error);
1194
- return crypto__default.default.randomBytes(16).toString("hex");
1195
- }
1196
- },
1197
- /**
1198
- * Get device name
1199
- */
1200
- getDeviceName() {
1201
- try {
1202
- return os__default.default.hostname() || "Unknown Device";
1203
- } catch (error) {
1204
- return "Unknown Device";
1205
- }
745
+ async list(viewer, params) {
746
+ const page = params.page ?? 1;
747
+ const pageSize = Math.min(params.pageSize ?? 25, LIMITS.pageSizeMax);
748
+ if (params.scope === "managed" && !viewer.canManage) {
749
+ throw new utils.errors.ForbiddenError("Listing all shared bookmarks needs the manage permission");
750
+ }
751
+ const and = [
752
+ params.scope === "managed" ? await managedFilter(viewer) : await accessFilter(viewer)
753
+ ];
754
+ if (params.scope === "mine") and.push({ creatorId: viewer.userId });
755
+ if (params.scope === "shared") {
756
+ and.push({ $or: [{ creatorId: { $ne: viewer.userId } }, { creatorId: { $null: true } }] });
757
+ }
758
+ if (params.scope === "pinned") {
759
+ const pinned = [...await pinnedIds(viewer.userId)];
760
+ if (!pinned.length) {
761
+ return { results: [], pagination: { page, pageSize, pageCount: 0, total: 0 } };
762
+ }
763
+ and.push({ documentId: { $in: pinned } });
764
+ }
765
+ if (params.contentType) and.push({ contentType: params.contentType });
766
+ if (params.q) and.push({ name: { $containsi: params.q } });
767
+ const filters = { $and: and };
768
+ const [rows, total] = await Promise.all([
769
+ documents().findMany({
770
+ filters,
771
+ fields: BOOKMARK_FIELDS,
772
+ sort: SORT_MAP[params.sort ?? "name:asc"],
773
+ start: (page - 1) * pageSize,
774
+ limit: pageSize
775
+ }),
776
+ documents().count({ filters })
777
+ ]);
778
+ return {
779
+ results: await toDtos(rows, viewer),
780
+ pagination: { page, pageSize, pageCount: Math.ceil(total / pageSize), total }
781
+ };
1206
782
  },
1207
783
  /**
1208
- * Get server IP address
784
+ * One bookmark. Owners and managers also get the sharing lists with display names.
785
+ * @throws {errors.NotFoundError} When it is not visible.
1209
786
  */
1210
- getIpAddress() {
1211
- try {
1212
- const networkInterfaces = os__default.default.networkInterfaces();
1213
- for (const name of Object.keys(networkInterfaces)) {
1214
- const interfaces = networkInterfaces[name];
1215
- if (interfaces) {
1216
- for (const iface of interfaces) {
1217
- if (iface.family === "IPv4" && !iface.internal) {
1218
- return iface.address;
1219
- }
1220
- }
1221
- }
787
+ async findOne(viewer, documentId2) {
788
+ const row = await findVisible(viewer, documentId2);
789
+ const [dto] = await toDtos([row], viewer);
790
+ if (!dto.canEdit) return dto;
791
+ const shares = await db.query(SHARE_UID).findMany({
792
+ where: { bookmarkDocumentId: documentId2 },
793
+ select: ["targetType", "targetId"]
794
+ });
795
+ const roleIds = shares.filter((s) => s.targetType === "role").map((s) => s.targetId);
796
+ const userIds = shares.filter((s) => s.targetType === "user").map((s) => s.targetId);
797
+ const [roles, users] = await Promise.all([
798
+ roleIds.length ? db.query(ADMIN_ROLE_UID).findMany({
799
+ where: { documentId: { $in: roleIds } },
800
+ select: ["documentId", "name"]
801
+ }) : [],
802
+ usersById(userIds, viewer.canReadUsers)
803
+ ]);
804
+ return {
805
+ ...dto,
806
+ sharing: {
807
+ roles: roles.map((role) => ({
808
+ documentId: role.documentId,
809
+ name: role.name
810
+ })),
811
+ users: userIds.filter((id) => users.has(id)).map((id) => {
812
+ const user = users.get(id);
813
+ return {
814
+ documentId: id,
815
+ name: displayName(user),
816
+ ...viewer.canReadUsers ? { email: user.email ?? null } : {}
817
+ };
818
+ })
1222
819
  }
1223
- return "127.0.0.1";
1224
- } catch (error) {
1225
- return "127.0.0.1";
1226
- }
820
+ };
1227
821
  },
1228
822
  /**
1229
- * Get user agent (server context)
823
+ * Creates a bookmark owned by the viewer.
824
+ * @sideeffect Inserts a bookmark and its share rows in one transaction.
1230
825
  */
1231
- getUserAgent() {
1232
- const strapiVersion = strapi.config.get("info.strapi") || "5.0.0";
1233
- return `MagicMark/${pluginVersion} Strapi/${strapiVersion} Node/${process.version} ${os__default.default.platform()}/${os__default.default.release()}`;
826
+ async create(viewer, input) {
827
+ const sharing2 = await resolveSharing(viewer, input);
828
+ const documentId2 = await db.transaction(async () => {
829
+ const created = await documents().create({
830
+ data: {
831
+ name: input.name,
832
+ description: input.description ?? "",
833
+ path: input.path.path,
834
+ contentType: input.path.contentType,
835
+ query: input.query ?? "",
836
+ emoji: input.icon ?? "bookmark",
837
+ creatorId: viewer.userId,
838
+ updaterId: viewer.userId,
839
+ isPublic: sharing2?.isPublic ?? false
840
+ },
841
+ fields: ["documentId"]
842
+ });
843
+ if (sharing2) await replaceShares(created.documentId, sharing2.roles, sharing2.users);
844
+ return created.documentId;
845
+ });
846
+ return this.findOne(viewer, documentId2);
1234
847
  },
1235
848
  /**
1236
- * Create a license
849
+ * Updates name, description, icon and sharing of a bookmark.
850
+ * @throws {errors.NotFoundError} / {errors.ForbiddenError} See findEditable; also 404 when
851
+ * the bookmark was deleted while this request waited for the row lock.
852
+ * @sideeffect Updates the bookmark and replaces its share rows in one transaction.
1237
853
  */
1238
- async createLicense({ email, firstName, lastName }) {
1239
- try {
1240
- const deviceId = this.generateDeviceId();
1241
- const deviceName = this.getDeviceName();
1242
- const ipAddress = this.getIpAddress();
1243
- const userAgent = this.getUserAgent();
1244
- const licenseServerUrl = this.getLicenseServerUrl();
1245
- const response = await fetch(`${licenseServerUrl}/api/licenses/create`, {
1246
- method: "POST",
1247
- headers: {
1248
- "Content-Type": "application/json"
1249
- },
1250
- body: JSON.stringify({
1251
- email,
1252
- firstName,
1253
- lastName,
1254
- deviceName,
1255
- deviceId,
1256
- ipAddress,
1257
- userAgent,
1258
- pluginName: "magic-mark",
1259
- productName: "MagicMark - Advanced Query Builder"
1260
- })
1261
- });
1262
- const data = await response.json();
1263
- if (data.success) {
1264
- log.info("[SUCCESS] License created successfully:", data.data.licenseKey);
1265
- return data.data;
1266
- } else {
1267
- log.error("[ERROR] License creation failed:", data);
1268
- return null;
1269
- }
1270
- } catch (error) {
1271
- log.error("[ERROR] Error creating license:", error);
1272
- return null;
1273
- }
854
+ async update(viewer, documentId2, input) {
855
+ await findEditable(viewer, documentId2);
856
+ const sharing2 = await resolveSharing(viewer, input);
857
+ const data = { updaterId: viewer.userId };
858
+ if (input.name !== void 0) data.name = input.name;
859
+ if (input.description !== void 0) data.description = input.description;
860
+ if (input.icon !== void 0) data.emoji = input.icon;
861
+ if (sharing2) data.isPublic = sharing2.isPublic;
862
+ await db.transaction(async ({ trx }) => {
863
+ await lockBookmark(trx, documentId2);
864
+ await documents().update({ documentId: documentId2, data, fields: ["documentId"] });
865
+ if (sharing2) await replaceShares(documentId2, sharing2.roles, sharing2.users);
866
+ });
867
+ return this.findOne(viewer, documentId2);
1274
868
  },
1275
869
  /**
1276
- * Verify a license (with grace period support)
870
+ * Replaces the saved list view query ("Update with current view").
1277
871
  */
1278
- async verifyLicense(licenseKey, allowGracePeriod = false) {
1279
- try {
1280
- const controller = new AbortController();
1281
- const timeoutId = setTimeout(() => controller.abort(), 5e3);
1282
- const licenseServerUrl = this.getLicenseServerUrl();
1283
- const response = await fetch(`${licenseServerUrl}/api/licenses/verify`, {
1284
- method: "POST",
1285
- headers: {
1286
- "Content-Type": "application/json"
1287
- },
1288
- body: JSON.stringify({
1289
- licenseKey,
1290
- pluginName: "magic-mark",
1291
- productName: "MagicMark - Advanced Query Builder"
1292
- }),
1293
- signal: controller.signal
872
+ async updateView(viewer, documentId2, query) {
873
+ await findEditable(viewer, documentId2);
874
+ await db.transaction(async ({ trx }) => {
875
+ await lockBookmark(trx, documentId2);
876
+ await documents().update({
877
+ documentId: documentId2,
878
+ data: { query, updaterId: viewer.userId },
879
+ fields: ["documentId"]
1294
880
  });
1295
- clearTimeout(timeoutId);
1296
- const data = await response.json();
1297
- if (data.success) {
1298
- const isValid = data.data.isActive && !data.data.isExpired;
1299
- const statusInfo = data.data.isExpired ? "EXPIRED" : data.data.isActive ? "ACTIVE" : "INACTIVE";
1300
- log.info(`[SUCCESS] License verified online: ${statusInfo} (Key: ${licenseKey?.substring(0, 8)}...)`);
1301
- if (isValid) {
1302
- const pluginStore = strapi.store({
1303
- type: "plugin",
1304
- name: "magic-mark"
1305
- });
1306
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
1307
- }
1308
- return {
1309
- valid: isValid,
1310
- data: data.data
1311
- };
1312
- } else {
1313
- log.warn(`[WARN] License verification failed: ${data.message || "Unknown error"} (Key: ${licenseKey?.substring(0, 8)}...)`);
1314
- return { valid: false, data: null };
1315
- }
1316
- } catch (error) {
1317
- if (allowGracePeriod) {
1318
- log.warn(`[WARN] Cannot verify license online: ${error.message} (Key: ${licenseKey?.substring(0, 8)}...)`);
1319
- log.info(`[GRACE] Grace period active - accepting stored license key`);
1320
- return { valid: true, data: null, gracePeriod: true };
1321
- }
1322
- log.error(`[ERROR] Error verifying license: ${error.message} (Key: ${licenseKey?.substring(0, 8)}...)`);
1323
- return { valid: false, data: null };
1324
- }
881
+ });
882
+ return this.findOne(viewer, documentId2);
1325
883
  },
1326
884
  /**
1327
- * Ping a license (lightweight check)
885
+ * Copies a visible bookmark into a new private bookmark owned by the viewer.
1328
886
  */
1329
- async pingLicense(licenseKey) {
1330
- try {
1331
- const licenseServerUrl = this.getLicenseServerUrl();
1332
- const response = await fetch(`${licenseServerUrl}/api/licenses/ping`, {
1333
- method: "POST",
1334
- headers: {
1335
- "Content-Type": "application/json"
1336
- },
1337
- body: JSON.stringify({
1338
- licenseKey,
1339
- pluginName: "magic-mark",
1340
- productName: "MagicMark - Advanced Query Builder"
1341
- })
1342
- });
1343
- const data = await response.json();
1344
- if (data.success) {
1345
- log.debug(`[PING] License ping successful: ${data.data?.isActive ? "ACTIVE" : "INACTIVE"} (Key: ${licenseKey?.substring(0, 8)}...)`);
1346
- return data.data;
1347
- } else {
1348
- log.debug(`[WARN] License ping failed: ${data.message || "Unknown error"} (Key: ${licenseKey?.substring(0, 8)}...)`);
1349
- return null;
1350
- }
1351
- } catch (error) {
1352
- log.debug(`License ping error: ${error.message} (Key: ${licenseKey?.substring(0, 8)}...)`);
1353
- return null;
1354
- }
887
+ async duplicate(viewer, documentId2, name2) {
888
+ const source = await findVisible(viewer, documentId2);
889
+ const normalized = normalizeListViewPath(source.path);
890
+ if (!normalized) throw new utils.errors.ValidationError("This bookmark has no valid list view");
891
+ return this.create(viewer, {
892
+ name: name2 ?? `${source.name} (copy)`.slice(0, 100),
893
+ description: source.description ?? "",
894
+ icon: ICON_KEYS.includes(source.emoji ?? "") ? source.emoji : "bookmark",
895
+ path: normalized,
896
+ // Rows from 3.x or older builds may hold an unnormalised query; never copy it as is.
897
+ query: normalizeListViewQuery(source.query) ?? ""
898
+ });
1355
899
  },
1356
900
  /**
1357
- * Get license by key
901
+ * Deletes a bookmark with its shares and preferences.
902
+ * @sideeffect Deletes rows in three tables in one transaction.
1358
903
  */
1359
- async getLicenseByKey(licenseKey) {
1360
- try {
1361
- const licenseServerUrl = this.getLicenseServerUrl();
1362
- const response = await fetch(`${licenseServerUrl}/api/licenses/key/${licenseKey}`);
1363
- const data = await response.json();
1364
- if (data.success) {
1365
- return data.data;
1366
- }
1367
- return null;
1368
- } catch (error) {
1369
- log.error("[ERROR] Error fetching license by key:", error);
1370
- return null;
1371
- }
904
+ async delete(viewer, documentId2) {
905
+ await findEditable(viewer, documentId2);
906
+ await db.transaction(async ({ trx }) => {
907
+ await lockBookmark(trx, documentId2);
908
+ await db.query(SHARE_UID).deleteMany({ where: { bookmarkDocumentId: documentId2 } });
909
+ await db.query(PREFERENCE_UID).deleteMany({ where: { bookmarkDocumentId: documentId2 } });
910
+ await documents().delete({ documentId: documentId2 });
911
+ });
912
+ return { documentId: documentId2 };
1372
913
  },
1373
914
  /**
1374
- * Get current license data from store (fetches fresh from server)
1375
- * This is the correct way to get license data with all feature flags
915
+ * Pins or unpins a visible bookmark for the viewer only. Idempotent: updates every
916
+ * preference row of the pair and creates one only when none exists. The bookmark row lock
917
+ * makes the check-then-insert safe across processes.
918
+ * @throws {errors.NotFoundError} When the bookmark is not visible or was deleted meanwhile.
919
+ * @sideeffect Writes one bookmark-preference row.
1376
920
  */
1377
- async getCurrentLicense() {
1378
- try {
1379
- const pluginStore = strapi.store({
1380
- type: "plugin",
1381
- name: "magic-mark"
921
+ async setPinned(viewer, documentId2, pinned) {
922
+ await findVisible(viewer, documentId2);
923
+ await db.transaction(async ({ trx }) => {
924
+ await lockBookmark(trx, documentId2);
925
+ const where = { userId: viewer.userId, bookmarkDocumentId: documentId2 };
926
+ const { count } = await db.query(PREFERENCE_UID).updateMany({
927
+ where,
928
+ data: { isPinned: pinned }
1382
929
  });
1383
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
1384
- if (!licenseKey) {
1385
- return null;
930
+ if (!count && pinned) {
931
+ await db.query(PREFERENCE_UID).create({ data: { ...where, isPinned: true } });
1386
932
  }
1387
- const license2 = await this.getLicenseByKey(licenseKey);
1388
- return license2;
1389
- } catch (error) {
1390
- log.error("[LICENSE] Error loading current license:", error);
1391
- return null;
1392
- }
933
+ });
934
+ return { documentId: documentId2, isPinned: pinned };
1393
935
  },
1394
936
  /**
1395
- * Start periodic pinging for a license
937
+ * Roles a bookmark can be shared with.
938
+ * @returns `[{ documentId, name }]`.
1396
939
  */
1397
- startPinging(licenseKey, intervalMinutes = 15) {
1398
- const intervalMs = intervalMinutes * 60 * 1e3;
1399
- this.pingLicense(licenseKey);
1400
- const pingInterval = setInterval(async () => {
1401
- await this.pingLicense(licenseKey);
1402
- }, intervalMs);
1403
- log.info(`[PING] Started pinging license every ${intervalMinutes} minutes`);
1404
- return pingInterval;
940
+ async listRoles() {
941
+ const roles = await db.query(ADMIN_ROLE_UID).findMany({
942
+ select: ["documentId", "name"],
943
+ orderBy: { name: "asc" }
944
+ });
945
+ return roles.map((role) => ({
946
+ documentId: role.documentId,
947
+ name: role.name
948
+ }));
1405
949
  },
1406
950
  /**
1407
- * Initialize license guard
1408
- * Checks for existing license or prompts for creation
951
+ * Searches active admin users a bookmark can be shared with (never the viewer).
952
+ * Email is searched and returned only when the viewer may read admin users.
1409
953
  */
1410
- async initialize() {
1411
- try {
1412
- log.info("[LICENSE] Initializing License Guard...");
1413
- const pluginStore = strapi.store({
1414
- type: "plugin",
1415
- name: "magic-mark"
1416
- });
1417
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
1418
- const lastValidated = await pluginStore.get({ key: "lastValidated" });
1419
- const now = /* @__PURE__ */ new Date();
1420
- const gracePeriodHours = 24;
1421
- let withinGracePeriod = false;
1422
- if (lastValidated) {
1423
- const lastValidatedDate = new Date(lastValidated);
1424
- const hoursSinceValidation = (now.getTime() - lastValidatedDate.getTime()) / (1e3 * 60 * 60);
1425
- withinGracePeriod = hoursSinceValidation < gracePeriodHours;
1426
- }
1427
- log.info("──────────────────────────────────────────────────────────");
1428
- log.info(`[STORE] Plugin Store Check:`);
1429
- if (licenseKey) {
1430
- log.info(` [OK] License Key found: ${licenseKey}`);
1431
- log.info(` [KEY] Key (short): ${licenseKey.substring(0, 8)}...`);
1432
- if (lastValidated) {
1433
- const lastValidatedDate = new Date(lastValidated);
1434
- const hoursAgo = Math.floor((now.getTime() - lastValidatedDate.getTime()) / (1e3 * 60 * 60));
1435
- log.info(` [TIME] Last validated: ${hoursAgo}h ago (Grace: ${withinGracePeriod ? "ACTIVE" : "EXPIRED"})`);
1436
- } else {
1437
- log.info(` [TIME] Last validated: Never (Grace: ACTIVE for first ${gracePeriodHours}h)`);
1438
- }
1439
- } else {
1440
- log.info(` [NONE] No license key stored`);
954
+ async searchUsers(viewer, params) {
955
+ const where = [
956
+ { isActive: true },
957
+ { documentId: { $ne: viewer.userId } }
958
+ ];
959
+ if (params.q) {
960
+ const fields = ["firstname", "lastname", "username"];
961
+ if (viewer.canReadUsers) fields.push("email");
962
+ where.push({ $or: fields.map((field) => ({ [field]: { $containsi: params.q } })) });
963
+ }
964
+ const select = ["documentId", "firstname", "lastname", "username"];
965
+ if (viewer.canReadUsers) select.push("email");
966
+ const { results, pagination } = await db.query(ADMIN_USER_UID).findPage({
967
+ where: { $and: where },
968
+ select,
969
+ orderBy: [{ firstname: "asc" }, { lastname: "asc" }, { id: "asc" }],
970
+ page: params.page ?? 1,
971
+ pageSize: LIMITS.userSearchPageSize
972
+ });
973
+ return {
974
+ results: results.map((user) => ({
975
+ documentId: user.documentId,
976
+ name: displayName(user),
977
+ ...viewer.canReadUsers ? { email: user.email ?? null } : {}
978
+ })),
979
+ pagination
980
+ };
981
+ }
982
+ };
983
+ };
984
+ const resolveLegacyIds = async (strapi, uid, raw) => {
985
+ if (!Array.isArray(raw) || raw.length === 0) return [];
986
+ const values = raw.slice(0, 1e3);
987
+ const numeric = values.map(
988
+ (value) => typeof value === "number" ? value : /^\d+$/.test(String(value)) ? Number(value) : NaN
989
+ ).filter((value) => Number.isInteger(value));
990
+ const strings = values.filter(
991
+ (value) => typeof value === "string" && !/^\d+$/.test(value)
992
+ );
993
+ const or = [];
994
+ if (numeric.length) or.push({ id: { $in: numeric } });
995
+ if (strings.length) or.push({ documentId: { $in: strings } });
996
+ if (!or.length) return [];
997
+ const rows = await strapi.db.query(uid).findMany({ where: { $or: or }, select: ["documentId"] });
998
+ return [...new Set(rows.map((row) => row.documentId))];
999
+ };
1000
+ const maintenanceService = ({ strapi }) => {
1001
+ const db = strapi.db;
1002
+ const dropped = { queries: 0 };
1003
+ const migrateRow = async (row) => {
1004
+ if (row.contentType === null || row.contentType === void 0) {
1005
+ const normalized = normalizeListViewPath(row.path);
1006
+ const query = normalizeListViewQuery(row.query);
1007
+ if (query === null) dropped.queries += 1;
1008
+ await db.query(BOOKMARK_UID).updateMany({
1009
+ where: { id: row.id, contentType: { $null: true } },
1010
+ data: {
1011
+ ...normalized ? { path: normalized.path, contentType: normalized.contentType } : { contentType: "" },
1012
+ query: query ?? ""
1441
1013
  }
1442
- log.info("──────────────────────────────────────────────────────────");
1443
- if (licenseKey) {
1444
- log.info("[VERIFY] Verifying stored license key...");
1445
- const verification = await this.verifyLicense(licenseKey, true);
1446
- if (verification.valid) {
1447
- if (verification.gracePeriod) {
1448
- log.info("[SUCCESS] License accepted (offline mode / grace period)");
1449
- } else {
1450
- log.info("[SUCCESS] License is valid and active");
1451
- }
1452
- const pingInterval = this.startPinging(licenseKey, 15);
1453
- strapi.licenseGuard = {
1454
- licenseKey,
1455
- pingInterval,
1456
- data: verification.data
1457
- };
1458
- return { valid: true, data: verification.data };
1459
- } else {
1460
- log.warn("[WARN] Stored license is invalid or expired");
1461
- if (!withinGracePeriod) {
1462
- await pluginStore.delete({ key: "licenseKey" });
1463
- await pluginStore.delete({ key: "lastValidated" });
1464
- }
1465
- }
1014
+ });
1015
+ }
1016
+ if (row.sharedWithRoles !== null || row.sharedWithUsers !== null) {
1017
+ const [roles, users] = await Promise.all([
1018
+ resolveLegacyIds(strapi, ADMIN_ROLE_UID, row.sharedWithRoles),
1019
+ resolveLegacyIds(strapi, ADMIN_USER_UID, row.sharedWithUsers)
1020
+ ]);
1021
+ await db.transaction(async () => {
1022
+ const { count } = await db.query(BOOKMARK_UID).updateMany({
1023
+ where: {
1024
+ id: row.id,
1025
+ $or: [{ sharedWithRoles: { $notNull: true } }, { sharedWithUsers: { $notNull: true } }]
1026
+ },
1027
+ data: { sharedWithRoles: null, sharedWithUsers: null }
1028
+ });
1029
+ if (count !== 1) return;
1030
+ const data = [
1031
+ ...roles.map((targetId) => ({ targetType: "role", targetId })),
1032
+ ...users.filter((targetId) => targetId !== row.creatorId).map((targetId) => ({ targetType: "user", targetId }))
1033
+ ].map((share) => ({ ...share, bookmarkDocumentId: row.documentId }));
1034
+ if (data.length) await db.query(SHARE_UID).createMany({ data });
1035
+ });
1036
+ }
1037
+ if (row.isPinned) {
1038
+ await db.transaction(async () => {
1039
+ const { count } = await db.query(BOOKMARK_UID).updateMany({
1040
+ where: { id: row.id, isPinned: true },
1041
+ data: { isPinned: false }
1042
+ });
1043
+ if (count !== 1 || !row.creatorId) return;
1044
+ const exists = await db.query(PREFERENCE_UID).count({
1045
+ where: { userId: row.creatorId, bookmarkDocumentId: row.documentId }
1046
+ });
1047
+ if (!exists) {
1048
+ await db.query(PREFERENCE_UID).create({
1049
+ data: { userId: row.creatorId, bookmarkDocumentId: row.documentId, isPinned: true }
1050
+ });
1466
1051
  }
1467
- log.warn("[WARN] No valid license found. Plugin will run with limited functionality.");
1468
- return { valid: false, demo: true };
1469
- } catch (error) {
1470
- log.error("[ERROR] Error initializing license guard:", error);
1471
- return { valid: false, error: error.message };
1472
- }
1473
- },
1052
+ });
1053
+ }
1054
+ };
1055
+ const grantActions = async (roleId, actions) => {
1056
+ await db.transaction(async ({ trx }) => {
1057
+ const role = await db.queryBuilder(ADMIN_ROLE_UID).select(["id"]).where({ id: roleId }).first().transacting(trx).forUpdate().execute();
1058
+ if (!role) return;
1059
+ const existing = await db.query(ADMIN_PERMISSION_UID).findMany({
1060
+ where: { role: { id: roleId }, action: { $in: actions } },
1061
+ select: ["action"]
1062
+ });
1063
+ const have = new Set(existing.map((row) => row.action));
1064
+ const missing = actions.filter((action) => !have.has(action));
1065
+ if (!missing.length) return;
1066
+ await strapi.admin.services.permission.createMany(
1067
+ missing.map((action) => ({
1068
+ action,
1069
+ subject: null,
1070
+ properties: {},
1071
+ conditions: [],
1072
+ role: roleId
1073
+ }))
1074
+ );
1075
+ });
1076
+ };
1077
+ return {
1474
1078
  /**
1475
- * Store license key after creation
1079
+ * Deletes the store keys of the removed 3.x license system.
1080
+ * @sideeffect Deletes plugin store rows `licenseKey` and `lastValidated`.
1476
1081
  */
1477
- async storeLicenseKey(licenseKey) {
1478
- try {
1479
- log.info(`[STORE] Storing license key: ${licenseKey}`);
1480
- const pluginStore = strapi.store({
1481
- type: "plugin",
1482
- name: "magic-mark"
1483
- });
1484
- await pluginStore.set({ key: "licenseKey", value: licenseKey });
1485
- await pluginStore.set({ key: "lastValidated", value: (/* @__PURE__ */ new Date()).toISOString() });
1486
- const stored = await pluginStore.get({ key: "licenseKey" });
1487
- if (stored === licenseKey) {
1488
- log.info("[SUCCESS] License key stored and verified successfully");
1489
- return true;
1490
- } else {
1491
- log.error("[ERROR] License key storage verification failed");
1492
- return false;
1493
- }
1494
- } catch (error) {
1495
- log.error("[ERROR] Error storing license key:", error);
1496
- return false;
1082
+ async removeLegacyLicenseKeys() {
1083
+ const store = strapi.store({ type: "plugin", name: PLUGIN_ID });
1084
+ for (const key of LEGACY_STORE_KEYS) {
1085
+ await store.delete({ key });
1497
1086
  }
1498
1087
  },
1499
1088
  /**
1500
- * Get bookmark limit based on license tier
1501
- * @returns Bookmark limit: 10 (free), 50 (premium), -1 (advanced/unlimited)
1089
+ * Migrates every 3.x bookmark row (paths, content types, queries, share JSON, global pins).
1090
+ * Walks by id cursor in batches; rows already migrated are not selected again.
1091
+ * @returns Number of rows inspected.
1502
1092
  */
1503
- async getBookmarkLimit() {
1504
- try {
1505
- const licenseGuard = strapi.licenseGuard;
1506
- const licenseData = licenseGuard?.data;
1507
- if (licenseData?.featureAdvanced) {
1508
- return -1;
1093
+ async migrateLegacyBookmarks() {
1094
+ let cursor = 0;
1095
+ let inspected = 0;
1096
+ for (; ; ) {
1097
+ const rows = await db.query(BOOKMARK_UID).findMany({
1098
+ where: {
1099
+ id: { $gt: cursor },
1100
+ $or: [
1101
+ { contentType: { $null: true } },
1102
+ { sharedWithRoles: { $notNull: true } },
1103
+ { sharedWithUsers: { $notNull: true } },
1104
+ { isPinned: true }
1105
+ ]
1106
+ },
1107
+ select: [
1108
+ "id",
1109
+ "documentId",
1110
+ "path",
1111
+ "contentType",
1112
+ "query",
1113
+ "creatorId",
1114
+ "isPinned",
1115
+ "sharedWithRoles",
1116
+ "sharedWithUsers"
1117
+ ],
1118
+ orderBy: { id: "asc" },
1119
+ limit: LIMITS.migrationBatch
1120
+ });
1121
+ if (!rows.length) {
1122
+ if (dropped.queries) {
1123
+ strapi.log.warn(
1124
+ `[magic-mark] ${dropped.queries} 3.x bookmark filter(s) could not be kept and were reset`
1125
+ );
1126
+ dropped.queries = 0;
1127
+ }
1128
+ return inspected;
1509
1129
  }
1510
- if (licenseData?.featurePremium) {
1511
- return 50;
1130
+ for (const row of rows) {
1131
+ try {
1132
+ await migrateRow(row);
1133
+ } catch (error) {
1134
+ strapi.log.error("[magic-mark] Bookmark migration failed for one row", {
1135
+ name: error?.name
1136
+ });
1137
+ }
1512
1138
  }
1513
- return 10;
1514
- } catch (error) {
1515
- log.debug("[LICENSE] Error getting bookmark limit, using free tier");
1516
- return 10;
1139
+ inspected += rows.length;
1140
+ cursor = rows[rows.length - 1].id;
1517
1141
  }
1518
1142
  },
1519
1143
  /**
1520
- * Check if user can create more bookmarks
1521
- * @param userId - User's documentId
1522
- * @returns Object with canCreate boolean and current/max counts
1144
+ * Grants the 4.x actions to every role that held a 3.x action. Runs before the admin
1145
+ * removes permissions of unregistered actions, so existing roles keep their access.
1146
+ * Safe when every process of a cluster runs it at once (per-role row lock).
1147
+ * @sideeffect Creates admin permission rows.
1523
1148
  */
1524
- async canCreateBookmark(userId) {
1525
- try {
1526
- const limit = await this.getBookmarkLimit();
1527
- if (limit === -1) {
1528
- return { canCreate: true, current: 0, max: -1 };
1529
- }
1530
- const BOOKMARK_UID2 = "plugin::magic-mark.bookmark";
1531
- const bookmarks = await strapi.documents(BOOKMARK_UID2).findMany({
1532
- filters: { creatorId: userId }
1533
- });
1534
- const currentCount = bookmarks?.length || 0;
1535
- if (currentCount >= limit) {
1536
- return {
1537
- canCreate: false,
1538
- current: currentCount,
1539
- max: limit,
1540
- message: `Bookmark limit reached (${currentCount}/${limit}). Upgrade to create more bookmarks.`
1541
- };
1542
- }
1543
- return { canCreate: true, current: currentCount, max: limit };
1544
- } catch (error) {
1545
- log.error("[LICENSE] Error checking bookmark limit:", error);
1546
- return { canCreate: true, current: 0, max: 10 };
1547
- }
1149
+ async migrateLegacyPermissions() {
1150
+ const legacy = await db.query(ADMIN_PERMISSION_UID).findMany({
1151
+ where: { action: { $in: Object.keys(LEGACY_ACTION_MAP) } },
1152
+ populate: ["role"]
1153
+ });
1154
+ const wanted = /* @__PURE__ */ new Map();
1155
+ for (const permission of legacy) {
1156
+ if (!permission.role?.id) continue;
1157
+ const set = wanted.get(permission.role.id) ?? /* @__PURE__ */ new Set();
1158
+ for (const key of LEGACY_ACTION_MAP[permission.action] ?? []) set.add(actionId(key));
1159
+ wanted.set(permission.role.id, set);
1160
+ }
1161
+ for (const [roleId, actions] of wanted) await grantActions(roleId, [...actions]);
1548
1162
  },
1549
1163
  /**
1550
- * Get current license limits and feature flags
1551
- * @param userId - User's documentId for bookmark count
1552
- * @returns License limits object
1164
+ * Gives the super admin role every Magic Mark action before the admin bootstrap runs.
1165
+ * Strapi's super admin sync (`resetSuperAdminPermissions`, admin bootstrap) does the same,
1166
+ * but without a lock: when several processes start at once, each one inserts the missing
1167
+ * actions and the role ends up with duplicates. Granting them here, under the role row lock,
1168
+ * leaves the admin sync nothing to insert. Does nothing before the role exists (first start
1169
+ * of a new project).
1170
+ * @sideeffect Creates admin permission rows for the super admin role.
1553
1171
  */
1554
- async getLicenseLimits(userId) {
1555
- try {
1556
- const license2 = await this.getCurrentLicense();
1557
- log.info("[LICENSE] getLicenseLimits - license exists:", !!license2);
1558
- if (license2) {
1559
- log.info("[LICENSE] getLicenseLimits - featurePremium:", license2.featurePremium);
1560
- log.info("[LICENSE] getLicenseLimits - featureAdvanced:", license2.featureAdvanced);
1561
- }
1562
- let tier = "free";
1563
- if (license2?.featureEnterprise === true) tier = "enterprise";
1564
- else if (license2?.featureAdvanced === true) tier = "advanced";
1565
- else if (license2?.featurePremium === true) tier = "premium";
1566
- const isPremium = tier === "premium" || tier === "advanced" || tier === "enterprise";
1567
- const isAdvanced = tier === "advanced" || tier === "enterprise";
1568
- log.info("[LICENSE] getLicenseLimits - detected tier:", tier);
1569
- const bookmarkCheck = await this.canCreateBookmark(userId);
1570
- return {
1571
- maxBookmarks: bookmarkCheck.max,
1572
- currentBookmarks: bookmarkCheck.current,
1573
- canCreate: bookmarkCheck.canCreate,
1574
- tier,
1575
- features: {
1576
- queryHistory: isPremium || isAdvanced,
1577
- export: isPremium || isAdvanced,
1578
- analytics: isAdvanced,
1579
- bulkOperations: isAdvanced,
1580
- customIntegrations: isAdvanced
1581
- }
1582
- };
1583
- } catch (error) {
1584
- log.error("[LICENSE] Error getting license limits:", error);
1585
- return {
1586
- maxBookmarks: 10,
1587
- currentBookmarks: 0,
1588
- canCreate: true,
1589
- tier: "free",
1590
- features: {
1591
- queryHistory: false,
1592
- export: false,
1593
- analytics: false,
1594
- bulkOperations: false,
1595
- customIntegrations: false
1596
- }
1597
- };
1598
- }
1172
+ async grantSuperAdminActions() {
1173
+ const role = await db.query(ADMIN_ROLE_UID).findOne({
1174
+ where: { code: SUPER_ADMIN_CODE },
1175
+ select: ["id"]
1176
+ });
1177
+ if (!role) return;
1178
+ await grantActions(
1179
+ role.id,
1180
+ Object.keys(ACTION_UIDS).map((key) => actionId(key))
1181
+ );
1599
1182
  },
1600
1183
  /**
1601
- * Check if a specific feature is available based on license
1602
- * @param feature - Feature key to check
1603
- * @returns Boolean indicating if feature is available
1184
+ * Removes duplicate Magic Mark permission rows (same role, action, subject, properties and
1185
+ * conditions), keeping the oldest. Duplicates can be left by an earlier start of several
1186
+ * processes at once on a new project, where the super admin role did not exist yet when
1187
+ * `grantSuperAdminActions` ran. Concurrent runs pick the same row to keep.
1188
+ * @returns Number of rows removed.
1189
+ * @sideeffect Deletes admin permission rows through the admin permission service.
1604
1190
  */
1605
- hasFeature(feature) {
1606
- try {
1607
- const licenseGuard = strapi.licenseGuard;
1608
- const licenseData = licenseGuard?.data;
1609
- const isPremium = licenseData?.featurePremium || false;
1610
- const isAdvanced = licenseData?.featureAdvanced || false;
1611
- const featureRequirements = {
1612
- // Free tier
1613
- basicBookmarks: "free",
1614
- basicFilters: "free",
1615
- // Premium tier
1616
- extendedBookmarks: "premium",
1617
- queryHistory: "premium",
1618
- exportBookmarks: "premium",
1619
- sharedBookmarks: "premium",
1620
- // Advanced tier
1621
- unlimitedBookmarks: "advanced",
1622
- advancedFilters: "advanced",
1623
- subGroups: "advanced",
1624
- bulkOperations: "advanced",
1625
- analytics: "advanced",
1626
- customIntegrations: "advanced"
1627
- };
1628
- const requiredTier = featureRequirements[feature] || "free";
1629
- let currentTierLevel = 0;
1630
- if (isAdvanced) currentTierLevel = 2;
1631
- else if (isPremium) currentTierLevel = 1;
1632
- const tierLevels = {
1633
- free: 0,
1634
- premium: 1,
1635
- advanced: 2
1636
- };
1637
- return currentTierLevel >= tierLevels[requiredTier];
1638
- } catch (error) {
1639
- log.debug("[LICENSE] Error checking feature:", feature);
1640
- return false;
1641
- }
1191
+ async removeDuplicatePermissions() {
1192
+ const rows = await db.query(ADMIN_PERMISSION_UID).findMany({
1193
+ where: {
1194
+ action: { $in: Object.keys(ACTION_UIDS).map((key) => actionId(key)) }
1195
+ },
1196
+ select: ["id", "action", "subject", "properties", "conditions"],
1197
+ populate: { role: { select: ["id"] } },
1198
+ orderBy: { id: "asc" }
1199
+ });
1200
+ const seen = /* @__PURE__ */ new Set();
1201
+ const duplicates = [];
1202
+ for (const row of rows) {
1203
+ const key = JSON.stringify([
1204
+ row.role?.id ?? null,
1205
+ row.action,
1206
+ row.subject ?? null,
1207
+ row.properties ?? {},
1208
+ row.conditions ?? []
1209
+ ]);
1210
+ if (seen.has(key)) duplicates.push(row.id);
1211
+ else seen.add(key);
1212
+ }
1213
+ if (duplicates.length) await strapi.admin.services.permission.deleteByIds(duplicates);
1214
+ return duplicates.length;
1642
1215
  },
1643
1216
  /**
1644
- * Get current tier name
1645
- * @returns 'free' | 'premium' | 'advanced'
1217
+ * Removes what deleted admin users leave behind: their shares and pins, and their
1218
+ * private bookmarks. Public or shared bookmarks stay; `bookmarks.manage` can remove them.
1219
+ * @param userIds - documentIds of the deleted users.
1646
1220
  */
1647
- getCurrentTier() {
1648
- try {
1649
- const licenseGuard = strapi.licenseGuard;
1650
- const licenseData = licenseGuard?.data;
1651
- if (licenseData?.featureAdvanced) return "advanced";
1652
- if (licenseData?.featurePremium) return "premium";
1653
- return "free";
1654
- } catch (error) {
1655
- return "free";
1656
- }
1221
+ async cleanupDeletedUsers(userIds) {
1222
+ if (!userIds.length) return;
1223
+ await db.query(SHARE_UID).deleteMany({
1224
+ where: { targetType: "user", targetId: { $in: userIds } }
1225
+ });
1226
+ await db.query(PREFERENCE_UID).deleteMany({ where: { userId: { $in: userIds } } });
1227
+ const owned = await db.query(BOOKMARK_UID).findMany({
1228
+ where: { creatorId: { $in: userIds }, isPublic: false },
1229
+ select: ["documentId"]
1230
+ });
1231
+ if (!owned.length) return;
1232
+ const ids = owned.map((row) => row.documentId);
1233
+ const shared = await db.query(SHARE_UID).findMany({
1234
+ where: { bookmarkDocumentId: { $in: ids } },
1235
+ select: ["bookmarkDocumentId"]
1236
+ });
1237
+ const sharedIds = new Set(
1238
+ shared.map((row) => row.bookmarkDocumentId)
1239
+ );
1240
+ const privateIds = ids.filter((id) => !sharedIds.has(id));
1241
+ if (!privateIds.length) return;
1242
+ await db.query(PREFERENCE_UID).deleteMany({
1243
+ where: { bookmarkDocumentId: { $in: privateIds } }
1244
+ });
1245
+ await db.query(BOOKMARK_UID).deleteMany({ where: { documentId: { $in: privateIds } } });
1657
1246
  },
1658
1247
  /**
1659
- * Cleanup on plugin destroy
1248
+ * Removes share rows that point at deleted roles.
1249
+ * @param roleIds - documentIds of the deleted roles.
1660
1250
  */
1661
- cleanup() {
1662
- const licenseGuard = strapi.licenseGuard;
1663
- if (licenseGuard && licenseGuard.pingInterval) {
1664
- clearInterval(licenseGuard.pingInterval);
1665
- log.info("[STOP] License pinging stopped");
1666
- }
1251
+ async cleanupDeletedRoles(roleIds) {
1252
+ if (!roleIds.length) return;
1253
+ await db.query(SHARE_UID).deleteMany({
1254
+ where: { targetType: "role", targetId: { $in: roleIds } }
1255
+ });
1667
1256
  }
1668
1257
  };
1669
1258
  };
1670
1259
  const services = {
1671
1260
  bookmarks: bookmarkService,
1672
- "license-guard": licenseGuardService
1261
+ maintenance: maintenanceService
1673
1262
  };
1674
1263
  const index = {
1675
1264
  register,
@@ -1679,8 +1268,6 @@ const index = {
1679
1268
  controllers,
1680
1269
  routes,
1681
1270
  services,
1682
- contentTypes,
1683
- policies,
1684
- middlewares
1271
+ contentTypes
1685
1272
  };
1686
- module.exports = index;
1273
+ exports.default = index;