@@ -3,15 +3,16 @@ import crypto from "node:crypto";
33const ENCRYPTION_KEY_ENV = process . env . WALLET_ENCRYPTION_KEY ;
44const ALGORITHM = "aes-256-gcm" ;
55
6- if ( ! ENCRYPTION_KEY_ENV || ENCRYPTION_KEY_ENV . length !== 64 ) {
7- throw new Error (
8- "WALLET_ENCRYPTION_KEY must be a 32-byte hex string (64 characters)"
9- ) ;
6+ // Lazy initialization - only validate when actually used (not at build time)
7+ function getEncryptionKey ( ) : string {
8+ if ( ! ENCRYPTION_KEY_ENV || ENCRYPTION_KEY_ENV . length !== 64 ) {
9+ throw new Error (
10+ "WALLET_ENCRYPTION_KEY must be a 32-byte hex string (64 characters)"
11+ ) ;
12+ }
13+ return ENCRYPTION_KEY_ENV ;
1014}
1115
12- // TypeScript now knows ENCRYPTION_KEY is definitely a string
13- const ENCRYPTION_KEY : string = ENCRYPTION_KEY_ENV ;
14-
1516/**
1617 * Encrypt sensitive userShare before storing in database
1718 * Uses AES-256-GCM for authenticated encryption
@@ -20,10 +21,11 @@ const ENCRYPTION_KEY: string = ENCRYPTION_KEY_ENV;
2021 * @returns Encrypted string in format: iv:authTag:encryptedData
2122 */
2223export function encryptUserShare ( userShare : string ) : string {
24+ const encryptionKey = getEncryptionKey ( ) ;
2325 const iv = crypto . randomBytes ( 16 ) ;
2426 const cipher = crypto . createCipheriv (
2527 ALGORITHM ,
26- Buffer . from ( ENCRYPTION_KEY , "hex" ) ,
28+ Buffer . from ( encryptionKey , "hex" ) ,
2729 iv
2830 ) ;
2931
@@ -43,6 +45,7 @@ export function encryptUserShare(userShare: string): string {
4345 * @returns Decrypted userShare for Para SDK
4446 */
4547export function decryptUserShare ( encryptedData : string ) : string {
48+ const encryptionKey = getEncryptionKey ( ) ;
4649 const parts = encryptedData . split ( ":" ) ;
4750 if ( parts . length !== 3 ) {
4851 throw new Error ( "Invalid encrypted data format" ) ;
@@ -54,7 +57,7 @@ export function decryptUserShare(encryptedData: string): string {
5457
5558 const decipher = crypto . createDecipheriv (
5659 ALGORITHM ,
57- Buffer . from ( ENCRYPTION_KEY , "hex" ) ,
60+ Buffer . from ( encryptionKey , "hex" ) ,
5861 iv
5962 ) ;
6063 decipher . setAuthTag ( authTag ) ;
0 commit comments