This article has been machine-translated from Chinese. The translation may contain inaccuracies or awkward phrasing. If in doubt, please refer to the original Chinese version.
Key Content of This Lesson
Security issues are common and can harm:
- Users
- Companies
- Programmers (sacrificed to the gods QAQ)
Two Perspectives on Web Security
If You Were a Hacker — Attack
Cross-Site Scripting (XSS)

Inject malicious scripts to complete the attack. Consequences: leaking user privacy, etc.
XSS mainly exploits the developer’s blind trust in user-submitted content.

Characteristics
- Usually hard to perceive from the UI (scripts typically execute covertly)
- Steal user information (cookie/token)
- Render UI (such as pop-ups), tricking users into clicking/filling forms
An example:
public async submit(ctx) {
const {content, id} = ctx.request.body;
await db.save({
content, // No filtering on content!!
id
});
}
public async render(ctx) {
const { content } = await db.query({
id: ctx.query.id
});
// No filtering on content!!
ctx.body = `<div>${content}</div>`;
}
As you can see, the code above performs absolutely no filtering on the user-submitted content. At this point, an attacker could submit a <script>alert('xss');</script> script to carry out the attack.
XSS attacks are also divided into several categories: Store XSS, Reflected XSS, DOM-based XSS, Mutation-based XSS
Store XSS
- The malicious script is stored in the database
- Visit page -> read data == attacked
- Most dangerous, visible to all users
- Example: On a video site, a malicious script is uploaded and stored in the database, and from then on, the e-commerce site has a shared video account.
Reflected XSS
-
Does not involve the database
-
Attacks via URL, carrying the script in the URL

DOM-based XSS
-
Does not require server involvement
-
Both initiation and execution of the malicious attack happen entirely in the browser

-
The script injection happens via the browser — this is what distinguishes it from Reflected XSS
Mutation-based XSS
-
A clever attack method that exploits browser features
If the rich text content provided by the user enters the innerHTML property through JavaScript code, some unexpected changes may cause this assumption to no longer hold: the browser’s rendering engine may render originally harmless HTML code into potentially dangerous XSS attack code.
-
Clever, and the hardest type to defend against — the attacker really understands browsers

Cross-Site Request Forgery (CSRF)
-
Without the user’s knowledge
-
Exploits user permissions (cookies)
-
Constructs specific HTTP requests to steal or modify sensitive user information

A user visits a malicious page, which sends a transfer request to the bank. ServerA, the bank’s server, sees that the request carries the user’s cookie and processes it successfully.
CSRF exploits trusted websites by disguising requests as coming from trusted users. Compared to XSS attacks, CSRF attacks tend to be less common (and thus fewer resources are devoted to defending against them) and harder to prevent, so they are considered
more dangerousthan XSS.
Injection
-
SQL Injection: Injection through SQL parameters

Case: Reading request fields and directly concatenating them as strings into SQL statements
public async rederForm(ctx) { const {username, form_id } = ctx.query; const result = await sql.query(` SELECT a, b, c FROM table WHERE username = ${username} AND form_id = ${form_id} `); ctx.body = renderForm(result); }An attacker could pass a username like:
any; DROP TABLE table;— and congratulations, you’ve achieved the “involuntary database deletion” achievement. -
Command line injection, etc.

-
Read + modify for traffic attacks

Denial of Service (DoS) Attacks
-
Through some method (constructing specific requests), server resources are significantly consumed,
-
Unable to respond to more requests in time, causing request backlog and a cascading failure.
-
Expanded topic: Regular expressions — greedy mode
- When matching repeatedly,
?/no ?: satisfy"one is enough"/as many as possible
- When matching repeatedly,
-
Example: ReDoS: DoS based on regular expressions
-
Greedy: n times doesn’t work? Try n-1 times? — backtracking

-
Distributed DoS (DDoS)
-
In a short period, a flood of request traffic from a large number of zombie devices overwhelms the server, which cannot complete all requests in time, causing request buildup and cascading failure, making it unable to respond to new requests. (It’s all about volume.)
-
Characteristics:
-
Directly accessing the IP
-
Any API
-
Consumes massive bandwidth (exhaustion)

