:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import sodium from 'libsodium-wrappers'
import {
EncryptResult,
KeyStore,
RecordingEncryptor,
SessionKey,
SessionKeyDeletedError,
} from '~/ingestion/pipelines/sessionreplay/shared/types'
export class SodiumRecordingEncryptor implements RecordingEncryptor {
constructor(private keyStore: KeyStore) {}
async start(): Promise<void> {
await sodium.ready
}
async encryptBlock(sessionId: string, teamId: number, blockData: Buffer): Promise<EncryptResult> {
const sessionKey = await this.keyStore.getKey(sessionId, teamId)
return this.encryptBlockWithKey(sessionId, teamId, blockData, sessionKey)
}
encryptBlockWithKey(sessionId: string, teamId: number, blockData: Buffer, sessionKey: SessionKey): EncryptResult {
if (sessionKey.sessionState === 'deleted') {
throw new SessionKeyDeletedError(sessionId, teamId, sessionKey.deletedAt)
}
if (sessionKey.sessionState === 'cleartext') {
return { data: blockData, sessionState: 'cleartext' }
}
// Generate a unique nonce for this block
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES)
// Encrypt block data
const cipherText = sodium.crypto_secretbox_easy(blockData, nonce, sessionKey.plaintextKey)
// Prepend nonce to the ciphertext
return { data: Buffer.concat([Buffer.from(nonce), Buffer.from(cipherText)]), sessionState: 'ciphertext' }
}
}