Blocks Policy

Enforcing

A policy gives answers. Enforcing is making those answers stop a request. You ask a policy by calling its action, which returns a boolean, and the code around that call decides what happens: on the server your code throws, and when rendering it shows or hides. A call whose result nothing reads does nothing.

The examples on this page use PostPolicy from the Quickstart: the author can update a post, and an admin can destroy it.

On the server: call the action and throw

Right before the work an action protects, call it, and throw when it returns false. The request stops there, and the code after it can assume the user was allowed. The library has no error class, so throw your app's own; a class that extends Error is enough.

Then turn that error into a response in one place, rather than in every handler:

enforcing/server.ts
import type { CurrentUser } from '@blocks/policy'
import { type Post, PostPolicy } from '../quickstart/post-policy'

/** Your app's error for a denied request. The library has none, and this is all it takes. */
export class ForbiddenError extends Error {
  override name = 'ForbiddenError'
}

type Handler = (request: Request, user: CurrentUser) => Promise<Response>

/** The one place a ForbiddenError becomes a 403. Every other error is left alone. */
export function withForbidden(handler: Handler): Handler {
  return async (request, user) => {
    try {
      return await handler(request, user)
    } catch (error) {
      if (error instanceof ForbiddenError) {
        return Response.json({ error: 'Forbidden' }, { status: 403 })
      }
      throw error
    }
  }
}

/** DELETE /posts/:id, with the posts it reads and writes. */
export function deletePostRoute(posts: Map<string, Post>): Handler {
  return withForbidden(async (request, user) => {
    const id = new URL(request.url).pathname.split('/').pop() ?? ''
    const post = posts.get(id)
    if (!post) return new Response(null, { status: 404 })

    // Call the action, and stop when it returns false.
    if (!new PostPolicy(user, post).destroy()) throw new ForbiddenError()

    posts.delete(id)
    return new Response(null, { status: 204 })
  })
}

ForbiddenError is defined in the example itself. deletePostRoute calls destroy() and throws it when the answer is false, and withForbidden catches it and answers 403. Any other error, such as a failed database call, passes through untouched, so it is not mistaken for a denial. Most servers have a natural home for this: an error handler or a wrapper that every route already goes through.

An action is a plain method, so if it throws, the error reaches the caller unchanged.

When rendering: booleans

A page needs to know which buttons to show. Call the actions and pass the booleans along:

enforcing/render.ts
import type { CurrentUser } from '@blocks/policy'
import { type Post, PostPolicy } from '../quickstart/post-policy'

/**
 * What the page needs to know to show its buttons: booleans, which any
 * template, component or client can take.
 */
export function postPermissions(user: CurrentUser, post: Post) {
  const policy = new PostPolicy(user, post)
  return {
    canEdit: policy.update(),
    canDelete: policy.destroy(),
  }
}

Booleans fit anywhere: a template, a component's props, or JSON sent to a client. A policy instance is a class with methods, so it does not survive being serialized; send the booleans instead. Recipes shows conditional rendering in React.

A client check never replaces the server's

Showing or hiding a button is a convenience for the person using the page. Anyone can send the request the button would have sent. The server must run its own check on every request that reads or changes something protected. The same policy class can run in both places, so the answer is the same; the server's check is still the one that counts.

Resolve first, then decide

Actions are synchronous on purpose. An async action returns a Promise, and a Promise is truthy, so if (policy.view()) is taken for everyone, whether the Promise would resolve to true or false. Load what the decision needs, then build the policy with it:

enforcing/async-mistake.ts
import { type CurrentUser, Policy } from '@blocks/policy'

export interface Report {
  id: string
  teamId: string
}

export interface Teams {
  isMember(userId: string, teamId: string): Promise<boolean>
}

// The mistake: an action that waits for data.
export class AsyncReportPolicy extends Policy<{ report: Report; teams: Teams }> {
  async view() {
    return this.resource.teams.isMember(this.user.id, this.resource.report.teamId)
  }
}

export function showReport(policy: AsyncReportPolicy) {
  // view() returns a Promise, and a Promise is truthy, so this is always 'shown'.
  // @ts-expect-error TypeScript rejects a Promise used directly as a condition.
  if (policy.view()) return 'shown'
  return 'hidden'
}

export function reportIsVisible(policy: AsyncReportPolicy) {
  // TypeScript accepts this one, and it is just as wrong: always true.
  return Boolean(policy.view())
}

// The fix: resolve the facts first, then decide synchronously.
export class ReportPolicy extends Policy<{ memberOfTeam: boolean }> {
  view(): boolean {
    return this.resource.memberOfTeam
  }
}

export async function reportPolicyFor(user: CurrentUser, report: Report, teams: Teams) {
  const memberOfTeam = await teams.isMember(user.id, report.teamId)
  return new ReportPolicy(user, { memberOfTeam })
}

AsyncReportPolicy.view awaits a lookup, so showReport returns 'shown' and reportIsVisible returns true even for a stranger. TypeScript rejects a Promise used directly as an if condition, which is why showReport needs @ts-expect-error to compile, but it accepts Boolean(policy.view()) and does not check code that is not type-checked.

ReportPolicy takes the answer as a fact instead: reportPolicyFor awaits the lookup first, and the policy decides from a boolean. It is also easier to test, because the test passes { memberOfTeam: true } instead of a fake lookup.

To keep an action synchronous, declare its return type, as ReportPolicy does with view(): boolean. An async method must return a Promise, so adding async in front of view(): boolean does not compile.