domma-cms 1.66.10 → 1.67.1

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.
@@ -764,6 +764,33 @@ nothing was stored (an end-form set not to record) - treat that as not sent. An
764
764
  `meta.updatedAt` with `meta.createdAt` if the answers must be as sent. When the person's data is erased, use
765
765
  `removeFormEntry`, and `formEntriesBy(form, userId)` for the entries they sent but your plugin never used. Feature-detect an older core: `import('../../server/services/formContext.js').catch(() => null)`.
766
766
 
767
+ ## Rich text Description fields
768
+
769
+ A Tool's Description field should be the shared rich text editor, not a bare textarea.
770
+
771
+ **Admin view** - keep the `<textarea>` in your template and, once it is in the page, call:
772
+
773
+ ```js
774
+ import {richDescription, showRichText, richTextSummary} from '/admin/js/lib/rich-field.js';
775
+
776
+ richDescription(root.querySelector('#my-description')); // before or after M.applyBindings
777
+ ```
778
+
779
+ The textarea stays the field: its `.value` is the editor's HTML (or `''` when empty), `data-model` bindings and `.val()` work as before, and it fires `input` and `change`. Remove any `maxlength` assumptions: the value now includes markup. To show a stored description in the admin use `showRichText(el, value)`; for a list row or a search use `richTextSummary(value, 140)` - never `innerHTML`.
780
+
781
+ **Server** - a description is one string, plain (typed before, or from an API client) or rich (from the editor):
782
+
783
+ ```js
784
+ import {cleanRichText, renderRichText, richTextToPlain, richTextSummary} from '../../server/services/richText.js';
785
+
786
+ record.description = cleanRichText(body.description, {max: 4000}); // on save
787
+ const html = renderRichText(record.description); // into a page or an HTML email: already safe, do not escape it again
788
+ const meta = richTextSummary(record.description, 160); // meta description, list row
789
+ const text = richTextToPlain(record.description); // plain email, CSV, ICS, JSON-LD, search
790
+ ```
791
+
792
+ Do not collapse whitespace or strip characters from the value before `cleanRichText`, and do not pass it through `escapeHtml` on a page: `renderRichText` escapes a plain description and cleans a rich one. Public scripts can import `/public/js/rich-text.mjs` for `isRichText`, `richTextToPlain` and `richTextSummary`; it does no cleaning, so use the server's `renderRichText` output for anything drawn as HTML.
793
+
767
794
  ## AI Assist: listing your AI chats
768
795
 
