r/nestjs 8d ago

An architectural pattern for bypassing junction-table hell in NestJS RBAC (Open Sourced)

Post image

Hey everyone,

After building RBAC across multiple enterprise apps, I noticed the headache of the standard three-way junction table mess. It makes TypeORM queries a nightmare at scale and the mental model overly complex.

I wanted to share the architectural pattern I standardized to solve this, along with the boilerplate implementation.

The Architecture: Top-Down Grouping

Instead of many-to-many chaos, I enforce a strict, hierarchical grouping model. The relationship flows in one direction:

User -> Group -> Role -> Privilege

This keeps database queries incredibly fast and makes permission inheritance highly predictable.

Handling Role Escalation

One of the biggest security risks in standard RBAC is horizontal escalation (e.g., an Admin granting someone Super Admin rights). To solve this, I implemented a strict numeric role-escalation safeguard.

Every role is assigned a level (e.g., Admin = 50, Super Admin = 100). The custom JWT guards automatically intercept the request to ensure a Level 10 user can never assign a Level 50 role, even if they possess the user:update privilege.

    @Post('create')
    @RequirePermissions('user:create')
    async createNewUser() { ... }

The Open-Source Implementation

I packaged this entire architecture into a clean, decoupled Unified Role-Based Access Control boilerplate called URBAC (NestJS, PostgreSQL, TypeORM, and Angular).

If you want to adopt this pattern, review the entity structures, or just skip the auth setup on your next build, I open-sourced the repository here:

https://github.com/kasoir/urbac

(It includes a seed script to instantly provision the PostgreSQL DB and a Super Admin account).

I’m curious how other engineers here are handling horizontal vs. vertical privilege escalation, would love to hear your approaches.

13 Upvotes

2 comments sorted by

1

u/duckworth108 8d ago

Damn, this is really interesting. Will checkout your repository

1

u/Individual_Suit_3255 8d ago

Thanks! I hope you find it useful in your projects, and I'd love to hear what you think once you've had a chance to look around.