Skip to content

Commit 537e945

Browse files
ryansolidClaude via Cursorcursoragent
authored
fix(web): SSR validates dynamic attribute and tag names (#3871)
A spread's keys and a `<Dynamic>` tag are runtime strings, and the server wrote them into markup with text-mode escaping only, so a name containing whitespace, a quote, `=`, `>` or `/` was read by the HTML parser as more than one name. The client never produces such an element: `setAttribute` and `createElement` refuse those names. - Attribute names (`ssrElement`'s spread walk, the binding-slot spread paths) are checked against what ends or breaks a name in the tokenizer: ASCII whitespace, `"`, `'`, `<`, `>`, `/`, `=`, NUL and other control characters, or an empty name. A failing name is dropped. A passing name is written as is: `&` is no longer escaped to `&amp;`, which the parser keeps literally in a name. - Tag names must also start with an ASCII letter; a failing tag throws, as the client's `createElement` does, into the nearest error boundary. - Both checks run on a cache miss only (`safeAttrNames`, `tagInfos`), and only passing names are cached; `escape` is unchanged. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 53ef0e6 commit 537e945

4 files changed

Lines changed: 171 additions & 20 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
SSR validates dynamic attribute and tag names: a spread key the HTML parser would not read back as one attribute name (whitespace, quotes, `<`, `>`, `/`, `=`, control characters, or empty) is dropped, as the client's `setAttribute` refuses it; other names are written as is (`&` is no longer escaped to `&amp;`, which the parser keeps literally in a name). A `<Dynamic>`/`ssrElement` tag that is not one element name throws, as the client's `createElement` does.

