background.js 97 KB

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