domma-cms 1.47.6 → 1.48.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.
@@ -218,7 +218,7 @@ function cleanAdminTags(meta) {
218
218
  else delete meta.adminTags;
219
219
  }
220
220
 
221
- export async function createPage(urlPath, frontmatter, body) {
221
+ export async function createPage(urlPath, frontmatter, body, {exclusive = false} = {}) {
222
222
  const filePath = urlPathToFilePath(urlPath);
223
223
  await fs.mkdir(path.dirname(filePath), { recursive: true });
224
224
 
@@ -243,7 +243,9 @@ export async function createPage(urlPath, frontmatter, body) {
243
243
  if (meta.project === '' || meta.project === undefined) delete meta.project;
244
244
  cleanAdminTags(meta);
245
245
 
246
- await fs.writeFile(filePath, serialiseMarkdown(meta, body || ''), 'utf8');
246
+ // `exclusive`: only ever a new file (an API token's create) - EEXIST when anything is there,
247
+ // even a page whose frontmatter will not parse (getPage reads that as missing).
248
+ await fs.writeFile(filePath, serialiseMarkdown(meta, body || ''), {encoding: 'utf8', ...(exclusive && {flag: 'wx'})});
247
249
  const page = await readPageFile(filePath);
248
250
  await cache.invalidateTags([`page:${urlPath}`, 'sitemap', 'pages:list']);
249
251
  hooks.emit('content:pageCreated', {page, urlPath});
@@ -1080,7 +1080,7 @@ function renderCollectionListgroup(entries, opts, ctxOpts = {}) {
1080
1080
  const itemClasses = ['list-group-item'];
1081
1081
  if (action) itemClasses.push('list-group-item-action');
1082
1082
  if (itemVariant && /^(primary|secondary|success|danger|warning|info)$/.test(itemVariant)) {
1083
- itemClasses.push(`list-group-item-${itemVariant}`);
1083
+ itemClasses.push(`list-group-item-${classToken(itemVariant)}`);
1084
1084
  }
1085
1085
  const itemClassStr = itemClasses.join(' ');
1086
1086
 
@@ -2247,7 +2247,7 @@ function processEffectsBlocks(markdown) {
2247
2247
  const attrs = parseShortcodeAttrs(attrStr);
2248
2248
  const flag = name => attrs[name] === true || attrs[name] === 'true';
2249
2249
  const classes = ['firework'];
2250
- for (const name of ['type', 'colour', 'size']) if (attrs[name]) classes.push(`firework-${escapeAttr(attrs[name])}`);
2250
+ for (const name of ['type', 'colour', 'size']) if (attrs[name]) classes.push(`firework-${classToken(attrs[name])}`);
2251
2251
  if (flag('continuous')) classes.push('firework-continuous');
2252
2252
  const hover = flag('hover');
2253
2253
  if (hover) classes.push('firework-on-hover');
@@ -2652,7 +2652,7 @@ function cardVariantClasses(attrs) {
2652
2652
  const valid = ['clean', 'gradient', 'glass', 'accent', 'dark', 'glow'];
2653
2653
  if (valid.includes(variant)) {
2654
2654
  classes.push(`dm-card-${variant}`);
2655
- if (variant === 'gradient') classes.push(`card-gradient-${gradient}`);
2655
+ if (variant === 'gradient') classes.push(`card-gradient-${classToken(gradient)}`);
2656
2656
  }
2657
2657
  // hover="off" (or false/none/no/0) switches the border colour transition
2658
2658
  // off. Body cards and boxes use the theme colour by default (site.css).
@@ -3841,7 +3841,7 @@ function processBadgeBlocks(markdown) {
3841
3841
  function buildBadge(attrStr, inner) {
3842
3842
  const attrs = parseShortcodeAttrs(attrStr || '');
3843
3843
  const variant = VALID_VARIANTS.has(attrs.variant) ? attrs.variant : 'primary';
3844
- const classes = ['badge', `badge-${variant}`];
3844
+ const classes = ['badge', `badge-${classToken(variant)}`];
3845
3845
 
3846
3846
  // Flag attributes (presence in the raw string, not key=value)
3847
3847
  if (/\bpill\b/i.test(attrStr)) classes.push('badge-pill');
@@ -3946,7 +3946,7 @@ function processButtonBlocks(markdown) {
3946
3946
  const href = attrs.href || '#';
3947
3947
  const label = inner !== null ? inner.trim() : (attrs.label || '');
3948
3948
  const variant = VALID_VARIANTS.has(attrs.variant) ? attrs.variant : 'primary';
3949
- const classes = ['btn', `btn-${variant}`];
3949
+ const classes = ['btn', `btn-${classToken(variant)}`];
3950
3950
  if (attrs.size === 'sm') classes.push('btn-sm');
3951
3951
  if (attrs.size === 'lg') classes.push('btn-lg');
3952
3952
  if (attrs.class) classes.push(escapeAttr(attrs.class));
@@ -4954,12 +4954,12 @@ function processHeroBlocks(markdown) {
4954
4954
  const blobsType = classToken(attrs['blobs-type']) || 'float-blobs';
4955
4955
 
4956
4956
  const classes = ['hero', 'hero-responsive'];
4957
- if (size) classes.push(`hero-${size}`);
4957
+ if (size) classes.push(`hero-${classToken(size)}`);
4958
4958
  if (size === 'xl') classes.push('hero-lg');
4959
- if (variant) classes.push(`hero-${variant}`);
4960
- if (align) classes.push(`hero-${align}`);
4959
+ if (variant) classes.push(`hero-${classToken(variant)}`);
4960
+ if (align) classes.push(`hero-${classToken(align)}`);
4961
4961
  if (image) classes.push('hero-cover');
4962
- if (overlay) classes.push(`hero-overlay-${overlay}`);
4962
+ if (overlay) classes.push(`hero-overlay-${classToken(overlay)}`);
4963
4963
  if (fullwidth) classes.push('hero-breakout');
4964
4964
  if (cls) classes.push(cls);
4965
4965
  classes.push(...injected.effectClasses);
@@ -5053,7 +5053,7 @@ function processBannerBlocks(markdown) {
5053
5053
  const dismissible = isTruthyAttr(attrs.dismissible ?? attrs.dismissable);
5054
5054
  const extraClass = attrs.class || '';
5055
5055
 
5056
- const classes = [`dm-banner`, `dm-banner--${type}`];
5056
+ const classes = [`dm-banner`, `dm-banner--${classToken(type)}`];
5057
5057
  if (extraClass) classes.push(extraClass);
5058
5058
  classes.push(...injected.effectClasses);
5059
5059
 
@@ -329,6 +329,8 @@ export function buildGitignore({sitePlugins = [], pluginContent = {}, sitePublic
329
329
  '/content/.cms-update.json',
330
330
  '/content/instances_log.json',
331
331
  '/content/preview-links.json',
332
+ // One-time API token handovers - ciphertext only (the key is in the link), but nothing for git.
333
+ '/content/token-handovers.json',
332
334
  // Each admin's own Dashboard Pro layout (keyed by user id); the site default beside it is tracked.
333
335
  '/content/dashboard/layouts/',
334
336
  '/content/dashboard/prefs/',
@@ -0,0 +1,369 @@
1
+ /**
2
+ * What an API token may put into a page or a block (routes/api/content-writes.js).
3
+ *
4
+ * The Markdown pipeline trusts its authors: whoever edits a page in the admin
5
+ * may use [dconfig], [collection], [cta], <style>, classes that site.js wires
6
+ * (dm-page-config, dm-cta-trigger…) and the rest - the sanitiser lets them
7
+ * through on purpose. A token is not that author. A bot's draft is rendered for
8
+ * the admin who reviews it, in the preview and on the same origin as their
9
+ * session, so what it writes is held to a much smaller language and checked by
10
+ * PARSING, not by pattern:
11
+ *
12
+ * - HTML is read with htmlparser2 (as a browser would: entities decoded,
13
+ * attributes split properly). Only TOKEN_TAGS, and on each only the
14
+ * attributes TAG_ATTRS lists - never class, id, style, data-* or on*.
15
+ * Address attributes (href, src, srcset, cite) only to http(s), mailto, tel
16
+ * or a path on this site.
17
+ * - Markdown links and images: the same address rule.
18
+ * - Shortcodes: only TOKEN_SHORTCODES (layout and decoration), with no class,
19
+ * id, style, data-* or on* attributes and safe addresses. Never a block
20
+ * ([block] or a block's short tag - a template's {{{raw}}} placeholders would
21
+ * print the token's text as markup), never a plugin's shortcode.
22
+ *
23
+ * Two checks, because a check of the INPUT can always be fooled by a later stage
24
+ * reading the text differently (the third review smuggled live markup through an
25
+ * HTML comment that the policy honoured and the Markdown stage, inside a code
26
+ * span, did not):
27
+ *
28
+ * 1. contentRefusal() - the input: no raw HTML at all (Markdown and the layout
29
+ * shortcodes only), safe addresses, allowlisted shortcodes and parameters.
30
+ * 2. renderedRefusal() - the OUTPUT of the real parseMarkdown(): every element,
31
+ * attribute, class and address checked against what those shortcodes and
32
+ * Markdown are known to emit. Whatever path text takes through the
33
+ * pipeline, what reaches the page is what is judged.
34
+ *
35
+ * Anything else is REFUSED (400, naming it), never silently stripped. Drafts a
36
+ * token wrote are also shown to their reviewer isolated (CSP sandbox, no
37
+ * same-origin), so a miss here still cannot reach the admin's session.
38
+ *
39
+ * Block names are global, and a block's name is also a short tag - so a new
40
+ * block must not take a name something already answers to or asks for.
41
+ */
42
+ import {Parser} from 'htmlparser2';
43
+ import {BUILTIN_SHORTCODES, parseMarkdown, parseShortcodeAttrs} from './markdown.js';
44
+ import {getShortcodeProcessors} from './hooks.js';
45
+
46
+ /**
47
+ * Shortcodes a token may use: static layout only. Not the effects and
48
+ * celebrations (counters, scribe, strobe, fireworks, messages drawn on a
49
+ * canvas…) - they come to life in the browser, and a token's draft is reviewed
50
+ * with scripts off, so the reviewer would never see what they do once published.
51
+ */
52
+ export const TOKEN_SHORTCODES = Object.freeze(['tabs', 'tab', 'accordion', 'item', 'carousel', 'slide', 'timeline', 'event', 'listgroup',
53
+ 'spacer', 'center', 'icon', 'image', 'hero', 'table', 'badge', 'text', 'button', 'link', 'grid', 'row', 'col', 'card', 'box', 'banner',
54
+ 'embed', 'map'].filter(n => BUILTIN_SHORTCODES.has(n)));
55
+ const SAFE_SHORTCODES = new Set(TOKEN_SHORTCODES);
56
+
57
+ /** Plain HTML a token may write, beside Markdown. No forms, frames, scripts, styles, SVG or components. */
58
+ export const TOKEN_TAGS = Object.freeze([
59
+ 'p', 'br', 'hr', 'strong', 'b', 'em', 'i', 'u', 's', 'del', 'ins', 'mark', 'small', 'sub', 'sup', 'span', 'div',
60
+ 'a', 'img', 'figure', 'figcaption', 'picture', 'source', 'blockquote', 'q', 'cite', 'code', 'pre', 'kbd', 'abbr',
61
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
62
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'details', 'summary', 'section', 'article', 'aside', 'header', 'footer'
63
+ ]);
64
+ const SAFE_TAGS = new Set(TOKEN_TAGS);
65
+
66
+ /** The only attributes a token's HTML may carry, per tag. Nothing site.js or Domma wires is among them. */
67
+ const TAG_ATTRS = {
68
+ a: ['href', 'title', 'rel', 'target'],
69
+ img: ['src', 'alt', 'title', 'width', 'height', 'loading'],
70
+ source: ['srcset', 'type', 'media', 'sizes'],
71
+ td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'],
72
+ ol: ['start', 'reversed'], details: ['open'], abbr: ['title'], q: ['cite'], blockquote: ['cite']
73
+ };
74
+ const ANY_TAG_ATTRS = new Set(['title', 'lang', 'dir']);
75
+ const URL_ATTRS = new Set(['href', 'src', 'cite', 'srcset']);
76
+
77
+ /** Shortcode attributes that are addresses. */
78
+ const URL_PARAMS = new Set(['href', 'url', 'src', 'link', 'to', 'image', 'img', 'poster', 'background', 'bg', 'video']);
79
+ /** Shortcode attributes that reach the rendered element as-is: never from a token. */
80
+ const FORBIDDEN_PARAM = /^(class|classes|id|style|on[a-z]+|data-.*|attrs?|html|raw|script)$/i;
81
+
82
+ /** Control, space and zero-width characters a browser ignores inside a URL scheme. */
83
+ const INVISIBLE = new RegExp('[\\u0000-\\u0020\\u007f-\\u00a0\\u200b-\\u200f\\u2028\\u2029\\ufeff]', 'g');
84
+ const NAMED = {amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", colon: ':', tab: '\t', newline: '\n', sol: '/', lpar: '(', rpar: ')'};
85
+
86
+ /** A numeric entity as a browser reads it: out of range (or 0) is U+FFFD, never a throw. */
87
+ const codePoint = (n) => String.fromCodePoint(Number.isInteger(n) && n > 0 && n <= 0x10ffff ? n : 0xfffd);
88
+
89
+ /** The text as a browser would read a URL in it: entities decoded, invisible characters gone, lower case. */
90
+ function normalised(text) {
91
+ return String(text)
92
+ .replace(/&#x([0-9a-f]+);?/gi, (_, h) => codePoint(parseInt(h, 16)))
93
+ .replace(/&#(\d+);?/g, (_, d) => codePoint(Number(d)))
94
+ .replace(/&([a-z]+);/gi, (m, n) => NAMED[n.toLowerCase()] ?? m)
95
+ .replace(INVISIBLE, '')
96
+ .toLowerCase();
97
+ }
98
+
99
+ /**
100
+ * Whether an address may be written by a token: http(s), mailto, tel, or a
101
+ * path/fragment/query on this site. Pure.
102
+ *
103
+ * @param {string} url
104
+ * @returns {boolean}
105
+ */
106
+ export function safeUrl(url) {
107
+ const u = normalised(url);
108
+ if (!u) return true;
109
+ // A backslash is a slash to a browser (/\evil.com is //evil.com); a protocol-relative // leaves the site.
110
+ if (u.includes('\\') || u.startsWith('//')) return false;
111
+ if (/^(\/(?!\/)|#|\?|\.\.?\/)/.test(u)) return true;
112
+ if (/^(https?:\/\/|mailto:|tel:)/.test(u)) return true;
113
+ // A bare relative name ("about", "pic.png") has no scheme at all.
114
+ return !/^[a-z][a-z0-9+.-]*:/.test(u) && !u.startsWith('//');
115
+ }
116
+
117
+ /** Every shortcode name the site answers to: the built-in ones, the plugins' and (given) the blocks'. */
118
+ export function knownShortcodes(blockNames = []) {
119
+ return new Set([...BUILTIN_SHORTCODES, ...getShortcodeProcessors().map(p => p.name), ...blockNames]);
120
+ }
121
+
122
+ function htmlRefusal(src) {
123
+ let why = null;
124
+ const parser = new Parser({
125
+ onopentag(name, attribs) {
126
+ if (why) return;
127
+ const tag = name.toLowerCase();
128
+ if (!SAFE_TAGS.has(tag)) { why = `<${tag}> cannot be written with a token - plain text, Markdown and simple HTML only`; return; }
129
+ const allowed = new Set([...(TAG_ATTRS[tag] || []), ...ANY_TAG_ATTRS]);
130
+ for (const [attr, value] of Object.entries(attribs)) {
131
+ const a = attr.toLowerCase();
132
+ if (!allowed.has(a)) { why = `<${tag} ${a}="…"> cannot be written with a token`; return; }
133
+ const urls = a === 'srcset' ? String(value).split(',').map(c => c.trim().split(/\s+/)[0]) : URL_ATTRS.has(a) ? [value] : [];
134
+ if (urls.some(u => !safeUrl(u))) { why = `<${tag} ${a}="${String(value).slice(0, 40)}"> is not an address a token may write`; return; }
135
+ }
136
+ }
137
+ }, {decodeEntities: true, lowerCaseTags: true, lowerCaseAttributeNames: true});
138
+ // Markdown autolinks (<https://…>, <mailto:…>) are links, not tags; their addresses are safe by scheme.
139
+ parser.write(String(src).replace(/<(?:https?:\/\/|mailto:)[^>\s]*>/gi, ''));
140
+ parser.end();
141
+ return why;
142
+ }
143
+
144
+ function markdownLinkRefusal(src) {
145
+ const urls = [
146
+ ...[...src.matchAll(/\]\(\s*<?([^)\s>]*)/g)].map(m => m[1]),
147
+ ...[...src.matchAll(/^\s{0,3}\[[^\]\n]+\]:\s*<?(\S+?)>?(\s|$)/gm)].map(m => m[1])
148
+ ];
149
+ const bad = urls.find(u => !safeUrl(u));
150
+ return bad === undefined ? null : `The link "${bad.slice(0, 40)}" is not an address a token may write`;
151
+ }
152
+
153
+ function shortcodeRefusal(src, known) {
154
+ for (const m of src.matchAll(/\[\s*(\/?)\s*([a-z][a-z0-9-]*)([^\]]*)\]/gi)) {
155
+ const name = m[2].toLowerCase();
156
+ if (!known.has(name)) continue; // plain text in brackets, not a shortcode
157
+ if (!SAFE_SHORTCODES.has(name)) return `[${name}] cannot be written with a token`;
158
+ if (m[1]) continue; // a closing tag has no attributes
159
+ // Mixed quotes are where two readers of the same text disagree about where a value ends.
160
+ if (m[3].includes('"') && m[3].includes("'")) return `[${name}] may not mix " and ' in its parameters`;
161
+ // Read the parameters exactly as the renderer will (parseShortcodeAttrs), never by a parser of our own.
162
+ for (const [key, value] of Object.entries(parseShortcodeAttrs(m[3]))) {
163
+ const param = key.toLowerCase();
164
+ if (FORBIDDEN_PARAM.test(param)) return `[${name} ${param}="…"] cannot be written with a token`;
165
+ if (typeof value !== 'string') continue;
166
+ if (/["'<>`{}\\]/.test(value)) return `[${name} ${param}] may not contain quotes, < >, { }, \` or \\`;
167
+ // ; and : are how a parameter written into a style becomes more style (color="red;position:fixed").
168
+ if (value.includes(';') || (!URL_PARAMS.has(param) && value.includes(':'))) return `[${name} ${param}] may not contain ; or :`;
169
+ if (URL_PARAMS.has(param) && !safeUrl(value)) return `[${name} ${param}="${value.slice(0, 40)}"] is not an address a token may write`;
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+
175
+ /**
176
+ * Why a token may not write this page or block body, or null when it may.
177
+ *
178
+ * @param {string} text
179
+ * @param {{blockNames?: string[]}} [site] - the site's block names (they are short tags)
180
+ * @returns {string|null}
181
+ */
182
+ export function contentRefusal(text, {blockNames = []} = {}) {
183
+ const src = String(text ?? '');
184
+ // A block template is spliced into a page as it stands; a leading --- block would be frontmatter in one
185
+ // reading and body in another. Nothing a token writes needs to start that way.
186
+ if (/^\s*---/.test(src)) return 'Text may not start with --- when written with a token';
187
+ // No HTML from a token: Markdown and shortcodes only. (Autolinks <https://…> are Markdown.)
188
+ if (/<\s*[a-zA-Z!/?]/.test(src.replace(/<(?:https?:\/\/|mailto:)[^>\s]*>/gi, ''))) {
189
+ return 'HTML cannot be written with a token - use Markdown and the layout shortcodes (write &lt; for a literal <)';
190
+ }
191
+ // {{placeholders}} are a block template's own syntax; {{{raw}}} prints a value as markup.
192
+ if (src.includes('{{')) return '{{…}} cannot be written with a token';
193
+ const flat = normalised(src);
194
+ for (const scheme of ['javascript:', 'vbscript:', 'data:text/html', 'data:image/svg']) {
195
+ if (flat.includes(scheme)) return `"${scheme}" addresses cannot be written with a token`;
196
+ }
197
+ return htmlRefusal(src) || markdownLinkRefusal(src) || shortcodeRefusal(src, knownShortcodes(blockNames));
198
+ }
199
+
200
+ /**
201
+ * Why a block's CSS may not be written with a token, or null. Pure.
202
+ *
203
+ * @param {string} css
204
+ * @returns {string|null}
205
+ */
206
+ export function cssRefusal(css) {
207
+ // CSS escapes (\69mport, \75rl) spell anything; a token's CSS has no need of them.
208
+ if (String(css ?? '').includes('\\')) return "A block's CSS may not use \\ escapes when written with a token";
209
+ const flat = normalised(css ?? '');
210
+ for (const bad of ['@import', 'expression(', 'javascript:', 'behavior:', '-moz-binding', '</style']) {
211
+ if (flat.includes(bad)) return `"${bad}" cannot be written in a block's CSS with a token`;
212
+ }
213
+ for (const m of flat.matchAll(/url\(\s*['"]?([^'")]*)/g)) {
214
+ // Only this site's media: any other host learns who looked, and what (CSS exfiltration).
215
+ if (!/^\/media\/[\w./-]+$/.test(m[1])) return 'CSS url() may only point at /media/…';
216
+ }
217
+ return null;
218
+ }
219
+
220
+ /**
221
+ * Why a token may not make a block with this name, or null.
222
+ *
223
+ * `bodies` are the site's markup (pages, blocks): a block is asked for there by
224
+ * `template="x"`, `block="x"` ([collection]/[view] displays) or its short tag.
225
+ * `configs` are raw JSON (views, site.json, menus…): any string value equal to
226
+ * the name counts - a view's display.block, a footer block.
227
+ *
228
+ * @param {string} name
229
+ * @param {{bodies?: string[], configs?: string[]}} site
230
+ * @returns {string|null}
231
+ */
232
+ export function blockNameRefusal(name, {bodies = [], configs = []} = {}) {
233
+ if (typeof name !== 'string' || name.length > 64) return 'A block name is at most 64 characters';
234
+ if (knownShortcodes().has(name)) return `"${name}" is a shortcode name - a block called that would take its place on every page`;
235
+ const esc = name.replace(/-/g, '\\-');
236
+ const asked = new RegExp(`(template|block)\\s*=\\s*["']?${esc}(["'\\s/\\]]|$)|\\[\\s*${esc}(?=[\\s/\\]])`, 'i');
237
+ if (bodies.some(b => asked.test(b))) return `Something on the site already asks for a block called "${name}" - choose another name`;
238
+ const quoted = `"${name}"`;
239
+ if (configs.some(c => c.includes(quoted))) return `The site's settings already name a block "${name}" - choose another name`;
240
+ return null;
241
+ }
242
+
243
+ // ---- 2. The rendered output -------------------------------------------------
244
+
245
+ /** Elements Markdown and the token shortcodes emit. */
246
+ const OUT_TAGS = new Set([...TOKEN_TAGS, 'button', 'iframe']);
247
+ /** Attributes they emit. data-* only these; nothing that site.js or Domma would act on. */
248
+ const OUT_ATTRS = new Set(['class', 'href', 'src', 'srcset', 'alt', 'title', 'loading', 'referrerpolicy', 'allow', 'allowfullscreen',
249
+ 'role', 'type', 'width', 'height', 'colspan', 'rowspan', 'scope', 'start', 'reversed', 'open', 'rel', 'target', 'style', 'cite', 'lang', 'dir',
250
+ 'data-date', 'data-icon', 'data-layout', 'data-mode', 'data-theme', 'data-to', 'data-multi', 'data-collapsible',
251
+ // [carousel]'s options, read by Domma's carousel (values are a token's plain words: no ; : quotes or brackets)
252
+ 'data-autoplay', 'data-interval', 'data-loop', 'data-animation', 'data-animation-duration', 'data-animation-easing', 'data-height',
253
+ 'data-arrow-color', 'data-arrow-background', 'data-background', 'data-mobile-popup']);
254
+ const OUT_ATTR_PATTERNS = [/^aria-[a-z]+$/, /^data-fx-[a-z-]+$/];
255
+ /**
256
+ * EVERY class the token shortcodes and Markdown emit, with their parameter
257
+ * values enumerated - nothing else. A site's stylesheet has classes that fix a
258
+ * panel over the page (fixed, modal, sidebar-overlay, fireworks-container…); a
259
+ * class a token could name freely is an overlay the style allowlist never sees.
260
+ */
261
+ const TONES = 'primary|secondary|success|danger|warning|info|light|dark';
262
+ const OUT_CLASSES = [
263
+ /^(accordion|accordion-(body|button|content|header|icon|item)|active|badge|badge-pill|btn|card|card-(body|header|title|subtitle|footer|media|media-img|collapsible|hover|no-hover|header-icon-inline|header-content|icon-sized)|carousel|carousel-(slide|slide-content|slide-description|track)|col|row|grid|grid-breakout|hero|hero-(body|content|title|subtitle|subtitle-responsive|image|responsive|title-responsive|cover|center|breakout)|mb-4|tab-(content|item|list|panel)|table|table-responsive|table-(striped|hover|bordered|compact|sm|dark)|tabs|list-group|list-group-flush|list-group-item|list-group-item-action|dm-tg|dm-tg--[a-z]{1,12})$/,
264
+ new RegExp(`^(badge-(${TONES}|outline)|btn-(${TONES}|outline|ghost|link|sm|lg)|list-group-item-(${TONES}))$`),
265
+ /^card-(font-(serif|mono)|gradient-[a-z]{1,20}|pad-(compact|spacious)|rounded-(none|xs|sm|lg|full)|shadow-(none|md|lg)|text-(sm|lg|xl)|align-(center|right)|span-([2-6]|full)|icon-align-[a-z]{1,10}|primary)$/,
266
+ /^(col-span-([1-9]|1[0-2])|gap-[0-9]|grid-cols-([1-9]|1[0-2])|grid-cols-(md|lg)-[1-6]|text-(left|center|right))$/,
267
+ new RegExp(`^hero-((sm|md|lg|xl|full|compact)|(left|right)|(${TONES}|gradient)|overlay-(light|dark|primary|gradient))$`),
268
+ /^language-[a-z0-9+#-]{1,20}$/,
269
+ /^dm-(banner|banner--(info|success|warning|danger)|banner__(body|title|icon|dismiss)|box|box-tone|box-(primary|secondary|success|danger|warning|info|light|dark|note|tip)|embed-(blocked|caption)|image--inline|image-missing|card-(clean|gradient|glass|accent|dark|glow)|embed|embed-frame|icon|image|image-frame|image-img|image--(left|center|right)|image--shadow-(sm|md|lg)|image--radius-(sm|md|lg|full)|map|map-frame|progression|progression-(item|item-body|item-title|title)|spacer)$/
270
+ ];
271
+ const classAllowed = (c) => OUT_CLASSES.some(re => re.test(c));
272
+
273
+ /**
274
+ * The style declarations the token shortcodes emit, and the values each may
275
+ * take. Anything else - positioning, transforms, negative margins, sizes that
276
+ * cover the page - is how a "session expired, sign in" overlay is drawn.
277
+ */
278
+ const LENGTH = /^(0|\d{1,4}(\.\d+)?(px|rem|em|%|vh|vw))$/;
279
+ const COLOUR = /^(#[0-9a-f]{3,8}|[a-z]{3,20}|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,\s*(0|1|0?\.\d+)\s*)?\)|var\(--[a-z0-9-]+\))$/;
280
+ const STYLE_VALUES = {
281
+ 'height': (v) => LENGTH.test(v) && !/vh$/.test(v), 'min-height': (v) => LENGTH.test(v) && !/vh$/.test(v),
282
+ 'max-width': (v) => LENGTH.test(v), 'width': (v) => /^(\d{1,3}%|\d{1,4}px|auto)$/.test(v),
283
+ 'text-align': (v) => /^(left|right|center|justify|start|end)$/.test(v),
284
+ 'aspect-ratio': (v) => /^\d{1,2}\s*\/\s*\d{1,2}$/.test(v),
285
+ 'color': (v) => COLOUR.test(v), 'background-color': (v) => COLOUR.test(v),
286
+ 'background-image': (v) => /^url\(\s*['"]?(\/media\/[\w./-]+|https:\/\/[^'"()\s]+)['"]?\s*\)$/.test(v),
287
+ 'background-size': (v) => /^(cover|contain)$/.test(v),
288
+ 'background-position': (v) => /^(left|center|right)\s+(top|center|bottom)$/.test(v),
289
+ 'font-weight': (v) => /^(normal|bold|[1-9]00)$/.test(v), 'font-style': (v) => /^(normal|italic)$/.test(v),
290
+ 'font-size': (v) => /^((\d|\d?\.\d+)(rem|em)|\d{1,3}px|\d{2,3}%)$/.test(v),
291
+ 'display': (v) => /^(block|inline-block|inline)$/.test(v)
292
+ };
293
+
294
+ /** Whole style values the embed and map shortcodes write themselves (no parameter reaches them). */
295
+ const STYLE_EXACT = [
296
+ /^margin:1\.5rem 0$/,
297
+ /^position:relative;width:100%;aspect-ratio:\d{1,2} \/ \d{1,2}$/,
298
+ /^position:absolute;inset:0;width:100%;height:100%;border:0$/
299
+ ];
300
+
301
+ function styleRefusal(style) {
302
+ const whole = String(style).trim().replace(/;$/, '');
303
+ if (STYLE_EXACT.some(re => re.test(whole))) return null;
304
+ for (const decl of String(style).split(';')) {
305
+ if (!decl.trim()) continue;
306
+ const i = decl.indexOf(':');
307
+ const prop = (i < 0 ? decl : decl.slice(0, i)).trim().toLowerCase();
308
+ const value = (i < 0 ? '' : decl.slice(i + 1)).trim().toLowerCase();
309
+ // [text gradient]'s two colours: theme variables, a colour, or color-mix() of them - never a url().
310
+ const ok = /^--dm-tg-[a-z]$/.test(prop) ? (v) => /^[#a-z0-9(),.%\s-]{1,120}$/.test(v) && !v.includes('url') : STYLE_VALUES[prop];
311
+ if (!ok) return `a style "${prop.slice(0, 30)}"`;
312
+ if (!ok(value)) return `a style "${prop}: ${value.slice(0, 30)}"`;
313
+ }
314
+ return null;
315
+ }
316
+
317
+ /**
318
+ * Why the HTML a token's text RENDERS to may not be published, or null. Pure.
319
+ *
320
+ * @param {string} html - parseMarkdown() output
321
+ * @returns {string|null}
322
+ */
323
+ export function renderedRefusal(html) {
324
+ let why = null;
325
+ const parser = new Parser({
326
+ onopentag(name, attribs) {
327
+ if (why) return;
328
+ const tag = name.toLowerCase();
329
+ if (!OUT_TAGS.has(tag)) { why = `it would render a <${tag}>`; return; }
330
+ for (const [attr, value] of Object.entries(attribs)) {
331
+ const a = attr.toLowerCase();
332
+ if (!OUT_ATTRS.has(a) && !OUT_ATTR_PATTERNS.some(re => re.test(a))) { why = `it would render <${tag} ${a}>`; return; }
333
+ if (['href', 'src', 'cite'].includes(a) && !safeUrl(value)) { why = `it would render an address "${String(value).slice(0, 40)}"`; return; }
334
+ if (a === 'srcset' && String(value).split(',').some(c => !safeUrl(c.trim().split(/\s+/)[0]))) { why = 'it would render an unsafe srcset'; return; }
335
+ if (a === 'style') { const bad = styleRefusal(value); if (bad) { why = `it would render ${bad}`; return; } }
336
+ if (a === 'class') {
337
+ const odd = String(value).split(/\s+/).find(c => c && !classAllowed(c));
338
+ if (odd) { why = `it would render the class "${odd.slice(0, 30)}"`; return; }
339
+ }
340
+ if (a === 'type' && tag === 'button' && value !== 'button') { why = 'it would render a submit button'; return; }
341
+ }
342
+ if (tag === 'iframe' && !/^https:\/\//.test(String(attribs.src || ''))) { why = 'it would render a frame that is not https'; return; }
343
+ }
344
+ }, {decodeEntities: true, lowerCaseTags: true, lowerCaseAttributeNames: true});
345
+ parser.write(String(html ?? ''));
346
+ parser.end();
347
+ return why;
348
+ }
349
+
350
+ /**
351
+ * Render a token's text through the real pipeline and judge the result.
352
+ *
353
+ * @param {string} text
354
+ * @returns {Promise<string|null>}
355
+ */
356
+ export async function renderedContentRefusal(text) {
357
+ let html;
358
+ try {
359
+ // Rendered as every real context renders it: the Blog prepends an empty frontmatter
360
+ // ('---\n---\n' + body) and a page body sits after its own. Without this, text that
361
+ // LOOKS like frontmatter was dropped here and rendered there.
362
+ const out = await parseMarkdown('---\n---\n' + String(text ?? ''));
363
+ html = typeof out === 'string' ? out : out?.html;
364
+ } catch {
365
+ return 'It could not be rendered';
366
+ }
367
+ const why = renderedRefusal(html);
368
+ return why ? `Refused: ${why}. Use Markdown and the layout shortcodes only.` : null;
369
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Token handovers - a one-time link that carries a new API token to the
3
+ * person or bot it is for, so the token itself is never pasted into an email
4
+ * or a chat.
5
+ *
6
+ * The server never sees the token. The admin's browser encrypts the
7
+ * connection details (token included) with a random AES-GCM key and sends
8
+ * only the ciphertext here. The key travels in the link's #fragment, which
9
+ * browsers never send to a server, so what is stored in
10
+ * content/token-handovers.json is useless on its own - a copy of the file, a
11
+ * backup or a log line gives nobody the token.
12
+ *
13
+ * A handover opens ONCE (the record is deleted as it is read) and only within
14
+ * its lifetime (24 hours at most). It also dies with its token: revoked or
15
+ * switched off, the link opens nothing.
16
+ */
17
+ import fs from 'node:fs/promises';
18
+ import path from 'node:path';
19
+ import crypto from 'node:crypto';
20
+ import {config} from '../config.js';
21
+
22
+ const STORE_PATH = () => path.join(config.content.contentDir, 'token-handovers.json');
23
+
24
+ export const HANDOVER_PATH = '/_token-handover';
25
+ export const DEFAULT_LIFETIME_MS = 24 * 3_600_000;
26
+ /** The longest a handover link lives - the same as the default: a link is for now, not for later. */
27
+ export const MAX_LIFETIME_MS = DEFAULT_LIFETIME_MS;
28
+ /** A connection file is well under 2 KB; the cap only stops the store being used as a dump. */
29
+ export const MAX_CIPHERTEXT = 16_384;
30
+ const B64URL = /^[A-Za-z0-9_-]+$/;
31
+ const ID_RE = /^[A-Za-z0-9_-]{32}$/;
32
+
33
+ /** Serialises reads-then-writes, so one link can never be opened twice at once. */
34
+ let chain = Promise.resolve();
35
+ function locked(fn) {
36
+ const run = chain.then(fn, fn);
37
+ chain = run.catch(() => {});
38
+ return run;
39
+ }
40
+
41
+ async function readStore() {
42
+ try {
43
+ const parsed = JSON.parse(await fs.readFile(STORE_PATH(), 'utf8'));
44
+ return Array.isArray(parsed) ? parsed : [];
45
+ } catch {
46
+ return [];
47
+ }
48
+ }
49
+
50
+ async function writeStore(rows, now = Date.now()) {
51
+ const kept = rows.filter(r => Date.parse(r.expiresAt) > now);
52
+ await fs.mkdir(path.dirname(STORE_PATH()), {recursive: true});
53
+ const tmp = `${STORE_PATH()}.${process.pid}.tmp`;
54
+ await fs.writeFile(tmp, JSON.stringify(kept, null, 2), {encoding: 'utf8', mode: 0o600});
55
+ await fs.rename(tmp, STORE_PATH());
56
+ }
57
+
58
+ /**
59
+ * Check what the browser sent. Pure.
60
+ *
61
+ * @param {{ciphertext?: unknown, iv?: unknown, lifetimeHours?: unknown}} body
62
+ * @returns {{ok: true, ciphertext: string, iv: string, lifetimeMs: number} | {ok: false, error: string}}
63
+ */
64
+ export function checkHandoverInput(body) {
65
+ const {ciphertext, iv, lifetimeHours} = body || {};
66
+ if (typeof ciphertext !== 'string' || !ciphertext || !B64URL.test(ciphertext)) return {ok: false, error: 'ciphertext must be base64url'};
67
+ if (ciphertext.length > MAX_CIPHERTEXT) return {ok: false, error: 'ciphertext is too large'};
68
+ if (typeof iv !== 'string' || !B64URL.test(iv) || iv.length !== 16) return {ok: false, error: 'iv must be 12 bytes, base64url'};
69
+ let lifetimeMs = DEFAULT_LIFETIME_MS;
70
+ if (lifetimeHours != null) {
71
+ const h = Number(lifetimeHours);
72
+ if (!Number.isFinite(h) || h <= 0) return {ok: false, error: 'lifetimeHours must be a positive number'};
73
+ lifetimeMs = Math.min(Math.round(h * 3_600_000), MAX_LIFETIME_MS);
74
+ }
75
+ return {ok: true, ciphertext, iv, lifetimeMs};
76
+ }
77
+
78
+ /**
79
+ * Store a handover for a token. The caller has already checked the token
80
+ * exists and that the admin may see it.
81
+ *
82
+ * @param {{tokenId: string, ciphertext: string, iv: string, lifetimeMs?: number, createdBy?: string|null}} input
83
+ * @returns {Promise<{id: string, expiresAt: string}>}
84
+ */
85
+ export function createHandover({tokenId, ciphertext, iv, lifetimeMs = DEFAULT_LIFETIME_MS, createdBy = null}, now = Date.now()) {
86
+ return locked(async () => {
87
+ const id = crypto.randomBytes(24).toString('base64url');
88
+ const expiresAt = new Date(now + lifetimeMs).toISOString();
89
+ const rows = await readStore();
90
+ rows.push({id, tokenId, ciphertext, iv, expiresAt, createdAt: new Date(now).toISOString(), createdBy});
91
+ await writeStore(rows, now);
92
+ return {id, expiresAt};
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Open a handover: answer its ciphertext and delete it, so it can never be
98
+ * read again. Null when it does not exist, has expired, or its token is no
99
+ * longer usable (`tokenUsable(tokenId)` false) - the record goes either way.
100
+ *
101
+ * @param {string} id
102
+ * @param {(tokenId: string) => Promise<boolean>} tokenUsable
103
+ * @returns {Promise<{ciphertext: string, iv: string, expiresAt: string} | null>}
104
+ */
105
+ export function openHandover(id, tokenUsable, now = Date.now()) {
106
+ if (typeof id !== 'string' || !ID_RE.test(id)) return Promise.resolve(null);
107
+ return locked(async () => {
108
+ const rows = await readStore();
109
+ const row = rows.find(r => r.id === id);
110
+ if (!row) return null;
111
+ await writeStore(rows.filter(r => r !== row), now);
112
+ if (!(Date.parse(row.expiresAt) > now)) return null;
113
+ if (!(await tokenUsable(row.tokenId))) return null;
114
+ return {ciphertext: row.ciphertext, iv: row.iv, expiresAt: row.expiresAt};
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Drop every handover of a token (on revoke). Not required for safety -
120
+ * openHandover() refuses a dead token - but it keeps the store honest.
121
+ *
122
+ * @param {string} tokenId
123
+ */
124
+ export function dropHandoversFor(tokenId) {
125
+ return locked(async () => {
126
+ const rows = await readStore();
127
+ const kept = rows.filter(r => r.tokenId !== tokenId);
128
+ if (kept.length !== rows.length) await writeStore(kept);
129
+ });
130
+ }
131
+
132
+ /**
133
+ * How many unopened handovers a token has, and when the last one expires -
134
+ * for the admin list. Never returns ids (an id plus the key is the token).
135
+ *
136
+ * @param {string} tokenId
137
+ * @returns {Promise<{pending: number, until: string|null}>}
138
+ */
139
+ export async function handoverStatus(tokenId, now = Date.now()) {
140
+ const rows = (await readStore()).filter(r => r.tokenId === tokenId && Date.parse(r.expiresAt) > now);
141
+ const until = rows.map(r => r.expiresAt).sort().at(-1) || null;
142
+ return {pending: rows.length, until};
143
+ }