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

trinity-edge-sso

v2.1.1

Published

Simplified Trinity Edge SSO utilities - core URL parsing and redirect functions for SSO authentication flow

Readme

Trinity Edge SSO

A comprehensive SSO authentication package for Trinity Edge integration. This package provides utilities for JWT token management, AES encryption, URL parsing, and API authentication to streamline Trinity Edge SSO implementation in any JavaScript/TypeScript project.

Features

  • 🔐 AES-256-CBC Encryption/Decryption for secure token storage
  • 🎯 JWT Token Management with automatic refresh capabilities
  • 🔗 URL Parameter Parsing for Trinity Edge callbacks
  • 📦 Framework Agnostic - works with React, Vue, Angular, Node.js
  • 🛡️ TypeScript Support with full type definitions
  • 🔄 Automatic Token Refresh with retry logic
  • 💾 Flexible Storage - localStorage, custom storage adapters
  • 🌐 API Helper Functions for request interceptors

Installation

pnpm install trinity-edge-sso

Or with other package managers:

npm install trinity-edge-sso
yarn add trinity-edge-sso

Quick Start

1. Configure the Package

import { configureSSOSettings, configureEncryption } from 'trinity-edge-sso';

// Configure SSO settings
configureSSOSettings({
  edgeUri: 'https://your-trinity-edge-url.com',
  platformGuid: 'your-platform-guid-here',
  redirectUrl: 'https://yourapp.com/callback',
  apiBaseUrl: 'https://your-api.com',
  aesSecretKey: 'your-base64-aes-key',
  aesIv: 'your-base64-aes-iv'
});

2. Initialize SSO on App Start

import { initializeSSO, isAuthenticated, getCurrentUser } from 'trinity-edge-sso';

// Initialize SSO when your app starts
const ssoResult = initializeSSO();

if (ssoResult.authenticated) {
  console.log('User is authenticated!');
  
  // Get user profile
  const user = await getCurrentUser();
  console.log('User:', user);
} else if (ssoResult.redirectUrl) {
  // Redirect to Trinity Edge login
  window.location.href = ssoResult.redirectUrl;
}

3. Set Up API Interceptor

import { getAuthHeader, handleAuthError, shouldRefreshToken } from 'trinity-edge-sso';
import axios from 'axios';

// Request interceptor
axios.interceptors.request.use(async (config) => {
  const authHeader = await getAuthHeader();
  if (authHeader) {
    config.headers.Authorization = authHeader;
  }
  return config;
});

// Response interceptor
axios.interceptors.response.use(
  (response) => response,
  async (error) => {
    const { shouldRefresh, shouldLogout } = handleAuthError(
      error.response?.status,
      error.response
    );

    if (shouldRefresh) {
      const newToken = await forceTokenRefresh();
      if (newToken) {
        // Retry the request
        return axios.request(error.config);
      }
    }

    if (shouldLogout) {
      logout(true); // Redirect to login
    }

    return Promise.reject(error);
  }
);

Core Functions

SSO Initialization

import { initializeSSO, SSOResult } from 'trinity-edge-sso';

const result: SSOResult = initializeSSO();
// Returns: { success: boolean, authenticated: boolean, tokens?, user?, redirectUrl?, error? }

Authentication Check

import { isAuthenticated } from 'trinity-edge-sso';

if (isAuthenticated()) {
  // User is authenticated
}

User Management

import { getCurrentUser, logout, trackUserLoginActivity } from 'trinity-edge-sso';

// Get current user profile
const user = await getCurrentUser();

// Track login activity (call once per session)
await trackUserLoginActivity();

// Logout user
logout(true); // true = redirect to login page

Token Management

import { 
  getCurrentAccessToken, 
  isTokenExpired, 
  forceTokenRefresh 
} from 'trinity-edge-sso';

// Get current valid access token (auto-refreshes if needed)
const token = await getCurrentAccessToken();

// Check if token is expired
if (isTokenExpired(token)) {
  // Handle expired token
}

// Force token refresh
const newToken = await forceTokenRefresh();

API Helpers

Request Headers

import { getAuthHeader, createAuthHeaders } from 'trinity-edge-sso';

// Get just the Authorization header
const authHeader = await getAuthHeader();
// Returns: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."

// Get complete headers object
const headers = await createAuthHeaders({
  'Custom-Header': 'value'
});
// Returns: { Authorization: "Bearer ...", "Content-Type": "application/json", "Custom-Header": "value" }

Error Handling

import { handleAuthError } from 'trinity-edge-sso';

const { shouldRefresh, shouldLogout, error } = handleAuthError(401, response);

if (shouldRefresh) {
  // Attempt token refresh
}

if (shouldLogout) {
  // User needs to login again
}

URL Parsing

Extract Tokens from Trinity Edge Callback

import { parseTokensFromUrl, clearTokensFromUrl } from 'trinity-edge-sso';

