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 🙏

© 2026 – Pkg Stats / Ryan Hefner

the-api-roles

v1.1.2

Published

Roles for the-api

Readme

the-api-roles

Role and permission management for applications built with TheAPI.

the-api-roles helps you:

  • define role-to-permission mappings in one place
  • inherit permissions between roles
  • support wildcard permissions such as users.* or *
  • perform owner checks for record-level access
  • enforce permissions through middleware or manual checks

Installation

npm install the-api-roles

Core concepts

  • role: a named group of permissions, such as admin or registered
  • permission: a string such as users.get or posts.delete
  • owner check: a permission check that is granted when the current user owns the target object and the owner role contains the required permission

Quick start

import Roles from 'the-api-roles';

const roles = new Roles({
  root: ['*'],
  guest: ['auth.login'],
  registered: ['_.guest', 'profile.get'],
  admin: ['_.registered', 'users.*'],
  owner: ['posts.update', 'posts.delete'],
});

roles.append({
  editor: ['_.registered', 'posts.create', 'posts.update'],
  admin: ['posts.*'],
});

Role inheritance

Use the _.roleName syntax to inherit all permissions from another role:

const roles = new Roles({
  guest: ['auth.login'],
  registered: ['_.guest', 'profile.get'],
  admin: ['_.registered', 'users.*'],
});

In this example:

  • registered inherits auth.login
  • admin inherits everything from registered

Wildcard permissions

The package supports wildcard permissions:

  • users.*: any permission in the users namespace
  • *: any permission in the system

Example:

const roles = new Roles({
  admin: ['users.*'],
  root: ['*'],
});

Virtual roles

Two roles are typically handled dynamically:

  • guest: permissions for unauthenticated users
  • owner: permissions used during owner checks

The owner role is not expected to be present in user.roles. Owner access is determined by comparing:

  • user.userId
  • objectToCheck.userId by default, or another field defined via objectToCheckUserKey

Usage with TheAPI

// roles.ts
import Roles from 'the-api-roles';

const roles = new Roles({
  root: ['*'],
  guest: ['auth.login'],
  registered: ['_.guest', 'profile.get', 'posts.read'],
  admin: ['_.registered', 'users.*'],
  owner: ['posts.update', 'posts.delete'],
});

roles.append({
  editor: ['_.registered', 'posts.create', 'posts.update'],
});

export default roles;
// index.ts
import { Routings, TheAPI } from 'the-api';
import roles from './roles';

const router = new Routings();

router.get('/posts', roles.checkPermissionMiddleware('posts.read'));
router.post('/posts', roles.checkPermissionMiddleware('posts.create'));
router.delete('/posts/:id', roles.checkPermissionMiddleware('posts.delete', 'posts'));
router.patch('/posts/:postId', roles.checkPermissionMiddleware('posts.update', 'posts', 'postId'));

router.delete('/posts/:postId/comments/:id', async (c, next) => {
  await roles.checkPermission('posts.delete', {
    c,
    tableName: 'posts',
    idParamName: 'postId',
  });

  await next();
});

const theAPI = new TheAPI({ roles, routings: [router] }); // it will make roles.init() automatically

await theAPI.up();

API

new Roles(roleDefinitions)

Creates a new Roles instance and initializes role mappings.

const roles = new Roles({
  guest: ['auth.login'],
  registered: ['_.guest', 'profile.get'],
  admin: ['_.registered', 'users.*'],
  owner: ['posts.update', 'posts.delete'],
});

Arguments:

  • roleDefinitions: Record<string, string[]> - role names mapped to permission arrays

roles.init(roleDefinitions?)

Rebuilds the internal permission mapping. Inherited roles are resolved into final permission lookups.

Returns:

  • Record<string, Record<string, true>>

Example:

roles.init();

roles.append(newRoles)

Adds new roles or appends permissions to existing roles, then rebuilds the resolved mapping.

roles.append({
  admin: ['posts.*'],
  editor: ['_.registered', 'posts.create'],
});

Arguments:

  • newRoles: Record<string, string[]> - additional role definitions

roles.checkPermission(permission, options?)

Checks whether the current user has a permission either through:

  • one of the user's roles
  • a wildcard permission
  • an owner check through the owner role

Returns:

  • true when access is granted

Throws:

  • Error when access is denied
await roles.checkPermission('posts.delete', {
  user: c.var.user,
  objectToCheck: c.var.db('posts').where({ id: c.req.param().postId }).first(),
});

await roles.checkPermission('posts.update', {
  c,
  tableName: 'posts',
  idParamName: 'postId',
});

Arguments:

  • permission: string - required permission, for example posts.delete
  • options?: object

Options:

  • c - request context; if provided, user and db can be read from c.var
  • user - current user object; usually c.var.user
  • tableName - table used to load the target object for an owner check
  • idParamName - route parameter name containing the target record ID; defaults to id
  • objectToCheck - object or promise resolving to an object for the owner check
  • objectToCheckUserKey - owner field name in the target object; defaults to userId

roles.checkPermissionMiddleware(permission, tableName?, idParamName?)

Creates middleware that runs checkPermission() before calling next().

router.delete('/posts/:id', roles.checkPermissionMiddleware('posts.delete', 'posts'));
router.patch('/posts/:postId', roles.checkPermissionMiddleware('posts.update', 'posts', 'postId'));

Arguments:

  • permission: string - required permission
  • tableName?: string - table used for owner checks
  • idParamName?: string - route parameter name containing the record ID

roles.addRoutePermissions(routePermissions)

Adds route-level permission mappings used by roles.rolesMiddleware().

roles.addRoutePermissions({
  'GET /posts': ['posts.read'],
  'POST /posts': ['posts.create'],
});

roles.rolesMiddleware(c, next)

Checks permissions for matched routes added via addRoutePermissions().

Error handling

When access is denied, the package throws a regular Error:

try {
  await roles.checkPermission('posts.delete', { user: c.var.user });
} catch (error) {
  if (error instanceof Error) {
    console.error(error.message);
  }
}

Notes

  • owner is evaluated separately from user.roles
  • wildcard permission matching supports both exact matches and namespace matches such as posts.*
  • cyclic role inheritance throws an error during init()