You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cryptpad/www/common/rpc.js

126 lines
3.3 KiB
JavaScript

define([
'/bower_components/tweetnacl/nacl-fast.min.js',
8 years ago
], function () {
var MAX_LAG_BEFORE_TIMEOUT = 30000;
var Nacl = window.nacl;
var uid = function () {
return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))
.toString(32).replace(/\./g, '');
};
8 years ago
var signMsg = function (data, signKey) {
var buffer = Nacl.util.decodeUTF8(JSON.stringify(data));
return Nacl.util.encodeBase64(Nacl.sign.detached(buffer, signKey));
};
8 years ago
/*
types of messages:
pin -> hash
unpin -> hash
getHash -> hash
getTotalSize -> bytes
getFileSize -> bytes
*/
8 years ago
var sendMsg = function (ctx, data, cb) {
var network = ctx.network;
var hkn = network.historyKeeper;
var txid = uid();
ctx.pending[txid] = cb;
8 years ago
return network.sendto(hkn, JSON.stringify([txid, data]));
};
var parse = function (msg) {
try {
return JSON.parse(msg);
} catch (e) {
return null;
}
};
var onMsg = function (ctx, msg) {
var parsed = parse(msg);
if (!parsed) {
8 years ago
return void console.error(new Error('could not parse message: %s', msg));
}
var txid = parsed[0];
var pending = ctx.pending[txid];
8 years ago
if (!(parsed && parsed.slice)) {
return void console.error('MALFORMED_RPC_RESPONSE');
}
var response = parsed.slice(1);
if (typeof(pending) === 'function') {
if (response[0] === 'ERROR') {
return void pending(response[1]);
}
pending(void 0, response);
} else {
console.log("No callback provided");
}
};
var create = function (network, edPrivateKey, edPublicKey) {
8 years ago
var signKey;
try {
8 years ago
signKey = Nacl.util.decodeBase64(edPrivateKey);
if (signKey.length !== 64) {
throw new Error('private key did not match expected length of 64');
}
8 years ago
} catch (err) { throw err; }
8 years ago
var pubBuffer;
try {
pubBuffer = Nacl.util.decodeBase64(edPublicKey);
if (pubBuffer.length !== 32) {
throw new Error('expected public key to be 32 uint');
}
} catch (err) { throw err; }
var ctx = {
seq: new Date().getTime(),
network: network,
timeouts: {}, // timeouts
pending: {}, // callbacks
8 years ago
cookie: null,
};
var send = function (type, msg, cb) {
// construct a signed message...
8 years ago
var data = [type, msg];
var sig = signMsg(data, signKey);
8 years ago
data.unshift(ctx.cookie); //
data.unshift(edPublicKey);
data.unshift(sig);
// [sig, edPublicKey, cookie, type, msg]
return sendMsg(ctx, data, cb);
};
var getCookie = function (cb) {
send('COOKIE', "", function (e, msg) {
console.log('cookie message', e, msg);
cb(e, msg);
});
};
8 years ago
network.on('message', function (msg, sender) {
onMsg(ctx, msg);
});
return {
send: send,
8 years ago
ready: getCookie,
};
};
return { create: create };
});