@parhelia/head 0.0.0-stage → 1.0.12903
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/LICENSE +8 -0
- package/README.md +194 -2
- package/package.json +119 -4
- package/src/bridge-core.d.ts +97 -0
- package/src/bridge-core.js +173 -0
- package/src/contentful.d.ts +5 -0
- package/src/contentful.js +28 -0
- package/src/env.d.ts +11 -0
- package/src/env.js +47 -0
- package/src/identity.d.ts +45 -0
- package/src/identity.js +137 -0
- package/src/index.d.ts +6 -0
- package/src/index.js +13 -0
- package/src/magnolia.d.ts +60 -0
- package/src/magnolia.js +199 -0
- package/src/refresh-dom.d.ts +9 -0
- package/src/refresh-dom.js +92 -0
- package/src/refresh.d.ts +14 -0
- package/src/refresh.js +63 -0
- package/src/rich-text-reader.js +263 -0
- package/src/rich-text.d.ts +17 -0
- package/src/rich-text.js +354 -0
- package/src/server.d.ts +38 -0
- package/src/server.js +113 -0
- package/src/settings.cjs +35 -0
- package/src/settings.d.cts +7 -0
- package/src/slot-markup.d.ts +5 -0
- package/src/slot-markup.js +24 -0
- package/src/typo3.d.ts +34 -0
- package/src/typo3.js +110 -0
- package/src/umbraco.d.ts +51 -0
- package/src/umbraco.js +146 -0
- package/src/vite.d.ts +18 -0
- package/src/vite.js +53 -0
package/src/rich-text.js
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@parhelia/head/rich-text` — **the allowlist for rich-text HTML a page renders from its CMS**, and a sanitiser that applies
|
|
3
|
+
* it to a string on the server (a server component, `getServerSideProps`) or in the browser, without a DOM.
|
|
4
|
+
*
|
|
5
|
+
* A head below Parhelia's rendering proxy is served from the editor's origin, so a script in a stored rich-text value would
|
|
6
|
+
* run with the editing person's session. Every head writes CMS rich text through `sanitizeRichTextHtml`; the editing bridge
|
|
7
|
+
* applies the same rule to the values it writes into the canvas (`richTextElementAction`, `sanitizeRichTextAttribute`), so
|
|
8
|
+
* the canvas and the page agree on what a value shows.
|
|
9
|
+
*
|
|
10
|
+
* The rule: formatting elements only (others are unwrapped, their text stays; scripts, styles, frames, objects, forms'
|
|
11
|
+
* lists, SVG and MathML are removed with their content); per element a fixed list of attributes, no event handler, no
|
|
12
|
+
* other `data-*` than Parhelia's own placeholder and internal-link markers; link, image and citation URLs only on safe
|
|
13
|
+
* schemes (an image also on `data:image/…` other than SVG); styles limited to formatting properties without resources;
|
|
14
|
+
* ids that cannot shadow a page global. Comments, doctypes and processing instructions are dropped.
|
|
15
|
+
*
|
|
16
|
+
* The sanitiser reads the markup with the HTML tokenizer's rules (tags, attributes, comments, raw-text elements, character
|
|
17
|
+
* references) and writes it again from what the rule keeps: allowlisted tags it spells itself, attribute values and text
|
|
18
|
+
* escaped. Whatever a browser would make of the input, the output holds no element, attribute or URL outside the rule, and its
|
|
19
|
+
* tags are balanced. The reader is `rich-text-reader.js`, pinned with the C# reader to one vector file.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { decodeAttribute, preprocess, RAW_TEXT_TAGS, tokenize } from "./rich-text-reader.js";
|
|
23
|
+
|
|
24
|
+
const ALLOWED_TAGS = new Set([
|
|
25
|
+
"a", "abbr", "b", "blockquote", "br", "caption", "cite", "code", "col",
|
|
26
|
+
"colgroup", "dd", "del", "dfn", "div", "dl", "dt", "em", "figcaption",
|
|
27
|
+
"figure", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "ins", "kbd",
|
|
28
|
+
"li", "mark", "ol", "p", "pre", "q", "s", "samp", "small", "span", "strong",
|
|
29
|
+
"sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "time", "tr",
|
|
30
|
+
"u", "ul", "wbr",
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
/** Removed with their content. Other elements outside the allowlist are unwrapped (their text stays). */
|
|
34
|
+
const DROPPED_TAGS = new Set([
|
|
35
|
+
"script", "style", "textarea", "option", "noscript", "xmp", "noembed",
|
|
36
|
+
"noframes", "iframe", "template", "title", "object", "embed", "applet",
|
|
37
|
+
"frame", "frameset", "select", "link", "meta", "base", "plaintext", "svg", "math",
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
/** Allowlisted elements without content or end tag. */
|
|
41
|
+
const VOID_TAGS = new Set(["br", "col", "hr", "img", "wbr"]);
|
|
42
|
+
|
|
43
|
+
/** Dropped elements without content: only the tag goes. */
|
|
44
|
+
const DROPPED_VOID_TAGS = new Set(["embed", "frame", "link", "meta", "base"]);
|
|
45
|
+
|
|
46
|
+
/** Foreign elements, whose self-closing tag has no content. */
|
|
47
|
+
const FOREIGN_TAGS = new Set(["svg", "math"]);
|
|
48
|
+
|
|
49
|
+
const GLOBAL_ATTRIBUTES = new Set(["class", "id", "title", "lang", "dir", "style"]);
|
|
50
|
+
|
|
51
|
+
const ARIA_ATTRIBUTE = /^aria-[^\s"'<>/=]+$/;
|
|
52
|
+
|
|
53
|
+
const TABLE_CELL_ATTRIBUTES = ["colspan", "rowspan", "headers", "scope", "align", "valign", "width", "height"];
|
|
54
|
+
|
|
55
|
+
/** @type {Record<string, Set<string>>} */
|
|
56
|
+
const TAG_ATTRIBUTES = {
|
|
57
|
+
// data-internal / data-item-id / data-querystring mark internal links for the editor.
|
|
58
|
+
a: new Set(["href", "target", "rel", "data-internal", "data-item-id", "data-querystring"]),
|
|
59
|
+
img: new Set(["src", "alt", "width", "height", "loading"]),
|
|
60
|
+
table: new Set(["border", "cellpadding", "cellspacing", "width", "align"]),
|
|
61
|
+
tr: new Set(["align", "valign"]),
|
|
62
|
+
td: new Set(TABLE_CELL_ATTRIBUTES),
|
|
63
|
+
th: new Set(TABLE_CELL_ATTRIBUTES),
|
|
64
|
+
col: new Set(["span", "width"]),
|
|
65
|
+
colgroup: new Set(["span", "width"]),
|
|
66
|
+
ol: new Set(["start", "reversed", "type"]),
|
|
67
|
+
li: new Set(["value"]),
|
|
68
|
+
time: new Set(["datetime"]),
|
|
69
|
+
del: new Set(["cite", "datetime"]),
|
|
70
|
+
ins: new Set(["cite", "datetime"]),
|
|
71
|
+
blockquote: new Set(["cite"]),
|
|
72
|
+
q: new Set(["cite"]),
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A canonical rich-text value carries an embed, a resource link or a gap as an empty placeholder element whose data
|
|
77
|
+
* attributes hold the whole node: inert data, kept on the placeholder elements only.
|
|
78
|
+
*/
|
|
79
|
+
const PLACEHOLDER_ATTRIBUTES = new Set([
|
|
80
|
+
"data-parhelia-embed",
|
|
81
|
+
"data-parhelia-target",
|
|
82
|
+
"data-parhelia-label",
|
|
83
|
+
"data-parhelia-node",
|
|
84
|
+
"data-parhelia-bare",
|
|
85
|
+
]);
|
|
86
|
+
const PLACEHOLDER_TAGS = new Set(["div", "span"]);
|
|
87
|
+
|
|
88
|
+
const URL_ATTRIBUTES = new Set(["href", "src", "cite"]);
|
|
89
|
+
const URL_SCHEMES = new Set(["http", "https", "mailto", "tel"]);
|
|
90
|
+
// A rich-text link to the store's own content is its canonical reference (`parhelia:entry/…`, `parhelia:asset/…`) until
|
|
91
|
+
// the page renders the stored link; inert in a browser. Only a link's href carries it.
|
|
92
|
+
const LINK_URL_SCHEMES = new Set([...URL_SCHEMES, "parhelia"]);
|
|
93
|
+
const IMAGE_URL_SCHEMES = new Set(["http", "https", "data"]);
|
|
94
|
+
/** The only `data:` URLs kept: an image's raster data. */
|
|
95
|
+
const IMAGE_DATA_URL = /^data:image\/(?!svg)[a-z0-9.+-]+[;,]/i;
|
|
96
|
+
|
|
97
|
+
const STYLE_PROPERTIES = new Set([
|
|
98
|
+
"color", "background-color", "font-family", "font-size", "font-style",
|
|
99
|
+
"font-weight", "letter-spacing", "line-height", "text-align",
|
|
100
|
+
"text-decoration", "text-decoration-line", "text-decoration-color",
|
|
101
|
+
"text-decoration-style", "text-indent", "text-transform", "vertical-align",
|
|
102
|
+
"white-space", "direction", "margin", "margin-top", "margin-right",
|
|
103
|
+
"margin-bottom", "margin-left", "padding", "padding-top", "padding-right",
|
|
104
|
+
"padding-bottom", "padding-left", "border", "border-top", "border-right",
|
|
105
|
+
"border-bottom", "border-left", "border-color", "border-style",
|
|
106
|
+
"border-width", "border-collapse", "border-spacing", "border-radius",
|
|
107
|
+
"width", "height", "min-width", "max-width", "min-height", "max-height",
|
|
108
|
+
"list-style-type", "float", "clear", "display",
|
|
109
|
+
]);
|
|
110
|
+
|
|
111
|
+
// Nothing that positions content over the page (an overlay inside the canvas) and no value that loads a resource.
|
|
112
|
+
const UNSAFE_STYLE_VALUE =
|
|
113
|
+
/url\s*\(|image-set\s*\(|image\s*\(|expression\s*\(|javascript:|vbscript:|@import|behavior|binding|\\/i;
|
|
114
|
+
|
|
115
|
+
// Leading underscores are what page scripts use for globals (__NEXT_DATA__, __PARHELIA_EDITING_BRIDGE_RUNTIME__); an id
|
|
116
|
+
// there would shadow them.
|
|
117
|
+
const SAFE_ID = /^[A-Za-z][\w:.-]*$/;
|
|
118
|
+
|
|
119
|
+
/** The browsing contexts a link may open in: its own frame, or a new one (an empty target is its own). */
|
|
120
|
+
const SAFE_TARGETS = new Set(["", "_self", "_blank"]);
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Whether a declaration's value reads the same written alone as inside the style: every quote closed on its line, no brace or
|
|
124
|
+
* bracket (CSS reads a block to its end, across later declarations).
|
|
125
|
+
* @param {string} value
|
|
126
|
+
*/
|
|
127
|
+
function isSettled(value) {
|
|
128
|
+
let quote = "";
|
|
129
|
+
for (const char of value) {
|
|
130
|
+
if (quote) {
|
|
131
|
+
if (char === quote) quote = "";
|
|
132
|
+
else if (char === "\n" || char === "\r" || char === "\f") return false;
|
|
133
|
+
} else if (char === '"' || char === "'") quote = char;
|
|
134
|
+
else if ("{}[]\n\r\f".includes(char)) return false;
|
|
135
|
+
}
|
|
136
|
+
return quote === "";
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* What the rule does with an element of the HTML namespace: keep it, unwrap it (its content stays) or drop it with its
|
|
141
|
+
* content. Elements of another namespace (SVG, MathML) are dropped.
|
|
142
|
+
* @param {string} tag the element's local name, lowercase
|
|
143
|
+
* @returns {"keep" | "unwrap" | "drop"}
|
|
144
|
+
*/
|
|
145
|
+
export function richTextElementAction(tag) {
|
|
146
|
+
if (ALLOWED_TAGS.has(tag)) return "keep";
|
|
147
|
+
return DROPPED_TAGS.has(tag) ? "drop" : "unwrap";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The value an attribute keeps on an allowlisted element, or null when the rule removes it. `value` is the attribute's
|
|
152
|
+
* value as a browser reads it (character references decoded). A style keeps its formatting declarations only.
|
|
153
|
+
* @param {string} tag the element's local name, lowercase
|
|
154
|
+
* @param {string} name the attribute's name, lowercase
|
|
155
|
+
* @param {string} value
|
|
156
|
+
* @returns {string | null}
|
|
157
|
+
*/
|
|
158
|
+
export function sanitizeRichTextAttribute(tag, name, value) {
|
|
159
|
+
const allowed =
|
|
160
|
+
GLOBAL_ATTRIBUTES.has(name) ||
|
|
161
|
+
ARIA_ATTRIBUTE.test(name) ||
|
|
162
|
+
TAG_ATTRIBUTES[tag]?.has(name) === true ||
|
|
163
|
+
(PLACEHOLDER_TAGS.has(tag) && PLACEHOLDER_ATTRIBUTES.has(name));
|
|
164
|
+
if (!allowed) return null;
|
|
165
|
+
if (URL_ATTRIBUTES.has(name)) {
|
|
166
|
+
const schemes = tag === "img" ? IMAGE_URL_SCHEMES : tag === "a" && name === "href" ? LINK_URL_SCHEMES : URL_SCHEMES;
|
|
167
|
+
return isAllowedUrl(value, schemes) ? value : null;
|
|
168
|
+
}
|
|
169
|
+
if (name === "id") return SAFE_ID.test(value) ? value : null;
|
|
170
|
+
// A link opens in its own browsing context or a new one: `_top`, `_parent` or a named target would navigate the frame the
|
|
171
|
+
// canvas lives in (the editor) or another window.
|
|
172
|
+
if (name === "target") return SAFE_TARGETS.has(value.trim().toLowerCase()) ? value : null;
|
|
173
|
+
if (name === "style") {
|
|
174
|
+
const style = sanitizeStyle(value);
|
|
175
|
+
if (style === "") return null;
|
|
176
|
+
return style === value ? value : style;
|
|
177
|
+
}
|
|
178
|
+
return value;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Filters rich-text HTML down to the rule above and writes it again; `""` for anything but a string.
|
|
183
|
+
* @param {string} html
|
|
184
|
+
* @returns {string}
|
|
185
|
+
*/
|
|
186
|
+
export function sanitizeRichTextHtml(html) {
|
|
187
|
+
if (typeof html !== "string" || html === "") return "";
|
|
188
|
+
const input = preprocess(html);
|
|
189
|
+
let out = "";
|
|
190
|
+
/** @type {{ name: string; depth: number } | null} */
|
|
191
|
+
let skipping = null;
|
|
192
|
+
// The kept elements open in the output: its tags are balanced, so a value never closes, or leaves open, an element of the
|
|
193
|
+
// page it is written into.
|
|
194
|
+
/** @type {string[]} */
|
|
195
|
+
const open = [];
|
|
196
|
+
for (const token of tokenize(input)) {
|
|
197
|
+
if (skipping) {
|
|
198
|
+
if (token.type === "start" && token.name === skipping.name && !opensNothing(token)) skipping.depth++;
|
|
199
|
+
else if (token.type === "end" && token.name === skipping.name && --skipping.depth === 0) skipping = null;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (token.type === "text") {
|
|
203
|
+
out += escapeText(token.value);
|
|
204
|
+
} else if (token.type === "start") {
|
|
205
|
+
const action = richTextElementAction(token.name);
|
|
206
|
+
if (action === "keep") {
|
|
207
|
+
out += startTag(token);
|
|
208
|
+
if (!VOID_TAGS.has(token.name)) open.push(token.name);
|
|
209
|
+
} else if (action === "drop" && !RAW_TEXT_TAGS.has(token.name) && !opensNothing(token))
|
|
210
|
+
skipping = { name: token.name, depth: 1 };
|
|
211
|
+
} else if (token.type === "end" && richTextElementAction(token.name) === "keep") {
|
|
212
|
+
// `</br>` is a line break to a browser; the other void elements have no end tag.
|
|
213
|
+
if (token.name === "br") out += "<br>";
|
|
214
|
+
else if (!VOID_TAGS.has(token.name)) {
|
|
215
|
+
// An end tag closes its element and every element opened inside it; one that closes nothing open is dropped.
|
|
216
|
+
const at = open.lastIndexOf(token.name);
|
|
217
|
+
if (at >= 0) while (open.length > at) out += `</${open.pop()}>`;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
while (open.length > 0) out += `</${open.pop()}>`;
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** @param {{ name: string; selfClosing: boolean }} token */
|
|
226
|
+
const opensNothing = token => DROPPED_VOID_TAGS.has(token.name) || (token.selfClosing && FOREIGN_TAGS.has(token.name));
|
|
227
|
+
|
|
228
|
+
/** @param {string} value @param {Set<string>} schemes */
|
|
229
|
+
function isAllowedUrl(value, schemes) {
|
|
230
|
+
// Browsers ignore ASCII whitespace and control characters here ("java\tscript:"), so the check does too.
|
|
231
|
+
const url = value.replace(/[\x00-\x20]+/g, "");
|
|
232
|
+
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url)?.[1]?.toLowerCase();
|
|
233
|
+
if (scheme === undefined) return true;
|
|
234
|
+
if (!schemes.has(scheme)) return false;
|
|
235
|
+
return scheme !== "data" || IMAGE_DATA_URL.test(url);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Splits "a: b; c: d" into declarations as CSS reads them: a comment is no text (it separates what stands around it), a `;`
|
|
240
|
+
* inside quotes, parentheses, brackets or braces ends nothing, and a line break inside quotes breaks the string, which makes its
|
|
241
|
+
* declaration invalid (CSS then reads on after it, so what follows is a declaration of its own).
|
|
242
|
+
* @param {string} style
|
|
243
|
+
* @returns {{ text: string; broken: boolean }[]}
|
|
244
|
+
*/
|
|
245
|
+
function cssDeclarations(style) {
|
|
246
|
+
/** @type {{ text: string; broken: boolean }[]} */
|
|
247
|
+
const declarations = [];
|
|
248
|
+
let current = "";
|
|
249
|
+
let broken = false;
|
|
250
|
+
let quote = "";
|
|
251
|
+
let depth = 0;
|
|
252
|
+
for (let i = 0; i < style.length; i++) {
|
|
253
|
+
const char = style.charAt(i);
|
|
254
|
+
if (quote) {
|
|
255
|
+
if (char === "\n" || char === "\r" || char === "\f") {
|
|
256
|
+
quote = "";
|
|
257
|
+
broken = true;
|
|
258
|
+
} else if (char === quote) quote = "";
|
|
259
|
+
current += char;
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (char === "/" && style.charAt(i + 1) === "*") {
|
|
263
|
+
const end = style.indexOf("*/", i + 2);
|
|
264
|
+
i = end < 0 ? style.length : end + 1;
|
|
265
|
+
current += " ";
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
if (char === '"' || char === "'") quote = char;
|
|
269
|
+
else if (char === "(" || char === "[" || char === "{") depth++;
|
|
270
|
+
else if (char === ")" || char === "]" || char === "}") depth = Math.max(0, depth - 1);
|
|
271
|
+
else if (char === ";" && depth === 0) {
|
|
272
|
+
declarations.push({ text: current, broken });
|
|
273
|
+
current = "";
|
|
274
|
+
broken = false;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
current += char;
|
|
278
|
+
}
|
|
279
|
+
declarations.push({ text: current, broken });
|
|
280
|
+
return declarations.map(({ text, broken }) => ({ text: text.trim(), broken })).filter(({ text }) => text !== "");
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* The style's formatting declarations, written again (`property: value; …`): an allowlisted property whose value loads no
|
|
285
|
+
* resource and keeps CSS's reading of the written style the same — no line break, no unbalanced quote, no brace.
|
|
286
|
+
* @param {string} style
|
|
287
|
+
*/
|
|
288
|
+
function sanitizeStyle(style) {
|
|
289
|
+
return cssDeclarations(style)
|
|
290
|
+
.filter(({ text, broken }) => {
|
|
291
|
+
if (broken) return false;
|
|
292
|
+
const colon = text.indexOf(":");
|
|
293
|
+
if (colon <= 0) return false;
|
|
294
|
+
const property = text.slice(0, colon).trim().toLowerCase();
|
|
295
|
+
const value = text.slice(colon + 1);
|
|
296
|
+
return STYLE_PROPERTIES.has(property) && !UNSAFE_STYLE_VALUE.test(value) && isSettled(value);
|
|
297
|
+
})
|
|
298
|
+
.map(({ text }) => text)
|
|
299
|
+
.join("; ");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ---- Writing ---------------------------------------------------------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
/** Text: no markup can start in it. Character references stay for the browser (they only ever make characters). */
|
|
305
|
+
const escapeText = (/** @type {string} */ text) => text.replace(/</g, "<").replace(/>/g, ">");
|
|
306
|
+
|
|
307
|
+
/** A decoded attribute value written back. */
|
|
308
|
+
const escapeAttribute = (/** @type {string} */ value) =>
|
|
309
|
+
value
|
|
310
|
+
.replace(/&/g, "&")
|
|
311
|
+
.replace(/"/g, """)
|
|
312
|
+
.replace(/ /g, " ")
|
|
313
|
+
.replace(/</g, "<")
|
|
314
|
+
.replace(/>/g, ">");
|
|
315
|
+
|
|
316
|
+
/** @param {import("./rich-text-reader.js").StartToken} token */
|
|
317
|
+
function startTag(token) {
|
|
318
|
+
let tag = `<${token.name}`;
|
|
319
|
+
/** @type {Set<string>} */
|
|
320
|
+
const seen = new Set();
|
|
321
|
+
for (const [name, raw] of token.attributes) {
|
|
322
|
+
// A repeated attribute is ignored, as a browser does.
|
|
323
|
+
if (seen.has(name)) continue;
|
|
324
|
+
seen.add(name);
|
|
325
|
+
const value = attributeValue(token.name, name, raw);
|
|
326
|
+
if (value !== null) tag += ` ${name}="${value}"`;
|
|
327
|
+
}
|
|
328
|
+
return `${tag}>`;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* The written value of one attribute, or null when the rule removes it. The value is decoded as a browser decodes it; a
|
|
333
|
+
* named reference this module does not know (it decodes to a character outside ASCII) is written back unchanged, so the
|
|
334
|
+
* browser decodes it the same. Such a reference before a URL's path, or anywhere in a style, removes the attribute.
|
|
335
|
+
* @param {string} tag @param {string} name @param {string} raw
|
|
336
|
+
*/
|
|
337
|
+
function attributeValue(tag, name, raw) {
|
|
338
|
+
const parts = decodeAttribute(raw);
|
|
339
|
+
const value = parts.map(part => part.text).join("");
|
|
340
|
+
const kept = sanitizeRichTextAttribute(tag, name, value);
|
|
341
|
+
if (kept === null) return null;
|
|
342
|
+
const opaque = parts.some(part => part.opaque);
|
|
343
|
+
if (opaque) {
|
|
344
|
+
if (name === "style") return null;
|
|
345
|
+
if (URL_ATTRIBUTES.has(name)) {
|
|
346
|
+
const end = value.search(/[/?#]/);
|
|
347
|
+
const head = end < 0 ? value : value.slice(0, end);
|
|
348
|
+
if (head.includes("&")) return null;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (kept !== value) return escapeAttribute(kept);
|
|
352
|
+
return parts.map(part => (part.opaque ? part.text : escapeAttribute(part.text))).join("");
|
|
353
|
+
}
|
|
354
|
+
|
package/src/server.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** A request whose headers carry the editor signal: a Node request, a Web `Request`, or a `Headers` (App Router `headers()`). */
|
|
2
|
+
export type EditorSignalRequest =
|
|
3
|
+
| { readonly headers?: Headers | Readonly<Record<string, string | readonly string[] | undefined>> }
|
|
4
|
+
| Headers
|
|
5
|
+
| null
|
|
6
|
+
| undefined;
|
|
7
|
+
|
|
8
|
+
/** A query as the Pages Router (`query`), the App Router (`searchParams`) or `URLSearchParams` hand it over. */
|
|
9
|
+
export type EditorFrameQuery = URLSearchParams | Readonly<Record<string, string | string[] | undefined>> | null | undefined;
|
|
10
|
+
|
|
11
|
+
/** The request header Parhelia's rendering proxy carries the host entry's `editorSecret` in (lower case). */
|
|
12
|
+
export declare const EDITOR_SIGNAL_HEADER: "x-parhelia-editor";
|
|
13
|
+
|
|
14
|
+
/** The environment variable a head keeps the host entry's `editorSecret` in (read at call time). */
|
|
15
|
+
export declare const EDITOR_SECRET_ENV: "PARHELIA_EDITOR_SECRET";
|
|
16
|
+
|
|
17
|
+
/** True only when a secret is configured and the header carries exactly that value (the first one when sent twice). */
|
|
18
|
+
export declare function editorSignalAccepted(
|
|
19
|
+
headerValue: string | readonly string[] | null | undefined,
|
|
20
|
+
configuredSecret: string | null | undefined,
|
|
21
|
+
): boolean;
|
|
22
|
+
|
|
23
|
+
/** Whether the request carries the rendering proxy's signal for this head's secret (`PARHELIA_EDITOR_SECRET` unless given). */
|
|
24
|
+
export declare function hasEditorSignal(request: EditorSignalRequest, configuredSecret?: string | null): boolean;
|
|
25
|
+
|
|
26
|
+
/** Whether the query names one of Parhelia's frames (`parhelia=1`, which every edit URL the editor builds carries). */
|
|
27
|
+
export declare function isEditorFrameQuery(query: EditorFrameQuery): boolean;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The editing decision of a request: one of Parhelia's frames that carries the proxy's signal for this head's secret
|
|
31
|
+
* (`PARHELIA_EDITOR_SECRET` unless given), or a live preview session.
|
|
32
|
+
*/
|
|
33
|
+
export declare function isEditingRequest(
|
|
34
|
+
request: EditorSignalRequest,
|
|
35
|
+
query: EditorFrameQuery,
|
|
36
|
+
hasPreviewSession: boolean,
|
|
37
|
+
configuredSecret?: string | null,
|
|
38
|
+
): boolean;
|
package/src/server.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@parhelia/head/server` — the editor signal of a rendering head (server-side only: `getServerSideProps`, route handlers,
|
|
3
|
+
* server components, a proxy). Framework-neutral: it reads a request's headers whatever their shape (a Node request, a Web
|
|
4
|
+
* `Request`/`NextRequest`, `headers()` of the App Router) and a query as the Pages Router, the App Router or
|
|
5
|
+
* `URLSearchParams` hand it over.
|
|
6
|
+
*
|
|
7
|
+
* A request is the Parhelia editor's canvas when it arrives through Parhelia's rendering proxy, which forwards requests only
|
|
8
|
+
* for a signed-in editor and stamps them with `X-Parhelia-Editor: <editorSecret>` from the host entry
|
|
9
|
+
* (`parhelia.host.{name}`; the proxy drops whatever the browser sent under that name), and the head's
|
|
10
|
+
* `PARHELIA_EDITOR_SECRET` equals it — or when the request carries a live Parhelia preview session (its ticket was redeemed,
|
|
11
|
+
* signed with the head's preview key, for a code only the editor mints; `@parhelia/preview-ticket`). Query parameters (`parhelia=1`)
|
|
12
|
+
* only say WHICH editor request this is, never WHETHER it is one: a visitor can type them. No secret configured and no
|
|
13
|
+
* session = never the editor.
|
|
14
|
+
*/
|
|
15
|
+
import { isParheliaFrameRequest } from "./identity.js";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The request header Parhelia's rendering proxy carries the host entry's `editorSecret` in (lower case, as Node keys it).
|
|
19
|
+
* The name is the preview protocol's `editorSignalHeader` (`@parhelia/preview-ticket`'s `fixtures/preview-protocol.json`,
|
|
20
|
+
* .NET `PreviewProtocol.EditorSignalHeader`), pinned by `server.test.ts`.
|
|
21
|
+
*/
|
|
22
|
+
export const EDITOR_SIGNAL_HEADER = "x-parhelia-editor";
|
|
23
|
+
|
|
24
|
+
/** The environment variable a head keeps the host entry's `editorSecret` in (read at call time, never at import). */
|
|
25
|
+
export const EDITOR_SECRET_ENV = "PARHELIA_EDITOR_SECRET";
|
|
26
|
+
|
|
27
|
+
/** @param {() => string | undefined} value */
|
|
28
|
+
const read = (value) => {
|
|
29
|
+
try {
|
|
30
|
+
return value() || "";
|
|
31
|
+
} catch {
|
|
32
|
+
return ""; // no `process` in this runtime
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** The head's configured editor secret, "" when none. */
|
|
37
|
+
const configuredEditorSecret = () => read(() => process.env[EDITOR_SECRET_ENV]);
|
|
38
|
+
|
|
39
|
+
const encoder = new TextEncoder();
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Equal strings, compared in time that depends only on their lengths (Web APIs only, so it runs on Node and the Edge alike).
|
|
43
|
+
* @param {string} supplied
|
|
44
|
+
* @param {string} expected
|
|
45
|
+
*/
|
|
46
|
+
const constantTimeEquals = (supplied, expected) => {
|
|
47
|
+
const a = encoder.encode(supplied);
|
|
48
|
+
const b = encoder.encode(expected);
|
|
49
|
+
if (a.length !== b.length) return false;
|
|
50
|
+
let difference = 0;
|
|
51
|
+
for (let index = 0; index < a.length; index++) difference |= /** @type {number} */ (a[index]) ^ /** @type {number} */ (b[index]);
|
|
52
|
+
return difference === 0;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* True only when a secret is configured and the header carries exactly that value (the first one when it was sent twice).
|
|
57
|
+
* @param {string | readonly string[] | null | undefined} headerValue
|
|
58
|
+
* @param {string | null | undefined} configuredSecret
|
|
59
|
+
*/
|
|
60
|
+
export function editorSignalAccepted(headerValue, configuredSecret) {
|
|
61
|
+
const secret = configuredSecret?.trim();
|
|
62
|
+
if (!secret) return false;
|
|
63
|
+
const supplied = Array.isArray(headerValue) ? headerValue[0] : headerValue;
|
|
64
|
+
return typeof supplied === "string" && constantTimeEquals(supplied, secret);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The editor signal header of a request: a Node request or `IncomingHttpHeaders`-like record, a Web `Request`, or a
|
|
69
|
+
* `Headers` (`await headers()` in the App Router).
|
|
70
|
+
* @param {{ headers?: unknown } | Headers | null | undefined} request
|
|
71
|
+
* @returns {string | readonly string[] | undefined}
|
|
72
|
+
*/
|
|
73
|
+
const signalHeaderOf = (request) => {
|
|
74
|
+
if (!request) return undefined;
|
|
75
|
+
const headers = typeof (/** @type {Headers} */ (request).get) === "function" ? request : /** @type {{ headers?: unknown }} */ (request).headers;
|
|
76
|
+
if (!headers || typeof headers !== "object") return undefined;
|
|
77
|
+
if (typeof (/** @type {Headers} */ (headers).get) === "function") return /** @type {Headers} */ (headers).get(EDITOR_SIGNAL_HEADER) ?? undefined;
|
|
78
|
+
const record = /** @type {Record<string, string | readonly string[] | undefined>} */ (headers);
|
|
79
|
+
if (EDITOR_SIGNAL_HEADER in record) return record[EDITOR_SIGNAL_HEADER];
|
|
80
|
+
const name = Object.keys(record).find((key) => key.toLowerCase() === EDITOR_SIGNAL_HEADER);
|
|
81
|
+
return name === undefined ? undefined : record[name];
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Whether the request carries the rendering proxy's signal for this head's secret (`PARHELIA_EDITOR_SECRET` unless given).
|
|
86
|
+
* @param {{ headers?: unknown } | Headers | null | undefined} request
|
|
87
|
+
* @param {string | null | undefined} [configuredSecret]
|
|
88
|
+
*/
|
|
89
|
+
export function hasEditorSignal(request, configuredSecret = configuredEditorSecret()) {
|
|
90
|
+
return editorSignalAccepted(signalHeaderOf(request), configuredSecret);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Whether the query names one of Parhelia's frames: `parhelia=1` (`isParheliaFrameRequest`), which every edit URL the editor builds
|
|
95
|
+
* carries (a CMS's own edit-mode parameters are that CMS's heads' business, not this SDK's).
|
|
96
|
+
* @param {URLSearchParams | Record<string, string | string[] | undefined> | null | undefined} query
|
|
97
|
+
*/
|
|
98
|
+
export function isEditorFrameQuery(query) {
|
|
99
|
+
if (!query) return false;
|
|
100
|
+
return isParheliaFrameRequest(query);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The editing decision of a request: one of Parhelia's frames (query) that carries the proxy's signal for this head's
|
|
105
|
+
* secret, or a live preview session. Only then does a head render markers, the rendered coordinate and empty components.
|
|
106
|
+
* @param {{ headers?: unknown } | Headers | null | undefined} request
|
|
107
|
+
* @param {URLSearchParams | Record<string, string | string[] | undefined> | null | undefined} query
|
|
108
|
+
* @param {boolean} hasPreviewSession
|
|
109
|
+
* @param {string | null | undefined} [configuredSecret]
|
|
110
|
+
*/
|
|
111
|
+
export function isEditingRequest(request, query, hasPreviewSession, configuredSecret = configuredEditorSecret()) {
|
|
112
|
+
return isEditorFrameQuery(query) && (hasPreviewSession || hasEditorSignal(request, configuredSecret));
|
|
113
|
+
}
|
package/src/settings.cjs
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `@parhelia/head/settings` — the build settings a head's framework adapter reads while the build is configured
|
|
4
|
+
* (`withParhelia` of `@parhelia/next/config`, the `parhelia()` Vite plugin of `@parhelia/head/vite`). CommonJS so a
|
|
5
|
+
* `next.config.js` can `require` it as well as an ES module can import it.
|
|
6
|
+
*
|
|
7
|
+
* PARHELIA_RENDERING_PROXY_PATH `/parhelia/proxy/<head name>`: served below Parhelia's same-origin rendering proxy
|
|
8
|
+
* (the base path). `NEXT_PUBLIC_BASE_PATH` is read when it is unset; `/` means none.
|
|
9
|
+
* PARHELIA_ORIGIN the Parhelia editor's origin: it may frame the head directly, and the browser loads
|
|
10
|
+
* the editing bridge from it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const ORIGIN = /^https?:\/\/[^\s/;,'"]+$/i;
|
|
14
|
+
|
|
15
|
+
/** The Parhelia origin from the environment: trimmed, without a trailing slash; "" when unset. */
|
|
16
|
+
function originFromEnv(env = process.env) {
|
|
17
|
+
const value = String(env.PARHELIA_ORIGIN || "").trim().replace(/\/+$/, "");
|
|
18
|
+
if (!value) return "";
|
|
19
|
+
if (!ORIGIN.test(value))
|
|
20
|
+
throw new Error(`PARHELIA_ORIGIN must be an origin such as https://cms.example.com, not "${value}".`);
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The rendering-proxy base path from the environment; "" when unset or `/`. */
|
|
25
|
+
function basePathFromEnv(env = process.env) {
|
|
26
|
+
const value = String(env.PARHELIA_RENDERING_PROXY_PATH || env.NEXT_PUBLIC_BASE_PATH || "")
|
|
27
|
+
.trim()
|
|
28
|
+
.replace(/\/+$/, "");
|
|
29
|
+
if (!value) return "";
|
|
30
|
+
if (!value.startsWith("/") || /[\s?#]/.test(value))
|
|
31
|
+
throw new Error(`PARHELIA_RENDERING_PROXY_PATH must be a path such as /parhelia/proxy/marketing, not "${value}".`);
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { originFromEnv, basePathFromEnv };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
2
|
+
|
|
3
|
+
/** The Parhelia origin from `PARHELIA_ORIGIN`: trimmed, without a trailing slash; "" when unset. Throws on a non-origin. */
|
|
4
|
+
export declare function originFromEnv(env?: Env): string;
|
|
5
|
+
|
|
6
|
+
/** The rendering-proxy base path from `PARHELIA_RENDERING_PROXY_PATH` (or `NEXT_PUBLIC_BASE_PATH`); "" when unset or `/`. */
|
|
7
|
+
export declare function basePathFromEnv(env?: Env): string;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const EMPTY_SLOT_ATTRIBUTE: "data-parhelia-empty-slot";
|
|
2
|
+
export declare const EMPTY_SLOT_MIN_HEIGHT: "6rem";
|
|
3
|
+
export declare function slotStartAttributes(name: string, description?: string): { "data-placeholder-start": string; "data-description": string };
|
|
4
|
+
export declare function slotEndAttributes(name: string): { "data-placeholder-end": string };
|
|
5
|
+
export declare function emptySlotAttributes(name: string): { "data-parhelia-empty-slot": string };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slot markers without a framework: the attributes of Parhelia's slot sentinels (inert `<script>` elements around a
|
|
3
|
+
* slot's rendering) and of the empty block an empty slot renders in Parhelia's frames, where the editor draws its drop
|
|
4
|
+
* zone. `ParheliaSlot` of `@parhelia/react` renders them with React; a head without React writes the same elements.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** The attribute of the block an empty slot renders in Parhelia's frames; its value is the slot's key. */
|
|
8
|
+
export const EMPTY_SLOT_ATTRIBUTE = "data-parhelia-empty-slot";
|
|
9
|
+
|
|
10
|
+
/** The default height of an empty slot's block. */
|
|
11
|
+
export const EMPTY_SLOT_MIN_HEIGHT = "6rem";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The opening sentinel `<script>`'s attributes.
|
|
15
|
+
* @param {string} name the slot's key as Parhelia names it
|
|
16
|
+
* @param {string} [description] its label (default `name`)
|
|
17
|
+
*/
|
|
18
|
+
export const slotStartAttributes = (name, description) => ({ "data-placeholder-start": name, "data-description": description || name });
|
|
19
|
+
|
|
20
|
+
/** The closing sentinel `<script>`'s attributes. @param {string} name */
|
|
21
|
+
export const slotEndAttributes = (name) => ({ "data-placeholder-end": name });
|
|
22
|
+
|
|
23
|
+
/** The empty block's attributes (its height is the head's: `min-height`, default `EMPTY_SLOT_MIN_HEIGHT`). @param {string} name */
|
|
24
|
+
export const emptySlotAttributes = (name) => ({ [EMPTY_SLOT_ATTRIBUTE]: name });
|
package/src/typo3.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** One rendered field's identity, as a TYPO3 render knows it. */
|
|
2
|
+
export type T3FieldRef = {
|
|
3
|
+
/** The record's TCA table (`tt_content`, `pages`, a Content Blocks table). */
|
|
4
|
+
table: string;
|
|
5
|
+
/** The item's uid (a translation row is named by its parent). */
|
|
6
|
+
uid: string | number;
|
|
7
|
+
/** The TCA column. */
|
|
8
|
+
field: string;
|
|
9
|
+
/** The language id of the row that was rendered (-1: a record of all languages). */
|
|
10
|
+
language: string | number;
|
|
11
|
+
/** The field's element holds rich text. */
|
|
12
|
+
richText?: boolean;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** The vocabulary's wire name. */
|
|
16
|
+
export declare const TYPO3_MARKER_VOCABULARY: "typo3";
|
|
17
|
+
/** The one entity kind a field marker names. */
|
|
18
|
+
export declare const T3_RECORD_KIND: "record";
|
|
19
|
+
export declare const T3_TABLE_ATTRIBUTE: string;
|
|
20
|
+
export declare const T3_UID_ATTRIBUTE: string;
|
|
21
|
+
export declare const T3_FIELD_ATTRIBUTE: string;
|
|
22
|
+
export declare const T3_LANGUAGE_ATTRIBUTE: string;
|
|
23
|
+
export declare const T3_RICHTEXT_ATTRIBUTE: string;
|
|
24
|
+
/** The language id of a record of all languages. */
|
|
25
|
+
export declare const T3_ALL_LANGUAGES: "-1";
|
|
26
|
+
/** Parhelia addresses a TYPO3 record as its current state in the mount's workspace. */
|
|
27
|
+
export declare const PARHELIA_TYPO3_VERSION: "0";
|
|
28
|
+
|
|
29
|
+
/** The key of a record marker, `{table}:{uid}`; undefined for a malformed table or uid. */
|
|
30
|
+
export declare function t3RecordKey(table: string, uid: string | number): string | undefined;
|
|
31
|
+
/** Reads a record key `{table}:{uid}`; undefined when it is not one. */
|
|
32
|
+
export declare function parseT3RecordKey(key: string): { table: string; uid: string } | undefined;
|
|
33
|
+
/** The field marker attributes of one rendered field; `{}` outside the editor. */
|
|
34
|
+
export declare function t3FieldAttributes(ref: T3FieldRef, edit: boolean): Record<string, string>;
|