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

energy-community-auth-sdk

v0.3.2

Published

Typed JS/TS SDK for energy-community-auth auth_service

Readme

energy-community-auth-sdk

SDK de TypeScript/JavaScript para consumir el servicio de autenticación de Energy Community.

Instalacion

npm i energy-community-auth-sdk

Uso rapido

import { AuthServiceSdk } from 'energy-community-auth-sdk';

const sdk = new AuthServiceSdk({
  appId: 'tu-app-id',
  apiKey: 'tu-api-key',
});

API disponible

Todas las funciones están en sdk.auth.

Registrar usuario

const registration = await sdk.auth.register({
  firstName: 'Ada',
  lastName: 'Lovelace',
  email: '[email protected]',
  password: 'StrongPass123!',
});

console.log(registration.user.id, registration.user.email);

Login

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

console.log(loginResult.user.id, loginResult.user.email);

Refresh token

const tokens = await sdk.auth.refresh({
  refreshToken: tokens.refreshToken,
});

Validar token

const result = await sdk.auth.validate({
  accessToken: tokens.accessToken,
});

Logout

await sdk.auth.logout(tokens.accessToken);

Listar sesiones

const sessions = await sdk.auth.sessions(tokens.accessToken);

Revocar una sesion

await sdk.auth.revokeSession(tokens.accessToken, 'session-id');

Consultar usuario por id

const user = await sdk.auth.getUserById('8db5f3bb-4f87-4a31-89fc-351b8eb6360c');

Solicitar recuperación de contraseña

Envía un correo con un enlace para restablecer la contraseña.

await sdk.auth.requestPasswordRecovery({
  email: '[email protected]',
});

Nota: Por seguridad, siempre devuelve éxito aunque el email no exista (para evitar enumeración).

Validar token de recuperación

Verifica si un token de recuperación es válido y no ha sido usado.

const validation = await sdk.auth.validateRecoveryToken({
  token: 'jwt-token-recibido',
});

if (validation.valid) {
  console.log('Token válido para:', validation.email);
} else {
  console.log('Token inválido o ya usado');
}

Restablecer contraseña

Actualiza la contraseña usando un token válido.

await sdk.auth.resetPassword({
  token: 'jwt-token-recibido',
  password: 'NuevaContraseña123!',
});

Nota: Al restablecer la contraseña, todas las sesiones activas se revocan automáticamente por seguridad.

Tipos principales

  • RequestPasswordRecoveryRequest
  • ValidateRecoveryTokenRequest
  • ValidateRecoveryTokenResponse
  • ResetPasswordRequest
  • RegisterRequest
  • LoginRequest
  • RefreshRequest
  • ValidateTokenRequest
  • UserResponse
  • RegisterResponse
  • LoginResponse
  • TokensResponse
  • ValidateTokenResponse
  • SessionResponse
  • SuccessResponse

También puedes importarlos directamente:

import type { TokensResponse, SessionResponse } from 'energy-community-auth-sdk';

Manejo de errores

El SDK lanza errores simples con status y message:

import { AuthServiceSdkError } from 'energy-community-auth-sdk';

try {
  await sdk.auth.login({ email: '[email protected]', password: 'bad-pass' });
} catch (error) {
  if (error instanceof AuthServiceSdkError) {
    console.error('Status:', error.status);   // ej: 401
    console.error('Message:', error.message); // ej: "Credenciales inválidas"
  }
}

Errores posibles:

  • status 400: Datos inválidos (email mal formato, contraseña débil, etc.)
  • status 401: No autenticado (credenciales incorrectas)
  • status 403: No autorizado (API key inválida)
  • status 404: Recurso no encontrado
  • status 409: Conflicto (email ya registrado, token ya usado)
  • status 429: Demasiadas peticiones (rate limit)
  • status 0: Error de red (no se pudo conectar al servidor)

Opciones avanzadas

Además de appId y apiKey, puedes pasar:

  • local_test: si es true, usa http://localhost:3000 como host base.
  • defaultHeaders: headers adicionales en todas las requests.
const sdk = new AuthServiceSdk({
  appId: 'tu-app-id',
  apiKey: 'tu-api-key',
  local_test: true,
  defaultHeaders: {
    'X-Trace-Id': 'trace-123',
  },
});