Security Guide
Comprehensive security guide for pxlpeak including data protection, access control, compliance, and best practices.
Introduction
Security is foundational to pxlpeak. This guide covers our security architecture, your responsibilities as a customer, and best practices for securing your analytics implementation.
Security Architecture Overview
pxlpeak Security Layers:
┌─────────────────────────────────────────────────────────────────────────────┐
│ APPLICATION LAYER │
│ ├── Authentication (SSO, MFA, API Keys) │
│ ├── Authorization (RBAC, Resource-level permissions) │
│ └── Input validation & sanitization │
├─────────────────────────────────────────────────────────────────────────────┤
│ NETWORK LAYER │
│ ├── TLS 1.3 encryption (all traffic) │
│ ├── WAF protection │
│ ├── DDoS mitigation │
│ └── IP allowlisting (optional) │
├─────────────────────────────────────────────────────────────────────────────┤
│ DATA LAYER │
│ ├── Encryption at rest (AES-256) │
│ ├── Encryption in transit (TLS 1.3) │
│ ├── Data isolation (tenant separation) │
│ └── Backup encryption │
├─────────────────────────────────────────────────────────────────────────────┤
│ INFRASTRUCTURE LAYER │
│ ├── SOC 2 Type II certified infrastructure │
│ ├── Private network architecture │
│ ├── Regular security audits │
│ └── Vulnerability management │
└─────────────────────────────────────────────────────────────────────────────┘User Account Security
Sign-Up Security
pxlpeak implements multiple security layers for user account creation:
Password Requirements
Minimum Requirements:
- 8+ characters (12+ recommended)
- Uppercase letter (A-Z)
- Lowercase letter (a-z)
- Number (0-9)
- Special character (!@#$%^&*()_+-=[]|;:,.<>?)
Password Strength Levels:
- Weak: Meets minimum requirements only
- Medium: 3-4 requirement categories met
- Strong: 5 requirement categories met
- Very Strong: 5+ categories + 12+ characters
Input Validation & Sanitization
All sign-up inputs are validated and sanitized:
// Server-side validation (Zod schema)
import { signUpSchema } from '@/lib/schemas/auth';
// Email sanitization
- Normalized to lowercase
- Trimmed whitespace
- Format validation (RFC 5322)
- Length limits (5-254 characters)
// Password validation
- Strength checking
- Length validation
- Character requirements
- No common passwords (future enhancement)
// Name sanitization
- Control character removal
- Length limits (2-100 characters)
- XSS preventionRate Limiting
Sign-up attempts are rate-limited to prevent abuse:
- Email sign-up: 5 attempts per email per hour
- OAuth sign-up: 10 attempts per IP per hour
- Global limit: 20 sign-ups per IP per day
Rate limits are enforced at the application level and can be configured per environment.
Email Verification
Security Benefits:
- Prevents fake/disposable email addresses
- Ensures user controls the email account
- Required before account activation
- Prevents account takeover via email changes
Verification Flow:
- User signs up → Confirmation email sent
- User clicks link → Email verified
- Account activated → User can sign in
- Link expires after 24 hours (security)
OAuth Security
OAuth sign-up provides enhanced security:
- No password storage - Managed by OAuth provider
- Token-based auth - Secure token exchange
- Provider verification - Email verified by provider
- Automatic updates - Profile sync from provider
Supported Providers:
- Google (OAuth 2.0)
- GitHub (OAuth 2.0)
Authentication
Single Sign-On (SSO)
// SSO Configuration
interface SSOConfig {
saml: {
enabled: boolean;
idpMetadataUrl: string;
entityId: string;
assertionConsumerServiceUrl: string;
signatureAlgorithm: 'RSA-SHA256' | 'RSA-SHA512';
signRequests: boolean;
encryptAssertions: boolean;
};
oidc: {
enabled: boolean;
issuer: string;
clientId: string;
clientSecret: string;
scopes: string[];
responseType: 'code';
pkce: boolean;
};
}
// Configure SAML SSO via API
await pxlpeak.admin.sso.configure({
type: 'saml',
config: {
idpMetadataUrl: 'https://idp.company.com/metadata',
allowIdpInitiated: false,
defaultRole: 'viewer',
autoProvision: true,
attributeMapping: {
email: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress',
firstName: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname',
lastName: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname',
groups: 'http://schemas.xmlsoap.org/claims/Group'
}
}
});
// Configure OIDC SSO
await pxlpeak.admin.sso.configure({
type: 'oidc',
config: {
issuer: 'https://login.company.com',
clientId: 'pxlpeak-client',
clientSecret: process.env.OIDC_CLIENT_SECRET,
scopes: ['openid', 'email', 'profile', 'groups'],
pkce: true,
autoProvision: true
}
});Multi-Factor Authentication (MFA)
// MFA Configuration
interface MFAConfig {
// Enforcement level
enforcement: 'optional' | 'required_for_admins' | 'required_for_all';
// Allowed methods
allowedMethods: ('totp' | 'sms' | 'email' | 'webauthn')[];
// Recovery options
recoveryOptions: {
backupCodes: boolean;
adminReset: boolean;
gracePeriodHours: number;
};
}
// Require MFA for all users
await pxlpeak.admin.security.configureMFA({
enforcement: 'required_for_all',
allowedMethods: ['totp', 'webauthn'],
gracePeriodDays: 7,
recoveryOptions: {
backupCodes: true,
adminReset: true
}
});
// User MFA enrollment
await pxlpeak.auth.enrollMFA({
method: 'totp',
// Returns QR code URI for authenticator app
});
// Verify MFA during login
await pxlpeak.auth.verifyMFA({
code: '123456',
method: 'totp'
});Session Management
// Session security configuration
const sessionConfig = {
// Session timeout (idle)
idleTimeoutMinutes: 30,
// Maximum session duration
maxSessionHours: 24,
// Concurrent sessions
allowConcurrentSessions: true,
maxConcurrentSessions: 5,
// Session binding
bindToIP: false,
bindToUserAgent: true,
// Secure cookies
secureCookies: true,
sameSite: 'strict' as const,
httpOnly: true
};
// Configure session security
await pxlpeak.admin.security.configureSessions(sessionConfig);
// View active sessions
const sessions = await pxlpeak.auth.listSessions();
// Revoke specific session
await pxlpeak.auth.revokeSession(sessionId);
// Revoke all sessions (force re-login)
await pxlpeak.auth.revokeAllSessions();API Security
API Key Management
// API Key types and scopes
interface APIKey {
id: string;
name: string;
type: 'server' | 'client' | 'admin';
prefix: string; // First 8 chars for identification
scopes: string[];
createdAt: string;
lastUsedAt: string;
expiresAt?: string;
ipAllowlist?: string[];
rateLimit?: {
requests: number;
windowSeconds: number;
};
}
// Create a server API key
const serverKey = await pxlpeak.apiKeys.create({
name: 'Production Server',
type: 'server',
scopes: [
'events:write',
'analytics:read',
'users:identify'
],
expiresAt: '2027-01-12',
ipAllowlist: ['203.0.113.0/24'],
rateLimit: {
requests: 1000,
windowSeconds: 60
}
});
// Create a client API key (public, limited scope)
const clientKey = await pxlpeak.apiKeys.create({
name: 'Website Tracking',
type: 'client',
scopes: [
'events:write' // Only event ingestion
],
// Client keys have domain restrictions
allowedDomains: ['example.com', '*.example.com']
});
// Rotate API key
const newKey = await pxlpeak.apiKeys.rotate(keyId);
// Revoke API key
await pxlpeak.apiKeys.revoke(keyId);Request Signing
// Sign API requests for additional security
import crypto from 'crypto';
function signRequest(
method: string,
path: string,
body: string,
timestamp: number,
secretKey: string
): string {
const message = `${method}\n${path}\n${timestamp}\n${body}`;
return crypto
.createHmac('sha256', secretKey)
.update(message)
.digest('hex');
}
// Signed request example
const timestamp = Date.now();
const signature = signRequest(
'POST',
'/v1/events',
JSON.stringify(eventData),
timestamp,
process.env.PXLPEAK_SECRET_KEY
);
await fetch('https://api.pxlpeak.com/v1/events', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'X-Pxlpeak-Timestamp': timestamp.toString(),
'X-Pxlpeak-Signature': signature,
'Content-Type': 'application/json'
},
body: JSON.stringify(eventData)
});IP Allowlisting
// Configure IP allowlist for API access
await pxlpeak.admin.security.configureIPAllowlist({
enabled: true,
mode: 'api_only', // or 'all' for dashboard too
// Allowed IP ranges
allowedRanges: [
'203.0.113.0/24', // Office
'198.51.100.0/24', // VPN
'192.0.2.0/24' // Data center
],
// Temporary bypass (for emergencies)
bypassTokenEnabled: true,
bypassTokenExpiry: '24h'
});
// Add IP range dynamically
await pxlpeak.admin.security.addIPRange({
cidr: '10.0.0.0/8',
description: 'Internal network',
expiresAt: null
});Data Security
Data Encryption
// Data encryption configuration (handled by pxlpeak)
const encryptionConfig = {
atRest: {
algorithm: 'AES-256-GCM',
keyManagement: 'AWS KMS',
keyRotation: 'annual'
},
inTransit: {
protocol: 'TLS 1.3',
cipherSuites: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256'
],
certificatePinning: false // Client-side option
},
fieldLevel: {
enabled: true,
encryptedFields: ['user_id', 'email_hash']
}
};
// Enable client-side encryption for sensitive data
pxlpeak.init('YOUR_SITE_ID', {
encryption: {
// Hash user_id before sending
hashFields: ['user_id'],
// Encrypt custom fields
encryptFields: ['custom_sensitive_field'],
publicKey: 'YOUR_PUBLIC_KEY'
}
});PII Handling
// PII protection best practices
const piiProtection = {
// Never track
blocked: [
'email',
'name',
'phone',
'address',
'ssn',
'credit_card',
'password'
],
// Hash before tracking
hashed: [
'email_hash', // SHA256 of normalized email
'phone_hash' // SHA256 of normalized phone
],
// Pseudonymize
pseudonymized: [
'user_id', // Internal ID, not PII
'session_id'
]
};
// Configure PII filtering
pxlpeak.init('YOUR_SITE_ID', {
privacy: {
// Block specific properties
blockedProperties: ['email', 'name', 'phone', 'address'],
// Auto-hash email-like values
autoHashEmails: true,
// Mask IP addresses
ipAnonymization: true,
// Remove query parameters with PII
removeQueryParams: ['email', 'user', 'token']
}
});
// Safe user identification
pxlpeak.identify({
user_id: 'usr_abc123', // Opaque ID - OK
email_hash: hashEmail(email), // Hashed - OK
// email: 'user@example.com' // BLOCKED automatically
});Data Residency
// Data residency configuration
interface DataResidencyConfig {
region: 'us' | 'eu' | 'ap' | 'custom';
processingLocation: string[];
storageLocation: string[];
backupLocation: string[];
}
// Configure EU data residency
await pxlpeak.admin.dataResidency.configure({
region: 'eu',
processingLocation: ['eu-west-1', 'eu-central-1'],
storageLocation: ['eu-west-1'],
backupLocation: ['eu-central-1']
});
// View current data residency
const residency = await pxlpeak.admin.dataResidency.get();
console.log(`Data stored in: ${residency.storageLocation}`);Data Retention
// Configure data retention
await pxlpeak.admin.dataRetention.configure({
// Event data retention
events: {
retentionDays: 365,
aggregationAfterDays: 90 // Aggregate old events
},
// User data retention
users: {
retentionDays: 730,
anonymizeAfterDays: 365 // Remove identifying info
},
// Logs retention
logs: {
retentionDays: 90
},
// Automatic deletion
autoDelete: {
enabled: true,
deleteOn: 'retention_expiry'
}
});
// Manual data deletion
await pxlpeak.admin.data.deleteUser({
userId: 'usr_abc123',
deleteType: 'full', // or 'anonymize'
reason: 'GDPR deletion request'
});
// Bulk data export before deletion
const exportJob = await pxlpeak.admin.data.export({
dataTypes: ['events', 'users'],
dateRange: { start: '2025-01-01', end: '2026-01-12' },
format: 'json',
encrypted: true
});Access Control
Role-Based Access Control (RBAC)
// Built-in roles
const builtInRoles = {
owner: {
description: 'Full access, can delete workspace',
permissions: ['*']
},
admin: {
description: 'Full access except billing and deletion',
permissions: [
'analytics:*',
'settings:*',
'users:*',
'api_keys:*',
'integrations:*'
]
},
editor: {
description: 'Create and modify analytics assets',
permissions: [
'analytics:read',
'analytics:write',
'dashboards:*',
'reports:*',
'goals:*'
]
},
analyst: {
description: 'View and analyze data',
permissions: [
'analytics:read',
'dashboards:read',
'reports:read',
'exports:create'
]
},
viewer: {
description: 'View dashboards only',
permissions: [
'dashboards:read'
]
}
};
// Create custom role
await pxlpeak.admin.roles.create({
name: 'marketing_analyst',
description: 'Marketing team analyst with export access',
permissions: [
'analytics:read',
'dashboards:read',
'dashboards:write',
'reports:read',
'reports:write',
'exports:create',
'exports:download'
],
siteAccess: ['site_marketing', 'site_campaigns']
});
// Assign role to user
await pxlpeak.admin.users.assignRole({
userId: 'user_123',
role: 'marketing_analyst',
scope: 'workspace' // or specific sites
});Resource-Level Permissions
// Site-level access control
await pxlpeak.admin.sites.setPermissions({
siteId: 'site_xxx',
permissions: [
{
userId: 'user_123',
role: 'editor'
},
{
teamId: 'team_marketing',
role: 'analyst'
}
]
});
// Dashboard-level permissions
await pxlpeak.dashboards.setPermissions({
dashboardId: 'dash_xxx',
permissions: {
owner: 'user_123',
editors: ['user_456', 'team_analytics'],
viewers: ['team_marketing', 'team_sales'],
public: false
}
});
// Report-level permissions
await pxlpeak.reports.setPermissions({
reportId: 'rpt_xxx',
permissions: {
canView: ['user_123', 'team_marketing'],
canEdit: ['user_123'],
canShare: ['user_123']
}
});Audit Logging
// All security events are logged
interface AuditLogEntry {
id: string;
timestamp: string;
actor: {
type: 'user' | 'api_key' | 'system';
id: string;
ip: string;
userAgent: string;
};
action: string;
resource: {
type: string;
id: string;
name: string;
};
details: Record<string, any>;
result: 'success' | 'failure' | 'error';
}
// Query audit logs
const logs = await pxlpeak.admin.auditLogs.query({
dateRange: { start: '2026-01-01', end: '2026-01-12' },
actions: ['user.login', 'user.login_failed', 'api_key.created'],
actors: ['user_123'],
resources: ['workspace_xxx'],
results: ['failure'],
limit: 100
});
// Export audit logs
const exportJob = await pxlpeak.admin.auditLogs.export({
dateRange: { start: '2025-01-01', end: '2026-01-12' },
format: 'json',
destination: 's3://audit-logs-bucket/'
});
// Set up audit log streaming
await pxlpeak.admin.auditLogs.configureStreaming({
enabled: true,
destination: {
type: 'siem',
provider: 'splunk',
endpoint: 'https://splunk.company.com:8088/services/collector',
token: process.env.SPLUNK_TOKEN
},
filters: {
severity: ['high', 'critical'],
categories: ['authentication', 'authorization', 'data_access']
}
});Compliance
GDPR Compliance
// GDPR compliance features
const gdprFeatures = {
// Consent management
consent: {
required: true,
granular: true, // Per-purpose consent
withdrawable: true
},
// Data subject rights
rights: {
access: true, // Right to access
rectification: true, // Right to rectification
erasure: true, // Right to be forgotten
portability: true, // Data portability
restriction: true, // Restrict processing
objection: true // Object to processing
},
// Legal basis tracking
legalBasis: {
trackPerUser: true,
defaultBasis: 'consent'
}
};
// Handle GDPR data request
async function handleGDPRRequest(request: GDPRRequest) {
switch (request.type) {
case 'access':
return await pxlpeak.gdpr.exportUserData(request.userId);
case 'erasure':
return await pxlpeak.gdpr.deleteUserData({
userId: request.userId,
scope: 'all',
notify: true
});
case 'rectification':
return await pxlpeak.gdpr.updateUserData({
userId: request.userId,
updates: request.corrections
});
case 'portability':
return await pxlpeak.gdpr.exportUserData({
userId: request.userId,
format: 'json',
machineReadable: true
});
}
}
// Track consent
pxlpeak.consent.update({
userId: 'user_123',
consents: {
analytics: true,
marketing: false,
personalization: true
},
timestamp: new Date().toISOString(),
source: 'cookie_banner'
});SOC 2 Compliance
// SOC 2 Type II certified
// Trust Service Criteria covered:
const soc2Criteria = {
security: {
description: 'Protection against unauthorized access',
controls: [
'Encryption at rest and in transit',
'Multi-factor authentication',
'Role-based access control',
'Network security',
'Vulnerability management'
]
},
availability: {
description: 'System availability as committed',
controls: [
'99.9% uptime SLA',
'Disaster recovery',
'Automated backups',
'Incident response'
]
},
confidentiality: {
description: 'Protection of confidential information',
controls: [
'Data classification',
'Access controls',
'Encryption',
'Secure disposal'
]
},
processingIntegrity: {
description: 'Complete and accurate processing',
controls: [
'Input validation',
'Data quality checks',
'Processing monitoring'
]
},
privacy: {
description: 'Collection and handling of personal data',
controls: [
'Privacy policy',
'Consent management',
'Data minimization',
'Purpose limitation'
]
}
};
// Request SOC 2 report
const report = await pxlpeak.admin.compliance.requestReport({
type: 'soc2',
period: '2025'
});HIPAA Compliance (Healthcare)
// HIPAA BAA available for enterprise customers
const hipaaFeatures = {
// Business Associate Agreement
baaRequired: true,
// PHI handling
phi: {
encryptionRequired: true,
auditLogging: true,
accessControls: true,
minimumNecessary: true
},
// Additional safeguards
safeguards: {
administrative: [
'Workforce training',
'Access management',
'Security incident procedures'
],
physical: [
'Facility access controls',
'Workstation security',
'Device controls'
],
technical: [
'Access controls',
'Audit controls',
'Integrity controls',
'Transmission security'
]
}
};
// Configure HIPAA mode
await pxlpeak.admin.compliance.enableHIPAA({
baaId: 'baa_xxx',
additionalControls: {
auditLogRetention: 'six_years',
accessReviewFrequency: 'quarterly',
minimumNecessary: true
}
});Security Best Practices
Implementation Checklist
## Security Checklist
### Authentication
- [ ] Enable MFA for all users
- [ ] Configure SSO if available
- [ ] Set appropriate session timeouts
- [ ] Disable unused authentication methods
### API Security
- [ ] Use server-side API keys for sensitive operations
- [ ] Rotate API keys regularly (quarterly)
- [ ] Configure IP allowlists where possible
- [ ] Monitor API key usage
### Data Protection
- [ ] Enable PII filtering
- [ ] Configure data retention policies
- [ ] Set up data residency if required
- [ ] Review collected data regularly
### Access Control
- [ ] Apply principle of least privilege
- [ ] Review user permissions quarterly
- [ ] Remove inactive users promptly
- [ ] Use teams for group permissions
### Monitoring
- [ ] Enable audit logging
- [ ] Set up security alerts
- [ ] Review audit logs regularly
- [ ] Stream logs to SIEM if available
### Compliance
- [ ] Complete compliance assessment
- [ ] Sign required agreements (DPA, BAA)
- [ ] Document data processing activities
- [ ] Train team on compliance requirementsSecurity Headers
// Recommended security headers for your site
const securityHeaders = {
// Content Security Policy
'Content-Security-Policy': `
default-src 'self';
script-src 'self' https://cdn.pxlpeak.com;
connect-src 'self' https://api.pxlpeak.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
`.replace(/\s+/g, ' ').trim(),
// Prevent clickjacking
'X-Frame-Options': 'DENY',
// Prevent MIME sniffing
'X-Content-Type-Options': 'nosniff',
// Referrer policy
'Referrer-Policy': 'strict-origin-when-cross-origin',
// Permissions policy
'Permissions-Policy': 'geolocation=(), microphone=(), camera=()'
};Incident Response
// Security incident reporting
async function reportSecurityIncident(incident: SecurityIncident) {
// 1. Immediately report to pxlpeak
await pxlpeak.security.reportIncident({
type: incident.type,
severity: incident.severity,
description: incident.description,
affectedResources: incident.resources,
discoveredAt: incident.discoveredAt
});
// 2. pxlpeak response SLAs
const responseSLA = {
critical: '1 hour',
high: '4 hours',
medium: '24 hours',
low: '72 hours'
};
// 3. Security contact
// security@pxlpeak.com
}
// Vulnerability disclosure
// https://www.pxlpeak.com/security/vulnerability-disclosureSecurity Resources
Documentation
- Security Whitepaper
- Privacy Policy
- Data Processing Agreement
- SOC 2 Report (available to customers)
Contacts
- Security Team: security@pxlpeak.com
- Privacy Team: privacy@pxlpeak.com
- Compliance: compliance@pxlpeak.com
Bug Bounty
We run a responsible disclosure program. Report security vulnerabilities to security@pxlpeak.com.
Next Steps
- Review Current Setup - Audit your security configuration
- Enable MFA - Require MFA for all users
- Configure RBAC - Apply least privilege access
- Enable Audit Logging - Track all security events
- Complete Compliance - Sign necessary agreements
Related Guides: