signup-page.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333
  1. // content/signup-page.js — Content script for ChatGPT signup entry + OpenAI auth pages
  2. // Injected on: auth0.openai.com, auth.openai.com, accounts.openai.com
  3. // Dynamically injected on: chatgpt.com
  4. console.log('[MultiPage:signup-page] Content script loaded on', location.href);
  5. const SIGNUP_PAGE_LISTENER_SENTINEL = 'data-multipage-signup-page-listener';
  6. if (document.documentElement.getAttribute(SIGNUP_PAGE_LISTENER_SENTINEL) !== '1') {
  7. document.documentElement.setAttribute(SIGNUP_PAGE_LISTENER_SENTINEL, '1');
  8. // Listen for commands from Background
  9. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  10. if (
  11. message.type === 'EXECUTE_STEP'
  12. || message.type === 'FILL_CODE'
  13. || message.type === 'STEP8_FIND_AND_CLICK'
  14. || message.type === 'STEP8_GET_STATE'
  15. || message.type === 'STEP8_TRIGGER_CONTINUE'
  16. || message.type === 'GET_LOGIN_AUTH_STATE'
  17. || message.type === 'PREPARE_SIGNUP_VERIFICATION'
  18. || message.type === 'RECOVER_AUTH_RETRY_PAGE'
  19. || message.type === 'RESEND_VERIFICATION_CODE'
  20. || message.type === 'ENSURE_SIGNUP_ENTRY_READY'
  21. || message.type === 'ENSURE_SIGNUP_PASSWORD_PAGE_READY'
  22. ) {
  23. resetStopState();
  24. handleCommand(message).then((result) => {
  25. sendResponse({ ok: true, ...(result || {}) });
  26. }).catch(err => {
  27. if (isStopError(err)) {
  28. if (message.step) {
  29. log(`步骤 ${message.step || 8}:已被用户停止。`, 'warn');
  30. }
  31. sendResponse({ stopped: true, error: err.message });
  32. return;
  33. }
  34. if (message.type === 'STEP8_FIND_AND_CLICK') {
  35. log(`步骤 9:${err.message}`, 'error');
  36. sendResponse({ error: err.message });
  37. return;
  38. }
  39. if (message.step) {
  40. reportError(message.step, err.message);
  41. }
  42. sendResponse({ error: err.message });
  43. });
  44. return true;
  45. }
  46. });
  47. } else {
  48. console.log('[MultiPage:signup-page] 消息监听已存在,跳过重复注册');
  49. }
  50. async function handleCommand(message) {
  51. switch (message.type) {
  52. case 'EXECUTE_STEP':
  53. switch (message.step) {
  54. case 2: return await step2_clickRegister(message.payload);
  55. case 3: return await step3_fillEmailPassword(message.payload);
  56. case 5: return await step5_fillNameBirthday(message.payload);
  57. case 7: return await step6_login(message.payload);
  58. case 9: return await step8_findAndClick();
  59. default: throw new Error(`signup-page.js 不处理步骤 ${message.step}`);
  60. }
  61. case 'FILL_CODE':
  62. // Step 4 = signup code, Step 7 = login code (same handler)
  63. return await fillVerificationCode(message.step, message.payload);
  64. case 'GET_LOGIN_AUTH_STATE':
  65. return serializeLoginAuthState(inspectLoginAuthState());
  66. case 'PREPARE_SIGNUP_VERIFICATION':
  67. return await prepareSignupVerificationFlow(message.payload);
  68. case 'RECOVER_AUTH_RETRY_PAGE':
  69. return await recoverCurrentAuthRetryPage(message.payload);
  70. case 'RESEND_VERIFICATION_CODE':
  71. return await resendVerificationCode(message.step);
  72. case 'ENSURE_SIGNUP_ENTRY_READY':
  73. return await ensureSignupEntryReady();
  74. case 'ENSURE_SIGNUP_PASSWORD_PAGE_READY':
  75. return await ensureSignupPasswordPageReady();
  76. case 'STEP8_FIND_AND_CLICK':
  77. return await step8_findAndClick();
  78. case 'STEP8_GET_STATE':
  79. return getStep8State();
  80. case 'STEP8_TRIGGER_CONTINUE':
  81. return await step8_triggerContinue(message.payload);
  82. }
  83. }
  84. const VERIFICATION_CODE_INPUT_SELECTOR = [
  85. 'input[name="code"]',
  86. 'input[name="otp"]',
  87. 'input[autocomplete="one-time-code"]',
  88. 'input[type="text"][maxlength="6"]',
  89. 'input[type="tel"][maxlength="6"]',
  90. 'input[aria-label*="code" i]',
  91. 'input[placeholder*="code" i]',
  92. 'input[inputmode="numeric"]',
  93. ].join(', ');
  94. const ONE_TIME_CODE_LOGIN_PATTERN = /使用一次性验证码登录|改用(?:一次性)?验证码(?:登录)?|使用验证码登录|一次性验证码|验证码登录|one[-\s]*time\s*(?:passcode|password|code)|use\s+(?:a\s+)?one[-\s]*time\s*(?:passcode|password|code)(?:\s+instead)?|use\s+(?:a\s+)?code(?:\s+instead)?|sign\s+in\s+with\s+(?:email|code)|email\s+(?:me\s+)?(?:a\s+)?code/i;
  95. const RESEND_VERIFICATION_CODE_PATTERN = /重新发送(?:验证码)?|再次发送(?:验证码)?|重发(?:验证码)?|未收到(?:验证码|邮件)|resend(?:\s+code)?|send\s+(?:a\s+)?new\s+code|send\s+(?:it\s+)?again|request\s+(?:a\s+)?new\s+code|didn'?t\s+receive/i;
  96. function isVisibleElement(el) {
  97. if (!el) return false;
  98. const style = window.getComputedStyle(el);
  99. const rect = el.getBoundingClientRect();
  100. return style.display !== 'none'
  101. && style.visibility !== 'hidden'
  102. && rect.width > 0
  103. && rect.height > 0;
  104. }
  105. function getVerificationCodeTarget() {
  106. const codeInput = document.querySelector(VERIFICATION_CODE_INPUT_SELECTOR);
  107. if (codeInput && isVisibleElement(codeInput)) {
  108. return { type: 'single', element: codeInput };
  109. }
  110. const singleInputs = Array.from(document.querySelectorAll('input[maxlength="1"]'))
  111. .filter(isVisibleElement);
  112. if (singleInputs.length >= 6) {
  113. return { type: 'split', elements: singleInputs };
  114. }
  115. return null;
  116. }
  117. function getActionText(el) {
  118. return [
  119. el?.textContent,
  120. el?.value,
  121. el?.getAttribute?.('aria-label'),
  122. el?.getAttribute?.('title'),
  123. ]
  124. .filter(Boolean)
  125. .join(' ')
  126. .replace(/\s+/g, ' ')
  127. .trim();
  128. }
  129. function isActionEnabled(el) {
  130. return Boolean(el)
  131. && !el.disabled
  132. && el.getAttribute('aria-disabled') !== 'true';
  133. }
  134. function findOneTimeCodeLoginTrigger() {
  135. const candidates = document.querySelectorAll(
  136. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  137. );
  138. for (const el of candidates) {
  139. if (!isVisibleElement(el)) continue;
  140. if (el.disabled || el.getAttribute('aria-disabled') === 'true') continue;
  141. const text = [
  142. el.textContent,
  143. el.value,
  144. el.getAttribute('aria-label'),
  145. el.getAttribute('title'),
  146. ]
  147. .filter(Boolean)
  148. .join(' ')
  149. .replace(/\s+/g, ' ')
  150. .trim();
  151. if (text && ONE_TIME_CODE_LOGIN_PATTERN.test(text)) {
  152. return el;
  153. }
  154. }
  155. return null;
  156. }
  157. function findResendVerificationCodeTrigger({ allowDisabled = false } = {}) {
  158. const candidates = document.querySelectorAll(
  159. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  160. );
  161. for (const el of candidates) {
  162. if (!isVisibleElement(el)) continue;
  163. if (!allowDisabled && !isActionEnabled(el)) continue;
  164. const text = getActionText(el);
  165. if (text && RESEND_VERIFICATION_CODE_PATTERN.test(text)) {
  166. return el;
  167. }
  168. }
  169. return null;
  170. }
  171. function isEmailVerificationPage() {
  172. return /\/email-verification(?:[/?#]|$)/i.test(location.pathname || '');
  173. }
  174. async function resendVerificationCode(step, timeout = 45000) {
  175. if (step === 8) {
  176. await waitForLoginVerificationPageReady();
  177. }
  178. const start = Date.now();
  179. let action = null;
  180. let loggedWaiting = false;
  181. while (Date.now() - start < timeout) {
  182. throwIfStopped();
  183. // Check for 405 error page and recover by clicking "Try again"
  184. if (is405MethodNotAllowedPage()) {
  185. await handle405ResendError(step, timeout - (Date.now() - start));
  186. // After recovery, loop back to find the resend button again
  187. loggedWaiting = false;
  188. continue;
  189. }
  190. action = findResendVerificationCodeTrigger({ allowDisabled: true });
  191. if (action && isActionEnabled(action)) {
  192. log(`步骤 ${step}:重新发送验证码按钮已可用。`);
  193. await humanPause(350, 900);
  194. simulateClick(action);
  195. await sleep(1200);
  196. // After clicking resend, check if 405 error appeared
  197. if (is405MethodNotAllowedPage()) {
  198. log(`步骤 ${step}:点击重新发送后出现 405 错误,正在恢复...`, 'warn');
  199. await handle405ResendError(step, timeout - (Date.now() - start));
  200. loggedWaiting = false;
  201. continue;
  202. }
  203. return {
  204. resent: true,
  205. buttonText: getActionText(action),
  206. };
  207. }
  208. if (action && !loggedWaiting) {
  209. loggedWaiting = true;
  210. log(`步骤 ${step}:正在等待重新发送验证码按钮变为可点击...`);
  211. }
  212. await sleep(250);
  213. }
  214. throw new Error('无法点击重新发送验证码按钮。URL: ' + location.href);
  215. }
  216. function is405MethodNotAllowedPage() {
  217. const pageText = document.body?.textContent || '';
  218. return /405\s+Method\s+Not\s+Allowed/i.test(pageText)
  219. || /Route\s+Error.*405/i.test(pageText);
  220. }
  221. async function handle405ResendError(step, remainingTimeout = 30000) {
  222. const start = Date.now();
  223. let retryCount = 0;
  224. while (Date.now() - start < remainingTimeout) {
  225. throwIfStopped();
  226. if (!is405MethodNotAllowedPage()) {
  227. // Page recovered — back to verification page
  228. log(`步骤 ${step}:405 错误已恢复,页面已返回验证码页面。`);
  229. return;
  230. }
  231. const retryBtn = getAuthRetryButton();
  232. if (retryBtn) {
  233. retryCount++;
  234. log(`步骤 ${step}:检测到 405 错误页面,正在点击"Try again"(第 ${retryCount} 次)...`, 'warn');
  235. await humanPause(300, 800);
  236. simulateClick(retryBtn);
  237. // Wait 3 seconds before checking again
  238. await sleep(3000);
  239. continue;
  240. }
  241. await sleep(500);
  242. }
  243. throw new Error(`步骤 ${step}:405 错误恢复超时,无法返回验证码页面。URL: ${location.href}`);
  244. }
  245. // ============================================================
  246. // Signup Entry Helpers
  247. // ============================================================
  248. const SIGNUP_ENTRY_TRIGGER_PATTERN = /免费注册|立即注册|注册|sign\s*up|register|create\s*account|create\s+account/i;
  249. const SIGNUP_EMAIL_INPUT_SELECTOR = 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i]';
  250. function getSignupEmailInput() {
  251. const input = document.querySelector(SIGNUP_EMAIL_INPUT_SELECTOR);
  252. return input && isVisibleElement(input) ? input : null;
  253. }
  254. function getSignupEmailContinueButton({ allowDisabled = false } = {}) {
  255. const direct = document.querySelector('button[type="submit"], input[type="submit"]');
  256. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  257. return direct;
  258. }
  259. const candidates = document.querySelectorAll(
  260. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  261. );
  262. return Array.from(candidates).find((el) => {
  263. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  264. return /continue|next|submit|继续|下一步/i.test(getActionText(el));
  265. }) || null;
  266. }
  267. function findSignupEntryTrigger() {
  268. const candidates = document.querySelectorAll('a, button, [role="button"], [role="link"]');
  269. return Array.from(candidates).find((el) => {
  270. if (!isVisibleElement(el) || !isActionEnabled(el)) return false;
  271. return SIGNUP_ENTRY_TRIGGER_PATTERN.test(getActionText(el));
  272. }) || null;
  273. }
  274. function getSignupPasswordDisplayedEmail() {
  275. const text = (document.body?.innerText || document.body?.textContent || '')
  276. .replace(/\s+/g, ' ')
  277. .trim();
  278. const matches = text.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig);
  279. return matches?.[0] ? String(matches[0]).trim().toLowerCase() : '';
  280. }
  281. function inspectSignupEntryState() {
  282. const passwordInput = getSignupPasswordInput();
  283. if (isSignupPasswordPage() && passwordInput) {
  284. return {
  285. state: 'password_page',
  286. passwordInput,
  287. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  288. displayedEmail: getSignupPasswordDisplayedEmail(),
  289. url: location.href,
  290. };
  291. }
  292. const emailInput = getSignupEmailInput();
  293. if (emailInput) {
  294. return {
  295. state: 'email_entry',
  296. emailInput,
  297. continueButton: getSignupEmailContinueButton({ allowDisabled: true }),
  298. url: location.href,
  299. };
  300. }
  301. const signupTrigger = findSignupEntryTrigger();
  302. if (signupTrigger) {
  303. return {
  304. state: 'entry_home',
  305. signupTrigger,
  306. url: location.href,
  307. };
  308. }
  309. return {
  310. state: 'unknown',
  311. url: location.href,
  312. };
  313. }
  314. function getSignupEntryDiagnostics() {
  315. const actionCandidates = document.querySelectorAll(
  316. 'a, button, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  317. );
  318. const allActions = Array.from(actionCandidates).map((el) => {
  319. const rect = typeof el?.getBoundingClientRect === 'function'
  320. ? el.getBoundingClientRect()
  321. : null;
  322. const text = getActionText(el);
  323. return {
  324. tag: (el.tagName || '').toLowerCase(),
  325. type: el.getAttribute?.('type') || '',
  326. text: text.slice(0, 80),
  327. visible: isVisibleElement(el),
  328. enabled: isActionEnabled(el),
  329. rect: rect
  330. ? {
  331. width: Math.round(rect.width || 0),
  332. height: Math.round(rect.height || 0),
  333. }
  334. : null,
  335. };
  336. });
  337. const visibleActions = Array.from(actionCandidates)
  338. .filter(isVisibleElement)
  339. .slice(0, 12)
  340. .map((el) => ({
  341. tag: (el.tagName || '').toLowerCase(),
  342. type: el.getAttribute?.('type') || '',
  343. text: getActionText(el).slice(0, 80),
  344. enabled: isActionEnabled(el),
  345. }))
  346. .filter((item) => item.text);
  347. const signupLikeActions = allActions
  348. .filter((item) => item.text && SIGNUP_ENTRY_TRIGGER_PATTERN.test(item.text))
  349. .slice(0, 12);
  350. return {
  351. url: location.href,
  352. title: document.title || '',
  353. readyState: document.readyState || '',
  354. hasEmailInput: Boolean(getSignupEmailInput()),
  355. hasPasswordInput: Boolean(getSignupPasswordInput()),
  356. bodyContainsSignupText: SIGNUP_ENTRY_TRIGGER_PATTERN.test(getPageTextSnapshot()),
  357. signupLikeActions,
  358. visibleActions,
  359. bodyTextPreview: getPageTextSnapshot().slice(0, 240),
  360. };
  361. }
  362. async function waitForSignupEntryState(options = {}) {
  363. const {
  364. timeout = 15000,
  365. autoOpenEntry = false,
  366. } = options;
  367. const start = Date.now();
  368. let lastTriggerClickAt = 0;
  369. while (Date.now() - start < timeout) {
  370. throwIfStopped();
  371. const snapshot = inspectSignupEntryState();
  372. if (snapshot.state === 'password_page' || snapshot.state === 'email_entry') {
  373. return snapshot;
  374. }
  375. if (snapshot.state === 'entry_home') {
  376. if (!autoOpenEntry) {
  377. return snapshot;
  378. }
  379. if (Date.now() - lastTriggerClickAt >= 1500) {
  380. lastTriggerClickAt = Date.now();
  381. log('步骤 2:正在点击官网注册入口...');
  382. await humanPause(350, 900);
  383. simulateClick(snapshot.signupTrigger);
  384. }
  385. }
  386. await sleep(250);
  387. }
  388. return inspectSignupEntryState();
  389. }
  390. async function ensureSignupEntryReady(timeout = 15000) {
  391. const snapshot = await waitForSignupEntryState({ timeout, autoOpenEntry: false });
  392. if (snapshot.state === 'entry_home' || snapshot.state === 'email_entry' || snapshot.state === 'password_page') {
  393. return {
  394. ready: true,
  395. state: snapshot.state,
  396. url: snapshot.url || location.href,
  397. };
  398. }
  399. log(`注册入口识别失败,诊断快照:${JSON.stringify(getSignupEntryDiagnostics())}`, 'warn');
  400. throw new Error('当前页面没有可用的注册入口,也不在邮箱/密码页。URL: ' + location.href);
  401. }
  402. async function ensureSignupPasswordPageReady(timeout = 20000) {
  403. const start = Date.now();
  404. while (Date.now() - start < timeout) {
  405. throwIfStopped();
  406. const passwordInput = getSignupPasswordInput();
  407. if (isSignupPasswordPage() && passwordInput) {
  408. return {
  409. ready: true,
  410. state: 'password_page',
  411. url: location.href,
  412. };
  413. }
  414. await sleep(200);
  415. }
  416. throw new Error('等待进入密码页超时。URL: ' + location.href);
  417. }
  418. async function fillSignupEmailAndContinue(email, step) {
  419. if (!email) throw new Error(`未提供邮箱地址,步骤 ${step} 无法继续。`);
  420. const normalizedEmail = String(email || '').trim().toLowerCase();
  421. const snapshot = await waitForSignupEntryState({
  422. timeout: 20000,
  423. autoOpenEntry: true,
  424. });
  425. if (snapshot.state === 'password_page') {
  426. if (snapshot.displayedEmail && snapshot.displayedEmail !== normalizedEmail) {
  427. throw new Error(`步骤 ${step}:当前密码页邮箱为 ${snapshot.displayedEmail},与目标邮箱 ${email} 不一致,请先回到步骤 1 重新开始。`);
  428. }
  429. log(`步骤 ${step}:当前已在密码页,无需重复提交邮箱。`);
  430. return {
  431. alreadyOnPasswordPage: true,
  432. url: snapshot.url || location.href,
  433. };
  434. }
  435. if (snapshot.state !== 'email_entry' || !snapshot.emailInput) {
  436. throw new Error(`步骤 ${step}:未找到可用的邮箱输入入口。URL: ${location.href}`);
  437. }
  438. log(`步骤 ${step}:正在填写邮箱:${email}`);
  439. await humanPause(500, 1400);
  440. fillInput(snapshot.emailInput, email);
  441. log(`步骤 ${step}:邮箱已填写`);
  442. const continueButton = snapshot.continueButton || getSignupEmailContinueButton({ allowDisabled: true });
  443. if (!continueButton || !isActionEnabled(continueButton)) {
  444. throw new Error(`步骤 ${step}:未找到可点击的“继续”按钮。URL: ${location.href}`);
  445. }
  446. log(`步骤 ${step}:邮箱已准备提交,正在前往密码页...`);
  447. window.setTimeout(() => {
  448. try {
  449. simulateClick(continueButton);
  450. } catch (error) {
  451. console.error('[MultiPage:signup-page] deferred signup email submit failed:', error?.message || error);
  452. }
  453. }, 120);
  454. return {
  455. submitted: true,
  456. email,
  457. url: location.href,
  458. };
  459. }
  460. // ============================================================
  461. // Step 2: Click Register, fill email, then continue to password page
  462. // ============================================================
  463. async function step2_clickRegister(payload = {}) {
  464. const { email } = payload;
  465. return fillSignupEmailAndContinue(email, 2);
  466. }
  467. // ============================================================
  468. // Step 3: Fill Password
  469. // ============================================================
  470. async function step3_fillEmailPassword(payload) {
  471. const { email, password } = payload;
  472. if (!password) throw new Error('未提供密码,步骤 3 需要可用密码。');
  473. const normalizedEmail = String(email || '').trim().toLowerCase();
  474. let snapshot = inspectSignupEntryState();
  475. if (snapshot.state === 'entry_home') {
  476. throw new Error('当前仍停留在 ChatGPT 官网首页,请先完成步骤 2。');
  477. }
  478. if (snapshot.state === 'email_entry') {
  479. const transition = await fillSignupEmailAndContinue(email, 3);
  480. if (!transition.alreadyOnPasswordPage) {
  481. await sleep(1200);
  482. await ensureSignupPasswordPageReady();
  483. }
  484. snapshot = inspectSignupEntryState();
  485. }
  486. if (snapshot.state !== 'password_page' || !snapshot.passwordInput) {
  487. await ensureSignupPasswordPageReady();
  488. snapshot = inspectSignupEntryState();
  489. }
  490. if (snapshot.state !== 'password_page' || !snapshot.passwordInput) {
  491. throw new Error('在密码页未找到密码输入框。URL: ' + location.href);
  492. }
  493. if (normalizedEmail && snapshot.displayedEmail && snapshot.displayedEmail !== normalizedEmail) {
  494. throw new Error(`当前密码页邮箱为 ${snapshot.displayedEmail},与目标邮箱 ${email} 不一致,请先回到步骤 1 重新开始。`);
  495. }
  496. await humanPause(600, 1500);
  497. fillInput(snapshot.passwordInput, password);
  498. log('步骤 3:密码已填写');
  499. const submitBtn = snapshot.submitButton
  500. || getSignupPasswordSubmitButton({ allowDisabled: true })
  501. || await waitForElementByText('button', /continue|sign\s*up|submit|注册|创建|create/i, 5000).catch(() => null);
  502. // Report complete BEFORE submit, because submit causes page navigation
  503. // which kills the content script connection
  504. const signupVerificationRequestedAt = submitBtn ? Date.now() : null;
  505. const completionPayload = {
  506. email,
  507. signupVerificationRequestedAt,
  508. deferredSubmit: Boolean(submitBtn),
  509. };
  510. reportComplete(3, completionPayload);
  511. if (submitBtn) {
  512. window.setTimeout(async () => {
  513. try {
  514. await sleep(500);
  515. await humanPause(500, 1300);
  516. simulateClick(submitBtn);
  517. log('步骤 3:表单已提交');
  518. } catch (error) {
  519. console.error('[MultiPage:signup-page] deferred step 3 submit failed:', error?.message || error);
  520. }
  521. }, 120);
  522. }
  523. return completionPayload;
  524. }
  525. // ============================================================
  526. // Fill Verification Code (used by step 4 and step 7)
  527. // ============================================================
  528. const INVALID_VERIFICATION_CODE_PATTERN = /代码不正确|验证码不正确|验证码错误|code\s+(?:is\s+)?incorrect|invalid\s+code|incorrect\s+code|try\s+again/i;
  529. const VERIFICATION_PAGE_PATTERN = /检查您的收件箱|输入我们刚刚向|重新发送电子邮件|重新发送验证码|代码不正确|email\s+verification|check\s+your\s+inbox|enter\s+the\s+code|we\s+just\s+sent|we\s+emailed|resend/i;
  530. const OAUTH_CONSENT_PAGE_PATTERN = /使用\s*ChatGPT\s*登录到\s*Codex|sign\s+in\s+to\s+codex(?:\s+with\s+chatgpt)?|login\s+to\s+codex|log\s+in\s+to\s+codex|authorize|授权/i;
  531. const OAUTH_CONSENT_FORM_SELECTOR = 'form[action*="/sign-in-with-chatgpt/" i][action*="/consent" i]';
  532. const CONTINUE_ACTION_PATTERN = /继续|continue/i;
  533. const ADD_PHONE_PAGE_PATTERN = /add[\s-]*phone|添加手机号|手机号码|手机号|phone\s+number|telephone/i;
  534. const STEP5_SUBMIT_ERROR_PATTERN = /无法根据该信息创建帐户|请重试|unable\s+to\s+create\s+(?:your\s+)?account|couldn'?t\s+create\s+(?:your\s+)?account|something\s+went\s+wrong|invalid\s+(?:birthday|birth|date)|生日|出生日期/i;
  535. const AUTH_TIMEOUT_ERROR_TITLE_PATTERN = /糟糕,出错了|something\s+went\s+wrong|oops/i;
  536. const AUTH_TIMEOUT_ERROR_DETAIL_PATTERN = /operation\s+timed\s+out|timed\s+out|请求超时|操作超时/i;
  537. const SIGNUP_EMAIL_EXISTS_PATTERN = /与此电子邮件地址相关联的帐户已存在|account\s+associated\s+with\s+this\s+email\s+address\s+already\s+exists|email\s+address.*already\s+exists/i;
  538. const authPageRecovery = self.MultiPageAuthPageRecovery?.createAuthPageRecovery?.({
  539. detailPattern: AUTH_TIMEOUT_ERROR_DETAIL_PATTERN,
  540. getActionText,
  541. getPageTextSnapshot,
  542. humanPause,
  543. isActionEnabled,
  544. isVisibleElement,
  545. log,
  546. simulateClick,
  547. sleep,
  548. throwIfStopped,
  549. titlePattern: AUTH_TIMEOUT_ERROR_TITLE_PATTERN,
  550. }) || null;
  551. function getVerificationErrorText() {
  552. const messages = [];
  553. const selectors = [
  554. '.react-aria-FieldError',
  555. '[slot="errorMessage"]',
  556. '[id$="-error"]',
  557. '[data-invalid="true"] + *',
  558. '[aria-invalid="true"] + *',
  559. '[class*="error"]',
  560. ];
  561. for (const selector of selectors) {
  562. document.querySelectorAll(selector).forEach((el) => {
  563. const text = (el.textContent || '').replace(/\s+/g, ' ').trim();
  564. if (text) {
  565. messages.push(text);
  566. }
  567. });
  568. }
  569. const invalidInput = document.querySelector(`${VERIFICATION_CODE_INPUT_SELECTOR}[aria-invalid="true"], ${VERIFICATION_CODE_INPUT_SELECTOR}[data-invalid="true"]`);
  570. if (invalidInput) {
  571. const wrapper = invalidInput.closest('form, [data-rac], ._root_18qcl_51, div');
  572. if (wrapper) {
  573. const text = (wrapper.textContent || '').replace(/\s+/g, ' ').trim();
  574. if (text) {
  575. messages.push(text);
  576. }
  577. }
  578. }
  579. return messages.find((text) => INVALID_VERIFICATION_CODE_PATTERN.test(text)) || '';
  580. }
  581. function isStep5Ready() {
  582. return Boolean(
  583. document.querySelector('input[name="name"], input[autocomplete="name"], input[name="birthday"], input[name="age"], [role="spinbutton"][data-type="year"]')
  584. );
  585. }
  586. function getPageTextSnapshot() {
  587. return (document.body?.innerText || document.body?.textContent || '')
  588. .replace(/\s+/g, ' ')
  589. .trim();
  590. }
  591. function getOAuthConsentForm() {
  592. return document.querySelector(OAUTH_CONSENT_FORM_SELECTOR);
  593. }
  594. function getPrimaryContinueButton() {
  595. const consentForm = getOAuthConsentForm();
  596. if (consentForm) {
  597. const formButtons = Array.from(
  598. consentForm.querySelectorAll('button[type="submit"], input[type="submit"], [role="button"]')
  599. );
  600. const formContinueButton = formButtons.find((el) => {
  601. if (!isVisibleElement(el)) return false;
  602. const ddActionName = el.getAttribute?.('data-dd-action-name') || '';
  603. return ddActionName === 'Continue' || CONTINUE_ACTION_PATTERN.test(getActionText(el));
  604. });
  605. if (formContinueButton) {
  606. return formContinueButton;
  607. }
  608. const firstVisibleSubmit = formButtons.find(isVisibleElement);
  609. if (firstVisibleSubmit) {
  610. return firstVisibleSubmit;
  611. }
  612. }
  613. const continueBtn = document.querySelector(
  614. `${OAUTH_CONSENT_FORM_SELECTOR} button[type="submit"], button[type="submit"][data-dd-action-name="Continue"], button[type="submit"]._primary_3rdp0_107`
  615. );
  616. if (continueBtn && isVisibleElement(continueBtn)) {
  617. return continueBtn;
  618. }
  619. const buttons = document.querySelectorAll('button, [role="button"]');
  620. return Array.from(buttons).find((el) => {
  621. if (!isVisibleElement(el)) return false;
  622. const ddActionName = el.getAttribute?.('data-dd-action-name') || '';
  623. return ddActionName === 'Continue' || CONTINUE_ACTION_PATTERN.test(getActionText(el));
  624. }) || null;
  625. }
  626. function isOAuthConsentPage() {
  627. const pageText = getPageTextSnapshot();
  628. if (OAUTH_CONSENT_PAGE_PATTERN.test(pageText)) {
  629. return true;
  630. }
  631. if (getOAuthConsentForm()) {
  632. return true;
  633. }
  634. return /\bcodex\b/i.test(pageText) && /\bchatgpt\b/i.test(pageText) && Boolean(getPrimaryContinueButton());
  635. }
  636. function isVerificationPageStillVisible() {
  637. if (getVerificationCodeTarget()) return true;
  638. if (findResendVerificationCodeTrigger({ allowDisabled: true })) return true;
  639. if (document.querySelector('form[action*="email-verification" i]')) return true;
  640. return VERIFICATION_PAGE_PATTERN.test(getPageTextSnapshot());
  641. }
  642. function isAddPhonePageReady() {
  643. const path = `${location.pathname || ''} ${location.href || ''}`;
  644. if (/\/add-phone(?:[/?#]|$)/i.test(path)) return true;
  645. const phoneInput = document.querySelector(
  646. 'input[type="tel"]:not([maxlength="6"]), input[name*="phone" i], input[id*="phone" i], input[autocomplete="tel"]'
  647. );
  648. if (phoneInput && isVisibleElement(phoneInput)) {
  649. return true;
  650. }
  651. return ADD_PHONE_PAGE_PATTERN.test(getPageTextSnapshot());
  652. }
  653. function isStep8Ready() {
  654. const continueBtn = getPrimaryContinueButton();
  655. if (!continueBtn) return false;
  656. if (isVerificationPageStillVisible()) return false;
  657. if (isAddPhonePageReady()) return false;
  658. return isOAuthConsentPage();
  659. }
  660. function normalizeInlineText(text) {
  661. return (text || '').replace(/\s+/g, ' ').trim();
  662. }
  663. function findBirthdayReactAriaSelect(labelText) {
  664. const normalizedLabel = normalizeInlineText(labelText);
  665. const roots = document.querySelectorAll('.react-aria-Select');
  666. for (const root of roots) {
  667. const labelEl = Array.from(root.querySelectorAll('span')).find((el) => normalizeInlineText(el.textContent) === normalizedLabel);
  668. if (!labelEl) continue;
  669. const item = root.closest('[class*="selectItem"], ._selectItem_ppsls_113') || root.parentElement;
  670. const nativeSelect = item?.querySelector('[data-testid="hidden-select-container"] select') || null;
  671. const button = root.querySelector('button[aria-haspopup="listbox"]') || null;
  672. const valueEl = root.querySelector('.react-aria-SelectValue') || null;
  673. return { root, item, labelEl, nativeSelect, button, valueEl };
  674. }
  675. return null;
  676. }
  677. async function setReactAriaBirthdaySelect(control, value) {
  678. if (!control?.nativeSelect) {
  679. throw new Error('未找到可写入的生日下拉框。');
  680. }
  681. const desiredValue = String(value);
  682. const option = Array.from(control.nativeSelect.options).find((item) => item.value === desiredValue);
  683. if (!option) {
  684. throw new Error(`生日下拉框中不存在值 ${desiredValue}。`);
  685. }
  686. control.nativeSelect.value = desiredValue;
  687. option.selected = true;
  688. control.nativeSelect.dispatchEvent(new Event('input', { bubbles: true }));
  689. control.nativeSelect.dispatchEvent(new Event('change', { bubbles: true }));
  690. await sleep(120);
  691. }
  692. function getStep5ErrorText() {
  693. const messages = [];
  694. const selectors = [
  695. '.react-aria-FieldError',
  696. '[slot="errorMessage"]',
  697. '[id$="-error"]',
  698. '[id$="-errors"]',
  699. '[role="alert"]',
  700. '[aria-live="assertive"]',
  701. '[aria-live="polite"]',
  702. '[class*="error"]',
  703. ];
  704. for (const selector of selectors) {
  705. document.querySelectorAll(selector).forEach((el) => {
  706. if (!isVisibleElement(el)) return;
  707. const text = normalizeInlineText(el.textContent);
  708. if (text) {
  709. messages.push(text);
  710. }
  711. });
  712. }
  713. const invalidField = Array.from(document.querySelectorAll('[aria-invalid="true"], [data-invalid="true"]'))
  714. .find((el) => isVisibleElement(el));
  715. if (invalidField) {
  716. const wrapper = invalidField.closest('form, fieldset, [data-rac], div');
  717. if (wrapper) {
  718. const text = normalizeInlineText(wrapper.textContent);
  719. if (text) {
  720. messages.push(text);
  721. }
  722. }
  723. }
  724. return messages.find((text) => STEP5_SUBMIT_ERROR_PATTERN.test(text)) || '';
  725. }
  726. function isSignupPasswordPage() {
  727. return /\/create-account\/password(?:[/?#]|$)/i.test(location.pathname || '');
  728. }
  729. function getSignupPasswordInput() {
  730. const input = document.querySelector('input[type="password"]');
  731. return input && isVisibleElement(input) ? input : null;
  732. }
  733. function getSignupPasswordSubmitButton({ allowDisabled = false } = {}) {
  734. const direct = document.querySelector('button[type="submit"]');
  735. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  736. return direct;
  737. }
  738. const candidates = document.querySelectorAll('button, [role="button"]');
  739. return Array.from(candidates).find((el) => {
  740. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  741. const text = getActionText(el);
  742. return /继续|continue|submit|创建|create/i.test(text);
  743. }) || null;
  744. }
  745. function getAuthRetryButton({ allowDisabled = false } = {}) {
  746. if (authPageRecovery?.getAuthRetryButton) {
  747. return authPageRecovery.getAuthRetryButton({ allowDisabled });
  748. }
  749. const direct = document.querySelector('button[data-dd-action-name="Try again"]');
  750. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  751. return direct;
  752. }
  753. const candidates = document.querySelectorAll('button, [role="button"]');
  754. return Array.from(candidates).find((el) => {
  755. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  756. const text = getActionText(el);
  757. return /重试|try\s+again/i.test(text);
  758. }) || null;
  759. }
  760. function getAuthTimeoutErrorPageState(options = {}) {
  761. if (authPageRecovery?.getAuthTimeoutErrorPageState) {
  762. return authPageRecovery.getAuthTimeoutErrorPageState(options);
  763. }
  764. const { pathPatterns = [] } = options;
  765. const path = location.pathname || '';
  766. if (pathPatterns.length && !pathPatterns.some((pattern) => pattern.test(path))) {
  767. return null;
  768. }
  769. const retryButton = getAuthRetryButton({ allowDisabled: true });
  770. if (!retryButton) {
  771. return null;
  772. }
  773. const text = getPageTextSnapshot();
  774. const titleMatched = AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(text)
  775. || AUTH_TIMEOUT_ERROR_TITLE_PATTERN.test(document.title || '');
  776. const detailMatched = AUTH_TIMEOUT_ERROR_DETAIL_PATTERN.test(text);
  777. if (!titleMatched && !detailMatched) {
  778. return null;
  779. }
  780. return {
  781. path,
  782. url: location.href,
  783. retryButton,
  784. retryEnabled: isActionEnabled(retryButton),
  785. titleMatched,
  786. detailMatched,
  787. };
  788. }
  789. function getAuthRetryPathPatternsForFlow(flow = 'auth') {
  790. switch (flow) {
  791. case 'signup_password':
  792. return [/\/create-account\/password(?:[/?#]|$)/i];
  793. case 'login':
  794. return [/\/log-in(?:[/?#]|$)/i];
  795. default:
  796. return [];
  797. }
  798. }
  799. function getCurrentAuthRetryPageState(flow = 'auth') {
  800. return getAuthTimeoutErrorPageState({
  801. pathPatterns: getAuthRetryPathPatternsForFlow(flow),
  802. });
  803. }
  804. async function recoverCurrentAuthRetryPage(payload = {}) {
  805. const {
  806. flow = 'auth',
  807. logLabel = '',
  808. step = null,
  809. timeoutMs = 12000,
  810. waitAfterClickMs = 1200,
  811. } = payload;
  812. const pathPatterns = getAuthRetryPathPatternsForFlow(flow);
  813. if (authPageRecovery?.recoverAuthRetryPage) {
  814. return authPageRecovery.recoverAuthRetryPage({
  815. logLabel,
  816. pathPatterns,
  817. step,
  818. timeoutMs,
  819. waitAfterClickMs,
  820. });
  821. }
  822. const start = Date.now();
  823. let clickCount = 0;
  824. while (Date.now() - start < timeoutMs) {
  825. throwIfStopped();
  826. const retryState = getCurrentAuthRetryPageState(flow);
  827. if (!retryState) {
  828. return {
  829. recovered: clickCount > 0,
  830. clickCount,
  831. url: location.href,
  832. };
  833. }
  834. if (retryState.retryButton && retryState.retryEnabled) {
  835. clickCount += 1;
  836. log(`${logLabel || `步骤 ${step || '?'}:检测到重试页,正在点击“重试”恢复`}(第 ${clickCount} 次)...`, 'warn');
  837. await humanPause(300, 800);
  838. simulateClick(retryState.retryButton);
  839. await sleep(waitAfterClickMs);
  840. continue;
  841. }
  842. await sleep(250);
  843. }
  844. throw new Error(`${logLabel || `步骤 ${step || '?'}:重试页恢复`}超时。URL: ${location.href}`);
  845. }
  846. function getSignupPasswordTimeoutErrorPageState() {
  847. return getAuthTimeoutErrorPageState({
  848. pathPatterns: [/\/create-account\/password(?:[/?#]|$)/i],
  849. });
  850. }
  851. function getLoginTimeoutErrorPageState() {
  852. return getAuthTimeoutErrorPageState({
  853. pathPatterns: [/\/log-in(?:[/?#]|$)/i],
  854. });
  855. }
  856. function getLoginEmailInput() {
  857. const input = document.querySelector(
  858. 'input[type="email"], input[name="email"], input[name="username"], input[id*="email"], input[placeholder*="email" i], input[placeholder*="Email"]'
  859. );
  860. return input && isVisibleElement(input) ? input : null;
  861. }
  862. function getLoginPasswordInput() {
  863. const input = document.querySelector('input[type="password"]');
  864. return input && isVisibleElement(input) ? input : null;
  865. }
  866. function getLoginSubmitButton({ allowDisabled = false } = {}) {
  867. const direct = document.querySelector('button[type="submit"], input[type="submit"]');
  868. if (direct && isVisibleElement(direct) && (allowDisabled || isActionEnabled(direct))) {
  869. return direct;
  870. }
  871. const candidates = document.querySelectorAll(
  872. 'button, a, [role="button"], [role="link"], input[type="button"], input[type="submit"]'
  873. );
  874. return Array.from(candidates).find((el) => {
  875. if (!isVisibleElement(el) || (!allowDisabled && !isActionEnabled(el))) return false;
  876. const text = getActionText(el);
  877. if (!text || ONE_TIME_CODE_LOGIN_PATTERN.test(text)) return false;
  878. return /continue|next|submit|sign\s*in|log\s*in|继续|下一步|登录/i.test(text);
  879. }) || null;
  880. }
  881. function inspectLoginAuthState() {
  882. const retryState = getLoginTimeoutErrorPageState();
  883. const verificationTarget = getVerificationCodeTarget();
  884. const passwordInput = getLoginPasswordInput();
  885. const emailInput = getLoginEmailInput();
  886. const switchTrigger = findOneTimeCodeLoginTrigger();
  887. const submitButton = getLoginSubmitButton({ allowDisabled: true });
  888. const verificationVisible = isVerificationPageStillVisible();
  889. const addPhonePage = isAddPhonePageReady();
  890. const consentReady = isStep8Ready();
  891. const oauthConsentPage = isOAuthConsentPage();
  892. const baseState = {
  893. state: 'unknown',
  894. url: location.href,
  895. path: location.pathname || '',
  896. retryButton: retryState?.retryButton || null,
  897. retryEnabled: Boolean(retryState?.retryEnabled),
  898. titleMatched: Boolean(retryState?.titleMatched),
  899. detailMatched: Boolean(retryState?.detailMatched),
  900. verificationTarget,
  901. passwordInput,
  902. emailInput,
  903. submitButton,
  904. switchTrigger,
  905. verificationVisible,
  906. addPhonePage,
  907. oauthConsentPage,
  908. consentReady,
  909. };
  910. if (verificationTarget) {
  911. return {
  912. ...baseState,
  913. state: 'verification_page',
  914. };
  915. }
  916. if (retryState) {
  917. return {
  918. ...baseState,
  919. state: 'login_timeout_error_page',
  920. };
  921. }
  922. if (addPhonePage) {
  923. return {
  924. ...baseState,
  925. state: 'add_phone_page',
  926. };
  927. }
  928. if (passwordInput || switchTrigger) {
  929. return {
  930. ...baseState,
  931. state: 'password_page',
  932. };
  933. }
  934. if (emailInput) {
  935. return {
  936. ...baseState,
  937. state: 'email_page',
  938. };
  939. }
  940. if (verificationVisible) {
  941. return {
  942. ...baseState,
  943. state: 'verification_page',
  944. };
  945. }
  946. return baseState;
  947. }
  948. function serializeLoginAuthState(snapshot) {
  949. return {
  950. state: snapshot?.state || 'unknown',
  951. url: snapshot?.url || location.href,
  952. path: snapshot?.path || location.pathname || '',
  953. retryEnabled: Boolean(snapshot?.retryEnabled),
  954. titleMatched: Boolean(snapshot?.titleMatched),
  955. detailMatched: Boolean(snapshot?.detailMatched),
  956. hasVerificationTarget: Boolean(snapshot?.verificationTarget),
  957. hasPasswordInput: Boolean(snapshot?.passwordInput),
  958. hasEmailInput: Boolean(snapshot?.emailInput),
  959. hasSubmitButton: Boolean(snapshot?.submitButton),
  960. hasSwitchTrigger: Boolean(snapshot?.switchTrigger),
  961. verificationVisible: Boolean(snapshot?.verificationVisible),
  962. addPhonePage: Boolean(snapshot?.addPhonePage),
  963. oauthConsentPage: Boolean(snapshot?.oauthConsentPage),
  964. consentReady: Boolean(snapshot?.consentReady),
  965. };
  966. }
  967. function getLoginAuthStateLabel(snapshot) {
  968. const state = snapshot?.state === 'oauth_consent_page' ? 'unknown' : snapshot?.state;
  969. switch (state) {
  970. case 'verification_page':
  971. return '登录验证码页';
  972. case 'password_page':
  973. return '密码页';
  974. case 'email_page':
  975. return '邮箱输入页';
  976. case 'login_timeout_error_page':
  977. return '登录超时报错页';
  978. case 'oauth_consent_page':
  979. return 'OAuth 授权页';
  980. case 'add_phone_page':
  981. return '手机号页';
  982. default:
  983. return '未知页面';
  984. }
  985. }
  986. async function waitForKnownLoginAuthState(timeout = 15000) {
  987. const start = Date.now();
  988. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  989. while (Date.now() - start < timeout) {
  990. throwIfStopped();
  991. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  992. if (snapshot.state !== 'unknown') {
  993. return snapshot;
  994. }
  995. await sleep(200);
  996. }
  997. return snapshot;
  998. }
  999. async function waitForLoginVerificationPageReady(timeout = 10000) {
  1000. const start = Date.now();
  1001. let snapshot = inspectLoginAuthState();
  1002. while (Date.now() - start < timeout) {
  1003. throwIfStopped();
  1004. snapshot = inspectLoginAuthState();
  1005. if (snapshot.state === 'verification_page') {
  1006. return snapshot;
  1007. }
  1008. if (snapshot.state !== 'unknown') {
  1009. break;
  1010. }
  1011. await sleep(200);
  1012. }
  1013. throw new Error(
  1014. `当前未进入登录验证码页面,请先重新完成步骤 7。当前状态:${getLoginAuthStateLabel(snapshot)}。URL: ${snapshot?.url || location.href}`
  1015. );
  1016. }
  1017. function createStep6SuccessResult(snapshot, options = {}) {
  1018. return {
  1019. step6Outcome: 'success',
  1020. state: snapshot?.state || 'verification_page',
  1021. url: snapshot?.url || location.href,
  1022. via: options.via || '',
  1023. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  1024. };
  1025. }
  1026. function createStep6RecoverableResult(reason, snapshot, options = {}) {
  1027. return {
  1028. step6Outcome: 'recoverable',
  1029. reason,
  1030. state: snapshot?.state || 'unknown',
  1031. url: snapshot?.url || location.href,
  1032. message: options.message || '',
  1033. loginVerificationRequestedAt: options.loginVerificationRequestedAt || null,
  1034. };
  1035. }
  1036. async function createStep6LoginTimeoutRecoverableResult(reason, snapshot, message) {
  1037. const resolvedSnapshot = normalizeStep6Snapshot(snapshot || inspectLoginAuthState());
  1038. if (resolvedSnapshot?.state === 'login_timeout_error_page') {
  1039. try {
  1040. const recoveryResult = await recoverCurrentAuthRetryPage({
  1041. flow: 'login',
  1042. logLabel: '步骤 7:检测到登录超时报错,正在点击“重试”恢复当前页面',
  1043. step: 6,
  1044. timeoutMs: 12000,
  1045. });
  1046. if (recoveryResult?.recovered) {
  1047. log('步骤 7:登录超时报错页已点击“重试”,准备重新执行当前步骤。', 'warn');
  1048. }
  1049. } catch (error) {
  1050. log(`步骤 7:登录超时报错页自动点击“重试”失败:${error.message}`, 'warn');
  1051. }
  1052. }
  1053. return createStep6RecoverableResult(reason, resolvedSnapshot, {
  1054. message,
  1055. });
  1056. }
  1057. function normalizeStep6Snapshot(snapshot) {
  1058. if (snapshot?.state !== 'oauth_consent_page') {
  1059. return snapshot;
  1060. }
  1061. return {
  1062. ...snapshot,
  1063. state: 'unknown',
  1064. };
  1065. }
  1066. function throwForStep6FatalState(snapshot) {
  1067. snapshot = normalizeStep6Snapshot(snapshot);
  1068. switch (snapshot?.state) {
  1069. case 'oauth_consent_page':
  1070. throw new Error(`当前页面已进入 OAuth 授权页,未经过登录验证码页,无法完成步骤 7。URL: ${snapshot.url}`);
  1071. case 'add_phone_page':
  1072. throw new Error(`当前页面已进入手机号页面,未经过登录验证码页,无法完成步骤 7。URL: ${snapshot.url}`);
  1073. case 'unknown':
  1074. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  1075. default:
  1076. return;
  1077. }
  1078. }
  1079. async function triggerLoginSubmitAction(button, fallbackField) {
  1080. const form = button?.form || fallbackField?.form || button?.closest?.('form') || fallbackField?.closest?.('form') || null;
  1081. await humanPause(400, 1100);
  1082. if (button && isActionEnabled(button)) {
  1083. simulateClick(button);
  1084. return;
  1085. }
  1086. if (form && typeof form.requestSubmit === 'function') {
  1087. if (button && button.form === form) {
  1088. form.requestSubmit(button);
  1089. } else {
  1090. form.requestSubmit();
  1091. }
  1092. return;
  1093. }
  1094. if (button && typeof button.click === 'function') {
  1095. button.click();
  1096. return;
  1097. }
  1098. throw new Error('未找到可用的登录提交按钮。URL: ' + location.href);
  1099. }
  1100. function isSignupPasswordErrorPage() {
  1101. return Boolean(getSignupPasswordTimeoutErrorPageState());
  1102. }
  1103. function isSignupEmailAlreadyExistsPage() {
  1104. return isSignupPasswordPage() && SIGNUP_EMAIL_EXISTS_PATTERN.test(getPageTextSnapshot());
  1105. }
  1106. function inspectSignupVerificationState() {
  1107. if (isStep5Ready()) {
  1108. return { state: 'step5' };
  1109. }
  1110. if (isVerificationPageStillVisible()) {
  1111. return { state: 'verification' };
  1112. }
  1113. if (isSignupPasswordErrorPage()) {
  1114. const timeoutPage = getSignupPasswordTimeoutErrorPageState();
  1115. return {
  1116. state: 'error',
  1117. retryButton: timeoutPage?.retryButton || null,
  1118. };
  1119. }
  1120. if (isSignupEmailAlreadyExistsPage()) {
  1121. return { state: 'email_exists' };
  1122. }
  1123. const passwordInput = getSignupPasswordInput();
  1124. if (passwordInput) {
  1125. return {
  1126. state: 'password',
  1127. passwordInput,
  1128. submitButton: getSignupPasswordSubmitButton({ allowDisabled: true }),
  1129. };
  1130. }
  1131. return { state: 'unknown' };
  1132. }
  1133. async function waitForSignupVerificationTransition(timeout = 5000) {
  1134. const start = Date.now();
  1135. while (Date.now() - start < timeout) {
  1136. throwIfStopped();
  1137. const snapshot = inspectSignupVerificationState();
  1138. if (snapshot.state === 'step5' || snapshot.state === 'verification' || snapshot.state === 'error' || snapshot.state === 'email_exists') {
  1139. return snapshot;
  1140. }
  1141. await sleep(200);
  1142. }
  1143. return inspectSignupVerificationState();
  1144. }
  1145. async function prepareSignupVerificationFlow(payload = {}, timeout = 30000) {
  1146. const { password } = payload;
  1147. const start = Date.now();
  1148. let recoveryRound = 0;
  1149. const maxRecoveryRounds = 3;
  1150. while (Date.now() - start < timeout && recoveryRound < maxRecoveryRounds) {
  1151. throwIfStopped();
  1152. const roundNo = recoveryRound + 1;
  1153. log(`步骤 4:等待页面进入验证码阶段(第 ${roundNo}/${maxRecoveryRounds} 轮,先等待 5 秒)...`, 'info');
  1154. const snapshot = await waitForSignupVerificationTransition(5000);
  1155. if (snapshot.state === 'step5') {
  1156. log('步骤 4:页面已进入验证码后的下一阶段,本步骤按已完成处理。', 'ok');
  1157. return { ready: true, alreadyVerified: true, retried: recoveryRound };
  1158. }
  1159. if (snapshot.state === 'verification') {
  1160. log(`步骤 4:验证码页面已就绪${recoveryRound ? `(期间自动恢复 ${recoveryRound} 次)` : ''}。`, 'ok');
  1161. return { ready: true, retried: recoveryRound };
  1162. }
  1163. if (snapshot.state === 'email_exists') {
  1164. throw new Error('当前邮箱已存在,需要重新开始新一轮。');
  1165. }
  1166. recoveryRound += 1;
  1167. if (snapshot.state === 'error') {
  1168. await recoverCurrentAuthRetryPage({
  1169. flow: 'signup_password',
  1170. logLabel: `步骤 4:检测到密码页超时报错,正在点击“重试”恢复(第 ${recoveryRound}/${maxRecoveryRounds} 次)`,
  1171. step: 4,
  1172. timeoutMs: 12000,
  1173. });
  1174. continue;
  1175. }
  1176. if (snapshot.state === 'password') {
  1177. if (!password) {
  1178. throw new Error('当前回到了密码页,但没有可用密码,无法自动重新提交。');
  1179. }
  1180. if ((snapshot.passwordInput.value || '') !== password) {
  1181. log('步骤 4:页面仍停留在密码页,正在重新填写密码...', 'warn');
  1182. await humanPause(450, 1100);
  1183. fillInput(snapshot.passwordInput, password);
  1184. }
  1185. if (snapshot.submitButton && isActionEnabled(snapshot.submitButton)) {
  1186. log(`步骤 4:页面仍停留在密码页,正在重新点击“继续”(第 ${recoveryRound}/${maxRecoveryRounds} 次)...`, 'warn');
  1187. await humanPause(350, 900);
  1188. simulateClick(snapshot.submitButton);
  1189. await sleep(1200);
  1190. continue;
  1191. }
  1192. log(`步骤 4:页面仍停留在密码页,但“继续”按钮暂不可用,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  1193. continue;
  1194. }
  1195. log(`步骤 4:页面仍在切换中,准备继续等待(${recoveryRound}/${maxRecoveryRounds})...`, 'warn');
  1196. }
  1197. throw new Error(`等待注册验证码页面就绪超时或自动恢复失败(已尝试 ${recoveryRound}/${maxRecoveryRounds} 轮)。URL: ${location.href}`);
  1198. }
  1199. async function waitForVerificationSubmitOutcome(step, timeout) {
  1200. const resolvedTimeout = timeout ?? (step === 8 ? 30000 : 12000);
  1201. const start = Date.now();
  1202. while (Date.now() - start < resolvedTimeout) {
  1203. throwIfStopped();
  1204. const errorText = getVerificationErrorText();
  1205. if (errorText) {
  1206. return { invalidCode: true, errorText };
  1207. }
  1208. if (step === 4 && isStep5Ready()) {
  1209. return { success: true };
  1210. }
  1211. if (step === 8 && isStep8Ready()) {
  1212. return { success: true };
  1213. }
  1214. if (step === 8 && isAddPhonePageReady()) {
  1215. return { success: true, addPhonePage: true };
  1216. }
  1217. await sleep(150);
  1218. }
  1219. if (isVerificationPageStillVisible()) {
  1220. return {
  1221. invalidCode: true,
  1222. errorText: getVerificationErrorText() || '提交后仍停留在验证码页面,准备重新发送验证码。',
  1223. };
  1224. }
  1225. return { success: true, assumed: true };
  1226. }
  1227. async function fillVerificationCode(step, payload) {
  1228. const { code } = payload;
  1229. if (!code) throw new Error('未提供验证码。');
  1230. log(`步骤 ${step}:正在填写验证码:${code}`);
  1231. if (step === 8) {
  1232. await waitForLoginVerificationPageReady();
  1233. }
  1234. // Find code input — could be a single input or multiple separate inputs
  1235. // Retry with 405 error recovery if needed
  1236. const maxRetries = 3;
  1237. let codeInput = null;
  1238. for (let retry = 0; retry <= maxRetries; retry++) {
  1239. throwIfStopped();
  1240. // Before looking for input, check if page is in 405 error state
  1241. if (is405MethodNotAllowedPage()) {
  1242. log(`步骤 ${step}:检测到 405 错误页面,正在恢复...`, 'warn');
  1243. await handle405ResendError(step, 30000);
  1244. continue;
  1245. }
  1246. try {
  1247. codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
  1248. break; // Found it
  1249. } catch {
  1250. // Check for multiple single-digit inputs (common pattern)
  1251. const singleInputs = document.querySelectorAll('input[maxlength="1"]');
  1252. if (singleInputs.length >= 6) {
  1253. log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
  1254. for (let i = 0; i < 6 && i < singleInputs.length; i++) {
  1255. fillInput(singleInputs[i], code[i]);
  1256. await sleep(100);
  1257. }
  1258. const outcome = await waitForVerificationSubmitOutcome(step);
  1259. if (outcome.invalidCode) {
  1260. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  1261. } else if (outcome.addPhonePage) {
  1262. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  1263. } else {
  1264. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  1265. }
  1266. return outcome;
  1267. }
  1268. // No input found — check if it's a 405 error and can be recovered
  1269. if (is405MethodNotAllowedPage() && retry < maxRetries) {
  1270. log(`步骤 ${step}:未找到验证码输入框且页面出现 405 错误,正在恢复...`, 'warn');
  1271. await handle405ResendError(step, 30000);
  1272. continue;
  1273. }
  1274. throw new Error('未找到验证码输入框。URL: ' + location.href);
  1275. }
  1276. }
  1277. if (!codeInput) {
  1278. throw new Error('未找到验证码输入框。URL: ' + location.href);
  1279. }
  1280. fillInput(codeInput, code);
  1281. log(`步骤 ${step}:验证码已填写`);
  1282. // Report complete BEFORE submit (page may navigate away)
  1283. // Submit
  1284. await sleep(500);
  1285. const submitBtn = document.querySelector('button[type="submit"]')
  1286. || await waitForElementByText('button', /verify|confirm|submit|continue|确认|验证/i, 5000).catch(() => null);
  1287. if (submitBtn) {
  1288. await humanPause(450, 1200);
  1289. simulateClick(submitBtn);
  1290. log(`步骤 ${step}:验证码已提交`);
  1291. }
  1292. const outcome = await waitForVerificationSubmitOutcome(step);
  1293. if (outcome.invalidCode) {
  1294. log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
  1295. } else if (outcome.addPhonePage) {
  1296. log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
  1297. } else {
  1298. log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
  1299. }
  1300. return outcome;
  1301. }
  1302. // ============================================================
  1303. // Step 6: Login with registered account (on OAuth auth page)
  1304. // ============================================================
  1305. async function waitForStep6EmailSubmitTransition(emailSubmittedAt, timeout = 12000) {
  1306. const start = Date.now();
  1307. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1308. while (Date.now() - start < timeout) {
  1309. throwIfStopped();
  1310. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1311. if (snapshot.state === 'verification_page') {
  1312. return {
  1313. action: 'done',
  1314. result: createStep6SuccessResult(snapshot, {
  1315. via: 'email_submit',
  1316. loginVerificationRequestedAt: emailSubmittedAt,
  1317. }),
  1318. };
  1319. }
  1320. if (snapshot.state === 'password_page') {
  1321. return { action: 'password', snapshot };
  1322. }
  1323. if (snapshot.state === 'login_timeout_error_page') {
  1324. return {
  1325. action: 'recoverable',
  1326. result: await createStep6LoginTimeoutRecoverableResult(
  1327. 'login_timeout_error_page',
  1328. snapshot,
  1329. '提交邮箱后进入登录超时报错页。'
  1330. ),
  1331. };
  1332. }
  1333. if (snapshot.state === 'oauth_consent_page') {
  1334. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1335. }
  1336. if (snapshot.state === 'add_phone_page') {
  1337. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1338. }
  1339. await sleep(250);
  1340. }
  1341. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1342. if (snapshot.state === 'verification_page') {
  1343. return {
  1344. action: 'done',
  1345. result: createStep6SuccessResult(snapshot, {
  1346. via: 'email_submit',
  1347. loginVerificationRequestedAt: emailSubmittedAt,
  1348. }),
  1349. };
  1350. }
  1351. if (snapshot.state === 'password_page') {
  1352. return { action: 'password', snapshot };
  1353. }
  1354. if (snapshot.state === 'login_timeout_error_page') {
  1355. return {
  1356. action: 'recoverable',
  1357. result: await createStep6LoginTimeoutRecoverableResult(
  1358. 'login_timeout_error_page',
  1359. snapshot,
  1360. '提交邮箱后进入登录超时报错页。'
  1361. ),
  1362. };
  1363. }
  1364. if (snapshot.state === 'oauth_consent_page') {
  1365. throw new Error(`提交邮箱后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1366. }
  1367. if (snapshot.state === 'add_phone_page') {
  1368. throw new Error(`提交邮箱后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1369. }
  1370. return {
  1371. action: 'recoverable',
  1372. result: createStep6RecoverableResult('email_submit_stalled', snapshot, {
  1373. message: '提交邮箱后长时间未进入密码页或登录验证码页。',
  1374. }),
  1375. };
  1376. }
  1377. async function waitForStep6PasswordSubmitTransition(passwordSubmittedAt, timeout = 10000) {
  1378. const start = Date.now();
  1379. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1380. while (Date.now() - start < timeout) {
  1381. throwIfStopped();
  1382. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1383. if (snapshot.state === 'verification_page') {
  1384. return {
  1385. action: 'done',
  1386. result: createStep6SuccessResult(snapshot, {
  1387. via: 'password_submit',
  1388. loginVerificationRequestedAt: passwordSubmittedAt,
  1389. }),
  1390. };
  1391. }
  1392. if (snapshot.state === 'login_timeout_error_page') {
  1393. return {
  1394. action: 'recoverable',
  1395. result: await createStep6LoginTimeoutRecoverableResult(
  1396. 'login_timeout_error_page',
  1397. snapshot,
  1398. '提交密码后进入登录超时报错页。'
  1399. ),
  1400. };
  1401. }
  1402. if (snapshot.state === 'oauth_consent_page') {
  1403. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1404. }
  1405. if (snapshot.state === 'add_phone_page') {
  1406. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1407. }
  1408. await sleep(250);
  1409. }
  1410. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1411. if (snapshot.state === 'verification_page') {
  1412. return {
  1413. action: 'done',
  1414. result: createStep6SuccessResult(snapshot, {
  1415. via: 'password_submit',
  1416. loginVerificationRequestedAt: passwordSubmittedAt,
  1417. }),
  1418. };
  1419. }
  1420. if (snapshot.state === 'login_timeout_error_page') {
  1421. return {
  1422. action: 'recoverable',
  1423. result: await createStep6LoginTimeoutRecoverableResult(
  1424. 'login_timeout_error_page',
  1425. snapshot,
  1426. '提交密码后进入登录超时报错页。'
  1427. ),
  1428. };
  1429. }
  1430. if (snapshot.state === 'oauth_consent_page') {
  1431. throw new Error(`提交密码后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1432. }
  1433. if (snapshot.state === 'add_phone_page') {
  1434. throw new Error(`提交密码后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1435. }
  1436. if (snapshot.state === 'password_page' && snapshot.switchTrigger) {
  1437. return { action: 'switch', snapshot };
  1438. }
  1439. return {
  1440. action: 'recoverable',
  1441. result: createStep6RecoverableResult('password_submit_stalled', snapshot, {
  1442. message: '提交密码后仍未进入登录验证码页。',
  1443. }),
  1444. };
  1445. }
  1446. async function waitForStep6SwitchTransition(loginVerificationRequestedAt, timeout = 10000) {
  1447. const start = Date.now();
  1448. let snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1449. while (Date.now() - start < timeout) {
  1450. throwIfStopped();
  1451. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1452. if (snapshot.state === 'verification_page') {
  1453. return createStep6SuccessResult(snapshot, {
  1454. via: 'switch_to_one_time_code_login',
  1455. loginVerificationRequestedAt,
  1456. });
  1457. }
  1458. if (snapshot.state === 'login_timeout_error_page') {
  1459. return await createStep6LoginTimeoutRecoverableResult(
  1460. 'login_timeout_error_page',
  1461. snapshot,
  1462. '切换到一次性验证码登录后进入登录超时报错页。'
  1463. );
  1464. }
  1465. if (snapshot.state === 'oauth_consent_page') {
  1466. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1467. }
  1468. if (snapshot.state === 'add_phone_page') {
  1469. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1470. }
  1471. await sleep(250);
  1472. }
  1473. snapshot = normalizeStep6Snapshot(inspectLoginAuthState());
  1474. if (snapshot.state === 'verification_page') {
  1475. return createStep6SuccessResult(snapshot, {
  1476. via: 'switch_to_one_time_code_login',
  1477. loginVerificationRequestedAt,
  1478. });
  1479. }
  1480. if (snapshot.state === 'login_timeout_error_page') {
  1481. return await createStep6LoginTimeoutRecoverableResult(
  1482. 'login_timeout_error_page',
  1483. snapshot,
  1484. '切换到一次性验证码登录后进入登录超时报错页。'
  1485. );
  1486. }
  1487. if (snapshot.state === 'oauth_consent_page') {
  1488. throw new Error(`切换到一次性验证码登录后页面直接进入 OAuth 授权页,未经过登录验证码页。URL: ${snapshot.url}`);
  1489. }
  1490. if (snapshot.state === 'add_phone_page') {
  1491. throw new Error(`切换到一次性验证码登录后页面直接进入手机号页面,未经过登录验证码页。URL: ${snapshot.url}`);
  1492. }
  1493. return createStep6RecoverableResult('one_time_code_switch_stalled', snapshot, {
  1494. message: '点击一次性验证码登录后仍未进入登录验证码页。',
  1495. });
  1496. }
  1497. async function step6SwitchToOneTimeCodeLogin(snapshot) {
  1498. const switchTrigger = snapshot?.switchTrigger || findOneTimeCodeLoginTrigger();
  1499. if (!switchTrigger || !isActionEnabled(switchTrigger)) {
  1500. return createStep6RecoverableResult('missing_one_time_code_trigger', normalizeStep6Snapshot(inspectLoginAuthState()), {
  1501. message: '当前登录页没有可用的一次性验证码登录入口。',
  1502. });
  1503. }
  1504. log('步骤 7:已检测到一次性验证码登录入口,准备切换...');
  1505. const loginVerificationRequestedAt = Date.now();
  1506. await humanPause(350, 900);
  1507. simulateClick(switchTrigger);
  1508. log('步骤 7:已点击一次性验证码登录');
  1509. await sleep(1200);
  1510. return waitForStep6SwitchTransition(loginVerificationRequestedAt);
  1511. }
  1512. async function step6LoginFromPasswordPage(payload, snapshot) {
  1513. const currentSnapshot = normalizeStep6Snapshot(snapshot || inspectLoginAuthState());
  1514. if (currentSnapshot.passwordInput) {
  1515. if (!payload.password) {
  1516. throw new Error('登录时缺少密码,步骤 7 无法继续。');
  1517. }
  1518. log('步骤 7:已进入密码页,准备填写密码...');
  1519. await humanPause(550, 1450);
  1520. fillInput(currentSnapshot.passwordInput, payload.password);
  1521. log('步骤 7:已填写密码');
  1522. await sleep(500);
  1523. const passwordSubmittedAt = Date.now();
  1524. await triggerLoginSubmitAction(currentSnapshot.submitButton, currentSnapshot.passwordInput);
  1525. log('步骤 7:已提交密码');
  1526. const transition = await waitForStep6PasswordSubmitTransition(passwordSubmittedAt);
  1527. if (transition.action === 'done') {
  1528. log('步骤 7:已进入登录验证码页面。', 'ok');
  1529. return transition.result;
  1530. }
  1531. if (transition.action === 'recoverable') {
  1532. log(`步骤 7:${transition.result.message || '提交密码后仍未进入登录验证码页面,准备重新执行步骤 7。'}`, 'warn');
  1533. return transition.result;
  1534. }
  1535. if (transition.action === 'switch') {
  1536. return step6SwitchToOneTimeCodeLogin(transition.snapshot);
  1537. }
  1538. return createStep6RecoverableResult('password_submit_unknown', normalizeStep6Snapshot(inspectLoginAuthState()), {
  1539. message: '提交密码后未得到可用的下一步状态。',
  1540. });
  1541. }
  1542. if (currentSnapshot.switchTrigger) {
  1543. return step6SwitchToOneTimeCodeLogin(currentSnapshot);
  1544. }
  1545. return createStep6RecoverableResult('password_page_unactionable', currentSnapshot, {
  1546. message: '当前停留在登录页,但没有可提交密码的输入框,也没有一次性验证码登录入口。',
  1547. });
  1548. }
  1549. async function step6LoginFromEmailPage(payload, snapshot) {
  1550. const currentSnapshot = normalizeStep6Snapshot(snapshot || inspectLoginAuthState());
  1551. const emailInput = currentSnapshot.emailInput || getLoginEmailInput();
  1552. if (!emailInput) {
  1553. throw new Error('在登录页未找到邮箱输入框。URL: ' + location.href);
  1554. }
  1555. if ((emailInput.value || '').trim() !== payload.email) {
  1556. await humanPause(500, 1400);
  1557. fillInput(emailInput, payload.email);
  1558. log('步骤 7:已填写邮箱');
  1559. } else {
  1560. log('步骤 7:邮箱已在输入框中,准备提交...');
  1561. }
  1562. await sleep(500);
  1563. const emailSubmittedAt = Date.now();
  1564. await triggerLoginSubmitAction(currentSnapshot.submitButton, emailInput);
  1565. log('步骤 7:已提交邮箱');
  1566. const transition = await waitForStep6EmailSubmitTransition(emailSubmittedAt);
  1567. if (transition.action === 'done') {
  1568. log('步骤 7:已进入登录验证码页面。', 'ok');
  1569. return transition.result;
  1570. }
  1571. if (transition.action === 'recoverable') {
  1572. log(`步骤 7:${transition.result.message || '提交邮箱后仍未进入目标页面,准备重新执行步骤 7。'}`, 'warn');
  1573. return transition.result;
  1574. }
  1575. if (transition.action === 'password') {
  1576. return step6LoginFromPasswordPage(payload, transition.snapshot);
  1577. }
  1578. return createStep6RecoverableResult('email_submit_unknown', normalizeStep6Snapshot(inspectLoginAuthState()), {
  1579. message: '提交邮箱后未得到可用的下一步状态。',
  1580. });
  1581. }
  1582. async function step6_login(payload) {
  1583. const { email } = payload;
  1584. if (!email) throw new Error('登录时缺少邮箱地址。');
  1585. log(`步骤 7:正在使用 ${email} 登录...`);
  1586. const snapshot = normalizeStep6Snapshot(await waitForKnownLoginAuthState(15000));
  1587. if (snapshot.state === 'verification_page') {
  1588. log('步骤 7:登录验证码页面已就绪。', 'ok');
  1589. return createStep6SuccessResult(snapshot, { via: 'already_on_verification_page' });
  1590. }
  1591. if (snapshot.state === 'login_timeout_error_page') {
  1592. log('步骤 7:检测到登录超时报错,准备重新执行步骤 7。', 'warn');
  1593. return await createStep6LoginTimeoutRecoverableResult(
  1594. 'login_timeout_error_page',
  1595. snapshot,
  1596. '当前页面处于登录超时报错页。'
  1597. );
  1598. }
  1599. if (snapshot.state === 'email_page') {
  1600. return step6LoginFromEmailPage(payload, snapshot);
  1601. }
  1602. if (snapshot.state === 'password_page') {
  1603. return step6LoginFromPasswordPage(payload, snapshot);
  1604. }
  1605. throwForStep6FatalState(snapshot);
  1606. throw new Error(`无法识别当前登录页面状态。URL: ${snapshot?.url || location.href}`);
  1607. }
  1608. // ============================================================
  1609. // Step 9: Find "继续" on OAuth consent page for debugger click
  1610. // ============================================================
  1611. // After login + verification, page shows:
  1612. // "使用 ChatGPT 登录到 Codex" with a "继续" submit button.
  1613. // Background performs the actual click through the debugger Input API.
  1614. async function step8_findAndClick() {
  1615. log('步骤 9:正在查找 OAuth 同意页的“继续”按钮...');
  1616. const continueBtn = await prepareStep8ContinueButton();
  1617. const rect = getSerializableRect(continueBtn);
  1618. log('步骤 9:已找到“继续”按钮并准备好调试器点击坐标。');
  1619. return {
  1620. rect,
  1621. buttonText: (continueBtn.textContent || '').trim(),
  1622. url: location.href,
  1623. };
  1624. }
  1625. function getStep8State() {
  1626. const continueBtn = getPrimaryContinueButton();
  1627. const retryState = getCurrentAuthRetryPageState('auth');
  1628. const state = {
  1629. url: location.href,
  1630. consentPage: isOAuthConsentPage(),
  1631. consentReady: isStep8Ready(),
  1632. verificationPage: isVerificationPageStillVisible(),
  1633. addPhonePage: isAddPhonePageReady(),
  1634. retryPage: Boolean(retryState),
  1635. retryEnabled: Boolean(retryState?.retryEnabled),
  1636. retryTitleMatched: Boolean(retryState?.titleMatched),
  1637. retryDetailMatched: Boolean(retryState?.detailMatched),
  1638. buttonFound: Boolean(continueBtn),
  1639. buttonEnabled: isButtonEnabled(continueBtn),
  1640. buttonText: continueBtn ? getActionText(continueBtn) : '',
  1641. };
  1642. if (continueBtn) {
  1643. try {
  1644. state.rect = getSerializableRect(continueBtn);
  1645. } catch {
  1646. state.rect = null;
  1647. }
  1648. }
  1649. return state;
  1650. }
  1651. async function step8_triggerContinue(payload = {}) {
  1652. const strategy = payload?.strategy || 'requestSubmit';
  1653. const continueBtn = await prepareStep8ContinueButton({
  1654. findTimeoutMs: payload?.findTimeoutMs,
  1655. enabledTimeoutMs: payload?.enabledTimeoutMs,
  1656. });
  1657. const form = continueBtn.form || continueBtn.closest('form');
  1658. switch (strategy) {
  1659. case 'requestSubmit':
  1660. if (!form || typeof form.requestSubmit !== 'function') {
  1661. throw new Error('“继续”按钮当前不在可提交的 form 中,无法使用 requestSubmit。URL: ' + location.href);
  1662. }
  1663. form.requestSubmit(continueBtn);
  1664. break;
  1665. case 'nativeClick':
  1666. continueBtn.click();
  1667. break;
  1668. case 'dispatchClick':
  1669. simulateClick(continueBtn);
  1670. break;
  1671. default:
  1672. throw new Error(`未知的 Step 9 触发策略:${strategy}`);
  1673. }
  1674. log(`Step 9: continue button triggered via ${strategy}.`);
  1675. return {
  1676. strategy,
  1677. ...getStep8State(),
  1678. };
  1679. }
  1680. async function prepareStep8ContinueButton(options = {}) {
  1681. const {
  1682. findTimeoutMs = 10000,
  1683. enabledTimeoutMs = 8000,
  1684. } = options;
  1685. const continueBtn = await findContinueButton(findTimeoutMs);
  1686. await waitForButtonEnabled(continueBtn, enabledTimeoutMs);
  1687. await humanPause(250, 700);
  1688. continueBtn.scrollIntoView({ behavior: 'auto', block: 'center' });
  1689. continueBtn.focus();
  1690. await waitForStableButtonRect(continueBtn);
  1691. return continueBtn;
  1692. }
  1693. async function findContinueButton(timeout = 10000) {
  1694. const start = Date.now();
  1695. while (Date.now() - start < timeout) {
  1696. throwIfStopped();
  1697. if (isAddPhonePageReady()) {
  1698. throw new Error('当前页面已进入手机号页面,不是 OAuth 授权同意页。URL: ' + location.href);
  1699. }
  1700. const button = getPrimaryContinueButton();
  1701. if (button && isStep8Ready()) {
  1702. return button;
  1703. }
  1704. await sleep(150);
  1705. }
  1706. throw new Error('在 OAuth 同意页未找到“继续”按钮,或页面尚未进入授权同意状态。URL: ' + location.href);
  1707. }
  1708. async function waitForButtonEnabled(button, timeout = 8000) {
  1709. const start = Date.now();
  1710. while (Date.now() - start < timeout) {
  1711. throwIfStopped();
  1712. if (isButtonEnabled(button)) return;
  1713. await sleep(150);
  1714. }
  1715. throw new Error('“继续”按钮长时间不可点击。URL: ' + location.href);
  1716. }
  1717. function isButtonEnabled(button) {
  1718. return Boolean(button)
  1719. && !button.disabled
  1720. && button.getAttribute('aria-disabled') !== 'true';
  1721. }
  1722. async function waitForStableButtonRect(button, timeout = 1500) {
  1723. let previous = null;
  1724. let stableSamples = 0;
  1725. const start = Date.now();
  1726. while (Date.now() - start < timeout) {
  1727. throwIfStopped();
  1728. const rect = button?.getBoundingClientRect?.();
  1729. if (rect && rect.width > 0 && rect.height > 0) {
  1730. const snapshot = {
  1731. left: rect.left,
  1732. top: rect.top,
  1733. width: rect.width,
  1734. height: rect.height,
  1735. };
  1736. if (
  1737. previous
  1738. && Math.abs(snapshot.left - previous.left) < 1
  1739. && Math.abs(snapshot.top - previous.top) < 1
  1740. && Math.abs(snapshot.width - previous.width) < 1
  1741. && Math.abs(snapshot.height - previous.height) < 1
  1742. ) {
  1743. stableSamples += 1;
  1744. if (stableSamples >= 2) {
  1745. return;
  1746. }
  1747. } else {
  1748. stableSamples = 0;
  1749. }
  1750. previous = snapshot;
  1751. }
  1752. await sleep(80);
  1753. }
  1754. }
  1755. function getSerializableRect(el) {
  1756. const rect = el.getBoundingClientRect();
  1757. if (!rect.width || !rect.height) {
  1758. throw new Error('滚动后“继续”按钮没有可点击尺寸。URL: ' + location.href);
  1759. }
  1760. return {
  1761. left: rect.left,
  1762. top: rect.top,
  1763. width: rect.width,
  1764. height: rect.height,
  1765. centerX: rect.left + (rect.width / 2),
  1766. centerY: rect.top + (rect.height / 2),
  1767. };
  1768. }
  1769. // ============================================================
  1770. // Step 5: Fill Name & Birthday / Age
  1771. // ============================================================
  1772. function getStep5DirectCompletionPayload({ isAgeMode = false } = {}) {
  1773. const payload = {
  1774. skippedPostSubmitCheck: true,
  1775. directProceedToStep6: true,
  1776. };
  1777. if (isAgeMode) {
  1778. payload.ageMode = true;
  1779. }
  1780. return payload;
  1781. }
  1782. async function step5_fillNameBirthday(payload) {
  1783. const { firstName, lastName, age, year, month, day } = payload;
  1784. if (!firstName || !lastName) throw new Error('未提供姓名数据。');
  1785. const resolvedAge = age ?? (year ? new Date().getFullYear() - Number(year) : null);
  1786. const hasBirthdayData = [year, month, day].every(value => value != null && !Number.isNaN(Number(value)));
  1787. if (!hasBirthdayData && (resolvedAge == null || Number.isNaN(Number(resolvedAge)))) {
  1788. throw new Error('未提供生日或年龄数据。');
  1789. }
  1790. const fullName = `${firstName} ${lastName}`;
  1791. log(`步骤 5:正在填写姓名:${fullName}`);
  1792. // Actual DOM structure:
  1793. // - Full name: <input name="name" placeholder="全名" type="text">
  1794. // - Birthday: React Aria DateField or hidden input[name="birthday"]
  1795. // - Age: <input name="age" type="text|number">
  1796. // --- Full Name (single field, not first+last) ---
  1797. let nameInput = null;
  1798. try {
  1799. nameInput = await waitForElement(
  1800. 'input[name="name"], input[placeholder*="全名"], input[autocomplete="name"]',
  1801. 10000
  1802. );
  1803. } catch {
  1804. throw new Error('未找到姓名输入框。URL: ' + location.href);
  1805. }
  1806. await humanPause(500, 1300);
  1807. fillInput(nameInput, fullName);
  1808. log(`步骤 5:姓名已填写:${fullName}`);
  1809. let birthdayMode = false;
  1810. let ageInput = null;
  1811. let yearSpinner = null;
  1812. let monthSpinner = null;
  1813. let daySpinner = null;
  1814. let hiddenBirthday = null;
  1815. let yearReactSelect = null;
  1816. let monthReactSelect = null;
  1817. let dayReactSelect = null;
  1818. let visibleAgeInput = false;
  1819. let visibleBirthdaySpinners = false;
  1820. let visibleBirthdaySelects = false;
  1821. for (let i = 0; i < 100; i++) {
  1822. yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1823. monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1824. daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1825. hiddenBirthday = document.querySelector('input[name="birthday"]');
  1826. ageInput = document.querySelector('input[name="age"]');
  1827. yearReactSelect = findBirthdayReactAriaSelect('年');
  1828. monthReactSelect = findBirthdayReactAriaSelect('月');
  1829. dayReactSelect = findBirthdayReactAriaSelect('天');
  1830. visibleAgeInput = Boolean(ageInput && isVisibleElement(ageInput));
  1831. visibleBirthdaySpinners = Boolean(
  1832. yearSpinner
  1833. && monthSpinner
  1834. && daySpinner
  1835. && isVisibleElement(yearSpinner)
  1836. && isVisibleElement(monthSpinner)
  1837. && isVisibleElement(daySpinner)
  1838. );
  1839. visibleBirthdaySelects = Boolean(
  1840. yearReactSelect?.button
  1841. && monthReactSelect?.button
  1842. && dayReactSelect?.button
  1843. && isVisibleElement(yearReactSelect.button)
  1844. && isVisibleElement(monthReactSelect.button)
  1845. && isVisibleElement(dayReactSelect.button)
  1846. );
  1847. if (visibleAgeInput) break;
  1848. if (visibleBirthdaySpinners || visibleBirthdaySelects) {
  1849. birthdayMode = true;
  1850. break;
  1851. }
  1852. await sleep(100);
  1853. }
  1854. if (birthdayMode) {
  1855. if (!hasBirthdayData) {
  1856. throw new Error('检测到生日字段,但未提供生日数据。');
  1857. }
  1858. const yearSpinner = document.querySelector('[role="spinbutton"][data-type="year"]');
  1859. const monthSpinner = document.querySelector('[role="spinbutton"][data-type="month"]');
  1860. const daySpinner = document.querySelector('[role="spinbutton"][data-type="day"]');
  1861. const yearReactSelect = findBirthdayReactAriaSelect('年');
  1862. const monthReactSelect = findBirthdayReactAriaSelect('月');
  1863. const dayReactSelect = findBirthdayReactAriaSelect('天');
  1864. if (yearReactSelect?.nativeSelect && monthReactSelect?.nativeSelect && dayReactSelect?.nativeSelect) {
  1865. const desiredDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1866. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1867. log('步骤 5:检测到 React Aria 下拉生日字段,正在填写生日...');
  1868. await humanPause(450, 1100);
  1869. await setReactAriaBirthdaySelect(yearReactSelect, year);
  1870. await humanPause(250, 650);
  1871. await setReactAriaBirthdaySelect(monthReactSelect, month);
  1872. await humanPause(250, 650);
  1873. await setReactAriaBirthdaySelect(dayReactSelect, day);
  1874. if (hiddenBirthday) {
  1875. const start = Date.now();
  1876. while (Date.now() - start < 2000) {
  1877. if ((hiddenBirthday.value || '') === desiredDate) break;
  1878. await sleep(100);
  1879. }
  1880. if ((hiddenBirthday.value || '') !== desiredDate) {
  1881. throw new Error(`生日值未成功写入页面。期望 ${desiredDate},实际 ${(hiddenBirthday.value || '空')}。`);
  1882. }
  1883. }
  1884. log(`步骤 5:React Aria 生日已填写:${desiredDate}`);
  1885. }
  1886. if (yearSpinner && monthSpinner && daySpinner) {
  1887. log('步骤 5:检测到生日字段,正在填写生日...');
  1888. async function setSpinButton(el, value) {
  1889. el.focus();
  1890. await sleep(100);
  1891. document.execCommand('selectAll', false, null);
  1892. await sleep(50);
  1893. const valueStr = String(value);
  1894. for (const char of valueStr) {
  1895. el.dispatchEvent(new KeyboardEvent('keydown', { key: char, code: `Digit${char}`, bubbles: true }));
  1896. el.dispatchEvent(new KeyboardEvent('keypress', { key: char, code: `Digit${char}`, bubbles: true }));
  1897. el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: char, bubbles: true }));
  1898. el.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: char, bubbles: true }));
  1899. await sleep(50);
  1900. }
  1901. el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab', code: 'Tab', bubbles: true }));
  1902. el.blur();
  1903. await sleep(100);
  1904. }
  1905. await humanPause(450, 1100);
  1906. await setSpinButton(yearSpinner, year);
  1907. await humanPause(250, 650);
  1908. await setSpinButton(monthSpinner, String(month).padStart(2, '0'));
  1909. await humanPause(250, 650);
  1910. await setSpinButton(daySpinner, String(day).padStart(2, '0'));
  1911. log(`步骤 5:生日已填写:${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`);
  1912. }
  1913. const hiddenBirthday = document.querySelector('input[name="birthday"]');
  1914. if (hiddenBirthday) {
  1915. const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  1916. hiddenBirthday.value = dateStr;
  1917. hiddenBirthday.dispatchEvent(new Event('input', { bubbles: true }));
  1918. hiddenBirthday.dispatchEvent(new Event('change', { bubbles: true }));
  1919. log(`步骤 5:已设置隐藏生日输入框:${dateStr}`);
  1920. }
  1921. } else if (ageInput) {
  1922. if (resolvedAge == null || Number.isNaN(Number(resolvedAge))) {
  1923. throw new Error('检测到年龄字段,但未提供年龄数据。');
  1924. }
  1925. await humanPause(500, 1300);
  1926. fillInput(ageInput, String(resolvedAge));
  1927. log(`步骤 5:年龄已填写:${resolvedAge}`);
  1928. } else {
  1929. throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
  1930. }
  1931. // 韩国IP判断勾选框""I agree"
  1932. const allConsentCheckbox = Array.from(document.querySelectorAll('input[name="allCheckboxes"][type="checkbox"]'))
  1933. .find((el) => {
  1934. const checkboxLabel = el.closest('label');
  1935. const labelText = normalizeInlineText(checkboxLabel?.textContent || '');
  1936. return (!checkboxLabel || isVisibleElement(checkboxLabel))
  1937. && /I\s+agree\s+to\s+all\s+of\s+the\s+following/i.test(labelText);
  1938. }) || null;
  1939. if (allConsentCheckbox) {
  1940. if (!allConsentCheckbox.checked) {
  1941. const checkboxLabel = allConsentCheckbox.closest('label');
  1942. await humanPause(500, 1500);
  1943. if (checkboxLabel && isVisibleElement(checkboxLabel)) {
  1944. simulateClick(checkboxLabel);
  1945. } else {
  1946. simulateClick(allConsentCheckbox);
  1947. }
  1948. await sleep(250);
  1949. if (!allConsentCheckbox.checked) {
  1950. allConsentCheckbox.click();
  1951. await sleep(250);
  1952. }
  1953. if (!allConsentCheckbox.checked) {
  1954. throw new Error('未能勾选 “I agree to all of the following” 复选框。');
  1955. }
  1956. log('步骤 5:已勾选 “I agree to all of the following”。');
  1957. } else {
  1958. log('步骤 5:“I agree to all of the following” 已勾选,跳过。');
  1959. }
  1960. }
  1961. // Click "完成帐户创建" button
  1962. await sleep(500);
  1963. const completeBtn = document.querySelector('button[type="submit"]')
  1964. || await waitForElementByText('button', /完成|create|continue|finish|done|agree/i, 5000).catch(() => null);
  1965. if (!completeBtn) {
  1966. throw new Error('未找到“完成帐户创建”按钮。URL: ' + location.href);
  1967. }
  1968. const isAgeMode = !birthdayMode && Boolean(ageInput);
  1969. if (isAgeMode) {
  1970. log('步骤 5:当前为年龄输入模式,点击“完成帐户创建”后将直接完成当前步骤。', 'warn');
  1971. }
  1972. await humanPause(500, 1300);
  1973. simulateClick(completeBtn);
  1974. const completionPayload = getStep5DirectCompletionPayload({ isAgeMode });
  1975. reportComplete(5, completionPayload);
  1976. if (isAgeMode) {
  1977. log('步骤 5:年龄模式已点击“完成帐户创建”,当前步骤直接完成,不再等待页面结果。', 'warn');
  1978. return completionPayload;
  1979. }
  1980. log('步骤 5:已点击“完成帐户创建”,当前步骤直接完成,不再等待页面结果。');
  1981. return completionPayload;
  1982. }