diff --git a/README.md b/README.md
index e6d835a8eb..4029fc232f 100755
--- a/README.md
+++ b/README.md
@@ -50,7 +50,7 @@ You can use as many operations as you like in simple or complex ways. Some examp
- Drag and drop
- Operations can be dragged in and out of the recipe list, or reorganised.
- - Files up to 500MB can be dragged over the input box to load them directly into the browser.
+ - Files up to 2GB can be dragged over the input box to load them directly into the browser.
- Auto Bake
- Whenever you modify the input or the recipe, CyberChef will automatically "bake" for you and produce the output immediately.
- This can be turned off and operated manually if it is affecting performance (if the input is very large, for instance).
@@ -67,7 +67,7 @@ You can use as many operations as you like in simple or complex ways. Some examp
- Highlighting
- When you highlight text in the input or output, the offset and length values will be displayed and, if possible, the corresponding data will be highlighted in the output or input respectively (example: [highlight the word 'question' in the input to see where it appears in the output][11]).
- Save to file and load from file
- - You can save the output to a file at any time or load a file by dragging and dropping it into the input field. Files up to around 500MB are supported (depending on your browser), however some operations may take a very long time to run over this much data.
+ - You can save the output to a file at any time or load a file by dragging and dropping it into the input field. Files up to around 2GB are supported (depending on your browser), however some operations may take a very long time to run over this much data.
- CyberChef is entirely client-side
- It should be noted that none of your recipe configuration or input (either text or files) is ever sent to the CyberChef web server - all processing is carried out within your browser, on your own computer.
- Due to this feature, CyberChef can be compiled into a single HTML file. You can download this file and drop it into a virtual machine, share it with other people, or use it independently on your local machine.
diff --git a/src/core/Chef.mjs b/src/core/Chef.mjs
index 33b7acbeee..0fcee7f5a1 100755
--- a/src/core/Chef.mjs
+++ b/src/core/Chef.mjs
@@ -28,8 +28,6 @@ class Chef {
* @param {Object[]} recipeConfig - The recipe configuration object
* @param {Object} options - The options object storing various user choices
* @param {boolean} options.attempHighlight - Whether or not to attempt highlighting
- * @param {number} progress - The position in the recipe to start from
- * @param {number} [step] - Whether to only execute one operation in the recipe
*
* @returns {Object} response
* @returns {string} response.result - The output of the recipe
@@ -38,46 +36,20 @@ class Chef {
* @returns {number} response.duration - The number of ms it took to execute the recipe
* @returns {number} response.error - The error object thrown by a failed operation (false if no error)
*/
- async bake(input, recipeConfig, options, progress, step) {
+ async bake(input, recipeConfig, options) {
log.debug("Chef baking");
const startTime = new Date().getTime(),
recipe = new Recipe(recipeConfig),
containsFc = recipe.containsFlowControl(),
notUTF8 = options && options.hasOwnProperty("treatAsUtf8") && !options.treatAsUtf8;
- let error = false;
-
- if (containsFc && ENVIRONMENT_IS_WORKER()) self.setOption("attemptHighlight", false);
-
- // Clean up progress
- if (progress >= recipeConfig.length) {
- progress = 0;
- }
-
- if (step) {
- // Unset breakpoint on this step
- recipe.setBreakpoint(progress, false);
- // Set breakpoint on next step
- recipe.setBreakpoint(progress + 1, true);
- }
-
- // If the previously run operation presented a different value to its
- // normal output, we need to recalculate it.
- if (recipe.lastOpPresented(progress)) {
+ let error = false,
progress = 0;
- }
- // If stepping with flow control, we have to start from the beginning
- // but still want to skip all previous breakpoints
- if (progress > 0 && containsFc) {
- recipe.removeBreaksUpTo(progress);
- progress = 0;
- }
+ if (containsFc && ENVIRONMENT_IS_WORKER()) self.setOption("attemptHighlight", false);
- // If starting from scratch, load data
- if (progress === 0) {
- const type = input instanceof ArrayBuffer ? Dish.ARRAY_BUFFER : Dish.STRING;
- this.dish.set(input, type);
- }
+ // Load data
+ const type = input instanceof ArrayBuffer ? Dish.ARRAY_BUFFER : Dish.STRING;
+ this.dish.set(input, type);
try {
progress = await recipe.execute(this.dish, progress);
@@ -196,6 +168,18 @@ class Chef {
return await newDish.get(type);
}
+ /**
+ * Gets the title of a dish and returns it
+ *
+ * @param {Dish} dish
+ * @param {number} [maxLength=100]
+ * @returns {string}
+ */
+ async getDishTitle(dish, maxLength=100) {
+ const newDish = new Dish(dish);
+ return await newDish.getTitle(maxLength);
+ }
+
}
export default Chef;
diff --git a/src/core/ChefWorker.js b/src/core/ChefWorker.js
index ad49893600..90b9e76b01 100644
--- a/src/core/ChefWorker.js
+++ b/src/core/ChefWorker.js
@@ -25,6 +25,8 @@ self.chef = new Chef();
self.OpModules = OpModules;
self.OperationConfig = OperationConfig;
+self.inputNum = -1;
+
// Tell the app that the worker has loaded and is ready to operate
self.postMessage({
@@ -35,6 +37,9 @@ self.postMessage({
/**
* Respond to message from parent thread.
*
+ * inputNum is optional and only used for baking multiple inputs.
+ * Defaults to -1 when one isn't sent with the bake message.
+ *
* Messages should have the following format:
* {
* action: "bake" | "silentBake",
@@ -43,8 +48,9 @@ self.postMessage({
* recipeConfig: {[Object]},
* options: {Object},
* progress: {number},
- * step: {boolean}
- * } | undefined
+ * step: {boolean},
+ * [inputNum=-1]: {number}
+ * }
* }
*/
self.addEventListener("message", function(e) {
@@ -62,6 +68,9 @@ self.addEventListener("message", function(e) {
case "getDishAs":
getDishAs(r.data);
break;
+ case "getDishTitle":
+ getDishTitle(r.data);
+ break;
case "docURL":
// Used to set the URL of the current document so that scripts can be
// imported into an inline worker.
@@ -91,30 +100,35 @@ self.addEventListener("message", function(e) {
async function bake(data) {
// Ensure the relevant modules are loaded
self.loadRequiredModules(data.recipeConfig);
-
try {
+ self.inputNum = (data.inputNum !== undefined) ? data.inputNum : -1;
const response = await self.chef.bake(
data.input, // The user's input
data.recipeConfig, // The configuration of the recipe
- data.options, // Options set by the user
- data.progress, // The current position in the recipe
- data.step // Whether or not to take one step or execute the whole recipe
+ data.options // Options set by the user
);
+ const transferable = (data.input instanceof ArrayBuffer) ? [data.input] : undefined;
self.postMessage({
action: "bakeComplete",
data: Object.assign(response, {
- id: data.id
+ id: data.id,
+ inputNum: data.inputNum,
+ bakeId: data.bakeId
})
- });
+ }, transferable);
+
} catch (err) {
self.postMessage({
action: "bakeError",
- data: Object.assign(err, {
- id: data.id
- })
+ data: {
+ error: err.message || err,
+ id: data.id,
+ inputNum: data.inputNum
+ }
});
}
+ self.inputNum = -1;
}
@@ -136,13 +150,33 @@ function silentBake(data) {
*/
async function getDishAs(data) {
const value = await self.chef.getDishAs(data.dish, data.type);
-
+ const transferable = (data.type === "ArrayBuffer") ? [value] : undefined;
self.postMessage({
action: "dishReturned",
data: {
value: value,
id: data.id
}
+ }, transferable);
+}
+
+
+/**
+ * Gets the dish title
+ *
+ * @param {object} data
+ * @param {Dish} data.dish
+ * @param {number} data.maxLength
+ * @param {number} data.id
+ */
+async function getDishTitle(data) {
+ const title = await self.chef.getDishTitle(data.dish, data.maxLength);
+ self.postMessage({
+ action: "dishReturned",
+ data: {
+ value: title,
+ id: data.id
+ }
});
}
@@ -193,7 +227,28 @@ self.loadRequiredModules = function(recipeConfig) {
self.sendStatusMessage = function(msg) {
self.postMessage({
action: "statusMessage",
- data: msg
+ data: {
+ message: msg,
+ inputNum: self.inputNum
+ }
+ });
+};
+
+
+/**
+ * Send progress update to the app.
+ *
+ * @param {number} progress
+ * @param {number} total
+ */
+self.sendProgressMessage = function(progress, total) {
+ self.postMessage({
+ action: "progressMessage",
+ data: {
+ progress: progress,
+ total: total,
+ inputNum: self.inputNum
+ }
});
};
diff --git a/src/core/Dish.mjs b/src/core/Dish.mjs
index 96aea716a7..f8d7dfd8dc 100755
--- a/src/core/Dish.mjs
+++ b/src/core/Dish.mjs
@@ -8,6 +8,7 @@
import Utils from "./Utils";
import DishError from "./errors/DishError";
import BigNumber from "bignumber.js";
+import {detectFileType} from "./lib/FileType";
import log from "loglevel";
/**
@@ -141,6 +142,56 @@ class Dish {
}
+ /**
+ * Detects the MIME type of the current dish
+ * @returns {string}
+ */
+ async detectDishType() {
+ const data = new Uint8Array(this.value.slice(0, 2048)),
+ types = detectFileType(data);
+
+ if (!types.length || !types[0].mime || !types[0].mime === "text/plain") {
+ return null;
+ } else {
+ return types[0].mime;
+ }
+ }
+
+
+ /**
+ * Returns the title of the data up to the specified length
+ *
+ * @param {number} maxLength - The maximum title length
+ * @returns {string}
+ */
+ async getTitle(maxLength) {
+ let title = "";
+ const cloned = this.clone();
+
+ switch (this.type) {
+ case Dish.FILE:
+ title = cloned.value.name;
+ break;
+ case Dish.LIST_FILE:
+ title = `${cloned.value.length} file(s)`;
+ break;
+ case Dish.ARRAY_BUFFER:
+ case Dish.BYTE_ARRAY:
+ title = await cloned.detectDishType();
+ if (title === null) {
+ cloned.value = cloned.value.slice(0, 2048);
+ title = await cloned.get(Dish.STRING);
+ }
+ break;
+ default:
+ title = await cloned.get(Dish.STRING);
+ }
+
+ title = title.slice(0, maxLength);
+ return title;
+ }
+
+
/**
* Translates the data to the given type format.
*
diff --git a/src/core/Recipe.mjs b/src/core/Recipe.mjs
index a11b4d02b1..bed6845c83 100755
--- a/src/core/Recipe.mjs
+++ b/src/core/Recipe.mjs
@@ -200,7 +200,12 @@ class Recipe {
try {
input = await dish.get(op.inputType);
- log.debug("Executing operation");
+ log.debug(`Executing operation '${op.name}'`);
+
+ if (ENVIRONMENT_IS_WORKER()) {
+ self.sendStatusMessage(`Baking... (${i+1}/${this.opList.length})`);
+ self.sendProgressMessage(i + 1, this.opList.length);
+ }
if (op.flowControl) {
// Package up the current state
diff --git a/src/web/App.mjs b/src/web/App.mjs
index 868684de8f..db530cf008 100755
--- a/src/web/App.mjs
+++ b/src/web/App.mjs
@@ -41,6 +41,7 @@ class App {
this.autoBakePause = false;
this.progress = 0;
this.ingId = 0;
+ this.timeouts = {};
}
@@ -87,7 +88,10 @@ class App {
setTimeout(function() {
document.getElementById("loader-wrapper").remove();
document.body.classList.remove("loaded");
- }, 1000);
+
+ // Bake initial input
+ this.manager.input.bakeAll();
+ }.bind(this), 1000);
// Clear the loading message interval
clearInterval(window.loadingMsgsInt);
@@ -96,6 +100,9 @@ class App {
window.removeEventListener("error", window.loadingErrorHandler);
document.dispatchEvent(this.manager.apploaded);
+
+ this.manager.input.calcMaxTabs();
+ this.manager.output.calcMaxTabs();
}
@@ -128,7 +135,6 @@ class App {
this.manager.recipe.updateBreakpointIndicator(false);
this.manager.worker.bake(
- this.getInput(), // The user's input
this.getRecipeConfig(), // The configuration of the recipe
this.options, // Options set by the user
this.progress, // The current position in the recipe
@@ -148,13 +154,46 @@ class App {
if (this.autoBake_ && !this.baking) {
log.debug("Auto-baking");
- this.bake();
+ this.manager.input.inputWorker.postMessage({
+ action: "autobake",
+ data: {
+ activeTab: this.manager.tabs.getActiveInputTab()
+ }
+ });
} else {
this.manager.controls.showStaleIndicator();
}
}
+ /**
+ * Executes the next step of the recipe.
+ */
+ step() {
+ if (this.baking) return;
+
+ // Reset status using cancelBake
+ this.manager.worker.cancelBake(true, false);
+
+ const activeTab = this.manager.tabs.getActiveInputTab();
+ if (activeTab === -1) return;
+
+ let progress = 0;
+ if (this.manager.output.outputs[activeTab].progress !== false) {
+ log.error(this.manager.output.outputs[activeTab]);
+ progress = this.manager.output.outputs[activeTab].progress;
+ }
+
+ this.manager.input.inputWorker.postMessage({
+ action: "step",
+ data: {
+ activeTab: activeTab,
+ progress: progress + 1
+ }
+ });
+ }
+
+
/**
* Runs a silent bake, forcing the browser to load and cache all the relevant JavaScript code needed
* to do a real bake.
@@ -175,24 +214,25 @@ class App {
}
- /**
- * Gets the user's input data.
- *
- * @returns {string}
- */
- getInput() {
- return this.manager.input.get();
- }
-
-
/**
* Sets the user's input data.
*
* @param {string} input - The string to set the input to
- * @param {boolean} [silent=false] - Suppress statechange event
*/
- setInput(input, silent=false) {
- this.manager.input.set(input, silent);
+ setInput(input) {
+ // Get the currently active tab.
+ // If there isn't one, assume there are no inputs so use inputNum of 1
+ let inputNum = this.manager.tabs.getActiveInputTab();
+ if (inputNum === -1) inputNum = 1;
+ this.manager.input.updateInputValue(inputNum, input);
+
+ this.manager.input.inputWorker.postMessage({
+ action: "setInput",
+ data: {
+ inputNum: inputNum,
+ silent: true
+ }
+ });
}
@@ -255,9 +295,11 @@ class App {
minSize: minimise ? [0, 0, 0] : [240, 310, 450],
gutterSize: 4,
expandToMin: true,
- onDrag: function() {
+ onDrag: this.debounce(function() {
this.manager.recipe.adjustWidth();
- }.bind(this)
+ this.manager.input.calcMaxTabs();
+ this.manager.output.calcMaxTabs();
+ }, 50, "dragSplitter", this, [])
});
this.ioSplitter = Split(["#input", "#output"], {
@@ -391,11 +433,12 @@ class App {
this.manager.recipe.initialiseOperationDragNDrop();
}
-
/**
- * Checks for input and recipe in the URI parameters and loads them if present.
+ * Gets the URI params from the window and parses them to extract the actual values.
+ *
+ * @returns {object}
*/
- loadURIParams() {
+ getURIParams() {
// Load query string or hash from URI (depending on which is populated)
// We prefer getting the hash by splitting the href rather than referencing
// location.hash as some browsers (Firefox) automatically URL decode it,
@@ -403,8 +446,20 @@ class App {
const params = window.location.search ||
window.location.href.split("#")[1] ||
window.location.hash;
- this.uriParams = Utils.parseURIParams(params);
+ const parsedParams = Utils.parseURIParams(params);
+ return parsedParams;
+ }
+
+ /**
+ * Searches the URI parameters for recipe and input parameters.
+ * If recipe is present, replaces the current recipe with the recipe provided in the URI.
+ * If input is present, decodes and sets the input to the one provided in the URI.
+ *
+ * @fires Manager#statechange
+ */
+ loadURIParams() {
this.autoBakePause = true;
+ this.uriParams = this.getURIParams();
// Read in recipe from URI params
if (this.uriParams.recipe) {
@@ -433,7 +488,7 @@ class App {
if (this.uriParams.input) {
try {
const inputData = fromBase64(this.uriParams.input);
- this.setInput(inputData, true);
+ this.setInput(inputData);
} catch (err) {}
}
@@ -522,6 +577,8 @@ class App {
this.columnSplitter.setSizes([20, 30, 50]);
this.ioSplitter.setSizes([50, 50]);
this.manager.recipe.adjustWidth();
+ this.manager.input.calcMaxTabs();
+ this.manager.output.calcMaxTabs();
}
@@ -656,6 +713,17 @@ class App {
this.progress = 0;
this.autoBake();
+ this.updateTitle(false, null, true);
+ }
+
+ /**
+ * Update the page title to contain the new recipe
+ *
+ * @param {boolean} includeInput
+ * @param {string} input
+ * @param {boolean} [changeUrl=true]
+ */
+ updateTitle(includeInput, input, changeUrl=true) {
// Set title
const recipeConfig = this.getRecipeConfig();
let title = "CyberChef";
@@ -674,8 +742,8 @@ class App {
document.title = title;
// Update the current history state (not creating a new one)
- if (this.options.updateUrl) {
- this.lastStateUrl = this.manager.controls.generateStateUrl(true, true, recipeConfig);
+ if (this.options.updateUrl && changeUrl) {
+ this.lastStateUrl = this.manager.controls.generateStateUrl(true, includeInput, input, recipeConfig);
window.history.replaceState({}, title, this.lastStateUrl);
}
}
@@ -691,6 +759,29 @@ class App {
this.loadURIParams();
}
+
+ /**
+ * Debouncer to stop functions from being executed multiple times in a
+ * short space of time
+ * https://davidwalsh.name/javascript-debounce-function
+ *
+ * @param {function} func - The function to be executed after the debounce time
+ * @param {number} wait - The time (ms) to wait before executing the function
+ * @param {string} id - Unique ID to reference the timeout for the function
+ * @param {object} scope - The object to bind to the debounced function
+ * @param {array} args - Array of arguments to be passed to func
+ * @returns {function}
+ */
+ debounce(func, wait, id, scope, args) {
+ return function() {
+ const later = function() {
+ func.apply(scope, args);
+ };
+ clearTimeout(this.timeouts[id]);
+ this.timeouts[id] = setTimeout(later, wait);
+ }.bind(this);
+ }
+
}
export default App;
diff --git a/src/web/InputWaiter.mjs b/src/web/InputWaiter.mjs
deleted file mode 100755
index 17b48b6f4f..0000000000
--- a/src/web/InputWaiter.mjs
+++ /dev/null
@@ -1,354 +0,0 @@
-/**
- * @author n1474335 [n1474335@gmail.com]
- * @copyright Crown Copyright 2016
- * @license Apache-2.0
- */
-
-import LoaderWorker from "worker-loader?inline&fallback=false!./LoaderWorker";
-import Utils from "../core/Utils";
-
-
-/**
- * Waiter to handle events related to the input.
- */
-class InputWaiter {
-
- /**
- * InputWaiter constructor.
- *
- * @param {App} app - The main view object for CyberChef.
- * @param {Manager} manager - The CyberChef event manager.
- */
- constructor(app, manager) {
- this.app = app;
- this.manager = manager;
-
- // Define keys that don't change the input so we don't have to autobake when they are pressed
- this.badKeys = [
- 16, //Shift
- 17, //Ctrl
- 18, //Alt
- 19, //Pause
- 20, //Caps
- 27, //Esc
- 33, 34, 35, 36, //PgUp, PgDn, End, Home
- 37, 38, 39, 40, //Directional
- 44, //PrntScrn
- 91, 92, //Win
- 93, //Context
- 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, //F1-12
- 144, //Num
- 145, //Scroll
- ];
-
- this.loaderWorker = null;
- this.fileBuffer = null;
- }
-
-
- /**
- * Gets the user's input from the input textarea.
- *
- * @returns {string}
- */
- get() {
- return this.fileBuffer || document.getElementById("input-text").value;
- }
-
-
- /**
- * Sets the input in the input area.
- *
- * @param {string|File} input
- * @param {boolean} [silent=false] - Suppress statechange event
- *
- * @fires Manager#statechange
- */
- set(input, silent=false) {
- const inputText = document.getElementById("input-text");
- if (input instanceof File) {
- this.setFile(input);
- inputText.value = "";
- this.setInputInfo(input.size, null);
- } else {
- inputText.value = input;
- this.closeFile();
- if (!silent) window.dispatchEvent(this.manager.statechange);
- const lines = input.length < (this.app.options.ioDisplayThreshold * 1024) ?
- input.count("\n") + 1 : null;
- this.setInputInfo(input.length, lines);
- }
- }
-
-
- /**
- * Shows file details.
- *
- * @param {File} file
- */
- setFile(file) {
- // Display file overlay in input area with details
- const fileOverlay = document.getElementById("input-file"),
- fileName = document.getElementById("input-file-name"),
- fileSize = document.getElementById("input-file-size"),
- fileType = document.getElementById("input-file-type"),
- fileLoaded = document.getElementById("input-file-loaded");
-
- this.fileBuffer = new ArrayBuffer();
- fileOverlay.style.display = "block";
- fileName.textContent = file.name;
- fileSize.textContent = file.size.toLocaleString() + " bytes";
- fileType.textContent = file.type || "unknown";
- fileLoaded.textContent = "0%";
- }
-
-
- /**
- * Displays information about the input.
- *
- * @param {number} length - The length of the current input string
- * @param {number} lines - The number of the lines in the current input string
- */
- setInputInfo(length, lines) {
- let width = length.toString().length;
- width = width < 2 ? 2 : width;
-
- const lengthStr = length.toString().padStart(width, " ").replace(/ /g, " ");
- let msg = "length: " + lengthStr;
-
- if (typeof lines === "number") {
- const linesStr = lines.toString().padStart(width, " ").replace(/ /g, " ");
- msg += "
lines: " + linesStr;
- }
-
- document.getElementById("input-info").innerHTML = msg;
- }
-
-
- /**
- * Handler for input change events.
- *
- * @param {event} e
- *
- * @fires Manager#statechange
- */
- inputChange(e) {
- // Ignore this function if the input is a File
- if (this.fileBuffer) return;
-
- // Remove highlighting from input and output panes as the offsets might be different now
- this.manager.highlighter.removeHighlights();
-
- // Reset recipe progress as any previous processing will be redundant now
- this.app.progress = 0;
-
- // Update the input metadata info
- const inputText = this.get();
- const lines = inputText.length < (this.app.options.ioDisplayThreshold * 1024) ?
- inputText.count("\n") + 1 : null;
-
- this.setInputInfo(inputText.length, lines);
-
- if (e && this.badKeys.indexOf(e.keyCode) < 0) {
- // Fire the statechange event as the input has been modified
- window.dispatchEvent(this.manager.statechange);
- }
- }
-
-
- /**
- * Handler for input paste events.
- * Checks that the size of the input is below the display limit, otherwise treats it as a file/blob.
- *
- * @param {event} e
- */
- inputPaste(e) {
- const pastedData = e.clipboardData.getData("Text");
-
- if (pastedData.length < (this.app.options.ioDisplayThreshold * 1024)) {
- this.inputChange(e);
- } else {
- e.preventDefault();
- e.stopPropagation();
-
- const file = new File([pastedData], "PastedData", {
- type: "text/plain",
- lastModified: Date.now()
- });
-
- this.loaderWorker = new LoaderWorker();
- this.loaderWorker.addEventListener("message", this.handleLoaderMessage.bind(this));
- this.loaderWorker.postMessage({"file": file});
- this.set(file);
- return false;
- }
- }
-
-
- /**
- * Handler for input dragover events.
- * Gives the user a visual cue to show that items can be dropped here.
- *
- * @param {event} e
- */
- inputDragover(e) {
- // This will be set if we're dragging an operation
- if (e.dataTransfer.effectAllowed === "move")
- return false;
-
- e.stopPropagation();
- e.preventDefault();
- e.target.closest("#input-text,#input-file").classList.add("dropping-file");
- }
-
-
- /**
- * Handler for input dragleave events.
- * Removes the visual cue.
- *
- * @param {event} e
- */
- inputDragleave(e) {
- e.stopPropagation();
- e.preventDefault();
- document.getElementById("input-text").classList.remove("dropping-file");
- document.getElementById("input-file").classList.remove("dropping-file");
- }
-
-
- /**
- * Handler for input drop events.
- * Loads the dragged data into the input textarea.
- *
- * @param {event} e
- */
- inputDrop(e) {
- // This will be set if we're dragging an operation
- if (e.dataTransfer.effectAllowed === "move")
- return false;
-
- e.stopPropagation();
- e.preventDefault();
-
- const file = e.dataTransfer.files[0];
- const text = e.dataTransfer.getData("Text");
-
- document.getElementById("input-text").classList.remove("dropping-file");
- document.getElementById("input-file").classList.remove("dropping-file");
-
- if (text) {
- this.closeFile();
- this.set(text);
- return;
- }
-
- if (file) {
- this.loadFile(file);
- }
- }
-
- /**
- * Handler for open input button events
- * Loads the opened data into the input textarea
- *
- * @param {event} e
- */
- inputOpen(e) {
- e.preventDefault();
- const file = e.srcElement.files[0];
- this.loadFile(file);
- }
-
-
- /**
- * Handler for messages sent back by the LoaderWorker.
- *
- * @param {MessageEvent} e
- */
- handleLoaderMessage(e) {
- const r = e.data;
- if (r.hasOwnProperty("progress")) {
- const fileLoaded = document.getElementById("input-file-loaded");
- fileLoaded.textContent = r.progress + "%";
- }
-
- if (r.hasOwnProperty("error")) {
- this.app.alert(r.error, 10000);
- }
-
- if (r.hasOwnProperty("fileBuffer")) {
- log.debug("Input file loaded");
- this.fileBuffer = r.fileBuffer;
- this.displayFilePreview();
- window.dispatchEvent(this.manager.statechange);
- }
- }
-
-
- /**
- * Shows a chunk of the file in the input behind the file overlay.
- */
- displayFilePreview() {
- const inputText = document.getElementById("input-text"),
- fileSlice = this.fileBuffer.slice(0, 4096);
-
- inputText.style.overflow = "hidden";
- inputText.classList.add("blur");
- inputText.value = Utils.printable(Utils.arrayBufferToStr(fileSlice));
- if (this.fileBuffer.byteLength > 4096) {
- inputText.value += "[truncated]...";
- }
- }
-
-
- /**
- * Handler for file close events.
- */
- closeFile() {
- if (this.loaderWorker) this.loaderWorker.terminate();
- this.fileBuffer = null;
- document.getElementById("input-file").style.display = "none";
- const inputText = document.getElementById("input-text");
- inputText.style.overflow = "auto";
- inputText.classList.remove("blur");
- }
-
-
- /**
- * Loads a file into the input.
- *
- * @param {File} file
- */
- loadFile(file) {
- if (file) {
- this.closeFile();
- this.loaderWorker = new LoaderWorker();
- this.loaderWorker.addEventListener("message", this.handleLoaderMessage.bind(this));
- this.loaderWorker.postMessage({"file": file});
- this.set(file);
- }
- }
-
-
- /**
- * Handler for clear IO events.
- * Resets the input, output and info areas.
- *
- * @fires Manager#statechange
- */
- clearIoClick() {
- this.closeFile();
- this.manager.output.closeFile();
- this.manager.highlighter.removeHighlights();
- document.getElementById("input-text").value = "";
- document.getElementById("output-text").value = "";
- document.getElementById("input-info").innerHTML = "";
- document.getElementById("output-info").innerHTML = "";
- document.getElementById("input-selection-info").innerHTML = "";
- document.getElementById("output-selection-info").innerHTML = "";
- window.dispatchEvent(this.manager.statechange);
- }
-
-}
-
-export default InputWaiter;
diff --git a/src/web/Manager.mjs b/src/web/Manager.mjs
index 5fa0e8c10f..2486f65dce 100755
--- a/src/web/Manager.mjs
+++ b/src/web/Manager.mjs
@@ -4,18 +4,19 @@
* @license Apache-2.0
*/
-import WorkerWaiter from "./WorkerWaiter";
-import WindowWaiter from "./WindowWaiter";
-import ControlsWaiter from "./ControlsWaiter";
-import RecipeWaiter from "./RecipeWaiter";
-import OperationsWaiter from "./OperationsWaiter";
-import InputWaiter from "./InputWaiter";
-import OutputWaiter from "./OutputWaiter";
-import OptionsWaiter from "./OptionsWaiter";
-import HighlighterWaiter from "./HighlighterWaiter";
-import SeasonalWaiter from "./SeasonalWaiter";
-import BindingsWaiter from "./BindingsWaiter";
-import BackgroundWorkerWaiter from "./BackgroundWorkerWaiter";
+import WorkerWaiter from "./waiters/WorkerWaiter";
+import WindowWaiter from "./waiters/WindowWaiter";
+import ControlsWaiter from "./waiters/ControlsWaiter";
+import RecipeWaiter from "./waiters/RecipeWaiter";
+import OperationsWaiter from "./waiters/OperationsWaiter";
+import InputWaiter from "./waiters/InputWaiter";
+import OutputWaiter from "./waiters/OutputWaiter";
+import OptionsWaiter from "./waiters/OptionsWaiter";
+import HighlighterWaiter from "./waiters/HighlighterWaiter";
+import SeasonalWaiter from "./waiters/SeasonalWaiter";
+import BindingsWaiter from "./waiters/BindingsWaiter";
+import BackgroundWorkerWaiter from "./waiters/BackgroundWorkerWaiter";
+import TabWaiter from "./waiters/TabWaiter";
/**
@@ -63,6 +64,7 @@ class Manager {
this.controls = new ControlsWaiter(this.app, this);
this.recipe = new RecipeWaiter(this.app, this);
this.ops = new OperationsWaiter(this.app, this);
+ this.tabs = new TabWaiter(this.app, this);
this.input = new InputWaiter(this.app, this);
this.output = new OutputWaiter(this.app, this);
this.options = new OptionsWaiter(this.app, this);
@@ -82,7 +84,9 @@ class Manager {
* Sets up the various components and listeners.
*/
setup() {
- this.worker.registerChefWorker();
+ this.input.setupInputWorker();
+ this.input.addInput(true);
+ this.worker.setupChefWorker();
this.recipe.initialiseOperationDragNDrop();
this.controls.initComponents();
this.controls.autoBakeChange();
@@ -142,11 +146,11 @@ class Manager {
this.addDynamicListener("textarea.arg", "drop", this.recipe.textArgDrop, this.recipe);
// Input
- this.addMultiEventListener("#input-text", "keyup", this.input.inputChange, this.input);
+ this.addMultiEventListener("#input-text", "keyup", this.input.debounceInputChange, this.input);
this.addMultiEventListener("#input-text", "paste", this.input.inputPaste, this.input);
document.getElementById("reset-layout").addEventListener("click", this.app.resetLayout.bind(this.app));
- document.getElementById("clr-io").addEventListener("click", this.input.clearIoClick.bind(this.input));
- this.addListeners("#open-file", "change", this.input.inputOpen, this.input);
+ this.addListeners("#clr-io,#btn-close-all-tabs", "click", this.input.clearAllIoClick, this.input);
+ this.addListeners("#open-file,#open-folder", "change", this.input.inputOpen, this.input);
this.addListeners("#input-text,#input-file", "dragover", this.input.inputDragover, this.input);
this.addListeners("#input-text,#input-file", "dragleave", this.input.inputDragleave, this.input);
this.addListeners("#input-text,#input-file", "drop", this.input.inputDrop, this.input);
@@ -155,9 +159,31 @@ class Manager {
document.getElementById("input-text").addEventListener("mousemove", this.highlighter.inputMousemove.bind(this.highlighter));
this.addMultiEventListener("#input-text", "mousedown dblclick select", this.highlighter.inputMousedown, this.highlighter);
document.querySelector("#input-file .close").addEventListener("click", this.input.clearIoClick.bind(this.input));
+ document.getElementById("btn-new-tab").addEventListener("click", this.input.addInputClick.bind(this.input));
+ document.getElementById("btn-previous-input-tab").addEventListener("mousedown", this.input.previousTabClick.bind(this.input));
+ document.getElementById("btn-next-input-tab").addEventListener("mousedown", this.input.nextTabClick.bind(this.input));
+ this.addListeners("#btn-next-input-tab,#btn-previous-input-tab", "mouseup", this.input.tabMouseUp, this.input);
+ this.addListeners("#btn-next-input-tab,#btn-previous-input-tab", "mouseout", this.input.tabMouseUp, this.input);
+ document.getElementById("btn-go-to-input-tab").addEventListener("click", this.input.goToTab.bind(this.input));
+ document.getElementById("btn-find-input-tab").addEventListener("click", this.input.findTab.bind(this.input));
+ this.addDynamicListener("#input-tabs li .input-tab-content", "click", this.input.changeTabClick, this.input);
+ document.getElementById("input-show-pending").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+ document.getElementById("input-show-loading").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+ document.getElementById("input-show-loaded").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+ this.addListeners("#input-filter-content,#input-filter-filename", "click", this.input.filterOptionClick, this.input);
+ document.getElementById("input-filter").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+ document.getElementById("input-filter").addEventListener("keyup", this.input.filterTabSearch.bind(this.input));
+ document.getElementById("input-num-results").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+ document.getElementById("input-num-results").addEventListener("keyup", this.input.filterTabSearch.bind(this.input));
+ document.getElementById("input-filter-refresh").addEventListener("click", this.input.filterTabSearch.bind(this.input));
+ this.addDynamicListener(".input-filter-result", "click", this.input.filterItemClick, this.input);
+ document.getElementById("btn-open-file").addEventListener("click", this.input.inputOpenClick.bind(this.input));
+ document.getElementById("btn-open-folder").addEventListener("click", this.input.folderOpenClick.bind(this.input));
+
// Output
document.getElementById("save-to-file").addEventListener("click", this.output.saveClick.bind(this.output));
+ document.getElementById("save-all-to-file").addEventListener("click", this.output.saveAllClick.bind(this.output));
document.getElementById("copy-output").addEventListener("click", this.output.copyClick.bind(this.output));
document.getElementById("switch").addEventListener("click", this.output.switchClick.bind(this.output));
document.getElementById("undo-switch").addEventListener("click", this.output.undoSwitchClick.bind(this.output));
@@ -174,6 +200,25 @@ class Manager {
this.addDynamicListener("#output-file-slice i", "click", this.output.displayFileSlice, this.output);
document.getElementById("show-file-overlay").addEventListener("click", this.output.showFileOverlayClick.bind(this.output));
this.addDynamicListener(".extract-file,.extract-file i", "click", this.output.extractFileClick, this.output);
+ this.addDynamicListener("#output-tabs-wrapper #output-tabs li .output-tab-content", "click", this.output.changeTabClick, this.output);
+ document.getElementById("btn-previous-output-tab").addEventListener("mousedown", this.output.previousTabClick.bind(this.output));
+ document.getElementById("btn-next-output-tab").addEventListener("mousedown", this.output.nextTabClick.bind(this.output));
+ this.addListeners("#btn-next-output-tab,#btn-previous-output-tab", "mouseup", this.output.tabMouseUp, this.output);
+ this.addListeners("#btn-next-output-tab,#btn-previous-output-tab", "mouseout", this.output.tabMouseUp, this.output);
+ document.getElementById("btn-go-to-output-tab").addEventListener("click", this.output.goToTab.bind(this.output));
+ document.getElementById("btn-find-output-tab").addEventListener("click", this.output.findTab.bind(this.output));
+ document.getElementById("output-show-pending").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-show-baking").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-show-baked").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-show-stale").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-show-errored").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-content-filter").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-content-filter").addEventListener("keyup", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-num-results").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-num-results").addEventListener("keyup", this.output.filterTabSearch.bind(this.output));
+ document.getElementById("output-filter-refresh").addEventListener("click", this.output.filterTabSearch.bind(this.output));
+ this.addDynamicListener(".output-filter-result", "click", this.output.filterItemClick, this.output);
+
// Options
document.getElementById("options").addEventListener("click", this.options.optionsClick.bind(this.options));
@@ -186,6 +231,7 @@ class Manager {
this.addDynamicListener(".option-item select", "change", this.options.selectChange, this.options);
document.getElementById("theme").addEventListener("change", this.options.themeChange.bind(this.options));
document.getElementById("logLevel").addEventListener("change", this.options.logLevelChange.bind(this.options));
+ document.getElementById("imagePreview").addEventListener("change", this.input.renderFileThumb.bind(this.input));
// Misc
window.addEventListener("keydown", this.bindings.parseInput.bind(this.bindings));
@@ -307,7 +353,6 @@ class Manager {
}
}
}
-
}
export default Manager;
diff --git a/src/web/OutputWaiter.mjs b/src/web/OutputWaiter.mjs
deleted file mode 100755
index eaafeb8ba3..0000000000
--- a/src/web/OutputWaiter.mjs
+++ /dev/null
@@ -1,547 +0,0 @@
-/**
- * @author n1474335 [n1474335@gmail.com]
- * @copyright Crown Copyright 2016
- * @license Apache-2.0
- */
-
-import Utils from "../core/Utils";
-import FileSaver from "file-saver";
-
-
-/**
- * Waiter to handle events related to the output.
- */
-class OutputWaiter {
-
- /**
- * OutputWaiter constructor.
- *
- * @param {App} app - The main view object for CyberChef.
- * @param {Manager} manager - The CyberChef event manager.
- */
- constructor(app, manager) {
- this.app = app;
- this.manager = manager;
-
- this.dishBuffer = null;
- this.dishStr = null;
- }
-
-
- /**
- * Gets the output string from the output textarea.
- *
- * @returns {string}
- */
- get() {
- return document.getElementById("output-text").value;
- }
-
-
- /**
- * Sets the output in the output textarea.
- *
- * @param {string|ArrayBuffer} data - The output string/HTML/ArrayBuffer
- * @param {string} type - The data type of the output
- * @param {number} duration - The length of time (ms) it took to generate the output
- * @param {boolean} [preserveBuffer=false] - Whether to preserve the dishBuffer
- */
- async set(data, type, duration, preserveBuffer) {
- log.debug("Output type: " + type);
- const outputText = document.getElementById("output-text");
- const outputHtml = document.getElementById("output-html");
- const outputFile = document.getElementById("output-file");
- const outputHighlighter = document.getElementById("output-highlighter");
- const inputHighlighter = document.getElementById("input-highlighter");
- let scriptElements, lines, length;
-
- if (!preserveBuffer) {
- this.closeFile();
- this.dishStr = null;
- document.getElementById("show-file-overlay").style.display = "none";
- }
-
- switch (type) {
- case "html":
- outputText.style.display = "none";
- outputHtml.style.display = "block";
- outputFile.style.display = "none";
- outputHighlighter.display = "none";
- inputHighlighter.display = "none";
-
- outputText.value = "";
- outputHtml.innerHTML = data;
-
- // Execute script sections
- scriptElements = outputHtml.querySelectorAll("script");
- for (let i = 0; i < scriptElements.length; i++) {
- try {
- eval(scriptElements[i].innerHTML); // eslint-disable-line no-eval
- } catch (err) {
- log.error(err);
- }
- }
-
- await this.getDishStr();
- length = this.dishStr.length;
- lines = this.dishStr.count("\n") + 1;
- break;
- case "ArrayBuffer":
- outputText.style.display = "block";
- outputHtml.style.display = "none";
- outputHighlighter.display = "none";
- inputHighlighter.display = "none";
-
- outputText.value = "";
- outputHtml.innerHTML = "";
- length = data.byteLength;
-
- this.setFile(data);
- break;
- case "string":
- default:
- outputText.style.display = "block";
- outputHtml.style.display = "none";
- outputFile.style.display = "none";
- outputHighlighter.display = "block";
- inputHighlighter.display = "block";
-
- outputText.value = Utils.printable(data, true);
- outputHtml.innerHTML = "";
-
- lines = data.count("\n") + 1;
- length = data.length;
- this.dishStr = data;
- break;
- }
-
- this.manager.highlighter.removeHighlights();
- this.setOutputInfo(length, lines, duration);
- this.backgroundMagic();
- }
-
-
- /**
- * Shows file details.
- *
- * @param {ArrayBuffer} buf
- */
- setFile(buf) {
- this.dishBuffer = buf;
- const file = new File([buf], "output.dat");
-
- // Display file overlay in output area with details
- const fileOverlay = document.getElementById("output-file"),
- fileSize = document.getElementById("output-file-size");
-
- fileOverlay.style.display = "block";
- fileSize.textContent = file.size.toLocaleString() + " bytes";
-
- // Display preview slice in the background
- const outputText = document.getElementById("output-text"),
- fileSlice = this.dishBuffer.slice(0, 4096);
-
- outputText.classList.add("blur");
- outputText.value = Utils.printable(Utils.arrayBufferToStr(fileSlice));
- }
-
-
- /**
- * Removes the output file and nulls its memory.
- */
- closeFile() {
- this.dishBuffer = null;
- document.getElementById("output-file").style.display = "none";
- document.getElementById("output-text").classList.remove("blur");
- }
-
-
- /**
- * Handler for file download events.
- */
- async downloadFile() {
- this.filename = window.prompt("Please enter a filename:", this.filename || "download.dat");
- await this.getDishBuffer();
- const file = new File([this.dishBuffer], this.filename);
- if (this.filename) FileSaver.saveAs(file, this.filename, false);
- }
-
-
- /**
- * Handler for file slice display events.
- */
- displayFileSlice() {
- const startTime = new Date().getTime(),
- showFileOverlay = document.getElementById("show-file-overlay"),
- sliceFromEl = document.getElementById("output-file-slice-from"),
- sliceToEl = document.getElementById("output-file-slice-to"),
- sliceFrom = parseInt(sliceFromEl.value, 10),
- sliceTo = parseInt(sliceToEl.value, 10),
- str = Utils.arrayBufferToStr(this.dishBuffer.slice(sliceFrom, sliceTo));
-
- document.getElementById("output-text").classList.remove("blur");
- showFileOverlay.style.display = "block";
- this.set(str, "string", new Date().getTime() - startTime, true);
- }
-
-
- /**
- * Handler for show file overlay events.
- *
- * @param {Event} e
- */
- showFileOverlayClick(e) {
- const outputFile = document.getElementById("output-file"),
- showFileOverlay = e.target;
-
- document.getElementById("output-text").classList.add("blur");
- outputFile.style.display = "block";
- showFileOverlay.style.display = "none";
- this.setOutputInfo(this.dishBuffer.byteLength, null, 0);
- }
-
-
- /**
- * Displays information about the output.
- *
- * @param {number} length - The length of the current output string
- * @param {number} lines - The number of the lines in the current output string
- * @param {number} duration - The length of time (ms) it took to generate the output
- */
- setOutputInfo(length, lines, duration) {
- let width = length.toString().length;
- width = width < 4 ? 4 : width;
-
- const lengthStr = length.toString().padStart(width, " ").replace(/ /g, " ");
- const timeStr = (duration.toString() + "ms").padStart(width, " ").replace(/ /g, " ");
-
- let msg = "time: " + timeStr + "
length: " + lengthStr;
-
- if (typeof lines === "number") {
- const linesStr = lines.toString().padStart(width, " ").replace(/ /g, " ");
- msg += "
lines: " + linesStr;
- }
-
- document.getElementById("output-info").innerHTML = msg;
- document.getElementById("input-selection-info").innerHTML = "";
- document.getElementById("output-selection-info").innerHTML = "";
- }
-
-
- /**
- * Handler for save click events.
- * Saves the current output to a file.
- */
- saveClick() {
- this.downloadFile();
- }
-
-
- /**
- * Handler for copy click events.
- * Copies the output to the clipboard.
- */
- async copyClick() {
- await this.getDishStr();
-
- // Create invisible textarea to populate with the raw dish string (not the printable version that
- // contains dots instead of the actual bytes)
- const textarea = document.createElement("textarea");
- textarea.style.position = "fixed";
- textarea.style.top = 0;
- textarea.style.left = 0;
- textarea.style.width = 0;
- textarea.style.height = 0;
- textarea.style.border = "none";
-
- textarea.value = this.dishStr;
- document.body.appendChild(textarea);
-
- // Select and copy the contents of this textarea
- let success = false;
- try {
- textarea.select();
- success = this.dishStr && document.execCommand("copy");
- } catch (err) {
- success = false;
- }
-
- if (success) {
- this.app.alert("Copied raw output successfully.", 2000);
- } else {
- this.app.alert("Sorry, the output could not be copied.", 3000);
- }
-
- // Clean up
- document.body.removeChild(textarea);
- }
-
-
- /**
- * Handler for switch click events.
- * Moves the current output into the input textarea.
- */
- async switchClick() {
- this.switchOrigData = this.manager.input.get();
- document.getElementById("undo-switch").disabled = false;
- if (this.dishBuffer) {
- this.manager.input.setFile(new File([this.dishBuffer], "output.dat"));
- this.manager.input.handleLoaderMessage({
- data: {
- progress: 100,
- fileBuffer: this.dishBuffer
- }
- });
- } else {
- await this.getDishStr();
- this.app.setInput(this.dishStr);
- }
- }
-
-
- /**
- * Handler for undo switch click events.
- * Removes the output from the input and replaces the input that was removed.
- */
- undoSwitchClick() {
- this.app.setInput(this.switchOrigData);
- const undoSwitch = document.getElementById("undo-switch");
- undoSwitch.disabled = true;
- $(undoSwitch).tooltip("hide");
- }
-
-
- /**
- * Handler for maximise output click events.
- * Resizes the output frame to be as large as possible, or restores it to its original size.
- */
- maximiseOutputClick(e) {
- const el = e.target.id === "maximise-output" ? e.target : e.target.parentNode;
-
- if (el.getAttribute("data-original-title").indexOf("Maximise") === 0) {
- this.app.initialiseSplitter(true);
- this.app.columnSplitter.collapse(0);
- this.app.columnSplitter.collapse(1);
- this.app.ioSplitter.collapse(0);
-
- $(el).attr("data-original-title", "Restore output pane");
- el.querySelector("i").innerHTML = "fullscreen_exit";
- } else {
- $(el).attr("data-original-title", "Maximise output pane");
- el.querySelector("i").innerHTML = "fullscreen";
- this.app.initialiseSplitter(false);
- this.app.resetLayout();
- }
- }
-
-
- /**
- * Save bombe object then remove it from the DOM so that it does not cause performance issues.
- */
- saveBombe() {
- this.bombeEl = document.getElementById("bombe");
- this.bombeEl.parentNode.removeChild(this.bombeEl);
- }
-
-
- /**
- * Shows or hides the output loading screen.
- * The animated Bombe SVG, whilst quite aesthetically pleasing, is reasonably CPU
- * intensive, so we remove it from the DOM when not in use. We only show it if the
- * recipe is taking longer than 200ms. We add it to the DOM just before that so that
- * it is ready to fade in without stuttering.
- *
- * @param {boolean} value - true == show loader
- */
- toggleLoader(value) {
- clearTimeout(this.appendBombeTimeout);
- clearTimeout(this.outputLoaderTimeout);
-
- const outputLoader = document.getElementById("output-loader"),
- outputElement = document.getElementById("output-text"),
- animation = document.getElementById("output-loader-animation");
-
- if (value) {
- this.manager.controls.hideStaleIndicator();
-
- // Start a timer to add the Bombe to the DOM just before we make it
- // visible so that there is no stuttering
- this.appendBombeTimeout = setTimeout(function() {
- animation.appendChild(this.bombeEl);
- }.bind(this), 150);
-
- // Show the loading screen
- this.outputLoaderTimeout = setTimeout(function() {
- outputElement.disabled = true;
- outputLoader.style.visibility = "visible";
- outputLoader.style.opacity = 1;
- this.manager.controls.toggleBakeButtonFunction(true);
- }.bind(this), 200);
- } else {
- // Remove the Bombe from the DOM to save resources
- this.outputLoaderTimeout = setTimeout(function () {
- try {
- animation.removeChild(this.bombeEl);
- } catch (err) {}
- }.bind(this), 500);
- outputElement.disabled = false;
- outputLoader.style.opacity = 0;
- outputLoader.style.visibility = "hidden";
- this.manager.controls.toggleBakeButtonFunction(false);
- this.setStatusMsg("");
- }
- }
-
-
- /**
- * Sets the baking status message value.
- *
- * @param {string} msg
- */
- setStatusMsg(msg) {
- const el = document.querySelector("#output-loader .loading-msg");
-
- el.textContent = msg;
- }
-
-
- /**
- * Returns true if the output contains carriage returns
- *
- * @returns {boolean}
- */
- async containsCR() {
- await this.getDishStr();
- return this.dishStr.indexOf("\r") >= 0;
- }
-
-
- /**
- * Retrieves the current dish as a string, returning the cached version if possible.
- *
- * @returns {string}
- */
- async getDishStr() {
- if (this.dishStr) return this.dishStr;
-
- this.dishStr = await new Promise(resolve => {
- this.manager.worker.getDishAs(this.app.dish, "string", r => {
- resolve(r.value);
- });
- });
- return this.dishStr;
- }
-
-
- /**
- * Retrieves the current dish as an ArrayBuffer, returning the cached version if possible.
- *
- * @returns {ArrayBuffer}
- */
- async getDishBuffer() {
- if (this.dishBuffer) return this.dishBuffer;
-
- this.dishBuffer = await new Promise(resolve => {
- this.manager.worker.getDishAs(this.app.dish, "ArrayBuffer", r => {
- resolve(r.value);
- });
- });
- return this.dishBuffer;
- }
-
-
- /**
- * Triggers the BackgroundWorker to attempt Magic on the current output.
- */
- backgroundMagic() {
- this.hideMagicButton();
- if (!this.app.options.autoMagic) return;
-
- const sample = this.dishStr ? this.dishStr.slice(0, 1000) :
- this.dishBuffer ? this.dishBuffer.slice(0, 1000) : "";
-
- if (sample.length) {
- this.manager.background.magic(sample);
- }
- }
-
-
- /**
- * Handles the results of a background Magic call.
- *
- * @param {Object[]} options
- */
- backgroundMagicResult(options) {
- if (!options.length ||
- !options[0].recipe.length)
- return;
-
- const currentRecipeConfig = this.app.getRecipeConfig();
- const newRecipeConfig = currentRecipeConfig.concat(options[0].recipe);
- const opSequence = options[0].recipe.map(o => o.op).join(", ");
-
- this.showMagicButton(opSequence, options[0].data, newRecipeConfig);
- }
-
-
- /**
- * Handler for Magic click events.
- *
- * Loads the Magic recipe.
- *
- * @fires Manager#statechange
- */
- magicClick() {
- const magicButton = document.getElementById("magic");
- this.app.setRecipeConfig(JSON.parse(magicButton.getAttribute("data-recipe")));
- window.dispatchEvent(this.manager.statechange);
- this.hideMagicButton();
- }
-
-
- /**
- * Displays the Magic button with a title and adds a link to a complete recipe.
- *
- * @param {string} opSequence
- * @param {string} result
- * @param {Object[]} recipeConfig
- */
- showMagicButton(opSequence, result, recipeConfig) {
- const magicButton = document.getElementById("magic");
- magicButton.setAttribute("data-original-title", `${opSequence} will produce "${Utils.escapeHtml(Utils.truncate(result), 30)}"`);
- magicButton.setAttribute("data-recipe", JSON.stringify(recipeConfig), null, "");
- magicButton.classList.remove("hidden");
- }
-
-
- /**
- * Hides the Magic button and resets its values.
- */
- hideMagicButton() {
- const magicButton = document.getElementById("magic");
- magicButton.classList.add("hidden");
- magicButton.setAttribute("data-recipe", "");
- magicButton.setAttribute("data-original-title", "Magic!");
- }
-
-
- /**
- * Handler for extract file events.
- *
- * @param {Event} e
- */
- async extractFileClick(e) {
- e.preventDefault();
- e.stopPropagation();
-
- const el = e.target.nodeName === "I" ? e.target.parentNode : e.target;
- const blobURL = el.getAttribute("blob-url");
- const fileName = el.getAttribute("file-name");
-
- const blob = await fetch(blobURL).then(r => r.blob());
- this.manager.input.loadFile(new File([blob], fileName, {type: blob.type}));
- }
-
-}
-
-export default OutputWaiter;
diff --git a/src/web/WorkerWaiter.mjs b/src/web/WorkerWaiter.mjs
deleted file mode 100755
index 7ef72263c7..0000000000
--- a/src/web/WorkerWaiter.mjs
+++ /dev/null
@@ -1,239 +0,0 @@
-/**
- * @author n1474335 [n1474335@gmail.com]
- * @copyright Crown Copyright 2017
- * @license Apache-2.0
- */
-
-import ChefWorker from "worker-loader?inline&fallback=false!../core/ChefWorker";
-
-/**
- * Waiter to handle conversations with the ChefWorker.
- */
-class WorkerWaiter {
-
- /**
- * WorkerWaiter constructor.
- *
- * @param {App} app - The main view object for CyberChef.
- * @param {Manager} manager - The CyberChef event manager.
- */
- constructor(app, manager) {
- this.app = app;
- this.manager = manager;
-
- this.callbacks = {};
- this.callbackID = 0;
- }
-
-
- /**
- * Sets up the ChefWorker and associated listeners.
- */
- registerChefWorker() {
- log.debug("Registering new ChefWorker");
- this.chefWorker = new ChefWorker();
- this.chefWorker.addEventListener("message", this.handleChefMessage.bind(this));
- this.setLogLevel();
-
- let docURL = document.location.href.split(/[#?]/)[0];
- const index = docURL.lastIndexOf("/");
- if (index > 0) {
- docURL = docURL.substring(0, index);
- }
- this.chefWorker.postMessage({"action": "docURL", "data": docURL});
- }
-
-
- /**
- * Handler for messages sent back by the ChefWorker.
- *
- * @param {MessageEvent} e
- */
- handleChefMessage(e) {
- const r = e.data;
- log.debug("Receiving '" + r.action + "' from ChefWorker");
-
- switch (r.action) {
- case "bakeComplete":
- this.bakingComplete(r.data);
- break;
- case "bakeError":
- this.app.handleError(r.data);
- this.setBakingStatus(false);
- break;
- case "dishReturned":
- this.callbacks[r.data.id](r.data);
- break;
- case "silentBakeComplete":
- break;
- case "workerLoaded":
- this.app.workerLoaded = true;
- log.debug("ChefWorker loaded");
- this.app.loaded();
- break;
- case "statusMessage":
- this.manager.output.setStatusMsg(r.data);
- break;
- case "optionUpdate":
- log.debug(`Setting ${r.data.option} to ${r.data.value}`);
- this.app.options[r.data.option] = r.data.value;
- break;
- case "setRegisters":
- this.manager.recipe.setRegisters(r.data.opIndex, r.data.numPrevRegisters, r.data.registers);
- break;
- case "highlightsCalculated":
- this.manager.highlighter.displayHighlights(r.data.pos, r.data.direction);
- break;
- default:
- log.error("Unrecognised message from ChefWorker", e);
- break;
- }
- }
-
-
- /**
- * Updates the UI to show if baking is in process or not.
- *
- * @param {bakingStatus}
- */
- setBakingStatus(bakingStatus) {
- this.app.baking = bakingStatus;
-
- this.manager.output.toggleLoader(bakingStatus);
- }
-
-
- /**
- * Cancels the current bake by terminating the ChefWorker and creating a new one.
- */
- cancelBake() {
- this.chefWorker.terminate();
- this.registerChefWorker();
- this.setBakingStatus(false);
- this.manager.controls.showStaleIndicator();
- }
-
-
- /**
- * Handler for completed bakes.
- *
- * @param {Object} response
- */
- bakingComplete(response) {
- this.setBakingStatus(false);
-
- if (!response) return;
-
- if (response.error) {
- this.app.handleError(response.error);
- }
-
- this.app.progress = response.progress;
- this.app.dish = response.dish;
- this.manager.recipe.updateBreakpointIndicator(response.progress);
- this.manager.output.set(response.result, response.type, response.duration);
- log.debug("--- Bake complete ---");
- }
-
-
- /**
- * Asks the ChefWorker to bake the current input using the current recipe.
- *
- * @param {string} input
- * @param {Object[]} recipeConfig
- * @param {Object} options
- * @param {number} progress
- * @param {boolean} step
- */
- bake(input, recipeConfig, options, progress, step) {
- this.setBakingStatus(true);
-
- this.chefWorker.postMessage({
- action: "bake",
- data: {
- input: input,
- recipeConfig: recipeConfig,
- options: options,
- progress: progress,
- step: step
- }
- });
- }
-
-
- /**
- * Asks the ChefWorker to run a silent bake, forcing the browser to load and cache all the relevant
- * JavaScript code needed to do a real bake.
- *
- * @param {Object[]} [recipeConfig]
- */
- silentBake(recipeConfig) {
- this.chefWorker.postMessage({
- action: "silentBake",
- data: {
- recipeConfig: recipeConfig
- }
- });
- }
-
-
- /**
- * Asks the ChefWorker to calculate highlight offsets if possible.
- *
- * @param {Object[]} recipeConfig
- * @param {string} direction
- * @param {Object} pos - The position object for the highlight.
- * @param {number} pos.start - The start offset.
- * @param {number} pos.end - The end offset.
- */
- highlight(recipeConfig, direction, pos) {
- this.chefWorker.postMessage({
- action: "highlight",
- data: {
- recipeConfig: recipeConfig,
- direction: direction,
- pos: pos
- }
- });
- }
-
-
- /**
- * Asks the ChefWorker to return the dish as the specified type
- *
- * @param {Dish} dish
- * @param {string} type
- * @param {Function} callback
- */
- getDishAs(dish, type, callback) {
- const id = this.callbackID++;
- this.callbacks[id] = callback;
- this.chefWorker.postMessage({
- action: "getDishAs",
- data: {
- dish: dish,
- type: type,
- id: id
- }
- });
- }
-
-
- /**
- * Sets the console log level in the worker.
- *
- * @param {string} level
- */
- setLogLevel(level) {
- if (!this.chefWorker) return;
-
- this.chefWorker.postMessage({
- action: "setLogLevel",
- data: log.getLevel()
- });
- }
-
-}
-
-
-export default WorkerWaiter;
diff --git a/src/web/html/index.html b/src/web/html/index.html
index 350c4a37aa..7fcb7415ac 100755
--- a/src/web/html/index.html
+++ b/src/web/html/index.html
@@ -218,9 +218,16 @@