File size: 9,083 Bytes
3cfdf1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
//
// CveServices - Service Worker Middleware
// Filename: sw.js
//
// Author: Ben N
//
// Description: Handles exchange of API requests with credentials.
//
// Copyright 2022, Ben Nott <[email protected]>.
// See LICENSE for a full copy of the license.
//

const storage = {};
const keyname = "cve-services.cvsskeyStore";
/* Encryption API using JavaScript native crypto.js and indexeDB for storing private keys */
const encrypt_storage_version = "1.1.14";
const cacheName = 'private';
const cacheURL = '/creds';

destroySession = () => {
    if ('creds' in storage) {
        delete storage['creds'];
        let bc = new BroadcastChannel('logout');
        bc.postMessage({ 'error': 'LOGOUT', message: 'The user has logged out' });
    }
    caches.open(cacheName).then(cache => {
        cache.delete(cacheURL);
    });
};

setSessionTimer = () => {
    let defaultTimeout = 1000 * 60 * 60; //1 hour timeout

    setTimeout(
        destroySession,
        defaultTimeout
    );
};

setCredentials = (e) => {
    storage.creds = e.data.creds;
    check_create_key(e.data.creds.user).then(function (newkey) {
        encryptMessage(e.data.creds.key, newkey.publicKey)
            .then(function (encBuffer) {
                arrayBuffertoURI(encBuffer)
                    .then(function (encURL) {
                        let f = JSON.parse(JSON.stringify(e.data.creds));
                        delete f['key'];
                        f['keyURL'] = encURL;
                        clientReply(e, { data: "ok" });
                        caches.open(cacheName).then(function (cache) {
                            let cachecreds = new Response(JSON.stringify(f));
                            cache.put(cacheURL, cachecreds);
                        });
                        setSessionTimer();
                    });
            });
    });
};

clientReply = (e, msg) => {
    e.ports[0].postMessage(msg);
};

deadSession = (e, debugString) => {
    clientReply(e, {
        error: "NO_SESSION",
        message: "Please login."
        //debug: debugString
    });
    return false;
}

checkSession = async (e) => {
    if (!('creds' in storage)) {
        try {
            let cache = await caches.open(cacheName);
            let cachecreds = await cache.match(cacheURL);
            if (cachecreds) {
                let result = await cachecreds.json();
                let ekey = await check_create_key(result.user);
                let encBuffer = URItoarrayBuffer(result.keyURL);
                let rawKey = await decryptMessage(encBuffer, ekey.privateKey);
                result.key = rawKey;
                delete result.keyURL;
                storage.creds = JSON.parse(JSON.stringify(result));
                return true;
            } else {
                return deadSession(e);
            }
        } catch (err) {
            return deadSession(e, String(err));
        }
    };
    return true;
};

defaultOpts = () => {
    return {
        headers: {
            'content-type': 'application/json',
            'CVE-API-KEY': storage.creds.key,
            'CVE-API-ORG': storage.creds.org,
            'CVE-API-USER': storage.creds.user,
        },
    };
};

getURL = (path, query) => {
    let url = new URL(`/api/${path}`, storage.serviceUri);

    if (query) {
        for (const [k, v] of Object.entries(query)) {
            url.searchParams.append(k, v);
        }
    }

    return url.toString();
};

doFetch = (event, url, opts) => {
    return fetch(url, opts)
        .then(res => {
            if (res.ok) {
                res.json().then(data => clientReply(event, data));
            } else {
                res.json().then(msg => {
                    clientReply(event, msg);
                });
            }
        })
        .catch(err => {
            clientReply(event, { error: err });
        });
};

requestService = (event) => {
    let { query, path, method } = event.data;

    let opts = defaultOpts();
    let url = getURL(path, query);

    if (['PUT', 'POST'].includes(method)) {
        opts.method = method;

        if ('body' in event.data) {
            opts.body = JSON.stringify(event.data.body);
        }
    }

    return doFetch(event, url, opts);
};

