Skip to main content

Idiomark Security Documentation

Version: 1.0.0 | Last Updated: 2026-02-10

This document outlines security considerations, best practices, and implementation guidelines for the Idiomark.


Table of Contents​

  1. Overview
  2. Data Privacy
  3. OAuth Security
  4. File Security
  5. API Security
  6. Privacy Best Practices
  7. Security Audit Checklist
  8. Vulnerability Reporting

Overview​

Idiomark is designed with a privacy-first architecture. The protocol prioritizes user control, data minimization, and transparent data handling throughout the extraction, analysis, and inference lifecycle.

Security Principles​

  1. User Control: Users own their data and personality profiles
  2. Data Minimization: Only necessary data is collected and processed
  3. Transparency: All data collection and processing is disclosed
  4. No Permanent Raw Storage: Platform data is processed, not archived
  5. Secure by Default: All implementations follow security best practices

Data Privacy​

What Data is Collected​

Idiomark collects derived personality data from public or user-owned platform content. The protocol does not store raw platform content permanently.

Data TypeSourceStorage DurationRetention Policy
Public ContentTwitter, GitHub, RedditTransient (processed immediately)Not retained
User MetadataPlatform APIsSession onlyCleared on completion
OAuth TokensPlatform AuthorizationSecure storage onlyRevocable
Idiomark FilesGenerated AnalysisUser-controlledUser managed

Data Classification​

┌─────────────────────────────────────────────────────────────┐
│ DATA CLASSIFICATION │
├─────────────────────────────────────────────────────────────┤
│ │
│ PUBLIC DATA ← Tweets, issues, comments (public) │
│ ↓ │
│ DERIVED DATA ← Personality metrics (aggregated) │
│ ↓ │
│ SENSITIVE DATA ← OAuth tokens, credentials (protected)│
│ ↓ │
│ PERSONAL DATA ← User identity, preferences (private) │
│ │
└─────────────────────────────────────────────────────────────┘

Data Storage Guidelines​

Raw Platform Data​

MUST NOT be stored permanently. Raw content from platforms (tweets, issues, comments) should:

  1. Be fetched and processed in memory
  2. Be converted to normalized format immediately
  3. Be discarded after personality extraction
// BAD: Storing raw platform data
const rawTweets = await fetchTweets()
await db.save('raw_tweets', rawTweets) // ❌ Violates privacy

// GOOD: Process and discard
const rawTweets = await fetchTweets()
const normalized = rawTweets.map(t => normalize(t))
const personality = await analyze(normalized)
// rawTweets is garbage collected ✅

Idiomark File Storage​

Idiomark files contain derived personality metrics, not raw content. When storing Idiomark files:

  1. Use user-controlled storage (local filesystem, user-provided cloud)
  2. Implement optional encryption for sensitive deployments
  3. Include metadata timestamp for accountability
// Recommended Idiomark file storage
interface IdiomarkStorage {
save(file: IdiomarkFile, options: {
encrypt?: boolean,
key?: string,
location: 'local' | 'user-cloud'
}): Promise<void>
}

Retention Policy​

Data TypeRetention PeriodDeletion Mechanism
Raw Platform Content0 secondsImmediate after processing
Session Data24 hoursAutomatic session cleanup
OAuth TokensUntil revocationUser-initiated revocation
Idiomark FilesIndefiniteUser-controlled deletion
Job Results7 daysAutomatic cleanup

OAuth Security​

Idiomark implementations MUST use PKCE (Proof Key for Code Exchange) for all OAuth 2.0 flows where supported.

Implementation Example​

// Generate code verifier and challenge
async function generatePKCE() {
// 1. Create code verifier (cryptographically random)
const codeVerifier = generateRandomString(43)

// 2. Create code challenge (SHA-256 hash)
const encoder = new TextEncoder()
const data = encoder.encode(codeVerifier)
const digest = await crypto.subtle.digest('SHA-256', data)
const codeChallenge = base64URLEncode(digest)

return { codeVerifier, codeChallenge }
}

// Authorization request
const authUrl = `https://platform.com/oauth/authorize?` + new URLSearchParams({
response_type: 'code',
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: 'tweet.read users.read',
state: generateState(),
code_challenge: codeChallenge,
code_challenge_method: 'S256'
})

Token Handling​

Secure Storage​

OAuth tokens MUST be stored securely:

// Environment-based configuration
const oauthConfig = {
clientId: process.env.PLATFORM_CLIENT_ID,
clientSecret: process.env.PLATFORM_CLIENT_SECRET, // Server-side only
redirectUri: process.env.PLATFORM_REDIRECT_URI
}

