domma-cms 1.47.5 → 1.48.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.
- package/CHANGELOG.md +13 -0
- package/CLAUDE.md +4 -0
- package/admin/js/api.js +1 -1
- package/admin/js/lib/api-tokens-arrange.js +3 -3
- package/admin/js/templates/api-tokens.html +16 -0
- package/admin/js/views/api-tokens.js +33 -6
- package/admin/js/views/page-editor.js +9 -9
- package/docs/DommaFeatures.md +2 -0
- package/docs/api-reference.md +97 -2
- package/docs/plugin-development.md +27 -1
- package/package.json +1 -1
- package/plugins/free-tier.lock.json +13 -11
- package/plugins/shopping-cart/CHANGELOG.md +6 -0
- package/plugins/shopping-cart/CLAUDE.md +7 -1
- package/plugins/shopping-cart/lib/render.js +16 -3
- package/plugins/shopping-cart/plugin.js +15 -3
- package/plugins/shopping-cart/plugin.json +1 -1
- package/plugins/shopping-cart/public/cart.js +17 -1
- package/plugins/shopping-cart/public/lib/orders.js +23 -0
- package/plugins/shopping-cart/public/shop.css +3 -1
- package/plugins/shopping-cart/tests/account-scope.test.js +102 -0
- package/plugins/shopping-cart/tests/accounts.test.js +1 -1
- package/plugins/shopping-cart/tests/checkout-wording.test.js +58 -0
- package/public/js/site.js +1 -1
- package/public/js/token-handover-page.mjs +2 -0
- package/public/js/token-handover.mjs +13 -0
- package/server/routes/api/api-tokens.js +116 -4
- package/server/routes/api/collections.js +69 -0
- package/server/routes/api/content-writes.js +334 -0
- package/server/routes/api/pages.js +21 -1
- package/server/routes/public.js +15 -0
- package/server/routes/token-handover-public.js +59 -0
- package/server/server.js +6 -0
- package/server/services/apiTokens.js +61 -16
- package/server/services/content.js +4 -2
- package/server/services/markdown.js +10 -10
- package/server/services/pluginScope.js +26 -0
- package/server/services/plugins.js +3 -2
- package/server/services/siteGitignore.js +2 -0
- package/server/services/tokenContentPolicy.js +369 -0
- package/server/services/tokenHandovers.js +143 -0
- package/server/services/tokenRecipes.js +207 -0
- package/server/templates/page.html +1 -1
- package/server/templates/token-handover.html +3 -0
|
@@ -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
|
-
|
|
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-${
|
|
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
|
|
|
@@ -83,3 +83,29 @@ export function authenticateFor(authenticate, manifest, scopeOf) {
|
|
|
83
83
|
return out;
|
|
84
84
|
};
|
|
85
85
|
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The auth preHandlers a plugin is handed in `options.auth`.
|
|
89
|
+
*
|
|
90
|
+
* `authenticate` is core's sign-in check plus the scope rule above.
|
|
91
|
+
* `authenticateSelf` is core's sign-in check alone - every token rule (an
|
|
92
|
+
* access token is required, a refresh token is refused, the same JWT
|
|
93
|
+
* verification), but no admin-scope rule. It exists for routes that act only
|
|
94
|
+
* on the caller's own record (`request.user.id`): a shop customer's account,
|
|
95
|
+
* say, whose role confines them to no plugin's screens. Such a route must
|
|
96
|
+
* read and write nothing but the caller's own data; an admin API or anything
|
|
97
|
+
* touching another user's data uses `authenticate`.
|
|
98
|
+
*
|
|
99
|
+
* @param {Function} authenticate - core's preHandler
|
|
100
|
+
* @param {object} manifest
|
|
101
|
+
* @param {(user: object) => ({home: string, allow: string[]}|null)} scopeOf
|
|
102
|
+
* @returns {{authenticate: Function, authenticateSelf: Function}}
|
|
103
|
+
*/
|
|
104
|
+
export function pluginAuthGuards(authenticate, manifest, scopeOf) {
|
|
105
|
+
return {
|
|
106
|
+
authenticate: authenticateFor(authenticate, manifest, scopeOf),
|
|
107
|
+
authenticateSelf: async function authenticateSelf(request, reply) {
|
|
108
|
+
return authenticate(request, reply);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
@@ -45,7 +45,7 @@ import {disableDashboardPro, enableDashboardPro, registerWidget, unregisterWidge
|
|
|
45
45
|
import {createCollection, getCollection} from './collections.js';
|
|
46
46
|
import * as defaultRolesService from './roles.js';
|
|
47
47
|
import {getAdminScope, normaliseAdminScope} from './roles.js';
|
|
48
|
-
import {
|
|
48
|
+
import {pluginAuthGuards} from './pluginScope.js';
|
|
49
49
|
import {getEffectiveRoles} from './userRoles.js';
|
|
50
50
|
import {isDcmStaff} from './staffAccess.js';
|
|
51
51
|
import * as defaultUsersService from './users.js';
|
|
@@ -545,7 +545,8 @@ export async function registerPlugins(fastify) {
|
|
|
545
545
|
prefix,
|
|
546
546
|
// A user confined to some admin screens (role.admin) may call this plugin's
|
|
547
547
|
// authenticated routes only if one of its screens is among them - see pluginScope.js.
|
|
548
|
-
|
|
548
|
+
// authenticateSelf skips that rule, for routes acting only on the caller's own record.
|
|
549
|
+
auth: {...pluginAuthGuards(authenticate, manifest, (user) => getAdminScope(getEffectiveRoles(user || {}))),
|
|
549
550
|
requireRole, requireAdmin, requireVisibility, requirePermission},
|
|
550
551
|
hooks: {registerShortcode, registerSanitizeRules, registerTransform, registerMenuLocation,
|
|
551
552
|
// Stamped with the plugin's name, so the Menus editor can say where a Tool came from.
|
|
@@ -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 < 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
|
+
}
|