Something went wrong. Try again.
mirror your GitHub repos to tangled.org automatically synchub.to
mirror sync tangled github git
Something went wrong. Try again.
2.6 kB · 75 lines
TypeScript
at main
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import crypto from 'node:crypto'import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { clearEncryptionKeyCache, decrypt, encrypt } from '../../server/utils/encryption'
const ORIGINAL_ENV = process.env.NUXT_ENCRYPTION_KEY
describe('encryption', () => { beforeEach(() => { process.env.NUXT_ENCRYPTION_KEY = crypto.randomBytes(32).toString('base64') clearEncryptionKeyCache() })
afterEach(() => { if (ORIGINAL_ENV === undefined) delete process.env.NUXT_ENCRYPTION_KEY else process.env.NUXT_ENCRYPTION_KEY = ORIGINAL_ENV clearEncryptionKeyCache() })
it('round-trips a string', () => { const { ciphertext, nonce } = encrypt('hello world') expect(decrypt(ciphertext, nonce)).toBe('hello world') })
it('round-trips JSON-shaped data', () => { const payload = JSON.stringify({ did: 'did:plc:foo', token: 'abc.def.ghi' }) const { ciphertext, nonce } = encrypt(payload) expect(JSON.parse(decrypt(ciphertext, nonce))).toEqual({ did: 'did:plc:foo', token: 'abc.def.ghi', }) })
it('produces different ciphertext for the same input (random nonce)', () => { const a = encrypt('same plaintext') const b = encrypt('same plaintext') expect(a.ciphertext.equals(b.ciphertext)).toBe(false) expect(a.nonce.equals(b.nonce)).toBe(false) })
it('throws on tampered ciphertext', () => { const { ciphertext, nonce } = encrypt('hello') const tampered = Buffer.from(ciphertext) tampered[0] = tampered[0]! ^ 0xFF expect(() => decrypt(tampered, nonce)).toThrow(/invalid tag|auth/i) })
it('throws on tampered nonce', () => { const { ciphertext, nonce } = encrypt('hello') const tampered = Buffer.from(nonce) tampered[0] = tampered[0]! ^ 0xFF expect(() => decrypt(ciphertext, tampered)).toThrow(/invalid tag|auth/i) })
it('throws when the key changes between encrypt and decrypt', () => { const { ciphertext, nonce } = encrypt('hello')
// Rotate the key. process.env.NUXT_ENCRYPTION_KEY = crypto.randomBytes(32).toString('base64') clearEncryptionKeyCache()
expect(() => decrypt(ciphertext, nonce)).toThrow(/invalid tag|auth/i) })
it('throws on wrong key length', () => { process.env.NUXT_ENCRYPTION_KEY = Buffer.from('too short').toString('base64') clearEncryptionKeyCache() expect(() => encrypt('hello')).toThrow(/32 bytes/) })
it('throws when the key is missing', () => { delete process.env.NUXT_ENCRYPTION_KEY clearEncryptionKeyCache() expect(() => encrypt('hello')).toThrow(/NUXT_ENCRYPTION_KEY/) })})