App.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. import Utils from "../core/Utils.js";
  2. import Chef from "../core/Chef.js";
  3. import Manager from "./Manager.js";
  4. import HTMLCategory from "./HTMLCategory.js";
  5. import HTMLOperation from "./HTMLOperation.js";
  6. import Split from "split.js";
  7. /**
  8. * HTML view for CyberChef responsible for building the web page and dealing with all user
  9. * interactions.
  10. *
  11. * @author n1474335 [n1474335@gmail.com]
  12. * @copyright Crown Copyright 2016
  13. * @license Apache-2.0
  14. *
  15. * @constructor
  16. * @param {CatConf[]} categories - The list of categories and operations to be populated.
  17. * @param {Object.<string, OpConf>} operations - The list of operation configuration objects.
  18. * @param {String[]} defaultFavourites - A list of default favourite operations.
  19. * @param {Object} options - Default setting for app options.
  20. */
  21. const App = function(categories, operations, defaultFavourites, defaultOptions) {
  22. this.categories = categories;
  23. this.operations = operations;
  24. this.dfavourites = defaultFavourites;
  25. this.doptions = defaultOptions;
  26. this.options = Utils.extend({}, defaultOptions);
  27. this.chef = new Chef();
  28. this.manager = new Manager(this);
  29. this.baking = false;
  30. this.autoBake_ = false;
  31. this.progress = 0;
  32. this.ingId = 0;
  33. window.chef = this.chef;
  34. };
  35. /**
  36. * This function sets up the stage and creates listeners for all events.
  37. *
  38. * @fires Manager#appstart
  39. */
  40. App.prototype.setup = function() {
  41. document.dispatchEvent(this.manager.appstart);
  42. this.initialiseSplitter();
  43. this.loadLocalStorage();
  44. this.populateOperationsList();
  45. this.manager.setup();
  46. this.resetLayout();
  47. this.setCompileMessage();
  48. this.loadURIParams();
  49. };
  50. /**
  51. * An error handler for displaying the error to the user.
  52. *
  53. * @param {Error} err
  54. */
  55. App.prototype.handleError = function(err) {
  56. console.error(err);
  57. const msg = err.displayStr || err.toString();
  58. this.alert(msg, "danger", this.options.errorTimeout, !this.options.showErrors);
  59. };
  60. /**
  61. * Updates the UI to show if baking is in process or not.
  62. *
  63. * @param {bakingStatus}
  64. */
  65. App.prototype.setBakingStatus = function(bakingStatus) {
  66. this.baking = bakingStatus;
  67. var inputLoadingIcon = document.querySelector("#input .title .loading-icon"),
  68. outputLoadingIcon = document.querySelector("#output .title .loading-icon"),
  69. outputElement = document.querySelector("#output-text");
  70. if (bakingStatus) {
  71. inputLoadingIcon.style.display = "inline-block";
  72. outputLoadingIcon.style.display = "inline-block";
  73. outputElement.classList.add("disabled");
  74. outputElement.disabled = true;
  75. } else {
  76. inputLoadingIcon.style.display = "none";
  77. outputLoadingIcon.style.display = "none";
  78. outputElement.classList.remove("disabled");
  79. outputElement.disabled = false;
  80. }
  81. };
  82. /**
  83. * Calls the Chef to bake the current input using the current recipe.
  84. *
  85. * @param {boolean} [step] - Set to true if we should only execute one operation instead of the
  86. * whole recipe.
  87. */
  88. App.prototype.bake = async function(step) {
  89. let response;
  90. if (this.baking) return;
  91. this.setBakingStatus(true);
  92. try {
  93. response = await this.chef.bake(
  94. this.getInput(), // The user's input
  95. this.getRecipeConfig(), // The configuration of the recipe
  96. this.options, // Options set by the user
  97. this.progress, // The current position in the recipe
  98. step // Whether or not to take one step or execute the whole recipe
  99. );
  100. } catch (err) {
  101. this.handleError(err);
  102. }
  103. this.setBakingStatus(false);
  104. if (!response) return;
  105. if (response.error) {
  106. this.handleError(response.error);
  107. }
  108. this.options = response.options;
  109. this.dishStr = response.type === "html" ? Utils.stripHtmlTags(response.result, true) : response.result;
  110. this.progress = response.progress;
  111. this.manager.recipe.updateBreakpointIndicator(response.progress);
  112. this.manager.output.set(response.result, response.type, response.duration);
  113. // If baking took too long, disable auto-bake
  114. if (response.duration > this.options.autoBakeThreshold && this.autoBake_) {
  115. this.manager.controls.setAutoBake(false);
  116. this.alert("Baking took longer than " + this.options.autoBakeThreshold +
  117. "ms, Auto Bake has been disabled.", "warning", 5000);
  118. }
  119. };
  120. /**
  121. * Runs Auto Bake if it is set.
  122. */
  123. App.prototype.autoBake = function() {
  124. if (this.autoBake_) {
  125. this.bake();
  126. }
  127. };
  128. /**
  129. * Runs a silent bake forcing the browser to load and cache all the relevant JavaScript code needed
  130. * to do a real bake.
  131. *
  132. * The output will not be modified (hence "silent" bake). This will only actually execute the
  133. * recipe if auto-bake is enabled, otherwise it will just load the recipe, ingredients and dish.
  134. *
  135. * @returns {number} - The number of miliseconds it took to run the silent bake.
  136. */
  137. App.prototype.silentBake = function() {
  138. let startTime = new Date().getTime(),
  139. recipeConfig = this.getRecipeConfig();
  140. if (this.autoBake_) {
  141. this.chef.silentBake(recipeConfig);
  142. }
  143. return new Date().getTime() - startTime;
  144. };
  145. /**
  146. * Gets the user's input data.
  147. *
  148. * @returns {string}
  149. */
  150. App.prototype.getInput = function() {
  151. const input = this.manager.input.get();
  152. // Save to session storage in case we need to restore it later
  153. sessionStorage.setItem("inputLength", input.length);
  154. sessionStorage.setItem("input", input);
  155. return input;
  156. };
  157. /**
  158. * Sets the user's input data.
  159. *
  160. * @param {string} input - The string to set the input to
  161. */
  162. App.prototype.setInput = function(input) {
  163. sessionStorage.setItem("inputLength", input.length);
  164. sessionStorage.setItem("input", input);
  165. this.manager.input.set(input);
  166. };
  167. /**
  168. * Populates the operations accordion list with the categories and operations specified in the
  169. * view constructor.
  170. *
  171. * @fires Manager#oplistcreate
  172. */
  173. App.prototype.populateOperationsList = function() {
  174. // Move edit button away before we overwrite it
  175. document.body.appendChild(document.getElementById("edit-favourites"));
  176. let html = "";
  177. let i;
  178. for (i = 0; i < this.categories.length; i++) {
  179. let catConf = this.categories[i],
  180. selected = i === 0,
  181. cat = new HTMLCategory(catConf.name, selected);
  182. for (let j = 0; j < catConf.ops.length; j++) {
  183. let opName = catConf.ops[j],
  184. op = new HTMLOperation(opName, this.operations[opName], this, this.manager);
  185. cat.addOperation(op);
  186. }
  187. html += cat.toHtml();
  188. }
  189. document.getElementById("categories").innerHTML = html;
  190. const opLists = document.querySelectorAll("#categories .op-list");
  191. for (i = 0; i < opLists.length; i++) {
  192. opLists[i].dispatchEvent(this.manager.oplistcreate);
  193. }
  194. // Add edit button to first category (Favourites)
  195. document.querySelector("#categories a").appendChild(document.getElementById("edit-favourites"));
  196. };
  197. /**
  198. * Sets up the adjustable splitter to allow the user to resize areas of the page.
  199. */
  200. App.prototype.initialiseSplitter = function() {
  201. this.columnSplitter = Split(["#operations", "#recipe", "#IO"], {
  202. sizes: [20, 30, 50],
  203. minSize: [240, 325, 440],
  204. gutterSize: 4,
  205. onDrag: function() {
  206. this.manager.controls.adjustWidth();
  207. this.manager.output.adjustWidth();
  208. }.bind(this)
  209. });
  210. this.ioSplitter = Split(["#input", "#output"], {
  211. direction: "vertical",
  212. gutterSize: 4,
  213. });
  214. this.resetLayout();
  215. };
  216. /**
  217. * Loads the information previously saved to the HTML5 local storage object so that user options
  218. * and favourites can be restored.
  219. */
  220. App.prototype.loadLocalStorage = function() {
  221. // Load options
  222. let lOptions;
  223. if (localStorage.options !== undefined) {
  224. lOptions = JSON.parse(localStorage.options);
  225. }
  226. this.manager.options.load(lOptions);
  227. // Load favourites
  228. this.loadFavourites();
  229. };
  230. /**
  231. * Loads the user's favourite operations from the HTML5 local storage object and populates the
  232. * Favourites category with them.
  233. * If the user currently has no saved favourites, the defaults from the view constructor are used.
  234. */
  235. App.prototype.loadFavourites = function() {
  236. let favourites = localStorage.favourites &&
  237. localStorage.favourites.length > 2 ?
  238. JSON.parse(localStorage.favourites) :
  239. this.dfavourites;
  240. favourites = this.validFavourites(favourites);
  241. this.saveFavourites(favourites);
  242. const favCat = this.categories.filter(function(c) {
  243. return c.name === "Favourites";
  244. })[0];
  245. if (favCat) {
  246. favCat.ops = favourites;
  247. } else {
  248. this.categories.unshift({
  249. name: "Favourites",
  250. ops: favourites
  251. });
  252. }
  253. };
  254. /**
  255. * Filters the list of favourite operations that the user had stored and removes any that are no
  256. * longer available. The user is notified if this is the case.
  257. * @param {string[]} favourites - A list of the user's favourite operations
  258. * @returns {string[]} A list of the valid favourites
  259. */
  260. App.prototype.validFavourites = function(favourites) {
  261. const validFavs = [];
  262. for (let i = 0; i < favourites.length; i++) {
  263. if (this.operations.hasOwnProperty(favourites[i])) {
  264. validFavs.push(favourites[i]);
  265. } else {
  266. this.alert("The operation \"" + Utils.escapeHtml(favourites[i]) +
  267. "\" is no longer available. It has been removed from your favourites.", "info");
  268. }
  269. }
  270. return validFavs;
  271. };
  272. /**
  273. * Saves a list of favourite operations to the HTML5 local storage object.
  274. *
  275. * @param {string[]} favourites - A list of the user's favourite operations
  276. */
  277. App.prototype.saveFavourites = function(favourites) {
  278. localStorage.setItem("favourites", JSON.stringify(this.validFavourites(favourites)));
  279. };
  280. /**
  281. * Resets favourite operations back to the default as specified in the view constructor and
  282. * refreshes the operation list.
  283. */
  284. App.prototype.resetFavourites = function() {
  285. this.saveFavourites(this.dfavourites);
  286. this.loadFavourites();
  287. this.populateOperationsList();
  288. this.manager.recipe.initialiseOperationDragNDrop();
  289. };
  290. /**
  291. * Adds an operation to the user's favourites.
  292. *
  293. * @param {string} name - The name of the operation
  294. */
  295. App.prototype.addFavourite = function(name) {
  296. const favourites = JSON.parse(localStorage.favourites);
  297. if (favourites.indexOf(name) >= 0) {
  298. this.alert("'" + name + "' is already in your favourites", "info", 2000);
  299. return;
  300. }
  301. favourites.push(name);
  302. this.saveFavourites(favourites);
  303. this.loadFavourites();
  304. this.populateOperationsList();
  305. this.manager.recipe.initialiseOperationDragNDrop();
  306. };
  307. /**
  308. * Checks for input and recipe in the URI parameters and loads them if present.
  309. */
  310. App.prototype.loadURIParams = function() {
  311. // Load query string from URI
  312. this.queryString = (function(a) {
  313. if (a === "") return {};
  314. const b = {};
  315. for (let i = 0; i < a.length; i++) {
  316. const p = a[i].split("=");
  317. if (p.length !== 2) {
  318. b[a[i]] = true;
  319. } else {
  320. b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
  321. }
  322. }
  323. return b;
  324. })(window.location.search.substr(1).split("&"));
  325. // Turn off auto-bake while loading
  326. const autoBakeVal = this.autoBake_;
  327. this.autoBake_ = false;
  328. // Read in recipe from query string
  329. if (this.queryString.recipe) {
  330. try {
  331. const recipeConfig = JSON.parse(this.queryString.recipe);
  332. this.setRecipeConfig(recipeConfig);
  333. } catch (err) {}
  334. } else if (this.queryString.op) {
  335. // If there's no recipe, look for single operations
  336. this.manager.recipe.clearRecipe();
  337. try {
  338. this.manager.recipe.addOperation(this.queryString.op);
  339. } catch (err) {
  340. // If no exact match, search for nearest match and add that
  341. const matchedOps = this.manager.ops.filterOperations(this.queryString.op, false);
  342. if (matchedOps.length) {
  343. this.manager.recipe.addOperation(matchedOps[0].name);
  344. }
  345. // Populate search with the string
  346. const search = document.getElementById("search");
  347. search.value = this.queryString.op;
  348. search.dispatchEvent(new Event("search"));
  349. }
  350. }
  351. // Read in input data from query string
  352. if (this.queryString.input) {
  353. try {
  354. const inputData = Utils.fromBase64(this.queryString.input);
  355. this.setInput(inputData);
  356. } catch (err) {}
  357. }
  358. // Restore auto-bake state
  359. this.autoBake_ = autoBakeVal;
  360. this.autoBake();
  361. };
  362. /**
  363. * Returns the next ingredient ID and increments it for next time.
  364. *
  365. * @returns {number}
  366. */
  367. App.prototype.nextIngId = function() {
  368. return this.ingId++;
  369. };
  370. /**
  371. * Gets the current recipe configuration.
  372. *
  373. * @returns {Object[]}
  374. */
  375. App.prototype.getRecipeConfig = function() {
  376. const recipeConfig = this.manager.recipe.getConfig();
  377. sessionStorage.setItem("recipeConfig", JSON.stringify(recipeConfig));
  378. return recipeConfig;
  379. };
  380. /**
  381. * Given a recipe configuration, sets the recipe to that configuration.
  382. *
  383. * @param {Object[]} recipeConfig - The recipe configuration
  384. */
  385. App.prototype.setRecipeConfig = function(recipeConfig) {
  386. sessionStorage.setItem("recipeConfig", JSON.stringify(recipeConfig));
  387. document.getElementById("rec-list").innerHTML = null;
  388. for (let i = 0; i < recipeConfig.length; i++) {
  389. const item = this.manager.recipe.addOperation(recipeConfig[i].op);
  390. // Populate arguments
  391. const args = item.querySelectorAll(".arg");
  392. for (let j = 0; j < args.length; j++) {
  393. if (args[j].getAttribute("type") === "checkbox") {
  394. // checkbox
  395. args[j].checked = recipeConfig[i].args[j];
  396. } else if (args[j].classList.contains("toggle-string")) {
  397. // toggleString
  398. args[j].value = recipeConfig[i].args[j].string;
  399. args[j].previousSibling.children[0].innerHTML =
  400. Utils.escapeHtml(recipeConfig[i].args[j].option) +
  401. " <span class='caret'></span>";
  402. } else {
  403. // all others
  404. args[j].value = recipeConfig[i].args[j];
  405. }
  406. }
  407. // Set disabled and breakpoint
  408. if (recipeConfig[i].disabled) {
  409. item.querySelector(".disable-icon").click();
  410. }
  411. if (recipeConfig[i].breakpoint) {
  412. item.querySelector(".breakpoint").click();
  413. }
  414. this.progress = 0;
  415. }
  416. };
  417. /**
  418. * Resets the splitter positions to default.
  419. */
  420. App.prototype.resetLayout = function() {
  421. this.columnSplitter.setSizes([20, 30, 50]);
  422. this.ioSplitter.setSizes([50, 50]);
  423. this.manager.controls.adjustWidth();
  424. this.manager.output.adjustWidth();
  425. };
  426. /**
  427. * Sets the compile message.
  428. */
  429. App.prototype.setCompileMessage = function() {
  430. // Display time since last build and compile message
  431. let now = new Date(),
  432. timeSinceCompile = Utils.fuzzyTime(now.getTime() - window.compileTime),
  433. compileInfo = "<span style=\"font-weight: normal\">Last build: " +
  434. timeSinceCompile.substr(0, 1).toUpperCase() + timeSinceCompile.substr(1) + " ago";
  435. if (window.compileMessage !== "") {
  436. compileInfo += " - " + window.compileMessage;
  437. }
  438. compileInfo += "</span>";
  439. document.getElementById("notice").innerHTML = compileInfo;
  440. };
  441. /**
  442. * Pops up a message to the user and writes it to the console log.
  443. *
  444. * @param {string} str - The message to display (HTML supported)
  445. * @param {string} style - The colour of the popup
  446. * "danger" = red
  447. * "warning" = amber
  448. * "info" = blue
  449. * "success" = green
  450. * @param {number} timeout - The number of milliseconds before the popup closes automatically
  451. * 0 for never (until the user closes it)
  452. * @param {boolean} [silent=false] - Don't show the message in the popup, only print it to the
  453. * console
  454. *
  455. * @example
  456. * // Pops up a red box with the message "[current time] Error: Something has gone wrong!"
  457. * // that will need to be dismissed by the user.
  458. * this.alert("Error: Something has gone wrong!", "danger", 0);
  459. *
  460. * // Pops up a blue information box with the message "[current time] Happy Christmas!"
  461. * // that will disappear after 5 seconds.
  462. * this.alert("Happy Christmas!", "info", 5000);
  463. */
  464. App.prototype.alert = function(str, style, timeout, silent) {
  465. const time = new Date();
  466. console.log("[" + time.toLocaleString() + "] " + str);
  467. if (silent) return;
  468. style = style || "danger";
  469. timeout = timeout || 0;
  470. let alertEl = document.getElementById("alert"),
  471. alertContent = document.getElementById("alert-content");
  472. alertEl.classList.remove("alert-danger");
  473. alertEl.classList.remove("alert-warning");
  474. alertEl.classList.remove("alert-info");
  475. alertEl.classList.remove("alert-success");
  476. alertEl.classList.add("alert-" + style);
  477. // If the box hasn't been closed, append to it rather than replacing
  478. if (alertEl.style.display === "block") {
  479. alertContent.innerHTML +=
  480. "<br><br>[" + time.toLocaleTimeString() + "] " + str;
  481. } else {
  482. alertContent.innerHTML =
  483. "[" + time.toLocaleTimeString() + "] " + str;
  484. }
  485. // Stop the animation if it is in progress
  486. $("#alert").stop();
  487. alertEl.style.display = "block";
  488. alertEl.style.opacity = 1;
  489. if (timeout > 0) {
  490. clearTimeout(this.alertTimeout);
  491. this.alertTimeout = setTimeout(function(){
  492. $("#alert").slideUp(100);
  493. }, timeout);
  494. }
  495. };
  496. /**
  497. * Pops up a box asking the user a question and sending the answer to a specified callback function.
  498. *
  499. * @param {string} title - The title of the box
  500. * @param {string} body - The question (HTML supported)
  501. * @param {function} callback - A function accepting one boolean argument which handles the
  502. * response e.g. function(answer) {...}
  503. * @param {Object} [scope=this] - The object to bind to the callback function
  504. *
  505. * @example
  506. * // Pops up a box asking if the user would like a cookie. Prints the answer to the console.
  507. * this.confirm("Question", "Would you like a cookie?", function(answer) {console.log(answer);});
  508. */
  509. App.prototype.confirm = function(title, body, callback, scope) {
  510. scope = scope || this;
  511. document.getElementById("confirm-title").innerHTML = title;
  512. document.getElementById("confirm-body").innerHTML = body;
  513. document.getElementById("confirm-modal").style.display = "block";
  514. this.confirmClosed = false;
  515. $("#confirm-modal").modal()
  516. .one("show.bs.modal", function(e) {
  517. this.confirmClosed = false;
  518. }.bind(this))
  519. .one("click", "#confirm-yes", function() {
  520. this.confirmClosed = true;
  521. callback.bind(scope)(true);
  522. $("#confirm-modal").modal("hide");
  523. }.bind(this))
  524. .one("hide.bs.modal", function(e) {
  525. if (!this.confirmClosed)
  526. callback.bind(scope)(false);
  527. this.confirmClosed = true;
  528. }.bind(this));
  529. };
  530. /**
  531. * Handler for the alert close button click event.
  532. * Closes the alert box.
  533. */
  534. App.prototype.alertCloseClick = function() {
  535. document.getElementById("alert").style.display = "none";
  536. };
  537. /**
  538. * Handler for CyerChef statechange events.
  539. * Fires whenever the input or recipe changes in any way.
  540. *
  541. * @listens Manager#statechange
  542. * @param {event} e
  543. */
  544. App.prototype.stateChange = function(e) {
  545. this.autoBake();
  546. // Update the current history state (not creating a new one)
  547. if (this.options.updateUrl) {
  548. this.lastStateUrl = this.manager.controls.generateStateUrl(true, true);
  549. window.history.replaceState({}, "CyberChef", this.lastStateUrl);
  550. }
  551. };
  552. /**
  553. * Handler for the history popstate event.
  554. * Reloads parameters from the URL.
  555. *
  556. * @param {event} e
  557. */
  558. App.prototype.popState = function(e) {
  559. if (window.location.href.split("#")[0] !== this.lastStateUrl) {
  560. this.loadURIParams();
  561. }
  562. };
  563. /**
  564. * Function to call an external API from this view.
  565. */
  566. App.prototype.callApi = function(url, type, data, dataType, contentType) {
  567. type = type || "POST";
  568. data = data || {};
  569. dataType = dataType || undefined;
  570. contentType = contentType || "application/json";
  571. let response = null,
  572. success = false;
  573. $.ajax({
  574. url: url,
  575. async: false,
  576. type: type,
  577. data: data,
  578. dataType: dataType,
  579. contentType: contentType,
  580. success: function(data) {
  581. success = true;
  582. response = data;
  583. },
  584. error: function(data) {
  585. success = false;
  586. response = data;
  587. },
  588. });
  589. return {
  590. success: success,
  591. response: response
  592. };
  593. };
  594. export default App;