magic-editor-x 2.0.0 → 2.1.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 (51) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +154 -68
  3. package/dist/admin/{ConfigurationPage-DvAifELO.mjs → ConfigurationPage-CK2AbfGW.mjs} +126 -7
  4. package/dist/admin/{ConfigurationPage-B1uCIE3J.js → ConfigurationPage-CzsT_dO_.js} +125 -4
  5. package/dist/admin/{CustomBlocksPage-6-OQwpXQ.mjs → CustomBlocksPage-B2A8S5MV.mjs} +4 -4
  6. package/dist/admin/{CustomBlocksPage-6eWCOreU.js → CustomBlocksPage-CvLrsBds.js} +4 -4
  7. package/dist/admin/{EditorField-ThSoOCPm.mjs → EditorField-7YCdXx-v.mjs} +2019 -661
  8. package/dist/admin/{EditorField-DocyD2Q3.js → EditorField-BdBCW15Q.js} +2015 -657
  9. package/dist/admin/{api-B-RsxJCs.js → api-CmccMxlN.js} +2 -0
  10. package/dist/admin/{api-C4XsDZxd.mjs → api-D5CAH0nh.mjs} +2 -0
  11. package/dist/admin/{de-RAxzvrwm.mjs → de-BHPyA2S-.mjs} +10 -2
  12. package/dist/admin/{de-BMxADn2Z.mjs → de-Bt6pYIWi.mjs} +16 -1
  13. package/dist/admin/{de-Dx7vUW0Z.js → de-CVbi685U.js} +16 -1
  14. package/dist/admin/{de-DcDPRzV4.js → de-CkUYGb7U.js} +22 -1
  15. package/dist/admin/{de-B8XFFhHh.js → de-RMs-_SCK.js} +10 -2
  16. package/dist/admin/{de-n5V6c5RT.mjs → de-rRIutpYJ.mjs} +22 -1
  17. package/dist/admin/{en-sNn4z9lA.js → en-BX362fTp.js} +16 -1
  18. package/dist/admin/{en-BQ5Pxe2o.mjs → en-B_HltUxZ.mjs} +16 -1
  19. package/dist/admin/{en-BzfyifEU.mjs → en-BluCStLw.mjs} +10 -2
  20. package/dist/admin/{en-DcWUTE2J.js → en-C81faOHP.js} +10 -2
  21. package/dist/admin/{en-D-DGftl0.js → en-DulOcmXb.js} +22 -1
  22. package/dist/admin/{en-BqNm3nMQ.mjs → en-Puup8TFi.mjs} +22 -1
  23. package/dist/admin/{es-SzeTV4q8.mjs → es-257SSB7f.mjs} +22 -1
  24. package/dist/admin/{es-Di0pyQCh.js → es-BoQZC86B.js} +22 -1
  25. package/dist/admin/{es-DVsXnS0N.js → es-CHHEZi44.js} +16 -1
  26. package/dist/admin/{es-C2OJVYkV.mjs → es-CQRI2Prp.mjs} +10 -2
  27. package/dist/admin/{es-B6NYq0VH.mjs → es-CrhwOq-5.mjs} +16 -1
  28. package/dist/admin/{es-BOtVc9qv.js → es-D1QzY0JW.js} +10 -2
  29. package/dist/admin/{fr-DmG3_Cn-.mjs → fr-5djKfQ3s.mjs} +16 -1
  30. package/dist/admin/{fr-Fwxcj4SM.js → fr-B3SL0TBV.js} +16 -1
  31. package/dist/admin/{fr-DhgPYHIH.mjs → fr-C5rSdKU4.mjs} +22 -1
  32. package/dist/admin/{fr-Bpo5Uq1f.mjs → fr-Di3R6gOX.mjs} +10 -2
  33. package/dist/admin/{fr-D6F--jIB.js → fr-HxFcPpv4.js} +22 -1
  34. package/dist/admin/{fr-DfxKaOc_.js → fr-R3_MbzT5.js} +10 -2
  35. package/dist/admin/{index-D1Q5Rlt6.mjs → index-0_b1iroK.mjs} +18 -18
  36. package/dist/admin/{index-CwfaB5-e.js → index-6SZLli70.js} +18 -18
  37. package/dist/admin/index.js +1 -1
  38. package/dist/admin/index.mjs +1 -1
  39. package/dist/admin/{pt-LCvjwk0y.js → pt-BCW1u_Hp.js} +10 -2
  40. package/dist/admin/{pt-BbdwHlWF.mjs → pt-BdnY2Cth.mjs} +16 -1
  41. package/dist/admin/{pt-BPo0ex21.js → pt-Cjn2Sc9k.js} +22 -1
  42. package/dist/admin/{pt-DqCXuI4S.mjs → pt-Cr9AL408.mjs} +10 -2
  43. package/dist/admin/{pt-BvSl1btT.mjs → pt-D6UuEtPy.mjs} +22 -1
  44. package/dist/admin/{pt-C6nr71Yw.js → pt-EVwCuBUK.js} +16 -1
  45. package/dist/admin/{sanitize-9UVcXFfc.js → sanitize-DP5aeU7V.js} +46 -1
  46. package/dist/admin/{sanitize-D4kfZ_ly.mjs → sanitize-jjCot5PM.mjs} +47 -2
  47. package/dist/admin/{useT-B5M49wGH.js → useT-91ruePzq.js} +1 -1
  48. package/dist/admin/{useT-CjX6fL2m.mjs → useT-vgY88N_H.mjs} +1 -1
  49. package/dist/server/index.js +1561 -321
  50. package/dist/server/index.mjs +1561 -321
  51. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,59 @@
1
1
  # Changelog
2
2
 
