utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. "use strict";
  6. const {Cc, Ci, Cu, components} = require("chrome");
  7. const Services = require("Services");
  8. const {LocalizationHelper} = require("devtools/shared/l10n");
  9. // Match the function name from the result of toString() or toSource().
  10. //
  11. // Examples:
  12. // (function foobar(a, b) { ...
  13. // function foobar2(a) { ...
  14. // function() { ...
  15. const REGEX_MATCH_FUNCTION_NAME = /^\(?function\s+([^(\s]+)\s*\(/;
  16. // Number of terminal entries for the self-xss prevention to go away
  17. const CONSOLE_ENTRY_THRESHOLD = 5;
  18. const CONSOLE_WORKER_IDS = exports.CONSOLE_WORKER_IDS = [
  19. "SharedWorker",
  20. "ServiceWorker",
  21. "Worker"
  22. ];
  23. var WebConsoleUtils = {
  24. /**
  25. * Wrap a string in an nsISupportsString object.
  26. *
  27. * @param string string
  28. * @return nsISupportsString
  29. */
  30. supportsString: function (string) {
  31. let str = Cc["@mozilla.org/supports-string;1"]
  32. .createInstance(Ci.nsISupportsString);
  33. str.data = string;
  34. return str;
  35. },
  36. /**
  37. * Clone an object.
  38. *
  39. * @param object object
  40. * The object you want cloned.
  41. * @param boolean recursive
  42. * Tells if you want to dig deeper into the object, to clone
  43. * recursively.
  44. * @param function [filter]
  45. * Optional, filter function, called for every property. Three
  46. * arguments are passed: key, value and object. Return true if the
  47. * property should be added to the cloned object. Return false to skip
  48. * the property.
  49. * @return object
  50. * The cloned object.
  51. */
  52. cloneObject: function (object, recursive, filter) {
  53. if (typeof object != "object") {
  54. return object;
  55. }
  56. let temp;
  57. if (Array.isArray(object)) {
  58. temp = [];
  59. Array.forEach(object, function (value, index) {
  60. if (!filter || filter(index, value, object)) {
  61. temp.push(recursive ? WebConsoleUtils.cloneObject(value) : value);
  62. }
  63. });
  64. } else {
  65. temp = {};
  66. for (let key in object) {
  67. let value = object[key];
  68. if (object.hasOwnProperty(key) &&
  69. (!filter || filter(key, value, object))) {
  70. temp[key] = recursive ? WebConsoleUtils.cloneObject(value) : value;
  71. }
  72. }
  73. }
  74. return temp;
  75. },
  76. /**
  77. * Copies certain style attributes from one element to another.
  78. *
  79. * @param nsIDOMNode from
  80. * The target node.
  81. * @param nsIDOMNode to
  82. * The destination node.
  83. */
  84. copyTextStyles: function (from, to) {
  85. let win = from.ownerDocument.defaultView;
  86. let style = win.getComputedStyle(from);
  87. to.style.fontFamily = style.getPropertyCSSValue("font-family").cssText;
  88. to.style.fontSize = style.getPropertyCSSValue("font-size").cssText;
  89. to.style.fontWeight = style.getPropertyCSSValue("font-weight").cssText;
  90. to.style.fontStyle = style.getPropertyCSSValue("font-style").cssText;
  91. },
  92. /**
  93. * Create a grip for the given value. If the value is an object,
  94. * an object wrapper will be created.
  95. *
  96. * @param mixed value
  97. * The value you want to create a grip for, before sending it to the
  98. * client.
  99. * @param function objectWrapper
  100. * If the value is an object then the objectWrapper function is
  101. * invoked to give us an object grip. See this.getObjectGrip().
  102. * @return mixed
  103. * The value grip.
  104. */
  105. createValueGrip: function (value, objectWrapper) {
  106. switch (typeof value) {
  107. case "boolean":
  108. return value;
  109. case "string":
  110. return objectWrapper(value);
  111. case "number":
  112. if (value === Infinity) {
  113. return { type: "Infinity" };
  114. } else if (value === -Infinity) {
  115. return { type: "-Infinity" };
  116. } else if (Number.isNaN(value)) {
  117. return { type: "NaN" };
  118. } else if (!value && 1 / value === -Infinity) {
  119. return { type: "-0" };
  120. }
  121. return value;
  122. case "undefined":
  123. return { type: "undefined" };
  124. case "object":
  125. if (value === null) {
  126. return { type: "null" };
  127. }
  128. // Fall through.
  129. case "function":
  130. return objectWrapper(value);
  131. default:
  132. console.error("Failed to provide a grip for value of " + typeof value
  133. + ": " + value);
  134. return null;
  135. }
  136. },
  137. /**
  138. * Determine if the given request mixes HTTP with HTTPS content.
  139. *
  140. * @param string request
  141. * Location of the requested content.
  142. * @param string location
  143. * Location of the current page.
  144. * @return boolean
  145. * True if the content is mixed, false if not.
  146. */
  147. isMixedHTTPSRequest: function (request, location) {
  148. try {
  149. let requestURI = Services.io.newURI(request, null, null);
  150. let contentURI = Services.io.newURI(location, null, null);
  151. return (contentURI.scheme == "https" && requestURI.scheme != "https");
  152. } catch (ex) {
  153. return false;
  154. }
  155. },
  156. /**
  157. * Helper function to deduce the name of the provided function.
  158. *
  159. * @param funtion function
  160. * The function whose name will be returned.
  161. * @return string
  162. * Function name.
  163. */
  164. getFunctionName: function (func) {
  165. let name = null;
  166. if (func.name) {
  167. name = func.name;
  168. } else {
  169. let desc;
  170. try {
  171. desc = func.getOwnPropertyDescriptor("displayName");
  172. } catch (ex) {
  173. // Ignore.
  174. }
  175. if (desc && typeof desc.value == "string") {
  176. name = desc.value;
  177. }
  178. }
  179. if (!name) {
  180. try {
  181. let str = (func.toString() || func.toSource()) + "";
  182. name = (str.match(REGEX_MATCH_FUNCTION_NAME) || [])[1];
  183. } catch (ex) {
  184. // Ignore.
  185. }
  186. }
  187. return name;
  188. },
  189. /**
  190. * Get the object class name. For example, the |window| object has the Window
  191. * class name (based on [object Window]).
  192. *
  193. * @param object object
  194. * The object you want to get the class name for.
  195. * @return string
  196. * The object class name.
  197. */
  198. getObjectClassName: function (object) {
  199. if (object === null) {
  200. return "null";
  201. }
  202. if (object === undefined) {
  203. return "undefined";
  204. }
  205. let type = typeof object;
  206. if (type != "object") {
  207. // Grip class names should start with an uppercase letter.
  208. return type.charAt(0).toUpperCase() + type.substr(1);
  209. }
  210. let className;
  211. try {
  212. className = ((object + "").match(/^\[object (\S+)\]$/) || [])[1];
  213. if (!className) {
  214. className = ((object.constructor + "")
  215. .match(/^\[object (\S+)\]$/) || [])[1];
  216. }
  217. if (!className && typeof object.constructor == "function") {
  218. className = this.getFunctionName(object.constructor);
  219. }
  220. } catch (ex) {
  221. // Ignore.
  222. }
  223. return className;
  224. },
  225. /**
  226. * Check if the given value is a grip with an actor.
  227. *
  228. * @param mixed grip
  229. * Value you want to check if it is a grip with an actor.
  230. * @return boolean
  231. * True if the given value is a grip with an actor.
  232. */
  233. isActorGrip: function (grip) {
  234. return grip && typeof (grip) == "object" && grip.actor;
  235. },
  236. /**
  237. * Value of devtools.selfxss.count preference
  238. *
  239. * @type number
  240. * @private
  241. */
  242. _usageCount: 0,
  243. get usageCount() {
  244. if (WebConsoleUtils._usageCount < CONSOLE_ENTRY_THRESHOLD) {
  245. WebConsoleUtils._usageCount =
  246. Services.prefs.getIntPref("devtools.selfxss.count");
  247. if (Services.prefs.getBoolPref("devtools.chrome.enabled")) {
  248. WebConsoleUtils.usageCount = CONSOLE_ENTRY_THRESHOLD;
  249. }
  250. }
  251. return WebConsoleUtils._usageCount;
  252. },
  253. set usageCount(newUC) {
  254. if (newUC <= CONSOLE_ENTRY_THRESHOLD) {
  255. WebConsoleUtils._usageCount = newUC;
  256. Services.prefs.setIntPref("devtools.selfxss.count", newUC);
  257. }
  258. },
  259. /**
  260. * The inputNode "paste" event handler generator. Helps prevent
  261. * self-xss attacks
  262. *
  263. * @param nsIDOMElement inputField
  264. * @param nsIDOMElement notificationBox
  265. * @returns A function to be added as a handler to 'paste' and
  266. *'drop' events on the input field
  267. */
  268. pasteHandlerGen: function (inputField, notificationBox, msg, okstring) {
  269. let handler = function (event) {
  270. if (WebConsoleUtils.usageCount >= CONSOLE_ENTRY_THRESHOLD) {
  271. inputField.removeEventListener("paste", handler);
  272. inputField.removeEventListener("drop", handler);
  273. return true;
  274. }
  275. if (notificationBox.getNotificationWithValue("selfxss-notification")) {
  276. event.preventDefault();
  277. event.stopPropagation();
  278. return false;
  279. }
  280. let notification = notificationBox.appendNotification(msg,
  281. "selfxss-notification", null,
  282. notificationBox.PRIORITY_WARNING_HIGH, null,
  283. function (eventType) {
  284. // Cleanup function if notification is dismissed
  285. if (eventType == "removed") {
  286. inputField.removeEventListener("keyup", pasteKeyUpHandler);
  287. }
  288. });
  289. function pasteKeyUpHandler(event2) {
  290. let value = inputField.value || inputField.textContent;
  291. if (value.includes(okstring)) {
  292. notificationBox.removeNotification(notification);
  293. inputField.removeEventListener("keyup", pasteKeyUpHandler);
  294. WebConsoleUtils.usageCount = CONSOLE_ENTRY_THRESHOLD;
  295. }
  296. }
  297. inputField.addEventListener("keyup", pasteKeyUpHandler);
  298. event.preventDefault();
  299. event.stopPropagation();
  300. return false;
  301. };
  302. return handler;
  303. },
  304. };
  305. exports.Utils = WebConsoleUtils;
  306. // Localization
  307. WebConsoleUtils.L10n = function (bundleURI) {
  308. this._helper = new LocalizationHelper(bundleURI);
  309. };
  310. WebConsoleUtils.L10n.prototype = {
  311. /**
  312. * Generates a formatted timestamp string for displaying in console messages.
  313. *
  314. * @param integer [milliseconds]
  315. * Optional, allows you to specify the timestamp in milliseconds since
  316. * the UNIX epoch.
  317. * @return string
  318. * The timestamp formatted for display.
  319. */
  320. timestampString: function (milliseconds) {
  321. let d = new Date(milliseconds ? milliseconds : null);
  322. let hours = d.getHours(), minutes = d.getMinutes();
  323. let seconds = d.getSeconds();
  324. milliseconds = d.getMilliseconds();
  325. let parameters = [hours, minutes, seconds, milliseconds];
  326. return this.getFormatStr("timestampFormat", parameters);
  327. },
  328. /**
  329. * Retrieve a localized string.
  330. *
  331. * @param string name
  332. * The string name you want from the Web Console string bundle.
  333. * @return string
  334. * The localized string.
  335. */
  336. getStr: function (name) {
  337. try {
  338. return this._helper.getStr(name);
  339. } catch (ex) {
  340. console.error("Failed to get string: " + name);
  341. throw ex;
  342. }
  343. },
  344. /**
  345. * Retrieve a localized string formatted with values coming from the given
  346. * array.
  347. *
  348. * @param string name
  349. * The string name you want from the Web Console string bundle.
  350. * @param array array
  351. * The array of values you want in the formatted string.
  352. * @return string
  353. * The formatted local string.
  354. */
  355. getFormatStr: function (name, array) {
  356. try {
  357. return this._helper.getFormatStr(name, ...array);
  358. } catch (ex) {
  359. console.error("Failed to format string: " + name);
  360. throw ex;
  361. }
  362. },
  363. };