File size: 2,004 Bytes
37fb9ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import 'dotenv/config';
import { PrismaClient } from '@prisma/client';
import { encrypt } from '../../../packages/shared-types/src/crypto';

// ATTENTION: CE SCRIPT DOIT ÊTRE EXÉCUTÉ AVEC LA CLÉ DE PRODUCTION
const prisma = new PrismaClient();

async function migrateSecrets() {
    const ENCRYPTION_SECRET = process.env.PROD_ENCRYPTION_SECRET || process.env.ENCRYPTION_SECRET;
    
    if (!ENCRYPTION_SECRET || ENCRYPTION_SECRET.length < 32) {
        console.error('❌ ERREUR: Une clé ENCRYPTION_SECRET valide de 32 caractères minimum est requise.');
        process.exit(1);
    }

    console.log('🔍 Début de la migration des secrets...');
    const orgs = await prisma.organization.findMany();
    let updatedCount = 0;

    for (const org of orgs) {
        const dataToUpdate: any = {};
        
        if (org.systemUserToken && !org.systemUserToken.startsWith('enc:')) {
            dataToUpdate.systemUserToken = encrypt(org.systemUserToken, ENCRYPTION_SECRET);
        }
        if (org.webhookSecret && !org.webhookSecret.startsWith('enc:')) {
            dataToUpdate.webhookSecret = encrypt(org.webhookSecret, ENCRYPTION_SECRET);
        }
        if (org.openAiApiKey && !org.openAiApiKey.startsWith('enc:')) {
            dataToUpdate.openAiApiKey = encrypt(org.openAiApiKey, ENCRYPTION_SECRET);
        }
        if (org.googleAiApiKey && !org.googleAiApiKey.startsWith('enc:')) {
            dataToUpdate.googleAiApiKey = encrypt(org.googleAiApiKey, ENCRYPTION_SECRET);
        }

        if (Object.keys(dataToUpdate).length > 0) {
            await prisma.organization.update({
                where: { id: org.id },
                data: dataToUpdate
            });
            console.log(`✅ Organisation sécurisée : ${org.name} (${org.id})`);
            updatedCount++;
        }
    }
    
    console.log(`\n🎉 Migration terminée. ${updatedCount} organisation(s) mise(s) à jour.`);
    await prisma.$disconnect();
}

migrateSecrets().catch(console.error);