UNPKG

cobox-config

Version:

load and save a cobox configuration

89 lines (75 loc) 2.5 kB
const yaml = require('js-yaml') const fs = require('fs') const path = require('path') const os = require('os') const mkdirp = require('mkdirp') const crypto = require('cobox-crypto') const constants = require('cobox-constants') const { loadParentKey, saveParentKey } = require('./lib/keys') const sodium = require('sodium-native') const CONFIG_FILE = 'config.yml' module.exports = (storage, opts) => new CoBoxConfig(storage, opts) const KeyHandler = require('./lib/handlers/keys') const MapHandler = require('./lib/handlers/map') const defaultConfig = (options = {}) => ({ options, groups: { byKey: {}, byName: {} }, replicators: { byKey: {}, byName: {} }, devices: { byKey: {}, byName: {} } }) class CoBoxConfig { constructor (storage, opts = {}) { this.root = storage || constants.storage this.storage = path.join(this.root, CONFIG_FILE) this._opts = opts mkdirp.sync(path.join(this.root, 'logs')) var config = Object.assign(defaultConfig()) if (!fs.existsSync(this.storage)) { fs.writeFileSync(this.storage, yaml.safeDump(defaultConfig(), { sortKeys: true })) this._groups = config.groups this._replicators = config.replicators this._devices = config.devices this._options = config.options } else { this.load() } this.deriveKeyPair = (id, context) => { var parentKey = loadParentKey(this.root) || crypto.masterKey() saveParentKey(this.root, parentKey) var keyPair = crypto.keyPair(parentKey, id, context) sodium.sodium_memzero(parentKey) return keyPair } this.groups = KeyHandler(this._groups) this.replicators = KeyHandler(this._replicators) this.devices = KeyHandler(this._devices) this.options = MapHandler(this._options) } save () { try { var config = defaultConfig() config.groups = this._groups config.replicators = this._replicators config.devices = this._devices config.options = this._options fs.writeFileSync(this.storage, yaml.safeDump(config, { sortKeys: true })) return true } catch (err) { console.error(err) return false } } load () { try { const config = yaml.safeLoad(fs.readFileSync(this.storage, 'utf8')) this._groups = config.groups this._replicators = config.replicators this._devices = config.devices this._options = config.options return true } catch (err) { console.error(err) return false } } }