@libp2p/keychain 3.0.7 → 3.0.8-0b4a2ee79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,563 @@
1
+ /* eslint max-nested-callbacks: ["error", 5] */
2
+
3
+ import { pbkdf2, randomBytes } from '@libp2p/crypto'
4
+ import { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'
5
+ import { CodeError } from '@libp2p/interface/errors'
6
+ import { peerIdFromKeys } from '@libp2p/peer-id'
7
+ import { Key } from 'interface-datastore/key'
8
+ import mergeOptions from 'merge-options'
9
+ import sanitize from 'sanitize-filename'
10
+ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
11
+ import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
12
+ import { codes } from './errors.js'
13
+ import type { KeychainComponents, KeychainInit, Keychain, KeyInfo } from './index.js'
14
+ import type { Logger } from '@libp2p/interface'
15
+ import type { KeyType } from '@libp2p/interface/keys'
16
+ import type { PeerId } from '@libp2p/interface/peer-id'
17
+
18
+ const keyPrefix = '/pkcs8/'
19
+ const infoPrefix = '/info/'
20
+ const privates = new WeakMap<object, { dek: string }>()
21
+
22
+ // NIST SP 800-132
23
+ const NIST = {
24
+ minKeyLength: 112 / 8,
25
+ minSaltLength: 128 / 8,
26
+ minIterationCount: 1000
27
+ }
28
+
29
+ const defaultOptions = {
30
+ // See https://cryptosense.com/parametesr-choice-for-pbkdf2/
31
+ dek: {
32
+ keyLength: 512 / 8,
33
+ iterationCount: 10000,
34
+ salt: 'you should override this value with a crypto secure random number',
35
+ hash: 'sha2-512'
36
+ }
37
+ }
38
+
39
+ function validateKeyName (name: string): boolean {
40
+ if (name == null) {
41
+ return false
42
+ }
43
+ if (typeof name !== 'string') {
44
+ return false
45
+ }
46
+ return name === sanitize(name.trim()) && name.length > 0
47
+ }
48
+
49
+ /**
50
+ * Throws an error after a delay
51
+ *
52
+ * This assumes than an error indicates that the keychain is under attack. Delay returning an
53
+ * error to make brute force attacks harder.
54
+ */
55
+ async function randomDelay (): Promise<void> {
56
+ const min = 200
57
+ const max = 1000
58
+ const delay = Math.random() * (max - min) + min
59
+
60
+ await new Promise(resolve => setTimeout(resolve, delay))
61
+ }
62
+
63
+ /**
64
+ * Converts a key name into a datastore name
65
+ */
66
+ function DsName (name: string): Key {
67
+ return new Key(keyPrefix + name)
68
+ }
69
+
70
+ /**
71
+ * Converts a key name into a datastore info name
72
+ */
73
+ function DsInfoName (name: string): Key {
74
+ return new Key(infoPrefix + name)
75
+ }
76
+
77
+ /**
78
+ * Manages the lifecycle of a key. Keys are encrypted at rest using PKCS #8.
79
+ *
80
+ * A key in the store has two entries
81
+ * - '/info/*key-name*', contains the KeyInfo for the key
82
+ * - '/pkcs8/*key-name*', contains the PKCS #8 for the key
83
+ *
84
+ */
85
+ export class DefaultKeychain implements Keychain {
86
+ private readonly components: KeychainComponents
87
+ private readonly init: KeychainInit
88
+ private readonly log: Logger
89
+
90
+ /**
91
+ * Creates a new instance of a key chain
92
+ */
93
+ constructor (components: KeychainComponents, init: KeychainInit) {
94
+ this.components = components
95
+ this.log = components.logger.forComponent('libp2p:keychain')
96
+ this.init = mergeOptions(defaultOptions, init)
97
+
98
+ // Enforce NIST SP 800-132
99
+ if (this.init.pass != null && this.init.pass?.length < 20) {
100
+ throw new Error('pass must be least 20 characters')
101
+ }
102
+ if (this.init.dek?.keyLength != null && this.init.dek.keyLength < NIST.minKeyLength) {
103
+ throw new Error(`dek.keyLength must be least ${NIST.minKeyLength} bytes`)
104
+ }
105
+ if (this.init.dek?.salt?.length != null && this.init.dek.salt.length < NIST.minSaltLength) {
106
+ throw new Error(`dek.saltLength must be least ${NIST.minSaltLength} bytes`)
107
+ }
108
+ if (this.init.dek?.iterationCount != null && this.init.dek.iterationCount < NIST.minIterationCount) {
109
+ throw new Error(`dek.iterationCount must be least ${NIST.minIterationCount}`)
110
+ }
111
+
112
+ const dek = this.init.pass != null && this.init.dek?.salt != null
113
+ ? pbkdf2(
114
+ this.init.pass,
115
+ this.init.dek?.salt,
116
+ this.init.dek?.iterationCount,
117
+ this.init.dek?.keyLength,
118
+ this.init.dek?.hash)
119
+ : ''
120
+
121
+ privates.set(this, { dek })
122
+ }
123
+
124
+ /**
125
+ * Generates the options for a keychain. A random salt is produced.
126
+ *
127
+ * @returns {object}
128
+ */
129
+ static generateOptions (): KeychainInit {
130
+ const options = Object.assign({}, defaultOptions)
131
+ const saltLength = Math.ceil(NIST.minSaltLength / 3) * 3 // no base64 padding
132
+ options.dek.salt = uint8ArrayToString(randomBytes(saltLength), 'base64')
133
+ return options
134
+ }
135
+
136
+ /**
137
+ * Gets an object that can encrypt/decrypt protected data.
138
+ * The default options for a keychain.
139
+ *
140
+ * @returns {object}
141
+ */
142
+ static get options (): typeof defaultOptions {
143
+ return defaultOptions
144
+ }
145
+
146
+ /**
147
+ * Create a new key.
148
+ *
149
+ * @param {string} name - The local key name; cannot already exist.
150
+ * @param {string} type - One of the key types; 'rsa'.
151
+ * @param {number} [size = 2048] - The key size in bits. Used for rsa keys only
152
+ */
153
+ async createKey (name: string, type: KeyType, size = 2048): Promise<KeyInfo> {
154
+ if (!validateKeyName(name) || name === 'self') {
155
+ await randomDelay()
156
+ throw new CodeError('Invalid key name', codes.ERR_INVALID_KEY_NAME)
157
+ }
158
+
159
+ if (typeof type !== 'string') {
160
+ await randomDelay()
161
+ throw new CodeError('Invalid key type', codes.ERR_INVALID_KEY_TYPE)
162
+ }
163
+
164
+ const dsname = DsName(name)
165
+ const exists = await this.components.datastore.has(dsname)
166
+ if (exists) {
167
+ await randomDelay()
168
+ throw new CodeError('Key name already exists', codes.ERR_KEY_ALREADY_EXISTS)
169
+ }
170
+
171
+ switch (type.toLowerCase()) {
172
+ case 'rsa':
173
+ if (!Number.isSafeInteger(size) || size < 2048) {
174
+ await randomDelay()
175
+ throw new CodeError('Invalid RSA key size', codes.ERR_INVALID_KEY_SIZE)
176
+ }
177
+ break
178
+ default:
179
+ break
180
+ }
181
+
182
+ let keyInfo
183
+ try {
184
+ const keypair = await generateKeyPair(type, size)
185
+ const kid = await keypair.id()
186
+ const cached = privates.get(this)
187
+
188
+ if (cached == null) {
189
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
190
+ }
191
+
192
+ const dek = cached.dek
193
+ const pem = await keypair.export(dek)
194
+ keyInfo = {
195
+ name,
196
+ id: kid
197
+ }
198
+ const batch = this.components.datastore.batch()
199
+ batch.put(dsname, uint8ArrayFromString(pem))
200
+ batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
201
+
202
+ await batch.commit()
203
+ } catch (err: any) {
204
+ await randomDelay()
205
+ throw err
206
+ }
207
+
208
+ return keyInfo
209
+ }
210
+
211
+ /**
212
+ * List all the keys.
213
+ *
214
+ * @returns {Promise<KeyInfo[]>}
215
+ */
216
+ async listKeys (): Promise<KeyInfo[]> {
217
+ const query = {
218
+ prefix: infoPrefix
219
+ }
220
+
221
+ const info = []
222
+ for await (const value of this.components.datastore.query(query)) {
223
+ info.push(JSON.parse(uint8ArrayToString(value.value)))
224
+ }
225
+
226
+ return info
227
+ }
228
+
229
+ /**
230
+ * Find a key by it's id
231
+ */
232
+ async findKeyById (id: string): Promise<KeyInfo> {
233
+ try {
234
+ const keys = await this.listKeys()
235
+ const key = keys.find((k) => k.id === id)
236
+
237
+ if (key == null) {
238
+ throw new CodeError(`Key with id '${id}' does not exist.`, codes.ERR_KEY_NOT_FOUND)
239
+ }
240
+
241
+ return key
242
+ } catch (err: any) {
243
+ await randomDelay()
244
+ throw err
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Find a key by it's name.
250
+ *
251
+ * @param {string} name - The local key name.
252
+ * @returns {Promise<KeyInfo>}
253
+ */
254
+ async findKeyByName (name: string): Promise<KeyInfo> {
255
+ if (!validateKeyName(name)) {
256
+ await randomDelay()
257
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
258
+ }
259
+
260
+ const dsname = DsInfoName(name)
261
+ try {
262
+ const res = await this.components.datastore.get(dsname)
263
+ return JSON.parse(uint8ArrayToString(res))
264
+ } catch (err: any) {
265
+ await randomDelay()
266
+ this.log.error(err)
267
+ throw new CodeError(`Key '${name}' does not exist.`, codes.ERR_KEY_NOT_FOUND)
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Remove an existing key.
273
+ *
274
+ * @param {string} name - The local key name; must already exist.
275
+ * @returns {Promise<KeyInfo>}
276
+ */
277
+ async removeKey (name: string): Promise<KeyInfo> {
278
+ if (!validateKeyName(name) || name === 'self') {
279
+ await randomDelay()
280
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
281
+ }
282
+ const dsname = DsName(name)
283
+ const keyInfo = await this.findKeyByName(name)
284
+ const batch = this.components.datastore.batch()
285
+ batch.delete(dsname)
286
+ batch.delete(DsInfoName(name))
287
+ await batch.commit()
288
+ return keyInfo
289
+ }
290
+
291
+ /**
292
+ * Rename a key
293
+ *
294
+ * @param {string} oldName - The old local key name; must already exist.
295
+ * @param {string} newName - The new local key name; must not already exist.
296
+ * @returns {Promise<KeyInfo>}
297
+ */
298
+ async renameKey (oldName: string, newName: string): Promise<KeyInfo> {
299
+ if (!validateKeyName(oldName) || oldName === 'self') {
300
+ await randomDelay()
301
+ throw new CodeError(`Invalid old key name '${oldName}'`, codes.ERR_OLD_KEY_NAME_INVALID)
302
+ }
303
+ if (!validateKeyName(newName) || newName === 'self') {
304
+ await randomDelay()
305
+ throw new CodeError(`Invalid new key name '${newName}'`, codes.ERR_NEW_KEY_NAME_INVALID)
306
+ }
307
+ const oldDsname = DsName(oldName)
308
+ const newDsname = DsName(newName)
309
+ const oldInfoName = DsInfoName(oldName)
310
+ const newInfoName = DsInfoName(newName)
311
+
312
+ const exists = await this.components.datastore.has(newDsname)
313
+ if (exists) {
314
+ await randomDelay()
315
+ throw new CodeError(`Key '${newName}' already exists`, codes.ERR_KEY_ALREADY_EXISTS)
316
+ }
317
+
318
+ try {
319
+ const pem = await this.components.datastore.get(oldDsname)
320
+ const res = await this.components.datastore.get(oldInfoName)
321
+
322
+ const keyInfo = JSON.parse(uint8ArrayToString(res))
323
+ keyInfo.name = newName
324
+ const batch = this.components.datastore.batch()
325
+ batch.put(newDsname, pem)
326
+ batch.put(newInfoName, uint8ArrayFromString(JSON.stringify(keyInfo)))
327
+ batch.delete(oldDsname)
328
+ batch.delete(oldInfoName)
329
+ await batch.commit()
330
+ return keyInfo
331
+ } catch (err: any) {
332
+ await randomDelay()
333
+ throw err
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Export an existing key as a PEM encrypted PKCS #8 string
339
+ */
340
+ async exportKey (name: string, password: string): Promise<string> {
341
+ if (!validateKeyName(name)) {
342
+ await randomDelay()
343
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
344
+ }
345
+ if (password == null) {
346
+ await randomDelay()
347
+ throw new CodeError('Password is required', codes.ERR_PASSWORD_REQUIRED)
348
+ }
349
+
350
+ const dsname = DsName(name)
351
+ try {
352
+ const res = await this.components.datastore.get(dsname)
353
+ const pem = uint8ArrayToString(res)
354
+ const cached = privates.get(this)
355
+
356
+ if (cached == null) {
357
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
358
+ }
359
+
360
+ const dek = cached.dek
361
+ const privateKey = await importKey(pem, dek)
362
+ const keyString = await privateKey.export(password)
363
+
364
+ return keyString
365
+ } catch (err: any) {
366
+ await randomDelay()
367
+ throw err
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Export an existing key as a PeerId
373
+ */
374
+ async exportPeerId (name: string): Promise<PeerId> {
375
+ const password = 'temporary-password'
376
+ const pem = await this.exportKey(name, password)
377
+ const privateKey = await importKey(pem, password)
378
+
379
+ return peerIdFromKeys(privateKey.public.bytes, privateKey.bytes)
380
+ }
381
+
382
+ /**
383
+ * Import a new key from a PEM encoded PKCS #8 string
384
+ *
385
+ * @param {string} name - The local key name; must not already exist.
386
+ * @param {string} pem - The PEM encoded PKCS #8 string
387
+ * @param {string} password - The password.
388
+ * @returns {Promise<KeyInfo>}
389
+ */
390
+ async importKey (name: string, pem: string, password: string): Promise<KeyInfo> {
391
+ if (!validateKeyName(name) || name === 'self') {
392
+ await randomDelay()
393
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
394
+ }
395
+ if (pem == null) {
396
+ await randomDelay()
397
+ throw new CodeError('PEM encoded key is required', codes.ERR_PEM_REQUIRED)
398
+ }
399
+ const dsname = DsName(name)
400
+ const exists = await this.components.datastore.has(dsname)
401
+ if (exists) {
402
+ await randomDelay()
403
+ throw new CodeError(`Key '${name}' already exists`, codes.ERR_KEY_ALREADY_EXISTS)
404
+ }
405
+
406
+ let privateKey
407
+ try {
408
+ privateKey = await importKey(pem, password)
409
+ } catch (err: any) {
410
+ await randomDelay()
411
+ throw new CodeError('Cannot read the key, most likely the password is wrong', codes.ERR_CANNOT_READ_KEY)
412
+ }
413
+
414
+ let kid
415
+ try {
416
+ kid = await privateKey.id()
417
+ const cached = privates.get(this)
418
+
419
+ if (cached == null) {
420
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
421
+ }
422
+
423
+ const dek = cached.dek
424
+ pem = await privateKey.export(dek)
425
+ } catch (err: any) {
426
+ await randomDelay()
427
+ throw err
428
+ }
429
+
430
+ const keyInfo = {
431
+ name,
432
+ id: kid
433
+ }
434
+ const batch = this.components.datastore.batch()
435
+ batch.put(dsname, uint8ArrayFromString(pem))
436
+ batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
437
+ await batch.commit()
438
+
439
+ return keyInfo
440
+ }
441
+
442
+ /**
443
+ * Import a peer key
444
+ */
445
+ async importPeer (name: string, peer: PeerId): Promise<KeyInfo> {
446
+ try {
447
+ if (!validateKeyName(name)) {
448
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
449
+ }
450
+ if (peer == null) {
451
+ throw new CodeError('PeerId is required', codes.ERR_MISSING_PRIVATE_KEY)
452
+ }
453
+ if (peer.privateKey == null) {
454
+ throw new CodeError('PeerId.privKey is required', codes.ERR_MISSING_PRIVATE_KEY)
455
+ }
456
+
457
+ const privateKey = await unmarshalPrivateKey(peer.privateKey)
458
+
459
+ const dsname = DsName(name)
460
+ const exists = await this.components.datastore.has(dsname)
461
+ if (exists) {
462
+ await randomDelay()
463
+ throw new CodeError(`Key '${name}' already exists`, codes.ERR_KEY_ALREADY_EXISTS)
464
+ }
465
+
466
+ const cached = privates.get(this)
467
+
468
+ if (cached == null) {
469
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
470
+ }
471
+
472
+ const dek = cached.dek
473
+ const pem = await privateKey.export(dek)
474
+ const keyInfo: KeyInfo = {
475
+ name,
476
+ id: peer.toString()
477
+ }
478
+ const batch = this.components.datastore.batch()
479
+ batch.put(dsname, uint8ArrayFromString(pem))
480
+ batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
481
+ await batch.commit()
482
+ return keyInfo
483
+ } catch (err: any) {
484
+ await randomDelay()
485
+ throw err
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Gets the private key as PEM encoded PKCS #8 string
491
+ */
492
+ async getPrivateKey (name: string): Promise<string> {
493
+ if (!validateKeyName(name)) {
494
+ await randomDelay()
495
+ throw new CodeError(`Invalid key name '${name}'`, codes.ERR_INVALID_KEY_NAME)
496
+ }
497
+
498
+ try {
499
+ const dsname = DsName(name)
500
+ const res = await this.components.datastore.get(dsname)
501
+ return uint8ArrayToString(res)
502
+ } catch (err: any) {
503
+ await randomDelay()
504
+ this.log.error(err)
505
+ throw new CodeError(`Key '${name}' does not exist.`, codes.ERR_KEY_NOT_FOUND)
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Rotate keychain password and re-encrypt all associated keys
511
+ */
512
+ async rotateKeychainPass (oldPass: string, newPass: string): Promise<void> {
513
+ if (typeof oldPass !== 'string') {
514
+ await randomDelay()
515
+ throw new CodeError(`Invalid old pass type '${typeof oldPass}'`, codes.ERR_INVALID_OLD_PASS_TYPE)
516
+ }
517
+ if (typeof newPass !== 'string') {
518
+ await randomDelay()
519
+ throw new CodeError(`Invalid new pass type '${typeof newPass}'`, codes.ERR_INVALID_NEW_PASS_TYPE)
520
+ }
521
+ if (newPass.length < 20) {
522
+ await randomDelay()
523
+ throw new CodeError(`Invalid pass length ${newPass.length}`, codes.ERR_INVALID_PASS_LENGTH)
524
+ }
525
+ this.log('recreating keychain')
526
+ const cached = privates.get(this)
527
+
528
+ if (cached == null) {
529
+ throw new CodeError('dek missing', codes.ERR_INVALID_PARAMETERS)
530
+ }
531
+
532
+ const oldDek = cached.dek
533
+ this.init.pass = newPass
534
+ const newDek = newPass != null && this.init.dek?.salt != null
535
+ ? pbkdf2(
536
+ newPass,
537
+ this.init.dek.salt,
538
+ this.init.dek?.iterationCount,
539
+ this.init.dek?.keyLength,
540
+ this.init.dek?.hash)
541
+ : ''
542
+ privates.set(this, { dek: newDek })
543
+ const keys = await this.listKeys()
544
+ for (const key of keys) {
545
+ const res = await this.components.datastore.get(DsName(key.name))
546
+ const pem = uint8ArrayToString(res)
547
+ const privateKey = await importKey(pem, oldDek)
548
+ const password = newDek.toString()
549
+ const keyAsPEM = await privateKey.export(password)
550
+
551
+ // Update stored key
552
+ const batch = this.components.datastore.batch()
553
+ const keyInfo = {
554
+ name: key.name,
555
+ id: key.id
556
+ }
557
+ batch.put(DsName(key.name), uint8ArrayFromString(keyAsPEM))
558
+ batch.put(DsInfoName(key.name), uint8ArrayFromString(JSON.stringify(keyInfo)))
559
+ await batch.commit()
560
+ }
561
+ this.log('keychain reconstructed')
562
+ }
563
+ }
@@ -1,10 +0,0 @@
1
- {
2
- "DefaultKeyChain": "https://libp2p.github.io/js-libp2p/classes/_libp2p_keychain.DefaultKeyChain.html",
3
- ".:DefaultKeyChain": "https://libp2p.github.io/js-libp2p/classes/_libp2p_keychain.DefaultKeyChain.html",
4
- "DEKConfig": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_keychain.DEKConfig.html",
5
- ".:DEKConfig": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_keychain.DEKConfig.html",
6
- "KeyChainComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_keychain.KeyChainComponents.html",
7
- ".:KeyChainComponents": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_keychain.KeyChainComponents.html",
8
- "KeyChainInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_keychain.KeyChainInit.html",
9
- ".:KeyChainInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_keychain.KeyChainInit.html"
10
- }