769
796
  A Tool with its own AI chats (the Site Builder's conversations, the Tool Builder's builds) can list them on
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.66.10",
3
+ "version": "1.67.1",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -0,0 +1,9 @@
1
+ const o=/^\s*<(p|ul|ol|h[2-4]|blockquote)(\s[^<>]*)?>/i;export function isRichText(r){return typeof r=="string"&&o.test(r)}export function escapeHtml(r){return String(r??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}export function plainToRichHtml(r){return String(r??"").replace(/\r\n?/g,`
2
+ `).split(/\n{2,}/).map(e=>e.trim()).filter(Boolean).map(e=>`<p>${escapeHtml(e).replace(/\n/g,"<br>")}</p>`).join("")}const c={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};export function richTextToPlain(r){const e=String(r??"");return isRichText(e)?e.replace(/<br\s*\/?>/gi,`
3
+ `).replace(/<li(\s[^<>]*)?>/gi,"- ").replace(/<\/(p|h[1-6]|blockquote|ul|ol)>/gi,`
4
+
5
+ `).replace(/<\/li>/gi,`
6
+ `).replace(/<[^<>]*>/g,"").replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(t,n)=>{if(n[0]!=="#")return c[n.toLowerCase()]??t;const i=n[1].toLowerCase()==="x"?Number.parseInt(n.slice(2),16):Number.parseInt(n.slice(1),10);return Number.isFinite(i)&&i>0&&i<=1114111?String.fromCodePoint(i):t}).replace(/[ \t]+\n/g,`
7
+ `).replace(/\n{3,}/g,`
8
+
9
+ `).trim():e.trim()}export function richTextSummary(r,e=160){const t=richTextToPlain(r).replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1).trimEnd()}\u2026`:t}
@@ -56,6 +56,7 @@ import {v4 as uuidv4} from 'uuid';
56
56
  import {ago, clip, plural} from '../../services/sidebarBadges.js';
57
57
  import {safeFetch} from '../../services/outbound.js';
58
58
  import {verifyFormContext} from '../../services/formContext.js';
59
+ import {cleanRichText} from '../../services/richText.js';
59
60
 
60
61
  /**
61
62
  * Detect form↔collection mismatches at save time so admins know BEFORE
@@ -678,7 +679,7 @@ export async function formsRoutes(fastify) {
678
679
  const form = {
679
680
  slug,
680
681
  title: title.trim(),
681
- description: body.description || '',
682
+ description: cleanRichText(body.description, {max: 4000}),
682
683
  fields: Array.isArray(body.fields) ? body.fields : [],
683
684
  settings: {
684
685
  submitText: 'Submit',
@@ -783,6 +784,7 @@ export async function formsRoutes(fastify) {
783
784
  createdAt: existing.createdAt,
784
785
  updatedAt: new Date().toISOString()
785
786
  };
787
+ if ('description' in body) updated.description = cleanRichText(body.description, {max: 4000});
786
788
  if (await refusedPluginTarget(request, reply, updated)) return;
787
789
  await writeForm(slug, updated);
788
790
 
@@ -31,6 +31,7 @@ import {createEntry, deleteEntry, getEntry, updateEntry} from './collections.js'
31
31
  import {checkEntryAccess} from './rowAccess.js';
32
32
  import {canReadView} from './views.js';
33
33
  import {getEffectiveLevel} from './userRoles.js';
34
+ import {cleanRichText} from './richText.js';
34
35
 
35
36
  /** MongoDB collection where action configs are stored. */
36
37
  const ACTIONS_COLLECTION = 'cms__actions';
@@ -343,7 +344,7 @@ export async function createAction(data, userId = null) {
343
344
  id: uuidv4(),
344
345
  slug,
345
346
  title: title.trim(),
346
- description: description.trim(),
347
+ description: cleanRichText(description, {max: 4000}),
347
348
  collection,
348
349
  trigger: {
349
350
  type: trigger?.type || 'manual',
@@ -391,6 +392,7 @@ export async function updateAction(slug, data) {
391
392
  if (!existing) throw new Error(`Action "${slug}" not found`);
392
393
 
393
394
  const { _id, id, meta: inputMeta, ...rest } = data;
395
+ if ('description' in rest) rest.description = cleanRichText(rest.description, {max: 4000});
394
396
  const updated = {
395
397
  ...existing,
396
398
  ...rest,
@@ -16,6 +16,10 @@ import {typedEntryData} from './entryValues.js';
16
16
  import {toCsv} from '../../public/js/collection-export.mjs';
17
17
  import {fileIn} from './safePath.js';
18
18
  import {SHARED_TOOL_SLUGS} from './presetCollections.js';
19
+ import {cleanRichText} from './richText.js';
20
+
21
+ /** A collection's description: rich text (see richText.js), markup included. */
22
+ const DESCRIPTION_MAX = 4000;
19
23
 
20
24
  const COLLECTIONS_DIR = path.resolve(config.content.collectionsDir);
21
25
  const TOOL_TRASH_SLUGS = new Set(['notes-notes', 'todo-items', 'contacts-contacts']);
@@ -203,7 +207,7 @@ export async function createCollection({title, slug, description = '', fields =
203
207
  const schema = {
204
208
  slug: finalSlug,
205
209
  title: title.trim(),
206
- description: description.trim(),
210
+ description: cleanRichText(description, {max: DESCRIPTION_MAX}),
207
211
  fields,
208
212
  api: { ...defaultApiAccess({owned: Boolean(plugin)}), ...api },
209
213
  storage: storage || {adapter: 'file'},
@@ -240,6 +244,7 @@ export async function updateCollection(slug, updates) {
240
244
  createdAt: schema.createdAt,
241
245
  updatedAt: new Date().toISOString()
242
246
  };
247
+ if ('description' in rest) updated.description = cleanRichText(rest.description, {max: DESCRIPTION_MAX});
243
248
 
244
249
  // `api.mine` (see mineAllowed in collectionAccess.js) is kept when an
245
250
  // update's api block does not mention it: clients that rebuild `api` from
@@ -11,6 +11,7 @@ import * as cache from './cache/index.js';
11
11
  import {buttonSettingsProblems, formClassProblems} from '../../public/js/form-submit.mjs';
12
12
  import {fileIn} from './safePath.js';
13
13
  import {getConfig} from '../config.js';
14
+ import {cleanRichText} from './richText.js';
14
15
 
15
16
  /** What one submission's files may hold in memory together when server.json sets nothing: 50 MB. */
16
17
  export const DEFAULT_MAX_SUBMISSION_BYTES = 50 * 1024 * 1024;
@@ -234,7 +235,7 @@ export async function createForm(data) {
234
235
  const form = {
235
236
  slug,
236
237
  title: trimmedTitle,
237
- description,
238
+ description: cleanRichText(description, {max: 4000}),
238
239
  ...(plugin ? {plugin} : {}),
239
240
  fields: Array.isArray(fields) ? fields : [],
240
241
  settings: {
@@ -6,7 +6,7 @@ import {decodeMessageAttribute} from '../../public/js/celebrations/message-attrs
6
6
  import {normaliseBackground, backgroundStyle} from '../../public/js/background-style.mjs';
7
7
  import {cssClasses} from '../../public/js/css-classes.mjs';
8
8
  import matter from 'gray-matter';
9
- import {marked} from 'marked';
9
+ import {Marked, marked} from 'marked';
10
10
  import sanitizeHtml from 'sanitize-html';
11
11
  import {readdir, readFile} from 'fs/promises';
12
12
  import {AsyncLocalStorage} from 'node:async_hooks';
@@ -29,6 +29,7 @@ import {CHARACTERS, resolveCharacterSize} from '../../public/js/celebrations/cha
29
29
  import {publicButtonSettings} from '../../public/js/form-submit.mjs';
30
30
  import {FILE_LIMITS_TAG, publicFileLimits} from './forms.js';
31
31
  import {applyShortcodeExpiry} from './shortcodeExpiry.js';
32
+ import {richTextToPlain} from '../../public/js/rich-text.mjs';
32
33
 
33
34
  const __dirname_md = path.dirname(fileURLToPath(import.meta.url));
34
35
  const BLOCKS_DIR = path.resolve(__dirname_md, '../../content/blocks');
@@ -89,8 +90,12 @@ marked.setOptions({
89
90
  * @returns {string}
90
91
  */
91
92
  export function inertShortcodes(html) {
93
+ // \x02 / \x03 frame the code-scrub placeholders: data must not be able to
94
+ // write one. A backslash after "[" is covered too, because Markdown reads
95
+ // "[\/card]" as "[/card]".
92
96
  return String(html ?? '')
93
- .replace(/\[([\w\s\/-])/g, (_, c) => `[&#${c.codePointAt(0)};`)
97
+ .replace(/[\x02\x03]/g, '')
98
+ .replace(/\[([\w\s\/\\-])/g, (_, c) => `[&#${c.codePointAt(0)};`)
94
99
  .replace(/\[$/, '&#91;');
95
100
  }
96
101
 
@@ -2089,7 +2094,9 @@ export function unindentShortTags(markdown) {
2089
2094
  }
2090
2095
 
2091
2096
  const SCRUB_PLACEHOLDER = /\x02SC(\d+):(\d+)\x03/g;
2092
- const SHIELD_PLACEHOLDER = /DMSCT(\d+)x(\d+)x/g;
2097
+ // The nonce keeps data from writing a placeholder of its own.
2098
+ const SHIELD_NONCE = randomUUID().replace(/-/g, '');
2099
+ const SHIELD_PLACEHOLDER = new RegExp(`DMSCT${SHIELD_NONCE}x(\\d+)x(\\d+)x`, 'g');
2093
2100
 
2094
2101
  /**
2095
2102
  * The two patterns a shortcode name is matched with - self-closing and wrapping -
@@ -2161,15 +2168,83 @@ let shieldCallId = 0;
2161
2168
  const ATTR_TAG = /\[\/?[a-z][\w-]*\s[^\]\n]*=[^\]\n]*\](?![(\[:])/gi;
2162
2169
  function markedBody(md) {
2163
2170
  const text = String(md ?? '');
2164
- if (!text.includes('=')) return marked.parse(text);
2171
+ if (!text.includes('=')) return markedKeepingInert(text);
2165
2172
  const id = ++shieldCallId;
2166
2173
  const held = [];
2167
2174
  const {scrubbed, restore} = scrubCodeRegions(text);
2168
- const shielded = restore(scrubbed.replace(ATTR_TAG, (tag) => { held.push(tag); return `DMSCT${id}x${held.length - 1}x`; }));
2169
- if (!held.length) return marked.parse(text);
2170
- return marked.parse(shielded).replace(SHIELD_PLACEHOLDER, (m, call, i) => (Number(call) === id ? held[Number(i)] : m));
2175
+ const shielded = restore(scrubbed.replace(ATTR_TAG, (tag) => { held.push(tag); return `DMSCT${SHIELD_NONCE}x${id}x${held.length - 1}x`; }));
2176
+ if (!held.length) return markedKeepingInert(text);
2177
+ return markedKeepingInert(shielded).replace(SHIELD_PLACEHOLDER, (m, call, i) => (Number(call) === id ? held[Number(i)] : m));
2171
2178
  }
2172
2179
 
2180
+ /**
2181
+ * marked for text that later shortcode stages will still read (a container's
2182
+ * body, a table, a list group item), keeping inert brackets inert.
2183
+ *
2184
+ * inertShortcodes() writes the character after a `[` as a numeric entity, and
2185
+ * marked reads numeric entities in text back into characters. So entry data
2186
+ * shown inside a [card], [tabs], [grid] or an effect came out of that
2187
+ * container's marked pass as a plain `[banner …]` / `[button …]` /
2188
+ * `[slideover …]` again, and the stages after the container ran it. The same
2189
+ * went for a bracket an entry spelt as an entity itself (`&#x5b;badge]`).
2190
+ *
2191
+ * These passes use `midMarked`, a marked that does not decode: its inlineText
2192
+ * tokenizer hands the text on as written, and the renderer's usual escaping
2193
+ * leaves existing entities alone. Nothing else differs - code, HTML blocks,
2194
+ * links and tables come out as marked's own. The LAST marked pass, in
2195
+ * parseMarkdown, stays on plain marked: nothing reads shortcodes after it.
2196
+ *
2197
+ * @param {string} text
2198
+ * @param {boolean} [inline] - parseInline instead of parse
2199
+ * @param {object} [options] - passed to marked as given
2200
+ * @returns {string}
2201
+ */
2202
+ function markedKeepingInert(text, inline = false, options = undefined) {
2203
+ const source = String(text ?? '');
2204
+ if (inline) return options === undefined ? midMarked.parseInline(source) : midMarked.parseInline(source, options);
2205
+ return options === undefined ? midMarked.parse(source) : midMarked.parse(source, options);
2206
+ }
2207
+
2208
+ const midMarked = new Marked({gfm: true, breaks: false});
2209
+ midMarked.use({
2210
+ tokenizer: {
2211
+ // marked's own inlineText, minus the numeric-entity decoding.
2212
+ inlineText(src) {
2213
+ const cap = this.rules.inline.text.exec(src);
2214
+ if (!cap) return undefined;
2215
+ return {type: 'text', raw: cap[0], text: cap[0], escaped: this.lexer.state.inRawBlock};
2216
+ },
2217
+ },
2218
+ // An image's alt text is its content with the markup taken out, which joins
2219
+ // "[**f**orm …]" back into "[form …]" inside the alt attribute - where the
2220
+ // later stages would run it. The flattened text is made inert again.
2221
+ walkTokens(token) {
2222
+ if (token.type !== 'image') return;
2223
+ token.text = inertShortcodes(token.tokens ? flatTokenText(token.tokens) : String(token.text ?? ''));
2224
+ delete token.tokens;
2225
+ },
2226
+ });
2227
+
2228
+ /** The plain text of inline tokens, as marked's text renderer would give it. */
2229
+ function flatTokenText(tokens) {
2230
+ let out = '';
2231
+ for (const token of tokens || []) {
2232
+ if (token.type === 'br') continue;
2233
+ if (token.type === 'image') out += token.tokens ? flatTokenText(token.tokens) : String(token.text ?? '');
2234
+ else if (token.tokens) out += flatTokenText(token.tokens);
2235
+ else out += String(token.text ?? token.raw ?? '');
2236
+ }
2237
+ return out;
2238
+ }
2239
+
2240
+ // marked for code that takes a marked-like object: the card renderers, and the
2241
+ // shortcode handlers plugins register (they render bodies that later stages
2242
+ // still read). Everything else on it is marked's own.
2243
+ const inertMarked = Object.assign((text, options) => markedKeepingInert(text, false, options), marked, {
2244
+ parse: (text, options) => markedKeepingInert(text, false, options),
2245
+ parseInline: (text, options) => markedKeepingInert(text, true, options),
2246
+ });
2247
+
2173
2248
  /**
2174
2249
  * Run all plugin-registered shortcode handlers against the markdown string.
2175
2250
  * Self-closing ([name attrs /]) and wrapping ([name attrs]...[/name]) forms are both supported.
@@ -2186,7 +2261,7 @@ async function processPluginShortcodes(markdown, user = null) {
2186
2261
  let result = scrubbed;
2187
2262
  // renderMap tells a plugin with its own [map] (Blog Pro: OpenStreetMap by lat/lon) that the CMS has one too, so it can
2188
2263
  // hand back the tags it cannot draw (an address, a postcode) for processMapBlocks.
2189
- const context = {parseShortcodeAttrs, scrubCodeRegions, marked, processCardBlocks, processGridBlocks, escapeAttr, renderMap, user};
2264
+ const context = {parseShortcodeAttrs, scrubCodeRegions, marked: inertMarked, processCardBlocks, processGridBlocks, escapeAttr, renderMap, user};
2190
2265
 
2191
2266
  async function replaceAsync(input, regex, mapMatch) {
2192
2267
  const matches = [];
@@ -2270,7 +2345,7 @@ function processEffectsBlocks(markdown) {
2270
2345
  .map(key => ` data-fx-${key}="${escapeAttr(String(attrs[key]))}"`).join('');
2271
2346
  return `<div class="dm-fx-celebrate dm-fx-character"${dataAttrs} style="display:inline-block;max-width:100%;width:${width}px;vertical-align:bottom"></div>`;
2272
2347
  }
2273
- const dataAttrs = Object.entries(attrs).map(([k, v]) => ` data-fx-${k}="${escapeAttr(String(v))}"`).join('');
2348
+ const dataAttrs = Object.entries(attrs).map(([k, v]) => ` data-fx-${k}="${bracketSafeAttr(v)}"`).join('');
2274
2349
  return `<div class="dm-fx-celebrate"${dataAttrs}></div>`;
2275
2350
  }
2276
2351
  apply('celebrate', renderCelebration);
@@ -2286,7 +2361,7 @@ function processEffectsBlocks(markdown) {
2286
2361
  const attrs = parseShortcodeAttrs(attrStr);
2287
2362
  if (typeof attrs.message === 'string') attrs.message = decodeMessageAttribute(attrs.message);
2288
2363
  delete attrs.theme;
2289
- const dataAttrs = Object.entries(attrs).map(([k, v]) => ` data-fx-${k}="${escapeAttr(String(v))}"`).join('');
2364
+ const dataAttrs = Object.entries(attrs).map(([k, v]) => ` data-fx-${k}="${bracketSafeAttr(v)}"`).join('');
2290
2365
  return `<div class="dm-fx-celebrate" data-fx-theme="${themeName}"${dataAttrs}></div>`;
2291
2366
  });
2292
2367
  });
@@ -2624,6 +2699,15 @@ export function collectAndRewriteComponents(source) {
2624
2699
  * @param {unknown} value
2625
2700
  * @returns {string}
2626
2701
  */
2702
+ /**
2703
+ * An attribute value whose square brackets are entities. A celebration's
2704
+ * message is decoded first (authors write &#91; for a bracket), so without
2705
+ * this a "[badge]" in it sat in the attribute as live text for later stages.
2706
+ */
2707
+ function bracketSafeAttr(value) {
2708
+ return escapeAttr(String(value)).replace(/\[/g, '&#91;').replace(/\]/g, '&#93;');
2709
+ }
2710
+
2627
2711
  export function classToken(value) {
2628
2712
  return String(value ?? '').replace(/[^\w-]/g, '');
2629
2713
  }
@@ -2943,7 +3027,7 @@ function cardImageParts(attrs, body, markedInstance) {
2943
3027
  const LAYOUT_RENDERERS = {};
2944
3028
 
2945
3029
  LAYOUT_RENDERERS['basic'] = (attrs, body) => {
2946
- const im = cardImageParts(attrs, body, marked);
3030
+ const im = cardImageParts(attrs, body, inertMarked);
2947
3031
  const bodyHtml = markedBody(im.body.trim());
2948
3032
  return `${cardRoot(attrs)}${im.media}${im.wrapBody(bodyHtml)}${cardFooterAttr(attrs)}</div>\n`;
2949
3033
  };
@@ -2951,7 +3035,7 @@ LAYOUT_RENDERERS['basic'] = (attrs, body) => {
2951
3035
  LAYOUT_RENDERERS['header-body'] = (attrs, body) => {
2952
3036
  const title = typeof attrs.title === 'string' ? attrs.title.trim() : '';
2953
3037
  const hdr = title ? `<div class="card-header"><div class="card-title">${escapeAttr(title)}</div></div>` : '';
2954
- const im = cardImageParts(attrs, body, marked);
3038
+ const im = cardImageParts(attrs, body, inertMarked);
2955
3039
  const bodyHtml = markedBody(processGridBlocks(processInlineShortcodes(im.body.trim())));
2956
3040
  return `${cardRoot(attrs)}${im.media}${hdr}${im.wrapBody(bodyHtml)}${cardFooterAttr(attrs)}</div>\n`;
2957
3041
  };
@@ -2960,7 +3044,7 @@ LAYOUT_RENDERERS['header-body-footer'] = (attrs, body) => {
2960
3044
  const title = typeof attrs.title === 'string' ? attrs.title.trim() : '';
2961
3045
  const footer = typeof attrs.footer === 'string' ? attrs.footer.trim() : '';
2962
3046
  const hdr = title ? `<div class="card-header"><div class="card-title">${escapeAttr(title)}</div></div>` : '';
2963
- const im = cardImageParts(attrs, body, marked);
3047
+ const im = cardImageParts(attrs, body, inertMarked);
2964
3048
  const bodyHtml = markedBody(processGridBlocks(processInlineShortcodes(im.body.trim())));
2965
3049
  const ftr = footer ? `<div class="card-footer">${escapeAttr(footer)}</div>` : '';
2966
3050
  return `${cardRoot(attrs)}${im.media}${hdr}${im.wrapBody(bodyHtml)}${ftr}</div>\n`;
@@ -2968,7 +3052,7 @@ LAYOUT_RENDERERS['header-body-footer'] = (attrs, body) => {
2968
3052
 
2969
3053
  LAYOUT_RENDERERS['no-header-footer'] = (attrs, body) => {
2970
3054
  const footer = typeof attrs.footer === 'string' ? attrs.footer.trim() : '';
2971
- const im = cardImageParts(attrs, body, marked);
3055
+ const im = cardImageParts(attrs, body, inertMarked);
2972
3056
  const bodyHtml = markedBody(processGridBlocks(processInlineShortcodes(im.body.trim())));
2973
3057
  const ftr = footer ? `<div class="card-footer">${escapeAttr(footer)}</div>` : '';
2974
3058
  return `${cardRoot(attrs)}${im.media}${im.wrapBody(bodyHtml)}${ftr}</div>\n`;
@@ -3598,7 +3682,7 @@ function processCardBlocks(markdown) {
3598
3682
  const renderer = LAYOUT_RENDERERS[layout] || renderLegacyCard;
3599
3683
  const html = range.name === 'box'
3600
3684
  ? renderBox(attrs, body)
3601
- : renderer(attrs, body, marked, escapeAttr);
3685
+ : renderer(attrs, body, inertMarked, escapeAttr);
3602
3686
  const token = `<!--cms-card-${nonce}-${held.size}-->`;
3603
3687
  held.set(token, html);
3604
3688
  const gap = nested ? '\n\n' : '';
@@ -3658,7 +3742,7 @@ function processTabsBlocks(markdown) {
3658
3742
  // that would confuse subsequent scrubCodeRegions calls.
3659
3743
  const restoredBody = restore(tabBody.trim());
3660
3744
  const bodyHtml = markedBody(processCardBlocks(processGridBlocks(processInlineShortcodes(restoredBody))));
3661
- const icon = tabAttrs.icon ? tabAttrs.icon.trim() : '';
3745
+ const icon = typeof tabAttrs.icon === 'string' ? tabAttrs.icon.trim() : '';
3662
3746
  items.push({title, icon, paneId, bodyHtml, first: tabIdx === 1});
3663
3747
  });
3664
3748
 
@@ -4132,7 +4216,7 @@ function processTableBlocks(markdown) {
4132
4216
  : '';
4133
4217
  const idAttr = attrs.id ? ` id="${escapeAttr(attrs.id)}"` : '';
4134
4218
 
4135
- let tableHtml = marked.parse(restore(body.trim()));
4219
+ let tableHtml = markedKeepingInert(restore(body.trim()));
4136
4220
 
4137
4221
  tableHtml = tableHtml.replace(
4138
4222
  '<table>',
@@ -4238,7 +4322,7 @@ function processListGroupBlocks(markdown) {
4238
4322
  const itemClassStr = itemClasses.join(' ');
4239
4323
  let items = '';
4240
4324
  body.replace(/\[item\]([\s\S]*?)\[\/item\]/gi, (__, content) => {
4241
- const html = marked.parseInline(processInlineShortcodes(restore(content.trim())));
4325
+ const html = markedKeepingInert(processInlineShortcodes(restore(content.trim())), true);
4242
4326
  items += `<div class="${itemClassStr}">${html}</div>\n`;
4243
4327
  });
4244
4328
 
@@ -4976,7 +5060,8 @@ async function expandReferenceFields(form) {
4976
5060
  */
4977
5061
  export function formSummaryHtml(form) {
4978
5062
  const title = String(form?.title ?? '').trim();
4979
- const description = String(form?.description ?? '').trim();
5063
+ // Read aloud, so the words alone: a rich description without its markup.
5064
+ const description = richTextToPlain(form?.description).replace(/\s+/g, ' ');
4980
5065
  if (!title && !description) return '';
4981
5066
  return inertShortcodes(`<div class="sr-only cms-form-embed-summary">`
4982
5067
  + (title ? `<p><strong>${escapeHtmlText(title)}</strong></p>` : '')
@@ -24,6 +24,7 @@ import {
24
24
  } from '../../public/js/menu-decor.mjs';
25
25
  import {fileIn} from './safePath.js';
26
26
  import {normaliseLook, lookProblems, itemLookProblems} from '../../public/js/menu-look.mjs';
27
+ import {cleanRichText} from './richText.js';
27
28
 
28
29
  export {normaliseLook};
29
30
 
@@ -617,7 +618,7 @@ export async function createMenu(input) {
617
618
  const menu = {
618
619
  slug: input.slug,
619
620
  name: input.name || input.slug,
620
- description: input.description || '',
621
+ description: cleanRichText(input.description, {max: 4000}),
621
622
  ...(input.variant != null && {variant: input.variant}),
622
623
  ...(input.position != null && {position: input.position}),
623
624
  ...(input.orientation != null && {orientation: input.orientation}),
@@ -691,7 +692,7 @@ export async function updateMenu(slug, input, opts = {}) {
691
692
  const merged = {
692
693
  slug,
693
694
  name: input.name || existing.name,
694
- description: input.description || '',
695
+ description: cleanRichText(input.description, {max: 4000}),
695
696
  ...(input.variant != null && {variant: input.variant}),
696
697
  ...(input.position != null && {position: input.position}),
697
698
  ...(input.orientation != null && {orientation: input.orientation}),
@@ -22,6 +22,7 @@
22
22
  import {createEntry, deleteEntry, listEntries, updateEntry} from './collections.js';
23
23
  import {getRoleLevel} from './roles.js';
24
24
  import * as cache from './cache/index.js';
25
+ import {cleanRichText} from './richText.js';
25
26
 
26
27
  /** Slug of the preset collection that stores project records. */
27
28
  export const PROJECTS_COLLECTION_SLUG = 'projects';
@@ -148,7 +149,7 @@ export async function createProject(input) {
148
149
  const data = {
149
150
  slug: input.slug,
150
151
  name: input.name,
151
- description: input.description || '',
152
+ description: cleanRichText(input.description, {max: 4000}),
152
153
  icon: input.icon || 'folder',
153
154
  ...(input.rootUrl != null && {rootUrl: input.rootUrl}),
154
155
  sortOrder: Number.isFinite(input.sortOrder) ? input.sortOrder : 0,
@@ -233,7 +234,7 @@ export async function updateProject(slug, input) {
233
234
  const merged = {
234
235
  ...existing,
235
236
  ...(input.name != null && {name: input.name}),
236
- ...(input.description != null && {description: input.description}),
237
+ ...(input.description != null && {description: cleanRichText(input.description, {max: 4000})}),
237
238
  ...(input.icon != null && {icon: input.icon}),
238
239
  ...(input.rootUrl != null && {rootUrl: input.rootUrl}),
239
240
  ...(Number.isFinite(input.sortOrder) && {sortOrder: input.sortOrder}),
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Rich text Description fields - cleaning what is saved and what is shown.
3
+ *
4
+ * See `public/js/rich-text.mjs` for how a description is stored (one string,
5
+ * plain or rich) and told apart. This is the half that needs a sanitiser:
6
+ *
7
+ * - `cleanRichText(value)` on SAVE. A rich value is reduced to the small set
8
+ * of elements the editor makes; a plain one is kept as typed.
9
+ * - `renderRichText(value)` wherever a description goes into a page or an
10
+ * HTML email. A rich value is cleaned again (what is stored may predate a
11
+ * rule, or have been written around the API); a plain one is escaped into
12
+ * paragraphs. Its result is always safe to put in a page.
13
+ * - `richTextToPlain` / `richTextSummary` (re-exported) for everything that is
14
+ * not HTML: meta descriptions, plain emails, CSV, ICS, search, JSON-LD.
15
+ *
16
+ * Deliberately far stricter than `sanitizePageHtml`: a description is a few
17
+ * formatted paragraphs, not a page. No images, classes, styles or embeds.
18
+ *
19
+ * @module server/services/richText
20
+ */
21
+ import sanitizeHtml from 'sanitize-html';
22
+ import {isRichText, plainToRichHtml, richTextToPlain, richTextSummary, escapeHtml} from '../../public/js/rich-text.mjs';
23
+
24
+ export {isRichText, plainToRichHtml, richTextToPlain, richTextSummary};
25
+
26
+ /** How long a description may be unless the caller says otherwise. */
27
+ export const RICH_TEXT_MAX = 20000;
28
+
29
+ const OPTIONS = {
30
+ allowedTags: ['p', 'br', 'strong', 'b', 'em', 'i', 'u', 's', 'ul', 'ol', 'li', 'a', 'h2', 'h3', 'h4', 'blockquote', 'code'],
31
+ allowedAttributes: {a: ['href', 'target', 'rel']},
32
+ allowedSchemes: ['http', 'https', 'mailto', 'tel'],
33
+ allowProtocolRelative: false,
34
+ // The editor makes divs and spans (a pasted line, a font change); their text is kept.
35
+ transformTags: {
36
+ div: 'p',
37
+ a: (tagName, attribs) => ({tagName, attribs: {
38
+ ...(attribs.href ? {href: attribs.href} : {}),
39
+ ...(attribs.target === '_blank' ? {target: '_blank'} : {}),
40
+ rel: 'noopener noreferrer'
41
+ }})
42
+ },
43
+ // A link with nowhere to go is its text.
44
+ exclusiveFilter: frame => frame.tag === 'a' && !frame.attribs.href && !frame.text.trim()
45
+ };
46
+
47
+ /**
48
+ * @param {string} html
49
+ * @returns {string} cleaned, starting with a block element; '' when it says nothing
50
+ */
51
+ function clean(html) {
52
+ // As the editor writes a line break, so an unedited description reads back the same.
53
+ let out = sanitizeHtml(html, OPTIONS).replace(/<br \/>/g, '<br>').trim();
54
+ // An empty list item reads as its bullet alone: that is still nothing.
55
+ if (!richTextToPlain(isRichText(out) ? out : `<p>${out}</p>`).replace(/^- ?$/gm, '').trim()) return '';
56
+ if (!isRichText(out)) out = `<p>${out}</p>`;
57
+ return out;
58
+ }
59
+
60
+ /**
61
+ * A description as it should be stored.
62
+ *
63
+ * @param {*} value - from a request body
64
+ * @param {{max?: number}} [options] - the longest it may be, markup included
65
+ * @returns {string}
66
+ */
67
+ export function cleanRichText(value, {max = RICH_TEXT_MAX} = {}) {
68
+ if (typeof value !== 'string') return '';
69
+ // eslint-disable-next-line no-control-regex
70
+ const raw = value.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
71
+ if (!isRichText(raw)) return raw.trim().slice(0, max);
72
+ const out = clean(raw);
73
+ // Cut, then cleaned again so no element is left open.
74
+ return out.length > max ? clean(out.slice(0, max)) : out;
75
+ }
76
+
77
+ /**
78
+ * A description as HTML that is safe to put in a page.
79
+ *
80
+ * @param {*} value - as stored
81
+ * @returns {string} '' for nothing
82
+ */
83
+ export function renderRichText(value) {
84
+ if (typeof value !== 'string' || !value.trim()) return '';
85
+ return isRichText(value) ? clean(value) : plainToRichHtml(value);
86
+ }
87
+
88
+ /**
89
+ * The same, for one line of plain text shown inline (a list row, a title
90
+ * attribute): always escaped text, never markup.
91
+ *
92
+ * @param {*} value
93
+ * @param {number} [max]
94
+ * @returns {string}
95
+ */
96
+ export function renderRichTextInline(value, max = 160) {
97
+ return escapeHtml(richTextSummary(value, max));
98
+ }
@@ -41,6 +41,7 @@ import {executePipeline} from './viewPipeline.js';
41
41
  import * as cache from './cache/index.js';
42
42
  import {fileIn} from './safePath.js';
43
43
  import {assertSafeMongoQuery, toSafeMongoPipeline} from './mongoQueryGuard.js';
44
+ import {cleanRichText} from './richText.js';
44
45
 
45
46
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
46
47
  const ROOT = path.resolve(__dirname, '..', '..');
@@ -293,7 +294,7 @@ export async function createView(data, userId = null) {
293
294
  id: uuidv4(),
294
295
  slug,
295
296
  title: title.trim(),
296
- description: description.trim(),
297
+ description: cleanRichText(description, {max: 4000}),
297
298
  connection,
298
299
  pipeline: { source: pipeline.source, stages },
299
300
  display: {
@@ -341,6 +342,7 @@ export async function updateView(slug, data) {
341
342
  // `_id` strip is load-bearing for configs migrated from the legacy
342
343
  // MongoDB store; `id` is immutable.
343
344
  const { _id, id, meta: inputMeta, ...rest } = data;
345
+ if ('description' in rest) rest.description = cleanRichText(rest.description, {max: 4000});
344
346
  const updated = {
345
347
  ...existing,
346
348
  ...rest,