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

latchql

v1.0.7

Published

A one stop shop for securing a graphQL API with customizable secure authorization levels

Downloads

54

Readme

LatchQL NPM Package

An open-source, free-to-use, lightweight middleware package that adds additional layers of security to authenticate/authorize and provide permissions for users to have different levels of access to a database through graphQL queries.

Features

  • Enables users to customize depth, cost, and rate limiting for all GraphQL queries sent to the server.
  • Authorize and customize limiting for admin, users, and non-user levels.
  • Throw errors before execution using depth and cost limiting algorithms.
  • Utilize a caching method with Redis for limiting the rate of user requests to your GraphQL endpoint.

Why do I need GraphQL limiters?

Cost limiting

Cost limiting is essential for securing your GraphQL endpoint. By putting a limit on the cost of a single GraphQL transaction, you can prevent resource overload by blocking excessively expensive requests.

Depth limiting

Depth limiting is vital for protecting the server against malicious query attacks. This limit is commonly used for never ending query loops that expose the endpoint to potential attacks. By using the depth limiter, you can validate the depth of imcoming queries on a user's permission level and prevent execution if it exceeds the limit.

Rate limiting

Rate limiting is a strategy used for limiting network traffic and strain on the server. It's mainly used to prevent bot activity, brute force, DoS, DDoS, and web scraping attacks. By using the rate limiter, users are allocated a maximum of n operations for every fixed size 1-minute time window. Once the client has performed n operations, they must wait.

Getting started

In your terminal:

  1. Install LatchQL
npm install LatchQL
  1. Create a configuration file called latch_config.json in your project's root directory to assign and store your limiters.
    Example:
{
  "Admin": {
    "depthLimit": "100",
    "rateLimit": "100",
    "costLimit": "100"
  },
  "Gary": {
    "depthLimit": "10",
    "rateLimit": "25",
    "costLimit": "10"
  },
  "Non-User": {
    "depthLimit": "0",
    "rateLimit": "0",
    "costLimit": "0"
  }
}
  1. Create a .env file and save SECRET_KEY as an environment variable. *Note: if none is set, it will default to "GENERICKEY".
SECRET_KEY=MYSECRETKEY
  1. Install redis globally on your machine. For macOS users, use Homebrew package manager. If you've already installed redis, skip this step.
 brew update
 brew install redis
  1. Run redis server
redis-server
  • If you get an error on step 5, you may be running an instance of redis somewhere. To stop it:
killall redis-server

and then repeat step 5.

Implementation

Sample Usage

import cors from "cors";
import express from "express";
import { readFile } from "fs/promises";
import { resolvers } from "./test-db/resolvers.js";
import { LatchQL, jwtController } from "latchql";

const app = express();
const port = 8080; // default port to listen
app.use(cors());
app.use(express.json());

//helper middleware function for testing JwtController
function authSet(req, res, next) {
  res.locals.authLevel = "user";
  res.locals.userName = "Ray";
  next();
}

// test route for jwtController
app.post("/login", authSet, jwtController.setJwt, (req, res) => {
  return res.status(200).send("YES RESPONSE");
});

const typeDefs = await readFile("./schema.graphql", "utf-8");
let latch = new LatchQL(typeDefs, resolvers);

// start the Express server
app.listen(port, () => {
  console.log(`server started at http://localhost:${port}`);
  console.log(`GraphQL endpoint: http://localhost:${port}/graphql`);
});

latch.startLatch(app, port);

In your server file...

Import LatchQL and jwtController from latchql

import { LatchQL, jwtController } from "latchql";

Implment jwtController.setJwt middleware in your authentication step. You will need to pass the username and the selected authorization level of a given user to the jwtController.setJwt middleware via res.locals.username and res.locals.authLevel

app.post("/login", authSet, jwtController.setJwt, (req, res) => {
  return res.status(200).send("YES RESPONSE");
});

Create a new instance of LatchQL passing in your schema and resolvers

let latch = new LatchQL(typeDefs, resolvers);

Lastly, invoke startLatch passing in your express server and port to access endpoints

latch.startLatch(app, port);

Don't have a server?

Included in the NPM-MODULE directory is a dummy folder which includes an already built-out mock express server which you can use to test the LatchQL authentication and middleware package. Clone the repo, navigate to the dummy directory, install dependencies and run the command npm start to spin up the server.

LatchQL Playground

The LatchQL Playground is an optional, built-in playground for testing your GraphQL endpoint.

Features

  • Preview cost and depth of your current query before execution.
  • Displays important metrics for tracking response time and CPU usage.
  • Save variables to reference in the body of your GraphQL queries.

Getting Started

  1. Install LatchQL npm package.

  2. Clone the playground.

  3. Install its dependencies:

    npm install --force
  4. Build the playground:

    npm run dev

How to use LatchQL Playground

  1. Select the right permission level Permission Level

  2. Preview Cost/Depth of the current query Preview

  3. Depth Limiter Depth Limiter

  4. Cost Limiter Cost Limiter

  5. Rate Limiter Rate Limiter

Authors

Alex McPhail: GitHubLinkedIn
Celine Leung: GitHubLinkedIn
Hannah Bernstein: GitHubLinkedIn
Johnjered Tolentino: GitHub | LinkedIn
Raymond Kim: GitHub | LinkedIn

How to Contribute

If you would like to contribute in improving the functionality of LatchQL, please submit your ideas and/or bug fixes to our team by forking the repo and submitting your changes via a pull request.

Iteration Opportunities

  1. Storing history GraphQL queries
  2. Editing user's permission level on GUI
  3. Calculating cost and depth of query mutations

To Learn More

Visit the LatchQL Website Read the LatchQL Medium article

License

Distributed under the MIT License. See LICENSE for more information.