npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@mahdi.golzar/csrfguard

v1.0.0

Published

csrfGuard

Readme

CSRFGuard

CSRFGuard is a simple tool for preventing Cross-Site Request Forgery (CSRF) attacks. It uses Node.js and built-in modules to generate and verify CSRF tokens, protecting web applications from CSRF attacks.

Features

  • Generates unique CSRF tokens
  • Simple session management
  • CSRF token verification
  • Dynamic implementation with the ability to add new routes and handlers

Installation

This project does not require any external dependencies and only requires Node.js to be installed on your system.

Usage

  1. Copy the Code First, save the following code in a file named server.js:
const http = require('http');
const crypto = require('crypto');
const { parse } = require('querystring');

class CSRFGuard {
    constructor() {
        this.sessions = new Map(); // Simple in-memory session store
        this.routes = {}; // Object to hold route handlers
        this.initRoutes();
    }

    generateCSRFToken() {
        return crypto.randomBytes(32).toString('hex');
    }

    createSession() {
        const sessionId = crypto.randomBytes(16).toString('hex');
        const csrfToken = this.generateCSRFToken();
        this.sessions.set(sessionId, { csrfToken });
        return { sessionId, csrfToken };
    }

    validateCSRFToken(sessionId, token) {
        const session = this.sessions.get(sessionId);
        return session && token === session.csrfToken;
    }

    initRoutes() {
        // Define route handlers
        this.routes['GET /'] = (req, res) => {
            const { sessionId, csrfToken } = this.createSession();
            res.writeHead(200, {
                'Content-Type': 'text/html',
                'Set-Cookie': `session=${sessionId}`
            });
            res.end(`
                <form action="/submit" method="POST">
                    <input type="hidden" name="_csrf" value="${csrfToken}">
                    <input type="text" name="example" placeholder="Enter something">
                    <button type="submit">Submit</button>
                </form>
            `);
        };

        this.routes['POST /submit'] = (req, res) => {
            req.on('data', chunk => {
                const body = parse(chunk.toString());
                const sessionId = req.headers.cookie?.split('=')[1];

                if (this.validateCSRFToken(sessionId, body._csrf)) {
                    res.writeHead(200, { 'Content-Type': 'text/plain' });
                    res.end('Form submitted successfully');
                } else {
                    res.writeHead(403, { 'Content-Type': 'text/plain' });
                    res.end('Invalid CSRF Token');
                }
            });
        };
    }

    handleRequest(req, res) {
        const url = new URL(req.url, `http://${req.headers.host}`);
        const method = req.method;
        const routeKey = `${method} ${url.pathname}`;

        const handler = this.routes[routeKey];
        if (handler) {
            handler(req, res);
        } else {
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.end('Not Found');
        }
    }

    startServer(port) {
        const server = http.createServer(this.handleRequest.bind(this));
        server.listen(port, () => {
            console.log(`Server running at http://localhost:${port}`);
        });
    }
}
// Usage
const csrfGuard = new CSRFGuard();
csrfGuard.startServer(3000);
  1. Run the Server To start the server, run the following command in your terminal:
node server.js
The server will run on port 3000, and you can access it in your browser at http://localhost:3000.
  1. Adding New Routes To add new routes and handlers, modify the initRoutes method in the CSRFGuard class. Simply add new routes and their corresponding handlers to the routes object.

  2. Method Descriptions generateCSRFToken(): Generates a unique CSRF token. createSession(): Creates a new session and generates a CSRF token. validateCSRFToken(sessionId, token): Validates the CSRF token. initRoutes(): Defines routes and their handlers. handleRequest(req, res): Processes incoming requests and routes them to the appropriate handler. startServer(port): Starts the HTTP server on the specified por