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

cascade-permissions

v1.2.1

Published

### Description

Downloads

3

Readme

Cascade-Permissions

Description

This package addresses the burden of managing multiple types of users with different, or at times, overlapping permissions.

Scaling

While working on an MVP application with role-based users that were:

  1. restricted from viewing a particular type of data
  2. restricted from viewing a property / properties on an authorized data.

We ran into issues scaling to other business-units as the legacy code base used conditionals which I named "multiple conditional hell"

Multiple-Conditional-Hell Example
Assume this object represents the relevant data
const dataFromStore = {
  username: 'someName',
  message: 'some message',
  chat_room: 'some chat room topic',
  creation_date: '2018-08-09',
  modified_data: '2018-08-10',
};
1. Started with an innucous conditional authorizing the "power_user" role users
// Using an ES6-Promise
return getUser(id).then(user => {
  if (user.role === 'power_user') {
    return dataFromStore;
  } else {
    return Promise.reject(user);
  }
});
2. As the application grew, the use-cases expanded
return getUser(id).then(user => {
  if (user.role === 'power_user' || user.seniority === 'senior') {
    return dataFromStore;
  } else {
    return Promise.reject(user);
  }
});
3. Expanded some more
return getUser(id).then(user => {
  if (user.role === 'power_user' || user.seniority === 'senior' || (user.role === 'basic_user' && user.associations.includes('permitted_data'))) {
    return dataFromStore;
  } else {
    return Promise.reject(user);
  }
});
4. When we moved out of the MVP phase, we encountered the problem that an authorized user required a subset of the permissions.
return getUser(id).then(user => {
  if (user.role === 'power_user' || user.seniority === 'senior' || (user.role === 'basic_user' && user.associations.includes('permitted_data'))) {
    if (user.role === 'basic_user' && user.associations.includes('permitted_data')) {
      // have to remove data the user is not authorized to see.
      delete dataFromStore.creation_date;
    }
    return dataFromStore;
  } else {
    return Promise.reject(user);
  }
});

Package Details

Using the Javascript's native prototype-chain and an "exclusion" list approach, role-based permissions become inheritable and therefore, may be cascaded across different groups / subgroups.

  1. Inheritable permissions
  • rules changes in the parent is dynamically reflected in the child.
  1. Restrictinng data access Using ES6-proxies (sorry IE users) and the user's runtime permissions:
  • accessing a restricted property will return undefined
  • setting a restricted property will result in an authorization error
  • Still a Proof-of-concept,
  • Limited to shallow objects (1 layer deep)

Installation

npm i cascade-permissions

Step 1: Basic Definitions

Define the properties that represents your application's data shape.

The example creates two domains, "roles" and "types"
// assume there are just three roles, "Admin", "Basic", "Moderator"

// the "values" can be any thing in this POC.
export default function Admin() {
return {
  authorized_date: '2018-01-30',
  id: 10,
  last_active_date: '2018-08-10',
  username: 'admin.doe',
};
}
export default function Basic() {
return {
  id: 7,
  last_active_date: '2018-08-01',
  signup_date: '2018-07-25',
  username: 'basic.doe',
};
}
export default function Moderator() {
return {
  authorized_date: '2018-07-23',
  id: 6,
  last_active_date: '2018-08-16',
  signup_date: '2018-03-20',
  username: 'moderator.doe',
};
}
Define Types (of data)
// assume there are just three types, "Account", "Message", "Transaction"

// the values "true" can be any thing in this POC.
// account.js
export default function Account() {
return {
  first_name: true,
  id: true,
  last_name: true,
  last_active_date: true,
  signup_date: true,
  username: true,
};
}
// message.js
export default function Message() {
return {
  account_id: true,
  date: true,
  forum: true,
  id: true,
  message: true,
  modified_date: true,
  receiver_username: true,
};
}
// transaction.js
export default function Transaction() {
return {
  account_id: true,
  date: true,
  id: true,
  invoice_amount: true,
  product: true,
  purchase_amount: true,
  purchase_method: true,
  repeated_purchase: true,
  tax_amount: true,
};
}

Step 2: Create Domain Rules

