HAPPN-3 released!
happn version 3 has been released, the repo is here - this version of happn has a bunch of maintainability updates whereby the code has been better structured. The intra-process client is now using the same code as the websockets one, now just spoofs the primus spark. There is also now notably a protocol abstraction layer, so we can now use different protocols to interact with the happn database and subscriptions, such as an MQTT plugin etc.
Introduction
Happn is a mini database combined with pub/sub, the system stores json objects on paths. Paths can be queried using wildcard syntax. The happn client can run in the browser or in a node process. Happn clients can subscribe to events on paths, events happn when data is changed by a client on a path, either by a set or a remove operation.
Happn stores its data in a collection called 'happn' by default on your mongodb/nedb. The happn system is actually built to be a module, this is because the idea is that you will be able to initialize a server in your own code, and possibly attach your own plugins to various system events.
A paid for alternative to happn would be firebase
Technologies used: Happn uses Primus to power websockets for its pub/sub framework and mongo or nedb depending on the mode it is running in as its data store, the API uses connect. nedb as the embedded database, although we have forked it happn's purposes here
Getting started
npm install happn
You need NodeJS and NPM of course, you also need to know how node works (as my setup instructions are pretty minimal) To run the tests, clone the repo, npm install then npm test:
git clone https://github.com/happner/happn.gitnpm installnpm test
But if you want to run your own service do the following: Create a directory you want to run your happn in, create a node application in it - with some kind of main.js and a package.json
In node_modules/happn/test in your folder, the e2e_test.js script demonstrates the server and client interactions shown in the following code snippets
starting service:
The service runs on port 55000 by default - the following code snippet demonstrates how to instantiate a server.
var happn = var happnInstance; //this will be your server instance //we are using a compact default config here, port defaults to 55000 happnservice;
In your console, go to your application folder and runnode mainyour server should start up and be listening on your port of choice.
Connecting to Happn
Using node:
var happn = ;var my_client_instance; //this will be your client instance happnclient;
To use the browser client, make sure the server is running, and reference the client javascript with the url pointing to the running server instances port and ip address like so:
SET
Puts the json in the branch e2e_test1/testsubscribe/data, creates the branch if it does not exist
//the noPublish parameter means this data change wont be published to other subscribers, it is false by default//there are a bunch other parameters - like noStore (the json isnt persisted, but the message is published) my_client_instance;
NB - by setting the option merge:true, the data at the end of the path is not overwritten by your json, it is rather merged with the data in your json, overwriting the fields you specify in your set data, but leaving the fields that are already at that branch.
SET SIBLING
sets your data to a unique path starting with the path you passed in as a parameter, suffixed with a random short id
my_client_instance
GET
Gets the data living at the specified branch
my_client_instance
You can also use wildcards, gets all items with the path starting e2e_test1/testsubscribe/data
my_client_instance
You can also just get paths, without data
my_client_instance
SEARCH
You can pass mongo style search parameters to look for data sets within specific key ranges
var options = fields: "name": 1 sort: "name": 1 limit: 1 var criteria = $or: "region": $in: 'North' 'South' 'East' 'West' "town": $in: 'North.Cape Town' 'South.East London' "surname": $in: "Bishop" "Emslie" publisherclient;
DELETE
deletes the data living at the specified branch
my_client_instance
EVENTS
you can listen to any SET & REMOVE events happening in your data - you can specifiy a path you want to listen on or you can listen to all SET and DELETE events using a catch-all listener
Specific listener:
my_client_instance;
Catch all listener:
my_client_instance;
EVENT DATA
- you can grab the data you are listening for immediately either by causing the events to be emitted immediately on successful subscription or you can have the data returned as part of the subscription callback using the initialCallback and initialEmit options respectively*
//get the data back as part of the subscription callbacklistenerclient;
//get the data emitted back immediately listenerclient;
UNSUBSCRIBING FROM EVENTS
//use the .off method to unsubscribe from a specific event (the handle is returned by the .on callback) or the .offPath method to unsubscribe from all listeners on a path:
var currentListenerId; var onRan = false; var pathOnRan = false; listenerclient;
TAGGING
You can do a set command and specify that you want to tag the data at the path. Tagging will take a snapshot of the data as it currently stands, and will save the snapshot to a new path in /_TAGS
my_client_instance;my_client_instance;
MERGING
you can do a set command and specify that you want to merge the json you are pushing with the existing dataset, this means any existing values that are not in the set json but exist in the database are persisted
my_client_instance;
SECURITY SERVER
happn server instances can be secured with user and group authentication, a default user and group called _ADMIN is created per happn instance, the admin password is 'happn' but is configurable (MAKE SURE PRODUCTION INSTANCES DO NOT RUN OFF THE DEFAULT PASSWORD)
var happn = var happnInstance; //this will be your server instance happnservice;
at the moment, adding users, groups and permissions can only be done by directly accessing the security service, to see how this is done - please look at the functional test for security
SECURITY CLIENT
the client needs to be instantiated with user credentials and with the secure option set to true to connect to a secure server
//logging in with the _ADMIN user var happn = ;happnclient
SECURITY PROFILES
profiles can be configured to fit different session types, profiles are ordered sets of rules that match incoming sessions with specific policies, the first matching rule in the set is selected when a session is profiled, so the order they are configured in the array is important
//there are 2 default profiles that exist in secure systems - here is an example configuration //showing how profiles can be configured for a service: var serviceConfig = services: data: security: config: sessionTokenSecret:"TESTTOKENSECRET" keyPair: privateKey: 'Kd9FQzddR7G6S9nJ/BK8vLF83AzOphW2lqDOQ/LjU4M=' publicKey: 'AlHCtJlFthb359xOxR5kiBLJpfoC2ZLPLWYHN3+hdzf2' profiles: //profiles are in an array, in descending order of priority, so if you fit more than one profile, the top profile is chosen name:"web-session" session: $and: user:username:$eq:'WEB_SESSION' type:$eq:0 policy: ttl: "4 seconds"//4 seconds = 4000ms, 4 days = 1000 * 60 * 60 * 24 * 4, allow for hours/minutes inactivity_threshold:2000//this is costly, as we need to store state on the server side name:"rest-device" session: $and: //filter by the security properties of the session - check if this session user belongs to a specific group user:groups: "REST_DEVICES" : $exists: true type:$eq:0 //token stateless policy: ttl: 2000//stale after 2 seconds name:"trusted-device" session: $and: //filter by the security properties of the session, so user, groups and permissions user:groups: "TRUSTED_DEVICES" : $exists: true type:$eq:1 //stateful connected device policy: ttl: 2000//stale after 2 seconds permissions://permissions that the holder of this token is limited, regardless of the underlying user '/TRUSTED_DEVICES/*':actions: '*' name:"specific-device" session:$and: //instance based mapping, so what kind of session is this? type:$in:01 //any type of session ip_address:$eq:'127.0.0.1' policy: ttl: Infinity//this device has this access no matter what inactivity_threshold:Infinity permissions://this device has read-only access to a specific item '/SPECIFIC_DEVICE/*':actions: 'get''on' name:"non-reusable" session:$and: //instance based mapping, so what kind of session is this? user:groups: "LIMITED_REUSE" : $exists: true type:$in:01 //stateless or stateful policy: usage_limit:2//you can only use this session call twice name:"default-stateful"// this is the default underlying profile for stateful sessions session: $and:type:$eq:1 policy: ttl: Infinity inactivity_threshold:Infinity name:"default-stateless"// this is the default underlying profile for ws sessions session: $and:type:$eq:0 policy: ttl: 60000 * 10//session goes stale after 10 minutes inactivity_threshold:Infinity ;
the test that clearly demonstrates profiles can be found here
the default policies look like this:
//stateful - so ws sessions: name:"default-stateful"// this is the default underlying profile for stateful sessions session: $and:type:$eq:1 policy: ttl: 0 //never goes stale inactivity_threshold:Infinity //stateless - so token based http requests (REST) name:"default-stateless"// this is the default underlying profile for stateless sessions (REST) session: $and:type:$eq:0 policy: ttl: 0 //never goes stale inactivity_threshold:Infinity
NB NB - if no matching profile is found for an incoming session, one of the above is selected based on whether the session is stateful or stateless, there is no ttl or inactivity timeout on both policies - this means that tokens can be reused forever (unless the user in the token is deleted) rather push to default polcies to your policy list which would sit above these less secure ones, with a ttl and possibly inactivity timeout
WEB PATH LEVEL SECURITY
the http/s server that happn uses can also have custom routes associated with it, when the service is run in secure mode - only people who belong to groups that are granted @HTTP permissions that match wildcard patterns for the request path can access resources on the paths, here is how we grant permissions to paths:
var happn = var happnInstance; //this will be your server instance happnservice;
logging in with a secure client gives us access to a token that can be used, either by embedding the token in a cookie called happn_token or a query string parameter called happn_token, if the login has happened on the browser, the happn_token is autmatically set by default
//logging in with the _ADMIN user, who has permission to all web routes var happn = ;happnclient;
HTTPS SERVER
happn can also run in https mode, the config has a section called transport
//cert and key defined in config var config = transport: mode:'https' cert: '-----BEGIN CERTIFICATE-----\n[CERT ETC...]\n-----END CERTIFICATE-----' key: '-----BEGIN RSA PRIVATE KEY-----\n[KEY ETC...]\n-----END RSA PRIVATE KEY-----' // or cert and key file paths defined in config// IF BOTH OF THESE FILES DONT EXIST, THEY ARE AUTOMATICALLY CREATED AS SELF SIGNED var config = transport: mode:'https' certPath:'home/my_cert.pem' keyPath:'home/my_key.rsa' // or have the system create a cert and key for you, in the home directory of the user that started the happn process - called .happn-https-cert and .happn-https-key var config = transport: mode:'https' var happn = var service = happnservice;var happnInstance; //this will be your server instance //create the service here - now in https mode - running over the default port 55000 service
HTTPS CLIENT
NB - the client must now be initialized with a protocol of https, and if it is the node based client and the cert and key file was self signed, the allowSelfSignedCerts option must be set to true
var happn = ; happnclient
PAYLOAD ENCRYPTION
if the server is running in secure mode, it can also be configured to encrypt payloads between it and socket clients, this means that the client must include a keypair as part of its credentials on logging in, to see payload encryption in action plase go to the following test
PUBSUB MIDDLEWARE
incoming and outgoing packets delivery can be intercepted on the server side, this is how payload encryption works, to add a custom middleware you need to add it to the pubsub service's configuration, a middleware must adhere to a specific interface, as demonstrated below:
var testMiddleware = incomingCount:0 outgoingCount:0 { //modify incoming packet here packetmodified = true; thisincomingCount++; ; } { //modify outgoing packet here packetmodified = true; thisoutgoingCount++; ; }; var happn_service = happnservice;var test_client = happnclient; var testConfig = secure: true port:44445 services: pubsub: config: transformMiddleware:instance:testMiddleware//middelware added in the order it is required to run in // either as an instance or as a path {path:'my-middleware-module'} // path style middlewares are instantiated using require and new ; service;
TESTING WITH KARMA
testing payload encryption on the browser: gulp --gulpfile test/test-browser/gulp-01.js
OTHER PLACES WHERE HAPPN IS USED:
HAPPNER - an experimental application engine that uses happn for its nervous system, see: www.github.com/happner/happner