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

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