export async function encrypt(path: string, key: string, out: string) {
const name = path.substring(path.lastIndexOf('\\') + 1)
const bytes =
key.length >= 32
? Buffer.from(key).slice(0, 32)
: Buffer.from(key).slice(0, key.length) + '-'.repeat(32 - key.length)
if (bytes.length != 32)
throw new Error('Encryption key is unstable in estuary.ts: encrypt()')
const iv = crypto.randomBytes(IV_LENGTH)
const cipher = crypto.createCipheriv('aes-256-cbc', bytes, iv)
const input = fs.createReadStream(path)
const output = fs.createWriteStream(join(out, name + '.enc'))
await new Promise((fulfill, reject) =>
output.write(iv, (err: any) => {
if (err) reject(err)
else fulfill(null)
})
)
const pipe = pipeline(input, cipher, output, (err: any) => console.error(err))
await new Promise(fulfill => pipe.on('finish', fulfill))
return join(out, name + '.enc')
}
ipcMain.on('app:file:download', async (event, data) => {
const file = data.file
const directory = data.directory.replace(/\//g, '\\')
const path = await readItem(file, join(app.getPath('userData'), 'Temp'))
if (!fs.existsSync(join(preferences.get('path'), directory)))
fs.mkdirSync(join(preferences.get('path'), directory))
await decrypt(
path,
preferences.get('key'),
join(preferences.get('path'), directory)
)
event.reply(`client:file:loaded:${directory + file.name}`)
})
export async function readItem(file: any, path: string) {
const res = await fetch(`https://dweb.link/ipfs/${file.cid}`)
const dest = fs.createWriteStream(join(path, file.name))
const data = res.body as fs.ReadStream
const pipe = pipeline(data, dest, (err: any) => console.error(err))
await new Promise(fulfill => pipe.on('finish', fulfill))
return join(path, file.name)
}