1 | var base64url = require('../utils/base64url')
|
2 | , assert = require('assert')
|
3 | , nacl = require('tweetnacl')
|
4 | , a = require('../utils/a')
|
5 |
|
6 | function parsePubkey (input, recipients) {
|
7 | var buf, name, email
|
8 | try {
|
9 |
|
10 | if (Buffer.isBuffer(input)) {
|
11 | buf = input
|
12 | }
|
13 |
|
14 | else if (typeof input === 'string') {
|
15 | var match = input.match(/(?:salty\-id)?\s*([a-zA-Z0-9-\_]+)\s*(?:"([^"]*)")?\s*(?:<([^>]*)>)?/)
|
16 | assert(match)
|
17 | buf = base64url.decode(match[1])
|
18 | name = match[2]
|
19 | email = match[3] ? match[3].toLowerCase() : null
|
20 | }
|
21 | assert.equal(buf.length, 64)
|
22 | }
|
23 | catch (e) {
|
24 | throw new Error('invalid pubkey')
|
25 | }
|
26 | if (recipients) {
|
27 |
|
28 | var recipient = recipients[buf.toString('base64')]
|
29 | if (recipient && !name && !email) {
|
30 | name = recipient.name
|
31 | email = recipient.email
|
32 | }
|
33 | }
|
34 | return {
|
35 | type: 'salty-id',
|
36 | encryptPk: buf.slice(0, 32),
|
37 | verifyPk: buf.slice(32),
|
38 | pubkey: base64url.encode(buf),
|
39 | name: name,
|
40 | email: email,
|
41 | verify: function (sig, detachedBuf) {
|
42 | if (detachedBuf) {
|
43 | return nacl.sign.detached.verify(a(detachedBuf), a(sig), a(this.verifyPk)) ? detachedBuf : false
|
44 | }
|
45 | var result = nacl.sign.open(a(sig), a(this.verifyPk))
|
46 | if (!result) return false
|
47 | return Buffer(result)
|
48 | },
|
49 | toString: function (nice) {
|
50 | var parts = nice ? [] : [
|
51 | 'salty-id',
|
52 | this.pubkey
|
53 | ]
|
54 | if (this.name) parts.push('"' + this.name.replace(/"/g, '') + '"')
|
55 | if (this.email) parts.push('<' + this.email.replace(/>/g, '') + '>')
|
56 | if (nice && !this.name && !this.email) parts.push(pubkeys)
|
57 | return parts.join(' ')
|
58 | },
|
59 | toBuffer: function () {
|
60 | return buf
|
61 | }
|
62 | }
|
63 | }
|
64 |
|
65 | module.exports = {
|
66 | parse: parsePubkey
|
67 | } |
\ | No newline at end of file |