-
-
Man-in-the-Middle Attack (Transport Layer)
-
Plaintext transmission
-
Information tampering goes undetected
-
Counterparty identity is not verified

If You Were a Developer — Defense
XSS Attack Defense
-
Never trust user submissions
- Don’t directly convert user submissions into DOM
-
Ready-made tools
- Mainstream frameworks defend against XSS by default (React, etc.)
- google-closure-library
- Server-side: DOMPurify
-
User requirements: They insist on dynamic DOM generation?
-
new DOMParser();
-
SVG: Must also be scanned, since script tags can be inserted within them
-
Don’t let users define redirect links (or filter them properly)!
<a href="javascript:alert('xss')"></a>
-
-
Watch out for custom styles too

Same-Origin Policy (CSP)
- Protocol
- Domain
- Port
If any of these differ, it’s cross-origin.
Same-origin policy - Web Security | MDN (mozilla.org)
Same-origin requests are generally fine, but cross-origin ones are not. CSP allows developers to define:
-
Which origins (domains) are considered safe
-
Scripts from safe origins can be executed; otherwise, an error is thrown directly
-
eval + inline scripts are directly rejected
-
Configuration:
- Server response headers
Content-Security-Policy: script-src 'self'; // same origin Content-Security-Policy: script-src 'self' https://domain.com- Browser response headers
<meta http-equiv=" Content-Security-Policy" content="script-src self" />
CSRF Attack Defense

-
Origin + Referrer
-
Other methods to determine whether a request comes from a legitimate source
- Page first, request second
- if request comes from a legitimate page
- then the server has received a page request
- then the server can identify it
- Page first, request second
-

-
iframe attack: Restricting Origin? I’ll just use same-origin requests
-
Avoid mixing GET + POST requests — an attacker can kill two birds with one stone!
// Don't combine update + read logic in a single GET endpoint like this public async getAndUpdate(ctx) { const { update, id } = ctx.query; if (update) { await this.update(update); } ctx.body = await this.get(id); } -
SameSite Cookie
-
Restrict Cookie domain
-
Whether the page domain matches
-
What about third-party services that depend on cookies?
Embedding a player from site X — can’t recognize the user’s login status, can’t send bullet comments
Set-Cookie: SameSite=None; Secure ;

-
-
SameSite vs CORS (Cross-Origin Resource Sharing)

With all these CSRF defense methods above, what is the proper way to defend against CSRF? Write a middleware specifically to generate these defenses.
Injection Defense
-
Find all places in the project that query SQL
-
Use prepared statements
PREPARE q FROM 'SELECT user FROM users WHERE gender = ?'; SET @gender = 'female'; EXECUTE q USING @gender; DEALLOCATE PREPARE q; -
Principle of least privilege
- Never run any commands with sudo or root
-
Establish allow lists + filtering
- rm: absolutely reject
-
Restrict URL-type parameters by protocol, domain, IP, etc.
- Prevent attackers from accessing the internal network
Defending Against DoS
- Code Review (avoid greedy matching, etc.)
- Code scanning + regex performance testing
- Avoid user-provided regular expressions
Defending Against DDoS

Transport Layer — Defending Against Man-in-the-Middle
Bring out the famous HTTPS
- Confidentiality: Encryption
- Integrity: MAC verification
- Non-repudiation: Digital signatures

-
Extended topic: Digital signatures
-
Private key (keep it to yourself)
-
Public key (publicly visible)
-
CA: Certificate Authority
-
Digital signatures, browsers have built-in CA public keys

-

- When the signature algorithm is not robust enough: brute-force cracking (now already quite mature)
HTTP Strict-Transport-Security (HSTS)
- Actively upgrade HTTP to HTTPS
Static resources being hijacked and tampered with? Compare hashes.

Epilogue
- Security is no small matter
- The dependencies you use (npm packages, or even NodeJS) can become the weakest link
- Maintain a learning mindset
Summary
This lesson used vivid illustrations to explain many web security topics in a very engaging way, covering types of web attacks and defense methods.
Most of the content cited in this article comes from Teacher Liu Yuchen’s course, MDN, and external blog references: This Time, Thoroughly Understand XSS Attacks, A Brief Discussion on CSRF
喜欢的话,留下你的评论吧~