@classic-homes/auth
v0.1.53
Published
Authentication services and Svelte bindings for Classic Theme apps
Readme
@classic-homes/auth
Framework-agnostic authentication core with Svelte bindings for the Classic Theme design system.
Features
- JWT-based authentication with automatic token refresh
- SSO (Single Sign-On) support with configurable providers and logout
- Multi-factor authentication (MFA/TOTP) support with type guards
- Auto-set auth state on successful login
- Pluggable storage adapter (localStorage, sessionStorage, or custom)
- Svelte reactive stores for authentication state
- Route guards for protected pages
- TypeScript-first with full type safety
Installation
npm install @classic-homes/authQuick Start
1. Initialize Authentication
In your app's entry point (e.g., hooks.client.ts for SvelteKit):
import { initAuth } from '@classic-homes/auth';
import { goto } from '$app/navigation';
import { base } from '$app/paths';
initAuth({
baseUrl: 'https://api.example.com',
storage: {
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
},
// SSO configuration (optional)
sso: {
enabled: true,
provider: 'authentik',
},
// Callback when auth errors occur
onAuthError: (error) => {
console.error('Auth error:', error);
},
// Callback when tokens are refreshed
onTokenRefresh: (tokens) => {
console.log('Tokens refreshed');
},
// Callback when user is logged out
onLogout: () => {
goto(`${base}/auth/login`);
},
});2. Login with Auto-Set Auth
The authService.login() method automatically sets the auth state on successful login:
import {
authService,
isMfaChallengeResponse,
getMfaToken,
getAvailableMethods,
} from '@classic-homes/auth/core';
import { goto } from '$app/navigation';
async function handleLogin(email: string, password: string) {
const response = await authService.login({
username: email,
password: password,
});
// Check if MFA is required
if (isMfaChallengeResponse(response)) {
const mfaToken = getMfaToken(response);
const methods = getAvailableMethods(response);
// Redirect to MFA challenge page
goto(`/auth/mfa-challenge?token=${mfaToken}&methods=${methods.join(',')}`);
return;
}
// Auth state is automatically set - redirect to dashboard
goto('/dashboard');
}To disable auto-set auth (for manual control):
const response = await authService.login(credentials, { autoSetAuth: false });
// Manually set auth state
authActions.setAuth(response.accessToken, response.refreshToken, response.user);3. Use the Auth Store (Svelte)
<script lang="ts">
import { authStore, authActions, isAuthenticated, currentUser } from '@classic-homes/auth/svelte';
// Using derived stores
// $isAuthenticated - boolean
// $currentUser - User | null
async function handleLogout() {
// SSO-aware logout
const result = await authActions.logoutWithSSO();
if (result.ssoLogoutUrl) {
// Redirect to SSO provider logout
window.location.href = result.ssoLogoutUrl;
} else {
goto('/auth/login');
}
}
</script>
{#if $isAuthenticated}
<p>Welcome, {$currentUser?.firstName}</p>
<button onclick={handleLogout}>Logout</button>
{:else}
<a href="/auth/login">Login</a>
{/if}4. SSO Login with Redirect URLs
import { authService } from '@classic-homes/auth/core';
function handleSSOLogin(redirectUrl: string) {
// Specify where to redirect after SSO callback
authService.initiateSSOLogin({
callbackUrl: `${window.location.origin}/auth/sso-callback`,
redirectUrl: redirectUrl, // Final destination after auth
});
}5. MFA Challenge Verification
import { authService } from '@classic-homes/auth/core';
async function handleMFAVerify(mfaToken: string, code: string, trustDevice: boolean) {
// Auto-sets auth state on success
const response = await authService.verifyMFAChallenge({
mfaToken,
code,
method: 'totp',
trustDevice,
});
// Auth state is automatically set - redirect to dashboard
goto('/dashboard');
}6. Protect Routes
// src/routes/dashboard/+page.ts
import { checkAuth, requireRole } from '@classic-homes/auth/svelte';
import { redirect } from '@sveltejs/kit';
import { browser } from '$app/environment';
export function load({ url }) {
if (browser) {
const result = checkAuth();
if (!result.allowed) {
throw redirect(302, `/auth/login?redirect=${encodeURIComponent(url.pathname)}`);
}
}
return {};
}
// For role-based access:
export function load({ url }) {
if (browser) {
const result = checkAuth({ roles: ['admin', 'manager'] });
if (!result.allowed) {
if (result.reason === 'not_authenticated') {
throw redirect(302, `/auth/login?redirect=${encodeURIComponent(url.pathname)}`);
}
if (result.reason === 'missing_role') {
throw redirect(302, '/unauthorized');
}
}
}
return {};
}API Reference
Core Exports
import {
// Initialization
initAuth,
getConfig,
isInitialized,
// Service
authService,
AuthService,
// API
authApi,
// MFA Guards
isMfaChallengeResponse,
isLoginSuccessResponse,
getMfaToken,
getAvailableMethods,
// JWT Utilities
decodeJWT,
isTokenExpired,
getTokenRemainingTime,
// Types
type User,
type AuthState,
type LoginCredentials,
type LoginResponse,
type LogoutResponse,
type RegisterData,
type AuthConfig,
type LoginOptions,
type MFAVerifyOptions,
} from '@classic-homes/auth/core';Svelte Exports
import {
// Store
authStore,
isAuthenticated,
currentUser,
// Actions
authActions,
// Guards
checkAuth,
createAuthGuard,
requireAuth,
requireRole,
requirePermission,
protectedLoad,
} from '@classic-homes/auth/svelte';Configuration Options
interface AuthConfig {
/** Base URL for the auth API */
baseUrl: string;
/** Custom fetch implementation (useful for SSR or testing) */
fetch?: typeof fetch;
/** Storage adapter for token persistence */
storage?: StorageAdapter;
/** Storage key prefix for auth data */
storageKey?: string;
/** SSO configuration */
sso?: {
enabled: boolean;
provider: string;
authorizeUrl?: string;
};
/** Callback when auth errors occur */
onAuthError?: (error: Error) => void;
/** Callback when tokens are refreshed */
onTokenRefresh?: (tokens: { accessToken: string; refreshToken: string }) => void;
/** Callback when user is logged out */
onLogout?: () => void;
}Auth Actions
The authActions object provides methods for authentication operations:
// Set auth data after login
authActions.setAuth(accessToken, refreshToken, user, sessionToken);
// Update tokens after refresh
authActions.updateTokens(accessToken, refreshToken);
// Update user profile
authActions.updateUser(user);
// Clear auth state (local logout)
authActions.logout();
// SSO-aware logout (calls API, returns SSO logout URL if applicable)
const result = await authActions.logoutWithSSO();
if (result.ssoLogoutUrl) {
window.location.href = result.ssoLogoutUrl;
}
// Permission and role checks
authActions.hasPermission('users:read');
authActions.hasRole('admin');
authActions.hasAnyRole(['admin', 'manager']);
authActions.hasAllRoles(['admin', 'manager']);
authActions.hasAnyPermission(['users:read', 'users:write']);
authActions.hasAllPermissions(['users:read', 'users:write']);
// Reload auth from storage
authActions.rehydrate();Auth Store State
interface AuthState {
accessToken: string | null;
refreshToken: string | null;
user: User | null;
isAuthenticated: boolean;
}Using with @classic-homes/theme-svelte
The auth package integrates with the form validation from @classic-homes/theme-svelte:
<script lang="ts">
import { useForm, loginSchema } from '@classic-homes/theme-svelte';
import { authService, isMfaChallengeResponse, getMfaToken } from '@classic-homes/auth/core';
import { goto } from '$app/navigation';
const form = useForm({
schema: loginSchema,
initialValues: {
email: '',
password: '',
rememberMe: false,
},
onSubmit: async (data) => {
const response = await authService.login({
username: data.email,
password: data.password,
});
if (isMfaChallengeResponse(response)) {
const mfaToken = getMfaToken(response);
goto(`/auth/mfa-challenge?token=${mfaToken}`);
return;
}
// Auth state automatically set
goto('/dashboard');
},
});
</script>
<form onsubmit={form.handleSubmit}>
<input bind:value={form.data.email} />
{#if form.errors.email}
<span class="error">{form.errors.email}</span>
{/if}
<!-- ... -->
</form>Automatic Token Refresh
Token refresh happens automatically when:
- An API request returns 401 Unauthorized
- The refresh token is valid
The Svelte store is automatically updated when tokens are refreshed, so your UI stays in sync.
Testing Utilities
The auth package includes comprehensive testing utilities for unit and integration tests.
Installation
# The testing utilities are included in the main package
npm install @classic-homes/authQuick Start
import { describe, it, beforeEach, afterEach, expect } from 'vitest';
import {
setupTestAuth,
mockUser,
configureMFAFlow,
assertAuthenticated,
} from '@classic-homes/auth/testing';
import { authService, isMfaChallengeResponse } from '@classic-homes/auth/core';
describe('Login Flow', () => {
let cleanup: () => void;
let mockFetch;
beforeEach(() => {
const ctx = setupTestAuth();
cleanup = ctx.cleanup;
mockFetch = ctx.mockFetch;
});
afterEach(() => cleanup());
it('handles successful login', async () => {
const response = await authService.login({
username: '[email protected]',
password: 'password',
});
expect(response.user).toMatchObject(mockUser);
mockFetch.assertCalled('/auth/login');
});
it('handles MFA flow', async () => {
configureMFAFlow(mockFetch);
const response = await authService.login({
username: '[email protected]',
password: 'password',
});
expect(isMfaChallengeResponse(response)).toBe(true);
});
});Testing Exports
import {
// Fixtures - Pre-defined test data
mockUser,
mockAdminUser,
mockSSOUser,
mockMFAUser,
mockAccessToken,
mockRefreshToken,
mockLoginSuccess,
mockMFARequired,
createMockUser,
createMockTokenPair,
createMockLoginSuccess,
// Mocks - Test doubles for dependencies
MockStorageAdapter,
MockFetchInstance,
MockAuthStore,
createMockStorage,
createMockFetch,
createMockAuthStore,
// Setup Helpers
setupTestAuth,
createTestAuthHelpers,
quickSetupAuth,
withTestAuth,
// State Simulation
authScenarios,
applyScenario,
configureMFAFlow,
configureTokenRefresh,
configureSSOLogout,
simulateLogin,
simulateLogout,
// Assertions
assertAuthenticated,
assertUnauthenticated,
assertHasPermissions,
assertHasRoles,
assertTokenValid,
assertApiCalled,
assertStoreMethodCalled,
assertRequiresMFA,
} from '@classic-homes/auth/testing';Mock Fetch
The MockFetchInstance provides a configurable mock fetch with pre-defined auth routes:
const ctx = setupTestAuth();
const { mockFetch } = ctx;
// Default routes are pre-configured for all auth endpoints
// Customize responses
mockFetch.requireMFA(); // Login requires MFA
mockFetch.failLogin('Invalid credentials'); // Login fails
mockFetch.enableSSOLogout(); // Logout returns SSO URL
// Add custom routes
mockFetch.addRoute({
method: 'GET',
path: '/custom/endpoint',
response: { data: 'custom response' },
});
// Fail specific endpoints
mockFetch.failEndpoint('GET', '/auth/profile', 403, 'Forbidden');
// Check call history
expect(mockFetch.wasCalled('/auth/login')).toBe(true);
mockFetch.assertCalled('/auth/profile');
mockFetch.assertNotCalled('/auth/logout');Mock Auth Store
The MockAuthStore mimics the Svelte auth store:
const store = createMockAuthStore();
// Simulate states
store.simulateAuthenticated(mockAdminUser);
store.simulateUnauthenticated();
// Direct state manipulation
store.setState({ isAuthenticated: true, user: mockUser });
// Check method calls
store.assertMethodCalled('setAuth');
store.assertMethodNotCalled('logout');
// Get call history
const calls = store.getCallsFor('setAuth');Pre-defined Scenarios
Apply common auth scenarios for testing:
import { authScenarios, applyScenario } from '@classic-homes/auth/testing';
// Available scenarios:
// - 'unauthenticated'
// - 'authenticated'
// - 'admin'
// - 'ssoUser'
// - 'mfaEnabled'
// - 'unverifiedEmail'
// - 'inactive'
// - 'expiredToken'
const store = createMockAuthStore();
applyScenario(store, 'admin');
expect(store.user?.roles).toContain('admin');Custom Assertions
Use built-in assertions for common checks:
import {
assertAuthenticated,
assertHasPermissions,
assertTokenValid,
assertApiCalled,
assertRequiresMFA,
} from '@classic-homes/auth/testing';
// Auth state assertions
assertAuthenticated(store.getState());
assertUnauthenticated(store.getState());
// Permission assertions
assertHasPermissions(user, ['read:profile', 'write:profile']);
assertHasRoles(user, ['admin']);
// Token assertions
assertTokenValid(accessToken);
assertTokenExpired(oldToken);
// API call assertions
assertApiCalled(mockFetch, 'POST', '/auth/login', {
times: 1,
body: { username: 'test', password: 'pass' },
});
// MFA assertions
assertRequiresMFA(loginResponse);
assertNoMFARequired(loginResponse);Isolated Test Context
Run tests in isolated auth contexts:
import { withTestAuth } from '@classic-homes/auth/testing';
// Automatic setup and cleanup
await withTestAuth(async ({ mockFetch, mockStore }) => {
mockFetch.requireMFA();
const response = await authService.login({ username: 'test', password: 'pass' });
expect(response.requiresMFA).toBe(true);
});User Fixtures
Create custom test users:
import {
mockUser,
mockAdminUser,
createMockUser,
createMockUserWithRoles,
} from '@classic-homes/auth/testing';
// Use pre-defined users
expect(mockUser.role).toBe('user');
expect(mockAdminUser.permissions).toContain('manage:system');
// Create custom users
const customUser = createMockUser({
email: '[email protected]',
firstName: 'Custom',
});
// Create users with specific RBAC
const managerUser = createMockUserWithRoles(['manager', 'user'], ['read:reports', 'write:reports']);License
MIT
