RolebookDocs

rolebook/middleware/hono

The exports of the optional Hono middleware entry point.

import { ... } from "rolebook/middleware/hono". Requires hono >=4.12.34 <5. For usage, see the Hono middleware guide.

createRolebookMiddleware

function createRolebookMiddleware<
  TRole extends string,
  TPermission extends string,
  TResources extends ResourceDefinitions = ResourceDefinitions,
>(
  options: RolebookMiddlewareOptions<TRole, TPermission, TResources>,
): Readonly<{
  onError: (error: unknown, context: Context) => Promise<Response>;
  requirePermission(
    request:
      | CheckRequest<RequestPermission<TPermission, TResources>>
      | ((
          context: Context,
        ) =>
          | CheckRequest<RequestPermission<TPermission, TResources>>
          | Promise<CheckRequest<RequestPermission<TPermission, TResources>>>),
  ): (context: Context, next: Next) => Promise<Response | undefined>;
}>;

Creates one authorizer for options.policy (with onEvaluationFault as its fault reporter) and returns a frozen object with:

  • requirePermission(request): a Hono middleware. For each request it gets the authorization (calling getBinding and binding, or reusing the request’s binding when reuseBindingPerRequest is on), answers onUnauthorized when there is none, sets the authorization context variable, resolves request (calling it with the context when it is a function), checks it, and answers onForbidden on a denial or calls next() on an allow. Errors thrown by getBinding or the request function propagate to Hono’s error handler.
  • onError(error, context): an error handler for app.onError. An AuthorizationError becomes onForbidden(context). An error with a getResponse() method returning a Response (Hono’s HTTPException) keeps that response. Anything else is reported to onInternalError and answered with context.text("Internal Server Error", 500). When classifying the error or building the response throws, both errors are reported and the answer is the same 500. It always returns a promise.

RolebookMiddlewareOptions

interface RolebookMiddlewareOptions<
  TRole extends string = string,
  TPermission extends string = string,
  TResources extends ResourceDefinitions = ResourceDefinitions,
> {
  readonly policy: RolebookPolicy<TRole, TPermission, TResources>;
  readonly getBinding: (
    context: Context,
  ) => BindInput<TRole> | undefined | Promise<BindInput<TRole> | undefined>;
  readonly onUnauthorized?: (context: Context) => Response | Promise<Response>;
  readonly onForbidden?: (context: Context) => Response | Promise<Response>;
  readonly onInternalError?: (error: unknown, context: Context) => void;
  readonly onEvaluationFault?: InternalErrorReporter;
  readonly reuseBindingPerRequest?: boolean;
}
OptionBehaviour
policyThe policy every check uses.
getBindingLoads the binding for the request. undefined becomes onUnauthorized and is never remembered.
onUnauthorizedDefault: context.json({ error: "Unauthorized" }, 401).
onForbiddenDefault: context.json({ error: "Forbidden" }, 403). Used for denied checks and downstream AuthorizationErrors.
onInternalErrorDefault: console.error(error). Diagnostics only: a throwing or rejecting reporter is ignored.
onEvaluationFaultPassed to createAuthorizer as onInternalError. A fault still fails closed, so the check still answers 403.
reuseBindingPerRequestDefault false. When true, bind once per request per middleware instance; see reuse.

RolebookEnv

interface RolebookEnv<TPolicy extends RolebookPolicy> extends Env {
  Variables: {
    authorization: BoundAuthorizer<
      RequestPermission<PolicyPermission<TPolicy>, TPolicy["resources"]>
    >;
  };
}

The Hono environment that types the authorization context variable set by requirePermission. Use new Hono<RolebookEnv<typeof policy>>(). PolicyPermission<TPolicy> is an internal helper type: the union of the permissions the policy’s rules name.