Blocks Policy
Authorization in plain classes. Write one class per resource and one method per action, and every method returns a boolean. Ask a policy before you render a button, and ask it again on the server before you do the work.
Get started
Install the package, write a policy for a resource, and call it. It has no dependencies and is plain ES2022 that uses no Node, Bun or browser API.
bun add @blocks/policyimport { 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
}