// Token storage (never expose to client)
interface TokenStorage {
getToken(userId: string): Promise<string | null>
setToken(userId: string, token: string): Promise<void>
deleteToken(userId: string): Promise<void>
}

Token Lifecycle​

// Token refresh with error handling
async function refreshAccessToken(refreshToken: string) {
try {
const response = await fetch(tokenEndpoint, {
method: 'POST',
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
client_secret: clientSecret
})
})

if (!response.ok) {
// Revoke token on refresh failure
await revokeToken(refreshToken)
throw new Error('Token refresh failed')
}

return await response.json()
} catch (error) {
// Clear local token storage
await tokenStorage.delete(userId)
throw error
}
}

Scope Limitations​

Idiomark implementations MUST request minimum necessary scopes:

PlatformRequired ScopesPurpose
Twittertweet.read, users.readRead tweets and user profile
GitHubread:user, repo (status only)Read user profile and repo metadata
Reddithistory, readRead user's post history
// Scope configuration by platform
const SCOPE_LIMITS = {
twitter: ['tweet.read', 'users.read', 'like.read'],
github: ['read:user', 'read:org', 'public_repo'],
reddit: ['history', 'read', 'subscribe']
}

function validateScopes(platform: string, scopes: string[]) {
const allowed = SCOPE_LIMITS[platform]
const invalid = scopes.filter(s => !allowed.includes(s))

if (invalid.length > 0) {
throw new Error(`Invalid scopes for ${platform}: ${invalid.join(', ')}`)
}
}

State Parameter Security​

Always use a secure, unpredictable state parameter:

// Cryptographically secure state generation
function generateState(): string {
const array = new Uint8Array(16)
crypto.getRandomValues(array)
return Array.from(array, b => b.toString(16).padStart(2, '0')).join('')
}

// Store state server-side for verification
interface StateStore {
set(state: string, timestamp: number): void
get(state: string): { timestamp: number } | null
delete(state: string): void
}

// Verify state in callback
async function handleCallback(code: string, state: string, redirectUri: string) {
const stored = stateStore.get(state)

if (!stored) {
throw new Error('Invalid state parameter')
}

// Check state age (reject after 10 minutes)
if (Date.now() - stored.timestamp > 10 * 60 * 1000) {
stateStore.delete(state)
throw new Error('State expired')
}

stateStore.delete(state)

// Proceed with token exchange...
}

File Security​

Idiomark File Structure​

The .idiomark file format is designed to be self-contained and safe:

{
"idiomark": "1.0.0",
"id": "idiomark_<uuid>",
"created": "2026-02-10T00:00:00Z",
"updated": "2026-02-10T00:00:00Z",
"metadata": {
"entity": {
"name": "Optional Entity Name",
"type": "human|brand|bot|fictional",
"sources": ["twitter", "github"]
},
"extraction": {
"date": "2026-02-10T00:00:00Z",
"sample_size": 1250,
"timeframe": {
"from": "2023-01-01T00:00:00Z",
"to": "2026-02-10T00:00:00Z"
}
}
},
"personality": {
"voice": {},
"patterns": {},
"domains": [],
"values": [],
"knowledge": {}
},
"signature": "<hash>"
}

File Integrity​

Idiomark files SHOULD include a signature for integrity verification:

// Signature generation
import { createHash } from 'crypto'

function signIdiomarkFile(idiomarkData: IdiomarkFile): string {
// Exclude signature field from hash
const { signature, ...dataToSign } = idiomarkData

// Sort keys for consistent hashing
const normalized = JSON.stringify(dataToSign, Object.keys(dataToSign).sort())

// Create SHA-256 hash
return createHash('sha256').update(normalized).digest('hex')
}

// Signature verification
function verifyIdiomarkFile(idiomarkData: IdiomarkFile): boolean {
const { signature } = idiomarkData

if (!signature) {
return false // Unsigned files are not trusted
}

const computed = signIdiomarkFile(idiomarkData)
return computed === signature
}

Sensitive Data Handling​

Idiomark files SHOULD NOT contain:

  • Raw platform content (verbatim tweets, posts, comments)
  • Private credentials (API keys, tokens)
  • Personally Identifiable Information (PII) beyond necessary metadata
  • Third-party content (content from users other than the entity)
// Content sanitization before Idiomark generation
function sanitizeContent(content: NormalizedContent[]): SanitizedContent[] {
return content.map(item => ({
id: item.id,
text: item.text,
// Remove raw platform data
timestamp: item.timestamp,
metrics: item.metrics,
metadata: {
language: item.metadata?.language,
// Remove sensitive metadata
hashtags: item.metadata?.hashtags,
mentions: item.metadata?.mentions
}
}))
}

