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

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