mirror of
https://github.com/streetwriters/notesnook.git
synced 2025-12-23 23:19:40 +01:00
feat: require password for encrypted backups
This commit is contained in:
@@ -61,22 +61,39 @@ export default class Backup {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param {string} data the backup data
|
* @param {any} backup the backup data
|
||||||
*/
|
*/
|
||||||
async import(data, key) {
|
async import(backup, password) {
|
||||||
if (!data) return;
|
if (!backup) return;
|
||||||
|
|
||||||
let backup = JSON.parse(data);
|
|
||||||
|
|
||||||
if (!this._validate(backup)) throw new Error("Invalid backup.");
|
if (!this._validate(backup)) throw new Error("Invalid backup.");
|
||||||
|
|
||||||
backup = this._migrateBackup(backup);
|
backup = this._migrateBackup(backup);
|
||||||
|
|
||||||
let db = backup.data;
|
let db = backup.data;
|
||||||
//check if we have encrypted data
|
const isEncrypted = db.salt && db.iv && db.cipher;
|
||||||
if (db.salt && db.iv) {
|
if (isEncrypted) {
|
||||||
if (!key) key = await this._db.user.getEncryptionKey();
|
if (!password)
|
||||||
backup.data = JSON.parse(await this._db.storage.decrypt(key, db));
|
throw new Error(
|
||||||
|
"Please provide a password to decrypt this backup & restore it."
|
||||||
|
);
|
||||||
|
|
||||||
|
const key = await this._db.storage.generateCryptoKey(password, db.salt);
|
||||||
|
if (!key)
|
||||||
|
throw new Error("Could not generate encryption key for backup.");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const decrypted = await this._db.storage.decrypt(key, db);
|
||||||
|
backup.data = JSON.parse(decrypted);
|
||||||
|
} catch (e) {
|
||||||
|
if (
|
||||||
|
e.message.includes("ciphertext cannot be decrypted") ||
|
||||||
|
e.message === "FAILURE"
|
||||||
|
)
|
||||||
|
throw new Error("Incorrect password.");
|
||||||
|
|
||||||
|
throw new Error(`Could not decrypt backup: ${e.message}`);
|
||||||
|
}
|
||||||
} else if (!this._verify(backup))
|
} else if (!this._verify(backup))
|
||||||
throw new Error("Backup file has been tempered, aborting...");
|
throw new Error("Backup file has been tempered, aborting...");
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,10 @@ export default class Storage {
|
|||||||
return this.storage.getCryptoKey(name);
|
return this.storage.getCryptoKey(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
generateCryptoKey(password, salt) {
|
||||||
|
return this.storage.generateCryptoKey(password, salt);
|
||||||
|
}
|
||||||
|
|
||||||
async generateRandomKey() {
|
async generateRandomKey() {
|
||||||
const passwordBytes = randomBytes(124);
|
const passwordBytes = randomBytes(124);
|
||||||
const password = passwordBytes.toString("base64");
|
const password = passwordBytes.toString("base64");
|
||||||
|
|||||||
Reference in New Issue
Block a user