File Encryption (Optional)​

For sensitive deployments, Idiomark files can be encrypted:

// Optional AES-256-GCM encryption
import { createCipheriv, createDecipheriv, randomBytes, scrypt } from 'crypto'

async function encryptIdiomarkFile(
idiomarkData: IdiomarkFile,
password: string
): Promise<{ data: Buffer; iv: Buffer; salt: Buffer }> {
const salt = randomBytes(16)
const iv = randomBytes(16)

// Derive key from password
const key = await scrypt(password, salt, 32) as Buffer

// Encrypt data
const cipher = createCipheriv('aes-256-gcm', key, iv)
const plaintext = JSON.stringify(idiomarkData)
const encrypted = Buffer.concat([
cipher.update(plaintext, 'utf8'),
cipher.final()
])
const authTag = cipher.getAuthTag()

return {
data: Buffer.concat([encrypted, authTag]),
iv,
salt
}
}

API Security​

Rate Limiting​

All platform adapters MUST respect platform rate limits:

// Twitter rate limiting (300 requests per 3 hours)
interface RateLimiter {
requests: number
maxRequests: number
windowStart: number
windowDuration: number
}

async function checkRateLimit(limiter: RateLimiter): Promise<void> {
const now = Date.now()
const windowElapsed = now - limiter.windowStart

// Reset window if expired
if (windowElapsed > limiter.windowDuration) {
limiter.requests = 0
limiter.windowStart = now
}

// Wait if limit reached
if (limiter.requests >= limiter.maxRequests) {
const waitTime = limiter.windowDuration - windowElapsed
await sleep(waitTime)
limiter.requests = 0
limiter.windowStart = Date.now()
}

limiter.requests++
}

Platform-Specific Limits​

PlatformRate LimitImplementation
Twitter300 req / 3hrSliding window
GitHub5000 req / hrHeader-based
Reddit60 req / minFixed window

Input Validation​

All API inputs MUST be validated:

// Platform validation
const SUPPORTED_PLATFORMS = ['twitter', 'github', 'reddit'] as const

function validatePlatforms(platforms: string[]): ValidationResult {
if (!platforms || platforms.length === 0) {
return { valid: false, error: 'At least one platform required' }
}

const invalid = platforms.filter(p => !SUPPORTED_PLATFORMS.includes(p as any))
if (invalid.length > 0) {
return { valid: false, error: `Invalid platforms: ${invalid.join(', ')}` }
}

return { valid: true }
}

// Sample size validation
function validateSampleSize(size: number): ValidationResult {
if (size < 10) return { valid: false, error: 'Minimum 10 items required' }
if (size > 10000) return { valid: false, error: 'Maximum 10000 items allowed' }
return { valid: true }
}

// Filename validation
function validateFilename(filename: string): ValidationResult {
if (!filename || filename.length === 0 || filename.length > 255) {
return { valid: false, error: 'Filename must be 1-255 characters' }
}

// Prevent path traversal
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
return { valid: false, error: 'Invalid filename characters' }
}

// Prevent executable extensions
if (/\.(exe|sh|bat|cmd|ps1)$/i.test(filename)) {
return { valid: false, error: 'Executable files not allowed' }
}

return { valid: true }
}

Authentication​

For production deployments, implement API authentication:

// API key authentication middleware
interface APIKey {
key: string
userId: string
rateLimit: number
scopes: string[]
}

async function authenticateAPI(request: Request): Promise<APIKey | null> {
const apiKey = request.headers.get('X-API-Key')

if (!apiKey) {
return null
}

// Lookup key in database
const key = await db.apiKeys.findUnique({ where: { key: apiKey } })

if (!key || key.revoked) {
return null
}

// Check rate limit
const usage = await db.apiUsage.count({
where: { apiKeyId: key.id, timestamp: { gte: Date.now() - 3600000 } }
})

if (usage >= key.rateLimit) {
throw new Error('Rate limit exceeded')
}

return key
}

Error Handling​

Never expose sensitive information in error messages:

// BAD: Exposing internal details
return NextResponse.json({
error: 'Database connection failed: Connection refused at localhost:5432'
}, { status: 500 })

// GOOD: Generic error message
return NextResponse.json({
error: 'Internal server error',
code: 'INTERNAL_ERROR'
}, { status: 500 })

// For development, use verbose logging server-side
console.error('Database error:', {
message: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
})

Privacy Best Practices​

Explicit consent MUST be obtained before data extraction:

interface ConsentRecord {
userId: string
platforms: string[]
timestamp: number
ipAddress: string
userAgent: string
}

