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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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('normalizeEmailGenerator'),
  50. extractFunction('parseUrlSafely'),
  51. extractFunction('isHotmailProvider'),
  52. extractFunction('isCustomMailProvider'),
  53. extractFunction('isGeneratedAliasProvider'),
  54. extractFunction('shouldUseCustomRegistrationEmail'),
  55. extractFunction('isLocalhostOAuthCallbackUrl'),
  56. extractFunction('isLocalhostOAuthCallbackTabMatch'),
  57. extractFunction('closeLocalhostCallbackTabs'),
  58. extractFunction('buildLocalhostCleanupPrefix'),
  59. extractFunction('closeTabsByUrlPrefix'),
  60. extractFunction('handleStepData'),
  61. ].join('\n');
  62. const api = new Function(`
  63. const HOTMAIL_PROVIDER = 'hotmail-api';
  64. const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
  65. const CLOUDFLARE_TEMP_EMAIL_GENERATOR = 'cloudflare-temp-email';
  66. let currentState = {
  67. tabRegistry: {
  68. 'signup-page': { tabId: 1, ready: true },
  69. 'vps-panel': { tabId: 99, ready: true },
  70. },
  71. };
  72. let currentTabs = [];
  73. const removedBatches = [];
  74. const logMessages = [];
  75. const chrome = {
  76. tabs: {
  77. async query() {
  78. return currentTabs;
  79. },
  80. async remove(ids) {
  81. removedBatches.push(ids);
  82. currentTabs = currentTabs.filter((tab) => !ids.includes(tab.id));
  83. },
  84. },
  85. };
  86. async function getState() {
  87. return currentState;
  88. }
  89. async function setState(updates) {
  90. currentState = { ...currentState, ...updates };
  91. }
  92. async function setEmailState(email) {
  93. currentState = { ...currentState, email };
  94. }
  95. async function setEmailStateSilently(email) {
  96. currentState = { ...currentState, email };
  97. }
  98. function isHotmailProvider() {
  99. return false;
  100. }
  101. function isLuckmailProvider() {
  102. return false;
  103. }
  104. async function patchHotmailAccount() {}
  105. async function clearLuckmailRuntimeState() {}
  106. function shouldUseCustomRegistrationEmail() {
  107. return false;
  108. }
  109. function broadcastDataUpdate() {}
  110. async function addLog(message) {
  111. logMessages.push(message);
  112. }
  113. async function finalizeIcloudAliasAfterSuccessfulFlow() {}
  114. function shouldUseCustomRegistrationEmail() {
  115. return false;
  116. }
  117. ${bundle}
  118. return {
  119. handleStepData,
  120. closeLocalhostCallbackTabs,
  121. isLocalhostOAuthCallbackTabMatch,
  122. reset({ tabs, tabRegistry }) {
  123. currentTabs = tabs;
  124. removedBatches.length = 0;
  125. logMessages.length = 0;
  126. currentState = {
  127. tabRegistry: tabRegistry || {},
  128. };
  129. },
  130. snapshot() {
  131. return {
  132. currentState,
  133. removedBatches,
  134. logMessages,
  135. };
  136. },
  137. };
  138. `)();
  139. (async () => {
  140. const codexCallbackUrl = 'http://127.0.0.1:8317/codex/callback?code=abc&state=xyz';
  141. const authCallbackUrl = 'http://localhost:1455/auth/callback?code=def&state=uvw';
  142. assert.strictEqual(
  143. api.isLocalhostOAuthCallbackTabMatch(codexCallbackUrl, codexCallbackUrl),
  144. true,
  145. '真实 callback 页应命中清理规则'
  146. );
  147. assert.strictEqual(
  148. api.isLocalhostOAuthCallbackTabMatch(codexCallbackUrl, authCallbackUrl),
  149. false,
  150. '/codex/callback 不应误伤 /auth/callback'
  151. );
  152. assert.strictEqual(
  153. api.isLocalhostOAuthCallbackTabMatch(authCallbackUrl, codexCallbackUrl),
  154. false,
  155. '/auth/callback 不应误伤 /codex/callback'
  156. );
  157. api.reset({
  158. tabs: [
  159. { id: 1, url: codexCallbackUrl },
  160. { id: 2, url: 'http://127.0.0.1:8317/codex/dashboard' },
  161. { id: 3, url: 'http://127.0.0.1:8317/codex/callback?code=other&state=xyz' },
  162. { id: 4, url: authCallbackUrl },
  163. ],
  164. tabRegistry: {
  165. 'signup-page': { tabId: 1, ready: true },
  166. 'vps-panel': { tabId: 99, ready: true },
  167. },
  168. });
  169. await api.handleStepData(9, { localhostUrl: codexCallbackUrl });
  170. let snapshot = api.snapshot();
  171. assert.deepStrictEqual(
  172. snapshot.removedBatches,
  173. [[1], [2]],
  174. 'handleStepData(9) 应先关闭当前 callback 页,再按同源首段路径清理残留页'
  175. );
  176. assert.strictEqual(
  177. snapshot.currentState.tabRegistry['signup-page'],
  178. null,
  179. '关闭 callback 页后应同步清理 signup-page 的 tabRegistry'
  180. );
  181. assert.deepStrictEqual(
  182. snapshot.currentState.tabRegistry['vps-panel'],
  183. { tabId: 99, ready: true },
  184. '不相关的 tabRegistry 项不应被误清理'
  185. );
  186. api.reset({
  187. tabs: [
  188. { id: 1, url: codexCallbackUrl },
  189. { id: 4, url: authCallbackUrl },
  190. { id: 5, url: 'http://localhost:1455/auth/dashboard' },
  191. ],
  192. tabRegistry: {},
  193. });
  194. const closedCount = await api.closeLocalhostCallbackTabs(authCallbackUrl);
  195. snapshot = api.snapshot();
  196. assert.strictEqual(closedCount, 1, 'auth callback 也应只关闭当前命中的 callback 页');
  197. assert.deepStrictEqual(snapshot.removedBatches, [[4]], '不应按 /auth 前缀批量清理页面');
  198. assert.strictEqual(snapshot.logMessages.length, 1, '发生清理时应记录一条日志');
  199. console.log('step9 localhost cleanup scope tests passed');
  200. })().catch((error) => {
  201. console.error(error);
  202. process.exit(1);
  203. });