Token Storage Strategy
Date: 2026-02-12 Status: Technical Specification Applies to: Idiomark Connect, Adapters, Web Applications
Executive Summary
This document defines the token storage strategy for Idiomark applications. The recommended approach is a hybrid model: use secure backend storage with short-lived session tokens in the frontend.
Key Principle: Never store long-lived access tokens or refresh tokens in browser localStorage. Use the backend as a secure token vault.
Threat Model
What We're Protecting Against
| Threat | Description | Risk Level |
|---|---|---|
| XSS Attacks | Malicious scripts read localStorage | HIGH |
| CSRF Attacks | Cross-site request forgery | MEDIUM |
| Physical Device Theft | Unauthorized device access | MEDIUM |
| MITM Attacks | Network interception (mitigated by HTTPS) | LOW |
| Insider Threat | Compromised employee/admin | LOW |
What We're Protecting
- Platform OAuth tokens (Twitter, GitHub, Discord, etc.)
- Idiomark Connect API keys
- Refresh tokens for long-lived access
- User authentication sessions
Comparison: localStorage vs. Backend Storage
localStorage / sessionStorage
Advantages
- Simple implementation
- No backend infrastructure needed
- Reduces server load
- Fast read/write
Disadvantages
- Accessible to any JavaScript (XSS vulnerability)
- No automatic expiration (requires manual cleanup)
- Not encrypted by default
- Shared across subdomains (potential leakage)
- Cannot be revoked centrally
- Limited to ~5-10MB
Secure Backend Storage
Advantages
- Protected from XSS (JavaScript cannot access)
- Centralized revocation capability
- Can implement encryption at rest
- Audit logging capabilities
- Supports secure token rotation
- Works across devices
Disadvantages
- Requires additional infrastructure
- Adds latency to token operations
- More complex implementation
- Requires secure session management
Recommended Strategy: Hybrid Approach
Architecture
┌─────────────────────────────────────────────────────────────────────┐
│ USER BROWSER │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Frontend │ │ httpOnly Cookie │ │
│ │ (Next.js) │◄────►│ (Session Token) │ │
│ │ │ │ - 15 min TTL │ │
│ │ No sensitive │ │ - HttpOnly │ │
│ │ tokens stored │ │ - Secure │ │
│ │ in memory only │ │ - SameSite │ │
│ └────────┬────────┘ └─────────────────┘ │
│ │ │
└───────────┼────────────────────────────────────────────────────────┘
│ HTTPS
│
┌───────────┼────────────────────────────────────────────────────────┐
│ │ BACKEND (Token Vault) │
├───────────┼────────────────────────────────────────────────────────┤
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Secure Storage │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │
│ │ │ Platform │ │ Platform │ │ Idiomark Connect │ │ │
│ │ │ Tokens │ │ Refresh │ │ API Keys │ │ │
│ │ │ (encrypted) │ │ Tokens │ │ (encrypted) │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ │
│ │ │ │
│ │ - Encryption at rest (AES-256) │ │
│ │ - Token rotation on refresh │ │
│ │ - Centralized revocation │ │
│ │ - Audit logging │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Token Proxy Layer │ │
│ │ GET /api/tokens/:platform → Returns proxied request │ │
│ │ POST /api/tokens/:platform → Stores new token │ │
│ │ DEL /api/tokens/:platform → Revokes token │ │
│ └─────────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────────┘
Token Types and Storage Locations
| Token Type | Storage Location | TTL | Rotation Strategy |
|---|---|---|---|
| Access Token (platform) | Backend encrypted | 1-2 hours | Auto-refresh with refresh token |
| Refresh Token (platform) | Backend encrypted | 30-90 days | Rotate on use |
| API Key (Idiomark) | Backend encrypted | No expiry | Manual rotation |
| Session Token (user auth) | httpOnly cookie | 15 minutes | Refresh on activity |
| CSRF Token | Server-backed validator | Per session | Regenerate on sensitive ops |
Implementation Guidelines
1. Frontend (Browser)
// ✅ GOOD: No sensitive tokens stored
// Session handled by httpOnly cookie
const response = await fetch('/api/extract', {
method: 'POST',
credentials: 'include', // Sends session cookie
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ platform: 'twitter', username })
})
// ❌ BAD: Never do this
localStorage.setItem('twitter_token', token)
localStorage.setItem('api_key', apiKey)
2. Backend (Token Vault)
// Secure token storage interface
interface TokenVault {
// Store encrypted token
store(userId: string, platform: string, token: OAuthToken): Promise<void>
// Retrieve token for API proxying
retrieve(userId: string, platform: string): Promise<OAuthToken | null>
// Revoke all tokens for user
revokeAll(userId: string): Promise<void>
// Rotate refresh token
rotateRefreshToken(userId: string, platform: string): Promise<string>
}
// Encryption at rest
class EncryptedTokenVault implements TokenVault {
private encryptionKey: Buffer
async store(userId: string, platform: string, token: OAuthToken) {
const encrypted = await this.encrypt(token)
await db.tokens.create({
userId,
platform,
accessToken: encrypted.accessToken,
refreshToken: encrypted.refreshToken,
expiresAt: token.expiresAt
})
}
}
3. Token Proxy Pattern
// Frontend requests data through our backend
// Backend adds the stored token to the outbound request
app.get('/api/proxy/twitter/user', async (req, res) => {
const userId = req.session.userId
// Retrieve stored token
const token = await tokenVault.retrieve(userId, 'twitter')
if (!token) {
return res.status(401).json({ error: 'Not connected' })
}
// Make request to Twitter with token
const twitterResponse = await fetch('https://api.twitter.com/2/users/me', {
headers: { Authorization: `Bearer ${token.accessToken}` }
})
return res.json(await twitterResponse.json())
})
4. Session Management
// httpOnly cookie configuration
app.use(session({
store: RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
cookie: {
httpOnly: true, // Not accessible to JavaScript
secure: true, // HTTPS only
sameSite: 'strict', // CSRF protection
maxAge: 15 * 60 * 1000, // 15 minutes
path: '/'
},
rolling: true, // Reset expiration on activity
resave: false,
saveUninitialized: false
}))
Security Checklist
For Development
- No access tokens in localStorage or sessionStorage
- No tokens in URLs or query parameters
- Session cookies are httpOnly and secure
- CSRF tokens on state-changing operations
- HTTPS enforced in production
For Backend
- Tokens encrypted at rest (AES-256 or better)
- Database credentials separate from app credentials
- Token rotation implemented
- Centralized revocation endpoint
- Audit logging for token operations
For OAuth Flow
- Use PKCE (Proof Key for Code Exchange)
- State parameter to prevent CSRF
- Validate redirect_uri
- Use secure, random redirect URLs
- Short-lived authorization codes
Platform-Specific Considerations
Twitter/X
- Access tokens: 2 hours
- Requires refresh token rotation
- Has additional security requirements for API v2
GitHub
- Access tokens: Valid until revoked (no auto-expire)
- Store in backend with manual expiration (30 days recommended)
- Supports token scopes
Discord
- Access tokens: ~7 days
- Refresh tokens: 30 days
- Requires webhook token storage for bot applications
Migration Path
Current State (if using localStorage)
- Immediate: Add backend token storage endpoints
- Migrate: Bulk-migrate existing tokens to backend
- Deprecate: Add warnings for localStorage access
- Remove: Eliminate localStorage token handling
Timeline
| Phase | Duration | Action |
|---|---|---|
| 1 | Immediate | Build backend token vault |
| 2 | 1 week | Implement OAuth flow with backend storage |
| 3 | 2 weeks | Migrate existing users |
| 4 | 1 month | Deprecate localStorage pattern |
| 5 | 2 months | Remove localStorage code paths |
Recommendations for Idiomark Connect
Core Principle
"The browser is an untrusted environment. All sensitive credentials must be stored server-side with short-lived session identifiers."
Implementation Priority
- Phase 1 (MVP): Backend token vault with httpOnly sessions
- Phase 2: Token rotation and centralized revocation
- Phase 3: Multi-device sync with encrypted backup
- Phase 4: Hardware security module (HSM) for enterprise
Acceptable Use Cases for localStorage
| Data Type | localStorage OK? | Notes |
|---|---|---|
| Session ID (token reference) | ✅ Yes | Non-sensitive reference only |
| User preferences | ✅ Yes | Non-sensitive settings |
| UI state | ✅ Yes | Temporary UI state |
| Access tokens | ❌ NO | Use backend |
| Refresh tokens | ❌ NO | Use backend |
| API keys | ❌ NO | Use backend |
| Passwords | ❌ NO | Never store |
References
- OWASP Session Management Cheat Sheet
- OAuth 2.0 for Browser-Based Apps
- MDN: Web Storage API security considerations
- Stop using JWT for sessions
Document version: 1.0 Last updated: 2026-02-12