Web Attacks: XSS, CSRF, NoSQL Injection, Sanitisation and Brute Force

Node.js and Express: Build a Back End API from Scratch · Authentication and Security · 8 min read · Updated

Four attacks, four defences

  1. XSS: user text becomes code in the page. Escape it on the way out.
  2. CSRF: the browser sends cookies for you. A secret header the attacker cannot read stops it.
  3. Injection: query operators hide in the JSON. Check the types and remove $ keys.
  4. Brute force: many guesses. Hash slowly, limit requests and pause after repeated failures.

Attackers do not need to be clever to break most web apps. They try the same few well-known tricks on thousands of sites, and the sites that did not prepare lose. The good news is that the defence against each trick is also well known. This lesson explains four common attacks in plain words, shows a small defence for each, and tests every one. It is for defence only: the examples show how to stop attacks on your own code.

1. Cross-site scripting (XSS)

XSS happens when your site shows text that a user typed, and the browser treats it as code. If a comment contains a script tag and you place it into a page unchanged, the script runs in every visitor's browser, and it can steal sessions or perform actions as them. The defence is to escape output: turn the characters that have a special meaning in HTML, such as <, >, & and quotes, into harmless entities. Modern front-end frameworks such as React do this by default. The danger returns when you build HTML strings yourself, or when you use features with names like dangerouslySetInnerHTML or innerHTML. If you must show user HTML, clean it with a library such as DOMPurify.

2. Cross-site request forgery (CSRF)

CSRF works because browsers attach cookies automatically. If you are logged in to your bank in one tab and visit a bad page in another, the bad page can make your browser send a request to the bank, and the cookie goes along. The defences are: sameSite cookies, which already stop most cases, and a CSRF token. In the *double-submit cookie* method the server sets a random value in a cookie and requires the same value in a header. A page on another site can make the browser send the cookie, but it cannot read it, so it cannot copy it into the header. APIs that use an Authorization header with a token instead of cookies are not exposed to CSRF in the same way.

3. NoSQL injection

With MongoDB, an attacker does not need SQL. If your login code is User.findOne({ email: req.body.email, password: req.body.password }) and the client sends JSON such as {"email": "a@b.com", "password": {"$ne": null}}, the query asks for a user whose password is *not null*, and the check passes without knowing the password. The defence is to never pass raw input into a query. Validate the type, since an email must be a string, with Zod from lesson 26, and strip keys that start with $ or contain a dot.

4. Brute force

Automated tools can try thousands of passwords per minute. Defences are: a slow password hash, bcrypt or Argon2, which makes every guess expensive; rate limiting, such as the express-rate-limit package; and a lockout that counts failures per account and per address, and pauses further tries for a time. Be careful with lockouts: an attacker can lock out a real user on purpose, so a temporary pause is kinder than a permanent block.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express.
  3. Save the code as defences.js. The test needs npm install -D supertest.
import express from 'express';
import cookieParser from 'cookie-parser';
import crypto from 'node:crypto';

// 1. XSS: escape user text before it goes into HTML.
export const escapeHtml = (text) =>
  String(text).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);

// 2. NoSQL injection: a body like {"email": {"$ne": null}} would match every user in MongoDB.
//    Remove any key that starts with $ or contains a dot, at any depth.
export function stripOperators(value) {
  if (Array.isArray(value)) return value.map(stripOperators);
  if (value && typeof value === 'object') {
    return Object.fromEntries(
      Object.entries(value).filter(([key]) => !key.startsWith('$') && !key.includes('.')).map(([key, v]) => [key, stripOperators(v)]),
    );
  }
  return value;
}
export const sanitizeBody = (req, res, next) => { req.body = stripOperators(req.body); next(); };

// 3. CSRF (double-submit cookie): the page must copy the cookie value into a header.
//    A site on another domain can make the browser SEND the cookie but cannot READ it to copy it.
export function csrf() {
  return (req, res, next) => {
    if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
      if (!req.cookies.csrf) res.cookie('csrf', crypto.randomBytes(24).toString('hex'), { sameSite: 'strict' });
      return next();
    }
    const header = req.get('x-csrf-token');
    if (!header || header !== req.cookies.csrf) return res.status(403).json({ error: 'Bad CSRF token' });
    next();
  };
}

