API Reference - Core
Complete API documentation for @alien_org/sso-sdk-core.
AlienSsoClient
Main client class for Alien SSO authentication.
Constructor
new AlienSsoClient(config: AlienSsoClientConfig)Parameters:
config.ssoBaseUrl(string, required): Base URL of the SSO serviceconfig.providerAddress(string, required): Your provider addressconfig.pollingInterval(number, optional): Polling interval in milliseconds (default: 5000)
Example:
const client = new AlienSsoClient({
ssoBaseUrl: 'https://sso.alien-api.com',
providerAddress: 'your-provider-address',
pollingInterval: 5000
});Methods
generateDeeplink()
Initiates authentication flow by generating a deep link and polling code.
async generateDeeplink(): Promise<AuthorizeResponse>Returns: Promise<AuthorizeResponse>
{
deep_link: string; // Deep link for QR code or mobile redirect
polling_code: string; // Code for polling authentication status
expired_at: number; // Unix timestamp when polling code expires
}Side Effects:
- Generates PKCE code verifier and challenge
- Stores code verifier in
sessionStoragewith keyalien-sso_code_verifier
Example:
const { deep_link, polling_code, expired_at } = await client.generateDeeplink();
console.log('Deep link:', deep_link);
console.log('Polling code:', polling_code);
console.log('Expires at:', new Date(expired_at * 1000));Throws:
- Network errors if request fails
- Validation errors if response doesn’t match schema
pollAuth()
Polls for authentication completion status.
async pollAuth(pollingCode: string): Promise<PollResponse>Parameters:
pollingCode(string): The polling code fromgenerateDeeplink()
Returns: Promise<PollResponse>
{
status: 'pending' | 'authorized' | 'rejected' | 'expired';
authorization_code?: string; // Only present when status is 'authorized'
}Status Values:
pending: User hasn’t completed authentication yetauthorized: User approved authentication,authorization_codeis availablerejected: User denied authenticationexpired: Polling code expired (user took too long)
Example:
const response = await client.pollAuth(polling_code);
if (response.status === 'authorized') {
console.log('Authorization code:', response.authorization_code);
} else if (response.status === 'pending') {
console.log('Still waiting...');
}Throws:
- Network errors if request fails
- Validation errors if response doesn’t match schema
exchangeToken()
Exchanges authorization code for access token.
async exchangeToken(authorizationCode: string): Promise<string>Parameters:
authorizationCode(string): The authorization code frompollAuth()
Returns: Promise<string> - JWT access token
Side Effects:
- Retrieves code verifier from
sessionStorage - Stores access token in
localStoragewith keyalien-sso_access_token
Example:
const token = await client.exchangeToken(authorization_code);
console.log('Access token:', token);Throws:
- Error if code verifier not found in sessionStorage
- Network errors if request fails
- Validation errors if response doesn’t match schema
verifyAuth()
Verifies if current access token is valid.
async verifyAuth(): Promise<boolean>Returns: Promise<boolean> - true if token is valid, false otherwise
Side Effects:
- If server returns a new token, updates token in
localStorage
Example:
const isValid = await client.verifyAuth();
if (isValid) {
console.log('Token is valid');
} else {
console.log('Token is invalid or expired');
}Throws:
- Network errors if request fails
getAccessToken()
Retrieves stored access token from localStorage.
getAccessToken(): string | nullReturns: string | null - Access token or null if not found
Example:
const token = client.getAccessToken();
if (token) {
console.log('Token exists:', token);
}getAuthData()
Decodes and validates JWT access token to extract session info.
getAuthData(): TokenInfo | nullReturns: TokenInfo | null
{
app_callback_session_address: string; // Session identifier
issued_at: number; // Unix timestamp
expired_at: number; // Unix timestamp
}Note: This method only decodes the token, it does NOT verify the signature. Use verifyAuth() for server-side verification.
Example:
const tokenInfo = client.getAuthData();
if (tokenInfo) {
console.log('Session:', tokenInfo.app_callback_session_address);
console.log('Issued:', new Date(tokenInfo.issued_at * 1000));
console.log('Expires:', new Date(tokenInfo.expired_at * 1000));
// Check if token expired
if (tokenInfo.expired_at * 1000 < Date.now()) {
console.log('Token is expired');
}
}logout()
Clears all stored authentication data.
logout(): voidSide Effects:
- Removes access token from
localStorage - Removes code verifier from
sessionStorage
Example:
client.logout();
console.log('Logged out successfully');Types
AlienSsoClientConfig
interface AlienSsoClientConfig {
ssoBaseUrl: string;
providerAddress: string;
pollingInterval?: number;
}AuthorizeResponse
interface AuthorizeResponse {
deep_link: string;
polling_code: string;
expired_at: number;
}PollResponse
interface PollResponse {
status: 'pending' | 'authorized' | 'rejected' | 'expired';
authorization_code?: string;
}ExchangeCodeResponse
interface ExchangeCodeResponse {
access_token: string;
}TokenInfo
interface TokenInfo {
app_callback_session_address: string;
issued_at: number;
expired_at: number;
}Storage Keys
The SDK uses the following browser storage keys:
localStorage
alien-sso_access_token: Access token (JWT format)
sessionStorage
alien-sso_code_verifier: PKCE code verifier (used during token exchange)
Error Handling
All async methods can throw errors. Always wrap in try-catch:
try {
const { deep_link, polling_code } = await client.generateDeeplink();
} catch (error) {
console.error('Failed to generate deep link:', error);
// Handle error appropriately
}Common Errors
Network Errors:
// Failed to fetch or timeout
throw new Error('Network request failed')Validation Errors:
// Response doesn't match expected schema
throw new ZodError(...)Missing Storage Data:
// Code verifier not found during token exchange
throw new Error('code_verifier not found in sessionStorage')Token Format
The access token is a JWT with the following structure:
Header:
{
"alg": "HS256",
"typ": "JWT"
}Payload:
{
"app_callback_session_address": "session-id-here",
"issued_at": 1234567890,
"expired_at": 1234567890
}The token is signed by the SSO service and can be verified server-side.
Example Usage
Complete Authentication Flow
import { AlienSsoClient } from '@alien_org/sso-sdk-core';
const client = new AlienSsoClient({
ssoBaseUrl: 'https://sso.alien-api.com',
providerAddress: 'your-provider-address',
});
async function authenticate() {
try {
// Check if already authenticated
const isValid = await client.verifyAuth();
if (isValid) {
const tokenInfo = client.getAuthData();
console.log('Already authenticated:', tokenInfo);
return;
}
// Generate deep link
const { deep_link, polling_code } = await client.generateDeeplink();
// Display QR code
displayQRCode(deep_link);
// Poll for authorization
const pollInterval = setInterval(async () => {
const response = await client.pollAuth(polling_code);
if (response.status === 'authorized') {
clearInterval(pollInterval);
// Exchange code for token
const token = await client.exchangeToken(response.authorization_code);
// Get user data
const tokenInfo = client.getAuthData();
console.log('Authenticated successfully:', tokenInfo);
hideQRCode();
} else if (response.status === 'rejected' || response.status === 'expired') {
clearInterval(pollInterval);
console.error('Authentication failed:', response.status);
hideQRCode();
}
}, 5000);
} catch (error) {
console.error('Authentication error:', error);
}
}Next Steps
- React API Reference - React SDK documentation
- Core Integration Guide - Integration guide
- Demo App - See complete implementation