self.onmessage = e => {
    switch (e.data.type) {
        case 'init':
            if ('serviceUri' in e.data) {
                storage.serviceUri = e.data.serviceUri;
                clientReply(e, 'ok');
            }
            break;
        case 'echo':
            clientReply(e, 'echo');
            break;
        case 'login':
            setCredentials(e);
            break;
        case 'request':
            checkSession(e).then(function (success) {
                if (success)
                    requestService(e);
                else
                    clientReply(e, { error: "NO_SESSION" });
            });
            break;
        case 'getOrg':
            checkSession(e).then(function (success) {
                if (success)
                    clientReply(e, storage.creds.org);
                else
                    clientReply(e, { error: "NO_SESSION" })
            });
            break;
        case 'destroy':
            destroySession();
            clientReply(e, "Cleaning up session");
            break;
        default:
            clientReply(e, { error: 'Not supported' });
            break;
    }
};

async function encryptMessage(message, publicKey) {
    let encoded = new TextEncoder().encode(message);
    let ciphertext = await crypto.subtle.encrypt(
        {
            name: "RSA-OAEP"
        },
        publicKey,
        encoded
    );
    return ciphertext;
}
async function decryptMessage(ciphertext, privateKey) {
    let decrypted = await crypto.subtle.decrypt(
        {
            name: "RSA-OAEP"
        },
        privateKey,
        ciphertext
    );

    let dec = new TextDecoder();
    return dec.decode(decrypted);
}
async function arrayBuffertoURI(arrayBuffer) {
    let blob = new Blob([arrayBuffer]);
    return new Promise((resolve) => {
        let reader = new FileReader()
        reader.onloadend = function () {
            resolve(reader.result);
        };
        reader.readAsDataURL(blob);
    });
}
function URItoarrayBuffer(URI) {
    var byteString = atob(URI.split(',')[1]);
    var arrayBuffer = new ArrayBuffer(byteString.length);
    var _ia = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteString.length; i++) {
        _ia[i] = byteString.charCodeAt(i);
    }
    return arrayBuffer;
}


async function sha256sum(msg) {
    let enc = new TextEncoder().encode(msg);
    const buff = await crypto.subtle.digest('SHA-256', enc);
    const barray = Array.from(new Uint8Array(buff));
    let hex = barray.map(function (b) {
        return b.toString(16).padStart(2, '0');
    }).join('');
    return hex;
};
function dbManager(user, key, sum) {
    return new Promise(function (resolve, reject) {
        var open = indexedDB.open(keyname, 1);
        open.onupgradeneeded = function () {
            var db = open.result;
            if (!db.objectStoreNames.contains("keyStore")) {
                var store = db.createObjectStore("keyStore",
                    { keyPath: "user" });
                var index = store.createIndex("sigIndex", ["sum.sha256"]);
            }
        };
        open.onsuccess = function () {
            var db = open.result;
            var tx = db.transaction("keyStore", "readwrite");
            var store = tx.objectStore("keyStore");
            if (key) {
                store.put({ user: user, key: key, sum: sum });
            } else {
                if (user) {
                    var getUser = store.get(user);
                    getUser.onsuccess = function (q) {
                        resolve(q);
                    };
                } else if (sum.sha256) {
                    var index = store.index("sigIndex");
                    var getSum = index.get([sum.sha256]);
                    getSum.onsuccess = function (q) {
                        resolve(q);
                    };
                } else {
                    reject("A user or a checksum is required");
                }
            };
            tx.oncomplete = function () {
                db.close();
            };
        }
    });
}

async function save_key(user, key) {
    let fpb = await crypto.subtle.exportKey("jwk", key.publicKey);
    let sum = { sha256: await sha256sum(fpb.n) };
    dbManager(user, key, sum);
    return key;
}

async function check_create_key(user) {
    let dbKey = await dbManager(user);
    if (('target' in dbKey) && (dbKey.target.result) &&
        (dbKey.target.result.user == user)) {
        return dbKey.target.result.key;
    }
    return crypto.subtle.generateKey(
        {
            name: "RSA-OAEP",
            modulusLength: 4096,
            publicExponent: new Uint8Array([1, 0, 1]),
            hash: "SHA-256",
        },
        false,
        ["encrypt", "decrypt"]
    ).then(function (key) {
        save_key(user, key);
        return key;
    });
}