Authentication services and Svelte bindings for Classic Theme apps
npm install @classic-homes/authFramework-agnostic authentication core with Svelte bindings for the Classic Theme design system.
- 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
``bash`
npm install @classic-homes/auth
In your app's entry point (e.g., hooks.client.ts for SvelteKit):
`typescript
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);`
},
});
The authService.login() method automatically sets the auth state on successful login:
`typescript
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):
`typescript`
const response = await authService.login(credentials, { autoSetAuth: false });
// Manually set auth state
authActions.setAuth(response.accessToken, response.refreshToken, response.user);
`svelte
{#if $isAuthenticated}
Welcome, {$currentUser?.firstName}
$3
`typescript
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
});
}
`$3
`typescript
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');
}
`$3
`typescript
// 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
$3
`typescript
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';
`$3
`typescript
import {
// Store
authStore,
isAuthenticated,
currentUser, // Actions
authActions,
// Guards
checkAuth,
createAuthGuard,
requireAuth,
requireRole,
requirePermission,
protectedLoad,
} from '@classic-homes/auth/svelte';
`Configuration Options
`typescript
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:`typescript
// 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
`typescript
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:`svelte
`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.
$3
`bash
The testing utilities are included in the main package
npm install @classic-homes/auth
`$3
`typescript
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: 'test@example.com',
password: 'password',
});
expect(response.user).toMatchObject(mockUser);
mockFetch.assertCalled('/auth/login');
});
it('handles MFA flow', async () => {
configureMFAFlow(mockFetch);
const response = await authService.login({
username: 'test@example.com',
password: 'password',
});
expect(isMfaChallengeResponse(response)).toBe(true);
});
});
`$3
`typescript
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';
`$3
The
MockFetchInstance provides a configurable mock fetch with pre-defined auth routes:`typescript
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');
`$3
The
MockAuthStore mimics the Svelte auth store:`typescript
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');
`$3
Apply common auth scenarios for testing:
`typescript
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');
`$3
Use built-in assertions for common checks:
`typescript
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);
`$3
Run tests in isolated auth contexts:
`typescript
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);
});
`$3
Create custom test users:
`typescript
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: 'custom@example.com',
firstName: 'Custom',
});
// Create users with specific RBAC
const managerUser = createMockUserWithRoles(['manager', 'user'], ['read:reports', 'write:reports']);
``MIT