// Parse tokens from URL (usually called automatically by initializeSSO)
const tokens = parseTokensFromUrl();

// Clean URL after extracting tokens (important for security)
clearTokensFromUrl();

Storage Management

Token Storage

import { 
  storeTokens, 
  getStoredTokens, 
  clearStoredTokens,
  hasStoredTokens 
} from 'trinity-edge-sso';

// Store tokens (automatically encrypted)
storeTokens({
  accessToken: 'your-access-token',
  refreshToken: 'your-refresh-token',
  signature: 'signature',
  isNewUser: false
});

// Get stored tokens (automatically decrypted)
const tokens = getStoredTokens();

// Check if tokens exist
if (hasStoredTokens()) {
  // Tokens are available
}

// Clear all stored tokens
clearStoredTokens();

Custom Storage Adapter

import { configureStorage, StorageInterface } from 'trinity-edge-sso';

// For React Native or other environments
class CustomStorage implements StorageInterface {
  async getItem(key: string): Promise<string | null> {
    // Your custom storage implementation
  }
  
  async setItem(key: string, value: string): Promise<void> {
    // Your custom storage implementation
  }
  
  async removeItem(key: string): Promise<void> {
    // Your custom storage implementation
  }
  
  async clear(): Promise<void> {
    // Your custom storage implementation
  }
}

configureStorage(new CustomStorage());

Encryption

AES Encryption/Decryption

import { encryptAES, decryptAES, configureEncryption } from 'trinity-edge-sso';

// Configure encryption (usually done in configureSSOSettings)
configureEncryption('your-base64-secret-key', 'your-base64-iv');

// Encrypt data
const encrypted = encryptAES('sensitive-data');

// Decrypt data
const decrypted = decryptAES(encrypted);

Framework-Specific Examples

React Hook Example

// hooks/useAuth.ts
import { useState, useEffect } from 'react';
import { 
  initializeSSO, 
  isAuthenticated, 
  getCurrentUser,
  logout,
  UserProfile 
} from 'trinity-edge-sso';

export function useAuth() {
  const [user, setUser] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    const initialize = async () => {
      const result = initializeSSO();
      
      if (result.authenticated) {
        setAuthenticated(true);
        const userProfile = await getCurrentUser();
        setUser(userProfile);
      } else if (result.redirectUrl) {
        window.location.href = result.redirectUrl;
      }
      
      setLoading(false);
    };

    initialize();
  }, []);

  const signOut = () => {
    logout(true);
    setUser(null);
    setAuthenticated(false);
  };

  return {
    user,
    loading,
    authenticated,
    signOut
  };
}

Vue Composition API Example

// composables/useAuth.ts
import { ref, onMounted } from 'vue';
import { 
  initializeSSO, 
  getCurrentUser,
  logout,
  UserProfile 
} from 'trinity-edge-sso';

export function useAuth() {
  const user = ref<UserProfile | null>(null);
  const loading = ref(true);
  const authenticated = ref(false);

  const initialize = async () => {
    const result = initializeSSO();
    
    if (result.authenticated) {
      authenticated.value = true;
      user.value = await getCurrentUser();
    } else if (result.redirectUrl) {
      window.location.href = result.redirectUrl;
    }
    
    loading.value = false;
  };

  const signOut = () => {
    logout(true);
    user.value = null;
    authenticated.value = false;
  };

  onMounted(initialize);

  return {
    user,
    loading,
    authenticated,
    signOut
  };
}

Environment Variables

The package supports these environment variables for configuration:

VITE_APP_EDGE_AES_SECRET_KEY=your-base64-aes-secret
VITE_APP_EDGE_AES_IV=your-base64-aes-iv
VITE_APP_EDGE_PLATFORM_GUID=your-platform-guid
VITE_APP_EDGE_REDIRECT_URI=https://trinity-edge-login.com

Error Handling

The package includes comprehensive error handling for common scenarios:

  • Invalid tokens - Automatic cleanup and redirect to login
  • Expired tokens - Automatic refresh attempts
  • Network errors - Graceful degradation
  • User exceptions - Specific handling for inactive users, domain issues, etc.

TypeScript Support

Full TypeScript definitions are included:

import { 
  TokenData, 
  SSOResult, 
  UserProfile, 
  SSOConfig,
  JWTPayload 
} from 'trinity-edge-sso';

Development

To work on this package locally:

# Clone the repository
git clone https://github.com/spault/trinity-edge-sso.git
cd trinity-edge-sso

# Install dependencies
pnpm install

# Build the package
pnpm run build

# Watch for changes during development
pnpm run dev

# Test locally in another project
pnpm link --global
# Then in your test project:
pnpm link --global trinity-edge-sso

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

For issues and questions:

  • Create an issue on GitHub
  • Contact Trinity Partners Innovation team

Trinity Edge SSO - Simplifying authentication for Trinity Edge integrations.