api.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /**
  2. * Wrap operations for consumption in Node.
  3. *
  4. * @author d98762625 [d98762625@gmail.com]
  5. * @copyright Crown Copyright 2018
  6. * @license Apache-2.0
  7. */
  8. /* eslint no-console: ["off"] */
  9. import NodeDish from "./NodeDish.mjs";
  10. import NodeRecipe from "./NodeRecipe.mjs";
  11. import OperationConfig from "../core/config/OperationConfig.json";
  12. import { sanitise, removeSubheadingsFromArray, sentenceToCamelCase } from "./apiUtils.mjs";
  13. import ExcludedOperationError from "../core/errors/ExcludedOperationError.mjs";
  14. /**
  15. * transformArgs
  16. *
  17. * Take the default args array and update with any user-defined
  18. * operation arguments. Allows user to define arguments in object style,
  19. * with accommodating name matching. Using named args in the API is more
  20. * clear to the user.
  21. *
  22. * Argument name matching is case and space insensitive
  23. * @private
  24. * @param {Object[]} originalArgs - the operation-s args list
  25. * @param {Object} newArgs - any inputted args
  26. */
  27. function transformArgs(opArgsList, newArgs) {
  28. if (newArgs && Array.isArray(newArgs)) {
  29. return newArgs;
  30. }
  31. // Filter out arg values that are list subheadings - they are surrounded in [].
  32. // See Strings op for example.
  33. const opArgs = Object.assign([], opArgsList).map((a) => {
  34. if (Array.isArray(a.value)) {
  35. a.value = removeSubheadingsFromArray(a.value);
  36. }
  37. return a;
  38. });
  39. // Reconcile object style arg info to fit operation args shape.
  40. if (newArgs) {
  41. Object.keys(newArgs).map((key) => {
  42. const index = opArgs.findIndex((arg) => {
  43. return arg.name.toLowerCase().replace(/ /g, "") ===
  44. key.toLowerCase().replace(/ /g, "");
  45. });
  46. if (index > -1) {
  47. const argument = opArgs[index];
  48. if (argument.type === "toggleString") {
  49. if (typeof newArgs[key] === "string") {
  50. argument.string = newArgs[key];
  51. } else {
  52. argument.string = newArgs[key].string;
  53. argument.option = newArgs[key].option;
  54. }
  55. } else if (argument.type === "editableOption") {
  56. // takes key: "option", key: {name, val: "string"}, key: {name, val: [...]}
  57. argument.value = typeof newArgs[key] === "string" ? newArgs[key]: newArgs[key].value;
  58. } else {
  59. argument.value = newArgs[key];
  60. }
  61. }
  62. });
  63. }
  64. // Sanitise args
  65. return opArgs.map((arg) => {
  66. if (arg.type === "option") {
  67. // pick default option if not already chosen
  68. return typeof arg.value === "string" ? arg.value : arg.value[0];
  69. }
  70. if (arg.type === "editableOption") {
  71. return typeof arg.value === "string" ? arg.value : arg.value[0].value;
  72. }
  73. if (arg.type === "toggleString") {
  74. // ensure string and option exist when user hasn't defined
  75. arg.string = arg.string || "";
  76. arg.option = arg.option || arg.toggleValues[0];
  77. return arg;
  78. }
  79. return arg.value;
  80. });
  81. }
  82. /**
  83. * Ensure an input is a SyncDish object.
  84. * @param input
  85. */
  86. function ensureIsDish(input) {
  87. if (!input) {
  88. return new NodeDish();
  89. }
  90. if (input instanceof NodeDish) {
  91. return input;
  92. } else {
  93. return new NodeDish(input);
  94. }
  95. }
  96. /**
  97. * prepareOp: transform args, make input the right type.
  98. * Also convert any Buffers to ArrayBuffers.
  99. * @param opInstance - instance of the operation
  100. * @param input - operation input
  101. * @param args - operation args
  102. */
  103. function prepareOp(opInstance, input, args) {
  104. const dish = ensureIsDish(input);
  105. // Transform object-style args to original args array
  106. const transformedArgs = transformArgs(opInstance.args, args);
  107. const transformedInput = dish.get(opInstance.inputType);
  108. return {transformedInput, transformedArgs};
  109. }
  110. /**
  111. * createArgInfo
  112. *
  113. * Create an object of options for each argument in the given operation
  114. *
  115. * Argument names are converted to camel case for consistency.
  116. *
  117. * @param {Operation} op - the operation to extract args from
  118. * @returns {{}} - arrays of options for args.
  119. */
  120. function createArgInfo(op) {
  121. const result = {};
  122. op.args.forEach((a) => {
  123. if (a.type === "option" || a.type === "editableOption") {
  124. result[sentenceToCamelCase(a.name)] = {
  125. type: a.type,
  126. options: removeSubheadingsFromArray(a.value)
  127. };
  128. } else if (a.type === "toggleString") {
  129. result[sentenceToCamelCase(a.name)] = {
  130. type: a.type,
  131. value: a.value,
  132. toggleValues: removeSubheadingsFromArray(a.toggleValues),
  133. };
  134. } else {
  135. result[sentenceToCamelCase(a.name)] = {
  136. type: a.type,
  137. value: a.value,
  138. };
  139. }
  140. });
  141. return result;
  142. }
  143. /**
  144. * Wrap an operation to be consumed by node API.
  145. * Checks to see if run function is async or not.
  146. * new Operation().run() becomes operation()
  147. * Perform type conversion on input
  148. * @private
  149. * @param {Operation} Operation
  150. * @returns {Function} The operation's run function, wrapped in
  151. * some type conversion logic
  152. */
  153. export function _wrap(OpClass) {
  154. // Check to see if class's run function is async.
  155. const opInstance = new OpClass();
  156. const isAsync = opInstance.run.constructor.name === "AsyncFunction";
  157. let wrapped;
  158. // If async, wrap must be async.
  159. if (isAsync) {
  160. /**
  161. * Async wrapped operation run function
  162. * @param {*} input
  163. * @param {Object | String[]} args - either in Object or normal args array
  164. * @returns {Promise<SyncDish>} operation's output, on a Dish.
  165. * @throws {OperationError} if the operation throws one.
  166. */
  167. wrapped = async (input, args=null) => {
  168. const {transformedInput, transformedArgs} = prepareOp(opInstance, input, args);
  169. const result = await opInstance.run(transformedInput, transformedArgs);
  170. return new NodeDish({
  171. value: result,
  172. type: opInstance.outputType,
  173. });
  174. };
  175. } else {
  176. /**
  177. * wrapped operation run function
  178. * @param {*} input
  179. * @param {Object | String[]} args - either in Object or normal args array
  180. * @returns {SyncDish} operation's output, on a Dish.
  181. * @throws {OperationError} if the operation throws one.
  182. */
  183. wrapped = (input, args=null) => {
  184. const {transformedInput, transformedArgs} = prepareOp(opInstance, input, args);
  185. const result = opInstance.run(transformedInput, transformedArgs);
  186. return new NodeDish({
  187. value: result,
  188. type: opInstance.outputType,
  189. });
  190. };
  191. }
  192. // used in chef.help
  193. wrapped.opName = OpClass.name;
  194. wrapped.args = createArgInfo(opInstance);
  195. return wrapped;
  196. }
  197. /**
  198. * help: Give information about operations matching the given search term,
  199. * or inputted operation.
  200. *
  201. * @param {String || wrapped operation} input - the name of the operation to get help for.
  202. * Case and whitespace are ignored in search.
  203. * @returns {Object[]} Config of matching operations.
  204. */
  205. export function help(input) {
  206. let searchTerm = false;
  207. if (typeof input === "string") {
  208. searchTerm = input;
  209. } else if (typeof input === "function") {
  210. searchTerm = input.opName;
  211. }
  212. if (!searchTerm) {
  213. return null;
  214. }
  215. let exactMatchExists = false;
  216. // Look for matches in operation name and description, listing name
  217. // matches first.
  218. const matches = Object.keys(OperationConfig)
  219. // hydrate operation: swap op name for op config object (with name)
  220. .map((m) => {
  221. const hydrated = OperationConfig[m];
  222. hydrated.name = m;
  223. // flag up an exact name match. Only first exact match counts.
  224. if (!exactMatchExists) {
  225. exactMatchExists = sanitise(hydrated.name) === sanitise(searchTerm);
  226. }
  227. // Return hydrated along with what type of match it was
  228. return {
  229. hydrated,
  230. nameExactMatch: sanitise(hydrated.name) === sanitise(searchTerm),
  231. nameMatch: sanitise(hydrated.name).includes(sanitise(searchTerm)),
  232. descMatch: sanitise(hydrated.description).includes(sanitise(searchTerm))
  233. };
  234. })
  235. // Filter out non-matches. If exact match exists, filter out all others.
  236. .filter((result) => {
  237. if (exactMatchExists) {
  238. return !!result.nameExactMatch;
  239. }
  240. return result.nameMatch || result.descMatch;
  241. })
  242. // sort results with name match first
  243. .sort((a, b) => {
  244. const aInt = a.nameMatch ? 1 : 0;
  245. const bInt = b.nameMatch ? 1 : 0;
  246. return bInt - aInt;
  247. })
  248. // extract just the hydrated config
  249. .map(result => result.hydrated);
  250. if (matches && matches.length) {
  251. // console.log(`${matches.length} result${matches.length > 1 ? "s" : ""} found.`);
  252. return matches;
  253. }
  254. // console.log("No results found.");
  255. return null;
  256. }
  257. /**
  258. * bake [Wrapped] - Perform an array of operations on some input.
  259. * @returns {Function}
  260. */
  261. export function bake() {
  262. /**
  263. * bake
  264. *
  265. * @param {*} input - some input for a recipe.
  266. * @param {String | Function | String[] | Function[] | [String | Function]} recipeConfig -
  267. * An operation, operation name, or an array of either.
  268. * @returns {SyncDish} of the result
  269. * @throws {TypeError} if invalid recipe given.
  270. */
  271. return function(input, recipeConfig) {
  272. const recipe = new NodeRecipe(recipeConfig);
  273. const dish = ensureIsDish(input);
  274. return recipe.execute(dish);
  275. };
  276. }
  277. /**
  278. * explainExcludedFunction
  279. *
  280. * Explain that the given operation is not included in the Node.js version.
  281. * @param {String} name - name of operation
  282. */
  283. export function _explainExcludedFunction(name) {
  284. /**
  285. * Throw new error type with useful message.
  286. */
  287. const func = () => {
  288. throw new ExcludedOperationError(`Sorry, the ${name} operation is not available in the Node.js version of CyberChef.`);
  289. };
  290. // Add opName prop so NodeRecipe can handle it, just like wrap does.
  291. func.opName = name;
  292. return func;
  293. }