-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathenvelope.js.html
514 lines (457 loc) · 15.5 KB
/
envelope.js.html
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: envelope.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: envelope.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import { Buffer } from 'buffer'
import { OpCode, Script } from 'bsv'
import cbor from 'borc'
import base64url from 'base64url'
import Header from './header.js'
import Recipient from './recipient.js'
import Signature from './signature.js'
import algs from './algs/index.js'
const UNIVRSE_PREFIX = 'UNIV'
/**
* Envelope class
*
* A Univrse Envelope is a structure containing a set of headers, a payload,
* and optionally one or more Signatures and Recipients.
*
* An Envelope can be converted to a compact CBOR encoded buffer, a Base64
* encoded string, or a Bitcoin OP_RETURN Script. This allows envelopes to be
* easily and efficiently transferred between different parties, who in turn can
* decode the wrapped payload.
*/
class Envelope {
/**
* Instantiates a new Envelope instance with the given params.
*
* Accepted params
*
* * `headers` - headers object
* * `payload` - data payload
* * `signature` - singature instance or array of signatures
* * `recipient` - recipient instance or array of recipients
*
* @param {Object} params
* @constructor
*/
constructor({ headers, payload, signature, recipient }) {
this.header = Header.wrap(headers)
this.payload = payload
this.signature = signature
this.recipient = recipient
}
/**
* Instantiates a new Envelope instance with the given array of parts.
*
* Used internally when decoding envelopes.
*
* @param {Array} parts
* @constructor
*/
static fromArray(parts) {
return new this({
headers: parts[0],
payload: parts[1],
signature: Array.isArray(parts[2]) ? Signature.fromArray(parts[2]) : undefined,
recipient: Array.isArray(parts[3]) ? Recipient.fromArray(parts[3]) : undefined
})
}
/**
* Decodes the given buffer and instantiates a new Envelope instance.
*
* @param {Buffer} buf
* @constructor
*/
static fromBuffer(buf) {
return this.fromArray(cbor.decode(buf))
}
/**
* Decodes the given Bitcoin Script and instantiates a new Envelope instance.
*
* @param {Script} script
* @constructor
*/
static fromScript(script) {
const idx = script.chunks.findIndex((c, i, chunks) => {
return c.opCodeNum === 106 && chunks[i+1].buf
&& chunks[i+1].buf.toString() === UNIVRSE_PREFIX
})
if (idx >= 0) {
const parts = script.chunks.slice(idx+2).map(c => cbor.decode(c.buf))
return this.fromArray(parts)
} else {
throw 'Invalid Univrse script'
}
}
/**
* Decodes the given base64 string and instantiates a new Envelope instance.
*
* @param {String} str
* @constructor
*/
static fromString(str) {
const parts = str.split('.')
.map(s => {
const buf = base64url.toBuffer(s)
return cbor.decode(buf)
})
return this.fromArray(parts)
}
/**
* Wraps the given payload and headers in a new Envelope instance.
*
* @param {*} payload
* @param {Object} headers
* @constructor
*/
static wrap(payload, headers = {}) {
return new this({ headers, payload })
}
/**
* CBOR encoded payload
*
* @type {Buffer}
*/
get encodedPayload() {
return cbor.encode(this.payload)
}
/**
* Sets the payload by decoding the given encoded payload.
*
* @type {Buffer}
*/
set encodedPayload(payload) {
this.payload = cbor.decode(payload)
}
/**
* Decrypts the payload using the given key.
*
* If the Envelope contains multiple recipients, it is assumed the key belongs
* to the first recipient. Otherwise, see `decryptAt()`.
*
* An second argument of options can be given for the relevant encryption
* algorithm.
*
* @param {Key} key
* @param {Object} opts
* @returns {Envelope}
*/
async decrypt(key, opts = {}) {
const header = Array.isArray(this.recipient) ? this.recipient[0].header : this.recipient.header
const { alg } = header.headers
const aad = cbor.encode([
'enc',
this.header.unwrap(),
opts.aad ? opts.aad : ''
])
const encOpts = {
...opts,
...['epk', 'iv', 'tag'].reduce((o, k) => { o[k] = header.headers[k]; return o }, {}),
aad
}
this.encodedPayload = await algs.decrypt(alg, this.payload, key, encOpts)
return this
}
/**
* Decrypts the payload by first decrypting the content key at the specified
* recipient index.
*
* The Envelope mustcontains multiple recipients.
*
* @param {Number} i recipient index
* @param {Key} key
* @param {Object} opts
* @returns {Envelope}
*/
async decryptAt(i, key, opts = {}) {
if (!Array.isArray(this.recipient) || this.recipient.length <= i) {
throw 'Invalid recipient index'
}
await this.recipient[i].decrypt(key, opts)
return this.decrypt(this.recipient[i].key, opts)
}
/**
* Encrypts the payload using the given key or array of keys.
*
* A headers object must be given including at least the encryption `alg`
* value.
*
* A third argument of options can be given for the relevant encryption
* algorithm.
*
* Where an array of keys is given, the first key is taken as the content key
* and used to encrypt the payload. The content key is then encrypted by each
* subsequent key and included in the Recipient instances that are attached to
* the envelope.
*
* When encrypting to multiple recipients, it is possible to specify different
* algorithms for each key by giving an array of two element arrays. The first
* element of each pair is the key and the second is a headers object.
*
* ## Examples
*
* Encrypts for a single recipient:
*
* envelope.encrypt(aesKey, { alg: 'A128GCM' })
*
* Encrypts for a multiple recipients using the same algorithm:
*
* envelope.encrypt([aesKey, recKey], { alg: 'A128GCM' })
*
* Encrypts for a multiple recipients using different algorithms:
*
* envelope.encrypt([
* aesKey,
* [rec1Key, { alg: 'ECDH-ES+A128GCM' }],
* [rec2Key, { alg: 'ECDH-ES+A128GCM' }],
* ], { alg: 'A128GCM' })
*
* @param {Key|Key[]|[Key, Object][]} key encryption key or array of keys
* @param {Object} headers
* @param {Object} opts
* @returns {Envelope}
*/
async encrypt(key, headers = {}, opts = {}) {
if (Array.isArray(key)) {
const [mkey, mheaders] = mergeKeyHeaders(key[0], headers)
await this.encrypt(mkey, mheaders)
let kkey, kheaders, krecipient
for (let i = 1; i < key.length; i++) {
[kkey, kheaders] = mergeKeyHeaders(key[i], headers)
krecipient = await mkey.encrypt(kkey, kheaders, opts)
this.pushRecipient(krecipient)
}
return this
}
const { alg } = headers
const aad = cbor.encode([
'enc',
this.header.unwrap(),
opts.aad ? opts.aad : ''
])
const encOpts = {
...opts,
...['iv'].reduce((o, k) => { o[k] = headers[k]; return o }, {}),
aad
}
const { encrypted, ...newHeaders } = await algs.encrypt(alg, this.encodedPayload, key, encOpts)
this.payload = encrypted
const recipient = Recipient.wrap(null, { ...headers, ...newHeaders })
return this.pushRecipient(recipient)
}
/**
* Attaches the given Recipient instance onto the Envelope.
*
* @param {Recipient} recipient
* @returns {Envelope}
*/
pushRecipient(recipient) {
if (Array.isArray(this.recipient)) {
this.recipient.push(recipient)
} else if (this.recipient) {
this.recipient = [this.recipient, recipient]
} else {
this.recipient = recipient
}
return this
}
/**
* Attaches the given Signature instance onto the Envelope.
*
* @param {Signature} signature
* @returns {Envelope}
*/
pushSignature(signature) {
if (Array.isArray(this.signature)) {
this.signature.push(signature)
} else if (this.signature) {
this.signature = [this.signature, signature]
} else {
this.signature = signature
}
return this
}
/**
* Signs the payload using the given key or array of keys.
*
* A headers object must be given including at least the signature `alg`
* value.
*
* Where an array of keys is given, it is possible to specify different
* algorithms for each key by giving an array of two element arrays. The first
* element of each pair is the key and the second is a headers object.
*
* ## Examples
*
* Creates a signature using a single key:
*
* envelope.sign(octKey, { alg: 'HS256' })
*
* Creates multiple signatures using the same algorithm:
*
* envelope.sign([userKey, appKey], { alg: 'HS256' })
*
* Creates multiple signatures using different algorithms:
*
* envelope.sign([
* octKey,
* [ecKey1, { alg: 'ES256K' }],
* [ecKey2, { alg: 'ES256K' }]
* ], { alg: 'HS256' })
*
* @param {Key|Key[]|[Key, Object][]} key signing key or array of keys
* @param {Object} headers
* @returns {Envelope}
*/
async sign(key, headers = {}) {
if (Array.isArray(key)) {
for (let i = 0; i < key.length; i++) {
if (Array.isArray(key[i]) && key[i].length === 2) {
await this.sign(key[i][0], { ...headers, ...key[i][1] })
} else {
await this.sign(key[i], headers)
}
}
return this
}
const alg = {
...this.header.headers,
...headers
}['alg']
const data = cbor.encode(this.toArray().slice(0, 2))
const sig = await algs.sign(alg, data, key)
return this.pushSignature(Signature.wrap(sig, headers))
}
/**
* Returns the Envelope as an array of component parts.
*
* Used internally prior to encoding the envelope.
*
* @returns {Array}
*/
toArray() {
const parts = [
this.header.unwrap(),
this.payload
]
if (Array.isArray(this.signature)) {
parts.push(this.signature.map(s => s.toArray()))
} else if (this.signature && typeof this.signature.toArray === 'function') {
parts.push(this.signature.toArray())
} else if (this.recipient) {
parts.push(null)
}
if (Array.isArray(this.recipient)) {
parts.push(this.recipient.map(s => s.toArray()))
} else if (this.recipient && typeof this.recipient.toArray === 'function') {
parts.push(this.recipient.toArray())
}
return parts
}
/**
* Returns the Envelope as a CBOR encoded Buffer.
*
* @returns {Buffer}
*/
toBuffer() {
return cbor.encode(this.toArray())
}
/**
* Returns the Envelope as bsv Script instance.
*
* @param {Boolean} [falseReturn=true]
* @returns {String}
*/
toScript(falseReturn = true) {
const script = new Script()
if (falseReturn) {
script.writeOpCode(OpCode.OP_FALSE)
}
script.writeOpCode(OpCode.OP_RETURN)
script.writeBuffer(Buffer.from(UNIVRSE_PREFIX))
return this.toArray()
.reduce((s, p) => {
return s.writeBuffer(cbor.encode(p))
}, script)
}
/**
* Returns the Envelope as Base64 encoded string.
*
* @returns {String}
*/
toString() {
return this.toArray()
.map(p => base64url.encode(cbor.encode(p)))
.join('.')
}
/**
* Verifies the signature(s) using the given Key or array of Keys.
*
* Where the envelope has multiple signature, can optionally specfify the
* signature index the key relates to.
*
* @param {Key|Key[]} key key or array of keys
* @param {Number} i signature index
* @returns {Boolean}
*/
async verify(key, i) {
// If index not provided and array of keys, iterate over each and verify each signature
if (!i && Array.isArray(key) && Array.isArray(this.signature) && key.length === this.signature.length) {
const verifications = key.map((k, i) => this.verify(k, i))
const results = await Promise.all(verifications)
return results.every(r => r === true)
}
// If index is given use the specified signature
let signature = this.signature
if (Number.isInteger(i) && Array.isArray(this.signature)) {
signature = this.signature[i]
}
const alg = {
...this.header.headers,
...signature.header.headers
}['alg']
const data = cbor.encode(this.toArray().slice(0, 2))
return algs.verify(alg, data, signature.signature, key)
}
}
/**
* Helper function to merge key headers
*/
function mergeKeyHeaders(key, headers) {
if (Array.isArray(key) && key.length === 2) {
return [key[0], { ...headers, ...key[1] }]
} else {
return [key, headers]
}
}
export default Envelope</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="Envelope.html">Envelope</a></li><li><a href="Envelope.fromArray.html">fromArray</a></li><li><a href="Envelope.fromBuffer.html">fromBuffer</a></li><li><a href="Envelope.fromScript.html">fromScript</a></li><li><a href="Envelope.fromString.html">fromString</a></li><li><a href="Envelope.wrap.html">wrap</a></li><li><a href="Header.html">Header</a></li><li><a href="Header.wrap.html">wrap</a></li><li><a href="Key.html">Key</a></li><li><a href="Key.decode.html">decode</a></li><li><a href="Key.generate.html">generate</a></li><li><a href="Recipient.html">Recipient</a></li><li><a href="Recipient.fromArray.html">fromArray</a></li><li><a href="Recipient.wrap.html">wrap</a></li><li><a href="Signature.html">Signature</a></li><li><a href="Signature.fromArray.html">fromArray</a></li><li><a href="Signature.wrap.html">wrap</a></li></ul><h3>Global</h3><ul><li><a href="global.html#AES_CBC_HMAC">AES_CBC_HMAC</a></li><li><a href="global.html#AES_GCM">AES_GCM</a></li><li><a href="global.html#algs">algs</a></li><li><a href="global.html#assertKey">assertKey</a></li><li><a href="global.html#computeSharedSecret">computeSharedSecret</a></li><li><a href="global.html#createMacMessage">createMacMessage</a></li><li><a href="global.html#ECDH_AES">ECDH_AES</a></li><li><a href="global.html#ECIES_BIE1">ECIES_BIE1</a></li><li><a href="global.html#ES256K">ES256K</a></li><li><a href="global.html#ES256K_BSM">ES256K_BSM</a></li><li><a href="global.html#fromBsvPrivKey">fromBsvPrivKey</a></li><li><a href="global.html#fromBsvPubKey">fromBsvPubKey</a></li><li><a href="global.html#HMAC">HMAC</a></li><li><a href="global.html#kdf">kdf</a></li><li><a href="global.html#mergeKeyHeaders">mergeKeyHeaders</a></li><li><a href="global.html#messageDigest">messageDigest</a></li><li><a href="global.html#params">params</a></li><li><a href="global.html#pubKeyBuf">pubKeyBuf</a></li><li><a href="global.html#splitKey">splitKey</a></li><li><a href="global.html#toBsvPrivKey">toBsvPrivKey</a></li><li><a href="global.html#toBsvPubKey">toBsvPubKey</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.6</a>
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>