rolebook/middleware/fastify
The exports of the optional Fastify middleware entry point.
import { ... } from "rolebook/middleware/fastify". Requires fastify >=5.0.0 <6, which ships its
own TypeScript declarations. Fastify is an optional peer: the entry point imports only Fastify
types, so rolebook alone never loads Fastify.
import Fastify from "fastify";
import { createRolebookMiddleware, type RolebookRequest } from "rolebook/middleware/fastify";
const app = Fastify();
app.register(async (routes) => {
const middleware = createRolebookMiddleware({
policy,
getBinding: (request) => loadAuthorizationContext(request),
});
// setErrorHandler, in the same plugin scope as the protected routes.
routes.setErrorHandler(middleware.onError);
routes.get(
"/projects/:id",
{
preHandler: middleware.requirePermission(async (request) => ({
permission: "project:read",
resource: await loadTrustedProject((request.params as { id: string }).id),
})),
},
async (request) => {
const authorization = (request as RolebookRequest<typeof policy>).authorization;
return { ok: authorization !== undefined };
},
);
}); Authenticate in an earlier hook. The adapter does not authenticate sessions or read a binding from headers or decorated request fields.
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: (error: unknown, request: FastifyRequest, reply: FastifyReply) => Promise<void>;
readonly requirePermission: (
check:
| CheckRequest<TPermission>
| ((
request: FastifyRequest,
) => CheckRequest<TPermission> | Promise<CheckRequest<TPermission>>),
) => (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
} requirePermission(check): an asyncpreHandler, not anonRequesthook. It does nothing when the reply is already sent. Otherwise it gets the authorization (callinggetBindingand binding, or reusing the request’s binding whenreuseBindingPerRequestis on) and answersonUnauthorizedwhen there is none. It then setsrequest.authorization, resolvescheck(calling it with the request when it is a function), checks it, and answersonForbiddenon a denial. On an allow it returns and the route runs. Errors fromgetBindingor the check function go to Fastify’s error pipeline.onError: install withsetErrorHandler, not theonErrorhook, in the plugin scope of the protected routes. It leaves an already-sent reply alone, answersonForbiddenfor anAuthorizationError, and rethrows anything else to the parent or default error handler.
A responder (onUnauthorized, onForbidden, or a default) must finish the reply before it settles.
When it does not, the adapter throws, so the protected route never runs.
RolebookMiddlewareOptions
interface RolebookMiddlewareOptions<
TRole extends string = string,
TPermission extends string = string,
TResources extends ResourceDefinitions = ResourceDefinitions,
> {
readonly policy: RolebookPolicy<TRole, TPermission, TResources>;
readonly getBinding: (
request: FastifyRequest,
) => BindInput<TRole> | undefined | Promise<BindInput<TRole> | undefined>;
readonly onUnauthorized?: (
request: FastifyRequest,
reply: FastifyReply,
) => unknown | Promise<unknown>;
readonly onForbidden?: (
request: FastifyRequest,
reply: FastifyReply,
) => 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: reply.code(401).send({ error: "Unauthorized" }). A replacement must finish the reply. |
onForbidden | Default: reply.code(403).send({ error: "Forbidden" }). Used for denied checks and downstream AuthorizationErrors. A replacement must finish the reply. |
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. |
RolebookRequest
interface RolebookRequest<TPolicy extends RolebookPolicy> extends FastifyRequest {
authorization?: BoundAuthorizer<
RequestPermission<PolicyPermission<TPolicy>, TPolicy["resources"]>
>;
} The request type after requirePermission allows it. authorization is optional because a request
exists before the preHandler runs. Use RolebookRequest<typeof policy> in a handler to keep the
policy’s concrete permission union without augmenting every Fastify request. 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.