@@ -28,31 +28,41 @@ const decryptionKeys = encryptionSecret
2828 ? [ primaryKey , deriveKey ( betterAuthSecret ) ]
2929 : [ primaryKey ] ;
3030
31- export const exportEncryptionKey = ( ) => primaryKey . toString ( "hex" ) ;
31+ // Derived keys only — never the raw secrets. A leaked key can decrypt
32+ // stored values, but the raw BETTER_AUTH_SECRET could also forge sessions.
33+ export const exportEncryptionKeys = ( ) =>
34+ decryptionKeys . map ( ( key ) => key . toString ( "hex" ) ) . join ( "\n" ) ;
3235
33- let restoredKey : Buffer | undefined ;
36+ let restoredKeys : Buffer [ ] | undefined ;
3437
3538// A backup created with "include encryption key" places the original
36- // server's key at BASE_PATH when restored; use it as a last-resort
39+ // server's keys at BASE_PATH when restored; use them as a last-resort
3740// decryption fallback so restored values keep working on the new server.
38- const loadRestoredKey = ( ) : Buffer | undefined => {
39- if ( restoredKey ) {
40- return restoredKey ;
41+ const loadRestoredKeys = ( ) : Buffer [ ] => {
42+ if ( restoredKeys ?. length ) {
43+ return restoredKeys ;
4144 }
4245 try {
4346 const { BASE_PATH } = paths ( ) ;
44- const hex = readFileSync (
47+ const keys = readFileSync (
4548 join ( BASE_PATH , ENCRYPTION_KEY_BACKUP_FILE ) ,
4649 "utf8" ,
47- ) . trim ( ) ;
48- const key = Buffer . from ( hex , "hex" ) ;
49- if ( key . length === 32 && ! key . equals ( primaryKey ) ) {
50- restoredKey = key ;
50+ )
51+ . split ( "\n" )
52+ . map ( ( line ) => line . trim ( ) )
53+ . filter ( Boolean )
54+ . map ( ( hex ) => Buffer . from ( hex , "hex" ) )
55+ . filter (
56+ ( key ) =>
57+ key . length === 32 && ! decryptionKeys . some ( ( own ) => own . equals ( key ) ) ,
58+ ) ;
59+ if ( keys . length ) {
60+ restoredKeys = keys ;
5161 }
5262 } catch {
5363 // No restored key file present.
5464 }
55- return restoredKey ;
65+ return restoredKeys ?? [ ] ;
5666} ;
5767
5868export const isEncrypted = ( value : string ) =>
@@ -79,8 +89,7 @@ export const decryptValue = (value: string): string => {
7989 const iv = payload . subarray ( 0 , IV_LENGTH ) ;
8090 const authTag = payload . subarray ( IV_LENGTH , IV_LENGTH + AUTH_TAG_LENGTH ) ;
8191 const encrypted = payload . subarray ( IV_LENGTH + AUTH_TAG_LENGTH ) ;
82- const restored = loadRestoredKey ( ) ;
83- const keys = restored ? [ ...decryptionKeys , restored ] : decryptionKeys ;
92+ const keys = [ ...decryptionKeys , ...loadRestoredKeys ( ) ] ;
8493 for ( const key of keys ) {
8594 try {
8695 const decipher = createDecipheriv ( "aes-256-gcm" , key , iv ) ;
0 commit comments