‎packages/web/src/server.ts‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1589,10 +1589,18 @@ interface TagInfo {
15891589
textarea: boolean;
15901590
raw: boolean;
15911591
}
1592+
// What ends a tag or attribute name in the HTML tokenizer (whitespace, `/`,
1593+
// `>`, `=`), what it reports as an error inside one (quotes, `<`, NUL), and
1594+
// the other control characters. A name containing none of them, and starting
1595+
// with an ASCII letter for a tag, is read back as exactly that one name.
1596+
const NOT_NAME = /[\0-\x20\x7F-\x9F"'<>/=]/;
1597+
const TAG_START = /^[a-zA-Z]/;
15921598
const tagInfos = /*#__PURE__*/ new Map<string, TagInfo>();
15931599
function tagInfo(tag: string): TagInfo {
15941600
let info = tagInfos.get(tag);
15951601
if (info === undefined) {
1602+
if (!TAG_START.test(tag) || NOT_NAME.test(tag))
1603+
throw new Error(`"${tag}" is not a valid tag name`);
15961604
info = {
15971605
open: "<" + tag,
15981606
close: "</" + tag + ">",
@@ -1604,17 +1612,19 @@ function tagInfo(tag: string): TagInfo {
16041612
}
16051613
return info;
16061614
}
1607-
// Attribute names a spread has already emitted unchanged. A spread's keys
1608-
// are author-written names from a small vocabulary, repeated on every
1609-
// element; `escape` runs a regex over each one every time, and a name that
1610-
// escaped to itself once escapes to itself always. Names that DO escape are
1611-
// never remembered, so a hit means "emit as is". Bounded like `tagInfos`.
1615+
// Whether a spread key can be written as an attribute name: a runtime string
1616+
// the parser would not read back as that one name is dropped, as the
1617+
// client's setAttribute refuses it. Written as is otherwise — the tokenizer
1618+
// decodes no character references in a name, so `&` stays `&`. A spread's
1619+
// keys are author-written names from a small vocabulary, repeated on every
1620+
// element, so the names that passed are remembered and a hit skips the
1621+
// regex. Names that fail are never remembered. Bounded like `tagInfos`.
16121622
const safeAttrNames = /*#__PURE__*/ new Set<string>();
1613-
function attrName(prop: string): string {
1614-
if (safeAttrNames.has(prop)) return prop;
1615-
const escaped = escape(prop);
1616-
if (escaped === prop && safeAttrNames.size < 512) safeAttrNames.add(prop);
1617-
return escaped;
1623+
function isAttrName(prop: string): boolean {
1624+
if (safeAttrNames.has(prop)) return true;
1625+
if (prop === "" || NOT_NAME.test(prop)) return false;
1626+
if (safeAttrNames.size < 512) safeAttrNames.add(prop);
1627+
return true;
16181628
}
16191629
// Fragment replacement helpers emitted into stream task scripts.
16201630
//
@@ -4600,11 +4610,9 @@ export function ssrElement(tag, props, children, needsId, skip, attrs, claims) {
46004610
} else if (prop === "class") {
46014611
result += ` class="${ssrClassName(value)}"`;
46024612
} else if (typeof value === "boolean") {
4603-
if (!value) continue;
4604-
result += ` ${attrName(prop)}`;
4605-
} else {
4606-
result +=
4607-
value === "" ? ` ${attrName(prop)}` : ` ${attrName(prop)}="${escape(value, true)}"`;
4613+
if (value && isAttrName(prop)) result += ` ${prop}`;
4614+
} else if (isAttrName(prop)) {
4615+
result += value === "" ? ` ${prop}` : ` ${prop}="${escape(value, true)}"`;
46084616
}
46094617
}
46104618
}
@@ -5017,6 +5025,7 @@ function eventPosition(prop) {
50175025
* (spreadBehaviorMarkers).
50185026
*/
50195027
function spreadBehaviorPosition(behaviors, prop, value, mode, index, settle) {
5028+
if (!isAttrName(prop)) return behaviors;
50205029
const pos = prop === "ref" ? "ref" : eventPosition(prop);
50215030
const entries = value == null ? "" : claimEntries(pos, value, mode);
50225031
if (!settle) {
@@ -5150,8 +5159,9 @@ function spreadPropPosition(prop, value) {
51505159
*/
51515160
function spreadObjectAttribute(prop, value) {
51525161
if (prop === "style" || prop === "class") return slotClassOrStyle(prop, value);
5153-
if (value[SLOT_VALUE] !== undefined) return slotAttribute(attrName(prop), value);
5154-
return ` ${attrName(prop)}="${escape(value, true)}"`;
5162+
if (!isAttrName(prop)) return "";
5163+
if (value[SLOT_VALUE] !== undefined) return slotAttribute(prop, value);
5164+
return ` ${prop}="${escape(value, true)}"`;
51555165
}
51565166

51575167
/**
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*/
4+
import { describe, expect, test } from "vitest";
5+
import { Errored } from "solid-js";
6+
import { Dynamic, renderToString, ssrElement } from "@solidjs/web";
7+
import { renderServerComponent } from "../../frames/src/frame-sink.js";
8+
9+
// A spread's keys and a dynamic tag are runtime strings. The HTML tokenizer
10+
// ends a name at whitespace, `/`, `>` or `=`, so a name containing one of
11+
// those (or a quote, `<`, a control character, or nothing at all) would not
12+
// be read back as the one name it was. The client's setAttribute and
13+
// createElement refuse such names; on the server an attribute with one is
14+
// dropped and a tag with one throws.
15+
const unreadable = ["a b", 'a"b', "a'b", "a=b", "a>b", "a<b", "a/b", "a\tb", "a\nb", "a\0b", ""];
16+
17+
describe("ssrElement attribute names", () => {
18+
test("a value attribute whose name is not one HTML name is dropped", () => {
19+
const props: Record<string, string> = {};
20+
for (const name of unreadable) props[name] = "v";
21+
props.id = "kept";
22+
expect(renderToString(() => ssrElement("div", props, undefined, false))).toBe(
23+
'<div id="kept"></div>'
24+
);
25+
});
26+
27+
test("a boolean or empty attribute whose name is not one HTML name is dropped", () => {
28+
const flags: Record<string, boolean> = {};
29+
const empties: Record<string, string> = {};
30+
for (const name of unreadable) {
31+
flags[name] = true;
32+
empties[name] = "";
33+
}
34+
expect(
35+
renderToString(() =>
36+
ssrElement("input", { type: "text", ...flags, placeholder: "p" }, undefined, false)
37+
)
38+
).toBe('<input type="text" placeholder="p" />');
39+
expect(
40+
renderToString(() => ssrElement("input", { ...empties, disabled: "" }, undefined, false))
41+
).toBe("<input disabled />");
42+
});
43+
44+
test("a dropped name stays dropped on every render", () => {
45+
for (let i = 0; i < 3; i++) {
46+
expect(
47+
renderToString(() => ssrElement("div", { "a b": "v", "a b c": true }, undefined, false))
48+
).toBe("<div></div>");
49+
}
50+
});
51+
52+
test("names the tokenizer reads whole render as written", () => {
53+
const props = {
54+
"data-x": "1",
55+
"aria-label": "l",
56+
"@click": "open = true",
57+
"x-on:click": "go()",
58+
":class": "c",
59+
"xlink:href": "#a",
60+
"a&b": "2",
61+
hidden: true
62+
};
63+
expect(renderToString(() => ssrElement("div", props, undefined, false))).toBe(
64+
'<div data-x="1" aria-label="l" @click="open = true" x-on:click="go()" :class="c" ' +
65+
'xlink:href="#a" a&b="2" hidden></div>'
66+
);
67+
});
68+
69+
test("through a compiled spread", () => {
70+
const props = { "a b": "v", 'a"b': true, "data-ok": "1" };
71+
expect(renderToString(() => <div {...props} />)).toMatch(
72+
/^<div( _hk=\w+)? data-ok="1"><\/div>$/
73+
);
74+
});
75+
76+
test("through <Dynamic> with a spread", () => {
77+
const props = { type: "text", "a b": "", "a=b": "v", placeholder: "p" };
78+
expect(renderToString(() => <Dynamic component="input" {...props} />)).toMatch(
79+
/^<input( _hk=\w+)? type="text" placeholder="p" \/>$/
80+
);
81+
});
82+
});
83+
84+
describe("ssrElement tag names", () => {
85+
const invalid = ["div x", "a>b", "a/b", 'a"b', "a=b", "a\tb", "a\0b", "1a", "-a", ""];
86+
87+
test("a tag that is not one HTML element name throws, on every render", () => {
88+
for (const tag of invalid) {
89+
for (let i = 0; i < 2; i++) {
90+
expect(() => renderToString(() => ssrElement(tag, {}, undefined, false))).toThrow(
91+
"is not a valid tag name"
92+
);
93+
}
94+
}
95+
});
96+
97+
test("<Dynamic> with such a tag fails into its error boundary", () => {
98+
expect(() => renderToString(() => <Dynamic component="div x" />)).toThrow(
99+
"is not a valid tag name"
100+
);
101+
const html = renderToString(() => (
102+
<Errored fallback={<p>fallback</p>}>
103+
<Dynamic component="div x" title="t" />
104+
</Errored>
105+
));
106+
expect(html).toContain(">fallback</p>");
107+
expect(html).not.toContain("<div");
108+
});
109+
110+
test("custom elements and case-sensitive SVG names render", () => {
111+
expect(renderToString(() => <Dynamic component="my-widget" data-x="1" />)).toMatch(
112+
/^<my-widget( _hk=\w+)? data-x="1"><\/my-widget>$/
113+
);
114+
expect(renderToString(() => <Dynamic component="foreignObject" />)).toMatch(
115+
/^<foreignObject( _hk=\w+)?><\/foreignObject>$/
116+
);
117+
expect(renderToString(() => ssrElement("x-a.b_c:d", {}, undefined, false))).toBe(
118+
"<x-a.b_c:d></x-a.b_c:d>"
119+
);
120+
});
121+
});
122+
123+
describe("binding-slot spread attribute names", () => {
124+
test("a stand-in at a key that is not one HTML name binds nothing", async () => {
125+
const Spread = (props: any) => {
126+
const row = props.row({ id: 1 });
127+
return <li {...{ "a b": row.v, "data-ok": row.w, "onClick x": row.pick, onClick: row.go }} />;
128+
};
129+
const chunks: any[] = await (renderServerComponent(Spread, { frame: { id: "names" } }) as any);
130+
const html = chunks
131+
.find(c => c.type === "html")
132+
.html.replace(/ data-lha="\d+"/g, "")
133+
.replace(/<!--lh:\/?\d+-->/g, "");
134+
expect(html).toContain('<li _s:data-ok="row#0:w" _s:on:click="row#0:go">');
135+
});
136+
});

‎packages/web/test/server/ssr-element-sources.spec.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -426,10 +426,10 @@ describe("ssrElement with an attribute string", () => {
426426
);
427427
});
428428

429-
test("attribute names that escape are still escaped, and remembered only when clean", () => {
430-
// a key that needs escaping never lands as-is, however often it is seen
429+
test("attribute names that are not one HTML name are dropped, and never remembered", () => {
430+
// a key that fails never lands, however often it is seen
431431
for (let i = 0; i < 3; i++) {
432-
expect(attrs({ "a<b": "1", ok: "2" }, undefined)).toBe('<div a&lt;b="1" ok="2"></div>');
432+
expect(attrs({ "a<b": "1", ok: "2" }, undefined)).toBe('<div ok="2"></div>');
433433
}
434434
});
435435
});

0 commit comments

Comments
 (0)