#Why this matters
In the previous lesson, you saw how browsers exchange HTTP requests and carry session cookies automatically. A browser also builds a live page from HTML and runs JavaScript from remote servers. If any script on one website could read responses from your bank or webmail tab using your stored cookies, a single malicious link would expose every active account.
Modern browser security relies on three layered controls: the Same-Origin Policy (SOP) isolates sites by default, Cross-Origin Resource Sharing (CORS) grants controlled cross-origin exceptions, and Content Security Policy (CSP) restricts which scripts and resources a page may execute.
#How browsers parse HTML and execute JavaScript
When a browser receives HTML, it parses tags into the Document Object Model (DOM), a live tree of elements. Whenever it encounters a script element or an inline event handler like onload, it runs that JavaScript with access to the DOM and any non-HttpOnly cookies.
Because the browser downloads all client-side JavaScript to run it, anyone can read or modify it in Browser DevTools (Network or Sources tab):
// Vulnerable client-only check: readable and bypassable in DevTools
function unlockReport(pin) {
if (pin === "4819") {
fetch("/api/internal-report").then(r => r.text()).then(console.log);
}
}Never store secrets or enforce access control solely in browser JavaScript.
#The Same-Origin Policy (SOP)
The origin of a URL is its (scheme, host, port) tuple. Two URLs share an origin only when all three match, as shown when comparing against https://app.lab.local/dashboard (port 443):
| Target URL | Scheme | Host | Port | Same origin? |
|---|---|---|---|---|
https://app.lab.local/settings |
https |
app.lab.local |
443 |
Yes |
http://app.lab.local/dashboard |
http |
app.lab.local |
80 |
No (scheme differs) |
https://api.lab.local/dashboard |
https |
api.lab.local |
443 |
No (host differs) |
https://app.lab.local:8443/dashboard |
https |
app.lab.local |
8443 |
No (port differs) |
Under SOP, JavaScript on https://attacker.test cannot read HTTP responses from https://app.lab.local. Crucially, SOP restricts reading responses via script, not sending cross-origin img loads or form submissions, which is why cookies also need SameSite flags and CSRF defences.
#Controlled sharing with CORS
Legitimate frontends often call an API on another subdomain, such as https://app.lab.local fetching JSON from https://api.lab.local. CORS lets the API declare allowed readers via response headers.
For non-simple methods like DELETE or custom headers, the browser first sends an OPTIONS preflight request to confirm permission.
CORS becomes dangerous when servers misconfigure trust:
- Dynamic Origin reflection with credentials: Echoing any incoming
Originheader intoAccess-Control-Allow-Originwhile settingAccess-Control-Allow-Credentials: truelets any site read authenticated user data. - Trusting
Origin: null: Sandboxediframeelements sendOrigin: null, so allow-listingnulllets untrusted pages read responses. - Weak string matching: Checking
origin.endsWith("lab.local")falsely trustshttps://evil-lab.local.
$ curl -s -i -H "Origin: https://attacker.test" http://api.lab.local/profile | grep -i "access-control"
Access-Control-Allow-Origin: https://attacker.test
Access-Control-Allow-Credentials: trueBrowsers forbid combining wildcard Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true, because that would expose private responses to every site.
#Restricting script execution with CSP
Content Security Policy (CSP) uses the Content-Security-Policy response header to restrict which scripts, endpoints, and frames a page may use, limiting the impact of HTML or script injection.
| Directive | Purpose | Safe example |
|---|---|---|
default-src |
Fallback for unlisted resource types | default-src 'self' |
script-src |
Controls which JavaScript may run | script-src 'nonce-r8K2mP9q' |
connect-src |
Limits fetch, XHR, and WebSocket targets |
connect-src 'self' https://api.lab.local |
object-src |
Controls legacy plugins | object-src 'none' |
base-uri |
Restricts base tag targets |
base-uri 'self' |
frame-ancestors |
Lists sites allowed to frame the page | frame-ancestors 'none' |
Strong policies avoid 'unsafe-inline' and 'unsafe-eval', issuing a fresh cryptographic nonce per response (a nonce="r8K2mP9q" attribute on the script element) so injected inline scripts without the matching nonce are blocked.
#Defending and common mistakes
- Treating client-side JS as hidden: Users can inspect and modify all browser code in DevTools; enforce secrets and authorization on the server.
- Reflecting
Originheaders blindly: MatchOriginagainst an exact allow-list of scheme, host, and port. - Weak CSP rules: Including
'unsafe-inline'orscript-src *lets injected scripts execute. - Relying on CSP alone: CSP mitigates XSS impact but never replaces context-aware output encoding.
#Summary
- Browsers parse HTML into the DOM and execute JavaScript with page access, so client-side checks cannot protect secrets.
- The Same-Origin Policy isolates sites by
(scheme, host, port), blocking cross-origin script reads by default. - CORS enables selective cross-origin reads, but reflecting arbitrary
Originheaders ornullwith credentials leaks private data. - Content Security Policy uses directives like
script-src,object-src, andframe-ancestorsto constrain scripts and framing.