Compare commits

...

4 commits
main ... api

Author SHA1 Message Date
yflory
1af7d0e15a Override vurnerable dependencies in package.json 2023-05-17 16:27:02 +02:00
yflory
7a35f0cb94 Add NodeJS login and register script 2023-05-11 17:18:16 +02:00
yflory
89fce28890 Update CryptPad code to match updated dependencies 2023-05-10 18:17:22 +02:00
yflory
11676ce3e4 Make CryptPad libraries NodeJS compatible 2023-05-10 18:15:51 +02:00
13 changed files with 1579 additions and 902 deletions

View file

@ -1,25 +1,20 @@
define([ define([
'jquery', 'jquery',
'chainpad-listmap', '/api/config',
'/bower_components/chainpad-crypto/crypto.js',
'/common/common-util.js',
'/common/outer/network-config.js', '/common/outer/network-config.js',
'/common/common-credential.js', '/common/common-credential.js',
'/bower_components/chainpad/chainpad.dist.js',
'/common/common-realtime.js', '/common/common-realtime.js',
'/common/common-constants.js', '/common/common-constants.js',
'/common/common-interface.js', '/common/common-interface.js',
'/common/common-feedback.js',
'/common/outer/local-store.js', '/common/outer/local-store.js',
'/customize/messages.js', '/customize/messages.js',
'/bower_components/nthen/index.js',
'/common/outer/login-block.js', '/common/outer/login-block.js',
'/common/common-hash.js', '/common/common-hash.js',
'/common/login.js',
'/bower_components/tweetnacl/nacl-fast.min.js',
'/bower_components/scrypt-async/scrypt-async.min.js', // better load speed '/bower_components/scrypt-async/scrypt-async.min.js', // better load speed
], function ($, Listmap, Crypto, Util, NetConfig, Cred, ChainPad, Realtime, Constants, UI, ], function ($, ApiConfig, NetConfig, Cred, Realtime, Constants, UI,
Feedback, LocalStore, Messages, nThen, Block, Hash) { LocalStore, Messages, Block, Hash, Login) {
var Exports = { var Exports = {
Cred: Cred, Cred: Cred,
Block: Block, Block: Block,
@ -28,8 +23,6 @@ define([
requiredBytes: 192, requiredBytes: 192,
}; };
var Nacl = window.nacl;
var redirectTo = '/drive/'; var redirectTo = '/drive/';
var setRedirectTo = function () { var setRedirectTo = function () {
var parsed = Hash.parsePadUrl(window.location.href); var parsed = Hash.parsePadUrl(window.location.href);
@ -42,402 +35,16 @@ define([
setRedirectTo(); setRedirectTo();
} }
var allocateBytes = Exports.allocateBytes = function (bytes) { var setMergeAnonDrive = function () { Exports.mergeAnonDrive = 1; };
var dispense = Cred.dispenser(bytes);
var opt = {}; var login = Login({
// dispense 18 bytes of entropy for your encryption key
var encryptionSeed = dispense(18);
// 16 bytes for a deterministic channel key
var channelSeed = dispense(16);
// 32 bytes for a curve key
var curveSeed = dispense(32);
var curvePair = Nacl.box.keyPair.fromSecretKey(new Uint8Array(curveSeed));
opt.curvePrivate = Nacl.util.encodeBase64(curvePair.secretKey);
opt.curvePublic = Nacl.util.encodeBase64(curvePair.publicKey);
// 32 more for a signing key
var edSeed = opt.edSeed = dispense(32);
// 64 more bytes to seed an additional signing key
var blockKeys = opt.blockKeys = Block.genkeys(new Uint8Array(dispense(64)));
opt.blockHash = Block.getBlockHash(blockKeys);
// derive a private key from the ed seed
var signingKeypair = Nacl.sign.keyPair.fromSeed(new Uint8Array(edSeed));
opt.edPrivate = Nacl.util.encodeBase64(signingKeypair.secretKey);
opt.edPublic = Nacl.util.encodeBase64(signingKeypair.publicKey);
var keys = opt.keys = Crypto.createEditCryptor(null, encryptionSeed);
// 24 bytes of base64
keys.editKeyStr = keys.editKeyStr.replace(/\//g, '-');
// 32 bytes of hex
var channelHex = opt.channelHex = Util.uint8ArrayToHex(channelSeed);
// should never happen
if (channelHex.length !== 32) { throw new Error('invalid channel id'); }
var channel64 = Util.hexToBase64(channelHex);
// we still generate a v1 hash because this function needs to deterministically
// derive the same values as it always has. New accounts will generate their own
// userHash values
opt.userHash = '/1/edit/' + [channel64, opt.keys.editKeyStr].join('/') + '/';
return opt;
};
var loginOptionsFromBlock = Exports.loginOptionsFromBlock = function (blockInfo) {
var opt = {};
var parsed = Hash.getSecrets('pad', blockInfo.User_hash);
opt.channelHex = parsed.channel;
opt.keys = parsed.keys;
opt.edPublic = blockInfo.edPublic;
opt.User_name = blockInfo.User_name;
return opt;
};
var loadUserObject = Exports.loadUserObject = function (opt, cb) {
var config = {
websocketURL: NetConfig.getWebsocketURL(), websocketURL: NetConfig.getWebsocketURL(),
channel: opt.channelHex, fileHost: ApiConfig.fileHost || window.location.origin,
data: {}, setMergeAnonDrive: setMergeAnonDrive
validateKey: opt.keys.validateKey, // derived validation key
crypto: Crypto.createEncryptor(opt.keys),
logLevel: 1,
classic: true,
ChainPad: ChainPad,
owners: [opt.edPublic]
};
var rt = opt.rt = Listmap.create(config);
rt.proxy
.on('ready', function () {
setTimeout(function () { cb(void 0, rt); });
})
.on('disconnect', function (info) {
cb('E_DISCONNECT', info);
}); });
}; Exports.allocateBytes = login.allocateBytes;
Exports.loginOrRegister = login.loginOrRegister;
var isProxyEmpty = function (proxy) {
var l = Object.keys(proxy).length;
return l === 0 || (l === 2 && proxy._events && proxy.on);
};
var setMergeAnonDrive = function () {
Exports.mergeAnonDrive = 1;
};
Exports.loginOrRegister = function (uname, passwd, isRegister, shouldImport, cb) {
if (typeof(cb) !== 'function') { return; }
// Usernames are all lowercase. No going back on this one
uname = uname.toLowerCase();
// validate inputs
if (!Cred.isValidUsername(uname)) { return void cb('INVAL_USER'); }
if (!Cred.isValidPassword(passwd)) { return void cb('INVAL_PASS'); }
if (isRegister && !Cred.isLongEnoughPassword(passwd)) {
return void cb('PASS_TOO_SHORT');
}
// results...
var res = {
register: isRegister,
};
var RT, blockKeys, blockHash, blockUrl, Pinpad, rpc, userHash;
nThen(function (waitFor) {
// derive a predefined number of bytes from the user's inputs,
// and allocate them in a deterministic fashion
Cred.deriveFromPassphrase(uname, passwd, Exports.requiredBytes, waitFor(function (bytes) {
res.opt = allocateBytes(bytes);
blockHash = res.opt.blockHash;
blockKeys = res.opt.blockKeys;
}));
}).nThen(function (waitFor) {
// the allocated bytes can be used either in a legacy fashion,
// or in such a way that a previously unused byte range determines
// the location of a layer of indirection which points users to
// an encrypted block, from which they can recover the location of
// the rest of their data
// determine where a block for your set of keys would be stored
blockUrl = Block.getBlockUrl(res.opt.blockKeys);
// Check whether there is a block at that location
Util.fetch(blockUrl, waitFor(function (err, block) {
// if users try to log in or register, we must check
// whether there is a block.
// the block is only useful if it can be decrypted, though
if (err) {
console.log("no block found");
return;
}
var decryptedBlock = Block.decrypt(block, blockKeys);
if (!decryptedBlock) {
console.error("Found a login block but failed to decrypt");
return;
}
//console.error(decryptedBlock);
res.blockInfo = decryptedBlock;
}));
}).nThen(function (waitFor) {
// we assume that if there is a block, it was created in a valid manner
// so, just proceed to the next block which handles that stuff
if (res.blockInfo) { return; }
var opt = res.opt;
// load the user's object using the legacy credentials
loadUserObject(opt, waitFor(function (err, rt) {
if (err) {
waitFor.abort();
return void cb(err);
}
// if a proxy is marked as deprecated, it is because someone had a non-owned drive
// but changed their password, and couldn't delete their old data.
// if they are here, they have entered their old credentials, so we should not
// allow them to proceed. In time, their old drive should get deleted, since
// it will should be pinned by anyone's drive.
if (rt.proxy[Constants.deprecatedKey]) {
waitFor.abort();
return void cb('NO_SUCH_USER', res);
}
if (isRegister && isProxyEmpty(rt.proxy)) {
// If they are trying to register,
// and the proxy is empty, then there is no 'legacy user' either
// so we should just shut down this session and disconnect.
//rt.network.disconnect();
return; // proceed to the next async block
}
// they tried to just log in but there's no such user
// and since we're here at all there is no modern-block
if (!isRegister && isProxyEmpty(rt.proxy)) {
//rt.network.disconnect(); // clean up after yourself
waitFor.abort();
return void cb('NO_SUCH_USER', res);
}
// they tried to register, but those exact credentials exist
if (isRegister && !isProxyEmpty(rt.proxy)) {
//rt.network.disconnect();
waitFor.abort();
Feedback.send('LOGIN', true);
return void cb('ALREADY_REGISTERED', res);
}
// if you are here, then there is no block, the user is trying
// to log in. The proxy is **not** empty. All values assigned here
// should have been deterministically created using their credentials
// so setting them is just a precaution to keep things in good shape
res.proxy = rt.proxy;
res.realtime = rt.realtime;
res.network = rt.network;
// they're registering...
res.userHash = opt.userHash;
res.userName = uname;
// export their signing key
res.edPrivate = opt.edPrivate;
res.edPublic = opt.edPublic;
// export their encryption key
res.curvePrivate = opt.curvePrivate;
res.curvePublic = opt.curvePublic;
if (shouldImport) { setMergeAnonDrive(); }
// don't proceed past this async block.
waitFor.abort();
// We have to call whenRealtimeSyncs asynchronously here because in the current
// version of listmap, onLocal calls `chainpad.contentUpdate(newValue)`
// asynchronously.
// The following setTimeout is here to make sure whenRealtimeSyncs is called after
// `contentUpdate` so that we have an update userDoc in chainpad.
setTimeout(function () {
Realtime.whenRealtimeSyncs(rt.realtime, function () {
// the following stages are there to initialize a new drive
// if you are registering
LocalStore.login(res.userHash, res.userName, function () {
setTimeout(function () { cb(void 0, res); });
});
});
});
}));
}).nThen(function (waitFor) { // MODERN REGISTRATION / LOGIN
var opt;
if (res.blockInfo) {
opt = loginOptionsFromBlock(res.blockInfo);
userHash = res.blockInfo.User_hash;
//console.error(opt, userHash);
} else {
console.log("allocating random bytes for a new user object");
opt = allocateBytes(Nacl.randomBytes(Exports.requiredBytes));
// create a random v2 hash, since we don't need backwards compatibility
userHash = opt.userHash = Hash.createRandomHash('drive');
var secret = Hash.getSecrets('drive', userHash);
opt.keys = secret.keys;
opt.channelHex = secret.channel;
}
// according to the location derived from the credentials which you entered
loadUserObject(opt, waitFor(function (err, rt) {
if (err) {
waitFor.abort();
return void cb('MODERN_REGISTRATION_INIT');
}
//console.error(JSON.stringify(rt.proxy));
// export the realtime object you checked
RT = rt;
var proxy = rt.proxy;
if (isRegister && !isProxyEmpty(proxy) && (!proxy.edPublic || !proxy.edPrivate)) {
console.error("INVALID KEYS");
console.log(JSON.stringify(proxy));
return;
}
res.proxy = rt.proxy;
res.realtime = rt.realtime;
res.network = rt.network;
// they're registering...
res.userHash = userHash;
res.userName = uname;
// somehow they have a block present, but nothing in the user object it specifies
// this shouldn't happen, but let's send feedback if it does
if (!isRegister && isProxyEmpty(rt.proxy)) {
// this really shouldn't happen, but let's handle it anyway
Feedback.send('EMPTY_LOGIN_WITH_BLOCK');
//rt.network.disconnect(); // clean up after yourself
waitFor.abort();
return void cb('NO_SUCH_USER', res);
}
// they tried to register, but those exact credentials exist
if (isRegister && !isProxyEmpty(rt.proxy)) {
//rt.network.disconnect();
waitFor.abort();
res.blockHash = blockHash;
if (shouldImport) {
setMergeAnonDrive();
}
return void cb('ALREADY_REGISTERED', res);
}
if (!isRegister && !isProxyEmpty(rt.proxy)) {
LocalStore.setBlockHash(blockHash);
waitFor.abort();
if (shouldImport) {
setMergeAnonDrive();
}
var l = Util.find(rt.proxy, ['settings', 'general', 'language']);
var LS_LANG = "CRYPTPAD_LANG";
if (l) {
localStorage.setItem(LS_LANG, l);
}
return void LocalStore.login(userHash, uname, function () {
cb(void 0, res);
});
}
if (isRegister && isProxyEmpty(rt.proxy)) {
proxy.edPublic = opt.edPublic;
proxy.edPrivate = opt.edPrivate;
proxy.curvePublic = opt.curvePublic;
proxy.curvePrivate = opt.curvePrivate;
proxy.login_name = uname;
proxy[Constants.displayNameKey] = uname;
if (shouldImport) {
setMergeAnonDrive();
} else {
proxy.version = 11;
}
Feedback.send('REGISTRATION', true);
} else {
Feedback.send('LOGIN', true);
}
setTimeout(waitFor(function () {
Realtime.whenRealtimeSyncs(rt.realtime, waitFor());
}));
}));
}).nThen(function (waitFor) {
require(['/common/pinpad.js'], waitFor(function (_Pinpad) {
console.log("loaded rpc module");
Pinpad = _Pinpad;
}));
}).nThen(function (waitFor) {
// send an RPC to store the block which you created.
console.log("initializing rpc interface");
Pinpad.create(RT.network, Block.keysToRPCFormat(res.opt.blockKeys), waitFor(function (e, _rpc) {
if (e) {
waitFor.abort();
console.error(e); // INVALID_KEYS
return void cb('RPC_CREATION_ERROR');
}
rpc = _rpc;
console.log("rpc initialized");
}));
}).nThen(function (waitFor) {
console.log("creating request to publish a login block");
// Finally, create the login block for the object you just created.
var toPublish = {};
toPublish[Constants.userNameKey] = uname;
toPublish[Constants.userHashKey] = userHash;
toPublish.edPublic = RT.proxy.edPublic;
var blockRequest = Block.serialize(JSON.stringify(toPublish), res.opt.blockKeys);
rpc.writeLoginBlock(blockRequest, waitFor(function (e) {
if (e) {
console.error(e);
waitFor.abort();
return void cb(e);
}
}));
}).nThen(function (waitFor) {
// confirm that the block was actually written before considering registration successful
Util.fetch(blockUrl, waitFor(function (err /*, block */) {
if (err) {
console.error(err);
waitFor.abort();
return void cb(err);
}
console.log("blockInfo available at:", blockHash);
LocalStore.setBlockHash(blockHash);
LocalStore.login(userHash, uname, function () {
cb(void 0, res);
});
}));
});
};
Exports.redirect = function () { Exports.redirect = function () {
if (redirectTo) { if (redirectTo) {
var h = redirectTo; var h = redirectTo;

1398
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -13,11 +13,16 @@
}, },
"dependencies": { "dependencies": {
"@mcrowe/minibloom": "^0.2.0", "@mcrowe/minibloom": "^0.2.0",
"chainpad": "^5.2.0",
"chainpad-crypto": "^0.2.5", "chainpad-crypto": "^0.2.5",
"chainpad-listmap": "^1.0.0",
"chainpad-netflux": "^1.0.0",
"chainpad-server": "^5.1.0", "chainpad-server": "^5.1.0",
"express": "~4.18.2", "express": "~4.18.2",
"faye-websocket": "^0.11.4",
"fs-extra": "^7.0.0", "fs-extra": "^7.0.0",
"get-folder-size": "^2.0.1", "get-folder-size": "^2.0.1",
"json.sortify": "~2.1.0",
"netflux-websocket": "^0.1.20", "netflux-websocket": "^0.1.20",
"nthen": "0.1.8", "nthen": "0.1.8",
"prompt-confirm": "^2.0.4", "prompt-confirm": "^2.0.4",
@ -34,6 +39,8 @@
"lesshint": "6.3.7" "lesshint": "6.3.7"
}, },
"overrides": { "overrides": {
"minimatch": "~3.0.8",
"minimist": "~1.2.3",
"glob-parent": "5.1.2", "glob-parent": "5.1.2",
"set-value": "4.0.1" "set-value": "4.0.1"
}, },

68
scripts/api.js Normal file
View file

@ -0,0 +1,68 @@
/* globals global */
// "/2/drive/edit/4SH+XD5NqierGNeW5S3vHqbx/"
/* XXX
* Use nacl-fast in chainpad-crypto
*/
/* TODO
* LOGIN
* [x] loadUserObject
* [x] Copy
* [x] ListMap
* [x] ChainPad
* [x] NetConfig
* [ ] Feedback.send
* [ ] if required, should be rewritten for node
* [ ] provide a stub in the meantime
* [x] setMergeAnonDrive
* [x] not needed in Node
* [x] Copy the function from old login code, check where it's used and how to transmit, maybe in the callback?
* [x] Realtime.whenRealtimeSyncs
* easy to reuse
* [x] loginOptionsFromBlock
* copy-paste, requires Hash
* [ ] pinpad
* should be easy
* [ ] LocalStore
* [x] Not needed in Node
* [ ] provide a stub to the factory
* Maybe we should split this huge function into smaller parts
* Deprecate old login in the node API?
*/
const WebSocketClient = require('faye-websocket').Client;
const n = require('tweetnacl/nacl-fast');
global.window = {
addEventListener: function () {},
WebSocket: WebSocketClient,
Proxy: Proxy,
localStorage: {
setItem: function (k, v) { this[k] = v; },
getItem: function (k) { return this[k]; },
removeItem: function (k) { delete this[k]; }
},
nacl: n
};
global.localStorage = window.localStorage;
const Login = require('../www/common/login');
const login = Login({
websocketURL: 'ws://localhost:3000/cryptpad_websocket',
fileHost: 'http://localhost:3000'
});
login.loginOrRegister('blu', 'register2', false, false, function (err, data) {
//console.error(err, data.proxy);
console.log(data.proxy['cryptpad.username']);
//data.proxy['cryptpad.username'] = "blu-reg";
});

View file

@ -311,7 +311,7 @@ define([
assert(function (cb) { assert(function (cb) {
var keys = Block.genkeys(Nacl.randomBytes(64)); var keys = Block.genkeys(Nacl.randomBytes(64));
var hash = Block.getBlockHash(keys); var hash = Block.getBlockHash(keys, ApiConfig.fileHost);
var parsed = Block.parseBlockHash(hash); var parsed = Block.parseBlockHash(hash);
cb(parsed && cb(parsed &&

View file

@ -306,7 +306,7 @@ define([
var opt = Login.allocateBytes(bytes); var opt = Login.allocateBytes(bytes);
var blockUrl = Login.Block.getBlockUrl(opt.blockKeys); var blockUrl = Login.Block.getBlockUrl(opt.blockKeys, ApiConfig.fileHost);
var blockRequest = Login.Block.serialize("{}", opt.blockKeys); var blockRequest = Login.Block.serialize("{}", opt.blockKeys);
var removeRequest = Login.Block.remove(opt.blockKeys); var removeRequest = Login.Block.remove(opt.blockKeys);
console.warn('Testing block URL (%s). One 404 is normal.', blockUrl); console.warn('Testing block URL (%s). One 404 is normal.', blockUrl);

View file

@ -1,4 +1,5 @@
define(['/customize/application_config.js'], function (AppConfig) { (function () {
var factory = function (AppConfig) {
return { return {
// localStorage // localStorage
userHashKey: 'User_hash', userHashKey: 'User_hash',
@ -20,4 +21,16 @@ define(['/customize/application_config.js'], function (AppConfig) {
criticalApps: ['profile', 'settings', 'debug', 'admin', 'support', 'notifications', 'calendar'], criticalApps: ['profile', 'settings', 'debug', 'admin', 'support', 'notifications', 'calendar'],
earlyAccessApps: ['doc', 'presentation'] earlyAccessApps: ['doc', 'presentation']
}; };
}); };
if (typeof(module) !== 'undefined' && module.exports) {
module.exports = factory(
{} // XXX AppConfig stub
);
} else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) {
define([
'/customize/application_config.js',
], factory);
}
})();

View file

@ -1,4 +1,5 @@
define([], function () { (function () {
var factory = function () {
var common = {}; var common = {};
/* /*
@ -18,4 +19,12 @@ define([], function () {
}; };
return common; return common;
}); };
if (typeof(module) !== 'undefined' && module.exports) {
module.exports = factory();
} else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) {
define([], factory);
}
})();

View file

@ -365,6 +365,22 @@
}; };
}; };
if (typeof module !== 'undefined' && module.exports) {
Util.fetch = function (src, cb) {
var CB = Util.once(Util.mkAsync(cb));
fetch(src).then(function (response) {
if (!response.ok) {
throw new Error(`HTTP error`);
}
return response.arrayBuffer();
}).catch(function (err) {
CB(err);
}).then(function (u8) {
CB(void 0, new Uint8Array(u8));
});
};
}
Util.dataURIToBlob = function (dataURI) { Util.dataURIToBlob = function (dataURI) {
var byteString = atob(dataURI.split(',')[1]); var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

View file

@ -2048,7 +2048,7 @@ define([
blockKeys = allocated.blockKeys; blockKeys = allocated.blockKeys;
})); }));
}).nThen(function (waitFor) { }).nThen(function (waitFor) {
var blockUrl = Block.getBlockUrl(blockKeys); var blockUrl = Block.getBlockUrl(blockKeys, Config.fileHost);
// Check whether there is a block at that location // Check whether there is a block at that location
Util.fetch(blockUrl, waitFor(function (err, block) { Util.fetch(blockUrl, waitFor(function (err, block) {
// If there is no block or the block is invalid, continue. // If there is no block or the block is invalid, continue.
@ -2092,7 +2092,7 @@ define([
} }
})); }));
}).nThen(function (waitFor) { }).nThen(function (waitFor) {
var blockUrl = Block.getBlockUrl(blockKeys); var blockUrl = Block.getBlockUrl(blockKeys, Config.fileHost);
Util.fetch(blockUrl, waitFor(function (err /* block */) { Util.fetch(blockUrl, waitFor(function (err /* block */) {
if (err) { if (err) {
console.error(err); console.error(err);
@ -2102,7 +2102,7 @@ define([
}); });
} }
console.log("new login block written"); console.log("new login block written");
var newBlockHash = Block.getBlockHash(blockKeys); var newBlockHash = Block.getBlockHash(blockKeys, Config.fileHost);
LocalStore.setBlockHash(newBlockHash); LocalStore.setBlockHash(newBlockHash);
})); }));
}).nThen(function (waitFor) { }).nThen(function (waitFor) {

462
www/common/login.js Normal file
View file

@ -0,0 +1,462 @@
(function () {
var factory = function (Cred, Util, Hash, Realtime, Constants, Block,
Crypto, nThen, Listmap, ChainPad, Nacl, LocalStore, Feedback) {
var REQUIRED_BYTES = 192;
var init = function (config) {
var Login = {
'REQUIRED_BYTES': REQUIRED_BYTES
};
var setMergeAnonDrive = config.setMergeAnonDrive || function () {};
var websocketURL = config.websocketURL;
var fileHost = config.fileHost;
var loadUserObject = Login.loadUserObject = function (opt, cb) {
var config = {
websocketURL: websocketURL,
channel: opt.channelHex,
data: {},
validateKey: opt.keys.validateKey, // derived validation key
crypto: Crypto.createEncryptor(opt.keys),
logLevel: 1,
classic: true,
ChainPad: ChainPad,
owners: [opt.edPublic]
};
var rt = opt.rt = Listmap.create(config);
rt.proxy
.on('ready', function () {
setTimeout(function () { cb(void 0, rt); });
})
.on('error', function (err)  { console.error(err); })
.on('error', function (err)  { console.error(err); })
.on('disconnect', function (info) {
cb('E_DISCONNECT', info);
});
};
var loginOptionsFromBlock = Login.loginOptionsFromBlock = function (blockInfo) {
var opt = {};
var parsed = Hash.getSecrets('pad', blockInfo.User_hash);
opt.channelHex = parsed.channel;
opt.keys = parsed.keys;
opt.edPublic = blockInfo.edPublic;
opt.User_name = blockInfo.User_name;
return opt;
};
var isProxyEmpty = function (proxy) {
var l = Object.keys(proxy).length;
return l === 0 || (l === 2 && proxy._events && proxy.on);
};
var allocateBytes = Login.allocateBytes = function (bytes) {
var dispense = Cred.dispenser(bytes);
var opt = {};
// dispense 18 bytes of entropy for your encryption key
var encryptionSeed = dispense(18);
// 16 bytes for a deterministic channel key
var channelSeed = dispense(16);
// 32 bytes for a curve key
var curveSeed = dispense(32);
var curvePair = Nacl.box.keyPair.fromSecretKey(new Uint8Array(curveSeed));
opt.curvePrivate = Nacl.util.encodeBase64(curvePair.secretKey);
opt.curvePublic = Nacl.util.encodeBase64(curvePair.publicKey);
// 32 more for a signing key
var edSeed = opt.edSeed = dispense(32);
// 64 more bytes to seed an additional signing key
var blockKeys = opt.blockKeys = Block.genkeys(new Uint8Array(dispense(64)));
opt.blockHash = Block.getBlockHash(blockKeys, fileHost);
// derive a private key from the ed seed
var signingKeypair = Nacl.sign.keyPair.fromSeed(new Uint8Array(edSeed));
opt.edPrivate = Nacl.util.encodeBase64(signingKeypair.secretKey);
opt.edPublic = Nacl.util.encodeBase64(signingKeypair.publicKey);
var keys = opt.keys = Crypto.createEditCryptor(null, encryptionSeed);
// 24 bytes of base64
keys.editKeyStr = keys.editKeyStr.replace(/\//g, '-');
// 32 bytes of hex
var channelHex = opt.channelHex = Util.uint8ArrayToHex(channelSeed);
// should never happen
if (channelHex.length !== 32) { throw new Error('invalid channel id'); }
var channel64 = Util.hexToBase64(channelHex);
// we still generate a v1 hash because this function needs to deterministically
// derive the same values as it always has. New accounts will generate their own
// userHash values
opt.userHash = '/1/edit/' + [channel64, opt.keys.editKeyStr].join('/') + '/';
return opt;
};
Login.loginOrRegister = function (uname, passwd, isRegister, shouldImport, cb) {
if (typeof(cb) !== 'function') { return; }
// Usernames are all lowercase. No going back on this one
uname = uname.toLowerCase();
// validate inputs
if (!Cred.isValidUsername(uname)) { return void cb('INVAL_USER'); }
if (!Cred.isValidPassword(passwd)) { return void cb('INVAL_PASS'); }
if (isRegister && !Cred.isLongEnoughPassword(passwd)) {
return void cb('PASS_TOO_SHORT');
}
// results...
var res = {
register: isRegister,
};
var RT, blockKeys, blockHash, blockUrl, Pinpad, rpc, userHash;
nThen(function (waitFor) {
// derive a predefined number of bytes from the user's inputs,
// and allocate them in a deterministic fashion
Cred.deriveFromPassphrase(uname, passwd, REQUIRED_BYTES, waitFor(function (bytes) {
res.opt = allocateBytes(bytes, fileHost);
blockHash = res.opt.blockHash;
blockKeys = res.opt.blockKeys;
}));
}).nThen(function (waitFor) {
// the allocated bytes can be used either in a legacy fashion,
// or in such a way that a previously unused byte range determines
// the location of a layer of indirection which points users to
// an encrypted block, from which they can recover the location of
// the rest of their data
// determine where a block for your set of keys would be stored
blockUrl = Block.getBlockUrl(res.opt.blockKeys, fileHost);
// Check whether there is a block at that location
Util.fetch(blockUrl, waitFor(function (err, block) {
// if users try to log in or register, we must check
// whether there is a block.
// the block is only useful if it can be decrypted, though
if (err) {
console.log("no block found");
return;
}
var decryptedBlock = Block.decrypt(block, blockKeys);
if (!decryptedBlock) {
console.error("Found a login block but failed to decrypt");
return;
}
//console.error(decryptedBlock);
res.blockInfo = decryptedBlock;
}));
}).nThen(function (waitFor) {
// we assume that if there is a block, it was created in a valid manner
// so, just proceed to the next block which handles that stuff
if (res.blockInfo) { return; }
var opt = res.opt;
// load the user's object using the legacy credentials
loadUserObject(opt, waitFor(function (err, rt) {
if (err) {
waitFor.abort();
return void cb(err);
}
// if a proxy is marked as deprecated, it is because someone had a non-owned drive
// but changed their password, and couldn't delete their old data.
// if they are here, they have entered their old credentials, so we should not
// allow them to proceed. In time, their old drive should get deleted, since
// it will should be pinned by anyone's drive.
if (rt.proxy[Constants.deprecatedKey]) {
waitFor.abort();
return void cb('NO_SUCH_USER', res);
}
if (isRegister && isProxyEmpty(rt.proxy)) {
// If they are trying to register,
// and the proxy is empty, then there is no 'legacy user' either
// so we should just shut down this session and disconnect.
//rt.network.disconnect();
return; // proceed to the next async block
}
// they tried to just log in but there's no such user
// and since we're here at all there is no modern-block
if (!isRegister && isProxyEmpty(rt.proxy)) {
//rt.network.disconnect(); // clean up after yourself
waitFor.abort();
return void cb('NO_SUCH_USER', res);
}
// they tried to register, but those exact credentials exist
if (isRegister && !isProxyEmpty(rt.proxy)) {
//rt.network.disconnect();
waitFor.abort();
Feedback.send('LOGIN', true);
return void cb('ALREADY_REGISTERED', res);
}
// if you are here, then there is no block, the user is trying
// to log in. The proxy is **not** empty. All values assigned here
// should have been deterministically created using their credentials
// so setting them is just a precaution to keep things in good shape
res.proxy = rt.proxy;
res.realtime = rt.realtime;
res.network = rt.network;
// they're registering...
res.userHash = opt.userHash;
res.userName = uname;
// export their signing key
res.edPrivate = opt.edPrivate;
res.edPublic = opt.edPublic;
// export their encryption key
res.curvePrivate = opt.curvePrivate;
res.curvePublic = opt.curvePublic;
if (shouldImport) { setMergeAnonDrive(); }
// don't proceed past this async block.
waitFor.abort();
// We have to call whenRealtimeSyncs asynchronously here because in the current
// version of listmap, onLocal calls `chainpad.contentUpdate(newValue)`
// asynchronously.
// The following setTimeout is here to make sure whenRealtimeSyncs is called after
// `contentUpdate` so that we have an update userDoc in chainpad.
setTimeout(function () {
Realtime.whenRealtimeSyncs(rt.realtime, function () {
// the following stages are there to initialize a new drive
// if you are registering
LocalStore.login(res.userHash, res.userName, function () {
setTimeout(function () { cb(void 0, res); });
});
});
});
}));
}).nThen(function (waitFor) { // MODERN REGISTRATION / LOGIN
var opt;
if (res.blockInfo) {
opt = loginOptionsFromBlock(res.blockInfo);
userHash = res.blockInfo.User_hash;
//console.error(opt, userHash);
} else {
console.log("allocating random bytes for a new user object");
opt = allocateBytes(Nacl.randomBytes(REQUIRED_BYTES), fileHost);
// create a random v2 hash, since we don't need backwards compatibility
userHash = opt.userHash = Hash.createRandomHash('drive');
var secret = Hash.getSecrets('drive', userHash);
opt.keys = secret.keys;
opt.channelHex = secret.channel;
}
// according to the location derived from the credentials which you entered
loadUserObject(opt, waitFor(function (err, rt) {
if (err) {
waitFor.abort();
return void cb('MODERN_REGISTRATION_INIT');
}
//console.error(JSON.stringify(rt.proxy));
// export the realtime object you checked
RT = rt;
var proxy = rt.proxy;
if (isRegister && !isProxyEmpty(proxy) && (!proxy.edPublic || !proxy.edPrivate)) {
console.error("INVALID KEYS");
console.log(JSON.stringify(proxy));
return;
}
res.proxy = rt.proxy;
res.realtime = rt.realtime;
res.network = rt.network;
// they're registering...
res.userHash = userHash;
res.userName = uname;
// somehow they have a block present, but nothing in the user object it specifies
// this shouldn't happen, but let's send feedback if it does
if (!isRegister && isProxyEmpty(rt.proxy)) {
// this really shouldn't happen, but let's handle it anyway
Feedback.send('EMPTY_LOGIN_WITH_BLOCK');
//rt.network.disconnect(); // clean up after yourself
waitFor.abort();
return void cb('NO_SUCH_USER', res);
}
// they tried to register, but those exact credentials exist
if (isRegister && !isProxyEmpty(rt.proxy)) {
//rt.network.disconnect();
waitFor.abort();
res.blockHash = blockHash;
if (shouldImport) {
setMergeAnonDrive();
}
return void cb('ALREADY_REGISTERED', res);
}
if (!isRegister && !isProxyEmpty(rt.proxy)) {
LocalStore.setBlockHash(blockHash);
waitFor.abort();
if (shouldImport) {
setMergeAnonDrive();
}
var l = Util.find(rt.proxy, ['settings', 'general', 'language']);
var LS_LANG = "CRYPTPAD_LANG";
if (l) {
localStorage.setItem(LS_LANG, l);
}
return void LocalStore.login(userHash, uname, function () {
cb(void 0, res);
});
}
if (isRegister && isProxyEmpty(rt.proxy)) {
proxy.edPublic = opt.edPublic;
proxy.edPrivate = opt.edPrivate;
proxy.curvePublic = opt.curvePublic;
proxy.curvePrivate = opt.curvePrivate;
proxy.login_name = uname;
proxy[Constants.displayNameKey] = uname;
if (shouldImport) {
setMergeAnonDrive();
} else {
proxy.version = 11;
}
Feedback.send('REGISTRATION', true);
} else {
Feedback.send('LOGIN', true);
}
setTimeout(waitFor(function () {
Realtime.whenRealtimeSyncs(rt.realtime, waitFor());
}));
}));
}).nThen(function (waitFor) {
if (typeof(module) !== 'undefined' && module.exports) {
Pinpad = require('./pinpad');
} else if ((typeof(define) !== 'undefined' && define !== null) && define.amd) {
require(['/common/pinpad.js'], waitFor(function (_Pinpad) {
console.log("loaded rpc module");
Pinpad = _Pinpad;
}));
}
}).nThen(function (waitFor) {
// send an RPC to store the block which you created.
console.log("initializing rpc interface");
console.log(Pinpad);
Pinpad.create(RT.network, Block.keysToRPCFormat(res.opt.blockKeys), waitFor(function (e, _rpc) {
if (e) {
waitFor.abort();
console.error(e); // INVALID_KEYS
return void cb('RPC_CREATION_ERROR');
}
rpc = _rpc;
console.log("rpc initialized");
}));
}).nThen(function (waitFor) {
console.log("creating request to publish a login block");
// Finally, create the login block for the object you just created.
var toPublish = {};
toPublish[Constants.userNameKey] = uname;
toPublish[Constants.userHashKey] = userHash;
toPublish.edPublic = RT.proxy.edPublic;
var blockRequest = Block.serialize(JSON.stringify(toPublish), res.opt.blockKeys);
rpc.writeLoginBlock(blockRequest, waitFor(function (e) {
if (e) {
console.error(e);
waitFor.abort();
return void cb(e);
}
}));
}).nThen(function (waitFor) {
// confirm that the block was actually written before considering registration successful
Util.fetch(blockUrl, waitFor(function (err /*, block */) {
if (err) {
console.error(err);
waitFor.abort();
return void cb(err);
}
console.log("blockInfo available at:", blockHash);
LocalStore.setBlockHash(blockHash);
LocalStore.login(userHash, uname, function () {
cb(void 0, res);
});
}));
});
};
return Login;
};
return init;
};
if (typeof(module) !== 'undefined' && module.exports) {
var lm = require('chainpad-listmap');
module.exports = factory(
require("./common-credential"),
require("./common-util"),
require("./common-hash"),
require("./common-realtime"),
require("./common-constants"),
require("./outer/login-block"),
require("chainpad-crypto"),
require('nthen'),
lm,
require('chainpad'),
require('tweetnacl/nacl-fast'),
require("./outer/local-store"),
{ send: function (k, v) { console.log('Feedback', k, v); } }
);
} else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) {
define([
'/common/common-credential.js',
'/common/common-util.js',
'/common/common-hash.js',
'/common/common-realtime.js',
'/common/common-feedback.js',
'/common/common-constants.js',
'/common/outer/login-block.js',
'/bower_components/chainpad-crypto/crypto.js',
'/common/outer/local-store.js',
'/bower_components/nthen/index.js',
'/bower_components/chainpad-listmap/chainpad-listmap.js',
'/bower_components/chainpad/chainpad.dist.js',
'/bower_components/tweetnacl/nacl-fast.min.js',
], function (Cred, Util, Hash, Realtime, Feedback, Constants,
Block, Crypto, nThen, LM, ChainPad, LocalStore) {
return factory(Cred, Util, Hash, Realtime, Constants,
Block, Crypto, nThen, LM, ChainPad, window.nacl, LocalStore, Feedback);
});
}
}());

View file

@ -1,11 +1,5 @@
define([ (function () {
'/common/common-constants.js', var factory = function (Constants, Hash, Cache, localForage, AppConfig, Util) {
'/common/common-hash.js',
'/common/outer/cache-store.js',
'/bower_components/localforage/dist/localforage.min.js',
'/customize/application_config.js',
'/common/common-util.js',
], function (Constants, Hash, Cache, localForage, AppConfig, Util) {
var LocalStore = {}; var LocalStore = {};
var safeSet = function (key, val) { var safeSet = function (key, val) {
@ -17,13 +11,16 @@ define([
}; };
LocalStore.setThumbnail = function (key, value, cb) { LocalStore.setThumbnail = function (key, value, cb) {
if (!localForage) { return void cb(); }
localForage.setItem(key, value, cb); localForage.setItem(key, value, cb);
}; };
LocalStore.getThumbnail = function (key, cb) { LocalStore.getThumbnail = function (key, cb) {
if (!localForage) { return void cb(); }
localForage.getItem(key, cb); localForage.getItem(key, cb);
}; };
LocalStore.clearThumbnail = function (cb) { LocalStore.clearThumbnail = function (cb) {
cb = cb || function () {}; cb = cb || function () {};
if (!localForage) { return void cb(); }
localForage.clear(cb); localForage.clear(cb);
}; };
@ -182,4 +179,26 @@ define([
return LocalStore; return LocalStore;
}); };
if (typeof(module) !== 'undefined' && module.exports) {
module.exports = factory(
require("../common-constants"),
require("../common-hash"),
{ clear: function () {} }, // Cache stub
undefined, // localForage
{}, // XXX AppConfig stub
require("../common-util")
);
} else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) {
define([
'/common/common-constants.js',
'/common/common-hash.js',
'/common/outer/cache-store.js',
'/bower_components/localforage/dist/localforage.min.js',
'/customize/application_config.js',
'/common/common-util.js',
], factory);
}
})();

View file

@ -1,9 +1,5 @@
define([ (function () {
'/common/common-util.js', var factory = function (Util, Nacl) {
'/api/config',
'/bower_components/tweetnacl/nacl-fast.min.js',
], function (Util, ApiConfig) {
var Nacl = window.nacl;
var Block = {}; var Block = {};
@ -128,17 +124,17 @@ define([
return Nacl.util.encodeBase64(u8).replace(/\//g, '-'); return Nacl.util.encodeBase64(u8).replace(/\//g, '-');
}; };
Block.getBlockUrl = function (keys) { Block.getBlockUrl = function (keys, fileHost) {
var publicKey = urlSafeB64(keys.sign.publicKey); var publicKey = urlSafeB64(keys.sign.publicKey);
// 'block/' here is hardcoded because it's hardcoded on the server // 'block/' here is hardcoded because it's hardcoded on the server
// if we want to make CryptPad work in server subfolders, we'll need // if we want to make CryptPad work in server subfolders, we'll need
// to update this path derivation // to update this path derivation
return (ApiConfig.fileHost || window.location.origin) return (fileHost || (typeof(window) !== "undefined" && window.location.origin))
+ '/block/' + publicKey.slice(0, 2) + '/' + publicKey; + '/block/' + publicKey.slice(0, 2) + '/' + publicKey;
}; };
Block.getBlockHash = function (keys) { Block.getBlockHash = function (keys, fileHost) {
var absolute = Block.getBlockUrl(keys); var absolute = Block.getBlockUrl(keys, fileHost);
var symmetric = urlSafeB64(keys.symmetric); var symmetric = urlSafeB64(keys.symmetric);
return absolute + '#' + symmetric; return absolute + '#' + symmetric;
}; };
@ -171,4 +167,22 @@ define([
}; };
return Block; return Block;
}); };
if (typeof(module) !== 'undefined' && module.exports) {
module.exports = factory(
require('../common-util'),
require("tweetnacl/nacl-fast")
);
} else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) {
define([
'/common/common-util.js',
'/bower_components/tweetnacl/nacl-fast.min.js',
], function (Util) {
return factory(Util, window.nacl);
});
} else {
// I'm not gonna bother supporting any other kind of instanciation
}
})();