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