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

tokenea-auth-component

v1.2.4

Published

Universal authentication component with WebAuthn Passkeys support

Readme

🔐 Tokenea Auth Component

Un componente React universal para autenticación con WebAuthn Passkeys, basado en la implementación exitosa de Tokenea.

✨ Características

  • 🔐 WebAuthn Passkeys: Autenticación biométrica sin contraseñas
  • 🎯 Conditional UI: Autocompletado nativo de passkeys
  • 📱 Responsive: Diseño adaptativo para móvil y desktop
  • 🔄 Flujo progresivo: Registro y login unificados
  • 💾 Sistema de recuperación: Códigos, QR y email
  • ⚡ Plug & Play: Fácil integración con tu backend PHP existente

🚀 Instalación

npm install @tokenea/auth-component

📋 Uso Básico

import TokeneaAuth from '@tokenea/auth-component';

function App() {
  const config = {
    apiEndpoints: {
      registerOptions: '/api/register-options.php',
      registerVerify: '/api/register-verify.php',
      loginOptions: '/api/login-options.php',
      loginVerify: '/api/login-verify.php',
      sendReminder: '/api/send-reminder.php' // Opcional
    },
    rpId: 'tu-dominio.com',
    rpName: 'Tu App',
    redirectUrls: {
      dashboard: '/dashboard'
    }
  };

  const handleSuccess = (result) => {
    console.log('✅ Autenticación exitosa:', result);
    // Manejar éxito (guardar token, redirigir, etc.)
  };

  const handleError = (error) => {
    console.error('❌ Error:', error);
    // Manejar error
  };

  return (
    <TokeneaAuth
      config={config}
      onSuccess={handleSuccess}
      onError={handleError}
      onModeChange={(mode) => console.log('Modo:', mode)}
    />
  );
}

⚙️ Configuración

Configuración Básica

const config = {
  // 🔗 Endpoints de tu API PHP (REQUERIDO)
  apiEndpoints: {
    registerOptions: '/api/register-options.php',
    registerVerify: '/api/register-verify.php',
    loginOptions: '/api/login-options.php',
    loginVerify: '/api/login-verify.php',
    sendReminder: '/api/send-reminder.php' // Opcional
  },
  
  // 🌐 Configuración WebAuthn (REQUERIDO)
  rpId: 'tu-dominio.com',
  rpName: 'Tu Aplicación',
  
  // 🔄 URLs de redirección (Opcional)
  redirectUrls: {
    dashboard: '/dashboard',
    login: '/login'
  }
};

Callbacks

const callbacks = {
  // ✅ Éxito en autenticación
  onSuccess: (result) => {
    // result contiene: { success, token, user, credential }
    localStorage.setItem('authToken', result.token);
    window.location.href = '/dashboard';
  },
  
  // ❌ Error en autenticación
  onError: (error) => {
    console.error('Error de autenticación:', error);
    // Mostrar notificación de error
  },
  
  // 🔄 Cambio de modo
  onModeChange: (mode) => {
    // Modos: 'initial', 'login', 'register', 'recovery-step'
    console.log('Modo actual:', mode);
  }
};

🏗️ Backend PHP

El componente está diseñado para funcionar con tu backend PHP existente. Necesitas estos endpoints:

1. register-options.php

// Generar opciones de registro
POST /api/register-options.php
Body: { "username": "[email protected]", "displayName": "Usuario" }
Response: { "success": true, "options": {...} }

2. register-verify.php

// Verificar registro
POST /api/register-verify.php
Body: { "id": "...", "rawId": "...", "response": {...} }
Response: { "success": true, "token": "...", "user": {...} }

3. login-options.php

// Generar opciones de login
POST /api/login-options.php
Body: { "username": "[email protected]" } // Opcional para Conditional UI
Response: { "challenge": "...", "allowCredentials": [...] }

4. login-verify.php

// Verificar login
POST /api/login-verify.php
Body: { "id": "...", "rawId": "...", "response": {...} }
Response: { "success": true, "token": "...", "user": {...} }

🎨 Personalización

Estilos CSS

El componente usa Tailwind CSS. Puedes personalizar los estilos:

/* Personalizar colores primarios */
.tokenea-auth {
  --primary-color: #667eea;
  --secondary-color: #764ba2;
}

/* Personalizar el contenedor */
.tokenea-auth .container {
  max-width: 600px;
  border-radius: 20px;
}

Temas

const config = {
  // ... otras opciones
  ui: {
    theme: 'dark', // 'light', 'dark', 'auto'
    showRecovery: true,
    showPasskeyEducation: true,
    customStyles: 'mi-tema-personalizado'
  }
};

🔧 Utilidades Exportadas

import { 
  base64urlDecode,
  base64urlEncode,
  isWebAuthnSupported,
  isConditionalUISupported,
  getDeviceInfo,
  apiRequest,
  isValidEmail,
  getPasswordStrength
} from '@tokenea/auth-component';

// Verificar soporte WebAuthn
if (isWebAuthnSupported()) {
  console.log('✅ WebAuthn soportado');
}

// Verificar soporte Conditional UI
const conditionalSupported = await isConditionalUISupported();
console.log('Conditional UI:', conditionalSupported);

// Información del dispositivo
const device = getDeviceInfo();
console.log('Navegador:', device.browser);

📱 Compatibilidad

Navegadores Soportados

  • Chrome 67+ - Soporte completo
  • Safari 13+ - Soporte completo
  • Firefox 60+ - Soporte completo
  • Edge 79+ - Soporte completo
  • ⚠️ Samsung Internet - Limitado

Dispositivos

  • 📱 iOS 16+ - Face ID, Touch ID
  • 🤖 Android 9+ - Huella, Face Unlock
  • 💻 Windows 10+ - Windows Hello
  • 🍎 macOS 13+ - Touch ID

🔍 Debugging

// Habilitar logs detallados
window.TOKENEA_DEBUG = true;

// Los logs aparecerán en la consola:
// 🔵 [base64urlDecode] Input: ...
// 🟢 [base64urlEncode] Output: ...
// 🌐 [API] POST /api/register-options.php
// 📤 [API] Request body: ...
// 📥 [API] Response data: ...

🚨 Manejo de Errores

const handleError = (error) => {
  switch (error) {
    case 'WebAuthn is not supported in this browser':
      // Mostrar mensaje de navegador no compatible
      break;
    case 'Registration cancelled or not authorized':
      // Usuario canceló el registro
      break;
    case 'This credential is already registered':
      // Credencial duplicada
      break;
    default:
      // Error genérico
      console.error('Error:', error);
  }
};

📦 Build y Distribución

# Desarrollo
npm run dev

# Build para producción
npm run build

# Preview del build
npm run preview

# Publicar a NPM
npm publish

🤝 Contribuir

  1. Fork el repositorio
  2. Crea una rama para tu feature (git checkout -b feature/nueva-funcionalidad)
  3. Commit tus cambios (git commit -am 'Añadir nueva funcionalidad')
  4. Push a la rama (git push origin feature/nueva-funcionalidad)
  5. Crea un Pull Request

📄 Licencia

MIT © Tokenea

🆘 Soporte


¡Hecho con ❤️ por el equipo de Tokenea!