New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details โ†’ โ†’
Socket
Book a DemoSign in
Socket

@builtwithjavascript/permissions

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@builtwithjavascript/permissions - npm Package Compare versions

Comparing version
1.0.3
to
1.0.7
+32
-32
dist/permissions.es.js

@@ -1,5 +0,5 @@

var p = Object.defineProperty;
var d = (t, s, e) => s in t ? p(t, s, { enumerable: !0, configurable: !0, writable: !0, value: e }) : t[s] = e;
var c = (t, s, e) => d(t, typeof s != "symbol" ? s + "" : s, e);
const a = {
var d = Object.defineProperty;
var p = (e, s, t) => s in e ? d(e, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[s] = t;
var a = (e, s, t) => p(e, typeof s != "symbol" ? s + "" : s, t);
const y = {
View: 1,

@@ -9,5 +9,5 @@ Add: 2,

Delete: 8
}, y = class {
static hasPermission(t, s) {
return t === (s & t);
}, u = class {
static hasPermission(e, s) {
return e === (s & e);
}

@@ -22,3 +22,3 @@ /**

* existing permission types.
* @implements {IPermissionsStatic}
* @implements {IPermissionStatic}
* @returns {IPermissionType} A new IPermissionType object with the additional permission types added.

@@ -35,11 +35,11 @@ * @example

*/
static extendTypes(t) {
const s = {}, e = Object.keys(a), i = a[e[0]];
let n = Object.keys(a).length;
return i === 0 && (n -= 1), t.forEach((r) => [
static extendTypes(e, s) {
const t = {}, i = Object.keys(e), n = e[i[0]];
let o = i.length;
return n === 0 && (o -= 1), s.forEach((c) => [
// double previous value
s[r] = Math.pow(2, n++)
t[c] = Math.pow(2, o++)
]), Object.freeze({
...a,
...s
...e,
...t
});

@@ -50,3 +50,3 @@ }

constructor(s) {
c(this, "types");
a(this, "types");
this.types = s;

@@ -56,15 +56,15 @@ }

this.types;
let e = 0;
let t = 0;
return s.forEach((i) => {
const n = this.types[i];
e = e | n;
}), e;
t = t | n;
}), t;
}
byExclusion(s) {
const e = Object.getOwnPropertyNames(this.types).filter(
const t = Object.getOwnPropertyNames(this.types).filter(
(i) => s.indexOf(i) === -1
);
return this.fromKeys(e);
return this.fromKeys(t);
}
fromRange(s, e) {
fromRange(s, t) {
this.types;

@@ -75,3 +75,3 @@ const i = Object.getOwnPropertyNames(this.types);

const r = this.types[o];
r >= s && r <= e && (n = n | r);
r >= s && r <= t && (n = n | r);
}), n;

@@ -82,14 +82,14 @@ }

constructor() {
c(this, "dataMap", /* @__PURE__ */ new Map());
a(this, "dataMap", /* @__PURE__ */ new Map());
}
addPermissionsInfo(s) {
setPermissionInfo(s) {
this.dataMap.set(s.id, s.permissions);
}
hasPermissions(s) {
const { id: e, domain: i, permissionType: n } = s;
if (this.dataMap.has(e)) {
const o = this.dataMap.get(e);
const { id: t, domain: i, permissionType: n } = s;
if (this.dataMap.has(t)) {
const o = this.dataMap.get(t);
if (o && o[i]) {
const r = o[i];
return y.hasPermission(n, r);
return u.hasPermission(n, r);
}

@@ -101,6 +101,6 @@ }

export {
a as PermissionType,
y as Permissions,
m as PermissionsBuilder,
m as PermissionBuilder,
y as PermissionType,
u as Permissions,
f as Security
};

@@ -1,1 +0,1 @@

(function(t,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(t=typeof globalThis<"u"?globalThis:t||self,s(t.permissions={}))})(this,function(t){"use strict";var y=Object.defineProperty;var m=(t,s,r)=>s in t?y(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var p=(t,s,r)=>m(t,typeof s!="symbol"?s+"":s,r);const s={View:1,Add:2,Update:4,Delete:8},r=class{static hasPermission(d,e){return d===(e&d)}static extendTypes(d){const e={},i=Object.keys(s),n=s[i[0]];let o=Object.keys(s).length;return n===0&&(o-=1),d.forEach(c=>[e[c]=Math.pow(2,o++)]),Object.freeze({...s,...e})}};class u{constructor(e){p(this,"types");this.types=e}fromKeys(e){this.types;let i=0;return e.forEach(n=>{const o=this.types[n];i=i|o}),i}byExclusion(e){const i=Object.getOwnPropertyNames(this.types).filter(n=>e.indexOf(n)===-1);return this.fromKeys(i)}fromRange(e,i){this.types;const n=Object.getOwnPropertyNames(this.types);let o=0;return n.forEach(a=>{const c=this.types[a];c>=e&&c<=i&&(o=o|c)}),o}}class f{constructor(){p(this,"dataMap",new Map)}addPermissionsInfo(e){this.dataMap.set(e.id,e.permissions)}hasPermissions(e){const{id:i,domain:n,permissionType:o}=e;if(this.dataMap.has(i)){const a=this.dataMap.get(i);if(a&&a[n]){const c=a[n];return r.hasPermission(o,c)}}return!1}}t.PermissionType=s,t.Permissions=r,t.PermissionsBuilder=u,t.Security=f,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
(function(s,t){typeof exports=="object"&&typeof module<"u"?t(exports):typeof define=="function"&&define.amd?define(["exports"],t):(s=typeof globalThis<"u"?globalThis:s||self,t(s.permissions={}))})(this,function(s){"use strict";var m=Object.defineProperty;var h=(s,t,c)=>t in s?m(s,t,{enumerable:!0,configurable:!0,writable:!0,value:c}):s[t]=c;var u=(s,t,c)=>h(s,typeof t!="symbol"?t+"":t,c);const t={View:1,Add:2,Update:4,Delete:8},c=class{static hasPermission(a,e){return a===(e&a)}static extendTypes(a,e){const i={},n=Object.keys(a),o=a[n[0]];let r=n.length;return o===0&&(r-=1),e.forEach(f=>[i[f]=Math.pow(2,r++)]),Object.freeze({...a,...i})}};class p{constructor(e){u(this,"types");this.types=e}fromKeys(e){this.types;let i=0;return e.forEach(n=>{const o=this.types[n];i=i|o}),i}byExclusion(e){const i=Object.getOwnPropertyNames(this.types).filter(n=>e.indexOf(n)===-1);return this.fromKeys(i)}fromRange(e,i){this.types;const n=Object.getOwnPropertyNames(this.types);let o=0;return n.forEach(r=>{const d=this.types[r];d>=e&&d<=i&&(o=o|d)}),o}}class y{constructor(){u(this,"dataMap",new Map)}setPermissionInfo(e){this.dataMap.set(e.id,e.permissions)}hasPermissions(e){const{id:i,domain:n,permissionType:o}=e;if(this.dataMap.has(i)){const r=this.dataMap.get(i);if(r&&r[n]){const d=r[n];return c.hasPermission(o,d)}}return!1}}s.PermissionBuilder=p,s.PermissionType=t,s.Permissions=c,s.Security=y,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});
import { IPermissionType } from './permission-type';
/**
* @name IPermissionsBuilder
* @name IPermissionBuilder
* @description

@@ -9,3 +9,3 @@ * Helper to build permissions values

*/
export interface IPermissionsBuilder {
export interface IPermissionBuilder {
fromKeys(keys: string[]): number;

@@ -16,20 +16,20 @@ byExclusion(keysToExclude: string[]): number;

/**
* @name PermissionsBuilder
* @name PermissionBuilder
* @description
* Implements IPermissionsBuilder helper functions
* Implements IPermissionBuilder helper functions
* that can build permissions values from specific keys,
* from a range of values, or by exluding specific keys.
* @implements {IPermissionsBuilder}
* @implements {IPermissionBuilder}
* @param {IPermissionType} types - The permission types to use for building permissions.
* @returns {IPermissionsBuilder} An instance of PermissionsBuilder.
* @returns {IPermissionBuilder} An instance of PermissionBuilder.
* @example
* const permissionsBuilder = new PermissionsBuilder(permissionTypes);
* const permissions = permissionsBuilder.fromKeys(['View', 'Add']);
* const permissionsExcluding = permissionsBuilder.byExclusion(['Delete']);
* const permissionsInRange = permissionsBuilder.fromRange(1, 3);
* const permissionBuilder = new PermissionBuilder(permissionTypes);
* const permissions = permissionBuilder.fromKeys(['View', 'Add']);
* const permissionExcluding = permissionBuilder.byExclusion(['Delete']);
* const permissionInRange = permissionBuilder.fromRange(1, 3);
* @see IPermissionType
* @see IPermissionsBuilder
* @see IPermissionBuilder
* @see https://example.com/permissions-builder
*/
export declare class PermissionsBuilder implements IPermissionsBuilder {
export declare class PermissionBuilder implements IPermissionBuilder {
private types;

@@ -36,0 +36,0 @@ constructor(types: IPermissionType);

import { IPermissionType } from './permission-type';
/**
* @name IPermissionsStatic
* @name IPermissionStatic
* @description

@@ -13,5 +13,5 @@ * TypeScript trick to declare methods

*/
export interface IPermissionsStatic {
export interface IPermissionStatic {
hasPermission(permissionType: number, permissions: number): boolean;
extendTypes(names: string[]): IPermissionType;
extendTypes(permissionTypes: IPermissionType, names: string[]): IPermissionType;
}

@@ -28,3 +28,3 @@ export interface IPermissions {

* @implements {IPermissions}
* @see IPermissionsStatic
* @see IPermissionStatic
* @see IPermissionType

@@ -36,2 +36,2 @@ * @see PermissionType

*/
export declare const Permissions: IPermissionsStatic;
export declare const Permissions: IPermissionStatic;
/**
* @name IHasPermissionsArgs
* @name IHasPermissionArgs
* @description
* Interface for the arguments required to check permissions.
* It includes the user or role ID, domain, and the type of permission to check.
* @interface IHasPermissionsArgs
* @interface IHasPermissionArgs
* @property {string} id - The ID of user or role.

@@ -11,5 +11,5 @@ * @property {string} domain - The domain for which to check permissions.

* @see ISecurity
* @see IPermissionsInfo
* @see IPermissionInfo
*/
export interface IHasPermissionsArgs {
export interface IHasPermissionArgs {
id: string;

@@ -20,7 +20,7 @@ domain: string;

/**
* @name IPermissionsInfo
* @name IPermissionInfo
* @description
* Interface for the permissions information associated with a user or role.
* It includes the ID and a map of permissions for different domains.
* @interface IPermissionsInfo
* @interface IPermissionInfo
* @property {string} id - The ID of the user or role.

@@ -30,5 +30,5 @@ * @property {Object} permissions - A map of domain names to permission values.

* @see ISecurity
* @see IHasPermissionsArgs
* @see IHasPermissionArgs
*/
export interface IPermissionsInfo {
export interface IPermissionInfo {
id: string;

@@ -45,11 +45,11 @@ permissions: {

* @interface ISecurity
* @property {function} addPermissionsInfo - Method to add permissions information for a user or role.
* @property {function} setPermissionInfo - Method to add permissions information for a user or role.
* @property {function} hasPermissions - Method to check if a user has specific permissions on a domain.
* @see IHasPermissionsArgs
* @see IPermissionsInfo
* @see IHasPermissionArgs
* @see IPermissionInfo
* @see Permissions
*/
export interface ISecurity {
addPermissionsInfo(params: IPermissionsInfo): void;
hasPermissions(params: IHasPermissionsArgs): boolean;
setPermissionInfo(params: IPermissionInfo): void;
hasPermissions(params: IHasPermissionArgs): boolean;
}

@@ -66,8 +66,8 @@ /**

* @implements {ISecurity}
* @see IHasPermissionsArgs
* @see IPermissionsInfo
* @see IHasPermissionArgs
* @see IPermissionInfo
* @see Permissions
* @example
* const security = new Security();
* security.addPermissionsInfo({
* security.setPermissionInfo({
* id: 'user123',

@@ -89,4 +89,4 @@ * permissions: {

constructor();
addPermissionsInfo(params: IPermissionsInfo): void;
hasPermissions(params: IHasPermissionsArgs): boolean;
setPermissionInfo(params: IPermissionInfo): void;
hasPermissions(params: IHasPermissionArgs): boolean;
}
{
"name": "@builtwithjavascript/permissions",
"version": "1.0.3",
"version": "1.0.7",
"description": "",

@@ -5,0 +5,0 @@ "author": "Damiano Fusco",

+172
-61
# @builtwithjavascript/permissions
A lightweight TypeScript utility for managing and evaluating permissions in web applications. Designed with extensibility and composability in mind.
A lightweight TypeScript utility for managing and evaluating permissions in web applications. Designed with extensibility and composability in mind, this library helps you define, add, and check access permissions efficiently.
---

@@ -19,5 +21,6 @@

- **Permission**: A rule describing access to a resource and action (optionally with a condition).
- **PermissionsBuilder**: A utility to register and evaluate sets of permissions.
- **Security**: A wrapper to centralize permission checks in an application.
- **PermissionType**: A set of predefined numerical values (powers of 2) representing different types of actions (e.g., View, Add, Update, Delete). These can be extended with custom types.
- **PermissionBuilder**: A utility to create permission values by combining `PermissionType` values, either by specifying keys, excluding keys, or within a range.
- **Permissions**: A static class providing methods to check if a specific permission is granted and to extend the default `PermissionType` with custom types.
- **Security**: (Optional) A wrapper to centralize and manage user/role-based permission checks within an application.

@@ -28,34 +31,106 @@

1. **Define Your Own Permissions**
Extend the base permission interface to define additional app-specific permissions:
**Define and Extend Permission Types**
The library provides a default `PermissionType`. You can extend this with your application-specific permissions using `Permissions.extendTypes()`.
```typescript
import { Permission, PermissionsBuilder } from '@builtwithjavascript/permissions'
import { IPermissionType, PermissionType, Permissions } from '@builtwithjavascript/permissions';
export interface YourAppPermission extends Permission {
readonly Publish?: boolean
readonly Share?: boolean
/**
* Extend IPermissionType with custom types
*/
export interface YourAppIPermissionType extends IPermissionType {
readonly Publish: number;
readonly Share: number;
}
/**
* Extend PermissionType with names matching your custom interface
*/
export const YourAppPermissionType: YourAppIPermissionType = Permissions.extendTypes(
PermissionType, // Use the base PermissionType
['Publish', 'Share']
) as YourAppIPermissionType;
console.log(YourAppPermissionType.Publish); // Will log a power of 2, e.g., 16
console.log(YourAppPermissionType.Share); // Will log a power of 2, e.g., 32
```
2. **Add Permissions**
**Build Permissions**
Use `PermissionBuilder` to combine `PermissionType` values into a single numerical permission value for a given resource or domain.
```typescript
const builder = new PermissionsBuilder()
builder.add(
{ resource: 'article', action: 'edit' },
{ resource: 'article', action: 'publish', condition: (ctx) => ctx?.isAdmin }
)
import { PermissionBuilder, PermissionType } from '@builtwithjavascript/permissions';
import { YourAppPermissionType } from './your-app-permission-type'; // Assuming you saved the extended type
const builder = new PermissionBuilder(PermissionType); // For default types
const yourAppBuilder = new PermissionBuilder(YourAppPermissionType); // For your extended types
// Build permissions using default types
const itemPermissions = builder.fromKeys(['View', 'Add']);
console.log(`Item Permissions (View, Add): ${itemPermissions}`); // e.g., 3 (1 | 2)
// Build permissions by exclusion
const allExceptDelete = builder.byExclusion(['Delete']);
console.log(`All Except Delete: ${allExceptDelete}`); // e.g., 7 (1 | 2 | 4)
// Build permissions using your extended types
const articlePublishAndShare = yourAppBuilder.fromKeys(['Publish', 'Share']);
console.log(`Article Publish & Share Permissions: ${articlePublishAndShare}`); // e.g., 48 (16 | 32)
```
3. **Check Access**
**Check Access**
The `Security` class allows you to set permission information for users/roles and then check if they have specific access.
```typescript
import { Security } from '@builtwithjavascript/permissions'
import { Security, PermissionType } from '@builtwithjavascript/permissions';
import { YourAppPermissionType } from './your-app-permission-type'; // Assuming you saved the extended type
const security = new Security(builder)
const security = new Security();
const canPublish = security.isAllowed(
{ resource: 'article', action: 'publish' },
{ isAdmin: true } // context
)
// Set permissions for a user
security.setPermissionInfo({
id: 'user123',
permissions: {
'Articles': new PermissionBuilder(YourAppPermissionType).fromKeys(['View', 'Publish']),
'Comments': new PermissionBuilder(PermissionType).fromKeys(['View', 'Add'])
}
});
console.log(canPublish) // true or false
// Check if user123 can view articles
const canViewArticles = security.hasPermissions({
id: 'user123',
domain: 'Articles',
permissionType: YourAppPermissionType.View
});
console.log(`Can user123 view articles? ${canViewArticles}`); // true
// Check if user123 can publish articles
const canPublishArticles = security.hasPermissions({
id: 'user123',
domain: 'Articles',
permissionType: YourAppPermissionType.Publish
});
console.log(`Can user123 publish articles? ${canPublishArticles}`); // true
// Check if user123 can delete articles (they don't have this permission)
const canDeleteArticles = security.hasPermissions({
id: 'user123',
domain: 'Articles',
permissionType: YourAppPermissionType.Delete
});
console.log(`Can user123 delete articles? ${canDeleteArticles}`); // false
// Check if user123 can add comments
const canAddComments = security.hasPermissions({
id: 'user123',
domain: 'Comments',
permissionType: PermissionType.Add
});
console.log(`Can user123 add comments? ${canAddComments}`); // true
```

@@ -65,51 +140,87 @@

## ๐Ÿงช Example: Extending Permission Types
## ๐Ÿ“š API Overview
### IPermissionType
```typescript
import { IPermissionType, Permissions } from '@builtwithjavascript/permissions'
/**
* Extend IPermissionType with custom types
*/
export interface YourAppIPermissionType extends IPermissionType {
readonly Publish: number
readonly Share: number
interface IPermissionType extends Record<string, number> {
View: number;
Add: number;
Update: number;
Delete: number;
// ... can be extended with more custom number-based permissions
}
```
/**
* Extend PermissionType with names matching your custom interface
*/
export const YourAppPermissionType: YourAppIPermissionType = Permissions.extendTypes([
'Publish',
'Share',
]) as YourAppIPermissionType
A base interface defining numerical permission types. Values are powers of 2 for efficient bitwise operations.
### PermissionType
```typescript
export const PermissionType: IPermissionType = {
View: 1,
Add: 2,
Update: 4,
Delete: 8
};
```
The default implementation of `IPermissionType`.
## ๐Ÿ“š API Overview
### Permissions
### Permissions (Static Class)
Provides static methods for permission checking and type extension.
- `static hasPermission(permissionType: number, permissions: number): boolean` Checks if a specific `permissionType` is included in a given `permissions` value.
- `static extendTypes(permissionTypes: IPermissionType, names: string[]): IPermissionType` Extends an existing `IPermissionType` object with new permission names, assigning them appropriate power-of-2 values.
### PermissionBuilder
```typescript
interface Permission {
resource: string
action: string
condition?: string | ((context?: any) => boolean)
class PermissionBuilder implements IPermissionBuilder {
constructor(types: IPermissionType);
fromKeys(keys: string[]): number;
byExclusion(keysToExclude: string[]): number;
fromRange(fromValue: number, toValue: number): number;
}
```
### PermissionsBuilder
A class to construct combined permission values based on `IPermissionType`.
- `add(...permissions: Permission[]): this`
Adds one or more permissions.
- `allows(permission: Permission, context?: any): boolean`
Checks if permission is granted.
- `list(): Permission[]`
Returns all stored permissions.
- `constructor(types: IPermissionType)`: Initializes the builder with a set of permission types.
- `fromKeys(keys: string[]): number`: Generates a permission value by combining the values of specified keys.
- `byExclusion(keysToExclude: string[]): number`: Generates a permission value by combining all types *except* those specified in `keysToExclude`.
- `fromRange(fromValue: number, toValue: number): number`: Generates a permission value by combining types whose numerical value falls within a given range.
### Security
- `isAllowed(permission: Permission, context?: any): boolean`
Delegates permission check to `PermissionsBuilder`.
### Security (optional)
```typescript
interface IPermissionInfo {
id: string;
permissions: { [key: string]: number }; // Maps domain names to their permission values
}
class Security implements ISecurity {
constructor();
setPermissionInfo(params: IPermissionInfo): void;
hasPermissions(params: { id: string; domain: string; permissionType: number }): boolean;
}
```
A service for managing and checking user/role permissions across different domains.
- `constructor()`: Initializes the Security service.
- `setPermissionInfo(params: IPermissionInfo)`: Stores permission information for a given `id` (e.g., user ID, role ID) and their associated domain permissions.
- `hasPermissions(params: { id: string; domain: string; permissionType: number }): boolean`: Checks if the specified `id` has the `permissionType` for the given `domain`.

@@ -122,9 +233,9 @@

โ”œโ”€โ”€ permissions/
โ”‚ โ”œโ”€โ”€ permission-type.ts
โ”‚ โ”œโ”€โ”€ permissions.ts
โ”‚ โ”œโ”€โ”€ permissions-builder.ts
โ”‚ โ”œโ”€โ”€ permission-type.ts # Defines IPermissionType and PermissionType
โ”‚ โ”œโ”€โ”€ permissions.ts # Implements Permissions static class (hasPermission, extendTypes)
โ”‚ โ”œโ”€โ”€ permissions-builder.ts # Implements PermissionBuilder
โ”œโ”€โ”€ security/
โ”‚ โ””โ”€โ”€ security.ts
โ””โ”€โ”€ index.ts
โ”‚ โ””โ”€โ”€ security.ts # Implements Security class
โ””โ”€โ”€ index.ts # Main export file
```