This repository has been archived by the owner. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
373 lines (325 loc) · 10.9 KB
/
index.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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
* Tide Protocol - Infrastructure for the Personal Data economy
* Copyright (C) 2019 Tide Foundation Ltd
*
* This program is free software and is subject to the terms of
* the Tide Community Open Source Licence as published by the
* Tide Foundation Limited. You may modify it and redistribute
* it in accordance with and subject to the terms of that licence.
* This program is distributed WITHOUT WARRANTY of any kind,
* including without any implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
* See the Tide Community Open Source Licence for more details.
* You should have received a copy of the Tide Community Open
* Source Licence along with this program.
* If not, see https://tide.org/licenses/tcosl-1.0.en.html
*/
const ecc = require('eosjs-ecc');
class Tide {
init(orkNodes, vendorEndpoint, vendorUsername, encryptionStrength = 32) {
this.nodeArray = orkNodes;
this.threshold = orkNodes.length - 1;
this.hashes = [];
this.encryptionStrength = encryptionStrength;
this.vendorEndpoint = vendorEndpoint;
this.vendorUsername = vendorUsername;
}
createMasterAccount(username, password, useOrks) {
var self = this;
return new Promise(async function(resolve, reject) {
try {
const hashedCreds = self.hashUsername(username);
// Create keys
const keys = await createBlockchainKeys();
// Initialize the account
const accountResult = await self.tideRequest(`${self.vendorEndpoint}/${actions.INIT_USER}`, {
username: hashedCreds.username,
publicKey: keys.pub,
});
if (!accountResult.success) return reject(accountResult.error);
if (useOrks) {
// Create fragments
const frags = cryptide.shareText(keys.priv, self.nodeArray.length, self.threshold);
// Hash password and get the password fragments
self.hashes = await cryptide.hashPasswords(password, hashedCreds.salt, self.nodeArray);
// Send fragments to the ork nodes
await postFragments(self.nodeArray, keys.pub, frags, hashedCreds.username, self.hashes);
}
// Confirm the account
await self.tideRequest(`${self.vendorEndpoint}/${actions.CONFIRM_USER}`, {
username: hashedCreds.username,
});
return resolve({
pub: keys.pub,
priv: keys.priv,
account: accountResult.content,
});
} catch (thrownError) {
return reject(`Failed sending fragments to all selected orks with error: ${thrownError}`);
}
});
}
postCredentials(username, password, useOrks, master = false) {
var self = this;
return new Promise(async function(resolve, reject) {
try {
const hashedCreds = self.hashUsername(username);
// Create keys. Eos for master and elgamal for vendor
const keys = createKeys();
if (useOrks) {
// Create fragments. Eos for master and elgamal for vendor
const frags = cryptide.shareKey(keys.priv, self.nodeArray.length, self.threshold);
// Hash password and get the password fragments
self.hashes = await cryptide.hashPasswords(password, hashedCreds.salt, self.nodeArray);
// Send fragments to ork nodes
await postFragments(self.nodeArray, keys.pub, frags, hashedCreds.username, self.hashes);
}
// If master, confirm the account
if (master) await self.tideRequest(`${self.vendorEndpoint}/${actions.CONFIRM_USER}`, hashedCreds);
return resolve({
pub: publicKey,
priv: keys.priv,
});
} catch (thrownError) {
return reject(`Failed sending fragments to all selected orks with error: ${thrownError}`);
}
});
}
getCredentials(username, password) {
var self = this;
return new window.Promise(async function(resolve, reject) {
const id = nextId();
log(id, `gathering user nodes...`);
try {
const hashedCreds = self.hashUsername(username);
// Gather the nodes the user used to register with Tide
const userNodes = await tideRequest(`${self.nodeArray[0]}/nodes`, {
username: hashedCreds.username,
});
log(id, `Gathered user nodes. Count: ${userNodes.length}`);
log(id, `Creating password fragments`);
self.hashes = await cryptide.hashPasswords(
password,
hashedCreds.salt,
userNodes.map(n => n.ork_url),
);
// Get the fragments from each node
const fragmentResult = await getFragments(
userNodes,
hashedCreds.username,
password,
self.hashes,
self.threshold,
);
return resolve(fragmentResult);
} catch (thrownError) {
log(nextId(), thrownError, 'error');
return reject();
}
});
}
processEncryption(encrypt, data, key) {
return new window.Promise(async function(resolve, reject) {
try {
if (data == '' || data == null) return resolve('');
return resolve(encrypt ? cryptide.encrypt(data, key) : cryptide.decrypt(data, key));
} catch (error) {
return reject('Incorrect private key');
}
});
}
hashUsername(data) {
var salt = cryptide.hashSha(data);
var username = cryptide.hashSha(salt);
var vendorUsername = cryptide.hashSha(`${salt}-${this.vendorUsername}`);
return {
salt: salt,
username: username,
vendorUsername: vendorUsername,
};
}
tideRequest(url, data) {
return executeTideRequest(url, data);
}
createKeys() {
const [privateKey, publicKey] = cryptide.getKeys(self.encryptionStrength);
return {
priv: privateKey,
pub: publicKey,
};
}
sign(message) {
return new window.Promise(async function(resolve, reject) {
try {
var flow = new cryptide.TSignFlow(
[
'https://raziel-ork-1.azurewebsites.net',
'https://raziel-ork-2.azurewebsites.net',
'https://raziel-ork-3.azurewebsites.net',
'https://raziel-ork-4.azurewebsites.net'
],
'admin',
);
flow
.sign(message)
.then(sign => {
resolve(sign);
})
.catch(err => {
console.log(err.response.text);
console.log(err);
reject(err);
});
} catch (error) {
reject(error);
}
});
}
}
function getlink(message, address, signature) {
return `https://brainwalletx.github.io/#verify?vrAddr=${address}&vrMsg=${encodeURI(message)}&vrSig=${encodeURI(
signature,
)}`;
}
function postFragments(nodes, pub, frags, username, hashes) {
return new Promise(async function(resolve, reject) {
var complete = 0;
for (let i = 0; i < nodes.length; i++) {
const nodeIndex = i;
const model = {
username: username,
accountPublic: pub,
accountPrivateFrag: frags[i],
PasswordHash: hashes.find(h => h.server == nodes[nodeIndex]).pass,
};
await executeTideRequest(nodes[nodeIndex] + '/PushFragment', model)
.then(r => {
if (r.success) {
complete++;
} else {
return reject(r.error);
}
if (complete == nodes.length) {
return resolve();
}
})
.catch(e => {
log(nextId(), `Failed pushing fragments`);
});
}
});
}
function getFragments(nodes, username, password, hashes, threshold) {
return new window.Promise(async function(resolve, reject) {
var frags = [];
var failedCount = 0;
const id = nextId();
const failId = nextId();
// Seed transient keys
log(nextId(), `Generating transient key-pair for transmission encryption`);
const [priv, pub] = cryptide.getKeys(32);
log(id, `Gathering fragments. ${frags.length}/${nodes.length}`);
const model = {
username: username,
publicKey: pub,
passwordHash: '',
};
const results = nodes.map(n => tideRequest(`${n.ork_url}/login`, appendHash(model, n.ork_url, hashes)));
for (const r of results) {
await r
.then(content => {
frags.push(content);
log(id, `Gathering fragments. ${frags.length}/${nodes.length}`);
if (frags.length == threshold) {
log(id, `Finished gathering fragments`, 'success');
return resolve({
priv: cryptide.combineKeys(frags.map(f => cryptide.decrypt(f.vendorFragment.private_key_frag, priv))),
pub: frags[0].vendorFragment.public_key,
});
}
})
.catch(e => {
log(failId, `Failed gathering ${failedCount++} fragments`);
if (failedCount > nodes.length - threshold) return reject(e);
});
}
});
}
function tideRequest(url, data) {
return new window.Promise(async function(resolve, reject) {
const http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200) {
const content = JSON.parse(this.responseText);
if (content.success) return resolve(content.content);
return reject(content.error);
} else return reject(this.error);
}
};
http.open(data != null ? 'POST' : 'GET', url);
if (data != null) {
http.setRequestHeader('Content-type', 'application/json; charset=utf-8');
http.send(JSON.stringify(data));
} else {
http.send();
}
});
}
function appendHash(model, node, hashes) {
model.passwordHash = hashes.find(h => h.server == node).pass;
return model;
}
var currentId = 0;
function nextId() {
return currentId++;
}
function log(id, msg, type = 'log') {
document.dispatchEvent(
new CustomEvent('tide-log', {
detail: {
id: id,
msg: msg,
type: type,
},
}),
);
}
function executeTideRequest(url, data) {
return new window.Promise(async function(resolve, reject) {
const http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200) {
const content = JSON.parse(this.responseText);
if (content.success) return resolve(content);
return reject(content.error);
} else return reject(this.error);
}
};
http.open(data != null ? 'POST' : 'GET', url);
if (data != null) {
http.setRequestHeader('Content-type', 'application/json; charset=utf-8');
http.send(JSON.stringify(data));
} else {
http.send();
}
});
}
function createBlockchainKeys() {
return new window.Promise(async function(resolve, reject) {
ecc.randomKey().then(privateKey => {
return resolve({
priv: privateKey,
pub: ecc.privateToPublic(privateKey),
});
});
});
}
const actions = {
INIT_USER: 'initializeAccount',
CONFIRM_USER: 'confirmAccount',
};
module.exports = {
Create: new Tide(),
};