A framework for creating authorization policies. Loosely inspired by OPA.
const { Agent, should } = require('node-policy-agent')
const policy = [
// /api/users/:id
[
should.matchUri('$input.path', '/api/users/:id'),
should.equal('$input.method', 'GET'),
should.contain('$input.user.roles', 'admin')
],
// /api/foo
[
should.matchUri('$input.path', '/api/foo'),
should.equal('POST', 'POST'),
// A custom rule
input => {
if (input.myParam === 'myValue' && 1 + 1 === 2) return true
return false
}
]
]
const myAgent = new Agent(policy)
const granted = myAgent.authorize({
path: '/api/foo/username',
method: 'GET',
user: {
roles: [
'admin',
'support'
]
}
})
// granted === true
Create a new Agent
Authorize some input, provided policies will be used in place of the ones used when creating the Agent.
Options for both the constructor and .authorize()
.
{
detailedResponse: false // Return more details when authorizing. Will return a Boolean if false. False is default.
}
Policies are defined by a set of rules. Each rule is a function that processes the input value and returns a boolean whether or not the rule passed. The optional output
argument is an object to use for any output data that should be sent back to .authorize()
if the option detailedResponse
is set to true
, if set to false
, output
will not be accessible.
const myPolicy = [
[
/**
* Rule without output
*/
input => {
return input.username === 'Alice'
},
/**
* Rule with output
*/
(input, output) => {
output.userIsAlice = input.username === 'Alice'
return input.username === 'Alice'
}
]
]
The exported require('node-policy-agent').should
contains the following pre-built rules:
Check if two values are equal
Check if two objects contain the same keys and values
Check if a string matches a regular expression
Check if a string matches a uri-pattern,
valid patterns can contain placeholders idicated by a colon, such as /api/users/:id
. Trailing slashes are automatically removed from both arguments.
Check if num1
is less than num2
Check if num1
is more than num2
Check if the set contains the value, the set can be either a string or an array