/bullet-catcher

Restrict put on gun server

Primary LanguageJavaScriptMIT LicenseMIT

Build Status js-standard-style

bullet-catcher

Restrict put on a gun server

This module will listen to in and run your supplied validation function against all put messages.

Usage

Install bullet-catcher from npm

$ npm i bullet-catcher

Require bullet-catcher in your gun server

const Gun = require('gun')
// MUST be required after Gun to work
require('bullet-catcher')

// This is an example validation function
function hasValidToken (msg) {
  return msg && msg && msg.headers && msg.headers.token && msg.headers.token === 'thisIsTheTokenForReals'
}

const server = require('http').createServer(Gun.serve(__dirname));

// Pass the validation function as isValid
const gun = Gun({
  file: 'data.json',
  web: server,
  isValid: hasValidToken
})

// Sync everything
gun.on('out', {get: {'#': {'*': ''}}})

server.listen(8000)

On your client add a listener for outgoing messages and enrich them with whatever you want to validate for

Gun.on('opt', function (ctx) {
  if (ctx.once) {
    return
  }
  ctx.on('out', function (msg) {
    var to = this.to
    // Adds headers for put
    msg.headers = {
      token: 'thisIsTheTokenForReals'
    }
    to.next(msg) // pass to next middleware
  })
})

If isValid returns an Error, that error will be added to the gun context.

function hasValidToken(msg) {
  if (msg.headers.token) {
    if (msg.headers.token.isExpired) {
      return new Error('Invalid token')
    }

    return true
  }

  return false
}
// `err` in the .put callback is now "Invalid token"

Related

License

MIT