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
@@ -42,7 +42,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
42
42
  var require_logger = __commonJS({
43
43
  "server/src/utils/logger.js"(exports, module) {
44
44
  "use strict";
45
- var PREFIX = "[magic-editor-x]";
45
+ var PREFIX2 = "[magic-editor-x]";
46
46
  var safeError = (error) => {
47
47
  if (!error || typeof error !== "object") return {};
48
48
  const out = {};
@@ -62,8 +62,8 @@ var require_logger = __commonJS({
62
62
  const write = (level, message, meta) => {
63
63
  const log = strapi?.log?.[level];
64
64
  if (typeof log !== "function") return;
65
- if (meta && Object.keys(meta).length > 0) log(`${PREFIX} ${message}`, meta);
66
- else log(`${PREFIX} ${message}`);
65
+ if (meta && Object.keys(meta).length > 0) log(`${PREFIX2} ${message}`, meta);
66
+ else log(`${PREFIX2} ${message}`);
67
67
  };
68
68
  return {
69
69
  debug: (message, meta) => debugEnabled() && write("debug", message, meta),
@@ -289,13 +289,15 @@ __export(sanitize_policy_exports, {
289
289
  INLINE_ATTRIBUTES: () => INLINE_ATTRIBUTES,
290
290
  INLINE_CLASSES: () => INLINE_CLASSES,
291
291
  INLINE_TAGS: () => INLINE_TAGS,
292
+ INTERNAL_LINK_ATTRIBUTES: () => INTERNAL_LINK_ATTRIBUTES,
292
293
  LINK_SCHEMES: () => LINK_SCHEMES,
294
+ cleanInternalLinkAttributes: () => cleanInternalLinkAttributes,
293
295
  sanitizeEditorData: () => sanitizeEditorData,
294
296
  sanitizeTarget: () => sanitizeTarget,
295
297
  sanitizeTunes: () => sanitizeTunes,
296
298
  sanitizeUrl: () => sanitizeUrl
297
299
  });
298
- var INLINE_TAGS, INLINE_ATTRIBUTES, INLINE_CLASSES, LINK_SCHEMES, MAX_URL_LENGTH, TARGETS, sanitizeUrl, plain, oneOf, int, bool, generic, listItems, BLOCK_POLICIES, sanitizeTunes, sanitizeEditorData, sanitizeTarget;
300
+ var INLINE_TAGS, INTERNAL_LINK_ATTRIBUTES, INTERNAL_LINK_RULES, cleanInternalLinkAttributes, INLINE_ATTRIBUTES, INLINE_CLASSES, LINK_SCHEMES, MAX_URL_LENGTH, TARGETS, sanitizeUrl, plain, oneOf, int, bool, generic, listItems, BLOCK_POLICIES, sanitizeTunes, sanitizeEditorData, sanitizeTarget;
299
301
  var init_sanitize_policy = __esm({
300
302
  "shared/sanitize-policy.mjs"() {
301
303
  init_editor_data();
@@ -314,8 +316,28 @@ var init_sanitize_policy = __esm({
314
316
  "sub",
315
317
  "sup"
316
318
  ]);
319
+ INTERNAL_LINK_ATTRIBUTES = Object.freeze([
320
+ "data-mex-uid",
321
+ "data-mex-document-id",
322
+ "data-mex-locale"
323
+ ]);
324
+ INTERNAL_LINK_RULES = Object.freeze({
325
+ "data-mex-uid": /^api::[a-z0-9-]{1,60}\.[a-z0-9-]{1,60}$/,
326
+ "data-mex-document-id": /^[a-z0-9]{1,64}$/,
327
+ "data-mex-locale": /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,3}$/
328
+ });
329
+ cleanInternalLinkAttributes = (attribs) => {
330
+ const out = {};
331
+ if (!attribs || typeof attribs !== "object") return out;
332
+ for (const name of INTERNAL_LINK_ATTRIBUTES) {
333
+ const value = attribs[name];
334
+ if (typeof value === "string" && INTERNAL_LINK_RULES[name].test(value)) out[name] = value;
335
+ }
336
+ if (!out["data-mex-uid"] || !out["data-mex-document-id"]) return {};
337
+ return out;
338
+ };
317
339
  INLINE_ATTRIBUTES = Object.freeze({
318
- a: ["href", "target", "rel", "title"],
340
+ a: ["href", "target", "rel", "title", ...INTERNAL_LINK_ATTRIBUTES],
319
341
  span: ["class", "data-tooltip"],
320
342
  mark: ["class"],
321
343
  u: ["class"],
@@ -580,7 +602,9 @@ var require_sanitizer = __commonJS({
580
602
  INLINE_CLASSES: INLINE_CLASSES2,
581
603
  LINK_SCHEMES: LINK_SCHEMES2,
582
604
  sanitizeEditorData: sanitizeEditorData2,
583
- sanitizeTarget: sanitizeTarget2
605
+ sanitizeTarget: sanitizeTarget2,
606
+ INTERNAL_LINK_ATTRIBUTES: INTERNAL_LINK_ATTRIBUTES2,
607
+ cleanInternalLinkAttributes: cleanInternalLinkAttributes2
584
608
  } = (init_sanitize_policy(), __toCommonJS(sanitize_policy_exports));
585
609
  var transformLink = (tagName, attribs) => {
586
610
  const out = { ...attribs };
@@ -597,6 +621,8 @@ var require_sanitizer = __commonJS({
597
621
  } else if (out.rel) {
598
622
  out.rel = String(out.rel).split(/\s+/).filter((value) => /^[a-z-]{1,20}$/.test(value)).join(" ");
599
623
  }
624
+ for (const name of INTERNAL_LINK_ATTRIBUTES2) delete out[name];
625
+ Object.assign(out, cleanInternalLinkAttributes2(attribs));
600
626
  return { tagName, attribs: out };
601
627
  };
602
628
  var INLINE_OPTIONS = Object.freeze({
@@ -663,10 +689,10 @@ var require_editor_fields = __commonJS({
663
689
  "server/src/utils/editor-fields.js"(exports, module) {
664
690
  "use strict";
665
691
  var CUSTOM_FIELD_UID = "plugin::magic-editor-x.richtext";
666
- var MAX_DEPTH = 8;
692
+ var MAX_DEPTH2 = 8;
667
693
  var isEditorAttribute = (attribute) => Boolean(attribute) && attribute.customField === CUSTOM_FIELD_UID;
668
694
  var schemaHasEditorFields = (strapi, schema, cache = /* @__PURE__ */ new Map(), depth = 0) => {
669
- if (!schema || depth > MAX_DEPTH) return false;
695
+ if (!schema || depth > MAX_DEPTH2) return false;
670
696
  const key = schema.uid;
671
697
  if (key && cache.has(key)) return cache.get(key);
672
698
  if (key) cache.set(key, false);
@@ -686,7 +712,7 @@ var require_editor_fields = __commonJS({
686
712
  return found;
687
713
  };
688
714
  var transformEditorFields = (strapi, schema, data, transform, depth = 0) => {
689
- if (!schema || !data || typeof data !== "object" || depth > MAX_DEPTH) return data;
715
+ if (!schema || !data || typeof data !== "object" || depth > MAX_DEPTH2) return data;
690
716
  for (const [name, attribute] of Object.entries(schema.attributes || {})) {
691
717
  if (!Object.prototype.hasOwnProperty.call(data, name)) continue;
692
718
  const value = data[name];
@@ -851,6 +877,16 @@ var require_bootstrap = __commonJS({
851
877
  } catch (error) {
852
878
  logger.error("database setup failed", error);
853
879
  }
880
+ try {
881
+ const csp = plugin.service("settings").inspectAdminCsp();
882
+ if (csp.frameSrcMissing.length || csp.imgSrcMissing) {
883
+ logger.debug(
884
+ "the admin Content Security Policy blocks some editor embeds or external images; Settings > Magic Editor X > Configuration shows the sources to add"
885
+ );
886
+ }
887
+ } catch (error) {
888
+ logger.error("the admin Content Security Policy could not be inspected", error);
889
+ }
854
890
  if (strapi.config.get("plugin::magic-editor-x.api.autoParseJSON") !== false) {
855
891
  strapi.server.use(plugin.middleware("parse-editor-fields")({}, { strapi }));
856
892
  }
@@ -859,6 +895,19 @@ var require_bootstrap = __commonJS({
859
895
  } catch (error) {
860
896
  logger.error("live collaboration could not start", error);
861
897
  }
898
+ const onPermissionChange = () => {
899
+ plugin.service("collaboration").permissionsChanged().catch(() => {
900
+ });
901
+ };
902
+ strapi.db.lifecycles.subscribe({
903
+ models: ["admin::permission", "admin::role", "admin::user"],
904
+ afterCreate: onPermissionChange,
905
+ afterCreateMany: onPermissionChange,
906
+ afterUpdate: onPermissionChange,
907
+ afterUpdateMany: onPermissionChange,
908
+ afterDelete: onPermissionChange,
909
+ afterDeleteMany: onPermissionChange
910
+ });
862
911
  };
863
912
  }
864
913
  });
@@ -878,11 +927,72 @@ var require_destroy = __commonJS({
878
927
  }
879
928
  });
880
929
 
930
+ // shared/link-pattern.mjs
931
+ var link_pattern_exports = {};
932
+ __export(link_pattern_exports, {
933
+ DEFAULT_LINK_PATTERN: () => DEFAULT_LINK_PATTERN,
934
+ LINK_PATTERN_PLACEHOLDERS: () => LINK_PATTERN_PLACEHOLDERS,
935
+ MAX_LINK_PATTERN_LENGTH: () => MAX_LINK_PATTERN_LENGTH,
936
+ isValidLinkPattern: () => isValidLinkPattern,
937
+ renderLinkPattern: () => renderLinkPattern
938
+ });
939
+ var LINK_PATTERN_PLACEHOLDERS, DEFAULT_LINK_PATTERN, MAX_LINK_PATTERN_LENGTH, TOKEN, PREFIX, FORBIDDEN, isValidLinkPattern, encode, renderLinkPattern;
940
+ var init_link_pattern = __esm({
941
+ "shared/link-pattern.mjs"() {
942
+ init_sanitize_policy();
943
+ LINK_PATTERN_PLACEHOLDERS = Object.freeze([
944
+ "documentId",
945
+ "locale",
946
+ "slug",
947
+ "collection",
948
+ "singular"
949
+ ]);
950
+ DEFAULT_LINK_PATTERN = "/{collection}/{documentId}";
951
+ MAX_LINK_PATTERN_LENGTH = 500;
952
+ TOKEN = /\{([A-Za-z]{1,20})\}/g;
953
+ PREFIX = /^(?:\/(?!\/)|https?:\/\/[A-Za-z0-9.-]{1,253}(?::\d{1,5})?(?:[/?#]|$))/;
954
+ FORBIDDEN = /[\s\u0000-\u001f\u007f<>"'`\\]/;
955
+ isValidLinkPattern = (pattern) => {
956
+ if (typeof pattern !== "string") return false;
957
+ if (pattern === "") return true;
958
+ if (pattern.length > MAX_LINK_PATTERN_LENGTH || FORBIDDEN.test(pattern) || !PREFIX.test(pattern))
959
+ return false;
960
+ let unknown = false;
961
+ const stripped = pattern.replace(TOKEN, (_match, name) => {
962
+ if (!LINK_PATTERN_PLACEHOLDERS.includes(name)) unknown = true;
963
+ return "x";
964
+ });
965
+ if (unknown || /[{}]/.test(stripped)) return false;
966
+ return Boolean(sanitizeUrl(stripped));
967
+ };
968
+ encode = (value) => {
969
+ const text = value === null || value === void 0 ? "" : String(value);
970
+ if (text === "." || text === "..") return text.replace(/\./g, "%2E");
971
+ return encodeURIComponent(text);
972
+ };
973
+ renderLinkPattern = (pattern, values) => {
974
+ const source = pattern || DEFAULT_LINK_PATTERN;
975
+ if (!isValidLinkPattern(source)) return "";
976
+ const data = { ...values, slug: values && values.slug || values && values.documentId };
977
+ const rendered = source.replace(TOKEN, (_match, name) => encode(data[name]));
978
+ const origin = /^https?:\/\/[^/?#]+/i.exec(rendered);
979
+ const head = origin ? origin[0] : "";
980
+ const rest = rendered.slice(head.length);
981
+ const split = rest.search(/[?#]/);
982
+ const path = split === -1 ? rest : rest.slice(0, split);
983
+ const tail = split === -1 ? "" : rest.slice(split);
984
+ const cleanPath = path.replace(/\/{2,}/g, "/");
985
+ return sanitizeUrl(head + (head || cleanPath ? cleanPath : "/") + tail);
986
+ };
987
+ }
988
+ });
989
+
881
990
  // server/src/config/index.js
882
991
  var require_config = __commonJS({
883
992
  "server/src/config/index.js"(exports, module) {
884
993
  "use strict";
885
994
  var { z } = __require("zod");
995
+ var { isValidLinkPattern: isValidLinkPattern2, MAX_LINK_PATTERN_LENGTH: MAX_LINK_PATTERN_LENGTH2 } = (init_link_pattern(), __toCommonJS(link_pattern_exports));
886
996
  var MiB = 1024 * 1024;
887
997
  var defaults = {
888
998
  debug: false,
@@ -927,11 +1037,32 @@ var require_config = __commonJS({
927
1037
  /** Automatic version-history snapshot while people edit live. 0 disables. */
928
1038
  snapshotIntervalMinutes: 10,
929
1039
  /** Lifetime of the one-time session token that opens the socket. */
930
- tokenTtlSeconds: 60
1040
+ tokenTtlSeconds: 60,
1041
+ /** Open sockets per admin across all processes. */
1042
+ maxConnectionsPerAdmin: 20,
1043
+ /** Different fields an admin may have open live at the same time. */
1044
+ maxRoomsPerAdmin: 20,
1045
+ /** Full permission re-check of open sockets (permission changes are applied within about a second anyway). */
1046
+ revalidateSeconds: 60,
1047
+ rateLimit: {
1048
+ /** Session tokens per admin and minute, shared by all processes. */
1049
+ sessionsPerMinute: 60,
1050
+ /** Updates per socket in 10 seconds. */
1051
+ updatesPer10s: 300,
1052
+ /** Update bytes per socket in 10 seconds. */
1053
+ bytesPer10s: 8 * MiB
1054
+ }
931
1055
  },
932
1056
  history: {
933
1057
  /** Snapshots kept per field and locale; older ones are removed. */
934
1058
  maxSnapshotsPerField: 50
1059
+ },
1060
+ links: {
1061
+ /**
1062
+ * href of internal links, e.g. '/{locale}/{collection}/{slug}' or 'https://www.example.com/{collection}/{documentId}'.
1063
+ * Placeholders: {documentId}, {locale}, {slug}, {collection}, {singular}. Empty uses '/{collection}/{documentId}'.
1064
+ */
1065
+ urlPattern: ""
935
1066
  }
936
1067
  };
937
1068
  var positiveInt = (max) => z.number().int().min(1).max(max);
@@ -960,9 +1091,20 @@ var require_config = __commonJS({
960
1091
  roomTtlMinutes: z.number().int().min(1).max(7 * 24 * 60),
961
1092
  maxMessageBytes: z.number().int().min(64 * 1024).max(20 * MiB),
962
1093
  snapshotIntervalMinutes: z.number().int().min(0).max(24 * 60),
963
- tokenTtlSeconds: z.number().int().min(10).max(600)
1094
+ tokenTtlSeconds: z.number().int().min(10).max(600),
1095
+ maxConnectionsPerAdmin: positiveInt(500),
1096
+ maxRoomsPerAdmin: positiveInt(500),
1097
+ revalidateSeconds: z.number().int().min(5).max(3600),
1098
+ rateLimit: z.looseObject({
1099
+ sessionsPerMinute: positiveInt(1e4),
1100
+ updatesPer10s: positiveInt(1e5),
1101
+ bytesPer10s: positiveInt(200 * MiB)
1102
+ })
964
1103
  }),
965
- history: z.looseObject({ maxSnapshotsPerField: positiveInt(1e3) })
1104
+ history: z.looseObject({ maxSnapshotsPerField: positiveInt(1e3) }),
1105
+ links: z.looseObject({
1106
+ urlPattern: z.string().max(MAX_LINK_PATTERN_LENGTH2).refine(isValidLinkPattern2)
1107
+ })
966
1108
  });
967
1109
  module.exports = {
968
1110
  default: defaults,
@@ -1236,6 +1378,13 @@ var require_validation = __commonJS({
1236
1378
  var documentIdSchema = z.string().regex(/^[a-z0-9]{1,64}$/);
1237
1379
  var localeSchema = z.string().regex(/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8}){0,3}$/);
1238
1380
  var fieldPathSchema = z.string().max(200).regex(/^[A-Za-z_][A-Za-z0-9_]{0,79}(\.(\d{1,4}|[A-Za-z_][A-Za-z0-9_]{0,79})){0,8}$/);
1381
+ var apiUidSchema = z.string().max(160).regex(/^api::[a-z0-9-]{1,60}\.[a-z0-9-]{1,60}$/);
1382
+ var linkSearchSchema = z.strictObject({
1383
+ uid: apiUidSchema,
1384
+ q: z.string().trim().max(100).regex(/^[^\u0000-\u001f\u007f]*$/).optional(),
1385
+ locale: localeSchema.optional(),
1386
+ page: z.coerce.number().int().min(1).max(500).optional()
1387
+ });
1239
1388
  var fieldTargetSchema = z.strictObject({
1240
1389
  uid: uidSchema,
1241
1390
  documentId: documentIdSchema,
@@ -1267,6 +1416,8 @@ var require_validation = __commonJS({
1267
1416
  localeSchema,
1268
1417
  fieldPathSchema,
1269
1418
  fieldTargetSchema,
1419
+ apiUidSchema,
1420
+ linkSearchSchema,
1270
1421
  parseOrThrow,
1271
1422
  issueDetails
1272
1423
  };
@@ -1510,6 +1661,41 @@ var require_settings = __commonJS({
1510
1661
  }
1511
1662
  });
1512
1663
 
1664
+ // server/src/controllers/links.js
1665
+ var require_links = __commonJS({
1666
+ "server/src/controllers/links.js"(exports, module) {
1667
+ "use strict";
1668
+ var { service } = require_helpers();
1669
+ var { parseOrThrow, linkSearchSchema } = require_validation();
1670
+ module.exports = ({ strapi }) => {
1671
+ const links = () => service(strapi, "links");
1672
+ return {
1673
+ /**
1674
+ * @route GET /magic-editor-x/links/types
1675
+ * @auth admin; plugin::magic-editor-x.access
1676
+ * @returns {{ data: Array<{ uid: string, kind: string, displayName: string, localized: boolean }> }} API types the caller can read.
1677
+ */
1678
+ async types(ctx) {
1679
+ ctx.body = { data: links().types(ctx.state.userAbility) };
1680
+ },
1681
+ /**
1682
+ * @route GET /magic-editor-x/links/search?uid&q&locale&page
1683
+ * @auth admin; plugin::magic-editor-x.access; CM read on the type (conditions and field permissions apply)
1684
+ * @returns {{ data: Array<{ documentId: string, uid: string, locale: string|null, title: string, href: string, status?: 'draft'|'published' }>, meta: { pagination: object } }} Up to 20 entries.
1685
+ * @throws {import('@strapi/utils').errors.ValidationError} 400 on invalid input.
1686
+ * @throws {import('@strapi/utils').errors.NotFoundError} 404 when the type does not exist or cannot be read.
1687
+ */
1688
+ async search(ctx) {
1689
+ const query = { ...ctx.query };
1690
+ for (const key of ["q", "locale", "page"]) if (query[key] === "") delete query[key];
1691
+ const input = parseOrThrow(linkSearchSchema, query);
1692
+ ctx.body = await links().search({ userAbility: ctx.state.userAbility, ...input });
1693
+ }
1694
+ };
1695
+ };
1696
+ }
1697
+ });
1698
+
1513
1699
  // server/src/controllers/index.js
1514
1700
  var require_controllers = __commonJS({
1515
1701
  "server/src/controllers/index.js"(exports, module) {
@@ -1521,7 +1707,8 @@ var require_controllers = __commonJS({
1521
1707
  collaboration: require_collaboration(),
1522
1708
  history: require_history(),
1523
1709
  ai: require_ai(),
1524
- settings: require_settings()
1710
+ settings: require_settings(),
1711
+ links: require_links()
1525
1712
  };
1526
1713
  }
1527
1714
  });
@@ -1532,9 +1719,9 @@ var require_parse_editor_fields = __commonJS({
1532
1719
  "use strict";
1533
1720
  var { looksLikeEditorData: looksLikeEditorData2 } = (init_editor_data(), __toCommonJS(editor_data_exports));
1534
1721
  var MAX_STRING = 5 * 1024 * 1024;
1535
- var MAX_DEPTH = 12;
1722
+ var MAX_DEPTH2 = 12;
1536
1723
  var parseValue = (value, depth = 0) => {
1537
- if (depth > MAX_DEPTH || value === null || typeof value !== "object") return value;
1724
+ if (depth > MAX_DEPTH2 || value === null || typeof value !== "object") return value;
1538
1725
  if (value instanceof Date) return value;
1539
1726
  if (Array.isArray(value)) {
1540
1727
  for (let i = 0; i < value.length; i += 1) value[i] = parseValue(value[i], depth + 1);
@@ -1597,6 +1784,8 @@ var require_routes = __commonJS({
1597
1784
  ["POST", "/image/byUrl", "editor.uploadImageUrl", [ACTIONS.access, UPLOAD_CREATE]],
1598
1785
  ["POST", "/file/upload", "editor.uploadAttachment", [ACTIONS.access, UPLOAD_CREATE]],
1599
1786
  ["GET", "/content-types", "editor.contentTypes", [ACTIONS.access]],
1787
+ ["GET", "/links/types", "links.types", [ACTIONS.access]],
1788
+ ["GET", "/links/search", "links.search", [ACTIONS.access]],
1600
1789
  ["GET", "/custom-blocks", "customBlocks.list", [ACTIONS.access]],
1601
1790
  ["GET", "/custom-blocks/export", "customBlocks.export", [ACTIONS.customBlocksManage]],
1602
1791
  ["POST", "/custom-blocks/import", "customBlocks.import", [ACTIONS.customBlocksManage]],
@@ -1634,7 +1823,8 @@ var require_store = __commonJS({
1634
1823
  var TABLES = Object.freeze({
1635
1824
  updates: "magic_editor_x_collab_updates",
1636
1825
  presence: "magic_editor_x_collab_presence",
1637
- locks: "magic_editor_x_locks"
1826
+ locks: "magic_editor_x_locks",
1827
+ counters: "magic_editor_x_counters"
1638
1828
  });
1639
1829
  module.exports = ({ strapi }) => {
1640
1830
  const logger = createLogger(strapi);
@@ -1684,6 +1874,11 @@ var require_store = __commonJS({
1684
1874
  t.string("owner", 64).notNullable();
1685
1875
  t.bigInteger("expires_at").notNullable();
1686
1876
  });
1877
+ await ensureTable(TABLES.counters, (t) => {
1878
+ t.string("key", 255).primary();
1879
+ t.integer("count").notNullable().defaultTo(0);
1880
+ t.bigInteger("expires_at").notNullable();
1881
+ });
1687
1882
  })().catch((error) => {
1688
1883
  ready = null;
1689
1884
  logger.error("collaboration tables could not be created", error);
@@ -1743,6 +1938,74 @@ var require_store = __commonJS({
1743
1938
  ids.map((row) => row.key)
1744
1939
  ).andWhere("expires_at", "<", Date.now()).del();
1745
1940
  },
1941
+ /**
1942
+ * Counts one event in a fixed window shared by all processes.
1943
+ * @param {string} key - Counter key (bounded by the caller, no personal data besides an admin id).
1944
+ * @param {number} windowMs - Window length.
1945
+ * @returns {Promise<{ count: number, resetAt: number }>} Events in the current window, including this one.
1946
+ */
1947
+ async hit(key, windowMs) {
1948
+ const now = Date.now();
1949
+ const windowKey = `${key}:${Math.floor(now / windowMs)}`.slice(0, 255);
1950
+ const expiresAt = (Math.floor(now / windowMs) + 1) * windowMs;
1951
+ try {
1952
+ await table(TABLES.counters).insert({ key: windowKey, count: 1, expires_at: expiresAt });
1953
+ } catch {
1954
+ await table(TABLES.counters).where({ key: windowKey }).increment("count", 1);
1955
+ }
1956
+ const row = await table(TABLES.counters).where({ key: windowKey }).first("count");
1957
+ return { count: Number(row?.count || 1), resetAt: expiresAt };
1958
+ },
1959
+ /**
1960
+ * Removes expired counters (bounded).
1961
+ * @returns {Promise<number>} Rows removed.
1962
+ */
1963
+ async pruneCounters() {
1964
+ const keys = await table(TABLES.counters).where("expires_at", "<", Date.now()).select("key").limit(500);
1965
+ if (keys.length === 0) return 0;
1966
+ return table(TABLES.counters).whereIn(
1967
+ "key",
1968
+ keys.map((row) => row.key)
1969
+ ).del();
1970
+ },
1971
+ /**
1972
+ * Sets a cluster-wide signal to a new random value (for example after a
1973
+ * permission change). Every process compares it on its next tick.
1974
+ * @param {string} name - Signal name.
1975
+ * @param {string} value - New value.
1976
+ * @returns {Promise<void>}
1977
+ */
1978
+ async setSignal(name, value) {
1979
+ const key = `signal:${name}`;
1980
+ const expiresAt = Date.now() + 10 * 365 * 24 * 3600 * 1e3;
1981
+ const updated = await table(TABLES.locks).where({ key }).update({ owner: value, expires_at: expiresAt });
1982
+ if (updated === 0) {
1983
+ try {
1984
+ await table(TABLES.locks).insert({ key, owner: value, expires_at: expiresAt });
1985
+ } catch {
1986
+ await table(TABLES.locks).where({ key }).update({ owner: value, expires_at: expiresAt });
1987
+ }
1988
+ }
1989
+ },
1990
+ /**
1991
+ * Reads a cluster-wide signal.
1992
+ * @param {string} name - Signal name.
1993
+ * @returns {Promise<string>} Current value ('' when never set).
1994
+ */
1995
+ async getSignal(name) {
1996
+ const row = await table(TABLES.locks).where({ key: `signal:${name}` }).first("owner");
1997
+ return row ? String(row.owner) : "";
1998
+ },
1999
+ /**
2000
+ * Live sockets and rooms of one admin across all processes.
2001
+ * @param {number} userId - Admin id.
2002
+ * @param {number} freshAfter - Heartbeat threshold.
2003
+ * @returns {Promise<{ sockets: number, rooms: Set<string> }>} Usage.
2004
+ */
2005
+ async presenceOfUser(userId, freshAfter) {
2006
+ const rows = await table(TABLES.presence).where({ user_id: userId }).andWhere("updated_at", ">", freshAfter).select("room");
2007
+ return { sockets: rows.length, rooms: new Set(rows.map((row) => row.room)) };
2008
+ },
1746
2009
  /**
1747
2010
  * Appends one Yjs update.
1748
2011
  * @param {string} room - Room key.
@@ -1765,13 +2028,14 @@ var require_store = __commonJS({
1765
2028
  /**
1766
2029
  * Reads every update of a room in insertion order.
1767
2030
  * @param {string} room - Room key.
1768
- * @returns {Promise<Array<{ id: number, kind: string, update: Uint8Array }>>} Updates.
2031
+ * @returns {Promise<Array<{ id: number, kind: string, createdAt: number, update: Uint8Array }>>} Updates.
1769
2032
  */
1770
2033
  async readRoom(room) {
1771
- const rows = await table(TABLES.updates).where({ room }).orderBy("id", "asc").select("id", "kind", "data");
2034
+ const rows = await table(TABLES.updates).where({ room }).orderBy("id", "asc").select("id", "kind", "data", "created_at");
1772
2035
  return rows.map((row) => ({
1773
2036
  id: Number(row.id),
1774
2037
  kind: row.kind,
2038
+ createdAt: Number(row.created_at),
1775
2039
  update: new Uint8Array(Buffer.from(row.data, "base64"))
1776
2040
  }));
1777
2041
  },
@@ -2009,6 +2273,159 @@ var require_access = __commonJS({
2009
2273
  }
2010
2274
  });
2011
2275
 
2276
+ // server/src/services/links.js
2277
+ var require_links2 = __commonJS({
2278
+ "server/src/services/links.js"(exports, module) {
2279
+ "use strict";
2280
+ var { errors } = __require("@strapi/utils");
2281
+ var { renderLinkPattern: renderLinkPattern2 } = (init_link_pattern(), __toCommonJS(link_pattern_exports));
2282
+ var PAGE_SIZE = 20;
2283
+ var TITLE_TYPES = /* @__PURE__ */ new Set(["string", "text", "email", "uid"]);
2284
+ var notFound = () => new errors.NotFoundError("Not found");
2285
+ module.exports = ({ strapi }) => {
2286
+ const access = () => strapi.plugin("magic-editor-x").service("access");
2287
+ const checker = (userAbility, uid) => strapi.plugin("content-manager").service("permission-checker").create({ userAbility, model: uid });
2288
+ const titleFieldFor = async (contentType) => {
2289
+ const attributes = contentType.attributes || {};
2290
+ let mainField;
2291
+ try {
2292
+ const configuration = await strapi.plugin("content-manager").service("content-types").findConfiguration(contentType);
2293
+ mainField = configuration && configuration.settings ? configuration.settings.mainField : null;
2294
+ } catch {
2295
+ mainField = null;
2296
+ }
2297
+ if (typeof mainField === "string" && attributes[mainField] && TITLE_TYPES.has(attributes[mainField].type))
2298
+ return mainField;
2299
+ const first = Object.entries(attributes).find(
2300
+ ([, attribute]) => attribute && TITLE_TYPES.has(attribute.type) && !attribute.private
2301
+ );
2302
+ return first ? first[0] : null;
2303
+ };
2304
+ const slugFieldFor = (contentType) => {
2305
+ const entry = Object.entries(contentType.attributes || {}).find(
2306
+ ([, attribute]) => attribute && attribute.type === "uid"
2307
+ );
2308
+ return entry ? entry[0] : null;
2309
+ };
2310
+ const isLocalized = (contentType) => Boolean(contentType.pluginOptions?.i18n?.localized);
2311
+ const hasDraftAndPublish = (contentType) => contentType.options?.draftAndPublish === true;
2312
+ return {
2313
+ PAGE_SIZE,
2314
+ /**
2315
+ * Content types the caller can read in the Content Manager.
2316
+ * @param {object} userAbility - CASL ability.
2317
+ * @returns {Array<{ uid: string, kind: string, displayName: string, localized: boolean }>} Types.
2318
+ */
2319
+ types(userAbility) {
2320
+ if (!userAbility) return [];
2321
+ return access().readableContentTypes(userAbility).map(({ uid, kind, displayName }) => ({
2322
+ uid,
2323
+ kind,
2324
+ displayName,
2325
+ localized: isLocalized(strapi.contentType(uid))
2326
+ }));
2327
+ },
2328
+ /**
2329
+ * Searches readable entries of one type by their title.
2330
+ * @param {{ userAbility: object, uid: string, q?: string, locale?: string, page?: number }} input - Validated input.
2331
+ * @returns {Promise<{ data: object[], meta: { pagination: { page: number, pageSize: number, pageCount: number, total: number } } }>} Page.
2332
+ * @throws {errors.NotFoundError} When the type does not exist or cannot be read.
2333
+ */
2334
+ async search({ userAbility, uid, q, locale, page = 1 }) {
2335
+ if (!userAbility) throw notFound();
2336
+ const contentType = strapi.contentType(uid);
2337
+ if (!contentType || !uid.startsWith("api::")) throw notFound();
2338
+ const pc = checker(userAbility, uid);
2339
+ if (pc.cannot.read()) throw notFound();
2340
+ let effectiveLocale = null;
2341
+ if (isLocalized(contentType)) {
2342
+ effectiveLocale = locale || await strapi.plugin("i18n")?.service("locales")?.getDefaultLocale?.() || null;
2343
+ if (!effectiveLocale) throw notFound();
2344
+ }
2345
+ const titleField = await titleFieldFor(contentType);
2346
+ const canTitle = Boolean(titleField) && !pc.cannot.read(null, titleField);
2347
+ const slugField = slugFieldFor(contentType);
2348
+ const canSlug = Boolean(slugField) && !pc.cannot.read(null, slugField);
2349
+ const fields = effectiveLocale ? ["documentId", "locale"] : ["documentId"];
2350
+ if (canTitle) fields.push(titleField);
2351
+ if (canSlug && slugField !== titleField) fields.push(slugField);
2352
+ const term = typeof q === "string" ? q.trim() : "";
2353
+ let filters;
2354
+ if (term) {
2355
+ filters = canTitle ? { [titleField]: { $containsi: term } } : { documentId: term };
2356
+ }
2357
+ const permission = await pc.sanitizedQuery.read({});
2358
+ const parts = [permission && permission.filters, filters].filter(Boolean);
2359
+ let where;
2360
+ if (parts.length > 1) where = { $and: parts };
2361
+ else if (parts.length === 1) where = parts[0];
2362
+ const base = {
2363
+ ...where ? { filters: where } : {},
2364
+ locale: effectiveLocale || void 0,
2365
+ status: "draft"
2366
+ };
2367
+ const documents = strapi.documents(uid);
2368
+ const [rows, total] = await Promise.all([
2369
+ documents.findMany({
2370
+ ...base,
2371
+ fields,
2372
+ ...canTitle ? { sort: [{ [titleField]: "asc" }] } : {},
2373
+ start: (page - 1) * PAGE_SIZE,
2374
+ limit: PAGE_SIZE
2375
+ }),
2376
+ documents.count(base)
2377
+ ]);
2378
+ let published = null;
2379
+ if (hasDraftAndPublish(contentType) && rows.length) {
2380
+ const versions = await documents.findMany({
2381
+ filters: { documentId: { $in: rows.map((row) => row.documentId) } },
2382
+ locale: effectiveLocale || void 0,
2383
+ status: "published",
2384
+ fields: ["documentId"]
2385
+ });
2386
+ published = new Set(versions.map((version) => version.documentId));
2387
+ }
2388
+ const pattern = strapi.config.get("plugin::magic-editor-x.links.urlPattern") || "";
2389
+ const data = [];
2390
+ for (const row of rows) {
2391
+ const clean = await pc.sanitizeOutput(row) || {};
2392
+ const documentId = typeof row.documentId === "string" ? row.documentId : null;
2393
+ if (!documentId) continue;
2394
+ const title = canTitle && typeof clean[titleField] === "string" ? clean[titleField].slice(0, 200) : "";
2395
+ const slug = canSlug && typeof clean[slugField] === "string" ? clean[slugField] : null;
2396
+ const item = {
2397
+ documentId,
2398
+ uid,
2399
+ locale: effectiveLocale,
2400
+ title,
2401
+ href: renderLinkPattern2(pattern, {
2402
+ documentId,
2403
+ locale: effectiveLocale,
2404
+ slug,
2405
+ collection: contentType.info?.pluralName || "",
2406
+ singular: contentType.info?.singularName || ""
2407
+ })
2408
+ };
2409
+ if (published) item.status = published.has(documentId) ? "published" : "draft";
2410
+ data.push(item);
2411
+ }
2412
+ return {
2413
+ data,
2414
+ meta: {
2415
+ pagination: {
2416
+ page,
2417
+ pageSize: PAGE_SIZE,
2418
+ pageCount: Math.ceil(total / PAGE_SIZE),
2419
+ total
2420
+ }
2421
+ }
2422
+ };
2423
+ }
2424
+ };
2425
+ };
2426
+ }
2427
+ });
2428
+
2012
2429
  // server/src/utils/url-security.js
2013
2430
  var require_url_security = __commonJS({
2014
2431
  "server/src/utils/url-security.js"(exports, module) {
@@ -2557,6 +2974,247 @@ var require_crypto = __commonJS({
2557
2974
  }
2558
2975
  });
2559
2976
 
2977
+ // shared/csp.mjs
2978
+ var csp_exports = {};
2979
+ __export(csp_exports, {
2980
+ EMBED_FRAME_SOURCES: () => EMBED_FRAME_SOURCES,
2981
+ buildCspSnippet: () => buildCspSnippet,
2982
+ effectiveDirectives: () => effectiveDirectives,
2983
+ findSecurityMiddleware: () => findSecurityMiddleware,
2984
+ governingSources: () => governingSources,
2985
+ inspectCsp: () => inspectCsp,
2986
+ matchesBlockedUri: () => matchesBlockedUri,
2987
+ sourcesAllow: () => sourcesAllow
2988
+ });
2989
+ var EMBED_FRAME_SOURCES, EXTERNAL_IMAGE_SAMPLE, STRAPI_DEFAULT_HOSTS, STRAPI_DEFAULT_DIRECTIVES, HELMET_DEFAULT_DIRECTIVES, FALLBACKS, isObject, dashify, findSecurityMiddleware, mergeDirective, effectiveDirectives, governingSources, HOST_SOURCE, DEFAULT_PORTS, expressions, expressionAllows, sourcesAllow, hasExplicitExternalHost, literal, unique, buildCspSnippet, inspectCsp, matchesBlockedUri;
2990
+ var init_csp = __esm({
2991
+ "shared/csp.mjs"() {
2992
+ EMBED_FRAME_SOURCES = Object.freeze({
2993
+ youtube: { origin: "https://www.youtube.com", sample: "https://www.youtube.com/embed/x" },
2994
+ vimeo: { origin: "https://player.vimeo.com", sample: "https://player.vimeo.com/video/1" },
2995
+ twitter: {
2996
+ origin: "https://platform.twitter.com",
2997
+ sample: "https://platform.twitter.com/embed/Tweet.html"
2998
+ },
2999
+ instagram: { origin: "https://www.instagram.com", sample: "https://www.instagram.com/p/x/embed" },
3000
+ codepen: { origin: "https://codepen.io", sample: "https://codepen.io/x/embed/y" },
3001
+ imgur: { origin: "https://imgur.com", sample: "https://imgur.com/x/embed" },
3002
+ pinterest: {
3003
+ origin: "https://assets.pinterest.com",
3004
+ sample: "https://assets.pinterest.com/ext/embed.html"
3005
+ },
3006
+ miro: { origin: "https://miro.com", sample: "https://miro.com/app/live-embed/x" },
3007
+ figma: { origin: "https://www.figma.com", sample: "https://www.figma.com/embed" },
3008
+ facebook: { origin: "https://www.facebook.com", sample: "https://www.facebook.com/plugins/post.php" }
3009
+ });
3010
+ EXTERNAL_IMAGE_SAMPLE = "https://images.example.com/picture.png";
3011
+ STRAPI_DEFAULT_HOSTS = /* @__PURE__ */ new Set(["market-assets.strapi.io", "strapi.io", "cdn.jsdelivr.net"]);
3012
+ STRAPI_DEFAULT_DIRECTIVES = Object.freeze({
3013
+ "connect-src": ["'self'", "https:"],
3014
+ "img-src": ["'self'", "data:", "blob:", "https://market-assets.strapi.io"],
3015
+ "media-src": ["'self'", "data:", "blob:"],
3016
+ "upgrade-insecure-requests": null
3017
+ });
3018
+ HELMET_DEFAULT_DIRECTIVES = Object.freeze({
3019
+ "default-src": ["'self'"],
3020
+ "base-uri": ["'self'"],
3021
+ "font-src": ["'self'", "https:", "data:"],
3022
+ "form-action": ["'self'"],
3023
+ "frame-ancestors": ["'self'"],
3024
+ "img-src": ["'self'", "data:"],
3025
+ "object-src": ["'none'"],
3026
+ "script-src": ["'self'"],
3027
+ "script-src-attr": ["'none'"],
3028
+ "style-src": ["'self'", "https:", "'unsafe-inline'"],
3029
+ "upgrade-insecure-requests": []
3030
+ });
3031
+ FALLBACKS = Object.freeze({
3032
+ "frame-src": ["frame-src", "child-src", "default-src"],
3033
+ "img-src": ["img-src", "default-src"],
3034
+ "media-src": ["media-src", "default-src"]
3035
+ });
3036
+ isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3037
+ dashify = (name) => name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
3038
+ findSecurityMiddleware = (middlewares) => {
3039
+ if (!Array.isArray(middlewares)) return { found: true, config: {} };
3040
+ for (const entry of middlewares) {
3041
+ if (entry === "strapi::security") return { found: true, config: {} };
3042
+ if (isObject(entry) && entry.name === "strapi::security") {
3043
+ return { found: true, config: isObject(entry.config) ? entry.config : {} };
3044
+ }
3045
+ }
3046
+ return { found: false, config: {} };
3047
+ };
3048
+ mergeDirective = (user, fallback) => {
3049
+ if (user === void 0) return Array.isArray(fallback) ? [...fallback] : fallback;
3050
+ if (Array.isArray(user) && Array.isArray(fallback)) {
3051
+ const merged = [...user];
3052
+ for (let index = user.length; index < fallback.length; index += 1) merged.push(fallback[index]);
3053
+ return merged;
3054
+ }
3055
+ return user;
3056
+ };
3057
+ effectiveDirectives = (middlewares) => {
3058
+ const { found, config } = findSecurityMiddleware(middlewares);
3059
+ const csp = config.contentSecurityPolicy;
3060
+ if (!found || csp === false || isObject(csp) && csp.reportOnly === true) {
3061
+ return { active: false, directives: /* @__PURE__ */ new Map() };
3062
+ }
3063
+ const options = isObject(csp) ? csp : {};
3064
+ const userDirectives = {};
3065
+ if (isObject(options.directives)) {
3066
+ for (const [name, value] of Object.entries(options.directives)) {
3067
+ userDirectives[dashify(name)] = value;
3068
+ }
3069
+ }
3070
+ const names = /* @__PURE__ */ new Set([...Object.keys(STRAPI_DEFAULT_DIRECTIVES), ...Object.keys(userDirectives)]);
3071
+ const result = /* @__PURE__ */ new Map();
3072
+ const disabled = /* @__PURE__ */ new Set();
3073
+ for (const name of names) {
3074
+ const value = mergeDirective(userDirectives[name], STRAPI_DEFAULT_DIRECTIVES[name]);
3075
+ if (value === null) disabled.add(name);
3076
+ else if (typeof value === "string") result.set(name, [value]);
3077
+ else if (Array.isArray(value))
3078
+ result.set(
3079
+ name,
3080
+ value.filter((item) => typeof item === "string")
3081
+ );
3082
+ else disabled.add(name);
3083
+ }
3084
+ if (options.useDefaults !== false) {
3085
+ for (const [name, value] of Object.entries(HELMET_DEFAULT_DIRECTIVES)) {
3086
+ if (!result.has(name) && !disabled.has(name)) result.set(name, [...value]);
3087
+ }
3088
+ }
3089
+ return { active: true, directives: result };
3090
+ };
3091
+ governingSources = (directives, directive) => {
3092
+ for (const name of FALLBACKS[directive] || [directive]) {
3093
+ if (directives.has(name)) return directives.get(name);
3094
+ }
3095
+ return null;
3096
+ };
3097
+ HOST_SOURCE = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|\*\.[^:/]+|[^:/*]+)(?::(\d+|\*))?(\/.*)?$/;
3098
+ DEFAULT_PORTS = { "http:": "80", "https:": "443" };
3099
+ expressions = (sources) => sources.flatMap((source) => String(source).trim().toLowerCase().split(/\s+/).filter(Boolean));
3100
+ expressionAllows = (expression, url) => {
3101
+ const protocol = url.protocol;
3102
+ if (expression === "*") return protocol === "http:" || protocol === "https:";
3103
+ if (expression.startsWith("'")) return false;
3104
+ if (/^[a-z][a-z0-9+.-]*:$/.test(expression)) {
3105
+ return expression === protocol || expression === "http:" && protocol === "https:";
3106
+ }
3107
+ const match = HOST_SOURCE.exec(expression);
3108
+ if (!match) return false;
3109
+ const [, scheme, host, port, path] = match;
3110
+ if (scheme) {
3111
+ if (`${scheme}:` !== protocol && !(scheme === "http" && protocol === "https:")) return false;
3112
+ } else if (protocol !== "http:" && protocol !== "https:") {
3113
+ return false;
3114
+ }
3115
+ const hostname = url.hostname.toLowerCase();
3116
+ if (host !== "*") {
3117
+ if (host.startsWith("*.")) {
3118
+ if (!hostname.endsWith(host.slice(1))) return false;
3119
+ } else if (host !== hostname) {
3120
+ return false;
3121
+ }
3122
+ }
3123
+ if (port && port !== "*") {
3124
+ const urlPort = url.port || DEFAULT_PORTS[protocol];
3125
+ if (port !== urlPort) return false;
3126
+ }
3127
+ if (path && path !== "/") {
3128
+ const pathname = url.pathname.toLowerCase();
3129
+ if (path.endsWith("/") ? !pathname.startsWith(path) : pathname !== path) return false;
3130
+ }
3131
+ return true;
3132
+ };
3133
+ sourcesAllow = (sources, url) => {
3134
+ if (sources === null) return true;
3135
+ let parsed;
3136
+ try {
3137
+ parsed = new URL(url);
3138
+ } catch {
3139
+ return false;
3140
+ }
3141
+ return expressions(sources).some((expression) => expressionAllows(expression, parsed));
3142
+ };
3143
+ hasExplicitExternalHost = (sources) => expressions(sources).some((expression) => {
3144
+ if (expression.startsWith("'") || /^[a-z][a-z0-9+.-]*:$/.test(expression)) return false;
3145
+ const match = HOST_SOURCE.exec(expression);
3146
+ return Boolean(match) && !STRAPI_DEFAULT_HOSTS.has(match[2]);
3147
+ });
3148
+ literal = (value) => value.includes("'") ? JSON.stringify(value) : `'${value.replace(/\\/g, "\\\\")}'`;
3149
+ unique = (values) => [...new Set(values)];
3150
+ buildCspSnippet = (directives, missing) => {
3151
+ const lines = [];
3152
+ const withoutNone = (list) => list.filter((item) => item.trim().toLowerCase() !== "'none'");
3153
+ if (missing.frameSrcMissing.length) {
3154
+ const base = governingSources(directives, "frame-src") || ["'self'"];
3155
+ lines.push(["frame-src", unique([...withoutNone(base), ...missing.frameSrcMissing])]);
3156
+ }
3157
+ if (missing.imgSrcMissing) {
3158
+ const base = governingSources(directives, "img-src") || ["'self'", "data:", "blob:"];
3159
+ lines.push(["img-src", unique([...withoutNone(base), "https:"])]);
3160
+ }
3161
+ if (!lines.length) return "";
3162
+ const body = lines.map(
3163
+ ([name, values]) => ` '${name}': [
3164
+ ${values.map((value) => ` ${literal(value)},`).join("\n")}
3165
+ ],`
3166
+ ).join("\n");
3167
+ return [
3168
+ "// config/middlewares.js: merge into your existing strapi::security entry",
3169
+ "module.exports = [",
3170
+ " // ...other middlewares",
3171
+ " {",
3172
+ " name: 'strapi::security',",
3173
+ " config: {",
3174
+ " contentSecurityPolicy: {",
3175
+ " useDefaults: true,",
3176
+ " directives: {",
3177
+ body,
3178
+ " },",
3179
+ " },",
3180
+ " },",
3181
+ " },",
3182
+ " // ...other middlewares",
3183
+ "];"
3184
+ ].join("\n");
3185
+ };
3186
+ inspectCsp = (middlewares) => {
3187
+ const { active, directives } = effectiveDirectives(middlewares);
3188
+ if (!active) return { active: false, frameSrcMissing: [], imgSrcMissing: false, snippet: "" };
3189
+ const frameSources = governingSources(directives, "frame-src");
3190
+ const frameSrcMissing = unique(
3191
+ Object.values(EMBED_FRAME_SOURCES).filter((service) => !sourcesAllow(frameSources, service.sample)).map((service) => service.origin)
3192
+ );
3193
+ const imgSources = governingSources(directives, "img-src");
3194
+ const imgSrcMissing = imgSources !== null && !sourcesAllow(imgSources, EXTERNAL_IMAGE_SAMPLE) && !hasExplicitExternalHost(imgSources);
3195
+ const missing = { frameSrcMissing, imgSrcMissing };
3196
+ return { active: true, ...missing, snippet: buildCspSnippet(directives, missing) };
3197
+ };
3198
+ matchesBlockedUri = (elementUrl, blockedUri) => {
3199
+ if (typeof elementUrl !== "string" || typeof blockedUri !== "string" || !elementUrl || !blockedUri) {
3200
+ return false;
3201
+ }
3202
+ if (elementUrl === blockedUri) return true;
3203
+ let element;
3204
+ let blocked;
3205
+ try {
3206
+ element = new URL(elementUrl);
3207
+ blocked = new URL(blockedUri);
3208
+ } catch {
3209
+ return false;
3210
+ }
3211
+ if (element.origin !== blocked.origin) return false;
3212
+ if (blocked.pathname === "/" && !blocked.search) return true;
3213
+ return element.href.split("#")[0] === blocked.href.split("#")[0];
3214
+ };
3215
+ }
3216
+ });
3217
+
2560
3218
  // server/src/services/settings.js
2561
3219
  var require_settings2 = __commonJS({
2562
3220
  "server/src/services/settings.js"(exports, module) {
@@ -2566,6 +3224,7 @@ var require_settings2 = __commonJS({
2566
3224
  var { errors } = __require("@strapi/utils");
2567
3225
  var { getEncryptionKey, encryptSecret, decryptSecret } = require_crypto();
2568
3226
  var { validateHttpUrl } = require_url_security();
3227
+ var { inspectCsp: inspectCsp2 } = (init_csp(), __toCommonJS(csp_exports));
2569
3228
  var PROVIDERS = ["anthropic", "openai", "openai-compatible"];
2570
3229
  var DEFAULT_MODELS = { anthropic: "claude-opus-5-5", openai: "gpt-6-luna", "openai-compatible": "" };
2571
3230
  var DEFAULT_BASE_URLS = {
@@ -2599,6 +3258,11 @@ var require_settings2 = __commonJS({
2599
3258
  const value = strapi.config.get(`plugin::magic-editor-x.${key}`);
2600
3259
  return value === void 0 ? fallback : value;
2601
3260
  };
3261
+ let cspReport = null;
3262
+ const inspectAdminCsp = () => {
3263
+ if (!cspReport) cspReport = inspectCsp2(strapi.config.get("middlewares"));
3264
+ return cspReport;
3265
+ };
2602
3266
  const readRaw = async () => {
2603
3267
  const stored = await store(strapi).get({ key: "settings" }) || {};
2604
3268
  return { ai: { ...DEFAULT_AI, ...stored.ai || {} } };
@@ -2647,7 +3311,8 @@ var require_settings2 = __commonJS({
2647
3311
  uploads: {
2648
3312
  maxImageBytes: config("uploads.maxImageBytes", 10 * 1024 * 1024),
2649
3313
  maxFileBytes: config("uploads.maxFileBytes", 20 * 1024 * 1024)
2650
- }
3314
+ },
3315
+ csp: inspectAdminCsp()
2651
3316
  }
2652
3317
  };
2653
3318
  };
@@ -2656,6 +3321,7 @@ var require_settings2 = __commonJS({
2656
3321
  DEFAULT_MODELS,
2657
3322
  DEFAULT_BASE_URLS,
2658
3323
  effectiveBaseUrl,
3324
+ inspectAdminCsp,
2659
3325
  /**
2660
3326
  * Settings for the settings page (no secrets).
2661
3327
  * @returns {Promise<object>} DTO.
@@ -2838,6 +3504,15 @@ var require_ai2 = __commonJS({
2838
3504
  return limiter;
2839
3505
  };
2840
3506
  const settings = () => strapi.plugin("magic-editor-x").service("settings");
3507
+ const allowRequest = async (userId) => {
3508
+ const perMinute = Number(strapi.config.get("plugin::magic-editor-x.ai.requestsPerMinute")) || 20;
3509
+ try {
3510
+ const { count } = await strapi.plugin("magic-editor-x").service("store").hit(`ai:${userId}`, 6e4);
3511
+ return count <= perMinute;
3512
+ } catch {
3513
+ return getLimiter().hit(`ai:${userId}`).allowed;
3514
+ }
3515
+ };
2841
3516
  const instructionFor = (action, options) => {
2842
3517
  let text = ACTIONS[action];
2843
3518
  if (action === "translate") {
@@ -2960,8 +3635,8 @@ ${text}
2960
3635
  if (textLength(input.text) > runtime.ai.maxInputChars) {
2961
3636
  throw new errors.PayloadTooLargeError("The text is longer than the configured limit");
2962
3637
  }
2963
- const verdict = getLimiter().hit(`ai:${user.id}`);
2964
- if (!verdict.allowed) throw new errors.RateLimitError("Too many AI requests. Try again in a minute.");
3638
+ if (!await allowRequest(user.id))
3639
+ throw new errors.RateLimitError("Too many AI requests. Try again in a minute.");
2965
3640
  const instruction = instructionFor(input.action, input);
2966
3641
  try {
2967
3642
  const answer = await callProvider(runtime, instruction, input.text);
@@ -3462,19 +4137,28 @@ __export(ydoc_exports, {
3462
4137
  applyLocalChanges: () => applyLocalChanges,
3463
4138
  applyTextDiff: () => applyTextDiff,
3464
4139
  applyTextEdit: () => applyTextEdit,
4140
+ createDocReader: () => createDocReader,
3465
4141
  createSeedUpdate: () => createSeedUpdate,
3466
4142
  docToEditorData: () => docToEditorData,
4143
+ epochOf: () => epochOf,
3467
4144
  getTypes: () => getTypes,
4145
+ lcsPairs: () => lcsPairs,
3468
4146
  legacyDeltaToHtml: () => legacyDeltaToHtml,
3469
4147
  legacyStateToEditorData: () => legacyStateToEditorData,
3470
- stableStringify: () => stableStringify
4148
+ readBlock: () => readBlock,
4149
+ readShared: () => readShared,
4150
+ stableStringify: () => stableStringify,
4151
+ toShared: () => toShared
3471
4152
  });
3472
4153
  import * as Y from "yjs";
3473
- var YDOC_SCHEMA, getTypes, stableStringify, applyTextDiff, readBlock, docToEditorData, writeData, lcsKeep, syncOrder, applyEditorDataToDoc, applyTextEdit, applyLocalChanges, lcsKeepIds, createSeedUpdate, legacyStateToEditorData, legacyDeltaToHtml;
4154
+ var YDOC_SCHEMA, MAX_DEPTH, FORBIDDEN_KEYS2, hasOwn, getTypes, stableStringify, equal, applyTextDiff, applyTextEdit, toShared, readShared, readBlock, docToEditorData, createDocReader, lcsPairs, kindOf, diffHunks, alignIndexes, mergeValue, mergeMap, mergeArray, mergeSlot, createEntry, applyLocalChanges, applyEditorDataToDoc, createSeedUpdate, epochOf, legacyStateToEditorData, legacyDeltaToHtml;
3474
4155
  var init_ydoc = __esm({
3475
4156
  "shared/ydoc.mjs"() {
3476
4157
  init_editor_data();
3477
- YDOC_SCHEMA = 2;
4158
+ YDOC_SCHEMA = 3;
4159
+ MAX_DEPTH = EDITOR_DATA_LIMITS.maxDepth;
4160
+ FORBIDDEN_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
4161
+ hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
3478
4162
  getTypes = (doc) => ({
3479
4163
  meta: doc.getMap("meta"),
3480
4164
  order: doc.getArray("order"),
@@ -3486,6 +4170,7 @@ var init_ydoc = __esm({
3486
4170
  const keys = Object.keys(value).sort();
3487
4171
  return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
3488
4172
  };
4173
+ equal = (a, b) => a === b || stableStringify(a) === stableStringify(b);
3489
4174
  applyTextDiff = (ytext, next) => {
3490
4175
  const current = ytext.toString();
3491
4176
  if (current === next) return false;
@@ -3502,31 +4187,95 @@ var init_ydoc = __esm({
3502
4187
  if (endNext > start) ytext.insert(start, next.slice(start, endNext));
3503
4188
  return true;
3504
4189
  };
4190
+ applyTextEdit = (ytext, base, local) => {
4191
+ if (base === local) return false;
4192
+ const shared = ytext.toString();
4193
+ if (shared === base) return applyTextDiff(ytext, local);
4194
+ let start = 0;
4195
+ while (start < base.length && start < local.length && base.charCodeAt(start) === local.charCodeAt(start))
4196
+ start += 1;
4197
+ let endBase = base.length;
4198
+ let endLocal = local.length;
4199
+ while (endBase > start && endLocal > start && base.charCodeAt(endBase - 1) === local.charCodeAt(endLocal - 1)) {
4200
+ endBase -= 1;
4201
+ endLocal -= 1;
4202
+ }
4203
+ let rp = 0;
4204
+ while (rp < base.length && rp < shared.length && base.charCodeAt(rp) === shared.charCodeAt(rp)) rp += 1;
4205
+ let rsBase = base.length;
4206
+ let rsShared = shared.length;
4207
+ while (rsBase > rp && rsShared > rp && base.charCodeAt(rsBase - 1) === shared.charCodeAt(rsShared - 1)) {
4208
+ rsBase -= 1;
4209
+ rsShared -= 1;
4210
+ }
4211
+ const shift = shared.length - base.length;
4212
+ const map = (index) => index <= rp ? index : index >= rsBase ? index + shift : Math.min(index + shift, shared.length);
4213
+ const from = map(start);
4214
+ const to = Math.max(from, map(endBase));
4215
+ if (to > from) ytext.delete(from, Math.min(to, shared.length) - from);
4216
+ const inserted = local.slice(start, endLocal);
4217
+ if (inserted) ytext.insert(Math.min(from, ytext.length), inserted);
4218
+ return true;
4219
+ };
4220
+ toShared = (value, depth = 0) => {
4221
+ if (depth > MAX_DEPTH) return null;
4222
+ if (typeof value === "string") return value ? new Y.Text(value) : new Y.Text();
4223
+ if (Array.isArray(value)) return Y.Array.from(value.map((item) => toShared(item, depth + 1)));
4224
+ if (isPlainObject(value)) {
4225
+ const entries = [];
4226
+ for (const key of Object.keys(value)) {
4227
+ if (FORBIDDEN_KEYS2.has(key) || value[key] === void 0) continue;
4228
+ entries.push([key, toShared(value[key], depth + 1)]);
4229
+ }
4230
+ return new Y.Map(entries);
4231
+ }
4232
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
4233
+ if (typeof value === "boolean" || value === null) return value;
4234
+ return null;
4235
+ };
4236
+ readShared = (value, depth = 0) => {
4237
+ if (value instanceof Y.Text) return value.toString();
4238
+ if (depth > MAX_DEPTH) return null;
4239
+ if (value instanceof Y.Array) return value.toArray().map((item) => readShared(item, depth + 1));
4240
+ if (value instanceof Y.Map) {
4241
+ const out = {};
4242
+ value.forEach((item, key) => {
4243
+ if (!FORBIDDEN_KEYS2.has(key)) out[key] = readShared(item, depth + 1);
4244
+ });
4245
+ return out;
4246
+ }
4247
+ if (value instanceof Y.AbstractType) return null;
4248
+ if (value === void 0) return null;
4249
+ if (value !== null && typeof value === "object") {
4250
+ try {
4251
+ return cloneJsonSafe(value, depth) ?? null;
4252
+ } catch {
4253
+ return null;
4254
+ }
4255
+ }
4256
+ if (typeof value === "number" && !Number.isFinite(value)) return null;
4257
+ return value;
4258
+ };
3505
4259
  readBlock = (id, entry) => {
3506
4260
  if (!(entry instanceof Y.Map)) return null;
3507
4261
  const type = entry.get("type");
3508
4262
  if (typeof type !== "string" || !type) return null;
3509
- const dataMap = entry.get("data");
3510
- const data = {};
3511
- if (dataMap instanceof Y.Map) {
3512
- dataMap.forEach((value, key) => {
3513
- data[key] = value instanceof Y.Text ? value.toString() : value;
3514
- });
3515
- }
3516
- const block = { id, type, data };
3517
- const tunes = entry.get("tunes");
4263
+ const rawData = readShared(entry.get("data"), 2);
4264
+ const block = { id, type, data: isPlainObject(rawData) ? rawData : {} };
4265
+ const tunes = readShared(entry.get("tunes"), 2);
3518
4266
  if (isPlainObject(tunes) && Object.keys(tunes).length > 0) block.tunes = tunes;
3519
4267
  return block;
3520
4268
  };
3521
- docToEditorData = (doc) => {
4269
+ docToEditorData = (doc, read = readBlock) => {
3522
4270
  const { meta, order, blocks } = getTypes(doc);
3523
4271
  const seen = /* @__PURE__ */ new Set();
3524
4272
  const out = [];
3525
4273
  for (const id of order.toArray()) {
3526
4274
  if (typeof id !== "string" || seen.has(id)) continue;
3527
4275
  seen.add(id);
3528
- const block = readBlock(id, blocks.get(id));
4276
+ const block = read(id, blocks.get(id));
3529
4277
  if (block) out.push(block);
4278
+ if (out.length >= EDITOR_DATA_LIMITS.maxBlocks) break;
3530
4279
  }
3531
4280
  return {
3532
4281
  time: Number(meta.get("time")) || 0,
@@ -3534,38 +4283,34 @@ var init_ydoc = __esm({
3534
4283
  version: typeof meta.get("version") === "string" ? meta.get("version") : "2.31.7"
3535
4284
  };
3536
4285
  };
3537
- writeData = (entry, data) => {
3538
- let dataMap = entry.get("data");
3539
- if (!(dataMap instanceof Y.Map)) {
3540
- dataMap = new Y.Map();
3541
- entry.set("data", dataMap);
3542
- }
3543
- let changed = false;
3544
- for (const key of Array.from(dataMap.keys())) {
3545
- if (!Object.prototype.hasOwnProperty.call(data, key)) {
3546
- dataMap.delete(key);
3547
- changed = true;
3548
- }
3549
- }
3550
- for (const [key, value] of Object.entries(data)) {
3551
- const current = dataMap.get(key);
3552
- if (typeof value === "string") {
3553
- if (current instanceof Y.Text) {
3554
- changed = applyTextDiff(current, value) || changed;
3555
- } else {
3556
- const text = new Y.Text();
3557
- dataMap.set(key, text);
3558
- text.insert(0, value);
3559
- changed = true;
4286
+ createDocReader = (doc) => {
4287
+ const { blocks } = getTypes(doc);
4288
+ const cache = /* @__PURE__ */ new Map();
4289
+ const observer = (events) => {
4290
+ for (const event of events) {
4291
+ if (event.target === blocks) {
4292
+ event.keysChanged.forEach((key) => cache.delete(key));
4293
+ } else if (event.path.length > 0) {
4294
+ cache.delete(event.path[0]);
3560
4295
  }
3561
- } else if (current instanceof Y.Text || stableStringify(current) !== stableStringify(value)) {
3562
- dataMap.set(key, value === void 0 ? null : value);
3563
- changed = true;
3564
4296
  }
3565
- }
3566
- return changed;
4297
+ };
4298
+ blocks.observeDeep(observer);
4299
+ const read = (id, entry) => {
4300
+ if (cache.has(id)) return cache.get(id);
4301
+ const block = readBlock(id, entry);
4302
+ cache.set(id, block);
4303
+ return block;
4304
+ };
4305
+ return {
4306
+ read: () => docToEditorData(doc, read),
4307
+ destroy: () => {
4308
+ blocks.unobserveDeep(observer);
4309
+ cache.clear();
4310
+ }
4311
+ };
3567
4312
  };
3568
- lcsKeep = (a, b) => {
4313
+ lcsPairs = (a, b) => {
3569
4314
  let start = 0;
3570
4315
  while (start < a.length && start < b.length && a[start] === b[start]) start += 1;
3571
4316
  let endA = a.length;
@@ -3574,129 +4319,161 @@ var init_ydoc = __esm({
3574
4319
  endA -= 1;
3575
4320
  endB -= 1;
3576
4321
  }
3577
- const keep = /* @__PURE__ */ new Set();
3578
- for (let i2 = 0; i2 < start; i2 += 1) keep.add(i2);
3579
- for (let i2 = endA; i2 < a.length; i2 += 1) keep.add(i2);
3580
- const midA = a.slice(start, endA);
3581
- const midB = b.slice(start, endB);
3582
- if (midA.length === 0 || midB.length === 0) return keep;
3583
- if (midA.length * midB.length > 4e6) return keep;
3584
- const rows = midA.length + 1;
3585
- const cols = midB.length + 1;
3586
- const table = new Uint16Array(rows * cols);
3587
- for (let i2 = midA.length - 1; i2 >= 0; i2 -= 1) {
3588
- for (let j2 = midB.length - 1; j2 >= 0; j2 -= 1) {
3589
- table[i2 * cols + j2] = midA[i2] === midB[j2] ? table[(i2 + 1) * cols + j2 + 1] + 1 : Math.max(table[(i2 + 1) * cols + j2], table[i2 * cols + j2 + 1]);
4322
+ const pairs = [];
4323
+ for (let i = 0; i < start; i += 1) pairs.push([i, i]);
4324
+ const midA = endA - start;
4325
+ const midB = endB - start;
4326
+ if (midA > 0 && midB > 0 && midA * midB <= 4e6) {
4327
+ const cols = midB + 1;
4328
+ const table = new Uint16Array((midA + 1) * cols);
4329
+ for (let i2 = midA - 1; i2 >= 0; i2 -= 1) {
4330
+ for (let j2 = midB - 1; j2 >= 0; j2 -= 1) {
4331
+ table[i2 * cols + j2] = a[start + i2] === b[start + j2] ? table[(i2 + 1) * cols + j2 + 1] + 1 : Math.max(table[(i2 + 1) * cols + j2], table[i2 * cols + j2 + 1]);
4332
+ }
4333
+ }
4334
+ let i = 0;
4335
+ let j = 0;
4336
+ while (i < midA && j < midB) {
4337
+ if (a[start + i] === b[start + j]) {
4338
+ pairs.push([start + i, start + j]);
4339
+ i += 1;
4340
+ j += 1;
4341
+ } else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) i += 1;
4342
+ else j += 1;
3590
4343
  }
3591
4344
  }
3592
- let i = 0;
3593
- let j = 0;
3594
- while (i < midA.length && j < midB.length) {
3595
- if (midA[i] === midB[j]) {
3596
- keep.add(start + i);
3597
- i += 1;
3598
- j += 1;
3599
- } else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) i += 1;
3600
- else j += 1;
4345
+ for (let k = 0; k < a.length - endA; k += 1) pairs.push([endA + k, endB + k]);
4346
+ return pairs;
4347
+ };
4348
+ kindOf = (value) => {
4349
+ if (typeof value === "string" || value instanceof Y.Text) return "text";
4350
+ if (Array.isArray(value) || value instanceof Y.Array) return "array";
4351
+ if (isPlainObject(value) || value instanceof Y.Map) return "map";
4352
+ return "scalar";
4353
+ };
4354
+ diffHunks = (a, b) => {
4355
+ const pairs = lcsPairs(a.map(stableStringify), b.map(stableStringify));
4356
+ const hunks = [];
4357
+ let pa = 0;
4358
+ let pb = 0;
4359
+ for (const [i, j] of [...pairs, [a.length, b.length]]) {
4360
+ if (i > pa || j > pb) hunks.push({ a0: pa, a1: i, b0: pb, b1: j });
4361
+ pa = i + 1;
4362
+ pb = j + 1;
4363
+ }
4364
+ return hunks;
4365
+ };
4366
+ alignIndexes = (base, current) => {
4367
+ const map = new Array(base.length).fill(-1);
4368
+ if (base.length === current.length && equal(base, current)) return base.map((_, i) => i);
4369
+ for (const [i, j] of lcsPairs(base.map(stableStringify), current.map(stableStringify))) map[i] = j;
4370
+ for (const hunk of diffHunks(base, current)) {
4371
+ const n = Math.min(hunk.a1 - hunk.a0, hunk.b1 - hunk.b0);
4372
+ for (let k = 0; k < n; k += 1) {
4373
+ if (kindOf(base[hunk.a0 + k]) === kindOf(current[hunk.b0 + k])) map[hunk.a0 + k] = hunk.b0 + k;
4374
+ }
3601
4375
  }
3602
- return keep;
4376
+ return map;
3603
4377
  };
3604
- syncOrder = (order, target) => {
3605
- const current = order.toArray();
3606
- if (current.length === target.length && current.every((id, i) => id === target[i])) return false;
3607
- const keep = lcsKeep(current, target);
3608
- const targetSet = new Set(target);
3609
- const keptIds = /* @__PURE__ */ new Set();
3610
- for (let i = 0; i < current.length; i += 1) {
3611
- if (!keep.has(i)) continue;
3612
- if (!targetSet.has(current[i]) || keptIds.has(current[i])) keep.delete(i);
3613
- else keptIds.add(current[i]);
4378
+ mergeValue = (current, base, local, depth) => {
4379
+ if (base !== void 0 && equal(base, local)) return "same";
4380
+ if (depth > MAX_DEPTH) return "replace";
4381
+ if (typeof local === "string" && current instanceof Y.Text) {
4382
+ applyTextEdit(current, typeof base === "string" ? base : current.toString(), local);
4383
+ return "merged";
3614
4384
  }
3615
- for (let i = current.length - 1; i >= 0; i -= 1) {
3616
- if (!keep.has(i)) order.delete(i, 1);
4385
+ if (Array.isArray(local) && current instanceof Y.Array) {
4386
+ mergeArray(current, Array.isArray(base) ? base : readShared(current, depth), local, depth);
4387
+ return "merged";
3617
4388
  }
3618
- let index = 0;
3619
- for (const id of target) {
3620
- if (keptIds.has(id)) {
3621
- index += 1;
3622
- } else {
3623
- order.insert(index, [id]);
3624
- index += 1;
4389
+ if (isPlainObject(local) && current instanceof Y.Map) {
4390
+ mergeMap(current, isPlainObject(base) ? base : readShared(current, depth), local, depth);
4391
+ return "merged";
4392
+ }
4393
+ if (!(current instanceof Y.AbstractType) && equal(readShared(current, depth), local)) return "same";
4394
+ return "replace";
4395
+ };
4396
+ mergeMap = (ymap, base, local, depth) => {
4397
+ const keys = /* @__PURE__ */ new Set([...Object.keys(base), ...Object.keys(local)]);
4398
+ for (const key of keys) {
4399
+ if (FORBIDDEN_KEYS2.has(key)) continue;
4400
+ const inLocal = hasOwn(local, key) && local[key] !== void 0;
4401
+ const inBase = hasOwn(base, key) && base[key] !== void 0;
4402
+ if (!inLocal) {
4403
+ if (inBase && ymap.has(key)) ymap.delete(key);
4404
+ continue;
3625
4405
  }
4406
+ const result = mergeValue(ymap.get(key), inBase ? base[key] : void 0, local[key], depth + 1);
4407
+ if (result === "replace") ymap.set(key, toShared(local[key], depth + 1));
3626
4408
  }
3627
- return true;
3628
4409
  };
3629
- applyEditorDataToDoc = (doc, data, origin = "local") => {
3630
- const { meta, order, blocks } = getTypes(doc);
3631
- let changed = false;
3632
- doc.transact(() => {
3633
- if (meta.get("schema") !== YDOC_SCHEMA) meta.set("schema", YDOC_SCHEMA);
3634
- const ids = [];
3635
- const seen = /* @__PURE__ */ new Set();
3636
- for (const block of data.blocks || []) {
3637
- if (!block || typeof block.id !== "string" || seen.has(block.id)) continue;
3638
- seen.add(block.id);
3639
- ids.push(block.id);
3640
- let entry = blocks.get(block.id);
3641
- if (!(entry instanceof Y.Map)) {
3642
- entry = new Y.Map();
3643
- blocks.set(block.id, entry);
3644
- changed = true;
3645
- }
3646
- if (entry.get("type") !== block.type) {
3647
- entry.set("type", block.type);
3648
- changed = true;
3649
- }
3650
- const tunes = isPlainObject(block.tunes) ? block.tunes : {};
3651
- if (stableStringify(entry.get("tunes") || {}) !== stableStringify(tunes)) {
3652
- entry.set("tunes", tunes);
3653
- changed = true;
3654
- }
3655
- changed = writeData(entry, isPlainObject(block.data) ? block.data : {}) || changed;
4410
+ mergeArray = (yarray, base, local, depth) => {
4411
+ if (equal(base, local)) return;
4412
+ const raw = yarray.toArray();
4413
+ const current = raw.map((item) => readShared(item, depth + 1));
4414
+ const target = alignIndexes(base, current);
4415
+ const ops = [];
4416
+ for (const hunk of diffHunks(base, local)) {
4417
+ const n = Math.min(hunk.a1 - hunk.a0, hunk.b1 - hunk.b0);
4418
+ for (let k = 0; k < n; k += 1) {
4419
+ const bi = hunk.a0 + k;
4420
+ if (target[bi] >= 0)
4421
+ ops.push({ at: target[bi], rank: 0, kind: "modify", bi, value: local[hunk.b0 + k] });
3656
4422
  }
3657
- changed = syncOrder(order, ids) || changed;
3658
- if (changed) {
3659
- if (data.time && meta.get("time") !== data.time) meta.set("time", data.time);
3660
- if (data.version && meta.get("version") !== data.version) meta.set("version", data.version);
4423
+ for (let bi = hunk.a0 + n; bi < hunk.a1; bi += 1) {
4424
+ if (target[bi] >= 0) ops.push({ at: target[bi], rank: 0, kind: "delete" });
4425
+ }
4426
+ if (hunk.b1 - hunk.b0 > n) {
4427
+ let at = 0;
4428
+ for (let bi = hunk.a0 + n - 1; bi >= 0; bi -= 1) {
4429
+ if (target[bi] >= 0) {
4430
+ at = target[bi] + 1;
4431
+ break;
4432
+ }
4433
+ }
4434
+ ops.push({ at, rank: 1, order: hunk.b0, kind: "insert", values: local.slice(hunk.b0 + n, hunk.b1) });
3661
4435
  }
3662
- }, origin);
3663
- return changed;
3664
- };
3665
- applyTextEdit = (ytext, base, local) => {
3666
- if (base === local) return false;
3667
- const shared = ytext.toString();
3668
- if (shared === base) return applyTextDiff(ytext, local);
3669
- let start = 0;
3670
- while (start < base.length && start < local.length && base.charCodeAt(start) === local.charCodeAt(start))
3671
- start += 1;
3672
- let endBase = base.length;
3673
- let endLocal = local.length;
3674
- while (endBase > start && endLocal > start && base.charCodeAt(endBase - 1) === local.charCodeAt(endLocal - 1)) {
3675
- endBase -= 1;
3676
- endLocal -= 1;
3677
4436
  }
3678
- let rp = 0;
3679
- while (rp < base.length && rp < shared.length && base.charCodeAt(rp) === shared.charCodeAt(rp)) rp += 1;
3680
- let rsBase = base.length;
3681
- let rsShared = shared.length;
3682
- while (rsBase > rp && rsShared > rp && base.charCodeAt(rsBase - 1) === shared.charCodeAt(rsShared - 1)) {
3683
- rsBase -= 1;
3684
- rsShared -= 1;
4437
+ ops.sort((x, y) => y.at - x.at || x.rank - y.rank || (y.order || 0) - (x.order || 0));
4438
+ for (const op of ops) {
4439
+ if (op.kind === "insert") {
4440
+ yarray.insert(
4441
+ Math.min(op.at, yarray.length),
4442
+ op.values.map((value) => toShared(value, depth + 1))
4443
+ );
4444
+ } else if (op.kind === "delete") {
4445
+ yarray.delete(op.at, 1);
4446
+ } else {
4447
+ const result = mergeValue(raw[op.at], base[op.bi], op.value, depth + 1);
4448
+ if (result === "replace") {
4449
+ yarray.delete(op.at, 1);
4450
+ yarray.insert(op.at, [toShared(op.value, depth + 1)]);
4451
+ }
4452
+ }
3685
4453
  }
3686
- const shift = shared.length - base.length;
3687
- const map = (index) => index <= rp ? index : index >= rsBase ? index + shift : Math.min(index + shift, shared.length);
3688
- const from = map(start);
3689
- const to = Math.max(from, map(endBase));
3690
- if (to > from) ytext.delete(from, Math.min(to, shared.length) - from);
3691
- const inserted = local.slice(start, endLocal);
3692
- if (inserted) ytext.insert(Math.min(from, ytext.length), inserted);
3693
- return true;
3694
4454
  };
4455
+ mergeSlot = (ymap, key, base, local, depth) => {
4456
+ const result = mergeValue(ymap.get(key), base, local, depth);
4457
+ if (result === "replace") ymap.set(key, toShared(local, depth));
4458
+ return result !== "same";
4459
+ };
4460
+ createEntry = (block) => new Y.Map([
4461
+ ["type", block.type],
4462
+ ["tunes", toShared(isPlainObject(block.tunes) ? block.tunes : {}, 2)],
4463
+ ["data", toShared(isPlainObject(block.data) ? block.data : {}, 2)]
4464
+ ]);
3695
4465
  applyLocalChanges = (doc, base, local, origin = "local") => {
3696
4466
  const { meta, order, blocks } = getTypes(doc);
3697
4467
  const baseById = new Map((base.blocks || []).map((block) => [block.id, block]));
3698
- const localIds = (local.blocks || []).map((block) => block.id);
3699
- const localSet = new Set(localIds);
4468
+ const localBlocks = [];
4469
+ const localSet = /* @__PURE__ */ new Set();
4470
+ for (const block of local.blocks || []) {
4471
+ if (!block || typeof block.id !== "string" || typeof block.type !== "string" || localSet.has(block.id))
4472
+ continue;
4473
+ localSet.add(block.id);
4474
+ localBlocks.push(block);
4475
+ }
4476
+ const localIds = localBlocks.map((block) => block.id);
3700
4477
  let changed = false;
3701
4478
  doc.transact(() => {
3702
4479
  if (meta.get("schema") !== YDOC_SCHEMA) meta.set("schema", YDOC_SCHEMA);
@@ -3711,7 +4488,7 @@ var init_ydoc = __esm({
3711
4488
  }
3712
4489
  }
3713
4490
  const baseIds = (base.blocks || []).map((block) => block.id).filter((id) => localSet.has(id));
3714
- const keep = lcsKeepIds(baseIds, localIds);
4491
+ const keep = new Set(lcsPairs(baseIds, localIds).map(([i]) => baseIds[i]));
3715
4492
  localIds.forEach((id, index) => {
3716
4493
  if (baseById.has(id) && keep.has(id)) return;
3717
4494
  const current = order.toArray();
@@ -3730,73 +4507,48 @@ var init_ydoc = __esm({
3730
4507
  order.insert(position, [id]);
3731
4508
  changed = true;
3732
4509
  });
3733
- for (const block of local.blocks || []) {
4510
+ for (const block of localBlocks) {
3734
4511
  const before = baseById.get(block.id);
3735
- let entry = blocks.get(block.id);
4512
+ const entry = blocks.get(block.id);
3736
4513
  if (!(entry instanceof Y.Map)) {
3737
- entry = new Y.Map();
3738
- blocks.set(block.id, entry);
3739
- entry.set("type", block.type);
3740
- entry.set("tunes", isPlainObject(block.tunes) ? block.tunes : {});
3741
- writeData(entry, isPlainObject(block.data) ? block.data : {});
4514
+ blocks.set(block.id, createEntry(block));
3742
4515
  changed = true;
3743
4516
  continue;
3744
4517
  }
3745
- if (!before) {
3746
- changed = writeData(entry, isPlainObject(block.data) ? block.data : {}) || changed;
3747
- continue;
3748
- }
3749
- if (before.type !== block.type) {
4518
+ const reference = before || readBlock(block.id, entry) || { type: block.type, data: {}, tunes: {} };
4519
+ if (entry.get("type") !== block.type && reference.type !== block.type) {
3750
4520
  entry.set("type", block.type);
4521
+ entry.set("data", toShared(isPlainObject(block.data) ? block.data : {}, 2));
3751
4522
  changed = true;
3752
- }
3753
- if (stableStringify(before.tunes || {}) !== stableStringify(block.tunes || {})) {
3754
- entry.set("tunes", isPlainObject(block.tunes) ? block.tunes : {});
3755
- changed = true;
3756
- }
3757
- let dataMap = entry.get("data");
3758
- if (!(dataMap instanceof Y.Map)) {
3759
- dataMap = new Y.Map();
3760
- entry.set("data", dataMap);
3761
- }
3762
- const baseData = isPlainObject(before.data) ? before.data : {};
3763
- const localData = isPlainObject(block.data) ? block.data : {};
3764
- for (const key of /* @__PURE__ */ new Set([...Object.keys(baseData), ...Object.keys(localData)])) {
3765
- const a = baseData[key];
3766
- const b = localData[key];
3767
- if (stableStringify(a) === stableStringify(b)) continue;
3768
- changed = true;
3769
- if (!(key in localData)) {
3770
- dataMap.delete(key);
3771
- } else if (typeof b === "string") {
3772
- const current = dataMap.get(key);
3773
- if (current instanceof Y.Text)
3774
- applyTextEdit(current, typeof a === "string" ? a : current.toString(), b);
3775
- else {
3776
- const text = new Y.Text();
3777
- dataMap.set(key, text);
3778
- text.insert(0, b);
3779
- }
3780
- } else {
3781
- dataMap.set(key, b === void 0 ? null : b);
4523
+ } else {
4524
+ if (!before && entry.get("type") !== block.type) {
4525
+ entry.set("type", block.type);
4526
+ changed = true;
3782
4527
  }
4528
+ changed = mergeSlot(entry, "data", reference.data || {}, isPlainObject(block.data) ? block.data : {}, 2) || changed;
3783
4529
  }
4530
+ changed = mergeSlot(entry, "tunes", reference.tunes || {}, isPlainObject(block.tunes) ? block.tunes : {}, 2) || changed;
4531
+ }
4532
+ if (changed) {
4533
+ if (local.time && meta.get("time") !== local.time) meta.set("time", local.time);
4534
+ if (local.version && meta.get("version") !== local.version) meta.set("version", local.version);
3784
4535
  }
3785
- if (changed && local.time) meta.set("time", local.time);
3786
4536
  }, origin);
3787
4537
  return changed;
3788
4538
  };
3789
- lcsKeepIds = (a, b) => {
3790
- const indexes = lcsKeep(a, b);
3791
- return new Set(Array.from(indexes).map((i) => a[i]));
3792
- };
3793
- createSeedUpdate = (data) => {
4539
+ applyEditorDataToDoc = (doc, data, origin = "local") => applyLocalChanges(doc, docToEditorData(doc), data, origin);
4540
+ createSeedUpdate = (data, epoch) => {
3794
4541
  const doc = new Y.Doc();
3795
4542
  applyEditorDataToDoc(doc, data, "seed");
4543
+ if (epoch) doc.getMap("meta").set("epoch", epoch);
3796
4544
  const update = Y.encodeStateAsUpdate(doc);
3797
4545
  doc.destroy();
3798
4546
  return update;
3799
4547
  };
4548
+ epochOf = (doc) => {
4549
+ const epoch = doc.getMap("meta").get("epoch");
4550
+ return typeof epoch === "string" ? epoch.slice(0, 64) : "";
4551
+ };
3800
4552
  legacyStateToEditorData = (update) => {
3801
4553
  const doc = new Y.Doc();
3802
4554
  try {
@@ -4036,32 +4788,256 @@ var require_history2 = __commonJS({
4036
4788
  }
4037
4789
  });
4038
4790
 
4791
+ // shared/ydoc-guard.mjs
4792
+ var ydoc_guard_exports = {};
4793
+ __export(ydoc_guard_exports, {
4794
+ applyCheckedUpdate: () => applyCheckedUpdate,
4795
+ inspectUpdate: () => inspectUpdate,
4796
+ touchedBy: () => touchedBy,
4797
+ validateTouched: () => validateTouched
4798
+ });
4799
+ import * as Y2 from "yjs";
4800
+ var ROOTS, FORBIDDEN_KEYS3, BLOCK_ID_PATTERN2, BLOCK_TYPE_PATTERN2, META_KEYS, MAX_KEY_LENGTH, MAX_BLOCK_BYTES, safeAny, inspectUpdate, rootName, touchedBy, validateTouched, applyCheckedUpdate;
4801
+ var init_ydoc_guard = __esm({
4802
+ "shared/ydoc-guard.mjs"() {
4803
+ init_editor_data();
4804
+ init_ydoc();
4805
+ ROOTS = /* @__PURE__ */ new Set(["meta", "order", "blocks"]);
4806
+ FORBIDDEN_KEYS3 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
4807
+ BLOCK_ID_PATTERN2 = /^[A-Za-z0-9_-]{1,64}$/;
4808
+ BLOCK_TYPE_PATTERN2 = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
4809
+ META_KEYS = { schema: "number", time: "number", version: "string", epoch: "string" };
4810
+ MAX_KEY_LENGTH = 128;
4811
+ MAX_BLOCK_BYTES = 1024 * 1024;
4812
+ safeAny = (value, depth = 0) => {
4813
+ if (depth > EDITOR_DATA_LIMITS.maxDepth) return false;
4814
+ if (value === null || ["string", "boolean"].includes(typeof value)) return true;
4815
+ if (typeof value === "number") return Number.isFinite(value);
4816
+ if (Array.isArray(value)) return value.every((item) => safeAny(item, depth + 1));
4817
+ if (typeof value === "object") {
4818
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
4819
+ return false;
4820
+ return Object.keys(value).every(
4821
+ (key) => !FORBIDDEN_KEYS3.has(key) && key.length <= MAX_KEY_LENGTH && safeAny(value[key], depth + 1)
4822
+ );
4823
+ }
4824
+ return false;
4825
+ };
4826
+ inspectUpdate = (update, stateVector) => {
4827
+ let decoded;
4828
+ try {
4829
+ decoded = Y2.decodeUpdate(update);
4830
+ } catch {
4831
+ return { ok: false, code: "INVALID_UPDATE" };
4832
+ }
4833
+ const { structs, ds } = decoded;
4834
+ const known = (client) => stateVector.get(client) || 0;
4835
+ const covered = /* @__PURE__ */ new Map();
4836
+ for (const struct of structs) {
4837
+ const { client, clock } = struct.id;
4838
+ const range = covered.get(client);
4839
+ if (!range) covered.set(client, { start: clock, end: clock + struct.length });
4840
+ else range.end = Math.max(range.end, clock + struct.length);
4841
+ }
4842
+ for (const [client, range] of covered)
4843
+ if (range.start > known(client)) return { ok: false, code: "MISSING_DEPENDENCY" };
4844
+ const exists = (id) => {
4845
+ if (!id) return true;
4846
+ if (id.clock < known(id.client)) return true;
4847
+ const range = covered.get(id.client);
4848
+ return Boolean(range && id.clock >= range.start && id.clock < range.end);
4849
+ };
4850
+ for (const struct of structs) {
4851
+ if (struct instanceof Y2.GC || struct instanceof Y2.Skip) {
4852
+ if (struct instanceof Y2.Skip && struct.id.clock + struct.length > known(struct.id.client))
4853
+ return { ok: false, code: "MISSING_DEPENDENCY" };
4854
+ continue;
4855
+ }
4856
+ if (!(struct instanceof Y2.Item)) return { ok: false, code: "INVALID_UPDATE" };
4857
+ if (!exists(struct.origin) || !exists(struct.rightOrigin))
4858
+ return { ok: false, code: "MISSING_DEPENDENCY" };
4859
+ if (typeof struct.parent === "string") {
4860
+ if (!ROOTS.has(struct.parent)) return { ok: false, code: "INVALID_UPDATE" };
4861
+ } else if (struct.parent && !exists(struct.parent)) return { ok: false, code: "MISSING_DEPENDENCY" };
4862
+ if (struct.parentSub !== null && struct.parentSub !== void 0) {
4863
+ const key = struct.parentSub;
4864
+ if (typeof key !== "string" || key.length > MAX_KEY_LENGTH || FORBIDDEN_KEYS3.has(key))
4865
+ return { ok: false, code: "INVALID_UPDATE" };
4866
+ if (struct.parent === "blocks" && !BLOCK_ID_PATTERN2.test(key))
4867
+ return { ok: false, code: "INVALID_UPDATE" };
4868
+ if (struct.parent === "meta" && !Object.prototype.hasOwnProperty.call(META_KEYS, key))
4869
+ return { ok: false, code: "INVALID_UPDATE" };
4870
+ }
4871
+ const content = struct.content;
4872
+ if (content instanceof Y2.ContentString || content instanceof Y2.ContentDeleted) continue;
4873
+ if (content instanceof Y2.ContentAny) {
4874
+ if (!content.arr.every((value) => safeAny(value))) return { ok: false, code: "INVALID_UPDATE" };
4875
+ continue;
4876
+ }
4877
+ if (content instanceof Y2.ContentType) {
4878
+ const type = content.type;
4879
+ if (type instanceof Y2.XmlElement || type instanceof Y2.XmlFragment || type instanceof Y2.XmlText || type instanceof Y2.XmlHook)
4880
+ return { ok: false, code: "INVALID_UPDATE" };
4881
+ if (!(type instanceof Y2.Map || type instanceof Y2.Array || type instanceof Y2.Text))
4882
+ return { ok: false, code: "INVALID_UPDATE" };
4883
+ continue;
4884
+ }
4885
+ return { ok: false, code: "INVALID_UPDATE" };
4886
+ }
4887
+ for (const [client, deletes] of ds.clients) {
4888
+ for (const item of deletes) {
4889
+ const end = item.clock + item.len;
4890
+ const range = covered.get(client);
4891
+ if (end > known(client) && !(range && end <= range.end))
4892
+ return { ok: false, code: "MISSING_DEPENDENCY" };
4893
+ }
4894
+ }
4895
+ return { ok: true };
4896
+ };
4897
+ rootName = (type) => {
4898
+ try {
4899
+ return Y2.findRootTypeKey(type);
4900
+ } catch {
4901
+ return "";
4902
+ }
4903
+ };
4904
+ touchedBy = (transaction, blocks) => {
4905
+ const ids = /* @__PURE__ */ new Set();
4906
+ let order = false;
4907
+ let meta = false;
4908
+ transaction.changed.forEach((keys, type) => {
4909
+ let current = type;
4910
+ let guard = 0;
4911
+ let child = null;
4912
+ while (current && current._item && guard < 4096) {
4913
+ child = current._item;
4914
+ current = current._item.parent;
4915
+ guard += 1;
4916
+ }
4917
+ const root = current === blocks ? "blocks" : rootName(current);
4918
+ if (root === "blocks") {
4919
+ if (child) ids.add(child.parentSub);
4920
+ else keys.forEach((key) => key && ids.add(key));
4921
+ } else if (root === "order") order = true;
4922
+ else meta = true;
4923
+ });
4924
+ return { ids, order, meta };
4925
+ };
4926
+ validateTouched = (doc, touched) => {
4927
+ const blocks = doc.getMap("blocks");
4928
+ if (blocks.size > EDITOR_DATA_LIMITS.maxBlocks * 4) return "TOO_MANY_BLOCKS";
4929
+ for (const id of touched.ids) {
4930
+ if (!BLOCK_ID_PATTERN2.test(id)) return "INVALID_BLOCK";
4931
+ const entry = blocks.get(id);
4932
+ if (entry === void 0) continue;
4933
+ if (!(entry instanceof Y2.Map)) return "INVALID_BLOCK";
4934
+ for (const key of entry.keys()) if (!["type", "data", "tunes"].includes(key)) return "INVALID_BLOCK";
4935
+ const type = entry.get("type");
4936
+ if (type !== void 0 && (typeof type !== "string" || !BLOCK_TYPE_PATTERN2.test(type)))
4937
+ return "INVALID_BLOCK";
4938
+ const data = entry.get("data");
4939
+ if (data !== void 0 && !(data instanceof Y2.Map) && (data === null || typeof data !== "object"))
4940
+ return "INVALID_BLOCK";
4941
+ if (type === void 0) continue;
4942
+ const block = readBlock(id, entry);
4943
+ if (!block) return "INVALID_BLOCK";
4944
+ try {
4945
+ if (JSON.stringify(block).length > MAX_BLOCK_BYTES) return "TOO_LARGE";
4946
+ const normalized = normalizeEditorData({ blocks: [block] });
4947
+ if (!normalized || normalized.blocks.length !== 1) return "INVALID_BLOCK";
4948
+ } catch (error) {
4949
+ return error && error.code || "INVALID_BLOCK";
4950
+ }
4951
+ }
4952
+ if (touched.order) {
4953
+ const order = doc.getArray("order");
4954
+ if (order.length > EDITOR_DATA_LIMITS.maxBlocks * 2) return "TOO_MANY_BLOCKS";
4955
+ const unique2 = /* @__PURE__ */ new Set();
4956
+ for (const id of order.toArray()) {
4957
+ if (typeof id !== "string" || !BLOCK_ID_PATTERN2.test(id)) return "INVALID_ORDER";
4958
+ unique2.add(id);
4959
+ }
4960
+ if (unique2.size > EDITOR_DATA_LIMITS.maxBlocks) return "TOO_MANY_BLOCKS";
4961
+ }
4962
+ if (touched.meta) {
4963
+ const meta = doc.getMap("meta");
4964
+ for (const [key, kind] of Object.entries(META_KEYS)) {
4965
+ const value = meta.get(key);
4966
+ if (value === void 0) continue;
4967
+ if (typeof value !== kind) return "INVALID_META";
4968
+ if (kind === "string" && value.length > 64) return "INVALID_META";
4969
+ }
4970
+ }
4971
+ return null;
4972
+ };
4973
+ applyCheckedUpdate = (doc, update) => {
4974
+ const inspected = inspectUpdate(update, Y2.decodeStateVector(Y2.encodeStateVector(doc)));
4975
+ if (!inspected.ok) return { ok: false, code: inspected.code, dirty: false };
4976
+ let touched = { ids: /* @__PURE__ */ new Set(), order: false, meta: false };
4977
+ let changed = false;
4978
+ const blocks = doc.getMap("blocks");
4979
+ doc.getMap("meta");
4980
+ doc.getArray("order");
4981
+ const listener = (transaction) => {
4982
+ const next = touchedBy(transaction, blocks);
4983
+ next.ids.forEach((id) => touched.ids.add(id));
4984
+ touched = { ids: touched.ids, order: touched.order || next.order, meta: touched.meta || next.meta };
4985
+ if (transaction.changed.size > 0 || transaction.deleteSet.clients.size > 0) changed = true;
4986
+ };
4987
+ doc.on("afterTransaction", listener);
4988
+ try {
4989
+ Y2.applyUpdate(doc, update, "checked");
4990
+ } catch {
4991
+ return { ok: false, code: "INVALID_UPDATE", dirty: true };
4992
+ } finally {
4993
+ doc.off("afterTransaction", listener);
4994
+ }
4995
+ const store = doc.store;
4996
+ if (store.pendingStructs || store.pendingDs) return { ok: false, code: "MISSING_DEPENDENCY", dirty: true };
4997
+ const error = validateTouched(doc, touched);
4998
+ if (error) return { ok: false, code: error, dirty: true };
4999
+ return { ok: true, changed };
5000
+ };
5001
+ }
5002
+ });
5003
+
4039
5004
  // server/src/services/collaboration.js
4040
5005
  var require_collaboration2 = __commonJS({
4041
5006
  "server/src/services/collaboration.js"(exports, module) {
4042
5007
  "use strict";
4043
5008
  var { randomUUID } = __require("node:crypto");
4044
5009
  var { Server } = __require("socket.io");
4045
- var Y2 = __require("yjs");
5010
+ var Y3 = __require("yjs");
4046
5011
  var { errors } = __require("@strapi/utils");
4047
5012
  var { createLogger } = require_logger();
4048
5013
  var { getTokenKey, signToken, verifyToken } = require_crypto();
4049
5014
  var { cleanEditorValue } = require_sanitizer();
4050
- var { createSeedUpdate: createSeedUpdate2, docToEditorData: docToEditorData2 } = (init_ydoc(), __toCommonJS(ydoc_exports));
5015
+ var { createRateLimiter } = require_rate_limit();
5016
+ var {
5017
+ createSeedUpdate: createSeedUpdate2,
5018
+ docToEditorData: docToEditorData2,
5019
+ epochOf: epochOf2,
5020
+ getTypes: getTypes2,
5021
+ stableStringify: stableStringify2
5022
+ } = (init_ydoc(), __toCommonJS(ydoc_exports));
5023
+ var { applyCheckedUpdate: applyCheckedUpdate2 } = (init_ydoc_guard(), __toCommonJS(ydoc_guard_exports));
5024
+ var PROTOCOL = 3;
4051
5025
  var PROCESS_ID = randomUUID();
4052
5026
  var PRESENCE_TTL_MS = 3e4;
4053
5027
  var HEARTBEAT_MS = 1e4;
4054
- var REVALIDATE_MS = 5 * 60 * 1e3;
5028
+ var SIGNAL_CHECK_MS = 1e3;
4055
5029
  var RESEND_WINDOW_MS = 5e3;
4056
5030
  var COMPACT_THRESHOLD = 200;
4057
5031
  var MAX_ROOM_BYTES = 64 * 1024 * 1024;
4058
- var COLORS = ["#4945ff", "#d02b20", "#328048", "#ac5e00", "#0c75af", "#8312d1", "#b72b1a", "#2f6846"];
5032
+ var MAX_INVALID_UPDATES = 5;
5033
+ var COLORS = ["primary", "danger", "success", "warning", "secondary", "alternative"];
4059
5034
  var colorFor = (userId) => COLORS[Math.abs(Number(userId) || 0) % COLORS.length];
4060
5035
  var displayName = (user) => {
4061
- const first = (user.firstname || "").trim();
4062
- const last = (user.lastname || "").trim();
5036
+ const first = String(user.firstname || "").trim();
5037
+ const last = String(user.lastname || "").trim();
4063
5038
  const name = [first, last ? `${last[0]}.` : ""].filter(Boolean).join(" ");
4064
- return (name || user.username || "Admin").slice(0, 80);
5039
+ const username = String(user.username || "").trim();
5040
+ return (name || (username && !username.includes("@") ? username : "") || "Admin").slice(0, 80);
4065
5041
  };
4066
5042
  var toBytes = (payload, maxBytes) => {
4067
5043
  let bytes = null;
@@ -4073,13 +5049,30 @@ var require_collaboration2 = __commonJS({
4073
5049
  if (!bytes || bytes.byteLength === 0 || bytes.byteLength > maxBytes) return null;
4074
5050
  return bytes;
4075
5051
  };
4076
- var isValidUpdate = (update) => {
4077
- try {
4078
- Y2.decodeUpdate(update);
4079
- return true;
4080
- } catch {
4081
- return false;
5052
+ var cleanCursor = (cursor) => {
5053
+ if (!cursor || typeof cursor !== "object" || Array.isArray(cursor)) return null;
5054
+ const idle = cursor.idle === true;
5055
+ const offset = (value) => Number.isInteger(value) && value >= 0 ? Math.min(value, 1e7) : 0;
5056
+ if (typeof cursor.blockId === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(cursor.blockId)) {
5057
+ const anchor = offset(cursor.anchor ?? cursor.offset);
5058
+ return {
5059
+ blockId: cursor.blockId,
5060
+ anchor,
5061
+ focus: cursor.focus === void 0 ? anchor : offset(cursor.focus),
5062
+ idle
5063
+ };
4082
5064
  }
5065
+ return { idle };
5066
+ };
5067
+ var targetOfRoom = (room) => {
5068
+ const parts = String(room).split("|");
5069
+ if (parts.length !== 4) return null;
5070
+ return { uid: parts[0], documentId: parts[1], locale: parts[2] === "-" ? null : parts[2], field: parts[3] };
5071
+ };
5072
+ var handshakeError = (code) => {
5073
+ const error = new Error(code);
5074
+ error.data = { code };
5075
+ return error;
4083
5076
  };
4084
5077
  module.exports = ({ strapi }) => {
4085
5078
  const logger = createLogger(strapi);
@@ -4094,17 +5087,28 @@ var require_collaboration2 = __commonJS({
4094
5087
  const timers = [];
4095
5088
  const rooms = /* @__PURE__ */ new Map();
4096
5089
  let polling = false;
5090
+ let permissionSignal = null;
5091
+ let revalidating = null;
5092
+ const sessionLimiter = createRateLimiter({ max: 60, windowMs: 6e4 });
4097
5093
  const roomState = (room) => {
4098
5094
  let state = rooms.get(room);
4099
5095
  if (!state) {
4100
- state = { sockets: /* @__PURE__ */ new Set(), seen: /* @__PURE__ */ new Map(), watermark: 0, presenceHash: "", target: null };
5096
+ state = {
5097
+ sockets: /* @__PURE__ */ new Set(),
5098
+ seen: /* @__PURE__ */ new Map(),
5099
+ watermark: 0,
5100
+ presenceHash: "",
5101
+ target: null,
5102
+ doc: null,
5103
+ loading: null
5104
+ };
4101
5105
  rooms.set(room, state);
4102
5106
  }
4103
5107
  return state;
4104
5108
  };
4105
5109
  const loadRoom = async (room) => {
4106
5110
  const rows = await store().readRoom(room);
4107
- const update = rows.length ? Y2.mergeUpdates(rows.map((row) => row.update)) : new Uint8Array([0, 0]);
5111
+ const update = rows.length ? Y3.mergeUpdates(rows.map((row) => row.update)) : new Uint8Array([0, 0]);
4108
5112
  return {
4109
5113
  update,
4110
5114
  lastId: rows.length ? rows[rows.length - 1].id : 0,
@@ -4113,14 +5117,48 @@ var require_collaboration2 = __commonJS({
4113
5117
  };
4114
5118
  };
4115
5119
  const materialize = (update) => {
4116
- const doc = new Y2.Doc();
5120
+ const doc = new Y3.Doc();
4117
5121
  try {
4118
- Y2.applyUpdate(doc, update);
5122
+ Y3.applyUpdate(doc, update);
4119
5123
  return docToEditorData2(doc);
4120
5124
  } finally {
4121
5125
  doc.destroy();
4122
5126
  }
4123
5127
  };
5128
+ const ensureDoc = async (room) => {
5129
+ const state = roomState(room);
5130
+ if (state.doc) return state.doc;
5131
+ if (!state.loading) {
5132
+ state.loading = (async () => {
5133
+ const rows = await store().readRoom(room);
5134
+ const doc = new Y3.Doc({ gc: true });
5135
+ getTypes2(doc);
5136
+ for (const row of rows) {
5137
+ try {
5138
+ Y3.applyUpdate(doc, row.update);
5139
+ } catch {
5140
+ }
5141
+ }
5142
+ const now = Date.now();
5143
+ const settled = rows.filter((row) => (row.createdAt || 0) < now - RESEND_WINDOW_MS);
5144
+ state.watermark = Math.max(state.watermark, settled.length ? settled[settled.length - 1].id : 0);
5145
+ for (const row of rows) if (row.id > state.watermark) state.seen.set(row.id, now);
5146
+ if (state.doc) state.doc.destroy();
5147
+ state.doc = doc;
5148
+ return doc;
5149
+ })().finally(() => {
5150
+ state.loading = null;
5151
+ });
5152
+ }
5153
+ return state.loading;
5154
+ };
5155
+ const dropDoc = (room) => {
5156
+ const state = rooms.get(room);
5157
+ if (state && state.doc) {
5158
+ state.doc.destroy();
5159
+ state.doc = null;
5160
+ }
5161
+ };
4124
5162
  const ensureSeed = async (room, loadContent, ttlMs) => {
4125
5163
  const stats = await store().roomStats(room);
4126
5164
  if (stats.count > 0) return false;
@@ -4131,7 +5169,7 @@ var require_collaboration2 = __commonJS({
4131
5169
  const content = await loadContent();
4132
5170
  await store().appendUpdate(
4133
5171
  room,
4134
- createSeedUpdate2(content || { time: Date.now(), blocks: [], version: "2.31.7" }),
5172
+ createSeedUpdate2(content || { time: Date.now(), blocks: [], version: "2.31.7" }, randomUUID()),
4135
5173
  "seed"
4136
5174
  );
4137
5175
  return true;
@@ -4166,24 +5204,36 @@ var require_collaboration2 = __commonJS({
4166
5204
  const emitPresence = (room, rows) => {
4167
5205
  const state = rooms.get(room);
4168
5206
  if (!state || !io) return;
4169
- const peers = rows.map((row) => ({
4170
- id: row.id,
4171
- name: row.name,
4172
- color: row.color,
4173
- canEdit: Boolean(row.can_edit),
4174
- cursor: (() => {
4175
- try {
4176
- return row.cursor ? JSON.parse(row.cursor) : null;
4177
- } catch {
4178
- return null;
4179
- }
4180
- })()
4181
- })).sort((a, b) => a.id.localeCompare(b.id));
5207
+ const peers = rows.map((row) => {
5208
+ let cursor;
5209
+ try {
5210
+ cursor = row.cursor ? cleanCursor(JSON.parse(row.cursor)) : null;
5211
+ } catch {
5212
+ cursor = null;
5213
+ }
5214
+ return {
5215
+ id: row.id,
5216
+ name: row.name,
5217
+ color: row.color,
5218
+ canEdit: Boolean(row.can_edit),
5219
+ idle: Boolean(cursor && cursor.idle),
5220
+ cursor: cursor && cursor.blockId ? { blockId: cursor.blockId, anchor: cursor.anchor, focus: cursor.focus } : null
5221
+ };
5222
+ }).sort((a, b) => a.id.localeCompare(b.id));
4182
5223
  const hash = JSON.stringify(peers);
4183
5224
  if (hash === state.presenceHash) return;
4184
5225
  state.presenceHash = hash;
4185
5226
  io.to(room).emit("mx:presence", peers);
4186
5227
  };
5228
+ const resetRoom = (room, code) => {
5229
+ const state = rooms.get(room);
5230
+ if (!state) return;
5231
+ dropDoc(room);
5232
+ for (const socket of Array.from(state.sockets)) {
5233
+ socket.emit("mx:error", { code });
5234
+ socket.disconnect(true);
5235
+ }
5236
+ };
4187
5237
  const poll = async () => {
4188
5238
  if (polling || rooms.size === 0) return;
4189
5239
  polling = true;
@@ -4194,11 +5244,32 @@ var require_collaboration2 = __commonJS({
4194
5244
  const rows = await store().readSince(names, after, 2e3);
4195
5245
  for (const row of rows) {
4196
5246
  const state = rooms.get(row.room);
4197
- if (!state || row.id <= state.watermark) continue;
4198
- if (!state.seen.has(row.id)) {
4199
- state.seen.set(row.id, now);
4200
- if (row.kind !== "compact") io.to(row.room).emit("mx:update", row.update);
5247
+ if (!state || row.id <= state.watermark || state.seen.has(row.id)) continue;
5248
+ state.seen.set(row.id, now);
5249
+ if (row.kind === "seed" && state.doc) {
5250
+ const probe = new Y3.Doc();
5251
+ let reset = false;
5252
+ try {
5253
+ Y3.applyUpdate(probe, row.update);
5254
+ reset = epochOf2(probe) !== epochOf2(state.doc);
5255
+ } catch {
5256
+ reset = false;
5257
+ } finally {
5258
+ probe.destroy();
5259
+ }
5260
+ if (reset) {
5261
+ resetRoom(row.room, "ROOM_RESET");
5262
+ continue;
5263
+ }
4201
5264
  }
5265
+ if (state.doc) {
5266
+ try {
5267
+ Y3.applyUpdate(state.doc, row.update, "relay");
5268
+ } catch {
5269
+ dropDoc(row.room);
5270
+ }
5271
+ }
5272
+ if (row.kind !== "compact") io.to(row.room).emit("mx:update", row.update);
4202
5273
  }
4203
5274
  for (const state of rooms.values()) {
4204
5275
  for (const [id, at] of state.seen) {
@@ -4232,27 +5303,59 @@ var require_collaboration2 = __commonJS({
4232
5303
  await store().release(key, PROCESS_ID);
4233
5304
  }
4234
5305
  };
4235
- const autoSnapshot = async (room, bucketKey) => {
5306
+ const autoSnapshot = async (room, bucketKey, options = {}) => {
4236
5307
  const state = rooms.get(room);
4237
- const target = state && state.target;
5308
+ const target = state && state.target || targetOfRoom(room);
4238
5309
  if (!target) return false;
4239
5310
  const key = `snap:${room}:${bucketKey}`.slice(0, 255);
4240
5311
  if (!await store().acquire(key, PROCESS_ID, 24 * 60 * 60 * 1e3)) return false;
4241
- const { update, count } = await loadRoom(room);
4242
- if (count === 0) return false;
4243
- const result = await history().create(target, materialize(update), { trigger: "auto", userId: null });
4244
- return result.created;
5312
+ try {
5313
+ const { update, count } = await loadRoom(room);
5314
+ if (count === 0) return false;
5315
+ const content = materialize(update);
5316
+ if (options.skipWhenSaved) {
5317
+ const rawHtml = strapi.config.get("plugin::magic-editor-x.rawHtml") || "sanitize";
5318
+ const clean = (value) => {
5319
+ try {
5320
+ return cleanEditorValue(value, { rawHtml });
5321
+ } catch {
5322
+ return null;
5323
+ }
5324
+ };
5325
+ const blocksOf = (value) => stableStringify2(value && Array.isArray(value.blocks) ? value.blocks : []);
5326
+ let saved = null;
5327
+ try {
5328
+ saved = clean(await readStoredValue(target));
5329
+ } catch {
5330
+ saved = null;
5331
+ }
5332
+ if (blocksOf(saved) === blocksOf(clean(content))) return false;
5333
+ }
5334
+ const result = await history().create(target, content, { trigger: "auto", userId: null });
5335
+ return result.created;
5336
+ } catch (error) {
5337
+ await store().release(key, PROCESS_ID).catch(() => {
5338
+ });
5339
+ throw error;
5340
+ }
4245
5341
  };
4246
5342
  const snapshotTick = async () => {
4247
5343
  const minutes = Number(conf("snapshotIntervalMinutes", 10));
4248
5344
  if (!minutes) return;
4249
- const bucket = Math.floor(Date.now() / (minutes * 6e4));
5345
+ const length = minutes * 6e4;
5346
+ const bucket = Math.floor(Date.now() / length);
4250
5347
  for (const [room, state] of rooms) {
4251
- if (state.sockets.size === 0 || state.lastBucket === bucket) continue;
4252
- state.lastBucket = bucket;
5348
+ if (state.sockets.size === 0) continue;
5349
+ if (state.lastBucket === void 0) {
5350
+ state.lastBucket = bucket;
5351
+ continue;
5352
+ }
5353
+ if (state.lastBucket === bucket) continue;
5354
+ const previous = bucket - 1;
4253
5355
  try {
4254
5356
  const stats = await store().roomStats(room);
4255
- if (stats.lastAt > Date.now() - minutes * 6e4) await autoSnapshot(room, `t${bucket}`);
5357
+ if (stats.lastAt >= previous * length) await autoSnapshot(room, `t${previous}`);
5358
+ state.lastBucket = bucket;
4256
5359
  } catch (error) {
4257
5360
  logger.warn("automatic snapshot failed", { code: error && error.code, name: error && error.name });
4258
5361
  }
@@ -4267,10 +5370,21 @@ var require_collaboration2 = __commonJS({
4267
5370
  if (await store().acquire("maintenance", PROCESS_ID, 55e3)) {
4268
5371
  await store().prunePresence(Date.now() - PRESENCE_TTL_MS * 2);
4269
5372
  await store().pruneLocks();
5373
+ await store().pruneCounters();
4270
5374
  const ttl = Number(conf("roomTtlMinutes", 30)) * 6e4;
4271
5375
  for (const room of await store().staleRooms(Date.now() - ttl)) {
4272
- if (!await store().hasPresence(room, Date.now() - PRESENCE_TTL_MS))
4273
- await store().deleteRoom(room);
5376
+ if (await store().hasPresence(room, Date.now() - PRESENCE_TTL_MS)) continue;
5377
+ try {
5378
+ const stats = await store().roomStats(room);
5379
+ await autoSnapshot(room, `end${stats.lastId}`, { skipWhenSaved: true });
5380
+ } catch (error) {
5381
+ logger.warn("final version before room clean-up failed", {
5382
+ code: error && error.code,
5383
+ name: error && error.name
5384
+ });
5385
+ continue;
5386
+ }
5387
+ await store().deleteRoom(room);
4274
5388
  }
4275
5389
  }
4276
5390
  } catch (error) {
@@ -4281,21 +5395,50 @@ var require_collaboration2 = __commonJS({
4281
5395
  }
4282
5396
  };
4283
5397
  const revalidate = async () => {
4284
- for (const state of rooms.values()) {
4285
- for (const socket of state.sockets) {
4286
- try {
4287
- const ability = await access().abilityForUser(socket.data.userId);
4288
- if (!ability) throw new errors.NotFoundError("gone");
4289
- const result = await access().checkField({ userAbility: ability, ...socket.data.target });
4290
- if (result.canUpdate !== socket.data.canEdit) {
4291
- socket.data.canEdit = result.canUpdate;
4292
- socket.emit("mx:role", { canEdit: result.canUpdate });
5398
+ if (revalidating) return revalidating;
5399
+ revalidating = (async () => {
5400
+ const abilities = /* @__PURE__ */ new Map();
5401
+ for (const state of Array.from(rooms.values())) {
5402
+ for (const socket of Array.from(state.sockets)) {
5403
+ try {
5404
+ const userId = socket.data.userId;
5405
+ if (!abilities.has(userId)) abilities.set(userId, await access().abilityForUser(userId));
5406
+ const ability = abilities.get(userId);
5407
+ if (!ability) throw new errors.NotFoundError("gone");
5408
+ const result = await access().checkField({ userAbility: ability, ...socket.data.target });
5409
+ if (result.canUpdate !== socket.data.canEdit) {
5410
+ socket.data.canEdit = result.canUpdate;
5411
+ socket.emit("mx:role", { canEdit: result.canUpdate });
5412
+ store().upsertPresence({
5413
+ id: socket.data.presenceId,
5414
+ room: socket.data.room,
5415
+ userId,
5416
+ name: socket.data.name,
5417
+ color: socket.data.color,
5418
+ canEdit: result.canUpdate,
5419
+ cursor: socket.data.cursor
5420
+ }).catch(() => {
5421
+ });
5422
+ }
5423
+ } catch {
5424
+ socket.emit("mx:error", { code: "ACCESS_REVOKED" });
5425
+ socket.disconnect(true);
4293
5426
  }
4294
- } catch {
4295
- socket.emit("mx:error", { code: "ACCESS_REVOKED" });
4296
- socket.disconnect(true);
4297
5427
  }
4298
5428
  }
5429
+ })().finally(() => {
5430
+ revalidating = null;
5431
+ });
5432
+ return revalidating;
5433
+ };
5434
+ const signalTick = async () => {
5435
+ try {
5436
+ const value = await store().getSignal("permissions");
5437
+ const changed = permissionSignal !== null && value !== permissionSignal;
5438
+ permissionSignal = value;
5439
+ if (changed && rooms.size > 0) await revalidate();
5440
+ } catch (error) {
5441
+ logger.warn("permission signal check failed", { code: error && error.code, name: error && error.name });
4299
5442
  }
4300
5443
  };
4301
5444
  const originAllowed = (req) => {
@@ -4315,46 +5458,69 @@ var require_collaboration2 = __commonJS({
4315
5458
  for (const value of conf("allowedOrigins", []) || []) allowed.add(String(value).replace(/\/+$/, ""));
4316
5459
  return allowed.has(origin);
4317
5460
  };
5461
+ const authenticate = async (socket, next) => {
5462
+ try {
5463
+ const auth = socket.handshake.auth || {};
5464
+ if (auth.protocol !== PROTOCOL) return next(handshakeError("UPGRADE_REQUIRED"));
5465
+ const claims = verifyToken(auth.token, getTokenKey(strapi));
5466
+ if (!claims || typeof claims.nonce !== "string" || claims.protocol !== PROTOCOL)
5467
+ return next(handshakeError("INVALID_TOKEN"));
5468
+ const fresh = await store().acquire(
5469
+ `tok:${claims.nonce}`,
5470
+ PROCESS_ID,
5471
+ Math.max(1e3, claims.exp - Date.now() + 6e4)
5472
+ );
5473
+ if (!fresh) return next(handshakeError("INVALID_TOKEN"));
5474
+ const usage = await store().presenceOfUser(claims.userId, Date.now() - PRESENCE_TTL_MS);
5475
+ if (usage.sockets >= Number(conf("maxConnectionsPerAdmin", 20)))
5476
+ return next(handshakeError("TOO_MANY_CONNECTIONS"));
5477
+ if (!usage.rooms.has(claims.room) && usage.rooms.size >= Number(conf("maxRoomsPerAdmin", 20)))
5478
+ return next(handshakeError("TOO_MANY_CONNECTIONS"));
5479
+ socket.data.claims = claims;
5480
+ return next();
5481
+ } catch (error) {
5482
+ logger.warn("collaboration handshake failed", { code: error && error.code, name: error && error.name });
5483
+ return next(handshakeError("UNAVAILABLE"));
5484
+ }
5485
+ };
4318
5486
  const onConnection = async (socket) => {
4319
5487
  const maxBytes = Number(conf("maxMessageBytes", 2 * 1024 * 1024));
4320
- const claims = verifyToken(socket.handshake.auth && socket.handshake.auth.token, getTokenKey(strapi));
4321
- if (!claims || typeof claims.nonce !== "string") {
4322
- socket.emit("mx:error", { code: "INVALID_TOKEN" });
4323
- socket.disconnect(true);
4324
- return;
4325
- }
4326
- const fresh = await store().acquire(
4327
- `tok:${claims.nonce}`,
4328
- PROCESS_ID,
4329
- Math.max(1e3, claims.exp - Date.now() + 6e4)
4330
- );
4331
- if (!fresh) {
4332
- socket.emit("mx:error", { code: "INVALID_TOKEN" });
4333
- socket.disconnect(true);
4334
- return;
4335
- }
5488
+ const claims = socket.data.claims;
4336
5489
  const room = claims.room;
4337
5490
  socket.data.userId = claims.userId;
4338
5491
  socket.data.canEdit = claims.canEdit === true;
4339
5492
  socket.data.target = claims.target;
5493
+ socket.data.room = room;
5494
+ socket.data.name = claims.name;
5495
+ socket.data.color = claims.color;
5496
+ socket.data.cursor = null;
4340
5497
  socket.data.presenceId = randomUUID();
4341
5498
  const state = roomState(room);
4342
5499
  state.target = claims.target;
4343
- await socket.join(room);
4344
5500
  state.sockets.add(socket);
5501
+ await socket.join(room);
5502
+ const rate = conf("rateLimit", {}) || {};
5503
+ const updates = createRateLimiter({
5504
+ max: Number(rate.updatesPer10s) || 300,
5505
+ windowMs: 1e4,
5506
+ maxKeys: 4
5507
+ });
5508
+ const bytesWindow = { start: Date.now(), bytes: 0 };
5509
+ const maxBytesPer10s = Number(rate.bytesPer10s) || 8 * 1024 * 1024;
5510
+ let invalid = 0;
5511
+ let lastResyncAt = 0;
5512
+ let lastCursorAt = 0;
4345
5513
  const sendSync = async (clientVector) => {
4346
- const { update, lastId } = await loadRoom(room);
4347
- if (state.watermark === 0) state.watermark = lastId;
4348
- let payload = update;
4349
- if (clientVector) {
4350
- try {
4351
- payload = Y2.diffUpdate(update, clientVector);
4352
- } catch {
4353
- payload = update;
4354
- }
5514
+ const doc2 = await ensureDoc(room);
5515
+ let payload;
5516
+ try {
5517
+ payload = clientVector ? Y3.encodeStateAsUpdate(doc2, clientVector) : Y3.encodeStateAsUpdate(doc2);
5518
+ } catch {
5519
+ payload = Y3.encodeStateAsUpdate(doc2);
4355
5520
  }
4356
- socket.emit("mx:sync", { update: payload, stateVector: Y2.encodeStateVectorFromUpdate(update) });
5521
+ socket.emit("mx:sync", { update: payload, stateVector: Y3.encodeStateVector(doc2), epoch: epochOf2(doc2) });
4357
5522
  };
5523
+ const doc = await ensureDoc(room);
4358
5524
  await store().upsertPresence({
4359
5525
  id: socket.data.presenceId,
4360
5526
  room,
@@ -4366,7 +5532,10 @@ var require_collaboration2 = __commonJS({
4366
5532
  socket.emit("mx:welcome", {
4367
5533
  canEdit: socket.data.canEdit,
4368
5534
  presenceId: socket.data.presenceId,
4369
- color: claims.color
5535
+ color: claims.color,
5536
+ name: claims.name,
5537
+ epoch: epochOf2(doc),
5538
+ protocol: PROTOCOL
4370
5539
  });
4371
5540
  await sendSync(null);
4372
5541
  poll();
@@ -4375,11 +5544,43 @@ var require_collaboration2 = __commonJS({
4375
5544
  };
4376
5545
  if (!socket.data.canEdit) return reply({ ok: false, code: "READ_ONLY" });
4377
5546
  const update = toBytes(payload, maxBytes);
4378
- if (!update || !isValidUpdate(update)) return reply({ ok: false, code: "INVALID_UPDATE" });
5547
+ if (!update) return reply({ ok: false, code: "INVALID_UPDATE" });
5548
+ const now = Date.now();
5549
+ if (now - bytesWindow.start > 1e4) {
5550
+ bytesWindow.start = now;
5551
+ bytesWindow.bytes = 0;
5552
+ }
5553
+ bytesWindow.bytes += update.byteLength;
5554
+ if (!updates.hit("u", now).allowed || bytesWindow.bytes > maxBytesPer10s)
5555
+ return reply({ ok: false, code: "RATE_LIMITED" });
4379
5556
  try {
5557
+ const roomDoc = await ensureDoc(room);
5558
+ const result = applyCheckedUpdate2(roomDoc, update);
5559
+ if (!result.ok) {
5560
+ if (result.dirty) dropDoc(room);
5561
+ if (result.code === "MISSING_DEPENDENCY") return reply({ ok: false, code: "RETRY" });
5562
+ invalid += 1;
5563
+ logger.warn("collaboration update refused", { code: result.code });
5564
+ reply({ ok: false, code: "INVALID_UPDATE" });
5565
+ if (invalid >= MAX_INVALID_UPDATES) {
5566
+ socket.emit("mx:error", { code: "INVALID_UPDATE" });
5567
+ socket.disconnect(true);
5568
+ }
5569
+ return void 0;
5570
+ }
5571
+ if (!result.changed) return reply({ ok: true, id: 0 });
4380
5572
  const stats = await store().roomStats(room);
4381
- if (stats.bytes + update.byteLength > MAX_ROOM_BYTES) return reply({ ok: false, code: "ROOM_FULL" });
4382
- const id = await store().appendUpdate(room, update, "update");
5573
+ if (stats.bytes + update.byteLength > MAX_ROOM_BYTES) {
5574
+ dropDoc(room);
5575
+ return reply({ ok: false, code: "ROOM_FULL" });
5576
+ }
5577
+ let id;
5578
+ try {
5579
+ id = await store().appendUpdate(room, update, "update");
5580
+ } catch (error) {
5581
+ dropDoc(room);
5582
+ throw error;
5583
+ }
4383
5584
  state.seen.set(id, Date.now());
4384
5585
  socket.to(room).emit("mx:update", update);
4385
5586
  reply({ ok: true, id });
@@ -4395,6 +5596,9 @@ var require_collaboration2 = __commonJS({
4395
5596
  return void 0;
4396
5597
  });
4397
5598
  socket.on("mx:resync", async (payload) => {
5599
+ const now = Date.now();
5600
+ if (now - lastResyncAt < 1e3) return;
5601
+ lastResyncAt = now;
4398
5602
  const vector = toBytes(payload, 64 * 1024);
4399
5603
  try {
4400
5604
  await sendSync(vector);
@@ -4402,15 +5606,11 @@ var require_collaboration2 = __commonJS({
4402
5606
  logger.warn("collaboration resync failed", { code: error && error.code, name: error && error.name });
4403
5607
  }
4404
5608
  });
4405
- let lastCursorAt = 0;
4406
5609
  socket.on("mx:cursor", async (cursor) => {
4407
5610
  const now = Date.now();
4408
- if (now - lastCursorAt < 150) return;
5611
+ if (now - lastCursorAt < 50) return;
4409
5612
  lastCursorAt = now;
4410
- const clean = cursor && typeof cursor === "object" && typeof cursor.blockId === "string" && cursor.blockId.length <= 64 ? {
4411
- blockId: cursor.blockId,
4412
- offset: Number.isInteger(cursor.offset) && cursor.offset >= 0 ? Math.min(cursor.offset, 1e7) : 0
4413
- } : null;
5613
+ socket.data.cursor = cleanCursor(cursor);
4414
5614
  try {
4415
5615
  await store().upsertPresence({
4416
5616
  id: socket.data.presenceId,
@@ -4419,7 +5619,7 @@ var require_collaboration2 = __commonJS({
4419
5619
  name: claims.name,
4420
5620
  color: claims.color,
4421
5621
  canEdit: socket.data.canEdit,
4422
- cursor: clean
5622
+ cursor: socket.data.cursor
4423
5623
  });
4424
5624
  poll();
4425
5625
  } catch {
@@ -4432,24 +5632,49 @@ var require_collaboration2 = __commonJS({
4432
5632
  if (state.sockets.size === 0) {
4433
5633
  const stats = await store().roomStats(room);
4434
5634
  await autoSnapshot(room, `end${stats.lastId}`).catch(() => false);
4435
- rooms.delete(room);
5635
+ if (state.sockets.size === 0) {
5636
+ dropDoc(room);
5637
+ rooms.delete(room);
5638
+ }
4436
5639
  }
4437
5640
  poll();
4438
5641
  } catch {
4439
5642
  }
4440
5643
  });
4441
5644
  };
5645
+ const permissionsChanged = async () => {
5646
+ try {
5647
+ const value = randomUUID();
5648
+ await store().setSignal("permissions", value);
5649
+ permissionSignal = value;
5650
+ } catch (error) {
5651
+ logger.warn("permission signal could not be raised", {
5652
+ code: error && error.code,
5653
+ name: error && error.name
5654
+ });
5655
+ }
5656
+ if (rooms.size > 0) await revalidate();
5657
+ };
4442
5658
  return {
4443
5659
  PROCESS_ID,
5660
+ PROTOCOL,
4444
5661
  /**
4445
5662
  * Issues a one-time session token for a field after checking access.
4446
5663
  * @param {{ userAbility: object, user: object, uid: string, documentId: string, locale?: string|null, field: string, initialValue?: unknown }} input - Request.
4447
5664
  * @returns {Promise<object>} Token and connection details.
4448
- * @throws {errors.NotFoundError|errors.ForbiddenError} When access is denied or collaboration is off.
5665
+ * @throws {errors.NotFoundError|errors.ForbiddenError|errors.RateLimitError} Access denied, collaboration off, too many sessions.
4449
5666
  */
4450
5667
  async createSession({ userAbility, user, uid, documentId, locale, field, initialValue }) {
4451
5668
  if (conf("enabled", true) === false || !io)
4452
5669
  throw new errors.ForbiddenError("Live collaboration is disabled");
5670
+ const limit = Number((conf("rateLimit", {}) || {}).sessionsPerMinute) || 60;
5671
+ let allowed;
5672
+ try {
5673
+ allowed = (await store().hit(`session:${user.id}`, 6e4)).count <= limit;
5674
+ } catch {
5675
+ allowed = sessionLimiter.hit(`session:${user.id}`).allowed;
5676
+ }
5677
+ if (!allowed) throw new errors.RateLimitError("Too many live editing sessions. Try again in a minute.");
4453
5678
  const result = await access().checkField({ userAbility, uid, documentId, locale, field });
4454
5679
  const target = { uid, documentId, locale: result.locale, field };
4455
5680
  const room = history().fieldKey(target);
@@ -4480,6 +5705,7 @@ var require_collaboration2 = __commonJS({
4480
5705
  name: displayName(user),
4481
5706
  color: colorFor(user.id),
4482
5707
  canEdit: result.canUpdate,
5708
+ protocol: PROTOCOL,
4483
5709
  nonce: randomUUID(),
4484
5710
  exp: Date.now() + ttl
4485
5711
  };
@@ -4488,6 +5714,7 @@ var require_collaboration2 = __commonJS({
4488
5714
  path: conf("path", "/magic-editor-x/realtime"),
4489
5715
  canEdit: result.canUpdate,
4490
5716
  seeded,
5717
+ protocol: PROTOCOL,
4491
5718
  expiresAt: claims.exp
4492
5719
  };
4493
5720
  },
@@ -4513,6 +5740,9 @@ var require_collaboration2 = __commonJS({
4513
5740
  pingTimeout: 2e4,
4514
5741
  cors: { origin: false }
4515
5742
  });
5743
+ io.use((socket, next) => {
5744
+ authenticate(socket, next);
5745
+ });
4516
5746
  io.on("connection", (socket) => {
4517
5747
  onConnection(socket).catch((error) => {
4518
5748
  logger.warn("collaboration connection failed", {
@@ -4532,8 +5762,9 @@ var require_collaboration2 = __commonJS({
4532
5762
  };
4533
5763
  every(poll, Math.max(50, Number(conf("pollIntervalMs", 400))));
4534
5764
  every(maintenanceTick, HEARTBEAT_MS);
4535
- every(snapshotTick, 3e4);
4536
- every(revalidate, REVALIDATE_MS);
5765
+ every(snapshotTick, 5e3);
5766
+ every(signalTick, SIGNAL_CHECK_MS);
5767
+ every(revalidate, Math.max(5, Number(conf("revalidateSeconds", 60))) * 1e3);
4537
5768
  },
4538
5769
  /**
4539
5770
  * Stops timers and closes sockets (process shutdown).
@@ -4553,18 +5784,26 @@ var require_collaboration2 = __commonJS({
4553
5784
  await new Promise((resolve) => io.close(() => resolve()));
4554
5785
  io = null;
4555
5786
  }
5787
+ for (const room of Array.from(rooms.keys())) dropDoc(room);
4556
5788
  rooms.clear();
4557
5789
  },
4558
5790
  /** True when the socket server runs in this process. */
4559
5791
  isRunning() {
4560
5792
  return Boolean(io);
4561
5793
  },
5794
+ /** Called by the admin lifecycle subscriber when roles, permissions or users change. */
5795
+ permissionsChanged,
4562
5796
  /** Test hook: runs one poll tick. */
4563
- pollNow: poll
5797
+ pollNow: poll,
5798
+ /** Test hook: runs one maintenance tick. */
5799
+ maintenanceNow: maintenanceTick
4564
5800
  };
4565
5801
  };
4566
5802
  module.exports.toBytes = toBytes;
4567
5803
  module.exports.displayName = displayName;
5804
+ module.exports.cleanCursor = cleanCursor;
5805
+ module.exports.targetOfRoom = targetOfRoom;
5806
+ module.exports.PROTOCOL = PROTOCOL;
4568
5807
  }
4569
5808
  });
4570
5809
 
@@ -4698,6 +5937,7 @@ var require_services = __commonJS({
4698
5937
  module.exports = {
4699
5938
  store: require_store(),
4700
5939
  access: require_access(),
5940
+ links: require_links2(),
4701
5941
  editor: require_editor2(),
4702
5942
  settings: require_settings2(),
4703
5943
  ai: require_ai2(),