cryptpad/www/common/sframe-common-outer.js

1514 lines
67 KiB
JavaScript
Raw Normal View History

2017-08-30 09:10:57 +00:00
// Load #1, load as little as possible because we are in a race to get the loading screen up.
define([
'/bower_components/nthen/index.js',
'/api/config',
'jquery',
], function (nThen, ApiConfig, $) {
var common = {};
2017-09-12 16:40:11 +00:00
common.start = function (cfg) {
cfg = cfg || {};
var realtime = !cfg.noRealtime;
2017-08-30 09:10:57 +00:00
var secret;
var hashes;
2017-12-07 17:51:50 +00:00
var isNewFile;
2017-08-30 09:10:57 +00:00
var CpNfOuter;
var Cryptpad;
var Crypto;
var Cryptget;
var SFrameChannel;
2017-08-30 09:10:57 +00:00
var sframeChan;
var FilePicker;
2019-05-29 17:00:20 +00:00
var Share;
var Messaging;
var Notifier;
2018-10-18 16:50:38 +00:00
var Utils = {
nThen: nThen
};
2017-12-07 17:51:50 +00:00
var AppConfig;
2017-12-14 10:34:44 +00:00
var Test;
var password;
2018-04-27 09:54:23 +00:00
var initialPathInDrive;
2017-08-30 09:10:57 +00:00
2020-01-27 12:53:54 +00:00
var currentPad = window.CryptPad_location = {
2020-01-27 11:18:25 +00:00
href: cfg.href || window.location.href,
hash: cfg.hash || window.location.hash
};
2017-08-30 09:10:57 +00:00
nThen(function (waitFor) {
// Load #2, the loading screen is up so grab whatever you need...
require([
'/common/sframe-chainpad-netflux-outer.js',
'/common/cryptpad-common.js',
'/bower_components/chainpad-crypto/crypto.js',
'/common/cryptget.js',
'/common/outer/worker-channel.js',
'/filepicker/main.js',
2019-05-29 17:00:20 +00:00
'/share/main.js',
'/common/common-messaging.js',
'/common/common-notifier.js',
2017-11-13 15:32:40 +00:00
'/common/common-hash.js',
'/common/common-util.js',
'/common/common-realtime.js',
2017-11-23 11:28:49 +00:00
'/common/common-constants.js',
'/common/common-feedback.js',
'/common/outer/local-store.js',
2017-12-07 17:51:50 +00:00
'/customize/application_config.js',
2017-12-14 10:34:44 +00:00
'/common/test.js',
'/common/userObject.js',
], waitFor(function (_CpNfOuter, _Cryptpad, _Crypto, _Cryptget, _SFrameChannel,
2019-05-29 17:00:20 +00:00
_FilePicker, _Share, _Messaging, _Notifier, _Hash, _Util, _Realtime,
_Constants, _Feedback, _LocalStore, _AppConfig, _Test, _UserObject) {
2017-08-30 09:10:57 +00:00
CpNfOuter = _CpNfOuter;
Cryptpad = _Cryptpad;
Crypto = Utils.Crypto = _Crypto;
2017-08-30 09:10:57 +00:00
Cryptget = _Cryptget;
SFrameChannel = _SFrameChannel;
FilePicker = _FilePicker;
2019-05-29 17:00:20 +00:00
Share = _Share;
Messaging = _Messaging;
Notifier = _Notifier;
2017-11-13 15:32:40 +00:00
Utils.Hash = _Hash;
Utils.Util = _Util;
Utils.Realtime = _Realtime;
2017-11-23 11:28:49 +00:00
Utils.Constants = _Constants;
Utils.Feedback = _Feedback;
Utils.LocalStore = _LocalStore;
Utils.UserObject = _UserObject;
2017-12-07 17:51:50 +00:00
AppConfig = _AppConfig;
2017-12-14 10:34:44 +00:00
Test = _Test;
if (localStorage.CRYPTPAD_URLARGS !== ApiConfig.requireConf.urlArgs) {
console.log("New version, flushing cache");
Object.keys(localStorage).forEach(function (k) {
if (k.indexOf('CRYPTPAD_CACHE|') !== 0) { return; }
delete localStorage[k];
});
localStorage.CRYPTPAD_URLARGS = ApiConfig.requireConf.urlArgs;
}
var cache = window.cpCache = {};
var localStore = window.localStore = {};
Object.keys(localStorage).forEach(function (k) {
2017-09-21 15:56:24 +00:00
if (k.indexOf('CRYPTPAD_CACHE|') === 0) {
cache[k.slice(('CRYPTPAD_CACHE|').length)] = localStorage[k];
return;
}
if (k.indexOf('CRYPTPAD_STORE|') === 0) {
localStore[k.slice(('CRYPTPAD_STORE|').length)] = localStorage[k];
return;
}
});
// The inner iframe tries to get some data from us every ms (cache, store...).
// It will send a "READY" message and wait for our answer with the correct txid.
// First, we have to answer to this message, otherwise we're going to block
// sframe-boot.js. Then we can start the channel.
var msgEv = _Util.mkEvent();
var iframe = $('#sbox-iframe')[0].contentWindow;
var postMsg = function (data) {
iframe.postMessage(data, '*');
};
var whenReady = waitFor(function (msg) {
if (msg.source !== iframe) { return; }
var data = JSON.parse(msg.data);
if (!data.txid) { return; }
// Remove the listener once we've received the READY message
window.removeEventListener('message', whenReady);
// Answer with the requested data
postMsg(JSON.stringify({ txid: data.txid, cache: cache, localStore: localStore, language: Cryptpad.getLanguage() }));
// Then start the channel
window.addEventListener('message', function (msg) {
if (msg.source !== iframe) { return; }
msgEv.fire(msg);
});
SFrameChannel.create(msgEv, postMsg, waitFor(function (sfc) {
2019-10-21 13:22:59 +00:00
Utils.sframeChan = sframeChan = sfc;
}));
});
window.addEventListener('message', whenReady);
Cryptpad.loading.onDriveEvent.reg(function (data) {
if (sframeChan) { sframeChan.event('EV_LOADING_INFO', data); }
});
Cryptpad.ready(waitFor(function () {
if (sframeChan) {
sframeChan.event('EV_LOADING_INFO', {
state: -1
});
}
}), {
2020-01-27 11:18:25 +00:00
driveEvents: cfg.driveEvents,
currentPad: currentPad
2017-12-01 13:49:21 +00:00
});
if (window.history && window.history.replaceState && currentPad.hash) {
var nHash = currentPad.hash;
if (!/^#/.test(nHash)) { nHash = '#' + nHash; }
window.history.replaceState({}, window.document.title, nHash);
}
2017-08-30 09:10:57 +00:00
}));
}).nThen(function (waitFor) {
if (!Utils.Hash.isValidHref(window.location.href)) {
waitFor.abort();
return void sframeChan.event('EV_LOADING_ERROR', 'INVALID_HASH');
}
2017-10-03 12:11:11 +00:00
$('#sbox-iframe').focus();
sframeChan.on('EV_CACHE_PUT', function (x) {
Object.keys(x).forEach(function (k) {
localStorage['CRYPTPAD_CACHE|' + k] = x[k];
});
});
2017-09-21 15:56:24 +00:00
sframeChan.on('EV_LOCALSTORE_PUT', function (x) {
Object.keys(x).forEach(function (k) {
if (typeof(x[k]) === "undefined") {
delete localStorage['CRYPTPAD_STORE|' + k];
return;
}
localStorage['CRYPTPAD_STORE|' + k] = x[k];
});
});
2017-11-30 09:33:09 +00:00
if (cfg.getSecrets) {
2017-11-30 17:22:26 +00:00
var w = waitFor();
2018-04-27 15:23:23 +00:00
// No password for drive, profile and todo
2017-11-30 09:33:09 +00:00
cfg.getSecrets(Cryptpad, Utils, waitFor(function (err, s) {
secret = Utils.secret = s;
2017-11-30 17:22:26 +00:00
Cryptpad.getShareHashes(secret, function (err, h) {
hashes = h;
w();
});
2017-11-30 09:33:09 +00:00
}));
} else {
2020-01-27 11:18:25 +00:00
var parsed = Utils.Hash.parsePadUrl(currentPad.href);
var todo = function () {
2020-01-27 11:18:25 +00:00
secret = Utils.secret = Utils.Hash.getSecrets(parsed.type, parsed.hash, password);
Cryptpad.getShareHashes(secret, waitFor(function (err, h) {
hashes = h;
2020-01-29 16:40:16 +00:00
// Update the rendered hash and the full hash with the "password" settings
if (password && !parsed.hashData.password) {
2020-01-29 16:40:16 +00:00
var opts = parsed.getOptions();
opts.password = true;
// Full hash
currentPad.href = parsed.getUrl(opts);
if (parsed.hashData) {
currentPad.hash = parsed.hashData.getHash(opts);
}
// Rendered (maybe hidden) hash
var renderedParsed = Utils.Hash.parsePadUrl(window.location.href);
var ohc = window.onhashchange;
window.onhashchange = function () {};
2020-01-29 16:40:16 +00:00
window.location.href = renderedParsed.getUrl(opts);
window.onhashchange = ohc;
ohc({reset: true});
}
}));
};
if (!parsed.hashData) { // No hash, no need to check for a password
return void todo();
}
// We now need to check if there is a password and if we know the correct password.
// We'll use getFileSize and isNewChannel to detect incorrect passwords.
// First we'll get the password value from our drive (getPadAttribute), and we'll check
// if the channel is valid. If the pad is not stored in our drive, we'll test with an
// empty password instead.
// If this initial check returns a valid channel, open the pad.
// If the channel is invalid:
// Option 1: this is a password-protected pad not stored in our drive --> password prompt
// Option 2: this is a pad stored in our drive
// 2a: 'edit' pad or file --> password-prompt
// 2b: 'view' pad no '/p/' --> the seed is incorrect
// 2c: 'view' pad and '/p/' and a wrong password stored --> the seed is incorrect
// 2d: 'view' pad and '/p/' and password never stored (security feature) --> password-prompt
var askPassword = function (wrongPasswordStored, cfg) {
2019-10-22 13:22:43 +00:00
// Ask for the password and check if the pad exists
// If the pad doesn't exist, it means the password isn't correct
// or the pad has been deleted
var correctPassword = waitFor();
sframeChan.on('Q_PAD_PASSWORD_VALUE', function (data, cb) {
password = data;
var next = function (e, isNew) {
if (Boolean(isNew)) {
// Ask again in the inner iframe
// We should receive a new Q_PAD_PASSWORD_VALUE
cb(false);
} else {
todo();
if (wrongPasswordStored) {
// Store the correct password
nThen(function (w) {
Cryptpad.setPadAttribute('password', password, w(), parsed.getUrl());
Cryptpad.setPadAttribute('channel', secret.channel, w(), parsed.getUrl());
if (parsed.hashData.mode === 'edit') {
var href = window.location.pathname + '#' + Utils.Hash.getEditHashFromKeys(secret);
Cryptpad.setPadAttribute('href', href, w(), parsed.getUrl());
var roHref = window.location.pathname + '#' + Utils.Hash.getViewHashFromKeys(secret);
Cryptpad.setPadAttribute('roHref', roHref, w(), parsed.getUrl());
}
}).nThen(correctPassword);
} else {
2019-10-22 13:22:43 +00:00
correctPassword();
}
2019-10-22 13:22:43 +00:00
cb(true);
}
2019-10-22 13:22:43 +00:00
};
if (parsed.type === "file") {
// `isNewChannel` doesn't work for files (not a channel)
// `getFileSize` is not adapted to channels because of metadata
2020-01-27 11:18:25 +00:00
Cryptpad.getFileSize(currentPad.href, password, function (e, size) {
2019-10-22 13:22:43 +00:00
next(e, size === 0);
});
return;
}
// Not a file, so we can use `isNewChannel`
2020-01-27 11:18:25 +00:00
Cryptpad.isNewChannel(currentPad.href, password, next);
2019-10-22 13:22:43 +00:00
});
sframeChan.event("EV_PAD_PASSWORD", cfg);
2019-10-22 13:22:43 +00:00
};
2019-10-22 13:22:43 +00:00
var done = waitFor();
var stored = false;
var passwordCfg = {
value: ''
};
2020-01-27 11:18:25 +00:00
// Hidden hash: can't find the channel in our drives: abort
var noPadData = function (err) {
sframeChan.event("EV_PAD_NODATA", err);
2020-01-27 11:18:25 +00:00
};
var newHref;
2019-10-22 13:22:43 +00:00
nThen(function (w) {
2020-01-27 11:18:25 +00:00
if (!parsed.hashData.key && parsed.hashData.channel) {
2020-01-28 09:46:26 +00:00
var edit = parsed.hashData.mode === 'edit';
2020-01-27 11:18:25 +00:00
Cryptpad.getPadDataFromChannel({
channel: parsed.hashData.channel,
2020-01-28 09:46:26 +00:00
edit: edit,
2020-01-27 14:45:57 +00:00
file: parsed.hashData.type === 'file'
2020-01-27 11:18:25 +00:00
}, w(function (err, res) {
// Error while getting data? abort
if (err || !res || res.error) {
w.abort();
return void noPadData(err || (!res ? 'EINVAL' : res.error));
}
// No data found? abort
if (!Object.keys(res).length) {
w.abort();
return void noPadData('NO_RESULT');
}
// Data found but weaker? warn
2020-01-28 09:46:26 +00:00
if (edit && !res.href) {
2020-01-29 16:40:16 +00:00
newHref = res.roHref;
2020-01-27 11:18:25 +00:00
}
// We have good data, keep the hash in memory
2020-01-28 09:46:26 +00:00
newHref = edit ? res.href : (res.roHref || res.href);
2020-01-27 11:18:25 +00:00
}));
}
}).nThen(function (w) {
if (newHref) {
// Get the options (embed, present, etc.) of the hidden hash
// Use the same options in the full hash
var opts = parsed.getOptions();
parsed = Utils.Hash.parsePadUrl(newHref);
currentPad.href = parsed.getUrl(opts);
currentPad.hash = parsed.hashData && parsed.hashData.getHash(opts);
}
2019-10-22 13:22:43 +00:00
Cryptpad.getPadAttribute('title', w(function (err, data) {
stored = (!err && typeof (data) === "string");
}));
Cryptpad.getPadAttribute('password', w(function (err, val) {
password = val;
}), parsed.getUrl());
}).nThen(function (w) {
if (!password && !stored && sessionStorage.newPadPassword) {
passwordCfg.value = sessionStorage.newPadPassword;
delete sessionStorage.newPadPassword;
}
2019-10-22 10:04:30 +00:00
if (parsed.type === "file") {
// `isNewChannel` doesn't work for files (not a channel)
// `getFileSize` is not adapted to channels because of metadata
2020-01-27 11:18:25 +00:00
Cryptpad.getFileSize(currentPad.href, password, w(function (e, size) {
2019-10-22 10:04:30 +00:00
if (size !== 0) { return void todo(); }
// Wrong password or deleted file?
askPassword(true, passwordCfg);
2019-10-22 10:04:30 +00:00
}));
return;
}
// Not a file, so we can use `isNewChannel`
2020-01-27 11:18:25 +00:00
Cryptpad.isNewChannel(currentPad.href, password, w(function(e, isNew) {
2019-10-22 10:04:30 +00:00
if (!isNew) { return void todo(); }
2019-10-22 13:22:43 +00:00
if (parsed.hashData.mode === 'view' && (password || !parsed.hashData.password)) {
// Error, wrong password stored, the view seed has changed with the password
// password will never work
sframeChan.event("EV_PAD_PASSWORD_ERROR");
waitFor.abort();
return;
}
2019-10-22 13:22:43 +00:00
if (!stored && !parsed.hashData.password) {
// We've received a link without /p/ and it doesn't work without a password: abort
return void todo();
}
// Wrong password or deleted file?
askPassword(true, passwordCfg);
}));
2019-10-22 13:22:43 +00:00
}).nThen(done);
2017-08-30 09:10:57 +00:00
}
2018-10-05 16:06:11 +00:00
}).nThen(function (waitFor) {
if (cfg.afterSecrets) {
cfg.afterSecrets(Cryptpad, Utils, secret, waitFor());
}
2017-12-07 17:51:50 +00:00
}).nThen(function (waitFor) {
// Check if the pad exists on server
2020-01-27 11:18:25 +00:00
if (!currentPad.hash) { isNewFile = true; return; }
if (realtime) {
2020-01-27 11:18:25 +00:00
// TODO we probably don't need to check again for password-protected pads
// (we use isNewChannel to test the password...)
Cryptpad.isNewChannel(currentPad.href, password, waitFor(function (e, isNew) {
if (e) { return console.error(e); }
isNewFile = Boolean(isNew);
}));
}
2017-08-30 09:10:57 +00:00
}).nThen(function () {
var readOnly = secret.keys && !secret.keys.editKeyStr;
2017-12-12 11:06:31 +00:00
var isNewHash = true;
if (!secret.keys) {
isNewHash = false;
secret.keys = secret.key;
2017-12-12 13:45:25 +00:00
readOnly = false;
2017-12-12 11:06:31 +00:00
}
Utils.crypto = Utils.Crypto.createEncryptor(Utils.secret.keys);
2020-01-27 11:18:25 +00:00
var parsed = Utils.Hash.parsePadUrl(currentPad.href);
2020-01-09 16:30:15 +00:00
var burnAfterReading = parsed && parsed.hashData && parsed.hashData.ownerKey;
2017-08-30 09:10:57 +00:00
if (!parsed.type) { throw new Error(); }
var defaultTitle = Utils.UserObject.getDefaultName(parsed);
var edPublic, curvePublic, notifications, isTemplate;
var settings = {};
2018-01-12 08:48:40 +00:00
var forceCreationScreen = cfg.useCreationScreen &&
sessionStorage[Utils.Constants.displayPadCreationScreen];
delete sessionStorage[Utils.Constants.displayPadCreationScreen];
2017-08-30 09:10:57 +00:00
var updateMeta = function () {
//console.log('EV_METADATA_UPDATE');
2019-07-18 15:18:36 +00:00
var metaObj;
2017-08-30 09:10:57 +00:00
nThen(function (waitFor) {
2017-11-30 09:33:09 +00:00
Cryptpad.getMetadata(waitFor(function (err, m) {
if (err) { console.log(err); }
metaObj = m;
2017-12-07 17:51:50 +00:00
edPublic = metaObj.priv.edPublic; // needed to create an owned pad
curvePublic = metaObj.user.curvePublic;
notifications = metaObj.user.notifications;
settings = metaObj.priv.settings;
2017-11-30 09:33:09 +00:00
}));
2019-07-18 15:18:36 +00:00
if (typeof(isTemplate) === "undefined") {
2020-01-27 11:18:25 +00:00
Cryptpad.isTemplate(currentPad.href, waitFor(function (err, t) {
2019-07-18 15:18:36 +00:00
if (err) { console.log(err); }
isTemplate = t;
}));
}
2017-08-30 09:10:57 +00:00
}).nThen(function (/*waitFor*/) {
2017-11-30 14:01:17 +00:00
metaObj.doc = {
2017-11-30 09:33:09 +00:00
defaultTitle: defaultTitle,
type: cfg.type || parsed.type
2017-11-30 09:33:09 +00:00
};
var additionalPriv = {
2019-05-29 17:00:20 +00:00
app: parsed.type,
2017-11-30 09:33:09 +00:00
accountName: Utils.LocalStore.getAccountName(),
origin: window.location.origin,
pathname: window.location.pathname,
fileHost: ApiConfig.fileHost,
readOnly: readOnly,
isTemplate: isTemplate,
feedbackAllowed: Utils.Feedback.state,
isPresent: parsed.hashData && parsed.hashData.present,
isEmbed: parsed.hashData && parsed.hashData.embed,
accounts: {
donateURL: Cryptpad.donateURL,
upgradeURL: Cryptpad.upgradeURL
2017-12-07 17:51:50 +00:00
},
2017-12-11 11:19:44 +00:00
isNewFile: isNewFile,
2020-01-27 11:18:25 +00:00
isDeleted: isNewFile && currentPad.hash.length > 0,
forceCreationScreen: forceCreationScreen,
2018-04-27 15:23:23 +00:00
password: password,
channel: secret.channel,
2019-01-04 14:10:13 +00:00
enableSF: localStorage.CryptPad_SF === "1", // TODO to remove when enabled by default
2019-01-31 14:27:01 +00:00
devMode: localStorage.CryptPad_dev === "1",
fromFileData: Cryptpad.fromFileData ? {
title: Cryptpad.fromFileData.title
} : undefined,
2020-01-09 16:30:15 +00:00
burnAfterReading: burnAfterReading,
2019-09-12 15:54:50 +00:00
storeInTeam: Cryptpad.initialTeam || (Cryptpad.initialPath ? -1 : undefined)
2017-09-12 16:40:11 +00:00
};
if (window.CryptPad_newSharedFolder) {
additionalPriv.newSharedFolder = window.CryptPad_newSharedFolder;
}
if (Utils.Constants.criticalApps.indexOf(parsed.type) === -1 &&
AppConfig.availablePadTypes.indexOf(parsed.type) === -1) {
additionalPriv.disabledApp = true;
}
if (!Utils.LocalStore.isLoggedIn() &&
2019-01-09 11:15:08 +00:00
AppConfig.registeredOnlyTypes.indexOf(parsed.type) !== -1 &&
parsed.type !== "file") {
additionalPriv.registeredOnly = true;
}
2019-05-29 17:00:20 +00:00
if (['debug', 'profile'].indexOf(parsed.type) !== -1) {
additionalPriv.hashes = hashes;
}
2017-11-30 09:33:09 +00:00
for (var k in additionalPriv) { metaObj.priv[k] = additionalPriv[k]; }
2017-09-12 16:40:11 +00:00
if (cfg.addData) {
cfg.addData(metaObj.priv, Cryptpad, metaObj.user);
2017-09-12 16:40:11 +00:00
}
2017-11-30 16:21:58 +00:00
2017-09-12 16:40:11 +00:00
sframeChan.event('EV_METADATA_UPDATE', metaObj);
2017-08-30 09:10:57 +00:00
});
};
2017-11-30 09:33:09 +00:00
Cryptpad.onMetadataChanged(updateMeta);
2017-08-30 09:10:57 +00:00
sframeChan.onReg('EV_METADATA_UPDATE', updateMeta);
2017-11-23 11:28:49 +00:00
Utils.LocalStore.onLogout(function () {
sframeChan.event('EV_LOGOUT');
});
2017-12-14 10:34:44 +00:00
Test.registerOuter(sframeChan);
2018-06-11 14:52:26 +00:00
Cryptpad.onNewVersionReconnect.reg(function () {
sframeChan.event("EV_NEW_VERSION");
});
// Put in the following function the RPC queries that should also work in filepicker
var addCommonRpc = function (sframeChan) {
sframeChan.on('Q_ANON_RPC_MESSAGE', function (data, cb) {
Cryptpad.anonRpcMsg(data.msg, data.content, function (err, response) {
cb({error: err, response: response});
});
});
sframeChan.on('Q_GET_PINNED_USAGE', function (data, cb) {
Cryptpad.getPinnedUsage({}, function (e, used) {
cb({
error: e,
quota: used
});
});
});
sframeChan.on('Q_GET_PIN_LIMIT_STATUS', function (data, cb) {
2019-09-23 13:45:24 +00:00
Cryptpad.isOverPinLimit(null, function (e, overLimit, limits) {
cb({
error: e,
overLimit: overLimit,
limits: limits
});
});
});
sframeChan.on('Q_THUMBNAIL_GET', function (data, cb) {
2017-11-23 11:28:49 +00:00
Utils.LocalStore.getThumbnail(data.key, function (e, data) {
cb({
error: e,
data: data
});
});
});
sframeChan.on('Q_THUMBNAIL_SET', function (data, cb) {
2017-11-23 11:28:49 +00:00
Utils.LocalStore.setThumbnail(data.key, data.value, function (e) {
cb({error:e});
});
2017-08-30 09:10:57 +00:00
});
2019-05-29 17:00:20 +00:00
sframeChan.on('Q_GET_ATTRIBUTE', function (data, cb) {
Cryptpad.getAttribute(data.key, function (e, data) {
cb({
error: e,
data: data
});
});
});
sframeChan.on('Q_SET_ATTRIBUTE', function (data, cb) {
Cryptpad.setAttribute(data.key, data.value, function (e) {
cb({error:e});
});
});
Cryptpad.mailbox.onEvent.reg(function (data, cb) {
sframeChan.query('EV_MAILBOX_EVENT', data, function (err, obj) {
if (!cb) { return; }
if (err) { return void cb({error: err}); }
cb(obj);
});
});
sframeChan.on('Q_MAILBOX_COMMAND', function (data, cb) {
Cryptpad.mailbox.execCommand(data, cb);
});
sframeChan.on('Q_SET_LOGIN_REDIRECT', function (data, cb) {
2020-01-27 11:18:25 +00:00
sessionStorage.redirectTo = currentPad.href;
cb();
});
2019-10-14 10:01:44 +00:00
sframeChan.on('Q_STORE_IN_TEAM', function (data, cb) {
Cryptpad.storeInTeam(data, cb);
});
sframeChan.on('EV_GOTO_URL', function (url) {
if (url) {
window.location.href = url;
} else {
window.location.reload();
}
});
sframeChan.on('EV_OPEN_URL', function (url) {
if (url) {
window.open(url);
}
});
sframeChan.on('Q_GET_PAD_METADATA', function (data, cb) {
if (!data || !data.channel) {
data = {
channel: secret.channel
};
}
Cryptpad.getPadMetadata(data, cb);
});
sframeChan.on('Q_SET_PAD_METADATA', function (data, cb) {
Cryptpad.setPadMetadata(data, cb);
});
2020-01-21 10:01:07 +00:00
sframeChan.on('Q_GET_PAD_ATTRIBUTE', function (data, cb) {
var href;
if (readOnly && hashes.editHash) {
// If we have a stronger hash, use it for pad attributes
href = window.location.pathname + '#' + hashes.editHash;
}
if (data.href) { href = data.href; }
Cryptpad.getPadAttribute(data.key, function (e, data) {
cb({
error: e,
data: data
});
}, href);
});
sframeChan.on('Q_SET_PAD_ATTRIBUTE', function (data, cb) {
var href;
if (readOnly && hashes.editHash) {
// If we have a stronger hash, use it for pad attributes
href = window.location.pathname + '#' + hashes.editHash;
}
if (data.href) { href = data.href; }
Cryptpad.setPadAttribute(data.key, data.value, function (e) {
cb({error:e});
}, href);
});
};
addCommonRpc(sframeChan);
2017-08-30 09:10:57 +00:00
var currentTitle;
var currentTabTitle;
var setDocumentTitle = function () {
if (!currentTabTitle) {
document.title = currentTitle || 'CryptPad';
return;
}
var title = currentTabTitle.replace(/\{title\}/g, currentTitle || 'CryptPad');
document.title = title;
};
2018-06-11 08:33:35 +00:00
sframeChan.on('Q_SET_PAD_TITLE_IN_DRIVE', function (newData, cb) {
var newTitle = newData.title || newData.defaultTitle;
currentTitle = newTitle;
setDocumentTitle();
2018-04-27 09:54:23 +00:00
var data = {
password: password,
title: newTitle,
channel: secret.channel,
2018-04-27 09:54:23 +00:00
path: initialPathInDrive // Where to store the pad if we don't have it in our drive
};
2020-01-27 11:18:25 +00:00
Cryptpad.setPadTitle(data, function (err, obj) {
if (!err && !(obj && obj.notStored)) {
// No error and the pad was correctly stored
// hide the hash
2020-01-27 11:18:25 +00:00
var opts = parsed.getOptions();
var hash = Utils.Hash.getHiddenHashFromKeys(parsed.type, secret, opts);
var useUnsafe = Utils.Util.find(settings, ['security', 'unsafeLinks']);
if (!useUnsafe && window.history && window.history.replaceState) {
2020-01-27 11:18:25 +00:00
if (!/^#/.test(hash)) { hash = '#' + hash; }
window.history.replaceState({}, window.document.title, hash);
}
}
2019-11-07 10:54:58 +00:00
cb({error: err});
2017-08-30 09:10:57 +00:00
});
});
sframeChan.on('EV_SET_TAB_TITLE', function (newTabTitle) {
currentTabTitle = newTabTitle;
setDocumentTitle();
});
2019-03-27 16:00:28 +00:00
sframeChan.on('EV_SET_HASH', function (hash) {
2020-01-27 11:18:25 +00:00
// In this case, we want to set the hash for the next page reload
// This hash is a category for the sidebar layout apps
// No need to store it in memory
2019-03-27 16:00:28 +00:00
window.location.hash = hash;
});
2018-08-27 12:58:09 +00:00
Cryptpad.autoStore.onStoreRequest.reg(function (data) {
sframeChan.event("EV_AUTOSTORE_DISPLAY_POPUP", data);
});
sframeChan.on('Q_AUTOSTORE_STORE', function (obj, cb) {
var data = {
password: password,
title: currentTitle,
channel: secret.channel,
path: initialPathInDrive, // Where to store the pad if we don't have it in our drive
forceSave: true
};
Cryptpad.setPadTitle(data, function (err) {
if (!err && !(obj && obj.notStored)) {
// No error and the pad was correctly stored
// hide the hash
var opts = parsed.getOptions();
var hash = Utils.Hash.getHiddenHashFromKeys(parsed.type, secret, opts);
var useUnsafe = Utils.Util.find(settings, ['security', 'unsafeLinks']);
if (!useUnsafe && window.history && window.history.replaceState) {
if (!/^#/.test(hash)) { hash = '#' + hash; }
window.history.replaceState({}, window.document.title, hash);
}
}
cb({error: err});
2018-08-27 12:58:09 +00:00
});
});
sframeChan.on('Q_IS_PAD_STORED', function (data, cb) {
Cryptpad.getPadAttribute('title', function (err, data) {
cb (!err && typeof (data) === "string");
});
});
sframeChan.on('Q_ACCEPT_OWNERSHIP', function (data, cb) {
2019-10-28 14:05:49 +00:00
var parsed = Utils.Hash.parsePadUrl(data.href);
if (parsed.type === 'drive') {
// Shared folder
var secret = Utils.Hash.getSecrets(parsed.type, parsed.hash, data.password);
Cryptpad.addSharedFolder(null, secret, cb);
} else {
var _data = {
password: data.password,
href: data.href,
channel: data.channel,
title: data.title,
owners: data.metadata.owners,
expire: data.metadata.expire,
forceSave: true
};
Cryptpad.setPadTitle(_data, function (err) {
cb({error: err});
});
}
2019-09-03 13:11:23 +00:00
// Also add your mailbox to the metadata object
var padParsed = Utils.Hash.parsePadUrl(data.href);
var padSecret = Utils.Hash.getSecrets(padParsed.type, padParsed.hash, data.password);
var padCrypto = Utils.Crypto.createEncryptor(padSecret.keys);
try {
var value = {};
value[edPublic] = padCrypto.encrypt(JSON.stringify({
notifications: notifications,
curvePublic: curvePublic
}));
var msg = {
channel: data.channel,
command: 'ADD_MAILBOX',
value: value
};
Cryptpad.setPadMetadata(msg, function (res) {
if (res.error) { console.error(res.error); }
});
} catch (err) {
return void console.error(err);
}
});
2018-08-27 12:58:09 +00:00
sframeChan.on('Q_IMPORT_MEDIATAG', function (obj, cb) {
var key = obj.key;
var channel = obj.channel;
var hash = Utils.Hash.getFileHashFromKeys({
version: 1,
channel: channel,
keys: {
fileKeyStr: key
}
});
var href = '/file/#' + hash;
var data = {
title: obj.name,
href: href,
channel: channel,
owners: obj.owners,
forceSave: true,
};
Cryptpad.setPadTitle(data, function (err) {
Cryptpad.setPadAttribute('fileType', obj.type, null, href);
cb(err);
});
});
2017-08-30 09:10:57 +00:00
sframeChan.on('Q_SETTINGS_SET_DISPLAY_NAME', function (newName, cb) {
Cryptpad.setDisplayName(newName, function (err) {
2017-08-30 09:10:57 +00:00
if (err) {
console.log("Couldn't set username");
console.error(err);
cb('ERROR');
return;
}
2017-11-30 17:22:26 +00:00
Cryptpad.changeMetadata();
2017-08-30 09:10:57 +00:00
cb();
});
});
sframeChan.on('Q_LOGOUT', function (data, cb) {
2017-11-23 11:28:49 +00:00
Utils.LocalStore.logout(cb);
2017-08-30 09:10:57 +00:00
});
sframeChan.on('EV_NOTIFY', function (data) {
Notifier.notify(data);
2017-08-30 09:10:57 +00:00
});
sframeChan.on('Q_MOVE_TO_TRASH', function (data, cb) {
cb = cb || $.noop;
if (readOnly && hashes.editHash) {
var appPath = window.location.pathname;
Cryptpad.moveToTrash(cb, appPath + '#' + hashes.editHash);
return;
}
2017-08-30 09:10:57 +00:00
Cryptpad.moveToTrash(cb);
});
sframeChan.on('Q_SAVE_AS_TEMPLATE', function (data, cb) {
Cryptpad.saveAsTemplate(Cryptget.put, data, cb);
});
2018-08-27 12:58:09 +00:00
// Messaging
2019-05-21 16:43:11 +00:00
sframeChan.on('Q_SEND_FRIEND_REQUEST', function (data, cb) {
Cryptpad.messaging.sendFriendRequest(data, cb);
2017-08-30 09:10:57 +00:00
});
2019-05-21 16:43:11 +00:00
sframeChan.on('Q_ANSWER_FRIEND_REQUEST', function (data, cb) {
Cryptpad.messaging.answerFriendRequest(data, cb);
2017-12-15 15:19:22 +00:00
});
2017-08-30 09:10:57 +00:00
2019-12-18 12:05:01 +00:00
sframeChan.on('Q_ANON_GET_PREVIEW_CONTENT', function (data, cb) {
Cryptpad.anonGetPreviewContent(data, cb);
});
2018-08-27 12:58:09 +00:00
// History
2017-08-30 09:10:57 +00:00
sframeChan.on('Q_GET_FULL_HISTORY', function (data, cb) {
var crypto = Crypto.createEncryptor(secret.keys);
Cryptpad.getFullHistory({
channel: secret.channel,
validateKey: secret.keys.validateKey
}, function (encryptedMsgs) {
2019-02-25 17:43:32 +00:00
var nt = nThen;
var decryptedMsgs = [];
var total = encryptedMsgs.length;
encryptedMsgs.forEach(function (msg, i) {
nt = nt(function (waitFor) {
// The 3rd parameter "true" means we're going to skip signature validation.
// We don't need it since the message is already validated serverside by hk
decryptedMsgs.push(crypto.decrypt(msg, true, true));
setTimeout(waitFor(function () {
sframeChan.event('EV_FULL_HISTORY_STATUS', (i+1)/total);
}));
2019-02-25 17:43:32 +00:00
}).nThen;
});
nt(function () {
cb(decryptedMsgs);
});
});
2017-08-30 09:10:57 +00:00
});
sframeChan.on('Q_GET_HISTORY_RANGE', function (data, cb) {
2018-07-19 15:07:14 +00:00
var nSecret = secret;
if (cfg.isDrive) {
2019-06-17 12:13:06 +00:00
// Shared folder or user hash or fs hash
2018-07-19 15:07:14 +00:00
var hash = Utils.LocalStore.getUserHash() || Utils.LocalStore.getFSHash();
2019-06-17 12:13:06 +00:00
if (data.sharedFolder) { hash = data.sharedFolder.hash; }
2018-07-19 15:07:14 +00:00
if (hash) {
2019-06-17 12:13:06 +00:00
var password = (data.sharedFolder && data.sharedFolder.password) || undefined;
nSecret = Utils.Hash.getSecrets('drive', hash, password);
2018-07-19 15:07:14 +00:00
}
}
var channel = nSecret.channel;
var validate = nSecret.keys.validateKey;
var crypto = Crypto.createEncryptor(nSecret.keys);
Cryptpad.getHistoryRange({
2018-07-19 15:07:14 +00:00
channel: channel,
validateKey: validate,
lastKnownHash: data.lastKnownHash
}, function (data) {
cb({
isFull: data.isFull,
messages: data.messages.map(function (msg) {
// The 3rd parameter "true" means we're going to skip signature validation.
// We don't need it since the message is already validated serverside by hk
return crypto.decrypt(msg, true, true);
}),
lastKnownHash: data.lastKnownHash
});
});
});
2017-08-30 09:10:57 +00:00
2018-08-27 12:58:09 +00:00
// Store
2019-02-25 17:43:32 +00:00
sframeChan.on('Q_DRIVE_GETDELETED', function (data, cb) {
Cryptpad.getDeletedPads(data, function (err, obj) {
if (err) { return void console.error(err); }
cb(obj);
});
});
2017-09-22 17:35:06 +00:00
sframeChan.on('Q_SESSIONSTORAGE_PUT', function (data, cb) {
2019-09-12 15:54:50 +00:00
if (typeof (data.value) === "undefined") {
delete sessionStorage[data.key];
} else {
sessionStorage[data.key] = data.value;
}
2017-09-22 17:35:06 +00:00
cb();
});
sframeChan.on('Q_IS_ONLY_IN_SHARED_FOLDER', function (data, cb) {
Cryptpad.isOnlyInSharedFolder(secret.channel, function (err, t) {
if (err) { return void cb({error: err}); }
cb(t);
});
});
2017-09-22 17:35:06 +00:00
2017-09-07 16:56:58 +00:00
// Present mode URL
sframeChan.on('Q_PRESENT_URL_GET_VALUE', function (data, cb) {
2020-01-27 11:18:25 +00:00
var parsed = Utils.Hash.parsePadUrl(currentPad.href);
2017-09-07 16:56:58 +00:00
cb(parsed.hashData && parsed.hashData.present);
});
sframeChan.on('EV_PRESENT_URL_SET_VALUE', function (data) {
2020-01-27 11:18:25 +00:00
// Update the rendered hash and the full hash with the "present" settings
var opts = parsed.getOptions();
opts.present = data;
// Full hash
currentPad.href = parsed.getUrl(opts);
if (parsed.hashData) { currentPad.hash = parsed.hashData.getHash(opts); }
// Rendered (maybe hidden) hash
var hiddenParsed = Utils.Hash.parsePadUrl(window.location.href);
window.location.href = hiddenParsed.getUrl(opts);
2017-09-07 16:56:58 +00:00
});
2017-08-30 16:47:50 +00:00
2017-09-07 16:56:58 +00:00
// File upload
var onFileUpload = function (sframeChan, data, cb) {
2017-11-09 17:17:49 +00:00
require(['/common/outer/upload.js'], function (Files) {
var sendEvent = function (data) {
sframeChan.event("EV_FILE_UPLOAD_STATE", data);
};
var updateProgress = function (progressValue) {
sendEvent({
uid: data.uid,
2017-11-09 17:17:49 +00:00
progress: progressValue
});
};
var onComplete = function (href) {
sendEvent({
complete: true,
uid: data.uid,
2017-11-09 17:17:49 +00:00
href: href
});
};
var onError = function (e) {
sendEvent({
uid: data.uid,
2017-11-09 17:17:49 +00:00
error: e
});
};
var onPending = function (cb) {
sframeChan.query('Q_CANCEL_PENDING_FILE_UPLOAD', {
uid: data.uid
}, function (err, data) {
2017-11-09 17:17:49 +00:00
if (data) {
cb();
}
});
};
data.blob = Crypto.Nacl.util.decodeBase64(data.blob);
Files.upload(data, data.noStore, Cryptpad, updateProgress, onComplete, onError, onPending);
cb();
});
};
sframeChan.on('Q_UPLOAD_FILE', function (data, cb) {
onFileUpload(sframeChan, data, cb);
});
2017-09-07 16:56:58 +00:00
// File picker
var FP = {};
var initFilePicker = function (cfg) {
2018-04-13 16:52:55 +00:00
// cfg.hidden means pre-loading the filepicker while keeping it hidden.
// if cfg.hidden is true and the iframe already exists, do nothing
if (!FP.$iframe) {
var config = {};
config.onFilePicked = function (data) {
sframeChan.event('EV_FILE_PICKED', data);
};
config.onClose = function () {
FP.$iframe.hide();
};
config.onFileUpload = onFileUpload;
config.types = cfg;
config.addCommonRpc = addCommonRpc;
config.modules = {
Cryptpad: Cryptpad,
2017-11-23 11:28:49 +00:00
SFrameChannel: SFrameChannel,
Utils: Utils
};
FP.$iframe = $('<iframe>', {id: 'sbox-filePicker-iframe'}).appendTo($('body'));
FP.picker = FilePicker.create(config);
2018-04-13 16:52:55 +00:00
} else if (!cfg.hidden) {
FP.$iframe.show();
FP.picker.refresh(cfg);
}
if (cfg.hidden) {
FP.$iframe.hide();
return;
}
FP.$iframe.focus();
};
2017-09-05 09:35:15 +00:00
sframeChan.on('EV_FILE_PICKER_OPEN', function (data) {
initFilePicker(data);
});
2019-05-29 17:00:20 +00:00
// Share modal
var ShareModal = {};
var initShareModal = function (cfg) {
cfg.hashes = hashes;
cfg.password = password;
2019-07-18 15:18:36 +00:00
cfg.isTemplate = isTemplate;
2019-05-29 17:00:20 +00:00
// cfg.hidden means pre-loading the filepicker while keeping it hidden.
// if cfg.hidden is true and the iframe already exists, do nothing
if (!ShareModal.$iframe) {
var config = {};
config.onShareAction = function (data) {
sframeChan.event('EV_SHARE_ACTION', data);
};
config.onClose = function () {
ShareModal.$iframe.hide();
};
config.data = cfg;
config.addCommonRpc = addCommonRpc;
config.modules = {
Cryptpad: Cryptpad,
SFrameChannel: SFrameChannel,
Utils: Utils
};
ShareModal.$iframe = $('<iframe>', {id: 'sbox-share-iframe'}).appendTo($('body'));
ShareModal.modal = Share.create(config);
} else if (!cfg.hidden) {
ShareModal.modal.refresh(cfg, function () {
ShareModal.$iframe.show();
});
2019-05-29 17:00:20 +00:00
}
if (cfg.hidden) {
ShareModal.$iframe.hide();
return;
}
ShareModal.$iframe.focus();
};
sframeChan.on('EV_SHARE_OPEN', function (data) {
initShareModal(data || {});
});
sframeChan.on('Q_TEMPLATE_USE', function (data, cb) {
Cryptpad.useTemplate(data, Cryptget, cb);
});
sframeChan.on('Q_TEMPLATE_EXIST', function (type, cb) {
2017-11-30 09:33:09 +00:00
Cryptpad.listTemplates(type, function (err, templates) {
cb(templates.length > 0);
});
});
2018-04-27 15:23:23 +00:00
var getKey = function (href, channel) {
2018-03-13 10:31:08 +00:00
var parsed = Utils.Hash.parsePadUrl(href);
2018-04-27 15:23:23 +00:00
return 'thumbnail-' + parsed.type + '-' + channel;
2018-03-13 10:31:08 +00:00
};
sframeChan.on('Q_CREATE_TEMPLATES', function (type, cb) {
Cryptpad.getSecureFilesList({
types: [type],
where: ['template']
}, function (err, data) {
// NOTE: Never return data directly!
if (err) { return void cb({error: err}); }
var res = [];
nThen(function (waitFor) {
Object.keys(data).map(function (el) {
2018-04-27 15:23:23 +00:00
var k = getKey(data[el].href, data[el].channel);
2018-03-13 10:31:08 +00:00
Utils.LocalStore.getThumbnail(k, waitFor(function (e, thumb) {
res.push({
id: el,
name: data[el].filename || data[el].title || '?',
2018-04-13 16:52:55 +00:00
thumbnail: thumb,
used: data[el].used || 0
2018-03-13 10:31:08 +00:00
});
}));
});
}).nThen(function () {
cb({data: res});
});
});
});
sframeChan.on('Q_GET_FILE_THUMBNAIL', function (data, cb) {
2019-08-13 16:05:03 +00:00
if (!Cryptpad.fromFileData || !Cryptpad.fromFileData.href) {
return void cb({
error: "EINVAL",
});
}
var key = getKey(Cryptpad.fromFileData.href, Cryptpad.fromFileData.channel);
Utils.LocalStore.getThumbnail(key, function (e, data) {
if (data === "EMPTY") { data = null; }
cb({
error: e,
data: data
});
});
});
2019-09-23 13:45:24 +00:00
sframeChan.on('Q_PIN_GET_USAGE', function (teamId, cb) {
Cryptpad.isOverPinLimit(teamId, function (err, overLimit, data) {
2017-09-21 15:56:24 +00:00
cb({
error: err,
data: data
});
});
});
sframeChan.on('Q_LANGUAGE_SET', function (data, cb) {
Cryptpad.setLanguage(data, cb);
});
sframeChan.on('Q_GET_ALL_TAGS', function (data, cb) {
Cryptpad.listAllTags(function (err, tags) {
cb({
error: err,
tags: tags
});
});
});
2019-10-30 17:29:33 +00:00
sframeChan.on('Q_BLOB_PASSWORD_CHANGE', function (data, cb) {
2020-01-27 11:18:25 +00:00
data.href = data.href || currentPad.href;
2019-10-31 11:12:45 +00:00
var onPending = function (cb) {
sframeChan.query('Q_BLOB_PASSWORD_CHANGE_PENDING', null, function (err, obj) {
if (obj && obj.cancel) { cb(); }
});
2019-10-30 17:29:33 +00:00
};
var updateProgress = function (p) {
2019-10-31 11:12:45 +00:00
sframeChan.event('EV_BLOB_PASSWORD_CHANGE_PROGRESS', p);
2019-10-30 17:29:33 +00:00
};
Cryptpad.changeBlobPassword(data, {
onPending: onPending,
updateProgress: updateProgress
}, cb);
});
2019-11-14 14:49:46 +00:00
sframeChan.on('Q_OO_PASSWORD_CHANGE', function (data, cb) {
2020-01-27 11:18:25 +00:00
data.href = data.href || currentPad.href;
2019-11-14 14:49:46 +00:00
Cryptpad.changeOOPassword(data, cb);
});
sframeChan.on('Q_PAD_PASSWORD_CHANGE', function (data, cb) {
2020-01-27 11:18:25 +00:00
data.href = data.href || currentPad.href;
2019-09-26 09:19:16 +00:00
Cryptpad.changePadPassword(Cryptget, Crypto, data, cb);
});
2018-06-22 08:37:54 +00:00
sframeChan.on('Q_CHANGE_USER_PASSWORD', function (data, cb) {
Cryptpad.changeUserPassword(Cryptget, edPublic, data, cb);
2018-06-20 14:39:01 +00:00
});
sframeChan.on('Q_WRITE_LOGIN_BLOCK', function (data, cb) {
Cryptpad.writeLoginBlock(data, cb);
});
2018-06-19 15:17:56 +00:00
sframeChan.on('Q_REMOVE_LOGIN_BLOCK', function (data, cb) {
Cryptpad.removeLoginBlock(data, cb);
});
2019-08-14 13:12:44 +00:00
// It seems we have performance issues when we open and close a lot of channels over
// the same network, maybe a memory leak. To fix this, we kill and create a new
// network every 30 cryptget calls (1 call = 1 channel)
2018-10-18 16:50:38 +00:00
var cgNetwork;
var whenCGReady = function (cb) {
if (cgNetwork && cgNetwork !== true) { console.log(cgNetwork); return void cb(); }
setTimeout(function () {
whenCGReady(cb);
}, 500);
};
var i = 0;
2018-10-17 12:32:33 +00:00
sframeChan.on('Q_CRYPTGET', function (data, cb) {
2018-10-18 16:50:38 +00:00
var todo = function () {
data.opts.network = cgNetwork;
Cryptget.get(data.hash, function (err, val) {
cb({
error: err,
data: val
});
2019-08-14 13:42:32 +00:00
}, data.opts, function (progress) {
sframeChan.event("EV_CRYPTGET_PROGRESS", {
hash: data.hash,
progress: progress,
});
});
2018-10-18 16:50:38 +00:00
};
//return void todo();
if (i > 30) {
i = 0;
cgNetwork = undefined;
}
2018-10-19 16:38:35 +00:00
i++;
2018-10-18 16:50:38 +00:00
if (!cgNetwork) {
cgNetwork = true;
return void Cryptpad.makeNetwork(function (err, nw) {
console.log(nw);
cgNetwork = nw;
todo();
2018-10-17 12:32:33 +00:00
});
2018-10-18 16:50:38 +00:00
} else if (cgNetwork === true) {
return void whenCGReady(todo);
}
todo();
});
sframeChan.on('EV_CRYPTGET_DISCONNECT', function () {
if (!cgNetwork) { return; }
cgNetwork.disconnect();
cgNetwork = undefined;
2018-10-17 12:32:33 +00:00
});
2017-09-12 16:40:11 +00:00
if (cfg.addRpc) {
2017-11-13 15:32:40 +00:00
cfg.addRpc(sframeChan, Cryptpad, Utils);
2017-09-12 16:40:11 +00:00
}
2018-12-04 16:18:42 +00:00
sframeChan.on('Q_CURSOR_OPENCHANNEL', function (data, cb) {
Cryptpad.cursor.execCommand({
cmd: 'INIT_CURSOR',
data: {
channel: data,
secret: secret
}
}, cb);
});
Cryptpad.cursor.onEvent.reg(function (data) {
sframeChan.event('EV_CURSOR_EVENT', data);
});
sframeChan.on('Q_CURSOR_COMMAND', function (data, cb) {
Cryptpad.cursor.execCommand(data, cb);
});
2017-10-02 16:57:17 +00:00
Cryptpad.universal.onEvent.reg(function (data) {
sframeChan.event('EV_UNIVERSAL_EVENT', data);
});
sframeChan.on('Q_UNIVERSAL_COMMAND', function (data, cb) {
Cryptpad.universal.execCommand(data, cb);
});
Cryptpad.onTimeoutEvent.reg(function () {
sframeChan.event('EV_WORKER_TIMEOUT');
});
2019-07-13 09:47:58 +00:00
sframeChan.on('EV_GIVE_ACCESS', function (data, cb) {
Cryptpad.padRpc.giveAccess(data, cb);
});
2019-09-09 12:46:50 +00:00
// REQUEST_ACCESS is used both to check IF we can contact an owner (send === false)
// AND also to send the request if we want (send === true)
sframeChan.on('Q_REQUEST_ACCESS', function (send, cb) {
2019-07-13 09:47:58 +00:00
if (readOnly && hashes.editHash) {
return void cb({error: 'ALREADYKNOWN'});
}
2019-09-09 12:46:50 +00:00
var owner, owners;
var crypto = Crypto.createEncryptor(secret.keys);
nThen(function (waitFor) {
// Try to get the owner's mailbox from the pad metadata first.
// If it's is an older owned pad, check if the owner is a friend
// or an acquaintance (from async-store directly in requestAccess)
2019-09-09 12:46:50 +00:00
Cryptpad.getPadMetadata({
channel: secret.channel
}, waitFor(function (obj) {
obj = obj || {};
if (obj.error) { return; }
2019-09-09 12:46:50 +00:00
owners = obj.owners;
2019-09-03 13:11:23 +00:00
var mailbox;
// Get the first available mailbox (the field can be an string or an object)
// TODO maybe we should send the request to all the owners?
if (typeof (obj.mailbox) === "string") {
mailbox = obj.mailbox;
} else if (obj.mailbox && obj.owners && obj.owners.length) {
mailbox = obj.mailbox[obj.owners[0]];
}
if (mailbox) {
try {
2019-09-03 13:11:23 +00:00
var dataStr = crypto.decrypt(mailbox, true, true);
var data = JSON.parse(dataStr);
if (!data.notifications || !data.curvePublic) { return; }
owner = data;
} catch (e) { console.error(e); }
}
}));
}).nThen(function () {
2019-09-09 12:46:50 +00:00
// If we are just checking (send === false) and there is a mailbox field, cb state true
// If there is no mailbox, we'll have to check if an owner is a friend in the worker
if (owner && !send) {
return void cb({state: true});
}
Cryptpad.padRpc.requestAccess({
2019-09-09 12:46:50 +00:00
send: send,
channel: secret.channel,
2019-09-09 12:46:50 +00:00
owner: owner,
owners: owners
}, cb);
});
2019-07-11 12:16:04 +00:00
});
2020-01-21 10:01:07 +00:00
sframeChan.on('EV_BURN_PAD', function (channel) {
if (!burnAfterReading) { return; }
Cryptpad.burnPad({
channel: channel,
ownerKey: burnAfterReading
});
});
2017-10-02 16:57:17 +00:00
if (cfg.messaging) {
Notifier.getPermission();
2017-10-02 16:57:17 +00:00
sframeChan.on('Q_CHAT_OPENPADCHAT', function (data, cb) {
2019-09-16 14:48:32 +00:00
Cryptpad.universal.execCommand({
type: 'messenger',
data: {
2019-09-16 14:48:32 +00:00
cmd: 'OPEN_PAD_CHAT',
data: {
channel: data,
secret: secret
}
}
}, cb);
2017-10-02 16:57:17 +00:00
});
}
2018-08-28 15:44:15 +00:00
// Chrome 68 on Mac contains a bug resulting in the page turning white after a few seconds
try {
if (navigator.platform.toUpperCase().indexOf('MAC') >= 0 &&
!localStorage.CryptPad_chrome68) {
var isChrome = !!window.chrome && !!window.chrome.webstore;
var getChromeVersion = function () {
var raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
return raw ? parseInt(raw[2], 10) : false;
};
if (isChrome && getChromeVersion() === 68) {
sframeChan.whenReg('EV_CHROME_68', function () {
sframeChan.event("EV_CHROME_68");
localStorage.CryptPad_chrome68 = "1";
});
}
}
} catch (e) {}
// If our channel was deleted from all of our drives, sitch back to full hash
// in the address bar
Cryptpad.padRpc.onChannelDeleted.reg(function (channel) {
if (channel !== secret.channel) { return; }
var ohc = window.onhashchange;
window.onhashchange = function () {};
window.location.href = currentPad.href;
window.onhashchange = ohc;
ohc({reset: true});
});
2017-09-12 16:40:11 +00:00
2017-12-07 17:51:50 +00:00
// Join the netflux channel
var rtStarted = false;
var startRealtime = function (rtConfig) {
rtConfig = rtConfig || {};
2017-12-07 17:51:50 +00:00
rtStarted = true;
2020-01-27 11:18:25 +00:00
2017-12-07 17:51:50 +00:00
var replaceHash = function (hash) {
2020-01-27 11:18:25 +00:00
// The pad has just been created but is not stored yet. We'll switch
// to hidden hash once the pad is stored
2017-12-07 17:51:50 +00:00
if (window.history && window.history.replaceState) {
if (!/^#/.test(hash)) { hash = '#' + hash; }
2018-03-13 10:31:08 +00:00
window.history.replaceState({}, window.document.title, hash);
2017-12-07 17:51:50 +00:00
if (typeof(window.onhashchange) === 'function') {
window.onhashchange();
}
return;
}
window.location.hash = hash;
};
2017-09-12 16:40:11 +00:00
2020-01-09 16:30:15 +00:00
if (burnAfterReading) {
Cryptpad.padRpc.onReadyEvent.reg(function () {
Cryptpad.burnPad({
password: password,
2020-01-27 11:18:25 +00:00
href: currentPad.href,
2020-01-09 16:30:15 +00:00
channel: secret.channel,
ownerKey: burnAfterReading
});
});
}
2018-01-12 16:08:41 +00:00
var cpNfCfg = {
2017-12-07 17:51:50 +00:00
sframeChan: sframeChan,
channel: secret.channel,
padRpc: Cryptpad.padRpc,
validateKey: secret.keys.validateKey || undefined,
2017-12-12 11:06:31 +00:00
isNewHash: isNewHash,
2017-12-07 17:51:50 +00:00
readOnly: readOnly,
crypto: Crypto.createEncryptor(secret.keys),
onConnect: function () {
2020-01-27 11:18:25 +00:00
if (currentPad.hash && currentPad.hash !== '#') {
/*window.location = parsed.getUrl({
2017-12-07 17:51:50 +00:00
present: parsed.hashData.present,
embed: parsed.hashData.embed
});*/
2017-12-07 17:51:50 +00:00
return;
}
if (readOnly || cfg.noHash) { return; }
replaceHash(Utils.Hash.getEditHashFromKeys(secret));
2017-11-13 15:32:40 +00:00
}
};
2018-03-22 14:16:19 +00:00
nThen(function (waitFor) {
2020-01-27 11:18:25 +00:00
if (isNewFile && cfg.owned && !currentPad.hash) {
2018-03-22 14:16:19 +00:00
Cryptpad.getMetadata(waitFor(function (err, m) {
cpNfCfg.owners = [m.priv.edPublic];
}));
2020-01-27 11:18:25 +00:00
} else if (isNewFile && !cfg.useCreationScreen && currentPad.hash) {
console.log("new file with hash in the address bar in an app without pcs and which requires owners");
sframeChan.onReady(function () {
sframeChan.query("EV_LOADING_ERROR", "DELETED");
});
waitFor.abort();
2018-03-22 14:16:19 +00:00
}
}).nThen(function () {
Object.keys(rtConfig).forEach(function (k) {
cpNfCfg[k] = rtConfig[k];
});
CpNfOuter.start(cpNfCfg);
2017-12-07 17:51:50 +00:00
});
2017-11-13 15:32:40 +00:00
};
2017-12-07 17:51:50 +00:00
sframeChan.on('Q_CREATE_PAD', function (data, cb) {
if (!isNewFile || rtStarted) { return; }
// Create a new hash
password = data.password;
var newHash = Utils.Hash.createRandomHash(parsed.type, password);
secret = Utils.secret = Utils.Hash.getSecrets(parsed.type, newHash, password);
Utils.crypto = Utils.Crypto.createEncryptor(Utils.secret.keys);
2017-12-07 17:51:50 +00:00
// Update the hash in the address bar
var ohc = window.onhashchange;
window.onhashchange = function () {};
window.location.hash = newHash;
2020-01-27 11:18:25 +00:00
currentPad.hash = newHash;
currentPad.href = '/' + parsed.type + '/#' + newHash;
2017-12-07 17:51:50 +00:00
window.onhashchange = ohc;
ohc({reset: true});
// Update metadata values and send new metadata inside
2020-01-27 11:18:25 +00:00
parsed = Utils.Hash.parsePadUrl(currentPad.href);
defaultTitle = Utils.UserObject.getDefaultName(parsed);
hashes = Utils.Hash.getHashes(secret);
2017-12-07 17:51:50 +00:00
readOnly = false;
updateMeta();
2019-07-13 13:23:32 +00:00
var rtConfig = {
metadata: {}
};
2019-09-12 15:54:50 +00:00
if (data.team) {
Cryptpad.initialTeam = data.team.id;
}
if (data.owned && data.team && data.team.edPublic) {
rtConfig.metadata.owners = [data.team.edPublic];
} else if (data.owned) {
2019-07-13 13:23:32 +00:00
rtConfig.metadata.owners = [edPublic];
2019-09-03 13:11:23 +00:00
rtConfig.metadata.mailbox = {};
rtConfig.metadata.mailbox[edPublic] = Utils.crypto.encrypt(JSON.stringify({
notifications: notifications,
curvePublic: curvePublic
}));
2017-08-30 09:10:57 +00:00
}
2017-12-11 11:19:44 +00:00
if (data.expire) {
2019-07-13 13:23:32 +00:00
rtConfig.metadata.expire = data.expire;
2017-12-11 11:19:44 +00:00
}
2019-07-13 13:23:32 +00:00
rtConfig.metadata.validateKey = (secret.keys && secret.keys.validateKey) || undefined;
Utils.rtConfig = rtConfig;
2018-03-13 10:31:08 +00:00
nThen(function(waitFor) {
if (data.templateId) {
if (data.templateId === -1) {
2018-04-27 09:54:23 +00:00
initialPathInDrive = ['template'];
2018-03-13 10:31:08 +00:00
return;
}
Cryptpad.getPadData(data.templateId, waitFor(function (err, d) {
data.template = d.href;
}));
}
}).nThen(function () {
var cryptputCfg = $.extend(true, {}, rtConfig, {password: password});
2018-03-13 10:31:08 +00:00
if (data.template) {
// Pass rtConfig to useTemplate because Cryptput will create the file and
// we need to have the owners and expiration time in the first line on the
// server
Cryptpad.useTemplate({
href: data.template
}, Cryptget, function () {
2018-03-13 10:31:08 +00:00
startRealtime();
cb();
}, cryptputCfg);
2018-03-13 10:31:08 +00:00
return;
}
// if we open a new code from a file
if (Cryptpad.fromFileData) {
Cryptpad.useFile(Cryptget, function () {
startRealtime();
cb();
}, cryptputCfg);
return;
}
2018-03-13 10:31:08 +00:00
// Start realtime outside the iframe and callback
startRealtime(rtConfig);
cb();
});
2017-08-30 09:10:57 +00:00
});
2017-12-07 17:51:50 +00:00
2020-01-09 16:30:15 +00:00
sframeChan.on('EV_BURN_AFTER_READING', function () {
startRealtime();
});
2017-12-07 17:51:50 +00:00
sframeChan.ready();
Utils.Feedback.reportAppUsage();
2018-04-10 14:38:31 +00:00
if (!realtime && !Test.testing) { return; }
if (isNewFile && cfg.useCreationScreen && !Test.testing) { return; }
2020-01-09 16:30:15 +00:00
if (burnAfterReading) { return; }
//if (isNewFile && Utils.LocalStore.isLoggedIn()
// && AppConfig.displayCreationScreen && cfg.useCreationScreen) { return; }
2017-12-07 17:51:50 +00:00
startRealtime();
2017-08-30 09:10:57 +00:00
});
};
return common;
});