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

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