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

mreauth-bridge

v1.2.4

Published

Una librería JavaScript ligera para la integración con Authentik para autenticación y gestión de sesiones.

Readme

MRE Auth Bridge

Librería para gestionar la autenticación con Authentik en aplicaciones web, especialmente diseñada para los servicios del Ministerio de Relaciones Exteriores.

Instalación

npm install mreauth-bridge
# o
pnpm add mreauth-bridge

Uso Básico

<!DOCTYPE html>
<html>
  <head>
    <title>MRE Auth Bridge Test</title>
    <script src="/mre-auth-bridge.umd.js"></script>
    <script>
      const authManager = new MreAuthBridge({
        authentikBaseUrl: "https://auth.rree.gob.bo",
        authentikClientId: "YOUR_CLIENT_ID",
        authentikRedirectUrl: window.location.origin,
        logoutRedirectUrl: "https://auth.rree.gob.bo/application/o/orges/end-session/",
        authentikScope: "openid email profile offline_access",
        authentikTypeClient: "public",
        onLoginSuccess: (token) => {
          console.log('Token recibido:', token);
        },
        onRefreshSuccess: (token) => {
          console.log('Token refrescado:', token);
        },
        onLoginError: (err) => {
          console.error('Error de autenticación:', err);
        },
        onCodeStateValid: (code, state, valid) => {
          console.log('Validación:', {code, state, valid});
        },
      });

      window.addEventListener("load", () => {
        authManager.init();
      });
    </script>
  </head>
  <body>
    <button onclick="authManager.login()">Iniciar Sesión</button>
    <button onclick="authManager.logout()">Cerrar Sesión</button>
    <div id="userInfo"></div>
  </body>
</html>

Integración con Vue.js (Vue 3 + TypeScript)

Para facilitar la integración en aplicaciones Vue.js, la librería mreauth-bridge ahora incluye un plugin oficial que maneja la inicialización y expone un estado reactivo y métodos a través de un composable.

1. Instalación del Plugin

Primero, asegúrate de que mreauth-bridge esté instalado en tu proyecto Vue.js:

npm install mreauth-bridge
# o
pnpm add mreauth-bridge

2. Configuración del Plugin en tu Aplicación Vue

En tu archivo main.ts (o similar, donde inicializas tu aplicación Vue), importa y usa el MreAuthPlugin.

// main.ts o src/boot/auth.ts (para Quasar/Nuxt)
import { createApp } from 'vue';
import App from './App.vue';
import { MreAuthPlugin } from 'mreauth-bridge/dist/vue-plugin'; // Importa el plugin

const app = createApp(App);

// Configuración para el plugin de autenticación
const authOptions = {
  authentikBaseUrl: 'https://auth.rree.gob.bo', // Reemplaza con tu URL base de Authentik
  authentikClientId: 'YOUR_CLIENT_ID', // Reemplaza con tu Client ID
  authentikRedirectUrl: window.location.origin + '/callback', // Reemplaza con tu URL de redirección
  logoutRedirectUrl: 'https://auth.rree.gob.bo/application/o/orges/end-session/', // Opcional: URL de redirección al cerrar sesión
  authentikScope: 'openid email profile offline_access', // Scopes requeridos
  // authentikTypeClient: 'confidential', // Descomentar para el modo 'confidential'
  
  // Callbacks opcionales
  onLoginSuccess: (response) => {
    console.log('Login exitoso desde el plugin:', response);
    // Aquí puedes manejar redirecciones o actualizaciones de UI post-login
  },
  onLoginError: (error) => {
    console.error('Error de login desde el plugin:', error);
    // Manejo de errores de autenticación
  },
  onCodeStateValid: (response) => {
    // Este callback solo se ejecuta en modo 'confidential'
    console.log('Código y estado listos para backend (modo confidential):', response);
    // En este punto, tu backend debería intercambiar el 'code' por tokens.
    // Puedes enviar 'response.code', 'response.state', y 'response.valid' a tu API.
  },
};

// Usa el plugin con tu configuración
app.use(MreAuthPlugin, authOptions);

app.mount('#app');

