Sigma Auth
Reference

Security Architecture

Sigma Auth implements multiple layers of security to protect user identities and prevent unauthorized access.

Cryptographic Foundation

ECDSA on secp256k1

Sigma Auth uses the same cryptographic primitives as Bitcoin:

  • Elliptic Curve: secp256k1 (same as Bitcoin)
  • Key Size: 256-bit private keys
  • Signature Algorithm: ECDSA (Elliptic Curve Digital Signature Algorithm)
  • Hash Function: SHA-256 for message hashing

Mathematical Security

Private Key Space: 2^256 possible keys (approximately 10^77)

Computational Security: Breaking a single private key would require:

  • Classical computers: 2^128 operations (practically impossible)
  • Quantum computers: Shor's algorithm could reduce this, but quantum-resistant migration paths exist

Signature Properties

Unforgeable: Cannot create valid signatures without the private key

Non-repudiation: Signatures prove the signer had access to the private key at signing time

Message Binding: Signatures are cryptographically bound to the specific message content

Authentication Security

Replay Attack Prevention

Timestamp Validation: All signatures include timestamps, preventing reuse of old signatures

timestamp-validation.js
// Server-side timestamp validation
const validateTimestamp = (timestamp, allowedDriftMs = 300000) => {
    const now = Date.now();
    const signatureTime = new Date(timestamp).getTime();
    const timeDrift = Math.abs(now - signatureTime);
    
    if (timeDrift > allowedDriftMs) {
        throw new Error('Signature timestamp too old or too far in future');
    }
    
    return true;
};

Nonce Support: Optional nonces can be included for additional replay protection

nonce-protection.js
// Enhanced replay protection with nonce
const signaturePayload = {
    timestamp: new Date().toISOString(),
    nonce: crypto.randomUUID(),
    requestPath: '/api/protected',
    clientId: 'app-name'
};

Request Binding

Signatures are bound to specific requests, preventing signature reuse across different endpoints:

request-binding.js
// Signature includes request path
const authToken = getAuthToken({
    privateKey: userWif,
    requestPath: '/api/user/profile', // Bound to this specific endpoint
    timestamp: new Date().toISOString()
});

Session Security

JWT Security: Access tokens are signed JWTs with configurable expiration

jwt-payload.js
// JWT payload includes essential claims
const jwtPayload = {
    sub: publicKey,           // Subject (user identifier)
    iss: 'auth.sigmaidentity.com',  // Issuer
    aud: clientId,            // Audience (client application)
    exp: Math.floor(Date.now() / 1000) + 3600, // Expiration (1 hour)
    iat: Math.floor(Date.now() / 1000),        // Issued at
    bitcoinAddress: address,
    publicKey: publicKey
};

Session Isolation: Each client application gets isolated sessions

Secure Storage: Sensitive data stored in Cloudflare KV with encryption at rest

OAuth 2.0 Security

PKCE (Proof Key for Code Exchange)

Sigma Auth implements PKCE for enhanced security in OAuth flows:

pkce-implementation.js
// Generate PKCE parameters
const codeVerifier = base64URLEncode(crypto.randomBytes(32));
const codeChallenge = base64URLEncode(sha256(codeVerifier));

// Authorization request includes challenge
const authUrl = new URL('/authorize', 'https://auth.sigmaidentity.com');
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');

// Token exchange includes verifier
const tokenRequest = {
    grant_type: 'authorization_code',
    code: authorizationCode,
    code_verifier: codeVerifier
};

State Parameter Validation

CSRF protection through state parameter validation:

state-validation.js
// Generate and store state
const state = crypto.randomUUID();
sessionStorage.setItem('oauth_state', state);

// Include in authorization request
authUrl.searchParams.set('state', state);

// Validate on callback
const callbackState = urlParams.get('state');
const storedState = sessionStorage.getItem('oauth_state');

if (callbackState !== storedState) {
    throw new Error('Invalid state parameter - possible CSRF attack');
}

Secure Redirects

Redirect URI Validation: Only registered redirect URIs are allowed

HTTPS Enforcement: All OAuth redirects must use HTTPS in production

Fragment Restrictions: No sensitive data in URL fragments

Key Management

Client-Side Key Security

Never Store Private Keys in localStorage: Use sessionStorage or encrypted storage

secure-key-storage.js
// ❌ Insecure: localStorage persists across sessions
localStorage.setItem('privateKey', wif);

// ✅ Secure: sessionStorage or encrypted storage
sessionStorage.setItem('privateKey', wif);
// or
const encryptedKey = encrypt(wif, userPassword);
localStorage.setItem('encryptedKey', encryptedKey);

Memory Management: Clear sensitive data from memory when possible

memory-cleanup.js
// Clear sensitive variables
privateKey = null;
wif = null;

// Force garbage collection if available
if (window.gc) {
    window.gc();
}

Server-Side Key Security

No Private Key Storage: Servers never store or have access to private keys

Public Key Validation: Verify public keys are valid secp256k1 points

public-key-validation.js
const validatePublicKey = (publicKeyHex) => {
    try {
        const pubKey = PublicKey.fromString(publicKeyHex);
        // Additional validation logic
        return pubKey.isValid();
    } catch (error) {
        return false;
    }
};

Hardware Security

Hardware Wallet Support: Integration with hardware wallets for enhanced security

