EXERCISE 1 — An Origin/Referer check middleware in Express ========================================================== const ALLOWED_ORIGINS = ["https://app.example.com"]; function checkOrigin(req, res, next) { // Only guard state-changing methods; safe methods (GET/HEAD) shouldn't // change state anyway. if (["GET", "HEAD", "OPTIONS"].includes(req.method)) return next(); const origin = req.get("Origin"); const referer = req.get("Referer"); let source = origin; if (!source && referer) { try { source = new URL(referer).origin; } catch { source = null; } } // Strict, EXACT-origin allowlist match (never substring/startsWith on the // raw header -- "https://app.example.com.evil.com" would slip past that). if (!source || !ALLOWED_ORIGINS.includes(source)) { return res.status(403).send("Cross-origin request rejected."); } next(); } app.post("/transfer", checkOrigin, /* ...csrf token check... */ handler); WHY IT MUST NOT BE THE ONLY CSRF DEFENCE: Reason 1 -- header absence / unreliability. - The Origin header is present on most state-changing cross-site requests today, but not guaranteed on every request shape historically, and Referer can be STRIPPED by the user's privacy settings, a corporate proxy, or the site's own Referrer-Policy. - That forces a bad choice: "reject if the header is absent" can break legitimate clients (false positives); "allow if absent" leaves a hole an attacker can aim for (suppress the header -> bypass). Neither is airtight, so it can't stand alone. Reason 2 -- the same-site sibling gap. - The check only distinguishes CROSS-SITE/cross-origin from your origin. A request from a sibling subdomain (blog.example.com) or any host you mistakenly allowlist is treated as acceptable, yet a compromised/XSS'd subdomain can forge from there. Origin checking does nothing about same-site attackers (the Chapter 7 site-vs-origin issue). CONCLUSION: Use exact-match Origin/Referer checking as a strong CORROBORATING layer on top of SameSite + anti-CSRF tokens, not as the sole mechanism. Match an explicit allowlist by exact origin string.