1629215600192-generate_user_server_key.ts 1.0 KB

123456789101112131415161718192021222324252627282930
  1. import { MigrationInterface, QueryRunner } from 'typeorm'
  2. import { CryptoNode } from '@standardnotes/sncrypto-node'
  3. export class generateUserServerKey1629215600192 implements MigrationInterface {
  4. public async up(queryRunner: QueryRunner): Promise<void> {
  5. const crypto = new CryptoNode()
  6. const users = await queryRunner.manager.query(
  7. 'SELECT * FROM users where encrypted_server_key IS NULL ORDER BY created_at',
  8. )
  9. for (const user of users) {
  10. const unencrypted = await crypto.generateRandomKey(256)
  11. const iv = await crypto.generateRandomKey(128)
  12. const encrypted = await crypto.aes256GcmEncrypt({
  13. unencrypted,
  14. iv,
  15. key: process.env.ENCRYPTION_SERVER_KEY as string,
  16. })
  17. const encryptedServerKey = JSON.stringify({ version: 1, encrypted })
  18. await queryRunner.manager.query(
  19. `UPDATE users SET encrypted_server_key = '${encryptedServerKey}', server_encryption_version = 1 WHERE uuid = "${user['uuid']}"`,
  20. )
  21. }
  22. }
  23. public async down(): Promise<void> {
  24. return
  25. }
  26. }