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 🙏

© 2024 – Pkg Stats / Ryan Hefner

owasp

v1.2.0

Published

This package is intended to assist developers to follow OWASP best practices.

Downloads

212

Readme

OWASP

This package is intended to assist developers to follow OWASP best practices.

Currently, it implements the OWASP Cheat Sheet for Application Logging Vocabulary, a standard vocabulary for logging security events.

The intent is to simplify monitoring and alerting such that, assuming developers trap errors and log them using this vocabulary, monitoring and alerting would be improved by simply keying on these terms.

This logging standard would seek to define specific keywords which, when applied consistently across software, would allow groups to simply monitor for these events terms across all applications and respond quickly in the event of an attack.

Installation

npm install owasp
# yarn add owasp
# pnpm install owasp
# bun install owasp

Usage

Logging vocabulary

Here is an example of how to use this package with pino and Express to log authentication events.

Authentication is a complex topic and this example is not intended to be used in production. Use this as a baseline for how to use this package to log authentication events.

You can use any logger you want! This package simply provides a set of standard events to log.

import { Router } from "express";
// Alternatively,
// import * as vocab from 'owasp/vocab';
import {
  authn_login_fail,
  authn_login_fail_max,
  authn_login_success,
} from "owasp/vocab";
import { logger as rootLogger } from "../logger.js";

const router = Router();

const MAX_FAILED_LOGIN_ATTEMPTS = 5;

router.route("/login").post(async (req, res, next) => {
  try {
    const { userId, password } = req.body;

    // Create a child logger to automatically include context in all logs
    // Note, `requestId` is a custom property that is added to the request
    // object by a middleware.
    const logger = rootLogger.child({ userId, requestId: req.requestId });

    if (!userId || !password || userId.length === 0 || password.length === 0) {
      logger.warn(
        {
          // owasp-helpers provides a set of standard events to log.
          // Use the `event` property to log the event.
          // The result of this function is: `authn_login_fail:${userId}`
          event: authn_login_fail(userId),
        },
        `User ${userId} login failed because username or password was not provided`
      );
      return res.status(401).send("Invalid username or password.");
    }

    const user = await getUserById(userId);

    if (!user) {
      logger.warn(
        {
          event: authn_login_fail(userId),
        },
        `User ${user} login failed because user does not exist`
      );
      return res.status(401).send("Invalid username or password.");
    }
    if (!checkPassword(user.password, password)) {
      user.failedLoginAttempts++;

      if (
        user.failedLoginAttempts >= MAX_FAILED_LOGIN_ATTEMPTS &&
        user.lastFailedLoginAttempt > Date.now() - 5 * 60 * 1000
      ) {
        logger.warn(
          {
            event: authn_login_fail_max(userId, MAX_FAILED_LOGIN_ATTEMPTS),
          },
          `User ${userId} reached the login fail limit of ${MAX_FAILED_LOGIN_ATTEMPTS}`
        );
        const lockReason = "maxretries";
        logger.warn(
          {
            event: authn_login_lock(userId, lockReason),
          },
          `User ${userId} login locked because ${lockReason} exceeded`
        );
        user.locked = true;
        await user.save();
        return res.status(429).send(
          `You have reached the login fail limit of ${MAX_FAILED_LOGIN_ATTEMPTS} attempts.\
                        Please wait 5 minutes and try again.`
        );
      }
      logger.warn(
        {
          event: authn_login_fail(userId),
        },
        `User ${user} login failed`
      );
      await user.save();
      return res.status(401).send("Invalid username or password.");
    }
    if (user.locked) {
      logger.warn(
        {
          event: authn_login_fail(userId),
        },
        `User ${userId} login failed because user is locked`
      );
      return res.status(401).send("Account is locked. Please contact support.");
    }

    if (user.failedLoginAttempts > 0) {
      logger.info(
        {
          event: authn_login_successafterfail(userId, user.failedLoginAttempts),
        },
        `User ${userId} login successfully`
      );
    } else {
      logger.info(
        {
          event: authn_login_success(userId),
        },
        `User ${userId} login successfully`
      );
    }

    user.failedLoginAttempts = 0;
    await user.save();

    res.cookie("session", createSession(user));

    const userResponse = toUserResponse(user);

    return res.status(200).send(userResponse);
  } catch (err) {
    next(err);
  }
});

export default router;

[!IMPORTANT]
Logging events is not enough to secure your application. You should also monitor these events and take action when necessary. We have provided some example implementations using popular logging and alerting tools.

DOM Utilities

This package also provides a set of DOM utilities to help increase security.

import { openPopup } from "owasp/dom";

function onClick() {
  // Applies the following attributes to the window:
  // * - `'noopener'`: Prevents the new window from having access to the originating window via `Window.opener`.
  // * - `'noreferrer'`: Omits the `Referer` header and sets `noopener` to true.
  // Subsequently, it resets the `opener` property of the new window to `null`.
  // This prevents the new window from being able to navigate the originating window.
  openPopup("https://example.com", "Window name", "width=200,height=200");
}

Contributing

Contributions are welcome!

bun install

Ensure linting, formatting, and tests pass before submitting a PR.

bun run check
bun test # let's keep the test coverage at 100%!