All files index.js

89.66% Statements 130/145
83.1% Branches 59/71
93.33% Functions 28/30
93.33% Lines 126/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3211x     1x   1x 1x   1x 1x   1x 1x 1x   1x 1x   1x 1x   1x   1x   1x 1x         1x       1x       1x           3x 3x   3x 3x 3x 3x 3x     3x           3x 3x       1x 1x         3x 3x 3x 3x                   3x 3x 3x         7x   7x     7x 1x       6x 6x 6x         3x 3x       3x 3x 3x       2x 2x       2x 2x       1x 1x 1x 1x 1x   1x           6x 6x               1x   6x 6x 6x 6x 6x 6x 6x 6x       7x 7x   7x       7x   7x 7x   7x   7x     16x                 16x   12x   4x                 7x 1x   1x 1x       7x     7x   6x 6x       7x 8x 8x 8x 8x 2x 2x     6x           7x 7x   7x   7x   4x 4x     3x 3x       3x         3x 3x     4x   4x 4x 4x       3x                       10x 7x     2x   5x     5x 5x             5x               15x         12x               1x  
const path = require('path')
 
// This is a dirty hack for browserify to work. 😅
Iif (!path.posix) path.posix = path
 
const Corestore = require('corestore')
const SwarmNetworker = require('@corestore/networker')
 
const Multifeed = require('hypermultifeed')
const MultifeedNetworker = require('hypermultifeed/networker')
 
const kappa = require('kappa-core')
const list = require('@DougAnderson444/kappa-view-list')
const memdb = require('level-mem')
 
const RAM = require('random-access-memory')
const RAI = require('@DougAnderson444/random-access-idb')
 
const hcrypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
 
const EventEmitter = require('events')
 
const utils = require('./utils.js')
 
const DEFAULT_APPLICATION_NAME = 'hypnsapplication'
const DEFAULT_SWARM_OPTS = {
  extensions: [],
  preferredPort: 42666
}
 
const isBrowser = process.title === 'browser'
 
// workaround until RAA / random-access-web is fixed
function getNewStorage (name) {
  Iif (isBrowser) {
    // const name = Math.random().toString()
    return RAI(name)
  } else {
    return name // RAA(name)
  }
}
 
class HyPNS {
  constructor (opts = {}) {
    this.applicationName = opts.applicationName || DEFAULT_APPLICATION_NAME
    this._storage =
      opts.persist === false ? RAM : getNewStorage(this.applicationName)
    this.store = opts.corestore || new Corestore(this._storage, opts.corestoreOpts)
    this.instances = new Map()
    this.swarmOpts = opts.swarmOpts
    this.opts = { staticNoiseKey: opts.staticNoiseKey || false }
    this.initialized = false
 
    // handle shutdown gracefully
    const closeHandler = async () => {
      console.log('Shutting down...')
      await this.close()
      process.exit()
    }
 
    process.on('SIGINT', closeHandler)
    process.on('SIGTERM', closeHandler)
  }
 
  get corestore () {
    return new Promise(resolve => {
      this.store.ready().then(resolve(this.store))
    })
  }
 
  async init () {
    Iif (this.initialized) return
    await this.store.ready()
    const swarmOpts = this.swarmOpts || {}
    Iif (this.opts.staticNoiseKey) {
      // Optionally Set up noiseKey to persist peer identity, just like in mauve's hyper-sdk
      const noiseSeed = this.store.inner._deriveSecret(this.applicationName, 'replication-keypair')
      const keyPair = {
        publicKey: Buffer.alloc(sodium.crypto_scalarmult_BYTES),
        secretKey: Buffer.alloc(sodium.crypto_scalarmult_SCALARBYTES)
      }
      sodium.crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, noiseSeed)
      Object.assign(swarmOpts, { keyPair }, DEFAULT_SWARM_OPTS)
    }
    this.swarmNetworker = new SwarmNetworker(this.store, swarmOpts)
    this.swarmNetworker.listen()
    this.initialized = true
  }
 
  // open a new instance on this hypns node
  async open (opts) {
    if (!this.swarmNetworker) await this.init()
 
    if (!this.network) this.network = new MultifeedNetworker(this.swarmNetworker)
 
    // return if exists already on this node
    if (opts && opts.keypair && opts.keypair.publicKey && this.instances.has(opts.keypair.publicKey)) {
      return this.instances.get(opts.keypair.publicKey)
    }
 
    // if doesnt exist, return a new instance
    const instance = new HyPNSInstance({ ...opts, ...this })
    this.instances.set(instance.publicKey, instance)
    return this.instances.get(instance.publicKey)
  }
 
  async close () {
    // TODO: Close all instances too?
    this.store.close()
    Eif (this.swarmNetworker) await this.swarmNetworker.close() // Shut down the swarm networker.
  }
 
  async getDeviceSeed (nameSpace = 'device-seed') {
    await this.store.ready()
    const noiseSeed = this.store.inner._deriveSecret(this.applicationName, nameSpace)
    return noiseSeed
  }
 
  async getKeypair (seed) {
    seed = seed || await this.getDeviceSeed()
    const keyPair = {
      publicKey: Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES),
      secretKey: Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES)
    }
    sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
    return keyPair
  }
 
  async deriveKeypair (context, subkeyNumber, origSeed) {
    origSeed = origSeed || await this.getDeviceSeed()
    const newSeed = Buffer.alloc(sodium.crypto_sign_SEEDBYTES)
    const ctx = Buffer.alloc(sodium.crypto_kdf_CONTEXTBYTES)
    ctx.write(context)
    sodium.crypto_kdf_derive_from_key(newSeed, subkeyNumber, ctx, origSeed)
 
    return this.getKeypair(newSeed)
  }
}
 
