@parhelia/head 0.0.0-stage → 1.0.12951

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.
@@ -0,0 +1,263 @@
1
+ /**
2
+ * The reader of `@parhelia/head/rich-text`: markup read with the HTML tokenizer's rules — the input stream's preprocessing, tags,
3
+ * attributes, comments, raw-text elements and character references in attribute values — as a browser reads it. The C# reader
4
+ * (`Parhelia.Markup`: `HtmlTokenizer`, `HtmlCharacterReferences`) follows the same rules; both run the one vector file beside this
5
+ * module (`rich-text.vectors.json`), so the two cannot drift apart unnoticed. Internal to the package (not in its exports).
6
+ */
7
+
8
+ /** Elements whose content the tokenizer reads as text up to their end tag (`plaintext`: to the end). */
9
+ export const RAW_TEXT_TAGS = new Set(["script", "style", "xmp", "iframe", "noembed", "noframes", "noscript", "textarea", "title"]);
10
+
11
+ /**
12
+ * The input stream's preprocessing: line breaks normalized and every NUL removed (a NUL is never content, so no reading may depend
13
+ * on where one stands).
14
+ * @param {string} html
15
+ */
16
+ export const preprocess = html => html.replace(/\r\n?/g, "\n").replace(/\0/g, "");
17
+
18
+ // ---- Character references ----------------------------------------------------------------------------------------------
19
+
20
+ /**
21
+ * The named references whose characters include ASCII (all of them, so a URL's scheme is read as a browser reads it), and
22
+ * the no-break space. Every other named reference decodes to characters outside ASCII.
23
+ * @type {Record<string, string>}
24
+ */
25
+ const NAMED_REFERENCES = {
26
+ Tab: "\t", NewLine: "\n", excl: "!", quot: '"', QUOT: '"', num: "#", dollar: "$", percnt: "%", amp: "&", AMP: "&",
27
+ apos: "'", lpar: "(", rpar: ")", ast: "*", midast: "*", plus: "+", comma: ",", period: ".", sol: "/", colon: ":",
28
+ semi: ";", lt: "<", LT: "<", equals: "=", gt: ">", GT: ">", quest: "?", commat: "@", lsqb: "[", lbrack: "[",
29
+ bsol: "\\", rsqb: "]", rbrack: "]", Hat: "^", lowbar: "_", UnderBar: "_", grave: "`", DiacriticalGrave: "`",
30
+ lcub: "{", lbrace: "{", verbar: "|", vert: "|", VerticalLine: "|", rcub: "}", rbrace: "}", fjlig: "fj",
31
+ nvlt: "<⃒", nvgt: ">⃒", bne: "=⃥", nbsp: " ", NonBreakingSpace: " ",
32
+ };
33
+
34
+ /**
35
+ * HTML 4's Latin-1 references (U+00A0 to U+00FF, in code point order): a browser decodes each with or without its semicolon
36
+ * (legacy references), as do the ASCII ones `amp`, `lt`, `gt`, `quot` and the upper-case `AMP`, `LT`, `GT`, `QUOT`, `COPY`, `REG`.
37
+ */
38
+ const LATIN_1 = (
39
+ "nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para " +
40
+ "middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute " +
41
+ "Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml " +
42
+ "Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth " +
43
+ "ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml"
44
+ ).split(" ");
45
+
46
+ /** @type {Record<string, string>} */
47
+ const LEGACY_REFERENCES = Object.fromEntries([
48
+ ...LATIN_1.map((name, index) => [name, String.fromCharCode(0xa0 + index)]),
49
+ ["COPY", "©"], ["REG", "®"],
50
+ ["amp", "&"], ["AMP", "&"], ["lt", "<"], ["LT", "<"], ["gt", ">"], ["GT", ">"], ["quot", '"'], ["QUOT", '"'],
51
+ ]);
52
+
53
+ /** Numeric references to C1 controls are read as windows-1252. */
54
+ const WINDOWS_1252 = {
55
+ 0x80: 0x20ac, 0x82: 0x201a, 0x83: 0x0192, 0x84: 0x201e, 0x85: 0x2026, 0x86: 0x2020, 0x87: 0x2021, 0x88: 0x02c6,
56
+ 0x89: 0x2030, 0x8a: 0x0160, 0x8b: 0x2039, 0x8c: 0x0152, 0x8e: 0x017d, 0x91: 0x2018, 0x92: 0x2019, 0x93: 0x201c,
57
+ 0x94: 0x201d, 0x95: 0x2022, 0x96: 0x2013, 0x97: 0x2014, 0x98: 0x02dc, 0x99: 0x2122, 0x9a: 0x0161, 0x9b: 0x203a,
58
+ 0x9c: 0x0153, 0x9e: 0x017e, 0x9f: 0x0178,
59
+ };
60
+
61
+ /** @param {string} digits @param {number} radix */
62
+ function numericReference(digits, radix) {
63
+ const significant = digits.replace(/^0+/, "");
64
+ const code = significant.length > 8 ? Infinity : significant === "" ? 0 : Number.parseInt(significant, radix);
65
+ if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return "�";
66
+ return String.fromCodePoint(/** @type {Record<number, number>} */ (WINDOWS_1252)[code] ?? code);
67
+ }
68
+
69
+ const REFERENCE = /&(?:#[xX]([0-9a-fA-F]+);?|#([0-9]+);?|([A-Za-z][A-Za-z0-9]*)(;?))/g;
70
+
71
+ /**
72
+ * An attribute value as a browser decodes it, in parts; an opaque part is a named reference left for the browser (one this
73
+ * module does not know: it decodes to characters outside ASCII and Latin-1).
74
+ * @param {string} raw
75
+ * @returns {{ text: string; opaque: boolean }[]}
76
+ */
77
+ export function decodeAttribute(raw) {
78
+ /** @type {{ text: string; opaque: boolean }[]} */
79
+ const parts = [];
80
+ let last = 0;
81
+ for (const match of raw.matchAll(REFERENCE)) {
82
+ const [whole, hex, decimal, name = "", semicolon] = match;
83
+ /** @type {string} */
84
+ let text;
85
+ let opaque = false;
86
+ if (hex !== undefined) text = numericReference(hex, 16);
87
+ else if (decimal !== undefined) text = numericReference(decimal, 10);
88
+ else if (semicolon && Object.hasOwn(NAMED_REFERENCES, name)) text = /** @type {string} */ (NAMED_REFERENCES[name]);
89
+ else if (semicolon && Object.hasOwn(LEGACY_REFERENCES, name)) text = /** @type {string} */ (LEGACY_REFERENCES[name]);
90
+ else if (semicolon) {
91
+ text = whole;
92
+ opaque = true;
93
+ } else if (Object.hasOwn(LEGACY_REFERENCES, name) && raw.charAt(match.index + whole.length) !== "=") {
94
+ // Without the semicolon only a legacy name decodes, and in an attribute not when '=' follows (a letter or digit cannot:
95
+ // the name runs over them).
96
+ text = /** @type {string} */ (LEGACY_REFERENCES[name]);
97
+ } else continue;
98
+ if (match.index > last) parts.push({ text: raw.slice(last, match.index), opaque: false });
99
+ parts.push({ text, opaque });
100
+ last = match.index + whole.length;
101
+ }
102
+ if (last < raw.length) parts.push({ text: raw.slice(last), opaque: false });
103
+ return parts;
104
+ }
105
+
106
+ // ---- Reading -----------------------------------------------------------------------------------------------------------
107
+
108
+ /**
109
+ * @typedef {{ type: "start"; name: string; attributes: [string, string][]; selfClosing: boolean }} StartToken
110
+ * @typedef {StartToken | { type: "end"; name: string } | { type: "text"; value: string }} Token
111
+ */
112
+
113
+ const WHITESPACE = /[\t\n\f ]/;
114
+ const ALPHA = /[A-Za-z]/;
115
+
116
+ /**
117
+ * The tokens of a fragment, by the HTML tokenizer's data, tag, attribute, comment and raw-text states. Comments, doctypes
118
+ * and bogus comments yield nothing; a tag cut off by the end of the input yields nothing (as in a browser); the content of
119
+ * a raw-text element yields nothing (only dropped elements have one).
120
+ * @param {string} input
121
+ * @returns {Generator<Token>}
122
+ */
123
+ export function* tokenize(input) {
124
+ const length = input.length;
125
+ let i = 0;
126
+ let text = "";
127
+ while (i < length) {
128
+ const lt = input.indexOf("<", i);
129
+ if (lt < 0) {
130
+ text += input.slice(i);
131
+ break;
132
+ }
133
+ text += input.slice(i, lt);
134
+ i = lt + 1;
135
+ const next = input.charAt(i);
136
+ if (next === "!") {
137
+ i = skipMarkupDeclaration(input, i + 1);
138
+ } else if (next === "?") {
139
+ i = skipBogusComment(input, i);
140
+ } else if (next === "/") {
141
+ const after = input[i + 1];
142
+ if (after === undefined) {
143
+ text += "</";
144
+ i = length;
145
+ } else if (after === ">") {
146
+ i += 2;
147
+ } else if (ALPHA.test(after)) {
148
+ const tag = readTag(input, i + 1);
149
+ if (!tag) break; // cut off by the end of the input
150
+ if (text) yield { type: "text", value: text };
151
+ text = "";
152
+ yield { type: "end", name: tag.name };
153
+ i = tag.end;
154
+ } else {
155
+ i = skipBogusComment(input, i + 1);
156
+ }
157
+ } else if (ALPHA.test(next)) {
158
+ const tag = readTag(input, i);
159
+ if (!tag) break;
160
+ if (text) yield { type: "text", value: text };
161
+ text = "";
162
+ yield { type: "start", name: tag.name, attributes: tag.attributes, selfClosing: tag.selfClosing };
163
+ i = tag.end;
164
+ if (tag.name === "plaintext") return;
165
+ if (RAW_TEXT_TAGS.has(tag.name)) i = rawTextEnd(input, i, tag.name);
166
+ } else {
167
+ text += "<";
168
+ }
169
+ }
170
+ if (text) yield { type: "text", value: text };
171
+ }
172
+
173
+ /** After `<!`: a comment (`<!-->` and `<!--->` end at once), a doctype or a bogus comment, up to its end. */
174
+ function skipMarkupDeclaration(/** @type {string} */ input, /** @type {number} */ i) {
175
+ if (input.startsWith("--", i)) {
176
+ let at = i + 2;
177
+ if (input[at] === ">") return at + 1;
178
+ if (input.startsWith("->", at)) return at + 2;
179
+ for (;;) {
180
+ const dash = input.indexOf("--", at);
181
+ if (dash < 0) return input.length;
182
+ if (input[dash + 2] === ">") return dash + 3;
183
+ if (input.startsWith("!>", dash + 2)) return dash + 4;
184
+ at = dash + 1;
185
+ }
186
+ }
187
+ return skipBogusComment(input, i);
188
+ }
189
+
190
+ /** A bogus comment or doctype: up to the next `>`. */
191
+ function skipBogusComment(/** @type {string} */ input, /** @type {number} */ i) {
192
+ const end = input.indexOf(">", i);
193
+ return end < 0 ? input.length : end + 1;
194
+ }
195
+
196
+ /** The position after a raw-text element's content: at its end tag (`</name` and white space, `/` or `>`), or the end. */
197
+ function rawTextEnd(/** @type {string} */ input, /** @type {number} */ i, /** @type {string} */ name) {
198
+ const close = new RegExp(`</${name}(?=[\\t\\n\\f />]|$)`, "gi");
199
+ close.lastIndex = i;
200
+ return close.exec(input)?.index ?? input.length;
201
+ }
202
+
203
+ /**
204
+ * A tag from its name's first character to after its `>`: the lowercase name, the attributes (lowercase names, raw values)
205
+ * and the self-closing flag; null when the input ends inside it.
206
+ * @param {string} input @param {number} start
207
+ * @returns {{ name: string; attributes: [string, string][]; selfClosing: boolean; end: number } | null}
208
+ */
209
+ function readTag(input, start) {
210
+ const length = input.length;
211
+ let i = start;
212
+ while (i < length && !isTagNameEnd(input.charAt(i))) i++;
213
+ const name = input.slice(start, i).toLowerCase();
214
+ /** @type {[string, string][]} */
215
+ const attributes = [];
216
+ let selfClosing = false;
217
+ for (;;) {
218
+ // Before an attribute name.
219
+ while (i < length && WHITESPACE.test(input.charAt(i))) i++;
220
+ if (i >= length) return null;
221
+ let char = input.charAt(i);
222
+ if (char === ">") return { name, attributes, selfClosing, end: i + 1 };
223
+ if (char === "/") {
224
+ i++;
225
+ if (i >= length) return null;
226
+ if (input.charAt(i) === ">") {
227
+ selfClosing = true;
228
+ return { name, attributes, selfClosing, end: i + 1 };
229
+ }
230
+ continue;
231
+ }
232
+ // An attribute name: a leading "=" is part of it.
233
+ const nameStart = i;
234
+ i++;
235
+ while (i < length && !isTagNameEnd(input.charAt(i)) && input.charAt(i) !== "=") i++;
236
+ const attributeName = input.slice(nameStart, i).toLowerCase();
237
+ // After the name.
238
+ while (i < length && WHITESPACE.test(input.charAt(i))) i++;
239
+ if (i >= length) return null;
240
+ if (input.charAt(i) !== "=") {
241
+ attributes.push([attributeName, ""]);
242
+ continue;
243
+ }
244
+ i++;
245
+ while (i < length && WHITESPACE.test(input.charAt(i))) i++;
246
+ if (i >= length) return null;
247
+ char = input.charAt(i);
248
+ if (char === '"' || char === "'") {
249
+ const close = input.indexOf(char, i + 1);
250
+ if (close < 0) return null;
251
+ attributes.push([attributeName, input.slice(i + 1, close)]);
252
+ i = close + 1;
253
+ } else if (char === ">") {
254
+ attributes.push([attributeName, ""]);
255
+ } else {
256
+ const valueStart = i;
257
+ while (i < length && !WHITESPACE.test(input.charAt(i)) && input.charAt(i) !== ">") i++;
258
+ attributes.push([attributeName, input.slice(valueStart, i)]);
259
+ }
260
+ }
261
+ }
262
+
263
+ const isTagNameEnd = (/** @type {string} */ char) => char === "/" || char === ">" || WHITESPACE.test(char);
@@ -0,0 +1,17 @@
1
+ /**
2
+ * What the rich-text rule does with an element of the HTML namespace: keep it, unwrap it (its content stays) or drop it
3
+ * with its content. Elements of another namespace (SVG, MathML) are dropped.
4
+ */
5
+ export declare function richTextElementAction(tag: string): "keep" | "unwrap" | "drop";
6
+
7
+ /**
8
+ * The value an attribute keeps on an allowlisted element, or null when the rule removes it. `value` is the attribute's
9
+ * value as a browser reads it (character references decoded). A style keeps its formatting declarations only.
10
+ */
11
+ export declare function sanitizeRichTextAttribute(tag: string, name: string, value: string): string | null;
12
+
13
+ /**
14
+ * Filters rich-text HTML down to the rule and writes it again (server or browser, no DOM needed); `""` for anything but a
15
+ * string.
16
+ */
17
+ export declare function sanitizeRichTextHtml(html: string): string;
@@ -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, "&lt;").replace(/>/g, "&gt;");
306
+
307
+ /** A decoded attribute value written back. */
308
+ const escapeAttribute = (/** @type {string} */ value) =>
309
+ value
310
+ .replace(/&/g, "&amp;")
311
+ .replace(/"/g, "&quot;")
312
+ .replace(/ /g, "&nbsp;")
313
+ .replace(/</g, "&lt;")
314
+ .replace(/>/g, "&gt;");
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
+
@@ -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;