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

@tgtone/auth-sdk

v1.2.1

Published

SDK de autenticación JWT + Bearer Token para el ecosistema TGT One

Downloads

187

Readme

🔐 TGT One Auth Client SDK

SDK para integrar autenticación JWT + Bearer Token en aplicaciones del ecosistema TGT One.


📦 Instalación

npm install @tgtone/auth-sdk

🚀 Quick Start

Crear cuenta nueva (Signup)

import { TGTAuthClient } from '@tgtone/auth-sdk';

const auth = new TGTAuthClient({
  identityUrl: 'https://identity.tgtone.cl',
  appDomain: window.location.hostname,
  debug: true
});

// Signup - Crear nueva cuenta
const result = await auth.signup({
  email: '[email protected]',
  password: 'MiPassword123!', // Opcional - si no se provee, se genera automática
  firstName: 'Juan',
  lastName: 'Pérez',
  tenantName: 'Mi Empresa'
});

console.log('Cuenta creada:', result.user.email);

Iniciar sesión (Login)

// Login - Iniciar sesión
const result = await auth.login({
  email: '[email protected]',
  password: 'MiPassword123!'
});

// Si tiene MFA habilitado
if (result.requiresMfa) {
  const code = prompt('Ingresa código de Google Authenticator:');
  const session = await auth.verifyMfa(result.tempToken, code);
  console.log('Login con MFA exitoso');
} else {
  console.log('Login exitoso:', result.user.email);
}

Verificar sesión existente

// Verificar sesión (redirige automáticamente si no hay sesión)
const session = await auth.checkSession();
if (session) {
  console.log('Usuario:', session.user.email);
  console.log('Tenant:', session.tenantName);
  console.log('Roles:', session.user.roles);
  console.log('Expira:', session.expiresAt);
}

Verificar sesión SIN redirigir (nuevo en v1.2.0)

// Solo verifica si el usuario está logeado - NO redirige
const session = await auth.checkSessionSilent();

if (session) {
  console.log('Usuario logeado:', session.user.email);
  // Mostrar contenido privado
} else {
  console.log('Usuario no logeado');
  // Mostrar botón de login
}

// Verificar sin validar con backend (más rápido, solo valida JWT localmente)
const session = await auth.checkSessionSilent(false);

Redirigir a login con URL de retorno personalizada

// Configurar hosts permitidos para redirecciones
const auth = new TGTAuthClient({
  identityUrl: 'https://identity.tgtone.cl',
  appDomain: 'tgtone.cl',
  allowedRedirectHosts: ['tgtone.cl', 'www.tgtone.cl', 'app.tgtone.cl']
});

// Desde la página /precios, redirigir a login y volver después
const currentUrl = window.location.href; // https://tgtone.cl/precios
auth.redirectToLogin(currentUrl);

// Después del login, el usuario volverá a /precios

📋 API Principal

Autenticación

signup(data: SignupData): Promise<AuthResponse>

Crea una nueva cuenta de usuario y tenant.

const result = await auth.signup({
  email: '[email protected]',
  password: 'Pass123!', // Opcional
  firstName: 'María',
  lastName: 'García',
  tenantName: 'Empresa XYZ'
});

if (result.mustChangePassword) {
  // Mostrar formulario de cambio de contraseña
}

login(data: LoginData): Promise<AuthResponse>

Inicia sesión con email y contraseña.

const result = await auth.login({
  email: '[email protected]',
  password: 'Pass123!'
});

verifyMfa(tempToken: string, code: string): Promise<TGTSession>

Verifica código MFA después de login (si el usuario tiene MFA habilitado).

if (result.requiresMfa) {
  const session = await auth.verifyMfa(result.tempToken, '123456');
}

Sesión

checkSession(): Promise<TGTSession | null>

Verifica sesión existente, valida JWT y hace request al backend. Redirige automáticamente a login si no hay sesión válida.

Retorna: TGTSession con { user, tenantId, tenantName, expiresAt } o null.

Uso: Apps que requieren autenticación obligatoria (dashboards, consolas).

checkSessionSilent(validateWithServer = true): Promise<TGTSession | null> 🆕

Verifica sesión SIN redirigir automáticamente. Ideal para saber si el usuario está logeado sin forzar redirecciones.

Parámetros:

  • validateWithServer (boolean): Si es true, valida con /api/v1/auth/me. Si es false, solo valida JWT localmente (más rápido).

Retorna: TGTSession o null si no hay sesión.

Uso: Landing pages, páginas públicas que muestran contenido diferente si el usuario está logeado.

// Ejemplo: Mostrar "Ir al Dashboard" si está logeado, sino "Login"
const session = await auth.checkSessionSilent();
if (session) {
  showButton('Ir al Dashboard', '/dashboard');
} else {
  showButton('Iniciar Sesión', () => auth.redirectToLogin());
}

getSession(): TGTSession | null

