trinity-edge-sso
v2.1.1
Published
Simplified Trinity Edge SSO utilities - core URL parsing and redirect functions for SSO authentication flow
Maintainers
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-ssoOr with other package managers:
npm install trinity-edge-sso
yarn add trinity-edge-ssoQuick 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 pageToken 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.comError 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-ssoContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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.
