@strav/auth
Authentication primitives for the Strav framework. Provides unopinionated, composable utilities for building secure authentication systems.
Install
bun add @strav/auth
Requires @strav/kernel as a peer dependency.
Features
- JWT Management - Sign and verify JWTs using the jose library
- Token Utilities - Signed opaque tokens, magic links, refresh tokens
- TOTP/2FA - Time-based one-time passwords and recovery codes
- Password Validation - Strength checking and policy enforcement
- OAuth Helpers - State management for OAuth flows
Usage
JWT Operations
import { signJWT, verifyJWT, createAccessToken, verifyAccessToken } from '@strav/auth'
const token = await signJWT(
{ userId: 123, role: 'admin' },
'your-secret-key',
{ expiresIn: '1h', issuer: 'my-app' }
)
const payload = await verifyJWT(token, 'your-secret-key', {
issuer: 'my-app'
})
const accessToken = await createAccessToken(userId, secret)
const userId = await verifyAccessToken(accessToken, secret)
TOTP / Two-Factor Authentication
import { generateSecret, verifyTotp, totpUri, generateRecoveryCodes } from '@strav/auth'
const { raw, base32 } = generateSecret()
const uri = totpUri({
secret: base32,
issuer: 'MyApp',
account: 'user@example.com'
})
const valid = await verifyTotp(raw, '123456')
const codes = generateRecoveryCodes(8)
Password Validation
import { validatePassword, calculatePasswordStrength, generatePassword } from '@strav/auth'
const result = validatePassword(password, {
minLength: 12,
requireUppercase: true,
requireNumbers: true,
requireSpecialChars: true
})
if (!result.valid) {
console.log(result.errors)
}
const strength = calculatePasswordStrength(password)
console.log(strength.score, strength.label)
const password = generatePassword(16)
Signed Opaque Tokens
import { createSignedToken, verifySignedToken } from '@strav/auth'
const token = createSignedToken(
{ sub: userId, typ: 'password-reset' },
60
)
const payload = verifySignedToken(token)
Magic Links
import { createMagicLinkToken, verifyMagicLinkToken } from '@strav/auth'
const token = createMagicLinkToken(userId, {
email: 'user@example.com',
redirect: '/dashboard',
expiresInMinutes: 15
})
const payload = verifyMagicLinkToken(token)
OAuth State Management
import { createOAuthStateStore } from '@strav/auth'
const stateStore = createOAuthStateStore({
async store(state) { },
async retrieve(value) { },
async delete(value) { },
ttl: 600
})
const stateValue = await stateStore.generate({
redirect: '/dashboard',
data: { provider: 'github' }
})
const state = await stateStore.verify(stateValue)
Architecture
This package provides low-level authentication primitives without imposing any specific authentication flow or pattern. It's designed to be:
- Unopinionated - Build any authentication pattern you need
- Composable - Mix and match utilities as required
- Secure - Uses modern standards and best practices
- Framework-agnostic - Works with any HTTP framework
License
MIT