Obtiene sesión completa en memoria (sin hacer request).

getTenantId(): string | null

Obtiene ID del tenant actual.

redirectToLogin(redirectUrl?: string): void 🆕

Redirige al login del Identity Provider.

Parámetros:

  • redirectUrl (string, opcional): URL completa a la que redirigir después del login. Solo funciona si el host está en allowedRedirectHosts.

Ejemplo:

// Redirigir a login y volver a la página actual
auth.redirectToLogin(window.location.href);

logout(): Promise<void>

Cierra sesión y limpia localStorage.

isRedirectAllowed(redirectUrl: string): boolean 🆕

Verifica si una URL de redirección está permitida según allowedRedirectHosts.

Ejemplo:

const url = 'https://tgtone.cl/precios';
if (auth.isRedirectAllowed(url)) {
  auth.redirectToLogin(url);
}

Autorización

hasRole(app: string, role: string): boolean

Verifica si el usuario tiene un rol específico en una app.

if (auth.hasRole('console', 'admin')) {
  // Mostrar admin panel
}

getRoles(app: string): string[]

Obtiene todos los roles del usuario en una app.

hasAccessToApp(app: string): boolean

Verifica si el usuario tiene acceso a una app.


🔄 Cómo Funciona

Flujo estándar (con checkSession())

  1. Usuario visita tu app
  2. checkSession() no encuentra token → redirige a Identity
  3. Usuario hace login en Identity
  4. Identity redirige a tu-app?token=eyJhbGci...
  5. SDK lee token de URL y guarda en localStorage
  6. SDK valida token con Authorization: Bearer ...
  7. Retorna usuario

Flujo sin redirección automática (con checkSessionSilent()) 🆕

  1. Usuario visita tu landing page
  2. checkSessionSilent() verifica si hay token válido
  3. Si hay sesión: muestra contenido personalizado (ej: "Ir al Dashboard")
  4. Si NO hay sesión: muestra botón de login
  5. Usuario hace click en login → redirectToLogin(window.location.href)
  6. Después del login, vuelve a la misma página

Caso de uso: Landing pages, páginas de precios, documentación pública que adapta contenido según si el usuario está logeado.


📚 Documentación Completa


🧪 Testing Rápido

// 1. Obtener token con curl
// curl -X POST https://identity-backend.run.app/api/v1/auth/login \
//   -d '{"email": "[email protected]", "password": "pass"}'

// 2. Guardar manualmente
localStorage.setItem('tgtone_auth_token', 'eyJhbGci...');

// 3. Usar
const user = await auth.checkSession();

👤 Estructura del Usuario

interface TGTUser {
  sub: string;              // ID
  email: string;
  name: string;
  tenant_id: string;
  tenant_name: string;
  roles: Record<string, string[]>; // { console: ['owner'], zenith: ['admin'] }
}

⚙️ Configuración

interface TGTAuthConfig {
  identityUrl: string;           // URL del backend Identity
  appDomain: string;             // Dominio de tu app
  allowedRedirectHosts?: string[]; // 🆕 Hosts permitidos para redirecciones (opcional)
  onAuthSuccess?: (session: TGTSession) => void;
  onAuthFailure?: () => void;
  debug?: boolean;
}

Ejemplo completo

const auth = new TGTAuthClient({
  identityUrl: 'https://identity.tgtone.cl',
  appDomain: 'tgtone.cl',
  
  // 🆕 Permitir redirecciones a estos dominios
  allowedRedirectHosts: [
    'tgtone.cl',
    'www.tgtone.cl',
    'app.tgtone.cl',
    'landing.tgtone.cl'
  ],
  
  // Callbacks opcionales
  onAuthSuccess: (session) => {
    console.log('Usuario autenticado:', session.user.email);
    // Redirigir a dashboard, cargar datos, etc.
  },
  
  onAuthFailure: () => {
    console.log('Sin sesión');
    // Mostrar landing page pública
  },
  
  debug: true // Logs en consola para desarrollo
});

🔐 Seguridad

  • Token storage: localStorage (tgtone_auth_token)
  • Transport: Authorization header con Bearer token
  • Validation: Backend valida JWT signature
  • No cookies: Todo con Bearer tokens

Versión: 1.2.0
Última actualización: 2025-10-30

🆕 Changelog

v1.2.0 (2025-10-30)

  • checkSessionSilent() - Verificar sesión sin redirigir automáticamente
  • allowedRedirectHosts - Configurar hosts permitidos para redirecciones
  • redirectToLogin(redirectUrl) - Redirigir con URL de retorno personalizada
  • isRedirectAllowed() - Validar URLs de redirección

v1.1.0 (2025-10-26)

  • signup() - Crear nuevas cuentas desde el SDK
  • login() - Iniciar sesión programáticamente
  • ✅ Soporte para MFA con verifyMfa()

v1.0.1 (2025-10-16)

  • Primera versión pública con SSO básico