|
| 1 | +import 'dotenv/config' |
| 2 | +import { csColumn, csTable } from '@cipherstash/schema' |
| 3 | +import { describe, expect, it } from 'vitest' |
| 4 | +import { protect } from '../src' |
| 5 | + |
| 6 | +const users = csTable('users', { |
| 7 | + email: csColumn('email'), |
| 8 | +}) |
| 9 | + |
| 10 | +describe('encryption and decryption with keyset id', () => { |
| 11 | + it('should encrypt and decrypt a payload', async () => { |
| 12 | + const protectClient = await protect({ |
| 13 | + schemas: [users], |
| 14 | + keyset: { |
| 15 | + id: '4152449b-505a-4186-93b6-d3d87eba7a47', |
| 16 | + }, |
| 17 | + }) |
| 18 | + |
| 19 | + const email = 'hello@example.com' |
| 20 | + |
| 21 | + const ciphertext = await protectClient.encrypt(email, { |
| 22 | + column: users.email, |
| 23 | + table: users, |
| 24 | + }) |
| 25 | + |
| 26 | + if (ciphertext.failure) { |
| 27 | + throw new Error(`[protect]: ${ciphertext.failure.message}`) |
| 28 | + } |
| 29 | + |
| 30 | + // Verify encrypted field |
| 31 | + expect(ciphertext.data).toHaveProperty('c') |
| 32 | + |
| 33 | + const a = ciphertext.data |
| 34 | + |
| 35 | + const plaintext = await protectClient.decrypt(ciphertext.data) |
| 36 | + |
| 37 | + expect(plaintext).toEqual({ |
| 38 | + data: email, |
| 39 | + }) |
| 40 | + }, 30000) |
| 41 | +}) |
| 42 | + |
| 43 | +describe('encryption and decryption with keyset name', () => { |
| 44 | + it('should encrypt and decrypt a payload', async () => { |
| 45 | + const protectClient = await protect({ |
| 46 | + schemas: [users], |
| 47 | + keyset: { |
| 48 | + name: 'Test', |
| 49 | + }, |
| 50 | + }) |
| 51 | + |
| 52 | + const email = 'hello@example.com' |
| 53 | + |
| 54 | + const ciphertext = await protectClient.encrypt(email, { |
| 55 | + column: users.email, |
| 56 | + table: users, |
| 57 | + }) |
| 58 | + |
| 59 | + if (ciphertext.failure) { |
| 60 | + throw new Error(`[protect]: ${ciphertext.failure.message}`) |
| 61 | + } |
| 62 | + |
| 63 | + // Verify encrypted field |
| 64 | + expect(ciphertext.data).toHaveProperty('c') |
| 65 | + |
| 66 | + const a = ciphertext.data |
| 67 | + |
| 68 | + const plaintext = await protectClient.decrypt(ciphertext.data) |
| 69 | + |
| 70 | + expect(plaintext).toEqual({ |
| 71 | + data: email, |
| 72 | + }) |
| 73 | + }, 30000) |
| 74 | +}) |
| 75 | + |
| 76 | +describe('encryption and decryption with invalid keyset id', () => { |
| 77 | + it('should throw an error', async () => { |
| 78 | + await expect( |
| 79 | + protect({ |
| 80 | + schemas: [users], |
| 81 | + keyset: { |
| 82 | + id: 'invalid-uuid', |
| 83 | + }, |
| 84 | + }), |
| 85 | + ).rejects.toThrow( |
| 86 | + '[protect]: Invalid UUID provided for keyset id. Must be a valid UUID.', |
| 87 | + ) |
| 88 | + }) |
| 89 | +}) |
0 commit comments