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

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