Create the rules-specific to a domain (ie. rules for the "Roles")

Invert the definition of an "admin" role to the keys that do not represent an "admin" role based of the dictionary (hence "exclusion-list").

Exclusion-list formula is [uniqueKeys] - [typeDefinitionKeys] = typeExclusionKeys

const Roles = {
  authorized_date: true,
  id: true,
  last_active_date: true,
  signup_date: true,
  username: true,
  [Symbol('admin')]: [
    /* adminExclusionList */
  ],
  [Symbol('basic')]: [
    /* basicExclusionList */
  ],
  [Symbol('moderator')]: [
    /* moderatorExclusionList */
  ],
};

Create Domain Rules: Implementation Options

Provide the definitions as an object to the CreateDomain and call the createRules helper method

import { helper } from 'cascade-permissions';

const { CreateDomain } = helper;

// application-defined types
import admin from './admin';
import basic from './basic';
import moderator from './moderator';
const allRoles = CreateDomain({
  admin,
  basic,
  moderator,
});

const Roles = AllRoles.createRules('roles');
import { helper } from 'cascade-permissions';

const { CreateDomain } = helper;

// application-defined types
import account from './account';
import message from './message';
import transaction from './transaction';
const allTypes = CreateDomain({
  account,
  **message**,
  transaction,
});

const Types = AllTypes.createRules('types');
A. Create a dictionary / unique list of keys for a domain
this is a naive method that works only for shallow objects.
// using the roles already created above
import account from '../someDirectory/account';
import message from '../someDirectory/message';
import transaction from '../someDirectory/transaction';

const allTypes = Object.assign({}, account(), message(), transaction());
// using the roles already created above
import admin from '../someDirectory/admin';
import basic from '../someDirectory/basic';
import moderator from '../someDirectory/moderator';

const allRoles = Object.assign({}, admin(), basic(), moderataor());
B. Define each type based on an "exclusion list" of keys.
The exclusion list formula is [uniqueKeys] - [typeDefinitionKeys] = typeExclusionKeys
For example, to define an admin data object
const adminObj = {
  first_name: 'someFirstName',
  last_name: 'someLastName',
  username: 'someUsername',
};
const messageObj = {
  message: 'some text written here',
  username: 'someUserName',
  createdDate: '2018-01-01',
  modifiedDate: '2018-01-03',
};
const allRolesKeys = ['createdDate', 'first_name', 'last_name', 'message', 'modifiedDate', 'username'];
const adminExclusionKeys = allRolesKeys.filter(item => !Object.keys(adminObj).includes(item)); // ['createdDate', 'message', 'modifiedDate'];
C. Create domain-rules object via "BaseFactory"
import { appSymbols, BaseFactory } from 'cascade-permissions';
const { _defineType } = appSymbols;

