verification-stop-propagation.test.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. const assert = require('assert');
  2. const fs = require('fs');
  3. const helperSource = fs.readFileSync('background.js', 'utf8');
  4. const verificationFlowSource = fs.readFileSync('background/verification-flow.js', 'utf8');
  5. function extractFunction(source, name) {
  6. const markers = [`async function ${name}(`, `function ${name}(`];
  7. const start = markers
  8. .map(marker => source.indexOf(marker))
  9. .find(index => index >= 0);
  10. if (start < 0) {
  11. throw new Error(`missing function ${name}`);
  12. }
  13. let parenDepth = 0;
  14. let signatureEnded = false;
  15. let braceStart = -1;
  16. for (let i = start; i < source.length; i += 1) {
  17. const ch = source[i];
  18. if (ch === '(') {
  19. parenDepth += 1;
  20. } else if (ch === ')') {
  21. parenDepth -= 1;
  22. if (parenDepth === 0) {
  23. signatureEnded = true;
  24. }
  25. } else if (ch === '{' && signatureEnded) {
  26. braceStart = i;
  27. break;
  28. }
  29. }
  30. if (braceStart < 0) {
  31. throw new Error(`missing body for function ${name}`);
  32. }
  33. let depth = 0;
  34. let end = braceStart;
  35. for (; end < source.length; end += 1) {
  36. const ch = source[end];
  37. if (ch === '{') depth += 1;
  38. if (ch === '}') {
  39. depth -= 1;
  40. if (depth === 0) {
  41. end += 1;
  42. break;
  43. }
  44. }
  45. }
  46. return source.slice(start, end);
  47. }
  48. async function testPollFreshVerificationCodeRethrowsStop() {
  49. const helperBundle = [
  50. extractFunction(helperSource, 'isStopError'),
  51. extractFunction(helperSource, 'throwIfStopped'),
  52. ].join('\n');
  53. const api = new Function('verificationFlowSource', `
  54. const self = {};
  55. let stopRequested = false;
  56. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  57. const HOTMAIL_PROVIDER = 'hotmail-api';
  58. const LUCKMAIL_PROVIDER = 'luckmail-api';
  59. const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
  60. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  61. const logs = [];
  62. let resendCalls = 0;
  63. function getHotmailVerificationPollConfig() {
  64. return {};
  65. }
  66. async function pollHotmailVerificationCode() {
  67. throw new Error('hotmail path should not run in this test');
  68. }
  69. async function pollLuckmailVerificationCode() {
  70. throw new Error('luckmail path should not run in this test');
  71. }
  72. async function pollCloudflareTempEmailVerificationCode() {
  73. throw new Error('cloudflare path should not run in this test');
  74. }
  75. async function sendToMailContentScriptResilient() {
  76. throw new Error(STOP_ERROR_MESSAGE);
  77. }
  78. async function requestVerificationCodeResend() {
  79. resendCalls += 1;
  80. }
  81. async function addLog(message, level) {
  82. logs.push({ message, level });
  83. }
  84. ${helperBundle}
  85. ${verificationFlowSource}
  86. const helpers = self.MultiPageBackgroundVerificationFlow.createVerificationFlowHelpers({
  87. addLog,
  88. chrome: {},
  89. CLOUDFLARE_TEMP_EMAIL_PROVIDER,
  90. completeStepFromBackground: async () => {},
  91. confirmCustomVerificationStepBypassRequest: async () => ({ confirmed: true }),
  92. getHotmailVerificationPollConfig,
  93. getHotmailVerificationRequestTimestamp: () => 123,
  94. getState: async () => ({}),
  95. getTabId: async () => null,
  96. HOTMAIL_PROVIDER,
  97. isStopError,
  98. LUCKMAIL_PROVIDER,
  99. pollCloudflareTempEmailVerificationCode,
  100. pollHotmailVerificationCode,
  101. pollLuckmailVerificationCode,
  102. sendToContentScript: async () => ({}),
  103. sendToMailContentScriptResilient,
  104. setState: async () => {},
  105. setStepStatus: async () => {},
  106. sleepWithStop: async () => {},
  107. throwIfStopped,
  108. VERIFICATION_POLL_MAX_ROUNDS,
  109. });
  110. return {
  111. pollFreshVerificationCode: helpers.pollFreshVerificationCode,
  112. snapshot() {
  113. return { logs, resendCalls };
  114. },
  115. };
  116. `)(verificationFlowSource);
  117. let error = null;
  118. try {
  119. await api.pollFreshVerificationCode(7, {}, { provider: 'qq' }, {});
  120. } catch (err) {
  121. error = err;
  122. }
  123. const state = api.snapshot();
  124. assert.strictEqual(error?.message, '流程已被用户停止。', 'Stop 错误应原样向上抛出');
  125. assert.strictEqual(state.resendCalls, 0, 'Stop 后不应继续请求新的验证码');
  126. assert.deepStrictEqual(state.logs, [], 'Stop 后不应再记录普通失败或重试日志');
  127. }
  128. async function testResolveVerificationStepRethrowsStopFromFreshRequest() {
  129. const helperBundle = [
  130. extractFunction(helperSource, 'isStopError'),
  131. ].join('\n');
  132. const api = new Function('verificationFlowSource', `
  133. const self = {};
  134. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  135. const HOTMAIL_PROVIDER = 'hotmail-api';
  136. const LUCKMAIL_PROVIDER = 'luckmail-api';
  137. const CLOUDFLARE_TEMP_EMAIL_PROVIDER = 'cloudflare-temp-email';
  138. const logs = [];
  139. let pollCalls = 0;
  140. async function addLog(message, level) {
  141. logs.push({ message, level });
  142. }
  143. const chrome = { tabs: { async update() {} } };
  144. ${helperBundle}
  145. ${verificationFlowSource}
  146. const helpers = self.MultiPageBackgroundVerificationFlow.createVerificationFlowHelpers({
  147. addLog,
  148. chrome,
  149. CLOUDFLARE_TEMP_EMAIL_PROVIDER,
  150. completeStepFromBackground: async () => {},
  151. confirmCustomVerificationStepBypassRequest: async () => ({ confirmed: true }),
  152. getHotmailVerificationPollConfig: () => ({}),
  153. getHotmailVerificationRequestTimestamp: () => 123,
  154. getState: async () => ({}),
  155. getTabId: async () => 1,
  156. HOTMAIL_PROVIDER,
  157. isStopError,
  158. LUCKMAIL_PROVIDER,
  159. pollCloudflareTempEmailVerificationCode: async () => ({}),
  160. pollHotmailVerificationCode: async () => ({}),
  161. pollLuckmailVerificationCode: async () => ({}),
  162. sendToContentScript: async () => {
  163. throw new Error(STOP_ERROR_MESSAGE);
  164. },
  165. sendToMailContentScriptResilient: async () => {
  166. pollCalls += 1;
  167. return {};
  168. },
  169. setState: async () => {},
  170. setStepStatus: async () => {},
  171. sleepWithStop: async () => {},
  172. throwIfStopped: () => {},
  173. VERIFICATION_POLL_MAX_ROUNDS: 5,
  174. });
  175. return {
  176. resolveVerificationStep: helpers.resolveVerificationStep,
  177. snapshot() {
  178. return { logs, pollCalls };
  179. },
  180. };
  181. `)(verificationFlowSource);
  182. let error = null;
  183. try {
  184. await api.resolveVerificationStep(7, {}, { provider: 'qq' }, { requestFreshCodeFirst: true });
  185. } catch (err) {
  186. error = err;
  187. }
  188. const state = api.snapshot();
  189. assert.strictEqual(error?.message, '流程已被用户停止。', '首次请求新验证码收到 Stop 后应立即终止');
  190. assert.strictEqual(state.pollCalls, 0, 'Stop 后不应继续进入邮箱轮询');
  191. assert.deepStrictEqual(state.logs, [], 'Stop 后不应追加降级日志');
  192. }
  193. (async () => {
  194. await testPollFreshVerificationCodeRethrowsStop();
  195. await testResolveVerificationStepRethrowsStopFromFreshRequest();
  196. console.log('verification stop propagation tests passed');
  197. })().catch((error) => {
  198. console.error(error);
  199. process.exit(1);
  200. });