Sub topic 12
Security Models Compared
This chapter assumes you have read the earlier chapters on browser host APIs and Node.js built-in modules. You should be comfortable with fetch, fs/promises, and starting a basic http server. You should also be able to run Node.js 22 or later from a terminal, because the permission flags shown here need a recent release.
The browser and Node.js run the same language on similar engines. They trust your code very differently. A browser assumes the code it runs may be hostile, because any website can send it. Node.js assumes the code it runs belongs to the person who started it. Most security differences between the two runtimes follow from that one assumption.
Two Different Trust Assumptions
In a browser, the user visits a URL and the page's scripts run automatically. The user never reviewed those scripts and could not have. The browser therefore puts each page in a sandbox, a restricted environment where code can only reach what the browser chooses to expose.
In Node.js, you type node app.js. The runtime treats that as consent. The script runs with your operating-system user's privileges. It can read your SSH keys, delete files in your home directory, open network sockets, and start other programs. Node.js adds no boundary between your code and the system unless you ask for one.
The Browser Sandbox in Layers
The browser sandbox has several layers. Each one blocks a different kind of attack.
Process isolation
Modern browsers render each site in a separate operating-system process with reduced privileges. Chrome calls this Site Isolation. A bug in the engine that lets an attacker run native code still leaves that attacker in a process that cannot open files or read another site's memory. You do not control this layer from JavaScript, but it explains why the engine itself is not the only line of defense.
The same-origin policy
An origin is the combination of scheme, host, and port, for example https://shop.example:443. The same-origin policy stops a script from one origin from reading data that belongs to another. A page on https://evil.example cannot read the DOM of an https://bank.example tab, and it cannot read the response body of a fetch to the bank. That holds even though the browser attaches the user's cookies to the request.
CORS: the server opts in
Cross-Origin Resource Sharing (CORS) lets a server relax the same-origin policy for specific origins. The browser sends the request. If the response lacks an Access-Control-Allow-Origin header that matches the page's origin, the browser keeps the response from the script and rejects the promise with a TypeError.
// Run in the browser console on any page except api.github.com
async function tryCrossOrigin(url) {
try {
const res = await fetch(url);
console.log('allowed, status', res.status);
} catch (err) {
// CORS failures and network failures look the same to script code
console.log('blocked or offline:', err.name, err.message);
}
}
tryCrossOrigin('https://api.github.com/zen'); // GitHub sends CORS headers: allowed
tryCrossOrigin('https://example.com/'); // no CORS header: blockedPermission-gated APIs
Some web APIs reach hardware or personal data: geolocation, camera, microphone, notifications, and clipboard reads. The browser requires a secure context (HTTPS or localhost) for these, and it asks the user before granting access. Many also require a user activation, which means the call must happen inside a click or key handler. Files work the same way. A page can read a file only after the user picks it through <input type="file"> or a file picker dialog.
// Browser: query the state without triggering a prompt
const status = await navigator.permissions.query({ name: 'geolocation' });
console.log(status.state); // 'granted', 'denied', or 'prompt'Content Security Policy
The sandbox protects the user from other sites. It does nothing when an attacker injects script into your own page, an attack called cross-site scripting (XSS). The injected code runs with your origin's full privileges. Two defenses help. Prefer textContent over innerHTML for untrusted strings. Also send a Content Security Policy (CSP) header, which tells the browser which script sources it may execute.
The following Node.js server demonstrates both CSP and CORS headers:
// server.mjs (run with: node server.mjs, then open http://localhost:3000)
import { createServer } from 'node:http';
const page = `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>CSP demo</title></head>
<body>
<p id="out">waiting</p>
<script>document.getElementById('out').textContent = 'inline ran';</script>
<script src="/app.js"></script>
</body></html>`;
const app = `document.getElementById('out').textContent += ' / app.js ran';`;
createServer((req, res) => {
if (req.url === '/app.js') {
res.writeHead(200, { 'Content-Type': 'text/javascript' });
return res.end(app);
}
if (req.url === '/api') {
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'https://trusted.example',
});
return res.end(JSON.stringify({ ok: true }));
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
// Only scripts from this origin; inline scripts are refused
'Content-Security-Policy': "script-src 'self'",
});
res.end(page);
}).listen(3000, () => console.log('http://localhost:3000'));When you open the page, the inline script is blocked and DevTools logs a CSP violation. The paragraph says waiting / app.js ran, because only the same-origin file executed.
Node.js: Full Access by Default
Node.js code can do anything the user who launched it can do. That is intended, since build tools, servers, and CLIs need it. It also means that every module you load, including every transitive npm dependency, runs with those same privileges. A package's postinstall script runs during npm install before you have imported anything.
The main risks are different from the browser's:
| Risk | Example | Mitigation |
|---|---|---|
| Malicious or hijacked dependency | A package reads `~/.npmrc` tokens and sends them out | Lockfiles, `npm audit`, fewer dependencies, `npm install --ignore-scripts` |
| Path traversal | `GET /files/../../etc/passwd` reaches `fs.readFile` | Resolve the path and check it stays inside a base directory |
| Command injection | `exec('convert ' + userInput)` | Use `execFile` or `spawn` with an argument array |
| Leaked secrets | Logging `process.env` | Read only the variables you need and never log them |
| Running as root | A bug becomes full system compromise | Run as an unprivileged user or in a container |
Path traversal is the most common mistake in hand-written file servers. The fix is to resolve the path and then check that it is still inside the base directory:
// safe-path.mjs
import path from 'node:path';
const BASE = path.resolve('public');
export function safeJoin(userPath) {
const full = path.resolve(BASE, '.' + path.sep + userPath);
if (full !== BASE && !full.startsWith(BASE + path.sep)) {
throw new Error('path escapes base directory');
}
return full;
}
console.log(safeJoin('img/logo.png')); // .../public/img/logo.png
try {
safeJoin('../../etc/passwd');
} catch (err) {
console.log(err.message); // path escapes base directory
}The Node.js permission model
Node.js now has an opt-in permission model. It shipped as --experimental-permission in Node.js 20 and became stable as --permission in Node.js 22.13 and 23.5. When the flag is on, file-system access, child processes, worker threads, native addons, and WASI are denied unless you grant them explicitly.
// perm.mjs
import { readFile, writeFile } from 'node:fs/promises';
console.log('can read ./data:', process.permission?.has('fs.read', './data'));
console.log('can write /tmp:', process.permission?.has('fs.write', '/tmp'));
try {
await writeFile('/tmp/should-fail.txt', 'x');
} catch (err) {
console.log('write failed:', err.code); // ERR_ACCESS_DENIED
}
try {
const text = await readFile('./data/info.txt', 'utf8');
console.log('read ok:', text.length, 'chars');
} catch (err) {
console.log('read failed:', err.code);
}mkdir -p data && echo "hello" > data/info.txt
node --permission --allow-fs-read=./data --allow-fs-read=./perm.mjs perm.mjsThe script must be able to read itself, which is why perm.mjs appears in the grant list. Without --permission, process.permission is undefined and every check above prints undefined.
Side-by-Side Comparison
| Concern | Browser | Node.js |
|---|---|---|
| Default trust in code | None; every page is untrusted | Full; runs as the launching user |
| File system | Only files the user picks | Anything the user can access |
| Network | Any URL, but cross-origin reads need CORS | Any host and port, no CORS |
| Hardware and personal data | Permission prompt, HTTPS required | Direct through OS or addons |
| Running other programs | Impossible | `child_process` |
| Primary threat | XSS, malicious sites | Dependencies, injection, traversal |
| Opt-in hardening | CSP, `sandbox` iframes, Trusted Types | `--permission`, containers, least-privilege user |
Choosing Where Code Should Run
The comparison gives a practical rule for deciding where logic belongs. Anything that needs a secret, such as an API key or database password, must run in Node.js or another server environment, because every byte sent to a browser can be read by the user. Anything that authorizes an action must also be checked on the server, because a user can edit browser code in DevTools. The browser is the right place for presentation and convenience checks, such as form validation that gives quick feedback before the server validates again.
Universal modules, covered in an earlier chapter, inherit the stricter limits of both runtimes. A shared fetch helper will hit CORS in the browser and none in Node.js. It must never assume it has file access, and it must never embed credentials.
Exercise
A teammate says, "Our API is safe from scraping because it only sends Access-Control-Allow-Origin for our own domain." Is that correct? Explain what the header actually prevents.
Show answer
It is not correct. CORS is enforced only by browsers, so curl, Node.js fetch, or any script outside a browser can call the API and read the response. The header only stops scripts on other origins from reading responses inside a user's browser, which protects that user's cookies and session data. Scraping protection needs authentication, rate limiting, or similar server-side controls.
Exercise
You run node --permission --allow-fs-read=./config app.mjs and app.mjs makes an https request to an external API. Does the request succeed? What happens if app.mjs calls fs.writeFile('./config/out.json', ...)?
Show answer
The network request succeeds because the permission model does not restrict network access. The write fails with an error whose code is ERRACCESSDENIED, since no --allow-fs-write grant was given. The command also needs read access to app.mjs itself, for example by granting --allow-fs-read=. or adding the file path, or Node.js cannot load the entry script.
Exercise
Rewrite this call so user input cannot inject shell commands: exec(git log --author=${name}, cb).
Show answer
Use execFile with an argument array so no shell parses the input: import { execFile } from 'node:child_process'; execFile('git', ['log', --author=${name}], cb);. The name becomes a single argument, so characters such as ; or $( ) are passed to git literally and never run as commands.