JS Cookie Monitor/Debugger Hook

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

当前为 2023-07-26 提交的版本,查看 最新版本

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