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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. function broadcastDataUpdate() {}
  96. async function addLog(message) {
  97. logMessages.push(message);
  98. }
  99. ${bundle}
  100. return {
  101. handleStepData,
  102. closeLocalhostCallbackTabs,
  103. isLocalhostOAuthCallbackTabMatch,
  104. reset({ tabs, tabRegistry }) {
  105. currentTabs = tabs;
  106. removedBatches.length = 0;
  107. logMessages.length = 0;
  108. currentState = {
  109. tabRegistry: tabRegistry || {},
  110. };
  111. },
  112. snapshot() {
  113. return {
  114. currentState,
  115. removedBatches,
  116. logMessages,
  117. };
  118. },
  119. };
  120. `)();
  121. (async () => {
  122. const codexCallbackUrl = 'http://127.0.0.1:8317/codex/callback?code=abc&state=xyz';
  123. const authCallbackUrl = 'http://localhost:1455/auth/callback?code=def&state=uvw';
  124. assert.strictEqual(
  125. api.isLocalhostOAuthCallbackTabMatch(codexCallbackUrl, codexCallbackUrl),
  126. true,
  127. '真实 callback 页应命中清理规则'
  128. );
  129. assert.strictEqual(
  130. api.isLocalhostOAuthCallbackTabMatch(codexCallbackUrl, authCallbackUrl),
  131. false,
  132. '/codex/callback 不应误伤 /auth/callback'
  133. );
  134. assert.strictEqual(
  135. api.isLocalhostOAuthCallbackTabMatch(authCallbackUrl, codexCallbackUrl),
  136. false,
  137. '/auth/callback 不应误伤 /codex/callback'
  138. );
  139. api.reset({
  140. tabs: [
  141. { id: 1, url: codexCallbackUrl },
  142. { id: 2, url: 'http://127.0.0.1:8317/codex/dashboard' },
  143. { id: 3, url: 'http://127.0.0.1:8317/codex/callback?code=other&state=xyz' },
  144. { id: 4, url: authCallbackUrl },
  145. ],
  146. tabRegistry: {
  147. 'signup-page': { tabId: 1, ready: true },
  148. 'vps-panel': { tabId: 99, ready: true },
  149. },
  150. });
  151. await api.handleStepData(9, { localhostUrl: codexCallbackUrl });
  152. let snapshot = api.snapshot();
  153. assert.deepStrictEqual(
  154. snapshot.removedBatches,
  155. [[1], [2]],
  156. 'handleStepData(9) 应先关闭当前 callback 页,再按同源首段路径清理残留页'
  157. );
  158. assert.strictEqual(
  159. snapshot.currentState.tabRegistry['signup-page'],
  160. null,
  161. '关闭 callback 页后应同步清理 signup-page 的 tabRegistry'
  162. );
  163. assert.deepStrictEqual(
  164. snapshot.currentState.tabRegistry['vps-panel'],
  165. { tabId: 99, ready: true },
  166. '不相关的 tabRegistry 项不应被误清理'
  167. );
  168. api.reset({
  169. tabs: [
  170. { id: 1, url: codexCallbackUrl },
  171. { id: 4, url: authCallbackUrl },
  172. { id: 5, url: 'http://localhost:1455/auth/dashboard' },
  173. ],
  174. tabRegistry: {},
  175. });
  176. const closedCount = await api.closeLocalhostCallbackTabs(authCallbackUrl);
  177. snapshot = api.snapshot();
  178. assert.strictEqual(closedCount, 1, 'auth callback 也应只关闭当前命中的 callback 页');
  179. assert.deepStrictEqual(snapshot.removedBatches, [[4]], '不应按 /auth 前缀批量清理页面');
  180. assert.strictEqual(snapshot.logMessages.length, 1, '发生清理时应记录一条日志');
  181. console.log('step9 localhost cleanup scope tests passed');
  182. })().catch((error) => {
  183. console.error(error);
  184. process.exit(1);
  185. });