This commit is contained in:
2020-09-22 11:48:45 +02:00
commit 6436cd087f
13 changed files with 641 additions and 0 deletions

114
src/generate.ts Normal file
View File

@@ -0,0 +1,114 @@
import * as fs from 'fs'
import * as nodemailer from 'nodemailer';
import { shuffleArray } from './util/shuffle';
import { mkstring } from './util/token';
import * as Handlebars from "handlebars";
import Mail from 'nodemailer/lib/mailer';
import { SecureVault } from './vault';
interface mail{
mail: string;
name: string;
}
export function generateToken(config: any,dataSafe: SecureVault): Promise<String[]>{
let pr = new Promise<String[]>((resolve,error) => {
let mailArray: mail[] = [];
// read and process mail list
let readline = require('readline'),
instream = fs.createReadStream(config.inFileMail),
outstream = new (require('stream'))(),
rl = readline.createInterface(instream, outstream);
rl.on('line', function (line:string) {
console.log(line);
mailArray.push({
mail: line.substr(0,line.indexOf(";")),
name: line.substr(line.indexOf(";") + 1)
})
});
rl.on('close', function (line:string) {
// next step
generateCodes(resolve,error,mailArray,config,dataSafe);
});
});
return pr;
}
// generate codes
async function generateCodes(resolve: (value?: String[]) => void,error: (reason?: any) => void,mailArray: mail[],config: any,dataSafe: SecureVault){
let codeArray: string[] = [];
let checkString: string = '';
let listString: string = '';
for(let i = 0; i < mailArray.length; i++){ // as many codes as adresses
// check that codes are unique
let code = mkstring(4);
while (codeArray.includes(code)){
code = mkstring(4);
}
codeArray.push(code);
checkString = `${checkString}|${code}`
listString = `${listString}\n${code}`
}
checkString = checkString.substr(1);
listString = listString.substr(1);
//write code lists
try {
fs.writeFileSync(config.outFileMatch, checkString);
fs.writeFileSync(config.outFileCodes, listString);
} catch (error) {
error(error);
}
sendMails(resolve,error,mailArray,codeArray,config,dataSafe);
}
// randomize mails and tokens
async function sendMails(resolve: (value?: String[]) => void,error: (reason?: any) => void,mailArray: mail[],codeArray: string[],config: any,dataSafe: SecureVault){
let mailserver = nodemailer.createTransport(config.mail);
// read mail template
let template!: HandlebarsTemplateDelegate<any>;
try {
const htmlSrc=fs.readFileSync(config.htmlPath, "utf8")
template = Handlebars.compile(htmlSrc)
} catch (error) {
console.error("Cannote read template file!")
error(error);
}
shuffleArray(mailArray);
shuffleArray(codeArray);
for(let i = 0; i < mailArray.length; i++){
// send mail
dataSafe.pushData({
name: mailArray[i].name,
mail: mailArray[i].mail,
code: codeArray[i]
})
await send(mailArray[i].name, mailArray[i].mail, codeArray[i],template,mailserver,config);
}
resolve(codeArray);
}
async function send(name: string, mail: string, code: string,template: HandlebarsTemplateDelegate<any>,mailserver: Mail,config: any){
// fill template
let html = template({
"name": name,
"mail": mail,
"code": code
})
let mailOptions = {
from: `${config.mailFrom} <${config.mail.auth.user}>`, // sender address
to: mail, // list of receivers
subject: `Dein Zugangscode zur BJR Wahl`, // Subject line
html: html
};
try {
await mailserver.sendMail(mailOptions);
} catch (error) {
console.log(`Error sendign mail to ${mail} : ${error}`)
}
}

8
src/util/shuffle.ts Normal file
View File

@@ -0,0 +1,8 @@
export function shuffleArray(array: any[]) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}

9
src/util/token.ts Normal file
View File

@@ -0,0 +1,9 @@
export function mkstring (length:number ) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}

101
src/vault.ts Normal file
View File

@@ -0,0 +1,101 @@
import * as crypto from 'crypto'
import path from 'path';
import * as fs from 'fs'
import { generateKeyPair } from 'crypto';
export interface SecureVaultItem {
d: string; // data
k: string; // key
iv: string; // init vector
}
export interface secureVaultList {
items: SecureVaultItem[];
publicKey?: Buffer;
privateKey?: Buffer;
}
export class SecureVault {
safe: secureVaultList;
privPath?: string;
pubPath?: string;
constructor (publicKey: string, privateKey?: string) {
this.safe = {
items: [],
publicKey: publicKey ?fs.readFileSync(path.resolve(publicKey)): undefined,
privateKey: privateKey ? fs.readFileSync(path.resolve(privateKey)): undefined
};
this.privPath = publicKey ? path.resolve(publicKey): undefined,
this.pubPath = privateKey ? path.resolve(privateKey): undefined
}
async pushData(data: any): Promise<void>{
// encrypt payload
const txtData = JSON.stringify(data);
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(txtData);
encrypted = Buffer.concat([encrypted, cipher.final()]);
// encrypt key
var buffer = new Buffer(key);
if (!this.safe.publicKey){
throw new Error("Public Key not found");
}
var asym_encrypted = crypto.publicEncrypt(this.safe.publicKey, buffer);
this.safe.items.push({
d: encrypted.toString('hex'),
k: asym_encrypted.toString("base64"),
iv: iv.toString('hex')
})
}
async saveData(path: string): Promise<void>{
fs.writeFileSync(path, JSON.stringify(this.safe.items));
}
async loadData(path: string): Promise<void>{
this.safe.items = JSON.parse(fs.readFileSync(path, 'utf8'))
}
async decryptData(): Promise<void>{
this.safe.items.forEach(el => {
// decrpyt key
let buffer = new Buffer(el.k, "base64");
if (!this.safe.privateKey){
throw new Error("Private Key not found");
}
var key = crypto.privateDecrypt(this.safe.privateKey, buffer);
// decrpyt payload
let iv = Buffer.from(el.iv, 'hex');
let encryptedText = Buffer.from(el.d, 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
const obj = JSON.parse(decrypted.toString());
console.log(obj);
})
}
static genKey(publicKeyDir: string, privateKeyDir: string){
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
}
}, (err, publicKey, privateKey) => {
fs.writeFileSync(privateKeyDir, privateKey);
fs.writeFileSync(publicKeyDir, publicKey);
});
}
}