Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

latchql

Package Overview
Dependencies
Maintainers
5
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

latchql

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

  • 1.0.7
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
12
increased by100%
Maintainers
5
Weekly downloads
 
Created
Source

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.

Keywords

FAQs

Package last updated on 10 Nov 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc