background.js 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js');
  3. const LOG_PREFIX = '[MultiPage:bg]';
  4. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  5. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  6. const HUMAN_STEP_DELAY_MIN = 700;
  7. const HUMAN_STEP_DELAY_MAX = 2200;
  8. const STEP7_RESTART_MAX_ROUNDS = 8;
  9. const AUTO_RUN_ALARM_NAME = 'scheduled-auto-run';
  10. const AUTO_RUN_DELAY_MIN_MINUTES = 1;
  11. const AUTO_RUN_DELAY_MAX_MINUTES = 1440;
  12. initializeSessionStorageAccess();
  13. // ============================================================
  14. // 状态管理(chrome.storage.session + chrome.storage.local)
  15. // ============================================================
  16. const PERSISTED_SETTING_DEFAULTS = {
  17. vpsUrl: '', // VPS 面板地址,可手动填写。
  18. vpsPassword: '', // VPS 面板登录密码,可手动填写。
  19. customPassword: '', // 自定义账号密码;留空时由程序自动生成随机密码。
  20. autoRunSkipFailures: false, // 自动运行遇到失败步骤后,是否继续执行后续流程。
  21. autoRunDelayEnabled: false, // 自动运行是否启用启动前倒计时。
  22. autoRunDelayMinutes: 30, // 自动运行倒计时分钟数。
  23. mailProvider: '163', // 验证码邮箱来源,当前支持 163 / inbucket。
  24. inbucketHost: '', // 仅当 mailProvider 为 inbucket 时填写 Inbucket 地址,其他情况保持为空。
  25. inbucketMailbox: '', // 仅当 mailProvider 为 inbucket 时填写邮箱名,其他情况保持为空。
  26. };
  27. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  28. const DEFAULT_STATE = {
  29. currentStep: 0, // 当前流程执行到的步骤编号。
  30. stepStatuses: {
  31. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', // 运行时步骤状态映射,不要手动预填。
  32. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  33. },
  34. oauthUrl: null, // 运行时抓取到的 OAuth 地址,不要手动预填。
  35. email: null, // 运行时邮箱,由程序自动获取并写入,不能手动预填。
  36. password: null, // 运行时实际密码,由 customPassword 或程序自动生成后写入。
  37. accounts: [], // 已生成账号记录:{ email, password, createdAt }。
  38. lastEmailTimestamp: null, // 最近一次获取到邮箱数据的运行时时间戳。
  39. lastSignupCode: null, // 注册验证码,运行时由程序自动读取并写入。
  40. lastLoginCode: null, // 登录验证码,运行时由程序自动读取并写入。
  41. localhostUrl: null, // 运行时捕获到的 localhost 回调地址,不要手动预填。
  42. flowStartTime: null, // 当前流程开始时间。
  43. tabRegistry: {}, // 程序维护的标签页注册表。
  44. sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。
  45. logs: [], // 侧边栏展示的运行日志。
  46. ...PERSISTED_SETTING_DEFAULTS, // 合并 chrome.storage.local 中持久化保存的用户配置。
  47. autoRunning: false, // 当前是否处于自动运行中。
  48. autoRunPhase: 'idle', // 当前自动运行阶段。
  49. autoRunCurrentRun: 0, // 自动运行当前执行到第几轮。
  50. autoRunTotalRuns: 1, // 自动运行计划总轮数。
  51. autoRunAttemptRun: 0, // 当前轮次的重试序号。
  52. scheduledAutoRunAt: null, // 自动运行计划启动时间戳。
  53. scheduledAutoRunPlan: null, // 自动运行计划参数快照。
  54. };
  55. function normalizeAutoRunDelayMinutes(value) {
  56. const numeric = Number(value);
  57. if (!Number.isFinite(numeric)) {
  58. return PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes;
  59. }
  60. return Math.min(
  61. AUTO_RUN_DELAY_MAX_MINUTES,
  62. Math.max(AUTO_RUN_DELAY_MIN_MINUTES, Math.floor(numeric))
  63. );
  64. }
  65. function normalizeRunCount(value) {
  66. const numeric = Number(value);
  67. if (!Number.isFinite(numeric)) {
  68. return 1;
  69. }
  70. return Math.min(50, Math.max(1, Math.floor(numeric)));
  71. }
  72. function normalizeScheduledAutoRunPlan(plan) {
  73. if (!plan || typeof plan !== 'object') {
  74. return null;
  75. }
  76. return {
  77. totalRuns: normalizeRunCount(plan.totalRuns),
  78. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  79. mode: plan.mode === 'continue' ? 'continue' : 'restart',
  80. };
  81. }
  82. async function getPersistedSettings() {
  83. const stored = await chrome.storage.local.get(PERSISTED_SETTING_KEYS);
  84. return {
  85. ...PERSISTED_SETTING_DEFAULTS,
  86. ...stored,
  87. autoRunSkipFailures: Boolean(stored.autoRunSkipFailures ?? PERSISTED_SETTING_DEFAULTS.autoRunSkipFailures),
  88. autoRunDelayEnabled: Boolean(stored.autoRunDelayEnabled ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayEnabled),
  89. autoRunDelayMinutes: normalizeAutoRunDelayMinutes(stored.autoRunDelayMinutes ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes),
  90. };
  91. }
  92. async function getState() {
  93. const [state, persistedSettings] = await Promise.all([
  94. chrome.storage.session.get(null),
  95. getPersistedSettings(),
  96. ]);
  97. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  98. }
  99. async function initializeSessionStorageAccess() {
  100. try {
  101. if (chrome.storage?.session?.setAccessLevel) {
  102. await chrome.storage.session.setAccessLevel({
  103. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  104. });
  105. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  106. }
  107. } catch (err) {
  108. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  109. }
  110. }
  111. async function setState(updates) {
  112. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  113. await chrome.storage.session.set(updates);
  114. }
  115. async function setPersistentSettings(updates) {
  116. const persistedUpdates = {};
  117. for (const key of PERSISTED_SETTING_KEYS) {
  118. if (updates[key] !== undefined) {
  119. if (key === 'autoRunSkipFailures' || key === 'autoRunDelayEnabled') {
  120. persistedUpdates[key] = Boolean(updates[key]);
  121. } else if (key === 'autoRunDelayMinutes') {
  122. persistedUpdates[key] = normalizeAutoRunDelayMinutes(updates[key]);
  123. } else {
  124. persistedUpdates[key] = updates[key];
  125. }
  126. }
  127. }
  128. if (Object.keys(persistedUpdates).length > 0) {
  129. await chrome.storage.local.set(persistedUpdates);
  130. }
  131. }
  132. function broadcastDataUpdate(payload) {
  133. chrome.runtime.sendMessage({
  134. type: 'DATA_UPDATED',
  135. payload,
  136. }).catch(() => { });
  137. }
  138. async function setEmailState(email) {
  139. await setState({ email });
  140. broadcastDataUpdate({ email });
  141. if (email) {
  142. await resumeAutoRunIfWaitingForEmail();
  143. }
  144. }
  145. async function setPasswordState(password) {
  146. await setState({ password });
  147. broadcastDataUpdate({ password });
  148. }
  149. async function resetState() {
  150. console.log(LOG_PREFIX, 'Resetting all state');
  151. // Preserve settings and persistent data across resets
  152. const [prev, persistedSettings] = await Promise.all([
  153. chrome.storage.session.get([
  154. 'seenCodes',
  155. 'seenInbucketMailIds',
  156. 'accounts',
  157. 'tabRegistry',
  158. 'sourceLastUrls',
  159. ]),
  160. getPersistedSettings(),
  161. ]);
  162. await chrome.storage.session.clear();
  163. await chrome.storage.session.set({
  164. ...DEFAULT_STATE,
  165. ...persistedSettings,
  166. seenCodes: prev.seenCodes || [],
  167. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  168. accounts: prev.accounts || [],
  169. tabRegistry: prev.tabRegistry || {},
  170. sourceLastUrls: prev.sourceLastUrls || {},
  171. });
  172. }
  173. /**
  174. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  175. */
  176. function generatePassword() {
  177. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  178. const lower = 'abcdefghjkmnpqrstuvwxyz';
  179. const digits = '23456789';
  180. const symbols = '!@#$%&*?';
  181. const all = upper + lower + digits + symbols;
  182. // Ensure at least one of each type
  183. let pw = '';
  184. pw += upper[Math.floor(Math.random() * upper.length)];
  185. pw += lower[Math.floor(Math.random() * lower.length)];
  186. pw += digits[Math.floor(Math.random() * digits.length)];
  187. pw += symbols[Math.floor(Math.random() * symbols.length)];
  188. // Fill remaining 10 chars
  189. for (let i = 0; i < 10; i++) {
  190. pw += all[Math.floor(Math.random() * all.length)];
  191. }
  192. // Shuffle
  193. return pw.split('').sort(() => Math.random() - 0.5).join('');
  194. }
  195. // ============================================================
  196. // Tab Registry
  197. // ============================================================
  198. async function getTabRegistry() {
  199. const state = await getState();
  200. return state.tabRegistry || {};
  201. }
  202. async function registerTab(source, tabId) {
  203. const registry = await getTabRegistry();
  204. registry[source] = { tabId, ready: true };
  205. await setState({ tabRegistry: registry });
  206. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  207. }
  208. async function isTabAlive(source) {
  209. const registry = await getTabRegistry();
  210. const entry = registry[source];
  211. if (!entry) return false;
  212. try {
  213. await chrome.tabs.get(entry.tabId);
  214. return true;
  215. } catch {
  216. // Tab no longer exists — clean up registry
  217. registry[source] = null;
  218. await setState({ tabRegistry: registry });
  219. return false;
  220. }
  221. }
  222. async function getTabId(source) {
  223. const registry = await getTabRegistry();
  224. return registry[source]?.tabId || null;
  225. }
  226. function parseUrlSafely(rawUrl) {
  227. if (!rawUrl) return null;
  228. try {
  229. return new URL(rawUrl);
  230. } catch {
  231. return null;
  232. }
  233. }
  234. function isSignupPageHost(hostname = '') {
  235. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  236. }
  237. function is163MailHost(hostname = '') {
  238. return hostname === 'mail.163.com'
  239. || hostname.endsWith('.mail.163.com')
  240. || hostname === 'webmail.vip.163.com';
  241. }
  242. function isLocalhostOAuthCallbackUrl(rawUrl) {
  243. const parsed = parseUrlSafely(rawUrl);
  244. if (!parsed) return false;
  245. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  246. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  247. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  248. const code = (parsed.searchParams.get('code') || '').trim();
  249. const state = (parsed.searchParams.get('state') || '').trim();
  250. return Boolean(code && state);
  251. }
  252. function isLocalCpaUrl(rawUrl) {
  253. const parsed = parseUrlSafely(rawUrl);
  254. if (!parsed) return false;
  255. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  256. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  257. }
  258. function shouldBypassStep9ForLocalCpa(state) {
  259. return Boolean(state?.localhostUrl) && isLocalCpaUrl(state?.vpsUrl);
  260. }
  261. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  262. const candidate = parseUrlSafely(candidateUrl);
  263. if (!candidate) return false;
  264. const reference = parseUrlSafely(referenceUrl);
  265. switch (source) {
  266. case 'signup-page':
  267. return isSignupPageHost(candidate.hostname);
  268. case 'duck-mail':
  269. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  270. case 'qq-mail':
  271. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  272. case 'mail-163':
  273. return is163MailHost(candidate.hostname);
  274. case 'inbucket-mail':
  275. return Boolean(reference)
  276. && candidate.origin === reference.origin
  277. && candidate.pathname.startsWith('/m/');
  278. case 'vps-panel':
  279. return Boolean(reference)
  280. && candidate.origin === reference.origin
  281. && candidate.pathname === reference.pathname;
  282. default:
  283. return false;
  284. }
  285. }
  286. async function rememberSourceLastUrl(source, url) {
  287. if (!source || !url) return;
  288. const state = await getState();
  289. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  290. sourceLastUrls[source] = url;
  291. await setState({ sourceLastUrls });
  292. }
  293. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  294. const { excludeTabIds = [] } = options;
  295. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  296. const state = await getState();
  297. const lastUrl = state.sourceLastUrls?.[source];
  298. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  299. if (!referenceUrls.length) return;
  300. const tabs = await chrome.tabs.query({});
  301. const matchedIds = tabs
  302. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  303. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  304. .map(tab => tab.id);
  305. if (!matchedIds.length) return;
  306. await chrome.tabs.remove(matchedIds).catch(() => { });
  307. const registry = await getTabRegistry();
  308. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  309. registry[source] = null;
  310. await setState({ tabRegistry: registry });
  311. }
  312. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  313. }
  314. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  315. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  316. return false;
  317. }
  318. const callback = parseUrlSafely(callbackUrl);
  319. const candidate = parseUrlSafely(candidateUrl);
  320. if (!callback || !candidate) return false;
  321. return callback.origin === candidate.origin
  322. && callback.pathname === candidate.pathname
  323. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  324. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  325. }
  326. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  327. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  328. const { excludeTabIds = [] } = options;
  329. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  330. const tabs = await chrome.tabs.query({});
  331. const matchedIds = tabs
  332. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  333. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  334. .map((tab) => tab.id);
  335. if (!matchedIds.length) return 0;
  336. await chrome.tabs.remove(matchedIds).catch(() => { });
  337. const registry = await getTabRegistry();
  338. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  339. registry['signup-page'] = null;
  340. await setState({ tabRegistry: registry });
  341. }
  342. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  343. return matchedIds.length;
  344. }
  345. async function pingContentScriptOnTab(tabId) {
  346. if (!Number.isInteger(tabId)) return null;
  347. try {
  348. return await chrome.tabs.sendMessage(tabId, {
  349. type: 'PING',
  350. source: 'background',
  351. payload: {},
  352. });
  353. } catch {
  354. return null;
  355. }
  356. }
  357. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  358. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  359. const start = Date.now();
  360. while (Date.now() - start < timeoutMs) {
  361. try {
  362. const tab = await chrome.tabs.get(tabId);
  363. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  364. return tab;
  365. }
  366. } catch {
  367. return null;
  368. }
  369. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  370. }
  371. return null;
  372. }
  373. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  374. const {
  375. inject = null,
  376. injectSource = null,
  377. timeoutMs = 30000,
  378. retryDelayMs = 700,
  379. logMessage = '',
  380. } = options;
  381. const start = Date.now();
  382. let lastError = null;
  383. let logged = false;
  384. let attempt = 0;
  385. console.log(
  386. LOG_PREFIX,
  387. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  388. );
  389. while (Date.now() - start < timeoutMs) {
  390. attempt += 1;
  391. const pong = await pingContentScriptOnTab(tabId);
  392. if (pong?.ok && (!pong.source || pong.source === source)) {
  393. console.log(
  394. LOG_PREFIX,
  395. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  396. );
  397. await registerTab(source, tabId);
  398. return;
  399. }
  400. if (!inject || !inject.length) {
  401. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  402. }
  403. const registry = await getTabRegistry();
  404. if (registry[source]) {
  405. registry[source].ready = false;
  406. await setState({ tabRegistry: registry });
  407. }
  408. try {
  409. if (injectSource) {
  410. await chrome.scripting.executeScript({
  411. target: { tabId },
  412. func: (injectedSource) => {
  413. window.__MULTIPAGE_SOURCE = injectedSource;
  414. },
  415. args: [injectSource],
  416. });
  417. }
  418. await chrome.scripting.executeScript({
  419. target: { tabId },
  420. files: inject,
  421. });
  422. } catch (err) {
  423. lastError = err;
  424. console.warn(
  425. LOG_PREFIX,
  426. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  427. );
  428. }
  429. const pongAfterInject = await pingContentScriptOnTab(tabId);
  430. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  431. console.log(
  432. LOG_PREFIX,
  433. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  434. );
  435. await registerTab(source, tabId);
  436. return;
  437. }
  438. if (logMessage && !logged) {
  439. console.warn(
  440. LOG_PREFIX,
  441. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  442. );
  443. await addLog(logMessage, 'warn');
  444. logged = true;
  445. }
  446. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  447. }
  448. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  449. }
  450. // ============================================================
  451. // Command Queue (for content scripts not yet ready)
  452. // ============================================================
  453. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  454. function getContentScriptResponseTimeoutMs(message) {
  455. if (!message || typeof message !== 'object') {
  456. return 30000;
  457. }
  458. if (message.type === 'POLL_EMAIL') {
  459. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  460. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  461. return Math.max(45000, maxAttempts * intervalMs + 25000);
  462. }
  463. if (message.type === 'FILL_CODE') {
  464. return Number(message.step) === 7 ? 45000 : 30000;
  465. }
  466. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  467. return 45000;
  468. }
  469. return 30000;
  470. }
  471. function getMessageDebugLabel(source, message, tabId = null) {
  472. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  473. if (Number.isInteger(message?.step)) {
  474. parts.push(`step=${message.step}`);
  475. }
  476. if (Number.isInteger(tabId)) {
  477. parts.push(`tab=${tabId}`);
  478. }
  479. return parts.join(' ');
  480. }
  481. function summarizeMessageResultForDebug(result) {
  482. if (result === undefined) return 'undefined';
  483. if (result === null) return 'null';
  484. if (typeof result !== 'object') return JSON.stringify(result);
  485. const summary = {};
  486. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  487. if (key in result) summary[key] = result[key];
  488. }
  489. if (result.payload && typeof result.payload === 'object') {
  490. summary.payloadKeys = Object.keys(result.payload);
  491. }
  492. return JSON.stringify(summary);
  493. }
  494. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  495. return new Promise((resolve, reject) => {
  496. let settled = false;
  497. const startedAt = Date.now();
  498. const debugLabel = getMessageDebugLabel(source, message, tabId);
  499. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  500. const timer = setTimeout(() => {
  501. if (settled) return;
  502. settled = true;
  503. const seconds = Math.ceil(responseTimeoutMs / 1000);
  504. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  505. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  506. }, responseTimeoutMs);
  507. chrome.tabs.sendMessage(tabId, message)
  508. .then((value) => {
  509. const elapsed = Date.now() - startedAt;
  510. if (settled) {
  511. console.warn(
  512. LOG_PREFIX,
  513. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  514. );
  515. return;
  516. }
  517. settled = true;
  518. clearTimeout(timer);
  519. console.log(
  520. LOG_PREFIX,
  521. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  522. );
  523. resolve(value);
  524. })
  525. .catch((error) => {
  526. const elapsed = Date.now() - startedAt;
  527. const errorMessage = error?.message || String(error);
  528. if (settled) {
  529. console.warn(
  530. LOG_PREFIX,
  531. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  532. );
  533. return;
  534. }
  535. settled = true;
  536. clearTimeout(timer);
  537. console.warn(
  538. LOG_PREFIX,
  539. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  540. );
  541. reject(error);
  542. });
  543. });
  544. }
  545. function queueCommand(source, message, timeout = 15000) {
  546. return new Promise((resolve, reject) => {
  547. const timer = setTimeout(() => {
  548. pendingCommands.delete(source);
  549. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  550. console.error(LOG_PREFIX, err);
  551. reject(new Error(err));
  552. }, timeout);
  553. pendingCommands.set(source, { message, resolve, reject, timer });
  554. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  555. });
  556. }
  557. function flushCommand(source, tabId) {
  558. const pending = pendingCommands.get(source);
  559. if (pending) {
  560. clearTimeout(pending.timer);
  561. pendingCommands.delete(source);
  562. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  563. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  564. }
  565. }
  566. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  567. for (const [source, pending] of pendingCommands.entries()) {
  568. clearTimeout(pending.timer);
  569. pending.reject(new Error(reason));
  570. pendingCommands.delete(source);
  571. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  572. }
  573. }
  574. // ============================================================
  575. // Reuse or create tab
  576. // ============================================================
  577. async function reuseOrCreateTab(source, url, options = {}) {
  578. const alive = await isTabAlive(source);
  579. if (alive) {
  580. const tabId = await getTabId(source);
  581. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  582. const currentTab = await chrome.tabs.get(tabId);
  583. const sameUrl = currentTab.url === url;
  584. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  585. const registry = await getTabRegistry();
  586. if (sameUrl) {
  587. await chrome.tabs.update(tabId, { active: true });
  588. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  589. if (shouldReloadOnReuse) {
  590. if (registry[source]) registry[source].ready = false;
  591. await setState({ tabRegistry: registry });
  592. await chrome.tabs.reload(tabId);
  593. await new Promise((resolve) => {
  594. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  595. const listener = (tid, info) => {
  596. if (tid === tabId && info.status === 'complete') {
  597. chrome.tabs.onUpdated.removeListener(listener);
  598. clearTimeout(timer);
  599. resolve();
  600. }
  601. };
  602. chrome.tabs.onUpdated.addListener(listener);
  603. });
  604. }
  605. // For dynamically injected pages like the VPS panel, re-inject immediately.
  606. if (options.inject) {
  607. if (registry[source]) registry[source].ready = false;
  608. await setState({ tabRegistry: registry });
  609. if (options.injectSource) {
  610. await chrome.scripting.executeScript({
  611. target: { tabId },
  612. func: (injectedSource) => {
  613. window.__MULTIPAGE_SOURCE = injectedSource;
  614. },
  615. args: [options.injectSource],
  616. });
  617. }
  618. await chrome.scripting.executeScript({
  619. target: { tabId },
  620. files: options.inject,
  621. });
  622. await new Promise(r => setTimeout(r, 500));
  623. }
  624. await rememberSourceLastUrl(source, url);
  625. return tabId;
  626. }
  627. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  628. if (registry[source]) registry[source].ready = false;
  629. await setState({ tabRegistry: registry });
  630. // Navigate existing tab to new URL
  631. await chrome.tabs.update(tabId, { url, active: true });
  632. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  633. // Wait for page load complete (with 30s timeout)
  634. await new Promise((resolve) => {
  635. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  636. const listener = (tid, info) => {
  637. if (tid === tabId && info.status === 'complete') {
  638. chrome.tabs.onUpdated.removeListener(listener);
  639. clearTimeout(timer);
  640. resolve();
  641. }
  642. };
  643. chrome.tabs.onUpdated.addListener(listener);
  644. });
  645. // If dynamic injection needed (VPS panel), re-inject after navigation
  646. if (options.inject) {
  647. if (options.injectSource) {
  648. await chrome.scripting.executeScript({
  649. target: { tabId },
  650. func: (injectedSource) => {
  651. window.__MULTIPAGE_SOURCE = injectedSource;
  652. },
  653. args: [options.injectSource],
  654. });
  655. }
  656. await chrome.scripting.executeScript({
  657. target: { tabId },
  658. files: options.inject,
  659. });
  660. }
  661. // Wait a bit for content script to inject and send READY
  662. await new Promise(r => setTimeout(r, 500));
  663. await rememberSourceLastUrl(source, url);
  664. return tabId;
  665. }
  666. // Create new tab
  667. await closeConflictingTabsForSource(source, url);
  668. const tab = await chrome.tabs.create({ url, active: true });
  669. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  670. // If dynamic injection needed (VPS panel), inject scripts after load
  671. if (options.inject) {
  672. await new Promise((resolve) => {
  673. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  674. const listener = (tabId, info) => {
  675. if (tabId === tab.id && info.status === 'complete') {
  676. chrome.tabs.onUpdated.removeListener(listener);
  677. clearTimeout(timer);
  678. resolve();
  679. }
  680. };
  681. chrome.tabs.onUpdated.addListener(listener);
  682. });
  683. if (options.injectSource) {
  684. await chrome.scripting.executeScript({
  685. target: { tabId: tab.id },
  686. func: (injectedSource) => {
  687. window.__MULTIPAGE_SOURCE = injectedSource;
  688. },
  689. args: [options.injectSource],
  690. });
  691. }
  692. await chrome.scripting.executeScript({
  693. target: { tabId: tab.id },
  694. files: options.inject,
  695. });
  696. }
  697. await rememberSourceLastUrl(source, url);
  698. return tab.id;
  699. }
  700. // ============================================================
  701. // Send command to content script (with readiness check)
  702. // ============================================================
  703. async function sendToContentScript(source, message, options = {}) {
  704. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  705. const registry = await getTabRegistry();
  706. const entry = registry[source];
  707. if (!entry || !entry.ready) {
  708. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  709. return queueCommand(source, message);
  710. }
  711. // Verify tab is still alive
  712. const alive = await isTabAlive(source);
  713. if (!alive) {
  714. // Tab was closed — queue the command, it will be sent when tab is reopened
  715. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  716. return queueCommand(source, message);
  717. }
  718. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  719. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  720. }
  721. async function sendToContentScriptResilient(source, message, options = {}) {
  722. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  723. const start = Date.now();
  724. let lastError = null;
  725. let logged = false;
  726. let attempt = 0;
  727. const debugLabel = getMessageDebugLabel(source, message);
  728. console.log(
  729. LOG_PREFIX,
  730. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  731. );
  732. while (Date.now() - start < timeoutMs) {
  733. throwIfStopped();
  734. attempt += 1;
  735. try {
  736. console.log(
  737. LOG_PREFIX,
  738. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  739. );
  740. const result = await sendToContentScript(source, message);
  741. console.log(
  742. LOG_PREFIX,
  743. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  744. );
  745. return result;
  746. } catch (err) {
  747. const retryable = isRetryableContentScriptTransportError(err);
  748. console.warn(
  749. LOG_PREFIX,
  750. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  751. );
  752. if (!retryable) {
  753. throw err;
  754. }
  755. lastError = err;
  756. if (logMessage && !logged) {
  757. await addLog(logMessage, 'warn');
  758. logged = true;
  759. }
  760. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  761. }
  762. }
  763. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  764. }
  765. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  766. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  767. const start = Date.now();
  768. let lastError = null;
  769. let recoveries = 0;
  770. let logged = false;
  771. while (Date.now() - start < timeoutMs) {
  772. throwIfStopped();
  773. try {
  774. return await sendToContentScript(mail.source, message);
  775. } catch (err) {
  776. if (!isRetryableContentScriptTransportError(err)) {
  777. throw err;
  778. }
  779. lastError = err;
  780. if (!logged) {
  781. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  782. logged = true;
  783. }
  784. if (recoveries >= maxRecoveryAttempts) {
  785. break;
  786. }
  787. recoveries += 1;
  788. await reuseOrCreateTab(mail.source, mail.url, {
  789. inject: mail.inject,
  790. injectSource: mail.injectSource,
  791. reloadIfSameUrl: true,
  792. });
  793. await new Promise((resolve) => setTimeout(resolve, 800));
  794. }
  795. }
  796. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  797. }
  798. // ============================================================
  799. // Logging
  800. // ============================================================
  801. async function addLog(message, level = 'info') {
  802. const state = await getState();
  803. const logs = state.logs || [];
  804. const entry = { message, level, timestamp: Date.now() };
  805. logs.push(entry);
  806. // Keep last 500 logs
  807. if (logs.length > 500) logs.splice(0, logs.length - 500);
  808. await setState({ logs });
  809. // Broadcast to side panel
  810. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  811. }
  812. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  813. if (!Number.isInteger(signupTabId) || !details) return '';
  814. if (details.tabId !== signupTabId) return '';
  815. if (details.frameId !== 0) return '';
  816. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  817. }
  818. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  819. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  820. const candidates = [changeInfo?.url, tab?.url];
  821. for (const candidate of candidates) {
  822. if (isLocalhostOAuthCallbackUrl(candidate)) {
  823. return candidate;
  824. }
  825. }
  826. return '';
  827. }
  828. function getSourceLabel(source) {
  829. const labels = {
  830. 'sidepanel': '侧边栏',
  831. 'signup-page': '认证页',
  832. 'vps-panel': 'CPA 面板',
  833. 'qq-mail': 'QQ 邮箱',
  834. 'mail-163': '163 邮箱',
  835. 'inbucket-mail': 'Inbucket 邮箱',
  836. 'duck-mail': 'Duck 邮箱',
  837. };
  838. return labels[source] || source || '未知来源';
  839. }
  840. // ============================================================
  841. // Step Status Management
  842. // ============================================================
  843. async function setStepStatus(step, status) {
  844. const state = await getState();
  845. const statuses = { ...state.stepStatuses };
  846. statuses[step] = status;
  847. await setState({ stepStatuses: statuses, currentStep: step });
  848. // Broadcast to side panel
  849. chrome.runtime.sendMessage({
  850. type: 'STEP_STATUS_CHANGED',
  851. payload: { step, status },
  852. }).catch(() => { });
  853. }
  854. function isStopError(error) {
  855. const message = typeof error === 'string' ? error : error?.message;
  856. return message === STOP_ERROR_MESSAGE;
  857. }
  858. function isRetryableContentScriptTransportError(error) {
  859. const message = String(typeof error === 'string' ? error : error?.message || '');
  860. return /back\/forward cache|message channel is closed|Receiving end does not exist|port closed before a response was received|A listener indicated an asynchronous response|did not respond in \d+s/i.test(message);
  861. }
  862. function getErrorMessage(error) {
  863. return String(typeof error === 'string' ? error : error?.message || '');
  864. }
  865. function isVerificationMailPollingError(error) {
  866. const message = getErrorMessage(error);
  867. return /未在 .*邮箱中找到新的匹配邮件|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  868. }
  869. function isRestartCurrentAttemptError(error) {
  870. const message = String(typeof error === 'string' ? error : error?.message || '');
  871. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  872. }
  873. function isStep9OAuthTimeoutError(error) {
  874. const message = String(typeof error === 'string' ? error : error?.message || '');
  875. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  876. }
  877. function isStepDoneStatus(status) {
  878. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  879. }
  880. function getFirstUnfinishedStep(statuses = {}) {
  881. for (let step = 1; step <= 9; step++) {
  882. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  883. return step;
  884. }
  885. }
  886. return null;
  887. }
  888. function hasSavedProgress(statuses = {}) {
  889. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  890. }
  891. function getDownstreamStateResets(step) {
  892. if (step <= 1) {
  893. return {
  894. oauthUrl: null,
  895. flowStartTime: null,
  896. password: null,
  897. lastEmailTimestamp: null,
  898. lastSignupCode: null,
  899. lastLoginCode: null,
  900. localhostUrl: null,
  901. };
  902. }
  903. if (step === 2) {
  904. return {
  905. password: null,
  906. lastEmailTimestamp: null,
  907. lastSignupCode: null,
  908. lastLoginCode: null,
  909. localhostUrl: null,
  910. };
  911. }
  912. if (step === 3 || step === 4) {
  913. return {
  914. lastEmailTimestamp: null,
  915. lastSignupCode: null,
  916. lastLoginCode: null,
  917. localhostUrl: null,
  918. };
  919. }
  920. if (step === 5 || step === 6 || step === 7) {
  921. return {
  922. lastLoginCode: null,
  923. localhostUrl: null,
  924. };
  925. }
  926. if (step === 8) {
  927. return {
  928. localhostUrl: null,
  929. };
  930. }
  931. return {};
  932. }
  933. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  934. const { logLabel = `步骤 ${step} 重新执行` } = options;
  935. const state = await getState();
  936. const statuses = { ...(state.stepStatuses || {}) };
  937. const changedSteps = [];
  938. for (let downstream = step + 1; downstream <= 9; downstream++) {
  939. if (statuses[downstream] !== 'pending') {
  940. statuses[downstream] = 'pending';
  941. changedSteps.push(downstream);
  942. }
  943. }
  944. if (changedSteps.length) {
  945. await setState({ stepStatuses: statuses });
  946. for (const downstream of changedSteps) {
  947. chrome.runtime.sendMessage({
  948. type: 'STEP_STATUS_CHANGED',
  949. payload: { step: downstream, status: 'pending' },
  950. }).catch(() => { });
  951. }
  952. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  953. }
  954. const resets = getDownstreamStateResets(step);
  955. if (Object.keys(resets).length) {
  956. await setState(resets);
  957. broadcastDataUpdate(resets);
  958. }
  959. }
  960. function clearStopRequest() {
  961. stopRequested = false;
  962. }
  963. function getAutoRunStatusPayload(phase, payload = {}) {
  964. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  965. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  966. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  967. const rawScheduledAt = phase === 'scheduled'
  968. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  969. : null;
  970. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  971. const autoRunning = phase === 'scheduled' || phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  972. return {
  973. autoRunning,
  974. autoRunPhase: phase,
  975. autoRunCurrentRun: currentRun,
  976. autoRunTotalRuns: totalRuns,
  977. autoRunAttemptRun: attemptRun,
  978. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  979. };
  980. }
  981. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  982. const rawScheduledAt = phase === 'scheduled'
  983. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  984. : null;
  985. const statusPayload = {
  986. phase,
  987. currentRun: payload.currentRun ?? autoRunCurrentRun,
  988. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  989. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  990. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  991. };
  992. await setState({
  993. ...extraState,
  994. ...getAutoRunStatusPayload(phase, statusPayload),
  995. });
  996. chrome.runtime.sendMessage({
  997. type: 'AUTO_RUN_STATUS',
  998. payload: statusPayload,
  999. }).catch(() => { });
  1000. }
  1001. function isAutoRunLockedState(state) {
  1002. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  1003. }
  1004. function isAutoRunPausedState(state) {
  1005. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  1006. }
  1007. function isAutoRunScheduledState(state) {
  1008. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1009. return Boolean(state.autoRunning)
  1010. && state.autoRunPhase === 'scheduled'
  1011. && Number.isFinite(scheduledAt)
  1012. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  1013. }
  1014. function formatAutoRunScheduleTime(timestamp) {
  1015. return new Date(timestamp).toLocaleString('zh-CN', {
  1016. hour12: false,
  1017. month: '2-digit',
  1018. day: '2-digit',
  1019. hour: '2-digit',
  1020. minute: '2-digit',
  1021. second: '2-digit',
  1022. });
  1023. }
  1024. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  1025. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  1026. return false;
  1027. }
  1028. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  1029. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  1030. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1031. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  1032. }
  1033. return true;
  1034. }
  1035. async function clearScheduledAutoRunAlarm() {
  1036. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1037. }
  1038. async function scheduleAutoRun(totalRuns, options = {}) {
  1039. const state = await getState();
  1040. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  1041. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  1042. }
  1043. if (isAutoRunScheduledState(state)) {
  1044. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1045. }
  1046. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  1047. const plan = normalizeScheduledAutoRunPlan({
  1048. totalRuns,
  1049. autoRunSkipFailures: options.autoRunSkipFailures,
  1050. mode: options.mode,
  1051. });
  1052. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  1053. autoRunCurrentRun = 0;
  1054. autoRunTotalRuns = plan.totalRuns;
  1055. autoRunAttemptRun = 0;
  1056. await ensureScheduledAutoRunAlarm(scheduledAt);
  1057. await broadcastAutoRunStatus(
  1058. 'scheduled',
  1059. {
  1060. currentRun: 0,
  1061. totalRuns: plan.totalRuns,
  1062. attemptRun: 0,
  1063. scheduledAt,
  1064. },
  1065. {
  1066. autoRunSkipFailures: plan.autoRunSkipFailures,
  1067. scheduledAutoRunPlan: plan,
  1068. }
  1069. );
  1070. await addLog(
  1071. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  1072. 'info'
  1073. );
  1074. return { ok: true, scheduledAt };
  1075. }
  1076. let scheduledAutoRunLaunching = false;
  1077. async function launchScheduledAutoRun(trigger = 'alarm') {
  1078. if (scheduledAutoRunLaunching) {
  1079. return false;
  1080. }
  1081. scheduledAutoRunLaunching = true;
  1082. try {
  1083. const state = await getState();
  1084. if (!isAutoRunScheduledState(state)) {
  1085. return false;
  1086. }
  1087. if (autoRunActive) {
  1088. return false;
  1089. }
  1090. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1091. if (!plan) {
  1092. await clearScheduledAutoRunAlarm();
  1093. await broadcastAutoRunStatus('idle', {
  1094. currentRun: 0,
  1095. totalRuns: 1,
  1096. attemptRun: 0,
  1097. }, {
  1098. scheduledAutoRunPlan: null,
  1099. });
  1100. return false;
  1101. }
  1102. await clearScheduledAutoRunAlarm();
  1103. await broadcastAutoRunStatus(
  1104. 'running',
  1105. {
  1106. currentRun: 0,
  1107. totalRuns: plan.totalRuns,
  1108. attemptRun: 0,
  1109. },
  1110. {
  1111. autoRunSkipFailures: plan.autoRunSkipFailures,
  1112. scheduledAutoRunPlan: null,
  1113. }
  1114. );
  1115. clearStopRequest();
  1116. await addLog(
  1117. trigger === 'manual'
  1118. ? '已手动跳过倒计时,自动运行立即开始。'
  1119. : '倒计时结束,自动运行开始执行。',
  1120. 'info'
  1121. );
  1122. autoRunLoop(plan.totalRuns, {
  1123. autoRunSkipFailures: plan.autoRunSkipFailures,
  1124. mode: plan.mode,
  1125. });
  1126. return true;
  1127. } finally {
  1128. scheduledAutoRunLaunching = false;
  1129. }
  1130. }
  1131. async function cancelScheduledAutoRun(options = {}) {
  1132. const state = await getState();
  1133. if (!isAutoRunScheduledState(state)) {
  1134. return false;
  1135. }
  1136. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1137. await clearScheduledAutoRunAlarm();
  1138. autoRunCurrentRun = 0;
  1139. autoRunTotalRuns = plan?.totalRuns || 1;
  1140. autoRunAttemptRun = 0;
  1141. await broadcastAutoRunStatus(
  1142. 'idle',
  1143. {
  1144. currentRun: 0,
  1145. totalRuns: plan?.totalRuns || 1,
  1146. attemptRun: 0,
  1147. },
  1148. {
  1149. scheduledAutoRunPlan: null,
  1150. }
  1151. );
  1152. if (options.logMessage !== false) {
  1153. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  1154. }
  1155. return true;
  1156. }
  1157. async function restoreScheduledAutoRunIfNeeded() {
  1158. const state = await getState();
  1159. if (state.autoRunPhase !== 'scheduled') {
  1160. return;
  1161. }
  1162. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1163. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1164. if (!plan || !Number.isFinite(scheduledAt)) {
  1165. await clearScheduledAutoRunAlarm();
  1166. await broadcastAutoRunStatus('idle', {
  1167. currentRun: 0,
  1168. totalRuns: 1,
  1169. attemptRun: 0,
  1170. }, {
  1171. scheduledAutoRunPlan: null,
  1172. });
  1173. return;
  1174. }
  1175. if (scheduledAt <= Date.now()) {
  1176. await launchScheduledAutoRun('restore');
  1177. return;
  1178. }
  1179. await ensureScheduledAutoRunAlarm(scheduledAt);
  1180. }
  1181. async function ensureManualInteractionAllowed(actionLabel) {
  1182. const state = await getState();
  1183. if (isAutoRunLockedState(state)) {
  1184. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  1185. }
  1186. if (isAutoRunPausedState(state)) {
  1187. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  1188. }
  1189. if (isAutoRunScheduledState(state)) {
  1190. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  1191. }
  1192. return state;
  1193. }
  1194. async function skipStep(step) {
  1195. const state = await ensureManualInteractionAllowed('跳过步骤');
  1196. if (!Number.isInteger(step) || step < 1 || step > 9) {
  1197. throw new Error(`无效步骤:${step}`);
  1198. }
  1199. const statuses = { ...(state.stepStatuses || {}) };
  1200. const currentStatus = statuses[step];
  1201. if (currentStatus === 'running') {
  1202. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  1203. }
  1204. if (isStepDoneStatus(currentStatus)) {
  1205. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  1206. }
  1207. if (step > 1) {
  1208. const prevStatus = statuses[step - 1];
  1209. if (!isStepDoneStatus(prevStatus)) {
  1210. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  1211. }
  1212. }
  1213. await setStepStatus(step, 'skipped');
  1214. await addLog(`步骤 ${step} 已跳过`, 'warn');
  1215. if (step === 1) {
  1216. const latestState = await getState();
  1217. const step2Status = latestState.stepStatuses?.[2];
  1218. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  1219. await setStepStatus(2, 'skipped');
  1220. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  1221. }
  1222. }
  1223. return { ok: true, step, status: 'skipped' };
  1224. }
  1225. function throwIfStopped() {
  1226. if (stopRequested) {
  1227. throw new Error(STOP_ERROR_MESSAGE);
  1228. }
  1229. }
  1230. async function sleepWithStop(ms) {
  1231. const start = Date.now();
  1232. while (Date.now() - start < ms) {
  1233. throwIfStopped();
  1234. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  1235. }
  1236. }
  1237. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  1238. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  1239. await sleepWithStop(duration);
  1240. }
  1241. async function clickWithDebugger(tabId, rect) {
  1242. if (!tabId) {
  1243. throw new Error('未找到用于调试点击的认证页面标签页。');
  1244. }
  1245. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  1246. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  1247. }
  1248. const target = { tabId };
  1249. try {
  1250. await chrome.debugger.attach(target, '1.3');
  1251. } catch (err) {
  1252. throw new Error(
  1253. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  1254. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  1255. );
  1256. }
  1257. try {
  1258. const x = Math.round(rect.centerX);
  1259. const y = Math.round(rect.centerY);
  1260. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  1261. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1262. type: 'mouseMoved',
  1263. x,
  1264. y,
  1265. button: 'none',
  1266. buttons: 0,
  1267. clickCount: 0,
  1268. });
  1269. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1270. type: 'mousePressed',
  1271. x,
  1272. y,
  1273. button: 'left',
  1274. buttons: 1,
  1275. clickCount: 1,
  1276. });
  1277. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1278. type: 'mouseReleased',
  1279. x,
  1280. y,
  1281. button: 'left',
  1282. buttons: 0,
  1283. clickCount: 1,
  1284. });
  1285. } finally {
  1286. await chrome.debugger.detach(target).catch(() => { });
  1287. }
  1288. }
  1289. async function broadcastStopToContentScripts() {
  1290. const registry = await getTabRegistry();
  1291. for (const entry of Object.values(registry)) {
  1292. if (!entry?.tabId) continue;
  1293. try {
  1294. await chrome.tabs.sendMessage(entry.tabId, {
  1295. type: 'STOP_FLOW',
  1296. source: 'background',
  1297. payload: {},
  1298. });
  1299. } catch { }
  1300. }
  1301. }
  1302. let stopRequested = false;
  1303. // ============================================================
  1304. // Message Handler (central router)
  1305. // ============================================================
  1306. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  1307. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  1308. handleMessage(message, sender).then(response => {
  1309. sendResponse(response);
  1310. }).catch(err => {
  1311. console.error(LOG_PREFIX, 'Handler error:', err);
  1312. sendResponse({ error: err.message });
  1313. });
  1314. return true; // async response
  1315. });
  1316. async function handleMessage(message, sender) {
  1317. switch (message.type) {
  1318. case 'CONTENT_SCRIPT_READY': {
  1319. const tabId = sender.tab?.id;
  1320. if (tabId && message.source) {
  1321. await registerTab(message.source, tabId);
  1322. flushCommand(message.source, tabId);
  1323. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  1324. }
  1325. return { ok: true };
  1326. }
  1327. case 'LOG': {
  1328. const { message: msg, level } = message.payload;
  1329. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  1330. return { ok: true };
  1331. }
  1332. case 'STEP_COMPLETE': {
  1333. if (stopRequested) {
  1334. await setStepStatus(message.step, 'stopped');
  1335. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  1336. return { ok: true };
  1337. }
  1338. await setStepStatus(message.step, 'completed');
  1339. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  1340. await handleStepData(message.step, message.payload);
  1341. notifyStepComplete(message.step, message.payload);
  1342. return { ok: true };
  1343. }
  1344. case 'STEP_ERROR': {
  1345. if (isStopError(message.error)) {
  1346. await setStepStatus(message.step, 'stopped');
  1347. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  1348. notifyStepError(message.step, message.error);
  1349. } else {
  1350. await setStepStatus(message.step, 'failed');
  1351. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  1352. notifyStepError(message.step, message.error);
  1353. }
  1354. return { ok: true };
  1355. }
  1356. case 'GET_STATE': {
  1357. return await getState();
  1358. }
  1359. case 'RESET': {
  1360. clearStopRequest();
  1361. await clearScheduledAutoRunAlarm();
  1362. await resetState();
  1363. await addLog('流程已重置', 'info');
  1364. return { ok: true };
  1365. }
  1366. case 'EXECUTE_STEP': {
  1367. clearStopRequest();
  1368. if (message.source === 'sidepanel') {
  1369. await ensureManualInteractionAllowed('手动执行步骤');
  1370. }
  1371. const step = message.payload.step;
  1372. if (message.source === 'sidepanel') {
  1373. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  1374. }
  1375. // Save email if provided (from side panel step 3)
  1376. if (message.payload.email) {
  1377. await setEmailState(message.payload.email);
  1378. }
  1379. await executeStep(step);
  1380. return { ok: true };
  1381. }
  1382. case 'AUTO_RUN': {
  1383. clearStopRequest();
  1384. const state = await getState();
  1385. if (isAutoRunScheduledState(state)) {
  1386. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1387. }
  1388. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1389. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  1390. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  1391. await setState({ autoRunSkipFailures });
  1392. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  1393. return { ok: true };
  1394. }
  1395. case 'SCHEDULE_AUTO_RUN': {
  1396. clearStopRequest();
  1397. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1398. return await scheduleAutoRun(totalRuns, {
  1399. delayMinutes: message.payload?.delayMinutes,
  1400. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  1401. mode: message.payload?.mode,
  1402. });
  1403. }
  1404. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  1405. clearStopRequest();
  1406. const started = await launchScheduledAutoRun('manual');
  1407. if (!started) {
  1408. throw new Error('当前没有可立即开始的倒计时计划。');
  1409. }
  1410. return { ok: true };
  1411. }
  1412. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  1413. const cancelled = await cancelScheduledAutoRun();
  1414. if (!cancelled) {
  1415. throw new Error('当前没有可取消的倒计时计划。');
  1416. }
  1417. return { ok: true };
  1418. }
  1419. case 'RESUME_AUTO_RUN': {
  1420. clearStopRequest();
  1421. if (message.payload.email) {
  1422. await setEmailState(message.payload.email);
  1423. }
  1424. resumeAutoRun(); // fire-and-forget
  1425. return { ok: true };
  1426. }
  1427. case 'TAKEOVER_AUTO_RUN': {
  1428. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  1429. await addLog('自动流程已切换为手动控制。', 'warn');
  1430. return { ok: true };
  1431. }
  1432. case 'SKIP_STEP': {
  1433. const step = Number(message.payload?.step);
  1434. return await skipStep(step);
  1435. }
  1436. case 'SAVE_SETTING': {
  1437. const updates = {};
  1438. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  1439. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  1440. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  1441. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  1442. if (message.payload.autoRunDelayEnabled !== undefined) updates.autoRunDelayEnabled = Boolean(message.payload.autoRunDelayEnabled);
  1443. if (message.payload.autoRunDelayMinutes !== undefined) updates.autoRunDelayMinutes = normalizeAutoRunDelayMinutes(message.payload.autoRunDelayMinutes);
  1444. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  1445. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  1446. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  1447. await setPersistentSettings(updates);
  1448. await setState(updates);
  1449. return { ok: true };
  1450. }
  1451. // Side panel data updates
  1452. case 'SAVE_EMAIL': {
  1453. const state = await getState();
  1454. if (isAutoRunLockedState(state)) {
  1455. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  1456. }
  1457. await setEmailState(message.payload.email);
  1458. await resumeAutoRun();
  1459. return { ok: true, email: message.payload.email };
  1460. }
  1461. case 'FETCH_DUCK_EMAIL': {
  1462. clearStopRequest();
  1463. const state = await getState();
  1464. if (isAutoRunLockedState(state)) {
  1465. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  1466. }
  1467. const email = await fetchDuckEmail(message.payload || {});
  1468. await resumeAutoRun();
  1469. return { ok: true, email };
  1470. }
  1471. case 'STOP_FLOW': {
  1472. await requestStop();
  1473. return { ok: true };
  1474. }
  1475. default:
  1476. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  1477. return { error: `Unknown message type: ${message.type}` };
  1478. }
  1479. }
  1480. // ============================================================
  1481. // Step Data Handlers
  1482. // ============================================================
  1483. async function handleStepData(step, payload) {
  1484. switch (step) {
  1485. case 1:
  1486. if (payload.oauthUrl) {
  1487. await setState({ oauthUrl: payload.oauthUrl });
  1488. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  1489. }
  1490. break;
  1491. case 3:
  1492. if (payload.email) await setEmailState(payload.email);
  1493. break;
  1494. case 4:
  1495. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  1496. break;
  1497. case 8:
  1498. if (payload.localhostUrl) {
  1499. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  1500. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  1501. }
  1502. await setState({ localhostUrl: payload.localhostUrl });
  1503. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  1504. }
  1505. break;
  1506. case 9: {
  1507. if (payload.localhostUrl) {
  1508. await closeLocalhostCallbackTabs(payload.localhostUrl);
  1509. }
  1510. break;
  1511. }
  1512. }
  1513. }
  1514. // ============================================================
  1515. // Step Completion Waiting
  1516. // ============================================================
  1517. // Map of step -> { resolve, reject } for waiting on step completion
  1518. const stepWaiters = new Map();
  1519. let resumeWaiter = null;
  1520. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  1521. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  1522. function waitForStepComplete(step, timeoutMs = 120000) {
  1523. return new Promise((resolve, reject) => {
  1524. throwIfStopped();
  1525. if (stepWaiters.has(step)) {
  1526. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  1527. }
  1528. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  1529. const timer = setTimeout(() => {
  1530. stepWaiters.delete(step);
  1531. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  1532. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  1533. }, timeoutMs);
  1534. stepWaiters.set(step, {
  1535. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  1536. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  1537. });
  1538. });
  1539. }
  1540. function notifyStepComplete(step, payload) {
  1541. const waiter = stepWaiters.get(step);
  1542. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  1543. if (waiter) waiter.resolve(payload);
  1544. }
  1545. function notifyStepError(step, error) {
  1546. const waiter = stepWaiters.get(step);
  1547. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  1548. if (waiter) waiter.reject(new Error(error));
  1549. }
  1550. async function completeStepFromBackground(step, payload = {}) {
  1551. if (stopRequested) {
  1552. await setStepStatus(step, 'stopped');
  1553. notifyStepError(step, STOP_ERROR_MESSAGE);
  1554. return;
  1555. }
  1556. await setStepStatus(step, 'completed');
  1557. await addLog(`步骤 ${step} 已完成`, 'ok');
  1558. await handleStepData(step, payload);
  1559. notifyStepComplete(step, payload);
  1560. }
  1561. async function markRunningStepsStopped() {
  1562. const state = await getState();
  1563. const runningSteps = Object.entries(state.stepStatuses || {})
  1564. .filter(([, status]) => status === 'running')
  1565. .map(([step]) => Number(step));
  1566. for (const step of runningSteps) {
  1567. await setStepStatus(step, 'stopped');
  1568. }
  1569. }
  1570. async function requestStop(options = {}) {
  1571. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  1572. const state = await getState();
  1573. if (isAutoRunScheduledState(state) && !autoRunActive) {
  1574. await cancelScheduledAutoRun({
  1575. logMessage: options.logMessage === false
  1576. ? false
  1577. : (options.logMessage || '已取消自动运行倒计时计划。'),
  1578. });
  1579. return;
  1580. }
  1581. if (stopRequested) return;
  1582. stopRequested = true;
  1583. cancelPendingCommands();
  1584. cleanupStep8NavigationListeners();
  1585. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  1586. await addLog(logMessage, 'warn');
  1587. await broadcastStopToContentScripts();
  1588. for (const waiter of stepWaiters.values()) {
  1589. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  1590. }
  1591. stepWaiters.clear();
  1592. if (resumeWaiter) {
  1593. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  1594. resumeWaiter = null;
  1595. }
  1596. await markRunningStepsStopped();
  1597. autoRunActive = false;
  1598. await broadcastAutoRunStatus('stopped', {
  1599. currentRun: autoRunCurrentRun,
  1600. totalRuns: autoRunTotalRuns,
  1601. attemptRun: autoRunAttemptRun,
  1602. });
  1603. }
  1604. // ============================================================
  1605. // Step Execution
  1606. // ============================================================
  1607. async function executeStep(step) {
  1608. console.log(LOG_PREFIX, `Executing step ${step}`);
  1609. throwIfStopped();
  1610. await setStepStatus(step, 'running');
  1611. await addLog(`步骤 ${step} 开始执行`);
  1612. await humanStepDelay();
  1613. const state = await getState();
  1614. // Set flow start time on first step
  1615. if (step === 1 && !state.flowStartTime) {
  1616. await setState({ flowStartTime: Date.now() });
  1617. }
  1618. try {
  1619. switch (step) {
  1620. case 1: await executeStep1(state); break;
  1621. case 2: await executeStep2(state); break;
  1622. case 3: await executeStep3(state); break;
  1623. case 4: await executeStep4(state); break;
  1624. case 5: await executeStep5(state); break;
  1625. case 6: await executeStep6(state); break;
  1626. case 7: await executeStep7(state); break;
  1627. case 8: await executeStep8(state); break;
  1628. case 9: await executeStep9(state); break;
  1629. default:
  1630. throw new Error(`未知步骤:${step}`);
  1631. }
  1632. } catch (err) {
  1633. if (isStopError(err)) {
  1634. await setStepStatus(step, 'stopped');
  1635. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  1636. throw err;
  1637. }
  1638. await setStepStatus(step, 'failed');
  1639. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  1640. throw err;
  1641. }
  1642. }
  1643. /**
  1644. * Execute a step and wait for it to complete before returning.
  1645. * @param {number} step
  1646. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  1647. */
  1648. async function executeStepAndWait(step, delayAfter = 2000) {
  1649. throwIfStopped();
  1650. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  1651. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  1652. await executeStep(step);
  1653. const latestState = await getState();
  1654. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  1655. } else {
  1656. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  1657. const completionResultPromise = waitForStepComplete(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS).then(
  1658. payload => ({ ok: true, payload }),
  1659. error => ({ ok: false, error }),
  1660. );
  1661. try {
  1662. await executeStep(step);
  1663. } catch (err) {
  1664. notifyStepError(step, getErrorMessage(err));
  1665. await completionResultPromise;
  1666. throw err;
  1667. }
  1668. const completionResult = await completionResultPromise;
  1669. if (!completionResult.ok) {
  1670. throw completionResult.error;
  1671. }
  1672. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  1673. }
  1674. // Extra delay for page transitions / DOM updates
  1675. if (delayAfter > 0) {
  1676. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  1677. }
  1678. }
  1679. async function fetchDuckEmail(options = {}) {
  1680. throwIfStopped();
  1681. const { generateNew = true } = options;
  1682. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  1683. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  1684. const result = await sendToContentScript('duck-mail', {
  1685. type: 'FETCH_DUCK_EMAIL',
  1686. source: 'background',
  1687. payload: { generateNew },
  1688. });
  1689. if (result?.error) {
  1690. throw new Error(result.error);
  1691. }
  1692. if (!result?.email) {
  1693. throw new Error('未返回 Duck 邮箱地址。');
  1694. }
  1695. await setEmailState(result.email);
  1696. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  1697. return result.email;
  1698. }
  1699. // ============================================================
  1700. // Auto Run Flow
  1701. // ============================================================
  1702. let autoRunActive = false;
  1703. let autoRunCurrentRun = 0;
  1704. let autoRunTotalRuns = 1;
  1705. let autoRunAttemptRun = 0;
  1706. const DUCK_EMAIL_MAX_ATTEMPTS = 5;
  1707. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  1708. const AUTO_STEP_DELAYS = {
  1709. 1: 2000,
  1710. 2: 2000,
  1711. 3: 3000,
  1712. 4: 2000,
  1713. 5: 3000,
  1714. 6: 3000,
  1715. 7: 2000,
  1716. 8: 2000,
  1717. 9: 1000,
  1718. };
  1719. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  1720. const { silent = false } = options;
  1721. const state = await getState();
  1722. if (!state.email || !isAutoRunPausedState(state)) {
  1723. return false;
  1724. }
  1725. if (resumeWaiter) {
  1726. if (!silent) {
  1727. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1728. }
  1729. resumeWaiter.resolve();
  1730. resumeWaiter = null;
  1731. return true;
  1732. }
  1733. return false;
  1734. }
  1735. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  1736. const currentState = await getState();
  1737. if (currentState.email) {
  1738. return currentState.email;
  1739. }
  1740. let lastDuckError = null;
  1741. for (let duckAttempt = 1; duckAttempt <= DUCK_EMAIL_MAX_ATTEMPTS; duckAttempt++) {
  1742. try {
  1743. if (duckAttempt > 1) {
  1744. await addLog(`Duck 邮箱:正在进行第 ${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  1745. }
  1746. const duckEmail = await fetchDuckEmail({ generateNew: true });
  1747. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试,Duck 第 ${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS} 次获取)===`, 'ok');
  1748. return duckEmail;
  1749. } catch (err) {
  1750. lastDuckError = err;
  1751. await addLog(`Duck 邮箱自动获取失败(${duckAttempt}/${DUCK_EMAIL_MAX_ATTEMPTS}):${err.message}`, 'warn');
  1752. }
  1753. }
  1754. await addLog(`Duck 邮箱自动获取已连续失败 ${DUCK_EMAIL_MAX_ATTEMPTS} 次:${lastDuckError?.message || '未知错误'}`, 'error');
  1755. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1756. await broadcastAutoRunStatus('waiting_email', {
  1757. currentRun: targetRun,
  1758. totalRuns,
  1759. attemptRun: attemptRuns,
  1760. });
  1761. await waitForResume();
  1762. const resumedState = await getState();
  1763. if (!resumedState.email) {
  1764. throw new Error('无法继续:当前没有邮箱地址。');
  1765. }
  1766. return resumedState.email;
  1767. }
  1768. async function runAutoSequenceFromStep(startStep, context = {}) {
  1769. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  1770. const maxStep9RestartAttempts = 5;
  1771. let step9RestartAttempts = 0;
  1772. if (continued) {
  1773. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  1774. } else {
  1775. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  1776. }
  1777. if (startStep <= 2) {
  1778. for (const step of [1, 2]) {
  1779. if (step < startStep) continue;
  1780. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1781. }
  1782. }
  1783. if (startStep <= 3) {
  1784. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  1785. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1786. await broadcastAutoRunStatus('running', {
  1787. currentRun: targetRun,
  1788. totalRuns,
  1789. attemptRun: attemptRuns,
  1790. });
  1791. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  1792. } else {
  1793. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  1794. }
  1795. const signupTabId = await getTabId('signup-page');
  1796. if (signupTabId) {
  1797. await chrome.tabs.update(signupTabId, { active: true });
  1798. }
  1799. let step = Math.max(startStep, 4);
  1800. while (step <= 9) {
  1801. try {
  1802. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1803. step += 1;
  1804. } catch (err) {
  1805. if (step === 9 && isStep9OAuthTimeoutError(err) && step9RestartAttempts < maxStep9RestartAttempts) {
  1806. step9RestartAttempts += 1;
  1807. await addLog(
  1808. `步骤 9:检测到 OAuth callback 超时,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  1809. 'warn'
  1810. );
  1811. await invalidateDownstreamAfterStepRestart(6, {
  1812. logLabel: `步骤 9 超时后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  1813. });
  1814. step = 6;
  1815. continue;
  1816. }
  1817. throw err;
  1818. }
  1819. }
  1820. }
  1821. // Outer loop: keep retrying until the target number of successful runs is reached.
  1822. async function autoRunLoop(totalRuns, options = {}) {
  1823. if (autoRunActive) {
  1824. await addLog('自动运行已在进行中', 'warn');
  1825. return;
  1826. }
  1827. clearStopRequest();
  1828. autoRunActive = true;
  1829. autoRunTotalRuns = totalRuns;
  1830. autoRunCurrentRun = 0;
  1831. autoRunAttemptRun = 0;
  1832. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  1833. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  1834. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  1835. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  1836. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  1837. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  1838. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  1839. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  1840. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  1841. let forceFreshTabsNextRun = false;
  1842. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  1843. await setState({
  1844. autoRunSkipFailures,
  1845. ...getAutoRunStatusPayload('running', {
  1846. currentRun: resumeCurrentRun,
  1847. totalRuns,
  1848. attemptRun: resumeAttemptRunsProcessed,
  1849. }),
  1850. });
  1851. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  1852. attemptRuns += 1;
  1853. const targetRun = successfulRuns + 1;
  1854. autoRunCurrentRun = targetRun;
  1855. autoRunAttemptRun = attemptRuns;
  1856. let startStep = 1;
  1857. let useExistingProgress = false;
  1858. if (continueCurrentOnFirstAttempt) {
  1859. const currentState = await getState();
  1860. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  1861. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  1862. startStep = resumeStep;
  1863. useExistingProgress = true;
  1864. } else if (hasSavedProgress(currentState.stepStatuses)) {
  1865. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  1866. }
  1867. continueCurrentOnFirstAttempt = false;
  1868. }
  1869. if (!useExistingProgress) {
  1870. // Reset everything at the start of each fresh attempt (keep user settings).
  1871. const prevState = await getState();
  1872. const keepSettings = {
  1873. vpsUrl: prevState.vpsUrl,
  1874. vpsPassword: prevState.vpsPassword,
  1875. customPassword: prevState.customPassword,
  1876. autoRunSkipFailures: prevState.autoRunSkipFailures,
  1877. mailProvider: prevState.mailProvider,
  1878. inbucketHost: prevState.inbucketHost,
  1879. inbucketMailbox: prevState.inbucketMailbox,
  1880. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1881. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  1882. };
  1883. await resetState();
  1884. await setState(keepSettings);
  1885. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  1886. await sleepWithStop(500);
  1887. } else {
  1888. await setState({
  1889. autoRunSkipFailures,
  1890. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1891. });
  1892. }
  1893. if (forceFreshTabsNextRun) {
  1894. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  1895. forceFreshTabsNextRun = false;
  1896. }
  1897. try {
  1898. throwIfStopped();
  1899. await broadcastAutoRunStatus('running', {
  1900. currentRun: targetRun,
  1901. totalRuns,
  1902. attemptRun: attemptRuns,
  1903. });
  1904. await runAutoSequenceFromStep(startStep, {
  1905. targetRun,
  1906. totalRuns,
  1907. attemptRuns,
  1908. continued: useExistingProgress,
  1909. });
  1910. successfulRuns += 1;
  1911. autoRunCurrentRun = successfulRuns;
  1912. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1913. continue;
  1914. } catch (err) {
  1915. if (isStopError(err)) {
  1916. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1917. await broadcastAutoRunStatus('stopped', {
  1918. currentRun: targetRun,
  1919. totalRuns,
  1920. attemptRun: attemptRuns,
  1921. });
  1922. break;
  1923. }
  1924. if (isRestartCurrentAttemptError(err)) {
  1925. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  1926. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  1927. await broadcastStopToContentScripts();
  1928. await broadcastAutoRunStatus('retrying', {
  1929. currentRun: targetRun,
  1930. totalRuns,
  1931. attemptRun: attemptRuns,
  1932. });
  1933. forceFreshTabsNextRun = true;
  1934. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  1935. continue;
  1936. }
  1937. if (!autoRunSkipFailures) {
  1938. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1939. await broadcastAutoRunStatus('stopped', {
  1940. currentRun: targetRun,
  1941. totalRuns,
  1942. attemptRun: attemptRuns,
  1943. });
  1944. break;
  1945. }
  1946. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1947. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1948. cancelPendingCommands('当前尝试已放弃。');
  1949. await broadcastStopToContentScripts();
  1950. await broadcastAutoRunStatus('retrying', {
  1951. currentRun: targetRun,
  1952. totalRuns,
  1953. attemptRun: attemptRuns,
  1954. });
  1955. forceFreshTabsNextRun = true;
  1956. }
  1957. }
  1958. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1959. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1960. await broadcastAutoRunStatus('stopped', {
  1961. currentRun: successfulRuns,
  1962. totalRuns: autoRunTotalRuns,
  1963. attemptRun: attemptRuns,
  1964. });
  1965. } else if (stopRequested) {
  1966. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1967. await broadcastAutoRunStatus('stopped', {
  1968. currentRun: successfulRuns,
  1969. totalRuns: autoRunTotalRuns,
  1970. attemptRun: attemptRuns,
  1971. });
  1972. } else if (successfulRuns >= autoRunTotalRuns) {
  1973. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  1974. await broadcastAutoRunStatus('complete', {
  1975. currentRun: successfulRuns,
  1976. totalRuns: autoRunTotalRuns,
  1977. attemptRun: attemptRuns,
  1978. });
  1979. } else {
  1980. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1981. await broadcastAutoRunStatus('stopped', {
  1982. currentRun: successfulRuns,
  1983. totalRuns: autoRunTotalRuns,
  1984. attemptRun: attemptRuns,
  1985. });
  1986. }
  1987. autoRunActive = false;
  1988. autoRunAttemptRun = attemptRuns;
  1989. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  1990. currentRun: successfulRuns,
  1991. totalRuns: autoRunTotalRuns,
  1992. attemptRun: attemptRuns,
  1993. }));
  1994. clearStopRequest();
  1995. }
  1996. async function waitForResume() {
  1997. throwIfStopped();
  1998. const state = await getState();
  1999. if (state.email) {
  2000. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2001. return;
  2002. }
  2003. return new Promise((resolve, reject) => {
  2004. resumeWaiter = { resolve, reject };
  2005. });
  2006. }
  2007. async function resumeAutoRun() {
  2008. throwIfStopped();
  2009. const state = await getState();
  2010. if (!state.email) {
  2011. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  2012. return false;
  2013. }
  2014. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  2015. if (resumedInMemory) {
  2016. return true;
  2017. }
  2018. if (!isAutoRunPausedState(state)) {
  2019. return false;
  2020. }
  2021. if (autoRunActive) {
  2022. return false;
  2023. }
  2024. const totalRuns = state.autoRunTotalRuns || 1;
  2025. const currentRun = state.autoRunCurrentRun || 1;
  2026. const attemptRun = state.autoRunAttemptRun || 1;
  2027. const successfulRuns = Math.max(0, currentRun - 1);
  2028. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  2029. autoRunLoop(totalRuns, {
  2030. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  2031. mode: 'continue',
  2032. resumeCurrentRun: currentRun,
  2033. resumeSuccessfulRuns: successfulRuns,
  2034. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  2035. });
  2036. return true;
  2037. }
  2038. // ============================================================
  2039. // Step 1: Get OAuth Link (via vps-panel.js)
  2040. // ============================================================
  2041. async function executeStep1(state) {
  2042. if (!state.vpsUrl) {
  2043. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2044. }
  2045. await addLog('步骤 1:正在打开 CPA 面板...');
  2046. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  2047. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  2048. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  2049. const tabId = tab.id;
  2050. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2051. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  2052. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  2053. timeoutMs: 15000,
  2054. retryDelayMs: 400,
  2055. });
  2056. if (!matchedTab) {
  2057. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  2058. }
  2059. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2060. inject: injectFiles,
  2061. timeoutMs: 45000,
  2062. retryDelayMs: 900,
  2063. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  2064. });
  2065. const result = await sendToContentScriptResilient('vps-panel', {
  2066. type: 'EXECUTE_STEP',
  2067. step: 1,
  2068. source: 'background',
  2069. payload: { vpsPassword: state.vpsPassword },
  2070. }, {
  2071. timeoutMs: 30000,
  2072. retryDelayMs: 700,
  2073. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  2074. });
  2075. if (result?.error) {
  2076. throw new Error(result.error);
  2077. }
  2078. }
  2079. // ============================================================
  2080. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  2081. // ============================================================
  2082. async function executeStep2(state) {
  2083. if (!state.oauthUrl) {
  2084. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2085. }
  2086. await addLog('步骤 2:正在打开认证链接...');
  2087. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2088. await sendToContentScript('signup-page', {
  2089. type: 'EXECUTE_STEP',
  2090. step: 2,
  2091. source: 'background',
  2092. payload: {},
  2093. });
  2094. }
  2095. // ============================================================
  2096. // Step 3: Fill Email & Password (via signup-page.js)
  2097. // ============================================================
  2098. async function executeStep3(state) {
  2099. if (!state.email) {
  2100. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  2101. }
  2102. const password = state.customPassword || generatePassword();
  2103. await setPasswordState(password);
  2104. // Save account record
  2105. const accounts = state.accounts || [];
  2106. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  2107. await setState({ accounts });
  2108. await addLog(
  2109. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  2110. );
  2111. await sendToContentScript('signup-page', {
  2112. type: 'EXECUTE_STEP',
  2113. step: 3,
  2114. source: 'background',
  2115. payload: { email: state.email, password },
  2116. });
  2117. }
  2118. // ============================================================
  2119. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  2120. // ============================================================
  2121. function getMailConfig(state) {
  2122. const provider = state.mailProvider || 'qq';
  2123. if (provider === '163') {
  2124. return { source: 'mail-163', url: 'https://mail.163.com/js6/main.jsp?df=mail163_letter#module=mbox.ListModule%7C%7B%22fid%22%3A1%2C%22order%22%3A%22date%22%2C%22desc%22%3Atrue%7D', label: '163 邮箱' };
  2125. }
  2126. if (provider === '163-vip') {
  2127. return { source: 'mail-163', url: 'https://webmail.vip.163.com/js6/main.jsp?df=mail163_letter#module=mbox.ListModule%7C%7B%22fid%22%3A1%2C%22order%22%3A%22date%22%2C%22desc%22%3Atrue%7D', label: '163 VIP 邮箱' };
  2128. }
  2129. if (provider === 'inbucket') {
  2130. const host = normalizeInbucketOrigin(state.inbucketHost);
  2131. const mailbox = (state.inbucketMailbox || '').trim();
  2132. if (!host) {
  2133. return { error: 'Inbucket 主机地址为空或无效。' };
  2134. }
  2135. if (!mailbox) {
  2136. return { error: 'Inbucket 邮箱名称为空。' };
  2137. }
  2138. return {
  2139. source: 'inbucket-mail',
  2140. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  2141. label: `Inbucket 邮箱(${mailbox})`,
  2142. navigateOnReuse: true,
  2143. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  2144. injectSource: 'inbucket-mail',
  2145. };
  2146. }
  2147. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  2148. }
  2149. function normalizeInbucketOrigin(rawValue) {
  2150. const value = (rawValue || '').trim();
  2151. if (!value) return '';
  2152. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  2153. try {
  2154. const parsed = new URL(candidate);
  2155. return parsed.origin;
  2156. } catch {
  2157. return '';
  2158. }
  2159. }
  2160. function getVerificationCodeStateKey(step) {
  2161. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  2162. }
  2163. function getVerificationCodeLabel(step) {
  2164. return step === 4 ? '注册' : '登录';
  2165. }
  2166. function getVerificationPollPayload(step, state, overrides = {}) {
  2167. if (step === 4) {
  2168. return {
  2169. filterAfterTimestamp: state.flowStartTime || 0,
  2170. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  2171. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  2172. targetEmail: state.email,
  2173. maxAttempts: 5,
  2174. intervalMs: 3000,
  2175. ...overrides,
  2176. };
  2177. }
  2178. return {
  2179. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  2180. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  2181. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  2182. targetEmail: state.email,
  2183. maxAttempts: 5,
  2184. intervalMs: 3000,
  2185. ...overrides,
  2186. };
  2187. }
  2188. async function requestVerificationCodeResend(step) {
  2189. const signupTabId = await getTabId('signup-page');
  2190. if (!signupTabId) {
  2191. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  2192. }
  2193. await chrome.tabs.update(signupTabId, { active: true });
  2194. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  2195. const result = await sendToContentScript('signup-page', {
  2196. type: 'RESEND_VERIFICATION_CODE',
  2197. step,
  2198. source: 'background',
  2199. payload: {},
  2200. });
  2201. if (result && result.error) {
  2202. throw new Error(result.error);
  2203. }
  2204. return Date.now();
  2205. }
  2206. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  2207. const stateKey = getVerificationCodeStateKey(step);
  2208. const rejectedCodes = new Set();
  2209. if (state[stateKey]) {
  2210. rejectedCodes.add(state[stateKey]);
  2211. }
  2212. for (const code of (pollOverrides.excludeCodes || [])) {
  2213. if (code) rejectedCodes.add(code);
  2214. }
  2215. let lastError = null;
  2216. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  2217. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  2218. for (let round = 1; round <= maxRounds; round++) {
  2219. if (round > 1) {
  2220. await requestVerificationCodeResend(step);
  2221. }
  2222. const payload = getVerificationPollPayload(step, state, {
  2223. ...pollOverrides,
  2224. filterAfterTimestamp,
  2225. excludeCodes: [...rejectedCodes],
  2226. });
  2227. try {
  2228. const result = await sendToMailContentScriptResilient(
  2229. mail,
  2230. {
  2231. type: 'POLL_EMAIL',
  2232. step,
  2233. source: 'background',
  2234. payload,
  2235. },
  2236. {
  2237. timeoutMs: 45000,
  2238. maxRecoveryAttempts: 2,
  2239. }
  2240. );
  2241. if (result && result.error) {
  2242. throw new Error(result.error);
  2243. }
  2244. if (!result || !result.code) {
  2245. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  2246. }
  2247. if (rejectedCodes.has(result.code)) {
  2248. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2249. }
  2250. return result;
  2251. } catch (err) {
  2252. lastError = err;
  2253. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  2254. if (round < maxRounds) {
  2255. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  2256. }
  2257. }
  2258. }
  2259. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  2260. }
  2261. async function submitVerificationCode(step, code) {
  2262. const signupTabId = await getTabId('signup-page');
  2263. if (!signupTabId) {
  2264. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  2265. }
  2266. await chrome.tabs.update(signupTabId, { active: true });
  2267. const result = await sendToContentScript('signup-page', {
  2268. type: 'FILL_CODE',
  2269. step,
  2270. source: 'background',
  2271. payload: { code },
  2272. });
  2273. if (result && result.error) {
  2274. throw new Error(result.error);
  2275. }
  2276. return result || {};
  2277. }
  2278. async function resolveVerificationStep(step, state, mail, options = {}) {
  2279. const stateKey = getVerificationCodeStateKey(step);
  2280. const rejectedCodes = new Set();
  2281. if (state[stateKey]) {
  2282. rejectedCodes.add(state[stateKey]);
  2283. }
  2284. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  2285. const requestFreshCodeFirst = Boolean(options.requestFreshCodeFirst);
  2286. const maxSubmitAttempts = 3;
  2287. if (requestFreshCodeFirst) {
  2288. try {
  2289. await requestVerificationCodeResend(step);
  2290. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  2291. } catch (err) {
  2292. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  2293. }
  2294. }
  2295. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  2296. const result = await pollFreshVerificationCode(step, state, mail, {
  2297. excludeCodes: [...rejectedCodes],
  2298. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  2299. });
  2300. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2301. const submitResult = await submitVerificationCode(step, result.code);
  2302. if (submitResult.invalidCode) {
  2303. rejectedCodes.add(result.code);
  2304. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  2305. if (attempt >= maxSubmitAttempts) {
  2306. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  2307. }
  2308. await requestVerificationCodeResend(step);
  2309. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  2310. continue;
  2311. }
  2312. await setState({
  2313. lastEmailTimestamp: result.emailTimestamp,
  2314. [stateKey]: result.code,
  2315. });
  2316. await completeStepFromBackground(step, {
  2317. emailTimestamp: result.emailTimestamp,
  2318. code: result.code,
  2319. });
  2320. return;
  2321. }
  2322. }
  2323. async function executeStep4(state) {
  2324. const mail = getMailConfig(state);
  2325. if (mail.error) throw new Error(mail.error);
  2326. const stepStartedAt = Date.now();
  2327. const signupTabId = await getTabId('signup-page');
  2328. if (!signupTabId) {
  2329. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  2330. }
  2331. await chrome.tabs.update(signupTabId, { active: true });
  2332. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  2333. const prepareResult = await sendToContentScriptResilient(
  2334. 'signup-page',
  2335. {
  2336. type: 'PREPARE_SIGNUP_VERIFICATION',
  2337. step: 4,
  2338. source: 'background',
  2339. payload: { password: state.password || state.customPassword || '' },
  2340. },
  2341. {
  2342. timeoutMs: 30000,
  2343. retryDelayMs: 700,
  2344. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  2345. }
  2346. );
  2347. if (prepareResult && prepareResult.error) {
  2348. throw new Error(prepareResult.error);
  2349. }
  2350. if (prepareResult?.alreadyVerified) {
  2351. await completeStepFromBackground(4, {});
  2352. return;
  2353. }
  2354. await addLog(`步骤 4:正在打开${mail.label}...`);
  2355. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  2356. const alive = await isTabAlive(mail.source);
  2357. if (alive) {
  2358. if (mail.navigateOnReuse) {
  2359. await reuseOrCreateTab(mail.source, mail.url, {
  2360. inject: mail.inject,
  2361. injectSource: mail.injectSource,
  2362. });
  2363. } else {
  2364. const tabId = await getTabId(mail.source);
  2365. await chrome.tabs.update(tabId, { active: true });
  2366. }
  2367. } else {
  2368. await reuseOrCreateTab(mail.source, mail.url, {
  2369. inject: mail.inject,
  2370. injectSource: mail.injectSource,
  2371. });
  2372. }
  2373. await resolveVerificationStep(4, state, mail, {
  2374. filterAfterTimestamp: stepStartedAt,
  2375. requestFreshCodeFirst: true,
  2376. });
  2377. return;
  2378. }
  2379. // ============================================================
  2380. // Step 5: Fill Name & Birthday (via signup-page.js)
  2381. // ============================================================
  2382. async function executeStep5(state) {
  2383. const { firstName, lastName } = generateRandomName();
  2384. const { year, month, day } = generateRandomBirthday();
  2385. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  2386. await sendToContentScript('signup-page', {
  2387. type: 'EXECUTE_STEP',
  2388. step: 5,
  2389. source: 'background',
  2390. payload: { firstName, lastName, year, month, day },
  2391. });
  2392. }
  2393. // ============================================================
  2394. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  2395. // ============================================================
  2396. async function refreshOAuthUrlBeforeStep6(state) {
  2397. if (!state.vpsUrl) {
  2398. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2399. }
  2400. await addLog('步骤 6:正在刷新登录用的 CPA OAuth 链接...');
  2401. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  2402. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  2403. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  2404. await executeStep1(state);
  2405. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  2406. await waitForFreshOAuth;
  2407. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  2408. const latestState = await getState();
  2409. if (!latestState.oauthUrl) {
  2410. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  2411. }
  2412. return latestState.oauthUrl;
  2413. }
  2414. async function executeStep6(state) {
  2415. if (!state.email) {
  2416. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  2417. }
  2418. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  2419. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  2420. // Reuse the signup-page tab — navigate it to the OAuth URL
  2421. await reuseOrCreateTab('signup-page', oauthUrl);
  2422. // signup-page.js will inject (same auth.openai.com domain) and handle login
  2423. await sendToContentScript('signup-page', {
  2424. type: 'EXECUTE_STEP',
  2425. step: 6,
  2426. source: 'background',
  2427. payload: { email: state.email, password: state.password },
  2428. });
  2429. }
  2430. // ============================================================
  2431. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  2432. // ============================================================
  2433. async function runStep7Attempt(state) {
  2434. const mail = getMailConfig(state);
  2435. if (mail.error) throw new Error(mail.error);
  2436. const stepStartedAt = Date.now();
  2437. const authTabId = await getTabId('signup-page');
  2438. if (authTabId) {
  2439. await chrome.tabs.update(authTabId, { active: true });
  2440. } else {
  2441. if (!state.oauthUrl) {
  2442. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2443. }
  2444. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2445. }
  2446. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  2447. const prepareResult = await sendToContentScript('signup-page', {
  2448. type: 'PREPARE_LOGIN_CODE',
  2449. step: 7,
  2450. source: 'background',
  2451. payload: {},
  2452. });
  2453. if (prepareResult && prepareResult.error) {
  2454. throw new Error(prepareResult.error);
  2455. }
  2456. await addLog(`步骤 7:正在打开${mail.label}...`);
  2457. const alive = await isTabAlive(mail.source);
  2458. if (alive) {
  2459. if (mail.navigateOnReuse) {
  2460. await reuseOrCreateTab(mail.source, mail.url, {
  2461. inject: mail.inject,
  2462. injectSource: mail.injectSource,
  2463. });
  2464. } else {
  2465. const tabId = await getTabId(mail.source);
  2466. await chrome.tabs.update(tabId, { active: true });
  2467. }
  2468. } else {
  2469. await reuseOrCreateTab(mail.source, mail.url, {
  2470. inject: mail.inject,
  2471. injectSource: mail.injectSource,
  2472. });
  2473. }
  2474. await resolveVerificationStep(7, state, mail, {
  2475. filterAfterTimestamp: stepStartedAt,
  2476. requestFreshCodeFirst: true,
  2477. });
  2478. }
  2479. async function rerunStep6ForStep7Recovery() {
  2480. const currentState = await getState();
  2481. const waitForStep6 = waitForStepComplete(6, 120000);
  2482. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  2483. await executeStep6(currentState);
  2484. await waitForStep6;
  2485. await sleepWithStop(3000);
  2486. }
  2487. async function executeStep7(state) {
  2488. let lastError = null;
  2489. for (let round = 1; round <= STEP7_RESTART_MAX_ROUNDS; round++) {
  2490. const currentState = round === 1 ? state : await getState();
  2491. try {
  2492. if (round > 1) {
  2493. await addLog(`步骤 7:正在进行第 ${round}/${STEP7_RESTART_MAX_ROUNDS} 轮登录验证码恢复尝试。`, 'warn');
  2494. }
  2495. await runStep7Attempt(currentState);
  2496. return;
  2497. } catch (err) {
  2498. lastError = err;
  2499. if (!isVerificationMailPollingError(err)) {
  2500. throw err;
  2501. }
  2502. if (round >= STEP7_RESTART_MAX_ROUNDS) {
  2503. break;
  2504. }
  2505. await addLog(`步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`, 'warn');
  2506. await rerunStep6ForStep7Recovery();
  2507. }
  2508. }
  2509. throw lastError || new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮后仍未成功。`);
  2510. }
  2511. // ============================================================
  2512. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  2513. // ============================================================
  2514. let webNavListener = null;
  2515. let webNavCommittedListener = null;
  2516. let step8TabUpdatedListener = null;
  2517. let step8PendingReject = null;
  2518. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 10000;
  2519. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  2520. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  2521. const STEP8_MAX_ROUNDS = 5;
  2522. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  2523. const STEP8_STRATEGIES = [
  2524. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  2525. { mode: 'debugger', label: 'debugger click' },
  2526. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  2527. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  2528. { mode: 'debugger', label: 'debugger click retry' },
  2529. ];
  2530. function cleanupStep8NavigationListeners() {
  2531. if (webNavListener) {
  2532. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  2533. webNavListener = null;
  2534. }
  2535. if (webNavCommittedListener) {
  2536. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  2537. webNavCommittedListener = null;
  2538. }
  2539. if (step8TabUpdatedListener) {
  2540. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  2541. step8TabUpdatedListener = null;
  2542. }
  2543. }
  2544. function rejectPendingStep8(error) {
  2545. if (!step8PendingReject) return;
  2546. const reject = step8PendingReject;
  2547. step8PendingReject = null;
  2548. reject(error);
  2549. }
  2550. function throwIfStep8SettledOrStopped(isSettled = false) {
  2551. if (isSettled || stopRequested) {
  2552. throw new Error(STOP_ERROR_MESSAGE);
  2553. }
  2554. }
  2555. async function ensureStep8SignupPageReady(tabId, options = {}) {
  2556. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  2557. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  2558. injectSource: 'signup-page',
  2559. timeoutMs: options.timeoutMs ?? 15000,
  2560. retryDelayMs: options.retryDelayMs ?? 600,
  2561. logMessage: options.logMessage || '',
  2562. });
  2563. }
  2564. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  2565. try {
  2566. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  2567. type: 'STEP8_GET_STATE',
  2568. source: 'background',
  2569. payload: {},
  2570. }, responseTimeoutMs);
  2571. if (result?.error) {
  2572. throw new Error(result.error);
  2573. }
  2574. return result;
  2575. } catch (err) {
  2576. if (isRetryableContentScriptTransportError(err)) {
  2577. return null;
  2578. }
  2579. throw err;
  2580. }
  2581. }
  2582. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  2583. const start = Date.now();
  2584. let recovered = false;
  2585. while (Date.now() - start < timeoutMs) {
  2586. throwIfStopped();
  2587. const pageState = await getStep8PageState(tabId);
  2588. if (pageState?.addPhonePage) {
  2589. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  2590. }
  2591. if (pageState?.consentReady) {
  2592. return pageState;
  2593. }
  2594. if (pageState === null && !recovered) {
  2595. recovered = true;
  2596. await ensureStep8SignupPageReady(tabId, {
  2597. timeoutMs: Math.min(10000, timeoutMs),
  2598. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  2599. });
  2600. continue;
  2601. }
  2602. recovered = false;
  2603. await sleepWithStop(250);
  2604. }
  2605. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  2606. }
  2607. async function prepareStep8DebuggerClick(tabId) {
  2608. await ensureStep8SignupPageReady(tabId, {
  2609. timeoutMs: 15000,
  2610. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  2611. });
  2612. const result = await sendToContentScriptResilient('signup-page', {
  2613. type: 'STEP8_FIND_AND_CLICK',
  2614. source: 'background',
  2615. payload: {},
  2616. }, {
  2617. timeoutMs: 15000,
  2618. retryDelayMs: 600,
  2619. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  2620. });
  2621. if (result?.error) {
  2622. throw new Error(result.error);
  2623. }
  2624. return result;
  2625. }
  2626. async function triggerStep8ContentStrategy(tabId, strategy) {
  2627. await ensureStep8SignupPageReady(tabId, {
  2628. timeoutMs: 15000,
  2629. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  2630. });
  2631. const result = await sendToContentScriptResilient('signup-page', {
  2632. type: 'STEP8_TRIGGER_CONTINUE',
  2633. source: 'background',
  2634. payload: {
  2635. strategy,
  2636. findTimeoutMs: 4000,
  2637. enabledTimeoutMs: 3000,
  2638. },
  2639. }, {
  2640. timeoutMs: 15000,
  2641. retryDelayMs: 600,
  2642. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  2643. });
  2644. if (result?.error) {
  2645. throw new Error(result.error);
  2646. }
  2647. return result;
  2648. }
  2649. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  2650. if (!Number.isInteger(tabId)) {
  2651. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  2652. }
  2653. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  2654. await new Promise((resolve, reject) => {
  2655. let settled = false;
  2656. const timer = setTimeout(() => {
  2657. if (settled) return;
  2658. settled = true;
  2659. chrome.tabs.onUpdated.removeListener(listener);
  2660. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  2661. }, timeoutMs);
  2662. const listener = (updatedTabId, changeInfo) => {
  2663. if (updatedTabId !== tabId) return;
  2664. if (changeInfo.status !== 'complete') return;
  2665. if (settled) return;
  2666. settled = true;
  2667. clearTimeout(timer);
  2668. chrome.tabs.onUpdated.removeListener(listener);
  2669. resolve();
  2670. };
  2671. chrome.tabs.onUpdated.addListener(listener);
  2672. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  2673. if (settled) return;
  2674. settled = true;
  2675. clearTimeout(timer);
  2676. chrome.tabs.onUpdated.removeListener(listener);
  2677. reject(err);
  2678. });
  2679. });
  2680. await ensureStep8SignupPageReady(tabId, {
  2681. timeoutMs: Math.min(15000, timeoutMs),
  2682. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  2683. });
  2684. }
  2685. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  2686. const start = Date.now();
  2687. let recovered = false;
  2688. while (Date.now() - start < timeoutMs) {
  2689. throwIfStopped();
  2690. const tab = await chrome.tabs.get(tabId).catch(() => null);
  2691. if (!tab) {
  2692. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  2693. }
  2694. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  2695. return { progressed: true, reason: 'url_changed', url: tab.url };
  2696. }
  2697. const pageState = await getStep8PageState(tabId);
  2698. if (pageState?.addPhonePage) {
  2699. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  2700. }
  2701. if (pageState === null) {
  2702. if (!recovered) {
  2703. recovered = true;
  2704. await ensureStep8SignupPageReady(tabId, {
  2705. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  2706. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  2707. }).catch(() => null);
  2708. continue;
  2709. }
  2710. await sleepWithStop(200);
  2711. continue;
  2712. }
  2713. recovered = false;
  2714. await sleepWithStop(200);
  2715. }
  2716. return { progressed: false, reason: 'no_effect' };
  2717. }
  2718. function getStep8EffectLabel(effect) {
  2719. switch (effect?.reason) {
  2720. case 'url_changed':
  2721. return `URL 已变化:${effect.url}`;
  2722. case 'page_reloading':
  2723. return '页面正在跳转或重载';
  2724. case 'left_consent_page':
  2725. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  2726. default:
  2727. return '页面仍停留在 OAuth 同意页';
  2728. }
  2729. }
  2730. async function executeStep8(state) {
  2731. if (!state.oauthUrl) {
  2732. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2733. }
  2734. await addLog('步骤 8:正在监听 localhost 回调地址...');
  2735. return new Promise((resolve, reject) => {
  2736. let resolved = false;
  2737. let signupTabId = null;
  2738. const cleanupListener = () => {
  2739. cleanupStep8NavigationListeners();
  2740. step8PendingReject = null;
  2741. };
  2742. const rejectStep8 = (error) => {
  2743. if (resolved) return;
  2744. resolved = true;
  2745. clearTimeout(timeout);
  2746. cleanupListener();
  2747. reject(error);
  2748. };
  2749. const finalizeStep8Callback = (callbackUrl) => {
  2750. if (resolved || !callbackUrl) return;
  2751. resolved = true;
  2752. cleanupListener();
  2753. clearTimeout(timeout);
  2754. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  2755. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  2756. }).then(() => {
  2757. resolve();
  2758. }).catch((err) => {
  2759. reject(err);
  2760. });
  2761. };
  2762. const timeout = setTimeout(() => {
  2763. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  2764. }, 120000);
  2765. step8PendingReject = (error) => {
  2766. rejectStep8(error);
  2767. };
  2768. webNavListener = (details) => {
  2769. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2770. finalizeStep8Callback(callbackUrl);
  2771. };
  2772. webNavCommittedListener = (details) => {
  2773. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2774. finalizeStep8Callback(callbackUrl);
  2775. };
  2776. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  2777. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  2778. finalizeStep8Callback(callbackUrl);
  2779. };
  2780. (async () => {
  2781. try {
  2782. throwIfStep8SettledOrStopped(resolved);
  2783. signupTabId = await getTabId('signup-page');
  2784. throwIfStep8SettledOrStopped(resolved);
  2785. if (signupTabId && await isTabAlive('signup-page')) {
  2786. await chrome.tabs.update(signupTabId, { active: true });
  2787. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  2788. } else {
  2789. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  2790. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  2791. }
  2792. throwIfStep8SettledOrStopped(resolved);
  2793. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  2794. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  2795. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  2796. await ensureStep8SignupPageReady(signupTabId, {
  2797. timeoutMs: 15000,
  2798. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  2799. });
  2800. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  2801. throwIfStep8SettledOrStopped(resolved);
  2802. const pageState = await waitForStep8Ready(signupTabId);
  2803. if (!pageState?.consentReady) {
  2804. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2805. continue;
  2806. }
  2807. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  2808. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  2809. if (strategy.mode === 'debugger') {
  2810. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  2811. throwIfStep8SettledOrStopped(resolved);
  2812. await clickWithDebugger(signupTabId, clickTarget?.rect);
  2813. } else {
  2814. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  2815. }
  2816. if (resolved) {
  2817. return;
  2818. }
  2819. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  2820. if (resolved) {
  2821. return;
  2822. }
  2823. if (effect.progressed) {
  2824. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  2825. break;
  2826. }
  2827. if (round >= STEP8_MAX_ROUNDS) {
  2828. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  2829. }
  2830. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  2831. await reloadStep8ConsentPage(signupTabId);
  2832. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2833. }
  2834. } catch (err) {
  2835. rejectStep8(err);
  2836. }
  2837. })();
  2838. });
  2839. }
  2840. // ============================================================
  2841. // Step 9: CPA 回调验证(通过 vps-panel.js)
  2842. // ============================================================
  2843. async function executeStep9(state) {
  2844. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  2845. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  2846. }
  2847. if (!state.localhostUrl) {
  2848. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  2849. }
  2850. if (!state.vpsUrl) {
  2851. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  2852. }
  2853. if (shouldBypassStep9ForLocalCpa(state)) {
  2854. await addLog('步骤 9:检测到本地 CPA,步骤 8 完成后已自动添加,无需重复提交回调地址。', 'info');
  2855. await completeStepFromBackground(9, {
  2856. localhostUrl: state.localhostUrl,
  2857. verifiedStatus: 'local-auto',
  2858. });
  2859. return;
  2860. }
  2861. await addLog('步骤 9:正在打开 CPA 面板...');
  2862. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  2863. let tabId = await getTabId('vps-panel');
  2864. const alive = tabId && await isTabAlive('vps-panel');
  2865. if (!alive) {
  2866. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  2867. inject: injectFiles,
  2868. reloadIfSameUrl: true,
  2869. });
  2870. } else {
  2871. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  2872. await chrome.tabs.update(tabId, { active: true });
  2873. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2874. }
  2875. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2876. inject: injectFiles,
  2877. });
  2878. await addLog('步骤 9:正在填写回调地址...');
  2879. const result = await sendToContentScriptResilient('vps-panel', {
  2880. type: 'EXECUTE_STEP',
  2881. step: 9,
  2882. source: 'background',
  2883. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  2884. }, {
  2885. timeoutMs: 30000,
  2886. retryDelayMs: 700,
  2887. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  2888. });
  2889. if (result?.error) {
  2890. throw new Error(result.error);
  2891. }
  2892. }
  2893. // ============================================================
  2894. // Open Side Panel on extension icon click
  2895. // ============================================================
  2896. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  2897. chrome.alarms.onAlarm.addListener((alarm) => {
  2898. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  2899. return;
  2900. }
  2901. launchScheduledAutoRun('alarm').catch((err) => {
  2902. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  2903. });
  2904. });
  2905. chrome.runtime.onStartup.addListener(() => {
  2906. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2907. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  2908. });
  2909. });
  2910. chrome.runtime.onInstalled.addListener(() => {
  2911. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2912. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  2913. });
  2914. });
  2915. restoreScheduledAutoRunIfNeeded().catch((err) => {
  2916. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  2917. });