RolebookDocs

Hono middleware

Guard Hono routes with a binding and a trusted resource per request.

The optional adapter at rolebook/middleware/hono resolves a bound authorization for each request and a concrete check for each route, and maps denials to HTTP responses. It contains no policy logic: every decision is an ordinary Rolebook check. It needs hono >=4.12.34 <5.

Using Express or Fastify instead? Rolebook ships matching middleware with the same binding contract at rolebook/middleware/express (Express 5) and rolebook/middleware/fastify (Fastify 5).

import { Hono } from "hono";
import { createRolebookMiddleware, type RolebookEnv } from "rolebook/middleware/hono";

const app = new Hono<RolebookEnv<typeof policy>>();

const middleware = createRolebookMiddleware({
  policy,
  getBinding: (context) => loadAuthorizationContext(context),
});

app.onError(middleware.onError);

app.get(
  "/projects/:id",
  middleware.requirePermission(async (context) => ({
    permission: "project:read",
    resource: await loadTrustedProject(context.req.param("id")),
  })),
  (context) => context.json({ ok: true }),
);

Parameterize RolebookEnv with the policy type so context.get("authorization") keeps the policy’s concrete permission union.

What each piece does

  • getBinding(context) returns the binding for the request: the authenticated subject, its assignments, and optional principals and context. It may be async. Returning undefined means the request is unauthenticated: the middleware answers 401 and never remembers that result.
  • requirePermission(request) takes a check request, or a function of the Hono context that returns one (sync or async). The middleware binds, stores the bound authorizer on the context as authorization, resolves the request, and checks it. A denial answers 403; an allow calls the next handler.
  • app.onError(middleware.onError) maps errors thrown downstream. It answers 403 for an AuthorizationError (from enforce() in a handler), preserves the response of a Hono HTTPException, and reports any other error before answering a plain-text 500. Without it, Hono answers an AuthorizationError with its default 500.

Inside a handler, use the stored authorization for further checks on the same binding:

import { Hono } from "hono";
import { createRolebookMiddleware, type RolebookEnv } from "rolebook/middleware/hono";

const app = new Hono<RolebookEnv<typeof policy>>();
const middleware = createRolebookMiddleware({ policy, getBinding: loadAuthorizationContext });
app.onError(middleware.onError);

app.delete(
  "/projects/:id",
  middleware.requirePermission(async (context) => ({
    permission: "project:update",
    resource: await loadTrustedProject(context.req.param("id")),
  })),
  async (context) => {
    const project = await loadTrustedProject(context.req.param("id"));
    // Throws AuthorizationError on denial; onError turns it into a 403.
    context.get("authorization").enforce({ permission: "project:delete", resource: project });
    return context.body(null, 204);
  },
);

Options

OptionDefaultPurpose
policyrequiredThe policy. The middleware creates one authorizer for it.
getBindingrequiredLoads the request’s binding, or undefined for 401.
onUnauthorized(context)context.json({ error: "Unauthorized" }, 401)The response when getBinding returns undefined.
onForbidden(context)context.json({ error: "Forbidden" }, 403)The response for a denied check and for a downstream AuthorizationError.
onInternalError(error, context)console.error(error)Reports an unexpected downstream error before the generic 500. Supply a logger, or a no-op to silence it.
onEvaluationFaultnoneReports evaluator faults; passed to createAuthorizer as onInternalError.
reuseBindingPerRequestfalseBind once per request and reuse it for later checks from this middleware instance.

onInternalError is diagnostics only. A reporter that throws or rejects is ignored, and the response is unchanged. If classifying the error or producing its response also fails (a throwing onForbidden, a hostile error object), both the original error and the secondary failure are reported and the answer is a plain-text 500. onError always returns a Promise<Response>; code that calls it directly rather than through app.onError must await it.

Reusing the binding per request

By default every requirePermission calls getBinding and binds afresh, so a route that stacks several checks loads the binding once per check. With reuseBindingPerRequest: true, the first check on a request binds and later checks from the same middleware instance on the same request reuse that authorization. Overlapping checks share one pending getBinding call. The next request loads again, and a load that returned undefined or failed is forgotten, so a later check on the same request tries again.

The reuse is private to the middleware instance and keyed by Hono’s per-request Context. The middleware never reads a binding or authorization back from a context variable, so a value other code puts there cannot stand in for one.

Enable reuse only for request-invariant bindings

With reuse on, a later check keeps the first binding even when its own answer would differ. An app-level check on /api/* cannot see a route parameter such as :tenant that a route-level check can, and middleware between two checks may swap or step down the identity. Turn it on only when getBinding depends solely on data that cannot change within a request, such as the authenticated session.

See the API reference for the exact types. The HTTP authorization recipe puts the same middleware on two document routes and uses onForbidden so a denial is indistinguishable from a missing document.