Policies
Official @nestjs/authorization policies, plus what this package adds — @PolicyFor, the AuthzPolicy base with superAdmin and the external engine, and PolicyIndex.
Policies are the official package's: a class marked @Policy() from @nestjs/authorization,
one method per ability, registered as a provider. See the
official docs for the contract. In short:
- an ability is
ability(user | null, ...args); only a literaltrueallows; - a policy may define
before(user, ability, ...args):trueallows,falsedenies, anything else falls through to the ability; - policies must be singletons, and a guest reaches them as
null(a guest denial is a 401).
This page covers the extras.
@PolicyFor(Resource)
import { Policy } from '@nestjs/authorization';
import { PolicyFor } from '@dudousxd/nestjs-authz';
@Policy()
@PolicyFor(Post)
export class PostPolicy {
update(user: User | null, post: Post) {
return post.authorId === user?.id;
}
create(user: User | null) {
return user?.verified === true;
}
}The link is what lets the extras go from a resource to its policy: gate.allows('update', post),
gate.allows('create', Post), gate.scope(Post), the Inertia/codegen ability maps. The official
API never needs it, and @PolicyFor applies @Policy() itself.
getPolicyResource(PostPolicy) reads the link back (Post), policyForResource(Post) the other
way, and policyLinks() lists them all.
A resource has one policy, and links are process-wide. @PolicyFor(Post) throws when Post is
already linked to a different policy; the same pair again is a no-op, and a re-declared class of
the same name (a hot reload, a test helper) replaces the link.
A string ability without a resource (gate.allows('create')) looks for a linked policy that
defines it. Two linked policies defining create throw AmbiguousAbilityException; pass the
class (gate.allows('create', Post)) or the policy (gate.allows(PostPolicy, 'create')).
AuthzPolicy: super-admin and the external engine
The official guard runs only each policy's own before(), so a global "super-admins may do
anything" needs every policy to ask. Extend AuthzPolicy:
import { AuthzPolicy, PolicyFor } from '@dudousxd/nestjs-authz';
@Policy()
@PolicyFor(Post)
export class PostPolicy extends AuthzPolicy {
update(user: User | null, post: Post) {
return post.authorId === user?.id;
}
}
AuthzModule.forRoot({ superAdmin: (user, ability, resource) => user?.isRoot === true });AuthzPolicy.before(user, ability, ...args) asks:
superAdmin(user, ability, resource)—trueallows. The resource is the ability's first argument (byId(Post)'s record), so the hook can scope the bypass.- the
DECISION_PROVIDER, when one is registered — its allow or deny is final,undefinedabstains. See External engines.
Then the ability decides. To add your own before(), override it and call
super.before(user, ability, ...args) first. A policy that cannot extend AuthzPolicy calls
superAdminBefore(user, ability, resource) and decisionProviderBefore(user, ability, resource)
from its own before().
RolePolicy and PermissionPolicy extend AuthzPolicy but ask only superAdmin: their
abilities name roles and permissions, not resources.
superAdmin is not global in the guard: a policy that neither extends AuthzPolicy nor calls
superAdminBefore never sees it on routes.
Query scopes
A policy may declare scope(user, entity) returning a ScopeConstraint built with eq, where,
and, or (or true / false). gate.scope(Post) runs it, and the ORM adapters' applyScope
turn it into a parameterized WHERE. scope is not an ability. See Gates.
PolicyIndex
The official registry is not exported, so PolicyIndex finds the official policies the same way
(the DiscoveryService, by token or marked metatype). It is what the extras use:
constructor(private readonly index: PolicyIndex) {}
this.index.all(); // [{ policy, instance, resource }], built-ins included
this.index.resourcePolicies(); // without RolePolicy / PermissionPolicy / GatePolicy
this.index.policyOf(post); // PostPolicy, by the instance's class
this.index.classAbilities(); // abilities that need no record, per policyclassAbilities() is what the Inertia integration shares with the
frontend.
The scan is cached. It runs again when a module or provider is added (a lazy module) or when a policy was not instantiated yet.
Next steps
Getting Started
Install @nestjs/authorization and @dudousxd/nestjs-authz, import both modules, write an official policy, guard a route, and check abilities in a service.
Gates
The service-layer Gate over the official AuthorizationService — policy-class and string checks, ad-hoc gates with define, forUser and BoundGate, allowsMany, roles and query scopes.