mobile: add async storage & encryption

This commit is contained in:
ammarahm-ed
2023-08-26 12:02:13 +05:00
committed by Abdullah Atta
parent ddd1c19c64
commit c4f894f8d0
2 changed files with 40 additions and 12 deletions

View File

@@ -126,6 +126,18 @@ export async function decrypt(password, data) {
return await Sodium.decrypt(password, _data); return await Sodium.decrypt(password, _data);
} }
export async function decryptMulti(password, data) {
if (!password.password && !password.key) return undefined;
if (password.password && password.password === "" && !password.key)
return undefined;
data = data.map((d) => {
d.output = "plain";
return d;
});
return await Sodium.decryptMulti(password, data);
}
export function parseAlgorithm(alg) { export function parseAlgorithm(alg) {
if (!alg) return {}; if (!alg) return {};
const [enc, kdf, compressed, compressionAlg, base64variant] = alg.split("-"); const [enc, kdf, compressed, compressionAlg, base64variant] = alg.split("-");

View File

@@ -27,11 +27,15 @@ import {
getCryptoKey, getCryptoKey,
getRandomBytes, getRandomBytes,
hash, hash,
removeCryptoKey removeCryptoKey,
decryptMulti
} from "./encryption"; } from "./encryption";
import { MMKV } from "./mmkv"; import { MMKV } from "./mmkv";
export class KV { export class KV {
/**
* @type {typeof MMKV}
*/
storage = null; storage = null;
constructor(storage) { constructor(storage) {
this.storage = storage; this.storage = storage;
@@ -60,18 +64,24 @@ export class KV {
if (keys.length <= 0) { if (keys.length <= 0) {
return []; return [];
} else { } else {
let data = await this.storage.getMultipleItemsAsync(keys.slice()); try {
let data = await this.storage.getMultipleItemsAsync(
keys.slice(),
"object"
);
return data.map(([key, value]) => {
let obj;
try {
obj = JSON.parse(value);
} catch (e) {
obj = value;
}
return data.map(([key, value]) => { return [key, obj];
let obj; });
try { } catch (e) {
obj = JSON.parse(value); console.log(e);
} catch (e) { }
obj = value;
}
return [key, obj];
});
} }
} }
@@ -96,6 +106,10 @@ export class KV {
); );
return keys; return keys;
} }
async writeMulti(items) {
return this.storage.setMultipleItemsAsync(items, "object");
}
} }
const DefaultStorage = new KV(MMKV); const DefaultStorage = new KV(MMKV);
@@ -129,8 +143,10 @@ export default {
remove: (key) => DefaultStorage.remove(key), remove: (key) => DefaultStorage.remove(key),
clear: () => DefaultStorage.clear(), clear: () => DefaultStorage.clear(),
getAllKeys: () => DefaultStorage.getAllKeys(), getAllKeys: () => DefaultStorage.getAllKeys(),
writeMulti: (items) => DefaultStorage.writeMulti(items),
encrypt, encrypt,
decrypt, decrypt,
decryptMulti,
getRandomBytes, getRandomBytes,
checkAndCreateDir, checkAndCreateDir,
requestPermission, requestPermission,