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

@geexbox/accesscontrol

v2.3.13

Published

Subject and Attribute based Access Control for Node.js

Downloads

14

Readme

This is an unofficial fork of AccessControl

Subject and Attribute based Access Control for Node.js

Many RBAC (Subject-Based Access Control) implementations differ, but the basics is widely adopted since it simulates real life subject (job) assignments. But while data is getting more and more complex; you need to define policies on resources, subjects or even environments. This is called ABAC (Attribute-Based Access Control).

With the idea of merging the best features of the two (see this NIST paper); this library implements RBAC basics and also focuses on resource and action attributes.

Core Features

  • Chainable, friendly API.
    e.g. ac.can(subject).create(resource)
  • Subject hierarchical inheritance.
  • Define grants at once (e.g. from database result) or one by one.
  • Grant/deny permissions by attributes defined by glob notation (with nested object support).
  • Ability to filter data (model) instance by allowed attributes.
  • Ability to control access on own or any resources.
  • Ability to lock underlying grants model.
  • No silent errors.
  • Fast. (Grants are stored in memory, no database queries.)
  • Brutally tested.
  • TypeScript support.

In order to build on more solid foundations, this library (v1.5.0+) is completely re-written in TypeScript.

Installation

with npm: npm i accesscontrol --save
with yarn: yarn add accesscontrol

Guide

const AccessControl = require('accesscontrol');
// or:
// import { AccessControl } from 'accesscontrol';

Basic Example

Define subjects and grants one by one.

const ac = new AccessControl();
ac.grant('user')                    // define new or modify existing subject. also takes an array.
    .createOwn('video')             // equivalent to .createOwn('video', ['*'])
    .deleteOwn('video')
    .readAny('video')
  .grant('admin')                   // switch to another subject without breaking the chain
    .extend('user')                 // inherit subject capabilities. also takes an array
    .updateAny('video', ['title'])  // explicitly defined attributes
    .deleteAny('video');

const permission = ac.can('user').createOwn('video');
console.log(permission.granted);    // —> true
console.log(permission.attributes); // —> ['*'] (all attributes)

permission = ac.can('admin').updateAny('video');
console.log(permission.granted);    // —> true
console.log(permission.attributes); // —> ['title']

Express.js Example

Check subject permissions for the requested resource and action, if granted; respond with filtered attributes.

const ac = new AccessControl(grants);
// ...
router.get('/videos/:title', function (req, res, next) {
    const permission = ac.can(req.user.subject).readAny('video');
    if (permission.granted) {
        Video.find(req.params.title, function (err, data) {
            if (err || !data) return res.status(404).end();
            // filter data by permission attributes and send.
            res.json(permission.filter(data));
        });
    } else {
        // resource is forbidden for this user/subject
        res.status(403).end();
    }
});

Subjects

You can create/define subjects simply by calling .grant(<subject>) or .deny(<subject>) methods on an AccessControl instance.

  • Subjects can extend other subjects.
// user subject inherits viewer subject permissions
ac.grant('user').extend('viewer');
// admin subject inherits both user and editor subject permissions
ac.grant('admin').extend(['user', 'editor']);
// both admin and superadmin subjects inherit moderator permissions
ac.grant(['admin', 'superadmin']).extend('moderator');
  • Inheritance is done by reference, so you can grant resource permissions before or after extending a subject.
// case #1
ac.grant('admin').extend('user') // assuming user subject already exists
  .grant('user').createOwn('video');

// case #2
ac.grant('user').createOwn('video')
  .grant('admin').extend('user');

// below results the same for both cases
const permission = ac.can('admin').createOwn('video');
console.log(permission.granted); // true

Notes on inheritance:

  • A subject cannot extend itself.
  • Cross-inheritance is not allowed.
    e.g. ac.grant('user').extend('admin').grant('admin').extend('user') will throw.
  • A subject cannot (pre)extend a non-existing subject. In other words, you should first create the base subject. e.g. ac.grant('baseRole').grant('subject').extend('baseRole')

Actions and Action-Attributes

CRUD operations are the actions you can perform on a resource. There are two action-attributes which define the possession of the resource: own and any.

For example, an admin subject can create, read, update or delete (CRUD) any account resource. But a user subject might only read or update its own account resource.

ac.grant('subject').readOwn('resource');
ac.deny('subject').deleteAny('resource');

Note that own requires you to also check for the actual possession. See this for more.

Resources and Resource-Attributes

Multiple subjects can have access to a specific resource. But depending on the context, you may need to limit the contents of the resource for specific subjects.

This is possible by resource attributes. You can use Glob notation to define allowed or denied attributes.

For example, we have a video resource that has the following attributes: id, title and runtime. All attributes of any video resource can be read by an admin subject:

ac.grant('admin').readAny('video', ['*']);
// equivalent to:
// ac.grant('admin').readAny('video');

But the id attribute should not be read by a user subject.

ac.grant('user').readOwn('video', ['*', '!id']);
// equivalent to:
// ac.grant('user').readOwn('video', ['title', 'runtime']);

You can also use nested objects (attributes).

ac.grant('user').readOwn('account', ['*', '!record.id']);

Checking Permissions and Filtering Attributes

You can call .can(<subject>).<action>(<resource>) on an AccessControl instance to check for granted permissions for a specific resource and action.

const permission = ac.can('user').readOwn('account');
permission.granted;       // true
permission.attributes;    // ['*', '!record.id']
permission.filter(data);  // filtered data (without record.id)

See express.js example.

Defining All Grants at Once

You can pass the grants directly to the AccessControl constructor. It accepts either an Object:

// This is actually how the grants are maintained internally.
let grantsObject = {
    admin: {
        video: {
            'create:any': ['*', '!views'],
            'read:any': ['*'],
            'update:any': ['*', '!views'],
            'delete:any': ['*']
        }
    },
    user: {
        video: {
            'create:own': ['*', '!rating', '!views'],
            'read:own': ['*'],
            'update:own': ['*', '!rating', '!views'],
            'delete:own': ['*']
        }
    }
};
const ac = new AccessControl(grantsObject);

... or an Array (useful when fetched from a database):

// grant list fetched from DB (to be converted to a valid grants object, internally)
let grantList = [
    { subject: 'admin', resource: 'video', action: 'create:any', attributes: '*, !views' },
    { subject: 'admin', resource: 'video', action: 'read:any', attributes: '*' },
    { subject: 'admin', resource: 'video', action: 'update:any', attributes: '*, !views' },
    { subject: 'admin', resource: 'video', action: 'delete:any', attributes: '*' },

    { subject: 'user', resource: 'video', action: 'create:own', attributes: '*, !rating, !views' },
    { subject: 'user', resource: 'video', action: 'read:any', attributes: '*' },
    { subject: 'user', resource: 'video', action: 'update:own', attributes: '*, !rating, !views' },
    { subject: 'user', resource: 'video', action: 'delete:own', attributes: '*' }
];
const ac = new AccessControl(grantList);

You can set grants any time...

const ac = new AccessControl();
ac.setGrants(grantsObject);
console.log(ac.getGrants());

...unless you lock it:

ac.lock().setGrants({}); // throws after locked

Documentation

You can read the full API reference with lots of details, features and examples.
And more at the F.A.Q. section.

Change-Log

See CHANGELOG.

Contributing

Clone original project:

git clone https://github.com/onury/accesscontrol.git

Install dependencies:

npm install

Add tests to relevant file under /test directory and run:

npm run build && npm run cover

Use included tslint.json and editorconfig for style and linting.
Travis build should pass, coverage should not degrade.

License

MIT.