-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathkeys.js
More file actions
101 lines (78 loc) · 1.64 KB
/
keys.js
File metadata and controls
101 lines (78 loc) · 1.64 KB
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
'use strict';
const fs = require('fs');
const crypto = require('crypto');
/*!
* A collection of keys backed by a file.
*/
function Keys(path) {
this.path = path || '.dpd/keys.json';
}
module.exports = Keys;
/*!
* Get a key from the given keys file.
*/
Keys.prototype.get = function (key, fn) {
this.readFile((err, data) => {
fn(err, data[key]);
});
};
/*!
* Generate a key using cryptographically strong pseudo-random data.
*/
Keys.prototype.generate = function () {
return crypto.randomBytes(256).toString('hex');
};
/*!
* Create a new key and save it in the keys file.
*/
Keys.prototype.create = function (fn) {
const key = this.generate();
const keys = this;
this.readFile((err, data) => {
if (err) return fn(err);
data[key] = true;
keys.writeFile(data, (errW) => {
fn(errW, key);
});
});
};
/*!
* Read the contents of the key file as JSON
*/
Keys.prototype.readFile = function (fn) {
fs.readFile(this.path, 'utf-8', (err, data) => {
let jsonData;
let error;
try {
jsonData = (data && JSON.parse(data)) || {};
} catch (ex) {
error = ex;
}
fn(error, jsonData);
});
};
/*!
* Write the contents of the key file as JSON
*/
Keys.prototype.writeFile = function (data, fn) {
let str;
try {
str = JSON.stringify(data);
} catch (e) {
return fn(e);
}
fs.writeFile(this.path, str, fn);
};
/*
* Get the first local key
*/
Keys.prototype.getLocal = function (fn) {
this.readFile((err, data) => {
if (err) return fn(err);
if (data && typeof data === 'object') {
fn(null, Object.keys(data)[0]);
} else {
fn();
}
});
};