// Consent tracking
async function recordConsent(
userId: string,
platforms: string[],
request: Request
): Promise<void> {
const consent: ConsentRecord = {
userId,
platforms,
timestamp: Date.now(),
ipAddress: request.headers.get('x-forwarded-for') || 'unknown',
userAgent: request.headers.get('user-agent') || 'unknown'
}

await db.consents.create({ data: consent })
}

// Consent verification
async function checkConsent(userId: string, platform: string): Promise<boolean> {
const consent = await db.consents.findFirst({
where: {
userId,
platforms: { has: platform }
}
})

return !!consent
}

Right to Deletion​

Users MUST be able to delete their data:

// GDPR/CCPA compliance
async function deleteUserData(userId: string): Promise<void> {
// Delete Idiomark files
await db.idiomarkFiles.deleteMany({ where: { userId } })

// Delete consent records
await db.consents.deleteMany({ where: { userId } })

// Delete OAuth tokens
await db.oauthTokens.deleteMany({ where: { userId } })

// Delete job history
await db.extractionJobs.deleteMany({ where: { userId } })

// Log deletion for audit
await db.auditLog.create({
data: {
action: 'DELETE_USER_DATA',
userId,
timestamp: Date.now(),
reason: 'User request'
}
})
}

Data Portability​

Users MUST be able to export their data:

// Data export functionality
async function exportUserData(userId: string): Promise<DataExport> {
const [idiomarkFiles, consents, jobs] = await Promise.all([
db.idiomarkFiles.findMany({ where: { userId } }),
db.consents.findMany({ where: { userId } }),
db.extractionJobs.findMany({ where: { userId } })
])

return {
format: 'idiomark-export',
version: '1.0',
exportedAt: new Date().toISOString(),
data: {
idiomarkFiles,
consents,
jobs
}
}
}

Privacy Preserving Analysis​

Use aggregation and anonymization:

// Anonymized metrics
interface AnonymizedMetrics {
sampleSize: number
timeframe: { from: string; to: string }
platform: string
// No user identifiers
}

// Differential privacy for metrics
function addNoise(value: number, epsilon: number = 0.1): number {
// Add Laplace noise for differential privacy
const scale = 1 / epsilon
const u = Math.random() - 0.5
return value + -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u))
}

Security Audit Checklist​

Implementation Review​

  • OAuth 2.0 with PKCE implemented
  • State parameter validation
  • Token storage is secure (never exposed to client)
  • Rate limiting implemented per platform
  • Input validation on all API endpoints
  • Output encoding to prevent XSS
  • SQL injection prevention (parameterized queries)
  • CSRF protection for state-changing operations

Data Protection​

  • Raw platform data not permanently stored
  • Idiomark files contain no raw content
  • User consent obtained before extraction
  • Right to deletion implemented
  • Data export functionality available
  • Encryption options available for sensitive deployments
  • Audit logging for security events

API Security​

  • API key authentication for production
  • Rate limiting per API key
  • Request size limits
  • Timeout configurations
  • Error messages don't expose internals
  • Security headers (CORS, CSP, etc.)
  • HTTPS only in production

Platform Adapters​

  • Minimum scopes requested
  • Platform rate limits respected
  • Token refresh implemented
  • Error handling for API failures
  • Pagination support for large datasets
  • Timeout handling for network requests

Compliance​

  • GDPR compliance (EU users)
  • CCPA compliance (California users)
  • Privacy policy published
  • Terms of service published
  • Cookie policy (if applicable)
  • Data processing agreement available

Vulnerability Reporting​

Responsible Disclosure​

If you discover a security vulnerability, please report it responsibly.

Reporting Process​

  1. Email: Send details to security@idiomark.org
  2. Include: Description, steps to reproduce, impact assessment
  3. Timeline: We aim to respond within 48 hours
  4. Disclosure: Coordinated disclosure after fix is deployed

Security Policy​

  • We investigate all reported vulnerabilities
  • We credit researchers in our security advisories
  • We work with researchers to understand and fix issues
  • We maintain confidentiality during the fix process

Bug Bounty​

Currently, we do not have a formal bug bounty program. However, we recognize responsible disclosure and may offer rewards for critical vulnerabilities at our discretion.

Security Advisories​

Past security advisories will be published at:

https://github.com/idiomark/security-advisories

Additional Resources​

Security Standards​

  • OWASP Top 10: Web application security risks
  • OWASP ASVS: Application security verification standard
  • GDPR: General Data Protection Regulation
  • CCPA: California Consumer Privacy Act

Contact​

For security questions or concerns:

  • Email: security@idiomark.org
  • PGP Key: Available on keyserver

Copyright (C) 2026 Idiomark contributors. Licensed under BUSL 1.1.