Migrate the file to a sandboxed iframe

pull/1/head
yflory 7 years ago
parent 5ac3e97dc8
commit 437f50fd4a

@ -293,7 +293,7 @@
&.cp-toolbar-hidden { &.cp-toolbar-hidden {
display: none; display: none;
} }
.cp-toolbar-drawer { .cp-toolbar-drawer-element {
display: none; display: none;
} }
// Bootstrap 4 colors (btn-secondary) // Bootstrap 4 colors (btn-secondary)
@ -447,6 +447,7 @@
.cp-toolbar-title-value-page { .cp-toolbar-title-value-page {
border: 1px solid transparent; border: 1px solid transparent;
padding: 0 5px; padding: 0 5px;
line-height: 48px;
} }
.cp-toolbar-title-edit, .cp-toolbar-title-save { .cp-toolbar-title-edit, .cp-toolbar-title-save {
display: flex; display: flex;

@ -25,5 +25,6 @@ html.cp-app-print {
body.cp-app-pad { @import "../../../pad/app-pad.less"; } body.cp-app-pad { @import "../../../pad/app-pad.less"; }
body.cp-app-code { @import "../../../code/app-code.less"; } body.cp-app-code { @import "../../../code/app-code.less"; }
body.cp-app-slide { @import "../../../slide/app-slide.less"; } body.cp-app-slide { @import "../../../slide/app-slide.less"; }
body.cp-app-file { @import "../../../file/app-file.less"; }
body.cp-app-filepicker { @import "../../../filepicker/app-filepicker.less"; } body.cp-app-filepicker { @import "../../../filepicker/app-filepicker.less"; }

@ -2024,6 +2024,7 @@ define([
common.getRecentPads(function (err, recent) { common.getRecentPads(function (err, recent) {
var parsed = parsePadUrl(window.location.href); var parsed = parsePadUrl(window.location.href);
if (!parsed.type || !parsed.hashData) { return void cb('E_INVALID_HREF'); } if (!parsed.type || !parsed.hashData) { return void cb('E_INVALID_HREF'); }
if (parsed.type === 'file') { secret.channel = Util.base64ToHex(secret.channel); }
var hashes = common.getHashes(secret.channel, secret); var hashes = common.getHashes(secret.channel, secret);
if (!hashes.editHash && !hashes.viewHash && parsed.hashData && !parsed.hashData.mode) { if (!hashes.editHash && !hashes.viewHash && parsed.hashData && !parsed.hashData.mode) {

@ -6,7 +6,9 @@ define([
], function (nThen, ApiConfig, $) { ], function (nThen, ApiConfig, $) {
var common = {}; var common = {};
common.start = function () { common.start = function (cfg) {
cfg = cfg || {};
var realtime = !cfg.noRealtime;
var secret; var secret;
var hashes; var hashes;
var CpNfOuter; var CpNfOuter;
@ -60,7 +62,7 @@ define([
name = n; name = n;
})); }));
}).nThen(function (/*waitFor*/) { }).nThen(function (/*waitFor*/) {
sframeChan.event('EV_METADATA_UPDATE', { var metaObj = {
doc: { doc: {
defaultTitle: defaultTitle, defaultTitle: defaultTitle,
type: parsed.type type: parsed.type
@ -77,6 +79,7 @@ define([
accountName: Cryptpad.getAccountName(), accountName: Cryptpad.getAccountName(),
origin: window.location.origin, origin: window.location.origin,
pathname: window.location.pathname, pathname: window.location.pathname,
fileHost: ApiConfig.fileHost,
readOnly: readOnly, readOnly: readOnly,
availableHashes: hashes, availableHashes: hashes,
isTemplate: Cryptpad.isTemplate(window.location.href), isTemplate: Cryptpad.isTemplate(window.location.href),
@ -86,7 +89,11 @@ define([
isPresent: parsed.hashData && parsed.hashData.present, isPresent: parsed.hashData && parsed.hashData.present,
isEmbed: parsed.hashData && parsed.hashData.embed, isEmbed: parsed.hashData && parsed.hashData.embed,
} }
}); };
if (cfg.addData) {
cfg.addData(metaObj.priv, Cryptpad);
}
sframeChan.event('EV_METADATA_UPDATE', metaObj);
}); });
}; };
Cryptpad.onDisplayNameChanged(updateMeta); Cryptpad.onDisplayNameChanged(updateMeta);
@ -341,8 +348,16 @@ define([
} }
}); });
if (cfg.addRpc) {
cfg.addRpc(sframeChan, Cryptpad);
}
sframeChan.ready(); sframeChan.ready();
Cryptpad.reportAppUsage();
if (!realtime) { return; }
CpNfOuter.start({ CpNfOuter.start({
sframeChan: sframeChan, sframeChan: sframeChan,
channel: secret.channel, channel: secret.channel,
@ -362,7 +377,6 @@ define([
Cryptpad.replaceHash(Cryptpad.getEditHashFromKeys(wc.id, secret.keys)); Cryptpad.replaceHash(Cryptpad.getEditHashFromKeys(wc.id, secret.keys));
} }
}); });
Cryptpad.reportAppUsage();
}); });
}; };

