smartyfy.mrindigi.com

Web Development Pro | Lesson 047 | Security: Untrusted Content and XSS

Web Development Pro · Lesson 47 of 60

Module 5: Quality, accessibility, and security

In this lesson

Prerequisites and learning outcomes

Complete lesson 46 first. This lesson builds on trust boundaries and safe output. By the end, you can keep external strings out of executable HTML and recognize context-dependent escaping. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Treat outside strings as data

Cross-site scripting, or XSS, occurs when untrusted content is interpreted as executable content in a page's context. The outside value might come from a query string, a saved preference, a fetched JSON file, or a message. A value being stored locally does not make it trustworthy; another script or a person can alter it.

Our learning directory displays public event titles. Its requirement is plain text, so the safest and simplest rendering contract is also plain text. An event title containing angle brackets should appear as those characters, not create a new element. There is no product need to interpret event titles as HTML.

Identify the source and the sink

The source is where a value enters the application. The sink is the operation that consumes it. A safe-looking source name does not protect an unsafe sink. JSON parsing creates JavaScript data; it does not sanitize strings for every later output context. Record validation checks shape and allowed values, while safe output determines how accepted strings are used.

export function makeTitle(doc, title) {
  const heading = doc.createElement('h2');
  heading.textContent = title;
  return heading;
}

The application creates the element itself and assigns the title as text. That separates trusted structure from outside content. Avoid building an HTML string by concatenating the title into innerHTML. Even when a current fixture looks harmless, the rendering rule should remain safe for future records containing punctuation and markup-like text.

The example uses an inert string such as “<b>Bike basics</b>” to show the boundary. A test double checks that this is assigned literally to textContent. It does not parse or execute HTML, so the test is evidence about the chosen API call, not a full browser security test.

Match protection to the output context

Plain text, HTML, URL attributes, CSS, and JavaScript source are different contexts. Escaping that is suitable for one context is not a universal protection for another. For example, assigning a string to textContent does not validate a separate href value. A dangerous URL scheme can remain dangerous even if the surrounding markup is well formed.

Do not write a homemade “remove suspicious words” sanitizer. Lists of forbidden substrings are brittle and can break legitimate content while missing harmful interpretations. If a future product genuinely needs rich HTML, use an appropriate maintained sanitizer and a carefully defined allowed-content policy, with review and tests. This course avoids that additional requirement.

Likewise, do not use eval or construct functions from outside strings to implement configuration. Model allowed choices as data and select among known behavior. A category named repair should choose a filter value, not become executable code.

Validate links with an explicit policy

The supplied safeLocalLink helper accepts a raw string and a base URL. It constructs a URL, requires HTTPS, requires the same origin, rejects embedded username/password fields, and requires the path to remain under /hub/. This is a teaching policy for one fictional site, not a universally correct rule for every product.

const url = new URL(raw, base);
if (url.protocol !== 'https:' || url.origin !== baseURL.origin) return null;
if (url.username || url.password || !url.pathname.startsWith('/hub/')) return null;
return url.href;

The complete file includes type checks, base parsing, and try/catch. Relative paths can be allowed, while javascript: and external HTTPS addresses are rejected by this policy. A protocol-relative address to another host is also external after parsing. Inspect the parsed URL rather than guessing from a substring such as “contains our domain.”

An allowed starting URL could still redirect elsewhere when actually hosted. URL validation here establishes only the parsed destination under the declared policy. A live service needs appropriate server behavior and separate authorization decisions; a client helper cannot guarantee the whole request chain.

Keep defenses layered without confusing their roles

Content Security Policy can reduce some consequences of script injection by limiting allowed resource execution and sources. It is a defense in depth, not a replacement for safe rendering. A weak policy with broad permissions may provide little benefit, and a strong policy can break legitimate behavior if it is deployed without testing.

HTTPS protects data in transit to the intended endpoint under its trust model. It does not turn every response string into safe HTML. Similarly, authentication answers who is acting, while authorization answers what they may do. Neither excuses interpreting an untrusted title as code.

Client-side validation improves predictability and user experience but cannot enforce a server's security boundary. A user can modify browser code or send a request directly. A real backend must validate and authorize operations itself. Our examples have no submission service and do not claim production security.

Review a small trust-boundary inventory

List the application's inputs: local JSON, query parameters, and harmless preferences. Next list outputs: text nodes, selected options, status strings, and approved links. Ask which operation consumes each value and whether that context is appropriate. This inventory often reveals a forgotten error message inserted as HTML or a URL copied without validation.

Keep errors useful without exposing raw sensitive data. A visitor can see “The event data is unavailable” while a private diagnostic record captures a bounded technical reason if such logging is authorized. Do not automatically send full records or query strings to an external error service.

Run the supplied Node tests to verify the URL-policy cases and literal text assignment. Then review the actual browser implementation when a browser is available. The tests do not simulate every browser parser, prove sanitizer correctness, inspect response headers, or certify the application against all security threats.

Worked practice

Worked exercise 1: Preserve a markup-like title

Task: An event title is “<b>Bike basics</b>.” Worked answer: create the heading with createElement and assign the complete string to textContent. The requirement is a title, not formatted HTML. Treating the string literally preserves the trust boundary and the author's exact text.

Worked exercise 2: Reject a misleading destination

Task: A URL contains the trusted hostname inside a different site's path. Worked answer: parse it with URL and compare the resulting origin against the allowed origin. A substring check can mistake text inside a path or username for the actual host.

Worked exercise 3: Explain CSP's role

Task: A teammate wants to keep unsafe HTML concatenation because CSP will be added later. Worked answer: fix the unsafe rendering first. A tested policy can add protection, but it does not remove the need for context-appropriate handling of outside values.

Knowledge check

Question 1

What does JSON parsing establish? A) Every string is safe HTML. B) The text was parsed into data successfully. C) All URLs are authorized. D) Every record is complete.

Check question 1: answer and explanation

Answer: B. Parsing, schema validation, and safe output are separate checks.

Question 2

Which sink fits an ordinary title? A) innerHTML after removing only the word script. B) innerHTML after successful JSON parsing. C) textContent on a created heading. D) HTML concatenation after checking only that the title is a string.

Check question 2: answer and explanation

Answer: C. The product needs text rather than executable markup.

Question 3

Why parse a URL before checking it? A) To inspect its actual scheme, host, and path. B) To establish that the final redirected page stays at the same origin. C) To establish that the visitor is authorized for the parsed path. D) To prevent every redirect.

Check question 3: answer and explanation

Answer: A. Structured checks are more reliable than searching raw text.

Question 4

What is CSP in this lesson? A) A substitute for checking what an authenticated request may do. B) A universal sanitizer. C) A guarantee that allowed-origin responses contain safe strings. D) An additional browser defense that needs careful configuration.

Check question 4: answer and explanation

Answer: D. Layered protection does not replace safe application behavior.

Question 5

What does the provided test double prove? A) All browser parsers reject attacks. B) The renderer assigns the literal string through the tested API. C) The production header policy is effective. D) Every rich-text sanitizer is correct.

Check question 5: answer and explanation

Answer: B. Its evidence is limited to the operations it records.

Sources and further reading