work-token
Simple proof of work generation and verification library based on hashcachgen. It works on node.js and in web browsers. The idea is that this can be used as an alternative to throttling on a web API. Instead of throttling, you give each client a challenge, it then performs a computationally hard problem on the challenge to produce a "work token". This can then be sent along with a request to the API. The server is then able to easilly verify that the work has been performed. Someone who wishes to abuse your API by sending large numbers of requests would then need to spend large amounts of time computing the work tokens.
Installation
npm install work-token
Usage
You can load either the synchronous or asynchronous version of this library and it can be used in the browser via browserify. We run tests on sauce labs separately so you can see the browser support for both the synchronous and asynchronous tests.
Sync
'use strict';
var work = require('work-token/sync');
var idgen = require('idgen')
var challenge = idgen();
var workToken = work.generate(challenge, 4);
assert(work.check(challenge, 4, workToken));
Async
Async on the server will spin out a separate worker process for each token you attempt to verify or generate. On the client, it will attempt to use web-workers if the browser supports them, and will fall back to using setTimeout
to break the loop every 15ms and avoid blocking the main thread.
It can be used with either callbacks or promises.
With Callbacks:
'use strict';
var work = require('work-token/async');
var idgen = require('idgen')
var challenge = idgen();
work.generate(challenge, 4, function (err, token) {
if (err) throw err;
return work.check(challenge, 4, workToken, function (err, isValid) {
if (err) throw err;
assert(isValid);
});
});
With Promises:
'use strict';
require('promise/polyfill');
var work = require('work-token/async');
var idgen = require('idgen')
var challenge = idgen();
work.generate(challenge, 4).then(function (token) {
return work.check(challenge, 4, workToken);
}).done(function (isValid) {
assert(isValid);
});
To avoid spinning up and tearing down processes for each request you can instead create a pool on the server. This is not currently implemented on the client.
'use strict';
require('promise/polyfill');
var work = require('work-token/async').pool(5);
var idgen = require('idgen')
var challenge = idgen();
work.generate(challenge, 4).then(function (token) {
return work.check(challenge, 4, workToken);
}).done(function (isValid) {
assert(isValid);
work.dispose();
});
License
MIT