Nota sobre authentikTypeClient:

  • Si no se especifica o se establece como 'public', el plugin manejará automáticamente el intercambio de tokens (flujo PKCE).
  • Si se establece como 'confidential', el plugin solo te proporcionará el code, state y valid a través del callback onCodeStateValid, esperando que tu backend realice el intercambio de tokens.

3. Uso del Composable useAuth() en Componentes

El plugin provee un composable useAuth() que te permite acceder al estado de autenticación y a los métodos de la librería desde cualquier componente de Vue.

// src/composables/useAuth.ts (opcional, puedes usarlo directamente en componentes)
import { useAuth as useAuthBridge } from 'mreauth-bridge/dist/vue-plugin';

// Re-exporta el composable para una importación más limpia en tu proyecto
export function useAuth() {
  return useAuthBridge();
}

Luego, en tus componentes Vue:

<template>
  <div>
    <div v-if="state.isLoading">Cargando autenticación...</div>
    <div v-else-if="state.error" style="color: red;">Error: {{ state.error }}</div>
    <div v-else>
      <p v-if="state.isAuthenticated">
        ¡Bienvenido, {{ state.user?.preferred_username || state.user?.name || 'Usuario' }}!
      </p>
      <p v-else>No autenticado.</p>

      <button @click="login" :disabled="state.isLoading || state.isAuthenticated">
        Iniciar Sesión
      </button>
      <button @click="logout" :disabled="state.isLoading || !state.isAuthenticated">
        Cerrar Sesión
      </button>

      <div v-if="state.token">
        <h3>Token de Acceso (parcial)</h3>
        <pre>{{ state.token.access_token.substring(0, 30) }}...</pre>
        <h3>Información del Usuario (decodificada del token)</h3>
        <pre>{{ JSON.stringify(state.user, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useAuth } from '@/composables/useAuth'; // O 'mreauth-bridge/dist/vue-plugin' si no creas un archivo local

const { state, login, logout } = useAuth();

// 'state' es un objeto reactivo que contiene:
// - isAuthenticated: boolean
// - token: Token | null (el objeto de token completo)
// - user: object | null (el payload decodificado del access_token)
// - isLoading: boolean (indica si el proceso de autenticación está en curso)
// - error: string | null (cualquier error ocurrido)

// 'login' es la función para iniciar el flujo de autenticación
// 'logout' es la función para cerrar la sesión
</script>

<style scoped>
pre {
  background-color: #eee;
  padding: 10px;
  border-radius: 5px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>

</script>

API

Configuración

| Propiedad | Tipo | Descripción | |-----------|------|-------------| | authentikBaseUrl | string | URL del servidor Authentik | | authentikClientId | string | ID del cliente OAuth | | authentikRedirectUrl | string | URL de redirección post-login | | logoutRedirectUrl | string | URL de redirección post-logout | | authentikScope | string | Scopes OAuth (default: "openid email profile offline_access") | | authentikTypeClient | string | Tipo de cliente ("public"/"confidential") | | activeSessionMonitor | boolean | Habilitar monitoreo de sesión |

Métodos Principales

  • init(): Inicializa el gestor de autenticación
  • login(): Inicia el flujo de autenticación
  • logout(): Cierra la sesión actual
  • hasValidToken(): Verifica existencia de token válido
  • getUserInfo(): Obtiene datos del usuario autenticado
  • refreshToken(): Renueva el token de acceso
  • getToken(): Obtiene el token actual

Eventos

  • onLoginSuccess(token): Éxito en autenticación
  • onLoginError(error): Error en autenticación
  • onRefreshSuccess(token): Token renovado exitosamente
  • onLogout(): Sesión cerrada
  • onCodeStateValid(code, state, valid): Validación de código/estado

Publicación en NPM

  1. Login en npm:
npm login
  1. Construir la librería:
npm run build
  1. Probar el paquete localmente:
npm pack
  1. Publicar:
npm publish

Para actualizaciones:

npm version patch|minor|major
npm publish

Licencia

MIT

Soporte

Para reportar problemas o solicitar funcionalidades, por favor usar el issue tracker