Files: 28939365d49976f347ac453a0e7ba7580b43c55b / util.js
1372 bytesRaw
1 | var chloride = require('chloride') |
2 | |
3 | function box (data, key) { |
4 | if(!data) return |
5 | var b = new Buffer(JSON.stringify(data)) |
6 | return chloride.crypto_secretbox_easy(b, key.slice(0, 24), key).toString('base64') |
7 | } |
8 | |
9 | function unbox (ctxt, key) { |
10 | var b = new Buffer(ctxt, 'base64') |
11 | var ptxt = chloride.crypto_secretbox_open_easy(b, key.slice(0, 24), key) |
12 | if(!ptxt) return |
13 | try { |
14 | return JSON.parse(ptxt) |
15 | } catch(err) { |
16 | console.error(err) |
17 | } |
18 | } |
19 | |
20 | |
21 | function hash(s) { |
22 | return chloride.crypto_hash_sha256( |
23 | 'string' == typeof s ? new Buffer(s, 'utf8') : s |
24 | ) |
25 | } |
26 | |
27 | exports.hash = hash |
28 | exports.box = box |
29 | exports.unbox = unbox |
30 | exports.parse = function (str) { |
31 | if(!/^inv\:/.test(str)) throw new Error('invites must start with "inv:", got '+JSON.stringify(str)) |
32 | var ary = str.substring(4).split(',') |
33 | return { |
34 | seed: ary[0], |
35 | invite: ary[1], |
36 | cap: ary[2], |
37 | pubs: ary.slice(3) |
38 | } |
39 | } |
40 | exports.stringify = function (invite) { |
41 | return 'inv:'+[ |
42 | invite.seed, |
43 | invite.invite, |
44 | invite.cap || '' |
45 | ] |
46 | .concat(invite.pubs) |
47 | .join(',') |
48 | } |
49 | |
50 | exports.sort = function (found) { |
51 | return found.sort(function (a, b) { |
52 | console.log([a.willReplicate, b.willReplicate], (!!a.willReplicate) - (!!b.willReplicate), b.availability - a.availability); |
53 | return (!!b.willReplicate) - (!!a.willReplicate) || (b.availability - a.availability) |
54 | }) |
55 | } |
56 |
Built with git-ssb-web