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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@anpdgovbr/rbac-provider

v0.2.0

Published

Contratos de provider/identidade e cache TTL para RBAC.

Downloads

74

Readme

@anpdgovbr/rbac-provider

npm version TypeScript License: MIT

Contratos e abstrações para providers de RBAC — Interfaces padronizadas para resolução de identidade e permissões.

✨ Características

  • 🔌 Pluggable — Interfaces padronizadas para diferentes fontes de dados
  • Cache TTL — Sistema de cache em memória com expiração configurável
  • 🎯 Type Safety — Contratos rigorosos para implementações
  • 🔄 Invalidação — Cache seletivo por identidade ou global
  • 🚀 Performance — Otimizado para alta concorrência

📦 Instalação

npm install @anpdgovbr/rbac-provider@beta

🎯 Conceitos Principais

Provider de Permissões

Interface padrão para resolução de permissões por identidade:

interface PermissionsProvider {
  getPermissionsByIdentity(identity: string): Promise<PermissionsMap>
  invalidate(identity?: string): void
}

Resolver de Identidade

Interface para extrair identidade de requests:

interface IdentityResolver<Req = unknown> {
  resolve(req: Req): Promise<Identity>
}

🎯 Uso Básico

Provider Customizado

import { PermissionsProvider } from "@anpdgovbr/rbac-provider"
import { toPermissionsMap } from "@anpdgovbr/rbac-core"

class DatabasePermissionsProvider implements PermissionsProvider {
  constructor(private db: Database) {}

  async getPermissionsByIdentity(email: string): Promise<PermissionsMap> {
    const permissions = await this.db.getUserPermissions(email)
    return toPermissionsMap(permissions)
  }

  invalidate(email?: string): void {
    // Limpar cache específico se necessário
    if (email) {
      this.db.clearUserCache(email)
    } else {
      this.db.clearAllCache()
    }
  }
}

Cache TTL Decorator

import { withTTLCache } from "@anpdgovbr/rbac-provider"

const baseProvider = new DatabasePermissionsProvider(db)

// Adiciona cache de 5 minutos
const cachedProvider = withTTLCache(baseProvider, 5 * 60 * 1000)

// Uso normal - cache transparente
const permissions = await cachedProvider.getPermissionsByIdentity("[email protected]")

// Invalidação seletiva
cachedProvider.invalidate("[email protected]") // apenas este usuário
cachedProvider.invalidate() // todos os usuários

Resolver de Identidade NextAuth

import { IdentityResolver } from "@anpdgovbr/rbac-provider"
import { getServerSession } from "next-auth"

class NextAuthIdentityResolver implements IdentityResolver<Request> {
  async resolve(req: Request): Promise<Identity> {
    const session = await getServerSession()

    if (!session?.user?.email) {
      throw new Error("Usuário não autenticado")
    }

    return {
      id: session.user.id,
      email: session.user.email,
    }
  }
}

🔧 API Completa

PermissionsProvider

Interface principal para providers de permissões.

interface PermissionsProvider {
  /**
   * Resolve permissões para uma identidade específica
   * @param identity - Email ou ID do usuário
   * @returns Mapa de permissões resolvidas
   */
  getPermissionsByIdentity(identity: string): Promise<PermissionsMap>

  /**
   * Invalida cache de permissões
   * @param identity - Identidade específica (opcional)
   */
  invalidate(identity?: string): void
}

IdentityResolver<Req>

Interface para resolução de identidade a partir de requests.

interface Identity {
  id: string
  email?: string
}

interface IdentityResolver<Req = unknown> {
  /**
   * Extrai identidade do request
   * @param req - Request object (Request, NextRequest, etc.)
   * @returns Identidade resolvida
   * @throws Error se não autenticado
   */
  resolve(req: Req): Promise<Identity>
}

withTTLCache(provider, ttlMs)

Decorator que adiciona cache TTL a qualquer provider.

Parâmetros:

  • provider: PermissionsProvider — Provider base
  • ttlMs: number — TTL em milissegundos

Retorna: PermissionsProvider — Provider com cache

// Cache de 10 minutos
const cached = withTTLCache(baseProvider, 10 * 60 * 1000)

Comportamento:

  • Cache por identidade individual
  • Expiração automática após TTL
  • Invalidação seletiva ou global
  • Thread-safe para concorrência

🧪 Exemplos Avançados

Provider com Fallback

class FallbackPermissionsProvider implements PermissionsProvider {
  constructor(
    private primary: PermissionsProvider,
    private fallback: PermissionsProvider
  ) {}

  async getPermissionsByIdentity(identity: string): Promise<PermissionsMap> {
    try {
      return await this.primary.getPermissionsByIdentity(identity)
    } catch (error) {
      console.warn(`Primary provider failed, using fallback:`, error)
      return await this.fallback.getPermissionsByIdentity(identity)
    }
  }

  invalidate(identity?: string): void {
    this.primary.invalidate(identity)
    this.fallback.invalidate(identity)
  }
}

Provider com Métricas

class MetricsPermissionsProvider implements PermissionsProvider {
  constructor(
    private provider: PermissionsProvider,
    private metrics: MetricsCollector
  ) {}

  async getPermissionsByIdentity(identity: string): Promise<PermissionsMap> {
    const startTime = Date.now()

    try {
      const result = await this.provider.getPermissionsByIdentity(identity)

      this.metrics.recordDuration("rbac.provider.success", Date.now() - startTime)
      this.metrics.increment("rbac.provider.calls.success")

      return result
    } catch (error) {
      this.metrics.recordDuration("rbac.provider.error", Date.now() - startTime)
      this.metrics.increment("rbac.provider.calls.error")
      throw error
    }
  }

  invalidate(identity?: string): void {
    this.metrics.increment("rbac.provider.invalidations")
    this.provider.invalidate(identity)
  }
}

Composição de Providers

// Camada completa com cache, métricas e fallback
const composedProvider = withTTLCache(
  new MetricsPermissionsProvider(
    new FallbackPermissionsProvider(
      new PrismaPermissionsProvider(prisma),
      new StaticPermissionsProvider(defaultPermissions)
    ),
    metricsCollector
  ),
  5 * 60 * 1000 // 5 minutos de cache
)

🔧 Desenvolvimento

# Build
npm run build

# Type checking
npm run typecheck

# Testes
npm test

📚 Documentação Relacionada

📄 Licença

MIT © 2024 ANPD (Agência Nacional de Proteção de Dados)