SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 58
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 58 of 90

Secure coding in JavaScript and Node.js

eval and new Functionprototype pollutionReDoS (regex denial of service)child_process safetyinput validation (schemas, zod)helmetexpress security settingsXSS in React (dangerouslySetInnerHTML)npm lifecycle scriptspackage-lock.jsonnpm auditNode.js permission modelDeno permissions (concept)

These are the notes for Cybersecurity Fundamentals (defensive), episode 58. Episodes 56 and 57 covered Java and Python. JavaScript is memory-safe too (no buffer overflows), but it has its own traps: running text as code, objects that share a hidden parent, regular expressions that freeze a server, shell commands built from input, web pages that run what users post, and the packages you install. This episode trips each one in a toy program, fixes it, and then limits what code is allowed to touch. Every term is defined the first time it appears; the Glossary collects them.

Scope. Defensive and educational only. Every program is a toy that works on its own files and its own data; no real system is touched, and no working exploit for real software is shown. The compiler samples were run on 13 Nov 2026 in the SyntaxPilot compiler (Node.js 24.22.3). The zod 4.6.7, helmet 8.3.0 (with Express 5.3.0), React 19.3.1, npm install, npm ci and npm audit outputs were produced the same day on the same machine with npm 10.9.9. Folder names and timings differ on your machine.

Words you need first

  • JavaScript: the programming language every web browser runs.
  • Node.js: a program that runs JavaScript outside the browser, on a server or your laptop. It runs your code on one main thread (one line of work at a time), handing slow jobs like file and network reads to the system in the background.
  • Memory-safe: the language checks every array access and manages memory for you, so buffer overflows (episode 53) do not happen in normal code.
  • Untrusted input: anything that comes from outside your program: a form field, a URL, a JSON request body, a file someone uploads.

The seven traps

Trap Fix
Text that runs as code: eval, new Function JSON.parse for data; never run input
Objects with a shared parent: prototype pollution skip __proto__/constructor/prototype, Object.hasOwn, Object.create(null), Map, schemas
Regexes that freeze: ReDoS no nested quantifiers, length limits, tested validators
Shell commands from input execFile / spawn with an argument list; schema validation (zod)
Web apps and pages helmet, body size limits, React's escaping, no dangerouslySetInnerHTML with user HTML
The packages you install --ignore-scripts, a committed package-lock.json, npm ci, npm audit
What code may touch the Node.js permission model (--permission), Deno permissions

Problem 1: text that runs as code (eval, new Function)

Real-life example: an office clerk who obeys any slip handed in ("add 2 and 3"... or "open the safe"), versus a clerk who only copies numbers onto a form.

  • eval(text) runs a string as JavaScript and returns the result.
  • new Function(text) builds a function from a string of code. It is eval in disguise: the text still runs as code.
  • The string forms of setTimeout("code", ms) and setInterval("code", ms) also run text as code.
  • If the text comes from a user, they can run any JavaScript in your server: read files, start programs, steal secrets. This is code injection.
  • JSON (JavaScript Object Notation) is a text format that can only hold data: strings, numbers, true/false, null, arrays and objects. JSON.parse(text) turns JSON text into data and can never run code.

Demo 1: eval vs JSON.parse

// A "settings box": the user types a list of marks, we turn it into data.
const honest = "[90, 85, 77]";
const typed = "process.cwd()";         // the user types CODE, not data

console.log("eval honest  ->", eval(honest));
console.log("eval typed   ->", eval(typed));      // it ran: server folder
const f = new Function("return " + typed);        // eval in disguise
console.log("new Function ->", f());

console.log("JSON.parse   ->", JSON.parse(honest));   // data only
try {
  JSON.parse(typed);
} catch (e) {
  console.log("JSON.parse   -> refused:", e.message);
}

