cryptpad/www/common/cryptpad-common.js

833 lines
27 KiB
JavaScript
Raw Normal View History

2016-05-28 11:13:54 +00:00
define([
2016-07-12 14:43:33 +00:00
'/customize/messages.js',
'/customize/store.js',
2016-06-23 14:44:20 +00:00
'/bower_components/chainpad-crypto/crypto.js',
2016-07-06 20:20:15 +00:00
'/bower_components/alertifyjs/dist/js/alertify.js',
2016-08-02 16:56:35 +00:00
'/bower_components/spin.js/spin.min.js',
2016-08-30 16:09:53 +00:00
'/customize/user.js',
2016-06-23 14:44:20 +00:00
'/bower_components/jquery/dist/jquery.min.js',
2016-08-30 16:09:53 +00:00
], function (Messages, Store, Crypto, Alertify, Spinner, User) {
/* This file exposes functionality which is specific to Cryptpad, but not to
any particular pad type. This includes functions for committing metadata
about pads to your local storage for future use and improved usability.
Additionally, there is some basic functionality for import/export.
*/
2016-06-23 14:44:20 +00:00
var $ = window.jQuery;
2016-07-06 20:20:15 +00:00
var common = {
User: User,
};
var store;
2016-08-30 16:09:53 +00:00
var userProxy;
var userStore;
var find = common.find = function (map, path) {
return (map && path.reduce(function (p, n) {
return typeof(p[n]) !== 'undefined' && p[n];
}, map));
};
2016-08-30 16:09:53 +00:00
var getStore = common.getStore = function (legacy) {
if (!legacy && userStore) { return userStore; }
if (store) { return store; }
throw new Error("Store is not ready!");
};
2016-08-30 16:09:53 +00:00
/*
* cb(err, proxy);
*/
var authorize = common.authorize = function (cb) {
console.log("Authorizing");
User.session(void 0, function (err, secret) {
if (!secret) {
// user is not authenticated
cb('user is not authenticated', void 0);
}
// for now we assume that things always work
User.connect(secret, function (err, proxy) {
cb(void 0, proxy);
});
});
};
// HERE
var deauthorize = common.deauthorize = function (cb) {
console.log("Deauthorizing");
// erase session data from storage
User.session(null, function (err) {
if (err) {
console.error(err);
}
/*
TODO better abort for this stuff...
*/
userStore = undefined;
userProxy = undefined;
2016-08-30 16:09:53 +00:00
});
};
Store.ready(function (err, Store) {
if (err) {
console.error(err);
return;
}
store = Store;
});
2016-05-28 11:13:54 +00:00
var isArray = function (o) { return Object.prototype.toString.call(o) === '[object Array]'; };
2016-08-29 16:10:15 +00:00
var fixHTML = common.fixHTML = function (html) {
return html.replace(/</g, '&lt;');
};
var truncate = common.truncate = function (text, len) {
if (typeof(text) === 'string' && text.length > len) {
return text.slice(0, len) + '…';
}
return text;
};
common.redirect = function (hash) {
var hostname = window.location.hostname;
// don't do anything funny unless you're on a cryptpad subdomain
2016-08-02 15:08:46 +00:00
if (!/cryptpad.fr$/i.test(hostname)) { return; }
2016-09-13 15:43:56 +00:00
if (hash.length >= 25) {
// you're on the right domain
return;
}
// old.cryptpad only supports these apps, so only redirect on a match
if (['/pad/', '/p/', '/code/'].indexOf(window.location.pathname) === -1) {
return;
}
// if you make it this far then there's something wrong with your hash
// you should probably be on old.cryptpad.fr...
window.location.hostname = 'old.cryptpad.fr';
};
2016-09-13 15:43:56 +00:00
var hexToBase64 = common.hexToBase64 = function (hex) {
var hexArray = hex
.replace(/\r|\n/g, "")
.replace(/([\da-fA-F]{2}) ?/g, "0x$1 ")
.replace(/ +$/, "")
.split(" ");
var byteString = String.fromCharCode.apply(null, hexArray);
return window.btoa(byteString).replace(/\//g, '-').slice(0,-2);
};
var base64ToHex = common.base64ToHex = function (b64String) {
var hexArray = [];
2016-09-16 16:45:40 +00:00
atob(b64String.replace(/-/g, '/')).split("").forEach(function(e){
2016-09-13 15:43:56 +00:00
var h = e.charCodeAt(0).toString(16);
if (h.length === 1) { h = "0"+h; }
hexArray.push(h);
});
return hexArray.join("");
};
2016-09-16 16:45:40 +00:00
var getEditHashFromKeys = common.getEditHashFromKeys = function (chanKey, keys) {
if (typeof keys === 'string') {
2016-09-20 16:22:40 +00:00
return chanKey + keys;
2016-09-16 16:45:40 +00:00
}
return '/1/edit/' + hexToBase64(chanKey) + '/' + Crypto.b64RemoveSlashes(keys.editKeyStr);
2016-09-13 15:43:56 +00:00
};
2016-09-16 16:45:40 +00:00
var getViewHashFromKeys = common.getViewHashFromKeys = function (chanKey, keys) {
2016-09-20 16:22:40 +00:00
if (typeof keys === 'string') {
return;
}
2016-09-16 16:45:40 +00:00
return '/1/view/' + hexToBase64(chanKey) + '/' + Crypto.b64RemoveSlashes(keys.viewKeyStr);
2016-09-13 15:43:56 +00:00
};
2016-09-16 16:45:40 +00:00
var getHashFromKeys = common.getHashFromKeys = getEditHashFromKeys;
2016-09-13 15:43:56 +00:00
2016-05-28 11:13:54 +00:00
var getSecrets = common.getSecrets = function () {
var secret = {};
if (!/#/.test(window.location.href)) {
2016-09-16 16:45:40 +00:00
secret.keys = Crypto.createEditCryptor();
secret.key = Crypto.createEditCryptor().editKeyStr;
2016-05-28 11:13:54 +00:00
} else {
var hash = window.location.hash.slice(1);
2016-09-13 15:43:56 +00:00
if (hash.length === 0) {
2016-09-16 16:45:40 +00:00
secret.keys = Crypto.createEditCryptor();
secret.key = Crypto.createEditCryptor().editKeyStr;
2016-09-13 15:43:56 +00:00
return secret;
}
common.redirect(hash);
2016-09-13 15:43:56 +00:00
// old hash system : #{hexChanKey}{cryptKey}
// new hash system : #/{hashVersion}/{b64ChanKey}/{cryptKey}
if (hash.slice(0,1) !== '/' && hash.length >= 56) {
// Old hash
secret.channel = hash.slice(0, 32);
secret.key = hash.slice(32);
}
else {
// New hash
var hashArray = hash.split('/');
if (hashArray.length < 4) {
common.alert("Unable to parse the key");
throw new Error("Unable to parse the key");
}
var version = hashArray[1];
2016-09-16 16:45:40 +00:00
/*if (version === "1") {
2016-09-13 15:43:56 +00:00
secret.channel = base64ToHex(hashArray[2]);
2016-09-20 16:22:40 +00:00
secret.key = hashArray[3].replace(/-/g, '/');
2016-09-13 15:43:56 +00:00
if (secret.channel.length !== 32 || secret.key.length !== 24) {
common.alert("The channel key and/or the encryption key is invalid");
throw new Error("The channel key and/or the encryption key is invalid");
}
2016-09-16 16:45:40 +00:00
}*/
if (version === "1") {
var mode = hashArray[2];
if (mode === 'edit') {
secret.channel = base64ToHex(hashArray[3]);
var keys = Crypto.createEditCryptor(hashArray[4].replace(/-/g, '/'));
secret.keys = keys;
secret.key = keys.editKeyStr;
if (secret.channel.length !== 32 || secret.key.length !== 24) {
common.alert("The channel key and/or the encryption key is invalid");
throw new Error("The channel key and/or the encryption key is invalid");
}
}
else if (mode === 'view') {
secret.channel = base64ToHex(hashArray[3]);
2016-09-23 15:53:24 +00:00
secret.keys = Crypto.createViewCryptor(hashArray[4].replace(/-/g, '/'));
2016-09-16 16:45:40 +00:00
if (secret.channel.length !== 32) {
common.alert("The channel key is invalid");
throw new Error("The channel key is invalid");
}
}
2016-09-13 15:43:56 +00:00
}
}
2016-05-28 11:13:54 +00:00
}
return secret;
};
var storageKey = common.storageKey = 'CryptPad_RECENTPADS';
2016-08-30 16:09:53 +00:00
/*
* localStorage formatting
*/
/*
the first time this gets called, your local storage will migrate to a
new format. No more indices for values, everything is named now.
* href
* atime (access time)
* title
* ??? // what else can we put in here?
*/
var migrateRecentPads = common.migrateRecentPads = function (pads) {
return pads.map(function (pad) {
if (isArray(pad)) {
var href = pad[0];
var hash;
href.replace(/\#(.*)$/, function (a, h) {
hash = h;
});
return {
href: pad[0],
atime: pad[1],
title: pad[2] || hash && hash.slice(0,8),
2016-06-30 13:15:38 +00:00
ctime: pad[1],
};
} else if (typeof(pad) === 'object') {
if (!pad.ctime) { pad.ctime = pad.atime; }
if (!pad.title) {
pad.href.replace(/#(.*)$/, function (x, hash) {
pad.title = hash.slice(0,8);
});
}
pad.href = pad.href.replace(/^https:\/\/beta\.cryptpad\.fr/,
'https://cryptpad.fr');
return pad;
} else {
console.error("[Cryptpad.migrateRecentPads] pad had unexpected value");
console.log(pad);
return {};
}
});
};
2016-07-22 10:24:54 +00:00
var getHash = common.getHash = function () {
return window.location.hash.slice(1);
};
2016-08-30 16:09:53 +00:00
var parsePadUrl = common.parsePadUrl = function (href) {
var patt = /^https*:\/\/([^\/]*)\/(.*?)\/#(.*)$/i;
var ret = {};
href.replace(patt, function (a, domain, type, hash) {
ret.domain = domain;
ret.type = type;
ret.hash = hash;
return '';
});
return ret;
};
2016-09-13 10:24:06 +00:00
var isNameAvailable = function (title, parsed, pads) {
return !pads.some(function (pad) {
// another pad is already using that title
if (pad.title === title) {
return true;
}
});
};
// Create untitled documents when no name is given
2016-09-13 15:43:56 +00:00
var getDefaultName = common.getDefaultName = function (parsed, recentPads) {
2016-09-13 10:24:06 +00:00
var type = parsed.type;
var untitledIndex = 1;
var name = (Messages.type)[type] + ' - ' + new Date().toString().split(' ').slice(0,4).join(' ');
if (isNameAvailable(name, parsed, recentPads)) { return name; }
while (!isNameAvailable(name + ' - ' + untitledIndex, parsed, recentPads)) { untitledIndex++; }
return name + ' - ' + untitledIndex;
};
2016-08-30 16:09:53 +00:00
var makePad = function (href, title) {
var now = ''+new Date();
return {
href: href,
atime: now,
ctime: now,
title: title || window.location.hash.slice(1, 9),
};
};
/* Sort pads according to how recently they were accessed */
var mostRecent = common.mostRecent = function (a, b) {
return new Date(b.atime).getTime() - new Date(a.atime).getTime();
};
// STORAGE
var setPadAttribute = common.setPadAttribute = function (attr, value, cb, legacy) {
getStore(legacy).set([getHash(), attr].join('.'), value, function (err, data) {
cb(err, data);
});
2016-07-22 10:24:54 +00:00
};
2016-09-22 15:12:46 +00:00
var setAttribute = common.setAttribute = function (attr, value, cb, legacy) {
getStore(legacy).set(["cryptpad", attr].join('.'), value, function (err, data) {
cb(err, data);
});
};
2016-07-22 10:24:54 +00:00
2016-08-30 16:09:53 +00:00
// STORAGE
var getPadAttribute = common.getPadAttribute = function (attr, cb, legacy) {
getStore(legacy).get([getHash(), attr].join('.'), function (err, data) {
cb(err, data);
});
2016-07-22 10:24:54 +00:00
};
2016-09-22 15:12:46 +00:00
var getAttribute = common.getAttribute = function (attr, cb, legacy) {
getStore(legacy).get(["cryptpad", attr].join('.'), function (err, data) {
cb(err, data);
});
};
2016-07-22 10:24:54 +00:00
2016-08-30 16:09:53 +00:00
// STORAGE
/* fetch and migrate your pad history from localStorage */
2016-08-30 16:09:53 +00:00
var getRecentPads = common.getRecentPads = function (cb, legacy) {
getStore(legacy).get(storageKey, function (err, recentPads) {
if (isArray(recentPads)) {
cb(void 0, migrateRecentPads(recentPads));
return;
}
cb(void 0, []);
});
};
2016-08-30 16:09:53 +00:00
// STORAGE
/* commit a list of pads to localStorage */
2016-08-30 16:09:53 +00:00
var setRecentPads = common.setRecentPads = function (pads, cb, legacy) {
getStore(legacy).set(storageKey, pads, function (err, data) {
cb(err, data);
});
};
2016-08-30 16:09:53 +00:00
// STORAGE
var forgetPad = common.forgetPad = function (href, cb, legacy) {
var parsed = parsePadUrl(href);
getRecentPads(function (err, recentPads) {
setRecentPads(recentPads.filter(function (pad) {
var p = parsePadUrl(pad.href);
// find duplicates
if (parsed.hash === p.hash && parsed.type === p.type) {
console.log("Found a duplicate");
return;
}
return true;
}), function (err, data) {
if (err) {
cb(err);
return;
}
2016-08-30 16:09:53 +00:00
getStore(legacy).keys(function (err, keys) {
if (err) {
cb(err);
return;
}
var toRemove = keys.filter(function (k) {
return k.indexOf(parsed.hash) === 0;
});
if (!toRemove.length) {
cb();
return;
}
2016-08-30 16:09:53 +00:00
getStore(legacy).removeBatch(toRemove, function (err, data) {
cb(err, data);
});
});
2016-08-30 16:09:53 +00:00
}, legacy);
}, legacy);
};
2016-08-30 16:09:53 +00:00
// STORAGE
var rememberPad = common.rememberPad = window.rememberPad = function (title, cb) {
// bail out early
if (!/#/.test(window.location.hash)) { return; }
getRecentPads(function (err, pads) {
if (err) {
cb(err);
return;
}
2016-08-25 09:19:09 +00:00
var now = ''+new Date();
var href = window.location.href;
var parsed = parsePadUrl(window.location.href);
var isUpdate = false;
var out = pads.map(function (pad) {
var p = parsePadUrl(pad.href);
if (p.hash === parsed.hash && p.type === parsed.type) {
isUpdate = true;
// bump the atime
pad.atime = now;
pad.title = title;
pad.href = href;
}
return pad;
});
if (!isUpdate) {
// href, ctime, atime, title
out.push(makePad(href, title));
}
setRecentPads(out, function (err, data) {
cb(err, data);
});
});
};
2016-08-30 16:09:53 +00:00
// STORAGE
var setPadTitle = common.setPadTitle = function (name, cb) {
var href = window.location.href;
var parsed = parsePadUrl(href);
getRecentPads(function (err, recent) {
if (err) {
cb(err);
return;
}
var contains;
var renamed = recent.map(function (pad) {
var p = parsePadUrl(pad.href);
if (p.hash === parsed.hash && p.type === parsed.type) {
contains = true;
// update the atime
pad.atime = new Date().toISOString();
// set the name
pad.title = name;
pad.href = href;
}
return pad;
});
if (!contains) {
renamed.push(makePad(href, name));
}
setRecentPads(renamed, function (err, data) {
cb(err, data);
});
});
};
2016-08-30 16:09:53 +00:00
// STORAGE
var getPadTitle = common.getPadTitle = function (cb) {
var href = window.location.href;
var parsed = parsePadUrl(window.location.href);
var hashSlice = window.location.hash.slice(1,9);
var title = '';
getRecentPads(function (err, pads) {
if (err) {
cb(err);
return;
}
pads.some(function (pad) {
var p = parsePadUrl(pad.href);
if (p.hash === parsed.hash && p.type === parsed.type) {
title = pad.title || hashSlice;
return true;
}
});
2016-09-13 10:24:06 +00:00
if (title === '') { title = getDefaultName(parsed, pads); }
cb(void 0, title);
});
2016-07-11 15:36:53 +00:00
};
2016-08-30 16:09:53 +00:00
// STORAGE
var causesNamingConflict = common.causesNamingConflict = function (title, cb) {
var href = window.location.href;
var parsed = parsePadUrl(href);
getRecentPads(function (err, pads) {
if (err) {
cb(err);
return;
}
var conflicts = pads.some(function (pad) {
// another pad is already using that title
if (pad.title === title) {
2016-09-13 10:24:06 +00:00
var p = parsePadUrl(pad.href);
if (p.type === parsed.type && p.hash === parsed.hash) {
// the duplicate pad has the same type and hash
// allow renames
} else {
// it's an entirely different pad... it conflicts
return true;
}
}
});
cb(void 0, conflicts);
});
};
// local name?
common.ready = function (f) {
var state = 0;
var env = {};
var cb = function () {
f(void 0, env);
};
Store.ready(function (err, store) {
2016-08-30 16:09:53 +00:00
common.store = env.store = store;
cb();
return;
/*
authorize(function (err, proxy) {
/*
TODO
listen for log(in|out) events
update information accordingly
* /
store.change(function (data) {
if (data.key === User.localKey) {
// HERE
if (!data.newValue) {
deauthorize(function (err) {
console.log("Deauthorized!!");
});
} else {
authorize(function (err, proxy) {
if (err) {
// not logged in
}
if (!proxy) {
userProxy = proxy;
userStore = User.prepareStore(proxy);
}
});
}
}
});
if (err) {
// not logged in
}
if (!proxy) {
cb();
return;
}
userProxy = env.proxy = proxy;
userStore = env.userStore = User.prepareStore(proxy);
2016-08-30 16:09:53 +00:00
cb();
}); */
});
};
2016-08-30 16:09:53 +00:00
/*
* Saving files
*/
var fixFileName = common.fixFileName = function (filename) {
2016-08-19 08:47:07 +00:00
return filename.replace(/ /g, '-').replace(/[\/\?]/g, '_')
.replace(/_+/g, '_');
};
var importContent = common.importContent = function (type, f) {
return function () {
2016-06-23 14:44:20 +00:00
var $files = $('<input type="file">').click();
$files.on('change', function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (e) { f(e.target.result, file); };
reader.readAsText(file, type);
});
};
};
2016-09-27 16:33:03 +00:00
/*
* Buttons
*/
var createButton = common.createButton = function (type, rightside) {
var button;
var size = "17px";
switch (type) {
case 'export':
button = $('<button>', {
title: Messages.exportButtonTitle,
'class': "fa fa-download",
style: 'font:'+size+' FontAwesome'
});
break;
case 'import':
button = $('<button>', {
title: Messages.importButtonTitle,
'class': "fa fa-upload",
style: 'font:'+size+' FontAwesome'
});
break;
case 'rename':
button = $('<button>', {
id: 'name-pad',
title: Messages.renameButtonTitle,
'class': "fa fa-bookmark cryptpad-rename",
style: 'font:'+size+' FontAwesome'
});
break;
case 'forget':
button = $('<button>', {
id: 'cryptpad-forget',
title: Messages.forgetButtonTitle,
'class': "fa fa-trash cryptpad-forget",
style: 'font:'+size+' FontAwesome'
});
break;
case 'username':
button = $('<button>', {
title: Messages.changeNameButton,
'class': "fa fa-user",
style: 'font:'+size+' FontAwesome'
});
break;
case 'readonly':
button = $('<button>', {
title: Messages.getViewButtonTitle,
'class': "fa fa-eye",
style: 'font:'+size+' FontAwesome'
});
break;
default:
button = $('<button>', {
'class': "fa fa-question",
style: 'font:'+size+' FontAwesome'
});
}
if (rightside) {
button.addClass('rightside-button')
}
return button;
};
2016-08-30 16:09:53 +00:00
/*
* Alertifyjs
*/
2016-07-06 20:20:15 +00:00
var styleAlerts = common.styleAlerts = function (href) {
var $link = $('link[href="/customize/alertify.css"]');
if ($link.length) { return; }
2016-07-06 20:20:15 +00:00
href = href || '/customize/alertify.css';
$('head').append($('<link>', {
rel: 'stylesheet',
id: 'alertifyCSS',
href: href,
}));
};
var findCancelButton = common.findCancelButton = function () {
return $('button.cancel');
};
var findOKButton = common.findOKButton = function () {
return $('button.ok');
};
var listenForKeys = function (yes, no) {
var handler = function (e) {
switch (e.which) {
case 27: // cancel
if (typeof(no) === 'function') { no(e); }
no();
break;
case 13: // enter
if (typeof(yes) === 'function') { yes(e); }
break;
}
};
$(window).keyup(handler);
return handler;
};
var stopListening = function (handler) {
$(window).off('keyup', handler);
};
2016-07-06 20:20:15 +00:00
common.alert = function (msg, cb) {
cb = cb || function () {};
var keyHandler = listenForKeys(function (e) { // yes
findOKButton().click();
});
Alertify.alert(msg, function (ev) {
cb(ev);
stopListening(keyHandler);
});
2016-07-06 20:20:15 +00:00
};
common.prompt = function (msg, def, cb, opt) {
opt = opt || {};
cb = cb || function () {};
var keyHandler = listenForKeys(function (e) { // yes
findOKButton().click();
}, function (e) { // no
findCancelButton().click();
});
2016-07-06 20:20:15 +00:00
Alertify
.defaultValue(def || '')
2016-07-12 14:43:33 +00:00
.okBtn(opt.ok || Messages.okButton || 'OK')
.cancelBtn(opt.cancel || Messages.cancelButton || 'Cancel')
2016-07-06 20:20:15 +00:00
.prompt(msg, function (val, ev) {
cb(val, ev);
stopListening(keyHandler);
2016-07-06 20:20:15 +00:00
}, function (ev) {
cb(null, ev);
stopListening(keyHandler);
2016-07-06 20:20:15 +00:00
});
};
common.confirm = function (msg, cb, opt) {
opt = opt || {};
cb = cb || function () {};
var keyHandler = listenForKeys(function (e) {
findOKButton().click();
}, function (e) {
findCancelButton().click();
});
2016-07-06 20:20:15 +00:00
Alertify
2016-07-12 14:43:33 +00:00
.okBtn(opt.ok || Messages.okButton || 'OK')
.cancelBtn(opt.cancel || Messages.cancelButton || 'Cancel')
2016-07-06 20:20:15 +00:00
.confirm(msg, function () {
cb(true);
stopListening(keyHandler);
2016-07-06 20:20:15 +00:00
}, function () {
cb(false);
stopListening(keyHandler);
2016-07-06 20:20:15 +00:00
});
};
common.log = function (msg) {
Alertify.success(msg);
};
common.warn = function (msg) {
Alertify.error(msg);
};
2016-08-30 16:09:53 +00:00
/*
* spinner
*/
2016-08-02 16:56:35 +00:00
common.spinner = function (parent) {
var $target = $('<div>', {
//
}).hide();
$(parent).append($target);
var opts = {
lines: 9, // The number of lines to draw
length: 12, // The length of each line
width: 11, // The line thickness
radius: 20, // The radius of the inner circle
scale: 2, // Scales overall size of the spinner
corners: 1, // Corner roundness (0..1)
color: '#777', // #rgb or #rrggbb or array of colors
opacity: 0.3, // Opacity of the lines
rotate: 31, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
speed: 0.9, // Rounds per second
trail: 49, // Afterglow percentage
fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
zIndex: 2e9, // The z-index (defaults to 2000000000)
className: 'spinner', // The CSS class to assign to the spinner
top: '50%', // Top position relative to parent
left: '50%', // Left position relative to parent
shadow: false, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
position: 'absolute', // Element positioning
2016-08-03 15:03:50 +00:00
};
2016-08-02 16:56:35 +00:00
var spinner = new Spinner(opts).spin($target[0]);
return {
show: function () {
$target.show();
return this;
},
hide: function () {
$target.hide();
return this;
},
get: function () {
return spinner;
},
};
};
2016-09-15 16:35:09 +00:00
Messages._applyTranslation();
2016-05-28 11:13:54 +00:00
return common;
});