Quickstart
@blocks/policy puts authorization in plain classes: one class per resource, one method per action, and every method returns a boolean. This page installs it, writes one policy, calls it in the two places that need it, and tests it.
Install
bun add @blocks/policyOr with npm:
npm install @blocks/policyThe package has no dependencies. It is plain ES2022 JavaScript with type declarations and uses no Node, Bun or browser API, so any runtime that loads ES2022 modules can run it; its own tests run it in Node and Bun. The declarations need TypeScript 5.4 or newer.
Write a policy
A policy is a class that extends Policy with the type of the resource it guards. The base class takes the user and the resource in its constructor and keeps them as this.user and this.resource. Each public method you add is an action, and returns true to allow it or false to deny it.
import { CurrentUser, Policy } from '@blocks/policy'
export interface Post {
id: string
authorId: string
}
export class PostPolicy extends Policy<Post> {
update() {
return this.user.isOwner(this.resource.authorId)
}
destroy() {
return this.user.hasRole('admin')
}
}
interface Session {
userId: string
role: string
}
/** Whether to render the Edit button: a boolean. */
export function showEditButton(session: Session, post: Post) {
const user = new CurrentUser({ id: session.userId, role: session.role })
return new PostPolicy(user, post).update()
}
/** Your app's own error for a denied request. The library has none. */
export class ForbiddenError extends Error {}
/** The server's check before deleting: throws ForbiddenError when denied. */
export function deletePost(session: Session, post: Post) {
const user = new CurrentUser({ id: session.userId, role: session.role })
if (!new PostPolicy(user, post).destroy()) throw new ForbiddenError()
// ...delete the post
}PostPolicy has two actions. update allows the post's author, using isOwner to compare the user's id with the post's authorId. destroy allows an admin, using hasRole.
The user is a CurrentUser: an id, one role, and any feature flags you have already resolved. Build it from what your session or auth provider already knows. You do not need a database call to make one.
Call it
There are two places to ask a policy, and the example has one of each.
- When you render, call the action for a boolean.
showEditButtonreturnspolicy.update(), and the page shows the Edit button only when it istrue. - On the server, before doing the work, call the action and stop when it returns
false.deletePostcallsdestroy()and throwsForbiddenErrorwhen it returnsfalse, so it never reaches the delete for anyone but an admin.ForbiddenErroris the example's own: the library has no error class, so throw your app's.
An action only returns a boolean. Calling it changes nothing by itself: the if around it is what hides the button or stops the request.
Hiding a button is for the person using the page. The server check is the one that protects the data, so make it on every request that changes something. Enforcing shows how to turn your error into a 403 in one place.
Test it
A policy is a class with a constructor. To test it, construct it with a user and a resource and assert on the result. There is nothing to mock and no server to start.
import { expect, test } from 'bun:test'
import { CurrentUser } from '@blocks/policy'
import { deletePost, ForbiddenError, PostPolicy, showEditButton } from './post-policy'
const post = { id: 'p1', authorId: 'u1' }
const author = new CurrentUser({ id: 'u1', role: 'member' })
const stranger = new CurrentUser({ id: 'u2', role: 'member' })
const admin = new CurrentUser({ id: 'u3', role: 'admin' })
test('only the author can update a post', () => {
expect(new PostPolicy(author, post).update()).toBe(true)
expect(new PostPolicy(stranger, post).update()).toBe(false)
expect(new PostPolicy(admin, post).update()).toBe(false)
})
test('only an admin can destroy a post', () => {
expect(new PostPolicy(admin, post).destroy()).toBe(true)
expect(new PostPolicy(author, post).destroy()).toBe(false)
})
test('the Edit button follows update', () => {
expect(showEditButton({ userId: 'u1', role: 'member' }, post)).toBe(true)
expect(showEditButton({ userId: 'u2', role: 'member' }, post)).toBe(false)
})
test('deleting a post throws ForbiddenError unless the user is an admin', () => {
expect(() => deletePost({ userId: 'u3', role: 'admin' }, post)).not.toThrow()
expect(() => deletePost({ userId: 'u1', role: 'member' }, post)).toThrow(ForbiddenError)
expect(() => deletePost({ userId: 'u2', role: 'member' }, post)).toThrow(ForbiddenError)
})Run it with bun test. The same file runs under Vitest with its first line importing from vitest instead of bun:test. Testing shows a table of cases for a larger policy.
Next
- Writing policies: how to shape a policy as it grows.
- The current user: typed role and flag names, extra fields, or your own user type.
- API: every export, with its edge cases.
@blocks/policy follows Pundit, the Ruby library, and pundit.js: a policy class per resource and a method per action.