Real output (the folder name is the stage's working folder; yours will differ):

eval honest  -> [ 90, 85, 77 ]
eval typed   -> /tmp/stage-...
new Function -> /tmp/stage-...
JSON.parse   -> [ 90, 85, 77 ]
JSON.parse   -> refused: Unexpected token 'p', "process.cwd()" is not valid JSON

process.cwd() asks Node for its current working folder. Harmless here, but the same door lets someone call require("fs") and read any file. Rule: never pass input to eval, new Function, or the string forms of setTimeout/setInterval. Parse data with JSON.parse, then validate its shape (see zod below). If you really need user maths, use a small parser or a maths library that does not run JavaScript.

Problem 2: prototype pollution

Real-life example: one family rulebook that every family member follows. Write a new rule in it, and everyone obeys, even people born later.

  • Prototype: every JavaScript object has a hidden parent object. When you read a property the object does not have, JavaScript looks in the parent (and the parent's parent). That is why an empty {} still has toString.
  • Object.prototype: the parent shared by every ordinary object.
  • __proto__: a special property name that points at an object's prototype. Writing obj.__proto__.x = 1 writes into the shared parent.
  • Deep merge: a helper that copies a source object into a target, key by key, going into nested objects.
  • Prototype pollution: when untrusted input makes your code write into Object.prototype (usually through a key named __proto__, or constructor.prototype). Every object in the program then "has" the injected property.

Demo 2: a brand-new object becomes admin

// Merge a user's saved settings into the defaults (a common helper).
function merge(target, src) {
  for (const key in src) {
    if (typeof src[key] === "object") {
      target[key] = target[key] || {};
      merge(target[key], src[key]);
    } else target[key] = src[key];
  }
}
const body = '{"theme": "dark", "__proto__": {"isAdmin": true}}';
merge({}, JSON.parse(body));         // the user's JSON request body
console.log("unsafe: new user isAdmin =", ({}).isAdmin);  // polluted!
delete Object.prototype.isAdmin;     // clean up, then the fix:

const BAD = ["__proto__", "constructor", "prototype"];
function mergeSafe(target, src) {
  for (const key of Object.keys(src)) {
    if (BAD.includes(key)) continue; // skip the dangerous keys
    if (typeof src[key] === "object") {
      if (!Object.hasOwn(target, key)) target[key] = {};
      mergeSafe(target[key], src[key]);
    } else target[key] = src[key];
  }
}
mergeSafe({}, JSON.parse(body));
console.log("safe:   new user isAdmin =", ({}).isAdmin);
const dict = Object.create(null);    // an object with NO prototype
console.log("Object.create(null) prototype:", Object.getPrototypeOf(dict));

Real output:

unsafe: new user isAdmin = true
safe:   new user isAdmin = undefined
Object.create(null) prototype: null

Why it happened: JSON.parse creates an ordinary own key called "__proto__". When merge reaches it, target["__proto__"] is Object.prototype (truthy), so merge(Object.prototype, {isAdmin: true}) runs, and every object now inherits isAdmin: true.

Fixes (use more than one):

  1. Skip the dangerous keys: __proto__, constructor, prototype.
  2. Object.hasOwn(obj, key): true only if the key belongs to the object itself, not to its parent. Use it instead of obj[key] truthiness or the in operator.
  3. Object.create(null): makes an object with no prototype, so __proto__ is just an ordinary key. Or use a Map for lookups keyed by user input.
  4. Validate the input's shape with a schema that rejects unknown keys (zod's .strict(), below).
  5. Keep libraries updated: old versions of popular merge helpers (for example lodash 4.17.11, see npm audit below) had prototype pollution bugs.

Problem 3: regexes that freeze (ReDoS)

Real-life example: a ticket checker who, to decide whether a queue of 27 people can be split into groups that all have tickets, tries every possible way of splitting the queue, when walking down it once would do.

  • Regular expression (regex): a small pattern language for matching text, e.g. /^a+$/ means "only the letter a, one or more times".
  • Quantifier: a symbol saying "how many": + (one or more), * (zero or more), {2,5}.
  • Nested quantifier: a quantifier on a group that itself contains a quantifier, like (a+)+.
  • Backtracking: when a match fails, JavaScript's regex engine goes back and tries another way to split the text between the parts of the pattern. With nested quantifiers there are exponentially many splits, and on a near-miss input it tries them all.
  • ReDoS (regular expression denial of service): an input crafted so a regex takes a very long time. Because Node runs your JavaScript on one main thread, one slow regex blocks every other request.

Demo 3: timing a nested regex

// Check a username is only letters "a": two regexes, same answers.
const evil = /^(a+)+$/;              // a group inside a group: nested +
const good = /^a+$/;                 // the same rule, written simply
evil.test("aaaaaaaaaaaaaaaa!");      // warm up the regex engine first

for (const n of [21, 23, 25, 27]) {
  const input = "a".repeat(n) + "!"; // almost matches, then fails
  let t = Date.now();
  evil.test(input);
  const slow = String(Date.now() - t).padStart(4);
  t = Date.now();
  good.test(input);
  console.log(`n=${n}  (a+)+: ${slow} ms   a+: ${Date.now() - t} ms`);
}

Real output (timings vary by machine):

n=21  (a+)+:   14 ms   a+: 0 ms
n=23  (a+)+:   59 ms   a+: 0 ms
n=25  (a+)+:  233 ms   a+: 0 ms
n=27  (a+)+:  877 ms   a+: 0 ms

Each 2 extra letters made the nested regex about 4x slower. Continuing that trend, 40 letters would take about 0.877 s x 2^13 ≈ 7,200 s, roughly two hours, while the simple /^a+$/ stays at 0 ms. Fixes: avoid nested quantifiers ((a+)+, (.*)*, (a|a)+), limit the input length before matching, prefer tested validator libraries, and lint for unsafe regexes.

Problem 4: shell commands from input (child_process)

Real-life example: an assistant who reads your whole note aloud to the office ("print file X; and then fire Ravi"), versus a form with fixed boxes.

  • child_process: Node's built-in module for running other programs.
  • Shell: the program (/bin/sh) that reads a command line and treats ;, |, &, $() as instructions.
  • exec(string) / execSync: hands one string to a shell.
  • execFile(program, [args]) / spawn: run one program with a list of arguments, with no shell (unless you pass shell: true).
  • Command injection: input that makes the shell run extra commands.

Demo 4: exec vs execFile

// Count the lines of a file the user names, with the wc command.
const { execSync, execFileSync } = require("node:child_process");
const fs = require("node:fs");
fs.writeFileSync("notes.txt", "chai\nsamosa\n");
const file = "notes.txt; echo INJECTED: a 2nd command ran"; // input

// UNSAFE: exec runs a SHELL, which reads ';' as "run another command"
const out = execSync("wc -l " + file, { encoding: "utf8" });
console.log("exec + string:", out.trim().replace("\n", " | "));

// SAFE: execFile, a program + a list of arguments, no shell at all
try {
  execFileSync("wc", ["-l", file], { encoding: "utf8", stdio: "pipe" });
} catch (e) {
  console.log("execFile list:", e.stderr.trim());
}

Real output:

exec + string: 2 notes.txt | INJECTED: a 2nd command ran
execFile list: wc: 'notes.txt; echo INJECTED: a 2nd command ran': No such file or directory

With exec, the shell read ; as "run another command". With execFile and a list, the whole input is one file name. Prefer execFile/spawn with an argument list, never shell: true with input, and put -- before user-supplied names (["-l", "--", name]) so a name starting with - cannot be read as an option.

Input validation with a schema (zod)

  • Input validation: checking that input has exactly the shape you expect (types, lengths, ranges, allowed keys) before using it.
  • Schema: a written description of that shape.
  • zod: a popular schema library for JavaScript and TypeScript (version 4.6.7 used here).
const { z } = require("zod");
const Order = z.object({
  item: z.string().min(1).max(30),
  qty: z.number().int().min(1).max(20),
}).strict();                       // unknown keys are refused

console.log(Order.parse({ item: "chai", qty: 2 }));
const r = Order.safeParse({ item: "chai", qty: -5, isAdmin: true });
console.log(r.success);
for (const i of r.error.issues) console.log(i.path.join(".") || "(object)", "->", i.message);

Real output:

{ item: 'chai', qty: 2 }
false
qty -> Too small: expected number to be >=1
(object) -> Unrecognized key: "isAdmin"

.strict() alone blocks a __proto__ or isAdmin key in a request body. Validate at the door: every request body, query string and uploaded JSON.

Problem 5: web apps (helmet, Express settings, XSS in React)

  • Express: the most popular web framework for Node.js.
  • HTTP header: a short name: value note sent with every response, telling the browser how to behave.
  • Middleware: a function Express runs on every request before your route.
  • helmet: a middleware (8.3.0 here) that sets safer HTTP headers in one line: app.use(helmet()).

Real headers with helmet() (shortened):

content-security-policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
cross-origin-opener-policy: same-origin
cross-origin-resource-policy: same-origin
origin-agent-cluster: ?1
referrer-policy: no-referrer
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-download-options: noopen
x-frame-options: SAMEORIGIN
x-permitted-cross-domain-policies: none
x-xss-protection: 0

Without helmet, the same app sent x-powered-by: Express (telling everyone what you run) and none of the above.

Header What it does
Content-Security-Policy (CSP) lists where scripts, styles and images may come from; script-src 'self' = only our own site
Strict-Transport-Security (HSTS) "use HTTPS only" for the next max-age seconds (here one year)
X-Content-Type-Options: nosniff don't guess file types (stops a text upload being run as a script)
X-Frame-Options: SAMEORIGIN / frame-ancestors other sites can't show us in a frame (stops clickjacking: tricking a user into clicking a hidden framed page)
Referrer-Policy: no-referrer don't leak our URLs to other sites

Other Express settings: limit body size (express.json({ limit: "10kb" })), mark cookies secure, httpOnly and sameSite, rate-limit login routes, and don't show stack traces to users in production.

XSS in React

  • XSS (cross-site scripting): an attacker's script ends up in a page and runs in other users' browsers (episode 40).
  • Escaping: turning <, >, &, " into &lt;, &gt;, &amp;, &quot; so they show as text.
  • React escapes anything you put in {curly braces}. dangerouslySetInnerHTML inserts a string as real HTML, with no escaping.
const comment = '<img src=x onerror="alert(1)">';      // what a user posted
const Safe = () => React.createElement("p", null, comment);
const Risky = () => React.createElement("p", { dangerouslySetInnerHTML: { __html: comment } });
console.log(renderToString(React.createElement(Safe)));
console.log(renderToString(React.createElement(Risky)));

Real output (react-dom/server 19.3.1):

<p>&lt;img src=x onerror=&quot;alert(1)&quot;&gt;</p>
<p><img src=x onerror="alert(1)"></p>

The second is a real tag: the image fails to load and the browser runs onerror. If you must show user HTML, clean it with a sanitizer (a library such as DOMPurify that removes scripts and event handlers) and keep a CSP as a second wall. Also never put user input into href="javascript:..." links.

Problem 6: the packages you install (npm)

  • npm: Node's package manager. npm install x downloads x and every package it depends on (transitive dependencies, episode 56).
  • Lifecycle scripts: commands a package declares in its package.json that npm runs at moments like install: preinstall, install, postinstall. They run with all of your user's permissions.
  • --ignore-scripts: tells npm not to run lifecycle scripts. You can make it the default with ignore-scripts=true in an .npmrc file, and allow scripts only for packages that need them.
  • package-lock.json: the lockfile: the exact version of every package in the tree, where it came from, and an integrity hash (a SHA-512 fingerprint of the exact file).
  • npm ci: a clean install for build servers: installs exactly what the lockfile says, and fails if a file's hash doesn't match.

Real output, with a harmless toy package whose postinstall only prints:

$ npm install ../toy-pkg/toy-colors-1.0.0.tgz --foreground-scripts
> toy-colors@1.0.0 postinstall
> node -e "console.log('postinstall ran as', require('os').userInfo().username, 'in', process.cwd())"
postinstall ran as root in /tmp/.../proj2/node_modules/toy-colors
added 1 package, and audited 2 packages in 365ms

$ npm install ../toy-pkg/toy-colors-1.0.0.tgz --ignore-scripts --foreground-scripts
added 1 package, and audited 2 packages in 359ms

The lockfile entry it wrote:

"node_modules/toy-colors": {
  "version": "1.0.0",
  "resolved": "file:../toy-pkg/toy-colors-1.0.0.tgz",
  "integrity": "sha512-BvcjEKlXXZMHkjPH7kOfFLhx9n2vRbDP5QRwvetotH/5kCsBqCndup+GUkn6JvIDQn0t5Vt3tV9smBfVAMl10g==",
  "hasInstallScript": true
}

After changing the recorded hash (to simulate a file that is not the one we pinned), npm ci refused:

npm error code EINTEGRITY
npm error sha512-AAAAEK... integrity checksum failed when using sha512: wanted sha512-AAAAEK... but got sha512-BvcjEK.... (237 bytes)

Habits: commit package-lock.json; use npm ci in builds; review new dependencies (and hasInstallScript) before adding them; consider ignore-scripts=true.

npm audit

  • npm audit "submits a description of the dependencies configured in your project to your default registry" and gets back a report of known vulnerabilities (npm docs).
  • --audit-level=high sets the failure threshold: the command exits non-zero only for high or critical issues. It "does not filter the report output, it simply changes the command's failure threshold".
  • npm audit fix applies the fixes it can (some need manual work).

Real report, after pinning an old lodash:

$ npm ls --depth=0
+-- lodash@4.17.11
$ npm audit
lodash  <=4.17.23
Severity: critical
Command Injection in lodash - https://github.com/advisories/GHSA-35jh-r3h4-6jhm
Prototype Pollution in lodash - https://github.com/advisories/GHSA-jf85-cpcp-j695
Prototype Pollution in lodash - https://github.com/advisories/GHSA-p6mc-m468-83gw
Regular Expression Denial of Service (ReDoS) in lodash - https://github.com/advisories/GHSA-29mw-wpgm-hmr9
lodash vulnerable to Code Injection via `_.template` imports key names - https://github.com/advisories/GHSA-r5fr-rjxr-66jc
Lodash has Prototype Pollution Vulnerability in `_.unset`, `_.omit`, and `_.pullAt` functions - https://github.com/advisories/GHSA-xxjr-mmjv-4gpg
fix available via `npm audit fix`
1 critical severity vulnerability
$ npm audit --audit-level=high ; echo $?
1
$ npm audit fix
found 0 vulnerabilities          (lodash is now 4.18.1)

Today's three traps (code injection, prototype pollution, ReDoS) all appear in a real, widely used library's history. npm audit signatures additionally checks registry signatures and provenance of downloaded packages.

Problem 7: limit what code may touch

Real-life example: a master key to every room versus a visitor pass for rooms 2 and 5 only.

  • Least privilege (episode 3): give a program only the access it needs.
  • Node.js permission model: start Node with --permission and file-system reads and writes, network access, child processes, worker threads, native addons, WASI and the inspector are restricted, unless allowed with flags such as --allow-fs-read=<path>, --allow-fs-write=<path>, --allow-child-process, --allow-worker. Denied calls throw ERR_ACCESS_DENIED. The docs mark it Stability: 2 - Stable, no longer experimental since v23.5.0 and v22.13.0.
  • It is a "seat belt": it stops trusted code from touching things by mistake, but "does not provide security guarantees in the presence of malicious code". For untrusted code, use real isolation (a container or a separate machine).

Demo 5: the permission model

// Run one small app twice: normally, then inside Node's permission model.
const { spawnSync } = require("node:child_process");
const fs = require("node:fs");
fs.writeFileSync("menu.txt", "chai 10, samosa 15");
fs.writeFileSync("secret.txt", "DB_PASSWORD=chai123");
fs.writeFileSync("app.js", `const fs = require("node:fs");
console.log("  menu  :", fs.readFileSync("menu.txt", "utf8"));
try { console.log("  secret:", fs.readFileSync("secret.txt", "utf8")); }
catch (e) { console.log("  secret:", e.code, e.permission); }`);

function run(flags) {
  console.log("$ node", ...flags, "app.js");
  const r = spawnSync("node", [...flags, "app.js"], { encoding: "utf8" });
  process.stdout.write(r.stdout);
}
run([]);
const allow = ["--allow-fs-read=menu.txt", "--allow-fs-read=app.js"];
run(["--permission", ...allow]);       // only these two files

Real output:

$ node app.js
  menu  : chai 10, samosa 15
  secret: DB_PASSWORD=chai123
$ node --permission --allow-fs-read=menu.txt --allow-fs-read=app.js app.js
  menu  : chai 10, samosa 15
  secret: ERR_ACCESS_DENIED FileSystemRead

Deno permissions

  • Deno is another JavaScript and TypeScript runtime. Its docs say "Deno is secure by default": no file, network or environment-variable access unless granted.
  • Grants: --allow-read[=path], --allow-write, --allow-net[=host], --allow-env, --allow-run. Most can be scoped (--allow-net=api.shop.in).
  • In a terminal, Deno asks before allowing; refused operations throw a NotCapable error; --no-prompt makes them fail outright.
  • Caution: --allow-run lets the script start programs that run outside the sandbox; grant it only for specific trusted programs.

The whole chain

  1. eval / new Function on input → JSON.parse + a schema.
  2. A merge that obeys __proto__ → skip the keys, Object.hasOwn, Object.create(null) / Map.
  3. (a+)+ freezes the server → a simple regex and a length limit.
  4. exec(string) → execFile(program, [args]); validate with zod.
  5. Web → helmet, small body limits, secure cookies, no dangerouslySetInnerHTML with user HTML.
  6. Packages → --ignore-scripts, a committed lockfile, npm ci, npm audit --audit-level=high.
  7. Reach → node --permission --allow-..., Deno --allow-....

Common mistakes (and the fix)

Mistake What you see Why Fix
eval(req.body.marks) eval typed -> /tmp/... (the code ran) text runs as code JSON.parse(text) + a schema
new Function("return " + input) same as eval builds code from text don't build code from input
merge(defaults, JSON.parse(body)) unsafe: new user isAdmin = true __proto__ wrote to the shared parent skip __proto__/constructor/prototype, Object.hasOwn
if (user.isAdmin) on a plain object true for everyone after pollution inherited property Object.hasOwn(user, "isAdmin"), Object.create(null)
/^(a+)+$/.test(input) n=27 (a+)+: 877 ms nested quantifier backtracks /^a+$/, length limit
exec("wc -l " + name) INJECTED: a 2nd command ran the shell reads ; execFile("wc", ["-l", "--", name])
<p dangerouslySetInnerHTML={{__html: post}} /> <p><img src=x onerror="alert(1)"></p> no escaping <p>{post}</p>, or sanitize first
no helmet() x-powered-by: Express, no CSP/HSTS default headers app.use(helmet())
lockfile not committed, npm install in CI different versions each build no pinning commit package-lock.json, npm ci
changed package file npm error code EINTEGRITY hash mismatch (good!) investigate; never just delete the lockfile
old lodash@4.17.11 Severity: critical known vulnerabilities npm audit fix (here to 4.18.1)
script reads any file secret: DB_PASSWORD=chai123 full access by default node --permission --allow-fs-read=...

Mini project: harden a toy order API

Write orders.js, an Express app with POST /orders (JSON body {item, qty}) and GET /search?q=. Requirements: app.use(helmet()); express.json({ limit: "10kb" }); validate the body with a zod .strict() schema; store orders in a Map; escape the search term in the response (or use a template engine with autoescape); no eval, no exec; a lockfile committed; npm audit --audit-level=high clean; and run it with node --permission --allow-fs-read=. to prove it needs nothing else. Test it with a body containing "__proto__" and an over-long q.

Practice

1. Fix the merge helper so that a {"__proto__": {...}} body cannot pollute, using Object.hasOwn.

Solution
const BAD = new Set(["__proto__", "constructor", "prototype"]);
function mergeSafe(target, src) {
  for (const key of Object.keys(src)) {          // own keys only
    if (BAD.has(key)) continue;
    const v = src[key];
    if (v && typeof v === "object" && !Array.isArray(v)) {
      if (!Object.hasOwn(target, key)) target[key] = {};
      mergeSafe(target[key], v);
    } else target[key] = v;
  }
  return target;
}
mergeSafe({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
console.log(({}).isAdmin);   // undefined

2. Why does Object.create(null) help, and what does it lose?

Solution

It has no prototype, so obj["__proto__"] is just an own key and nothing can reach Object.prototype through it. It loses inherited methods: obj.toString() and obj.hasOwnProperty() don't exist; use Object.hasOwn(obj, k) and Object.keys(obj) instead. A Map is often clearer.

3. Time your own regex. Is /^([a-z]+\s?)+$/ safe for a 40-character near-miss input like "a".repeat(40) + "!"?

Solution

No: ([a-z]+\s?)+ is a nested quantifier (the \s? is optional, so the group can match the same letters in many ways), and it backtracks exponentially on a near miss. Rewrite as /^[a-z]+(\s[a-z]+)*$/ (each space is required between words, so there is only one way to split), and cap the length first: if (s.length > 100) reject.

4. Rewrite exec("convert " + file + " out.png") safely.

Solution
const { execFile } = require("node:child_process");
execFile("convert", ["--", file, "out.png"], (err, stdout, stderr) => { /* ... */ });

Validate file too (an allow-listed folder and extension, path resolved inside it, as in episode 57).

5. Write a zod schema for a signup body: email (an email), name (1-40 chars), age (integer 13-120), nothing else.

Solution
const Signup = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(40),
  age: z.number().int().min(13).max(120),
}).strict();

6. Your CI should fail only on high or critical npm advisories. Which command?

Solution

npm ci && npm audit --audit-level=high. npm ci installs exactly the lockfile; --audit-level=high exits non-zero only for high/critical, while still printing everything.

7. Run a script that may read only ./data and write only ./out, with nothing else allowed.

Solution

node --permission --allow-fs-read=./data --allow-fs-write=./out app.js (the entry file itself is allowed to be read automatically). Child processes, workers and the inspector stay blocked unless you add --allow-child-process, --allow-worker, and so on.

Quick quiz

const body = JSON.parse(req.body);   // from the user

A: const s = {};                 merge(s, body)
B: const s = Object.create(null); merge(s, body)
C: const s = { theme: 'light' };  merge(s, body)
D: const s = new Object();       merge(s, body)

Which object can't be polluted through __proto__?

Answer

B. Object.create(null) has no prototype, so a "__proto__" key is just an ordinary key on it and cannot reach Object.prototype. A, C and D are ordinary objects whose parent is Object.prototype. A deep merge can still pollute through nested objects it creates with {}, so also skip the dangerous keys or validate with a schema.

Interview questions

  1. What is prototype pollution, and how do you prevent it? Untrusted keys like __proto__ make code write into Object.prototype, so every object inherits attacker-chosen properties. Prevent with key filtering, Object.hasOwn, Object.create(null)/Map, strict schemas, and patched libraries.
  2. Why is new Function(str) as dangerous as eval? It compiles and runs arbitrary code from a string.
  3. What is ReDoS and why does it hurt Node.js especially? A regex with catastrophic backtracking takes exponential time on crafted input; Node runs JavaScript on one main thread, so it blocks all requests.
  4. exec vs execFile? exec runs a command string through a shell (injection risk); execFile runs a program with an argument array and no shell.
  5. What does helmet do? Sets security headers (CSP, HSTS, nosniff, frame protection, referrer policy) and removes X-Powered-By.
  6. Is React immune to XSS? It escapes {} content, but dangerouslySetInnerHTML, javascript: URLs and direct DOM writes bypass it.
  7. Why commit package-lock.json and use npm ci? Reproducible installs of exact versions with integrity hashes; npm ci fails on mismatches.
  8. What are npm lifecycle scripts and why are they risky? preinstall/install/postinstall commands run automatically during install with the user's permissions; malicious packages abuse them. Use --ignore-scripts and review dependencies.
  9. What is the Node.js permission model, and what is it not? --permission restricts fs, network, child processes, workers and more to what you allow; it is a seat belt for trusted code, not a sandbox against malicious code.
  10. How does Deno's model differ? Deno denies by default without any flag; Node denies only when started with --permission.

Glossary

Term Meaning
JavaScript the language every web browser runs
Node.js a program that runs JavaScript outside the browser (servers, laptops)
main thread / event loop Node runs your JavaScript one piece at a time on one thread; a slow task blocks the rest
memory-safe the language manages memory and checks array bounds, so no buffer overflows
untrusted input any data from outside your program
eval runs a string as JavaScript
new Function builds a function from a string of code (eval in disguise)
code injection user input that ends up running as code
JSON JavaScript Object Notation: a text format for plain data only
JSON.parse turns JSON text into data; never runs code
object a collection of key: value properties
prototype an object's hidden parent, consulted when a property is missing
Object.prototype the parent shared by every ordinary object
__proto__ special property name that points at an object's prototype
prototype pollution input that writes into a shared prototype, so every object inherits it
deep merge copying one object into another key by key, including nested objects
Object.hasOwn true only if a key belongs to the object itself
Object.create(null) creates an object with no prototype
Map a built-in key-value collection with no inherited keys
regular expression (regex) a pattern language for matching text
quantifier +, *, ?, {m,n}: how many times something repeats
nested quantifier a quantified group containing a quantifier, e.g. (a+)+
backtracking the regex engine going back to try other ways to match
ReDoS regular expression denial of service: crafted input makes a regex run for a very long time
denial of service making a service unavailable to its real users
child_process Node's module for running other programs
shell the program that reads command lines and interprets ;, |, &
exec / execSync run a command string through a shell
execFile / spawn run a program with an argument list, no shell
command injection input that makes a shell run extra commands
input validation checking input's type, size, range and allowed keys before use
schema a written description of the shape data must have
zod a JavaScript/TypeScript schema validation library
.strict() zod option that refuses unknown keys
Express the most popular Node.js web framework
middleware a function run on every request before your route
HTTP header a name: value note sent with a request or response
helmet Express middleware that sets security headers
CSP (Content Security Policy) a header listing where scripts and other content may load from
HSTS (Strict-Transport-Security) a header telling the browser to use HTTPS only
nosniff header value: don't guess file types
clickjacking tricking a user into clicking something on a hidden, framed page
X-Powered-By a header announcing the server framework; remove it
XSS (cross-site scripting) an attacker's script running in other users' browsers via your page
escaping turning < > & " into harmless text entities like &lt;
React a library for building web pages from components
dangerouslySetInnerHTML React prop that inserts a string as real, unescaped HTML
sanitizer (DOMPurify) a library that removes scripts and event handlers from HTML
npm Node's package manager and registry
package / dependency code from someone else that your project uses
transitive dependency a dependency of a dependency
lifecycle scripts preinstall, install, postinstall: commands npm runs during install
--ignore-scripts npm option not to run lifecycle scripts
.npmrc npm's settings file
package-lock.json (lockfile) exact versions, sources and integrity hashes of every installed package
integrity hash a SHA-512 fingerprint of the exact package file
npm ci clean install exactly from the lockfile; fails on mismatches
EINTEGRITY npm error: a downloaded file's hash doesn't match the lockfile
npm audit checks your dependency tree against known vulnerabilities
--audit-level the severity at which npm audit exits non-zero
npm audit fix upgrades packages to fixed versions where possible
advisory (GHSA) a published vulnerability report; GHSA = GitHub Security Advisory ID
least privilege giving a program only the access it needs
Node.js permission model --permission plus --allow-... flags restricting what a script can access
ERR_ACCESS_DENIED the error Node throws when the permission model blocks a call
seat belt (not a sandbox) protection against mistakes by trusted code, not against malicious code
Deno a JavaScript/TypeScript runtime that denies access by default
--allow-read / --allow-net / --allow-env / --allow-run Deno grants for files, network, environment variables, starting programs
NotCapable the error Deno throws for a refused permission

Summary

  • Never run text as code: no eval, new Function or string timers on input; parse data with JSON.parse and validate it with a schema.
  • Guard against prototype pollution: skip __proto__/constructor/prototype, use Object.hasOwn, Object.create(null) or Map, and keep libraries patched.
  • Keep regexes simple and inputs short: nested quantifiers can freeze a single-threaded server.
  • Use execFile/spawn with argument lists; never a shell with input.
  • helmet(), body limits and secure cookies for Express; let React escape, and avoid dangerouslySetInnerHTML with user HTML.
  • Treat installs as running code: --ignore-scripts, a committed lockfile, npm ci, npm audit --audit-level=high.
  • Limit reach with node --permission (a seat belt) or Deno's default-deny permissions.
  • Next episode: secrets management.

Sources (fetched 13 Nov 2026)

  • Node.js docs, Permissions: https://nodejs.org/api/permissions.html
  • Deno docs, Security and permissions: https://docs.deno.com/runtime/fundamentals/security
  • npm docs, npm audit: https://docs.npmjs.com/cli/v10/commands/npm-audit
  • npm registry metadata (npm view): helmet 8.3.0, zod 4.6.7, express 5.3.0, react / react-dom 19.3.1, lodash 4.18.1
  • GitHub advisories listed by npm audit for lodash (GHSA-35jh-r3h4-6jhm, GHSA-jf85-cpcp-j695, GHSA-p6mc-m468-83gw, GHSA-29mw-wpgm-hmr9, GHSA-r5fr-rjxr-66jc, GHSA-xxjr-mmjv-4gpg)