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