JS Cookie Monitor/Debugger Hook

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

目前为 2021-01-09 提交的版本,查看 最新版本

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