Before reviewing a comment system, it helps to know which pieces of HTML can run code: script tags, event attributes such as onerror, and javascript: links.
What to build
For each line of HTML, list the parts that would run code if a browser read it as HTML.
Requirements
- Look for: a
<scripttag (any case), an attribute starting withonfollowed by letters and then=(any case, after a space), and the textjavascript:(any case). - Print
safeif none is found. Otherwise printruns code:followed by the findings in the order script, then event attributes (each distinct name, lower case, in order of first appearance), then javascript:, separated by,.
Input
One line of HTML per line.
Output
One line per input.
Constraints
1 to 30 lines.
Example
Input:
<b>hello</b>
<script>alert(1)</script>
Output:
safe
runs code: script
Why it works
These three are the common ways text in HTML becomes code; listing them shows why filtering only the word script misses attacks such as an image's onerror.
Examples
Example 1 · Input
<b>hello</b> <script>alert(1)</script>
Expected output
safe runs code: script
Example 2 · Input
<img src=x onerror="go()">
Expected output
runs code: onerror
Hints
Hint 1
/<script/i tests for a script tag.
Hint 2
line.matchAll(/\son([a-z]+)\s*=/gi) finds event attributes.
Solution
Show one correct solution (try it yourself first)
let line = prompt();
while (line !== null) {
const found = [];
if (/<script/i.test(line)) found.push("script");
const names = [];
for (const m of line.matchAll(/\son([a-z]+)\s*=/gi)) {
const name = ("on" + m[1]).toLowerCase();
if (!names.includes(name)) names.push(name);
}
found.push(...names);
if (/javascript:/i.test(line)) found.push("javascript:");
console.log(found.length ? `runs code: ${found.join(", ")}` : "safe");
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step