Skip to content

: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.

refactor: Support for multiple encryption keys in nodejs Temporal (#61177)

Tomás Farías Santanafa0e9fbfd44e
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/codec.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/codec.test.ts
index 1c8fec0acba2..937de0a282c2 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/codec.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/codec.test.ts
@@ -12,9 +12,21 @@ const PYTHON_FIXTURE = {
const te = new TextEncoder()
const td = new TextDecoder()
+const TEST_SECRET_KEY = 'test-secret-key-for-codec-000000'
+const ENCODED_KEY_BYTES = Buffer.from('decaf???'.repeat(4), 'utf-8')
+const ENCODED_KEY_BASE64 = ENCODED_KEY_BYTES.toString('base64')
+const ENCODED_KEY_BASE64_URLSAFE = ENCODED_KEY_BASE64.replace(/\+/g, '-').replace(/\//g, '_')
+
+function restoreNodeEnv(nodeEnv: string | undefined): void {
+ if (nodeEnv === undefined) {
+ delete process.env.NODE_ENV
+ return
+ }
+ process.env.NODE_ENV = nodeEnv
+}
describe('EncryptionCodec', () => {
- const codec = new EncryptionCodec(PYTHON_FIXTURE.secretKey)
+ const codec = new EncryptionCodec(TEST_SECRET_KEY)
it('round-trips encode then decode', async () => {
const original = {
@@ -33,17 +45,82 @@ describe('EncryptionCodec', () => {
})
it('decodes a token encrypted by the Python EncryptionCodec', async () => {
- const encryptedToken = Buffer.from(PYTHON_FIXTURE.encryptedTokenB64, 'base64')
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation()
+ try {
+ const pythonCodec = new EncryptionCodec(PYTHON_FIXTURE.secretKey)
+ const encryptedToken = Buffer.from(PYTHON_FIXTURE.encryptedTokenB64, 'base64')
- const outerPayload = {
- metadata: { encoding: te.encode('binary/encrypted') },
- data: encryptedToken,
+ const outerPayload = {
+ metadata: { encoding: te.encode('binary/encrypted') },
+ data: encryptedToken,
+ }
+
+ const decoded = await pythonCodec.decode([outerPayload])
+ expect(decoded).toHaveLength(1)
+ expect(td.decode(decoded[0].metadata!['encoding']!)).toBe('json/plain')
+ expect(td.decode(decoded[0].data!)).toBe('{"key":"value"}')
+ expect(warnSpy).toHaveBeenCalledWith(
+ 'EncryptionCodec: secret key is only 25 bytes; use a 32-byte key in production'
+ )
+ } finally {
+ warnSpy.mockRestore()
}
+ })
+
+ it('decodes payloads encrypted with fallback keys', async () => {
+ const original = {
+ metadata: { encoding: te.encode('json/plain') },
+ data: te.encode('{"rotated":true}'),
+ }
+ const oldSecretKey = 'old-secret-key-for-codec-0000000'
+ const oldCodec = new EncryptionCodec(oldSecretKey)
+ const rotatedCodec = new EncryptionCodec('new-secret-key-for-codec-0000000', [
+ 'older-secret-key-for-codec-00000',
+ oldSecretKey,
+ ])
+
+ const encodedWithOldKey = await oldCodec.encode([original])
+ const decoded = await rotatedCodec.decode(encodedWithOldKey)
- const decoded = await codec.decode([outerPayload])
expect(decoded).toHaveLength(1)
expect(td.decode(decoded[0].metadata!['encoding']!)).toBe('json/plain')
- expect(td.decode(decoded[0].data!)).toBe('{"key":"value"}')
+ expect(td.decode(decoded[0].data!)).toBe('{"rotated":true}')
+ })
+
+ it.each([
+ { encoding: 'hex', secretKey: `hex:${ENCODED_KEY_BYTES.toString('hex')}` },
+ { encoding: 'base64-urlsafe', secretKey: `base64-urlsafe:${ENCODED_KEY_BASE64_URLSAFE}` },
+ { encoding: 'base64', secretKey: `base64:${ENCODED_KEY_BASE64}` },
+ ])('loads $encoding secret keys as decoded bytes', async ({ secretKey }) => {
+ const original = {
+ metadata: { encoding: te.encode('json/plain') },
+ data: te.encode('{"encoded":true}'),
+ }
+ const legacyCodec = new EncryptionCodec(ENCODED_KEY_BYTES.toString('utf-8'))
+ const encodedKeyCodec = new EncryptionCodec(secretKey)
+
+ const encodedWithLegacyKey = await legacyCodec.encode([original])
+ const decoded = await encodedKeyCodec.decode(encodedWithLegacyKey)
+
+ expect(td.decode(decoded[0].data!)).toBe('{"encoded":true}')
+ })
+
+ it('encrypts with the primary key instead of fallback keys', async () => {
+ const original = {
+ metadata: { encoding: te.encode('json/plain') },
+ data: te.encode('{"primary":true}'),
+ }
+ const primarySecretKey = 'new-secret-key-for-codec-0000000'
+ const oldSecretKey = 'old-secret-key-for-codec-0000000'
+ const primaryCodec = new EncryptionCodec(primarySecretKey)
+ const oldCodec = new EncryptionCodec(oldSecretKey)
+ const rotatedCodec = new EncryptionCodec(primarySecretKey, [oldSecretKey])
+
+ const encoded = await rotatedCodec.encode([original])
+
+ const decodedWithPrimary = await primaryCodec.decode(encoded)
+ expect(td.decode(decodedWithPrimary[0].data!)).toBe('{"primary":true}')
+ await expect(oldCodec.decode(encoded)).rejects.toThrow('HMAC verification failed')
})
it('passes through payloads without encrypted encoding', async () => {
@@ -118,28 +195,76 @@ describe('EncryptionCodec', () => {
await expect(codec.decode([tooShort])).rejects.toThrow('Fernet token too short')
})
- it('round-trips with short secret keys (padding)', async () => {
- const shortCodec = new EncryptionCodec('ab')
- const original = {
- metadata: { encoding: te.encode('json/plain') },
- data: te.encode('test'),
+ it('rejects empty secret keys', () => {
+ expect(() => new EncryptionCodec('')).toThrow('EncryptionCodec: empty secret key is not allowed')
+ expect(() => new EncryptionCodec(TEST_SECRET_KEY, [''])).toThrow(
+ 'EncryptionCodec: empty secret key is not allowed'
+ )
+ })
+
+ it('rejects short secret keys in production', () => {
+ const originalNodeEnv = process.env.NODE_ENV
+ process.env.NODE_ENV = 'production'
+
+ try {
+ expect(() => new EncryptionCodec('ab')).toThrow(
+ 'EncryptionCodec: secret key must be at least 32 bytes in production (got 2)'
+ )
+ expect(() => new EncryptionCodec('base64:YWI=')).toThrow(
+ 'EncryptionCodec: secret key must be at least 32 bytes in production (got 2)'
+ )
+ } finally {
+ restoreNodeEnv(originalNodeEnv)
}
+ })
- const encoded = await shortCodec.encode([original])
- const decoded = await shortCodec.decode(encoded)
- expect(td.decode(decoded[0].data!)).toBe('test')
+ it.each([
+ { secretKey: 'hex:not-hex', error: 'EncryptionCodec: invalid hex secret key' },
+ { secretKey: 'base64:not-base64!', error: 'EncryptionCodec: invalid base64 secret key' },
+ { secretKey: 'base64-urlsafe:not/base64url', error: 'EncryptionCodec: invalid base64-urlsafe secret key' },
+ ])('rejects invalid encoded secret keys', ({ secretKey, error }) => {
+ expect(() => new EncryptionCodec(secretKey)).toThrow(error)
})
- it('round-trips with long secret keys (truncation)', async () => {
- const longCodec = new EncryptionCodec('a'.repeat(100))
- const original = {
- metadata: { encoding: te.encode('json/plain') },
- data: te.encode('test'),
+ it('round-trips with short secret keys (padding)', async () => {
+ const originalNodeEnv = process.env.NODE_ENV
+ process.env.NODE_ENV = 'test'
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation()
+ try {
+ const shortCodec = new EncryptionCodec('ab')
+ const original = {
+ metadata: { encoding: te.encode('json/plain') },
+ data: te.encode('test'),
+ }
+
+ const encoded = await shortCodec.encode([original])
+ const decoded = await shortCodec.decode(encoded)
+ expect(td.decode(decoded[0].data!)).toBe('test')
+ expect(warnSpy).toHaveBeenCalledWith(
+ 'EncryptionCodec: secret key is only 2 bytes; use a 32-byte key in production'
+ )
+ } finally {
+ warnSpy.mockRestore()
+ restoreNodeEnv(originalNodeEnv)
}
+ })
- const encoded = await longCodec.encode([original])
- const decoded = await longCodec.decode(encoded)
- expect(td.decode(decoded[0].data!)).toBe('test')
+ it('round-trips with long secret keys (truncation)', async () => {
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation()
+ try {
+ const longCodec = new EncryptionCodec('a'.repeat(100))
+ const original = {
+ metadata: { encoding: te.encode('json/plain') },
+ data: te.encode('test'),
+ }
+
+ const encoded = await longCodec.encode([original])
+ const decoded = await longCodec.decode(encoded)
+ expect(td.decode(decoded[0].data!)).toBe('test')
+ expect(warnSpy).toHaveBeenCalledWith('EncryptionCodec: secret key is 100 bytes, truncating to 32')
+ } finally {
+ warnSpy.mockRestore()
+ }
})
it('produces base64url-encoded tokens that decode to Fernet version 0x80', async () => {
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
index 3f13bb68b77a..cb557c412c54 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
@@ -1,4 +1,5 @@
import { buildCaptureConfig, buildPlayerConfig, validateInput } from '../capture/config'
+import { parseList } from '../config'
import { RasterizeRecordingInput } from '../types'
function baseInput(overrides: Partial<RasterizeRecordingInput> = {}): RasterizeRecordingInput {
@@ -12,6 +13,35 @@ function baseInput(overrides: Partial<RasterizeRecordingInput> = {}): RasterizeR
}
describe('config', () => {
+ describe('parseList', () => {
+ it.each([
+ { text: undefined, expected: [] },
+ { text: '', expected: [] },
+ { text: 'a,b, c ', expected: ['a', 'b', 'c'] },
+ { text: 'a,,b', expected: ['a', '', 'b'] },
+ ])('parses $text', ({ text, expected }) => {
+ expect(parseList(text)).toEqual(expected)
+ })
+
+ it('filters empty fallback keys from config', async () => {
+ const originalFallbackKeys = process.env.TEMPORAL_FALLBACK_SECRET_KEYS
+ process.env.TEMPORAL_FALLBACK_SECRET_KEYS = 'a,,b,'
+
+ try {
+ jest.resetModules()
+ const { config } = await import('../config.js')
+ expect(config.fallbackKeys).toEqual(['a', 'b'])
+ } finally {
+ if (originalFallbackKeys === undefined) {
+ delete process.env.TEMPORAL_FALLBACK_SECRET_KEYS
+ } else {
+ process.env.TEMPORAL_FALLBACK_SECRET_KEYS = originalFallbackKeys
+ }
+ jest.resetModules()
+ }
+ })
+ })
+
describe('validateInput', () => {
it('accepts valid input', () => {
expect(() => validateInput(baseInput())).not.toThrow()
diff --git a/nodejs/src/session-replay/recording-rasterizer/config.ts b/nodejs/src/session-replay/recording-rasterizer/config.ts
index 6b2620cdcf8f..5b76b24ee84c 100644
--- a/nodejs/src/session-replay/recording-rasterizer/config.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/config.ts
@@ -1,3 +1,10 @@
+export function parseList(text: string | undefined): string[] {
+ if (!text) {
+ return []
+ }
+ return text.split(',').map((item) => item.trim())
+}
+
export const config = {
// Temporal
temporalHost: process.env.TEMPORAL_HOST || '127.0.0.1',
@@ -19,7 +26,8 @@ export const config = {
metricsPort: parseInt(process.env.METRICS_PORT || '6738', 10),
// Encryption
- secretKey: process.env.SECRET_KEY,
+ secretKey: process.env.TEMPORAL_SECRET_KEY || process.env.SECRET_KEY,
+ fallbackKeys: parseList(process.env.TEMPORAL_FALLBACK_SECRET_KEYS ?? process.env.SECRET_KEY).filter(Boolean),
// S3
s3Endpoint: process.env.VIDEO_EXPORT_OBJECT_STORAGE_ENDPOINT,
diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/codec.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/codec.ts
index e452b5168921..7f06123ea525 100644
--- a/nodejs/src/session-replay/recording-rasterizer/temporal/codec.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/codec.ts
@@ -9,30 +9,107 @@ const FERNET_VERSION = 0x80
const FERNET_HEADER_SIZE = 1 + 8 + 16 // version + timestamp + IV
const HMAC_SIZE = 32
+type FernetKey = {
+ signingKey: Buffer
+ encryptionKey: Buffer
+}
+
+type RawSecretKey = string | Uint8Array
+
+function decodeHex(secret: string): Buffer {
+ const normalized = secret.replace(/\s/g, '')
+ if (normalized.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(normalized)) {
+ throw new Error('EncryptionCodec: invalid hex secret key')
+ }
+ return Buffer.from(normalized, 'hex')
+}
+
+function decodeBase64(secret: string): Buffer {
+ if (secret.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(secret)) {
+ throw new Error('EncryptionCodec: invalid base64 secret key')
+ }
+ return Buffer.from(secret, 'base64')
+}
+
+function decodeBase64Urlsafe(secret: string): Buffer {
+ if (secret.length % 4 !== 0 || !/^[A-Za-z0-9_-]*={0,2}$/.test(secret)) {
+ throw new Error('EncryptionCodec: invalid base64-urlsafe secret key')
+ }
+ return Buffer.from(secret, 'base64url')
+}
+
/**
* Fernet-compatible encryption codec that matches PostHog's Python EncryptionCodec.
*
- * The Python side (posthog/temporal/common/codec.py) derives a Fernet key from
- * Django's SECRET_KEY: zero-pad to 32 bytes, base64url-encode. The first 16 bytes
- * of the decoded key are the HMAC-SHA256 signing key, the last 16 bytes are the
- * AES-128-CBC encryption key.
+ * The Python side (posthog/temporal/common/codec.py) derives each Fernet key by
+ * zero-padding to 32 bytes, then base64url-encoding. The first 16 decoded bytes
+ * are the HMAC-SHA256 signing key, and the last 16 are the AES-128-CBC key.
*/
export class EncryptionCodec implements PayloadCodec {
- private signingKey: Buffer
- private encryptionKey: Buffer
+ private primaryKey: FernetKey
+ private fallbackKeys: FernetKey[]
+
+ constructor(secretKey: RawSecretKey, fallbackKeys: RawSecretKey[] = []) {
+ this.primaryKey = this.prepareKey(secretKey)
+ this.fallbackKeys = fallbackKeys.map((fallbackKey) => this.prepareKey(fallbackKey))
+ }
+
+ private loadAsBytes(raw: RawSecretKey): Buffer {
+ if (raw instanceof Uint8Array) {
+ return Buffer.from(raw)
+ }
+
+ const separatorIndex = raw.indexOf(':')
+ if (separatorIndex === -1) {
+ return Buffer.from(raw, 'utf-8')
+ }
+
+ const prefix = raw.slice(0, separatorIndex)
+ const secret = raw.slice(separatorIndex + 1)
+
+ switch (prefix) {
+ case 'hex':
+ return decodeHex(secret)
+ case 'base64-urlsafe':
+ return decodeBase64Urlsafe(secret)
+ case 'base64':
+ return decodeBase64(secret)
+ default:
+ // Legacy format, kept for compatibility with Python's _load_as_bytes.
+ return Buffer.from(raw, 'utf-8')
+ }
+ }
+
+ private prepareKey(secretKey: RawSecretKey): FernetKey {
+ const keyBytes = this.loadAsBytes(secretKey)
+
+ if (keyBytes.length === 0) {
+ throw new Error('EncryptionCodec: empty secret key is not allowed')
+ }
+
+ if (keyBytes.length < 32 && process.env.NODE_ENV === 'production') {
+ throw new Error(
+ `EncryptionCodec: secret key must be at least 32 bytes in production (got ${keyBytes.length})`
+ )
+ }
+ if (keyBytes.length < 32) {
+ console.warn(
+ `EncryptionCodec: secret key is only ${keyBytes.length} bytes; use a 32-byte key in production`
+ )
+ }
- constructor(secretKey: string) {
// Match Python: pad with null bytes on the left, truncate to 32 bytes
const padded = Buffer.alloc(32)
- const keyBytes = Buffer.from(secretKey, 'utf-8')
if (keyBytes.length > 32) {
console.warn(`EncryptionCodec: secret key is ${keyBytes.length} bytes, truncating to 32`)
}
const padLen = Math.max(32 - keyBytes.length, 0)
keyBytes.copy(padded, padLen, 0, Math.min(keyBytes.length, 32))
- this.signingKey = padded.subarray(0, 16)
- this.encryptionKey = padded.subarray(16, 32)
+ return {
+ signingKey: padded.subarray(0, 16),
+ encryptionKey: padded.subarray(16, 32),
+ }
}
// eslint-disable-next-line @typescript-eslint/require-await
@@ -59,7 +136,7 @@ export class EncryptionCodec implements PayloadCodec {
const iv = crypto.randomBytes(16)
const timestamp = BigInt(Math.floor(Date.now() / 1000))
- const cipher = crypto.createCipheriv('aes-128-cbc', this.encryptionKey, iv)
+ const cipher = crypto.createCipheriv('aes-128-cbc', this.primaryKey.encryptionKey, iv)
const ciphertext = Buffer.concat([cipher.update(data), cipher.final()])
// Fernet token: version || timestamp (big-endian 64-bit) || IV || ciphertext
@@ -69,7 +146,7 @@ export class EncryptionCodec implements PayloadCodec {
iv.copy(body, 9)
ciphertext.copy(body, FERNET_HEADER_SIZE)
- const hmac = crypto.createHmac('sha256', this.signingKey).update(body).digest()
+ const hmac = crypto.createHmac('sha256', this.primaryKey.signingKey).update(body).digest()
const raw = Buffer.concat([body, hmac])
// Python's Fernet expects base64url with padding — use standard base64
@@ -89,16 +166,26 @@ export class EncryptionCodec implements PayloadCodec {
const body = buf.subarray(0, buf.length - HMAC_SIZE)
const providedHmac = buf.subarray(buf.length - HMAC_SIZE)
- const computedHmac = crypto.createHmac('sha256', this.signingKey).update(body).digest()
+ let decryptError: Error | undefined
- if (!crypto.timingSafeEqual(providedHmac, computedHmac)) {
- throw new Error('Fernet HMAC verification failed')
- }
+ for (const key of [this.primaryKey, ...this.fallbackKeys]) {
+ const computedHmac = crypto.createHmac('sha256', key.signingKey).update(body).digest()
+
+ if (!crypto.timingSafeEqual(providedHmac, computedHmac)) {
+ continue
+ }
+
+ const iv = buf.subarray(9, 25)
+ const ciphertext = buf.subarray(FERNET_HEADER_SIZE, buf.length - HMAC_SIZE)
- const iv = buf.subarray(9, 25)
- const ciphertext = buf.subarray(FERNET_HEADER_SIZE, buf.length - HMAC_SIZE)
+ try {
+ const decipher = crypto.createDecipheriv('aes-128-cbc', key.encryptionKey, iv)
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()])
+ } catch (error) {
+ decryptError = error instanceof Error ? error : new Error(String(error))
+ }
+ }
- const decipher = crypto.createDecipheriv('aes-128-cbc', this.encryptionKey, iv)
- return Buffer.concat([decipher.update(ciphertext), decipher.final()])
+ throw decryptError ?? new Error('Fernet HMAC verification failed')
}
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts
index 54d2240ca1b3..eed488b2afc8 100644
--- a/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts
@@ -125,7 +125,9 @@ async function main(): Promise<void> {
taskQueue: config.taskQueue,
activities: createActivities(pool, playerHtml),
maxConcurrentActivityTaskExecutions: config.maxConcurrentActivities,
- dataConverter: config.secretKey ? { payloadCodecs: [new EncryptionCodec(config.secretKey)] } : undefined,
+ dataConverter: config.secretKey
+ ? { payloadCodecs: [new EncryptionCodec(config.secretKey, config.fallbackKeys)] }
+ : undefined,
// Throttle heartbeat *server flushes* (not heartbeat() calls) to 2s. Without
// this override, the SDK throttles to 80% of the activity's heartbeat_timeout
// (30s → 24s), which means capture-phase frame progress never reaches the