This repository has been archived by the owner on Jun 1, 2019. It is now read-only.
forked from garvankeeley/kinto-lockbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lockboxItem.js
58 lines (52 loc) · 1.78 KB
/
lockboxItem.js
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
// @ts-check
// faked
function decryptItem(encryptedItem) {
return kinto.collection(DB.perItemKeys.name).list({
filters: { [DB.perItemKeys.C.itemId]: encryptedItem.id }
}).then(results => {
if (results.data.length !== 1) {
return Promise.reject(new Error(`decryptItem: Result count incorrect: ${results.data.length}`));
}
const secret = results.data[0][DB.perItemKeys.C.key];
let str = atob(encryptedItem[DB.items.C.encryptedData]);
return JSON.parse(str.replace(secret, ''));
});
}
function addItem(itemData) {
function createPerItemKey(itemUuid, encryptionKey) {
// deriveKey(itemUuid, encryptionKey).then(...)
const key = encryptionKey + itemUuid;
return kinto.collection(DB.perItemKeys.name).create({
[DB.perItemKeys.C.itemId]: itemUuid,
[DB.perItemKeys.C.key]: key
})
.then(added => {
return added.data;
});
}
function createEmptyItem() {
return kinto.collection(DB.items.name).create({})
.then(result => result.data.id)
}
// faked
function encryptItem(itemData, perItemKey) {
const str = JSON.stringify(itemData);
const b64 = btoa(str + perItemKey[DB.perItemKeys.C.key]);
return Promise.resolve({
id: perItemKey[DB.perItemKeys.C.itemId],
[DB.items.C.encryptedData]: b64
});
}
function updateItemEncryptedData(encryptedItem) {
return kinto.collection(DB.items.name).update(encryptedItem);
}
return createEmptyItem()
.then(resultId => createPerItemKey(resultId, masterEncryptionKey))
.then(perItemKey => encryptItem(itemData, perItemKey))
.then(encryptedItem => updateItemEncryptedData(encryptedItem))
.then(updatedItem => createOriginHash(updatedItem.data.id, itemData.site))
.catch(ex => {
console.error(ex);
console.trace();
});
}