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

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