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

trpc-shield

v0.4.4

Published

tRPC permissions as another layer of abstraction!

Downloads

4,880

Readme

Contributors Forks Stargazers Issues MIT License

Overview

tRPC Shield helps you create a permission layer for your application. Using an intuitive rule-API, you'll gain the power of the shield engine on every request. This way you can make sure no internal data will be exposed.

Supported tRPC Versions

tRPC 10

  • 0.2.0 and higher

tRPC 9

  • 0.1.2 and lower

Installation

Using npm

npm install trpc-shield

Using yarn

yarn add trpc-shield

Usage

  • Don't forget to star this repo 😉
import * as trpc from '@trpc/server';
import { rule, shield, and, or, not } from 'trpc-shield';
import { Context } from '../../src/context';

// Rules

const isAuthenticated = rule<Context>()(async (ctx, type, path, input, rawInput) => {
  return ctx.user !== null
})

const isAdmin = rule<Context>()(async (ctx, type, path, input, rawInput) => {
  return ctx.user.role === 'admin'
})

const isEditor = rule<Context>()(async (ctx, type, path, input, rawInput) => {
  return ctx.user.role === 'editor'
})

// Permissions

const permissions = shield<Context>({
  query: {
    frontPage: not(isAuthenticated),
    fruits: and(isAuthenticated, or(isAdmin, isEditor)),
    customers: and(isAuthenticated, isAdmin),
  },
  mutation: {
    addFruitToBasket: isAuthenticated,
  },
});

export const t = trpc.initTRPC.context<Context>().create();

export const permissionsMiddleware = t.middleware(permissions);

export const shieldedProcedure = t.procedure.use(permissionsMiddleware);

For a fully working example, go here.

Documentation

Namespaced routers

export const permissions = shield<Context>({
  user: {
    query: {
      aggregateUser: allow,
      findFirstUser: allow,
      findManyUser: isAuthenticated,
      findUniqueUser: allow,
      groupByUser: allow,
    },
    mutation: {
      createOneUser: isAuthenticated,
      deleteManyUser: allow,
      deleteOneUser: allow,
      updateManyUser: allow,
      updateOneUser: allow,
      upsertOneUser: allow,
    },
  },
});

API

shield(rules?, options?)

Generates tRPC Middleware layer from your rules.

rules

All rules must be created using the rule function.

Limitations
  • All rules must have a distinct name. Usually, you won't have to care about this as all names are by default automatically generated to prevent such problems. In case your function needs additional variables from other parts of the code and is defined as a function, you'll set a specific name to your rule to avoid name generation.
// Normal
const admin = rule<Context>()(async (ctx, type, path, input, rawInput) => true)

// With external data
const admin = (bool) => rule<Context>(`name-${bool}`)(async (ctx, type, path, input, rawInput) => bool)

options

| Property | Required | Default | Description | | ------------------- | -------- | ------------------------ | -------------------------------------------------- | | allowExternalErrors | false | false | Toggle catching internal errors. | | debug | false | false | Toggle debug mode. | | fallbackRule | false | allow | The default rule for every "rule-undefined" field. | | fallbackError | false | Error('Not Authorised!') | Error Permission system fallbacks to. |

By default shield ensures no internal data is exposed to client if it was not meant to be. Therefore, all thrown errors during execution resolve in Not Authorised! error message if not otherwise specified using error wrapper. This can be turned off by setting allowExternalErrors option to true.

Basic rules

allow, deny are tRPC Shield predefined rules.

allow and deny rules do exactly what their names describe.

Logic Rules

and, or, not, chain, race

and, or and not allow you to nest rules in logic operations.

and rule

and rule allows access only if all sub rules used return true.

chain rule

chain rule allows you to chain the rules, meaning that rules won't be executed all at once, but one by one until one fails or all pass.

The left-most rule is executed first.

or rule

or rule allows access if at least one sub rule returns true and no rule throws an error.

race rule

race rule allows you to chain the rules so that execution stops once one of them returns true.

not

not works as usual not in code works.

You may also add a custom error message as the second parameter not(rule, error).

import { shield, rule, and, or } from 'trpc-shield'

const isAdmin = rule<Context>()(async (ctx, type, path, input, rawInput) => {
  return ctx.user.role === 'admin'
})

const isEditor = rule<Context>()(async (ctx, type, path, input, rawInput) => {
  return ctx.user.role === 'editor'
})

const isOwner = rule<Context>()(async (ctx, type, path, input, rawInput) => {
  return ctx.user.role === 'owner'
})

const permissions = shield<Context>({
  query: {
    users: or(isAdmin, isEditor),
  },
  mutation: {
    createBlogPost: or(isAdmin, and(isOwner, isEditor)),
  },
})

Global Fallback Error

tRPC Shield allows you to set a globally defined fallback error that is used instead of Not Authorised! default response. This might be particularly useful for localization. You can use string or even custom Error to define it.

const permissions = shield<Context>(
  {
    query: {
      items: allow,
    },
  },
  {
    fallbackError: 'To je napaka!', // meaning "This is a mistake" in Slovene.
  },
)

const permissions = shield<Context>(
  {
    query: {
      items: allow,
    },
  },
  {
    fallbackError: new CustomError('You are something special!'),
  },
)

Whitelisting vs Blacklisting

Shield allows you to lock-in access. This way, you can seamlessly develop and publish your work without worrying about exposing your data. To lock in your service simply set fallbackRule to deny like this;

const permissions = shield<Context>(
  {
    query: {
      users: allow,
    },
  },
  { fallbackRule: deny },
)

Contributors

This project exists thanks to all the people who contribute.

Contributing

We are always looking for people to help us grow trpc-shield! If you have an issue, feature request, or pull request, let us know!

Acknowledgments

A huge thank you goes to everybody who worked on Graphql Shield, as this project is based on it.

Also thanks goes to flaticon, for use of one of their icons in the logo: Shield icons created by Freepik - Flaticon