Flexible, type-safe JavaScript library for efficient authorization and permission checking. Easily manage permissions, and context-aware access control with minimal overhead and a simple API.
Install package:
# ✨ Auto-detect
npx nypm install guantr
# npm
npm install guantr
# yarn
yarn add guantr
# pnpm
pnpm install guantr
# bun
bun install guantr
# deno
deno install guantr
Import:
ESM (Node.js, Bun, Deno)
import { createGuantr } from "guantr";
CommonJS (Legacy Node.js)
const { createGuantr } = require("guantr");
CDN (Deno, Bun and Browsers)
import { createGuantr } from "https://esm.sh/guantr";
Initialize:
const guantr = await createGuantr()
// With Typescript Meta:
type Meta = GuantrMeta<{
post: {
action: 'create' | 'read' | 'update' | 'delete'
model: {
id: number,
title: string,
published: boolean
}
}
}>;
const guantr = await createGuantr<Meta>()
// Contextual
const user = {
id: number,
name: 'John Doe',
roles: ['admin']
}
const guantrWithContext = await createGuantr<Meta, { user: typeof user }>({
getContext: () => ({ user })
})
Setting rules:
await guantr.setRules((can, cannot) => {
can('read', 'post')
cannot('read', ['post', { published: ['eq', false] }])
})
// Or
await guantr.setRules([
{
resource: 'post',
action: 'read',
condition: null,
effect: 'allow'
},
{
resource: 'post',
action: 'read',
condition: {
published: ['eq', false]
},
effect: 'deny'
}
])
Rules also can be set on instance creation:
const guantr = await createGuantr<Meta>([
{
resource: 'post',
action: 'read',
condition: {
published: ['eq', false]
},
effect: 'deny'
}
])
Authorize:
await guantr.can('read', 'post') // true
const post = {
id: 1,
title: 'Hello World',
published: false
}
await guantr.can('read', ['post', post]) // false
local development
- Clone this repository
- Install latest LTS version of Node.js
- Enable Corepack using corepack enable
- Install dependencies using pnpm install
- Run interactive tests using pnpm dev
🤖 auto updated with automd