@ -16,7 +16,7 @@ define(['jquery'], function ($) {
var $title; var $title;
exp.setToolbar = function (toolbar) { exp.setToolbar = function (toolbar) {
$title = toolbar && toolbar.title; $title = toolbar && (toolbar.title || toolbar.pageTitle);
}; };
exp.getTitle = function () { return exp.title; }; exp.getTitle = function () { return exp.title; };
@ -41,8 +41,10 @@ define(['jquery'], function ($) {
metadataMgr.onChange(function () { metadataMgr.onChange(function () {
var md = metadataMgr.getMetadata(); var md = metadataMgr.getMetadata();
if ($title) {
$title.find('span.cp-toolbar-title-value').text(md.title || md.defaultTitle); $title.find('span.cp-toolbar-title-value').text(md.title || md.defaultTitle);
$title.find('input').val(md.title || md.defaultTitle); $title.find('input').val(md.title || md.defaultTitle);
}
exp.title = md.title; exp.title = md.title;
}); });
metadataMgr.onTitleChange(function (title) { metadataMgr.onTitleChange(function (title) {

@ -57,8 +57,7 @@ define([
funcs.getAppConfig = function () { return AppConfig; }; funcs.getAppConfig = function () { return AppConfig; };
funcs.isLoggedIn = function () { funcs.isLoggedIn = function () {
if (!ctx.cpNfInner) { throw new Error("cpNfInner is not ready!"); } return ctx.metadataMgr.getPrivateData().accountName;
return ctx.cpNfInner.metadataMgr.getPrivateData().accountName;
}; };
// MISC // MISC
@ -78,6 +77,7 @@ define([
funcs.openTemplatePicker = callWithCommon(UI.openTemplatePicker); funcs.openTemplatePicker = callWithCommon(UI.openTemplatePicker);
funcs.displayAvatar = callWithCommon(UI.displayAvatar); funcs.displayAvatar = callWithCommon(UI.displayAvatar);
funcs.createButton = callWithCommon(UI.createButton); funcs.createButton = callWithCommon(UI.createButton);
funcs.getFileSize = callWithCommon(UI.getFileSize);
// History // History
funcs.getHistory = callWithCommon(History.create); funcs.getHistory = callWithCommon(History.create);
@ -88,6 +88,24 @@ define([
// Files // Files
funcs.uploadFile = callWithCommon(File.uploadFile); funcs.uploadFile = callWithCommon(File.uploadFile);
funcs.createFileManager = callWithCommon(File.create); funcs.createFileManager = callWithCommon(File.create);
funcs.getMediatagScript = function () {
var origin = ctx.metadataMgr.getPrivateData().origin;
return '<script src="' + origin + '/common/media-tag-nacl.min.js"></script>';
};
funcs.getMediatagFromHref = function (href) {
var parsed = Cryptpad.parsePadUrl(href);
var secret = Cryptpad.getSecrets('file', parsed.hash);
var data = ctx.metadataMgr.getPrivateData();
if (secret.keys && secret.channel) {
var cryptKey = secret.keys && secret.keys.fileKeyStr;
var hexFileName = Cryptpad.base64ToHex(secret.channel);
var origin = data.fileHost || data.origin;
var src = origin + Cryptpad.getBlobPathFromHex(hexFileName);
return '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + cryptKey + '">' +
'</media-tag>';
}
return;
};
// CodeMirror // CodeMirror
funcs.initCodeMirrorApp = callWithCommon(CodeMirror.create); funcs.initCodeMirrorApp = callWithCommon(CodeMirror.create);
@ -171,6 +189,7 @@ define([
funcs.isStrongestStored = function () { funcs.isStrongestStored = function () {
var data = ctx.metadataMgr.getPrivateData(); var data = ctx.metadataMgr.getPrivateData();
if (data.availableHashes.fileHash) { return true; }
return !data.readOnly || !data.availableHashes.editHash; return !data.readOnly || !data.availableHashes.editHash;
}; };

@ -345,6 +345,7 @@ define([
show(); show();
}); });
initUserList(toolbar, config);
return $container; return $container;
}; };
@ -473,22 +474,59 @@ define([
return "Loading share button"; return "Loading share button";
}; };
var createFileShare = function (toolbar) { var createFileShare = function (toolbar, config) {
if (true) { throw new Error('TODO: Update createFileShare to add "embed" and work in secure iframes'); } if (!config.metadataMgr) {
if (!window.location.hash) { throw new Error("You must provide a `metadataMgr` to display the userlist");
throw new Error("Unable to display the share button: hash required in the URL");
} }
var metadataMgr = config.metadataMgr;
var origin = config.metadataMgr.getPrivateData().origin;
var pathname = config.metadataMgr.getPrivateData().pathname;
var hashes = metadataMgr.getPrivateData().availableHashes;
var url = origin + pathname + '#' + hashes.fileHash;
var $shareIcon = $('<span>', {'class': 'fa fa-share-alt'}); var $shareIcon = $('<span>', {'class': 'fa fa-share-alt'});
var $button = $('<button>', {'title': Messages.shareButton}).append($shareIcon); var options = [];
$button.addClass('cp-toolbar-share-button'); options.push({
$button.click(function () { tag: 'a',
var url = window.location.href; attributes: {title: Messages.editShareTitle, 'class': 'cp-toolbar-share-file-copy'},
content: '<span class="fa fa-file"></span> ' + Messages.fileShare
});
options.push({
tag: 'a',
attributes: {title: Messages.fileEmbedTitle, 'class': 'cp-toolbar-share-file-embed'},
content: '<span class="fa fa-file"></span> ' + Messages.getEmbedCode
});
var dropdownConfigShare = {
text: $('<div>').append($shareIcon).html(),
options: options,
feedback: 'FILESHARE_MENU',
};
var $shareBlock = Cryptpad.createDropdown(dropdownConfigShare);
$shareBlock.find('.cp-dropdown-content').addClass(SHARE_CLS);
$shareBlock.addClass('cp-toolbar-share-button');
$shareBlock.find('button').attr('title', Messages.shareButton);
// Add handlers
$shareBlock.find('a.cp-toolbar-share-file-copy').click(function () {
var success = Cryptpad.Clipboard.copy(url); var success = Cryptpad.Clipboard.copy(url);
if (success) { Cryptpad.log(Messages.shareSuccess); } if (success) { Cryptpad.log(Messages.shareSuccess); }
}); });
$shareBlock.find('a.cp-toolbar-share-file-embed').click(function () {
var $content = $('<div>');
$('<input>', {'style':'display:none;'}).appendTo($content);
$('<h3>').text(Messages.fileEmbedTitle).appendTo($content);
var $script = $('<p>').text(Messages.fileEmbedScript).appendTo($content);
$('<br>').appendTo($script);
$script.append(Cryptpad.dialog.selectable(Common.getMediatagScript()));
var $tag = $('<p>').text(Messages.fileEmbedTag).appendTo($content);
$('<br>').appendTo($tag);
$tag.append(Cryptpad.dialog.selectable(Common.getMediatagFromHref(url)));
Cryptpad.alert($content[0], null, true);
});
toolbar.$leftside.append($button); toolbar.$leftside.append($shareBlock);
return $button; return $shareBlock;
}; };
var createTitle = function (toolbar, config) { var createTitle = function (toolbar, config) {
@ -820,13 +858,13 @@ define([
$title.find('input').trigger(ev); $title.find('input').trigger(ev);
}; };
// Click in the main window // Click in the main window
var w = config.ifrw || window; var w = window;
$(w).on('click', removeDropdowns); $(w).on('click', removeDropdowns);
$(w).on('click', cancelEditTitle); $(w).on('click', cancelEditTitle);
// Click in iframes // Click in iframes
try { try {
if (w.$ && w.$('iframe').length) { if (w.$ && w.$('iframe').length) {
config.ifrw.$('iframe').each(function (i, el) { w.$('iframe').each(function (i, el) {
$(el.contentWindow).on('click', removeDropdowns); $(el.contentWindow).on('click', removeDropdowns);
$(el.contentWindow).on('click', cancelEditTitle); $(el.contentWindow).on('click', cancelEditTitle);
}); });
@ -956,9 +994,9 @@ define([
var tb = {}; var tb = {};
tb['userlist'] = createUserList; tb['userlist'] = createUserList;
tb['share'] = createShare; tb['share'] = createShare;
tb['fileshare'] = createFileShare;//TODO tb['fileshare'] = createFileShare;
tb['title'] = createTitle; tb['title'] = createTitle;
tb['pageTitle'] = createPageTitle;//TODO tb['pageTitle'] = createPageTitle;
tb['lag'] = $.noop; tb['lag'] = $.noop;
tb['spinner'] = createSpinner; tb['spinner'] = createSpinner;
tb['state'] = $.noop; tb['state'] = $.noop;
@ -980,7 +1018,6 @@ define([
}; };
addElement(config.displayed, {}, true); addElement(config.displayed, {}, true);
initUserList(toolbar, config);
toolbar['linkToMain'] = createLinkToMain(toolbar, config); toolbar['linkToMain'] = createLinkToMain(toolbar, config);

@ -0,0 +1,130 @@
@import (once) "../../customize/src/less2/include/browser.less";
@import (once) "../../customize/src/less2/include/toolbar.less";
@import (once) "../../customize/src/less2/include/markdown.less";
@import (once) '../../customize/src/less2/include/fileupload.less';
@import (once) '../../customize/src/less2/include/alertify.less';
.toolbar_main();
.fileupload_main();
.alertify_main();
@button-border: 2px;
/*html, body {
margin: 0px;
height: 100%;
}*/
// body
display: flex;
flex-flow: column;
#cp-app-file-content {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
#cp-app-file-content.ready {
//background: url('/customize/bg3.jpg') no-repeat center center;
background-size: cover;
background-position: center;
}
#cp-app-file-upfile, #cp-app-file-dlfile {
display: block;
height: 100%;
width: 100%;
border: @button-border solid black;
}
.cp-app-file-input {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
media-tag {
img {
max-width: 100%;
max-height: ~"calc(100vh - 96px)";
}
}
#cp-app-file-upload-form, #cp-app-file-download-form {
padding: 0px;
margin: 0px;
position: relative;
width: 50vh;
height: 50vh;
display: block;
margin: 50px auto;
max-width: 80vw;
label {
line-height: ~"calc(50vh - 20px)";
text-align: center;
position: relative;
padding: 10px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
height: 50vh;
box-sizing: border-box;
}
}
#cp-app-file-download-form {
label {
display: flex;
justify-content: center;
align-items: center;
white-space: normal;
word-wrap: break-word;
span {
width: 50vh;
max-width: 80vw;
text-align: center;
line-height: 1.5em;
}
}
}
.cp-app-file-hovering {
background-color: rgba(255, 0, 115, 0.5) !important;
}
.cp-app-file-block {
display: block;
}
.cp-app-file-hidden {
display: none;
}
.cp-app-file-input + label {
//border: 2px solid black;
//background-color: rgba(50, 50, 50, .10);
display: block;
}
.cp-app-file-input:focus + label,
.cp-app-file-input + label:hover {
//background-color: rgba(50, 50, 50, 0.30);
}
#cp-app-file-dlprogress {
position: absolute;
top: 0;
left: 0;
height: 100%;
transition: width 200ms;
width: 0%;
max-width: 100%;
max-height: 100%;
background-color: rgba(255, 0, 115, 0.75);
z-index: 10000;
display: block;
}

@ -1,16 +1,17 @@
<!DOCTYPE html> <!DOCTYPE html>
<html class="cp pad"> <html>
<head> <head>
<title>CryptPad</title> <title>CryptPad</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/> <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<script async data-bootload="/customize/template.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script> <meta name="referrer" content="no-referrer" />
<script async data-bootload="main.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style> <style>
html, body { html, body {
margin: 0px; margin: 0px;
padding: 0px; padding: 0px;
} }
#pad-iframe { #sbox-iframe {
position:fixed; position:fixed;
top:0px; top:0px;
left:0px; left:0px;
@ -26,5 +27,4 @@
</style> </style>
</head> </head>
<body> <body>
<iframe id="pad-iframe"></iframe><script src="/common/noscriptfix.js"></script> <iframe id="sbox-iframe">

@ -1,28 +1,30 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html class="cp-app-noscroll">
<head> <head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/> <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<script src="/bower_components/jquery/dist/jquery.min.js"></script> <script async data-bootload="/file/inner.js" data-main="/common/sframe-boot.js?ver=1.1" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<script async data-bootload="/file/inner.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script> <style>
<style>.loading-hidden, .loading-hidden * {display: none !important;}</style> .loading-hidden { display: none; }
#editor1 { display: none; }
</style>
</head> </head>
<body class="loading-hidden"> <body class="cp-app-file">
<div id="toolbar" class="toolbar-container"></div> <div id="cp-toolbar" class="cp-toolbar-container"></div>
<div id="app"> <div id="cp-app-file-content">
<div id="upload-form" style="display: none;"> <div id="cp-app-file-upload-form" style="display: none;">
<input type="file" name="file" id="file" class="inputfile" /> <input type="file" name="file" id="cp-app-file-upfile" class="cp-app-file-input" />
<label for="file" class="btn btn-primary block unselectable" data-localization-title="upload_choose" <label for="cp-app-file-upfile" class="btn btn-primary cp-app-file-block unselectable" data-localization-title="upload_choose"
data-localization="upload_choose"></label> data-localization="upload_choose"></label>
</div> </div>
<div id="download-form" style="display: none;"> <div id="cp-app-file-download-form" style="display: none;">
<input type="button" name="dl" id="dl" class="inputfile" /> <input type="button" name="dl" id="cp-app-file-dlfile" class="cp-app-file-input" />
<label for="dl" class="btn btn-success block unselectable" data-localization-title="download_button"><span data-localization="download_button"></span></label> <label for="cp-app-file-dlfile" class="btn btn-success cp-app-file-block unselectable" data-localization-title="download_button"><span data-localization="download_button"></span></label>
<span class="block" id="progress"></span> <span class="cp-app-file-block" id="cp-app-file-dlprogress"></span>
</div> </div>
<div id="download-view" style="display: none;"> <div id="cp-app-file-download-view" style="display: none;">
<media-tag id="encryptedFile"></media-tag> <media-tag id="cp-app-file-view"></media-tag>
</div> </div>
<div id="feedback" class="block hidden"> <div id="cp-app-file-feedback" class="cp-app-file-block cp-app-file-hidden">
</div> </div>
</div> </div>
</body> </body>

@ -1,14 +1,795 @@
define([ define([
'jquery', 'jquery',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css', '/bower_components/chainpad-crypto/crypto.js',
'/common/toolbar3.js',
'/common/cryptpad-common.js',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/common/common-realtime.js',
'/file/file-crypto.js',
'/common/media-tag.js',
'/bower_components/file-saver/FileSaver.min.js',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css', 'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'less!/file/file.less', 'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less/cryptpad.less', 'less!/customize/src/less2/main.less',
'less!/customize/src/less/toolbar.less',
], function ($) { ], function (
$('.loading-hidden').removeClass('loading-hidden'); $,
// dirty hack to get rid the flash of the lock background Crypto,
setTimeout(function () { Toolbar,
$('#app').addClass('ready'); Cryptpad,
}, 100); nThen,
SFCommon,
CommonRealtime,
FileCrypto,
MediaTag)
{
var Messages = Cryptpad.Messages;
var saveAs = window.saveAs;
var Nacl = window.nacl;
var APP = window.APP = {
Cryptpad: Cryptpad,
};
var andThen = function (common) {
var $appContainer = $('#cp-app-file-content');
var $form = $('#cp-app-file-upload-form');
var $dlform = $('#cp-app-file-download-form');
var $dlview = $('#cp-app-file-download-view');
var $label = $form.find('label');
var $dllabel = $dlform.find('label span');
var $progress = $('#cp-app-file-dlprogress');
var $bar = $('.cp-toolbar-container');
var $body = $('body');
$body.on('dragover', function (e) { e.preventDefault(); });
$body.on('drop', function (e) { e.preventDefault(); });
var uploadMode = false;
var secret;
var hexFileName;
var metadataMgr = common.getMetadataMgr();
var priv = metadataMgr.getPrivateData();
if (!priv.filehash) {
uploadMode = true;
} else {
secret = Cryptpad.getSecrets('file', priv.filehash);
if (!secret.keys) { throw new Error("You need a hash"); }
hexFileName = Cryptpad.base64ToHex(secret.channel);
}
var Title = common.createTitle({});
var displayed = ['useradmin', 'newpad', 'limit', 'upgrade'];
if (!uploadMode) {
displayed.push('fileshare');
}
var configTb = {
displayed: displayed,
common: Cryptpad,
//hideDisplayName: true,
$container: $bar,
metadataMgr: metadataMgr,
sfCommon: common,
};
if (uploadMode) {
displayed.push('pageTitle'); //TODO in toolbar
configTb.pageTitle = Messages.upload_title;
}
var toolbar = APP.toolbar = Toolbar.create(configTb);
toolbar.$rightside.html('');
if (!uploadMode) {
var src = Cryptpad.getBlobPathFromHex(hexFileName);
var cryptKey = secret.keys && secret.keys.fileKeyStr;
var key = Nacl.util.decodeBase64(cryptKey);
FileCrypto.fetchDecryptedMetadata(src, key, function (e, metadata) {
if (e) { return void console.error(e); }
var title = document.title = metadata.name;
Title.updateTitle(title || Title.defaultTitle);
toolbar.addElement(['pageTitle'], {pageTitle: title});
var displayFile = function (ev, sizeMb, CB) {
var called_back;
var cb = function (e) {
if (called_back) { return; }
called_back = true;
if (CB) { CB(e); }
};
var $mt = $dlview.find('media-tag');
var cryptKey = secret.keys && secret.keys.fileKeyStr;
var hexFileName = Cryptpad.base64ToHex(secret.channel);
$mt.attr('src', '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName);
$mt.attr('data-crypto-key', 'cryptpad:'+cryptKey);
var rightsideDisplayed = false;
$(window.document).on('decryption', function (e) {
var decrypted = e.originalEvent;
if (decrypted.callback) {
decrypted.callback();
}
console.log(decrypted);
$dlview.show();
$dlform.hide();
var $dlButton = $dlview.find('media-tag button');
if (ev) { $dlButton.click(); }
if (!$dlButton.length) {
$appContainer.css('background', 'white');
}
$dlButton.addClass('btn btn-success');
var text = Messages.download_mt_button + '<br>';
text += '<b>' + Cryptpad.fixHTML(title) + '</b><br>';
text += '<em>' + Messages._getKey('formattedMB', [sizeMb]) + '</em>';
$dlButton.html(text);
if (!rightsideDisplayed) {
toolbar.$rightside
.append(common.createButton('export', true, {}, function () {
saveAs(decrypted.blob, decrypted.metadata.name);
}))
.append(common.createButton('forget', true, {}, function () {
// not sure what to do here
}));
rightsideDisplayed = true;
}
// make pdfs big
var toolbarHeight = $('#cp-toolbar').height();
var $another_iframe = $('media-tag iframe').css({
'height': 'calc(100vh - ' + toolbarHeight + 'px)',
'width': '100vw',
'position': 'absolute',
'bottom': 0,
'left': 0,
'border': 0
});
if ($another_iframe.length) {
$another_iframe.load(function () {
cb();
});
} else {
cb();
}
})
.on('decryptionError', function (e) {
var error = e.originalEvent;
//Cryptpad.alert(error.message);
cb(error.message);
})
.on('decryptionProgress', function (e) {
var progress = e.originalEvent;
var p = progress.percent +'%';
$progress.width(p);
console.log(progress.percent);
});
/**
* Allowed mime types that have to be set for a rendering after a decryption.
*
* @type {Array}
*/
var allowedMediaTypes = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'audio/mp3',
'audio/ogg',
'audio/wav',
'audio/webm',
'video/mp4',
'video/ogg',
'video/webm',
'application/pdf',
'application/dash+xml',
'download'
];
MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);
MediaTag($mt[0]);
};
var todoBigFile = function (sizeMb) {
$dlform.show();
Cryptpad.removeLoadingScreen();
$dllabel.append($('<br>'));
$dllabel.append(Cryptpad.fixHTML(metadata.name));
// don't display the size if you don't know it.
if (typeof(sizeM) === 'number') {
$dllabel.append($('<br>'));
$dllabel.append(Messages._getKey('formattedMB', [sizeMb]));
}
var decrypting = false;
var onClick = function (ev) {
if (decrypting) { return; }
decrypting = true;
displayFile(ev, sizeMb, function (err) {
if (err) { Cryptpad.alert(err); }
});
};
if (typeof(sizeMb) === 'number' && sizeMb < 5) { return void onClick(); }
$dlform.find('#cp-app-file-dlfile, #cp-app-file-dlprogress').click(onClick);
};
var href = priv.origin + priv.pathname + priv.filehash;
common.getFileSize(href, function (e, data) {
if (e) {
return void Cryptpad.errorLoadingScreen(e);
}
var size = Cryptpad.bytesToMegabytes(data);
return void todoBigFile(size);
});
});
return;
}
if (!common.isLoggedIn()) {
// TODO
return Cryptpad.alert(Messages.upload_mustLogin, function () {
if (sessionStorage) {
sessionStorage.redirectTo = window.location.href;
}
window.location.href = '/login/';
});
}
$form.css({
display: 'block',
});
var fmConfig = {
dropArea: $form,
hoverArea: $label,
body: $body,
keepTable: true // Don't fadeOut the tbale with the uploaded files
};
var FM = common.createFileManager(fmConfig);
$form.find("#cp-app-file-upfile").on('change', function (e) {
var file = e.target.files[0];
FM.handleFile(file);
});
// we're in upload mode
Cryptpad.removeLoadingScreen();
return;
//===========================================================================
var readOnly = false;
var cpNfInner;
var metadataMgr;
var $bar = $('#cme_toolbox');
var isHistoryMode = false;
var setEditable = APP.setEditable = function (bool) {
if (readOnly && bool) { return; }
editor.setOption('readOnly', !bool);
};
var Title;
var config = {
readOnly: readOnly,
transformFunction: JsonOT.validate,
// cryptpad debug logging (default is 1)
// logLevel: 0,
validateContent: function (content) {
try {
JSON.parse(content);
return true;
} catch (e) {
console.log("Failed to parse, rejecting patch");
return false;
}
}
};
var canonicalize = function (t) { return t.replace(/\r\n/g, '\n'); };
var setHistory = function (bool, update) {
isHistoryMode = bool;
setEditable(!bool);
if (!bool && update) {
config.onRemote();
}
};
var $contentContainer = $('#cp-app-code-editor');
var $previewContainer = $('#cp-app-code-preview');
var $preview = $('#cp-app-code-preview-content');
$preview.click(function (e) {
if (!e.target) { return; }
var $t = $(e.target);
if ($t.is('a') || $t.parents('a').length) {
e.preventDefault();
var $a = $t.is('a') ? $t : $t.parents('a').first();
var href = $a.attr('href');
window.open(href);
}
});
var setIndentation = APP.setIndentation = function (units, useTabs) {
if (typeof(units) !== 'number') { return; }
editor.setOption('indentUnit', units);
editor.setOption('tabSize', units);
editor.setOption('indentWithTabs', useTabs);
};
var indentKey = 'indentUnit';
var useTabsKey = 'indentWithTabs';
var updateIndentSettings = function () {
if (!metadataMgr) { return; }
var data = metadataMgr.getPrivateData().settings;
data = data.codemirror || {};
var indentUnit = data[indentKey];
var useTabs = data[useTabsKey];
setIndentation(
typeof(indentUnit) === 'number'? indentUnit: 2,
typeof(useTabs) === 'boolean'? useTabs: false);
};
CommonRealtime.onInfiniteSpinner(function () { setEditable(false); });
setEditable(false);
var initializing = true;
var stringifyInner = function (textValue) {
var obj = {
content: textValue,
metadata: metadataMgr.getMetadataLazy()
};
/* metadata: {
users: UserList.userData,
defaultTitle: Title.defaultTitle
}
};
if (!initializing) {
obj.metadata.title = Title.title;
}*/
// set mode too...
obj.highlightMode = CodeMirror.highlightMode;
// stringify the json and send it into chainpad
return stringify(obj);
};
var forceDrawPreview = function () {
try {
DiffMd.apply(DiffMd.render(editor.getValue()), $preview);
} catch (e) { console.error(e); }
};
var drawPreview = Cryptpad.throttle(function () {
if (CodeMirror.highlightMode !== 'markdown') { return; }
if (!$previewContainer.is(':visible')) { return; }
forceDrawPreview();
}, 150);
var onLocal = config.onLocal = function () {
if (initializing) { return; }
if (isHistoryMode) { return; }
if (readOnly) { return; }
editor.save();
drawPreview();
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson = stringifyInner(textValue);
APP.patchText(shjson);
if (APP.realtime.getUserDoc() !== shjson) {
console.error("realtime.getUserDoc() !== shjson");
}
};
var mediaTagModes = [
'markdown',
'html',
'htmlembedded',
'htmlmixed',
'index.html',
'php',
'velocity',
'xml',
];
var onModeChanged = function (mode) {
var $codeMirror = $('.CodeMirror');
window.clearTimeout(APP.previewTo);
$codeMirror.addClass('transition');
APP.previewTo = window.setTimeout(function () {
$codeMirror.removeClass('transition');
}, 500);
if (mediaTagModes.indexOf(mode) !== -1) {
$(APP.$mediaTagButton).show();
} else { $(APP.$mediaTagButton).hide(); }
if (mode === "markdown") {
APP.$previewButton.show();
common.getPadAttribute('previewMode', function (e, data) {
if (e) { return void console.error(e); }
if (data !== false) {
$previewContainer.show();
APP.$previewButton.addClass('active');
$codeMirror.removeClass('fullPage');
}
});
return;
}
APP.$previewButton.hide();
$previewContainer.hide();
APP.$previewButton.removeClass('active');
$codeMirror.addClass('fullPage');
};
config.onInit = function (info) {
metadataMgr.onChangeLazy(updateIndentSettings);
updateIndentSettings();
readOnly = metadataMgr.getPrivateData().readOnly;
var titleCfg = { getHeadingText: CodeMirror.getHeadingText };
Title = common.createTitle(titleCfg, config.onLocal);
var configTb = {
displayed: ['title', 'useradmin', 'spinner', 'share', 'userlist', 'newpad', 'limit'],
title: Title.getTitleConfig(),
metadataMgr: metadataMgr,
readOnly: readOnly,
ifrw: window,
realtime: info.realtime,
common: Cryptpad,
sfCommon: common,
$container: $bar,
$contentContainer: $contentContainer
};
toolbar = APP.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
CodeMirror.init(config.onLocal, Title, toolbar);
var $rightside = toolbar.$rightside;
var $drawer = toolbar.$drawer;
/* add a history button */
var histConfig = {
onLocal: config.onLocal,
onRemote: config.onRemote,
setHistory: setHistory,
applyVal: function (val) {
var remoteDoc = JSON.parse(val || '{}').content;
editor.setValue(remoteDoc || '');
editor.save();
},
$toolbar: $bar
};
var $hist = common.createButton('history', true, {histConfig: histConfig});
$drawer.append($hist);
/* save as template */
if (!metadataMgr.getPrivateData().isTemplate) {
var templateObj = {
rt: info.realtime,
getTitle: function () { return metadataMgr.getMetadata().title; }
};
var $templateButton = common.createButton('template', true, templateObj);
$rightside.append($templateButton);
}
/* add an export button */
var $export = common.createButton('export', true, {}, CodeMirror.exportText);
$drawer.append($export);
if (!readOnly) {
/* add an import button */
var $import = common.createButton('import', true, {}, CodeMirror.importText);
$drawer.append($import);
}
/* add a forget button */
var forgetCb = function (err) {
if (err) { return; }
setEditable(false);
};
var $forgetPad = common.createButton('forget', true, {}, forgetCb);
$rightside.append($forgetPad);
var $previewButton = APP.$previewButton = common.createButton(null, true);
$previewButton.removeClass('fa-question').addClass('fa-eye');
$previewButton.attr('title', Messages.previewButtonTitle);
$previewButton.click(function () {
var $codeMirror = $('.CodeMirror');
window.clearTimeout(APP.previewTo);
$codeMirror.addClass('transition');
APP.previewTo = window.setTimeout(function () {
$codeMirror.removeClass('transition');
}, 500);
if (CodeMirror.highlightMode !== 'markdown') {
$previewContainer.show();
}
$previewContainer.toggle();
if ($previewContainer.is(':visible')) {
forceDrawPreview();
$codeMirror.removeClass('cp-ap-code-fullpage');
$previewButton.addClass('cp-toolbar-button-active');
common.setPadAttribute('previewMode', true, function (e) {
if (e) { return console.log(e); }
});
} else {
$codeMirror.addClass('cp-app-code-fullpage');
$previewButton.removeClass('cp-toolbar-button-active');
common.setPadAttribute('previewMode', false, function (e) {
if (e) { return console.log(e); }
});
}
});
$rightside.append($previewButton);
if (!readOnly) {
CodeMirror.configureTheme(function () {
CodeMirror.configureLanguage(null, onModeChanged);
});
}
else {
CodeMirror.configureTheme();
}
if (!readOnly) {
var fileDialogCfg = {
onSelect: function (data) {
if (data.type === 'file') {
var mt = '<media-tag src="' + data.src + '" data-crypto-key="cryptpad:' + data.key + '"></media-tag>';
editor.replaceSelection(mt);
return;
}
}
};
common.initFilePicker(fileDialogCfg);
APP.$mediaTagButton = $('<button>', {
title: Messages.filePickerButton,
'class': 'cp-toolbar-rightside-button fa fa-picture-o',
style: 'font-size: 17px'
}).click(function () {
var pickerCfg = {
types: ['file'],
where: ['root']
};
common.openFilePicker(pickerCfg);
}).appendTo($rightside);
}
};
config.onReady = function (info) {
console.log('onready');
if (APP.realtime !== info.realtime) {
var realtime = APP.realtime = info.realtime;
APP.patchText = TextPatcher.create({
realtime: realtime,
//logging: true
});
}
var userDoc = APP.realtime.getUserDoc();
var isNew = false;
if (userDoc === "" || userDoc === "{}") { isNew = true; }
var newDoc = "";
if (userDoc !== "") {
var hjson = JSON.parse(userDoc);
if (hjson && hjson.metadata) {
metadataMgr.updateMetadata(hjson.metadata);
}
if (typeof (hjson) !== 'object' || Array.isArray(hjson) ||
(typeof(hjson.type) !== 'undefined' && hjson.type !== 'code')) {
var errorText = Messages.typeError;
Cryptpad.errorLoadingScreen(errorText);
throw new Error(errorText);
}
newDoc = hjson.content;
if (hjson.highlightMode) {
CodeMirror.setMode(hjson.highlightMode, onModeChanged);
}
} else {
Title.updateTitle(Cryptpad.initialName || Title.defaultTitle);
}
if (!CodeMirror.highlightMode) {
CodeMirror.setMode('markdown', onModeChanged);
//console.log("%s => %s", CodeMirror.highlightMode, CodeMirror.$language.val());
}
// Update the user list (metadata) from the hyperjson
//Metadata.update(userDoc);
if (newDoc) {
editor.setValue(newDoc);
}
if (Cryptpad.initialName && Title.isDefaultTitle()) {
Title.updateTitle(Cryptpad.initialName);
}
common.getPadAttribute('previewMode', function (e, data) {
if (e) { return void console.error(e); }
if (data === false && APP.$previewButton) {
APP.$previewButton.click();
}
});
/*
// add the splitter
if (!$iframe.has('.cp-splitter').length) {
var $preview = $iframe.find('#previewContainer');
var splitter = $('<div>', {
'class': 'cp-splitter'
}).appendTo($preview);
$preview.on('scroll', function() {
splitter.css('top', $preview.scrollTop() + 'px');
});
var $target = $iframe.find('.CodeMirror');
splitter.on('mousedown', function (e) {
e.preventDefault();
var x = e.pageX;
var w = $target.width();
$iframe.on('mouseup mousemove', function handler(evt) {
if (evt.type === 'mouseup') {
$iframe.off('mouseup mousemove', handler);
return;
}
$target.css('width', (w - x + evt.pageX) + 'px');
});
});
}
*/
Cryptpad.removeLoadingScreen();
setEditable(!readOnly);
initializing = false;
onLocal(); // push local state to avoid parse errors later.
if (readOnly) {
config.onRemote();
return;
}
if (isNew) {
common.openTemplatePicker();
}
var fmConfig = {
dropArea: $('.CodeMirror'),
body: $('body'),
onUploaded: function (ev, data) {
//var cursor = editor.getCursor();
//var cleanName = data.name.replace(/[\[\]]/g, '');
//var text = '!['+cleanName+']('+data.url+')';
var parsed = Cryptpad.parsePadUrl(data.url);
var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel);
var src = '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName;
var mt = '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>';
editor.replaceSelection(mt);
}
};
APP.FM = common.createFileManager(fmConfig);
};
config.onRemote = function () {
if (initializing) { return; }
if (isHistoryMode) { return; }
var oldDoc = canonicalize(CodeMirror.$textarea.val());
var shjson = APP.realtime.getUserDoc();
// Update the user list (metadata) from the hyperjson
//Metadata.update(shjson);
var hjson = JSON.parse(shjson);
var remoteDoc = hjson.content;
if (hjson.metadata) {
metadataMgr.updateMetadata(hjson.metadata);
}
var highlightMode = hjson.highlightMode;
if (highlightMode && highlightMode !== APP.highlightMode) {
CodeMirror.setMode(highlightMode, onModeChanged);
}
CodeMirror.setValueAndCursor(oldDoc, remoteDoc, TextPatcher);
drawPreview();
if (!readOnly) {
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson2 = stringifyInner(textValue);
if (shjson2 !== shjson) {
console.error("shjson2 !== shjson");
TextPatcher.log(shjson, TextPatcher.diff(shjson, shjson2));
APP.patchText(shjson2);
}
}
if (oldDoc !== remoteDoc) { Cryptpad.notify(); }
};
config.onAbort = function () {
// inform of network disconnect
setEditable(false);
toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
};
config.onConnectionChange = function (info) {
setEditable(info.state);
//toolbar.failed();
if (info.state) {
initializing = true;
//toolbar.reconnecting(info.myId);
Cryptpad.findOKButton().click();
} else {
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}
};
config.onError = onConnectError;
cpNfInner = common.startRealtime(config);
metadataMgr = cpNfInner.metadataMgr;
cpNfInner.onInfiniteSpinner(function () {
setEditable(false);
Cryptpad.confirm(Messages.realtime_unrecoverableError, function (yes) {
if (!yes) { return; }
common.gotoURL();
});
});
editor.on('change', onLocal);
Cryptpad.onLogout(function () { setEditable(false); });
};
var main = function () {
var common;
nThen(function (waitFor) {
$(waitFor(function () {
Cryptpad.addLoadingScreen();
}));
SFCommon.create(waitFor(function (c) { APP.common = common = c; }));
}).nThen(function (/*waitFor*/) {
common.getSframeChannel().onReady(function () {
andThen(common);
});
});
};
main();
}); });

@ -1,269 +1,47 @@
// Load #1, load as little as possible because we are in a race to get the loading screen up.
define([ define([
'/bower_components/nthen/index.js',
'/api/config',
'jquery', 'jquery',
'/bower_components/chainpad-crypto/crypto.js', '/common/requireconfig.js',
'/bower_components/chainpad-netflux/chainpad-netflux.js', '/common/sframe-common-outer.js'
'/common/toolbar2.js', ], function (nThen, ApiConfig, $, RequireConfig, SFCommonO) {
'/common/cryptpad-common.js', var requireConfig = RequireConfig();
'/common/visible.js',
'/common/notify.js', // Loaded in load #2
'/file/file-crypto.js', nThen(function (waitFor) {
$(waitFor());
'/common/media-tag.js', }).nThen(function (waitFor) {
var req = {
'/bower_components/file-saver/FileSaver.min.js', cfg: requireConfig,
req: [ '/common/loading.js' ],
'css!/bower_components/components-font-awesome/css/font-awesome.min.css', pfx: window.location.origin
'less!/customize/src/less/cryptpad.less',
], function ($, Crypto, realtimeInput, Toolbar, Cryptpad, Visible, Notify, FileCrypto, MediaTag) {
var Messages = Cryptpad.Messages;
var saveAs = window.saveAs;
var Nacl = window.nacl;
var APP = window.APP = {};
$(function () {
var andThen = function () {
var ifrw = $('#pad-iframe')[0].contentWindow;
var $iframe = $('#pad-iframe').contents();
var $appContainer = $iframe.find('#app');
var $form = $iframe.find('#upload-form');
var $dlform = $iframe.find('#download-form');
var $dlview = $iframe.find('#download-view');
var $label = $form.find('label');
var $dllabel = $dlform.find('label span');
var $progress = $iframe.find('#progress');
var $body = $iframe.find('body');
$body.on('dragover', function (e) { e.preventDefault(); });
$body.on('drop', function (e) { e.preventDefault(); });
Cryptpad.addLoadingScreen();
var Title;
var uploadMode = false;
var $bar = $iframe.find('.toolbar-container');
var secret;
var hexFileName;
if (window.location.hash) {
secret = Cryptpad.getSecrets();
if (!secret.keys) { throw new Error("You need a hash"); } // TODO
hexFileName = Cryptpad.base64ToHex(secret.channel);
} else {
uploadMode = true;
}
Title = Cryptpad.createTitle({}, function(){}, Cryptpad);
var displayed = ['useradmin', 'newpad', 'limit', 'upgrade'];
if (secret && hexFileName) {
displayed.push('fileshare');
}
var configTb = {
displayed: displayed,
ifrw: ifrw,
common: Cryptpad,
//hideDisplayName: true,
$container: $bar,
};
if (uploadMode) {
displayed.push('pageTitle');
configTb.pageTitle = Messages.upload_title;
}
var toolbar = APP.toolbar = Toolbar.create(configTb);
toolbar.$rightside.html(''); // Remove the drawer if we don't use it to hide the toolbar
if (!uploadMode) {
var src = Cryptpad.getBlobPathFromHex(hexFileName);
var cryptKey = secret.keys && secret.keys.fileKeyStr;
var key = Nacl.util.decodeBase64(cryptKey);
FileCrypto.fetchDecryptedMetadata(src, key, function (e, metadata) {
if (e) { return void console.error(e); }
var title = document.title = metadata.name;
Title.updateTitle(title || Title.defaultTitle);
toolbar.addElement(['pageTitle'], {pageTitle: title});
console.error(metadata);
var displayFile = function (ev, sizeMb, CB) {
var called_back;
var cb = function (e) {
if (called_back) { return; }
called_back = true;
if (CB) { CB(e); }
};
var $mt = $dlview.find('media-tag');
var cryptKey = secret.keys && secret.keys.fileKeyStr;
var hexFileName = Cryptpad.base64ToHex(secret.channel);
$mt.attr('src', '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName);
$mt.attr('data-crypto-key', 'cryptpad:'+cryptKey);
var rightsideDisplayed = false;
$(window.document).on('decryption', function (e) {
var decrypted = e.originalEvent;
if (decrypted.callback) {
decrypted.callback();
}
console.log(decrypted);
$dlview.show();
$dlform.hide();
var $dlButton = $dlview.find('media-tag button');
if (ev) { $dlButton.click(); }
if (!$dlButton.length) {
$appContainer.css('background', 'white');
}
$dlButton.addClass('btn btn-success');
var text = Messages.download_mt_button + '<br>';
text += '<b>' + Cryptpad.fixHTML(title) + '</b><br>';
text += '<em>' + Messages._getKey('formattedMB', [sizeMb]) + '</em>';
$dlButton.html(text);
if (!rightsideDisplayed) {
toolbar.$rightside.append(Cryptpad.createButton('export', true, {}, function () {
saveAs(decrypted.blob, decrypted.metadata.name);
}))
.append(Cryptpad.createButton('forget', true, {}, function () {
// not sure what to do here
}));
rightsideDisplayed = true;
}
// make pdfs big
var toolbarHeight = $iframe.find('#toolbar').height();
var $another_iframe = $iframe.find('media-tag iframe').css({
'height': 'calc(100vh - ' + toolbarHeight + 'px)',
'width': '100vw',
'position': 'absolute',
'bottom': 0,
'left': 0,
'border': 0
});
if ($another_iframe.length) {
$another_iframe.load(function () {
cb();
});
} else {
cb();
}
})
.on('decryptionError', function (e) {
var error = e.originalEvent;
//Cryptpad.alert(error.message);
cb(error.message);
})
.on('decryptionProgress', function (e) {
var progress = e.originalEvent;
var p = progress.percent +'%';
$progress.width(p);
console.log(progress.percent);
});
/**
* Allowed mime types that have to be set for a rendering after a decryption.
*
* @type {Array}
*/
var allowedMediaTypes = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'audio/mp3',
'audio/ogg',
'audio/wav',
'audio/webm',
'video/mp4',
'video/ogg',
'video/webm',
'application/pdf',
'application/dash+xml',
'download'
];
MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);
MediaTag($mt[0]);
}; };
window.rc = requireConfig;
var todoBigFile = function (sizeMb) { window.apiconf = ApiConfig;
$dlform.show(); $('#sbox-iframe').attr('src',
Cryptpad.removeLoadingScreen(); ApiConfig.httpSafeOrigin + '/file/inner.html?' + requireConfig.urlArgs +
$dllabel.append($('<br>')); '#' + encodeURIComponent(JSON.stringify(req)));
$dllabel.append(Cryptpad.fixHTML(metadata.name));
// This is a cheap trick to avoid loading sframe-channel in parallel with the
// don't display the size if you don't know it. // loading screen setup.
if (typeof(sizeM) === 'number') { var done = waitFor();
$dllabel.append($('<br>')); var onMsg = function (msg) {
$dllabel.append(Messages._getKey('formattedMB', [sizeMb])); var data = JSON.parse(msg.data);
} if (data.q !== 'READY') { return; }
var decrypting = false; window.removeEventListener('message', onMsg);
var onClick = function (ev) { var _done = done;
if (decrypting) { return; } done = function () { };
decrypting = true; _done();
displayFile(ev, sizeMb, function (err) {
if (err) { Cryptpad.alert(err); }
});
}; };
if (typeof(sizeMb) === 'number' && sizeMb < 5) { return void onClick(); } window.addEventListener('message', onMsg);
$dlform.find('#dl, #progress').click(onClick); }).nThen(function (/*waitFor*/) {
var addData = function (meta) {
meta.filehash = window.location.hash;
}; };
Cryptpad.getFileSize(window.location.href, function (e, data) { SFCommonO.start({
if (e) { noRealtime: true,
return void Cryptpad.errorLoadingScreen(e); addData: addData
}
var size = Cryptpad.bytesToMegabytes(data);
return void todoBigFile(size);
});
}); });
return;
}
if (!Cryptpad.isLoggedIn()) {
return Cryptpad.alert(Messages.upload_mustLogin, function () {
if (sessionStorage) {
sessionStorage.redirectTo = window.location.href;
}
window.location.href = '/login/';
});
}
$form.css({
display: 'block',
});
var fmConfig = {
dropArea: $form,
hoverArea: $label,
body: $body,
keepTable: true // Don't fadeOut the tbale with the uploaded files
};
var FM = Cryptpad.createFileManager(fmConfig);
$form.find("#file").on('change', function (e) {
var file = e.target.files[0];
FM.handleFile(file);
});
// we're in upload mode
Cryptpad.removeLoadingScreen();
};
Cryptpad.ready(function () {
andThen();
Cryptpad.reportAppUsage();
});
}); });
}); });

@ -0,0 +1,271 @@
define([
'/bower_components/tweetnacl/nacl-fast.min.js',
], function () {
var Nacl = window.nacl;
var PARANOIA = true;
var plainChunkLength = 128 * 1024;
var cypherChunkLength = 131088;
var computeEncryptedSize = function (bytes, meta) {
var metasize = Nacl.util.decodeUTF8(JSON.stringify(meta)).length;
var chunks = Math.ceil(bytes / plainChunkLength);
return metasize + 18 + (chunks * 16) + bytes;
};
var encodePrefix = function (p) {
return [
65280, // 255 << 8
255,
].map(function (n, i) {
return (p & n) >> ((1 - i) * 8);
});
};
var decodePrefix = function (A) {
return (A[0] << 8) | A[1];
};
var slice = function (A) {
return Array.prototype.slice.call(A);
};
var createNonce = function () {
return new Uint8Array(new Array(24).fill(0));
};
var increment = function (N) {
var l = N.length;
while (l-- > 1) {
if (PARANOIA) {
if (typeof(N[l]) !== 'number') {
throw new Error('E_UNSAFE_TYPE');
}
if (N[l] > 255) {
throw new Error('E_OUT_OF_BOUNDS');
}
}
/* jshint probably suspects this is unsafe because we lack types
but as long as this is only used on nonces, it should be safe */
if (N[l] !== 255) { return void N[l]++; } // jshint ignore:line
N[l] = 0;
// you don't need to worry about this running out.
// you'd need a REAAAALLY big file
if (l === 0) {
throw new Error('E_NONCE_TOO_LARGE');
}
}
};
var joinChunks = function (chunks) {
return new Blob(chunks);
};
var concatBuffer = function (a, b) { // TODO make this not so ugly
return new Uint8Array(slice(a).concat(slice(b)));
};
var fetchMetadata = function (src, cb) {
var done = false;
var CB = function (err, res) {
if (done) { return; }
done = true;
cb(err, res);
};
var xhr = new XMLHttpRequest();
xhr.open("GET", src, true);
xhr.setRequestHeader('Range', 'bytes=0-1');
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (/^4/.test('' + this.status)) { return CB('XHR_ERROR'); }
var res = new Uint8Array(xhr.response);
var size = decodePrefix(res);
var xhr2 = new XMLHttpRequest();
xhr2.open("GET", src, true);
xhr2.setRequestHeader('Range', 'bytes=2-' + (size + 2));
xhr2.responseType = 'arraybuffer';
xhr2.onload = function () {
if (/^4/.test('' + this.status)) { return CB('XHR_ERROR'); }
var res2 = new Uint8Array(xhr2.response);
var all = concatBuffer(res, res2);
CB(void 0, all);
};
xhr2.send(null);
};
xhr.send(null);
};
var decryptMetadata = function (u8, key) {
var prefix = u8.subarray(0, 2);
var metadataLength = decodePrefix(prefix);
var metaBox = new Uint8Array(u8.subarray(2, 2 + metadataLength));
var metaChunk = Nacl.secretbox.open(metaBox, createNonce(), key);
try {
return JSON.parse(Nacl.util.encodeUTF8(metaChunk));
}
catch (e) { return null; }
};
var fetchDecryptedMetadata = function (src, key, cb) {
if (typeof(src) !== 'string') {
return window.setTimeout(function () {
cb('NO_SOURCE');
});
}
fetchMetadata(src, function (e, buffer) {
if (e) { return cb(e); }
cb(void 0, decryptMetadata(buffer, key));
});
};
var decrypt = function (u8, key, done, progress) {
var MAX = u8.length;
var _progress = function (offset) {
if (typeof(progress) !== 'function') { return; }
progress(Math.min(1, offset / MAX));
};
var nonce = createNonce();
var i = 0;
var prefix = u8.subarray(0, 2);
var metadataLength = decodePrefix(prefix);
var res = {
metadata: undefined,
};
var metaBox = new Uint8Array(u8.subarray(2, 2 + metadataLength));
var metaChunk = Nacl.secretbox.open(metaBox, nonce, key);
increment(nonce);
try {
res.metadata = JSON.parse(Nacl.util.encodeUTF8(metaChunk));
} catch (e) {
return window.setTimeout(function () {
done('E_METADATA_DECRYPTION');
});
}
if (!res.metadata) {
return void setTimeout(function () {
done('NO_METADATA');
});
}
var takeChunk = function (cb) {
var start = i * cypherChunkLength + 2 + metadataLength;
var end = start + cypherChunkLength;
i++;
var box = new Uint8Array(u8.subarray(start, end));
// decrypt the chunk
var plaintext = Nacl.secretbox.open(box, nonce, key);
increment(nonce);
if (!plaintext) { return cb('DECRYPTION_ERROR'); }
_progress(end);
cb(void 0, plaintext);
};
var chunks = [];
var again = function () {
takeChunk(function (e, plaintext) {
if (e) {
return setTimeout(function () {
done(e);
});
}
if (plaintext) {
if ((2 + metadataLength + i * cypherChunkLength) < u8.length) { // not done
chunks.push(plaintext);
return setTimeout(again);
}
chunks.push(plaintext);
res.content = joinChunks(chunks);
return done(void 0, res);
}
done('UNEXPECTED_ENDING');
});
};
again();
};
// metadata
/* { filename: 'raccoon.jpg', type: 'image/jpeg' } */
var encrypt = function (u8, metadata, key) {
var nonce = createNonce();
// encode metadata
var plaintext = Nacl.util.decodeUTF8(JSON.stringify(metadata));
// if metadata is too large, drop the thumbnail.
if (plaintext.length > 65535) {
var temp = JSON.parse(JSON.stringify(metadata));
delete metadata.thumbnail;
plaintext = Nacl.util.decodeUTF8(JSON.stringify(temp));
}
var i = 0;
var state = 0;
var next = function (cb) {
if (state === 2) { return void cb(); }
var start;
var end;
var part;
var box;
if (state === 0) { // metadata...
part = new Uint8Array(plaintext);
box = Nacl.secretbox(part, nonce, key);
increment(nonce);
if (box.length > 65535) {
return void cb('METADATA_TOO_LARGE');
}
var prefixed = new Uint8Array(encodePrefix(box.length)
.concat(slice(box)));
state++;
return void cb(void 0, prefixed);
}
// encrypt the rest of the file...
start = i * plainChunkLength;
end = start + plainChunkLength;
part = u8.subarray(start, end);
box = Nacl.secretbox(part, nonce, key);
increment(nonce);
i++;
// regular data is done
if (i * plainChunkLength >= u8.length) { state = 2; }
return void cb(void 0, box);
};
return next;
};
return {
decrypt: decrypt,
encrypt: encrypt,
joinChunks: joinChunks,
computeEncryptedSize: computeEncryptedSize,
decryptMetadata: decryptMetadata,
fetchMetadata: fetchMetadata,
fetchDecryptedMetadata: fetchDecryptedMetadata,
};
});

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html class="cp pad">
<head>
<title>CryptPad</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script async data-bootload="/customize/template.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style>
html, body {
margin: 0px;
padding: 0px;
}
#pad-iframe {
position:fixed;
top:0px;
left:0px;
bottom:0px;
right:0px;
width:100%;
height:100%;
border:none;
margin:0;
padding:0;
overflow:hidden;
}
</style>
</head>
<body>
<iframe id="pad-iframe"></iframe><script src="/common/noscriptfix.js"></script>

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script async data-bootload="/file/inner.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style>.loading-hidden, .loading-hidden * {display: none !important;}</style>
</head>
<body class="loading-hidden">
<div id="toolbar" class="toolbar-container"></div>
<div id="app">
<div id="upload-form" style="display: none;">
<input type="file" name="file" id="file" class="inputfile" />
<label for="file" class="btn btn-primary block unselectable" data-localization-title="upload_choose"
data-localization="upload_choose"></label>
</div>
<div id="download-form" style="display: none;">
<input type="button" name="dl" id="dl" class="inputfile" />
<label for="dl" class="btn btn-success block unselectable" data-localization-title="download_button"><span data-localization="download_button"></span></label>
<span class="block" id="progress"></span>
</div>
<div id="download-view" style="display: none;">
<media-tag id="encryptedFile"></media-tag>
</div>
<div id="feedback" class="block hidden">
</div>
</div>
</body>
</html>

@ -0,0 +1,14 @@
define([
'jquery',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'less!/file/file.less',
'less!/customize/src/less/cryptpad.less',
'less!/customize/src/less/toolbar.less',
], function ($) {
$('.loading-hidden').removeClass('loading-hidden');
// dirty hack to get rid the flash of the lock background
setTimeout(function () {
$('#app').addClass('ready');
}, 100);
});

@ -0,0 +1,269 @@
define([
'jquery',
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/chainpad-netflux/chainpad-netflux.js',
'/common/toolbar2.js',
'/common/cryptpad-common.js',
'/common/visible.js',
'/common/notify.js',
'/file/file-crypto.js',
'/common/media-tag.js',
'/bower_components/file-saver/FileSaver.min.js',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less/cryptpad.less',
], function ($, Crypto, realtimeInput, Toolbar, Cryptpad, Visible, Notify, FileCrypto, MediaTag) {
var Messages = Cryptpad.Messages;
var saveAs = window.saveAs;
var Nacl = window.nacl;
var APP = window.APP = {};
$(function () {
var andThen = function () {
var ifrw = $('#pad-iframe')[0].contentWindow;
var $iframe = $('#pad-iframe').contents();
var $appContainer = $iframe.find('#app');
var $form = $iframe.find('#upload-form');
var $dlform = $iframe.find('#download-form');
var $dlview = $iframe.find('#download-view');
var $label = $form.find('label');
var $dllabel = $dlform.find('label span');
var $progress = $iframe.find('#progress');
var $body = $iframe.find('body');
$body.on('dragover', function (e) { e.preventDefault(); });
$body.on('drop', function (e) { e.preventDefault(); });
Cryptpad.addLoadingScreen();
var Title;
var uploadMode = false;
var $bar = $iframe.find('.toolbar-container');
var secret;
var hexFileName;
if (window.location.hash) {
secret = Cryptpad.getSecrets();
if (!secret.keys) { throw new Error("You need a hash"); } // TODO
hexFileName = Cryptpad.base64ToHex(secret.channel);
} else {
uploadMode = true;
}
Title = Cryptpad.createTitle({}, function(){}, Cryptpad);
var displayed = ['useradmin', 'newpad', 'limit', 'upgrade'];
if (secret && hexFileName) {
displayed.push('fileshare');
}
var configTb = {
displayed: displayed,
ifrw: ifrw,
common: Cryptpad,
//hideDisplayName: true,
$container: $bar,
};
if (uploadMode) {
displayed.push('pageTitle');
configTb.pageTitle = Messages.upload_title;
}
var toolbar = APP.toolbar = Toolbar.create(configTb);
toolbar.$rightside.html(''); // Remove the drawer if we don't use it to hide the toolbar
if (!uploadMode) {
var src = Cryptpad.getBlobPathFromHex(hexFileName);
var cryptKey = secret.keys && secret.keys.fileKeyStr;
var key = Nacl.util.decodeBase64(cryptKey);
FileCrypto.fetchDecryptedMetadata(src, key, function (e, metadata) {
if (e) { return void console.error(e); }
var title = document.title = metadata.name;
Title.updateTitle(title || Title.defaultTitle);
toolbar.addElement(['pageTitle'], {pageTitle: title});
console.error(metadata);
var displayFile = function (ev, sizeMb, CB) {
var called_back;
var cb = function (e) {
if (called_back) { return; }
called_back = true;
if (CB) { CB(e); }
};
var $mt = $dlview.find('media-tag');
var cryptKey = secret.keys && secret.keys.fileKeyStr;
var hexFileName = Cryptpad.base64ToHex(secret.channel);
$mt.attr('src', '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName);
$mt.attr('data-crypto-key', 'cryptpad:'+cryptKey);
var rightsideDisplayed = false;
$(window.document).on('decryption', function (e) {
var decrypted = e.originalEvent;
if (decrypted.callback) {
decrypted.callback();
}
console.log(decrypted);
$dlview.show();
$dlform.hide();
var $dlButton = $dlview.find('media-tag button');
if (ev) { $dlButton.click(); }
if (!$dlButton.length) {
$appContainer.css('background', 'white');
}
$dlButton.addClass('btn btn-success');
var text = Messages.download_mt_button + '<br>';
text += '<b>' + Cryptpad.fixHTML(title) + '</b><br>';
text += '<em>' + Messages._getKey('formattedMB', [sizeMb]) + '</em>';
$dlButton.html(text);
if (!rightsideDisplayed) {
toolbar.$rightside.append(Cryptpad.createButton('export', true, {}, function () {
saveAs(decrypted.blob, decrypted.metadata.name);
}))
.append(Cryptpad.createButton('forget', true, {}, function () {
// not sure what to do here
}));
rightsideDisplayed = true;
}
// make pdfs big
var toolbarHeight = $iframe.find('#toolbar').height();
var $another_iframe = $iframe.find('media-tag iframe').css({
'height': 'calc(100vh - ' + toolbarHeight + 'px)',
'width': '100vw',
'position': 'absolute',
'bottom': 0,
'left': 0,
'border': 0
});
if ($another_iframe.length) {
$another_iframe.load(function () {
cb();
});
} else {
cb();
}
})
.on('decryptionError', function (e) {
var error = e.originalEvent;
//Cryptpad.alert(error.message);
cb(error.message);
})
.on('decryptionProgress', function (e) {
var progress = e.originalEvent;
var p = progress.percent +'%';
$progress.width(p);
console.log(progress.percent);
});
/**
* Allowed mime types that have to be set for a rendering after a decryption.
*
* @type {Array}
*/
var allowedMediaTypes = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'audio/mp3',
'audio/ogg',
'audio/wav',
'audio/webm',
'video/mp4',
'video/ogg',
'video/webm',
'application/pdf',
'application/dash+xml',
'download'
];
MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);
MediaTag($mt[0]);
};
var todoBigFile = function (sizeMb) {
$dlform.show();
Cryptpad.removeLoadingScreen();
$dllabel.append($('<br>'));
$dllabel.append(Cryptpad.fixHTML(metadata.name));
// don't display the size if you don't know it.
if (typeof(sizeM) === 'number') {
$dllabel.append($('<br>'));
$dllabel.append(Messages._getKey('formattedMB', [sizeMb]));
}
var decrypting = false;
var onClick = function (ev) {
if (decrypting) { return; }
decrypting = true;
displayFile(ev, sizeMb, function (err) {
if (err) { Cryptpad.alert(err); }
});
};
if (typeof(sizeMb) === 'number' && sizeMb < 5) { return void onClick(); }
$dlform.find('#dl, #progress').click(onClick);
};
Cryptpad.getFileSize(window.location.href, function (e, data) {
if (e) {
return void Cryptpad.errorLoadingScreen(e);
}
var size = Cryptpad.bytesToMegabytes(data);
return void todoBigFile(size);
});
});
return;
}
if (!Cryptpad.isLoggedIn()) {
return Cryptpad.alert(Messages.upload_mustLogin, function () {
if (sessionStorage) {
sessionStorage.redirectTo = window.location.href;
}
window.location.href = '/login/';
});
}
$form.css({
display: 'block',
});
var fmConfig = {
dropArea: $form,
hoverArea: $label,
body: $body,
keepTable: true // Don't fadeOut the tbale with the uploaded files
};
var FM = Cryptpad.createFileManager(fmConfig);
$form.find("#file").on('change', function (e) {
var file = e.target.files[0];
FM.handleFile(file);
});
// we're in upload mode
Cryptpad.removeLoadingScreen();
};
Cryptpad.ready(function () {
andThen();
Cryptpad.reportAppUsage();
});
});
});
Loading…
Cancel
Save