npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

exguard-backend

v1.0.40

Published

ExGuard backend SDK for user role and permission validation

Readme

ExGuard Backend SDK

Simple RBAC/ABAC permission guard for NestJS.

Installation

npm install exguard-backend

Quick Setup

1. Copy Guard Files

Create src/exguard/exguard.guard.ts:

import { Injectable, CanActivate, ExecutionContext, UnauthorizedException, ForbiddenException, Inject, Optional } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ExGuardBackend } from 'exguard-backend';

export const EXGUARD_PERMISSIONS_KEY = 'exguard_permissions';
export const EXGUARD_ROLES_KEY = 'exguard_roles';

@Injectable()
export class ExGuardPermissionGuard implements CanActivate {
  constructor(
    @Optional() @Inject('EXGUARD_INSTANCE') private exGuard: ExGuardBackend,
    private reflector: Reflector,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = this.extractToken(request);

    if (!token) throw new UnauthorizedException('No token provided');
    if (!this.exGuard) return true;

    const authResult = await this.exGuard.authenticate({ token, request });

    if (!authResult.allowed) throw new ForbiddenException(authResult.error || 'Access denied');
    if (!authResult.user) throw new ForbiddenException('User not found');

    const handler = context.getHandler();
    const permMeta = this.reflector.get(EXGUARD_PERMISSIONS_KEY, handler);

    if (permMeta) {
      const { permissions, requireAll } = permMeta;
      const userPermissions = authResult.user.modules?.flatMap(m => m.permissions) || [];

      if (requireAll) {
        if (!permissions.every(p => userPermissions.includes(p))) {
          throw new ForbiddenException('Insufficient permissions');
        }
      } else {
        if (!permissions.some(p => userPermissions.includes(p))) {
          throw new ForbiddenException('Insufficient permissions');
        }
      }
    }

    request.user = authResult.user;
    return true;
  }

  private extractToken(request: any): string | null {
    const auth = request.headers?.authorization;
    return auth?.startsWith('Bearer ') ? auth.substring(7) : request.headers?.['x-access-token'] || null;
  }
}

export function RequirePermissions(permissions: string[], requireAll = false) {
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    Reflect.defineMetadata(EXGUARD_PERMISSIONS_KEY, { permissions, requireAll }, descriptor.value);
  };
}

Create src/exguard/exguard.module.ts:

import { Module, Global, DynamicModule } from '@nestjs/common';
import { ExGuardBackend } from 'exguard-backend';

@Global()
@Module({})
export class ExGuardModule {
  static forRoot(options: { baseUrl: string; apiKey: string; cache?: { enabled?: boolean; ttl?: number } }): DynamicModule {
    const exGuard = new ExGuardBackend({
      baseUrl: options.baseUrl,
      apiKey: options.apiKey,
      cache: options.cache || { enabled: true, ttl: 300000 },
    });

    return {
      module: ExGuardModule,
      providers: [
        { provide: 'EXGUARD_INSTANCE', useValue: exGuard },
      ],
      exports: ['EXGUARD_INSTANCE'],
    };
  }
}

2. Configure AppModule

import { Module } from '@nestjs/common';
import { ExGuardModule } from './exguard/exguard.module';

@Module({
  imports: [
    ExGuardModule.forRoot({
      baseUrl: 'https://api.exguard.com',
      apiKey: process.env.EXGUARD_API_KEY,
      cache: { enabled: true, ttl: 300000 },
    }),
  ],
})
export class AppModule {}

3. Use in Controllers

import { Controller, Get, Post, UseGuards } from '@nestjs/common';
import { ExGuardPermissionGuard, RequirePermissions } from '@/exguard/exguard.guard';

@Controller('items')
@UseGuards(ExGuardPermissionGuard)
export class ItemsController {
  
  @Get()
  @RequirePermissions(['item:read'])
  findAll() { }

  @Post()
  @RequirePermissions(['item:create'])
  create() { }

  @Get('drafts')
  @RequirePermissions(['item:read_draft', 'item:admin']) // ANY of these
  findDrafts() { }

  @Delete(':id')
  @RequirePermissions(['item:delete', 'admin'], true) // ALL of these
  delete() { }
}

Token Format

The guard extracts token from:

  • Authorization: Bearer <token> header
  • x-access-token header

Configuration

| Option | Type | Default | Description | |--------|------|---------|-------------| | baseUrl | string | required | ExGuard API URL | | apiKey | string | required | Your API key | | cache.enabled | boolean | true | Enable caching | | cache.ttl | number | 300000 | Cache TTL in ms (5 min) |

Express/Fastify (Non-NestJS)

import { createExGuardExpress } from 'exguard-backend';

const guard = createExGuardExpress({
  baseUrl: 'https://api.exguard.com',
  apiKey: process.env.EXGUARD_API_KEY,
});

// Use as middleware
app.use('/api', guard.requirePermissions(['item:read']));

License

MIT