JS Cookie Monitor/Debugger Hook

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

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