// 4. Brute force: count failed logins per account AND per IP, and lock for a while.
export function loginGuard({ maxFails = 5, lockMs = 15 * 60_000, now = () => Date.now() } = {}) {
  const fails = new Map();   // key -> { count, lockedUntil }
  return {
    isLocked(key) { const f = fails.get(key); return Boolean(f && f.lockedUntil > now()); },
    fail(key) {
      const f = fails.get(key) ?? { count: 0, lockedUntil: 0 };
      f.count += 1;
      if (f.count >= maxFails) { f.lockedUntil = now() + lockMs; f.count = 0; }
      fails.set(key, f);
    },
    success(key) { fails.delete(key); },
  };
}

export function createApp() {
  const app = express();
  app.use(express.json(), cookieParser(), sanitizeBody, csrf());
  app.get('/token', (req, res) => res.json({ ok: true }));
  app.post('/search', (req, res) => res.json({ received: req.body }));
  app.get('/greet', (req, res) => res.type('html').send(`<p>Hello ${escapeHtml(req.query.name ?? 'guest')}</p>`));
  return app;
}
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp, escapeHtml, stripOperators, loginGuard } from './sec31-defences.js';

// Test passwords are built at run time, so no password literal sits in the source.
const pw = (word) => [...word].reverse().join('') + '!9';

test('xss escaping', async () => {
  assert.equal(escapeHtml('<script>alert(1)</script>'), '&lt;script&gt;alert(1)&lt;/script&gt;');
  const res = await request(createApp()).get('/greet').query({ name: '<img src=x onerror=alert(1)>' });
  assert.ok(!res.text.includes('<img'));
});

test('operator injection is removed', () => {
  assert.deepEqual(stripOperators({ email: { $ne: null }, password: pw('x'), 'a.b': 1 }), { email: {}, password: pw('x') });
});

test('csrf double-submit cookie', async () => {
  const app = createApp();
  const agent = request.agent(app);
  const first = await agent.get('/token');                      // receives the csrf cookie
  const token = /csrf=([0-9a-f]+)/.exec(first.headers['set-cookie'][0])[1];
  assert.equal((await agent.post('/search').send({ q: 1 })).status, 403);   // cookie sent, header missing
  assert.equal((await agent.post('/search').set('x-csrf-token', token).send({ q: 1 })).status, 200);
  assert.equal((await request(app).post('/search').set('x-csrf-token', token).send({})).status, 403);   // other site: no cookie
});

test('brute force lock', () => {
  let time = 0;
  const guard = loginGuard({ maxFails: 3, lockMs: 1000, now: () => time });
  for (let i = 0; i < 3; i++) guard.fail('a@x.com');
  assert.equal(guard.isLocked('a@x.com'), true);
  time = 1001;
  assert.equal(guard.isLocked('a@x.com'), false);
});
ok 1 - xss escaping
ok 2 - operator injection is removed
ok 3 - csrf double-submit cookie
ok 4 - brute force lock

In the CSRF test, three requests are made. One carries the cookie but not the header, and gets 403. One carries both, and passes. One comes from a client that has no cookie, as a hostile site would, and gets 403. The brute-force test makes five failures, sees the lock, and then moves the fake clock past the lock time to see the account unlock.

  • Escape output, and validate input.
  • Never put raw request data into a database query.
  • Use sameSite cookies and a CSRF token wherever cookies authenticate.
  • Slow down and limit login attempts.

Your task

  1. Write a test that sends a body with { "$gt": "" } as a password and confirm that it is cleaned.
  2. Add express-rate-limit to the login route, five attempts per 15 minutes.
  3. Try printing user text into an HTML string without escaping, and then fix it.

How to check it worked

  • All four tests pass.
  • You can describe each attack in one sentence.
  • You can say why a CSRF token cannot be copied by another site.

Frequently asked questions

Does React protect me from XSS?

It escapes text by default. You are exposed again if you use dangerouslySetInnerHTML or build HTML strings yourself.

Do I need CSRF protection for a token API?

If authentication uses an Authorization header that the browser does not attach by itself, CSRF is not the same problem. If it uses cookies, yes.

Is MongoDB safe from injection?

Not automatically. Raw request data in a query can carry operators such as $ne, so validate types and strip operator keys.

Practise with interview questions