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

wollen-auth-bypass

v1.0.1

Published

Componente de bypass de autenticación para testing automatizado en proyectos Wollen

Readme

@wollen/auth-bypass

Componente React para bypass de autenticación passwordless en testing automatizado. Diseñado para integrarse con Better Auth y facilitar las pruebas E2E en proyectos de Wollen.

🚀 Instalación

npm install @wollen/auth-bypass
# o
yarn add @wollen/auth-bypass
# o
pnpm add @wollen/auth-bypass

📖 Uso Básico

import { WollenAuthBypass } from '@wollen/auth-bypass';
import '@wollen/auth-bypass/styles.css';

function TestLoginPage() {
  return (
    <WollenAuthBypass
      apiUrl="https://api.tuempresa.com/auth/login"
      accessTokenKey="data.accessToken"
      refreshTokenKey="data.refreshToken"
      onSuccess={(tokens) => {
        console.log('Login exitoso:', tokens);
        // Redirigir o hacer algo después del login
      }}
      onError={(error) => {
        console.error('Error de login:', error);
      }}
    />
  );
}

⚙️ Props

| Prop | Tipo | Default | Descripción | |------|------|---------|-------------| | apiUrl | string | requerido | URL de la API para hacer login | | accessTokenKey | string | 'accessToken' | Key donde viene el access token en la respuesta (soporta dot notation) | | refreshTokenKey | string | 'refreshToken' | Key donde viene el refresh token en la respuesta (soporta dot notation) | | onSuccess | (tokens: AuthTokens) => void | - | Callback cuando el login es exitoso | | onError | (error: Error) => void | - | Callback cuando hay un error | | submitText | string | 'Iniciar sesión' | Texto del botón de submit | | loadingText | string | 'Autenticando...' | Texto del botón cuando está cargando | | emailPlaceholder | string | '[email protected]' | Placeholder del input de email | | passwordPlaceholder | string | '••••••••' | Placeholder del input de password | | className | string | '' | Clase CSS adicional para el contenedor | | setBetterAuthSession | boolean | true | Si debe setear automáticamente la sesión en Better Auth | | sessionCookieName | string | 'better-auth.session_token' | Nombre de la cookie para el token de sesión | | additionalHeaders | Record<string, string> | - | Headers adicionales para la petición | | additionalBody | Record<string, unknown> | - | Body adicional para mergear con email/password |

🔐 Integración con Better Auth

El componente automáticamente setea la sesión de Better Auth cuando el login es exitoso. Esto permite que Better Auth reconozca al usuario como autenticado sin necesidad de pasar por el flujo de passwordless.

<WollenAuthBypass
  apiUrl="/api/auth/bypass-login"
  setBetterAuthSession={true}
  sessionCookieName="better-auth.session_token"
/>

Endpoint de API Recomendado

Tu API debería tener un endpoint específico para testing que acepte email/password:

// pages/api/auth/bypass-login.ts o similar
import { auth } from '@/lib/auth'; // tu instancia de better-auth

export async function POST(request: Request) {
  const { email, password } = await request.json();
  
  // Verificar que solo funciona en entornos de testing
  if (process.env.NODE_ENV === 'production') {
    return Response.json({ error: 'Not allowed' }, { status: 403 });
  }
  
  // Validar credenciales de testing
  const user = await validateTestCredentials(email, password);
  
  if (!user) {
    return Response.json({ error: 'Invalid credentials' }, { status: 401 });
  }
  
  // Crear sesión con better-auth
  const session = await auth.api.signInEmail({
    body: { email, password },
    asResponse: false,
  });
  
  return Response.json({
    accessToken: session.token,
    refreshToken: session.refreshToken,
    user: session.user,
  });
}

🎨 Personalización de Estilos

Variables CSS

Puedes personalizar los estilos usando variables CSS:

.wollen-auth-bypass {
  --wollen-primary: #your-color;
  --wollen-primary-hover: #your-hover-color;
  --wollen-bg: #your-bg;
  --wollen-surface: #your-surface;
  --wollen-border: #your-border;
  --wollen-text: #your-text;
  --wollen-text-muted: #your-muted;
  --wollen-error: #your-error;
  --wollen-success: #your-success;
  --wollen-radius: 12px;
}

Estilos Personalizados

<WollenAuthBypass
  apiUrl="/api/login"
  className="my-custom-login"
/>

🧪 Uso en Tests E2E

Con Playwright

// tests/login.spec.ts
import { test, expect } from '@playwright/test';

test('should login via bypass', async ({ page }) => {
  await page.goto('/test-login');
  
  await page.fill('input[type="email"]', '[email protected]');
  await page.fill('input[type="password"]', 'test-password');
  await page.click('button[type="submit"]');
  
  // Esperar a que aparezca el mensaje de éxito
  await expect(page.locator('.wollen-auth-bypass__success')).toBeVisible();
  
  // Ahora el usuario está autenticado
  await page.goto('/dashboard');
  await expect(page).toHaveURL('/dashboard');
});

Con Cypress

// cypress/e2e/login.cy.ts
describe('Login Bypass', () => {
  it('should login successfully', () => {
    cy.visit('/test-login');
    
    cy.get('input[type="email"]').type('[email protected]');
    cy.get('input[type="password"]').type('test-password');
    cy.get('button[type="submit"]').click();
    
    cy.get('.wollen-auth-bypass__success').should('be.visible');
    
    // Usuario autenticado
    cy.visit('/dashboard');
    cy.url().should('include', '/dashboard');
  });
});

📦 Utilidades Exportadas

El paquete también exporta utilidades que puedes usar independientemente:

import { 
  performLogin,
  setBetterAuthSession,
  clearBetterAuthSession 
} from '@wollen/auth-bypass';

// Login manual
const tokens = await performLogin({
  apiUrl: '/api/login',
  credentials: { email: '[email protected]', password: '123' },
  accessTokenKey: 'token',
  refreshTokenKey: 'refresh',
});

// Setear sesión manualmente
setBetterAuthSession(tokens.accessToken);

// Limpiar sesión
clearBetterAuthSession();

🔒 Seguridad

⚠️ IMPORTANTE: Este componente está diseñado exclusivamente para entornos de testing.

NUNCA lo uses en producción o lo expongas en URLs públicas.

Recomendaciones:

  • Usa variables de entorno para habilitar/deshabilitar el bypass
  • Protege el endpoint de API con verificaciones de entorno
  • No incluyas credenciales de producción en los tests
// Solo renderizar en desarrollo/testing
{process.env.NODE_ENV !== 'production' && (
  <WollenAuthBypass apiUrl="/api/auth/bypass" />
)}

📝 TypeScript

El paquete incluye tipos completos:

import type { 
  WollenAuthBypassProps,
  AuthTokens,
  LoginCredentials,
  LoginOptions 
} from '@wollen/auth-bypass';

📄 Licencia

MIT © Wollen