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

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