const allRolesDictionary = {
// list of unique key + arbitrary values
};
const adminExclusionKeys = [// uniqueKeys that do not represent an admin]
const basicExclusionKeys = [// uniqueKeys that do not represent an basic]
const moderatorExclusionKeys = [// uniqueKeys that do not represent an moderator]

// this return an object that includes a _defineType method;
const Roles = BaseFactory('roles', {}, allRolesDictionary);
Roles[_defineType]('admin', {
restrictedKeys: adminExclusionKeys,
restrictedTypes: ['basic','moderator']
})

Roles[_defineType]('basic', {
restrictedKeys: basicExclusionKeys,
restrictedTypes: ['admin','moderator']
})

Roles[_defineType]('moderator', {
restrictedKeys: moderatorExclusionKeys,
restrictedTypes: ['admin','basic']
})
import { appSymbols, BaseFactory } from 'cascade-permissions';
const { _defineType } = appSymbols;

const allTypesDictionary = {
// list of unique key + arbitrary values
};
const accountExclusionKeys = [// uniqueKeys that do not represent an account]
const messageExclusionKeys = [// uniqueKeys that do not represent an message]
const transactionExclusionKeys = [// uniqueKeys that do not represent an transaction]

// this return an object that includes a _defineType method;
const Types = BaseFactory('types', {}, allTypesDictionary);
Types[_defineType]('account', {
restrictedKeys: accountExclusionKeys,
restrictedTypes: ['message','transaction']
})

Types[_defineType]('message', {
restrictedKeys: messageExclusionKeys,
restrictedTypes: ['account','transaction']
})

Types[_defineType]('transaction', {
restrictedKeys: transactionExclusionKeys,
restrictedTypes: ['account','message']
})

Step 3: Inherit Domain Rules

The fun part begins. How do you inherit these rules for your application?

Example assumes application has 2 groups of users "internal" and "external".
import { appSymbols, BaseFactory, helper } from 'cascade-permissions';

// assume allRoles is defined as we did earlier
const Roles = allRoles().createRules('rules');
// assume allTypes is defined as we did earlier
const Types = allTypes().createRules('types');

// create a Groups object
const Groups = BaseFactory(
  'groups',
  {},
  {
    [Symbol('roles')]: Roles,
    [Symbol('types')]: Types,
  }
);

Scenarios

Situation: "internal" users have zero restrictions
Groups[_inherit]('internal', {
  restrictedTypes: ['external'],
});

The interal user will have all "roles" and all "types"

Situation: "external" users are restricted from "admin" role and "transaction" type
Groups[_inherit]('internal', {
  restrictedTypes: ['internal', 'admin', 'transaction'],
});

The external user will have all "roles" except the "admin" role, and all "types" except the "transaction" types.

Situation: "external" users are restricted from "admin" role and "transaction" type. In addition, the "id" property is not authorized any domains.

Groups[_inherit]('internal', {
  restrictedKeys: ['id'],
  restrictedTypes: ['internal', 'admin', 'transaction'],
});

The external user will have all "roles" except the "admin" role, and all "types" except the "transaction" types. In addition, any domain types with an "id" property is not visible to the user.

Situation: "external" users are restricted from "admin" role and "transaction" type. In addition, the "account" type ['first_name', 'last_name'] and "basic" role ['last_active_date'] are not authorized.

Groups[_inherit]('internal', {
  restrictedKeys: {
    account: ['first_name', 'last_name'],
    basic: ['last_active_date'],
  },
  restrictedTypes: ['internal', 'admin', 'transaction'],
});

The external user will have all "roles" except the "admin" role, and all "types" except the "transaction" types. In addition, the "basic" role's "last_active_date" and the "account" type's "first_name" & "last_name" are not visible.

Situation: Scenario of above step + there is a name conflict. In both the roles and types domain, there is a "workspace" domain type and external user is authorized only for the "types" domain.

Groups[_inherit]('internal', {
  restrictedKeys: {
    account: ['first_name', 'last_name'],
    basic: ['last_active_date'],
  },
  restrictedTypes: ['internal', { [Symbol('types')]: ['transaction'] }, { [Symbol('roles')]: ['admin', 'workspace'] }],
});

The external user will have all "roles" except the "admin" and "workspace" role, and all "types" except the "transaction" types. In addition, the "basic" role's "last_active_date" and the "account" type's "first_name" & "last_name" are not visible.

Step 4. Wrapping Application Data with the TypeWrapper

Situation: Assume an interal user is restricted the "basic" role's "last_active_date" and receives data representing another user's "basic" data.

import { helper } from 'cascade-permissions';

const { TypeWrapper } = helper;

const someUsersBasicData = {
  id: 1023,
  last_active_date: '2018-01-18',
  signup_date: '2017-10-14',
  username: 'john.doe',
};

//assume the Roles and Types is already defined;
const Groups = BaseFactory(
  'groups',
  {},
  {
    [Symbol('roles')]: Roles,
    [Symbol('types')]: Types,
  }
);
Groups[_inherit]('internal', {
  restrictedKeys: {
    account: ['first_name', 'last_name'],
    basic: ['last_active_date'],
  },
  restrictedTypes: ['internal', 'admin', 'transaction'],
});
const wrappedData = TypeWrapper(Groups, 'roles')('internal', 'basic', someUsersBasicData);

wrapperData.id; // 1023
wrappedData.last_active_date; // undefined
wrappedData.last_active_date = Date(); // the key "last_active_date" is restricted and cannot be set