hardware-wallet.js
// Hardware wallet integration example
const signWithHardwareWallet = async (message) => {
    if (typeof window.bitcoin !== 'undefined') {
        return await window.bitcoin.signMessage(message);
    }
    throw new Error('Hardware wallet not available');
};

Network Security

HTTPS Enforcement

TLS 1.3: Latest TLS version for optimal security

HSTS Headers: HTTP Strict Transport Security prevents downgrade attacks

security-headers.js
// Cloudflare Worker headers
const securityHeaders = {
    'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
    'X-Content-Type-Options': 'nosniff',
    'X-Frame-Options': 'DENY',
    'X-XSS-Protection': '1; mode=block',
    'Referrer-Policy': 'strict-origin-when-cross-origin'
};

CORS Configuration

Strict CORS: Only allow requests from registered origins

cors-headers.js
const corsHeaders = {
    'Access-Control-Allow-Origin': allowedOrigin,
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Auth-Token',
    'Access-Control-Max-Age': '86400'
};

⚠️ Important CORS Security Note:

The default sigma-auth deployment uses Access-Control-Allow-Origin: * for development convenience. For production deployments, configure the ALLOWED_ORIGINS environment variable with your specific domains. See the self-hosting guide for detailed configuration instructions.

CORS Security Implications:

  • Cross-Site Request Forgery: Unrestricted CORS can enable CSRF attacks
  • Data Exposure: Allows any website to attempt API requests
  • Token Security: Even with secure tokens, restrict origins for defense in depth
  • Phishing Protection: Prevents malicious sites from impersonating your auth flow

Rate Limiting

Cloudflare Rate Limiting: Built-in DDoS protection

Application-Level Limits: Additional rate limiting for sensitive endpoints

rate-limiting.js
const rateLimiter = {
    '/token': { requests: 10, window: 60 },      // 10 requests per minute
    '/userinfo': { requests: 100, window: 60 },  // 100 requests per minute
    '/backup': { requests: 5, window: 300 }      // 5 requests per 5 minutes
};

Data Protection

Encryption at Rest

KV Storage: All data in Cloudflare KV is encrypted at rest

Backup Encryption: User backups are client-side encrypted before storage

backup-encryption.js
// Client-side backup encryption
const encryptBackup = async (data, password) => {
    const key = await deriveKey(password);
    const iv = crypto.getRandomValues(new Uint8Array(16));
    
    const encrypted = await crypto.subtle.encrypt(
        { name: 'AES-GCM', iv },
        key,
        new TextEncoder().encode(JSON.stringify(data))
    );
    
    return {
        encrypted: arrayBufferToBase64(encrypted),
        iv: arrayBufferToBase64(iv),
        algorithm: 'AES-GCM'
    };
};

Data Minimization

Minimal Data Collection: Only collect data necessary for authentication

No PII Storage: Personal information stored off-chain when possible

Retention Policies: Automatic data deletion after configurable periods

Vulnerability Management

Security Monitoring

Automated Scanning: Regular security scans of all components

Dependency Updates: Automated updates for security patches

Log Analysis: Security event logging and analysis

Incident Response

Security Team: Dedicated security team for incident response

Disclosure Process: Responsible disclosure process for security researchers

Patch Management: Rapid patch deployment for critical vulnerabilities

Threat Model

Threats Mitigated

Credential Theft: No passwords to steal

Server Compromise: No private keys on servers

Replay Attacks: Timestamp and nonce validation

MITM Attacks: HTTPS and signature verification

CSRF Attacks: State parameter validation

Session Hijacking: Secure JWT tokens

Threats to Consider

⚠️ Client Compromise: Malware on user devices

⚠️ Social Engineering: Tricking users into revealing keys

⚠️ Implementation Bugs: Code vulnerabilities

⚠️ Quantum Computing: Future threat to ECDSA

Mitigation Strategies

Client Protection: Hardware wallets, secure enclaves

User Education: Best practices documentation

Code Review: Comprehensive security reviews

Quantum Resistance: Research into post-quantum cryptography

Compliance

Standards Compliance

OAuth 2.0 RFC 6749: Full compliance with OAuth specification

OpenID Connect: OIDC compliance for identity layer

PKCE RFC 7636: Proof Key for Code Exchange implementation

JWT RFC 7519: JSON Web Token standard compliance

Regulatory Compliance

GDPR: European data protection compliance

CCPA: California privacy law compliance

SOC 2: Security controls documentation

Security Audits

Regular Audits

Code Reviews: All code reviewed by security team

Penetration Testing: Regular penetration tests

Third-Party Audits: External security audits

Best Practices for Developers

Implementation Security

  1. Always verify signatures server-side
  2. Use HTTPS for all communications
  3. Validate all input parameters
  4. Implement proper error handling
  5. Use secure random number generation

Key Management

  1. Never log private keys
  2. Use hardware wallets for high-value applications
  3. Implement key rotation for long-lived applications
  4. Provide secure backup mechanisms
  5. Clear sensitive data from memory

Application Security

  1. Implement Content Security Policy (CSP)
  2. Use secure cookie attributes
  3. Validate all user inputs
  4. Implement rate limiting
  5. Monitor for suspicious activity

Security Contact

Report vulnerabilities through our responsible disclosure process via GitHub issues. We appreciate the security community's efforts to improve the security of Sigma Auth.