summaryrefslogtreecommitdiff
path: root/backend/data-aggregate.cjs
blob: 974f1e1c3cc3856451488e8956e7f45e28dfd26e (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const archiver = require('archiver');
const fs = require('fs');
const crypto = require('crypto');

function jwt_secret() {
  let file = fs.readFileSync( '../data/jwt_secret.txt', 'utf8' );
  if( file.endsWith( '\n' ) ) {
    file = file.slice( 0, -1 );
  }

  return file;
}

function read( filename ) {
  const contents = fs.readFileSync( filename, 'utf8' );
  const salt = Buffer.from( contents.slice( 0, 32 ), 'hex' );
  const iv = Buffer.from( contents.slice( 32, 56 ), 'hex' );
  const authTag = Buffer.from( contents.slice( 56, 88 ), 'hex' );
  const data = contents.slice( 88 );

  const key = crypto.pbkdf2Sync( jwt_secret(), salt, 100000, 32, 'sha512' );
  const decipher = crypto.createDecipheriv( 'aes-256-gcm', key, iv );
  decipher.setAuthTag( authTag );

  let decrypted = decipher.update( data, 'hex', 'utf8' );
  decrypted += decipher.final( 'utf8' );

  return decrypted;
}

async function main() {
  try {
    const userdata = JSON.parse( JSON.parse( process.argv[2] ) );
    const archive = archiver( 'zip', {
      zlib: { level: 9 }
    } );

    archive.pipe( process.stdout );
    archive.append( process.argv[2], { name: '000-user.json' } );

    const chats = userdata.chat_files;
    for( let chat of chats.files ) {
      if( !chat.id )
        continue;

      try {
        let chatFile = read( `../data/chats/${chat.id}.json` );
        archive.append( chatFile, { name: chat.id + '.json' } );
      } catch( e ) {}
    }
    try {
      let notesFile = fs.readFileSync( `../data/notes/${userdata.uuid}-notes.json` );
      archive.append( notesFile, { name: `${userdata.uuid}-notes.json` } );
    } catch( e ) {
      archive.append( "{}", { name: `${userdata.uuid}-notes.json` } );
    }

    archive.finalize();
  } catch (e) {
    console.log( '0' );
    console.log( e );
  }
}

main();