This repository has been archived on 2023-11-14. You can view files and clone it, but cannot push or open issues/pull-requests.
valnet/lib/Identity.js

74 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-11-11 19:38:39 -05:00
const Keyv = require('keyv');
const { KeyvFile } = require('keyv-file');
const { hri } = require('human-readable-ids');
const os = require('os');
const NodeRSA = require('node-rsa');
2020-11-12 11:43:35 -05:00
let log = require('signale').scope('Identity(null)');
2020-11-11 19:38:39 -05:00
module.exports.Identity = class Identity {
kv;
key;
name;
2020-11-13 10:19:44 -05:00
/// ASYNC CONSTRUCTOR
2020-11-11 19:38:39 -05:00
constructor(module, id) {
2020-11-13 10:19:44 -05:00
return new Promise(async (res, rej) => {
2021-04-01 01:04:17 -04:00
const appdata = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Preferences' : process.env.HOME + "/.local/share")
2020-11-13 10:19:44 -05:00
const kv = new Keyv({
store: new KeyvFile({
2021-04-01 01:04:17 -04:00
filename: `${appdata}/valnet/${module}/${id}.json`
2020-11-13 10:19:44 -05:00
})
});
log = log.scope(`Identity(${module}/${id})`);
2020-11-11 19:38:39 -05:00
2020-11-13 10:19:44 -05:00
this.key = await new Promise(async (res) => {
log.info(`Searching for identity`);
if(! await kv.get('private-key')
|| ! await kv.get('public-key')
|| ! await kv.get('name')) {
2020-11-11 19:38:39 -05:00
2020-11-13 10:19:44 -05:00
log.warn(`no keypair found, generating...`);
const name = hri.random();
const key = new NodeRSA({b: 512});
key.generateKeyPair();
await kv.set('name', name);
await kv.set('private-key', key.exportKey('pkcs8-private-pem'));
await kv.set('public-key', key.exportKey('pkcs8-public-pem'));
log.success(`done!`);
}
2020-11-11 19:38:39 -05:00
2020-11-13 10:19:44 -05:00
const identity = new NodeRSA();
identity.importKey(await kv.get('private-key'), 'pkcs8-private-pem');
identity.importKey(await kv.get('public-key'), 'pkcs8-public-pem');
log.info(`Identity imported.`);
2020-11-11 19:38:39 -05:00
2020-11-13 10:19:44 -05:00
this.name = await kv.get('name');
res(identity);
});
2020-11-11 19:38:39 -05:00
2020-11-13 10:19:44 -05:00
res(this);
2020-11-11 19:38:39 -05:00
});
}
2020-11-13 10:19:44 -05:00
get publicKey() {
return this.key.exportKey('pkcs8-public-pem');
}
2020-11-11 19:38:39 -05:00
async name() {
return this.name;
}
2020-11-13 10:19:44 -05:00
async encrypt(...args) {
2020-11-11 19:38:39 -05:00
return this.key.encrypt(...args);
}
2020-11-13 10:19:44 -05:00
async decrypt(...args) {
2020-11-11 19:38:39 -05:00
return this.key.decrypt(...args);
}
toString() {
return `[Identity(${this.name})]`;
}
}