Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Remove API_KEY_ENCRYPTION_SECRET dependency

Blue Mouse82157cfce881
diff --git a/backend/.env.example b/backend/.env.example
index aec7157fb..36df96d93 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -8,10 +8,6 @@ CLIENT_URL='http://localhost:3000'
# Can be generated via: openssl rand -base64 48
SECRET_KEY_BASE=
-# Optional dedicated secret for encrypted API keys; defaults to SECRET_KEY_BASE.
-# Keep this stable: changing it prevents revealing stored keys. Authentication still works.
-API_KEY_ENCRYPTION_SECRET=
-
# Time in seconds
# 30 minutes
JWT_ACCESS_TOKEN_LIFETIME=1800
diff --git a/backend/apps/cloud/src/api-key/api-key.crypto.ts b/backend/apps/cloud/src/api-key/api-key.crypto.ts
index 71f46fa65..8dfab6e36 100644
--- a/backend/apps/cloud/src/api-key/api-key.crypto.ts
+++ b/backend/apps/cloud/src/api-key/api-key.crypto.ts
@@ -4,16 +4,15 @@ import {
createHash,
randomBytes,
} from 'crypto'
+import { deriveKey } from '../common/utils'
export const hashApiKey = (key: string) =>
createHash('sha256').update(key).digest('hex')
export const generateApiKey = () => `swx_${randomBytes(32).toString('hex')}`
const encryptionKey = () => {
- const secret =
- process.env.API_KEY_ENCRYPTION_SECRET || process.env.SECRET_KEY_BASE
- if (!secret)
- throw new Error('API_KEY_ENCRYPTION_SECRET or SECRET_KEY_BASE is required')
- return createHash('sha256').update(`swetrix-api-keys:${secret}`).digest()
+ if (!process.env.SECRET_KEY_BASE)
+ throw new Error('SECRET_KEY_BASE is required')
+ return Buffer.from(deriveKey('api-key', 32), 'hex')
}
export const encryptApiKey = (key: string, userId: string, id: string) => {
const iv = randomBytes(12)
diff --git a/backend/apps/cloud/src/api-key/api-key.spec.ts b/backend/apps/cloud/src/api-key/api-key.spec.ts
index cdf639b15..9e86911a6 100644
--- a/backend/apps/cloud/src/api-key/api-key.spec.ts
+++ b/backend/apps/cloud/src/api-key/api-key.spec.ts
@@ -5,8 +5,10 @@ import { ForbiddenException, UnauthorizedException } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { validate } from 'class-validator'
import { plainToInstance } from 'class-transformer'
+import { createDecipheriv, hkdfSync } from 'crypto'
jest.mock('./api-key.store', () => ({ ApiKeyStore: class {} }))
+jest.mock('../common/constants', () => ({}))
import { ApiKeyService } from './api-key.service'
import { ApiKeyGuard } from './api-key.guard'
import { ApiKeyRecord, ApiKeyPolicy } from './api-key.types'
@@ -114,6 +116,37 @@ describe('scoped API keys', () => {
expect(decryptApiKey(cipher, userId, 'id')).toBe(secret)
expect(() => decryptApiKey(cipher, 'other', 'id')).toThrow()
expect(() => decryptApiKey(cipher, userId, 'other')).toThrow()
+
+ const derivedKey = Buffer.from(
+ hkdfSync('sha256', process.env.SECRET_KEY_BASE, '', 'api-key', 32),
+ )
+ const [iv, tag, encrypted] = cipher
+ .split('.')
+ .map((part) => Buffer.from(part, 'base64'))
+ const decipher = createDecipheriv('aes-256-gcm', derivedKey, iv)
+ decipher.setAAD(Buffer.from(`${userId}:id`))
+ decipher.setAuthTag(tag)
+ expect(
+ Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(
+ 'utf8',
+ ),
+ ).toBe(secret)
+ })
+
+ it('requires a base secret even in test environments', () => {
+ const cipher = encryptApiKey('secret', userId, 'id')
+ const base = process.env.SECRET_KEY_BASE
+ delete process.env.SECRET_KEY_BASE
+ try {
+ expect(() => encryptApiKey('secret', userId, 'id')).toThrow(
+ 'SECRET_KEY_BASE is required',
+ )
+ expect(() => decryptApiKey(cipher, userId, 'id')).toThrow(
+ 'SECRET_KEY_BASE is required',
+ )
+ } finally {
+ process.env.SECRET_KEY_BASE = base
+ }
})
it('lists metadata without secrets and reveals only to the owner', async () => {
diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.ts
index fd199ab84..aab20d3ba 100644
--- a/backend/apps/cloud/src/common/utils.ts
+++ b/backend/apps/cloud/src/common/utils.ts
@@ -37,13 +37,14 @@ export const deriveKey = (
| 'access-token'
| 'gsc-token'
| 'ga4-token'
- | 'revenue',
+ | 'revenue'
+ | 'api-key',
length = 32,
) => {
const baseStr = process.env.SECRET_KEY_BASE
- // Security footgun: if SECRET_KEY_BASE is missing, token secrets become
- // predictable across deployments. Fail closed outside dev/test.
+ // If SECRET_KEY_BASE is missing, token secrets become predictable across deployments.
+ // Fail closed outside dev/test.
if (!baseStr) {
const env = process.env.NODE_ENV
if (env === 'development' || env === 'test') {
diff --git a/backend/apps/community/src/api-key/api-key.crypto.ts b/backend/apps/community/src/api-key/api-key.crypto.ts
index 71f46fa65..8dfab6e36 100644
--- a/backend/apps/community/src/api-key/api-key.crypto.ts
+++ b/backend/apps/community/src/api-key/api-key.crypto.ts
@@ -4,16 +4,15 @@ import {
createHash,
randomBytes,
} from 'crypto'
+import { deriveKey } from '../common/utils'
export const hashApiKey = (key: string) =>
createHash('sha256').update(key).digest('hex')
export const generateApiKey = () => `swx_${randomBytes(32).toString('hex')}`
const encryptionKey = () => {
- const secret =
- process.env.API_KEY_ENCRYPTION_SECRET || process.env.SECRET_KEY_BASE
- if (!secret)
- throw new Error('API_KEY_ENCRYPTION_SECRET or SECRET_KEY_BASE is required')
- return createHash('sha256').update(`swetrix-api-keys:${secret}`).digest()
+ if (!process.env.SECRET_KEY_BASE)
+ throw new Error('SECRET_KEY_BASE is required')
+ return Buffer.from(deriveKey('api-key', 32), 'hex')
}
export const encryptApiKey = (key: string, userId: string, id: string) => {
const iv = randomBytes(12)
diff --git a/backend/apps/community/src/api-key/api-key.spec.ts b/backend/apps/community/src/api-key/api-key.spec.ts
index cdf639b15..5f19c8e81 100644
--- a/backend/apps/community/src/api-key/api-key.spec.ts
+++ b/backend/apps/community/src/api-key/api-key.spec.ts
@@ -5,8 +5,11 @@ import { ForbiddenException, UnauthorizedException } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { validate } from 'class-validator'
import { plainToInstance } from 'class-transformer'
+import { createDecipheriv, hkdfSync } from 'crypto'
jest.mock('./api-key.store', () => ({ ApiKeyStore: class {} }))
+jest.mock('../common/constants', () => ({}))
+jest.mock('../common/integrations/clickhouse', () => ({}))
import { ApiKeyService } from './api-key.service'
import { ApiKeyGuard } from './api-key.guard'
import { ApiKeyRecord, ApiKeyPolicy } from './api-key.types'
@@ -114,6 +117,37 @@ describe('scoped API keys', () => {
expect(decryptApiKey(cipher, userId, 'id')).toBe(secret)
expect(() => decryptApiKey(cipher, 'other', 'id')).toThrow()
expect(() => decryptApiKey(cipher, userId, 'other')).toThrow()
+
+ const derivedKey = Buffer.from(
+ hkdfSync('sha256', process.env.SECRET_KEY_BASE, '', 'api-key', 32),
+ )
+ const [iv, tag, encrypted] = cipher
+ .split('.')
+ .map((part) => Buffer.from(part, 'base64'))
+ const decipher = createDecipheriv('aes-256-gcm', derivedKey, iv)
+ decipher.setAAD(Buffer.from(`${userId}:id`))
+ decipher.setAuthTag(tag)
+ expect(
+ Buffer.concat([decipher.update(encrypted), decipher.final()]).toString(
+ 'utf8',
+ ),
+ ).toBe(secret)
+ })
+
+ it('requires a base secret even in test environments', () => {
+ const cipher = encryptApiKey('secret', userId, 'id')
+ const base = process.env.SECRET_KEY_BASE
+ delete process.env.SECRET_KEY_BASE
+ try {
+ expect(() => encryptApiKey('secret', userId, 'id')).toThrow(
+ 'SECRET_KEY_BASE is required',
+ )
+ expect(() => decryptApiKey(cipher, userId, 'id')).toThrow(
+ 'SECRET_KEY_BASE is required',
+ )
+ } finally {
+ process.env.SECRET_KEY_BASE = base
+ }
})
it('lists metadata without secrets and reveals only to the owner', async () => {
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index a8aeaebb6..17e719020 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -85,7 +85,12 @@ export const hash = (content: string): string => {
* Derives a key from the SECRET_KEY_BASE environment variable using the HKDF algorithm.
*/
export const deriveKey = (
- purpose: 'refresh-token' | 'access-token' | 'gsc-token' | 'ga4-token',
+ purpose:
+ | 'refresh-token'
+ | 'access-token'
+ | 'gsc-token'
+ | 'ga4-token'
+ | 'api-key',
length = 32,
) => {
const base = Buffer.from(process.env.SECRET_KEY_BASE || '', 'utf8')