CyberChef/src/core/operations/legacy/URL.js

119 lines
2.9 KiB
JavaScript
Raw Normal View History

2016-11-28 11:42:58 +01:00
/* globals unescape */
import url from "url";
2016-11-28 11:42:58 +01:00
/**
* URL operations.
* Namespace is appended with an underscore to prevent overwriting the global URL object.
*
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2016
* @license Apache-2.0
*
* @namespace
*/
const URL_ = {
2016-11-28 11:42:58 +01:00
/**
* @constant
* @default
*/
ENCODE_ALL: false,
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* URL Encode operation.
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
runTo: function(input, args) {
2017-04-13 19:08:50 +02:00
const encodeAll = args[0];
return encodeAll ? URL_._encodeAllChars(input) : encodeURI(input);
2016-11-28 11:42:58 +01:00
},
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* URL Decode operation.
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
runFrom: function(input, args) {
2017-04-13 19:08:50 +02:00
const data = input.replace(/\+/g, "%20");
2016-11-28 11:42:58 +01:00
try {
return decodeURIComponent(data);
2017-02-09 16:09:33 +01:00
} catch (err) {
2016-11-28 11:42:58 +01:00
return unescape(data);
}
},
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* Parse URI operation.
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
runParse: function(input, args) {
const uri = url.parse(input, true);
let output = "";
if (uri.protocol) output += "Protocol:\t" + uri.protocol + "\n";
if (uri.auth) output += "Auth:\t\t" + uri.auth + "\n";
if (uri.hostname) output += "Hostname:\t" + uri.hostname + "\n";
if (uri.port) output += "Port:\t\t" + uri.port + "\n";
if (uri.pathname) output += "Path name:\t" + uri.pathname + "\n";
if (uri.query) {
let keys = Object.keys(uri.query),
padding = 0;
keys.forEach(k => {
padding = (k.length > padding) ? k.length : padding;
});
output += "Arguments:\n";
for (let key in uri.query) {
output += "\t" + key.padEnd(padding, " ");
if (uri.query[key].length) {
output += " = " + uri.query[key] + "\n";
} else {
output += "\n";
2016-11-28 11:42:58 +01:00
}
}
}
if (uri.hash) output += "Hash:\t\t" + uri.hash + "\n";
2017-02-09 16:09:33 +01:00
return output;
2016-11-28 11:42:58 +01:00
},
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* URL encodes additional special characters beyond the standard set.
*
* @private
* @param {string} str
* @returns {string}
*/
_encodeAllChars: function(str) {
2016-11-28 11:42:58 +01:00
//TODO Do this programatically
return encodeURIComponent(str)
.replace(/!/g, "%21")
.replace(/#/g, "%23")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A")
2017-07-24 15:49:16 +02:00
.replace(/-/g, "%2D")
2016-11-28 11:42:58 +01:00
.replace(/\./g, "%2E")
.replace(/_/g, "%5F")
.replace(/~/g, "%7E");
},
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
};
export default URL_;