domma-cms 1.66.10 → 1.67.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.
@@ -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.0",
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: {
@@ -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');
@@ -4976,7 +4977,8 @@ async function expandReferenceFields(form) {
4976
4977
  */
4977
4978
  export function formSummaryHtml(form) {
4978
4979
  const title = String(form?.title ?? '').trim();
4979
- const description = String(form?.description ?? '').trim();
4980
+ // Read aloud, so the words alone: a rich description without its markup.
4981
+ const description = richTextToPlain(form?.description).replace(/\s+/g, ' ');
4980
4982
  if (!title && !description) return '';
4981
4983
  return inertShortcodes(`<div class="sr-only cms-form-embed-summary">`
4982
4984
  + (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,