3
+ # [2.1.0](https://github.com/Schero94/Magic-Editor-X/compare/v2.0.0...v2.1.0) (2026-11-11)
4
+
5
+
6
+ ### Features
7
+
8
+ * conflict-free structured collaboration, presence and hardened realtime (2.1.0) ([#4](https://github.com/Schero94/Magic-Editor-X/issues/4)) ([edc2fac](https://github.com/Schero94/Magic-Editor-X/commit/edc2face5e1da174de8d95c86480792b411de86a))
9
+
10
+
11
+ Magic Editor X 2.1 makes live collaboration conflict-free for every kind of block, adds presence with carets, hardens the realtime server and closes the remaining limitations of 2.0. No migration is needed; stored content keeps the same Editor.js JSON.
12
+
13
+ ### Highlights
14
+
15
+ - **Conflict-free structured collaboration.** Every table cell, list item, checklist entry, tune (alignment, text variant, indent) and custom block field is merged separately (collaboration schema 3). Two people can edit different cells of one table, different items of one list, or the text and alignment of one paragraph at the same time and both changes are kept. Same-value conflicts resolve the same way on every screen.
16
+ - **Presence.** Coloured carets and selections of the others, an "editing this block" marker, avatars with first name and last initial (never e-mail addresses), away state, polite screen-reader announcements of joins and leaves, light and dark theme, reduced motion respected.
17
+ - **Robust connections.** Offline editing with automatic resync, exponential backoff with jitter, immediate reconnect after sleep, tab switch or network return, no duplicated content after a reconnect or a room reset, clean leave on tab close, new states Reconnecting and Offline in the toolbar.
18
+ - **Per-user undo.** Undo and redo during live editing only revert your own changes.
19
+ - **Permission changes apply within about a second** on every process (role, permission and user changes); losing update access makes the editor read-only, losing read access ends live editing.
20
+ - **Hardened realtime server.** Every update is checked before it is stored or relayed (allowed structures only, dependencies present, valid blocks), remote content is sanitised before the editor renders it, rate limits per socket and per admin, protocol version check.
21
+ - **No lost work.** Rooms that are cleaned up with edits nobody saved get a final version first.
22
+ - **Cluster-wide limits.** The AI rate limit and the new session limit are shared by all processes.
23
+ - **Content Security Policy notice.** Settings > Magic Editor X > Configuration shows when the admin CSP blocks editor embeds (`frame-src`) or external images (`img-src`), with a ready-to-copy `config/middlewares.js` snippet. The plugin never changes the CSP. Blocked embeds and images show an accessible placeholder in the editor instead of a broken frame.
24
+ - **Internal links.** "Link to an entry" in the link tool searches entries of your content types and inserts a link; only types and entries you can read in the Content Manager appear. No paid add-on is needed.
25
+
26
+ ### Added
27
+
28
+ - Admin routes `GET /magic-editor-x/links/types` and `GET /magic-editor-x/links/search`.
29
+ - `GET /magic-editor-x/settings` returns `data.environment.csp` (`active`, `frameSrcMissing`, `imgSrcMissing`, `snippet`).
30
+ - Config keys `collaboration.maxConnectionsPerAdmin` (20), `collaboration.maxRoomsPerAdmin` (20), `collaboration.revalidateSeconds` (60), `collaboration.rateLimit` (`sessionsPerMinute` 60, `updatesPer10s` 300, `bytesPer10s` 8 MiB) and `links.urlPattern` (placeholders `{documentId}`, `{locale}`, `{slug}`, `{collection}`, `{singular}`; default `/{collection}/{documentId}`).
31
+ - Internal links keep a plain `href` and carry `data-mex-uid`, `data-mex-document-id` and `data-mex-locale`; the shared sanitiser allows them on `<a>` only, with validated values.
32
+ - Table `magic_editor_x_counters` (created on startup) for cluster-wide rate limits.
33
+ - `scripts/soak.mjs` and a cluster acceptance run with process kills, network partitions, offline clients and 12 concurrent clients.
34
+
35
+ ### Changed
36
+
37
+ - Collaboration protocol 3: the handshake carries `auth: { token, protocol: 3 }`; refusals arrive as `connect_error` with `data.code`. A browser tab still running the 2.0 admin is asked to reload.
38
+ - `POST /magic-editor-x/collaboration/session` also returns `seeded` and `protocol` and answers 429 above `collaboration.rateLimit.sessionsPerMinute`.
39
+ - `ai.requestsPerMinute` is counted per admin across all processes (was per process).
40
+ - Presence colours are Design System colour families instead of fixed hex values.
41
+
42
+ ### Fixed
43
+
44
+ - Opening 1.x content no longer marks the form as changed.
45
+ - Enter in the link-preview and image-URL fields no longer adds an empty block.
46
+ - Automatic versions during live editing are taken when each period ends, not a few seconds after someone starts typing.
47
+ - The tamper check of the AES-GCM unit test no longer fails in 1 of 64 runs.
48
+
49
+ ### Security
50
+
51
+ - See [docs/security-audit-2.1.md](./docs/security-audit-2.1.md): sanitising of remote content before rendering (MEX-21-01), update validation (MEX-21-02, -03), permission changes within seconds (MEX-21-04), rate limits (MEX-21-05, -06), protocol check (MEX-21-07), presence (MEX-21-08), no lost edits (MEX-21-09).
52
+
53
+ ### Migration
54
+
55
+ - No action needed. Rebuild the admin (`npm run build`) after updating. Live rooms created by 2.0 keep working and are converted on the first edit; open 2.0 browser tabs show "Reload the page to keep editing live".
56
+
3
57
  # [2.0.0](https://github.com/Schero94/Magic-Editor-X/compare/v1.6.0...v2.0.0) (2026-11-11)
4
58
 
5
59
 
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/Schero94/Magic-Editor-X/main/docs/site/img/icon.svg" alt="Magic Editor X" width="96" height="96" />
3
+ </p>
4
+
1
5
  # Magic Editor X
2
6
 
3
7
  Block editor for Strapi 5: an [Editor.js](https://editorjs.io/) custom field with Media Library uploads, custom blocks, version history, live collaboration across several servers and an optional AI assistant that uses your own provider. Free and open source under the MIT license.
@@ -39,7 +43,7 @@ Every feature is available in every installation. There is nothing to activate,
39
43
  - code: plain code (`code`), code with syntax highlighting (`codeFlask`; Prism with JavaScript, TypeScript, JSX/TSX, JSON, HTML, CSS/SCSS, PHP, Python, Ruby, Go, Rust, Java, Kotlin, Swift, C, C++, C#, SQL, Bash, YAML, Markdown, GraphQL, Docker and diff);
40
44
  - media: image upload by file or URL into the Media Library (`image`), picking images from the Media Library (`mediaLib`, inserts `image` blocks), image by URL without upload (`simpleImage`), file attachments (`attaches`), embeds such as YouTube, Vimeo, CodePen, GitHub, Figma and others (`embed`);
41
45
  - other: link preview card (`linkTool`), person card (`personality`), call-to-action button (`button`), raw HTML (`raw`).
42
- - **Inline tools:** bold, italic, link with target and rel (`hyperlink`), marker, underline, strikethrough, inline code, tooltip, and the AI assistant when it is enabled.
46
+ - **Inline tools:** bold, italic, link with target and rel (`hyperlink`, with a built-in picker that links an entry of your content types, see [Internal links](#internal-links)), marker, underline, strikethrough, inline code, tooltip, and the AI assistant when it is enabled.
43
47
  - **Block tunes:** alignment (`alignmentTune`), text variant call-out / citation / details (`textVariant`), indent (`indentTune`).
44
48
  - **Editing:** undo and redo, drag and drop of blocks, full screen mode, block and word count.
45
49
  - **Custom blocks:** define your own blocks in Settings: simple blocks with fields (text, textarea, URL, number, select, checkbox, image, colour) and an optional HTML template, or embedded-entry blocks that link an entry of another content type. Import and export as JSON.
@@ -128,30 +132,35 @@ After the first start, Super Admins can use everything. Other roles need the plu
128
132
 
129
133
  All keys are optional. Infrastructure options live in `config/plugins`; the AI provider is edited at runtime in Settings > Magic Editor X > Configuration.
130
134
 
131
- | Key | Type | Default | Effect |
132
- | --------------------------------------- | ---------------------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
133
- | `debug` | boolean | `false` | Writes debug log lines (never content or personal data). |
134
- | `rawHtml` | `'sanitize'` \| `'allow'` \| `'disable'` | `'sanitize'` | Raw HTML block on save: `sanitize` removes scripts, event handlers, iframes and unsafe URLs; `allow` stores the HTML as typed; `disable` empties it. |
135
- | `sanitizeOnSave` | boolean | `true` | Normalise and sanitise Magic Editor X values on every Document Service write. Turning this off is not recommended. |
136
- | `encryptionKey` | string (32+ characters) | unset | Key for the stored AI provider key. Prefer the `MAGIC_EDITOR_X_ENCRYPTION_KEY` environment variable. |
137
- | `uploads.maxImageBytes` | integer | `10485760` (10 MiB) | Largest image accepted by file or URL (hard cap 500 MiB). |
138
- | `uploads.maxFileBytes` | integer | `20971520` (20 MiB) | Largest attachment. |
139
- | `linkPreview.enabled` | boolean | `true` | Link preview cards. When `false`, `GET /magic-editor-x/link` answers 404. |
140
- | `linkPreview.timeoutMs` | integer | `8000` | Time limit for fetching a page (1000 to 30000). |
141
- | `api.autoParseJSON` | boolean | `true` | Turn 1.x JSON strings into objects in Content API GET responses. |
142
- | `ai.allowPrivateBaseUrl` | boolean | `false` | Allow AI base URLs on loopback or private networks (for local models). Owner decision; not editable in the admin. |
143
- | `ai.apiKey` | string | unset | Provider key from the environment. When set it wins over a key stored in the settings. |
144
- | `ai.requestsPerMinute` | integer | `20` | AI requests per admin per minute, counted per process. |
145
- | `ai.timeoutMs` | integer | `60000` | Time limit for one provider request. |
146
- | `collaboration.enabled` | boolean | `true` | Live collaboration and its Socket.IO server. |
147
- | `collaboration.path` | string | `'/magic-editor-x/realtime'` | Socket.IO path on the Strapi HTTP server. |
148
- | `collaboration.allowedOrigins` | string[] | `[]` | Extra browser origins allowed to open the socket. The admin URL and the server URL are always allowed. |
149
- | `collaboration.pollIntervalMs` | integer | `400` | How often each process reads updates written by other processes (50 to 10000). |
150
- | `collaboration.roomTtlMinutes` | integer | `30` | Keep a room's live state this long after the last person left. |
151
- | `collaboration.maxMessageBytes` | integer | `2097152` (2 MiB) | Largest accepted socket message. |
152
- | `collaboration.snapshotIntervalMinutes` | integer | `10` | Automatic version while people edit live. `0` turns it off. |
153
- | `collaboration.tokenTtlSeconds` | integer | `60` | Lifetime of the one-time token that opens the socket. |
154
- | `history.maxSnapshotsPerField` | integer | `50` | Versions kept per field and locale; older ones are deleted. |
135
+ | Key | Type | Default | Effect |
136
+ | --------------------------------------- | ---------------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
137
+ | `debug` | boolean | `false` | Writes debug log lines (never content or personal data). |
138
+ | `rawHtml` | `'sanitize'` \| `'allow'` \| `'disable'` | `'sanitize'` | Raw HTML block on save: `sanitize` removes scripts, event handlers, iframes and unsafe URLs; `allow` stores the HTML as typed; `disable` empties it. |
139
+ | `sanitizeOnSave` | boolean | `true` | Normalise and sanitise Magic Editor X values on every Document Service write. Turning this off is not recommended. |
140
+ | `encryptionKey` | string (32+ characters) | unset | Key for the stored AI provider key. Prefer the `MAGIC_EDITOR_X_ENCRYPTION_KEY` environment variable. |
141
+ | `uploads.maxImageBytes` | integer | `10485760` (10 MiB) | Largest image accepted by file or URL (hard cap 500 MiB). |
142
+ | `uploads.maxFileBytes` | integer | `20971520` (20 MiB) | Largest attachment. |
143
+ | `linkPreview.enabled` | boolean | `true` | Link preview cards. When `false`, `GET /magic-editor-x/link` answers 404. |
144
+ | `linkPreview.timeoutMs` | integer | `8000` | Time limit for fetching a page (1000 to 30000). |
145
+ | `api.autoParseJSON` | boolean | `true` | Turn 1.x JSON strings into objects in Content API GET responses. |
146
+ | `ai.allowPrivateBaseUrl` | boolean | `false` | Allow AI base URLs on loopback or private networks (for local models). Owner decision; not editable in the admin. |
147
+ | `ai.apiKey` | string | unset | Provider key from the environment. When set it wins over a key stored in the settings. |
148
+ | `ai.requestsPerMinute` | integer | `20` | AI requests per admin per minute, counted per process. |
149
+ | `ai.timeoutMs` | integer | `60000` | Time limit for one provider request. |
150
+ | `collaboration.enabled` | boolean | `true` | Live collaboration and its Socket.IO server. |
151
+ | `collaboration.path` | string | `'/magic-editor-x/realtime'` | Socket.IO path on the Strapi HTTP server. |
152
+ | `collaboration.allowedOrigins` | string[] | `[]` | Extra browser origins allowed to open the socket. The admin URL and the server URL are always allowed. |
153
+ | `collaboration.pollIntervalMs` | integer | `400` | How often each process reads updates written by other processes (50 to 10000). |
154
+ | `collaboration.roomTtlMinutes` | integer | `30` | Keep a room's live state this long after the last person left. |
155
+ | `collaboration.maxMessageBytes` | integer | `2097152` (2 MiB) | Largest accepted socket message. |
156
+ | `collaboration.snapshotIntervalMinutes` | integer | `10` | Automatic version while people edit live. `0` turns it off. |
157
+ | `collaboration.tokenTtlSeconds` | integer | `60` | Lifetime of the one-time token that opens the socket. |
158
+ | `collaboration.maxConnectionsPerAdmin` | integer | `20` | Open live sockets per admin across all processes. |
159
+ | `collaboration.maxRoomsPerAdmin` | integer | `20` | Different fields one admin may have open live at the same time, across all processes. |
160
+ | `collaboration.revalidateSeconds` | integer | `60` | Full permission re-check of open sockets. Role, permission and user changes are applied within about a second anyway. |
161
+ | `collaboration.rateLimit` | object | `{ sessionsPerMinute: 60, updatesPer10s: 300, bytesPer10s: 8388608 }` | Session tokens per admin and minute (shared by all processes), updates and update bytes per socket in 10 seconds. |
162
+ | `history.maxSnapshotsPerField` | integer | `50` | Versions kept per field and locale; older ones are deleted. |
163
+ | `links.urlPattern` | string | `''` | `href` of internal links, for example `'/{locale}/{collection}/{slug}'` or `'https://www.example.com/{collection}/{documentId}'`. Placeholders: `{documentId}`, `{locale}`, `{slug}`, `{collection}`, `{singular}`. Empty means `'/{collection}/{documentId}'`. See [Internal links](#internal-links). |
155
164
 
156
165
  The validator rejects wrong types and ranges at startup and names the key, never the value. Keys from 1.x that no longer exist are ignored with a warning; see [Migrating from 1.x](#migrating-from-1x).
157
166
 
@@ -181,12 +190,22 @@ Settings > Magic Editor X > Configuration stores these values in the Strapi stor
181
190
 
182
191
  When a document has been saved once, the editor joins the room of its field. Everyone with Content Manager read access to that document, locale and field and the `collaborate` action can join; people with update access can type, others watch as viewers.
183
192
 
184
- - Edits merge at character level when two people type in the same text field of a block, and per block otherwise. Every client and server converge on the same document (Yjs CRDT).
185
- - Presence avatars show who is in the room; the badge shows the connection state (Connecting, Syncing, Live, Reconnecting).
186
- - Changes made by others become part of your form. Save the entry as usual to store them.
187
- - Text typed during a short network or server interruption is kept and sent after the reconnect.
193
+ How it works:
194
+
195
+ - **Conflict-free structure.** The field is shared as a Yjs document in which every block has a stable id and every part of its data has its own shared type: texts merge character by character, and every table cell, list item, checklist entry, tune (alignment, text variant, indent) and custom block field is merged separately. Two people can edit different cells of one table, different items of one list, or the text and the alignment of one paragraph at the same time and both changes are kept. When two people change the same number, switch or option at the same moment, one value wins on every screen. The stored Editor.js JSON does not change.
196
+ - **Presence.** Avatars with first name and last initial (never e-mail addresses), coloured carets and selections of the others in the text, a coloured marker at the block someone is editing and an "away" state after a minute without activity or when the tab is hidden. Joins and leaves are announced politely to screen readers. Colours follow the light and dark theme; the caret does not blink when reduced motion is requested.
197
+ - **Connection state** in the toolbar: Connecting, Syncing, Live, Reconnecting, Offline, View only, or Live editing unavailable.
198
+ - **Offline and reconnects.** You can keep typing while the connection is gone. Unsent changes are kept, sent again after the reconnect and merged with what others did meanwhile, without duplicates. Reconnects use exponential backoff with jitter and a new one-time token; waking a laptop or returning to a tab reconnects at once. Closing the tab leaves the room immediately.
199
+ - **Undo and redo** (toolbar, Cmd/Ctrl+Z, Shift+Cmd/Ctrl+Z) only revert your own changes, never what others typed (the last 200 steps).
200
+ - **Saving.** Changes made by others become part of your form. Save, publish and discard work as usual. Version history restores into the live room, so everyone sees the restored content. Each locale has its own room.
201
+ - **Permissions** are checked when you join, re-checked within about a second when roles, permissions or users change (on every process), and every `collaboration.revalidateSeconds`. An admin who loses update access becomes a viewer; one who loses read access is disconnected.
202
+ - **Nothing typed is lost.** Edits are stored in the database before they are confirmed. When a room is cleaned up `collaboration.roomTtlMinutes` after the last person left and contains edits nobody saved, a version is created first, so they can be restored from the history.
203
+
204
+ Limits:
205
+
188
206
  - A new entry that has not been saved yet has no room.
189
- - Access is checked again every five minutes; an admin who loses access is disconnected.
207
+ - Text formatting (bold, links, …) is part of the text; two people formatting the same word at the same moment can produce nested tags, which the sanitiser keeps valid.
208
+ - Up to 5000 blocks per field (the stored-content limit); rooms above 64 MiB of history refuse further edits until they are compacted.
190
209
 
191
210
  ## Running several instances
192
211
 
@@ -198,9 +217,11 @@ How it works:
198
217
  - The session token is signed with a key derived from `admin.auth.secret`, so any process can accept a token issued by another one. All processes must use the same `ADMIN_JWT_SECRET`.
199
218
  - Every update is written to the table `magic_editor_x_collab_updates` before it is acknowledged. Other processes read new rows every `collaboration.pollIntervalMs` and send them to their own sockets.
200
219
  - Presence is stored in `magic_editor_x_collab_presence` with heartbeats; leases and one-time keys in `magic_editor_x_locks`. Seeding a room, compaction, automatic versions and cleanup each run once across all processes.
201
- - Clients resynchronise their state every 20 seconds and after each reconnect, so a process restart loses nothing that was acknowledged.
220
+ - Every process keeps the active rooms in memory, checks every update before it is stored (only the structures the editor uses, every dependency present, every touched block valid within the content limits) and relays it.
221
+ - Clients resynchronise their state every 20 seconds and after each reconnect, so a process restart or deploy loses nothing that was acknowledged.
222
+ - Permission changes set a signal in `magic_editor_x_locks` that every process checks every second. Session and AI rate limits are counted in `magic_editor_x_counters`, so they apply to the whole cluster.
202
223
 
203
- The plugin creates these three tables on startup. They are not content types, so Strapi's schema sync leaves them alone.
224
+ The plugin creates these four tables on startup. They are not content types, so Strapi's schema sync leaves them alone.
204
225
 
205
226
  Behind a proxy, also set `server.proxy` in `config/server` (`koa: true` and the number of trusted hops in `maxIpsCount`) so Strapi sees the real client address.
206
227
 
@@ -219,7 +240,7 @@ The assistant is off until an administrator turns it on in Settings > Magic Edit
219
240
  - The key stays on the server. It is encrypted at rest with `MAGIC_EDITOR_X_ENCRYPTION_KEY` or read from `ai.apiKey`, and it is never sent to the browser or written to logs.
220
241
  - The selected text (with its inline formatting) and a fixed instruction are sent to the provider. Nothing else from the document is sent. The text is never logged.
221
242
  - Base URLs must be public https URLs. Loopback and private hosts are allowed only with `ai.allowPrivateBaseUrl: true` in `config/plugins`. Redirects are not followed.
222
- - Input is limited by "Max input characters", output by "Max output tokens". Each admin can send `ai.requestsPerMinute` requests per minute per process.
243
+ - Input is limited by "Max input characters", output by "Max output tokens". Each admin can send `ai.requestsPerMinute` requests per minute; the counter is shared by all processes.
223
244
  - The answer is sanitised to the inline tags the editor uses before it reaches the browser. The admin reviews the suggestion and chooses Replace selection; nothing changes before that.
224
245
 
225
246
  ## Data format
@@ -269,7 +290,24 @@ Data of each block type as stored after sanitising (`shared/sanitize-policy.mjs`
269
290
  | custom simple block | `{ content, <field values>, blockType: 'simple', blockName }` |
270
291
  | custom embedded-entry block | `{ entry: { id, documentId, title, <display fields> }, contentType, displayMode }` |
271
292
 
272
- Inline HTML may contain `b`, `strong`, `i`, `em`, `u`, `s`, `mark`, `code`, `a` (`href`, `target`, `rel`, `title`), `br`, `span` (class `cdx-tooltip` with `data-tooltip`), `sub` and `sup`. Links allow `http`, `https`, `mailto`, `tel` and relative URLs. Escape plain-text fields (`code`, `personality`, `button.text`, link card text) when you render them.
293
+ Inline HTML may contain `b`, `strong`, `i`, `em`, `u`, `s`, `mark`, `code`, `a` (`href`, `target`, `rel`, `title`, and for internal links `data-mex-uid`, `data-mex-document-id`, `data-mex-locale`), `br`, `span` (class `cdx-tooltip` with `data-tooltip`), `sub` and `sup`. Links allow `http`, `https`, `mailto`, `tel` and relative URLs. Escape plain-text fields (`code`, `personality`, `button.text`, link card text) when you render them.
294
+
295
+ ### Internal links
296
+
297
+ The link tool (`CMD+K`) has a **Link to an entry** button: choose a content type, search by title (arrow keys move through the results, Enter picks, Escape closes) and the selected text becomes a link to that entry. The picker lists only the content types and entries you can read in the Content Manager, with its conditions and field permissions. The link is stored as plain HTML:
298
+
299
+ ```html
300
+ <a
301
+ href="/articles/x7k2m9q4p1v8"
302
+ data-mex-uid="api::article.article"
303
+ data-mex-document-id="x7k2m9q4p1v8"
304
+ data-mex-locale="en"
305
+ >our guide</a
306
+ >
307
+ ```
308
+
309
+ - `href` is always a normal URL, so every frontend can render the link as it is. It is built on the server from `links.urlPattern` when the link is inserted: `{documentId}`, `{locale}` (empty for types without i18n; empty path segments are removed), `{slug}` (the first `uid` attribute of the type, or the documentId when there is none), `{collection}` (plural API name) and `{singular}` (singular API name). Values are URL-encoded. The pattern must be a site-relative path or an `http(s)` URL with a fixed host. Without a pattern the link is `/{collection}/{documentId}`.
310
+ - `data-mex-uid`, `data-mex-document-id` and `data-mex-locale` identify the entry, so a frontend can resolve the current URL itself (for example when a slug changed after the link was inserted). They are kept only when they are valid and only on `<a>`; a link whose address you edit by hand becomes a normal link.
273
311
 
274
312
  Tunes are stored per block in `tunes`: `alignmentTune: { alignment }`, `textVariant: '' | 'call-out' | 'citation' | 'details'`, `indentTune: { indentLevel }`.
275
313
 
@@ -279,14 +317,14 @@ The Content API returns the object as stored. Entries saved with 1.x may still c
279
317
 
280
318
  ### Permissions
281
319
 
282
- | Action | Label in Roles | Gates |
283
- | --------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
284
- | `plugin::magic-editor-x.access` | Use the editor (uploads, link previews, custom blocks, version history) | Editor configuration, link previews, uploads (with the Media Library permission), content type list, custom block list, version history, collaboration and AI routes |
285
- | `plugin::magic-editor-x.collaborate` | Edit together in real time | Joining live rooms |
286
- | `plugin::magic-editor-x.ai.use` | Use the AI assistant | AI requests |
287
- | `plugin::magic-editor-x.custom-blocks.manage` | Manage custom blocks | Settings > Custom blocks and its routes |
288
- | `plugin::magic-editor-x.settings.read` | Read settings | Settings > Configuration (read) |
289
- | `plugin::magic-editor-x.settings.update` | Update settings | Saving settings, testing the AI connection |
320
+ | Action | Label in Roles | Gates |
321
+ | --------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
322
+ | `plugin::magic-editor-x.access` | Use the editor (uploads, link previews, custom blocks, version history) | Editor configuration, link previews, uploads (with the Media Library permission), content type list, internal-link search, custom block list, version history, collaboration and AI routes |
323
+ | `plugin::magic-editor-x.collaborate` | Edit together in real time | Joining live rooms |
324
+ | `plugin::magic-editor-x.ai.use` | Use the AI assistant | AI requests |
325
+ | `plugin::magic-editor-x.custom-blocks.manage` | Manage custom blocks | Settings > Custom blocks and its routes |
326
+ | `plugin::magic-editor-x.settings.read` | Read settings | Settings > Configuration (read) |
327
+ | `plugin::magic-editor-x.settings.update` | Update settings | Saving settings, testing the AI connection |
290
328
 
291
329
  Uploads also need the Media Library action `plugin::upload.assets.create`. Version history and collaboration also apply the Content Manager permissions of the document: read access (including conditions such as "is creator", locale and field permissions) to list versions and join a room, update access to save versions, restore and type. A document you cannot read answers 404, the same as a document that does not exist.
292
330
 
@@ -296,30 +334,32 @@ Super Admins have all actions. The `access` action keeps its 1.x id, so roles th
296
334
 
297
335
  All routes are admin routes served at `/magic-editor-x/...` and need an admin session (`Authorization: Bearer <admin JWT>`). There are no Content API routes. Errors use the Strapi envelope `{ "data": null, "error": { "status", "name", "message", "details" } }`; validation errors carry `details.fieldErrors` keyed by field path. Editor.js tool routes answer `{ "success": 0, "message" }` on errors, as the tools expect.
298
336
 
299
- | Method | Path | Actions | Body / query | Response |
300
- | ------ | --------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
301
- | GET | `/magic-editor-x/config` | access | | `{ data: { collaboration, ai, uploads, linkPreview, rawHtml, permissions } }` |
302
- | GET | `/magic-editor-x/link` | access | `?url=` | `{ success: 1, link, meta }` |
303
- | POST | `/magic-editor-x/image/byFile` | access, upload | multipart `image` | `{ success: 1, file: { url, ... } }` |
304
- | POST | `/magic-editor-x/image/byUrl` | access, upload | `{ url }` | `{ success: 1, file }` |
305
- | POST | `/magic-editor-x/file/upload` | access, upload | multipart `file` | `{ success: 1, file: { url, name, title, size, extension } }` |
306
- | GET | `/magic-editor-x/content-types` | access | | `{ data: [{ uid, kind, displayName, attributes }] }` (types you can read) |
307
- | GET | `/magic-editor-x/custom-blocks` | access (`?all=true` also needs custom-blocks.manage) | `?all=true` | `{ data: [block] }` |
308
- | GET | `/magic-editor-x/custom-blocks/export` | custom-blocks.manage | | `{ data: { format: 'magic-editor-x/custom-blocks', version: 2, exportedAt, blocks } }` |
309
- | POST | `/magic-editor-x/custom-blocks/import` | custom-blocks.manage | export document | `{ data: { created: [name], skipped: [{ name, reason }] } }` |
310
- | PUT | `/magic-editor-x/custom-blocks/order` | custom-blocks.manage | `{ ids }` (every block once) | `{ data: [block] }` |
311
- | POST | `/magic-editor-x/custom-blocks` | custom-blocks.manage | block definition | 201 `{ data: block }` |
312
- | PUT | `/magic-editor-x/custom-blocks/:id` | custom-blocks.manage | full block definition | `{ data: block }` |
313
- | DELETE | `/magic-editor-x/custom-blocks/:id` | custom-blocks.manage | | `{ data: { id } }` |
314
- | POST | `/magic-editor-x/custom-blocks/:id/duplicate` | custom-blocks.manage | | 201 `{ data: block }` |
315
- | POST | `/magic-editor-x/collaboration/session` | access, collaborate | `{ uid, documentId, locale?, field, initialValue? }` | `{ data: { token, path, canEdit, expiresAt } }` |
316
- | GET | `/magic-editor-x/history` | access | `?uid&documentId&locale&field` | `{ data: [version], meta: { canRestore, canCreate } }` |
317
- | GET | `/magic-editor-x/history/:id` | access | | `{ data: { ...version, content } }` |
318
- | POST | `/magic-editor-x/history` | access | `{ uid, documentId, locale?, field, content }` | 201 new version, 200 with `meta.created: false` when unchanged |
319
- | POST | `/magic-editor-x/ai/:action` | access, ai.use | `{ text, language?, tone? }` | `{ data: { text } }` |
320
- | GET | `/magic-editor-x/settings` | settings.read | | `{ data: { ai, environment } }` (no secrets) |
321
- | PUT | `/magic-editor-x/settings` | settings.read, settings.update | `{ ai: { enabled, provider, baseUrl, model, maxInputChars, maxOutputTokens, apiKey? } }` | `{ data: { ai, environment } }` |
322
- | POST | `/magic-editor-x/settings/ai/test` | settings.read, settings.update | `{ ai: {...} }` | `{ data: { ok: true } }` |
337
+ | Method | Path | Actions | Body / query | Response |
338
+ | ------ | --------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
339
+ | GET | `/magic-editor-x/config` | access | | `{ data: { collaboration, ai, uploads, linkPreview, rawHtml, permissions } }` |
340
+ | GET | `/magic-editor-x/link` | access | `?url=` | `{ success: 1, link, meta }` |
341
+ | POST | `/magic-editor-x/image/byFile` | access, upload | multipart `image` | `{ success: 1, file: { url, ... } }` |
342
+ | POST | `/magic-editor-x/image/byUrl` | access, upload | `{ url }` | `{ success: 1, file }` |
343
+ | POST | `/magic-editor-x/file/upload` | access, upload | multipart `file` | `{ success: 1, file: { url, name, title, size, extension } }` |
344
+ | GET | `/magic-editor-x/content-types` | access | | `{ data: [{ uid, kind, displayName, attributes }] }` (types you can read) |
345
+ | GET | `/magic-editor-x/links/types` | access | | `{ data: [{ uid, kind, displayName, localized }] }` (API types you can read) |
346
+ | GET | `/magic-editor-x/links/search` | access (+ Content Manager read) | `?uid=api::x.y&q=&locale=&page=` (`q` up to 100 characters) | `{ data: [{ documentId, uid, locale, title, href, status? }], meta: { pagination } }` (up to 20 readable entries; unknown or unreadable type 404) |
347
+ | GET | `/magic-editor-x/custom-blocks` | access (`?all=true` also needs custom-blocks.manage) | `?all=true` | `{ data: [block] }` |
348
+ | GET | `/magic-editor-x/custom-blocks/export` | custom-blocks.manage | | `{ data: { format: 'magic-editor-x/custom-blocks', version: 2, exportedAt, blocks } }` |
349
+ | POST | `/magic-editor-x/custom-blocks/import` | custom-blocks.manage | export document | `{ data: { created: [name], skipped: [{ name, reason }] } }` |
350
+ | PUT | `/magic-editor-x/custom-blocks/order` | custom-blocks.manage | `{ ids }` (every block once) | `{ data: [block] }` |
351
+ | POST | `/magic-editor-x/custom-blocks` | custom-blocks.manage | block definition | 201 `{ data: block }` |
352
+ | PUT | `/magic-editor-x/custom-blocks/:id` | custom-blocks.manage | full block definition | `{ data: block }` |
353
+ | DELETE | `/magic-editor-x/custom-blocks/:id` | custom-blocks.manage | | `{ data: { id } }` |
354
+ | POST | `/magic-editor-x/custom-blocks/:id/duplicate` | custom-blocks.manage | | 201 `{ data: block }` |
355
+ | POST | `/magic-editor-x/collaboration/session` | access, collaborate | `{ uid, documentId, locale?, field, initialValue? }` | `{ data: { token, path, canEdit, expiresAt } }` |
356
+ | GET | `/magic-editor-x/history` | access | `?uid&documentId&locale&field` | `{ data: [version], meta: { canRestore, canCreate } }` |
357
+ | GET | `/magic-editor-x/history/:id` | access | | `{ data: { ...version, content } }` |
358
+ | POST | `/magic-editor-x/history` | access | `{ uid, documentId, locale?, field, content }` | 201 new version, 200 with `meta.created: false` when unchanged |
359
+ | POST | `/magic-editor-x/ai/:action` | access, ai.use | `{ text, language?, tone? }` | `{ data: { text } }` |
360
+ | GET | `/magic-editor-x/settings` | settings.read | | `{ data: { ai, environment } }` (no secrets) |
361
+ | PUT | `/magic-editor-x/settings` | settings.read, settings.update | `{ ai: { enabled, provider, baseUrl, model, maxInputChars, maxOutputTokens, apiKey? } }` | `{ data: { ai, environment } }` |
362
+ | POST | `/magic-editor-x/settings/ai/test` | settings.read, settings.update | `{ ai: {...} }` | `{ data: { ok: true } }` |
323
363
 
324
364
  `upload` means `plugin::upload.assets.create`. AI actions: `improve`, `grammar`, `shorten`, `expand`, `summarize`, `simplify`, `translate` (with `language`), `tone` (with `tone`), `continue`. Provider problems answer with `name: 'AIProviderError'` and `details.code` (`DISABLED`, `NOT_CONFIGURED`, `NO_API_KEY`, `AUTH_FAILED`, `PROVIDER_RATE_LIMIT`, `TIMEOUT`, `REFUSED`, `PROVIDER_ERROR`). Too long text answers 413, too many requests 429.
325
365
 
@@ -354,14 +394,59 @@ Content-Type: application/json
354
394
  - **Stored content:** every Magic Editor X value is normalised and sanitised on save by a Document Service middleware (Content Manager, Content API, imports and code). Unknown keys of known block types are dropped, URLs are checked, inline HTML is limited to the tags above and the raw HTML block follows `rawHtml`. Values over 5 MiB, with more than 5000 blocks or nested deeper than 24 levels are rejected with 400, never truncated. The admin sanitises again before rendering (DOMPurify with the same rules).
355
395
  - **Outgoing requests:** link previews and images by URL only fetch public http(s) addresses: the host is resolved once, every address must be public, the connection is pinned to that address, redirects are re-checked (at most 3), and size, type and time are limited. The AI provider is called only when an administrator configured it.
356
396
  - **Uploads** are checked by their first bytes (not by the file name or the browser's MIME type) and stored through the Media Library with the admin as creator.
357
- - **Collaboration:** tokens are signed, expire after `collaboration.tokenTtlSeconds` and work once; the socket accepts the admin and server origins and `collaboration.allowedOrigins`; messages are size-limited and must be valid Yjs updates; viewers cannot write.
397
+ - **Collaboration:** tokens are signed, bound to admin, document, locale and field, expire after `collaboration.tokenTtlSeconds` and work once on any process; the socket accepts the admin and server origins and `collaboration.allowedOrigins` and only clients of the current protocol; every update is checked (allowed structures only, no prototype keys, dependencies present, touched blocks valid) before it is stored or relayed, and a socket that keeps sending invalid updates is closed; names and colours of other people come from the server, never from a client; remote content is sanitised before the editor renders it; updates, sessions, sockets and rooms per admin are rate limited; viewers cannot write. See [docs/security-audit-2.1.md](./docs/security-audit-2.1.md).
358
398
  - **Secrets:** the AI key is encrypted with AES-256-GCM (random IV, versioned format) and never returned. Changing the provider or base URL requires entering the key again, so a stored key cannot be sent to another host.
359
399
  - **Logs** contain operation names and error codes only, never content, URLs with queries, tokens, user ids or email addresses.
360
400
  - **Stored data:** custom block definitions, versions (field content and the admin who saved it), live rooms (Yjs updates, removed `collaboration.roomTtlMinutes` after the last person left) and presence rows (admin display name, colour, caret position; removed when the socket closes or after missed heartbeats).
361
- - **Content Security Policy:** Editor.js and the Design System add inline styles, which Strapi's default `style-src 'unsafe-inline'` allows. The socket connects to the same origin as the admin, which `connect-src 'self'` covers; add the `wss:` origin only when the admin runs on another host. Embed iframes need `frame-src` only on your frontend.
401
+ - **Content Security Policy:** Editor.js and the Design System add inline styles, which Strapi's default `style-src 'unsafe-inline'` allows. The socket connects to the same origin as the admin, which `connect-src 'self'` covers; add the `wss:` origin only when the admin runs on another host. Embeds and external images in the editor preview need `frame-src` and `img-src` sources; see [Content Security Policy](#content-security-policy) below.
362
402
 
363
403
  Report vulnerabilities privately through GitHub security advisories on the repository.
364
404
 
405
+ ### Content Security Policy
406
+
407
+ Strapi's default admin CSP (`strapi::security`) has no `frame-src`, so embed iframes fall back to `default-src 'self'`, and its `img-src` allows only `'self'`, `data:`, `blob:` and `market-assets.strapi.io`. YouTube, Vimeo and the other embeds, and images from other hosts (for example link preview images), are therefore blocked in the editor preview. The stored content is not affected and your frontend has its own CSP.
408
+
409
+ The plugin never changes the CSP. Instead:
410
+
411
+ - **Settings > Magic Editor X > Configuration** shows a "Content Security Policy" notice when sources are missing: what is blocked and the exact `config/middlewares.js` snippet, with a copy button. The server reads the effective `strapi::security` configuration once at startup (string and object entries, `useDefaults`, `frame-src`, `child-src`, `default-src`, `img-src`) and returns it in `GET /magic-editor-x/settings` as `data.environment.csp` (`{ active, frameSrcMissing, imgSrcMissing, snippet }`). Only CSP sources are returned; browsers receive them in every response header anyway.
412
+ - **In the editor**, a blocked embed or image is replaced by a placeholder inside the block ("This embed is blocked by your Content Security Policy.") with a link to the settings page for admins who can read the settings. The block data is saved unchanged.
413
+
414
+ The snippet for Strapi's defaults (merge it into your existing `strapi::security` entry and keep your other directives, for example the hosts of your upload provider; Strapi merges arrays with its defaults by position):
415
+
416
+ ```js
417
+ // config/middlewares.js
418
+ module.exports = [
419
+ // ...other middlewares
420
+ {
421
+ name: 'strapi::security',
422
+ config: {
423
+ contentSecurityPolicy: {
424
+ useDefaults: true,
425
+ directives: {
426
+ 'frame-src': [
427
+ "'self'",
428
+ 'https://www.youtube.com',
429
+ 'https://player.vimeo.com',
430
+ 'https://platform.twitter.com',
431
+ 'https://www.instagram.com',
432
+ 'https://codepen.io',
433
+ 'https://imgur.com',
434
+ 'https://assets.pinterest.com',
435
+ 'https://miro.com',
436
+ 'https://www.figma.com',
437
+ 'https://www.facebook.com',
438
+ ],
439
+ 'img-src': ["'self'", 'data:', 'blob:', 'https://market-assets.strapi.io', 'https:'],
440
+ },
441
+ },
442
+ },
443
+ },
444
+ // ...other middlewares
445
+ ];
446
+ ```
447
+
448
+ Add only the services you use. Instead of `https:` in `img-src` you can list your image hosts; the notice then counts external images as allowed. GitHub gist embeds load a `data:` iframe that inherits the admin CSP and needs a remote script, so they stay blocked under a strict policy, and Imgur's embed URL uses `http:`, which an `https` admin blocks as mixed content.
449
+
365
450
  ## Troubleshooting
366
451
 
367
452
  | Symptom | Cause | Fix |
@@ -371,6 +456,7 @@ Report vulnerabilities privately through GitHub security advisories on the repos
371
456
  | No version history (clock) button | The entry was never saved | Save the entry once. |
372
457
  | Badge shows "Live editing unavailable" | No `collaborate` action, no read access to the document, or `collaboration.enabled: false` | Grant the action or check the Content Manager permissions. |
373
458
  | Badge stays at "Connecting" or "Reconnecting" | The proxy does not forward WebSocket upgrades on `collaboration.path`, or the origin is not allowed | Allow upgrades on the path; add the admin origin to `collaboration.allowedOrigins` when the admin runs on another host. |
459
+ | "Reload the page to keep editing live" | The browser still runs the admin of an older version after an update | Reload the page. |
374
460
  | Settings say the API key cannot be stored | `MAGIC_EDITOR_X_ENCRYPTION_KEY` is missing or shorter than 32 characters | Set the variable and restart, or use `ai.apiKey`. |
375
461
  | Settings say the stored key is unreadable | The encryption key changed | Enter the provider key again. |
376
462
  | AI error "The AI provider rejected the key." | Wrong key for this provider | Enter the key again and use Test connection. |
@@ -1,12 +1,12 @@
1
1
  import { jsx, jsxs } from "react/jsx-runtime";
2
- import { Box, Flex, Typography, Switch, Grid, Field, SingleSelect, SingleSelectOption, TextInput, TextButton, NumberInput, Button, Badge, Alert } from "@strapi/design-system";
3
- import { useForm, useFetchClient, useNotification, useRBAC, Page, Form, Blocker } from "@strapi/strapi/admin";
4
- import { Check } from "@strapi/icons";
5
- import { P as PERMISSIONS } from "./index-D1Q5Rlt6.mjs";
6
- import { u as useT, S as SectionCard, P as PageShell, C as ConfirmAction } from "./useT-CjX6fL2m.mjs";
2
+ import { Box, Flex, Typography, Switch, Grid, Field, SingleSelect, SingleSelectOption, TextInput, TextButton, NumberInput, Button, Badge, Alert, IconButton } from "@strapi/design-system";
3
+ import { useForm, useFetchClient, useClipboard, useNotification, useRBAC, Page, Form, Blocker } from "@strapi/strapi/admin";
4
+ import { Duplicate, Check } from "@strapi/icons";
5
+ import { P as PERMISSIONS } from "./index-0_b1iroK.mjs";
6
+ import { u as useT, S as SectionCard, P as PageShell, C as ConfirmAction } from "./useT-vgY88N_H.mjs";
7
7
  import { useEffect, useState, useRef, useCallback, useMemo } from "react";
8
- import "styled-components";
9
- import { A as API, r as readApiError } from "./api-C4XsDZxd.mjs";
8
+ import styled from "styled-components";
9
+ import { A as API, r as readApiError } from "./api-D5CAH0nh.mjs";
10
10
  import { useIntl } from "react-intl";
11
11
  const DraftSync = ({ values }) => {
12
12
  const setValues = useForm("MagicEditorXDraftSync", (state) => state.setValues);
@@ -611,6 +611,124 @@ const EnvironmentSection = ({ environment }) => {
611
611
  }
612
612
  );
613
613
  };
614
+ const CodeBlock = styled.pre`
615
+ margin: 0;
616
+ max-width: 100%;
617
+ overflow-x: auto;
618
+ padding: ${({ theme }) => theme.spaces[4]};
619
+ border: 1px solid ${({ theme }) => theme.colors.neutral200};
620
+ border-radius: ${({ theme }) => theme.borderRadius};
621
+ background: ${({ theme }) => theme.colors.neutral100};
622
+ color: ${({ theme }) => theme.colors.neutral800};
623
+ font-family: 'SF Mono', SFMono-Regular, ui-monospace, Menlo, Consolas, monospace;
624
+ font-size: ${({ theme }) => theme.fontSizes[1]};
625
+ line-height: 1.6;
626
+ white-space: pre;
627
+
628
+ &:focus-visible {
629
+ outline: 2px solid ${({ theme }) => theme.colors.primary600};
630
+ outline-offset: 2px;
631
+ }
632
+ `;
633
+ const selectText = (node) => {
634
+ if (!node || typeof window.getSelection !== "function") return;
635
+ const range = document.createRange();
636
+ range.selectNodeContents(node);
637
+ const selection = window.getSelection();
638
+ selection.removeAllRanges();
639
+ selection.addRange(range);
640
+ node.focus();
641
+ };
642
+ const CspSection = ({ csp }) => {
643
+ const t = useT();
644
+ const { copy } = useClipboard();
645
+ const { toggleNotification } = useNotification();
646
+ const codeRef = useRef(null);
647
+ const [alertOpen, setAlertOpen] = useState(true);
648
+ const frameMissing = csp && Array.isArray(csp.frameSrcMissing) && csp.frameSrcMissing || [];
649
+ const imgMissing = Boolean(csp && csp.imgSrcMissing);
650
+ if (!csp || !csp.active || !csp.snippet || !frameMissing.length && !imgMissing) return null;
651
+ const onCopy = async () => {
652
+ const ok = await copy(csp.snippet);
653
+ if (ok) {
654
+ toggleNotification({
655
+ type: "success",
656
+ message: t("settings.csp.copied", "Snippet copied to the clipboard.")
657
+ });
658
+ } else {
659
+ selectText(codeRef.current);
660
+ toggleNotification({
661
+ type: "warning",
662
+ message: t(
663
+ "settings.csp.copyFailed",
664
+ "The browser did not allow copying. The snippet is selected; copy it with Ctrl+C or Cmd+C."
665
+ )
666
+ });
667
+ }
668
+ };
669
+ const allowed = t("settings.csp.allowed", "Allowed");
670
+ const codeLabel = t("settings.csp.codeLabel", "Snippet for config/middlewares.js");
671
+ return /* @__PURE__ */ jsxs(
672
+ SectionCard,
673
+ {
674
+ title: t("settings.csp.title", "Content Security Policy"),
675
+ subtitle: t(
676
+ "settings.csp.subtitle",
677
+ "The admin Content Security Policy is set in config/middlewares.js. The plugin never changes it."
678
+ ),
679
+ children: [
680
+ alertOpen ? /* @__PURE__ */ jsx(
681
+ Alert,
682
+ {
683
+ variant: "warning",
684
+ closeLabel: t("settings.close", "Close"),
685
+ onClose: () => setAlertOpen(false),
686
+ title: t("settings.csp.alertTitle", "Some editor previews are blocked"),
687
+ children: t(
688
+ "settings.csp.alertBody",
689
+ "Your Content Security Policy blocks content the editor shows. Stored content is not affected; editors see a placeholder instead. To allow it, add the sources below to the strapi::security middleware and restart Strapi."
690
+ )
691
+ }
692
+ ) : null,
693
+ /* @__PURE__ */ jsx(
694
+ PropertyList,
695
+ {
696
+ items: [
697
+ {
698
+ key: "frame",
699
+ label: t("settings.csp.frames", "Embeds (frame-src)"),
700
+ value: frameMissing.length ? t("settings.csp.framesBlocked", "Blocked: {sources}", { sources: frameMissing.join(", ") }) : allowed
701
+ },
702
+ {
703
+ key: "img",
704
+ label: t("settings.csp.images", "External images (img-src)"),
705
+ value: imgMissing ? t(
706
+ "settings.csp.imagesBlocked",
707
+ "Blocked: images from other hosts (for example link previews)"
708
+ ) : allowed,
709
+ hint: imgMissing ? t(
710
+ "settings.csp.imagesHint",
711
+ "The snippet adds https:. You can list your image hosts instead."
712
+ ) : void 0
713
+ }
714
+ ]
715
+ }
716
+ ),
717
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, minWidth: 0, children: [
718
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 2, wrap: "wrap", children: [
719
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", id: "mex-csp-snippet-label", children: codeLabel }),
720
+ /* @__PURE__ */ jsx(IconButton, { label: t("settings.csp.copy", "Copy the snippet"), variant: "tertiary", onClick: onCopy, children: /* @__PURE__ */ jsx(Duplicate, {}) })
721
+ ] }),
722
+ /* @__PURE__ */ jsx(Box, { minWidth: 0, children: /* @__PURE__ */ jsx(CodeBlock, { ref: codeRef, tabIndex: 0, "aria-labelledby": "mex-csp-snippet-label", children: /* @__PURE__ */ jsx("code", { children: csp.snippet }) }) }),
723
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(
724
+ "settings.csp.mergeHint",
725
+ "Keep your other directives (for example the hosts of your upload provider) and restart Strapi after the change."
726
+ ) })
727
+ ] })
728
+ ]
729
+ }
730
+ );
731
+ };
614
732
  const RBAC = [...PERMISSIONS.settingsRead, ...PERMISSIONS.settingsUpdate];
615
733
  const testErrorText = (t, code) => {
616
734
  switch (code) {
@@ -753,6 +871,7 @@ const ConfigurationPage = () => {
753
871
  ) : null,
754
872
  /* @__PURE__ */ jsx(AiSection, { form, readOnly, onTest }),
755
873
  /* @__PURE__ */ jsx(EnvironmentSection, { environment: form.dto.environment }),
874
+ /* @__PURE__ */ jsx(CspSection, { csp: form.dto.environment && form.dto.environment.csp }),
756
875
  /* @__PURE__ */ jsxs(Form, { method: "PUT", initialValues: form.saved, children: [
757
876
  /* @__PURE__ */ jsx(DraftSync, { values: form.draft }),
758
877
  /* @__PURE__ */ jsx(Blocker, {})