rolebook/middleware/express
The exports of the optional Express middleware entry point.
import { ... } from "rolebook/middleware/express". Requires express >=5.1.0 <6; TypeScript
applications also install @types/express. Express is an optional peer: the entry point imports
only Express types, so rolebook alone never loads Express.
import express from "express";
import { createRolebookMiddleware } from "rolebook/middleware/express";
const app = express();
const middleware = createRolebookMiddleware({
policy,
getBinding: (request) => loadAuthorizationContext(request),
});
app.get(
"/projects/:id",
middleware.requirePermission(async (request) => {
const { id } = request.params;
return {
permission: "project:read",
resource: await loadTrustedProject(typeof id === "string" ? id : undefined),
};
}),
(_request, response) => {
response.json({ ok: true });
},
);
// After the routes: Express recognizes an error handler by its four parameters.
app.use(middleware.onError); Authenticate before requirePermission runs. The adapter does not authenticate sessions or read a
binding from headers, request.user or response.locals.
createRolebookMiddleware
function createRolebookMiddleware<
TRole extends string,
TPermission extends string,
TResources extends ResourceDefinitions = ResourceDefinitions,
>(
options: RolebookMiddlewareOptions<TRole, TPermission, TResources>,
): RolebookMiddleware<RequestPermission<TPermission, TResources>>; Creates one authorizer for options.policy (with onEvaluationFault as its fault reporter) and
returns a frozen RolebookMiddleware.
RolebookMiddleware
interface RolebookMiddleware<TPermission extends string> {
readonly onError: ErrorRequestHandler;
readonly requirePermission: (
check:
| CheckRequest<TPermission>
| ((request: Request) => CheckRequest<TPermission> | Promise<CheckRequest<TPermission>>),
) => RequestHandler;
} requirePermission(check): an Express 5 request handler. For each request it gets the authorization (callinggetBindingand binding, or reusing the request’s binding whenreuseBindingPerRequestis on) and answersonUnauthorizedwhen there is none. Otherwise it setsresponse.locals.authorization, resolvescheck(calling it with the request when it is a function), checks it, and answersonForbiddenon a denial or callsnext()on an allow. Errors fromgetBindingor the check function reject, and Express 5 passes them to its error pipeline.onError: an error handler to mount after the routes. When headers have already been sent it callsnext(error). AnAuthorizationError(fromenforce()in a handler) becomesonForbidden. Any other error goes tonext(error), so install the application’s own error handler after this one.
RolebookMiddlewareOptions
interface RolebookMiddlewareOptions<
TRole extends string = string,
TPermission extends string = string,
TResources extends ResourceDefinitions = ResourceDefinitions,
> {
readonly policy: RolebookPolicy<TRole, TPermission, TResources>;
readonly getBinding: (
request: Request,
) => BindInput<TRole> | undefined | Promise<BindInput<TRole> | undefined>;
readonly onUnauthorized?: (request: Request, response: Response) => unknown | Promise<unknown>;
readonly onForbidden?: (request: Request, response: Response) => unknown | Promise<unknown>;
readonly onEvaluationFault?: InternalErrorReporter;
readonly reuseBindingPerRequest?: boolean;
} | Option | Behaviour |
|---|---|
policy | The policy every check uses. |
getBinding | Loads the binding for the request. undefined becomes onUnauthorized and is never remembered. |
onUnauthorized | Default: response.status(401).json({ error: "Unauthorized" }). A replacement must finish the response. |
onForbidden | Default: response.status(403).json({ error: "Forbidden" }). Used for denied checks and downstream AuthorizationErrors. A replacement must finish the response. |
onEvaluationFault | Passed to createAuthorizer as onInternalError. A fault still fails closed, so the check still answers 403. |
reuseBindingPerRequest | Default false. When true, bind once per request per middleware instance. Enable only when identity and assignments cannot change during the request. |
RolebookLocals
interface RolebookLocals<TPolicy extends RolebookPolicy> {
authorization: BoundAuthorizer<
RequestPermission<PolicyPermission<TPolicy>, TPolicy["resources"]>
>;
} The type of response.locals after requirePermission allows a request. Use
Response<Body, RolebookLocals<typeof policy>> in a handler to keep the policy’s concrete
permission union for further check() and enforce() calls. It is output for the application: the
adapter never reads it back as authority. PolicyPermission<TPolicy> is an internal helper type:
the union of the permissions the policy’s rules name.