@misar/sso (1.0.0)
Installation
@misar:registry=npm install @misar/sso@1.0.0"@misar/sso": "1.0.0"About this package
@misar/sso
Server-side SSO (Single Sign-On) utilities for the MisarIO ecosystem.
Overview
This package provides server-side SSO functionality for cross-domain authentication between MisarIO applications. It handles token generation, verification, and validation for secure SSO flows.
Features
- JWT Token Management: Secure token generation and verification using HS256
- Cross-Domain SSO: Support for authentication across different TLDs (misar.io, misar.dev, etc.)
- Token Validation: Comprehensive validation of redirect URLs and platform domains
- One-Time Use Tokens: Prevents token replay attacks
- Redis Integration: Optional Redis for token state management
- Platform Registry: Configurable platform validation system
Installation
pnpm add @misar/sso
Usage
Basic Token Generation
import { generateSSOToken, verifySSOToken } from '@misar/sso';
// Generate a token
const token = await generateSSOToken(
{
userId: 'user-123',
email: 'user@example.com',
redirect: 'https://misar.dev/callback',
target: 'misar.dev',
},
{
jwtSecret: process.env.JWT_SECRET!,
}
);
// Verify a token
const payload = await verifySSOToken(token, {
jwtSecret: process.env.JWT_SECRET!,
});
SSO Check Endpoint
import { validateRedirectURL, getPlatformByDomain } from '@misar/sso';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const returnUrl = searchParams.get('returnUrl');
// Validate redirect URL
const validation = validateRedirectURL(returnUrl);
if (!validation.valid) {
return NextResponse.json({ error: 'Invalid redirect URL' }, { status: 400 });
}
// Get platform info
const platform = getPlatformByDomain(new URL(returnUrl).hostname);
// Continue with SSO flow...
}
API Reference
Token Management
generateSSOToken(params, env)
Generates a signed SSO token.
Parameters:
params: Token payloaduserId: User IDemail: User emailredirect: Final redirect URLtarget: Target platform domain
env: Environment configurationjwtSecret: JWT signing secretredisUrl?: Redis URL for token stateredisToken?: Redis token
Returns: Signed JWT token string
verifySSOToken(token, env)
Verifies and decodes an SSO token.
Parameters:
token: JWT token stringenv: Environment configuration
Returns: Decoded payload or null if invalid
markTokenUsed(jti, env)
Marks a token as used to prevent replay attacks.
Validation
validateRedirectURL(url)
Validates a redirect URL against the SSO registry.
Parameters:
url: URL string to validate
Returns: Validation result with normalized URL
getPlatformByDomain(domain)
Gets platform information by domain.
Parameters:
domain: Domain string
Returns: Platform configuration or null
Configuration
Environment Variables
JWT_SECRET: Secret for signing JWT tokensREDIS_URL: Redis connection URL (optional)REDIS_TOKEN: Redis authentication token (optional)
Platform Registry
Platforms are configured in constants.ts:
export const SSO_PLATFORM_REGISTRY = {
'misar.dev': {
name: 'Misar Dev',
paths: ['/', '/callback', '/auth/*'],
},
// Add more platforms as needed
};
Security Features
- Cryptographically Secure Tokens: Uses
crypto.randomUUID()for token IDs - Short Token TTL: 60-second default expiration
- One-Time Use: Tokens are marked as used after verification
- Domain Validation: Only registered domains are allowed
- Path Validation: Specific paths must be whitelisted per platform
Error Handling
The package provides comprehensive error handling for:
- Invalid tokens
- Expired tokens
- Replay attacks
- Invalid redirect URLs
- Unregistered platforms
Development
# Run tests
pnpm test
# Type check
pnpm typecheck
# Build
pnpm build
Testing
The package includes comprehensive tests covering:
- Token generation and verification
- Redirect URL validation
- Platform registry functionality
- Error scenarios
- Security edge cases
Contributing
- Add tests for new functionality
- Ensure TypeScript types are complete
- Update documentation
- Follow security best practices
License
MIT
Dependencies
Dependencies
| ID | Version |
|---|---|
| ioredis | ^5.4.2 |
| jose | ^5.9.6 |
Development dependencies
| ID | Version |
|---|---|
| typescript | ^5.7.3 |