# the-api-roles

> Roles for the-api

Latest version **1.1.2** (published 2026-03-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install the-api-roles
pnpm add the-api-roles
yarn add the-api-roles
bun add the-api-roles
```

## Health

**Score 60/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 1.1.2 |
| Published | 2026-03-17 |
| First published | 2024-06-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 28.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Dimitry Ivanov |
| Maintainers | ivanoff |
| Keywords | the-api, roles |

## Links

- npm: https://www.npmjs.com/package/the-api-roles
- Repository: https://github.com/the-api/the-api-roles
- Homepage: https://github.com/the-api/the-api-roles#readme
- Issues: https://github.com/the-api/the-api-roles/issues
- npm.io page: https://npm.io/package/the-api-roles

## Recent versions

- 1.1.2 (latest) — 2026-03-17
- 1.1.1 — 2026-03-12
- 0.1.8 — 2026-03-04
- 0.1.7 — 2026-03-04
- 0.1.6 — 2026-03-04
- 0.1.5 — 2026-03-04
- 0.1.4 — 2026-03-04
- 0.1.3 — 2026-03-04
- 0.1.2 — 2026-03-04
- 0.1.1 — 2024-06-25
- 0.0.1 — 2024-06-25

## 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

```bash
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

```typescript
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:

```typescript
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:

```typescript
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

```typescript
// 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;
```

```typescript
// 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.

```typescript
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:

```typescript
roles.init();
```

### `roles.append(newRoles)`

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

```typescript
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

```typescript
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()`.

```typescript
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()`.

```typescript
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`:

```typescript
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()`

---
_Source: https://npm.io/package/the-api-roles · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
