Skip to main content

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​

ThreatDescriptionRisk Level
XSS AttacksMalicious scripts read localStorageHIGH
CSRF AttacksCross-site request forgeryMEDIUM
Physical Device TheftUnauthorized device accessMEDIUM
MITM AttacksNetwork interception (mitigated by HTTPS)LOW
Insider ThreatCompromised employee/adminLOW

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

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 TypeStorage LocationTTLRotation Strategy
Access Token (platform)Backend encrypted1-2 hoursAuto-refresh with refresh token
Refresh Token (platform)Backend encrypted30-90 daysRotate on use
API Key (Idiomark)Backend encryptedNo expiryManual rotation
Session Token (user auth)httpOnly cookie15 minutesRefresh on activity
CSRF TokenServer-backed validatorPer sessionRegenerate 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)​

  1. Immediate: Add backend token storage endpoints
  2. Migrate: Bulk-migrate existing tokens to backend
  3. Deprecate: Add warnings for localStorage access
  4. Remove: Eliminate localStorage token handling

Timeline​

PhaseDurationAction
1ImmediateBuild backend token vault
21 weekImplement OAuth flow with backend storage
32 weeksMigrate existing users
41 monthDeprecate localStorage pattern
52 monthsRemove 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​

  1. Phase 1 (MVP): Backend token vault with httpOnly sessions
  2. Phase 2: Token rotation and centralized revocation
  3. Phase 3: Multi-device sync with encrypted backup
  4. Phase 4: Hardware security module (HSM) for enterprise

Acceptable Use Cases for localStorage​

Data TypelocalStorage OK?Notes
Session ID (token reference)✅ YesNon-sensitive reference only
User preferences✅ YesNon-sensitive settings
UI state✅ YesTemporary UI state
Access tokens❌ NOUse backend
Refresh tokens❌ NOUse backend
API keys❌ NOUse backend
Passwords❌ NONever store

References​


Document version: 1.0 Last updated: 2026-02-12