JS Cookie Monitor/Debugger Hook

用于监控js对cookie的修改,或者在cookie符合给定条件时进入断点

目前为 2021-01-08 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name JS Cookie Monitor/Debugger Hook
  3. // @namespace https://github.com/CC11001100/crawler-js-hook-framework-public
  4. // @version 0.6
  5. // @description 用于监控js对cookie的修改,或者在cookie符合给定条件时进入断点
  6. // @document https://github.com/CC11001100/crawler-js-hook-framework-public/tree/master/001-cookie-hook
  7. // @author CC11001100
  8. // @match *://*/*
  9. // @run-at document-start
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. (() => {
  14.  
  15. // 使用文档: https://github.com/CC11001100/crawler-js-hook-framework-public/tree/master/001-cookie-hook
  16.  
  17. // @since v0.6 断点规则发生了向后不兼容变化,详情请查阅文档
  18. const debuggerRules = [];
  19.  
  20. // 设置事件断点是否开启,一般保持默认即可
  21. const enableEventDebugger = {
  22. "add": true,
  23. "update": true,
  24. "delete": false
  25. }
  26.  
  27. // 在控制台打印日志时字体大小,根据自己喜好调整
  28. // 众所周知,12px是宇宙通用大小
  29. const consoleLogFontSize = 12;
  30.  
  31. // 使用document.cookie更新cookie,但是cookie新的值和原来的值一样,此时要不要忽略这个事件
  32. const ignoreUpdateButNotChanged = false;
  33.  
  34. (function addCookieHook() {
  35. Object.defineProperty(document, "cookie", {
  36. get: () => {
  37. delete document.cookie;
  38. const currentDocumentCookie = document.cookie;
  39. addCookieHook();
  40. return currentDocumentCookie;
  41. },
  42. set: newValue => {
  43. cc11001100_onSetCookie(newValue);
  44. delete document.cookie;
  45. document.cookie = newValue;
  46. addCookieHook();
  47. },
  48. configurable: true
  49. });
  50. })();
  51.  
  52. /**
  53. * 这个方法的前缀起到命名空间的作用,等下调用栈追溯赋值cookie的代码时需要用这个名字作为终结标志
  54. *
  55. * @param newValue
  56. */
  57. function cc11001100_onSetCookie(newValue) {
  58. const cookiePair = parseSetCookie(newValue);
  59. const currentCookieMap = getCurrentCookieMap();
  60.  
  61. // 如果过期时间为当前时间之前,则为删除,有可能没设置?虽然目前为止没碰到这样的...
  62. if (cookiePair.expires !== null && new Date().getTime() >= cookiePair.expires) {
  63. onDeleteCookie(newValue, cookiePair.name, cookiePair.value || (currentCookieMap.get(cookiePair.name) || {}).value);
  64. return;
  65. }
  66.  
  67. // 如果之前已经存在,则是修改
  68. if (currentCookieMap.has(cookiePair.name)) {
  69. onCookieUpdate(newValue, cookiePair.name, currentCookieMap.get(cookiePair.name).value, cookiePair.value);
  70. return;
  71. }
  72.  
  73. // 否则则为添加
  74. onCookieAdd(newValue, cookiePair.name, cookiePair.value);
  75. }
  76.  
  77. function onDeleteCookie(cookieOriginalValue, cookieName, cookieValue) {
  78. const valueStyle = `color: black; background: #E50000; font-size: ${consoleLogFontSize}px; font-weight: bold;`;
  79. const normalStyle = `color: black; background: #FF6766; font-size: ${consoleLogFontSize}px;`;
  80.  
  81. const message = [
  82.  
  83. normalStyle,
  84. now(),
  85.  
  86. normalStyle,
  87. "JS Cookie Monitor: ",
  88.  
  89. normalStyle,
  90. "delete cookie, cookieName = ",
  91.  
  92. valueStyle,
  93. `${cookieName}`,
  94.  
  95. ...(() => {
  96. if (!cookieValue) {
  97. return [];
  98. }
  99. return [
  100. normalStyle,
  101. ", value = ",
  102.  
  103. valueStyle,
  104. `${cookieValue}`,
  105. ];
  106. })(),
  107.  
  108. normalStyle,
  109. `, code location = ${getCodeLocation()}`
  110. ];
  111. console.log(genFormatArray(message), ...message);
  112.  
  113. testDebuggerRules(cookieOriginalValue, "delete", cookieName, cookieValue);
  114. }
  115.  
  116. function onCookieUpdate(cookieOriginalValue, cookieName, oldCookieValue, newCookieValue) {
  117.  
  118. const cookieValueChanged = oldCookieValue !== newCookieValue;
  119.  
  120. if (ignoreUpdateButNotChanged && !cookieValueChanged) {
  121. return;
  122. }
  123.  
  124. const valueStyle = `color: black; background: #FE9900; font-size: ${consoleLogFontSize}px; font-weight: bold;`;
  125. const normalStyle = `color: black; background: #FFCC00; font-size: ${consoleLogFontSize}px;`;
  126.  
  127. const message = [
  128.  
  129. normalStyle,
  130. now(),
  131.  
  132. normalStyle,
  133. "JS Cookie Monitor: ",
  134.  
  135. normalStyle,
  136. "update cookie, cookieName = ",
  137.  
  138. valueStyle,
  139. `${cookieName}`,
  140.  
  141. ...(() => {
  142. if (cookieValueChanged) {
  143. return [
  144. normalStyle,
  145. `, oldValue = `,
  146.  
  147. valueStyle,
  148. `${oldCookieValue}`,
  149.  
  150. normalStyle,
  151. `, newValue = `,
  152.  
  153. valueStyle,
  154. `${newCookieValue}`
  155. ]
  156. } else {
  157. return [
  158. normalStyle,
  159. `, value = `,
  160.  
  161. valueStyle,
  162. `${newCookieValue}`,
  163. ];
  164. }
  165. })(),
  166.  
  167. normalStyle,
  168. `, valueChanged = `,
  169.  
  170. valueStyle,
  171. `${cookieValueChanged}`,
  172.  
  173. normalStyle,
  174. `, code location = ${getCodeLocation()}`
  175. ];
  176. console.log(genFormatArray(message), ...message);
  177.  
  178. testDebuggerRules(cookieOriginalValue, "update", cookieName, newCookieValue);
  179. }
  180.  
  181. function onCookieAdd(cookieOriginalValue, cookieName, cookieValue) {
  182. const valueStyle = `color: black; background: #669934; font-size: ${consoleLogFontSize}px; font-weight: bold;`;
  183. const normalStyle = `color: black; background: #65CC66; font-size: ${consoleLogFontSize}px;`;
  184.  
  185. const message = [
  186.  
  187. normalStyle,
  188. now(),
  189.  
  190. normalStyle,
  191. "JS Cookie Monitor: ",
  192.  
  193. normalStyle,
  194. "add cookie, cookieName = ",
  195.  
  196. valueStyle,
  197. `${cookieName}`,
  198.  
  199. normalStyle,
  200. ", cookieValue = ",
  201.  
  202. valueStyle,
  203. `${cookieValue}`,
  204.  
  205. normalStyle,
  206. `, code location = ${getCodeLocation()}`
  207. ];
  208. console.log(genFormatArray(message), ...message);
  209.  
  210. testDebuggerRules(cookieOriginalValue, "add", cookieName, cookieValue);
  211. }
  212.  
  213. // 根据cookie名字判断你是否需要进入断点
  214. function isNeedDebuggerByCookieName(eventName, cookieName) {
  215.  
  216. // 如果没有开启此类事件进入断点,则直接忽略即可
  217. if (!enableEventDebugger[eventName]) {
  218. return;
  219. }
  220.  
  221. // 名称完全匹配
  222. for (let x of debuggerOnChangeAndCookieNameEquals) {
  223. if (typeof x === "string" && x === cookieName) {
  224. debugger;
  225. } else if (typeof x === "object" && x[eventName] && x[eventName] === cookieName) {
  226. debugger;
  227. }
  228. }
  229.  
  230. // 正则匹配
  231. for (let x of debuggerOnChangeAndCookieNameRegex) {
  232. if (x instanceof RegExp && x.test(cookieName)) {
  233. debugger;
  234. } else if (x[eventName] && x[eventName].test(cookieName)) {
  235. debugger;
  236. }
  237. }
  238. }
  239.  
  240. // 根据cookie值判断是否需要进入断点
  241. function isNeedDebuggerByCookieValue(eventName, cookieValue) {
  242.  
  243. // 如果没有开启此类事件进入断点,则直接忽略即可
  244. if (!enableEventDebugger[eventName]) {
  245. return;
  246. }
  247.  
  248. // 此时rule都是DebuggerRule类型的
  249. for (let rule of debuggerRules) {
  250. if (rule.eventName && rule.eventName !== eventName) {
  251. continue;
  252. } else if (!rule.cookieValueFilter) {
  253. continue;
  254. }
  255. }
  256. }
  257.  
  258. function now() {
  259. // 东八区专属...
  260. return "[" + new Date(new Date().getTime() + 1000 * 60 * 60 * 8).toJSON().replace("T", " ").replace("Z", "") + "] ";
  261. }
  262.  
  263. function genFormatArray(messageAndStyleArray) {
  264. const formatArray = [];
  265. for (let i = 0, end = messageAndStyleArray.length / 2; i < end; i++) {
  266. formatArray.push("%c%s");
  267. }
  268. return formatArray.join("");
  269. }
  270.  
  271. function getCodeLocation() {
  272. const callstack = new Error().stack.split("\n");
  273. while (callstack.length && callstack[0].indexOf("cc11001100") === -1) {
  274. callstack.shift();
  275. }
  276. callstack.shift();
  277. callstack.shift();
  278.  
  279. return callstack[0].trim();
  280. }
  281.  
  282. /**
  283. * 将本次设置cookie的字符串解析为容易处理的形式
  284. *
  285. * @param cookieString
  286. * @returns {CookiePair}
  287. */
  288. function parseSetCookie(cookieString) {
  289. // uuid_tt_dd=10_37476713480-1609821005397-659114; Expires=Thu, 01 Jan 1025 00:00:00 GMT; Path=/; Domain=.csdn.net;
  290. const cookieStringSplit = cookieString.split(";");
  291. const cookieNameValueArray = cookieStringSplit[0].split("=", 2);
  292. const cookieName = decodeURIComponent(cookieNameValueArray[0].trim());
  293. const cookieValue = cookieNameValueArray.length > 1 ? decodeURIComponent(cookieNameValueArray[1].trim()) : "";
  294. const map = new Map();
  295. for (let i = 1; i < cookieStringSplit.length; i++) {
  296. const ss = cookieStringSplit[i].split("=", 2);
  297. const key = ss[0].trim().toLowerCase();
  298. const value = ss.length > 1 ? ss[1].trim() : "";
  299. map.set(key, value);
  300. }
  301. // 当不设置expires的时候关闭浏览器就过期
  302. const expires = map.get("expires");
  303. return new CookiePair(cookieName, cookieValue, expires ? new Date(expires).getTime() : null)
  304. }
  305.  
  306. /**
  307. * 获取当前所有已经设置的cookie
  308. *
  309. * @returns {Map<string, CookiePair>}
  310. */
  311. function getCurrentCookieMap() {
  312. const cookieMap = new Map();
  313. if (!document.cookie) {
  314. return cookieMap;
  315. }
  316. document.cookie.split(";").forEach(x => {
  317. const ss = x.split("=", 2);
  318. const key = decodeURIComponent(ss[0].trim());
  319. const value = ss.length > 1 ? decodeURIComponent(ss[1].trim()) : "";
  320. cookieMap.set(key, new CookiePair(key, value));
  321. });
  322. return cookieMap;
  323. }
  324.  
  325. class DebuggerRule {
  326.  
  327. constructor(eventName, cookieNameFilter, cookieValueFilter) {
  328. this.eventName = eventName;
  329. this.cookieNameFilter = cookieNameFilter;
  330. this.cookieValueFilter = cookieValueFilter;
  331. }
  332.  
  333. test(eventName, cookieName, cookieValue) {
  334. return this.testByEventName(eventName) && (this.testByCookieNameFilter(cookieName) || this.testByCookieValueFilter(cookieValue));
  335. }
  336.  
  337. testByEventName(eventName) {
  338. // 事件不设置则匹配任何事件
  339. if (!this.eventName) {
  340. return true;
  341. }
  342. return this.eventName === eventName;
  343. }
  344.  
  345. testByCookieNameFilter(cookieName) {
  346. if (!cookieName || !this.cookieNameFilter) {
  347. return false;
  348. }
  349. if (typeof this.cookieNameFilter === "string") {
  350. return this.cookieNameFilter === cookieName;
  351. }
  352. if (this.cookieNameFilter instanceof RegExp) {
  353. return this.cookieNameFilter.test(cookieName);
  354. }
  355. return false;
  356. }
  357.  
  358. testByCookieValueFilter(cookieValue) {
  359. if (!cookieValue || !this.cookieValueFilter) {
  360. return false;
  361. }
  362. if (typeof this.cookieValueFilter === "string") {
  363. return this.cookieValueFilter === cookieValue;
  364. }
  365. if (this.cookieValueFilter instanceof RegExp) {
  366. return this.cookieValueFilter.test(cookieValue);
  367. }
  368. return false;
  369. }
  370.  
  371. }
  372.  
  373. // 将规则整理为标准
  374. (function standardizingRules() {
  375. const newRules = [];
  376. while (debuggerRules.length) {
  377. const rule = debuggerRules.pop();
  378.  
  379. // 如果是字符串或者正则
  380. if (typeof rule === "string" || rule instanceof RegExp) {
  381. newRules.push(new DebuggerRule(null, rule, null));
  382. continue;
  383. }
  384.  
  385. // 如果是字典对象,则似乎有点麻烦
  386. for (let key in rule) {
  387. let events = null;
  388. let cookieNameFilter = null;
  389. let cookieValueFilter = null;
  390. if (key === "events") {
  391. events = rule["events"] || "add|delete|update";
  392. cookieNameFilter = rule["name"]
  393. cookieValueFilter = rule["value"];
  394. } else if (key !== "name" && key !== "value") {
  395. events = key;
  396. cookieNameFilter = rule[key];
  397. cookieValueFilter = rule["value"];
  398. } else {
  399. // name & value ignore
  400. continue;
  401. }
  402. // cookie的名字是必须配置的
  403. if (!cookieNameFilter) {
  404. // TODO 提示更友好
  405. throw new Error("Cookie Monitor: 规则配置错误");
  406. }
  407. events.split("|").forEach(eventName => {
  408. newRules.push(new DebuggerRule(eventName.trim(), cookieNameFilter, cookieValueFilter));
  409. })
  410. }
  411. }
  412.  
  413. // 是否需要合并重复规则呢?
  414. // 还是不了,而且静态合并对于正则没办法,用户应该知道自己在做什么
  415.  
  416. for (let rule of newRules) {
  417. debuggerRules.push(rule);
  418. }
  419. })();
  420.  
  421. /**
  422. * 当断点停在这里时查看这个方法各个参数的值能够大致了解断点情况
  423. *
  424. * @param setCookieOriginalValue 目标网站使用document.cookie时赋值的原始值是什么
  425. * @param eventName 本次是发生了什么事件,add增加新cookie、update更新cookie的值、delete cookie被删除
  426. * @param cookieName 本脚本对setCookieOriginalValue解析出的cookie名字
  427. * @param cookieValue 本脚本对setCookieOriginalValue解析出的cookie值
  428. */
  429. function testDebuggerRules(setCookieOriginalValue, eventName, cookieName, cookieValue) {
  430. for (let rule of debuggerRules) {
  431. //rule当前的值表示被什么断点规则匹配到了
  432. if (rule.test(eventName, cookieName, cookieValue)) {
  433. debugger;
  434. }
  435. }
  436. }
  437.  
  438. class CookiePair {
  439. constructor(name, value, expires) {
  440. this.name = name;
  441. this.value = value;
  442. this.expires = expires;
  443. }
  444. }
  445. }
  446.  
  447. )();