class HyPNSInstance extends EventEmitter {
  constructor (opts = {}) {
    super()
    if (
      !opts.keypair ||
      !opts.keypair.publicKey ||
      !opts.keypair.publicKey === null ||
      Buffer.byteLength(opts.keypair.publicKey, 'hex') !==
      sodium.crypto_sign_PUBLICKEYBYTES
    ) {
      // make new keypair for them
      opts.keypair = hcrypto.keyPair()
    }
    this._keypair = opts.keypair // can be hex or buffer
    this.key = this._keypair.publicKey
    this.store = opts.temp ? new Corestore(RAM, opts.corestoreOpts) : opts.store
    this.network = opts.network
    this.latest = null
    this.writable = false
    this.publish = null
    this.setMaxListeners(0)
  }
 
  async ready () {
    return new Promise((resolve, reject) => {
      const self = this
 
      this.multi = new Multifeed(this.store, {
        rootKey: this._keypair.publicKey,
        valueEncoding: 'json'
      })
      this.network.swarm(this.multi)
 
      this.multi.ready(async (err) => {
        Iif (err) throw Error('Multifeed not ready')
 
        this.core = kappa(this.store, { multifeed: this.multi }) // store not used since we pass in a multifeed
 
        const timestampView = list(memdb(), (msg, next) => {
          // only index those msg with valid signature
          const valid =
            msg.value &&
            msg.value.payload &&
            msg.value.timestamp &&
            typeof msg.value.timestamp === 'string' &&
            this.verify(
              Buffer.from(utils.hashIt(JSON.stringify(msg.value.payload) + '.' + msg.value.timestamp), 'utf8'),
              Buffer.from(msg.value.signature, 'hex')
            )
 
          if (valid) {
            // sort on the 'timestamp' field
            next(null, [msg.value.timestamp])
          } else {
            next()
          }
        })
 
        /**
         * If there are pre-exisitng hypercore feeds in storage,
         * then wait for that feed to be ready so it can be indexed
         * by the kappa view
         */
        if (this.core.feeds().length > 0) {
          await new Promise((resolve, reject) => {
            // TODO: multiple pre-existing feeds, foreach
            this.core.feeds()[0].ready(() => {
              resolve()
            })
          })
        }
        this.core.use('pointer', timestampView)
 
        // perm listener
        this.core.api.pointer.tail(1, (msgs) => {
          // console.log('tail updated', msgs[0].value)
          this.latest = msgs[0].value.payload
          this.emit('update', msgs[0].value.payload)
        })
 
        // initial read, if pre-existing tail value
        this.readLatest = async (limit = 1) => {
          return new Promise((resolve, reject) => {
            this.core.api.pointer.read({ limit, reverse: true }, (err, msgs) => {
              Iif (err) console.error(err)
              if (msgs.length > 0) {
                this.latest = msgs[0].value.payload
                resolve(msgs)
              } else {
                // console.log('no tail msgs, resolve false')
                resolve(false)
              }
            })
          })
        }
 
        this.core.ready((err) => {
          Iif (err) throw Error('Core not ready')
 
          this.readLatest()
 
          if (this.writeEnabled()) {
            // writer
            this.core.writer('kappa-local', (err, feed) => {
              Iif (err) reject(err)
 
              function pub (payload) {
                const timestamp = new Date().toISOString()
                const signature = hcrypto.sign(
                  Buffer.from(utils.hashIt(JSON.stringify(payload) + '.' + timestamp), 'utf8'),
                  Buffer.from(self._keypair.secretKey, 'hex') // has to be self._ so that .bind doesn't replace it with feed
                )
                const objPub = {
                  payload,
                  signature: signature.toString('hex'),
                  timestamp
                }
                this.append(objPub) // this gets bound to the object's kappa-local feed above
                return objPub
              }
 
              this.publish = pub.bind(feed) // bind feed to this in pub()
 
              feed.ready(() => {
                this.writable = true
                resolve(this)
              })
            })
          } else {
            resolve(this)
          }
        })
      })
    })
  }
 
  async close () {
    this.multi.close() // closes individual multifeed
  }
 
  writeEnabled () {
    if (!this._keypair.secretKey) return false
    if (
      Buffer.byteLength(this._keypair.secretKey, 'hex') !==
      sodium.crypto_sign_SECRETKEYBYTES
    ) { return false }
 
    const message = Buffer.from('any msg will do', 'utf8')
 
    // sign something with this secretKey
    const signature = Buffer.allocUnsafe(sodium.crypto_sign_BYTES)
    sodium.crypto_sign_detached(
      signature,
      message,
      Buffer.from(this._keypair.secretKey, 'hex')
    )
 
    // verify the signature matches the given public key
    return sodium.crypto_sign_verify_detached(
      signature,
      message,
      Buffer.from(this._keypair.publicKey, 'hex')
    )
  }
 
  get publicKey () {
    return this._keypair.publicKey.toString('hex')
  }
 
  verify (message, signature) {
    // verify(message, signature, publicKey) // verify the signature of this value matches the public key under which it was published
    return hcrypto.verify(
      message,
      signature,
      Buffer.from(this._keypair.publicKey, 'hex')
    )
  }
}
 
module.exports = HyPNS