step9-localhost-cleanup-scope.test.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. const assert = require('assert');
  2. const fs = require('fs');
  3. const source = fs.readFileSync('background.js', 'utf8');
  4. function extractFunction(name) {
  5. const markers = [`async function ${name}(`, `function ${name}(`];
  6. const start = markers
  7. .map(marker => source.indexOf(marker))
  8. .find(index => index >= 0);
  9. if (start < 0) {
  10. throw new Error(`missing function ${name}`);
  11. }
  12. let parenDepth = 0;
  13. let signatureEnded = false;
  14. let braceStart = -1;
  15. for (let i = start; i < source.length; i++) {
  16. const ch = source[i];
  17. if (ch === '(') {
  18. parenDepth += 1;
  19. } else if (ch === ')') {
  20. parenDepth -= 1;
  21. if (parenDepth === 0) {
  22. signatureEnded = true;
  23. }
  24. } else if (ch === '{' && signatureEnded) {
  25. braceStart = i;
  26. break;
  27. }
  28. }
  29. if (braceStart < 0) {
  30. throw new Error(`missing body for function ${name}`);
  31. }
  32. let depth = 0;
  33. let end = braceStart;
  34. for (; end < source.length; end++) {
  35. const ch = source[end];
  36. if (ch === '{') depth += 1;
  37. if (ch === '}') {
  38. depth -= 1;
  39. if (depth === 0) {
  40. end += 1;
  41. break;
  42. }
  43. }
  44. }
  45. return source.slice(start, end);
  46. }
  47. const bundle = [
  48. extractFunction('getTabRegistry'),
  49. extractFunction('parseUrlSafely'),
  50. extractFunction('isLocalhostOAuthCallbackUrl'),
  51. extractFunction('isLocalhostOAuthCallbackTabMatch'),
  52. extractFunction('closeLocalhostCallbackTabs'),
  53. extractFunction('buildLocalhostCleanupPrefix'),
  54. extractFunction('closeTabsByUrlPrefix'),
  55. extractFunction('handleStepData'),
  56. ].join('\n');
  57. const api = new Function(`
  58. let currentState = {
  59. tabRegistry: {
  60. 'signup-page': { tabId: 1, ready: true },
  61. 'vps-panel': { tabId: 99, ready: true },
  62. },
  63. };
  64. let currentTabs = [];
  65. const removedBatches = [];
  66. const logMessages = [];
  67. const chrome = {
  68. tabs: {
  69. async query() {
  70. return currentTabs;
  71. },
  72. async remove(ids) {
  73. removedBatches.push(ids);
  74. currentTabs = currentTabs.filter((tab) => !ids.includes(tab.id));
  75. },
  76. },
  77. };
  78. async function getState() {
  79. return currentState;
  80. }
  81. async function setState(updates) {
  82. currentState = { ...currentState, ...updates };
  83. }
  84. async function setEmailState(email) {
  85. currentState = { ...currentState, email };
  86. }
  87. async function setEmailStateSilently(email) {
  88. currentState = { ...currentState, email };
  89. }
  90. function isHotmailProvider() {
  91. return false;
  92. }
  93. function isLuckmailProvider() {
  94. return false;
  95. }
  96. async function patchHotmailAccount() {}
  97. async function clearLuckmailRuntimeState() {}
  98. function shouldUseCustomRegistrationEmail() {
  99. return false;
  100. }
  101. function broadcastDataUpdate() {}
  102. async function addLog(message) {
  103. logMessages.push(message);
  104. }
  105. ${bundle}
  106. return {
  107. handleStepData,
  108. closeLocalhostCallbackTabs,
  109. isLocalhostOAuthCallbackTabMatch,
  110. reset({ tabs, tabRegistry }) {
  111. currentTabs = tabs;
  112. removedBatches.length = 0;
  113. logMessages.length = 0;
  114. currentState = {
  115. tabRegistry: tabRegistry || {},
  116. };
  117. },
  118. snapshot() {
  119. return {
  120. currentState,
  121. removedBatches,
  122. logMessages,
  123. };
  124. },
  125. };
  126. `)();
  127. (async () => {
  128. const codexCallbackUrl = 'http://127.0.0.1:8317/codex/callback?code=abc&state=xyz';
  129. const authCallbackUrl = 'http://localhost:1455/auth/callback?code=def&state=uvw';
  130. assert.strictEqual(
  131. api.isLocalhostOAuthCallbackTabMatch(codexCallbackUrl, codexCallbackUrl),
  132. true,
  133. '真实 callback 页应命中清理规则'
  134. );
  135. assert.strictEqual(
  136. api.isLocalhostOAuthCallbackTabMatch(codexCallbackUrl, authCallbackUrl),
  137. false,
  138. '/codex/callback 不应误伤 /auth/callback'
  139. );
  140. assert.strictEqual(
  141. api.isLocalhostOAuthCallbackTabMatch(authCallbackUrl, codexCallbackUrl),
  142. false,
  143. '/auth/callback 不应误伤 /codex/callback'
  144. );
  145. api.reset({
  146. tabs: [
  147. { id: 1, url: codexCallbackUrl },
  148. { id: 2, url: 'http://127.0.0.1:8317/codex/dashboard' },
  149. { id: 3, url: 'http://127.0.0.1:8317/codex/callback?code=other&state=xyz' },
  150. { id: 4, url: authCallbackUrl },
  151. ],
  152. tabRegistry: {
  153. 'signup-page': { tabId: 1, ready: true },
  154. 'vps-panel': { tabId: 99, ready: true },
  155. },
  156. });
  157. await api.handleStepData(9, { localhostUrl: codexCallbackUrl });
  158. let snapshot = api.snapshot();
  159. assert.deepStrictEqual(
  160. snapshot.removedBatches,
  161. [[1], [2, 3]],
  162. 'handleStepData(9) 应先关闭当前 callback 页,再按同前缀路径清理残留页'
  163. );
  164. assert.strictEqual(
  165. snapshot.currentState.tabRegistry['signup-page'],
  166. null,
  167. '关闭 callback 页后应同步清理 signup-page 的 tabRegistry'
  168. );
  169. assert.deepStrictEqual(
  170. snapshot.currentState.tabRegistry['vps-panel'],
  171. { tabId: 99, ready: true },
  172. '不相关的 tabRegistry 项不应被误清理'
  173. );
  174. api.reset({
  175. tabs: [
  176. { id: 1, url: codexCallbackUrl },
  177. { id: 4, url: authCallbackUrl },
  178. { id: 5, url: 'http://localhost:1455/auth/dashboard' },
  179. ],
  180. tabRegistry: {},
  181. });
  182. const closedCount = await api.closeLocalhostCallbackTabs(authCallbackUrl);
  183. snapshot = api.snapshot();
  184. assert.strictEqual(closedCount, 1, 'auth callback 也应只关闭当前命中的 callback 页');
  185. assert.deepStrictEqual(snapshot.removedBatches, [[4]], '不应按 /auth 前缀批量清理页面');
  186. assert.strictEqual(snapshot.logMessages.length, 1, '发生清理时应记录一条日志');
  187. console.log('step9 localhost cleanup scope tests passed');
  188. })().catch((error) => {
  189. console.error(error);
  190. process.exit(1);
  191. });