cryptpad/rpc.js

376 lines
9.8 KiB
JavaScript
Raw Normal View History

2017-03-27 16:15:15 +00:00
/* Use Nacl for checking signatures of messages */
var Nacl = require("tweetnacl");
var RPC = module.exports;
2017-04-03 17:24:57 +00:00
var Store = require("./storage/file");
2017-03-15 14:55:25 +00:00
var isValidChannel = function (chan) {
return /^[a-fA-F0-9]/.test(chan);
};
var makeToken = function () {
return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))
.toString(16);
};
var makeCookie = function (token) {
var time = (+new Date());
time -= time % 5000;
2017-03-27 16:15:15 +00:00
return [
time,
2017-03-27 16:15:15 +00:00
process.pid, // jshint ignore:line
token
2017-04-03 17:24:57 +00:00
];
2017-03-27 16:15:15 +00:00
};
var parseCookie = function (cookie) {
if (!(cookie && cookie.split)) { return null; }
var parts = cookie.split('|');
if (parts.length !== 3) { return null; }
2017-03-27 16:15:15 +00:00
var c = {};
c.time = new Date(parts[0]);
2017-04-03 17:24:57 +00:00
c.pid = Number(parts[1]);
c.seq = parts[2];
2017-03-27 16:15:15 +00:00
return c;
};
var addTokenForKey = function (Cookies, publicKey, token) {
if (!Cookies[publicKey]) { throw new Error('undefined user'); }
var user = Cookies[publicKey];
user.tokens.push(token);
user.atime = +new Date();
if (user.tokens.length > 2) { user.tokens.shift(); }
};
var isTooOld = function (time, now) {
return (now - time) > 300000;
};
2017-04-03 17:24:57 +00:00
var isValidCookie = function (Cookies, publicKey, cookie) {
var parsed = parseCookie(cookie);
if (!parsed) { return false; }
2017-04-03 17:24:57 +00:00
var now = +new Date();
if (!parsed.time) { return false; }
if (isTooOld(parsed.time, now)) {
2017-03-27 16:15:15 +00:00
return false;
}
// different process. try harder
if (process.pid !== parsed.pid) { // jshint ignore:line
2017-03-27 16:15:15 +00:00
return false;
}
var user = Cookies[publicKey];
if (!user) { return false; }
var idx = user.tokens.indexOf(parsed.seq);
if (idx === -1) { return false; }
var next;
if (idx > 0) {
// make a new token
addTokenForKey(Cookies, publicKey, makeToken());
}
2017-03-27 16:15:15 +00:00
return true;
};
var checkSignature = function (signedMsg, signature, publicKey) {
if (!(signedMsg && publicKey)) { return false; }
2017-03-20 17:02:11 +00:00
var signedBuffer;
var pubBuffer;
2017-03-27 16:15:15 +00:00
var signatureBuffer;
try {
2017-03-27 16:15:15 +00:00
signedBuffer = Nacl.util.decodeUTF8(signedMsg);
} catch (e) {
2017-03-27 16:15:15 +00:00
console.log('invalid signedBuffer');
console.log(signedMsg);
return null;
}
2017-03-27 16:15:15 +00:00
try {
pubBuffer = Nacl.util.decodeBase64(publicKey);
} catch (e) {
return false;
}
try {
signatureBuffer = Nacl.util.decodeBase64(signature);
} catch (e) {
return false;
}
if (pubBuffer.length !== 32) {
console.log('public key length: ' + pubBuffer.length);
console.log(publicKey);
return false;
}
2017-03-27 16:15:15 +00:00
if (signatureBuffer.length !== 64) {
return false;
}
2017-03-27 16:15:15 +00:00
return Nacl.sign.detached.verify(signedBuffer, signatureBuffer, pubBuffer);
};
2017-04-03 17:24:57 +00:00
var getChannelList = function (store, publicKey, cb) {
// to accumulate pinned channels
var pins = {};
store.getMessages(publicKey, function (msg) {
// handle messages...
var parsed;
try {
parsed = JSON.parse(msg);
switch (parsed[0]) {
case 'PIN':
pins[parsed[1]] = true;
break;
case 'UNPIN':
pins[parsed[1]] = false;
break;
case 'RESET':
Object.keys(pins).forEach(function (pin) {
pins[pin] = false;
});
break;
default:
console.error('invalid message read from store');
}
} catch (e) {
console.log('invalid message read from store');
console.error(e);
}
}, function () {
// no more messages
var pinned = Object.keys(pins).filter(function (pin) {
return pins[pin];
});
cb(pinned);
});
};
2017-04-07 08:09:59 +00:00
var getFileSize = function (store, channel, cb) {
2017-04-07 08:34:03 +00:00
if (!isValidChannel(channel)) { return void cb('INVALID_CHAN'); }
2017-04-07 08:09:59 +00:00
return void store.getChannelSize(channel, function (e, size) {
if (e) { return void cb(e.code); }
cb(void 0, size);
});
};
var getTotalSize = function (pinStore, messageStore, publicKey, cb) {
var bytes = 0;
return void getChannelList(pinStore, publicKey, function (channels) {
if (!channels) { cb('NO_ARRAY'); } // unexpected
var count = channels.length;
if (!count) { cb(void 0, 0); }
channels.forEach(function (channel) {
return messageStore.getChannelSize(channel, function (e, size) {
count--;
if (!e) { bytes += size; }
if (count === 0) { return cb(void 0, bytes); }
});
});
});
};
2017-04-03 17:24:57 +00:00
var hashChannelList = function (A) {
var uniques = [];
A.forEach(function (a) {
if (uniques.indexOf(a) === -1) { uniques.push(a); }
});
uniques.sort();
var hash = Nacl.util.encodeBase64(Nacl.hash(Nacl
.util.decodeUTF8(JSON.stringify(uniques))));
return hash;
};
var getHash = function (store, publicKey, cb) {
getChannelList(store, publicKey, function (channels) {
2017-04-07 08:30:40 +00:00
cb(void 0, hashChannelList(channels));
});
};
var storeMessage = function (store, publicKey, msg, cb) {
store.message(publicKey, JSON.stringify(msg), cb);
};
var pinChannel = function (store, publicKey, channel, cb) {
store.message(publicKey, JSON.stringify(['PIN', channel]),
function (e) {
if (e) { return void cb(e); }
getHash(store, publicKey, function (e, hash) {
cb(e, hash);
});
2017-04-03 17:24:57 +00:00
});
};
2017-04-07 08:30:40 +00:00
var unpinChannel = function (store, publicKey, channel, cb) {
store.message(publicKey, JSON.stringify(['UNPIN', channel]),
function (e) {
if (e) { return void cb(e); }
getHash(store, publicKey, function (e, hash) {
cb(e, hash);
});
});
};
var resetUserPins = function (store, publicKey, channelList, cb) {
// TODO make this atomic
store.message(publicKey, JSON.stringify(['RESET']), cb);
};
var expireSessions = function (Cookies) {
var now = +new Date();
Object.keys(Cookies).forEach(function (key) {
if (isTooOld(Cookies[key].atime, now)) {
delete Cookies[key];
}
});
};
RPC.create = function (config, cb) {
// load pin-store...
console.log('loading rpc module...');
2017-03-27 16:15:15 +00:00
var Cookies = {};
2017-04-03 17:24:57 +00:00
var store;
2017-03-27 16:15:15 +00:00
var addUser = function (key) {
if (Cookies[key]) { return; }
var user = Cookies[key] = {};
user.atime = +new Date();
user.tokens = [
makeToken()
];
};
2017-03-27 16:15:15 +00:00
var rpc = function (ctx, data, respond) {
if (!data.length) {
return void respond("INSUFFICIENT_ARGS");
2017-03-27 16:15:15 +00:00
} else if (data.length !== 1) {
console.log(data.length);
}
2017-03-27 16:15:15 +00:00
var msg = data[0].slice(0);
2017-04-03 17:24:57 +00:00
2017-03-27 16:15:15 +00:00
var signature = msg.shift();
var publicKey = msg.shift();
2017-04-05 15:28:04 +00:00
// make sure a user object is initialized in the cookie jar
addUser(publicKey);
var cookie = msg[0];
if (!isValidCookie(Cookies, publicKey, cookie)) {
2017-03-27 16:15:15 +00:00
// no cookie is fine if the RPC is to get a cookie
if (msg[1] !== 'COOKIE') {
2017-03-27 16:15:15 +00:00
return void respond('NO_COOKIE');
}
}
var serialized = JSON.stringify(msg);
2017-04-05 15:28:04 +00:00
if (!(serialized && typeof(publicKey) === 'string')) {
2017-03-27 16:15:15 +00:00
return void respond('INVALID_MESSAGE_OR_PUBLIC_KEY');
}
2017-04-05 15:28:04 +00:00
2017-03-27 16:15:15 +00:00
if (checkSignature(serialized, signature, publicKey) !== true) {
return void respond("INVALID_SIGNATURE_OR_PUBLIC_KEY");
}
2017-04-05 15:28:04 +00:00
var safeKey = publicKey.replace(/\//g, '-');
/* If you have gotten this far, you have signed the message with the
public key which you provided.
We can safely modify the state for that key
*/
// discard validated cookie from message
msg.shift();
var Respond = function (e, msg) {
var token = Cookies[publicKey].tokens.slice(-1)[0];
var cookie = makeCookie(token).join('|');
respond(e, [cookie].concat(msg||[]));
};
if (typeof(msg) !== 'object' || !msg.length) {
return void Respond('INVALID_MSG');
}
switch (msg[0]) {
2017-03-27 16:15:15 +00:00
case 'COOKIE':
return void Respond(void 0);
case 'ECHO':
return void Respond(void 0, msg);
2017-04-05 15:28:04 +00:00
/* TODO
reset should be atomic in case the operation is aborted */
case 'RESET':
2017-04-05 15:28:04 +00:00
return resetUserPins(store, safeKey, [], function (e) {
return void Respond(e);
2017-04-03 17:24:57 +00:00
});
2017-04-05 15:28:04 +00:00
case 'PIN':
2017-04-07 08:30:40 +00:00
return pinChannel(store, safeKey, msg[1], function (e, hash) {
Respond(e, hash);
2017-04-03 17:24:57 +00:00
});
case 'UNPIN':
2017-04-07 08:30:40 +00:00
return unpinChannel(store, safeKey, msg[1], function (e, hash) {
Respond(e, hash);
2017-04-03 17:24:57 +00:00
});
case 'GET_HASH':
2017-04-07 08:30:40 +00:00
return void getHash(store, safeKey, function (e, hash) {
Respond(e, hash);
2017-04-03 17:24:57 +00:00
});
case 'GET_TOTAL_SIZE':
2017-04-07 08:09:59 +00:00
return getTotalSize(store, ctx.store, safeKey, function (e, size) {
if (e) { return void Respond(e); }
Respond(e, size);
2017-03-15 14:55:25 +00:00
});
2017-04-07 08:09:59 +00:00
case 'GET_FILE_SIZE':
return void getFileSize(ctx.store, msg[1], Respond);
default:
return void Respond('UNSUPPORTED_RPC_CALL', msg);
}
};
2017-04-03 17:24:57 +00:00
Store.create({
filePath: './pins'
}, function (s) {
store = s;
cb(void 0, rpc);
// expire old sessions once per minute
setInterval(function () {
expireSessions(Cookies);
}, 60000);
2017-04-03 17:24:57 +00:00
});
};